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