forked from Ben0it-T/timetracker
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclass.tdcron.php
More file actions
441 lines (294 loc) · 12 KB
/
class.tdcron.php
File metadata and controls
441 lines (294 loc) · 12 KB
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
<?php
define('IDX_MINUTE', 0);
define('IDX_HOUR', 1);
define('IDX_DAY', 2);
define('IDX_MONTH', 3);
define('IDX_WEEKDAY', 4);
define('IDX_YEAR', 5);
/*
* tdCron v0.0.1 beta - CRON-Parser for PHP
*
* Copyright (c) 2010 Christian Land / tagdocs.de
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @author Christian Land <devel@tagdocs.de>
* @package tdCron
* @copyright Copyright (c) 2010, Christian Land / tagdocs.de
* @version v0.0.1 beta
*/
class tdCron {
/**
* Parsed cron-expressions cache.
* @var mixed
*/
static private $pcron = array();
/**
* getNextOccurrence() uses a cron-expression to calculate the time and date at which a cronjob
* should be executed the next time. If a reference-time is passed, the next time and date
* after that time is calculated.
*
* @access public
* @param string $expression cron-expression to use
* @param int $timestamp optional reference-time
* @return int
*/
static public function getNextOccurrence($expression, $timestamp = null) {
try {
// Convert timestamp to array
$next = self::getTimestamp($timestamp);
// Calculate date/time
$next_time = self::calculateDateTime($expression, $next);
} catch (Exception $e) {
throw $e;
}
// return calculated time
return $next_time;
}
/**
* getLastOccurrence() does pretty much the same as getNextOccurrence(). The only difference
* is, that it doesn't calculate the next but the last time a cronjob should have been executed.
*
* @access public
* @param string $expression cron-expression to use
* @param int $timestamp optional reference-time
* @return int
*/
static public function getLastOccurrence($expression, $timestamp = null) {
try {
// Convert timestamp to array
$last = self::getTimestamp($timestamp);
// Calculate date/time
$last_time = self::calculateDateTime($expression, $last, false);
} catch (Exception $e) {
throw $e;
}
// return calculated time
return $last_time;
}
/**
* calculateDateTime() is the function where all the magic happens :-)
*
* It calculates the time and date at which the next/last call of a cronjob is/was due.
*
* @access private
* @param mixed $value cron-expression
* @param mixed $rtime reference-time
* @param bool $next true = nextOccurence, false = lastOccurence
* @return int
*/
static private function calculateDateTime($expression, $rtime, $next = true) {
// Initialize vars
$calc_date = true;
// Parse cron-expression (if neccessary)
$cron = self::getExpression($expression, !$next);
// OK, lets see if the day/month/weekday of the reference-date exist in our
// $cron-array.
if (!in_array($rtime[IDX_DAY], $cron[IDX_DAY]) ||
!in_array($rtime[IDX_MONTH], $cron[IDX_MONTH]) ||
!in_array($rtime[IDX_WEEKDAY], $cron[IDX_WEEKDAY])) {
// OK, things are easy. The day/month/weekday of the reference time
// can't be found in the $cron-array. This means that no matter what
// happens, we WILL end up at at a different date than that of our
// reference-time. And in this case, the lastOccurrence will ALWAYS
// happen at the latest possible time of the day and the nextOccurrence
// at the earliest possible time.
//
// In both cases, the time can be found in the first elements of the
// hour/minute cron-arrays.
$rtime[IDX_HOUR] = reset($cron[IDX_HOUR]);
$rtime[IDX_MINUTE] = reset($cron[IDX_MINUTE]);
} else {
// OK, things are getting a little bit more complicated...
$nhour = self::findValue($rtime[IDX_HOUR], $cron[IDX_HOUR], $next);
// Meh. Such a cruel world. Something has gone awry. Lets see HOW awry it went.
if ($nhour === false) { // Fix as per http://www.phpclasses.org/discuss/package/6699/thread/3/
// Ah, the hour-part went wrong. Thats easy. Wrong hour means that no
// matter what we do we'll end up at a different date. Thus we can use
// some simple operations to make things look pretty ;-)
//
// As alreasy mentioned before -> different date means earliest/latest
// time:
$rtime[IDX_HOUR] = reset($cron[IDX_HOUR]);
$rtime[IDX_MINUTE] = reset($cron[IDX_MINUTE]);
// Now all we have to do is add/subtract a day to get a new reference time
// to use later to find the right date. The following line probably looks
// a little odd but thats the easiest way of adding/substracting a day without
// screwing up the date. Just trust me on that one ;-)
$rtime = explode(',', date("i,H,d,m,w,Y", mktime($rtime[IDX_HOUR], $rtime[IDX_MINUTE], 0, $rtime[IDX_MONTH], $rtime[IDX_DAY], $rtime[IDX_YEAR]) + ((($next) ? 1 : -1) * 86400)));
} else {
// OK, there is a higher/lower hour available. Check the minutes-part.
$nminute = self::findValue($rtime[IDX_MINUTE], $cron[IDX_MINUTE], $next);
if ($nminute === false) {
// No matching minute-value found... lets see what happens if we substract/add an hour
$nhour = self::findValue($rtime[IDX_HOUR] + (($next) ? 1 : -1), $cron[IDX_HOUR], $next);
if ($nhour === false) {
// No more hours available... add/substract a day... you know what happens ;-)
$nminute = reset($cron[IDX_MINUTE]);
$nhour = reset($cron[IDX_HOUR]);
$rtime = explode(',', date("i,H,d,m,w,Y", mktime($nhour, $nminute, 0, $rtime[IDX_MONTH], $rtime[IDX_DAY], $rtime[IDX_YEAR]) + ((($next) ? 1 : -1) * 86400)));
} else {
// OK, there was another hour. Set the right minutes-value
$rtime[IDX_HOUR] = $nhour;
$rtime[IDX_MINUTE] = (($next) ? reset($cron[IDX_MINUTE]) : end($cron[IDX_MINUTE]));
$calc_date = false;
}
} else {
// OK, there is a matching minute... reset minutes if hour has changed
if ($nhour <> $rtime[IDX_HOUR]) {
$nminute = reset($cron[IDX_MINUTE]);
}
// Set time
$rtime[IDX_HOUR] = $nhour;
$rtime[IDX_MINUTE] = $nminute;
$calc_date = false;
}
}
}
// If we have to calculate the date... we'll do so
if ($calc_date) {
if (in_array($rtime[IDX_DAY], $cron[IDX_DAY]) &&
in_array($rtime[IDX_MONTH], $cron[IDX_MONTH]) &&
in_array($rtime[IDX_WEEKDAY], $cron[IDX_WEEKDAY])) {
return mktime($rtime[1], $rtime[0], 0, $rtime[3], $rtime[2], $rtime[5]);
} else {
// OK, some searching necessary...
$cdate = mktime(0, 0, 0, $rtime[IDX_MONTH], $rtime[IDX_DAY], $rtime[IDX_YEAR]);
// OK, these three nested loops are responsible for finding the date...
//
// The class has 2 limitations/bugs right now:
//
// -> it doesn't work for dates in 2036 or later!
// -> it will most likely fail if you search for a Feburary, 29th with a given weekday
// (this does happen because the class only searches in the next/last 10 years! And
// while it usually takes less than 10 years for a "normal" date to iterate through
// all weekdays, it can take 20+ years for Feb, 29th to iterate through all weekdays!
for ($nyear = $rtime[IDX_YEAR];(($next) ? ($nyear <= $rtime[IDX_YEAR] + 10) : ($nyear >= $rtime[IDX_YEAR] -10));$nyear = $nyear + (($next) ? 1 : -1)) {
foreach ($cron[IDX_MONTH] as $nmonth) {
foreach ($cron[IDX_DAY] as $nday) {
if (checkdate($nmonth,$nday,$nyear)) {
$ndate = mktime(0,0,1,$nmonth,$nday,$nyear);
if (($next) ? ($ndate >= $cdate) : ($ndate <= $cdate)) {
$dow = date('w',$ndate);
// The date is "OK" - lets see if the weekday matches, too...
if (in_array($dow,$cron[IDX_WEEKDAY])) {
// WIN! :-) We found a valid date...
$rtime = explode(',', date("i,H,d,m,w,Y", mktime($rtime[IDX_HOUR], $rtime[IDX_MINUTE], 0, $nmonth, $nday, $nyear)));
return mktime($rtime[1], $rtime[0], 0, $rtime[3], $rtime[2], $rtime[5]);
}
}
}
}
}
}
}
throw new Exception('Failed to find date, No matching date found in a 10 years range!', 10004);
}
return mktime($rtime[1], $rtime[0], 0, $rtime[3], $rtime[2], $rtime[5]);
}
/**
* getTimestamp() converts an unix-timestamp to an array. The returned array contains the following values:
*
* [0] -> minute
* [1] -> hour
* [2] -> day
* [3] -> month
* [4] -> weekday
* [5] -> year
*
* The array is used by various functions.
*
* @access private
* @param int $timestamp If none is given, the current time is used
* @return mixed
*/
static private function getTimestamp($timestamp = null) {
if (is_null($timestamp)) {
$arr = explode(',', date("i,H,d,m,w,Y", time()));
} else {
$arr = explode(',', date("i,H,d,m,w,Y", $timestamp));
}
// Remove leading zeros (or we'll get in trouble ;-)
foreach ($arr as $key=>$value) {
$arr[$key] = (int)ltrim($value,'0');
}
return $arr;
}
/**
* findValue() checks if the given value exists in an array. If it does not exist, the next
* higher/lower value is returned (depending on $next). If no higher/lower value exists,
* false is returned.
*
* @access public
* @param int $value
* @param mixed $data
* @param bool $next
* @return mixed
*/
static private function findValue($value, $data, $next = true) {
if (in_array($value, $data)) {
return (int)$value;
} else {
if (($next) ? ($value <= end($data)) : ($value >= end($data))) {
foreach ($data as $curval) {
if (($next) ? ($value <= (int)$curval) : ($curval <= $value)) {
return (int)$curval;
}
}
}
}
return false;
}
/**
* getExpression() returns a parsed cron-expression. Parsed cron-expressions are cached to reduce
* unneccessary calls of the parser.
*
* @access public
* @param string $value
* @param bool $reverse
* @return mixed
*/
static private function getExpression($expression, $reverse=false) {
// First of all we cleanup the expression and remove all duplicate tabs/spaces/etc.
// For example "* * * * *" would be converted to "* * * * *", etc.
$expression = preg_replace('/(\s+)/', ' ', strtolower(trim($expression)));
// Lets see if we've already parsed that expression
if (!isset(self::$pcron[$expression])) {
// Nope - parse it!
try {
self::$pcron[$expression] = tdCronEntry::parse($expression);
self::$pcron['reverse'][$expression] = self::arrayReverse(self::$pcron[$expression]);
} catch (Exception $e) {
throw $e;
}
}
return ($reverse ? self::$pcron['reverse'][$expression] : self::$pcron[$expression]);
}
/**
* arrayReverse() reverses all sub-arrays of our cron array. The reversed values are used for calculations
* that are run when getLastOccurence() is called.
*
* @access public
* @param mixed $cron
* @return mixed
*/
static private function arrayReverse($cron) {
foreach ($cron as $key=>$value) {
$cron[$key] = array_reverse($value);
}
return $cron;
}
}