summaryrefslogtreecommitdiff
blob: eee90f0cf57482a02ed3884b5fd0b10966abd474 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
<?php

  /*
   * Crontab-syntax support
   * Single elements : * 12 
   * Multiple elements : 1,2,3 4,6,1
   * Ranged elements: 1-4 9-12
   * Steped ranges : 1-16/2 *\/2 
   *
   * Not supported
   * Compound elements : 1,4,9-14 2,4-29,31 3,9-15,29
   */

class CronException extends Exception {
     // Redefine the exception so message isn't optional
     public function __construct($message, $code = 0) {
	  
	  // make sure everything is assigned properly
	  parent::__construct($message, $code);
     }
     
     // custom string representation of object
     public function __toString() {
	  return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
     }
  }

class Debug {
     private $debugLevel;
     private $debugMessage = "";
     private $functionScope = "main";

     public function __construct($debugLevel = 0) {
	  if ($debugLevel <= 0) {
	       $this->debugLevel = 0;
	  }
	  else if ($debugLevel >= 2) {
	       $this->debugLevel = 2;
	  }
	  else
	       $this->debugLevel = 1;
     }

     public function addDebugMessage($message, $function = "") {
	  // If we change of scope we need to record the new scope
	  if ($function != "") 
	       $this->functionScope = $function;
	  // What level of debugging are we in?
	  if ($this->debugLevel == 0)
	       return;
	  if ($this->debugLevel >= 2) {
	       print $this->functionScope;
	       print "------------";
	       if (is_string($message)) 
		    print $message;
	       else
		    echo var_dump($message);
	       print "------------";
	  }

	  $this->debugMessage .= "\n". $this->functionScope . ": ";
	  if (is_array($message)) {
	       ob_start();var_dump($message);$output=ob_get_contents();ob_end_clean();
	       $this->debugMessage .= $output;
	  } else
	       $this->debugMessage .= $message;
     }
     
     public function __toString() {
	  echo $this->debugMessage;
     }
}

class CronParser {
     private $input;
     private $elements = array();
     private $isValid = true;
     private $_elementsRanges;
     private $_elementPattern;
     private $_elementRangePattern;
     private $_elementRangeStepPattern;
     private $_now;
     public $debug;     

     function __construct($str, $debug = 1) {
	  $this->_initialize();
	  $this->debug = new Debug($debug);
	  $this->input = $str;
	  $this->_preprocessInput();
     }
     
     /*! Initialize some variables
      */
     private function _initialize() {
	  $this->isValid = false;
	  $this->_elementsRanges = array (
	       "minutes" => array (
		    "min" => 0,
		    "max" => 59),
	       "hours" => array (
		    "min" => 0,
		    "max" => 23),
	       "days" => array (
		    "min" => 1,
		    "max" => 31),
	       "months" => array (
		    "min" => 1,
		    "max" => 12),
	       "weekdays" => array(
		    "min" => 0,
		    "max" => 6));
	  // This patter may add experimental support to compound elements
	  //$this->_elementPattern = "/^\d+((\d+)?(,\d)?(\-\d+($|\/\d+$)?)?)+$/";
	  $this->_elementPattern = "/^\d+(,\d+)*$/";
	  $this->_elementRangeStepPattern = "/^(\*|\d+-\d+)\/\d+$/";
	  $this->_elementRangePattern = "/^\d+-\d+$/";
     }

