PageRenderTime 58ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-admin/includes/class-wp-upgrader.php

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