[BUGFIX] Fix some broken classname substitutions in scheduler
[Packages/TYPO3.CMS.git] / typo3 / sysext / scheduler / Classes / Scheduler.php
1 <?php
2 namespace TYPO3\CMS\Scheduler;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2005 Christian Jul Jensen <julle@typo3.org>
8 *
9 * All rights reserved
10 *
11 * This script is part of the TYPO3 project. The TYPO3 project is
12 * free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * The GNU General Public License can be found at
18 * http://www.gnu.org/copyleft/gpl.html.
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * TYPO3 Scheduler. This class handles scheduling and execution of tasks.
29 * Formerly known as "Gabriel TYPO3 arch angel"
30 *
31 * @author Fran├žois Suter <francois@typo3.org>
32 * @author Christian Jul Jensen <julle@typo3.org>
33 * @package TYPO3
34 * @subpackage tx_scheduler
35 */
36 class Scheduler implements \TYPO3\CMS\Core\SingletonInterface {
37
38 /**
39 * @var array $extConf: settings from the extension manager
40 * @todo Define visibility
41 */
42 public $extConf = array();
43
44 /**
45 * Constructor, makes sure all derived client classes are included
46 *
47 * @return \TYPO3\CMS\Scheduler\Scheduler
48 */
49 public function __construct() {
50 // Get configuration from the extension manager
51 $this->extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['scheduler']);
52 if (empty($this->extConf['maxLifetime'])) {
53 $this->extConf['maxLifetime'] = 1440;
54 }
55 if (empty($this->extConf['useAtdaemon'])) {
56 $this->extConf['useAtdaemon'] = 0;
57 }
58 // Clean up the serialized execution arrays
59 $this->cleanExecutionArrays();
60 }
61
62 /**
63 * Adds a task to the pool
64 *
65 * @param \TYPO3\CMS\Scheduler\Task $task The object representing the task to add
66 * @return boolean TRUE if the task was successfully added, FALSE otherwise
67 */
68 public function addTask(\TYPO3\CMS\Scheduler\Task $task) {
69 $taskUid = $task->getTaskUid();
70 if (empty($taskUid)) {
71 $fields = array(
72 'crdate' => $GLOBALS['EXEC_TIME'],
73 'classname' => get_class($task),
74 'disable' => $task->isDisabled(),
75 'serialized_task_object' => 'RESERVED'
76 );
77 $result = $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_scheduler_task', $fields);
78 if ($result) {
79 $task->setTaskUid($GLOBALS['TYPO3_DB']->sql_insert_id());
80 $task->save();
81 $result = TRUE;
82 } else {
83 $result = FALSE;
84 }
85 } else {
86 $result = FALSE;
87 }
88 return $result;
89 }
90
91 /**
92 * Cleans the execution lists of the scheduled tasks, executions older than 24h are removed
93 * TODO: find a way to actually kill the job
94 *
95 * @return void
96 */
97 protected function cleanExecutionArrays() {
98 $tstamp = $GLOBALS['EXEC_TIME'];
99 // Select all tasks with executions
100 // NOTE: this cleanup is done for disabled tasks too,
101 // to avoid leaving old executions lying around
102 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid, classname, serialized_executions', 'tx_scheduler_task', 'serialized_executions <> \'\'');
103 $maxDuration = $this->extConf['maxLifetime'] * 60;
104 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
105 if ($serialized_executions = unserialize($row['serialized_executions'])) {
106 $executions = array();
107 foreach ($serialized_executions as $task) {
108 if ($tstamp - $task < $maxDuration) {
109 $executions[] = $task;
110 } else {
111 $logMessage = (((('Removing logged execution, assuming that the process is dead. Execution of \'' . $row['classname']) . '\' (UID: ') . $row['uid']) . ') was started at ') . date('Y-m-d H:i:s', $task);
112 $this->log($logMessage);
113 }
114 }
115 }
116 if (count($serialized_executions) != count($executions)) {
117 if (count($executions) == 0) {
118 $value = '';
119 } else {
120 $value = serialize($executions);
121 }
122 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_scheduler_task', 'uid = ' . intval($row['uid']), array('serialized_executions' => $value));
123 }
124 }
125 $GLOBALS['TYPO3_DB']->sql_free_result($res);
126 }
127
128 /**
129 * This method executes the given task and properly marks and records that execution
130 * It is expected to return FALSE if the task was barred from running or if it was not saved properly
131 *
132 * @param \TYPO3\CMS\Scheduler\Task $task The task to execute
133 * @return boolean Whether the task was saved successfully to the database or not
134 */
135 public function executeTask(\TYPO3\CMS\Scheduler\Task $task) {
136 // Trigger the saving of the task, as this will calculate its next execution time
137 // This should be calculated all the time, even if the execution is skipped
138 // (in case it is skipped, this pushes back execution to the next possible date)
139 $task->save();
140 // Set a scheduler object for the task again,
141 // as it was removed during the save operation
142 $task->setScheduler();
143 $result = TRUE;
144 // Task is already running and multiple executions are not allowed
145 if (!$task->areMultipleExecutionsAllowed() && $task->isExecutionRunning()) {
146 // Log multiple execution error
147 $logMessage = (('Task is already running and multiple executions are not allowed, skipping! Class: ' . get_class($task)) . ', UID: ') . $task->getTaskUid();
148 $this->log($logMessage);
149 $result = FALSE;
150 } else {
151 // Log scheduler invocation
152 $logMessage = (('Start execution. Class: ' . get_class($task)) . ', UID: ') . $task->getTaskUid();
153 $this->log($logMessage);
154 // Register execution
155 $executionID = $task->markExecution();
156 $failure = NULL;
157 try {
158 // Execute task
159 $successfullyExecuted = $task->execute();
160 if (!$successfullyExecuted) {
161 throw new \TYPO3\CMS\Scheduler\FailedExecutionException((('Task failed to execute successfully. Class: ' . get_class($task)) . ', UID: ') . $task->getTaskUid(), 1250596541);
162 }
163 } catch (\Exception $e) {
164 // Store exception, so that it can be saved to database
165 $failure = $e;
166 }
167 // Un-register execution
168 $task->unmarkExecution($executionID, $failure);
169 // Log completion of execution
170 $logMessage = (('Task executed. Class: ' . get_class($task)) . ', UID: ') . $task->getTaskUid();
171 $this->log($logMessage);
172 // Now that the result of the task execution has been handled,
173 // throw the exception again, if any
174 if ($failure instanceof \Exception) {
175 throw $failure;
176 }
177 }
178 return $result;
179 }
180
181 /**
182 * This method stores information about the last run of the Scheduler into the system registry
183 *
184 * @param string $type Type of run (manual or command-line (assumed to be cron))
185 * @return void
186 */
187 public function recordLastRun($type = 'cron') {
188 // Validate input value
189 if ($type !== 'manual' && $type !== 'cli-by-id') {
190 $type = 'cron';
191 }
192 /** @var \TYPO3\CMS\Core\Registry $registry */
193 $registry = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Registry');
194 $runInformation = array('start' => $GLOBALS['EXEC_TIME'], 'end' => time(), 'type' => $type);
195 $registry->set('tx_scheduler', 'lastRun', $runInformation);
196 }
197
198 /**
199 * Removes a task completely from the system.
200 * TODO: find a way to actually kill the existing jobs
201 *
202 * @param \TYPO3\CMS\Scheduler\Task $task The object representing the task to delete
203 * @return boolean TRUE if task was successfully deleted, FALSE otherwise
204 */
205 public function removeTask(\TYPO3\CMS\Scheduler\Task $task) {
206 $taskUid = $task->getTaskUid();
207 if (!empty($taskUid)) {
208 $result = $GLOBALS['TYPO3_DB']->exec_DELETEquery('tx_scheduler_task', 'uid = ' . $taskUid);
209 } else {
210 $result = FALSE;
211 }
212 if ($result) {
213 $this->scheduleNextSchedulerRunUsingAtDaemon();
214 }
215 return $result;
216 }
217
218 /**
219 * Updates a task in the pool
220 *
221 * @param \TYPO3\CMS\Scheduler\Task $task Scheduler task object
222 * @return boolean False if submitted task was not of proper class
223 */
224 public function saveTask(\TYPO3\CMS\Scheduler\Task $task) {
225 $taskUid = $task->getTaskUid();
226 if (!empty($taskUid)) {
227 try {
228 $executionTime = $task->getNextDueExecution();
229 $task->setExecutionTime($executionTime);
230 } catch (\Exception $e) {
231 $task->setDisabled(TRUE);
232 $executionTime = 0;
233 }
234 $task->unsetScheduler();
235 $fields = array(
236 'nextexecution' => $executionTime,
237 'classname' => get_class($task),
238 'disable' => $task->isDisabled(),
239 'serialized_task_object' => serialize($task)
240 );
241 $result = $GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_scheduler_task', 'uid = ' . $taskUid, $fields);
242 } else {
243 $result = FALSE;
244 }
245 if ($result) {
246 $this->scheduleNextSchedulerRunUsingAtDaemon();
247 }
248 return $result;
249 }
250
251 /**
252 * Fetches and unserializes a task object from the db. If an uid is given the object
253 * with the uid is returned, else the object representing the next due task is returned.
254 * If there are no due tasks the method throws an exception.
255 *
256 * @param integer $uid Primary key of a task
257 * @return \TYPO3\CMS\Scheduler\Task The fetched task object
258 */
259 public function fetchTask($uid = 0) {
260 // Define where clause
261 // If no uid is given, take any non-disabled task which has a next execution time in the past
262 if (empty($uid)) {
263 $whereClause = 'disable = 0 AND nextexecution != 0 AND nextexecution <= ' . $GLOBALS['EXEC_TIME'];
264 } else {
265 $whereClause = 'uid = ' . intval($uid);
266 }
267 $queryArray = array(
268 'SELECT' => 'uid, serialized_task_object',
269 'FROM' => 'tx_scheduler_task',
270 'WHERE' => $whereClause,
271 'LIMIT' => 1
272 );
273 $res = $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($queryArray);
274 // If there are no available tasks, thrown an exception
275 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) == 0) {
276 throw new \OutOfBoundsException('No task', 1247827244);
277 } else {
278 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
279 /** @var $task \TYPO3\CMS\Scheduler\Task */
280 $task = unserialize($row['serialized_task_object']);
281 if ($this->isValidTaskObject($task)) {
282 // The task is valid, return it
283 $task->setScheduler();
284 } else {
285 // Forcibly set the disable flag to 1 in the database,
286 // so that the task does not come up again and again for execution
287 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_scheduler_task', 'uid = ' . $row['uid'], array('disable' => 1));
288 // Throw an exception to raise the problem
289 throw new \UnexpectedValueException('Could not unserialize task', 1255083671);
290 }
291 $GLOBALS['TYPO3_DB']->sql_free_result($res);
292 }
293 return $task;
294 }
295
296 /**
297 * This method is used to get the database record for a given task
298 * It returns the database record and not the task object
299 *
300 * @param integer $uid Primary key of the task to get
301 * @return array Database record for the task
302 * @see tx_scheduler::fetchTask()
303 */
304 public function fetchTaskRecord($uid) {
305 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'tx_scheduler_task', 'uid = ' . intval($uid));
306 // If the task is not found, throw an exception
307 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) == 0) {
308 throw new \OutOfBoundsException('No task', 1247827244);
309 } else {
310 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
311 $GLOBALS['TYPO3_DB']->sql_free_result($res);
312 }
313 return $row;
314 }
315
316 /**
317 * Fetches and unserializes task objects selected with some (SQL) condition
318 * Objects are returned as an array
319 *
320 * @param string $where Part of a SQL where clause (without the "WHERE" keyword)
321 * @param boolean $includeDisabledTasks TRUE if disabled tasks should be fetched too, FALSE otherwise
322 * @return array List of task objects
323 */
324 public function fetchTasksWithCondition($where, $includeDisabledTasks = FALSE) {
325 $whereClause = '';
326 $tasks = array();
327 if (!empty($where)) {
328 $whereClause = $where;
329 }
330 if (!$includeDisabledTasks) {
331 if (!empty($whereClause)) {
332 $whereClause .= ' AND ';
333 }
334 $whereClause .= 'disable = 0';
335 }
336 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('serialized_task_object', 'tx_scheduler_task', $whereClause);
337 if ($res) {
338 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
339 /** @var $task Task */
340 $task = unserialize($row['serialized_task_object']);
341 // Add the task to the list only if it is valid
342 if ($this->isValidTaskObject($task)) {
343 $task->setScheduler();
344 $tasks[] = $task;
345 }
346 }
347 $GLOBALS['TYPO3_DB']->sql_free_result($res);
348 }
349 return $tasks;
350 }
351
352 /**
353 * This method encapsulates a very simple test for the purpose of clarity.
354 * Registered tasks are stored in the database along with a serialized task object.
355 * When a registered task is fetched, its object is unserialized.
356 * At that point, if the class corresponding to the object is not available anymore
357 * (e.g. because the extension providing it has been uninstalled),
358 * the unserialization will produce an incomplete object.
359 * This test checks whether the unserialized object is of the right (parent) class or not.
360 *
361 * @param object $task The object to test
362 * @return boolean TRUE if object is a task, FALSE otherwise
363 */
364 public function isValidTaskObject($task) {
365 return $task instanceof \TYPO3\CMS\Scheduler\Task;
366 }
367
368 /**
369 * This is a utility method that writes some message to the BE Log
370 * It could be expanded to write to some other log
371 *
372 * @param string $message The message to write to the log
373 * @param integer $status Status (0 = message, 1 = error)
374 * @param mixed $code Key for the message
375 * @return void
376 */
377 public function log($message, $status = 0, $code = 'scheduler') {
378 // Log only if enabled
379 if (!empty($this->extConf['enableBELog'])) {
380 $GLOBALS['BE_USER']->writelog(4, 0, $status, $code, '[scheduler]: ' . $message, array());
381 }
382 }
383
384 /**
385 * Schedule the next run of scheduler
386 * For the moment only the "at"-daemon is used, and only if it is enabled
387 *
388 * @return boolean Successfully scheduled next execution using "at"-daemon
389 * @see tx_scheduler::fetchTask()
390 */
391 public function scheduleNextSchedulerRunUsingAtDaemon() {
392 if ((int) $this->extConf['useAtdaemon'] !== 1) {
393 return FALSE;
394 }
395 /** @var $registry \TYPO3\CMS\Core\Registry */
396 $registry = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Registry');
397 // Get at job id from registry and remove at job
398 $atJobId = $registry->get('tx_scheduler', 'atJobId');
399 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($atJobId)) {
400 shell_exec(('atrm ' . (int) $atJobId) . ' 2>&1');
401 }
402 // Can not use fetchTask() here because if tasks have just executed
403 // they are not in the list of next executions
404 $tasks = $this->fetchTasksWithCondition('');
405 $nextExecution = FALSE;
406 foreach ($tasks as $task) {
407 /** @var $task \TYPO3\CMS\Scheduler\Task */
408 $tempNextExecution = $task->getNextDueExecution();
409 if ($nextExecution === FALSE || $tempNextExecution < $nextExecution) {
410 $nextExecution = $tempNextExecution;
411 }
412 }
413 if ($nextExecution !== FALSE) {
414 if ($nextExecution > $GLOBALS['EXEC_TIME']) {
415 $startTime = strftime('%H:%M %F', $nextExecution);
416 } else {
417 $startTime = 'now+1minute';
418 }
419 $cliDispatchPath = PATH_site . 'typo3/cli_dispatch.phpsh';
420 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
421 $currentLocale = setlocale(LC_CTYPE, 0);
422 setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
423 }
424 $cmd = ((('echo ' . escapeshellarg($cliDispatchPath)) . ' scheduler | at ') . escapeshellarg($startTime)) . ' 2>&1';
425 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
426 setlocale(LC_CTYPE, $currentLocale);
427 }
428 $output = shell_exec($cmd);
429 $outputParts = '';
430 foreach (explode(LF, $output) as $outputLine) {
431 if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($outputLine, 'job')) {
432 $outputParts = explode(' ', $outputLine, 3);
433 break;
434 }
435 }
436 if ($outputParts[0] === 'job' && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($outputParts[1])) {
437 $atJobId = (int) $outputParts[1];
438 $registry->set('tx_scheduler', 'atJobId', $atJobId);
439 }
440 }
441 return TRUE;
442 }
443
444 }
445
446
447 ?>