JobSchedulerCronTab.inc 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. <?php
  2. /**
  3. * @file
  4. * JobSchedulerCronTab class.
  5. */
  6. /**
  7. * Jose's cron tab parser = Better try only simple crontab strings.
  8. *
  9. * Usage:
  10. * // Run 23 minutes after midn, 2am, 4am ..., everyday
  11. * $crontab = new JobSchedulerCronTab('23 0-23/2 * * *');
  12. * // When this needs to run next, from current time?
  13. * $next_time = $crontab->nextTime(time());
  14. *
  15. * I hate Sundays.
  16. */
  17. class JobSchedulerCronTab {
  18. // Original crontab elements
  19. public $crontab;
  20. // Parsed numeric values indexed by type
  21. public $cron;
  22. /**
  23. * Constructor
  24. *
  25. * About crontab strings, see all about possible formats
  26. * http://linux.die.net/man/5/crontab
  27. *
  28. * @param $crontab string
  29. * Crontab text line: minute hour day-of-month month day-of-week
  30. */
  31. public function __construct($crontab) {
  32. $this->crontab = $crontab;
  33. $this->cron = is_array($crontab) ? $this->values($crontab) : $this->parse($crontab);
  34. }
  35. /**
  36. * Parse full crontab string into an array of type => values
  37. *
  38. * Note this one is static and can be used to validate values
  39. */
  40. public static function parse($crontab) {
  41. // Crontab elements, names match PHP date indexes (getdate)
  42. $keys = array('minutes', 'hours', 'mday', 'mon', 'wday');
  43. // Replace multiple spaces by single space
  44. $crontab = preg_replace('/(\s+)/', ' ', $crontab);
  45. // Expand into elements and parse all
  46. $values = explode(' ', trim($crontab));
  47. return self::values($values);
  48. }
  49. /**
  50. * Parse array of values, check whether this is valid
  51. */
  52. public static function values($array) {
  53. if (count($array) == 5) {
  54. $values = array_combine(array('minutes', 'hours', 'mday', 'mon', 'wday'), array_map('trim', $array));
  55. $elements = array();
  56. foreach ($values as $type => $string) {
  57. $elements[$type] = self::parseElement($type, $string, TRUE);
  58. }
  59. // Return only if we have the right number of elements
  60. // Dangerous means works running every second or things like that.
  61. if (count(array_filter($elements)) == 5) {
  62. return $elements;
  63. }
  64. }
  65. return NULL;
  66. }
  67. /**
  68. * Find the next occurrence within the next year as unix timestamp
  69. *
  70. * @param $start_time timestamp
  71. * Starting time
  72. */
  73. public function nextTime($start_time = NULL, $limit = 366) {
  74. $start_time = isset($start_time) ? $start_time : time();
  75. $start_date = getdate($start_time); // Get minutes, hours, mday, wday, mon, year
  76. if ($date = $this->nextDate($start_date, $limit)) {
  77. return mktime($date['hours'], $date['minutes'], 0, $date['mon'], $date['mday'], $date['year']);
  78. }
  79. else {
  80. return 0;
  81. }
  82. }
  83. /**
  84. * Find the next occurrence within the next year as a date array,
  85. *
  86. * @see getdate()
  87. *
  88. * @param $date
  89. * Date array with: 'mday', 'mon', 'year', 'hours', 'minutes'
  90. */
  91. public function nextDate($date, $limit = 366) {
  92. $date['seconds'] = 0;
  93. // It is possible that the current date doesn't match
  94. if ($this->checkDay($date) && ($nextdate = $this->nextHour($date))) {
  95. return $nextdate;
  96. }
  97. elseif ($nextdate = $this->nextDay($date, $limit)) {
  98. return $nextdate;
  99. }
  100. else {
  101. return FALSE;
  102. }
  103. }
  104. /**
  105. * Check whether date's day is a valid one
  106. */
  107. protected function checkDay($date) {
  108. foreach (array('wday', 'mday', 'mon') as $key) {
  109. if (!in_array($date[$key], $this->cron[$key])) {
  110. return FALSE;
  111. }
  112. }
  113. return TRUE;
  114. }
  115. /**
  116. * Find the next day from date that matches with cron parameters
  117. *
  118. * Maybe it's possible that it's within the next years, maybe no day of a year matches all conditions.
  119. * However, to prevent infinite loops we restrict it to the next year.
  120. */
  121. protected function nextDay($date, $limit = 366) {
  122. $i = 0; // Safety check, we love infinite loops...
  123. while ($i++ <= $limit) {
  124. // This should fix values out of range, like month > 12, day > 31....
  125. // So we can trust we get the next valid day, can't we?
  126. $time = mktime(0, 0, 0, $date['mon'], $date['mday'] + 1, $date['year']);
  127. $date = getdate($time);
  128. if ($this->checkDay($date)) {
  129. $date['hours'] = reset($this->cron['hours']);
  130. $date['minutes'] = reset($this->cron['minutes']);
  131. return $date;
  132. }
  133. }
  134. }
  135. /**
  136. * Find the next available hour within the same day
  137. */
  138. protected function nextHour($date) {
  139. $cron = $this->cron;
  140. while ($cron['hours']) {
  141. $hour = array_shift($cron['hours']);
  142. // Current hour; next minute.
  143. if ($date['hours'] == $hour) {
  144. foreach ($cron['minutes'] as $minute) {
  145. if ($date['minutes'] < $minute) {
  146. $date['hours'] = $hour;
  147. $date['minutes'] = $minute;
  148. return $date;
  149. }
  150. }
  151. }
  152. // Next hour; first avaiable minute.
  153. elseif ($date['hours'] < $hour) {
  154. $date['hours'] = $hour;
  155. $date['minutes'] = reset($cron['minutes']);
  156. return $date;
  157. }
  158. }
  159. return FALSE;
  160. }
  161. /**
  162. * Parse each text element. Recursive up to some point...
  163. */
  164. protected static function parseElement($type, $string, $translate = FALSE) {
  165. $string = trim($string);
  166. if ($translate) {
  167. $string = self::translateNames($type, $string);
  168. }
  169. if ($string === '*') {
  170. // This means all possible values, return right away, no need to double check
  171. return self::possibleValues($type);
  172. }
  173. elseif (strpos($string, '/')) {
  174. // Multiple. Example */2, for weekday will expand into 2, 4, 6
  175. list($values, $multiple) = explode('/', $string);
  176. $values = self::parseElement($type, $values);
  177. foreach ($values as $value) {
  178. if (!($value % $multiple)) {
  179. $range[] = $value;
  180. }
  181. }
  182. }
  183. elseif (strpos($string, ',')) {
  184. // Now process list parts, expand into items, process each and merge back
  185. $list = explode(',', $string);
  186. $range = array();
  187. foreach ($list as $item) {
  188. if ($values = self::parseElement($type, $item)) {
  189. $range = array_merge($range, $values);
  190. }
  191. }
  192. }
  193. elseif (strpos($string, '-')) {
  194. // This defines a range. Example 1-3, will expand into 1,2,3
  195. list($start, $end) = explode('-', $string);
  196. // Double check the range is within possible values
  197. $range = range($start, $end);
  198. }
  199. elseif (is_numeric($string)) {
  200. // This looks like a single number, double check it's int
  201. $range = array((int)$string);
  202. }
  203. // Return unique sorted values and double check they're within possible values
  204. if (!empty($range)) {
  205. $range = array_intersect(array_unique($range), self::possibleValues($type));
  206. sort($range);
  207. // Sunday validation. We need cron values to match PHP values, thus week day 7 is not allowed, must be 0
  208. if ($type == 'wday' && in_array(7, $range)) {
  209. array_pop($range);
  210. array_unshift($range, 0);
  211. }
  212. return $range;
  213. }
  214. else {
  215. // No match found for this one, will produce an error with validation
  216. return array();
  217. }
  218. }
  219. /**
  220. * Get values for each type
  221. */
  222. public static function possibleValues($type) {
  223. switch ($type) {
  224. case 'minutes':
  225. return range(0, 59);
  226. case 'hours':
  227. return range(0, 23);
  228. case 'mday':
  229. return range(1, 31);
  230. case 'mon':
  231. return range(1, 12);
  232. case 'wday':
  233. // These are PHP values, not *nix ones
  234. return range(0, 6);
  235. }
  236. }
  237. /**
  238. * Replace element names by values
  239. */
  240. public static function translateNames($type, $string) {
  241. switch ($type) {
  242. case 'wday':
  243. $replace = array_merge(
  244. // Tricky, tricky, we need sunday to be zero at the beginning of a range, but 7 at the end
  245. array('-sunday' => '-7', '-sun' => '-7', 'sunday-' => '0-', 'sun-' => '0-'),
  246. array_flip(array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday')),
  247. array_flip(array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'))
  248. );
  249. break;
  250. case 'mon':
  251. $replace = array_merge(
  252. array_flip(array('nomonth1', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december')),
  253. array_flip(array('nomonth2', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')),
  254. array('sept' => 9)
  255. );
  256. break;
  257. }
  258. if (empty($replace)) {
  259. return $string;
  260. }
  261. else {
  262. return strtr($string, $replace);
  263. }
  264. }
  265. }