Scheduler.php 9.6 KB

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