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