Cron.php 15 KB

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