Scheduler.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. <?php
  2. namespace YahnisElsts\PluginUpdateChecker\v5p1;
  3. if ( !class_exists(Scheduler::class, false) ):
  4. /**
  5. * The scheduler decides when and how often to check for updates.
  6. * It calls @see UpdateChecker::checkForUpdates() to perform the actual checks.
  7. */
  8. class Scheduler {
  9. public $checkPeriod = 12; //How often to check for updates (in hours).
  10. public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
  11. public $throttledCheckPeriod = 72;
  12. protected $hourlyCheckHooks = array('load-update.php');
  13. /**
  14. * @var UpdateChecker
  15. */
  16. protected $updateChecker;
  17. private $cronHook = null;
  18. /**
  19. * Scheduler constructor.
  20. *
  21. * @param UpdateChecker $updateChecker
  22. * @param int $checkPeriod How often to check for updates (in hours).
  23. * @param array $hourlyHooks
  24. */
  25. public function __construct($updateChecker, $checkPeriod, $hourlyHooks = array('load-plugins.php')) {
  26. $this->updateChecker = $updateChecker;
  27. $this->checkPeriod = $checkPeriod;
  28. //Set up the periodic update checks
  29. $this->cronHook = $this->updateChecker->getUniqueName('cron_check_updates');
  30. if ( $this->checkPeriod > 0 ){
  31. //Trigger the check via Cron.
  32. //Try to use one of the default schedules if possible as it's less likely to conflict
  33. //with other plugins and their custom schedules.
  34. $defaultSchedules = array(
  35. 1 => 'hourly',
  36. 12 => 'twicedaily',
  37. 24 => 'daily',
  38. );
  39. if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) {
  40. $scheduleName = $defaultSchedules[$this->checkPeriod];
  41. } else {
  42. //Use a custom cron schedule.
  43. $scheduleName = 'every' . $this->checkPeriod . 'hours';
  44. //phpcs:ignore WordPress.WP.CronInterval.ChangeDetected -- WPCS fails to parse the callback.
  45. add_filter('cron_schedules', array($this, '_addCustomSchedule'));
  46. }
  47. if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
  48. //Randomly offset the schedule to help prevent update server traffic spikes. Without this
  49. //most checks may happen during times of day when people are most likely to install new plugins.
  50. $upperLimit = max($this->checkPeriod * 3600 - 15 * 60, 1);
  51. if ( function_exists('wp_rand') ) {
  52. $randomOffset = wp_rand(0, $upperLimit);
  53. } else {
  54. //This constructor may be called before wp_rand() is available.
  55. //phpcs:ignore WordPress.WP.AlternativeFunctions.rand_rand
  56. $randomOffset = rand(0, $upperLimit);
  57. }
  58. $firstCheckTime = time() - $randomOffset;
  59. $firstCheckTime = apply_filters(
  60. $this->updateChecker->getUniqueName('first_check_time'),
  61. $firstCheckTime
  62. );
  63. wp_schedule_event($firstCheckTime, $scheduleName, $this->cronHook);
  64. }
  65. add_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
  66. //In case Cron is disabled or unreliable, we also manually trigger
  67. //the periodic checks while the user is browsing the Dashboard.
  68. add_action( 'admin_init', array($this, 'maybeCheckForUpdates') );
  69. //Like WordPress itself, we check more often on certain pages.
  70. /** @see wp_update_plugins */
  71. add_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
  72. //phpcs:ignore Squiz.PHP.CommentedOutCode.Found -- Not actually code, just file names.
  73. //"load-update.php" and "load-plugins.php" or "load-themes.php".
  74. $this->hourlyCheckHooks = array_merge($this->hourlyCheckHooks, $hourlyHooks);
  75. foreach($this->hourlyCheckHooks as $hook) {
  76. add_action($hook, array($this, 'maybeCheckForUpdates'));
  77. }
  78. //This hook fires after a bulk update is complete.
  79. add_action('upgrader_process_complete', array($this, 'removeHooksIfLibraryGone'), 1, 0);
  80. add_action('upgrader_process_complete', array($this, 'upgraderProcessComplete'), 11, 2);
  81. } else {
  82. //Periodic checks are disabled.
  83. wp_clear_scheduled_hook($this->cronHook);
  84. }
  85. }
  86. /**
  87. * Remove all hooks if this version of PUC has been deleted or overwritten.
  88. *
  89. * Callback for the "upgrader_process_complete" action.
  90. */
  91. public function removeHooksIfLibraryGone() {
  92. //Cancel all further actions if the current version of PUC has been deleted or overwritten
  93. //by a different version during the upgrade. If we try to do anything more in that situation,
  94. //we could trigger a fatal error by trying to autoload a deleted class.
  95. clearstatcache();
  96. if ( !file_exists(__FILE__) ) {
  97. $this->removeHooks();
  98. $this->updateChecker->removeHooks();
  99. }
  100. }
  101. /**
  102. * Runs upon the WP action upgrader_process_complete.
  103. *
  104. * We look at the parameters to decide whether to call maybeCheckForUpdates() or not.
  105. * We also check if the update checker has been removed by the update.
  106. *
  107. * @param \WP_Upgrader $upgrader WP_Upgrader instance
  108. * @param array $upgradeInfo extra information about the upgrade
  109. */
  110. public function upgraderProcessComplete(
  111. /** @noinspection PhpUnusedParameterInspection */
  112. $upgrader, $upgradeInfo
  113. ) {
  114. //Sanity check and limitation to relevant types.
  115. if (
  116. !is_array($upgradeInfo) || !isset($upgradeInfo['type'], $upgradeInfo['action'])
  117. || 'update' !== $upgradeInfo['action'] || !in_array($upgradeInfo['type'], array('plugin', 'theme'))
  118. ) {
  119. return;
  120. }
  121. //Filter out notifications of upgrades that should have no bearing upon whether or not our
  122. //current info is up-to-date.
  123. if ( is_a($this->updateChecker, Theme\UpdateChecker::class) ) {
  124. if ( 'theme' !== $upgradeInfo['type'] || !isset($upgradeInfo['themes']) ) {
  125. return;
  126. }
  127. //Letting too many things going through for checks is not a real problem, so we compare widely.
  128. if ( !in_array(
  129. strtolower($this->updateChecker->directoryName),
  130. array_map('strtolower', $upgradeInfo['themes'])
  131. ) ) {
  132. return;
  133. }
  134. }
  135. if ( is_a($this->updateChecker, Plugin\UpdateChecker::class) ) {
  136. if ( 'plugin' !== $upgradeInfo['type'] || !isset($upgradeInfo['plugins']) ) {
  137. return;
  138. }
  139. //Themes pass in directory names in the information array, but plugins use the relative plugin path.
  140. if ( !in_array(
  141. strtolower($this->updateChecker->directoryName),
  142. array_map('dirname', array_map('strtolower', $upgradeInfo['plugins']))
  143. ) ) {
  144. return;
  145. }
  146. }
  147. $this->maybeCheckForUpdates();
  148. }
  149. /**
  150. * Check for updates if the configured check interval has already elapsed.
  151. * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
  152. *
  153. * You can override the default behaviour by using the "puc_check_now-$slug" filter.
  154. * The filter callback will be passed three parameters:
  155. * - Current decision. TRUE = check updates now, FALSE = don't check now.
  156. * - Last check time as a Unix timestamp.
  157. * - Configured check period in hours.
  158. * Return TRUE to check for updates immediately, or FALSE to cancel.
  159. *
  160. * This method is declared public because it's a hook callback. Calling it directly is not recommended.
  161. */
  162. public function maybeCheckForUpdates() {
  163. if ( empty($this->checkPeriod) ){
  164. return;
  165. }
  166. $state = $this->updateChecker->getUpdateState();
  167. $shouldCheck = ($state->timeSinceLastCheck() >= $this->getEffectiveCheckPeriod());
  168. if ( $shouldCheck ) {
  169. //Sanity check: Do not proceed if one of the critical classes is missing.
  170. //That can happen - theoretically and extremely rarely - if maybeCheckForUpdates()
  171. //is called before the old version of our plugin has been fully deleted, or
  172. //called from an independent AJAX request during deletion.
  173. if ( !(
  174. class_exists(Utils::class)
  175. && class_exists(Metadata::class)
  176. && class_exists(Plugin\Update::class)
  177. && class_exists(Theme\Update::class)
  178. ) ) {
  179. return;
  180. }
  181. }
  182. //Let plugin authors substitute their own algorithm.
  183. $shouldCheck = apply_filters(
  184. $this->updateChecker->getUniqueName('check_now'),
  185. $shouldCheck,
  186. $state->getLastCheck(),
  187. $this->checkPeriod
  188. );
  189. if ( $shouldCheck ) {
  190. $this->updateChecker->checkForUpdates();
  191. }
  192. }
  193. /**
  194. * Calculate the actual check period based on the current status and environment.
  195. *
  196. * @return int Check period in seconds.
  197. */
  198. protected function getEffectiveCheckPeriod() {
  199. $currentFilter = current_filter();
  200. if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) {
  201. //Check more often when the user visits "Dashboard -> Updates" or does a bulk update.
  202. $period = 60;
  203. } else if ( in_array($currentFilter, $this->hourlyCheckHooks) ) {
  204. //Also check more often on /wp-admin/update.php and the "Plugins" or "Themes" page.
  205. $period = 3600;
  206. } else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) {
  207. //Check less frequently if it's already known that an update is available.
  208. $period = $this->throttledCheckPeriod * 3600;
  209. } else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
  210. //WordPress cron schedules are not exact, so lets do an update check even
  211. //if slightly less than $checkPeriod hours have elapsed since the last check.
  212. $cronFuzziness = 20 * 60;
  213. $period = $this->checkPeriod * 3600 - $cronFuzziness;
  214. } else {
  215. $period = $this->checkPeriod * 3600;
  216. }
  217. return $period;
  218. }
  219. /**
  220. * Add our custom schedule to the array of Cron schedules used by WP.
  221. *
  222. * @param array $schedules
  223. * @return array
  224. */
  225. public function _addCustomSchedule($schedules) {
  226. if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
  227. $scheduleName = 'every' . $this->checkPeriod . 'hours';
  228. $schedules[$scheduleName] = array(
  229. 'interval' => $this->checkPeriod * 3600,
  230. 'display' => sprintf('Every %d hours', $this->checkPeriod),
  231. );
  232. }
  233. return $schedules;
  234. }
  235. /**
  236. * Remove the scheduled cron event that the library uses to check for updates.
  237. *
  238. * @return void
  239. */
  240. public function removeUpdaterCron() {
  241. wp_clear_scheduled_hook($this->cronHook);
  242. }
  243. /**
  244. * Get the name of the update checker's WP-cron hook. Mostly useful for debugging.
  245. *
  246. * @return string
  247. */
  248. public function getCronHookName() {
  249. return $this->cronHook;
  250. }
  251. /**
  252. * Remove most hooks added by the scheduler.
  253. */
  254. public function removeHooks() {
  255. remove_filter('cron_schedules', array($this, '_addCustomSchedule'));
  256. remove_action('admin_init', array($this, 'maybeCheckForUpdates'));
  257. remove_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
  258. if ( $this->cronHook !== null ) {
  259. remove_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
  260. }
  261. if ( !empty($this->hourlyCheckHooks) ) {
  262. foreach ($this->hourlyCheckHooks as $hook) {
  263. remove_action($hook, array($this, 'maybeCheckForUpdates'));
  264. }
  265. }
  266. }
  267. }
  268. endif;