[TASK] Remove classname from insert fields 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 'disable' => $task->isDisabled(),
74 'serialized_task_object' => 'RESERVED'
75 );
76 $result = $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_scheduler_task', $fields);
77 if ($result) {
78 $task->setTaskUid($GLOBALS['TYPO3_DB']->sql_insert_id());
79 $task->save();
80 $result = TRUE;
81 } else {
82 $result = FALSE;
83 }
84 } else {
85 $result = FALSE;
86 }
87 return $result;
88 }
89
90 /**
91 * Cleans the execution lists of the scheduled tasks, executions older than 24h are removed
92 * TODO: find a way to actually kill the job
93 *
94 * @return void
95 */
96 protected function cleanExecutionArrays() {
97 $tstamp = $GLOBALS['EXEC_TIME'];
98 // Select all tasks with executions
99 // NOTE: this cleanup is done for disabled tasks too,
100 // to avoid leaving old executions lying around
101 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid, serialized_executions, serialized_task_object', 'tx_scheduler_task', 'serialized_executions <> \'\'');
102 $maxDuration = $this->extConf['maxLifetime'] * 60;
103 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
104 $executions = array();
105 if ($serialized_executions = unserialize($row['serialized_executions'])) {
106 foreach ($serialized_executions as $task) {
107 if ($tstamp - $task < $maxDuration) {
108 $executions[] = $task;
109 } else {
110 $task = unserialize($row['serialized_task_object']);
111 $logMessage = 'Removing logged execution, assuming that the process is dead. Execution of \'' . get_class($task) . '\' (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 $registry \TYPO3\CMS\Core\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 'disable' => $task->isDisabled(),
238 'serialized_task_object' => serialize($task)
239 );
240 $result = $GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_scheduler_task', 'uid = ' . $taskUid, $fields);
241 } else {
242 $result = FALSE;
243 }
244 if ($result) {
245 $this->scheduleNextSchedulerRunUsingAtDaemon();
246 }
247 return $result;
248 }
249
250 /**
251 * Fetches and unserializes a task object from the db. If an uid is given the object
252 * with the uid is returned, else the object representing the next due task is returned.
253 * If there are no due tasks the method throws an exception.
254 *
255 * @param integer $uid Primary key of a task
256 * @return \TYPO3\CMS\Scheduler\Task The fetched task object
257 */
258 public function fetchTask($uid = 0) {
259 // Define where clause
260 // If no uid is given, take any non-disabled task which has a next execution time in the past
261 if (empty($uid)) {
262 $whereClause = 'disable = 0 AND nextexecution != 0 AND nextexecution <= ' . $GLOBALS['EXEC_TIME'];
263 } else {
264 $whereClause = 'uid = ' . intval($uid);
265 }
266 $queryArray = array(
267 'SELECT' => 'uid, serialized_task_object',
268 'FROM' => 'tx_scheduler_task',
269 'WHERE' => $whereClause,
270 'LIMIT' => 1
271 );
272 $res = $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($queryArray);
273 // If there are no available tasks, thrown an exception
274 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) == 0) {
275 throw new \OutOfBoundsException('No task', 1247827244);
276 } else {
277 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
278 /** @var $task \TYPO3\CMS\Scheduler\Task */
279 $task = unserialize($row['serialized_task_object']);
280 if ($this->isValidTaskObject($task)) {
281 // The task is valid, return it
282 $task->setScheduler();
283 } else {
284 // Forcibly set the disable flag to 1 in the database,
285 // so that the task does not come up again and again for execution
286 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_scheduler_task', 'uid = ' . $row['uid'], array('disable' => 1));
287 // Throw an exception to raise the problem
288 throw new \UnexpectedValueException('Could not unserialize task', 1255083671);
289 }
290 $GLOBALS['TYPO3_DB']->sql_free_result($res);
291 }
292 return $task;
293 }
294
295 /**
296 * This method is used to get the database record for a given task
297 * It returns the database record and not the task object
298 *
299 * @param integer $uid Primary key of the task to get
300 * @return array Database record for the task
301 * @see tx_scheduler::fetchTask()
302 */
303 public function fetchTaskRecord($uid) {
304 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'tx_scheduler_task', 'uid = ' . intval($uid));
305 // If the task is not found, throw an exception
306 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) == 0) {
307 throw new \OutOfBoundsException('No task', 1247827244);
308 } else {
309 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
310 $GLOBALS['TYPO3_DB']->sql_free_result($res);
311 }
312 return $row;
313 }
314
315 /**
316 * Fetches and unserializes task objects selected with some (SQL) condition
317 * Objects are returned as an array
318 *
319 * @param string $where Part of a SQL where clause (without the "WHERE" keyword)
320 * @param boolean $includeDisabledTasks TRUE if disabled tasks should be fetched too, FALSE otherwise
321 * @return array List of task objects
322 */
323 public function fetchTasksWithCondition($where, $includeDisabledTasks = FALSE) {
324 $whereClause = '';
325 $tasks = array();
326 if (!empty($where)) {
327 $whereClause = $where;
328 }
329 if (!$includeDisabledTasks) {
330 if (!empty($whereClause)) {
331 $whereClause .= ' AND ';
332 }
333 $whereClause .= 'disable = 0';
334 }
335 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('serialized_task_object', 'tx_scheduler_task', $whereClause);
336 if ($res) {
337 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
338 /** @var $task Task */
339 $task = unserialize($row['serialized_task_object']);
340 // Add the task to the list only if it is valid
341 if ($this->isValidTaskObject($task)) {
342 $task->setScheduler();
343 $tasks[] = $task;
344 }
345 }
346 $GLOBALS['TYPO3_DB']->sql_free_result($res);
347 }
348 return $tasks;
349 }
350
351 /**
352 * This method encapsulates a very simple test for the purpose of clarity.
353 * Registered tasks are stored in the database along with a serialized task object.
354 * When a registered task is fetched, its object is unserialized.
355 * At that point, if the class corresponding to the object is not available anymore
356 * (e.g. because the extension providing it has been uninstalled),
357 * the unserialization will produce an incomplete object.
358 * This test checks whether the unserialized object is of the right (parent) class or not.
359 *
360 * @param object $task The object to test
361 * @return boolean TRUE if object is a task, FALSE otherwise
362 */
363 public function isValidTaskObject($task) {
364 return $task instanceof \TYPO3\CMS\Scheduler\Task;
365 }
366
367 /**
368 * This is a utility method that writes some message to the BE Log
369 * It could be expanded to write to some other log
370 *
371 * @param string $message The message to write to the log
372 * @param integer $status Status (0 = message, 1 = error)
373 * @param mixed $code Key for the message
374 * @return void
375 */
376 public function log($message, $status = 0, $code = 'scheduler') {
377 // Log only if enabled
378 if (!empty($this->extConf['enableBELog'])) {
379 $GLOBALS['BE_USER']->writelog(4, 0, $status, $code, '[scheduler]: ' . $message, array());
380 }
381 }
382
383 /**
384 * Schedule the next run of scheduler
385 * For the moment only the "at"-daemon is used, and only if it is enabled
386 *
387 * @return boolean Successfully scheduled next execution using "at"-daemon
388 * @see tx_scheduler::fetchTask()
389 */
390 public function scheduleNextSchedulerRunUsingAtDaemon() {
391 if ((int) $this->extConf['useAtdaemon'] !== 1) {
392 return FALSE;
393 }
394 /** @var $registry \TYPO3\CMS\Core\Registry */
395 $registry = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Registry');
396 // Get at job id from registry and remove at job
397 $atJobId = $registry->get('tx_scheduler', 'atJobId');
398 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($atJobId)) {
399 shell_exec('atrm ' . (int) $atJobId . ' 2>&1');
400 }
401 // Can not use fetchTask() here because if tasks have just executed
402 // they are not in the list of next executions
403 $tasks = $this->fetchTasksWithCondition('');
404 $nextExecution = FALSE;
405 foreach ($tasks as $task) {
406 /** @var $task \TYPO3\CMS\Scheduler\Task */
407 $tempNextExecution = $task->getNextDueExecution();
408 if ($nextExecution === FALSE || $tempNextExecution < $nextExecution) {
409 $nextExecution = $tempNextExecution;
410 }
411 }
412 if ($nextExecution !== FALSE) {
413 if ($nextExecution > $GLOBALS['EXEC_TIME']) {
414 $startTime = strftime('%H:%M %F', $nextExecution);
415 } else {
416 $startTime = 'now+1minute';
417 }
418 $cliDispatchPath = PATH_site . 'typo3/cli_dispatch.phpsh';
419 $currentLocale = setlocale(LC_CTYPE, 0);
420 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
421 setlocale(LC_CTYPE, $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']);
422 }
423 $cmd = 'echo ' . escapeshellarg($cliDispatchPath) . ' scheduler | at ' . escapeshellarg($startTime) . ' 2>&1';
424 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
425 setlocale(LC_CTYPE, $currentLocale);
426 }
427 $output = shell_exec($cmd);
428 $outputParts = '';
429 foreach (explode(LF, $output) as $outputLine) {
430 if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($outputLine, 'job')) {
431 $outputParts = explode(' ', $outputLine, 3);
432 break;
433 }
434 }
435 if ($outputParts[0] === 'job' && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($outputParts[1])) {
436 $atJobId = (int) $outputParts[1];
437 $registry->set('tx_scheduler', 'atJobId', $atJobId);
438 }
439 }
440 return TRUE;
441 }
442
443 }
444
445
446 ?>