]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/class-wp-upgrader.php
WordPress 3.7.2
[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 http://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         var $strings = array();
25         var $skin = null;
26         var $result = array();
27
28         function __construct($skin = null) {
29                 if ( null == $skin )
30                         $this->skin = new WP_Upgrader_Skin();
31                 else
32                         $this->skin = $skin;
33         }
34
35         function init() {
36                 $this->skin->set_upgrader($this);
37                 $this->generic_strings();
38         }
39
40         function generic_strings() {
41                 $this->strings['bad_request'] = __('Invalid Data provided.');
42                 $this->strings['fs_unavailable'] = __('Could not access filesystem.');
43                 $this->strings['fs_error'] = __('Filesystem error.');
44                 $this->strings['fs_no_root_dir'] = __('Unable to locate WordPress Root directory.');
45                 $this->strings['fs_no_content_dir'] = __('Unable to locate WordPress Content directory (wp-content).');
46                 $this->strings['fs_no_plugins_dir'] = __('Unable to locate WordPress Plugin directory.');
47                 $this->strings['fs_no_themes_dir'] = __('Unable to locate WordPress Theme directory.');
48                 /* translators: %s: directory name */
49                 $this->strings['fs_no_folder'] = __('Unable to locate needed folder (%s).');
50
51                 $this->strings['download_failed'] = __('Download failed.');
52                 $this->strings['installing_package'] = __('Installing the latest version&#8230;');
53                 $this->strings['no_files'] = __('The package contains no files.');
54                 $this->strings['folder_exists'] = __('Destination folder already exists.');
55                 $this->strings['mkdir_failed'] = __('Could not create directory.');
56                 $this->strings['incompatible_archive'] = __('The package could not be installed.');
57
58                 $this->strings['maintenance_start'] = __('Enabling Maintenance mode&#8230;');
59                 $this->strings['maintenance_end'] = __('Disabling Maintenance mode&#8230;');
60         }
61
62         function fs_connect( $directories = array() ) {
63                 global $wp_filesystem;
64
65                 if ( false === ($credentials = $this->skin->request_filesystem_credentials()) )
66                         return false;
67
68                 if ( ! WP_Filesystem($credentials) ) {
69                         $error = true;
70                         if ( is_object($wp_filesystem) && $wp_filesystem->errors->get_error_code() )
71                                 $error = $wp_filesystem->errors;
72                         $this->skin->request_filesystem_credentials($error); //Failed to connect, Error and request again
73                         return false;
74                 }
75
76                 if ( ! is_object($wp_filesystem) )
77                         return new WP_Error('fs_unavailable', $this->strings['fs_unavailable'] );
78
79                 if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
80                         return new WP_Error('fs_error', $this->strings['fs_error'], $wp_filesystem->errors);
81
82                 foreach ( (array)$directories as $dir ) {
83                         switch ( $dir ) {
84                                 case ABSPATH:
85                                         if ( ! $wp_filesystem->abspath() )
86                                                 return new WP_Error('fs_no_root_dir', $this->strings['fs_no_root_dir']);
87                                         break;
88                                 case WP_CONTENT_DIR:
89                                         if ( ! $wp_filesystem->wp_content_dir() )
90                                                 return new WP_Error('fs_no_content_dir', $this->strings['fs_no_content_dir']);
91                                         break;
92                                 case WP_PLUGIN_DIR:
93                                         if ( ! $wp_filesystem->wp_plugins_dir() )
94                                                 return new WP_Error('fs_no_plugins_dir', $this->strings['fs_no_plugins_dir']);
95                                         break;
96                                 case get_theme_root():
97                                         if ( ! $wp_filesystem->wp_themes_dir() )
98                                                 return new WP_Error('fs_no_themes_dir', $this->strings['fs_no_themes_dir']);
99                                         break;
100                                 default:
101                                         if ( ! $wp_filesystem->find_folder($dir) )
102                                                 return new WP_Error( 'fs_no_folder', sprintf( $this->strings['fs_no_folder'], esc_html( basename( $dir ) ) ) );
103                                         break;
104                         }
105                 }
106                 return true;
107         } //end fs_connect();
108
109         function download_package($package) {
110
111                 /**
112                  * Filter whether to return the package.
113                  *
114                  * @since 3.7.0
115                  *
116                  * @param bool    $reply   Whether to bail without returning the package. Default is false.
117                  * @param string  $package The package file name.
118                  * @param object  $this    The WP_Upgrader instance.
119                  */
120                 $reply = apply_filters( 'upgrader_pre_download', false, $package, $this );
121                 if ( false !== $reply )
122                         return $reply;
123
124                 if ( ! preg_match('!^(http|https|ftp)://!i', $package) && file_exists($package) ) //Local file or remote?
125                         return $package; //must be a local file..
126
127                 if ( empty($package) )
128                         return new WP_Error('no_package', $this->strings['no_package']);
129
130                 $this->skin->feedback('downloading_package', $package);
131
132                 $download_file = download_url($package);
133
134                 if ( is_wp_error($download_file) )
135                         return new WP_Error('download_failed', $this->strings['download_failed'], $download_file->get_error_message());
136
137                 return $download_file;
138         }
139
140         function unpack_package($package, $delete_package = true) {
141                 global $wp_filesystem;
142
143                 $this->skin->feedback('unpack_package');
144
145                 $upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade/';
146
147                 //Clean up contents of upgrade directory beforehand.
148                 $upgrade_files = $wp_filesystem->dirlist($upgrade_folder);
149                 if ( !empty($upgrade_files) ) {
150                         foreach ( $upgrade_files as $file )
151                                 $wp_filesystem->delete($upgrade_folder . $file['name'], true);
152                 }
153
154                 //We need a working directory
155                 $working_dir = $upgrade_folder . basename($package, '.zip');
156
157                 // Clean up working directory
158                 if ( $wp_filesystem->is_dir($working_dir) )
159                         $wp_filesystem->delete($working_dir, true);
160
161                 // Unzip package to working directory
162                 $result = unzip_file( $package, $working_dir );
163
164                 // Once extracted, delete the package if required.
165                 if ( $delete_package )
166                         unlink($package);
167
168                 if ( is_wp_error($result) ) {
169                         $wp_filesystem->delete($working_dir, true);
170                         if ( 'incompatible_archive' == $result->get_error_code() ) {
171                                 return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], $result->get_error_data() );
172                         }
173                         return $result;
174                 }
175
176                 return $working_dir;
177         }
178
179         function install_package( $args = array() ) {
180                 global $wp_filesystem, $wp_theme_directories;
181
182                 $defaults = array(
183                         'source' => '', // Please always pass this
184                         'destination' => '', // and this
185                         'clear_destination' => false,
186                         'clear_working' => false,
187                         'abort_if_destination_exists' => true,
188                         'hook_extra' => array()
189                 );
190
191                 $args = wp_parse_args($args, $defaults);
192                 extract($args);
193
194                 @set_time_limit( 300 );
195
196                 if ( empty($source) || empty($destination) )
197                         return new WP_Error('bad_request', $this->strings['bad_request']);
198
199                 $this->skin->feedback('installing_package');
200
201                 $res = apply_filters('upgrader_pre_install', true, $hook_extra);
202                 if ( is_wp_error($res) )
203                         return $res;
204
205                 //Retain the Original source and destinations
206                 $remote_source = $source;
207                 $local_destination = $destination;
208
209                 $source_files = array_keys( $wp_filesystem->dirlist($remote_source) );
210                 $remote_destination = $wp_filesystem->find_folder($local_destination);
211
212                 //Locate which directory to copy to the new folder, This is based on the actual folder holding the files.
213                 if ( 1 == count($source_files) && $wp_filesystem->is_dir( trailingslashit($source) . $source_files[0] . '/') ) //Only one folder? Then we want its contents.
214                         $source = trailingslashit($source) . trailingslashit($source_files[0]);
215                 elseif ( count($source_files) == 0 )
216                         return new WP_Error( 'incompatible_archive_empty', $this->strings['incompatible_archive'], $this->strings['no_files'] ); // There are no files?
217                 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.
218                         $source = trailingslashit($source);
219
220                 //Hook ability to change the source file location..
221                 $source = apply_filters('upgrader_source_selection', $source, $remote_source, $this);
222                 if ( is_wp_error($source) )
223                         return $source;
224
225                 //Has the source location changed? If so, we need a new source_files list.
226                 if ( $source !== $remote_source )
227                         $source_files = array_keys( $wp_filesystem->dirlist($source) );
228
229                 // Protection against deleting files in any important base directories.
230                 // Theme_Upgrader & Plugin_Upgrader also trigger this, as they pass the destination directory (WP_PLUGIN_DIR / wp-content/themes)
231                 // intending to copy the directory into the directory, whilst they pass the source as the actual files to copy.
232                 $protected_directories = array( ABSPATH, WP_CONTENT_DIR, WP_PLUGIN_DIR, WP_CONTENT_DIR . '/themes' );
233                 if ( is_array( $wp_theme_directories ) )
234                         $protected_directories = array_merge( $protected_directories, $wp_theme_directories );
235                 if ( in_array( $destination, $protected_directories ) ) {
236                         $remote_destination = trailingslashit($remote_destination) . trailingslashit(basename($source));
237                         $destination = trailingslashit($destination) . trailingslashit(basename($source));
238                 }
239
240                 if ( $clear_destination ) {
241                         //We're going to clear the destination if there's something there
242                         $this->skin->feedback('remove_old');
243                         $removed = true;
244                         if ( $wp_filesystem->exists($remote_destination) )
245                                 $removed = $wp_filesystem->delete($remote_destination, true);
246                         $removed = apply_filters('upgrader_clear_destination', $removed, $local_destination, $remote_destination, $hook_extra);
247
248                         if ( is_wp_error($removed) )
249                                 return $removed;
250                         else if ( ! $removed )
251                                 return new WP_Error('remove_old_failed', $this->strings['remove_old_failed']);
252                 } elseif ( $abort_if_destination_exists && $wp_filesystem->exists($remote_destination) ) {
253                         //If we're not clearing the destination folder and something exists there already, Bail.
254                         //But first check to see if there are actually any files in the folder.
255                         $_files = $wp_filesystem->dirlist($remote_destination);
256                         if ( ! empty($_files) ) {
257                                 $wp_filesystem->delete($remote_source, true); //Clear out the source files.
258                                 return new WP_Error('folder_exists', $this->strings['folder_exists'], $remote_destination );
259                         }
260                 }
261
262                 //Create destination if needed
263                 if ( !$wp_filesystem->exists($remote_destination) )
264                         if ( !$wp_filesystem->mkdir($remote_destination, FS_CHMOD_DIR) )
265                                 return new WP_Error( 'mkdir_failed_destination', $this->strings['mkdir_failed'], $remote_destination );
266
267                 // Copy new version of item into place.
268                 $result = copy_dir($source, $remote_destination);
269                 if ( is_wp_error($result) ) {
270                         if ( $clear_working )
271                                 $wp_filesystem->delete($remote_source, true);
272                         return $result;
273                 }
274
275                 //Clear the Working folder?
276                 if ( $clear_working )
277                         $wp_filesystem->delete($remote_source, true);
278
279                 $destination_name = basename( str_replace($local_destination, '', $destination) );
280                 if ( '.' == $destination_name )
281                         $destination_name = '';
282
283                 $this->result = compact('local_source', 'source', 'source_name', 'source_files', 'destination', 'destination_name', 'local_destination', 'remote_destination', 'clear_destination', 'delete_source_dir');
284
285                 $res = apply_filters('upgrader_post_install', true, $hook_extra, $this->result);
286                 if ( is_wp_error($res) ) {
287                         $this->result = $res;
288                         return $res;
289                 }
290
291                 //Bombard the calling function will all the info which we've just used.
292                 return $this->result;
293         }
294
295         function run($options) {
296
297                 $defaults = array(
298                         'package' => '', // Please always pass this.
299                         'destination' => '', // And this
300                         'clear_destination' => false,
301                         'abort_if_destination_exists' => true, // Abort if the Destination directory exists, Pass clear_destination as false please
302                         'clear_working' => true,
303                         'is_multi' => false,
304                         'hook_extra' => array() // Pass any extra $hook_extra args here, this will be passed to any hooked filters.
305                 );
306
307                 $options = wp_parse_args($options, $defaults);
308                 extract($options);
309
310                 if ( ! $is_multi ) // call $this->header separately if running multiple times
311                         $this->skin->header();
312
313                 // Connect to the Filesystem first.
314                 $res = $this->fs_connect( array(WP_CONTENT_DIR, $destination) );
315                 // Mainly for non-connected filesystem.
316                 if ( ! $res ) {
317                         if ( ! $is_multi )
318                                 $this->skin->footer();
319                         return false;
320                 }
321
322                 $this->skin->before();
323
324                 if ( is_wp_error($res) ) {
325                         $this->skin->error($res);
326                         $this->skin->after();
327                         if ( ! $is_multi )
328                                 $this->skin->footer();
329                         return $res;
330                 }
331
332                 //Download the package (Note, This just returns the filename of the file if the package is a local file)
333                 $download = $this->download_package( $package );
334                 if ( is_wp_error($download) ) {
335                         $this->skin->error($download);
336                         $this->skin->after();
337                         if ( ! $is_multi )
338                                 $this->skin->footer();
339                         return $download;
340                 }
341
342                 $delete_package = ($download != $package); // Do not delete a "local" file
343
344                 //Unzips the file into a temporary directory
345                 $working_dir = $this->unpack_package( $download, $delete_package );
346                 if ( is_wp_error($working_dir) ) {
347                         $this->skin->error($working_dir);
348                         $this->skin->after();
349                         if ( ! $is_multi )
350                                 $this->skin->footer();
351                         return $working_dir;
352                 }
353
354                 //With the given options, this installs it to the destination directory.
355                 $result = $this->install_package( array(
356                         'source' => $working_dir,
357                         'destination' => $destination,
358                         'clear_destination' => $clear_destination,
359                         'abort_if_destination_exists' => $abort_if_destination_exists,
360                         'clear_working' => $clear_working,
361                         'hook_extra' => $hook_extra
362                 ) );
363
364                 $this->skin->set_result($result);
365                 if ( is_wp_error($result) ) {
366                         $this->skin->error($result);
367                         $this->skin->feedback('process_failed');
368                 } else {
369                         //Install Succeeded
370                         $this->skin->feedback('process_success');
371                 }
372
373                 $this->skin->after();
374
375                 if ( ! $is_multi ) {
376                         do_action( 'upgrader_process_complete', $this, $hook_extra );
377                         $this->skin->footer();
378                 }
379
380                 return $result;
381         }
382
383         function maintenance_mode($enable = false) {
384                 global $wp_filesystem;
385                 $file = $wp_filesystem->abspath() . '.maintenance';
386                 if ( $enable ) {
387                         $this->skin->feedback('maintenance_start');
388                         // Create maintenance file to signal that we are upgrading
389                         $maintenance_string = '<?php $upgrading = ' . time() . '; ?>';
390                         $wp_filesystem->delete($file);
391                         $wp_filesystem->put_contents($file, $maintenance_string, FS_CHMOD_FILE);
392                 } else if ( !$enable && $wp_filesystem->exists($file) ) {
393                         $this->skin->feedback('maintenance_end');
394                         $wp_filesystem->delete($file);
395                 }
396         }
397
398 }
399
400 /**
401  * Plugin Upgrader class for WordPress Plugins, It is designed to upgrade/install plugins from a local zip, remote zip URL, or uploaded zip file.
402  *
403  * @package WordPress
404  * @subpackage Upgrader
405  * @since 2.8.0
406  */
407 class Plugin_Upgrader extends WP_Upgrader {
408
409         var $result;
410         var $bulk = false;
411         var $show_before = '';
412
413         function upgrade_strings() {
414                 $this->strings['up_to_date'] = __('The plugin is at the latest version.');
415                 $this->strings['no_package'] = __('Update package not available.');
416                 $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;');
417                 $this->strings['unpack_package'] = __('Unpacking the update&#8230;');
418                 $this->strings['remove_old'] = __('Removing the old version of the plugin&#8230;');
419                 $this->strings['remove_old_failed'] = __('Could not remove the old plugin.');
420                 $this->strings['process_failed'] = __('Plugin update failed.');
421                 $this->strings['process_success'] = __('Plugin updated successfully.');
422         }
423
424         function install_strings() {
425                 $this->strings['no_package'] = __('Install package not available.');
426                 $this->strings['downloading_package'] = __('Downloading install package from <span class="code">%s</span>&#8230;');
427                 $this->strings['unpack_package'] = __('Unpacking the package&#8230;');
428                 $this->strings['installing_package'] = __('Installing the plugin&#8230;');
429                 $this->strings['no_files'] = __('The plugin contains no files.');
430                 $this->strings['process_failed'] = __('Plugin install failed.');
431                 $this->strings['process_success'] = __('Plugin installed successfully.');
432         }
433
434         function install( $package, $args = array() ) {
435
436                 $defaults = array(
437                         'clear_update_cache' => true,
438                 );
439                 $parsed_args = wp_parse_args( $args, $defaults );
440
441                 $this->init();
442                 $this->install_strings();
443
444                 add_filter('upgrader_source_selection', array($this, 'check_package') );
445
446                 $this->run( array(
447                         'package' => $package,
448                         'destination' => WP_PLUGIN_DIR,
449                         'clear_destination' => false, // Do not overwrite files.
450                         'clear_working' => true,
451                         'hook_extra' => array(
452                                 'type' => 'plugin',
453                                 'action' => 'install',
454                         )
455                 ) );
456
457                 remove_filter('upgrader_source_selection', array($this, 'check_package') );
458
459                 if ( ! $this->result || is_wp_error($this->result) )
460                         return $this->result;
461
462                 // Force refresh of plugin update information
463                 wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
464
465                 return true;
466         }
467
468         function upgrade( $plugin, $args = array() ) {
469
470                 $defaults = array(
471                         'clear_update_cache' => true,
472                 );
473                 $parsed_args = wp_parse_args( $args, $defaults );
474
475                 $this->init();
476                 $this->upgrade_strings();
477
478                 $current = get_site_transient( 'update_plugins' );
479                 if ( !isset( $current->response[ $plugin ] ) ) {
480                         $this->skin->before();
481                         $this->skin->set_result(false);
482                         $this->skin->error('up_to_date');
483                         $this->skin->after();
484                         return false;
485                 }
486
487                 // Get the URL to the zip file
488                 $r = $current->response[ $plugin ];
489
490                 add_filter('upgrader_pre_install', array($this, 'deactivate_plugin_before_upgrade'), 10, 2);
491                 add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4);
492                 //'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.
493
494                 $this->run( array(
495                         'package' => $r->package,
496                         'destination' => WP_PLUGIN_DIR,
497                         'clear_destination' => true,
498                         'clear_working' => true,
499                         'hook_extra' => array(
500                                 'plugin' => $plugin,
501                                 'type' => 'plugin',
502                                 'action' => 'update',
503                         ),
504                 ) );
505
506                 // Cleanup our hooks, in case something else does a upgrade on this connection.
507                 remove_filter('upgrader_pre_install', array($this, 'deactivate_plugin_before_upgrade'));
508                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'));
509
510                 if ( ! $this->result || is_wp_error($this->result) )
511                         return $this->result;
512
513                 // Force refresh of plugin update information
514                 wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
515
516                 return true;
517         }
518
519         function bulk_upgrade( $plugins, $args = array() ) {
520
521                 $defaults = array(
522                         'clear_update_cache' => true,
523                 );
524                 $parsed_args = wp_parse_args( $args, $defaults );
525
526                 $this->init();
527                 $this->bulk = true;
528                 $this->upgrade_strings();
529
530                 $current = get_site_transient( 'update_plugins' );
531
532                 add_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'), 10, 4);
533
534                 $this->skin->header();
535
536                 // Connect to the Filesystem first.
537                 $res = $this->fs_connect( array(WP_CONTENT_DIR, WP_PLUGIN_DIR) );
538                 if ( ! $res ) {
539                         $this->skin->footer();
540                         return false;
541                 }
542
543                 $this->skin->bulk_header();
544
545                 // Only start maintenance mode if:
546                 // - running Multisite and there are one or more plugins specified, OR
547                 // - a plugin with an update available is currently active.
548                 // @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
549                 $maintenance = ( is_multisite() && ! empty( $plugins ) );
550                 foreach ( $plugins as $plugin )
551                         $maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin] ) );
552                 if ( $maintenance )
553                         $this->maintenance_mode(true);
554
555                 $results = array();
556
557                 $this->update_count = count($plugins);
558                 $this->update_current = 0;
559                 foreach ( $plugins as $plugin ) {
560                         $this->update_current++;
561                         $this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true);
562
563                         if ( !isset( $current->response[ $plugin ] ) ) {
564                                 $this->skin->set_result(true);
565                                 $this->skin->before();
566                                 $this->skin->feedback('up_to_date');
567                                 $this->skin->after();
568                                 $results[$plugin] = true;
569                                 continue;
570                         }
571
572                         // Get the URL to the zip file
573                         $r = $current->response[ $plugin ];
574
575                         $this->skin->plugin_active = is_plugin_active($plugin);
576
577                         $result = $this->run( array(
578                                 'package' => $r->package,
579                                 'destination' => WP_PLUGIN_DIR,
580                                 'clear_destination' => true,
581                                 'clear_working' => true,
582                                 'is_multi' => true,
583                                 'hook_extra' => array(
584                                         'plugin' => $plugin
585                                 )
586                         ) );
587
588                         $results[$plugin] = $this->result;
589
590                         // Prevent credentials auth screen from displaying multiple times
591                         if ( false === $result )
592                                 break;
593                 } //end foreach $plugins
594
595                 $this->maintenance_mode(false);
596
597                 do_action( 'upgrader_process_complete', $this, array(
598                         'action' => 'update',
599                         'type' => 'plugin',
600                         'bulk' => true,
601                         'plugins' => $plugins,
602                 ) );
603
604                 $this->skin->bulk_footer();
605
606                 $this->skin->footer();
607
608                 // Cleanup our hooks, in case something else does a upgrade on this connection.
609                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_plugin'));
610
611                 // Force refresh of plugin update information
612                 wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
613
614                 return $results;
615         }
616
617         function check_package($source) {
618                 global $wp_filesystem;
619
620                 if ( is_wp_error($source) )
621                         return $source;
622
623                 $working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit(WP_CONTENT_DIR), $source);
624                 if ( ! is_dir($working_directory) ) // Sanity check, if the above fails, lets not prevent installation.
625                         return $source;
626
627                 // Check the folder contains at least 1 valid plugin.
628                 $plugins_found = false;
629                 foreach ( glob( $working_directory . '*.php' ) as $file ) {
630                         $info = get_plugin_data($file, false, false);
631                         if ( !empty( $info['Name'] ) ) {
632                                 $plugins_found = true;
633                                 break;
634                         }
635                 }
636
637                 if ( ! $plugins_found )
638                         return new WP_Error( 'incompatible_archive_no_plugins', $this->strings['incompatible_archive'], __( 'No valid plugins were found.' ) );
639
640                 return $source;
641         }
642
643         //return plugin info.
644         function plugin_info() {
645                 if ( ! is_array($this->result) )
646                         return false;
647                 if ( empty($this->result['destination_name']) )
648                         return false;
649
650                 $plugin = get_plugins('/' . $this->result['destination_name']); //Ensure to pass with leading slash
651                 if ( empty($plugin) )
652                         return false;
653
654                 $pluginfiles = array_keys($plugin); //Assume the requested plugin is the first in the list
655
656                 return $this->result['destination_name'] . '/' . $pluginfiles[0];
657         }
658
659         //Hooked to pre_install
660         function deactivate_plugin_before_upgrade($return, $plugin) {
661
662                 if ( is_wp_error($return) ) //Bypass.
663                         return $return;
664
665                 // When in cron (background updates) don't deactivate the plugin, as we require a browser to reactivate it
666                 if ( defined( 'DOING_CRON' ) && DOING_CRON )
667                         return $return;
668
669                 $plugin = isset($plugin['plugin']) ? $plugin['plugin'] : '';
670                 if ( empty($plugin) )
671                         return new WP_Error('bad_request', $this->strings['bad_request']);
672
673                 if ( is_plugin_active($plugin) ) {
674                         //Deactivate the plugin silently, Prevent deactivation hooks from running.
675                         deactivate_plugins($plugin, true);
676                 }
677         }
678
679         //Hooked to upgrade_clear_destination
680         function delete_old_plugin($removed, $local_destination, $remote_destination, $plugin) {
681                 global $wp_filesystem;
682
683                 if ( is_wp_error($removed) )
684                         return $removed; //Pass errors through.
685
686                 $plugin = isset($plugin['plugin']) ? $plugin['plugin'] : '';
687                 if ( empty($plugin) )
688                         return new WP_Error('bad_request', $this->strings['bad_request']);
689
690                 $plugins_dir = $wp_filesystem->wp_plugins_dir();
691                 $this_plugin_dir = trailingslashit( dirname($plugins_dir . $plugin) );
692
693                 if ( ! $wp_filesystem->exists($this_plugin_dir) ) //If it's already vanished.
694                         return $removed;
695
696                 // If plugin is in its own directory, recursively delete the directory.
697                 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
698                         $deleted = $wp_filesystem->delete($this_plugin_dir, true);
699                 else
700                         $deleted = $wp_filesystem->delete($plugins_dir . $plugin);
701
702                 if ( ! $deleted )
703                         return new WP_Error('remove_old_failed', $this->strings['remove_old_failed']);
704
705                 return true;
706         }
707 }
708
709 /**
710  * Theme Upgrader class for WordPress Themes, It is designed to upgrade/install themes from a local zip, remote zip URL, or uploaded zip file.
711  *
712  * @package WordPress
713  * @subpackage Upgrader
714  * @since 2.8.0
715  */
716 class Theme_Upgrader extends WP_Upgrader {
717
718         var $result;
719         var $bulk = false;
720
721         function upgrade_strings() {
722                 $this->strings['up_to_date'] = __('The theme is at the latest version.');
723                 $this->strings['no_package'] = __('Update package not available.');
724                 $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;');
725                 $this->strings['unpack_package'] = __('Unpacking the update&#8230;');
726                 $this->strings['remove_old'] = __('Removing the old version of the theme&#8230;');
727                 $this->strings['remove_old_failed'] = __('Could not remove the old theme.');
728                 $this->strings['process_failed'] = __('Theme update failed.');
729                 $this->strings['process_success'] = __('Theme updated successfully.');
730         }
731
732         function install_strings() {
733                 $this->strings['no_package'] = __('Install package not available.');
734                 $this->strings['downloading_package'] = __('Downloading install package from <span class="code">%s</span>&#8230;');
735                 $this->strings['unpack_package'] = __('Unpacking the package&#8230;');
736                 $this->strings['installing_package'] = __('Installing the theme&#8230;');
737                 $this->strings['no_files'] = __('The theme contains no files.');
738                 $this->strings['process_failed'] = __('Theme install failed.');
739                 $this->strings['process_success'] = __('Theme installed successfully.');
740                 /* translators: 1: theme name, 2: version */
741                 $this->strings['process_success_specific'] = __('Successfully installed the theme <strong>%1$s %2$s</strong>.');
742                 $this->strings['parent_theme_search'] = __('This theme requires a parent theme. Checking if it is installed&#8230;');
743                 /* translators: 1: theme name, 2: version */
744                 $this->strings['parent_theme_prepare_install'] = __('Preparing to install <strong>%1$s %2$s</strong>&#8230;');
745                 /* translators: 1: theme name, 2: version */
746                 $this->strings['parent_theme_currently_installed'] = __('The parent theme, <strong>%1$s %2$s</strong>, is currently installed.');
747                 /* translators: 1: theme name, 2: version */
748                 $this->strings['parent_theme_install_success'] = __('Successfully installed the parent theme, <strong>%1$s %2$s</strong>.');
749                 $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.');
750         }
751
752         function check_parent_theme_filter($install_result, $hook_extra, $child_result) {
753                 // Check to see if we need to install a parent theme
754                 $theme_info = $this->theme_info();
755
756                 if ( ! $theme_info->parent() )
757                         return $install_result;
758
759                 $this->skin->feedback( 'parent_theme_search' );
760
761                 if ( ! $theme_info->parent()->errors() ) {
762                         $this->skin->feedback( 'parent_theme_currently_installed', $theme_info->parent()->display('Name'), $theme_info->parent()->display('Version') );
763                         // We already have the theme, fall through.
764                         return $install_result;
765                 }
766
767                 // We don't have the parent theme, lets install it
768                 $api = themes_api('theme_information', array('slug' => $theme_info->get('Template'), 'fields' => array('sections' => false, 'tags' => false) ) ); //Save on a bit of bandwidth.
769
770                 if ( ! $api || is_wp_error($api) ) {
771                         $this->skin->feedback( 'parent_theme_not_found', $theme_info->get('Template') );
772                         // Don't show activate or preview actions after install
773                         add_filter('install_theme_complete_actions', array($this, 'hide_activate_preview_actions') );
774                         return $install_result;
775                 }
776
777                 // Backup required data we're going to override:
778                 $child_api = $this->skin->api;
779                 $child_success_message = $this->strings['process_success'];
780
781                 // Override them
782                 $this->skin->api = $api;
783                 $this->strings['process_success_specific'] = $this->strings['parent_theme_install_success'];//, $api->name, $api->version);
784
785                 $this->skin->feedback('parent_theme_prepare_install', $api->name, $api->version);
786
787                 add_filter('install_theme_complete_actions', '__return_false', 999); // Don't show any actions after installing the theme.
788
789                 // Install the parent theme
790                 $parent_result = $this->run( array(
791                         'package' => $api->download_link,
792                         'destination' => get_theme_root(),
793                         'clear_destination' => false, //Do not overwrite files.
794                         'clear_working' => true
795                 ) );
796
797                 if ( is_wp_error($parent_result) )
798                         add_filter('install_theme_complete_actions', array($this, 'hide_activate_preview_actions') );
799
800                 // Start cleaning up after the parents installation
801                 remove_filter('install_theme_complete_actions', '__return_false', 999);
802
803                 // Reset child's result and data
804                 $this->result = $child_result;
805                 $this->skin->api = $child_api;
806                 $this->strings['process_success'] = $child_success_message;
807
808                 return $install_result;
809         }
810
811         function hide_activate_preview_actions($actions) {
812                 unset($actions['activate'], $actions['preview']);
813                 return $actions;
814         }
815
816         function install( $package, $args = array() ) {
817
818                 $defaults = array(
819                         'clear_update_cache' => true,
820                 );
821                 $parsed_args = wp_parse_args( $args, $defaults );
822
823                 $this->init();
824                 $this->install_strings();
825
826                 add_filter('upgrader_source_selection', array($this, 'check_package') );
827                 add_filter('upgrader_post_install', array($this, 'check_parent_theme_filter'), 10, 3);
828
829                 $this->run( array(
830                         'package' => $package,
831                         'destination' => get_theme_root(),
832                         'clear_destination' => false, //Do not overwrite files.
833                         'clear_working' => true,
834                         'hook_extra' => array(
835                                 'type' => 'theme',
836                                 'action' => 'install',
837                         ),
838                 ) );
839
840                 remove_filter('upgrader_source_selection', array($this, 'check_package') );
841                 remove_filter('upgrader_post_install', array($this, 'check_parent_theme_filter'));
842
843                 if ( ! $this->result || is_wp_error($this->result) )
844                         return $this->result;
845
846                 // Refresh the Theme Update information
847                 wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
848
849                 return true;
850         }
851
852         function upgrade( $theme, $args = array() ) {
853
854                 $defaults = array(
855                         'clear_update_cache' => true,
856                 );
857                 $parsed_args = wp_parse_args( $args, $defaults );
858
859                 $this->init();
860                 $this->upgrade_strings();
861
862                 // Is an update available?
863                 $current = get_site_transient( 'update_themes' );
864                 if ( !isset( $current->response[ $theme ] ) ) {
865                         $this->skin->before();
866                         $this->skin->set_result(false);
867                         $this->skin->error('up_to_date');
868                         $this->skin->after();
869                         return false;
870                 }
871
872                 $r = $current->response[ $theme ];
873
874                 add_filter('upgrader_pre_install', array($this, 'current_before'), 10, 2);
875                 add_filter('upgrader_post_install', array($this, 'current_after'), 10, 2);
876                 add_filter('upgrader_clear_destination', array($this, 'delete_old_theme'), 10, 4);
877
878                 $this->run( array(
879                         'package' => $r['package'],
880                         'destination' => get_theme_root( $theme ),
881                         'clear_destination' => true,
882                         'clear_working' => true,
883                         'hook_extra' => array(
884                                 'theme' => $theme,
885                                 'type' => 'theme',
886                                 'action' => 'update',
887                         ),
888                 ) );
889
890                 remove_filter('upgrader_pre_install', array($this, 'current_before'));
891                 remove_filter('upgrader_post_install', array($this, 'current_after'));
892                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_theme'));
893
894                 if ( ! $this->result || is_wp_error($this->result) )
895                         return $this->result;
896
897                 wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
898
899                 return true;
900         }
901
902         function bulk_upgrade( $themes, $args = array() ) {
903
904                 $defaults = array(
905                         'clear_update_cache' => true,
906                 );
907                 $parsed_args = wp_parse_args( $args, $defaults );
908
909                 $this->init();
910                 $this->bulk = true;
911                 $this->upgrade_strings();
912
913                 $current = get_site_transient( 'update_themes' );
914
915                 add_filter('upgrader_pre_install', array($this, 'current_before'), 10, 2);
916                 add_filter('upgrader_post_install', array($this, 'current_after'), 10, 2);
917                 add_filter('upgrader_clear_destination', array($this, 'delete_old_theme'), 10, 4);
918
919                 $this->skin->header();
920
921                 // Connect to the Filesystem first.
922                 $res = $this->fs_connect( array(WP_CONTENT_DIR) );
923                 if ( ! $res ) {
924                         $this->skin->footer();
925                         return false;
926                 }
927
928                 $this->skin->bulk_header();
929
930                 // Only start maintenance mode if:
931                 // - running Multisite and there are one or more themes specified, OR
932                 // - a theme with an update available is currently in use.
933                 // @TODO: For multisite, maintenance mode should only kick in for individual sites if at all possible.
934                 $maintenance = ( is_multisite() && ! empty( $themes ) );
935                 foreach ( $themes as $theme )
936                         $maintenance = $maintenance || $theme == get_stylesheet() || $theme == get_template();
937                 if ( $maintenance )
938                         $this->maintenance_mode(true);
939
940                 $results = array();
941
942                 $this->update_count = count($themes);
943                 $this->update_current = 0;
944                 foreach ( $themes as $theme ) {
945                         $this->update_current++;
946
947                         $this->skin->theme_info = $this->theme_info($theme);
948
949                         if ( !isset( $current->response[ $theme ] ) ) {
950                                 $this->skin->set_result(true);
951                                 $this->skin->before();
952                                 $this->skin->feedback('up_to_date');
953                                 $this->skin->after();
954                                 $results[$theme] = true;
955                                 continue;
956                         }
957
958                         // Get the URL to the zip file
959                         $r = $current->response[ $theme ];
960
961                         $result = $this->run( array(
962                                 'package' => $r['package'],
963                                 'destination' => get_theme_root( $theme ),
964                                 'clear_destination' => true,
965                                 'clear_working' => true,
966                                 'hook_extra' => array(
967                                         'theme' => $theme
968                                 ),
969                         ) );
970
971                         $results[$theme] = $this->result;
972
973                         // Prevent credentials auth screen from displaying multiple times
974                         if ( false === $result )
975                                 break;
976                 } //end foreach $plugins
977
978                 $this->maintenance_mode(false);
979
980                 do_action( 'upgrader_process_complete', $this, array(
981                         'action' => 'update',
982                         'type' => 'plugin',
983                         'bulk' => true,
984                         'themes' => $themes,
985                 ) );
986
987                 $this->skin->bulk_footer();
988
989                 $this->skin->footer();
990
991                 // Cleanup our hooks, in case something else does a upgrade on this connection.
992                 remove_filter('upgrader_pre_install', array($this, 'current_before'));
993                 remove_filter('upgrader_post_install', array($this, 'current_after'));
994                 remove_filter('upgrader_clear_destination', array($this, 'delete_old_theme'));
995
996                 // Refresh the Theme Update information
997                 wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
998
999                 return $results;
1000         }
1001
1002         function check_package($source) {
1003                 global $wp_filesystem;
1004
1005                 if ( is_wp_error($source) )
1006                         return $source;
1007
1008                 // Check the folder contains a valid theme
1009                 $working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit(WP_CONTENT_DIR), $source);
1010                 if ( ! is_dir($working_directory) ) // Sanity check, if the above fails, lets not prevent installation.
1011                         return $source;
1012
1013                 // A proper archive should have a style.css file in the single subdirectory
1014                 if ( ! file_exists( $working_directory . 'style.css' ) )
1015                         return new WP_Error( 'incompatible_archive_theme_no_style', $this->strings['incompatible_archive'], __( 'The theme is missing the <code>style.css</code> stylesheet.' ) );
1016
1017                 $info = get_file_data( $working_directory . 'style.css', array( 'Name' => 'Theme Name', 'Template' => 'Template' ) );
1018
1019                 if ( empty( $info['Name'] ) )
1020                         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." ) );
1021
1022                 // If it's not a child theme, it must have at least an index.php to be legit.
1023                 if ( empty( $info['Template'] ) && ! file_exists( $working_directory . 'index.php' ) )
1024                         return new WP_Error( 'incompatible_archive_theme_no_index', $this->strings['incompatible_archive'], __( 'The theme is missing the <code>index.php</code> file.' ) );
1025
1026                 return $source;
1027         }
1028
1029         function current_before($return, $theme) {
1030
1031                 if ( is_wp_error($return) )
1032                         return $return;
1033
1034                 $theme = isset($theme['theme']) ? $theme['theme'] : '';
1035
1036                 if ( $theme != get_stylesheet() ) //If not current
1037                         return $return;
1038                 //Change to maintenance mode now.
1039                 if ( ! $this->bulk )
1040                         $this->maintenance_mode(true);
1041
1042                 return $return;
1043         }
1044
1045         function current_after($return, $theme) {
1046                 if ( is_wp_error($return) )
1047                         return $return;
1048
1049                 $theme = isset($theme['theme']) ? $theme['theme'] : '';
1050
1051                 if ( $theme != get_stylesheet() ) // If not current
1052                         return $return;
1053
1054                 // Ensure stylesheet name hasn't changed after the upgrade:
1055                 if ( $theme == get_stylesheet() && $theme != $this->result['destination_name'] ) {
1056                         wp_clean_themes_cache();
1057                         $stylesheet = $this->result['destination_name'];
1058                         switch_theme( $stylesheet );
1059                 }
1060
1061                 //Time to remove maintenance mode
1062                 if ( ! $this->bulk )
1063                         $this->maintenance_mode(false);
1064                 return $return;
1065         }
1066
1067         function delete_old_theme( $removed, $local_destination, $remote_destination, $theme ) {
1068                 global $wp_filesystem;
1069
1070                 if ( is_wp_error( $removed ) )
1071                         return $removed; // Pass errors through.
1072
1073                 if ( ! isset( $theme['theme'] ) )
1074                         return $removed;
1075
1076                 $theme = $theme['theme'];
1077                 $themes_dir = trailingslashit( $wp_filesystem->wp_themes_dir( $theme ) );
1078                 if ( $wp_filesystem->exists( $themes_dir . $theme ) ) {
1079                         if ( ! $wp_filesystem->delete( $themes_dir . $theme, true ) )
1080                                 return false;
1081                 }
1082
1083                 return true;
1084         }
1085
1086         function theme_info($theme = null) {
1087
1088                 if ( empty($theme) ) {
1089                         if ( !empty($this->result['destination_name']) )
1090                                 $theme = $this->result['destination_name'];
1091                         else
1092                                 return false;
1093                 }
1094                 return wp_get_theme( $theme );
1095         }
1096
1097 }
1098
1099 add_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
1100
1101 /**
1102  * Language pack upgrader, for updating translations of plugins, themes, and core.
1103  *
1104  * @package WordPress
1105  * @subpackage Upgrader
1106  * @since 3.7.0
1107  */
1108 class Language_Pack_Upgrader extends WP_Upgrader {
1109
1110         var $result;
1111         var $bulk = true;
1112
1113         static function async_upgrade( $upgrader = false ) {
1114                 // Avoid recursion.
1115                 if ( $upgrader && $upgrader instanceof Language_Pack_Upgrader )
1116                         return;
1117
1118                 // Nothing to do?
1119                 $language_updates = wp_get_translation_updates();
1120                 if ( ! $language_updates )
1121                         return;
1122
1123                 $skin = new Language_Pack_Upgrader_Skin( array(
1124                         'skip_header_footer' => true,
1125                 ) );
1126
1127                 $lp_upgrader = new Language_Pack_Upgrader( $skin );
1128                 $lp_upgrader->upgrade();
1129         }
1130
1131         function upgrade_strings() {
1132                 $this->strings['starting_upgrade'] = __( 'Some of your translations need updating. Sit tight for a few more seconds while we update them as well.' );
1133                 $this->strings['up_to_date'] = __( 'The translation is up to date.' ); // We need to silently skip this case
1134                 $this->strings['no_package'] = __( 'Update package not available.' );
1135                 $this->strings['downloading_package'] = __( 'Downloading translation from <span class="code">%s</span>&#8230;' );
1136                 $this->strings['unpack_package'] = __( 'Unpacking the update&#8230;' );
1137                 $this->strings['process_failed'] = __( 'Translation update failed.' );
1138                 $this->strings['process_success'] = __( 'Translation updated successfully.' );
1139         }
1140
1141         function upgrade( $update = false, $args = array() ) {
1142                 if ( $update )
1143                         $update = array( $update );
1144                 $results = $this->bulk_upgrade( $update, $args );
1145                 return $results[0];
1146         }
1147
1148         function bulk_upgrade( $language_updates = array(), $args = array() ) {
1149                 global $wp_filesystem;
1150
1151                 $defaults = array(
1152                         'clear_update_cache' => true,
1153                 );
1154                 $parsed_args = wp_parse_args( $args, $defaults );
1155
1156                 $this->init();
1157                 $this->upgrade_strings();
1158
1159                 if ( ! $language_updates )
1160                         $language_updates = wp_get_translation_updates();
1161
1162                 if ( empty( $language_updates ) ) {
1163                         $this->skin->header();
1164                         $this->skin->before();
1165                         $this->skin->set_result( true );
1166                         $this->skin->feedback( 'up_to_date' );
1167                         $this->skin->after();
1168                         $this->skin->bulk_footer();
1169                         $this->skin->footer();
1170                         return true;
1171                 }
1172
1173                 if ( 'upgrader_process_complete' == current_filter() )
1174                         $this->skin->feedback( 'starting_upgrade' );
1175
1176                 add_filter( 'upgrader_source_selection', array( &$this, 'check_package' ), 10, 3 );
1177
1178                 $this->skin->header();
1179
1180                 // Connect to the Filesystem first.
1181                 $res = $this->fs_connect( array( WP_CONTENT_DIR, WP_LANG_DIR ) );
1182                 if ( ! $res ) {
1183                         $this->skin->footer();
1184                         return false;
1185                 }
1186
1187                 $results = array();
1188
1189                 $this->update_count = count( $language_updates );
1190                 $this->update_current = 0;
1191
1192                 // The filesystem's mkdir() is not recursive. Make sure WP_LANG_DIR exists,
1193                 // as we then may need to create a /plugins or /themes directory inside of it.
1194                 $remote_destination = $wp_filesystem->find_folder( WP_LANG_DIR );
1195                 if ( ! $wp_filesystem->exists( $remote_destination ) )
1196                         if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) )
1197                                 return new WP_Error( 'mkdir_failed_lang_dir', $this->strings['mkdir_failed'], $remote_destination );
1198
1199                 foreach ( $language_updates as $language_update ) {
1200
1201                         $this->skin->language_update = $language_update;
1202
1203                         $destination = WP_LANG_DIR;
1204                         if ( 'plugin' == $language_update->type )
1205                                 $destination .= '/plugins';
1206                         elseif ( 'theme' == $language_update->type )
1207                                 $destination .= '/themes';
1208
1209                         $this->update_current++;
1210
1211                         $options = array(
1212                                 'package' => $language_update->package,
1213                                 'destination' => $destination,
1214                                 'clear_destination' => false,
1215                                 'abort_if_destination_exists' => false, // We expect the destination to exist.
1216                                 'clear_working' => true,
1217                                 'is_multi' => true,
1218                                 'hook_extra' => array(
1219                                         'language_update_type' => $language_update->type,
1220                                         'language_update' => $language_update,
1221                                 )
1222                         );
1223
1224                         $result = $this->run( $options );
1225
1226                         $results[] = $this->result;
1227
1228                         // Prevent credentials auth screen from displaying multiple times.
1229                         if ( false === $result )
1230                                 break;
1231                 }
1232
1233                 $this->skin->bulk_footer();
1234
1235                 $this->skin->footer();
1236
1237                 // Clean up our hooks, in case something else does an upgrade on this connection.
1238                 remove_filter( 'upgrader_source_selection', array( &$this, 'check_package' ), 10, 2 );
1239
1240                 if ( $parsed_args['clear_update_cache'] ) {
1241                         wp_clean_themes_cache( true );
1242                         wp_clean_plugins_cache( true );
1243                         delete_site_transient( 'update_core' );
1244                 }
1245
1246                 return $results;
1247         }
1248
1249         function check_package( $source, $remote_source ) {
1250                 global $wp_filesystem;
1251
1252                 if ( is_wp_error( $source ) )
1253                         return $source;
1254
1255                 // Check that the folder contains a valid language.
1256                 $files = $wp_filesystem->dirlist( $remote_source );
1257
1258                 // Check to see if a .po and .mo exist in the folder.
1259                 $po = $mo = false;
1260                 foreach ( (array) $files as $file => $filedata ) {
1261                         if ( '.po' == substr( $file, -3 ) )
1262                                 $po = true;
1263                         elseif ( '.mo' == substr( $file, -3 ) )
1264                                 $mo = true;
1265                 }
1266
1267                 if ( ! $mo || ! $po )
1268                         return new WP_Error( 'incompatible_archive_pomo', $this->strings['incompatible_archive'],
1269                                 __( 'The language pack is missing either the <code>.po</code> or <code>.mo</code> files.' ) );
1270
1271                 return $source;
1272         }
1273
1274         function get_name_for_update( $update ) {
1275                 switch ( $update->type ) {
1276                         case 'core':
1277                                 return 'WordPress'; // Not translated
1278                                 break;
1279                         case 'theme':
1280                                 $theme = wp_get_theme( $update->slug );
1281                                 if ( $theme->exists() )
1282                                         return $theme->Get( 'Name' );
1283                                 break;
1284                         case 'plugin':
1285                                 $plugin_data = get_plugins( '/' . $update->slug );
1286                                 $plugin_data = array_shift( $plugin_data );
1287                                 if ( $plugin_data )
1288                                         return $plugin_data['Name'];
1289                                 break;
1290                 }
1291                 return '';
1292         }
1293
1294 }
1295
1296 /**
1297  * Core Upgrader class for WordPress. It allows for WordPress to upgrade itself in combination with the wp-admin/includes/update-core.php file
1298  *
1299  * @package WordPress
1300  * @subpackage Upgrader
1301  * @since 2.8.0
1302  */
1303 class Core_Upgrader extends WP_Upgrader {
1304
1305         function upgrade_strings() {
1306                 $this->strings['up_to_date'] = __('WordPress is at the latest version.');
1307                 $this->strings['no_package'] = __('Update package not available.');
1308                 $this->strings['downloading_package'] = __('Downloading update from <span class="code">%s</span>&#8230;');
1309                 $this->strings['unpack_package'] = __('Unpacking the update&#8230;');
1310                 $this->strings['copy_failed'] = __('Could not copy files.');
1311                 $this->strings['copy_failed_space'] = __('Could not copy files. You may have run out of disk space.' );
1312                 $this->strings['start_rollback'] = __( 'Attempting to roll back to previous version.' );
1313                 $this->strings['rollback_was_required'] = __( 'Due to an error during updating, WordPress has rolled back to your previous version.' );
1314         }
1315
1316         function upgrade( $current, $args = array() ) {
1317                 global $wp_filesystem;
1318
1319                 include ABSPATH . WPINC . '/version.php'; // $wp_version;
1320
1321                 $start_time = time();
1322
1323                 $defaults = array(
1324                         'pre_check_md5'    => true,
1325                         'attempt_rollback' => false,
1326                         'do_rollback'      => false,
1327                 );
1328                 $parsed_args = wp_parse_args( $args, $defaults );
1329
1330                 $this->init();
1331                 $this->upgrade_strings();
1332
1333                 // Is an update available?
1334                 if ( !isset( $current->response ) || $current->response == 'latest' )
1335                         return new WP_Error('up_to_date', $this->strings['up_to_date']);
1336
1337                 $res = $this->fs_connect( array(ABSPATH, WP_CONTENT_DIR) );
1338                 if ( ! $res || is_wp_error( $res ) ) {
1339                         return $res;
1340                 }
1341
1342                 $wp_dir = trailingslashit($wp_filesystem->abspath());
1343
1344                 $partial = true;
1345                 if ( $parsed_args['do_rollback'] )
1346                         $partial = false;
1347                 elseif ( $parsed_args['pre_check_md5'] && ! $this->check_files() )
1348                         $partial = false;
1349
1350                 // If partial update is returned from the API, use that, unless we're doing a reinstall.
1351                 // If we cross the new_bundled version number, then use the new_bundled zip.
1352                 // Don't though if the constant is set to skip bundled items.
1353                 // If the API returns a no_content zip, go with it. Finally, default to the full zip.
1354                 if ( $parsed_args['do_rollback'] && $current->packages->rollback )
1355                         $to_download = 'rollback';
1356                 elseif ( $current->packages->partial && 'reinstall' != $current->response && $wp_version == $current->partial_version && $partial )
1357                         $to_download = 'partial';
1358                 elseif ( $current->packages->new_bundled && version_compare( $wp_version, $current->new_bundled, '<' )
1359                         && ( ! defined( 'CORE_UPGRADE_SKIP_NEW_BUNDLED' ) || ! CORE_UPGRADE_SKIP_NEW_BUNDLED ) )
1360                         $to_download = 'new_bundled';
1361                 elseif ( $current->packages->no_content )
1362                         $to_download = 'no_content';
1363                 else
1364                         $to_download = 'full';
1365
1366                 $download = $this->download_package( $current->packages->$to_download );
1367                 if ( is_wp_error($download) )
1368                         return $download;
1369
1370                 $working_dir = $this->unpack_package( $download );
1371                 if ( is_wp_error($working_dir) )
1372                         return $working_dir;
1373
1374                 // Copy update-core.php from the new version into place.
1375                 if ( !$wp_filesystem->copy($working_dir . '/wordpress/wp-admin/includes/update-core.php', $wp_dir . 'wp-admin/includes/update-core.php', true) ) {
1376                         $wp_filesystem->delete($working_dir, true);
1377                         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' );
1378                 }
1379                 $wp_filesystem->chmod($wp_dir . 'wp-admin/includes/update-core.php', FS_CHMOD_FILE);
1380
1381                 require_once( ABSPATH . 'wp-admin/includes/update-core.php' );
1382
1383                 if ( ! function_exists( 'update_core' ) )
1384                         return new WP_Error( 'copy_failed_space', $this->strings['copy_failed_space'] );
1385
1386                 $result = update_core( $working_dir, $wp_dir );
1387
1388                 // In the event of an issue, we may be able to roll back.
1389                 if ( $parsed_args['attempt_rollback'] && $current->packages->rollback && ! $parsed_args['do_rollback'] ) {
1390                         $try_rollback = false;
1391                         if ( is_wp_error( $result ) ) {
1392                                 $error_code = $result->get_error_code();
1393                                 // Not all errors are equal. These codes are critical: copy_failed__copy_dir,
1394                                 // mkdir_failed__copy_dir, copy_failed__copy_dir_retry, and disk_full.
1395                                 // do_rollback allows for update_core() to trigger a rollback if needed.
1396                                 if ( false !== strpos( $error_code, 'do_rollback' ) )
1397                                         $try_rollback = true;
1398                                 elseif ( false !== strpos( $error_code, '__copy_dir' ) )
1399                                         $try_rollback = true;
1400                                 elseif ( 'disk_full' === $error_code )
1401                                         $try_rollback = true;
1402                         }
1403
1404                         if ( $try_rollback ) {
1405                                 apply_filters( 'update_feedback', $result );
1406                                 apply_filters( 'update_feedback', $this->strings['start_rollback'] );
1407
1408                                 $rollback_result = $this->upgrade( $current, array_merge( $parsed_args, array( 'do_rollback' => true ) ) );
1409
1410                                 $original_result = $result;
1411                                 $result = new WP_Error( 'rollback_was_required', $this->strings['rollback_was_required'], (object) array( 'update' => $original_result, 'rollback' => $rollback_result ) );
1412                         }
1413                 }
1414
1415                 do_action( 'upgrader_process_complete', $this, array( 'action' => 'update', 'type' => 'core' ) );
1416
1417                 // Clear the current updates
1418                 delete_site_transient( 'update_core' );
1419
1420                 if ( ! $parsed_args['do_rollback'] ) {
1421                         $stats = array(
1422                                 'update_type'      => $current->response,
1423                                 'success'          => true,
1424                                 'fs_method'        => $wp_filesystem->method,
1425                                 'fs_method_forced' => defined( 'FS_METHOD' ) || has_filter( 'filesystem_method' ),
1426                                 'time_taken'       => time() - $start_time,
1427                                 'reported'         => $wp_version,
1428                                 'attempted'        => $current->version,
1429                         );
1430
1431                         if ( is_wp_error( $result ) ) {
1432                                 $stats['success'] = false;
1433                                 // Did a rollback occur?
1434                                 if ( ! empty( $try_rollback ) ) {
1435                                         $stats['error_code'] = $original_result->get_error_code();
1436                                         $stats['error_data'] = $original_result->get_error_data();
1437                                         // Was the rollback successful? If not, collect its error too.
1438                                         $stats['rollback'] = ! is_wp_error( $rollback_result );
1439                                         if ( is_wp_error( $rollback_result ) ) {
1440                                                 $stats['rollback_code'] = $rollback_result->get_error_code();
1441                                                 $stats['rollback_data'] = $rollback_result->get_error_data();
1442                                         }
1443                                 } else {
1444                                         $stats['error_code'] = $result->get_error_code();
1445                                         $stats['error_data'] = $result->get_error_data();
1446                                 }
1447                         }
1448
1449                         wp_version_check( $stats );
1450                 }
1451
1452                 return $result;
1453         }
1454
1455         // Determines if this WordPress Core version should update to $offered_ver or not
1456         static function should_update_to_version( $offered_ver /* x.y.z */ ) {
1457                 include ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z
1458
1459                 $current_branch = implode( '.', array_slice( preg_split( '/[.-]/', $wp_version  ), 0, 2 ) ); // x.y
1460                 $new_branch     = implode( '.', array_slice( preg_split( '/[.-]/', $offered_ver ), 0, 2 ) ); // x.y
1461                 $current_is_development_version = (bool) strpos( $wp_version, '-' );
1462
1463                 // Defaults:
1464                 $upgrade_dev   = true;
1465                 $upgrade_minor = true;
1466                 $upgrade_major = false;
1467
1468                 // WP_AUTO_UPDATE_CORE = true (all), 'minor', false.
1469                 if ( defined( 'WP_AUTO_UPDATE_CORE' ) ) {
1470                         if ( false === WP_AUTO_UPDATE_CORE ) {
1471                                 // Defaults to turned off, unless a filter allows it
1472                                 $upgrade_dev = $upgrade_minor = $upgrade_major = false;
1473                         } elseif ( true === WP_AUTO_UPDATE_CORE ) {
1474                                 // ALL updates for core
1475                                 $upgrade_dev = $upgrade_minor = $upgrade_major = true;
1476                         } elseif ( 'minor' === WP_AUTO_UPDATE_CORE ) {
1477                                 // Only minor updates for core
1478                                 $upgrade_dev = $upgrade_major = false;
1479                                 $upgrade_minor = true;
1480                         }
1481                 }
1482
1483                 // 1: If we're already on that version, not much point in updating?
1484                 if ( $offered_ver == $wp_version )
1485                         return false;
1486
1487                 // 2: If we're running a newer version, that's a nope
1488                 if ( version_compare( $wp_version, $offered_ver, '>' ) )
1489                         return false;
1490
1491                 $failure_data = get_site_option( 'auto_core_update_failed' );
1492                 if ( $failure_data ) {
1493                         // If this was a critical update failure, cannot update.
1494                         if ( ! empty( $failure_data['critical'] ) )
1495                                 return false;
1496
1497                         // Don't claim we can update on update-core.php if we have a non-critical failure logged.
1498                         if ( $wp_version == $failure_data['current'] && false !== strpos( $offered_ver, '.1.next.minor' ) )
1499                                 return false;
1500
1501                         // Cannot update if we're retrying the same A to B update that caused a non-critical failure.
1502                         // Some non-critical failures do allow retries, like download_failed.
1503                         // 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.
1504                         if ( empty( $failure_data['retry'] ) && $wp_version == $failure_data['current'] && $offered_ver == $failure_data['attempted'] )
1505                                 return false;
1506                 }
1507
1508                 // 3: 3.7-alpha-25000 -> 3.7-alpha-25678 -> 3.7-beta1 -> 3.7-beta2
1509                 if ( $current_is_development_version ) {
1510                         if ( ! apply_filters( 'allow_dev_auto_core_updates', $upgrade_dev ) )
1511                                 return false;
1512                         // else fall through to minor + major branches below
1513                 }
1514
1515                 // 4: Minor In-branch updates (3.7.0 -> 3.7.1 -> 3.7.2 -> 3.7.4)
1516                 if ( $current_branch == $new_branch )
1517                         return apply_filters( 'allow_minor_auto_core_updates', $upgrade_minor );
1518
1519                 // 5: Major version updates (3.7.0 -> 3.8.0 -> 3.9.1)
1520                 if ( version_compare( $new_branch, $current_branch, '>' ) )
1521                         return apply_filters( 'allow_major_auto_core_updates', $upgrade_major );
1522
1523                 // If we're not sure, we don't want it
1524                 return false;
1525         }
1526
1527         function check_files() {
1528                 global $wp_version, $wp_local_package;
1529
1530                 $checksums = get_core_checksums( $wp_version, isset( $wp_local_package ) ? $wp_local_package : 'en_US' );
1531
1532                 if ( ! is_array( $checksums ) )
1533                         return false;
1534
1535                 foreach ( $checksums as $file => $checksum ) {
1536                         // Skip files which get updated
1537                         if ( 'wp-content' == substr( $file, 0, 10 ) )
1538                                 continue;
1539                         if ( ! file_exists( ABSPATH . $file ) || md5_file( ABSPATH . $file ) !== $checksum )
1540                                 return false;
1541                 }
1542
1543                 return true;
1544         }
1545 }
1546
1547 /**
1548  * 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.
1549  *
1550  * @package WordPress
1551  * @subpackage Upgrader
1552  * @since 2.8.0
1553  */
1554 class File_Upload_Upgrader {
1555         var $package;
1556         var $filename;
1557         var $id = 0;
1558
1559         function __construct($form, $urlholder) {
1560
1561                 if ( empty($_FILES[$form]['name']) && empty($_GET[$urlholder]) )
1562                         wp_die(__('Please select a file'));
1563
1564                 //Handle a newly uploaded file, Else assume it's already been uploaded
1565                 if ( ! empty($_FILES) ) {
1566                         $overrides = array( 'test_form' => false, 'test_type' => false );
1567                         $file = wp_handle_upload( $_FILES[$form], $overrides );
1568
1569                         if ( isset( $file['error'] ) )
1570                                 wp_die( $file['error'] );
1571
1572                         $this->filename = $_FILES[$form]['name'];
1573                         $this->package = $file['file'];
1574
1575                         // Construct the object array
1576                         $object = array(
1577                                 'post_title' => $this->filename,
1578                                 'post_content' => $file['url'],
1579                                 'post_mime_type' => $file['type'],
1580                                 'guid' => $file['url'],
1581                                 'context' => 'upgrader',
1582                                 'post_status' => 'private'
1583                         );
1584
1585                         // Save the data
1586                         $this->id = wp_insert_attachment( $object, $file['file'] );
1587
1588                         // schedule a cleanup for 2 hours from now in case of failed install
1589                         wp_schedule_single_event( time() + 7200, 'upgrader_scheduled_cleanup', array( $this->id ) );
1590
1591                 } elseif ( is_numeric( $_GET[$urlholder] ) ) {
1592                         // Numeric Package = previously uploaded file, see above.
1593                         $this->id = (int) $_GET[$urlholder];
1594                         $attachment = get_post( $this->id );
1595                         if ( empty($attachment) )
1596                                 wp_die(__('Please select a file'));
1597
1598                         $this->filename = $attachment->post_title;
1599                         $this->package = get_attached_file( $attachment->ID );
1600                 } else {
1601                         // Else, It's set to something, Back compat for plugins using the old (pre-3.3) File_Uploader handler.
1602                         if ( ! ( ( $uploads = wp_upload_dir() ) && false === $uploads['error'] ) )
1603                                 wp_die( $uploads['error'] );
1604
1605                         $this->filename = $_GET[$urlholder];
1606                         $this->package = $uploads['basedir'] . '/' . $this->filename;
1607                 }
1608         }
1609
1610         function cleanup() {
1611                 if ( $this->id )
1612                         wp_delete_attachment( $this->id );
1613
1614                 elseif ( file_exists( $this->package ) )
1615                         return @unlink( $this->package );
1616
1617                 return true;
1618         }
1619 }
1620
1621 /**
1622  * The WordPress automatic background updater.
1623  *
1624  * @package WordPress
1625  * @subpackage Upgrader
1626  * @since 3.7.0
1627  */
1628 class WP_Automatic_Updater {
1629
1630         /**
1631          * Tracks update results during processing.
1632          *
1633          * @var array
1634          */
1635         protected $update_results = array();
1636
1637         /**
1638          * Whether the entire automatic updater is disabled.
1639          *
1640          * @since 3.7.0
1641          */
1642         public function is_disabled() {
1643                 // Background updates are disabled if you don't want file changes.
1644                 if ( defined( 'DISALLOW_FILE_MODS' ) && DISALLOW_FILE_MODS )
1645                         return true;
1646
1647                 if ( defined( 'WP_INSTALLING' ) )
1648                         return true;
1649
1650                 // More fine grained control can be done through the WP_AUTO_UPDATE_CORE constant and filters.
1651                 $disabled = defined( 'AUTOMATIC_UPDATER_DISABLED' ) && AUTOMATIC_UPDATER_DISABLED;
1652
1653                 /**
1654                  * Filter whether to entirely disable background updates.
1655                  *
1656                  * There are more fine-grained filters and controls for selective disabling.
1657                  * This filter parallels the AUTOMATIC_UPDATER_DISABLED constant in name.
1658                  *
1659                  * This also disables update notification emails. That may change in the future.
1660                  *
1661                  * @since 3.7.0
1662                  * @param bool $disabled Whether the updater should be disabled.
1663                  */
1664                 return apply_filters( 'automatic_updater_disabled', $disabled );
1665         }
1666
1667         /**
1668          * Check for version control checkouts.
1669          *
1670          * Checks for Subversion, Git, Mercurial, and Bazaar. It recursively looks up the
1671          * filesystem to the top of the drive, erring on the side of detecting a VCS
1672          * checkout somewhere.
1673          *
1674          * ABSPATH is always checked in addition to whatever $context is (which may be the
1675          * wp-content directory, for example). The underlying assumption is that if you are
1676          * using version control *anywhere*, then you should be making decisions for
1677          * how things get updated.
1678          *
1679          * @since 3.7.0
1680          *
1681          * @param string $context The filesystem path to check, in addition to ABSPATH.
1682          */
1683         public function is_vcs_checkout( $context ) {
1684                 $context_dirs = array( untrailingslashit( $context ) );
1685                 if ( $context !== ABSPATH )
1686                         $context_dirs[] = untrailingslashit( ABSPATH );
1687
1688                 $vcs_dirs = array( '.svn', '.git', '.hg', '.bzr' );
1689                 $check_dirs = array();
1690
1691                 foreach ( $context_dirs as $context_dir ) {
1692                         // Walk up from $context_dir to the root.
1693                         do {
1694                                 $check_dirs[] = $context_dir;
1695
1696                                 // Once we've hit '/' or 'C:\', we need to stop. dirname will keep returning the input here.
1697                                 if ( $context_dir == dirname( $context_dir ) )
1698                                         break;
1699
1700                         // Continue one level at a time.
1701                         } while ( $context_dir = dirname( $context_dir ) );
1702                 }
1703
1704                 $check_dirs = array_unique( $check_dirs );
1705
1706                 // Search all directories we've found for evidence of version control.
1707                 foreach ( $vcs_dirs as $vcs_dir ) {
1708                         foreach ( $check_dirs as $check_dir ) {
1709                                 if ( $checkout = @is_dir( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" ) )
1710                                         break 2;
1711                         }
1712                 }
1713
1714                 /**
1715                  * Filter whether the automatic updater should consider a filesystem location to be potentially
1716                  * managed by a version control system.
1717                  *
1718                  * @since 3.7.0
1719                  *
1720                  * @param bool $checkout  Whether a VCS checkout was discovered at $context or ABSPATH, or anywhere higher.
1721                  * @param string $context The filesystem context (a path) against which filesystem status should be checked.
1722                  */
1723                 return apply_filters( 'automatic_updates_is_vcs_checkout', $checkout, $context );
1724         }
1725
1726         /**
1727          * Tests to see if we can and should update a specific item.
1728          *
1729          * @since 3.7.0
1730          *
1731          * @param string $type    The type of update being checked: 'core', 'theme', 'plugin', 'translation'.
1732          * @param object $item    The update offer.
1733          * @param string $context The filesystem context (a path) against which filesystem access and status
1734          *                        should be checked.
1735          */
1736         public function should_update( $type, $item, $context ) {
1737                 // Used to see if WP_Filesystem is set up to allow unattended updates.
1738                 $skin = new Automatic_Upgrader_Skin;
1739
1740                 if ( $this->is_disabled() )
1741                         return false;
1742
1743                 // If we can't do an auto core update, we may still be able to email the user.
1744                 if ( ! $skin->request_filesystem_credentials( false, $context ) || $this->is_vcs_checkout( $context ) ) {
1745                         if ( 'core' == $type )
1746                                 $this->send_core_update_notification_email( $item );
1747                         return false;
1748                 }
1749
1750                 // Next up, is this an item we can update?
1751                 if ( 'core' == $type )
1752                         $update = Core_Upgrader::should_update_to_version( $item->current );
1753                 else
1754                         $update = ! empty( $item->autoupdate );
1755
1756                 /**
1757                  * Filter whether to automatically update core, a plugin, a theme, or a language.
1758                  *
1759                  * The dynamic portion of the hook name, $type, refers to the type of update
1760                  * being checked. Can be 'core', 'theme', 'plugin', or 'translation'.
1761                  *
1762                  * Generally speaking, plugins, themes, and major core versions are not updated by default,
1763                  * while translations and minor and development versions for core are updated by default.
1764                  *
1765                  * See the filters allow_dev_auto_core_updates, allow_minor_auto_core_updates, and
1766                  * allow_major_auto_core_updates more straightforward filters to adjust core updates.
1767                  *
1768                  * @since 3.7.0
1769                  *
1770                  * @param bool   $update Whether to update.
1771                  * @param object $item   The update offer.
1772                  */
1773                 $update = apply_filters( 'auto_update_' . $type, $update, $item );
1774
1775                 if ( ! $update ) {
1776                         if ( 'core' == $type )
1777                                 $this->send_core_update_notification_email( $item );
1778                         return false;
1779                 }
1780
1781                 // If it's a core update, are we actually compatible with its requirements?
1782                 if ( 'core' == $type ) {
1783                         global $wpdb;
1784
1785                         $php_compat = version_compare( phpversion(), $item->php_version, '>=' );
1786                         if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) )
1787                                 $mysql_compat = true;
1788                         else
1789                                 $mysql_compat = version_compare( $wpdb->db_version(), $item->mysql_version, '>=' );
1790
1791                         if ( ! $php_compat || ! $mysql_compat )
1792                                 return false;
1793                 }
1794
1795                 return true;
1796         }
1797
1798         /**
1799          * Notifies an administrator of a core update.
1800          *
1801          * @since 3.7.0
1802          *
1803          * @param object $item The update offer.
1804          */
1805         protected function send_core_update_notification_email( $item ) {
1806                 $notify   = true;
1807                 $notified = get_site_option( 'auto_core_update_notified' );
1808
1809                 // Don't notify if we've already notified the same email address of the same version.
1810                 if ( $notified && $notified['email'] == get_site_option( 'admin_email' ) && $notified['version'] == $item->current )
1811                         return false;
1812
1813                 // See if we need to notify users of a core update.
1814                 $notify = ! empty( $item->notify_email );
1815
1816                 /**
1817                  * Whether to notify the site administrator of a new core update.
1818                  *
1819                  * By default, administrators are notified when the update offer received from WordPress.org
1820                  * sets a particular flag. This allows for discretion in if and when to notify.
1821                  *
1822                  * This filter only fires once per release -- if the same email address was already
1823                  * notified of the same new version, we won't repeatedly email the administrator.
1824                  *
1825                  * This filter is also used on about.php to check if a plugin has disabled these notifications.
1826                  *
1827                  * @since 3.7.0
1828                  *
1829                  * @param bool $notify Whether the site administrator is notified.
1830                  * @param object $item The update offer.
1831                  */
1832                 if ( ! apply_filters( 'send_core_update_notification_email', $notify, $item ) )
1833                         return false;
1834
1835                 $this->send_email( 'manual', $item );
1836                 return true;
1837         }
1838
1839         /**
1840          * Update an item, if appropriate.
1841          *
1842          * @since 3.7.0
1843          *
1844          * @param string $type The type of update being checked: 'core', 'theme', 'plugin', 'translation'.
1845          * @param object $item The update offer.
1846          */
1847         public function update( $type, $item ) {
1848                 $skin = new Automatic_Upgrader_Skin;
1849
1850                 switch ( $type ) {
1851                         case 'core':
1852                                 // The Core upgrader doesn't use the Upgrader's skin during the actual main part of the upgrade, instead, firing a filter.
1853                                 add_filter( 'update_feedback', array( $skin, 'feedback' ) );
1854                                 $upgrader = new Core_Upgrader( $skin );
1855                                 $context  = ABSPATH;
1856                                 break;
1857                         case 'plugin':
1858                                 $upgrader = new Plugin_Upgrader( $skin );
1859                                 $context  = WP_PLUGIN_DIR; // We don't support custom Plugin directories, or updates for WPMU_PLUGIN_DIR
1860                                 break;
1861                         case 'theme':
1862                                 $upgrader = new Theme_Upgrader( $skin );
1863                                 $context  = get_theme_root( $item );
1864                                 break;
1865                         case 'translation':
1866                                 $upgrader = new Language_Pack_Upgrader( $skin );
1867                                 $context  = WP_CONTENT_DIR; // WP_LANG_DIR;
1868                                 break;
1869                 }
1870
1871                 // Determine whether we can and should perform this update.
1872                 if ( ! $this->should_update( $type, $item, $context ) )
1873                         return false;
1874
1875                 $upgrader_item = $item;
1876                 switch ( $type ) {
1877                         case 'core':
1878                                 $skin->feedback( __( 'Updating to WordPress %s' ), $item->version );
1879                                 $item_name = sprintf( __( 'WordPress %s' ), $item->version );
1880                                 break;
1881                         case 'theme':
1882                                 $upgrader_item = $item->theme;
1883                                 $theme = wp_get_theme( $upgrader_item );
1884                                 $item_name = $theme->Get( 'Name' );
1885                                 $skin->feedback( __( 'Updating theme: %s' ), $item_name );
1886                                 break;
1887                         case 'plugin':
1888                                 $upgrader_item = $item->plugin;
1889                                 $plugin_data = get_plugin_data( $context . '/' . $upgrader_item );
1890                                 $item_name = $plugin_data['Name'];
1891                                 $skin->feedback( __( 'Updating plugin: %s' ), $item_name );
1892                                 break;
1893                         case 'translation':
1894                                 $language_item_name = $upgrader->get_name_for_update( $item );
1895                                 $item_name = sprintf( __( 'Translations for %s' ), $language_item_name );
1896                                 $skin->feedback( sprintf( __( 'Updating translations for %1$s (%2$s)&#8230;' ), $language_item_name, $item->language ) );
1897                                 break;
1898                 }
1899
1900                 // Boom, This sites about to get a whole new splash of paint!
1901                 $upgrade_result = $upgrader->upgrade( $upgrader_item, array(
1902                         'clear_update_cache' => false,
1903                         'pre_check_md5'      => false, /* always use partial builds if possible for core updates */
1904                         'attempt_rollback'   => true, /* only available for core updates */
1905                 ) );
1906
1907                 // if the filesystem is unavailable, false is returned.
1908                 if ( false === $upgrade_result ) {
1909                         $upgrade_result = new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
1910                 }
1911
1912                 // Core doesn't output this, so lets append it so we don't get confused
1913                 if ( 'core' == $type ) {
1914                         if ( is_wp_error( $upgrade_result ) ) {
1915                                 $skin->error( __( 'Installation Failed' ), $upgrade_result );
1916                         } else {
1917                                 $skin->feedback( __( 'WordPress updated successfully' ) );
1918                         }
1919                 }
1920
1921                 $this->update_results[ $type ][] = (object) array(
1922                         'item'     => $item,
1923                         'result'   => $upgrade_result,
1924                         'name'     => $item_name,
1925                         'messages' => $skin->get_upgrade_messages()
1926                 );
1927
1928                 return $upgrade_result;
1929         }
1930
1931         /**
1932          * Kicks off the background update process, looping through all pending updates.
1933          *
1934          * @since 3.7.0
1935          */
1936         public function run() {
1937                 global $wpdb, $wp_version;
1938
1939                 if ( $this->is_disabled() )
1940                         return;
1941
1942                 if ( ! is_main_network() || ! is_main_site() )
1943                         return;
1944
1945                 $lock_name = 'auto_updater.lock';
1946
1947                 // Try to lock
1948                 $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) );
1949
1950                 if ( ! $lock_result ) {
1951                         $lock_result = get_option( $lock_name );
1952
1953                         // If we couldn't create a lock, and there isn't a lock, bail
1954                         if ( ! $lock_result )
1955                                 return;
1956
1957                         // Check to see if the lock is still valid
1958                         if ( $lock_result > ( time() - HOUR_IN_SECONDS ) )
1959                                 return;
1960                 }
1961
1962                 // Update the lock, as by this point we've definately got a lock, just need to fire the actions
1963                 update_option( $lock_name, time() );
1964
1965                 // Don't automatically run these thins, as we'll handle it ourselves
1966                 remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
1967                 remove_action( 'upgrader_process_complete', 'wp_version_check' );
1968                 remove_action( 'upgrader_process_complete', 'wp_update_plugins' );
1969                 remove_action( 'upgrader_process_complete', 'wp_update_themes' );
1970
1971                 // Next, Plugins
1972                 wp_update_plugins(); // Check for Plugin updates
1973                 $plugin_updates = get_site_transient( 'update_plugins' );
1974                 if ( $plugin_updates && !empty( $plugin_updates->response ) ) {
1975                         foreach ( $plugin_updates->response as $plugin ) {
1976                                 $this->update( 'plugin', $plugin );
1977                         }
1978                         // Force refresh of plugin update information
1979                         wp_clean_plugins_cache();
1980                 }
1981
1982                 // Next, those themes we all love
1983                 wp_update_themes();  // Check for Theme updates
1984                 $theme_updates = get_site_transient( 'update_themes' );
1985                 if ( $theme_updates && !empty( $theme_updates->response ) ) {
1986                         foreach ( $theme_updates->response as $theme ) {
1987                                 $this->update( 'theme', (object) $theme );
1988                         }
1989                         // Force refresh of theme update information
1990                         wp_clean_themes_cache();
1991                 }
1992
1993                 // Next, Process any core update
1994                 wp_version_check(); // Check for Core updates
1995                 $core_update = find_core_auto_update();
1996
1997                 if ( $core_update )
1998                         $this->update( 'core', $core_update );
1999
2000                 // Clean up, and check for any pending translations
2001                 // (Core_Upgrader checks for core updates)
2002                 $theme_stats = array();
2003                 if ( isset( $this->update_results['theme'] ) ) {
2004                         foreach ( $this->update_results['theme'] as $upgrade ) {
2005                                 $theme_stats[ $upgrade->item->theme ] = ( true === $upgrade->result );
2006                         }
2007                 }
2008                 wp_update_themes( $theme_stats );  // Check for Theme updates
2009
2010                 $plugin_stats = array();
2011                 if ( isset( $this->update_results['plugin'] ) ) {
2012                         foreach ( $this->update_results['plugin'] as $upgrade ) {
2013                                 $plugin_stats[ $upgrade->item->plugin ] = ( true === $upgrade->result );
2014                         }
2015                 }
2016                 wp_update_plugins( $plugin_stats ); // Check for Plugin updates
2017
2018                 // Finally, Process any new translations
2019                 $language_updates = wp_get_translation_updates();
2020                 if ( $language_updates ) {
2021                         foreach ( $language_updates as $update ) {
2022                                 $this->update( 'translation', $update );
2023                         }
2024
2025                         // Clear existing caches
2026                         wp_clean_plugins_cache();
2027                         wp_clean_themes_cache();
2028                         delete_site_transient( 'update_core' );
2029
2030                         wp_version_check();  // check for Core updates
2031                         wp_update_themes();  // Check for Theme updates
2032                         wp_update_plugins(); // Check for Plugin updates
2033                 }
2034
2035                 // Send debugging email to all development installs.
2036                 if ( ! empty( $this->update_results ) ) {
2037                         $development_version = false !== strpos( $wp_version, '-' );
2038                         /**
2039                          * Filter whether to send a debugging email for each automatic background update.
2040                          *
2041                          * @since 3.7.0
2042                          * @param bool $development_version By default, emails are sent if the install is a development version.
2043                          *                                  Return false to avoid the email.
2044                          */
2045                         if ( apply_filters( 'automatic_updates_send_debug_email', $development_version ) )
2046                                 $this->send_debug_email();
2047
2048                         if ( ! empty( $this->update_results['core'] ) )
2049                                 $this->after_core_update( $this->update_results['core'][0] );
2050                 }
2051
2052                 // Clear the lock
2053                 delete_option( $lock_name );
2054         }
2055
2056         /**
2057          * If we tried to perform a core update, check if we should send an email,
2058          * and if we need to avoid processing future updates.
2059          *
2060          * @param object $update_result The result of the core update. Includes the update offer and result.
2061          */
2062         protected function after_core_update( $update_result ) {
2063                 global $wp_version;
2064
2065                 $core_update = $update_result->item;
2066                 $result      = $update_result->result;
2067
2068                 if ( ! is_wp_error( $result ) ) {
2069                         $this->send_email( 'success', $core_update );
2070                         return;
2071                 }
2072
2073                 $error_code = $result->get_error_code();
2074
2075                 // Any of these WP_Error codes are critical failures, as in they occurred after we started to copy core files.
2076                 // We should not try to perform a background update again until there is a successful one-click update performed by the user.
2077                 $critical = false;
2078                 if ( $error_code === 'disk_full' || false !== strpos( $error_code, '__copy_dir' ) ) {
2079                         $critical = true;
2080                 } elseif ( $error_code === 'rollback_was_required' && is_wp_error( $result->get_error_data()->rollback ) ) {
2081                         // A rollback is only critical if it failed too.
2082                         $critical = true;
2083                         $rollback_result = $result->get_error_data()->rollback;
2084                 } elseif ( false !== strpos( $error_code, 'do_rollback' ) ) {
2085                         $critical = true;
2086                 }
2087
2088                 if ( $critical ) {
2089                         $critical_data = array(
2090                                 'attempted'  => $core_update->current,
2091                                 'current'    => $wp_version,
2092                                 'error_code' => $error_code,
2093                                 'error_data' => $result->get_error_data(),
2094                                 'timestamp'  => time(),
2095                                 'critical'   => true,
2096                         );
2097                         if ( isset( $rollback_result ) ) {
2098                                 $critical_data['rollback_code'] = $rollback_result->get_error_code();
2099                                 $critical_data['rollback_data'] = $rollback_result->get_error_data();
2100                         }
2101                         update_site_option( 'auto_core_update_failed', $critical_data );
2102                         $this->send_email( 'critical', $core_update, $result );
2103                         return;
2104                 }
2105
2106                 /*
2107                  * Any other WP_Error code (like download_failed or files_not_writable) occurs before
2108                  * we tried to copy over core files. Thus, the failures are early and graceful.
2109                  *
2110                  * We should avoid trying to perform a background update again for the same version.
2111                  * But we can try again if another version is released.
2112                  *
2113                  * For certain 'transient' failures, like download_failed, we should allow retries.
2114                  * In fact, let's schedule a special update for an hour from now. (It's possible
2115                  * the issue could actually be on WordPress.org's side.) If that one fails, then email.
2116                  */
2117                 $send = true;
2118                 $transient_failures = array( 'incompatible_archive', 'download_failed', 'insane_distro' );
2119                 if ( in_array( $error_code, $transient_failures ) && ! get_site_option( 'auto_core_update_failed' ) ) {
2120                         wp_schedule_single_event( time() + HOUR_IN_SECONDS, 'wp_maybe_auto_update' );
2121                         $send = false;
2122                 }
2123
2124                 $n = get_site_option( 'auto_core_update_notified' );
2125                 // Don't notify if we've already notified the same email address of the same version of the same notification type.
2126                 if ( $n && 'fail' == $n['type'] && $n['email'] == get_site_option( 'admin_email' ) && $n['version'] == $core_update->current )
2127                         $send = false;
2128
2129                 update_site_option( 'auto_core_update_failed', array(
2130                         'attempted'  => $core_update->current,
2131                         'current'    => $wp_version,
2132                         'error_code' => $error_code,
2133                         'error_data' => $result->get_error_data(),
2134                         'timestamp'  => time(),
2135                         'retry'      => in_array( $error_code, $transient_failures ),
2136                 ) );
2137
2138                 if ( $send )
2139                         $this->send_email( 'fail', $core_update, $result );
2140         }
2141
2142         /**
2143          * Sends an email upon the completion or failure of a background core update.
2144          *
2145          * @since 3.7.0
2146          *
2147          * @param string $type        The type of email to send. Can be one of 'success', 'fail', 'manual', 'critical'.
2148          * @param object $core_update The update offer that was attempted.
2149          * @param mixed  $result      Optional. The result for the core update. Can be WP_Error.
2150          */
2151         protected function send_email( $type, $core_update, $result = null ) {
2152                 update_site_option( 'auto_core_update_notified', array(
2153                         'type'      => $type,
2154                         'email'     => get_site_option( 'admin_email' ),
2155                         'version'   => $core_update->current,
2156                         'timestamp' => time(),
2157                 ) );
2158
2159                 $next_user_core_update = get_preferred_from_update_core();
2160                 // If the update transient is empty, use the update we just performed
2161                 if ( ! $next_user_core_update )
2162                         $next_user_core_update = $core_update;
2163                 $newer_version_available = ( 'upgrade' == $next_user_core_update->response && version_compare( $next_user_core_update->version, $core_update->version, '>' ) );
2164
2165                 /**
2166                  * Filter whether to send an email following an automatic background core update.
2167                  *
2168                  * @since 3.7.0
2169                  *
2170                  * @param bool   $send        Whether to send the email. Default true.
2171                  * @param string $type        The type of email to send. Can be one of 'success', 'fail', 'critical'.
2172                  * @param object $core_update The update offer that was attempted.
2173                  * @param mixed  $result      The result for the core update. Can be WP_Error.
2174                  */
2175                 if ( 'manual' !== $type && ! apply_filters( 'auto_core_update_send_email', true, $type, $core_update, $result ) )
2176                         return;
2177
2178                 switch ( $type ) {
2179                         case 'success' : // We updated.
2180                                 /* translators: 1: Site name, 2: WordPress version number. */
2181                                 $subject = __( '[%1$s] Your site has updated to WordPress %2$s' );
2182                                 break;
2183
2184                         case 'fail' :   // We tried to update but couldn't.
2185                         case 'manual' : // We can't update (and made no attempt).
2186                                 /* translators: 1: Site name, 2: WordPress version number. */
2187                                 $subject = __( '[%1$s] WordPress %2$s is available. Please update!' );
2188                                 break;
2189
2190                         case 'critical' : // We tried to update, started to copy files, then things went wrong.
2191                                 /* translators: 1: Site name. */
2192                                 $subject = __( '[%1$s] URGENT: Your site may be down due to a failed update' );
2193                                 break;
2194
2195                         default :
2196                                 return;
2197                 }
2198
2199                 // If the auto update is not to the latest version, say that the current version of WP is available instead.
2200                 $version = 'success' === $type ? $core_update->current : $next_user_core_update->current;
2201                 $subject = sprintf( $subject, wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), $version );
2202
2203                 $body = '';
2204
2205                 switch ( $type ) {
2206                         case 'success' :
2207                                 $body .= sprintf( __( 'Howdy! Your site at %1$s has been updated automatically to WordPress %2$s.' ), home_url(), $core_update->current );
2208                                 $body .= "\n\n";
2209                                 if ( ! $newer_version_available )
2210                                         $body .= __( 'No further action is needed on your part.' ) . ' ';
2211
2212                                 // Can only reference the About screen if their update was successful.
2213                                 list( $about_version ) = explode( '-', $core_update->current, 2 );
2214                                 $body .= sprintf( __( "For more on version %s, see the About WordPress screen:" ), $about_version );
2215                                 $body .= "\n" . admin_url( 'about.php' );
2216
2217                                 if ( $newer_version_available ) {
2218                                         $body .= "\n\n" . sprintf( __( 'WordPress %s is also now available.' ), $next_user_core_update->current ) . ' ';
2219                                         $body .= __( 'Updating is easy and only takes a few moments:' );
2220                                         $body .= "\n" . network_admin_url( 'update-core.php' );
2221                                 }
2222
2223                                 break;
2224
2225                         case 'fail' :
2226                         case 'manual' :
2227                                 $body .= sprintf( __( 'Please update your site at %1$s to WordPress %2$s.' ), home_url(), $next_user_core_update->current );
2228
2229                                 $body .= "\n\n";
2230
2231                                 // Don't show this message if there is a newer version available.
2232                                 // Potential for confusion, and also not useful for them to know at this point.
2233                                 if ( 'fail' == $type && ! $newer_version_available )
2234                                         $body .= __( 'We tried but were unable to update your site automatically.' ) . ' ';
2235
2236                                 $body .= __( 'Updating is easy and only takes a few moments:' );
2237                                 $body .= "\n" . network_admin_url( 'update-core.php' );
2238                                 break;
2239
2240                         case 'critical' :
2241                                 if ( $newer_version_available )
2242                                         $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 );
2243                                 else
2244                                         $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 );
2245
2246                                 $body .= "\n\n" . __( "This means your site may be offline or broken. Don't panic; this can be fixed." );
2247
2248                                 $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:" );
2249                                 $body .= "\n" . network_admin_url( 'update-core.php' );
2250                                 break;
2251                 }
2252
2253                 // Updates are important!
2254                 if ( $type != 'success' || $newer_version_available )
2255                         $body .= "\n\n" . __( 'Keeping your site updated is important for security. It also makes the internet a safer place for you and your readers.' );
2256
2257                 // Add a note about the support forums to all emails.
2258                 $body .= "\n\n" . __( 'If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.' );
2259                 $body .= "\n" . __( 'http://wordpress.org/support/' );
2260
2261                 // If things are successful and we're now on the latest, mention plugins and themes if any are out of date.
2262                 if ( $type == 'success' && ! $newer_version_available && ( get_plugin_updates() || get_theme_updates() ) ) {
2263                         $body .= "\n\n" . __( 'You also have some plugins or themes with updates available. Update them now:' );
2264                         $body .= "\n" . network_admin_url();
2265                 }
2266
2267                 $body .= "\n\n" . __( 'The WordPress Team' ) . "\n";
2268
2269                 if ( 'critical' == $type && is_wp_error( $result ) ) {
2270                         $body .= "\n***\n\n";
2271                         $body .= sprintf( __( 'Your site was running version %s.' ), $GLOBALS['wp_version'] );
2272                         $body .= ' ' . __( 'We have some data that describes the error your site encountered.' );
2273                         $body .= ' ' . __( 'Your hosting company, support forum volunteers, or a friendly developer may be able to use this information to help you:' );
2274
2275                         // If we had a rollback and we're still critical, then the rollback failed too.
2276                         // Loop through all errors (the main WP_Error, the update result, the rollback result) for code, data, etc.
2277                         if ( 'rollback_was_required' == $result->get_error_code() )
2278                                 $errors = array( $result, $result->get_error_data()->update, $result->get_error_data()->rollback );
2279                         else
2280                                 $errors = array( $result );
2281
2282                         foreach ( $errors as $error ) {
2283                                 if ( ! is_wp_error( $error ) )
2284                                         continue;
2285                                 $error_code = $error->get_error_code();
2286                                 $body .= "\n\n" . sprintf( __( "Error code: %s" ), $error_code );
2287                                 if ( 'rollback_was_required' == $error_code )
2288                                         continue;
2289                                 if ( $error->get_error_message() )
2290                                         $body .= "\n" . $error->get_error_message();
2291                                 $error_data = $error->get_error_data();
2292                                 if ( $error_data )
2293                                         $body .= "\n" . implode( ', ', (array) $error_data );
2294                         }
2295                         $body .= "\n";
2296                 }
2297
2298                 $to  = get_site_option( 'admin_email' );
2299                 $headers = '';
2300
2301                 $email = compact( 'to', 'subject', 'body', 'headers' );
2302                 /**
2303                  * Filter the email sent following an automatic background core update.
2304                  *
2305                  * @since 3.7.0
2306                  *
2307                  * @param array $email {
2308                  *     Array of email arguments that will be passed to wp_mail().
2309                  *
2310                  *     @type string $to      The email recipient. An array of emails can be returned, as handled by wp_mail().
2311                  *     @type string $subject The email's subject.
2312                  *     @type string $body    The email message body.
2313                  *     @type string $headers Any email headers, defaults to no headers.
2314                  * }
2315                  * @param string $type        The type of email being sent. Can be one of 'success', 'fail', 'manual', 'critical'.
2316                  * @param object $core_update The update offer that was attempted.
2317                  * @param mixed  $result      The result for the core update. Can be WP_Error.
2318                  */
2319                 $email = apply_filters( 'auto_core_update_email', $email, $type, $core_update, $result );
2320
2321                 wp_mail( $email['to'], $email['subject'], $email['body'], $email['headers'] );
2322         }
2323
2324         /**
2325          * Prepares and sends an email of a full log of background update results, useful for debugging and geekery.
2326          *
2327          * @since 3.7.0
2328          */
2329         protected function send_debug_email() {
2330                 $update_count = 0;
2331                 foreach ( $this->update_results as $type => $updates )
2332                         $update_count += count( $updates );
2333
2334                 $body = array();
2335                 $failures = 0;
2336
2337                 $body[] = 'WordPress site: ' . network_home_url( '/' );
2338
2339                 // Core
2340                 if ( isset( $this->update_results['core'] ) ) {
2341                         $result = $this->update_results['core'][0];
2342                         if ( $result->result && ! is_wp_error( $result->result ) ) {
2343                                 $body[] = sprintf( 'SUCCESS: WordPress was successfully updated to %s', $result->name );
2344                         } else {
2345                                 $body[] = sprintf( 'FAILED: WordPress failed to update to %s', $result->name );
2346                                 $failures++;
2347                         }
2348                         $body[] = '';
2349                 }
2350
2351                 // Plugins, Themes, Translations
2352                 foreach ( array( 'plugin', 'theme', 'translation' ) as $type ) {
2353                         if ( ! isset( $this->update_results[ $type ] ) )
2354                                 continue;
2355                         $success_items = wp_list_filter( $this->update_results[ $type ], array( 'result' => true ) );
2356                         if ( $success_items ) {
2357                                 $body[] = "The following {$type}s were successfully updated:";
2358                                 foreach ( wp_list_pluck( $success_items, 'name' ) as $name )
2359                                         $body[] = ' * SUCCESS: ' . $name;
2360                         }
2361                         if ( $success_items != $this->update_results[ $type ] ) {
2362                                 // Failed updates
2363                                 $body[] = "The following {$type}s failed to update:";
2364                                 foreach ( $this->update_results[ $type ] as $item ) {
2365                                         if ( ! $item->result || is_wp_error( $item->result ) ) {
2366                                                 $body[] = ' * FAILED: ' . $item->name;
2367                                                 $failures++;
2368                                         }
2369                                 }
2370                         }
2371                         $body[] = '';
2372                 }
2373
2374                 if ( $failures ) {
2375                         $body[] = '';
2376                         $body[] = 'BETA TESTING?';
2377                         $body[] = '=============';
2378                         $body[] = '';
2379                         $body[] = 'This debugging email is sent when you are using a development version of WordPress.';
2380                         $body[] = '';
2381                         $body[] = 'If you think these failures might be due to a bug in WordPress, could you report it?';
2382                         $body[] = ' * Open a thread in the support forums: http://wordpress.org/support/forum/alphabeta';
2383                         $body[] = " * Or, if you're comfortable writing a bug report: http://core.trac.wordpress.org/";
2384                         $body[] = '';
2385                         $body[] = 'Thanks! -- The WordPress Team';
2386                         $body[] = '';
2387                         $subject = sprintf( '[%s] There were failures during background updates', get_bloginfo( 'name' ) );
2388                 } else {
2389                         $subject = sprintf( '[%s] Background updates have finished', get_bloginfo( 'name' ) );
2390                 }
2391
2392                 $body[] = 'UPDATE LOG';
2393                 $body[] = '==========';
2394                 $body[] = '';
2395
2396                 foreach ( array( 'core', 'plugin', 'theme', 'translation' ) as $type ) {
2397                         if ( ! isset( $this->update_results[ $type ] ) )
2398                                 continue;
2399                         foreach ( $this->update_results[ $type ] as $update ) {
2400                                 $body[] = $update->name;
2401                                 $body[] = str_repeat( '-', strlen( $update->name ) );
2402                                 foreach ( $update->messages as $message )
2403                                         $body[] = "  " . html_entity_decode( str_replace( '&#8230;', '...', $message ) );
2404                                 if ( is_wp_error( $update->result ) ) {
2405                                         $results = array( 'update' => $update->result );
2406                                         // If we rolled back, we want to know an error that occurred then too.
2407                                         if ( 'rollback_was_required' === $update->result->get_error_code() )
2408                                                 $results = (array) $update->result->get_error_data();
2409                                         foreach ( $results as $result_type => $result ) {
2410                                                 if ( ! is_wp_error( $result ) )
2411                                                         continue;
2412                                                 $body[] = '  ' . ( 'rollback' === $result_type ? 'Rollback ' : '' ) . 'Error: [' . $result->get_error_code() . '] ' . $result->get_error_message();
2413                                                 if ( $result->get_error_data() )
2414                                                         $body[] = '         ' . implode( ', ', (array) $result->get_error_data() );
2415                                         }
2416                                 }
2417                                 $body[] = '';
2418                         }
2419                 }
2420
2421                 //echo "<h1>\n$subject\n</h1>\n";
2422                 //echo "<pre>\n" . implode( "\n", $body ) . "\n</pre>";
2423
2424                 wp_mail( get_site_option( 'admin_email' ), $subject, implode( "\n", $body ) );
2425         }
2426 }