     /*! Preprocess the input so it can be used
      *
      * This preprocessing involves: triming, eliminating useless
      * blank spaces between elements of the entry, validation,
      * ranges expansion, step calculation.
      */
     private function _preprocessInput() {
	  $this->debug->addDebugMessage("Entering function", "preprocessInput");

	  // Trim extra space from the beginning and end of $input
	  $tmp = trim($this->input);
	  $output= "";
	  $this->debug->addDebugMessage("Finished triming : " . $tmp);

	  // Eliminate extra spaces inside $input
	  $jump = false;
	  for ($i=0; $i<strlen($tmp); $i++) {
	       if ($tmp[$i] != ' ') {
		    $output = $output . $tmp[$i];
		    $jump = false;
	       }
	       else
		    if (!$jump) {
			 $output = $output . $tmp[$i];
			 $jump = true;
		    }
	  }
	  $this->debug->addDebugMessage("Cleaning finished : " . $output);

	  // Split $input into its elements
	  $tmp = explode(" ", $output);
	  if (count($tmp) != 5) 
	       throw new CronException("Wrong number of parameters." . $output);
	  $this->elements = array ( "minutes" => $tmp[0],
				    "hours" => $tmp[1],
				    "days" => $tmp[2],
				    "months" => $tmp[3],
				    "weekdays" => $tmp[4]);
	  $this->debug->addDebugMessage("Input splitted : ");
	  $this->debug->addDebugMessage($this->elements);

	  // Validate input and expand values
	  foreach (array("minutes", "hours", "days", "months", "weekdays") as $elementName) { 
	       $currentElement =& $this->elements[$elementName];
	       $currentRange =& $this->_elementsRanges[$elementName];
	       // It is the whole range?
	       if ($currentElement == "*") 
	       {
		    // Days calculation is different
		    if (in_array($elementName, array("days", "weekdays"))) 
			 continue;
		    
		    $currentElement = range($currentRange["min"],
					    $currentRange["max"]);
	       }
	       // It is a range with a step?
	       else if (preg_match($this->_elementRangeStepPattern, $currentElement)) {
		    $pieces = explode("/", $currentElement);
		    // if an asterix range
		    if ($pieces[0] == "*") {
			 $totalRange = range($currentRange["min"],
					     $currentRange["max"]);
		    } 
		    // it *has* to be an numeric range
		    else {
			 $atoms = explode("-", $pieces[0]);
			 $atoms[0] = (int)$atoms[0];
			 $atoms[1] = (int)$atoms[1];
			 if ($atoms[0] > $atoms[1] ||
			     $atoms[0] < $currentRange["min"] || $atoms[0] > $currentRange["max"] ||
			     $atoms[1] < $currentRange["min"] || $atoms[1] > $currentRange["max"]) {
			      throw new CronException("Bad formatted entry(range): " . $currentElement);
			 }
			 $totalRange = range($atoms[0], $atoms[1]);
		    }
		    $sol = array();
		    // now use the step to filter the range
		    foreach (range(0,count($totalRange),(int)$pieces[1]) as $i) { 
			 if (isset($totalRange[$i]))			      
			      $sol[] = $totalRange[$i];		    
		    }		    
		    $currentElement = $sol;
	       }
	       // it is a range withouth step
	       else if (preg_match($this->_elementRangePattern, $currentElement)) {
		    $atoms = explode("-", $currentElement);
		    $atoms[0] = (int)$atoms[0];
		    $atoms[1] = (int)$atoms[1];
		    if ($atoms[0] > $atoms[1] ||
			$atoms[0] < $currentRange["min"] || $atoms[0] > $currentRange["max"] ||
			$atoms[1] < $currentRange["min"] || $atoms[1] > $currentRange["max"]) {
			 throw new CronException("Bad formatted entry(range): " . $currentElement);
		    }
		    $currentElement = range($atoms[0], $atoms[1]);
	       }
	       // It is an element
	       else if (preg_match($this->_elementPattern, $currentElement)){
		    $sol = array();
 		    if (preg_match("/^\d+$/", $currentElement)) {
			 if ((int)$currentElement > $currentRange["max"] || (int)$currentElement < $currentRange["min"]){
			      throw new CronException("Parameter out of range: " . $atom . " of " . $this->input);
			 }
			 $currentElement = array((int)$currentElement);
 		    }
		    else {
			 foreach (explode(",",$currentElement) as $atom) {
			      if ((int)$atom > $currentRange["max"] || (int)$atom < $currentRange["min"]){
				   throw new CronException("Parameter out of range: " . $atom . " of " . $this->input);
			      }
			      $sol[] = (int)$atom;
			 }
			 $currentElement = $sol;
		    }
	       }
	       else {
		    throw new CronException("Bad formatted entry (element): " . $currentElement);
	       }
	  }
	  $this->isValid = true;
     }

     /*! Defines the $now of the class
      *
      * The only pourpuse of this function is to let the user define
      * what time should the class take as reference to calculate Next
      * and Prev
      */
     public function setNow(&$now) {
	  $this->_now = explode(",", $now);
     }

     /*! Returns the reference NOW time
      *
      * This function returns the reference NOW that is used by the
      * class to make its computations. If the var is not set by the
      * getNow method, it return time() properly formatted;
      */
     public function getNow() {
	  if (isset($this->_now)) {
	       return $this->_now;
	  }
	  else {
	       $t = strftime("%M,%H,%d,%m,%w,%Y", time()); //Get the values for now in a format we can use
	       return  explode(",", $t); //Make this an array
	  }
     }

     
     private function getWeekDays($month, $year){
	  $ret = array();
	  echo"gettingWeekdays: all days";
	  $days = range($this->_elementsRanges["days"]["min"],
			$this->daysInMonth($month, $year));		
	  var_dump($days);
	  foreach ($days as $day){
	       if (in_array(jddayofweek(gregoriantojd($month, $day, $year),0), $this->elements["weekdays"])){
			 $ret[] = $day;
	       }
	  }
	  echo "sol:";
	  var_dump($ret);
	  return $ret;		
     }

     /*! Computes the last day of a Month
      *
      * Given a month and a year, this function calculates the last
      * day of the month. It supports leap years (february 29)
      */
     private function daysInMonth($month, $year){
	  if(checkdate($month, 31, $year)) return 31;
	  if(checkdate($month, 30, $year)) return 30;
	  if(checkdate($month, 29, $year)) return 29;
	  if(checkdate($month, 28, $year)) return 28;
	  return 0; // error
     }	

