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