Scheduler.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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, 'upgraderProcessComplete'), 11, 2);
  80. } else {
  81. //Periodic checks are disabled.
  82. wp_clear_scheduled_hook($this->cronHook);
  83. }
  84. }
  85. /**
  86. * Runs upon the WP action upgrader_process_complete.
  87. *
  88. * We look at the parameters to decide whether to call maybeCheckForUpdates() or not.
  89. * We also check if the update checker has been removed by the update.
  90. *
  91. * @param \WP_Upgrader $upgrader WP_Upgrader instance
  92. * @param array $upgradeInfo extra information about the upgrade
  93. */
  94. public function upgraderProcessComplete(
  95. /** @noinspection PhpUnusedParameterInspection */
  96. $upgrader, $upgradeInfo
  97. ) {
  98. //Cancel all further actions if the current version of PUC has been deleted or overwritten
  99. //by a different version during the upgrade. If we try to do anything more in that situation,
  100. //we could trigger a fatal error by trying to autoload a deleted class.
  101. clearstatcache();
  102. if ( !file_exists(__FILE__) ) {
  103. $this->removeHooks();
  104. $this->updateChecker->removeHooks();
  105. return;
  106. }
  107. //Sanity check and limitation to relevant types.
  108. if (
  109. !is_array($upgradeInfo) || !isset($upgradeInfo['type'], $upgradeInfo['action'])
  110. || 'update' !== $upgradeInfo['action'] || !in_array($upgradeInfo['type'], array('plugin', 'theme'))
  111. ) {
  112. return;
  113. }
  114. //Filter out notifications of upgrades that should have no bearing upon whether or not our
  115. //current info is up-to-date.
  116. if ( is_a($this->updateChecker, Theme\UpdateChecker::class) ) {
  117. if ( 'theme' !== $upgradeInfo['type'] || !isset($upgradeInfo['themes']) ) {
  118. return;
  119. }
  120. //Letting too many things going through for checks is not a real problem, so we compare widely.
  121. if ( !in_array(
  122. strtolower($this->updateChecker->directoryName),
  123. array_map('strtolower', $upgradeInfo['themes'])
  124. ) ) {
  125. return;
  126. }
  127. }
  128. if ( is_a($this->updateChecker, Plugin\UpdateChecker::class) ) {
  129. if ( 'plugin' !== $upgradeInfo['type'] || !isset($upgradeInfo['plugins']) ) {
  130. return;
  131. }
  132. //Themes pass in directory names in the information array, but plugins use the relative plugin path.
  133. if ( !in_array(
  134. strtolower($this->updateChecker->directoryName),
  135. array_map('dirname', array_map('strtolower', $upgradeInfo['plugins']))
  136. ) ) {
  137. return;
  138. }
  139. }
  140. $this->maybeCheckForUpdates();
  141. }
  142. /**
  143. * Check for updates if the configured check interval has already elapsed.
  144. * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
  145. *
  146. * You can override the default behaviour by using the "puc_check_now-$slug" filter.
  147. * The filter callback will be passed three parameters:
  148. * - Current decision. TRUE = check updates now, FALSE = don't check now.
  149. * - Last check time as a Unix timestamp.
  150. * - Configured check period in hours.
  151. * Return TRUE to check for updates immediately, or FALSE to cancel.
  152. *
  153. * This method is declared public because it's a hook callback. Calling it directly is not recommended.
  154. */
  155. public function maybeCheckForUpdates() {
  156. if ( empty($this->checkPeriod) ){
  157. return;
  158. }
  159. $state = $this->updateChecker->getUpdateState();
  160. $shouldCheck = ($state->timeSinceLastCheck() >= $this->getEffectiveCheckPeriod());
  161. //Let plugin authors substitute their own algorithm.
  162. $shouldCheck = apply_filters(
  163. $this->updateChecker->getUniqueName('check_now'),
  164. $shouldCheck,
  165. $state->getLastCheck(),
  166. $this->checkPeriod
  167. );
  168. if ( $shouldCheck ) {
  169. $this->updateChecker->checkForUpdates();
  170. }
  171. }
  172. /**
  173. * Calculate the actual check period based on the current status and environment.
  174. *
  175. * @return int Check period in seconds.
  176. */
  177. protected function getEffectiveCheckPeriod() {
  178. $currentFilter = current_filter();
  179. if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) {
  180. //Check more often when the user visits "Dashboard -> Updates" or does a bulk update.
  181. $period = 60;
  182. } else if ( in_array($currentFilter, $this->hourlyCheckHooks) ) {
  183. //Also check more often on /wp-admin/update.php and the "Plugins" or "Themes" page.
  184. $period = 3600;
  185. } else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) {
  186. //Check less frequently if it's already known that an update is available.
  187. $period = $this->throttledCheckPeriod * 3600;
  188. } else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
  189. //WordPress cron schedules are not exact, so lets do an update check even
  190. //if slightly less than $checkPeriod hours have elapsed since the last check.
  191. $cronFuzziness = 20 * 60;
  192. $period = $this->checkPeriod * 3600 - $cronFuzziness;
  193. } else {
  194. $period = $this->checkPeriod * 3600;
  195. }
  196. return $period;
  197. }
  198. /**
  199. * Add our custom schedule to the array of Cron schedules used by WP.
  200. *
  201. * @param array $schedules
  202. * @return array
  203. */
  204. public function _addCustomSchedule($schedules) {
  205. if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
  206. $scheduleName = 'every' . $this->checkPeriod . 'hours';
  207. $schedules[$scheduleName] = array(
  208. 'interval' => $this->checkPeriod * 3600,
  209. 'display' => sprintf('Every %d hours', $this->checkPeriod),
  210. );
  211. }
  212. return $schedules;
  213. }
  214. /**
  215. * Remove the scheduled cron event that the library uses to check for updates.
  216. *
  217. * @return void
  218. */
  219. public function removeUpdaterCron() {
  220. wp_clear_scheduled_hook($this->cronHook);
  221. }
  222. /**
  223. * Get the name of the update checker's WP-cron hook. Mostly useful for debugging.
  224. *
  225. * @return string
  226. */
  227. public function getCronHookName() {
  228. return $this->cronHook;
  229. }
  230. /**
  231. * Remove most hooks added by the scheduler.
  232. */
  233. public function removeHooks() {
  234. remove_filter('cron_schedules', array($this, '_addCustomSchedule'));
  235. remove_action('admin_init', array($this, 'maybeCheckForUpdates'));
  236. remove_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
  237. if ( $this->cronHook !== null ) {
  238. remove_action($this->cronHook, array($this, 'maybeCheckForUpdates'));
  239. }
  240. if ( !empty($this->hourlyCheckHooks) ) {
  241. foreach ($this->hourlyCheckHooks as $hook) {
  242. remove_action($hook, array($this, 'maybeCheckForUpdates'));
  243. }
  244. }
  245. }
  246. }
  247. endif;