Cron.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. <?php
  2. /**
  3. * @package Grav\Common\Scheduler
  4. * @author Originally based on jqCron by Arnaud Buathier <arnaud@arnapou.net> modified for Grav integration
  5. * @copyright Copyright (c) 2015 - 2023 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Scheduler;
  9. /*
  10. * Usage examples :
  11. * ----------------
  12. *
  13. * $cron = new Cron('10-30/5 12 * * *');
  14. *
  15. * var_dump($cron->getMinutes());
  16. * // array(5) {
  17. * // [0]=> int(10)
  18. * // [1]=> int(15)
  19. * // [2]=> int(20)
  20. * // [3]=> int(25)
  21. * // [4]=> int(30)
  22. * // }
  23. *
  24. * var_dump($cron->getText('fr'));
  25. * // string(32) "Chaque jour à 12:10,15,20,25,30"
  26. *
  27. * var_dump($cron->getText('en'));
  28. * // string(30) "Every day at 12:10,15,20,25,30"
  29. *
  30. * var_dump($cron->getType());
  31. * // string(3) "day"
  32. *
  33. * var_dump($cron->getCronHours());
  34. * // string(2) "12"
  35. *
  36. * var_dump($cron->matchExact(new \DateTime('2012-07-01 13:25:10')));
  37. * // bool(false)
  38. *
  39. * var_dump($cron->matchExact(new \DateTime('2012-07-01 12:15:20')));
  40. * // bool(true)
  41. *
  42. * var_dump($cron->matchWithMargin(new \DateTime('2012-07-01 12:32:50'), -3, 5));
  43. * // bool(true)
  44. */
  45. use DateInterval;
  46. use DateTime;
  47. use RuntimeException;
  48. use function count;
  49. use function in_array;
  50. use function is_array;
  51. use function is_string;
  52. class Cron
  53. {
  54. public const TYPE_UNDEFINED = '';
  55. public const TYPE_MINUTE = 'minute';
  56. public const TYPE_HOUR = 'hour';
  57. public const TYPE_DAY = 'day';
  58. public const TYPE_WEEK = 'week';
  59. public const TYPE_MONTH = 'month';
  60. public const TYPE_YEAR = 'year';
  61. /**
  62. *
  63. * @var array
  64. */
  65. protected $texts = [
  66. 'fr' => [
  67. 'empty' => '-tout-',
  68. 'name_minute' => 'minute',
  69. 'name_hour' => 'heure',
  70. 'name_day' => 'jour',
  71. 'name_week' => 'semaine',
  72. 'name_month' => 'mois',
  73. 'name_year' => 'année',
  74. 'text_period' => 'Chaque %s',
  75. 'text_mins' => 'à %s minutes',
  76. 'text_time' => 'à %02s:%02s',
  77. 'text_dow' => 'le %s',
  78. 'text_month' => 'de %s',
  79. 'text_dom' => 'le %s',
  80. 'weekdays' => ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche'],
  81. 'months' => ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
  82. ],
  83. 'en' => [
  84. 'empty' => '-all-',
  85. 'name_minute' => 'minute',
  86. 'name_hour' => 'hour',
  87. 'name_day' => 'day',
  88. 'name_week' => 'week',
  89. 'name_month' => 'month',
  90. 'name_year' => 'year',
  91. 'text_period' => 'Every %s',
  92. 'text_mins' => 'at %s minutes past the hour',
  93. 'text_time' => 'at %02s:%02s',
  94. 'text_dow' => 'on %s',
  95. 'text_month' => 'of %s',
  96. 'text_dom' => 'on the %s',
  97. 'weekdays' => ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'],
  98. 'months' => ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'],
  99. ],
  100. ];
  101. /**
  102. * min hour dom month dow
  103. * @var string
  104. */
  105. protected $cron = '';
  106. /**
  107. *
  108. * @var array
  109. */
  110. protected $minutes = [];
  111. /**
  112. *
  113. * @var array
  114. */
  115. protected $hours = [];
  116. /**
  117. *
  118. * @var array
  119. */
  120. protected $months = [];
  121. /**
  122. * 0-7 : sunday, monday, ... saturday, sunday
  123. * @var array
  124. */
  125. protected $dow = [];
  126. /**
  127. *
  128. * @var array
  129. */
  130. protected $dom = [];
  131. /**
  132. * @param string|null $cron
  133. */
  134. public function __construct($cron = null)
  135. {
  136. if (null !== $cron) {
  137. $this->setCron($cron);
  138. }
  139. }
  140. /**
  141. * @return string
  142. */
  143. public function getCron()
  144. {
  145. return implode(' ', [
  146. $this->getCronMinutes(),
  147. $this->getCronHours(),
  148. $this->getCronDaysOfMonth(),
  149. $this->getCronMonths(),
  150. $this->getCronDaysOfWeek(),
  151. ]);
  152. }
  153. /**
  154. * @param string $lang 'fr' or 'en'
  155. * @return string
  156. */
  157. public function getText($lang)
  158. {
  159. // check lang
  160. if (!isset($this->texts[$lang])) {
  161. return $this->getCron();
  162. }
  163. $texts = $this->texts[$lang];
  164. // check type
  165. $type = $this->getType();
  166. if ($type === self::TYPE_UNDEFINED) {
  167. return $this->getCron();
  168. }
  169. // init
  170. $elements = [];
  171. $elements[] = sprintf($texts['text_period'], $texts['name_' . $type]);
  172. // hour
  173. if ($type === self::TYPE_HOUR) {
  174. $elements[] = sprintf($texts['text_mins'], $this->getCronMinutes());
  175. }
  176. // week
  177. if ($type === self::TYPE_WEEK) {
  178. $dow = $this->getCronDaysOfWeek();
  179. foreach ($texts['weekdays'] as $i => $wd) {
  180. $dow = str_replace((string) ($i + 1), $wd, $dow);
  181. }
  182. $elements[] = sprintf($texts['text_dow'], $dow);
  183. }
  184. // month + year
  185. if (in_array($type, [self::TYPE_MONTH, self::TYPE_YEAR], true)) {
  186. $elements[] = sprintf($texts['text_dom'], $this->getCronDaysOfMonth());
  187. }
  188. // year
  189. if ($type === self::TYPE_YEAR) {
  190. $months = $this->getCronMonths();
  191. for ($i = count($texts['months']) - 1; $i >= 0; $i--) {
  192. $months = str_replace((string) ($i + 1), $texts['months'][$i], $months);
  193. }
  194. $elements[] = sprintf($texts['text_month'], $months);
  195. }
  196. // day + week + month + year
  197. if (in_array($type, [self::TYPE_DAY, self::TYPE_WEEK, self::TYPE_MONTH, self::TYPE_YEAR], true)) {
  198. $elements[] = sprintf($texts['text_time'], $this->getCronHours(), $this->getCronMinutes());
  199. }
  200. return str_replace('*', $texts['empty'], implode(' ', $elements));
  201. }
  202. /**
  203. * @return string
  204. */
  205. public function getType()
  206. {
  207. $mask = preg_replace('/[^\* ]/', '-', $this->getCron());
  208. $mask = preg_replace('/-+/', '-', $mask);
  209. $mask = preg_replace('/[^-\*]/', '', $mask);
  210. if ($mask === '*****') {
  211. return self::TYPE_MINUTE;
  212. }
  213. if ($mask === '-****') {
  214. return self::TYPE_HOUR;
  215. }
  216. if (substr($mask, -3) === '***') {
  217. return self::TYPE_DAY;
  218. }
  219. if (substr($mask, -3) === '-**') {
  220. return self::TYPE_MONTH;
  221. }
  222. if (substr($mask, -3) === '**-') {
  223. return self::TYPE_WEEK;
  224. }
  225. if (substr($mask, -2) === '-*') {
  226. return self::TYPE_YEAR;
  227. }
  228. return self::TYPE_UNDEFINED;
  229. }
  230. /**
  231. * @param string $cron
  232. * @return $this
  233. */
  234. public function setCron($cron)
  235. {
  236. // sanitize
  237. $cron = trim($cron);
  238. $cron = preg_replace('/\s+/', ' ', $cron);
  239. // explode
  240. $elements = explode(' ', $cron);
  241. if (count($elements) !== 5) {
  242. throw new RuntimeException('Bad number of elements');
  243. }
  244. $this->cron = $cron;
  245. $this->setMinutes($elements[0]);
  246. $this->setHours($elements[1]);
  247. $this->setDaysOfMonth($elements[2]);
  248. $this->setMonths($elements[3]);
  249. $this->setDaysOfWeek($elements[4]);
  250. return $this;
  251. }
  252. /**
  253. * @return string
  254. */
  255. public function getCronMinutes()
  256. {
  257. return $this->arrayToCron($this->minutes);
  258. }
  259. /**
  260. * @return string
  261. */
  262. public function getCronHours()
  263. {
  264. return $this->arrayToCron($this->hours);
  265. }
  266. /**
  267. * @return string
  268. */
  269. public function getCronDaysOfMonth()
  270. {
  271. return $this->arrayToCron($this->dom);
  272. }
  273. /**
  274. * @return string
  275. */
  276. public function getCronMonths()
  277. {
  278. return $this->arrayToCron($this->months);
  279. }
  280. /**
  281. * @return string
  282. */
  283. public function getCronDaysOfWeek()
  284. {
  285. return $this->arrayToCron($this->dow);
  286. }
  287. /**
  288. * @return array
  289. */
  290. public function getMinutes()
  291. {
  292. return $this->minutes;
  293. }
  294. /**
  295. * @return array
  296. */
  297. public function getHours()
  298. {
  299. return $this->hours;
  300. }
  301. /**
  302. * @return array
  303. */
  304. public function getDaysOfMonth()
  305. {
  306. return $this->dom;
  307. }
  308. /**
  309. * @return array
  310. */
  311. public function getMonths()
  312. {
  313. return $this->months;
  314. }
  315. /**
  316. * @return array
  317. */
  318. public function getDaysOfWeek()
  319. {
  320. return $this->dow;
  321. }
  322. /**
  323. * @param string|string[] $minutes
  324. * @return $this
  325. */
  326. public function setMinutes($minutes)
  327. {
  328. $this->minutes = $this->cronToArray($minutes, 0, 59);
  329. return $this;
  330. }
  331. /**
  332. * @param string|string[] $hours
  333. * @return $this
  334. */
  335. public function setHours($hours)
  336. {
  337. $this->hours = $this->cronToArray($hours, 0, 23);
  338. return $this;
  339. }
  340. /**
  341. * @param string|string[] $months
  342. * @return $this
  343. */
  344. public function setMonths($months)
  345. {
  346. $this->months = $this->cronToArray($months, 1, 12);
  347. return $this;
  348. }
  349. /**
  350. * @param string|string[] $dow
  351. * @return $this
  352. */
  353. public function setDaysOfWeek($dow)
  354. {
  355. $this->dow = $this->cronToArray($dow, 0, 7);
  356. return $this;
  357. }
  358. /**
  359. * @param string|string[] $dom
  360. * @return $this
  361. */
  362. public function setDaysOfMonth($dom)
  363. {
  364. $this->dom = $this->cronToArray($dom, 1, 31);
  365. return $this;
  366. }
  367. /**
  368. * @param mixed $date
  369. * @param int $min
  370. * @param int $hour
  371. * @param int $day
  372. * @param int $month
  373. * @param int $weekday
  374. * @return DateTime
  375. */
  376. protected function parseDate($date, &$min, &$hour, &$day, &$month, &$weekday)
  377. {
  378. if (is_numeric($date) && (int)$date == $date) {
  379. $date = new DateTime('@' . $date);
  380. } elseif (is_string($date)) {
  381. $date = new DateTime('@' . strtotime($date));
  382. }
  383. if ($date instanceof DateTime) {
  384. $min = (int)$date->format('i');
  385. $hour = (int)$date->format('H');
  386. $day = (int)$date->format('d');
  387. $month = (int)$date->format('m');
  388. $weekday = (int)$date->format('w'); // 0-6
  389. } else {
  390. throw new RuntimeException('Date format not supported');
  391. }
  392. return new DateTime($date->format('Y-m-d H:i:sP'));
  393. }
  394. /**
  395. * @param int|string|DateTime $date
  396. */
  397. public function matchExact($date)
  398. {
  399. $date = $this->parseDate($date, $min, $hour, $day, $month, $weekday);
  400. return
  401. (empty($this->minutes) || in_array($min, $this->minutes, true)) &&
  402. (empty($this->hours) || in_array($hour, $this->hours, true)) &&
  403. (empty($this->dom) || in_array($day, $this->dom, true)) &&
  404. (empty($this->months) || in_array($month, $this->months, true)) &&
  405. (empty($this->dow) || in_array($weekday, $this->dow, true) || ($weekday == 0 && in_array(7, $this->dow, true)) || ($weekday == 7 && in_array(0, $this->dow, true))
  406. );
  407. }
  408. /**
  409. * @param int|string|DateTime $date
  410. * @param int $minuteBefore
  411. * @param int $minuteAfter
  412. */
  413. public function matchWithMargin($date, $minuteBefore = 0, $minuteAfter = 0)
  414. {
  415. if ($minuteBefore > 0) {
  416. throw new RuntimeException('MinuteBefore parameter cannot be positive !');
  417. }
  418. if ($minuteAfter < 0) {
  419. throw new RuntimeException('MinuteAfter parameter cannot be negative !');
  420. }
  421. $date = $this->parseDate($date, $min, $hour, $day, $month, $weekday);
  422. $interval = new DateInterval('PT1M'); // 1 min
  423. if ($minuteBefore !== 0) {
  424. $date->sub(new DateInterval('PT' . abs($minuteBefore) . 'M'));
  425. }
  426. $n = $minuteAfter - $minuteBefore + 1;
  427. for ($i = 0; $i < $n; $i++) {
  428. if ($this->matchExact($date)) {
  429. return true;
  430. }
  431. $date->add($interval);
  432. }
  433. return false;
  434. }
  435. /**
  436. * @param array $array
  437. * @return string
  438. */
  439. protected function arrayToCron($array)
  440. {
  441. $n = count($array);
  442. if (!is_array($array) || $n === 0) {
  443. return '*';
  444. }
  445. $cron = [$array[0]];
  446. $s = $c = $array[0];
  447. for ($i = 1; $i < $n; $i++) {
  448. if ($array[$i] == $c + 1) {
  449. $c = $array[$i];
  450. $cron[count($cron) - 1] = $s . '-' . $c;
  451. } else {
  452. $s = $c = $array[$i];
  453. $cron[] = $c;
  454. }
  455. }
  456. return implode(',', $cron);
  457. }
  458. /**
  459. *
  460. * @param array|string $string
  461. * @param int $min
  462. * @param int $max
  463. * @return array
  464. */
  465. protected function cronToArray($string, $min, $max)
  466. {
  467. $array = [];
  468. if (is_array($string)) {
  469. foreach ($string as $val) {
  470. if (is_numeric($val) && (int)$val == $val && $val >= $min && $val <= $max) {
  471. $array[] = (int)$val;
  472. }
  473. }
  474. } elseif ($string !== '*') {
  475. while ($string !== '') {
  476. // test "*/n" expression
  477. if (preg_match('/^\*\/([0-9]+),?/', $string, $m)) {
  478. for ($i = max(0, $min); $i <= min(59, $max); $i += $m[1]) {
  479. $array[] = (int)$i;
  480. }
  481. $string = substr($string, strlen($m[0]));
  482. continue;
  483. }
  484. // test "a-b/n" expression
  485. if (preg_match('/^([0-9]+)-([0-9]+)\/([0-9]+),?/', $string, $m)) {
  486. for ($i = max($m[1], $min); $i <= min($m[2], $max); $i += $m[3]) {
  487. $array[] = (int)$i;
  488. }
  489. $string = substr($string, strlen($m[0]));
  490. continue;
  491. }
  492. // test "a-b" expression
  493. if (preg_match('/^([0-9]+)-([0-9]+),?/', $string, $m)) {
  494. for ($i = max($m[1], $min); $i <= min($m[2], $max); $i++) {
  495. $array[] = (int)$i;
  496. }
  497. $string = substr($string, strlen($m[0]));
  498. continue;
  499. }
  500. // test "c" expression
  501. if (preg_match('/^([0-9]+),?/', $string, $m)) {
  502. if ($m[1] >= $min && $m[1] <= $max) {
  503. $array[] = (int)$m[1];
  504. }
  505. $string = substr($string, strlen($m[0]));
  506. continue;
  507. }
  508. // something goes wrong in the expression
  509. return [];
  510. }
  511. }
  512. sort($array, SORT_NUMERIC);
  513. return $array;
  514. }
  515. }