WordPress 4.5
[autoinstalls/wordpress.git] / wp-admin / includes / class-wp-upgrader.php
1 <?php
2 /**
3  * Upgrade API: WP_Upgrader, Plugin_Upgrader, Theme_Upgrader, Language_Pack_Upgrader,
4  * Core_Upgrader, File_Upload_Upgrader, and WP_Automatic_Updater classes
5  *
6  * This set of classes are designed to be used to upgrade/install a local set of files
7  * on the filesystem via the Filesystem Abstraction classes.
8  *
9  * @package WordPress
10  * @subpackage Upgrader
11  * @since 2.8.0
12  */
13
14 require ABSPATH . 'wp-admin/includes/class-wp-upgrader-skins.php';
15
16 /**
17  * Core class used for upgrading/installing a local set of files via
18  * the Filesystem Abstraction classes from a Zip file.
19  *
20  * @since 2.8.0
21  */
22 class WP_Upgrader {
23
24         /**
25          * The error/notification strings used to update the user on the progress.
26          *
27          * @since 2.8.0
28          * @access public
29          * @var string $strings
30          */
31         public $strings = array();
32
33         /**
34          * The upgrader skin being used.
35          *
36          * @since 2.8.0
37          * @access public
38          * @var WP_Upgrader_Skin $skin
39          */
40         public $skin = null;
41
42         /**
43          * The result of the installation.
44          *
45          * This is set by {@see WP_Upgrader::install_package()}, only when the package is installed
46          * successfully. It will then be an array, unless a {@see WP_Error} is returned by the
47          * {@see 'upgrader_post_install'} filter. In that case, the `WP_Error` will be assigned to
48          * it.
49          *
50          * @since 2.8.0
51          * @access public
52          *
53          * @var WP_Error|array $result {
54          *      @type string $source             The full path to the source the files were installed from.
55          *      @type string $source_files       List of all the files in the source directory.
56          *      @type string $destination        The full path to the install destination folder.
57          *      @type string $destination_name   The name of the destination folder, or empty if `$destination`
58          *                                       and `$local_destination` are the same.
59          *      @type string $local_destination  The full local path to the destination folder. This is usually
60          *                                       the same as `$destination`.
61          *      @type string $remote_destination The full remote path to the destination folder
62          *                                       (i.e., from `$wp_filesystem`).
63          *      @type bool   $clear_destination  Whether the destination folder was cleared.
64          * }
65          */
66         public $result = array();
67
68         /**
69          * The total number of updates being performed.
70          *
71          * Set by the bulk update methods.
72          *
73          * @since 3.0.0
74          * @access public
75          * @var int $update_count
76          */
77         public $update_count = 0;
78
79         /**
80          * The current update if multiple updates are being performed.
81          *
82          * Used by the bulk update methods, and incremented for each update.
83          *
84          * @since 3.0.0
85          * @access public
86          * @var int
87          */
88         public $update_current = 0;
89
90         /**
91          * Construct the upgrader with a skin.
92          *
93          * @since 2.8.0
94          * @access public
95          *
96          * @param WP_Upgrader_Skin $skin The upgrader skin to use. Default is a {@see WP_Upgrader_Skin}
97          *                               instance.
98          */
99         public function __construct( $skin = null ) {
100                 if ( null == $skin )
101                         $this->skin = new WP_Upgrader_Skin();
102                 else
103                         $this->skin = $skin;
104         }
105
106         /**
107          * Initialize the upgrader.
108          *
109          * This will set the relationship between the skin being used and this upgrader,
110          * and also add the generic strings to `WP_Upgrader::$strings`.
111          *
112          * @since 2.8.0
113          * @access public
114          */
115         public function init() {
116                 $this->skin->set_upgrader($this);
117                 $this->generic_strings();
118         }
119
120         /**
121          * Add the generic strings to WP_Upgrader::$strings.
122          *
123          * @since 2.8.0
124          * @access public
125          */
126         public function generic_strings() {
127                 $this->strings['bad_request'] = __('Invalid Data provided.');
128                 $this->strings['fs_unavailable'] = __('Could not access filesystem.');
129                 $this->strings['fs_error'] = __('Filesystem error.');
130                 $this->strings['fs_no_root_dir'] = __('Unable to locate WordPress Root directory.');
131                 $this->strings['fs_no_content_dir'] = __('Unable to locate WordPress Content directory (wp-content).');
132                 $this->strings['fs_no_plugins_dir'] = __('Unable to locate WordPress Plugin directory.');
133                 $this->strings['fs_no_themes_dir'] = __('Unable to locate WordPress Theme directory.');
134                 /* translators: %s: directory name */
135                 $this->strings['fs_no_folder'] = __('Unable to locate needed folder (%s).');
136
137                 $this->strings['download_failed'] = __('Download failed.');
138                 $this->strings['installing_package'] = __('Installing the latest version&#8230;');
139                 $this->strings['no_files'] = __('The package contains no files.');
140                 $this->strings['folder_exists'] = __('Destination folder already exists.');
141                 $this->strings['mkdir_failed'] = __('Could not create directory.');
142                 $this->strings['incompatible_archive'] = __('The package could not be installed.');
143                 $this->strings['files_not_writable'] = __( 'The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.' );
144
145                 $this->strings['maintenance_start'] = __('Enabling Maintenance mode&#8230;');
146                 $this->strings['maintenance_end'] = __('Disabling Maintenance mode&#8230;');
147         }
148
149         /**
150          * Connect to the filesystem.
151          *
152          * @since 2.8.0
153          * @access public
154          *
155          * @global WP_Filesystem_Base $wp_filesystem Subclass
156          *
157          * @param array $directories                  Optional. A list of directories. If any of these do
158          *                                            not exist, a {@see WP_Error} object will be returned.
159          *                                            Default empty array.
160          * @param bool  $allow_relaxed_file_ownership Whether to allow relaxed file ownership.
161          *                                            Default false.
162          * @return bool|WP_Error True if able to connect, false or a {@see WP_Error} otherwise.
163          */
164         public function fs_connect( $directories = array(), $allow_relaxed_file_ownership = false ) {
165                 global $wp_filesystem;
166
167                 if ( false === ( $credentials = $this->skin->request_filesystem_credentials( false, $directories[0], $allow_relaxed_file_ownership ) ) ) {
168                         return false;
169                 }
170
171                 if ( ! WP_Filesystem( $credentials, $directories[0], $allow_relaxed_file_ownership ) ) {
172                         $error = true;
173                         if ( is_object($wp_filesystem) && $wp_filesystem->errors->get_error_code() )
174                                 $error = $wp_filesystem->errors;
175                         // Failed to connect, Error and request again
176                         $this->skin->request_filesystem_credentials( $error, $directories[0], $allow_relaxed_file_ownership );
177                         return false;
178                 }
179
180                 if ( ! is_object($wp_filesystem) )
181                         return new WP_Error('fs_unavailable', $this->strings['fs_unavailable'] );
182
183                 if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
184                         return new WP_Error('fs_error', $this->strings['fs_error'], $wp_filesystem->errors);
185
186                 foreach ( (array)$directories as $dir ) {
187                         switch ( $dir ) {
188                                 case ABSPATH:
189                                         if ( ! $wp_filesystem->abspath() )
190                                                 return new WP_Error('fs_no_root_dir', $this->strings['fs_no_root_dir']);
191                                         break;
192                                 case WP_CONTENT_DIR:
193                                         if ( ! $wp_filesystem->wp_content_dir() )
194                                                 return new WP_Error('fs_no_content_dir', $this->strings['fs_no_content_dir']);
195                                         break;
196                                 case WP_PLUGIN_DIR:
197                                         if ( ! $wp_filesystem->wp_plugins_dir() )
198                                                 return new WP_Error('fs_no_plugins_dir', $this->strings['fs_no_plugins_dir']);
199                                         break;
200                                 case get_theme_root():
201                                         if ( ! $wp_filesystem->wp_themes_dir() )
202                                                 return new WP_Error('fs_no_themes_dir', $this->strings['fs_no_themes_dir']);
203                                         break;
204                                 default:
205                                         if ( ! $wp_filesystem->find_folder($dir) )
206                                                 return new WP_Error( 'fs_no_folder', sprintf( $this->strings['fs_no_folder'], esc_html( basename( $dir ) ) ) );
207                                         break;
208                         }
209                 }
210                 return true;
211         } //end fs_connect();
212
213         /**
214          * Download a package.
215          *
216          * @since 2.8.0
217          * @access public
218          *
219          * @param string $package The URI of the package. If this is the full path to an
220          *                        existing local file, it will be returned untouched.
221          * @return string|WP_Error The full path to the downloaded package file, or a {@see WP_Error} object.
222          */
223         public function download_package( $package ) {
224
225                 /**
226                  * Filter whether to return the package.
227                  *
228                  * @since 3.7.0
229                  * @access public
230                  *
231                  * @param bool        $reply   Whether to bail without returning the package.
232                  *                             Default false.
233                  * @param string      $package The package file name.
234                  * @param WP_Upgrader $this    The WP_Upgrader instance.
235                  */
236                 $reply = apply_filters( 'upgrader_pre_download', false, $package, $this );
237                 if ( false !== $reply )
238                         return $reply;
239
240                 if ( ! preg_match('!^(http|https|ftp)://!i', $package) && file_exists($package) ) //Local file or remote?
241                         return $package; //must be a local file..
242
243                 if ( empty($package) )
244                         return new WP_Error('no_package', $this->strings['no_package']);
245
246                 $this->skin->feedback('downloading_package', $package);
247
248                 $download_file = download_url($package);
249
250                 if ( is_wp_error($download_file) )
251                         return new WP_Error('download_failed', $this->strings['download_failed'], $download_file->get_error_message());
252
253                 return $download_file;
254         }
255
256         /**
257          * Unpack a compressed package file.
258          *
259          * @since 2.8.0
260          * @access public
261          *
262          * @global WP_Filesystem_Base $wp_filesystem Subclass
263          *
264          * @param string $package        Full path to the package file.
265          * @param bool   $delete_package Optional. Whether to delete the package file after attempting
266          *                               to unpack it. Default true.
267          * @return string|WP_Error The path to the unpacked contents, or a {@see WP_Error} on failure.
268          */
269         public function unpack_package( $package, $delete_package = true ) {
270                 global $wp_filesystem;
271
272                 $this->skin->feedback('unpack_package');
273
274                 $upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade/';
275
276                 //Clean up contents of upgrade directory beforehand.
277                 $upgrade_files = $wp_filesystem->dirlist($upgrade_folder);
278                 if ( !empty($upgrade_files) ) {
279                         foreach ( $upgrade_files as $file )
280                                 $wp_filesystem->delete($upgrade_folder . $file['name'], true);
281                 }
282
283                 // We need a working directory - Strip off any .tmp or .zip suffixes
284                 $working_dir = $upgrade_folder . basename( basename( $package, '.tmp' ), '.zip' );
285
286                 // Clean up working directory
287                 if ( $wp_filesystem->is_dir($working_dir) )
288                         $wp_filesystem->delete($working_dir, true);
289
290                 // Unzip package to working directory
291                 $result = unzip_file( $package, $working_dir );
292
293                 // Once extracted, delete the package if required.
294                 if ( $delete_package )
295                         unlink($package);
296
297                 if ( is_wp_error($result) ) {
298                         $wp_filesystem->delete($working_dir, true);
299                         if ( 'incompatible_archive' == $result->get_error_code() ) {
300                                 return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], $result->get_error_data() );
301                         }
302                         return $result;
303                 }
304
305                 return $working_dir;
306         }
307
308         /**
309          * Clears the directory where this item is going to be installed into.
310          *
311          * @since 4.3.0
312          * @access public
313          *
314          * @global WP_Filesystem_Base $wp_filesystem Subclass
315          *
316          * @param string $remote_destination The location on the remote filesystem to be cleared
317          * @return bool|WP_Error True upon success, WP_Error on failure.
318          */
319         public function clear_destination( $remote_destination ) {
320                 global $wp_filesystem;
321
322                 if ( ! $wp_filesystem->exists( $remote_destination ) ) {
323                         return true;
324                 }
325
326                 // Check all files are writable before attempting to clear the destination.
327                 $unwritable_files = array();
328
329                 $_files = $wp_filesystem->dirlist( $remote_destination, true, true );
330
331                 // Flatten the resulting array, iterate using each as we append to the array during iteration.
332                 while ( $f = each( $_files ) ) {
333                         $file = $f['value'];
334                         $name = $f['key'];
335
336                         if ( ! isset( $file['files'] ) ) {
337                                 continue;
338                         }
339
340                         foreach ( $file['files'] as $filename => $details ) {
341                                 $_files[ $name . '/' . $filename ] = $details;
342                         }
343                 }
344
345                 // Check writability.
346                 foreach ( $_files as $filename => $file_details ) {
347                         if ( ! $wp_filesystem->is_writable( $remote_destination . $filename ) ) {
348
349                                 // Attempt to alter permissions to allow writes and try again.
350                                 $wp_filesystem->chmod( $remote_destination . $filename, ( 'd' == $file_details['type'] ? FS_CHMOD_DIR : FS_CHMOD_FILE ) );
351                                 if ( ! $wp_filesystem->is_writable( $remote_destination . $filename ) ) {
352                                         $unwritable_files[] = $filename;
353                                 }
354                         }
355                 }
356
357                 if ( ! empty( $unwritable_files ) ) {
358                         return new WP_Error( 'files_not_writable', $this->strings['files_not_writable'], implode( ', ', $unwritable_files ) );
359                 }
360
361                 if ( ! $wp_filesystem->delete( $remote_destination, true ) ) {
362                         return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] );
363                 }
364
365                 return true;
366         }
367
368         /**
369          * Install a package.
370          *
371          * Copies the contents of a package form a source directory, and installs them in
372          * a destination directory. Optionally removes the source. It can also optionally
373          * clear out the destination folder if it already exists.
374          *
375          * @since 2.8.0
376          * @access public
377          *
378          * @global WP_Filesystem_Base $wp_filesystem Subclass
379          * @global array              $wp_theme_directories
380          *
381          * @param array|string $args {
382          *     Optional. Array or string of arguments for installing a package. Default empty array.
383          *
384          *     @type string $source                      Required path to the package source. Default empty.
385          *     @type string $destination                 Required path to a folder to install the package in.
386          *                                               Default empty.
387          *     @type bool   $clear_destination           Whether to delete any files already in the destination
388          *                                               folder. Default false.
389          *     @type bool   $clear_working               Whether to delete the files form the working directory
390          *                                               after copying to the destination. Default false.
391          *     @type bool   $abort_if_destination_exists Whether to abort the installation if
392          *                                               the destination folder already exists. Default true.
393          *     @type array  $hook_extra                  Extra arguments to pass to the filter hooks called by
394          *                                               {@see WP_Upgrader::install_package()}. Default empty array.
395          * }
396          *
397          * @return array|WP_Error The result (also stored in `WP_Upgrader:$result`), or a {@see WP_Error} on failure.
398          */
399         public function install_package( $args = array() ) {
400                 global $wp_filesystem, $wp_theme_directories;
401
402                 $defaults = array(
403                         'source' => '', // Please always pass this
404                         'destination' => '', // and this
405                         'clear_destination' => false,
406                         'clear_working' => false,
407                         'abort_if_destination_exists' => true,
408                         'hook_extra' => array()
409                 );
410
411                 $args = wp_parse_args($args, $defaults);
412
413                 // These were previously extract()'d.
414                 $source = $args['source'];
415                 $destination = $args['destination'];
416                 $clear_destination = $args['clear_destination'];
417
418                 @set_time_limit( 300 );
419
420                 if ( empty( $source ) || empty( $destination ) ) {
421                         return new WP_Error( 'bad_request', $this->strings['bad_request'] );
422                 }
423                 $this->skin->feedback( 'installing_package' );
424
425                 /**
426                  * Filter the install response before the installation has started.
427                  *
428                  * Returning a truthy value, or one that could be evaluated as a WP_Error
429                  * will effectively short-circuit the installation, returning that value
430                  * instead.
431                  *
432                  * @since 2.8.0
433                  *
434                  * @param bool|WP_Error $response   Response.
435                  * @param array         $hook_extra Extra arguments passed to hooked filters.
436                  */
437                 $res = apply_filters( 'upgrader_pre_install', true, $args['hook_extra'] );
438
439                 if ( is_wp_error( $res ) ) {
440                         return $res;
441                 }
442
443                 //Retain the Original source and destinations
444                 $remote_source = $args['source'];
445                 $local_destination = $destination;
446
447                 $source_files = array_keys( $wp_filesystem->dirlist( $remote_source ) );
448                 $remote_destination = $wp_filesystem->find_folder( $local_destination );
449
450                 //Locate which directory to copy to the new folder, This is based on the actual folder holding the files.
451                 if ( 1 == count( $source_files ) && $wp_filesystem->is_dir( trailingslashit( $args['source'] ) . $source_files[0] . '/' ) ) { //Only one folder? Then we want its contents.
452                         $source = trailingslashit( $args['source'] ) . trailingslashit( $source_files[0] );
453                 } elseif ( count( $source_files ) == 0 ) {
454                         return new WP_Error( 'incompatible_archive_empty', $this->strings['incompatible_archive'], $this->strings['no_files'] ); // There are no files?
455                 } else { // It's only a single file, the upgrader will use the folder name of this file as the destination folder. Folder name is based on zip filename.
456                         $source = trailingslashit( $args['source'] );
457                 }
458
459                 /**
460                  * Filter the source file location for the upgrade package.
461                  *
462                  * @since 2.8.0
463                  * @since 4.4.0 The $hook_extra parameter became available.
464                  *
465                  * @param string      $source        File source location.
466                  * @param string      $remote_source Remote file source location.
467                  * @param WP_Upgrader $this          WP_Upgrader instance.
468                  * @param array       $hook_extra    Extra arguments passed to hooked filters.
469                  */
470                 $source = apply_filters( 'upgrader_source_selection', $source, $remote_source, $this, $args['hook_extra'] );
471
472                 if ( is_wp_error( $source ) ) {
473                         return $source;
474                 }
475
476                 // Has the source location changed? If so, we need a new source_files list.
477                 if ( $source !== $remote_source ) {
478                         $source_files = array_keys( $wp_filesystem->dirlist( $source ) );
479                 }
480
481                 /*
482                  * Protection against deleting files in any important base directories.
483                  * Theme_Upgrader & Plugin_Upgrader also trigger this, as they pass the
484                  * destination directory (WP_PLUGIN_DIR / wp-content/themes) intending
485                  * to copy the directory into the directory, whilst they pass the source
486                  * as the actual files to copy.
487                  */
488                 $protected_directories = array( ABSPATH, WP_CONTENT_DIR, WP_PLUGIN_DIR, WP_CONTENT_DIR . '/themes' );
489
490                 if ( is_array( $wp_theme_directories ) ) {
491                         $protected_directories = array_merge( $protected_directories, $wp_theme_directories );
492                 }
493
494                 if ( in_array( $destination, $protected_directories ) ) {
495                         $remote_destination = trailingslashit( $remote_destination ) . trailingslashit( basename( $source ) );
496                         $destination = trailingslashit( $destination ) . trailingslashit( basename( $source ) );
497                 }
498
499                 if ( $clear_destination ) {
500                         // We're going to clear the destination if there's something there.
501                         $this->skin->feedback('remove_old');
502
503                         $removed = $this->clear_destination( $remote_destination );
504
505                         /**
506                          * Filter whether the upgrader cleared the destination.
507                          *
508                          * @since 2.8.0
509                          *
510                          * @param mixed  $removed            Whether the destination was cleared. true on success, WP_Error on failure
511                          * @param string $local_destination  The local package destination.
512                          * @param string $remote_destination The remote package destination.
513                          * @param array  $hook_extra         Extra arguments passed to hooked filters.
514                          */
515                         $removed = apply_filters( 'upgrader_clear_destination', $removed, $local_destination, $remote_destination, $args['hook_extra'] );
516
517                         if ( is_wp_error( $removed ) ) {
518                                 return $removed;
519                         }
520                 } elseif ( $args['abort_if_destination_exists'] && $wp_filesystem->exists($remote_destination) ) {
521                         //If we're not clearing the destination folder and something exists there already, Bail.
522                         //But first check to see if there are actually any files in the folder.
523                         $_files = $wp_filesystem->dirlist($remote_destination);
524                         if ( ! empty($_files) ) {
525                                 $wp_filesystem->delete($remote_source, true); //Clear out the source files.
526                                 return new WP_Error('folder_exists', $this->strings['folder_exists'], $remote_destination );
527                         }
528                 }
529
530                 //Create destination if needed
531                 if ( ! $wp_filesystem->exists( $remote_destination ) ) {
532                         if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) ) {
533                                 return new WP_Error( 'mkdir_failed_destination', $this->strings['mkdir_failed'], $remote_destination );
534                         }
535                 }
536                 // Copy new version of item into place.
537                 $result = copy_dir($source, $remote_destination);
538                 if ( is_wp_error($result) ) {
539                         if ( $args['clear_working'] ) {
540                                 $wp_filesystem->delete( $remote_source, true );
541                         }
542                         return $result;
543                 }
544
545                 //Clear the Working folder?
546                 if ( $args['clear_working'] ) {
547                         $wp_filesystem->delete( $remote_source, true );
548                 }
549
550                 $destination_name = basename( str_replace($local_destination, '', $destination) );
551                 if ( '.' == $destination_name ) {
552                         $destination_name = '';
553                 }
554
555                 $this->result = compact( 'source', 'source_files', 'destination', 'destination_name', 'local_destination', 'remote_destination', 'clear_destination' );
556
557                 /**
558                  * Filter the install response after the installation has finished.
559                  *
560                  * @since 2.8.0
561                  *
562                  * @param bool  $response   Install response.
563                  * @param array $hook_extra Extra arguments passed to hooked filters.
564                  * @param array $result     Installation result data.
565                  */
566                 $res = apply_filters( 'upgrader_post_install', true, $args['hook_extra'], $this->result );
567
568                 if ( is_wp_error($res) ) {
569                         $this->result = $res;
570                         return $res;
571                 }
572
573                 //Bombard the calling function will all the info which we've just used.
574                 return $this->result;
575         }
576
577         /**
578          * Run an upgrade/install.
579          *
580          * Attempts to download the package (if it is not a local file), unpack it, and
581          * install it in the destination folder.
582          *
583          * @since 2.8.0
584          * @access public
585          *
586          * @param array $options {
587          *     Array or string of arguments for upgrading/installing a package.
588          *
589          *     @type string $package                     The full path or URI of the package to install.
590          *                                               Default empty.
591          *     @type string $destination                 The full path to the destination folder.
592          *                                               Default empty.
593          *     @type bool   $clear_destination           Whether to delete any files already in the
594          *                                               destination folder. Default false.
595          *     @type bool   $clear_working               Whether to delete the files form the working
596          *                                               directory after copying to the destination.
597          *                                               Default false.
598          *     @type bool   $abort_if_destination_exists Whether to abort the installation if the destination
599          *                                               folder already exists. When true, `$clear_destination`
600          *                                               should be false. Default true.
601          *     @type bool   $is_multi                    Whether this run is one of multiple upgrade/install
602          *                                               actions being performed in bulk. When true, the skin
603          *                                               {@see WP_Upgrader::header()} and {@see WP_Upgrader::footer()}
604          *                                               aren't called. Default false.
605          *     @type array  $hook_extra                  Extra arguments to pass to the filter hooks called by
606          *                                               {@see WP_Upgrader::run()}.
607          * }
608          * @return array|false|WP_error The result from self::install_package() on success, otherwise a WP_Error,
609          *                              or false if unable to connect to the filesystem.
610          */
611         public function run( $options ) {
612
613                 $defaults = array(
614                         'package' => '', // Please always pass this.
615                         'destination' => '', // And this
616                         'clear_destination' => false,
617                         'abort_if_destination_exists' => true, // Abort if the Destination directory exists, Pass clear_destination as false please
618                         'clear_working' => true,
619                         'is_multi' => false,
620                         'hook_extra' => array() // Pass any extra $hook_extra args here, this will be passed to any hooked filters.
621                 );
622
623                 $options = wp_parse_args( $options, $defaults );
624
625                 /**
626                  * Filter the package options before running an update.
627                  *
628                  * @since 4.3.0
629                  *
630                  * @param array $options {
631                  *     Options used by the upgrader.
632                  *
633                  *     @type string $package                     Package for update.
634                  *     @type string $destination                 Update location.
635                  *     @type bool   $clear_destination           Clear the destination resource.
636                  *     @type bool   $clear_working               Clear the working resource.
637                  *     @type bool   $abort_if_destination_exists Abort if the Destination directory exists.
638                  *     @type bool   $is_multi                    Whether the upgrader is running multiple times.
639                  *     @type array  $hook_extra                  Extra hook arguments.
640                  * }
641                  */
642                 $options = apply_filters( 'upgrader_package_options', $options );
643
644                 if ( ! $options['is_multi'] ) { // call $this->header separately if running multiple times
645                         $this->skin->header();
646                 }
647
648                 // Connect to the Filesystem first.
649                 $res = $this->fs_connect( array( WP_CONTENT_DIR, $options['destination'] ) );
650                 // Mainly for non-connected filesystem.
651                 if ( ! $res ) {
652                         if ( ! $options['is_multi'] ) {
653                                 $this->skin->footer();
654                         }
655                         return false;
656                 }
657
658                 $this->skin->before();
659
660                 if ( is_wp_error($res) ) {
661                         $this->skin->error($res);
662                         $this->skin->after();
663                         if ( ! $options['is_multi'] ) {
664                                 $this->skin->footer();
665                         }
666                         return $res;
667                 }
668
669                 /*
670                  * Download the package (Note, This just returns the filename
671                  * of the file if the package is a local file)
672                  */
673                 $download = $this->download_package( $options['package'] );
674                 if ( is_wp_error($download) ) {
675                         $this->skin->error($download);
676                         $this->skin->after();
677                         if ( ! $options['is_multi'] ) {
678                                 $this->skin->footer();
679                         }
680                         return $download;
681                 }
682
683                 $delete_package = ( $download != $options['package'] ); // Do not delete a "local" file
684
685                 // Unzips the file into a temporary directory.
686                 $working_dir = $this->unpack_package( $download, $delete_package );
687                 if ( is_wp_error($working_dir) ) {
688                         $this->skin->error($working_dir);
689                         $this->skin->after();
690                         if ( ! $options['is_multi'] ) {
691                                 $this->skin->footer();
692                         }
693                         return $working_dir;
694                 }
695
696                 // With the given options, this installs it to the destination directory.
697                 $result = $this->install_package( array(
698                         'source' => $working_dir,
699                         'destination' => $options['destination'],
700                         'clear_destination' => $options['clear_destination'],
701                         'abort_if_destination_exists' => $options['abort_if_destination_exists'],
702                         'clear_working' => $options['clear_working'],
703                         'hook_extra' => $options['hook_extra']
704                 ) );
705
706                 $this->skin->set_result($result);
707                 if ( is_wp_error($result) ) {
708                         $this->skin->error($result);
709                         $this->skin->feedback('process_failed');
710                 } else {
711                         // Install succeeded.
712                         $this->skin->feedback('process_success');
713                 }
714
715                 $this->skin->after();
716
717                 if ( ! $options['is_multi'] ) {
718
719                         /** This action is documented in wp-admin/includes/class-wp-upgrader.php */
720                         do_action( 'upgrader_process_complete', $this, $options['hook_extra'] );
721                         $this->skin->footer();
722                 }
723
724                 return $result;
725         }
726
727         /**
728          * Toggle maintenance mode for the site.
729          *
730          * Creates/deletes the maintenance file to enable/disable maintenance mode.
731          *
732          * @since 2.8.0
733          * @access public
734          *
735          * @global WP_Filesystem_Base $wp_filesystem Subclass
736          *
737          * @param bool $enable True to enable maintenance mode, false to disable.
738          */
739         public function maintenance_mode( $enable = false ) {
740                 global $wp_filesystem;
741                 $file = $wp_filesystem->abspath() . '.maintenance';
742                 if ( $enable ) {
743                         $this->skin->feedback('maintenance_start');
744                         // Create maintenance file to signal that we are upgrading
745                         $maintenance_string = '<?php $upgrading = ' . time() . '; ?>';
746                         $wp_filesystem->delete($file);
747                         $wp_filesystem->put_contents($file, $maintenance_string, FS_CHMOD_FILE);
748                 } elseif ( ! $enable && $wp_filesystem->exists( $file ) ) {
749                         $this->skin->feedback('maintenance_end');
750                         $wp_filesystem->delete($file);
751                 }
752         }
753
754         /**
755          * Creates a lock using WordPress options.
756          *
757          * @since 4.5.0
758          * @access public
759          * @static
760          *
761          * @param string $lock_name       The name of this unique lock.
762          * @param int    $release_timeout Optional. The duration in seconds to respect an existing lock.
763          *                                Default: 1 hour.
764          * @return bool False if a lock couldn't be created or if the lock is no longer valid. True otherwise.
765          */
766         public static function create_lock( $lock_name, $release_timeout = null ) {
767                 global $wpdb;
768                 if ( ! $release_timeout ) {
769                         $release_timeout = HOUR_IN_SECONDS;
770                 }
771                 $lock_option = $lock_name . '.lock';
772
773                 // Try to lock.
774                 $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_option, time() ) );
775
776                 if ( ! $lock_result ) {
777                         $lock_result = get_option( $lock_option );
778
779                         // If a lock couldn't be created, and there isn't a lock, bail.
780                         if ( ! $lock_result ) {
781                                 return false;
782                         }
783
784                         // Check to see if the lock is still valid. If not, bail.
785                         if ( $lock_result > ( time() - $release_timeout ) ) {
786                                 return false;
787                         }
788
789                         // There must exist an expired lock, clear it and re-gain it.
790                         WP_Upgrader::release_lock( $lock_name );
791
792                         return WP_Upgrader::create_lock( $lock_name, $release_timeout );
793                 }
794
795                 // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
796                 update_option( $lock_option, time() );
797
798                 return true;
799         }
800
801         /**
802          * Releases an upgrader lock.
803          *
804          * @since 4.5.0
805          * @access public
806          * @static
807          *
808          * @see WP_Upgrader::create_lock()
809          *
810          * @param string $lock_name The name of this unique lock.
811          * @return bool True if the lock was successfully released. False on failure.
812          */
813         public static function release_lock( $lock_name ) {
814                 return delete_option( $lock_name . '.lock' );
815         }
816
817 }
818
819 /**
820  * Core class used for upgrading/installing plugins.
821  *
822  * It is designed to upgrade/install plugins from a local zip, remote zip URL,
823  * or uploaded zip file.
824  *
825  * @since 2.8.0
826  *
827  * @see WP_Upgrader
828  */
829 class Plugin_Upgrader extends WP_Upgrader {
830
831         /**
832          * Plugin upgrade result.
833          *
834          * @since 2.8.0
835          * @access public
836          * @var array|WP_Error $result
837          *
838          * @see WP_Upgrader::$result
839          */
840         public $result;
841
842         /**
843          * Whether a bulk upgrade/install is being performed.
844          *
845          * @since 2.9.0
846          * @access public
847          * @var bool $bulk
848          */
849         public $bulk = false;
850
851         /**
852          * Initialize the upgrade strings.
853          *
854          * @since 2.8.0
855          * @access public
856          */
857         public function upgrade_strings() {
858                 $this->strings['up_to_date'] = __('The plugin is at the latest version.');
859                 $this->strings['no_package'] = __('Update package not available.');
860                 $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;');
861                 $this->strings['unpack_package'] = __('Unpacking the update&#8230;');
862                 $this->strings['remove_old'] = __('Removing the old version of the plugin&#8230;');
863                 $this->strings['remove_old_failed'] = __('Could not remove the old plugin.');
864                 $this->strings['process_failed'] = __('Plugin update failed.');
865                 $this->strings['process_success'] = __('Plugin updated successfully.');
866                 $this->strings['process_bulk_success'] = __('Plugins updated successfully.');
867         }
868
869         /**
870          * Initialize the install strings.
871          *
872          * @since 2.8.0
873          * @access public
874          */
875         public function install_strings() {
876                 $this->strings['no_package'] = __('Install package not available.');
877                 $this->strings['downloading_package'] = __('Downloading install package from <span class="code">%s</span>&#8230;');
878                 $this->strings['unpack_package'] = __('Unpacking the package&#8230;');
879                 $this->strings['installing_package'] = __('Installing the plugin&#8230;');
880                 $this->strings['no_files'] = __('The plugin contains no files.');
881                 $this->strings['process_failed'] = __('Plugin install failed.');
882                 $this->strings['process_success'] = __('Plugin installed successfully.');
883         }
884
885         /**
886          * Install a plugin package.
887          *
888          * @since 2.8.0
889          * @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional.
890          * @access public
891          *
892          * @param string $package The full local path or URI of the package.
893          * @param array  $args {
894          *     Optional. Other arguments for installing a plugin package. Default empty array.
895          *
896          *     @type bool $clear_update_cache Whether to clear the plugin updates cache if successful.
897          *                                    Default true.
898          * }
899          * @return bool|WP_Error True if the install was successful, false or a WP_Error otherwise.
900          */
901         public function install( $package, $args = array() ) {
902
903                 $defaults = array(
904                         'clear_update_cache' => true,
905                 );
906                 $parsed_args = wp_parse_args( $args, $defaults );
907
908                 $this->init();
909                 $this->install_strings();
910
911                 add_filter('upgrader_source_selection', array($this, 'check_package') );
912                 // Clear cache so wp_update_plugins() knows about the new plugin.
913                 add_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9, 0 );
914
915                 $this->run( array(
916                         'package' => $package,
917                         'destination' => WP_PLUGIN_DIR,
918                         'clear_destination' => false, // Do not overwrite files.
919                         'clear_working' => true,
920                         'hook_extra' => array(
921                                 'type' => 'plugin',
922                                 'action' => 'install',
923                         )
924                 ) );
925
926                 remove_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9 );
927                 remove_filter('upgrader_source_selection', array($this, 'check_package') );
928
929                 if ( ! $this->result || is_wp_error($this->result) )
930                         return $this->result;
931
932                 // Force refresh of plugin update information
933                 wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
934
935                 return true;
936         }
937
938         /**
939          * Upgrade a plugin.
940          *
941          * @since 2.8.0
942          * @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional.
943          * @access public
944          *
945          * @param string $plugin The basename path to the main plugin file.
946          * @param array  $args {
947          *     Optional. Other arguments for upgrading a plugin package. Default empty array.
948          *
949          *     @type bool $clear_update_cache Whether to clear the plugin updates cache if successful.
950          *                                    Default true.
951          * }
952          * @return bool|WP_Error True if the upgrade was successful, false or a {@see WP_Error} object otherwise.
953          */
954         public function upgrade( $plugin, $args = array() ) {
955
956                 $defaults = array(
957                         'clear_update_cache' => true,
958                 );
959                 $parsed_args = wp_parse_args( $args, $defaults );
960
961                 $this->init();
962                 $this->upgrade_strings();
963
964                 $current = get_site_transient( 'update_plugins' );
965                 if ( !isset( $current->response[ $plugin ] ) ) {
966                         $this->skin->before();
967                         $this->skin->set_result(false);
968                         $this->skin->error('up_to_date');
969                         $this->skin->after();
970                         return false;
971                 }
972
973                 // Get the URL to the zip file
974                 $r = $current->response[ $plugin ];
975
976                 add_filter('upgrader_pre_install', array($this, 'deactivate_plugin_before_upgrade'), 10, 2);
977                 add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4);
978                 //'source_selection' => array($this, 'source_selection'), //there's a trac ticket to move up the directory for zip's which are made a bit differently, useful for non-.org plugins.
979
980                 $this->run( array(
981                         'package' => $r->package,
982                         'destination' => WP_PLUGIN_DIR,
983                         'clear_destination' => true,
984                         'clear_working' => true,
985                         'hook_extra' => array(
986                                 'plugin' => $plugin,
987                                 'type' => 'plugin',
988                                 'action' => 'update',
989                         ),
990                 ) );
991
992                 // Cleanup our hooks, in case something else does a upgrade on this connection.
993                 remove_filter('upgrader_pre_install', array($this, 'deactivate_plugin_before_upgrade'));
994                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'));
995
996                 if ( ! $this->result || is_wp_error($this->result) )
997                         return $this->result;
998
999                 // Force refresh of plugin update information
1000                 wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
1001
1002                 return true;
1003         }
1004
1005         /**
1006          * Bulk upgrade several plugins at once.
1007          *
1008          * @since 2.8.0
1009          * @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional.
1010          * @access public
1011          *
1012          * @param array $plugins Array of the basename paths of the plugins' main files.
1013          * @param array $args {
1014          *     Optional. Other arguments for upgrading several plugins at once. Default empty array.
1015          *
1016          *     @type bool $clear_update_cache Whether to clear the plugin updates cache if successful.
1017          *                                    Default true.
1018          * }
1019          * @return array|false An array of results indexed by plugin file, or false if unable to connect to the filesystem.
1020          */
1021         public function bulk_upgrade( $plugins, $args = array() ) {
1022
1023                 $defaults = array(
1024                         'clear_update_cache' => true,
1025                 );
1026                 $parsed_args = wp_parse_args( $args, $defaults );
1027
1028                 $this->init();
1029                 $this->bulk = true;
1030                 $this->upgrade_strings();
1031
1032                 $current = get_site_transient( 'update_plugins' );
1033
1034                 add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4);
1035
1036                 $this->skin->header();
1037
1038                 // Connect to the Filesystem first.
1039                 $res = $this->fs_connect( array(WP_CONTENT_DIR, WP_PLUGIN_DIR) );
1040                 if ( ! $res ) {
1041                         $this->skin->footer();
1042                         return false;
1043                 }
1044
1045                 $this->skin->bulk_header();
1046
1047                 /*
1048                  * Only start maintenance mode if:
1049                  * - running Multisite and there are one or more plugins specified, OR
1050                  * - a plugin with an update available is currently active.
1051                  * @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
1052                  */
1053                 $maintenance = ( is_multisite() && ! empty( $plugins ) );
1054                 foreach ( $plugins as $plugin )
1055                         $maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin] ) );
1056                 if ( $maintenance )
1057                         $this->maintenance_mode(true);
1058
1059                 $results = array();
1060
1061                 $this->update_count = count($plugins);
1062                 $this->update_current = 0;
1063                 foreach ( $plugins as $plugin ) {
1064                         $this->update_current++;
1065                         $this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true);
1066
1067                         if ( !isset( $current->response[ $plugin ] ) ) {
1068                                 $this->skin->set_result('up_to_date');
1069                                 $this->skin->before();
1070                                 $this->skin->feedback('up_to_date');
1071                                 $this->skin->after();
1072                                 $results[$plugin] = true;
1073                                 continue;
1074                         }
1075
1076                         // Get the URL to the zip file.
1077                         $r = $current->response[ $plugin ];
1078
1079                         $this->skin->plugin_active = is_plugin_active($plugin);
1080
1081                         $result = $this->run( array(
1082                                 'package' => $r->package,
1083                                 'destination' => WP_PLUGIN_DIR,
1084                                 'clear_destination' => true,
1085                                 'clear_working' => true,
1086                                 'is_multi' => true,
1087                                 'hook_extra' => array(
1088                                         'plugin' => $plugin
1089                                 )
1090                         ) );
1091
1092                         $results[$plugin] = $this->result;
1093
1094                         // Prevent credentials auth screen from displaying multiple times
1095                         if ( false === $result )
1096                                 break;
1097                 } //end foreach $plugins
1098
1099                 $this->maintenance_mode(false);
1100
1101                 /**
1102                  * Fires when the bulk upgrader process is complete.
1103                  *
1104                  * @since 3.6.0
1105                  *
1106                  * @param Plugin_Upgrader $this Plugin_Upgrader instance. In other contexts, $this, might
1107                  *                              be a Theme_Upgrader or Core_Upgrade instance.
1108                  * @param array           $data {
1109                  *     Array of bulk item update data.
1110                  *
1111                  *     @type string $action   Type of action. Default 'update'.
1112                  *     @type string $type     Type of update process. Accepts 'plugin', 'theme', or 'core'.
1113                  *     @type bool   $bulk     Whether the update process is a bulk update. Default true.
1114                  *     @type array  $packages Array of plugin, theme, or core packages to update.
1115                  * }
1116                  */
1117                 do_action( 'upgrader_process_complete', $this, array(
1118                         'action' => 'update',
1119                         'type' => 'plugin',
1120                         'bulk' => true,
1121                         'plugins' => $plugins,
1122                 ) );
1123
1124                 $this->skin->bulk_footer();
1125
1126                 $this->skin->footer();
1127
1128                 // Cleanup our hooks, in case something else does a upgrade on this connection.
1129                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'));
1130
1131                 // Force refresh of plugin update information.
1132                 wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
1133
1134                 return $results;
1135         }
1136
1137         /**
1138          * Check a source package to be sure it contains a plugin.
1139          *
1140          * This function is added to the {@see 'upgrader_source_selection'} filter by
1141          * {@see Plugin_Upgrader::install()}.
1142          *
1143          * @since 3.3.0
1144          * @access public
1145          *
1146          * @global WP_Filesystem_Base $wp_filesystem Subclass
1147          *
1148          * @param string $source The path to the downloaded package source.
1149          * @return string|WP_Error The source as passed, or a {@see WP_Error} object
1150          *                         if no plugins were found.
1151          */
1152         public function check_package($source) {
1153                 global $wp_filesystem;
1154
1155                 if ( is_wp_error($source) )
1156                         return $source;
1157
1158                 $working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit(WP_CONTENT_DIR), $source);
1159                 if ( ! is_dir($working_directory) ) // Sanity check, if the above fails, let's not prevent installation.
1160                         return $source;
1161
1162                 // Check the folder contains at least 1 valid plugin.
1163                 $plugins_found = false;
1164                 $files = glob( $working_directory . '*.php' );
1165                 if ( $files ) {
1166                         foreach ( $files as $file ) {
1167                                 $info = get_plugin_data( $file, false, false );
1168                                 if ( ! empty( $info['Name'] ) ) {
1169                                         $plugins_found = true;
1170                                         break;
1171                                 }
1172                         }
1173                 }
1174
1175                 if ( ! $plugins_found )
1176                         return new WP_Error( 'incompatible_archive_no_plugins', $this->strings['incompatible_archive'], __( 'No valid plugins were found.' ) );
1177
1178                 return $source;
1179         }
1180
1181         /**
1182          * Retrieve the path to the file that contains the plugin info.
1183          *
1184          * This isn't used internally in the class, but is called by the skins.
1185          *
1186          * @since 2.8.0
1187          * @access public
1188          *
1189          * @return string|false The full path to the main plugin file, or false.
1190          */
1191         public function plugin_info() {
1192                 if ( ! is_array($this->result) )
1193                         return false;
1194                 if ( empty($this->result['destination_name']) )
1195                         return false;
1196
1197                 $plugin = get_plugins('/' . $this->result['destination_name']); //Ensure to pass with leading slash
1198                 if ( empty($plugin) )
1199                         return false;
1200
1201                 $pluginfiles = array_keys($plugin); //Assume the requested plugin is the first in the list
1202
1203                 return $this->result['destination_name'] . '/' . $pluginfiles[0];
1204         }
1205
1206         /**
1207          * Deactivates a plugin before it is upgraded.
1208          *
1209          * Hooked to the {@see 'upgrader_pre_install'} filter by {@see Plugin_Upgrader::upgrade()}.
1210          *
1211          * @since 2.8.0
1212          * @since 4.1.0 Added a return value.
1213          * @access public
1214          *
1215          * @param bool|WP_Error  $return Upgrade offer return.
1216          * @param array          $plugin Plugin package arguments.
1217          * @return bool|WP_Error The passed in $return param or {@see WP_Error}.
1218          */
1219         public function deactivate_plugin_before_upgrade($return, $plugin) {
1220
1221                 if ( is_wp_error($return) ) //Bypass.
1222                         return $return;
1223
1224                 // When in cron (background updates) don't deactivate the plugin, as we require a browser to reactivate it
1225                 if ( defined( 'DOING_CRON' ) && DOING_CRON )
1226                         return $return;
1227
1228                 $plugin = isset($plugin['plugin']) ? $plugin['plugin'] : '';
1229                 if ( empty($plugin) )
1230                         return new WP_Error('bad_request', $this->strings['bad_request']);
1231
1232                 if ( is_plugin_active($plugin) ) {
1233                         //Deactivate the plugin silently, Prevent deactivation hooks from running.
1234                         deactivate_plugins($plugin, true);
1235                 }
1236
1237                 return $return;
1238         }
1239
1240         /**
1241          * Delete the old plugin during an upgrade.
1242          *
1243          * Hooked to the {@see 'upgrader_clear_destination'} filter by
1244          * {@see Plugin_Upgrader::upgrade()} and {@see Plugin_Upgrader::bulk_upgrade()}.
1245          *
1246          * @since 2.8.0
1247          * @access public
1248          *
1249          * @global WP_Filesystem_Base $wp_filesystem Subclass
1250      *
1251          * @param bool|WP_Error $removed
1252          * @param string        $local_destination
1253          * @param string        $remote_destination
1254          * @param array         $plugin
1255          * @return WP_Error|bool
1256          */
1257         public function delete_old_plugin($removed, $local_destination, $remote_destination, $plugin) {
1258                 global $wp_filesystem;
1259
1260                 if ( is_wp_error($removed) )
1261                         return $removed; //Pass errors through.
1262
1263                 $plugin = isset($plugin['plugin']) ? $plugin['plugin'] : '';
1264                 if ( empty($plugin) )
1265                         return new WP_Error('bad_request', $this->strings['bad_request']);
1266
1267                 $plugins_dir = $wp_filesystem->wp_plugins_dir();
1268                 $this_plugin_dir = trailingslashit( dirname($plugins_dir . $plugin) );
1269
1270                 if ( ! $wp_filesystem->exists($this_plugin_dir) ) //If it's already vanished.
1271                         return $removed;
1272
1273                 // If plugin is in its own directory, recursively delete the directory.
1274                 if ( strpos($plugin, '/') && $this_plugin_dir != $plugins_dir ) //base check on if plugin includes directory separator AND that it's not the root plugin folder
1275                         $deleted = $wp_filesystem->delete($this_plugin_dir, true);
1276                 else
1277                         $deleted = $wp_filesystem->delete($plugins_dir . $plugin);
1278
1279                 if ( ! $deleted )
1280                         return new WP_Error('remove_old_failed', $this->strings['remove_old_failed']);
1281
1282                 return true;
1283         }
1284 }
1285
1286 /**
1287  * Core class used for upgrading/installing themes.
1288  *
1289  * It is designed to upgrade/install themes from a local zip, remote zip URL,
1290  * or uploaded zip file.
1291  *
1292  * @since 2.8.0
1293  *
1294  * @see WP_Upgrader
1295  */
1296 class Theme_Upgrader extends WP_Upgrader {
1297
1298         /**
1299          * Result of the theme upgrade offer.
1300          *
1301          * @since 2.8.0
1302          * @access public
1303          * @var array|WP_Error $result
1304          * @see WP_Upgrader::$result
1305          */
1306         public $result;
1307
1308         /**
1309          * Whether multiple themes are being upgraded/installed in bulk.
1310          *
1311          * @since 2.9.0
1312          * @access public
1313          * @var bool $bulk
1314          */
1315         public $bulk = false;
1316
1317         /**
1318          * Initialize the upgrade strings.
1319          *
1320          * @since 2.8.0
1321          * @access public
1322          */
1323         public function upgrade_strings() {
1324                 $this->strings['up_to_date'] = __('The theme is at the latest version.');
1325                 $this->strings['no_package'] = __('Update package not available.');
1326                 $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;');
1327                 $this->strings['unpack_package'] = __('Unpacking the update&#8230;');
1328                 $this->strings['remove_old'] = __('Removing the old version of the theme&#8230;');
1329                 $this->strings['remove_old_failed'] = __('Could not remove the old theme.');
1330                 $this->strings['process_failed'] = __('Theme update failed.');
1331                 $this->strings['process_success'] = __('Theme updated successfully.');
1332         }
1333
1334         /**
1335          * Initialize the install strings.
1336          *
1337          * @since 2.8.0
1338          * @access public
1339          */
1340         public function install_strings() {
1341                 $this->strings['no_package'] = __('Install package not available.');
1342                 $this->strings['downloading_package'] = __('Downloading install package from <span class="code">%s</span>&#8230;');
1343                 $this->strings['unpack_package'] = __('Unpacking the package&#8230;');
1344                 $this->strings['installing_package'] = __('Installing the theme&#8230;');
1345                 $this->strings['no_files'] = __('The theme contains no files.');
1346                 $this->strings['process_failed'] = __('Theme install failed.');
1347                 $this->strings['process_success'] = __('Theme installed successfully.');
1348                 /* translators: 1: theme name, 2: version */
1349                 $this->strings['process_success_specific'] = __('Successfully installed the theme <strong>%1$s %2$s</strong>.');
1350                 $this->strings['parent_theme_search'] = __('This theme requires a parent theme. Checking if it is installed&#8230;');
1351                 /* translators: 1: theme name, 2: version */
1352                 $this->strings['parent_theme_prepare_install'] = __('Preparing to install <strong>%1$s %2$s</strong>&#8230;');
1353                 /* translators: 1: theme name, 2: version */
1354                 $this->strings['parent_theme_currently_installed'] = __('The parent theme, <strong>%1$s %2$s</strong>, is currently installed.');
1355                 /* translators: 1: theme name, 2: version */
1356                 $this->strings['parent_theme_install_success'] = __('Successfully installed the parent theme, <strong>%1$s %2$s</strong>.');
1357                 $this->strings['parent_theme_not_found'] = __('<strong>The parent theme could not be found.</strong> You will need to install the parent theme, <strong>%s</strong>, before you can use this child theme.');
1358         }
1359
1360         /**
1361          * Check if a child theme is being installed and we need to install its parent.
1362          *
1363          * Hooked to the {@see 'upgrader_post_install'} filter by {@see Theme_Upgrader::install()}.
1364          *
1365          * @since 3.4.0
1366          * @access public
1367          *
1368          * @param bool  $install_result
1369          * @param array $hook_extra
1370          * @param array $child_result
1371          * @return type
1372          */
1373         public function check_parent_theme_filter( $install_result, $hook_extra, $child_result ) {
1374                 // Check to see if we need to install a parent theme
1375                 $theme_info = $this->theme_info();
1376
1377                 if ( ! $theme_info->parent() )
1378                         return $install_result;
1379
1380                 $this->skin->feedback( 'parent_theme_search' );
1381
1382                 if ( ! $theme_info->parent()->errors() ) {
1383                         $this->skin->feedback( 'parent_theme_currently_installed', $theme_info->parent()->display('Name'), $theme_info->parent()->display('Version') );
1384                         // We already have the theme, fall through.
1385                         return $install_result;
1386                 }
1387
1388                 // We don't have the parent theme, let's install it.
1389                 $api = themes_api('theme_information', array('slug' => $theme_info->get('Template'), 'fields' => array('sections' => false, 'tags' => false) ) ); //Save on a bit of bandwidth.
1390
1391                 if ( ! $api || is_wp_error($api) ) {
1392                         $this->skin->feedback( 'parent_theme_not_found', $theme_info->get('Template') );
1393                         // Don't show activate or preview actions after install
1394                         add_filter('install_theme_complete_actions', array($this, 'hide_activate_preview_actions') );
1395                         return $install_result;
1396                 }
1397
1398                 // Backup required data we're going to override:
1399                 $child_api = $this->skin->api;
1400                 $child_success_message = $this->strings['process_success'];
1401
1402                 // Override them
1403                 $this->skin->api = $api;
1404                 $this->strings['process_success_specific'] = $this->strings['parent_theme_install_success'];//, $api->name, $api->version);
1405
1406                 $this->skin->feedback('parent_theme_prepare_install', $api->name, $api->version);
1407
1408                 add_filter('install_theme_complete_actions', '__return_false', 999); // Don't show any actions after installing the theme.
1409
1410                 // Install the parent theme
1411                 $parent_result = $this->run( array(
1412                         'package' => $api->download_link,
1413                         'destination' => get_theme_root(),
1414                         'clear_destination' => false, //Do not overwrite files.
1415                         'clear_working' => true
1416                 ) );
1417
1418                 if ( is_wp_error($parent_result) )
1419                         add_filter('install_theme_complete_actions', array($this, 'hide_activate_preview_actions') );
1420
1421                 // Start cleaning up after the parents installation
1422                 remove_filter('install_theme_complete_actions', '__return_false', 999);
1423
1424                 // Reset child's result and data
1425                 $this->result = $child_result;
1426                 $this->skin->api = $child_api;
1427                 $this->strings['process_success'] = $child_success_message;
1428
1429                 return $install_result;
1430         }
1431
1432         /**
1433          * Don't display the activate and preview actions to the user.
1434          *
1435          * Hooked to the {@see 'install_theme_complete_actions'} filter by
1436          * {@see Theme_Upgrader::check_parent_theme_filter()} when installing
1437          * a child theme and installing the parent theme fails.
1438          *
1439          * @since 3.4.0
1440          * @access public
1441          *
1442          * @param array $actions Preview actions.
1443          * @return array
1444          */
1445         public function hide_activate_preview_actions( $actions ) {
1446                 unset($actions['activate'], $actions['preview']);
1447                 return $actions;
1448         }
1449
1450         /**
1451          * Install a theme package.
1452          *
1453          * @since 2.8.0
1454          * @since 3.7.0 The `$args` parameter was added, making clearing the update cache optional.
1455          * @access public
1456          *
1457          * @param string $package The full local path or URI of the package.
1458          * @param array  $args {
1459          *     Optional. Other arguments for installing a theme package. Default empty array.
1460          *
1461          *     @type bool $clear_update_cache Whether to clear the updates cache if successful.
1462          *                                    Default true.
1463          * }
1464          *
1465          * @return bool|WP_Error True if the install was successful, false or a {@see WP_Error} object otherwise.
1466          */
1467         public function install( $package, $args = array() ) {
1468
1469                 $defaults = array(
1470                         'clear_update_cache' => true,
1471                 );
1472                 $parsed_args = wp_parse_args( $args, $defaults );
1473
1474                 $this->init();
1475                 $this->install_strings();
1476
1477                 add_filter('upgrader_source_selection', array($this, 'check_package') );
1478                 add_filter('upgrader_post_install', array($this, 'check_parent_theme_filter'), 10, 3);
1479                 // Clear cache so wp_update_themes() knows about the new theme.
1480                 add_action( 'upgrader_process_complete', 'wp_clean_themes_cache', 9, 0 );
1481
1482                 $this->run( array(
1483                         'package' => $package,
1484                         'destination' => get_theme_root(),
1485                         'clear_destination' => false, //Do not overwrite files.
1486                         'clear_working' => true,
1487                         'hook_extra' => array(
1488                                 'type' => 'theme',
1489                                 'action' => 'install',
1490                         ),
1491                 ) );
1492
1493                 remove_action( 'upgrader_process_complete', 'wp_clean_themes_cache', 9 );
1494                 remove_filter('upgrader_source_selection', array($this, 'check_package') );
1495                 remove_filter('upgrader_post_install', array($this, 'check_parent_theme_filter'));
1496
1497                 if ( ! $this->result || is_wp_error($this->result) )
1498                         return $this->result;
1499
1500                 // Refresh the Theme Update information
1501                 wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
1502
1503                 return true;
1504         }
1505
1506         /**
1507          * Upgrade a theme.
1508          *
1509          * @since 2.8.0
1510          * @since 3.7.0 The `$args` parameter was added, making clearing the update cache optional.
1511          * @access public
1512          *
1513          * @param string $theme The theme slug.
1514          * @param array  $args {
1515          *     Optional. Other arguments for upgrading a theme. Default empty array.
1516          *
1517          *     @type bool $clear_update_cache Whether to clear the update cache if successful.
1518          *                                    Default true.
1519          * }
1520          * @return bool|WP_Error True if the upgrade was successful, false or a {@see WP_Error} object otherwise.
1521          */
1522         public function upgrade( $theme, $args = array() ) {
1523
1524                 $defaults = array(
1525                         'clear_update_cache' => true,
1526                 );
1527                 $parsed_args = wp_parse_args( $args, $defaults );
1528
1529                 $this->init();
1530                 $this->upgrade_strings();
1531
1532                 // Is an update available?
1533                 $current = get_site_transient( 'update_themes' );
1534                 if ( !isset( $current->response[ $theme ] ) ) {
1535                         $this->skin->before();
1536                         $this->skin->set_result(false);
1537                         $this->skin->error( 'up_to_date' );
1538                         $this->skin->after();
1539                         return false;
1540                 }
1541
1542                 $r = $current->response[ $theme ];
1543
1544                 add_filter('upgrader_pre_install', array($this, 'current_before'), 10, 2);
1545                 add_filter('upgrader_post_install', array($this, 'current_after'), 10, 2);
1546                 add_filter('upgrader_clear_destination', array($this, 'delete_old_theme'), 10, 4);
1547
1548                 $this->run( array(
1549                         'package' => $r['package'],
1550                         'destination' => get_theme_root( $theme ),
1551                         'clear_destination' => true,
1552                         'clear_working' => true,
1553                         'hook_extra' => array(
1554                                 'theme' => $theme,
1555                                 'type' => 'theme',
1556                                 'action' => 'update',
1557                         ),
1558                 ) );
1559
1560                 remove_filter('upgrader_pre_install', array($this, 'current_before'));
1561                 remove_filter('upgrader_post_install', array($this, 'current_after'));
1562                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_theme'));
1563
1564                 if ( ! $this->result || is_wp_error($this->result) )
1565                         return $this->result;
1566
1567                 wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
1568
1569                 return true;
1570         }
1571
1572         /**
1573          * Upgrade several themes at once.
1574          *
1575          * @since 3.0.0
1576          * @since 3.7.0 The `$args` parameter was added, making clearing the update cache optional.
1577          * @access public
1578          *
1579          * @param array $themes The theme slugs.
1580          * @param array $args {
1581          *     Optional. Other arguments for upgrading several themes at once. Default empty array.
1582          *
1583          *     @type bool $clear_update_cache Whether to clear the update cache if successful.
1584          *                                    Default true.
1585          * }
1586          * @return array[]|false An array of results, or false if unable to connect to the filesystem.
1587          */
1588         public function bulk_upgrade( $themes, $args = array() ) {
1589
1590                 $defaults = array(
1591                         'clear_update_cache' => true,
1592                 );
1593                 $parsed_args = wp_parse_args( $args, $defaults );
1594
1595                 $this->init();
1596                 $this->bulk = true;
1597                 $this->upgrade_strings();
1598
1599                 $current = get_site_transient( 'update_themes' );
1600
1601                 add_filter('upgrader_pre_install', array($this, 'current_before'), 10, 2);
1602                 add_filter('upgrader_post_install', array($this, 'current_after'), 10, 2);
1603                 add_filter('upgrader_clear_destination', array($this, 'delete_old_theme'), 10, 4);
1604
1605                 $this->skin->header();
1606
1607                 // Connect to the Filesystem first.
1608                 $res = $this->fs_connect( array(WP_CONTENT_DIR) );
1609                 if ( ! $res ) {
1610                         $this->skin->footer();
1611                         return false;
1612                 }
1613
1614                 $this->skin->bulk_header();
1615
1616                 // Only start maintenance mode if:
1617                 // - running Multisite and there are one or more themes specified, OR
1618                 // - a theme with an update available is currently in use.
1619                 // @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
1620                 $maintenance = ( is_multisite() && ! empty( $themes ) );
1621                 foreach ( $themes as $theme )
1622                         $maintenance = $maintenance || $theme == get_stylesheet() || $theme == get_template();
1623                 if ( $maintenance )
1624                         $this->maintenance_mode(true);
1625
1626                 $results = array();
1627
1628                 $this->update_count = count($themes);
1629                 $this->update_current = 0;
1630                 foreach ( $themes as $theme ) {
1631                         $this->update_current++;
1632
1633                         $this->skin->theme_info = $this->theme_info($theme);
1634
1635                         if ( !isset( $current->response[ $theme ] ) ) {
1636                                 $this->skin->set_result(true);
1637                                 $this->skin->before();
1638                                 $this->skin->feedback( 'up_to_date' );
1639                                 $this->skin->after();
1640                                 $results[$theme] = true;
1641                                 continue;
1642                         }
1643
1644                         // Get the URL to the zip file
1645                         $r = $current->response[ $theme ];
1646
1647                         $result = $this->run( array(
1648                                 'package' => $r['package'],
1649                                 'destination' => get_theme_root( $theme ),
1650                                 'clear_destination' => true,
1651                                 'clear_working' => true,
1652                                 'is_multi' => true,
1653                                 'hook_extra' => array(
1654                                         'theme' => $theme
1655                                 ),
1656                         ) );
1657
1658                         $results[$theme] = $this->result;
1659
1660                         // Prevent credentials auth screen from displaying multiple times
1661                         if ( false === $result )
1662                                 break;
1663                 } //end foreach $plugins
1664
1665                 $this->maintenance_mode(false);
1666
1667                 /** This action is documented in wp-admin/includes/class-wp-upgrader.php */
1668                 do_action( 'upgrader_process_complete', $this, array(
1669                         'action' => 'update',
1670                         'type' => 'theme',
1671                         'bulk' => true,
1672                         'themes' => $themes,
1673                 ) );
1674
1675                 $this->skin->bulk_footer();
1676
1677                 $this->skin->footer();
1678
1679                 // Cleanup our hooks, in case something else does a upgrade on this connection.
1680                 remove_filter('upgrader_pre_install', array($this, 'current_before'));
1681                 remove_filter('upgrader_post_install', array($this, 'current_after'));
1682                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_theme'));
1683
1684                 // Refresh the Theme Update information
1685                 wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
1686
1687                 return $results;
1688         }
1689
1690         /**
1691          * Check that the package source contains a valid theme.
1692          *
1693          * Hooked to the {@see 'upgrader_source_selection'} filter by {@see Theme_Upgrader::install()}.
1694          * It will return an error if the theme doesn't have style.css or index.php
1695          * files.
1696          *
1697          * @since 3.3.0
1698          * @access public
1699          *
1700          * @global WP_Filesystem_Base $wp_filesystem Subclass
1701          *
1702          * @param string $source The full path to the package source.
1703          * @return string|WP_Error The source or a WP_Error.
1704          */
1705         public function check_package( $source ) {
1706                 global $wp_filesystem;
1707
1708                 if ( is_wp_error($source) )
1709                         return $source;
1710
1711                 // Check the folder contains a valid theme
1712                 $working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit(WP_CONTENT_DIR), $source);
1713                 if ( ! is_dir($working_directory) ) // Sanity check, if the above fails, let's not prevent installation.
1714                         return $source;
1715
1716                 // A proper archive should have a style.css file in the single subdirectory
1717                 if ( ! file_exists( $working_directory . 'style.css' ) ) {
1718                         return new WP_Error( 'incompatible_archive_theme_no_style', $this->strings['incompatible_archive'],
1719                                 /* translators: %s: style.css */
1720                                 sprintf( __( 'The theme is missing the %s stylesheet.' ),
1721                                         '<code>style.css</code>'
1722                                 )
1723                         );
1724                 }
1725
1726                 $info = get_file_data( $working_directory . 'style.css', array( 'Name' => 'Theme Name', 'Template' => 'Template' ) );
1727
1728                 if ( empty( $info['Name'] ) ) {
1729                         return new WP_Error( 'incompatible_archive_theme_no_name', $this->strings['incompatible_archive'],
1730                                 /* translators: %s: style.css */
1731                                 sprintf( __( 'The %s stylesheet doesn&#8217;t contain a valid theme header.' ),
1732                                         '<code>style.css</code>'
1733                                 )
1734                         );
1735                 }
1736
1737                 // If it's not a child theme, it must have at least an index.php to be legit.
1738                 if ( empty( $info['Template'] ) && ! file_exists( $working_directory . 'index.php' ) ) {
1739                         return new WP_Error( 'incompatible_archive_theme_no_index', $this->strings['incompatible_archive'],
1740                                 /* translators: %s: index.php */
1741                                 sprintf( __( 'The theme is missing the %s file.' ),
1742                                         '<code>index.php</code>'
1743                                 )
1744                         );
1745                 }
1746
1747                 return $source;
1748         }
1749
1750         /**
1751          * Turn on maintenance mode before attempting to upgrade the current theme.
1752          *
1753          * Hooked to the {@see 'upgrader_pre_install'} filter by {@see Theme_Upgrader::upgrade()} and
1754          * {@see Theme_Upgrader::bulk_upgrade()}.
1755          *
1756          * @since 2.8.0
1757          * @access public
1758          *
1759          * @param bool|WP_Error  $return
1760          * @param array          $theme
1761          * @return bool|WP_Error
1762          */
1763         public function current_before($return, $theme) {
1764                 if ( is_wp_error($return) )
1765                         return $return;
1766
1767                 $theme = isset($theme['theme']) ? $theme['theme'] : '';
1768
1769                 if ( $theme != get_stylesheet() ) //If not current
1770                         return $return;
1771                 //Change to maintenance mode now.
1772                 if ( ! $this->bulk )
1773                         $this->maintenance_mode(true);
1774
1775                 return $return;
1776         }
1777
1778         /**
1779          * Turn off maintenance mode after upgrading the current theme.
1780          *
1781          * Hooked to the {@see 'upgrader_post_install'} filter by {@see Theme_Upgrader::upgrade()}
1782          * and {@see Theme_Upgrader::bulk_upgrade()}.
1783          *
1784          * @since 2.8.0
1785          * @access public
1786          *
1787          * @param bool|WP_Error  $return
1788          * @param array          $theme
1789          * @return bool|WP_Error
1790          */
1791         public function current_after($return, $theme) {
1792                 if ( is_wp_error($return) )
1793                         return $return;
1794
1795                 $theme = isset($theme['theme']) ? $theme['theme'] : '';
1796
1797                 if ( $theme != get_stylesheet() ) // If not current
1798                         return $return;
1799
1800                 // Ensure stylesheet name hasn't changed after the upgrade:
1801                 if ( $theme == get_stylesheet() && $theme != $this->result['destination_name'] ) {
1802                         wp_clean_themes_cache();
1803                         $stylesheet = $this->result['destination_name'];
1804                         switch_theme( $stylesheet );
1805                 }
1806
1807                 //Time to remove maintenance mode
1808                 if ( ! $this->bulk )
1809                         $this->maintenance_mode(false);
1810                 return $return;
1811         }
1812
1813         /**
1814          * Delete the old theme during an upgrade.
1815          *
1816          * Hooked to the {@see 'upgrader_clear_destination'} filter by {@see Theme_Upgrader::upgrade()}
1817          * and {@see Theme_Upgrader::bulk_upgrade()}.
1818          *
1819          * @since 2.8.0
1820          * @access public
1821          *
1822          * @global WP_Filesystem_Base $wp_filesystem Subclass
1823          *
1824          * @param bool   $removed
1825          * @param string $local_destination
1826          * @param string $remote_destination
1827          * @param array  $theme
1828          * @return bool
1829          */
1830         public function delete_old_theme( $removed, $local_destination, $remote_destination, $theme ) {
1831                 global $wp_filesystem;
1832
1833                 if ( is_wp_error( $removed ) )
1834                         return $removed; // Pass errors through.
1835
1836                 if ( ! isset( $theme['theme'] ) )
1837                         return $removed;
1838
1839                 $theme = $theme['theme'];
1840                 $themes_dir = trailingslashit( $wp_filesystem->wp_themes_dir( $theme ) );
1841                 if ( $wp_filesystem->exists( $themes_dir . $theme ) ) {
1842                         if ( ! $wp_filesystem->delete( $themes_dir . $theme, true ) )
1843                                 return false;
1844                 }
1845
1846                 return true;
1847         }
1848
1849         /**
1850          * Get the WP_Theme object for a theme.
1851          *
1852          * @since 2.8.0
1853          * @since 3.0.0 The `$theme` argument was added.
1854          * @access public
1855          *
1856          * @param string $theme The directory name of the theme. This is optional, and if not supplied,
1857          *                      the directory name from the last result will be used.
1858          * @return WP_Theme|false The theme's info object, or false `$theme` is not supplied
1859          *                        and the last result isn't set.
1860          */
1861         public function theme_info($theme = null) {
1862
1863                 if ( empty($theme) ) {
1864                         if ( !empty($this->result['destination_name']) )
1865                                 $theme = $this->result['destination_name'];
1866                         else
1867                                 return false;
1868                 }
1869                 return wp_get_theme( $theme );
1870         }
1871
1872 }
1873
1874 /**
1875  * Core class used for updating/installing language packs (translations)
1876  * for plugins, themes, and core.
1877  *
1878  * @since 3.7.0
1879  *
1880  * @see WP_Upgrader
1881  */
1882 class Language_Pack_Upgrader extends WP_Upgrader {
1883
1884         /**
1885          * Result of the language pack upgrade.
1886          *
1887          * @since 3.7.0
1888          * @access public
1889          * @var array|WP_Error $result
1890          * @see WP_Upgrader::$result
1891          */
1892         public $result;
1893
1894         /**
1895          * Whether a bulk upgrade/install is being performed.
1896          *
1897          * @since 3.7.0
1898          * @access public
1899          * @var bool $bulk
1900          */
1901         public $bulk = true;
1902
1903         /**
1904          * Asynchronously upgrades language packs after other upgrades have been made.
1905          *
1906          * Hooked to the {@see 'upgrader_process_complete'} action by default.
1907          *
1908          * @since 3.7.0
1909          * @access public
1910          * @static
1911          *
1912          * @param false|WP_Upgrader $upgrader Optional. WP_Upgrader instance or false. If `$upgrader` is
1913          *                                    a Language_Pack_Upgrader instance, the method will bail to
1914          *                                    avoid recursion. Otherwise unused. Default false.
1915          */
1916         public static function async_upgrade( $upgrader = false ) {
1917                 // Avoid recursion.
1918                 if ( $upgrader && $upgrader instanceof Language_Pack_Upgrader ) {
1919                         return;
1920                 }
1921
1922                 // Nothing to do?
1923                 $language_updates = wp_get_translation_updates();
1924                 if ( ! $language_updates ) {
1925                         return;
1926                 }
1927
1928                 /*
1929                  * Avoid messing with VCS installs, at least for now.
1930                  * Noted: this is not the ideal way to accomplish this.
1931                  */
1932                 $check_vcs = new WP_Automatic_Updater;
1933                 if ( $check_vcs->is_vcs_checkout( WP_CONTENT_DIR ) ) {
1934                         return;
1935                 }
1936
1937                 foreach ( $language_updates as $key => $language_update ) {
1938                         $update = ! empty( $language_update->autoupdate );
1939
1940                         /**
1941                          * Filter whether to asynchronously update translation for core, a plugin, or a theme.
1942                          *
1943                          * @since 4.0.0
1944                          *
1945                          * @param bool   $update          Whether to update.
1946                          * @param object $language_update The update offer.
1947                          */
1948                         $update = apply_filters( 'async_update_translation', $update, $language_update );
1949
1950                         if ( ! $update ) {
1951                                 unset( $language_updates[ $key ] );
1952                         }
1953                 }
1954
1955                 if ( empty( $language_updates ) ) {
1956                         return;
1957                 }
1958
1959                 // Re-use the automatic upgrader skin if the parent upgrader is using it.
1960                 if ( $upgrader && $upgrader->skin instanceof Automatic_Upgrader_Skin ) {
1961                         $skin = $upgrader->skin;
1962                 } else {
1963                         $skin = new Language_Pack_Upgrader_Skin( array(
1964                                 'skip_header_footer' => true,
1965                         ) );
1966                 }
1967
1968                 $lp_upgrader = new Language_Pack_Upgrader( $skin );
1969                 $lp_upgrader->bulk_upgrade( $language_updates );
1970         }
1971
1972         /**
1973          * Initialize the upgrade strings.
1974          *
1975          * @since 3.7.0
1976          * @access public
1977          */
1978         public function upgrade_strings() {
1979                 $this->strings['starting_upgrade'] = __( 'Some of your translations need updating. Sit tight for a few more seconds while we update them as well.' );
1980                 $this->strings['up_to_date'] = __( 'The translation is up to date.' ); // We need to silently skip this case
1981                 $this->strings['no_package'] = __( 'Update package not available.' );
1982                 $this->strings['downloading_package'] = __( 'Downloading translation from <span class="code">%s</span>&#8230;' );
1983                 $this->strings['unpack_package'] = __( 'Unpacking the update&#8230;' );
1984                 $this->strings['process_failed'] = __( 'Translation update failed.' );
1985                 $this->strings['process_success'] = __( 'Translation updated successfully.' );
1986         }
1987
1988         /**
1989          * Upgrade a language pack.
1990          *
1991          * @since 3.7.0
1992          * @access public
1993          *
1994          * @param string|false $update Optional. Whether an update offer is available. Default false.
1995          * @param array        $args   Optional. Other optional arguments, see
1996          *                             {@see Language_Pack_Upgrader::bulk_upgrade()}. Default empty array.
1997          * @return array|bool|WP_Error The result of the upgrade, or a {@see wP_Error} object instead.
1998          */
1999         public function upgrade( $update = false, $args = array() ) {
2000                 if ( $update ) {
2001                         $update = array( $update );
2002                 }
2003
2004                 $results = $this->bulk_upgrade( $update, $args );
2005
2006                 if ( ! is_array( $results ) ) {
2007                         return $results;
2008                 }
2009
2010                 return $results[0];
2011         }
2012
2013         /**
2014          * Bulk upgrade language packs.
2015          *
2016          * @since 3.7.0
2017          * @access public
2018          *
2019          * @global WP_Filesystem_Base $wp_filesystem Subclass
2020          *
2021          * @param array $language_updates Optional. Language pack updates. Default empty array.
2022          * @param array $args {
2023          *     Optional. Other arguments for upgrading multiple language packs. Default empty array
2024          *
2025          *     @type bool $clear_update_cache Whether to clear the update cache when done.
2026          *                                    Default true.
2027          * }
2028          * @return array|bool|WP_Error Will return an array of results, or true if there are no updates,
2029          *                                   false or WP_Error for initial errors.
2030          */
2031         public function bulk_upgrade( $language_updates = array(), $args = array() ) {
2032                 global $wp_filesystem;
2033
2034                 $defaults = array(
2035                         'clear_update_cache' => true,
2036                 );
2037                 $parsed_args = wp_parse_args( $args, $defaults );
2038
2039                 $this->init();
2040                 $this->upgrade_strings();
2041
2042                 if ( ! $language_updates )
2043                         $language_updates = wp_get_translation_updates();
2044
2045                 if ( empty( $language_updates ) ) {
2046                         $this->skin->header();
2047                         $this->skin->before();
2048                         $this->skin->set_result( true );
2049                         $this->skin->feedback( 'up_to_date' );
2050                         $this->skin->after();
2051                         $this->skin->bulk_footer();
2052                         $this->skin->footer();
2053                         return true;
2054                 }
2055
2056                 if ( 'upgrader_process_complete' == current_filter() )
2057                         $this->skin->feedback( 'starting_upgrade' );
2058
2059                 // Remove any existing upgrade filters from the plugin/theme upgraders #WP29425 & #WP29230
2060                 remove_all_filters( 'upgrader_pre_install' );
2061                 remove_all_filters( 'upgrader_clear_destination' );
2062                 remove_all_filters( 'upgrader_post_install' );
2063                 remove_all_filters( 'upgrader_source_selection' );
2064
2065                 add_filter( 'upgrader_source_selection', array( $this, 'check_package' ), 10, 2 );
2066
2067                 $this->skin->header();
2068
2069                 // Connect to the Filesystem first.
2070                 $res = $this->fs_connect( array( WP_CONTENT_DIR, WP_LANG_DIR ) );
2071                 if ( ! $res ) {
2072                         $this->skin->footer();
2073                         return false;
2074                 }
2075
2076                 $results = array();
2077
2078                 $this->update_count = count( $language_updates );
2079                 $this->update_current = 0;
2080
2081                 /*
2082                  * The filesystem's mkdir() is not recursive. Make sure WP_LANG_DIR exists,
2083                  * as we then may need to create a /plugins or /themes directory inside of it.
2084                  */
2085                 $remote_destination = $wp_filesystem->find_folder( WP_LANG_DIR );
2086                 if ( ! $wp_filesystem->exists( $remote_destination ) )
2087                         if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) )
2088                                 return new WP_Error( 'mkdir_failed_lang_dir', $this->strings['mkdir_failed'], $remote_destination );
2089
2090                 foreach ( $language_updates as $language_update ) {
2091
2092                         $this->skin->language_update = $language_update;
2093
2094                         $destination = WP_LANG_DIR;
2095                         if ( 'plugin' == $language_update->type )
2096                                 $destination .= '/plugins';
2097                         elseif ( 'theme' == $language_update->type )
2098                                 $destination .= '/themes';
2099
2100                         $this->update_current++;
2101
2102                         $options = array(
2103                                 'package' => $language_update->package,
2104                                 'destination' => $destination,
2105                                 'clear_destination' => false,
2106                                 'abort_if_destination_exists' => false, // We expect the destination to exist.
2107                                 'clear_working' => true,
2108                                 'is_multi' => true,
2109                                 'hook_extra' => array(
2110                                         'language_update_type' => $language_update->type,
2111                                         'language_update' => $language_update,
2112                                 )
2113                         );
2114
2115                         $result = $this->run( $options );
2116
2117                         $results[] = $this->result;
2118
2119                         // Prevent credentials auth screen from displaying multiple times.
2120                         if ( false === $result )
2121                                 break;
2122                 }
2123
2124                 $this->skin->bulk_footer();
2125
2126                 $this->skin->footer();
2127
2128                 // Clean up our hooks, in case something else does an upgrade on this connection.
2129                 remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
2130
2131                 if ( $parsed_args['clear_update_cache'] ) {
2132                         wp_clean_update_cache();
2133                 }
2134
2135                 return $results;
2136         }
2137
2138         /**
2139          * Check the package source to make sure there are .mo and .po files.
2140          *
2141          * Hooked to the {@see 'upgrader_source_selection'} filter by
2142          * {@see Language_Pack_Upgrader::bulk_upgrade()}.
2143          *
2144          * @since 3.7.0
2145          * @access public
2146          *
2147          * @global WP_Filesystem_Base $wp_filesystem Subclass
2148          *
2149          * @param string|WP_Error $source
2150          * @param string          $remote_source
2151          */
2152         public function check_package( $source, $remote_source ) {
2153                 global $wp_filesystem;
2154
2155                 if ( is_wp_error( $source ) )
2156                         return $source;
2157
2158                 // Check that the folder contains a valid language.
2159                 $files = $wp_filesystem->dirlist( $remote_source );
2160
2161                 // Check to see if a .po and .mo exist in the folder.
2162                 $po = $mo = false;
2163                 foreach ( (array) $files as $file => $filedata ) {
2164                         if ( '.po' == substr( $file, -3 ) )
2165                                 $po = true;
2166                         elseif ( '.mo' == substr( $file, -3 ) )
2167                                 $mo = true;
2168                 }
2169
2170                 if ( ! $mo || ! $po ) {
2171                         return new WP_Error( 'incompatible_archive_pomo', $this->strings['incompatible_archive'],
2172                                 /* translators: 1: .po 2: .mo */
2173                                 sprintf( __( 'The language pack is missing either the %1$s or %2$s files.' ),
2174                                         '<code>.po</code>',
2175                                         '<code>.mo</code>'
2176                                 )
2177                         );
2178                 }
2179
2180                 return $source;
2181         }
2182
2183         /**
2184          * Get the name of an item being updated.
2185          *
2186          * @since 3.7.0
2187          * @access public
2188          *
2189          * @param object $update The data for an update.
2190          * @return string The name of the item being updated.
2191          */
2192         public function get_name_for_update( $update ) {
2193                 switch ( $update->type ) {
2194                         case 'core':
2195                                 return 'WordPress'; // Not translated
2196
2197                         case 'theme':
2198                                 $theme = wp_get_theme( $update->slug );
2199                                 if ( $theme->exists() )
2200                                         return $theme->Get( 'Name' );
2201                                 break;
2202                         case 'plugin':
2203                                 $plugin_data = get_plugins( '/' . $update->slug );
2204                                 $plugin_data = reset( $plugin_data );
2205                                 if ( $plugin_data )
2206                                         return $plugin_data['Name'];
2207                                 break;
2208                 }
2209                 return '';
2210         }
2211
2212 }
2213
2214 /**
2215  * Core class used for updating core.
2216  *
2217  * It allows for WordPress to upgrade itself in combination with
2218  * the wp-admin/includes/update-core.php file.
2219  *
2220  * @since 2.8.0
2221  *
2222  * @see WP_Upgrader
2223  */
2224 class Core_Upgrader extends WP_Upgrader {
2225
2226         /**
2227          * Initialize the upgrade strings.
2228          *
2229          * @since 2.8.0
2230          * @access public
2231          */
2232         public function upgrade_strings() {
2233                 $this->strings['up_to_date'] = __('WordPress is at the latest version.');
2234                 $this->strings['locked'] = __('Another update is currently in progress.');
2235                 $this->strings['no_package'] = __('Update package not available.');
2236                 $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;');
2237                 $this->strings['unpack_package'] = __('Unpacking the update&#8230;');
2238                 $this->strings['copy_failed'] = __('Could not copy files.');
2239                 $this->strings['copy_failed_space'] = __('Could not copy files. You may have run out of disk space.' );
2240                 $this->strings['start_rollback'] = __( 'Attempting to roll back to previous version.' );
2241                 $this->strings['rollback_was_required'] = __( 'Due to an error during updating, WordPress has rolled back to your previous version.' );
2242         }
2243
2244         /**
2245          * Upgrade WordPress core.
2246          *
2247          * @since 2.8.0
2248          * @access public
2249          *
2250          * @global WP_Filesystem_Base $wp_filesystem Subclass
2251          * @global callable           $_wp_filesystem_direct_method
2252          *
2253          * @param object $current Response object for whether WordPress is current.
2254          * @param array  $args {
2255          *        Optional. Arguments for upgrading WordPress core. Default empty array.
2256          *
2257          *        @type bool $pre_check_md5    Whether to check the file checksums before
2258          *                                     attempting the upgrade. Default true.
2259          *        @type bool $attempt_rollback Whether to attempt to rollback the chances if
2260          *                                     there is a problem. Default false.
2261          *        @type bool $do_rollback      Whether to perform this "upgrade" as a rollback.
2262          *                                     Default false.
2263          * }
2264          * @return null|false|WP_Error False or WP_Error on failure, null on success.
2265          */
2266         public function upgrade( $current, $args = array() ) {
2267                 global $wp_filesystem;
2268
2269                 include( ABSPATH . WPINC . '/version.php' ); // $wp_version;
2270
2271                 $start_time = time();
2272
2273                 $defaults = array(
2274                         'pre_check_md5'    => true,
2275                         'attempt_rollback' => false,
2276                         'do_rollback'      => false,
2277                         'allow_relaxed_file_ownership' => false,
2278                 );
2279                 $parsed_args = wp_parse_args( $args, $defaults );
2280
2281                 $this->init();
2282                 $this->upgrade_strings();
2283
2284                 // Is an update available?
2285                 if ( !isset( $current->response ) || $current->response == 'latest' )
2286                         return new WP_Error('up_to_date', $this->strings['up_to_date']);
2287
2288                 $res = $this->fs_connect( array( ABSPATH, WP_CONTENT_DIR ), $parsed_args['allow_relaxed_file_ownership'] );
2289                 if ( ! $res || is_wp_error( $res ) ) {
2290                         return $res;
2291                 }
2292
2293                 $wp_dir = trailingslashit($wp_filesystem->abspath());
2294
2295                 $partial = true;
2296                 if ( $parsed_args['do_rollback'] )
2297                         $partial = false;
2298                 elseif ( $parsed_args['pre_check_md5'] && ! $this->check_files() )
2299                         $partial = false;
2300
2301                 /*
2302                  * If partial update is returned from the API, use that, unless we're doing
2303                  * a reinstall. If we cross the new_bundled version number, then use
2304                  * the new_bundled zip. Don't though if the constant is set to skip bundled items.
2305                  * If the API returns a no_content zip, go with it. Finally, default to the full zip.
2306                  */
2307                 if ( $parsed_args['do_rollback'] && $current->packages->rollback )
2308                         $to_download = 'rollback';
2309                 elseif ( $current->packages->partial && 'reinstall' != $current->response && $wp_version == $current->partial_version && $partial )
2310                         $to_download = 'partial';
2311                 elseif ( $current->packages->new_bundled && version_compare( $wp_version, $current->new_bundled, '<' )
2312                         && ( ! defined( 'CORE_UPGRADE_SKIP_NEW_BUNDLED' ) || ! CORE_UPGRADE_SKIP_NEW_BUNDLED ) )
2313                         $to_download = 'new_bundled';
2314                 elseif ( $current->packages->no_content )
2315                         $to_download = 'no_content';
2316                 else
2317                         $to_download = 'full';
2318
2319                 // Lock to prevent multiple Core Updates occuring
2320                 $lock = WP_Upgrader::create_lock( 'core_updater', 15 * MINUTE_IN_SECONDS );
2321                 if ( ! $lock ) {
2322                         return new WP_Error( 'locked', $this->strings['locked'] );
2323                 }
2324
2325                 $download = $this->download_package( $current->packages->$to_download );
2326                 if ( is_wp_error( $download ) ) {
2327                         WP_Upgrader::release_lock( 'core_updater' );
2328                         return $download;
2329                 }
2330
2331                 $working_dir = $this->unpack_package( $download );
2332                 if ( is_wp_error( $working_dir ) ) {
2333                         WP_Upgrader::release_lock( 'core_updater' );
2334                         return $working_dir;
2335                 }
2336
2337                 // Copy update-core.php from the new version into place.
2338                 if ( !$wp_filesystem->copy($working_dir . '/wordpress/wp-admin/includes/update-core.php', $wp_dir . 'wp-admin/includes/update-core.php', true) ) {
2339                         $wp_filesystem->delete($working_dir, true);
2340                         WP_Upgrader::release_lock( 'core_updater' );
2341                         return new WP_Error( 'copy_failed_for_update_core_file', __( 'The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.' ), 'wp-admin/includes/update-core.php' );
2342                 }
2343                 $wp_filesystem->chmod($wp_dir . 'wp-admin/includes/update-core.php', FS_CHMOD_FILE);
2344
2345                 require_once( ABSPATH . 'wp-admin/includes/update-core.php' );
2346
2347                 if ( ! function_exists( 'update_core' ) ) {
2348                         WP_Upgrader::release_lock( 'core_updater' );
2349                         return new WP_Error( 'copy_failed_space', $this->strings['copy_failed_space'] );
2350                 }
2351
2352                 $result = update_core( $working_dir, $wp_dir );
2353
2354                 // In the event of an issue, we may be able to roll back.
2355                 if ( $parsed_args['attempt_rollback'] && $current->packages->rollback && ! $parsed_args['do_rollback'] ) {
2356                         $try_rollback = false;
2357                         if ( is_wp_error( $result ) ) {
2358                                 $error_code = $result->get_error_code();
2359                                 /*
2360                                  * Not all errors are equal. These codes are critical: copy_failed__copy_dir,
2361                                  * mkdir_failed__copy_dir, copy_failed__copy_dir_retry, and disk_full.
2362                                  * do_rollback allows for update_core() to trigger a rollback if needed.
2363                                  */
2364                                 if ( false !== strpos( $error_code, 'do_rollback' ) )
2365                                         $try_rollback = true;
2366                                 elseif ( false !== strpos( $error_code, '__copy_dir' ) )
2367                                         $try_rollback = true;
2368                                 elseif ( 'disk_full' === $error_code )
2369                                         $try_rollback = true;
2370                         }
2371
2372                         if ( $try_rollback ) {
2373                                 /** This filter is documented in wp-admin/includes/update-core.php */
2374                                 apply_filters( 'update_feedback', $result );
2375
2376                                 /** This filter is documented in wp-admin/includes/update-core.php */
2377                                 apply_filters( 'update_feedback', $this->strings['start_rollback'] );
2378
2379                                 $rollback_result = $this->upgrade( $current, array_merge( $parsed_args, array( 'do_rollback' => true ) ) );
2380
2381                                 $original_result = $result;
2382                                 $result = new WP_Error( 'rollback_was_required', $this->strings['rollback_was_required'], (object) array( 'update' => $original_result, 'rollback' => $rollback_result ) );
2383                         }
2384                 }
2385
2386                 /** This action is documented in wp-admin/includes/class-wp-upgrader.php */
2387                 do_action( 'upgrader_process_complete', $this, array( 'action' => 'update', 'type' => 'core' ) );
2388
2389                 // Clear the current updates
2390                 delete_site_transient( 'update_core' );
2391
2392                 if ( ! $parsed_args['do_rollback'] ) {
2393                         $stats = array(
2394                                 'update_type'      => $current->response,
2395                                 'success'          => true,
2396                                 'fs_method'        => $wp_filesystem->method,
2397                                 'fs_method_forced' => defined( 'FS_METHOD' ) || has_filter( 'filesystem_method' ),
2398                                 'fs_method_direct' => !empty( $GLOBALS['_wp_filesystem_direct_method'] ) ? $GLOBALS['_wp_filesystem_direct_method'] : '',
2399                                 'time_taken'       => time() - $start_time,
2400                                 'reported'         => $wp_version,
2401                                 'attempted'        => $current->version,
2402                         );
2403
2404                         if ( is_wp_error( $result ) ) {
2405                                 $stats['success'] = false;
2406                                 // Did a rollback occur?
2407                                 if ( ! empty( $try_rollback ) ) {
2408                                         $stats['error_code'] = $original_result->get_error_code();
2409                                         $stats['error_data'] = $original_result->get_error_data();
2410                                         // Was the rollback successful? If not, collect its error too.
2411                                         $stats['rollback'] = ! is_wp_error( $rollback_result );
2412                                         if ( is_wp_error( $rollback_result ) ) {
2413                                                 $stats['rollback_code'] = $rollback_result->get_error_code();
2414                                                 $stats['rollback_data'] = $rollback_result->get_error_data();
2415                                         }
2416                                 } else {
2417                                         $stats['error_code'] = $result->get_error_code();
2418                                         $stats['error_data'] = $result->get_error_data();
2419                                 }
2420                         }
2421
2422                         wp_version_check( $stats );
2423                 }
2424
2425                 WP_Upgrader::release_lock( 'core_updater' );
2426
2427                 return $result;
2428         }
2429
2430         /**
2431          * Determines if this WordPress Core version should update to an offered version or not.
2432          *
2433          * @since 3.7.0
2434          * @access public
2435          *
2436          * @static
2437          *
2438          * @param string $offered_ver The offered version, of the format x.y.z.
2439          * @return bool True if we should update to the offered version, otherwise false.
2440          */
2441         public static function should_update_to_version( $offered_ver ) {
2442                 include( ABSPATH . WPINC . '/version.php' ); // $wp_version; // x.y.z
2443
2444                 $current_branch = implode( '.', array_slice( preg_split( '/[.-]/', $wp_version  ), 0, 2 ) ); // x.y
2445                 $new_branch     = implode( '.', array_slice( preg_split( '/[.-]/', $offered_ver ), 0, 2 ) ); // x.y
2446                 $current_is_development_version = (bool) strpos( $wp_version, '-' );
2447
2448                 // Defaults:
2449                 $upgrade_dev   = true;
2450                 $upgrade_minor = true;
2451                 $upgrade_major = false;
2452
2453                 // WP_AUTO_UPDATE_CORE = true (all), 'minor', false.
2454                 if ( defined( 'WP_AUTO_UPDATE_CORE' ) ) {
2455                         if ( false === WP_AUTO_UPDATE_CORE ) {
2456                                 // Defaults to turned off, unless a filter allows it
2457                                 $upgrade_dev = $upgrade_minor = $upgrade_major = false;
2458                         } elseif ( true === WP_AUTO_UPDATE_CORE ) {
2459                                 // ALL updates for core
2460                                 $upgrade_dev = $upgrade_minor = $upgrade_major = true;
2461                         } elseif ( 'minor' === WP_AUTO_UPDATE_CORE ) {
2462                                 // Only minor updates for core
2463                                 $upgrade_dev = $upgrade_major = false;
2464                                 $upgrade_minor = true;
2465                         }
2466                 }
2467
2468                 // 1: If we're already on that version, not much point in updating?
2469                 if ( $offered_ver == $wp_version )
2470                         return false;
2471
2472                 // 2: If we're running a newer version, that's a nope
2473                 if ( version_compare( $wp_version, $offered_ver, '>' ) )
2474                         return false;
2475
2476                 $failure_data = get_site_option( 'auto_core_update_failed' );
2477                 if ( $failure_data ) {
2478                         // If this was a critical update failure, cannot update.
2479                         if ( ! empty( $failure_data['critical'] ) )
2480                                 return false;
2481
2482                         // Don't claim we can update on update-core.php if we have a non-critical failure logged.
2483                         if ( $wp_version == $failure_data['current'] && false !== strpos( $offered_ver, '.1.next.minor' ) )
2484                                 return false;
2485
2486                         // Cannot update if we're retrying the same A to B update that caused a non-critical failure.
2487                         // Some non-critical failures do allow retries, like download_failed.
2488                         // 3.7.1 => 3.7.2 resulted in files_not_writable, if we are still on 3.7.1 and still trying to update to 3.7.2.
2489                         if ( empty( $failure_data['retry'] ) && $wp_version == $failure_data['current'] && $offered_ver == $failure_data['attempted'] )
2490                                 return false;
2491                 }
2492
2493                 // 3: 3.7-alpha-25000 -> 3.7-alpha-25678 -> 3.7-beta1 -> 3.7-beta2
2494                 if ( $current_is_development_version ) {
2495
2496                         /**
2497                          * Filter whether to enable automatic core updates for development versions.
2498                          *
2499                          * @since 3.7.0
2500                          *
2501                          * @param bool $upgrade_dev Whether to enable automatic updates for
2502                          *                          development versions.
2503                          */
2504                         if ( ! apply_filters( 'allow_dev_auto_core_updates', $upgrade_dev ) )
2505                                 return false;
2506                         // Else fall through to minor + major branches below.
2507                 }
2508
2509                 // 4: Minor In-branch updates (3.7.0 -> 3.7.1 -> 3.7.2 -> 3.7.4)
2510                 if ( $current_branch == $new_branch ) {
2511
2512                         /**
2513                          * Filter whether to enable minor automatic core updates.
2514                          *
2515                          * @since 3.7.0
2516                          *
2517                          * @param bool $upgrade_minor Whether to enable minor automatic core updates.
2518                          */
2519                         return apply_filters( 'allow_minor_auto_core_updates', $upgrade_minor );
2520                 }
2521
2522                 // 5: Major version updates (3.7.0 -> 3.8.0 -> 3.9.1)
2523                 if ( version_compare( $new_branch, $current_branch, '>' ) ) {
2524
2525                         /**
2526                          * Filter whether to enable major automatic core updates.
2527                          *
2528                          * @since 3.7.0
2529                          *
2530                          * @param bool $upgrade_major Whether to enable major automatic core updates.
2531                          */
2532                         return apply_filters( 'allow_major_auto_core_updates', $upgrade_major );
2533                 }
2534
2535                 // If we're not sure, we don't want it
2536                 return false;
2537         }
2538
2539         /**
2540          * Compare the disk file checksums against the expected checksums.
2541          *
2542          * @since 3.7.0
2543          * @access public
2544          *
2545          * @global string $wp_version
2546          * @global string $wp_local_package
2547          *
2548          * @return bool True if the checksums match, otherwise false.
2549          */
2550         public function check_files() {
2551                 global $wp_version, $wp_local_package;
2552
2553                 $checksums = get_core_checksums( $wp_version, isset( $wp_local_package ) ? $wp_local_package : 'en_US' );
2554
2555                 if ( ! is_array( $checksums ) )
2556                         return false;
2557
2558                 foreach ( $checksums as $file => $checksum ) {
2559                         // Skip files which get updated
2560                         if ( 'wp-content' == substr( $file, 0, 10 ) )
2561                                 continue;
2562                         if ( ! file_exists( ABSPATH . $file ) || md5_file( ABSPATH . $file ) !== $checksum )
2563                                 return false;
2564                 }
2565
2566                 return true;
2567         }
2568 }
2569
2570 /**
2571  * Core class used for handling file uploads.
2572  *
2573  * This class handles the upload process and passes it as if it's a local file
2574  * to the Upgrade/Installer functions.
2575  *
2576  * @since 2.8.0
2577  */
2578 class File_Upload_Upgrader {
2579
2580         /**
2581          * The full path to the file package.
2582          *
2583          * @since 2.8.0
2584          * @access public
2585          * @var string $package
2586          */
2587         public $package;
2588
2589         /**
2590          * The name of the file.
2591          *
2592          * @since 2.8.0
2593          * @access public
2594          * @var string $filename
2595          */
2596         public $filename;
2597
2598         /**
2599          * The ID of the attachment post for this file.
2600          *
2601          * @since 3.3.0
2602          * @access public
2603          * @var int $id
2604          */
2605         public $id = 0;
2606
2607         /**
2608          * Construct the upgrader for a form.
2609          *
2610          * @since 2.8.0
2611          * @access public
2612          *
2613          * @param string $form      The name of the form the file was uploaded from.
2614          * @param string $urlholder The name of the `GET` parameter that holds the filename.
2615          */
2616         public function __construct( $form, $urlholder ) {
2617
2618                 if ( empty($_FILES[$form]['name']) && empty($_GET[$urlholder]) )
2619                         wp_die(__('Please select a file'));
2620
2621                 //Handle a newly uploaded file, Else assume it's already been uploaded
2622                 if ( ! empty($_FILES) ) {
2623                         $overrides = array( 'test_form' => false, 'test_type' => false );
2624                         $file = wp_handle_upload( $_FILES[$form], $overrides );
2625
2626                         if ( isset( $file['error'] ) )
2627                                 wp_die( $file['error'] );
2628
2629                         $this->filename = $_FILES[$form]['name'];
2630                         $this->package = $file['file'];
2631
2632                         // Construct the object array
2633                         $object = array(
2634                                 'post_title' => $this->filename,
2635                                 'post_content' => $file['url'],
2636                                 'post_mime_type' => $file['type'],
2637                                 'guid' => $file['url'],
2638                                 'context' => 'upgrader',
2639                                 'post_status' => 'private'
2640                         );
2641
2642                         // Save the data.
2643                         $this->id = wp_insert_attachment( $object, $file['file'] );
2644
2645                         // Schedule a cleanup for 2 hours from now in case of failed install.
2646                         wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $this->id ) );
2647
2648                 } elseif ( is_numeric( $_GET[$urlholder] ) ) {
2649                         // Numeric Package = previously uploaded file, see above.
2650                         $this->id = (int) $_GET[$urlholder];
2651                         $attachment = get_post( $this->id );
2652                         if ( empty($attachment) )
2653                                 wp_die(__('Please select a file'));
2654
2655                         $this->filename = $attachment->post_title;
2656                         $this->package = get_attached_file( $attachment->ID );
2657                 } else {
2658                         // Else, It's set to something, Back compat for plugins using the old (pre-3.3) File_Uploader handler.
2659                         if ( ! ( ( $uploads = wp_upload_dir() ) && false === $uploads['error'] ) )
2660                                 wp_die( $uploads['error'] );
2661
2662                         $this->filename = $_GET[$urlholder];
2663                         $this->package = $uploads['basedir'] . '/' . $this->filename;
2664                 }
2665         }
2666
2667         /**
2668          * Delete the attachment/uploaded file.
2669          *
2670          * @since 3.2.2
2671          * @access public
2672          *
2673          * @return bool Whether the cleanup was successful.
2674          */
2675         public function cleanup() {
2676                 if ( $this->id )
2677                         wp_delete_attachment( $this->id );
2678
2679                 elseif ( file_exists( $this->package ) )
2680                         return @unlink( $this->package );
2681
2682                 return true;
2683         }
2684 }
2685
2686 /**
2687  * Core class used for handling automatic background updates.
2688  *
2689  * @since 3.7.0
2690  */
2691 class WP_Automatic_Updater {
2692
2693         /**
2694          * Tracks update results during processing.
2695          *
2696          * @var array
2697          * @access protected
2698          */
2699         protected $update_results = array();
2700
2701         /**
2702          * Whether the entire automatic updater is disabled.
2703          *
2704          * @since 3.7.0
2705          * @access public
2706          */
2707         public function is_disabled() {
2708                 // Background updates are disabled if you don't want file changes.
2709                 if ( defined( 'DISALLOW_FILE_MODS' ) && DISALLOW_FILE_MODS )
2710                         return true;
2711
2712                 if ( wp_installing() )
2713                         return true;
2714
2715                 // More fine grained control can be done through the WP_AUTO_UPDATE_CORE constant and filters.
2716                 $disabled = defined( 'AUTOMATIC_UPDATER_DISABLED' ) && AUTOMATIC_UPDATER_DISABLED;
2717
2718                 /**
2719                  * Filter whether to entirely disable background updates.
2720                  *
2721                  * There are more fine-grained filters and controls for selective disabling.
2722                  * This filter parallels the AUTOMATIC_UPDATER_DISABLED constant in name.
2723                  *
2724                  * This also disables update notification emails. That may change in the future.
2725                  *
2726                  * @since 3.7.0
2727                  *
2728                  * @param bool $disabled Whether the updater should be disabled.
2729                  */
2730                 return apply_filters( 'automatic_updater_disabled', $disabled );
2731         }
2732
2733         /**
2734          * Check for version control checkouts.
2735          *
2736          * Checks for Subversion, Git, Mercurial, and Bazaar. It recursively looks up the
2737          * filesystem to the top of the drive, erring on the side of detecting a VCS
2738          * checkout somewhere.
2739          *
2740          * ABSPATH is always checked in addition to whatever $context is (which may be the
2741          * wp-content directory, for example). The underlying assumption is that if you are
2742          * using version control *anywhere*, then you should be making decisions for
2743          * how things get updated.
2744          *
2745          * @since 3.7.0
2746          * @access public
2747          *
2748          * @param string $context The filesystem path to check, in addition to ABSPATH.
2749          */
2750         public function is_vcs_checkout( $context ) {
2751                 $context_dirs = array( untrailingslashit( $context ) );
2752                 if ( $context !== ABSPATH )
2753                         $context_dirs[] = untrailingslashit( ABSPATH );
2754
2755                 $vcs_dirs = array( '.svn', '.git', '.hg', '.bzr' );
2756                 $check_dirs = array();
2757
2758                 foreach ( $context_dirs as $context_dir ) {
2759                         // Walk up from $context_dir to the root.
2760                         do {
2761                                 $check_dirs[] = $context_dir;
2762
2763                                 // Once we've hit '/' or 'C:\', we need to stop. dirname will keep returning the input here.
2764                                 if ( $context_dir == dirname( $context_dir ) )
2765                                         break;
2766
2767                         // Continue one level at a time.
2768                         } while ( $context_dir = dirname( $context_dir ) );
2769                 }
2770
2771                 $check_dirs = array_unique( $check_dirs );
2772
2773                 // Search all directories we've found for evidence of version control.
2774                 foreach ( $vcs_dirs as $vcs_dir ) {
2775                         foreach ( $check_dirs as $check_dir ) {
2776                                 if ( $checkout = @is_dir( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" ) )
2777                                         break 2;
2778                         }
2779                 }
2780
2781                 /**
2782                  * Filter whether the automatic updater should consider a filesystem
2783                  * location to be potentially managed by a version control system.
2784                  *
2785                  * @since 3.7.0
2786                  *
2787                  * @param bool $checkout  Whether a VCS checkout was discovered at $context
2788                  *                        or ABSPATH, or anywhere higher.
2789                  * @param string $context The filesystem context (a path) against which
2790                  *                        filesystem status should be checked.
2791                  */
2792                 return apply_filters( 'automatic_updates_is_vcs_checkout', $checkout, $context );
2793         }
2794
2795         /**
2796          * Tests to see if we can and should update a specific item.
2797          *
2798          * @since 3.7.0
2799          * @access public
2800          *
2801          * @global wpdb $wpdb WordPress database abstraction object.
2802          *
2803          * @param string $type    The type of update being checked: 'core', 'theme',
2804          *                        'plugin', 'translation'.
2805          * @param object $item    The update offer.
2806          * @param string $context The filesystem context (a path) against which filesystem
2807          *                        access and status should be checked.
2808          */
2809         public function should_update( $type, $item, $context ) {
2810                 // Used to see if WP_Filesystem is set up to allow unattended updates.
2811                 $skin = new Automatic_Upgrader_Skin;
2812
2813                 if ( $this->is_disabled() )
2814                         return false;
2815
2816                 // Only relax the filesystem checks when the update doesn't include new files
2817                 $allow_relaxed_file_ownership = false;
2818                 if ( 'core' == $type && isset( $item->new_files ) && ! $item->new_files ) {
2819                         $allow_relaxed_file_ownership = true;
2820                 }
2821
2822                 // If we can't do an auto core update, we may still be able to email the user.
2823                 if ( ! $skin->request_filesystem_credentials( false, $context, $allow_relaxed_file_ownership ) || $this->is_vcs_checkout( $context ) ) {
2824                         if ( 'core' == $type )
2825                                 $this->send_core_update_notification_email( $item );
2826                         return false;
2827                 }
2828
2829                 // Next up, is this an item we can update?
2830                 if ( 'core' == $type )
2831                         $update = Core_Upgrader::should_update_to_version( $item->current );
2832                 else
2833                         $update = ! empty( $item->autoupdate );
2834
2835                 /**
2836                  * Filter whether to automatically update core, a plugin, a theme, or a language.
2837                  *
2838                  * The dynamic portion of the hook name, `$type`, refers to the type of update
2839                  * being checked. Can be 'core', 'theme', 'plugin', or 'translation'.
2840                  *
2841                  * Generally speaking, plugins, themes, and major core versions are not updated
2842                  * by default, while translations and minor and development versions for core
2843                  * are updated by default.
2844                  *
2845                  * See the {@see 'allow_dev_auto_core_updates', {@see 'allow_minor_auto_core_updates'},
2846                  * and {@see 'allow_major_auto_core_updates'} filters for a more straightforward way to
2847                  * adjust core updates.
2848                  *
2849                  * @since 3.7.0
2850                  *
2851                  * @param bool   $update Whether to update.
2852                  * @param object $item   The update offer.
2853                  */
2854                 $update = apply_filters( 'auto_update_' . $type, $update, $item );
2855
2856                 if ( ! $update ) {
2857                         if ( 'core' == $type )
2858                                 $this->send_core_update_notification_email( $item );
2859                         return false;
2860                 }
2861
2862                 // If it's a core update, are we actually compatible with its requirements?
2863                 if ( 'core' == $type ) {
2864                         global $wpdb;
2865
2866                         $php_compat = version_compare( phpversion(), $item->php_version, '>=' );
2867                         if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) )
2868                                 $mysql_compat = true;
2869                         else
2870                                 $mysql_compat = version_compare( $wpdb->db_version(), $item->mysql_version, '>=' );
2871
2872                         if ( ! $php_compat || ! $mysql_compat )
2873                                 return false;
2874                 }
2875
2876                 return true;
2877         }
2878
2879         /**
2880          * Notifies an administrator of a core update.
2881          *
2882          * @since 3.7.0
2883          * @access protected
2884          *
2885          * @param object $item The update offer.
2886          */
2887         protected function send_core_update_notification_email( $item ) {
2888                 $notified = get_site_option( 'auto_core_update_notified' );
2889
2890                 // Don't notify if we've already notified the same email address of the same version.
2891                 if ( $notified && $notified['email'] == get_site_option( 'admin_email' ) && $notified['version'] == $item->current )
2892                         return false;
2893
2894                 // See if we need to notify users of a core update.
2895                 $notify = ! empty( $item->notify_email );
2896
2897                 /**
2898                  * Filter whether to notify the site administrator of a new core update.
2899                  *
2900                  * By default, administrators are notified when the update offer received
2901                  * from WordPress.org sets a particular flag. This allows some discretion
2902                  * in if and when to notify.
2903                  *
2904                  * This filter is only evaluated once per release. If the same email address
2905                  * was already notified of the same new version, WordPress won't repeatedly
2906                  * email the administrator.
2907                  *
2908                  * This filter is also used on about.php to check if a plugin has disabled
2909                  * these notifications.
2910                  *
2911                  * @since 3.7.0
2912                  *
2913                  * @param bool   $notify Whether the site administrator is notified.
2914                  * @param object $item   The update offer.
2915                  */
2916                 if ( ! apply_filters( 'send_core_update_notification_email', $notify, $item ) )
2917                         return false;
2918
2919                 $this->send_email( 'manual', $item );
2920                 return true;
2921         }
2922
2923         /**
2924          * Update an item, if appropriate.
2925          *
2926          * @since 3.7.0
2927          * @access public
2928          *
2929          * @param string $type The type of update being checked: 'core', 'theme', 'plugin', 'translation'.
2930          * @param object $item The update offer.
2931          *
2932          * @return null|WP_Error
2933          */
2934         public function update( $type, $item ) {
2935                 $skin = new Automatic_Upgrader_Skin;
2936
2937                 switch ( $type ) {
2938                         case 'core':
2939                                 // The Core upgrader doesn't use the Upgrader's skin during the actual main part of the upgrade, instead, firing a filter.
2940                                 add_filter( 'update_feedback', array( $skin, 'feedback' ) );
2941                                 $upgrader = new Core_Upgrader( $skin );
2942                                 $context  = ABSPATH;
2943                                 break;
2944                         case 'plugin':
2945                                 $upgrader = new Plugin_Upgrader( $skin );
2946                                 $context  = WP_PLUGIN_DIR; // We don't support custom Plugin directories, or updates for WPMU_PLUGIN_DIR
2947                                 break;
2948                         case 'theme':
2949                                 $upgrader = new Theme_Upgrader( $skin );
2950                                 $context  = get_theme_root( $item->theme );
2951                                 break;
2952                         case 'translation':
2953                                 $upgrader = new Language_Pack_Upgrader( $skin );
2954                                 $context  = WP_CONTENT_DIR; // WP_LANG_DIR;
2955                                 break;
2956                 }
2957
2958                 // Determine whether we can and should perform this update.
2959                 if ( ! $this->should_update( $type, $item, $context ) )
2960                         return false;
2961
2962                 /**
2963                  * Fires immediately prior to an auto-update.
2964                  *
2965                  * @since 4.4.0
2966                  *
2967                  * @param string $type    The type of update being checked: 'core', 'theme', 'plugin', or 'translation'.
2968                  * @param object $item    The update offer.
2969                  * @param string $context The filesystem context (a path) against which filesystem access and status
2970                  *                        should be checked.
2971                  */
2972                 do_action( 'pre_auto_update', $type, $item, $context );
2973
2974                 $upgrader_item = $item;
2975                 switch ( $type ) {
2976                         case 'core':
2977                                 $skin->feedback( __( 'Updating to WordPress %s' ), $item->version );
2978                                 $item_name = sprintf( __( 'WordPress %s' ), $item->version );
2979                                 break;
2980                         case 'theme':
2981                                 $upgrader_item = $item->theme;
2982                                 $theme = wp_get_theme( $upgrader_item );
2983                                 $item_name = $theme->Get( 'Name' );
2984                                 $skin->feedback( __( 'Updating theme: %s' ), $item_name );
2985                                 break;
2986                         case 'plugin':
2987                                 $upgrader_item = $item->plugin;
2988                                 $plugin_data = get_plugin_data( $context . '/' . $upgrader_item );
2989                                 $item_name = $plugin_data['Name'];
2990                                 $skin->feedback( __( 'Updating plugin: %s' ), $item_name );
2991                                 break;
2992                         case 'translation':
2993                                 $language_item_name = $upgrader->get_name_for_update( $item );
2994                                 $item_name = sprintf( __( 'Translations for %s' ), $language_item_name );
2995                                 $skin->feedback( sprintf( __( 'Updating translations for %1$s (%2$s)&#8230;' ), $language_item_name, $item->language ) );
2996                                 break;
2997                 }
2998
2999                 $allow_relaxed_file_ownership = false;
3000                 if ( 'core' == $type && isset( $item->new_files ) && ! $item->new_files ) {
3001                         $allow_relaxed_file_ownership = true;
3002                 }
3003
3004                 // Boom, This sites about to get a whole new splash of paint!
3005                 $upgrade_result = $upgrader->upgrade( $upgrader_item, array(
3006                         'clear_update_cache' => false,
3007                         // Always use partial builds if possible for core updates.
3008                         'pre_check_md5'      => false,
3009                         // Only available for core updates.
3010                         'attempt_rollback'   => true,
3011                         // Allow relaxed file ownership in some scenarios
3012                         'allow_relaxed_file_ownership' => $allow_relaxed_file_ownership,
3013                 ) );
3014
3015                 // If the filesystem is unavailable, false is returned.
3016                 if ( false === $upgrade_result ) {
3017                         $upgrade_result = new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
3018                 }
3019
3020                 if ( 'core' == $type ) {
3021                         if ( is_wp_error( $upgrade_result ) && ( 'up_to_date' == $upgrade_result->get_error_code() || 'locked' == $upgrade_result->get_error_code() ) ) {
3022                                 // These aren't actual errors, treat it as a skipped-update instead to avoid triggering the post-core update failure routines.
3023                                 return false;
3024                         }
3025
3026                         // Core doesn't output this, so let's append it so we don't get confused.
3027                         if ( is_wp_error( $upgrade_result ) ) {
3028                                 $skin->error( __( 'Installation Failed' ), $upgrade_result );
3029                         } else {
3030                                 $skin->feedback( __( 'WordPress updated successfully' ) );
3031                         }
3032                 }
3033
3034                 $this->update_results[ $type ][] = (object) array(
3035                         'item'     => $item,
3036                         'result'   => $upgrade_result,
3037                         'name'     => $item_name,
3038                         'messages' => $skin->get_upgrade_messages()
3039                 );
3040
3041                 return $upgrade_result;
3042         }
3043
3044         /**
3045          * Kicks off the background update process, looping through all pending updates.
3046          *
3047          * @since 3.7.0
3048          * @access public
3049          *
3050          * @global wpdb   $wpdb
3051          * @global string $wp_version
3052          */
3053         public function run() {
3054                 global $wpdb, $wp_version;
3055
3056                 if ( $this->is_disabled() )
3057                         return;
3058
3059                 if ( ! is_main_network() || ! is_main_site() )
3060                         return;
3061
3062                 if ( ! WP_Upgrader::create_lock( 'auto_updater' ) )
3063                         return;
3064
3065                 // Don't automatically run these thins, as we'll handle it ourselves
3066                 remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
3067                 remove_action( 'upgrader_process_complete', 'wp_version_check' );
3068                 remove_action( 'upgrader_process_complete', 'wp_update_plugins' );
3069                 remove_action( 'upgrader_process_complete', 'wp_update_themes' );
3070
3071                 // Next, Plugins
3072                 wp_update_plugins(); // Check for Plugin updates
3073                 $plugin_updates = get_site_transient( 'update_plugins' );
3074                 if ( $plugin_updates && !empty( $plugin_updates->response ) ) {
3075                         foreach ( $plugin_updates->response as $plugin ) {
3076                                 $this->update( 'plugin', $plugin );
3077                         }
3078                         // Force refresh of plugin update information
3079                         wp_clean_plugins_cache();
3080                 }
3081
3082                 // Next, those themes we all love
3083                 wp_update_themes();  // Check for Theme updates
3084                 $theme_updates = get_site_transient( 'update_themes' );
3085                 if ( $theme_updates && !empty( $theme_updates->response ) ) {
3086                         foreach ( $theme_updates->response as $theme ) {
3087                                 $this->update( 'theme', (object) $theme );
3088                         }
3089                         // Force refresh of theme update information
3090                         wp_clean_themes_cache();
3091                 }
3092
3093                 // Next, Process any core update
3094                 wp_version_check(); // Check for Core updates
3095                 $core_update = find_core_auto_update();
3096
3097                 if ( $core_update )
3098                         $this->update( 'core', $core_update );
3099
3100                 // Clean up, and check for any pending translations
3101                 // (Core_Upgrader checks for core updates)
3102                 $theme_stats = array();
3103                 if ( isset( $this->update_results['theme'] ) ) {
3104                         foreach ( $this->update_results['theme'] as $upgrade ) {
3105                                 $theme_stats[ $upgrade->item->theme ] = ( true === $upgrade->result );
3106                         }
3107                 }
3108                 wp_update_themes( $theme_stats );  // Check for Theme updates
3109
3110                 $plugin_stats = array();
3111                 if ( isset( $this->update_results['plugin'] ) ) {
3112                         foreach ( $this->update_results['plugin'] as $upgrade ) {
3113                                 $plugin_stats[ $upgrade->item->plugin ] = ( true === $upgrade->result );
3114                         }
3115                 }
3116                 wp_update_plugins( $plugin_stats ); // Check for Plugin updates
3117
3118                 // Finally, Process any new translations
3119                 $language_updates = wp_get_translation_updates();
3120                 if ( $language_updates ) {
3121                         foreach ( $language_updates as $update ) {
3122                                 $this->update( 'translation', $update );
3123                         }
3124
3125                         // Clear existing caches
3126                         wp_clean_update_cache();
3127
3128                         wp_version_check();  // check for Core updates
3129                         wp_update_themes();  // Check for Theme updates
3130                         wp_update_plugins(); // Check for Plugin updates
3131                 }
3132
3133                 // Send debugging email to all development installs.
3134                 if ( ! empty( $this->update_results ) ) {
3135                         $development_version = false !== strpos( $wp_version, '-' );
3136
3137                         /**
3138                          * Filter whether to send a debugging email for each automatic background update.
3139