3 * Upgrade API: File_Upload_Upgrader class
11 * Core class used for handling file uploads.
13 * This class handles the upload process and passes it as if it's a local file
14 * to the Upgrade/Installer functions.
17 * @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader.php.
19 class File_Upload_Upgrader {
22 * The full path to the file package.
26 * @var string $package
31 * The name of the file.
35 * @var string $filename
40 * The ID of the attachment post for this file.
49 * Construct the upgrader for a form.
54 * @param string $form The name of the form the file was uploaded from.
55 * @param string $urlholder The name of the `GET` parameter that holds the filename.
57 public function __construct( $form, $urlholder ) {
59 if ( empty($_FILES[$form]['name']) && empty($_GET[$urlholder]) )
60 wp_die(__('Please select a file'));
62 //Handle a newly uploaded file, Else assume it's already been uploaded
63 if ( ! empty($_FILES) ) {
64 $overrides = array( 'test_form' => false, 'test_type' => false );
65 $file = wp_handle_upload( $_FILES[$form], $overrides );
67 if ( isset( $file['error'] ) )
68 wp_die( $file['error'] );
70 $this->filename = $_FILES[$form]['name'];
71 $this->package = $file['file'];
73 // Construct the object array
75 'post_title' => $this->filename,
76 'post_content' => $file['url'],
77 'post_mime_type' => $file['type'],
78 'guid' => $file['url'],
79 'context' => 'upgrader',
80 'post_status' => 'private'
84 $this->id = wp_insert_attachment( $object, $file['file'] );
86 // Schedule a cleanup for 2 hours from now in case of failed install.
87 wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $this->id ) );
89 } elseif ( is_numeric( $_GET[$urlholder] ) ) {
90 // Numeric Package = previously uploaded file, see above.
91 $this->id = (int) $_GET[$urlholder];
92 $attachment = get_post( $this->id );
93 if ( empty($attachment) )
94 wp_die(__('Please select a file'));
96 $this->filename = $attachment->post_title;
97 $this->package = get_attached_file( $attachment->ID );
99 // Else, It's set to something, Back compat for plugins using the old (pre-3.3) File_Uploader handler.
100 if ( ! ( ( $uploads = wp_upload_dir() ) && false === $uploads['error'] ) )
101 wp_die( $uploads['error'] );
103 $this->filename = $_GET[$urlholder];
104 $this->package = $uploads['basedir'] . '/' . $this->filename;
109 * Delete the attachment/uploaded file.
114 * @return bool Whether the cleanup was successful.
116 public function cleanup() {
118 wp_delete_attachment( $this->id );
120 elseif ( file_exists( $this->package ) )
121 return @unlink( $this->package );