1
\$\begingroup\$

I wrote a plugin that allows a user to upload a zip file, then the plugin will create a unique directory inside of 'uploads' and then it will unzip the file. I did this so if a user needs to upload several files every day, they can do it using a zip file and the plugin will take care of the rest.

For this particular code, I have it set up so that every time someone uploads files, the old files in that directory are deleted. That's because this client wanted a way to to update links going to PDFs every day. Now the links can stay the same, but the PDFs will change when he/she uploads the zip folder containing all the PDFs.

The delete button will delete the old file in the database, and then every time there's an upload the plugin will delete the files in the created directory.

It works great, but I'm sure it could be improved as well. I would also like to add some functionality to make it universal, but I wanted to get some feedback before moving on. This is the file for the admin aspect of the plugin, which is all I really am needing at this point (other than the required plugin stuff for WP).

Thanks for any help!

require_once(ABSPATH .'wp-includes/pluggable.php');

function add_plugin_page() {
  add_options_page('WP File Unzipper', 'Unzipper Settings', 'manage_options', 'wp-file-unzipper-admin.php', 'admin_content');
}

add_action( 'admin_menu', 'add_plugin_page' );

function admin_content() {
  ?>
    <h2>Delete old files</h2>
      <form id="delete_old_files_button" method="post" action="#">
        <input type="hidden" name="post_id" id="post_id" value="0" />
        <?php wp_nonce_field('delete_old_files', 'delete_old_files_nonce'); ?>
        <input id="delete_old_files" name="delete_old_files" type="submit" value="Delete" />
      </form>
      <?php delete_files()?>

    <h2>Upload your zip file</h2>
    <form id="pdf_zip_upload" method="post" action="#" enctype="multipart/form-data">
      <input type="file" name="pdf_uploader" id="pdf_uploader"  multiple="false" />
      <input type="hidden" name="post_id" id="post_id" value="0" />
      <?php wp_nonce_field( 'pdf_uploader', 'pdf_uploader_nonce' ); ?>
      <input id="submit_pdf_uploader" name="submit_pdf_uploader" type="submit" value="Upload" />
  </form>
  <?php upload_files();
}

function delete_files() {
    if (
      isset($_POST['delete_old_files'])
      && wp_verify_nonce( $_POST['delete_old_files_nonce'], 'delete_old_files')
    ){
      $upload_url = get_site_url() . "/wp-content/uploads/PDFs.zip";
      $upload_id = pn_get_attachment_id_from_url($upload_url);
      wp_delete_post($upload_id);
      echo "Old PDFs have been deleted. Proceed to upload .zip file with filename: PDFs.zip";
  }
}

function upload_files() {
//check the nonce and save the upload to the database
// Check that the nonce is valid, and the user can edit this post.
  if (
    isset( $_POST['pdf_uploader_nonce'], $_POST['post_id'] )
    && wp_verify_nonce( $_POST['pdf_uploader_nonce'], 'pdf_uploader' )
    && current_user_can( 'edit_posts', $_POST['post_id'] )
  ) {
    // The nonce was valid and the user has the capabilities, it is safe to continue.

    // These files need to be included as dependencies when on the front end.
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    require_once( ABSPATH . 'wp-admin/includes/media.php' );

    // Let WordPress handle the upload.
    // $check_filetype = wp_check_filetype( 'pdf_uploader', $_POST['post_id'] );
    $attachment_id = media_handle_upload( 'pdf_uploader', $_POST['post_id'] );
    $uploaded_file_path = get_attached_file($attachment_id); //holds path to where file was uploaded
    $uploaded_file_name = basename($uploaded_file_path); //holds just the uploaded file name
    $temp = wp_upload_dir();
    $upload_dir = trailingslashit($temp['basedir']); //gets file path to uploads folder and adds a trailing slash
    $new_folder_path = $upload_dir . "PDF-archive"; //gets file path to new PDF folder
    $new_file_path = $new_folder_path . "/" . $uploaded_file_name;

    if ( is_wp_error( $attachment_id ) ) {
        echo 'Error uploading the file. Try again, and if the problem persists, contact Kite Media.';
    }
    else {
      //file upload worked, now create directory and unzip file
      $get_filetype = substr($uploaded_file_path, -4, 4); //gets last four characters of string to check if it's a zip file
        echo 'File uploaded succesfully. Links should all be up to date.<br>';
          if ($get_filetype == '.zip') {
            //first, check if there's an existing directory
              if (file_exists($upload_dir . "PDF-archive")){
                  //if the directory exists, delete all the files inside
                  $file_names = glob($upload_dir . "PDF-archive/*");
                  foreach ($file_names as $files){
                    if (is_file($files)){
                      unlink($files);
                    }
                  }          
              }
              else {
                //if directory doesn't exist, create a new one
                $pdf_archive_dir = $temp['basedir'];
                $pdf_archive_dir = $pdf_archive_dir . '/PDF-archive';
                wp_mkdir_p($pdf_archive_dir);
              }
              //directory is created and empty, now add files and unzip them
              rename($uploaded_file_path, $new_file_path); //move zip files into new directory
              unzip_zips($uploaded_file_name); //unzips the uploaded file
          }
          else {
            echo 'Try uploading a .zip file';
          }
        }

}  else {
    //add error message later
  }
}

function unzip_zips($input) {
  WP_Filesystem();
  $destination = wp_upload_dir();
  $destination_path = $destination['path'];
  $unzipfile = unzip_file( $destination_path . "/PDF-archive" . "/$input", $destination_path . "/PDF-archive");
}

function pn_get_attachment_id_from_url( $attachment_url = '' ) {

    global $wpdb;
    $attachment_id = false;

    // If there is no url, return.
    if ( '' == $attachment_url )
        return;

    // Get the upload directory paths
    $upload_dir_paths = wp_upload_dir();

    // Make sure the upload path base directory exists in the attachment URL, to verify that we're working with a media library image
    if ( false !== strpos( $attachment_url, $upload_dir_paths['baseurl'] ) ) {
        $attachment_url = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|zip)$)/i', '', $attachment_url );
        $attachment_url = str_replace( $upload_dir_paths['baseurl'] . '/', '', $attachment_url );
        $attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $attachment_url ) );
    }

    return $attachment_id;
}
?>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.