[BUGFIX] Fix PHP warning in EXT:beuser
[Packages/TYPO3.CMS.git] / typo3 / sysext / scheduler / class.tx_scheduler_croncmd.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2008-2011 Markus Friedrich (markus.friedrich@dkd.de)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 *
17 * This script is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * This copyright notice MUST APPEAR in all copies of the script!
23 ***************************************************************/
24
25 /**
26 * This class provides calulations for the cron command format.
27 *
28 * @author Markus Friedrich <markus.friedrich@dkd.de>
29 * @author Christian Kuhn <lolli@schwarzbu.ch>
30 * @package TYPO3
31 * @subpackage tx_scheduler
32 */
33 class tx_scheduler_CronCmd {
34
35 /**
36 * Normalized sections of the cron command.
37 * Allowed are comma separated lists of integers and the character '*'
38 *
39 * field lower and upper bound
40 * ----- --------------
41 * minute 0-59
42 * hour 0-23
43 * day of month 1-31
44 * month 1-12
45 * day of week 1-7
46 *
47 * @var array $cronCommandSections
48 */
49 protected $cronCommandSections;
50
51 /**
52 * Timestamp of next execution date.
53 * This value starts with 'now + 1 minute' if not set externally
54 * by unit tests. After a call to calculateNextValue() it holds the timestamp of
55 * the next execution date which matches the cron command restrictions.
56 */
57 protected $timestamp;
58
59 /**
60 * Constructor
61 *
62 * @api
63 * @param string $cronCommand The cron command can hold any combination documented as valid
64 * expression in usual unix like crons like vixiecron. Special commands like
65 * "@weekly", ranges, steps and three letter month and weekday abbreviations are allowed.
66 * @param bool|int $timestamp Optional start time, used in unit tests
67 *
68 * @return tx_scheduler_CronCmd
69 */
70 public function __construct($cronCommand, $timestamp = FALSE) {
71 $cronCommand = tx_scheduler_CronCmd_Normalize::normalize($cronCommand);
72
73 // Explode cron command to sections
74 $this->cronCommandSections = t3lib_div::trimExplode(' ', $cronCommand);
75
76 // Initialize the values with the starting time
77 // This takes care that the calculated time is always in the future
78 if ($timestamp === FALSE) {
79 $timestamp = strtotime('+1 minute');
80 } else {
81 $timestamp += 60;
82 }
83 $this->timestamp = $this->roundTimestamp($timestamp);
84 }
85
86 /**
87 * Calculates the date of the next execution.
88 *
89 * @api
90 * @return void
91 */
92 public function calculateNextValue() {
93 $newTimestamp = $this->getTimestamp();
94
95 // Calculate next minute and hour field
96 $loopCount = 0;
97 while (TRUE) {
98 $loopCount ++;
99 // If there was no match within two days, cron command is invalid.
100 // The second day is needed to catch the summertime leap in some countries.
101 if ($loopCount > 2880) {
102 throw new RuntimeException(
103 'Unable to determine next execution timestamp: Hour and minute combination is invalid.',
104 1291494126
105 );
106 }
107 if ($this->minuteAndHourMatchesCronCommand($newTimestamp)) {
108 break;
109 }
110 $newTimestamp += 60;
111 }
112
113 $loopCount = 0;
114 while (TRUE) {
115 $loopCount ++;
116 // A date must match within the next 4 years, this high number makes
117 // sure leap year cron command configuration are caught.
118 // If the loop runs longer than that, the cron command is invalid.
119 if ($loopCount > 1464) {
120 throw new RuntimeException(
121 'Unable to determine next execution timestamp: Day of month, month and day of week combination is invalid.',
122 1291501280
123 );
124 }
125 if ($this->dayMatchesCronCommand($newTimestamp)) {
126 break;
127 }
128 $newTimestamp += $this->numberOfSecondsInDay($newTimestamp);
129 }
130
131 $this->timestamp = $newTimestamp;
132 }
133
134 /*
135 * Get next timestamp
136 *
137 * @api
138 * @return integer Unix timestamp
139 */
140 public function getTimestamp() {
141 return $this->timestamp;
142 }
143
144 /**
145 * Get cron command sections. Array of strings, each containing either
146 * a list of comma separated integers or *
147 *
148 * @return array command sections:
149 * 0 => minute
150 * 1 => hour
151 * 2 => day of month
152 * 3 => month
153 * 4 => day of week
154 */
155 public function getCronCommandSections() {
156 return $this->cronCommandSections;
157 }
158
159 /**
160 * Determine if current timestamp matches minute and hour cron command restriction.
161 *
162 * @param integer $timestamp to test
163 * @return boolean TRUE if cron command conditions are met
164 */
165 protected function minuteAndHourMatchesCronCommand($timestamp) {
166 $minute = intval(date('i', $timestamp));
167 $hour = intval(date('G', $timestamp));
168
169 $commandMatch = FALSE;
170 if (
171 $this->isInCommandList($this->cronCommandSections[0], $minute)
172 && $this->isInCommandList($this->cronCommandSections[1], $hour)
173 ) {
174 $commandMatch = TRUE;
175 }
176
177 return $commandMatch;
178 }
179
180 /**
181 * Determine if current timestamp matches day of month, month and day of week
182 * cron command restriction
183 *
184 * @param integer $timestamp to test
185 * @return boolean TRUE if cron command conditions are met
186 */
187 protected function dayMatchesCronCommand($timestamp) {
188 $dayOfMonth = date('j', $timestamp);
189 $month = date('n', $timestamp);
190 $dayOfWeek = date('N', $timestamp);
191
192 $isInDayOfMonth = $this->isInCommandList($this->cronCommandSections[2], $dayOfMonth);
193 $isInMonth = $this->isInCommandList($this->cronCommandSections[3], $month);
194 $isInDayOfWeek = $this->isInCommandList($this->cronCommandSections[4], $dayOfWeek);
195
196 // Quote from vixiecron:
197 // Note: The day of a command's execution can be specified by two fields — day of month, and day of week.
198 // If both fields are restricted (i.e., aren't *), the command will be run when either field
199 // matches the current time. For example, `30 4 1,15 * 5' would cause
200 // a command to be run at 4:30 am on the 1st and 15th of each month, plus every Friday.
201
202 $isDayOfMonthRestricted = (string)$this->cronCommandSections[2] === '*' ? FALSE : TRUE;
203 $isDayOfWeekRestricted = (string)$this->cronCommandSections[4] === '*' ? FALSE : TRUE;
204
205 $commandMatch = FALSE;
206 if ($isInMonth) {
207 if (
208 ($isInDayOfMonth && $isDayOfMonthRestricted)
209 || ($isInDayOfWeek && $isDayOfWeekRestricted)
210 || ($isInDayOfMonth && !$isDayOfMonthRestricted && $isInDayOfWeek && !$isDayOfWeekRestricted)
211 ) {
212 $commandMatch = TRUE;
213 }
214 }
215
216 return $commandMatch;
217 }
218
219 /**
220 * Determine if a given number validates a cron command section. The given cron
221 * command must be a 'normalized' list with only comma separated integers or '*'
222 *
223 * @param string $commandExpression: cron command
224 * @param integer $numberToMatch: number to look up
225 * @return boolean TRUE if number is in list
226 */
227 protected function isInCommandList($commandExpression, $numberToMatch) {
228 $inList = FALSE;
229 if ((string)$commandExpression === '*') {
230 $inList = TRUE;
231 } else {
232 $inList = t3lib_div::inList($commandExpression, $numberToMatch);
233 }
234
235 return $inList;
236 }
237
238 /**
239 * Helper method to calculate number of seconds in a day.
240 *
241 * This is not always 86400 (60*60*24) and depends on the timezone:
242 * Some countries like Germany have a summertime / wintertime switch,
243 * on every last sunday in march clocks are forwarded by one hour (set from 2:00 to 3:00),
244 * and on last sunday of october they are set back one hour (from 3:00 to 2:00).
245 * This shortens and lengthens the length of a day by one hour.
246 *
247 * @param integer $timestamp Unix timestamp
248 * @return integer Number of seconds of day
249 */
250 protected function numberOfSecondsInDay($timestamp) {
251 $now = mktime(0, 0, 0, date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp));
252 // Make sure to be in next day, even if day has 25 hours
253 $nextDay = $now + 60*60*25;
254 $nextDay = mktime(0, 0, 0, date('n', $nextDay), date('j', $nextDay), date('Y', $nextDay));
255
256 return ($nextDay - $now);
257 }
258
259 /**
260 * Round a timestamp down to full minute.
261 *
262 * @param integer $timestamp Unix timestamp
263 * @return integer Rounded timestamp
264 */
265 protected function roundTimestamp($timestamp) {
266 return mktime(date('H', $timestamp), date('i', $timestamp), 0, date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp));
267 }
268 }
269 ?>