[FEATURE] Group task list in scheduler by extension
[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
761 // Group registered classes by classname
762 $groupedClasses = array();
763 foreach ($registeredClasses as $class => $classInfo) {
764 $groupedClasses[$classInfo['extension']][$class] = $classInfo;
765 }
766 ksort($groupedClasses);
767 // Loop on all grouped classes to display a selector
768 foreach ($groupedClasses as $extension => $class) {
769 $cell .= '<optgroup label="' . $extension .'">';
770 foreach ($groupedClasses[$extension] as $class => $classInfo) {
771 $selected = ($class == $taskInfo['class']) ? ' selected="selected"' : '';
772 $cell .= '<option value="' . $class . '"'
773 . 'title="' . $classInfo['description'] . '"'
774 . $selected . '>' . $classInfo['title'] . '</option>';
775 }
776 $cell .= '</optgroup>';
777 }
778 $cell .= '</select>';
779 }
780 $table[$tr][] = $cell;
781 // Make sure each row has a unique id, for manipulation with JS
782 $tableLayout[$tr] = array (
783 'tr' => array('<tr id="task_class_row">', '</tr>'),
784 'defCol' => $defaultCell,
785 '0' => array('<td class="td-label">', '</td>')
786 );
787 $tr++;
788
789 // Task type selector
790 $label = '<label for="task_type">' . $GLOBALS['LANG']->getLL('label.type') . '</label>';
791 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_type', $label);
792 $table[$tr][] =
793 '<select name="tx_scheduler[type]" id="task_type" onchange="actOnChangedTaskType(this)">' .
794 '<option value="1"' . ($taskInfo['type'] == 1 ? ' selected="selected"' : '') . '>' . $GLOBALS['LANG']->getLL('label.type.single') . '</option>' .
795 '<option value="2"' . ($taskInfo['type'] == 2 ? ' selected="selected"' : '') . '>' . $GLOBALS['LANG']->getLL('label.type.recurring') . '</option>' .
796 '</select>';
797 $tableLayout[$tr] = array (
798 'tr' => array('<tr id="task_type_row">', '</tr>'),
799 'defCol' => $defaultCell,
800 '0' => array('<td class="td-label">', '</td>'),
801 );
802 $tr++;
803
804 // Start date/time field
805 // NOTE: datetime fields need a special id naming scheme
806 $label = '<label for="tceforms-datetimefield-task_start">' . $GLOBALS['LANG']->getLL('label.start') . '</label>';
807 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_start', $label);
808 $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'])) . '" />' .
809 t3lib_iconWorks::getSpriteIcon(
810 'actions-edit-pick-date',
811 array(
812 'style' => 'cursor:pointer;',
813 'id' => 'picker-tceforms-datetimefield-task_start'
814 )
815 );
816 $tableLayout[$tr] = array (
817 'tr' => array('<tr id="task_start_row">', '</tr>'),
818 'defCol' => $defaultCell,
819 '0' => array('<td class="td-label">', '</td>')
820 );
821 $tr++;
822
823 // End date/time field
824 // NOTE: datetime fields need a special id naming scheme
825 $label = '<label for="tceforms-datetimefield-task_end">' . $GLOBALS['LANG']->getLL('label.end') . '</label>';
826 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_end', $label);
827 $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'])) . '" />' .
828 t3lib_iconWorks::getSpriteIcon(
829 'actions-edit-pick-date',
830 array(
831 'style' => 'cursor:pointer;',
832 'id' => 'picker-tceforms-datetimefield-task_end'
833 )
834 );
835 $tableLayout[$tr] = array (
836 'tr' => array('<tr id="task_end_row"' . $style . '>', '</tr>'),
837 'defCol' => $defaultCell,
838 '0' => array('<td class="td-label">', '</td>'),
839 );
840 $tr++;
841
842 // Frequency input field
843 $label = '<label for="task_frequency">' . $GLOBALS['LANG']->getLL('label.frequency.long') . '</label>';
844 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_frequency', $label);
845 $cell = '<input type="text" name="tx_scheduler[frequency]" id="task_frequency" value="' . $taskInfo['frequency'] . '" />';
846 $table[$tr][] = $cell;
847 $tableLayout[$tr] = array (
848 'tr' => array('<tr id="task_frequency_row"' . $style . '>', '</tr>'),
849 'defCol' => $defaultCell,
850 '0' => array('<td class="td-label">', '</td>'),
851 );
852 $tr++;
853
854 // Multiple execution selector
855 $label = '<label for="task_multiple">' . $GLOBALS['LANG']->getLL('label.parallel.long') . '</label>';
856 $table[$tr][] = t3lib_BEfunc::wrapInHelp($this->cshKey, 'task_multiple', $label);
857 $table[$tr][] =
858 '<input type="hidden" name="tx_scheduler[multiple]" value="0" />
859 <input type="checkbox" name="tx_scheduler[multiple]" value="1" id="task_multiple"' . ($taskInfo['multiple'] == 1 ? ' checked="checked"' : '') . ' />';
860 $tableLayout[$tr] = array (
861 'tr' => array('<tr id="task_multiple_row"' . $style . '>', '</tr>'),
862 'defCol' => $defaultCell,
863 '0' => array('<td class="td-label">', '</td>')
864 );
865 $tr++;
866
867 // Display additional fields
868 foreach ($allAdditionalFields as $class => $fields) {
869 if ($class == $taskInfo['class']) {
870 $additionalFieldsStyle = '';
871 } else {
872 $additionalFieldsStyle = ' style="display: none"';
873 }
874
875 // Add each field to the display, if there are indeed any
876 if (isset($fields) && is_array($fields)) {
877 foreach ($fields as $fieldID => $fieldInfo) {
878 $label = '<label for="' . $fieldID . '">' . $GLOBALS['LANG']->sL($fieldInfo['label']) . '</label>';
879 $table[$tr][] = t3lib_BEfunc::wrapInHelp($fieldInfo['cshKey'], $fieldInfo['cshLabel'], $label);
880 $table[$tr][] = $fieldInfo['code'];
881 $tableLayout[$tr] = array (
882 'tr' => array('<tr id="' . $fieldID . '_row"' . $additionalFieldsStyle .' class="extraFields extra_fields_' . $class . '">', '</tr>'),
883 'defCol' => $defaultCell,
884 '0' => array('<td class="td-label">', '</td>')
885 );
886 $tr++;
887 }
888 }
889 }
890
891 // Render the add/edit task form
892 $content .= '<div style="float: left;"><div class="typo3-dyntabmenu-divs">';
893 $content .= $this->doc->table($table, $tableLayout);
894 $content .= '</div></div>';
895
896 $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) . '" /> '
897 . '<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>';
898
899 // Display information about server time usage
900 $content .= $this->displayServerTime();
901
902 return $content;
903 }
904
905 /**
906 * Execute all selected tasks
907 *
908 * @return void
909 */
910 protected function executeTasks() {
911 // Continue if some elements have been chosen for execution
912 if (isset($this->submittedData['execute']) && count($this->submittedData['execute']) > 0) {
913
914 // Get list of registered classes
915 $registeredClasses = self::getRegisteredClasses();
916
917 // Loop on all selected tasks
918 foreach ($this->submittedData['execute'] as $uid) {
919
920 try {
921 // Try fetching the task
922 $task = $this->scheduler->fetchTask($uid);
923 $class = get_class($task);
924 $name = $registeredClasses[$class]['title']. ' (' . $registeredClasses[$class]['extension'] . ')';
925 // Now try to execute it and report on outcome
926 try {
927 $result = $this->scheduler->executeTask($task);
928 if ($result) {
929 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.executed'), $name));
930 } else {
931 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.notExecuted'), $name), t3lib_FlashMessage::ERROR);
932 }
933 }
934 catch (Exception $e) {
935 // An exception was thrown, display its message as an error
936 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.executionFailed'), $name, $e->getMessage()), t3lib_FlashMessage::ERROR);
937 }
938 }
939 // The task was not found, for some reason
940 catch (OutOfBoundsException $e) {
941 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $uid), t3lib_FlashMessage::ERROR);
942 }
943 // The task object was not valid
944 catch (UnexpectedValueException $e) {
945 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.executionFailed'), $name, $e->getMessage()), t3lib_FlashMessage::ERROR);
946 }
947 }
948 // Record the run in the system registry
949 $this->scheduler->recordLastRun('manual');
950 // Make sure to switch to list view after execution
951 $this->CMD = 'list';
952 }
953 }
954
955 /**
956 * Assemble display of list of scheduled tasks
957 *
958 * @return string Table of pending tasks
959 */
960 protected function listTasks() {
961 // Define display format for dates
962 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
963 $content = '';
964
965 // Get list of registered classes
966 $registeredClasses = self::getRegisteredClasses();
967
968 // Get all registered tasks
969 $query = array(
970 'SELECT' => '*',
971 'FROM' => 'tx_scheduler_task',
972 'WHERE' => '1=1',
973 'ORDERBY' => 'nextexecution'
974 );
975
976 $res = $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($query);
977 $numRows = $GLOBALS['TYPO3_DB']->sql_num_rows($res);
978 // No tasks defined, display information message
979 if ($numRows == 0) {
980 /** @var t3lib_FlashMessage $flashMessage */
981 $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage',
982 $GLOBALS['LANG']->getLL('msg.noTasks'),
983 '',
984 t3lib_FlashMessage::INFO
985 );
986 $content .= $flashMessage->render();
987 } else {
988 // Load ExtJS framework and specific JS library
989 /** @var $pageRenderer t3lib_PageRenderer */
990 $pageRenderer = $this->doc->getPageRenderer();
991 $pageRenderer->loadExtJS();
992 $pageRenderer->addJsFile(t3lib_extMgm::extRelPath('scheduler') . 'res/tx_scheduler_be.js');
993
994 // Initialise table layout
995 $tableLayout = array(
996 'table' => array(
997 '<table border="0" cellspacing="0" cellpadding="0" class="typo3-dblist">', '</table>'
998 ),
999 '0' => array(
1000 'tr' => array('<tr class="t3-row-header">', '</tr>'),
1001 'defCol' => array('<td>', '</td>'),
1002 '1' => array('<td style="width: 36px;">', '</td>'),
1003 '3' => array('<td colspan="2">', '</td>'),
1004 ),
1005 'defRow' => 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 )
1011 );
1012 $disabledTaskRow = array (
1013 'tr' => array('<tr class="db_list_normal disabled">', '</tr>'),
1014 'defCol' => array('<td>', '</td>'),
1015 '1' => array('<td class="right">', '</td>'),
1016 '2' => array('<td class="right">', '</td>'),
1017 );
1018 $rowWithSpan = array (
1019 'tr' => array('<tr class="db_list_normal">', '</tr>'),
1020 'defCol' => array('<td>', '</td>'),
1021 '1' => array('<td class="right">', '</td>'),
1022 '2' => array('<td class="right">', '</td>'),
1023 '3' => array('<td colspan="6">', '</td>'),
1024 );
1025 $table = array();
1026 $tr = 0;
1027
1028 // Header row
1029 $table[$tr][] = '<a href="#" onclick="toggleCheckboxes();" title="' . $GLOBALS['LANG']->getLL('label.checkAll', TRUE) . '" class="icon">' .
1030 t3lib_iconWorks::getSpriteIcon('actions-document-select') .
1031 '</a>';
1032 $table[$tr][] = '&nbsp;';
1033 $table[$tr][] = $GLOBALS['LANG']->getLL('label.id');
1034 $table[$tr][] = $GLOBALS['LANG']->getLL('task');
1035 $table[$tr][] = $GLOBALS['LANG']->getLL('label.type');
1036 $table[$tr][] = $GLOBALS['LANG']->getLL('label.frequency');
1037 $table[$tr][] = $GLOBALS['LANG']->getLL('label.parallel');
1038 $table[$tr][] = $GLOBALS['LANG']->getLL('label.lastExecution');
1039 $table[$tr][] = $GLOBALS['LANG']->getLL('label.nextExecution');
1040 $tr++;
1041
1042 // Loop on all tasks
1043 while (($schedulerRecord = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))) {
1044 // Define action icons
1045 $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>';
1046 $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>';
1047 $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>';
1048 // Define some default values
1049 $lastExecution = '-';
1050 $isRunning = FALSE;
1051 $executionStatus = 'scheduled';
1052 $executionStatusOutput = '';
1053 $name = '';
1054 $nextDate = '-';
1055 $execType = '-';
1056 $frequency = '-';
1057 $multiple = '-';
1058 $startExecutionElement = '&nbsp;';
1059
1060 // Restore the serialized task and pass it a reference to the scheduler object
1061 /** @var $task tx_scheduler_Task */
1062 $task = unserialize($schedulerRecord['serialized_task_object']);
1063
1064 // Assemble information about last execution
1065 $context = '';
1066 if (!empty($schedulerRecord['lastexecution_time'])) {
1067 $lastExecution = date($dateFormat, $schedulerRecord['lastexecution_time']);
1068 if ($schedulerRecord['lastexecution_context'] == 'CLI') {
1069 $context = $GLOBALS['LANG']->getLL('label.cron');
1070 } else {
1071 $context = $GLOBALS['LANG']->getLL('label.manual');
1072 }
1073 $lastExecution .= ' (' . $context . ')';
1074 }
1075
1076 if ($this->scheduler->isValidTaskObject($task)) {
1077 // The task object is valid
1078
1079 $name = htmlspecialchars($registeredClasses[$schedulerRecord['classname']]['title']. ' (' . $registeredClasses[$schedulerRecord['classname']]['extension'] . ')');
1080 $additionalInformation = $task->getAdditionalInformation();
1081 if (!empty($additionalInformation)) {
1082 $name .= '<br />[' . htmlspecialchars($additionalInformation) . ']';
1083 }
1084
1085 // Check if task currently has a running execution
1086 if (!empty($schedulerRecord['serialized_executions'])) {
1087 $isRunning = TRUE;
1088 $executionStatus = 'running';
1089 }
1090
1091 // Prepare display of next execution date
1092 // If task is currently running, date is not displayed (as next hasn't been calculated yet)
1093 // Also hide the date if task is disabled (the information doesn't make sense, as it will not run anyway)
1094 if ($isRunning || $schedulerRecord['disable'] == 1) {
1095 $nextDate = '-';
1096 }
1097 else {
1098 $nextDate = date($dateFormat, $schedulerRecord['nextexecution']);
1099 if (empty($schedulerRecord['nextexecution'])) {
1100 $nextDate = $GLOBALS['LANG']->getLL('none');
1101 } elseif ($schedulerRecord['nextexecution'] < $GLOBALS['EXEC_TIME']) {
1102 // Next execution is overdue, highlight date
1103 $nextDate = '<span class="late" title="' . $GLOBALS['LANG']->getLL('status.legend.scheduled') . '">' . $nextDate . '</span>';
1104 $executionStatus = 'late';
1105 }
1106 }
1107
1108 // Get execution type
1109 if ($task->getExecution()->getInterval() == 0 && $task->getExecution()->getCronCmd() == '') {
1110 $execType = $GLOBALS['LANG']->getLL('label.type.single');
1111 $frequency = '-';
1112 } else {
1113 $execType = $GLOBALS['LANG']->getLL('label.type.recurring');
1114 if ($task->getExecution()->getCronCmd() == '') {
1115 $frequency = $task->getExecution()->getInterval();
1116 } else {
1117 $frequency = $task->getExecution()->getCronCmd();
1118 }
1119 }
1120
1121 // Get multiple executions setting
1122 if ($task->getExecution()->getMultiple()) {
1123 $multiple = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes');
1124 } else {
1125 $multiple = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:no');
1126 }
1127
1128 // Define checkbox
1129 $startExecutionElement = '<input type="checkbox" name="tx_scheduler[execute][]" value="' . $schedulerRecord['uid'] . '" id="task_' . $schedulerRecord['uid'] . '" class="checkboxes" />';
1130
1131 // Show no action links (edit, delete) if task is running
1132 $actions = $editAction . $deleteAction;
1133 if ($isRunning) {
1134 $actions = $stopAction;
1135 }
1136
1137 // Check the disable status
1138 // Row is shown dimmed if task is disabled, unless it is still running
1139 if ($schedulerRecord['disable'] == 1 && !$isRunning) {
1140 $tableLayout[$tr] = $disabledTaskRow;
1141 $executionStatus = 'disabled';
1142 }
1143
1144 // Check if the last run failed
1145 $failureOutput = '';
1146 if (!empty($schedulerRecord['lastexecution_failure'])) {
1147 // Try to get the stored exception object
1148 /** @var $exception Exception */
1149 $exception = unserialize($schedulerRecord['lastexecution_failure']);
1150 // If the exception could not be unserialized, issue a default error message
1151 if ($exception === FALSE || ($exception instanceof __PHP_Incomplete_Class)) {
1152 $failureDetail = $GLOBALS['LANG']->getLL('msg.executionFailureDefault');
1153 } else {
1154 $failureDetail = sprintf($GLOBALS['LANG']->getLL('msg.executionFailureReport'), $exception->getCode(), $exception->getMessage());
1155 }
1156 $failureOutput = ' <img ' . t3lib_iconWorks::skinImg(t3lib_extMgm::extRelPath('scheduler'), 'res/gfx/status_failure.png') . ' alt="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.failure')) . '" title="' . htmlspecialchars($failureDetail) . '" />';
1157 }
1158
1159 // Format the execution status,
1160 // including failure feedback, if any
1161 $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;
1162
1163 $table[$tr][] = $startExecutionElement;
1164 $table[$tr][] = $actions;
1165 $table[$tr][] = $schedulerRecord['uid'];
1166 $table[$tr][] = $executionStatusOutput;
1167 $table[$tr][] = $name;
1168 $table[$tr][] = $execType;
1169 $table[$tr][] = $frequency;
1170 $table[$tr][] = $multiple;
1171 $table[$tr][] = $lastExecution;
1172 $table[$tr][] = $nextDate;
1173
1174 } else {
1175 // The task object is not valid
1176 // Prepare to issue an error
1177
1178 /** @var t3lib_FlashMessage $flashMessage */
1179 $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage',
1180 sprintf($GLOBALS['LANG']->getLL('msg.invalidTaskClass'), $schedulerRecord['classname']),
1181 '',
1182 t3lib_FlashMessage::ERROR
1183 );
1184 $executionStatusOutput = $flashMessage->render();
1185
1186 $tableLayout[$tr] = $rowWithSpan;
1187 $table[$tr][] = $startExecutionElement;
1188 $table[$tr][] = $deleteAction;
1189 $table[$tr][] = $schedulerRecord['uid'];
1190 $table[$tr][] = $executionStatusOutput;
1191 }
1192
1193 $tr++;
1194 }
1195 // Render table
1196 $content .= $this->doc->table($table, $tableLayout);
1197
1198 $content .= '<input type="submit" class="button" name="go" id="scheduler_executeselected" value="' . $GLOBALS['LANG']->getLL('label.executeSelected') . '" />';
1199 }
1200
1201 if (!count($registeredClasses) > 0) {
1202 /** @var t3lib_FlashMessage $flashMessage */
1203 $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage',
1204 $GLOBALS['LANG']->getLL('msg.noTasksDefined'),
1205 '',
1206 t3lib_FlashMessage::INFO
1207 );
1208 $content .= $flashMessage->render();
1209 }
1210
1211 // Display legend, if there's at least one registered task
1212 // Also display information about the usage of server time
1213 if ($numRows > 0) {
1214 $content .= $this->doc->spacer(20);
1215 $content .= '<h4>' . $GLOBALS['LANG']->getLL('status.legend') . '</h4>
1216 <ul>
1217 <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>
1218 <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>
1219 <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>
1220 <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>
1221 <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>
1222 </ul>';
1223 $content .= $this->doc->spacer(10);
1224 $content .= $this->displayServerTime();
1225 }
1226
1227
1228 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1229
1230 return $content;
1231 }
1232
1233 /**
1234 * Saves a task specified in the backend form to the database
1235 *
1236 * @return void
1237 */
1238 protected function saveTask() {
1239
1240 // If a task is being edited fetch old task data
1241 if (!empty($this->submittedData['uid'])) {
1242 try {
1243 $taskRecord = $this->scheduler->fetchTaskRecord($this->submittedData['uid']);
1244 /** @var tx_scheduler_Task $task */
1245 $task = unserialize($taskRecord['serialized_task_object']);
1246 } catch (OutOfBoundsException $e) {
1247 // If the task could not be fetched, issue an error message
1248 // and exit early
1249 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $this->submittedData['uid']), t3lib_FlashMessage::ERROR);
1250 return;
1251 }
1252
1253 // Register single execution
1254 if ($this->submittedData['type'] == 1) {
1255 $task->registerSingleExecution($this->submittedData['start']);
1256
1257 // Else, it's a recurring task
1258 } else {
1259 if (!empty($this->submittedData['croncmd'])) {
1260 // Definition by cron-like syntax
1261
1262 $interval = 0;
1263 $cronCmd = $this->submittedData['croncmd'];
1264 } else {
1265 // Definition by interval
1266
1267 $interval = $this->submittedData['interval'];
1268 $cronCmd = '';
1269 }
1270
1271 // Register recurring execution
1272 $task->registerRecurringExecution($this->submittedData['start'], $interval, $this->submittedData['end'], $this->submittedData['multiple'], $cronCmd);
1273 }
1274
1275 // Set disable flag
1276 $task->setDisabled($this->submittedData['disable']);
1277
1278 // Save additional input values
1279 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) {
1280 /** @var $providerObject tx_scheduler_AdditionalFieldProvider */
1281 $providerObject = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']);
1282 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider) {
1283 $providerObject->saveAdditionalFields($this->submittedData, $task);
1284 }
1285 }
1286
1287 // Save to database
1288 $result = $this->scheduler->saveTask($task);
1289 if ($result) {
1290 $GLOBALS['BE_USER']->writeLog(4, 0, 0, 0, 'Scheduler task "%s" (UID: %s, Class: "%s") was updated', array($task->getTaskTitle(), $task->getTaskUid(), $task->getTaskClassName()));
1291 $this->addMessage($GLOBALS['LANG']->getLL('msg.updateSuccess'));
1292 } else {
1293 $this->addMessage($GLOBALS['LANG']->getLL('msg.updateError'), t3lib_FlashMessage::ERROR);
1294 }
1295 } else {
1296 // A new task is being created
1297
1298 // Create an instance of chosen class
1299 $task = t3lib_div::makeInstance($this->submittedData['class']);
1300
1301 if ($this->submittedData['type'] == 1) {
1302 // Set up single execution
1303 $task->registerSingleExecution($this->submittedData['start']);
1304 } else {
1305 // Set up recurring execution
1306 $task->registerRecurringExecution($this->submittedData['start'], $this->submittedData['interval'], $this->submittedData['end'], $this->submittedData['multiple'], $this->submittedData['croncmd']);
1307 }
1308
1309 // Save additional input values
1310 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) {
1311 /** @var $providerObject tx_scheduler_AdditionalFieldProvider */
1312 $providerObject = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']);
1313 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider) {
1314 $providerObject->saveAdditionalFields($this->submittedData, $task);
1315 }
1316 }
1317
1318 // Set disable flag
1319 $task->setDisabled($this->submittedData['disable']);
1320
1321 // Add to database
1322 $result = $this->scheduler->addTask($task);
1323 if ($result) {
1324 $GLOBALS['BE_USER']->writeLog(4, 0, 0, 0, 'Scheduler task "%s" (UID: %s, Class: "%s") was added', array($task->getTaskTitle(), $task->getTaskUid(), $task->getTaskClassName()));
1325 $this->addMessage($GLOBALS['LANG']->getLL('msg.addSuccess'));
1326 } else {
1327 $this->addMessage($GLOBALS['LANG']->getLL('msg.addError'), t3lib_FlashMessage::ERROR);
1328 }
1329 }
1330 }
1331
1332
1333 /*************************
1334 *
1335 * INPUT PROCESSING UTILITIES
1336 *
1337 *************************/
1338
1339 /**
1340 * Checks the submitted data and performs some pre-processing on it
1341 *
1342 * @return boolean TRUE if everything was ok, FALSE otherwise
1343 */
1344 protected function preprocessData() {
1345 $result = TRUE;
1346
1347 // Validate id
1348 $this->submittedData['uid'] = (empty($this->submittedData['uid'])) ? 0 : intval($this->submittedData['uid']);
1349
1350 // Validate selected task class
1351 if (!class_exists($this->submittedData['class'])) {
1352 $this->addMessage($GLOBALS['LANG']->getLL('msg.noTaskClassFound'), t3lib_FlashMessage::ERROR);
1353 }
1354
1355 // Check start date
1356 if (empty($this->submittedData['start'])) {
1357 $this->addMessage($GLOBALS['LANG']->getLL('msg.noStartDate'), t3lib_FlashMessage::ERROR);
1358 $result = FALSE;
1359 } else {
1360 try {
1361 $timestamp = $this->checkDate($this->submittedData['start']);
1362 $this->submittedData['start'] = $timestamp;
1363 } catch (Exception $e) {
1364 $this->addMessage($GLOBALS['LANG']->getLL('msg.invalidStartDate'), t3lib_FlashMessage::ERROR);
1365 $result = FALSE;
1366 }
1367 }
1368
1369 // Check end date, if recurring task
1370 if ($this->submittedData['type'] == 2 && !empty($this->submittedData['end'])) {
1371 try {
1372 $timestamp = $this->checkDate($this->submittedData['end']);
1373 $this->submittedData['end'] = $timestamp;
1374
1375 if ($this->submittedData['end'] < $this->submittedData['start']) {
1376 $this->addMessage($GLOBALS['LANG']->getLL('msg.endDateSmallerThanStartDate'), t3lib_FlashMessage::ERROR);
1377 $result = FALSE;
1378 }
1379 } catch (Exception $e) {
1380 $this->addMessage($GLOBALS['LANG']->getLL('msg.invalidEndDate'), t3lib_FlashMessage::ERROR);
1381 $result = FALSE;
1382 }
1383 }
1384
1385 // Set default values for interval and cron command
1386 $this->submittedData['interval'] = 0;
1387 $this->submittedData['croncmd'] = '';
1388
1389 // Check type and validity of frequency, if recurring
1390 if ($this->submittedData['type'] == 2) {
1391 $frequency = trim($this->submittedData['frequency']);
1392
1393 if (empty($frequency)) {
1394 // Empty frequency, not valid
1395
1396 $this->addMessage($GLOBALS['LANG']->getLL('msg.noFrequency'), t3lib_FlashMessage::ERROR);
1397 $result = FALSE;
1398 } else {
1399 $cronErrorCode = 0;
1400 $cronErrorMessage = '';
1401
1402 // Try interpreting the cron command
1403 try {
1404 tx_scheduler_CronCmd_Normalize::normalize($frequency);
1405 $this->submittedData['croncmd'] = $frequency;
1406 }
1407 // If the cron command was invalid, we may still have a valid frequency in seconds
1408 catch (Exception $e) {
1409 // Store the exception's result
1410 $cronErrorMessage = $e->getMessage();
1411 $cronErrorCode = $e->getCode();
1412 // Check if the frequency is a valid number
1413 // If yes, assume it is a frequency in seconds, and unset cron error code
1414 if (is_numeric($frequency)) {
1415 $this->submittedData['interval'] = intval($frequency);
1416 unset($cronErrorCode);
1417 }
1418 }
1419 // If there's a cron error code, issue validation error message
1420 if (!empty($cronErrorCode)) {
1421 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.frequencyError'), $cronErrorMessage, $cronErrorCode), t3lib_FlashMessage::ERROR);
1422 $result = FALSE;
1423 }
1424 }
1425 }
1426
1427 // Validate additional input fields
1428 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) {
1429 $providerObject = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']);
1430 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider) {
1431 // The validate method will return TRUE if all went well, but that must not
1432 // override previous FALSE values => AND the returned value with the existing one
1433 $result &= $providerObject->validateAdditionalFields($this->submittedData, $this);
1434 }
1435 }
1436
1437 return $result;
1438 }
1439
1440 /**
1441 * This method checks whether the given string can be considered a valid date or not
1442 * Allowed values are anything that matches natural language (see PHP function strtotime())
1443 * or TYPO3's date syntax: HH:ii yyyy-mm-dd
1444 * If the string is a valid date, the corresponding timestamp is returned.
1445 * Otherwise an exception is thrown
1446 *
1447 * @param string $string String to check
1448 * @return integer Unix timestamp
1449 */
1450 public function checkDate($string) {
1451 // Try with strtotime
1452 $timestamp = strtotime($string);
1453
1454 // That failed. Try TYPO3's standard date/time input format
1455 if ($timestamp === FALSE) {
1456 // Split time and date
1457 $dateParts = t3lib_div::trimExplode(' ', $string, TRUE);
1458 // Proceed if there are indeed two parts
1459 // Extract each component of date and time
1460 if (count($dateParts) == 2) {
1461 list($time, $date) = $dateParts;
1462 list($hour, $minutes) = t3lib_div::trimExplode(':', $time, TRUE);
1463 list($day, $month, $year) = t3lib_div::trimExplode('-', $date, TRUE);
1464 // Get a timestamp from all these parts
1465 $timestamp = @mktime($hour, $minutes, 0, $month, $day, $year);
1466 }
1467 // If the timestamp is still FALSE, throw an exception
1468 if ($timestamp === FALSE) {
1469 throw new InvalidArgumentException('"' . $string . '" seems not to be a correct date.', 1294587694);
1470 }
1471 }
1472 return $timestamp;
1473 }
1474
1475 /*************************
1476 *
1477 * APPLICATION LOGIC UTILITIES
1478 *
1479 *************************/
1480
1481 /**
1482 * This method is used to add a message to the internal queue
1483 *
1484 * @param string $message The message itself
1485 * @param integer $severity Message level (according to t3lib_FlashMessage class constants)
1486 * @return void
1487 */
1488 public function addMessage($message, $severity = t3lib_FlashMessage::OK) {
1489 $message = t3lib_div::makeInstance(
1490 't3lib_FlashMessage',
1491 $message,
1492 '',
1493 $severity
1494 );
1495
1496 t3lib_FlashMessageQueue::addMessage($message);
1497 }
1498
1499 /**
1500 * This method a list of all classes that have been registered with the Scheduler
1501 * For each item the following information is provided, as an associative array:
1502 *
1503 * ['extension'] => Key of the extension which provides the class
1504 * ['filename'] => Path to the file containing the class
1505 * ['title'] => String (possibly localized) containing a human-readable name for the class
1506 * ['provider'] => Name of class that implements the interface for additional fields, if necessary
1507 *
1508 * The name of the class itself is used as the key of the list array
1509 *
1510 * @return array List of registered classes
1511 */
1512 protected static function getRegisteredClasses() {
1513 $list = array();
1514 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'])) {
1515 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'] as $class => $registrationInformation) {
1516
1517 $title = isset($registrationInformation['title']) ? $GLOBALS['LANG']->sL($registrationInformation['title']) : '';
1518 $description = isset($registrationInformation['description']) ? $GLOBALS['LANG']->sL($registrationInformation['description']) : '';
1519
1520 $list[$class] = array(
1521 'extension' => $registrationInformation['extension'],
1522 'title' => $title,
1523 'description' => $description,
1524 'provider' => isset($registrationInformation['additionalFields']) ? $registrationInformation['additionalFields'] : ''
1525 );
1526 }
1527 }
1528
1529 return $list;
1530 }
1531
1532
1533 /*************************
1534 *
1535 * RENDERING UTILITIES
1536 *
1537 *************************/
1538
1539 /**
1540 * Gets the filled markers that are used in the HTML template.
1541 *
1542 * @return array The filled marker array
1543 */
1544 protected function getTemplateMarkers() {
1545 $markers = array(
1546 'CSH' => t3lib_BEfunc::wrapInHelp('_MOD_tools_txschedulerM1', ''),
1547 'FUNC_MENU' => $this->getFunctionMenu(),
1548 'CONTENT' => $this->content,
1549 'TITLE' => $GLOBALS['LANG']->getLL('title'),
1550 );
1551
1552 return $markers;
1553 }
1554
1555 /**
1556 * Gets the function menu selector for this backend module.
1557 *
1558 * @return string The HTML representation of the function menu selector
1559 */
1560 protected function getFunctionMenu() {
1561 $functionMenu = t3lib_BEfunc::getFuncMenu(
1562 0,
1563 'SET[function]',
1564 $this->MOD_SETTINGS['function'],
1565 $this->MOD_MENU['function']
1566 );
1567
1568 return $functionMenu;
1569 }
1570
1571 /**
1572 * Gets the buttons that shall be rendered in the docHeader.
1573 *
1574 * @return array Available buttons for the docHeader
1575 */
1576 protected function getDocHeaderButtons() {
1577 $buttons = array(
1578 'addtask' => '',
1579 'reload' => '',
1580 'shortcut' => $this->getShortcutButton(),
1581 );
1582
1583 if (empty($this->CMD) || $this->CMD == 'list') {
1584 $buttons['reload'] = '<a href="' . $GLOBALS['MCONF']['_'] . '" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.reload', TRUE) . '">' .
1585 t3lib_iconWorks::getSpriteIcon('actions-system-refresh') .
1586 '</a>';
1587 if ($this->MOD_SETTINGS['function'] === 'scheduler' && count(self::getRegisteredClasses())) {
1588 $link = $GLOBALS['MCONF']['_'] . '&CMD=add';
1589 $image = '<img ' . t3lib_iconWorks::skinImg($this->backPath, 'gfx/new_el.gif') .
1590 ' alt="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:new', TRUE) . '" />';
1591 $buttons['addtask'] = '<a href="' . htmlspecialchars($link) . '" ' .
1592 'title="' . $GLOBALS['LANG']->getLL('action.add') . '">' . $image . '</a>';
1593 }
1594 }
1595
1596 return $buttons;
1597 }
1598
1599 /**
1600 * Gets the button to set a new shortcut in the backend (if current user is allowed to).
1601 *
1602 * @return string HTML representation of the shortcut button
1603 */
1604 protected function getShortcutButton() {
1605 $result = '';
1606 if ($GLOBALS['BE_USER']->mayMakeShortcut()) {
1607 $result = $this->doc->makeShortcutIcon('', 'function', $this->MCONF['name']);
1608 }
1609
1610 return $result;
1611 }
1612 }
1613
1614 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/scheduler/class.tx_scheduler_module.php'])) {
1615 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/scheduler/class.tx_scheduler_module.php']);
1616 }
1617 ?>