     /*! Computes the Days of a Month
      *
      * Given a month, it calculates the days that fulfill the
      * requirements of the cron string
      */
     private function getDaysArray($month, $year = 0) {
	  $now = $this->getNow();
	  if ($year == 0) {
	       $year = $now[5];
	  }
//	  $this->debug("Getting days for $month");
	  $days = array();
   		
	  if (is_array($this->elements["weekdays"])) {
	       $days = $this->getWeekDays($month, $year);
//	       $this->debug("Weekdays:");
//	       $this->debug($days);
	       if (is_array($this->elements["days"])) {
		    $days += $this->elements["days"];
	       }
	  }
	  else {
	       if (is_array($this->elements["days"]))
		    $days = $this->elements["days"];
	       else
		    $days = range($this->_elementsRanges["days"]["min"],
				  $this->daysInMonth($month, $year));
	  }
//	  $this->debug($days);
	  return $days;
     }

     /*! Retrieves the next element of the array
      *
      * Given an array and an element, it calculates the next element
      * of the array and returns it, false otherwise
      */
     private function getNextArray($arr, $current) {
	  if (is_array($arr)) {
	       foreach ($arr as $v) { 
		    if ($v >= $current)
			 return $v;
	       }
	  }
	  return false;
     }

     /*! Retrieves the next element of the array
      *
      * Given an array and an element, it calculates the previous element
      * of the array and returns it, false otherwise
      */
     private function getPrevArray($arr, $current) {
	  if (is_array($arr)) {
	       foreach ($arr as $v) { 
		    if ($v <= $current)
			 return $v;
	       }
	  }
	  return false;
     }

     private function getNextMonth(&$sol){
	  //month
	  $tmp = $this->getNextArray($this->elements["months"], $sol["month"]);
	  echo "next month: " ;
	  echo var_dump($tmp);
	  if ($tmp === false) {
	       $days = $this->getDaysArray($this->elements["months"][0], $sol["year"]+1);
	       return array($this->elements["minutes"][0],
			    $this->elements["hours"][0],
			    $days[0],
			    $this->elements["months"][0],
			    $sol["year"]+1);
	  }
	  else if ($tmp != $sol["month"]) {
	       $days = $this->getDaysArray($tmp, $sol["year"]);
	       return array($this->elements["minutes"][0],
			    $this->elements["hours"][0],
			    $days[0],
			    $tmp,
			    $sol["year"]);
	  }
	  $sol["month"] = $tmp;
	  return $this->getNextDay($sol);
     }

     private function getNextDay(&$sol) {
	  $tmp = $this->getNextArray($this->getDaysArray($sol["month"], $year), $sol["day"]);
	  echo "next day:";
	  echo var_dump($tmp);
	  if ($tmp === false) {
	       $sol["month"] += 1;
	       $sol["day"] = $this->_elementsRanges["days"]["min"];
	       return $this->getNextMonth($sol);
	  }
	  else if ($tmp != $sol["day"]) {
	       return array($this->elements["minutes"][0],
			    $this->elements["hours"][0],
			    $tmp,
			    $sol["month"],
			    $sol["year"]);
	  }
	  $sol["day"] = $tmp;
	  return $this->getNextHour($sol);

     }

     private function getNextHour(&$sol) {
	  $tmp = $this->getNextArray($this->elements["hours"], $sol["hour"]);
	  echo "next hour:";
	  echo var_dump($tmp);
	  if ($tmp === false) {
	       $sol["day"] += 1;
	       $sol["hour"] = $this->_elementsRanges["hours"]["min"];
	       return $this->getNextDay($sol);
	  }
	  else if ($tmp != $sol["hour"]) {
	       return array($this->elements["minutes"][0],
			    $tmp,
			    $sol["day"],
			    $sol["month"],
			    $sol["year"]);
	  }
	  $sol["hour"] = $tmp;
	  return $this->getNextMinute($sol);
     }

     private function getNextMinute(&$sol) {
	  $tmp = $this->getNextArray($this->elements["minutes"], $sol["minute"]);
	  echo "next minute:";
	  echo var_dump($tmp);
	  if ($tmp === false) {
	       $sol["hour"] += 1;
	       $sol["minute"] = $this->_elementsRanges["minutes"]["min"];
	       return $this->getNextHour($sol);
	  }
	  return array($tmp,
		       $sol["hour"],
		       $sol["day"],
		       $sol["month"],
		       $sol["year"]);
     }

     public function calculateNextRun() {
	  if (!$this->isValid) {
	       throw new CronException("Invalid input");
	  }
	  $tmp = $this->getNow();
	  $sol = array (
	       "minute" => $tmp[0],
	       "hour" => $tmp[1],
	       "day" => $tmp[2],
	       "month" => $tmp[3],
	       "weekday" => $tmp[4],
	       "year" => $tmp[5]);
	  echo "now :";
	  echo var_dump($sol);
	  return $this->getNextMonth($sol);

     }
     
     public function calculatePrevRun() {
	  if (!$this->isValid) {
	       throw new CronException("Invalid input");
	  }
     }


}

?>