Projet

Général

Profil

Paste
Télécharger (8,43 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / job_scheduler / JobSchedulerCronTab.inc @ 1f142f4f

1
<?php
2

    
3
/**
4
 * @file
5
 * JobSchedulerCronTab class.
6
 */
7

    
8
/**
9
 * Jose's cron tab parser = Better try only simple crontab strings.
10
 *
11
 * Usage:
12
 *   // Run 23 minutes after midn, 2am, 4am ..., everyday
13
 *   $crontab = new JobSchedulerCronTab('23 0-23/2 * * *');
14
 *   // When this needs to run next, from current time?
15
 *   $next_time = $crontab->nextTime(time());
16
 *
17
 * I hate Sundays.
18
 */
19
class JobSchedulerCronTab {
20
  // Original crontab elements
21
  public $crontab;
22
  // Parsed numeric values indexed by type
23
  public $cron;
24

    
25
  /**
26
   * Constructor
27
   *
28
   * About crontab strings, see all about possible formats
29
   * http://linux.die.net/man/5/crontab
30
   *
31
   * @param $crontab string
32
   *   Crontab text line: minute hour day-of-month month day-of-week
33
   */
34
  public function __construct($crontab) {
35
    $this->crontab = $crontab;
36
    $this->cron = is_array($crontab) ? $this->values($crontab) : $this->parse($crontab);
37
  }
38

    
39
  /**
40
   * Parse full crontab string into an array of type => values
41
   *
42
   * Note this one is static and can be used to validate values
43
   */
44
  public static function parse($crontab) {
45
    // Crontab elements, names match PHP date indexes (getdate)
46
    $keys = array('minutes', 'hours', 'mday', 'mon', 'wday');
47
    // Replace multiple spaces by single space
48
    $crontab = preg_replace('/(\s+)/', ' ', $crontab);
49
    // Expand into elements and parse all
50
    $values = explode(' ', trim($crontab));
51
    return self::values($values);
52
  }
53

    
54
  /**
55
   * Parse array of values, check whether this is valid
56
   */
57
  public static function values($array) {
58
    if (count($array) == 5) {
59
      $values = array_combine(array('minutes', 'hours', 'mday', 'mon', 'wday'), array_map('trim', $array));
60
      $elements = array();
61
      foreach ($values as $type => $string) {
62
        $elements[$type] = self::parseElement($type, $string, TRUE);
63
      }
64
      // Return only if we have the right number of elements
65
      // Dangerous means works running every second or things like that.
66
      if (count(array_filter($elements)) == 5) {
67
        return $elements;
68
      }
69
    }
70
    return NULL;
71
  }
72

    
73
  /**
74
   * Find the next occurrence within the next year as unix timestamp
75
   *
76
   * @param $start_time timestamp
77
   *   Starting time
78
   */
79
  public function nextTime($start_time = NULL, $limit = 366) {
80
    $start_time = isset($start_time) ? $start_time : time();
81
    $start_date = getdate($start_time); // Get minutes, hours, mday, wday, mon, year
82
    if ($date = $this->nextDate($start_date, $limit)) {
83
      return mktime($date['hours'], $date['minutes'], 0, $date['mon'], $date['mday'], $date['year']);
84
    }
85
    else {
86
      return 0;
87
    }
88
  }
89

    
90
  /**
91
   * Find the next occurrence within the next year as a date array,
92
   *
93
   * @see getdate()
94
   *
95
   * @param $date
96
   *   Date array with: 'mday', 'mon', 'year', 'hours', 'minutes'
97
   */
98
  public function nextDate($date, $limit = 366) {
99
    $date['seconds'] = 0;
100
    // It is possible that the current date doesn't match
101
    if ($this->checkDay($date) && ($nextdate = $this->nextHour($date))) {
102
      return $nextdate;
103
    }
104
    elseif ($nextdate = $this->nextDay($date, $limit)) {
105
      return $nextdate;
106
    }
107
    else {
108
      return FALSE;
109
    }
110
  }
111

    
112
  /**
113
   * Check whether date's day is a valid one
114
   */
115
  protected function checkDay($date) {
116
    foreach (array('wday', 'mday', 'mon') as $key) {
117
      if (!in_array($date[$key], $this->cron[$key])) {
118
        return FALSE;
119
      }
120
    }
121
    return TRUE;
122
  }
123

    
124
  /**
125
   * Find the next day from date that matches with cron parameters
126
   *
127
   * Maybe it's possible that it's within the next years, maybe no day of a year matches all conditions.
128
   * However, to prevent infinite loops we restrict it to the next year.
129
   */
130
  protected function nextDay($date, $limit = 366) {
131
    $i = 0; // Safety check, we love infinite loops...
132
    while ($i++ <= $limit) {
133
      // This should fix values out of range, like month > 12, day > 31....
134
      // So we can trust we get the next valid day, can't we?
135
      $time = mktime(0, 0, 0, $date['mon'], $date['mday'] + 1, $date['year']);
136
      $date = getdate($time);
137
      if ($this->checkDay($date)) {
138
        $date['hours'] = reset($this->cron['hours']);
139
        $date['minutes'] = reset($this->cron['minutes']);
140
        return $date;
141
      }
142
    }
143
  }
144
  /**
145
   * Find the next available hour within the same day
146
   */
147
  protected function nextHour($date) {
148
    $cron = $this->cron;
149
    while ($cron['hours']) {
150
      $hour = array_shift($cron['hours']);
151
      // Current hour; next minute.
152
      if ($date['hours'] == $hour) {
153
        foreach ($cron['minutes'] as $minute) {
154
          if ($date['minutes'] < $minute) {
155
            $date['hours'] = $hour;
156
            $date['minutes'] = $minute;
157
            return $date;
158
          }
159
        }
160
      }
161
      // Next hour; first avaiable minute.
162
      elseif ($date['hours'] < $hour) {
163
        $date['hours'] = $hour;
164
        $date['minutes'] = reset($cron['minutes']);
165
        return $date;
166
      }
167
    }
168
    return FALSE;
169
  }
170

    
171
  /**
172
   * Parse each text element. Recursive up to some point...
173
   */
174
  protected static function parseElement($type, $string, $translate = FALSE) {
175
    $string = trim($string);
176
    if ($translate) {
177
      $string = self::translateNames($type, $string);
178
    }
179
    if ($string === '*') {
180
      // This means all possible values, return right away, no need to double check
181
      return self::possibleValues($type);
182
    }
183
    elseif (strpos($string, '/')) {
184
      // Multiple. Example */2, for weekday will expand into 2, 4, 6
185
      list($values, $multiple) = explode('/', $string);
186
      $values = self::parseElement($type, $values);
187
      foreach ($values as $value) {
188
        if (!($value % $multiple)) {
189
          $range[] = $value;
190
        }
191
      }
192
    }
193
    elseif (strpos($string, ',')) {
194
      // Now process list parts, expand into items, process each and merge back
195
      $list = explode(',', $string);
196
      $range = array();
197
      foreach ($list as $item) {
198
        if ($values = self::parseElement($type, $item)) {
199
          $range = array_merge($range, $values);
200
        }
201
      }
202
    }
203
    elseif (strpos($string, '-')) {
204
      // This defines a range. Example 1-3, will expand into 1,2,3
205
      list($start, $end) = explode('-', $string);
206
      // Double check the range is within possible values
207
      $range = range($start, $end);
208
    }
209
    elseif (is_numeric($string)) {
210
      // This looks like a single number, double check it's int
211
      $range = array((int)$string);
212
    }
213

    
214
    // Return unique sorted values and double check they're within possible values
215
    if (!empty($range)) {
216
      $range = array_intersect(array_unique($range), self::possibleValues($type));
217
      sort($range);
218
      // Sunday validation. We need cron values to match PHP values, thus week day 7 is not allowed, must be 0
219
      if ($type == 'wday' && in_array(7, $range)) {
220
        array_pop($range);
221
        array_unshift($range, 0);
222
      }
223
      return $range;
224
    }
225
    else {
226
      // No match found for this one, will produce an error with validation
227
      return array();
228
    }
229
  }
230

    
231
  /**
232
   * Get values for each type
233
   */
234
  public static function possibleValues($type) {
235
    switch ($type) {
236
      case 'minutes':
237
        return range(0, 59);
238
      case 'hours':
239
        return range(0, 23);
240
      case 'mday':
241
        return range(1, 31);
242
      case 'mon':
243
        return range(1, 12);
244
      case 'wday':
245
        // These are PHP values, not *nix ones
246
        return range(0, 6);
247

    
248
    }
249
  }
250

    
251
  /**
252
   * Replace element names by values
253
   */
254
  public static function translateNames($type, $string) {
255
    switch ($type) {
256
      case 'wday':
257
        $replace = array_merge(
258
          // Tricky, tricky, we need sunday to be zero at the beginning of a range, but 7 at the end
259
          array('-sunday' => '-7', '-sun' => '-7', 'sunday-' => '0-', 'sun-' => '0-'),
260
          array_flip(array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday')),
261
          array_flip(array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'))
262
        );
263
        break;
264
      case 'mon':
265
        $replace = array_merge(
266
          array_flip(array('nomonth1', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december')),
267
          array_flip(array('nomonth2', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec')),
268
          array('sept' => 9)
269
        );
270
        break;
271
    }
272
    if (empty($replace)) {
273
      return $string;
274
    }
275
    else {
276
      return strtr($string, $replace);
277
    }
278
  }
279
}