Guest User

Untitled

a guest
Mar 18th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. <?php
  2.  
  3. class CronExp {
  4. public function match($expression, $time = NULL){
  5. if(empty($time)){
  6. $time = time() - time() % 60; // rounded to current minute
  7. }elseif(is_string($time)){
  8. $time = strtotime($time);
  9. }
  10.  
  11. $tmp = self::replaceSpecialStrings($expression);
  12. if($tmp){
  13. $expression = $tmp;
  14. }
  15.  
  16. $cronpart = self::checkValid($expression);
  17. if(!$cronpart){
  18. return FALSE;
  19. }
  20.  
  21. $procs = [
  22. ['i', 0, 59],
  23. ['G', 0, 23],
  24. ['j', 0, 31],
  25. ['n', 1, 12],
  26. ['w', 0, 6]
  27. ];
  28.  
  29. foreach($cronpart as $i => $match){
  30. foreach(explode(",", $match) as $expr){
  31. if(!self::checkCronParam(
  32. $expr, $time,
  33. $procs[$i][0], $procs[$i][1], $procs[$i][2])
  34. ){
  35. return FALSE;
  36. }
  37. }
  38. }
  39. return TRUE;
  40. }
  41.  
  42. private function replaceSpecialStrings($expression){
  43. $strings = [
  44. 'yearly' => '0 0 1 1 *',
  45. 'annually' => '0 0 1 1 *',
  46. 'monthly' => '0 0 1 * *',
  47. 'weekly' => '0 0 * * 0',
  48. 'daily' => '0 0 * * *',
  49. 'midnight' => '0 0 * * *',
  50. 'hourly' => '0 * * * *'
  51. ];
  52.  
  53. $expression = str_replace("@", "", $expression);
  54. if(array_key_exists($expression, $strings)){
  55. return $strings[$expression];
  56. }
  57. return FALSE;
  58. }
  59.  
  60. public function checkValid($expression){
  61. $r = preg_match_all('/(([*\-\,\/\d]+)(\s+|$))/', $expression, $matches, PREG_PATTERN_ORDER);
  62. // If not 5 matches, not valid cron.
  63. if($r != 5){ return FALSE; }
  64. return $matches[2];
  65. }
  66.  
  67. private function checkCronParam($expr, $time, $datesel, $mmin, $mmax){
  68. $dmatch = (int) date($datesel, $time);
  69.  
  70. if(in_array($expr, ['*', '*/1'])){ return TRUE; }
  71. if(is_numeric($expr)){
  72. return ( (int) $expr == $dmatch );
  73. }
  74. if(preg_match('/^\*\/(\d{1,2})$/', $expr, $matches)){
  75. // Data 00 always match.
  76. if($dmatch === 0){ return TRUE; }
  77. return ($dmatch % (int) $matches[1] == 0);
  78. }elseif(preg_match('/^(\d{1,2})-(\d{1,2})$/', $expr, $matches)){
  79. $min = (int) $matches[1];
  80. $max = (int) $matches[2];
  81. // Not match if invalid.
  82. if(
  83. $min > $max or
  84. $min < $mmin or
  85. $max > $mmax
  86. ){ return FALSE; }
  87.  
  88. return ($dmatch >= $min and $dmatch <= $max);
  89. }
  90.  
  91. // Others or not meeting get FALSE.
  92. return FALSE;
  93. }
  94. }
  95.  
  96. ?>
Add Comment
Please, Sign In to add comment