[SECURITY] Missing escaping in scheduler
[Packages/TYPO3.CMS.git] / typo3 / sysext / scheduler / class.tx_scheduler_module.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2009-2011 Fran├žois Suter <francois@typo3.org>
6 * (c) 2005 Christian Jul Jensen <julle@typo3.org>
7 * All rights reserved
8 *
9 * This script is part of the TYPO3 project. The TYPO3 project is
10 * free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * The GNU General Public License can be found at
16 * http://www.gnu.org/copyleft/gpl.html.
17 *
18 * This script is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * This copyright notice MUST APPEAR in all copies of the script!
24 ***************************************************************/
25
26 /**
27 * Module 'TYPO3 Scheduler administration module' for the 'scheduler' extension.
28 *
29 * @author Fran├žois Suter <francois@typo3.org>
30 * @author Christian Jul Jensen <julle@typo3.org>
31 * @author Ingo Renner <ingo@typo3.org>
32 * @package TYPO3
33 * @subpackage tx_scheduler
34 */
35 class tx_scheduler_Module extends t3lib_SCbase {
36
37 /**
38 * Back path to typo3 main dir
39 *
40 * @var string $backPath
41 */
42 public $backPath;
43
44 /**
45 * Array containing submitted data when editing or adding a task
46 *
47 * @var array $submittedData
48 */
49 protected $submittedData = array();
50
51 /**
52 * Array containing all messages issued by the application logic
53 * Contains the error's severity and the message itself
54 *
55 * @var array $messages
56 */
57 protected $messages = array();
58
59 /**
60 * @var string Key of the CSH file
61 */
62 protected $cshKey;
63
64 /**
65 *
66 * @var tx_scheduler Local scheduler instance
67 */
68 protected $scheduler;
69
70 /**
71 * Constructor
72 *
73 * @return tx_scheduler_Module
74 */
75 public function __construct() {
76 $this->backPath = $GLOBALS['BACK_PATH'];
77 // Set key for CSH
78 $this->cshKey = '_MOD_' . $GLOBALS['MCONF']['name'];
79 }
80
81 /**
82 * Initializes the backend module
83 *
84 * @return void
85 */
86 public function init() {
87 parent::init();
88
89 // Initialize document
90 $this->doc = t3lib_div::makeInstance('template');
91 $this->doc->setModuleTemplate(t3lib_extMgm::extPath('scheduler') . 'mod1/mod_template.html');
92 $this->doc->getPageRenderer()->addCssFile(t3lib_extMgm::extRelPath('scheduler') . 'res/tx_scheduler_be.css');
93 $this->doc->backPath = $this->backPath;
94 $this->doc->bodyTagId = 'typo3-mod-php';
95 $this->doc->bodyTagAdditions = 'class="tx_scheduler_mod1"';
96
97 // Create scheduler instance
98 $this->scheduler = t3lib_div::makeInstance('tx_scheduler');
99 }
100
101 /**
102 * Adds items to the ->MOD_MENU array. Used for the function menu selector.
103 *
104 * @return void
105 */
106 public function menuConfig() {
107 $this->MOD_MENU = array(
108 'function' => array(
109 'scheduler' => $GLOBALS['LANG']->getLL('function.scheduler'),
110 'check' => $GLOBALS['LANG']->getLL('function.check'),
111 'info' => $GLOBALS['LANG']->getLL('function.info'),
112 )
113 );
114
115 parent::menuConfig();
116 }
117
118 /**
119 * Main function of the module. Write the content to $this->content
120 *
121 * @return void
122 */
123 public function main() {
124 // Access check!
125 // The page will show only if user has admin rights
126 if ($GLOBALS['BE_USER']->user['admin']) {
127
128 // Set the form
129 $this->doc->form = '<form name="tx_scheduler_form" id="tx_scheduler_form" method="post" action="">';
130
131 // JavaScript for main function menu
132 $this->doc->JScode = '
133 <script language="javascript" type="text/javascript">
134 script_ended = 0;
135 function jumpToUrl(URL) {
136 document.location = URL;
137 }
138 </script>
139 ';
140 $this->doc->getPageRenderer()->addInlineSetting('scheduler', 'runningIcon', t3lib_extMgm::extRelPath('scheduler') . 'res/gfx/status_running.png');
141
142 // Prepare main content
143 $this->content = $this->doc->header(
144 $GLOBALS['LANG']->getLL('function.' . $this->MOD_SETTINGS['function'])
145 );
146 $this->content .= $this->doc->spacer(5);
147 $this->content .= $this->getModuleContent();
148 } else {
149 // If no access, only display the module's title
150 $this->content = $this->doc->header($GLOBALS['LANG']->getLL('title'));
151 $this->content .= $this->doc->spacer(5);
152 }
153
154 // Place content inside template
155 $content = $this->doc->moduleBody(
156 array(),
157 $this->getDocHeaderButtons(),
158 $this->getTemplateMarkers()
159 );
160
161 // Renders the module page
162 $this->content = $this->doc->render(
163 $GLOBALS['LANG']->getLL('title'),
164 $content
165 );
166 }
167
168 /**
169 * Generate the module's content
170 *
171 * @return string HTML of the module's main content
172 */
173 protected function getModuleContent() {
174 $content = '';
175 $sectionTitle = '';
176
177 // Get submitted data
178 $this->submittedData = t3lib_div::_GPmerged('tx_scheduler');
179 $this->submittedData['uid'] = intval($this->submittedData['uid']);
180
181 // If a save command was submitted, handle saving now
182 if ($this->CMD == 'save') {
183 $previousCMD = t3lib_div::_GP('previousCMD');
184 // First check the submitted data
185 $result = $this->preprocessData();
186
187 // If result is ok, proceed with saving
188 if ($result) {
189 $this->saveTask();
190 // Unset command, so that default screen gets displayed
191 unset($this->CMD);
192
193 // Errors occurred
194 // Go back to previous step
195 } else {
196 $this->CMD = $previousCMD;
197 }
198 }
199
200 // Handle chosen action
201 switch((string)$this->MOD_SETTINGS['function']) {
202 case 'scheduler':
203 // Scheduler's main screen
204 $content .= $this->executeTasks();
205
206 // Execute chosen action
207 switch ($this->CMD) {
208 case 'add':
209 case 'edit':
210 try {
211 // Try adding or editing
212 $content .= $this->editTask();
213 $sectionTitle = $GLOBALS['LANG']->getLL('action.' . $this->CMD);
214 } catch (Exception $e) {
215 // An exception may happen when the task to
216 // edit could not be found. In this case revert
217 // to displaying the list of tasks
218 // It can also happen when attempting to edit a running task
219 $content .= $this->listTasks();
220 }
221 break;
222 case 'delete':
223 $this->deleteTask();
224 $content .= $this->listTasks();
225 break;
226 case 'stop':
227 $this->stopTask();
228 $content .= $this->listTasks();
229 break;
230 case 'list':
231 default:
232 $content .= $this->listTasks();
233 break;
234 }
235 break;
236 case 'check':
237 // Setup check screen
238 // TODO: move check to the report module
239 $content .= $this->displayCheckScreen();
240 break;
241 case 'info':
242 // Information screen
243 $content .= $this->displayInfoScreen();
244 break;
245 }
246
247 // Wrap the content in a section
248 return $this->doc->section($sectionTitle, '<div class="tx_scheduler_mod1">' . $content . '</div>', 0, 1);
249 }
250
251 /**
252 * This method actually prints out the module's HTML content
253 *
254 * @return void
255 */
256 public function render() {
257 echo $this->content;
258 }
259
260 /**
261 * This method checks the status of the '_cli_scheduler' user
262 * It will differentiate between a non-existing user and an existing,
263 * but disabled user (as per enable fields)
264 *
265 * @return integer -1 if user doesn't exist
266 * 0 if user exists, but is disabled
267 * 1 if user exists and is not disabled
268 */
269 protected function checkSchedulerUser() {
270 $schedulerUserStatus = -1;
271 // Assemble base WHERE clause
272 $where = 'username = \'_cli_scheduler\' AND admin = 0' . t3lib_BEfunc::deleteClause('be_users');
273 // Check if user exists at all
274 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
275 '1',
276 'be_users',
277 $where
278 );
279 if ($GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
280 $schedulerUserStatus = 0;
281 // Check if user exists and is enabled
282 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
283 '1',
284 'be_users',
285 $where . t3lib_BEfunc::BEenableFields('be_users')
286 );
287 if ($GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
288 $schedulerUserStatus = 1;
289 }
290 }
291 $GLOBALS['TYPO3_DB']->sql_free_result($res);
292
293 return $schedulerUserStatus;
294 }
295
296 /**
297 * This method creates the "cli_scheduler" BE user if it doesn't exist
298 *
299 * @return void
300 */
301 protected function createSchedulerUser() {
302 // Check _cli_scheduler user status
303 $checkUser = $this->checkSchedulerUser();
304 // Prepare default message
305 $message = $GLOBALS['LANG']->getLL('msg.userExists');
306 $severity = t3lib_FlashMessage::WARNING;
307 // If the user does not exist, try creating it
308 if ($checkUser == -1) {
309 // Prepare necessary data for _cli_scheduler user creation
310 $password = md5(uniqid('scheduler', TRUE));
311 $data = array('be_users' => array('NEW' => array('username' => '_cli_scheduler', 'password' => $password, 'pid' => 0)));
312 /** @var t3lib_TCEmain $tcemain */
313 $tcemain = t3lib_div::makeInstance('t3lib_TCEmain');
314 $tcemain->stripslashes_values = 0;
315 $tcemain->start($data, array());
316 $tcemain->process_datamap();
317 // Check if a new uid was indeed generated (i.e. a new record was created)
318 // (counting TCEmain errors doesn't work as some failures don't report errors)
319 $numberOfNewIDs = count($tcemain->substNEWwithIDs);
320 if ($numberOfNewIDs == 1) {
321 $message = $GLOBALS['LANG']->getLL('msg.userCreated');
322 $severity = t3lib_FlashMessage::OK;
323 } else {
324 $message = $GLOBALS['LANG']->getLL('msg.userNotCreated');
325 $severity = t3lib_FlashMessage::ERROR;
326 }
327 }
328 $this->addMessage($message, $severity);
329 }
330
331 /**
332 * This method displays the result of a number of checks
333 * on whether the Scheduler is ready to run or running properly
334 *
335 * @return string Further information
336 */
337 protected function displayCheckScreen() {
338 $message = '';
339 $severity = t3lib_FlashMessage::OK;
340
341 // First, check if _cli_scheduler user creation was requested
342 if ($this->CMD == 'user') {
343 $this->createSchedulerUser();
344 }
345
346 // Start generating the content
347 $content = $GLOBALS['LANG']->getLL('msg.schedulerSetupCheck');
348
349 // Display information about last automated run, as stored in the system registry
350 /** @var t3lib_Registry $registry */
351 $registry = t3lib_div::makeInstance('t3lib_Registry');
352 $lastRun = $registry->get('tx_scheduler', 'lastRun');
353 if (!is_array($lastRun)) {
354 $message = $GLOBALS['LANG']->getLL('msg.noLastRun');
355 $severity = t3lib_FlashMessage::WARNING;
356 } else {
357 if (empty($lastRun['end']) || empty($lastRun['start']) || empty($lastRun['type'])) {
358 $message = $GLOBALS['LANG']->getLL('msg.incompleteLastRun');
359 $severity = t3lib_FlashMessage::WARNING;
360 } else {
361 $startDate = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $lastRun['start']);
362 $startTime = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $lastRun['start']);
363 $endDate = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $lastRun['end']);
364 $endTime = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $lastRun['end']);
365 $label = 'automatically';
366 if ($lastRun['type'] == 'manual') {
367 $label = 'manually';
368 }
369 $type = $GLOBALS['LANG']->getLL('label.' . $label);
370 $message = sprintf($GLOBALS['LANG']->getLL('msg.lastRun'), $type, $startDate, $startTime, $endDate, $endTime);
371 $severity = t3lib_FlashMessage::INFO;
372 }
373 }
374 /** @var $flashMessage t3lib_FlashMessage */
375 $flashMessage = t3lib_div::makeInstance(
376 't3lib_FlashMessage',
377 $message,
378 '',
379 $severity
380 );
381 $content .= '<div class="info-block">';
382 $content .= '<h3>' . $GLOBALS['LANG']->getLL('hdg.lastRun') . '</h3>';
383 $content .= $flashMessage->render();
384 $content .= '</div>';
385
386 // Check CLI user
387 $content .= '<div class="info-block">';
388 $content .= '<h3>' . $GLOBALS['LANG']->getLL('hdg.schedulerUser') . '</h3>';
389 $content .= '<p>' . $GLOBALS['LANG']->getLL('msg.schedulerUser') . '</p>';
390
391 $checkUser = $this->checkSchedulerUser();
392 if ($checkUser == -1) {
393 $link = $GLOBALS['MCONF']['_'] . '&SET[function]=check&CMD=user';
394 $message = sprintf($GLOBALS['LANG']->getLL('msg.schedulerUserMissing'), htmlspecialchars($link));
395 $severity = t3lib_FlashMessage::ERROR;
396 } elseif ($checkUser == 0) {
397 $message = $GLOBALS['LANG']->getLL('msg.schedulerUserFoundButDisabled');
398 $severity = t3lib_FlashMessage::WARNING;
399 } else {
400 $message = $GLOBALS['LANG']->getLL('msg.schedulerUserFound');
401 $severity = t3lib_FlashMessage::OK;
402 }
403 $flashMessage = t3lib_div::makeInstance(
404 't3lib_FlashMessage',
405 $message,
406 '',
407 $severity
408 );
409 $content .= $flashMessage->render() . '</div>';
410
411 // Check if CLI script is executable or not
412 $script = PATH_typo3 . 'cli_dispatch.phpsh';
413 $isExecutable = FALSE;
414 // Skip this check if running Windows, as rights do not work the same way on this platform
415 // (i.e. the script will always appear as *not* executable)
416 if (TYPO3_OS === 'WIN') {
417 $isExecutable = TRUE;
418 } else {
419 $isExecutable = is_executable($script);
420 }
421 $content .= '<div class="info-block">';
422 $content .= '<h3>' . $GLOBALS['LANG']->getLL('hdg.cliScript') . '</h3>';
423 $content .= '<p>' . sprintf($GLOBALS['LANG']->getLL('msg.cliScript'), $script) . '</p>';
424
425 if ($isExecutable) {
426 $message = $GLOBALS['LANG']->getLL('msg.cliScriptExecutable');
427 $severity = t3lib_FlashMessage::OK;
428 } else {
429 $message = $GLOBALS['LANG']->getLL('msg.cliScriptNotExecutable');
430 $severity = t3lib_FlashMessage::ERROR;
431 }
432 $flashMessage = t3lib_div::makeInstance(
433 't3lib_FlashMessage',
434 $message,
435 '',
436 $severity
437 );
438 $content .= $flashMessage->render() . '</div>';
439
440 return $content;
441 }
442
443 /**
444 * This method gathers information about all available task classes and displays it
445 *
446 * @return string HTML content to display
447 */
448 protected function displayInfoScreen() {
449 $content = '';
450 $registeredClasses = self::getRegisteredClasses();
451
452 // No classes available, display information message
453 if (count($registeredClasses) == 0) {
454 /** @var t3lib_FlashMessage $flashMessage */
455 $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage',
456 $GLOBALS['LANG']->getLL('msg.noTasksDefined'),
457 '',
458 t3lib_FlashMessage::INFO
459 );
460 $content .= $flashMessage->render();
461
462 // Display the list of all available classes
463 } else {
464 // Initialise table layout
465 $tableLayout = array (
466 'table' => array ('<table border="0" cellspacing="0" cellpadding="0" class="typo3-dblist">', '</table>'),
467 '0' => array (
468 'tr' => array('<tr class="t3-row-header" valign="top">', '</tr>'),
469 'defCol' => array('<td>', '</td>')
470 ),
471 'defRow' => array (
472 'tr' => array('<tr class="db_list_normal">', '</tr>'),
473 'defCol' => array('<td>', '</td>')
474 )
475 );
476 $table = array();
477 $tr = 0;
478
479 // Header row
480 $table[$tr][] = $GLOBALS['LANG']->getLL('label.name');
481 $table[$tr][] = $GLOBALS['LANG']->getLL('label.extension');
482 $table[$tr][] = $GLOBALS['LANG']->getLL('label.description');
483 $table[$tr][] = '';
484 $tr++;
485
486 // Display information about each service
487 foreach ($registeredClasses as $class => $classInfo) {
488 $table[$tr][] = $classInfo['title'];
489 $table[$tr][] = $classInfo['extension'];
490 $table[$tr][] = $classInfo['description'];
491 $link = $GLOBALS['MCONF']['_'] . '&SET[function]=list&CMD=add&tx_scheduler[class]=' . $class;
492 $table[$tr][] = '<a href="' . htmlspecialchars($link) . '" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:new', TRUE) . '" class="icon">' . t3lib_iconWorks::getSpriteIcon('actions-document-new') . '</a>';
493 $tr++;
494 }
495
496 // Render the table and return it
497 $content = '<div>' . $GLOBALS['LANG']->getLL('msg.infoScreenIntro') . '</div>';
498 $content .= $this->doc->spacer(5);
499 $content .= $this->doc->table($table, $tableLayout);
500 }
501
502 return $content;
503 }
504
505 /**
506 * Display the current server's time along with a help text about server time
507 * usage in the Scheduler
508 *
509 * @return string HTML to display
510 */
511 protected function displayServerTime() {
512 // Get the current time, formatted
513 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] . ' T (e';
514 $now = date($dateFormat) . ', GMT ' . date('P') . ')';
515 // Display the help text
516 $serverTime = '<h4>' . $GLOBALS['LANG']->getLL('label.serverTime') . '</h4>';
517 $serverTime .= '<p>' . $GLOBALS['LANG']->getLL('msg.serverTimeHelp') . '</p>';
518 $serverTime .= '<p>' . sprintf($GLOBALS['LANG']->getLL('msg.serverTime'), $now) . '</p>';
519 return $serverTime;
520 }
521
522 /**
523 * Delete a task from the execution queue
524 *
525 * @return void
526 */
527 protected function deleteTask() {
528 try {
529 // Try to fetch the task and delete it
530 $task = $this->scheduler->fetchTask($this->submittedData['uid']);
531 // If the task is currently running, it may not be deleted
532 if ($task->isExecutionRunning()) {
533 $this->addMessage($GLOBALS['LANG']->getLL('msg.maynotDeleteRunningTask'), t3lib_FlashMessage::ERROR);
534 } else {
535 if ($this->scheduler->removeTask($task)) {
536 $GLOBALS['BE_USER']->writeLog(4, 0, 0, 0, 'Scheduler task "%s" (UID: %s, Class: "%s") was deleted', array($task->getTaskTitle(), $task->getTaskUid(), $task->getTaskClassName()));
537 $this->addMessage($GLOBALS['LANG']->getLL('msg.deleteSuccess'));
538 } else {
539 $this->addMessage($GLOBALS['LANG']->getLL('msg.deleteError'), t3lib_FlashMessage::ERROR);
540 }
541 }
542 } catch (UnexpectedValueException $e) {
543 // The task could not be unserialized properly, simply delete the database record
544 $result = $GLOBALS['TYPO3_DB']->exec_DELETEquery('tx_scheduler_task', 'uid = ' . intval($this->submittedData['uid']));
545 if ($result) {
546 $this->addMessage($GLOBALS['LANG']->getLL('msg.deleteSuccess'));
547 } else {
548 $this->addMessage($GLOBALS['LANG']->getLL('msg.deleteError'), t3lib_FlashMessage::ERROR);
549 }
550 } catch (OutOfBoundsException $e) {
551 // The task was not found, for some reason
552 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $this->submittedData['uid']), t3lib_FlashMessage::ERROR);
553 }
554 }
555
556 /**
557 * Clears the registered running executions from the task
558 * Note that this doesn't actually stop the running script. It just unmarks
559 * all executions.
560 * TODO: find a way to really kill the running task
561 *
562 * @return void
563 */
564 protected function stopTask() {
565 try {
566 // Try to fetch the task and stop it
567 $task = $this->scheduler->fetchTask($this->submittedData['uid']);
568 if ($task->isExecutionRunning()) {
569 // If the task is indeed currently running, clear marked executions
570
571 $result = $task->unmarkAllExecutions();
572 if ($result) {
573 $this->addMessage($GLOBALS['LANG']->getLL('msg.stopSuccess'));
574 } else {
575 $this->addMessage($GLOBALS['LANG']->getLL('msg.stopError'), t3lib_FlashMessage::ERROR);
576 }
577 } else {
578 // The task is not running, nothing to unmark
579
580 $this->addMessage($GLOBALS['LANG']->getLL('msg.maynotStopNonRunningTask'), t3lib_FlashMessage::WARNING);
581 }
582 } catch (Exception $e) {
583 // The task was not found, for some reason
584 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $this->submittedData['uid']), t3lib_FlashMessage::ERROR);
585 }
586 }
587
588 /**
589 * Return a form to add a new task or edit an existing one
590 *
591 * @return string HTML form to add or edit a task
592 */
593 protected function editTask() {
594 $registeredClasses = self::getRegisteredClasses();
595 $content = '';
596 $taskInfo = array();
597 $task = NULL;
598 $process = 'edit';
599
600 if ($this->submittedData['uid'] > 0) {
601 // If editing, retrieve data for existing task
602 try {
603 $taskRecord = $this->scheduler->fetchTaskRecord($this->submittedData['uid']);
604 // If there's a registered execution, the task should not be edited
605 if (!empty($taskRecord['serialized_executions'])) {
606 $this->addMessage($GLOBALS['LANG']->getLL('msg.maynotEditRunningTask'), t3lib_FlashMessage::ERROR);
607 throw new LogicException('Runnings tasks cannot not be edited', 1251232849);
608 }
609 // Get the task object
610 /** @var $task tx_scheduler_Task */
611 $task = unserialize($taskRecord['serialized_task_object']);
612
613 // Set some task information
614 $class = $taskRecord['classname'];
615 $taskInfo['disable'] = $taskRecord['disable'];
616
617 // Check that the task object is valid
618 if ($this->scheduler->isValidTaskObject($task)) {
619 // The task object is valid, process with fetching current data
620
621 $taskInfo['class'] = $class;
622
623 // Get execution information
624 $taskInfo['start'] = $task->getExecution()->getStart();
625 $taskInfo['end'] = $task->getExecution()->getEnd();
626 $taskInfo['interval'] = $task->getExecution()->getInterval();
627 $taskInfo['croncmd'] = $task->getExecution()->getCronCmd();
628 $taskInfo['multiple'] = $task->getExecution()->getMultiple();
629
630 if (!empty($taskInfo['interval']) || !empty($taskInfo['croncmd'])) {
631 // Guess task type from the existing information
632 // If an interval or a cron command is defined, it's a recurring task
633
634 // FIXME: remove magic numbers for the type, use class constants instead
635 $taskInfo['type'] = 2;
636 $taskInfo['frequency'] = (empty($taskInfo['interval'])) ? $taskInfo['croncmd'] : $taskInfo['interval'];
637 } else {
638 // It's not a recurring task
639 // Make sure interval and cron command are both empty
640 $taskInfo['type'] = 1;
641 $taskInfo['frequency'] = '';
642 $taskInfo['end'] = 0;
643 }
644 } else {
645 // The task object is not valid
646
647 // Issue error message
648 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.invalidTaskClassEdit'), $class), t3lib_FlashMessage::ERROR);
649 // Initialize empty values
650 $taskInfo['start'] = 0;
651 $taskInfo['end'] = 0;
652 $taskInfo['frequency'] = '';
653 $taskInfo['multiple'] = FALSE;
654 $taskInfo['type'] = 1;
655 }
656 } catch (OutOfBoundsException $e) {
657 // Add a message and continue throwing the exception
658 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $this->submittedData['uid']), t3lib_FlashMessage::ERROR);
659 throw $e;
660 }
661 } else {
662 // If adding a new object, set some default values
663 $taskInfo['class'] = key($registeredClasses);
664 $taskInfo['type'] = 2;
665 $taskInfo['start'] = $GLOBALS['EXEC_TIME'];
666 $taskInfo['end'] = '';
667 $taskInfo['frequency'] = '';
668 $taskInfo['multiple'] = 0;
669 $process = 'add';
670 }
671
672 if (count($this->submittedData) > 0) {
673 // If some data was already submitted, use it to override
674 // existing data
675 $taskInfo = t3lib_div::array_merge_recursive_overrule($taskInfo, $this->submittedData);
676 }
677
678 // Get the extra fields to display for each task that needs some
679 $allAdditionalFields = array();
680 if ($process == 'add') {
681 foreach ($registeredClasses as $class => $registrationInfo) {
682 if (!empty($registrationInfo['provider'])) {
683 /** @var $providerObject tx_scheduler_AdditionalFieldProvider */
684 $providerObject = t3lib_div::getUserObj($registrationInfo['provider']);
685 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider) {
686 $additionalFields = $providerObject->getAdditionalFields($taskInfo, NULL, $this);
687 $allAdditionalFields = array_merge($allAdditionalFields, array($class => $additionalFields));
688 }
689 }
690 }
691
692 // In case of edit, get only the extra fields for the current task class
693 } else {
694 if (!empty($registeredClasses[$taskInfo['class']]['provider'])) {
695 $providerObject = t3lib_div::getUserObj($registeredClasses[$taskInfo['class']]['provider']);
696 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider) {
697 $allAdditionalFields[$taskInfo['class']] = $providerObject->getAdditionalFields($taskInfo, $task, $this);
698 }
699 }
700 }
701
702 // Load necessary JavaScript
703 /** @var $pageRenderer t3lib_PageRenderer */
704 $pageRenderer = $this->doc->getPageRenderer();
705 $pageRenderer->loadExtJS();
706 $pageRenderer->addJsFile(t3lib_extMgm::extRelPath('scheduler') . 'res/tx_scheduler_be.js');
707 $pageRenderer->addJsFile($this->backPath . '../t3lib/js/extjs/tceforms.js');
708 $pageRenderer->addJsFile($this->backPath . '../t3lib/js/extjs/ux/Ext.ux.DateTimePicker.js');
709
710 // Define settings for Date Picker
711 $typo3Settings = array(
712 'datePickerUSmode' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['USdateFormat'] ? 1 : 0,
713 'dateFormat' => array('j-n-Y', 'G:i j-n-Y'),
714 'dateFormatUS' => array('n-j-Y', 'G:i n-j-Y'),
715 );
716 $pageRenderer->addInlineSettingArray('', $typo3Settings);
717
718 // Define table layout for add/edit form
719 $tableLayout = array (
720 'table' => array ('<table border="0" cellspacing="0" cellpadding="0" id="edit_form" class="typo3-usersettings">', '</table>'),
721 );
722
723 // Define a style for hiding
724 // Some fields will be hidden when the task is not recurring
725 $style = '';
726 if ($taskInfo['type'] == 1) {
727 $style = ' style="display: none"';
728 }
729
730 // Start rendering the add/edit form
731 $content .= '<input type="hidden" name="tx_scheduler[uid]" value="' . $this->submittedData['uid'] . '" />';
732 $content .= '<input type="hidden" name="previousCMD" value="' . $this->CMD . '" />';
733 $content .= '<input type="hidden" name="CMD" value="save" />';
734
735 $table = array();
736 $tr = 0;
737 $defaultCell = array('<td class="td-input">', '</td>');
738
739 // Disable checkbox
740 $label = '<label for="task_disable">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:disable') . '</label>';
741 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_disable', $label);
742 $table[$tr][] =
743 '<input type="hidden" name="tx_scheduler[disable]" value="0" />
744 <input type="checkbox" name="tx_scheduler[disable]" value="1" id="task_disable"' . ($taskInfo['disable'] == 1 ? ' checked="checked"' : '') . ' />';
745 $tableLayout[$tr] = array (
746 'tr' => array('<tr id="task_disable_row">', '</tr>'),
747 'defCol' => $defaultCell,
748 '0' => array('<td class="td-label">', '</td>')
749 );
750 $tr++;
751
752 // Task class selector
753 $label = '<label for="task_class">' . $GLOBALS['LANG']->getLL('label.class') . '</label>';
754 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_class', $label);
755 // On editing, don't allow changing of the task class, unless it was not valid
756 if ($this->submittedData['uid'] > 0 && !empty($taskInfo['class'])) {
757 $cell = $registeredClasses[$taskInfo['class']]['title'] . ' (' . $registeredClasses[$taskInfo['class']]['extension'] . ')';
758 $cell .= '<input type="hidden" name="tx_scheduler[class]" id="task_class" value="' . $taskInfo['class'] . '" />';
759 } else {
760 $cell = '<select name="tx_scheduler[class]" id="task_class" class="wide" onchange="actOnChangedTaskClass(this)">';
761
762 // Group registered classes by classname
763 $groupedClasses = array();
764 foreach ($registeredClasses as $class => $classInfo) {
765 $groupedClasses[$classInfo['extension']][$class] = $classInfo;
766 }
767 ksort($groupedClasses);
768 // Loop on all grouped classes to display a selector
769 foreach ($groupedClasses as $extension => $class) {
770 $cell .= '<optgroup label="' . $extension .'">';
771 foreach ($groupedClasses[$extension] as $class => $classInfo) {
772 $selected = ($class == $taskInfo['class']) ? ' selected="selected"' : '';
773 $cell .= '<option value="' . $class . '"'
774 . 'title="' . $classInfo['description'] . '"'
775 . $selected . '>' . $classInfo['title'] . '</option>';
776 }
777 $cell .= '</optgroup>';
778 }
779 $cell .= '</select>';
780 }
781 $table[$tr][] = $cell;
782 // Make sure each row has a unique id, for manipulation with JS
783 $tableLayout[$tr] = array (
784 'tr' => array('<tr id="task_class_row">', '</tr>'),
785 'defCol' => $defaultCell,
786 '0' => array('<td class="td-label">', '</td>')
787 );
788 $tr++;
789
790 // Task type selector
791 $label = '<label for="task_type">' . $GLOBALS['LANG']->getLL('label.type') . '</label>';
792 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_type', $label);
793 $table[$tr][] =
794 '<select name="tx_scheduler[type]" id="task_type" onchange="actOnChangedTaskType(this)">' .
795 '<option value="1"' . ($taskInfo['type'] == 1 ? ' selected="selected"' : '') . '>' . $GLOBALS['LANG']->getLL('label.type.single') . '</option>' .
796 '<option value="2"' . ($taskInfo['type'] == 2 ? ' selected="selected"' : '') . '>' . $GLOBALS['LANG']->getLL('label.type.recurring') . '</option>' .
797 '</select>';
798 $tableLayout[$tr] = array (
799 'tr' => array('<tr id="task_type_row">', '</tr>'),
800 'defCol' => $defaultCell,
801 '0' => array('<td class="td-label">', '</td>'),
802 );
803 $tr++;
804
805 // Start date/time field
806 // NOTE: datetime fields need a special id naming scheme
807 $label = '<label for="tceforms-datetimefield-task_start">' . $GLOBALS['LANG']->getLL('label.start') . '</label>';
808 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_start', $label);
809 $table[$tr][] = '<input name="tx_scheduler[start]" type="text" id="tceforms-datetimefield-task_start" value="' . ((empty($taskInfo['start'])) ? '' : strftime('%H:%M %d-%m-%Y', $taskInfo['start'])) . '" />' .
810 t3lib_iconWorks::getSpriteIcon(
811 'actions-edit-pick-date',
812 array(
813 'style' => 'cursor:pointer;',
814 'id' => 'picker-tceforms-datetimefield-task_start'
815 )
816 );
817 $tableLayout[$tr] = array (
818 'tr' => array('<tr id="task_start_row">', '</tr>'),
819 'defCol' => $defaultCell,
820 '0' => array('<td class="td-label">', '</td>')
821 );
822 $tr++;
823
824 // End date/time field
825 // NOTE: datetime fields need a special id naming scheme
826 $label = '<label for="tceforms-datetimefield-task_end">' . $GLOBALS['LANG']->getLL('label.end') . '</label>';
827 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_end', $label);
828 $table[$tr][] = '<input name="tx_scheduler[end]" type="text" id="tceforms-datetimefield-task_end" value="' . ((empty($taskInfo['end'])) ? '' : strftime('%H:%M %d-%m-%Y', $taskInfo['end'])) . '" />' .
829 t3lib_iconWorks::getSpriteIcon(
830 'actions-edit-pick-date',
831 array(
832 'style' => 'cursor:pointer;',
833 'id' => 'picker-tceforms-datetimefield-task_end'
834 )
835 );
836 $tableLayout[$tr] = array (
837 'tr' => array('<tr id="task_end_row"' . $style . '>', '</tr>'),
838 'defCol' => $defaultCell,
839 '0' => array('<td class="td-label">', '</td>'),
840 );
841 $tr++;
842
843 // Frequency input field
844 $label = '<label for="task_frequency">' . $GLOBALS['LANG']->getLL('label.frequency.long') . '</label>';
845 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_frequency', $label);
846 $cell = '<input type="text" name="tx_scheduler[frequency]" id="task_frequency" value="' . htmlspecialchars($taskInfo['frequency']) . '" />';
847 $table[$tr][] = $cell;
848 $tableLayout[$tr] = array (
849 'tr' => array('<tr id="task_frequency_row"' . $style . '>', '</tr>'),
850 'defCol' => $defaultCell,
851 '0' => array('<td class="td-label">', '</td>'),
852 );
853 $tr++;
854
855 // Multiple execution selector
856 $label = '<label for="task_multiple">' . $GLOBALS['LANG']->getLL('label.parallel.long') . '</label>';
857 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_multiple', $label);
858 $table[$tr][] =
859 '<input type="hidden" name="tx_scheduler[multiple]" value="0" />
860 <input type="checkbox" name="tx_scheduler[multiple]" value="1" id="task_multiple"' . ($taskInfo['multiple'] == 1 ? ' checked="checked"' : '') . ' />';
861 $tableLayout[$tr] = array (
862 'tr' => array('<tr id="task_multiple_row"' . $style . '>', '</tr>'),
863 'defCol' => $defaultCell,
864 '0' => array('<td class="td-label">', '</td>')
865 );
866 $tr++;
867
868 // Display additional fields
869 foreach ($allAdditionalFields as $class => $fields) {
870 if ($class == $taskInfo['class']) {
871 $additionalFieldsStyle = '';
872 } else {
873 $additionalFieldsStyle = ' style="display: none"';
874 }
875
876 // Add each field to the display, if there are indeed any
877 if (isset($fields) && is_array($fields)) {
878 foreach ($fields as $fieldID => $fieldInfo) {
879 $label = '<label for="' . $fieldID . '">' . $GLOBALS['LANG']->sL($fieldInfo['label']) . '</label>';
880 $table[$tr][] = t3lib_BEfunc::wrapInHelp($fieldInfo['cshKey'], $fieldInfo['cshLabel'], $label);
881 $table[$tr][] = $fieldInfo['code'];
882 $tableLayout[$tr] = array (
883 'tr' => array('<tr id="' . $fieldID . '_row"' . $additionalFieldsStyle .' class="extraFields extra_fields_' . $class . '">', '</tr>'),
884 'defCol' => $defaultCell,
885 '0' => array('<td class="td-label">', '</td>')
886 );
887 $tr++;
888 }
889 }
890 }
891
892 // Render the add/edit task form
893 $content .= '<div style="float: left;"><div class="typo3-dyntabmenu-divs">';
894 $content .= $this->doc->table($table, $tableLayout);
895 $content .= '</div></div>';
896
897 $content .= '<div style="padding-top: 20px; clear: both;"></div><div><input type="submit" name="save" class="button" value="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:save', TRUE) . '" /> '
898 . '<input type="button" name="cancel" class="button" value="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:cancel', TRUE) . '" onclick="document.location=\'' . $GLOBALS['MCONF']['_'] . '\'" /></div>';
899
900 // Display information about server time usage
901 $content .= $this->displayServerTime();
902
903 return $content;
904 }
905
906 /**
907 * Execute all selected tasks
908 *
909 * @return void
910 */
911 protected function executeTasks() {
912 // Continue if some elements have been chosen for execution
913 if (isset($this->submittedData['execute']) && count($this->submittedData['execute']) > 0) {
914
915 // Get list of registered classes
916 $registeredClasses = self::getRegisteredClasses();
917
918 // Loop on all selected tasks
919 foreach ($this->submittedData['execute'] as $uid) {
920
921 try {
922 // Try fetching the task
923 $task = $this->scheduler->fetchTask($uid);
924 $class = get_class($task);
925 $name = $registeredClasses[$class]['title']. ' (' . $registeredClasses[$class]['extension'] . ')';
926 // Now try to execute it and report on outcome
927 try {
928 $result = $this->scheduler->executeTask($task);
929 if ($result) {
930 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.executed'), $name));
931 } else {
932 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.notExecuted'), $name), t3lib_FlashMessage::ERROR);
933 }
934 }
935 catch (Exception $e) {
936 // An exception was thrown, display its message as an error
937 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.executionFailed'), $name, $e->getMessage()), t3lib_FlashMessage::ERROR);
938 }
939 }
940 // The task was not found, for some reason
941 catch (OutOfBoundsException $e) {
942 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $uid), t3lib_FlashMessage::ERROR);
943 }
944 // The task object was not valid
945 catch (UnexpectedValueException $e) {
946 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.executionFailed'), $name, $e->getMessage()), t3lib_FlashMessage::ERROR);
947 }
948 }
949 // Record the run in the system registry
950 $this->scheduler->recordLastRun('manual');
951 // Make sure to switch to list view after execution
952 $this->CMD = 'list';
953 }
954 }
955
956 /**
957 * Assemble display of list of scheduled tasks
958 *
959 * @return string Table of pending tasks
960 */
961 protected function listTasks() {
962 // Define display format for dates
963 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
964 $content = '';
965
966 // Get list of registered classes
967 $registeredClasses = self::getRegisteredClasses();
968
969 // Get all registered tasks
970 $query = array(
971 'SELECT' => '*',
972 'FROM' => 'tx_scheduler_task',
973 'WHERE' => '1=1',
974 'ORDERBY' => 'nextexecution'
975 );
976
977 $res = $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($query);
978 $numRows = $GLOBALS['TYPO3_DB']->sql_num_rows($res);
979 // No tasks defined, display information message
980 if ($numRows == 0) {
981 /** @var t3lib_FlashMessage $flashMessage */
982 $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage',
983 $GLOBALS['LANG']->getLL('msg.noTasks'),
984 '',
985 t3lib_FlashMessage::INFO
986 );
987 $content .= $flashMessage->render();
988 } else {
989 // Load ExtJS framework and specific JS library
990 /** @var $pageRenderer t3lib_PageRenderer */
991 $pageRenderer = $this->doc->getPageRenderer();
992 $pageRenderer->loadExtJS();
993 $pageRenderer->addJsFile(t3lib_extMgm::extRelPath('scheduler') . 'res/tx_scheduler_be.js');
994
995 // Initialise table layout
996 $tableLayout = array(
997 'table' => array(
998 '<table border="0" cellspacing="0" cellpadding="0" class="typo3-dblist">', '</table>'
999 ),
1000 '0' => array(
1001 'tr' => array('<tr class="t3-row-header">', '</tr>'),
1002 'defCol' => array('<td>', '</td>'),
1003 '1' => array('<td style="width: 36px;">', '</td>'),
1004 '3' => array('<td colspan="2">', '</td>'),
1005 ),
1006 'defRow' => array(
1007 'tr' => array('<tr class="db_list_normal">', '</tr>'),
1008 'defCol' => array('<td>', '</td>'),
1009 '1' => array('<td class="right">', '</td>'),
1010 '2' => array('<td class="right">', '</td>'),
1011 )
1012 );
1013 $disabledTaskRow = array (
1014 'tr' => array('<tr class="db_list_normal disabled">', '</tr>'),
1015 'defCol' => array('<td>', '</td>'),
1016 '1' => array('<td class="right">', '</td>'),
1017 '2' => array('<td class="right">', '</td>'),
1018 );
1019 $rowWithSpan = array (
1020 'tr' => array('<tr class="db_list_normal">', '</tr>'),
1021 'defCol' => array('<td>', '</td>'),
1022 '1' => array('<td class="right">', '</td>'),
1023 '2' => array('<td class="right">', '</td>'),
1024 '3' => array('<td colspan="6">', '</td>'),
1025 );
1026 $table = array();
1027 $tr = 0;
1028
1029 // Header row
1030 $table[$tr][] = '<a href="#" onclick="toggleCheckboxes();" title="' . $GLOBALS['LANG']->getLL('label.checkAll', TRUE) . '" class="icon">' .
1031 t3lib_iconWorks::getSpriteIcon('actions-document-select') .
1032 '</a>';
1033 $table[$tr][] = '&nbsp;';
1034 $table[$tr][] = $GLOBALS['LANG']->getLL('label.id');
1035 $table[$tr][] = $GLOBALS['LANG']->getLL('task');
1036 $table[$tr][] = $GLOBALS['LANG']->getLL('label.type');
1037 $table[$tr][] = $GLOBALS['LANG']->getLL('label.frequency');
1038 $table[$tr][] = $GLOBALS['LANG']->getLL('label.parallel');
1039 $table[$tr][] = $GLOBALS['LANG']->getLL('label.lastExecution');
1040 $table[$tr][] = $GLOBALS['LANG']->getLL('label.nextExecution');
1041 $tr++;
1042
1043 // Loop on all tasks
1044 while (($schedulerRecord = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))) {
1045 // Define action icons
1046 $editAction = '<a href="' . $GLOBALS['MCONF']['_'] . '&CMD=edit&tx_scheduler[uid]=' . $schedulerRecord['uid'] . '" title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:edit', TRUE) . '" class="icon">' . t3lib_iconWorks::getSpriteIcon('actions-document-open') . '</a>';
1047 $deleteAction = '<a href="' . $GLOBALS['MCONF']['_'] . '&CMD=delete&tx_scheduler[uid]=' . $schedulerRecord['uid'] . '" onclick="return confirm(\'' . $GLOBALS['LANG']->getLL('msg.delete') . '\');" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:delete', TRUE) . '" class="icon">' . t3lib_iconWorks::getSpriteIcon('actions-edit-delete') . '</a>';
1048 $stopAction = '<a href="' . $GLOBALS['MCONF']['_'] . '&CMD=stop&tx_scheduler[uid]=' . $schedulerRecord['uid'] . '" onclick="return confirm(\'' . $GLOBALS['LANG']->getLL('msg.stop') . '\');" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:stop', TRUE) . '" class="icon"><img ' . t3lib_iconWorks::skinImg($this->backPath, t3lib_extMgm::extRelPath('scheduler') . '/res/gfx/stop.png') . ' alt="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:stop') . '" /></a>';
1049 // Define some default values
1050 $lastExecution = '-';
1051 $isRunning = FALSE;
1052 $executionStatus = 'scheduled';
1053 $executionStatusOutput = '';
1054 $name = '';
1055 $nextDate = '-';
1056 $execType = '-';
1057 $frequency = '-';
1058 $multiple = '-';
1059 $startExecutionElement = '&nbsp;';
1060
1061 // Restore the serialized task and pass it a reference to the scheduler object
1062 /** @var $task tx_scheduler_Task */
1063 $task = unserialize($schedulerRecord['serialized_task_object']);
1064
1065 // Assemble information about last execution
1066 $context = '';
1067 if (!empty($schedulerRecord['lastexecution_time'])) {
1068 $lastExecution = date($dateFormat, $schedulerRecord['lastexecution_time']);
1069 if ($schedulerRecord['lastexecution_context'] == 'CLI') {
1070 $context = $GLOBALS['LANG']->getLL('label.cron');
1071 } else {
1072 $context = $GLOBALS['LANG']->getLL('label.manual');
1073 }
1074 $lastExecution .= ' (' . $context . ')';
1075 }
1076
1077 if ($this->scheduler->isValidTaskObject($task)) {
1078 // The task object is valid
1079
1080 $name = htmlspecialchars($registeredClasses[$schedulerRecord['classname']]['title']. ' (' . $registeredClasses[$schedulerRecord['classname']]['extension'] . ')');
1081 $additionalInformation = $task->getAdditionalInformation();
1082 if (!empty($additionalInformation)) {
1083 $name .= '<br />[' . htmlspecialchars($additionalInformation) . ']';
1084 }
1085
1086 // Check if task currently has a running execution
1087 if (!empty($schedulerRecord['serialized_executions'])) {
1088 $isRunning = TRUE;
1089 $executionStatus = 'running';
1090 }
1091
1092 // Prepare display of next execution date
1093 // If task is currently running, date is not displayed (as next hasn't been calculated yet)
1094 // Also hide the date if task is disabled (the information doesn't make sense, as it will not run anyway)
1095 if ($isRunning || $schedulerRecord['disable'] == 1) {
1096 $nextDate = '-';
1097 }
1098 else {
1099 $nextDate = date($dateFormat, $schedulerRecord['nextexecution']);
1100 if (empty($schedulerRecord['nextexecution'])) {
1101 $nextDate = $GLOBALS['LANG']->getLL('none');
1102 } elseif ($schedulerRecord['nextexecution'] < $GLOBALS['EXEC_TIME']) {
1103 // Next execution is overdue, highlight date
1104 $nextDate = '<span class="late" title="' . $GLOBALS['LANG']->getLL('status.legend.scheduled') . '">' . $nextDate . '</span>';
1105 $executionStatus = 'late';
1106 }
1107 }
1108
1109 // Get execution type
1110 if ($task->getExecution()->getInterval() == 0 && $task->getExecution()->getCronCmd() == '') {
1111 $execType = $GLOBALS['LANG']->getLL('label.type.single');
1112 $frequency = '-';
1113 } else {
1114 $execType = $GLOBALS['LANG']->getLL('label.type.recurring');
1115 if ($task->getExecution()->getCronCmd() == '') {
1116 $frequency = $task->getExecution()->getInterval();
1117 } else {
1118 $frequency = $task->getExecution()->getCronCmd();
1119 }
1120 }
1121
1122 // Get multiple executions setting
1123 if ($task->getExecution()->getMultiple()) {
1124 $multiple = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes');
1125 } else {
1126 $multiple = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:no');
1127 }
1128
1129 // Define checkbox
1130 $startExecutionElement = '<input type="checkbox" name="tx_scheduler[execute][]" value="' . $schedulerRecord['uid'] . '" id="task_' . $schedulerRecord['uid'] . '" class="checkboxes" />';
1131
1132 // Show no action links (edit, delete) if task is running
1133 $actions = $editAction . $deleteAction;
1134 if ($isRunning) {
1135 $actions = $stopAction;
1136 }
1137
1138 // Check the disable status
1139 // Row is shown dimmed if task is disabled, unless it is still running
1140 if ($schedulerRecord['disable'] == 1 && !$isRunning) {
1141 $tableLayout[$tr] = $disabledTaskRow;
1142 $executionStatus = 'disabled';
1143 }
1144
1145 // Check if the last run failed
1146 $failureOutput = '';
1147 if (!empty($schedulerRecord['lastexecution_failure'])) {
1148 // Try to get the stored exception object
1149 /** @var $exception Exception */
1150 $exception = unserialize($schedulerRecord['lastexecution_failure']);
1151 // If the exception could not be unserialized, issue a default error message
1152 if ($exception === FALSE || ($exception instanceof __PHP_Incomplete_Class)) {
1153 $failureDetail = $GLOBALS['LANG']->getLL('msg.executionFailureDefault');
1154 } else {
1155 $failureDetail = sprintf($GLOBALS['LANG']->getLL('msg.executionFailureReport'), $exception->getCode(), $exception->getMessage());
1156 }
1157 $failureOutput = ' <img ' . t3lib_iconWorks::skinImg(t3lib_extMgm::extRelPath('scheduler'), 'res/gfx/status_failure.png') . ' alt="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.failure')) . '" title="' . htmlspecialchars($failureDetail) . '" />';
1158 }
1159
1160 // Format the execution status,
1161 // including failure feedback, if any
1162 $executionStatusOutput = '<img ' . t3lib_iconWorks::skinImg(t3lib_extMgm::extRelPath('scheduler'), 'res/gfx/status_' . $executionStatus . '.png') . ' id="executionstatus_' . $schedulerRecord['uid'] . '" alt="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.' . $executionStatus)) . '" title="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.legend.' . $executionStatus)) . '" />' . $failureOutput;
1163
1164 $table[$tr][] = $startExecutionElement;
1165 $table[$tr][] = $actions;
1166 $table[$tr][] = $schedulerRecord['uid'];
1167 $table[$tr][] = $executionStatusOutput;
1168 $table[$tr][] = $name;
1169 $table[$tr][] = $execType;
1170 $table[$tr][] = $frequency;
1171 $table[$tr][] = $multiple;
1172 $table[$tr][] = $lastExecution;
1173 $table[$tr][] = $nextDate;
1174
1175 } else {
1176 // The task object is not valid
1177 // Prepare to issue an error
1178
1179 /** @var t3lib_FlashMessage $flashMessage */
1180 $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage',
1181 sprintf($GLOBALS['LANG']->getLL('msg.invalidTaskClass'), $schedulerRecord['classname']),
1182 '',
1183 t3lib_FlashMessage::ERROR
1184 );
1185 $executionStatusOutput = $flashMessage->render();
1186
1187 $tableLayout[$tr] = $rowWithSpan;
1188 $table[$tr][] = $startExecutionElement;
1189 $table[$tr][] = $deleteAction;
1190 $table[$tr][] = $schedulerRecord['uid'];
1191 $table[$tr][] = $executionStatusOutput;
1192 }
1193
1194 $tr++;
1195 }
1196 // Render table
1197 $content .= $this->doc->table($table, $tableLayout);
1198
1199 $content .= '<input type="submit" class="button" name="go" id="scheduler_executeselected" value="' . $GLOBALS['LANG']->getLL('label.executeSelected') . '" />';
1200 }
1201
1202 if (!count($registeredClasses) > 0) {
1203 /** @var t3lib_FlashMessage $flashMessage */
1204 $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage',
1205 $GLOBALS['LANG']->getLL('msg.noTasksDefined'),
1206 '',
1207 t3lib_FlashMessage::INFO
1208 );
1209 $content .= $flashMessage->render();
1210 }
1211
1212 // Display legend, if there's at least one registered task
1213 // Also display information about the usage of server time
1214 if ($numRows > 0) {
1215 $content .= $this->doc->spacer(20);
1216 $content .= '<h4>' . $GLOBALS['LANG']->getLL('status.legend') . '</h4>
1217 <ul>
1218 <li><img ' . t3lib_iconWorks::skinImg(t3lib_extMgm::extRelPath('scheduler'), 'res/gfx/status_failure.png') . ' alt="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.failure')) . '" title="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.failure')) . '" /> ' . $GLOBALS['LANG']->getLL('status.legend.failure') . '</li>
1219 <li><img ' . t3lib_iconWorks::skinImg(t3lib_extMgm::extRelPath('scheduler'), 'res/gfx/status_late.png') . ' alt="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.late')) . '" title="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.late')) . '" /> ' . $GLOBALS['LANG']->getLL('status.legend.late') . '</li>
1220 <li><img ' . t3lib_iconWorks::skinImg(t3lib_extMgm::extRelPath('scheduler'), 'res/gfx/status_running.png') . ' alt="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.running')) . '" title="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.running')) . '" /> ' . $GLOBALS['LANG']->getLL('status.legend.running') . '</li>
1221 <li><img ' . t3lib_iconWorks::skinImg(t3lib_extMgm::extRelPath('scheduler'), 'res/gfx/status_scheduled.png') . ' alt="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.scheduled')) . '" title="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.scheduled')) . '" /> ' . $GLOBALS['LANG']->getLL('status.legend.scheduled') . '</li>
1222 <li><img ' . t3lib_iconWorks::skinImg(t3lib_extMgm::extRelPath('scheduler'), 'res/gfx/status_disabled.png') . ' alt="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.disabled')) . '" title="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.disabled')) . '" /> ' . $GLOBALS['LANG']->getLL('status.legend.disabled') . '</li>
1223 </ul>';
1224 $content .= $this->doc->spacer(10);
1225 $content .= $this->displayServerTime();
1226 }
1227
1228
1229 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1230
1231 return $content;
1232 }
1233
1234 /**
1235 * Saves a task specified in the backend form to the database
1236 *
1237 * @return void
1238 */
1239 protected function saveTask() {
1240
1241 // If a task is being edited fetch old task data
1242 if (!empty($this->submittedData['uid'])) {
1243 try {
1244 $taskRecord = $this->scheduler->fetchTaskRecord($this->submittedData['uid']);
1245 /** @var tx_scheduler_Task $task */
1246 $task = unserialize($taskRecord['serialized_task_object']);
1247 } catch (OutOfBoundsException $e) {
1248 // If the task could not be fetched, issue an error message
1249 // and exit early
1250 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $this->submittedData['uid']), t3lib_FlashMessage::ERROR);
1251 return;
1252 }
1253
1254 // Register single execution
1255 if ($this->submittedData['type'] == 1) {
1256 $task->registerSingleExecution($this->submittedData['start']);
1257
1258 // Else, it's a recurring task
1259 } else {
1260 if (!empty($this->submittedData['croncmd'])) {
1261 // Definition by cron-like syntax
1262
1263 $interval = 0;
1264 $cronCmd = $this->submittedData['croncmd'];
1265 } else {
1266 // Definition by interval
1267
1268 $interval = $this->submittedData['interval'];
1269 $cronCmd = '';
1270 }
1271
1272 // Register recurring execution
1273 $task->registerRecurringExecution($this->submittedData['start'], $interval, $this->submittedData['end'], $this->submittedData['multiple'], $cronCmd);
1274 }
1275
1276 // Set disable flag
1277 $task->setDisabled($this->submittedData['disable']);
1278
1279 // Save additional input values
1280 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) {
1281 /** @var $providerObject tx_scheduler_AdditionalFieldProvider */
1282 $providerObject = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']);
1283 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider) {
1284 $providerObject->saveAdditionalFields($this->submittedData, $task);
1285 }
1286 }
1287
1288 // Save to database
1289 $result = $this->scheduler->saveTask($task);
1290 if ($result) {
1291 $GLOBALS['BE_USER']->writeLog(4, 0, 0, 0, 'Scheduler task "%s" (UID: %s, Class: "%s") was updated', array($task->getTaskTitle(), $task->getTaskUid(), $task->getTaskClassName()));
1292 $this->addMessage($GLOBALS['LANG']->getLL('msg.updateSuccess'));
1293 } else {
1294 $this->addMessage($GLOBALS['LANG']->getLL('msg.updateError'), t3lib_FlashMessage::ERROR);
1295 }
1296 } else {
1297 // A new task is being created
1298
1299 // Create an instance of chosen class
1300 $task = t3lib_div::makeInstance($this->submittedData['class']);
1301
1302 if ($this->submittedData['type'] == 1) {
1303 // Set up single execution
1304 $task->registerSingleExecution($this->submittedData['start']);
1305 } else {
1306 // Set up recurring execution
1307 $task->registerRecurringExecution($this->submittedData['start'], $this->submittedData['interval'], $this->submittedData['end'], $this->submittedData['multiple'], $this->submittedData['croncmd']);
1308 }
1309
1310 // Save additional input values
1311 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) {
1312 /** @var $providerObject tx_scheduler_AdditionalFieldProvider */
1313 $providerObject = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']);
1314 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider) {
1315 $providerObject->saveAdditionalFields($this->submittedData, $task);
1316 }
1317 }
1318
1319 // Set disable flag
1320 $task->setDisabled($this->submittedData['disable']);
1321
1322 // Add to database
1323 $result = $this->scheduler->addTask($task);
1324 if ($result) {
1325 $GLOBALS['BE_USER']->writeLog(4, 0, 0, 0, 'Scheduler task "%s" (UID: %s, Class: "%s") was added', array($task->getTaskTitle(), $task->getTaskUid(), $task->getTaskClassName()));
1326 $this->addMessage($GLOBALS['LANG']->getLL('msg.addSuccess'));
1327 } else {
1328 $this->addMessage($GLOBALS['LANG']->getLL('msg.addError'), t3lib_FlashMessage::ERROR);
1329 }
1330 }
1331 }
1332
1333
1334 /*************************
1335 *
1336 * INPUT PROCESSING UTILITIES
1337 *
1338 *************************/
1339
1340 /**
1341 * Checks the submitted data and performs some pre-processing on it
1342 *
1343 * @return boolean TRUE if everything was ok, FALSE otherwise
1344 */
1345 protected function preprocessData() {
1346 $result = TRUE;
1347
1348 // Validate id
1349 $this->submittedData['uid'] = (empty($this->submittedData['uid'])) ? 0 : intval($this->submittedData['uid']);
1350
1351 // Validate selected task class
1352 if (!class_exists($this->submittedData['class'])) {
1353 $this->addMessage($GLOBALS['LANG']->getLL('msg.noTaskClassFound'), t3lib_FlashMessage::ERROR);
1354 }
1355
1356 // Check start date
1357 if (empty($this->submittedData['start'])) {
1358 $this->addMessage($GLOBALS['LANG']->getLL('msg.noStartDate'), t3lib_FlashMessage::ERROR);
1359 $result = FALSE;
1360 } else {
1361 try {
1362 $timestamp = $this->checkDate($this->submittedData['start']);
1363 $this->submittedData['start'] = $timestamp;
1364 } catch (Exception $e) {
1365 $this->addMessage($GLOBALS['LANG']->getLL('msg.invalidStartDate'), t3lib_FlashMessage::ERROR);
1366 $result = FALSE;
1367 }
1368 }
1369
1370 // Check end date, if recurring task
1371 if ($this->submittedData['type'] == 2 && !empty($this->submittedData['end'])) {
1372 try {
1373 $timestamp = $this->checkDate($this->submittedData['end']);
1374 $this->submittedData['end'] = $timestamp;
1375
1376 if ($this->submittedData['end'] < $this->submittedData['start']) {
1377 $this->addMessage($GLOBALS['LANG']->getLL('msg.endDateSmallerThanStartDate'), t3lib_FlashMessage::ERROR);
1378 $result = FALSE;
1379 }
1380 } catch (Exception $e) {
1381 $this->addMessage($GLOBALS['LANG']->getLL('msg.invalidEndDate'), t3lib_FlashMessage::ERROR);
1382 $result = FALSE;
1383 }
1384 }
1385
1386 // Set default values for interval and cron command
1387 $this->submittedData['interval'] = 0;
1388 $this->submittedData['croncmd'] = '';
1389
1390 // Check type and validity of frequency, if recurring
1391 if ($this->submittedData['type'] == 2) {
1392 $frequency = trim($this->submittedData['frequency']);
1393
1394 if (empty($frequency)) {
1395 // Empty frequency, not valid
1396
1397 $this->addMessage($GLOBALS['LANG']->getLL('msg.noFrequency'), t3lib_FlashMessage::ERROR);
1398 $result = FALSE;
1399 } else {
1400 $cronErrorCode = 0;
1401 $cronErrorMessage = '';
1402
1403 // Try interpreting the cron command
1404 try {
1405 tx_scheduler_CronCmd_Normalize::normalize($frequency);
1406 $this->submittedData['croncmd'] = $frequency;
1407 }
1408 // If the cron command was invalid, we may still have a valid frequency in seconds
1409 catch (Exception $e) {
1410 // Store the exception's result
1411 $cronErrorMessage = $e->getMessage();
1412 $cronErrorCode = $e->getCode();
1413 // Check if the frequency is a valid number
1414 // If yes, assume it is a frequency in seconds, and unset cron error code
1415 if (is_numeric($frequency)) {
1416 $this->submittedData['interval'] = intval($frequency);
1417 unset($cronErrorCode);
1418 }
1419 }
1420 // If there's a cron error code, issue validation error message
1421 if (!empty($cronErrorCode)) {
1422 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.frequencyError'), $cronErrorMessage, $cronErrorCode), t3lib_FlashMessage::ERROR);
1423 $result = FALSE;
1424 }
1425 }
1426 }
1427
1428 // Validate additional input fields
1429 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) {
1430 $providerObject = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']);
1431 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider) {
1432 // The validate method will return TRUE if all went well, but that must not
1433 // override previous FALSE values => AND the returned value with the existing one
1434 $result &= $providerObject->validateAdditionalFields($this->submittedData, $this);
1435 }
1436 }
1437
1438 return $result;
1439 }
1440
1441 /**
1442 * This method checks whether the given string can be considered a valid date or not
1443 * Allowed values are anything that matches natural language (see PHP function strtotime())
1444 * or TYPO3's date syntax: HH:ii yyyy-mm-dd
1445 * If the string is a valid date, the corresponding timestamp is returned.
1446 * Otherwise an exception is thrown
1447 *
1448 * @param string $string String to check
1449 * @return integer Unix timestamp
1450 */
1451 public function checkDate($string) {
1452 // Try with strtotime
1453 $timestamp = strtotime($string);
1454
1455 // That failed. Try TYPO3's standard date/time input format
1456 if ($timestamp === FALSE) {
1457 // Split time and date
1458 $dateParts = t3lib_div::trimExplode(' ', $string, TRUE);
1459 // Proceed if there are indeed two parts
1460 // Extract each component of date and time
1461 if (count($dateParts) == 2) {
1462 list($time, $date) = $dateParts;
1463 list($hour, $minutes) = t3lib_div::trimExplode(':', $time, TRUE);
1464 list($day, $month, $year) = t3lib_div::trimExplode('-', $date, TRUE);
1465 // Get a timestamp from all these parts
1466 $timestamp = @mktime($hour, $minutes, 0, $month, $day, $year);
1467 }
1468 // If the timestamp is still FALSE, throw an exception
1469 if ($timestamp === FALSE) {
1470 throw new InvalidArgumentException('"' . $string . '" seems not to be a correct date.', 1294587694);
1471 }
1472 }
1473 return $timestamp;
1474 }
1475
1476 /*************************
1477 *
1478 * APPLICATION LOGIC UTILITIES
1479 *
1480 *************************/
1481
1482 /**
1483 * This method is used to add a message to the internal queue
1484 *
1485 * @param string $message The message itself
1486 * @param integer $severity Message level (according to t3lib_FlashMessage class constants)
1487 * @return void
1488 */
1489 public function addMessage($message, $severity = t3lib_FlashMessage::OK) {
1490 $message = t3lib_div::makeInstance(
1491 't3lib_FlashMessage',
1492 $message,
1493 '',
1494 $severity
1495 );
1496
1497 t3lib_FlashMessageQueue::addMessage($message);
1498 }
1499
1500 /**
1501 * This method a list of all classes that have been registered with the Scheduler
1502 * For each item the following information is provided, as an associative array:
1503 *
1504 * ['extension'] => Key of the extension which provides the class
1505 * ['filename'] => Path to the file containing the class
1506 * ['title'] => String (possibly localized) containing a human-readable name for the class
1507 * ['provider'] => Name of class that implements the interface for additional fields, if necessary
1508 *
1509 * The name of the class itself is used as the key of the list array
1510 *
1511 * @return array List of registered classes
1512 */
1513 protected static function getRegisteredClasses() {
1514 $list = array();
1515 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'])) {
1516 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'] as $class => $registrationInformation) {
1517
1518 $title = isset($registrationInformation['title']) ? $GLOBALS['LANG']->sL($registrationInformation['title']) : '';
1519 $description = isset($registrationInformation['description']) ? $GLOBALS['LANG']->sL($registrationInformation['description']) : '';
1520
1521 $list[$class] = array(
1522 'extension' => $registrationInformation['extension'],
1523 'title' => $title,
1524 'description' => $description,
1525 'provider' => isset($registrationInformation['additionalFields']) ? $registrationInformation['additionalFields'] : ''
1526 );
1527 }
1528 }
1529
1530 return $list;
1531 }
1532
1533
1534 /*************************
1535 *
1536 * RENDERING UTILITIES
1537 *
1538 *************************/
1539
1540 /**
1541 * Gets the filled markers that are used in the HTML template.
1542 *
1543 * @return array The filled marker array
1544 */
1545 protected function getTemplateMarkers() {
1546 $markers = array(
1547 'CSH' => t3lib_BEfunc::wrapInHelp('_MOD_tools_txschedulerM1', ''),
1548 'FUNC_MENU' => $this->getFunctionMenu(),
1549 'CONTENT' => $this->content,
1550 'TITLE' => $GLOBALS['LANG']->getLL('title'),
1551 );
1552
1553 return $markers;
1554 }
1555
1556 /**
1557 * Gets the function menu selector for this backend module.
1558 *
1559 * @return string The HTML representation of the function menu selector
1560 */
1561 protected function getFunctionMenu() {
1562 $functionMenu = t3lib_BEfunc::getFuncMenu(
1563 0,
1564 'SET[function]',
1565 $this->MOD_SETTINGS['function'],
1566 $this->MOD_MENU['function']
1567 );
1568
1569 return $functionMenu;
1570 }
1571
1572 /**
1573 * Gets the buttons that shall be rendered in the docHeader.
1574 *
1575 * @return array Available buttons for the docHeader
1576 */
1577 protected function getDocHeaderButtons() {
1578 $buttons = array(
1579 'addtask' => '',
1580 'reload' => '',
1581 'shortcut' => $this->getShortcutButton(),
1582 );
1583
1584 if (empty($this->CMD) || $this->CMD == 'list') {
1585 $buttons['reload'] = '<a href="' . $GLOBALS['MCONF']['_'] . '" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.reload', TRUE) . '">' .
1586 t3lib_iconWorks::getSpriteIcon('actions-system-refresh') .
1587 '</a>';
1588 if ($this->MOD_SETTINGS['function'] === 'scheduler' && count(self::getRegisteredClasses())) {
1589 $link = $GLOBALS['MCONF']['_'] . '&CMD=add';
1590 $image = '<img ' . t3lib_iconWorks::skinImg($this->backPath, 'gfx/new_el.gif') .
1591 ' alt="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:new', TRUE) . '" />';
1592 $buttons['addtask'] = '<a href="' . htmlspecialchars($link) . '" ' .
1593 'title="' . $GLOBALS['LANG']->getLL('action.add') . '">' . $image . '</a>';
1594 }
1595 }
1596
1597 return $buttons;
1598 }
1599
1600 /**
1601 * Gets the button to set a new shortcut in the backend (if current user is allowed to).
1602 *
1603 * @return string HTML representation of the shortcut button
1604 */
1605 protected function getShortcutButton() {
1606 $result = '';
1607 if ($GLOBALS['BE_USER']->mayMakeShortcut()) {
1608 $result = $this->doc->makeShortcutIcon('', 'function', $this->MCONF['name']);
1609 }
1610
1611 return $result;
1612 }
1613 }
1614
1615 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/scheduler/class.tx_scheduler_module.php'])) {
1616 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/scheduler/class.tx_scheduler_module.php']);
1617 }
1618 ?>