2 /***************************************************************
5 * (c) 2009-2011 François Suter <francois@typo3.org>
6 * (c) 2005 Christian Jul Jensen <julle@typo3.org>
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.
15 * The GNU General Public License can be found at
16 * http://www.gnu.org/copyleft/gpl.html.
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.
23 * This copyright notice MUST APPEAR in all copies of the script!
24 ***************************************************************/
27 * Module 'TYPO3 Scheduler administration module' for the 'scheduler' extension.
29 * @author François Suter <francois@typo3.org>
30 * @author Christian Jul Jensen <julle@typo3.org>
31 * @author Ingo Renner <ingo@typo3.org>
33 * @subpackage tx_scheduler
35 class tx_scheduler_Module
extends t3lib_SCbase
{
38 * Back path to typo3 main dir
40 * @var string $backPath
45 * Array containing submitted data when editing or adding a task
47 * @var array $submittedData
49 protected $submittedData = array();
52 * Array containing all messages issued by the application logic
53 * Contains the error's severity and the message itself
55 * @var array $messages
57 protected $messages = array();
60 * @var string Key of the CSH file
66 * @var tx_scheduler Local scheduler instance
75 public function __construct() {
76 $this->backPath
= $GLOBALS['BACK_PATH'];
78 $this->cshKey
= '_MOD_' . $GLOBALS['MCONF']['name'];
82 * Initializes the backend module
86 public function init() {
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"';
97 // Create scheduler instance
98 $this->scheduler
= t3lib_div
::makeInstance('tx_scheduler');
102 * Adds items to the ->MOD_MENU array. Used for the function menu selector.
106 public function menuConfig() {
107 $this->MOD_MENU
= array(
109 'scheduler' => $GLOBALS['LANG']->getLL('function.scheduler'),
110 'check' => $GLOBALS['LANG']->getLL('function.check'),
111 'info' => $GLOBALS['LANG']->getLL('function.info'),
115 parent
::menuConfig();
119 * Main function of the module. Write the content to $this->content
123 public function main() {
125 // The page will show only if user has admin rights
126 if ($GLOBALS['BE_USER']->user
['admin']) {
129 $this->doc
->form
= '<form name="tx_scheduler_form" id="tx_scheduler_form" method="post" action="">';
131 // JavaScript for main function menu
132 $this->doc
->JScode
= '
133 <script language="javascript" type="text/javascript">
135 function jumpToUrl(URL) {
136 document.location = URL;
141 // Prepare main content
142 $this->content
= $this->doc
->header(
143 $GLOBALS['LANG']->getLL('function.' . $this->MOD_SETTINGS
['function'])
145 $this->content
.= $this->doc
->spacer(5);
146 $this->content
.= $this->getModuleContent();
148 // If no access, only display the module's title
149 $this->content
= $this->doc
->header($GLOBALS['LANG']->getLL('title'));
150 $this->content
.= $this->doc
->spacer(5);
153 // Place content inside template
155 $content = $this->doc
->moduleBody(
157 $this->getDocHeaderButtons(),
158 $this->getTemplateMarkers()
161 // Renders the module page
162 $this->content
= $this->doc
->render(
163 $GLOBALS['LANG']->getLL('title'),
169 * Generate the module's content
171 * @return string HTML of the module's main content
173 protected function getModuleContent() {
177 // Get submitted data
178 $this->submittedData
= t3lib_div
::_GPmerged('tx_scheduler');
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();
186 // If result is ok, proceed with saving
189 // Unset command, so that default screen gets displayed
193 // Go back to previous step
195 $this->CMD
= $previousCMD;
199 // Handle chosen action
200 switch((string)$this->MOD_SETTINGS
['function']) {
202 // Scheduler's main screen
203 $content .= $this->executeTasks();
205 // Execute chosen action
206 switch ($this->CMD
) {
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 happend when attempting to edit a running task
218 $content .= $this->listTasks();
223 $content .= $this->listTasks();
227 $content .= $this->listTasks();
231 $content .= $this->listTasks();
236 // Setup check screen
237 // TODO: move check to the report module
238 $content .= $this->displayCheckScreen();
241 // Information screen
242 $content .= $this->displayInfoScreen();
246 // Wrap the content in a section
247 return $this->doc
->section($sectionTitle, '<div class="tx_scheduler_mod1">' . $content . '</div>', 0, 1);
251 * This method actually prints out the module's HTML content
255 public function render() {
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)
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
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(
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(
284 $where . t3lib_BEfunc
::BEenableFields('be_users')
286 if ($GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
287 $schedulerUserStatus = 1;
290 $GLOBALS['TYPO3_DB']->sql_free_result($res);
292 return $schedulerUserStatus;
296 * This method creates the "cli_scheduler" BE user if it doesn't exist
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)));
312 * Create an instance of TCEmain and execute user creation
316 $tcemain = t3lib_div
::makeInstance('t3lib_TCEmain');
317 $tcemain->stripslashes_values
= 0;
318 $tcemain->start($data, array());
319 $tcemain->process_datamap();
320 // Check if a new uid was indeed generated (i.e. a new record was created)
321 // (counting TCEmain errors doesn't work as some failures don't report errors)
322 $numberOfNewIDs = count($tcemain->substNEWwithIDs
);
323 if ($numberOfNewIDs == 1) {
324 $message = $GLOBALS['LANG']->getLL('msg.userCreated');
325 $severity = t3lib_FlashMessage
::OK
;
327 $message = $GLOBALS['LANG']->getLL('msg.userNotCreated');
328 $severity = t3lib_FlashMessage
::ERROR
;
331 $this->addMessage($message, $severity);
335 * This method displays the result of a number of checks
336 * on whether the Scheduler is ready to run or running properly
338 * @return string further information
340 protected function displayCheckScreen() {
342 $severity = t3lib_FlashMessage
::OK
;
344 // First, check if cli_sceduler user creation was requested
345 if ($this->CMD
== 'user') {
346 $this->createSchedulerUser();
349 // Start generating the content
350 $content = $GLOBALS['LANG']->getLL('msg.schedulerSetupCheck');
352 // Display information about last automated run, as stored in the system registry
354 * @var t3lib_Registry
356 $registry = t3lib_div
::makeInstance('t3lib_Registry');
357 $lastRun = $registry->get('tx_scheduler', 'lastRun');
358 if (!is_array($lastRun)) {
359 $message = $GLOBALS['LANG']->getLL('msg.noLastRun');
360 $severity = t3lib_FlashMessage
::WARNING
;
362 if (empty($lastRun['end']) ||
empty($lastRun['start']) ||
empty($lastRun['type'])) {
363 $message = $GLOBALS['LANG']->getLL('msg.incompleteLastRun');
364 $severity = t3lib_FlashMessage
::WARNING
;
366 $startDate = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $lastRun['start']);
367 $startTime = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $lastRun['start']);
368 $endDate = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $lastRun['end']);
369 $endTime = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $lastRun['end']);
370 $label = 'automatically';
371 if ($lastRun['type'] == 'manual') {
374 $type = $GLOBALS['LANG']->getLL('label.' . $label);
375 $message = sprintf($GLOBALS['LANG']->getLL('msg.lastRun'), $type, $startDate, $startTime, $endDate, $endTime);
376 $severity = t3lib_FlashMessage
::INFO
;
379 $flashMessage = t3lib_div
::makeInstance(
380 't3lib_FlashMessage',
385 $content .= '<div class="info-block">';
386 $content .= '<h3>' . $GLOBALS['LANG']->getLL('hdg.lastRun') . '</h3>';
387 $content .= $flashMessage->render();
388 $content .= '</div>';
391 $content .= '<div class="info-block">';
392 $content .= '<h3>' . $GLOBALS['LANG']->getLL('hdg.schedulerUser') . '</h3>';
393 $content .= '<p>' . $GLOBALS['LANG']->getLL('msg.schedulerUser') . '</p>';
395 $checkUser = $this->checkSchedulerUser();
396 if ($checkUser == -1) {
397 $link = $GLOBALS['MCONF']['_'] . '&SET[function]=check&CMD=user';
398 $message = sprintf($GLOBALS['LANG']->getLL('msg.schedulerUserMissing'), htmlspecialchars($link));
399 $severity = t3lib_FlashMessage
::ERROR
;
400 } elseif ($checkUser == 0) {
401 $message = $GLOBALS['LANG']->getLL('msg.schedulerUserFoundButDisabled');
402 $severity = t3lib_FlashMessage
::WARNING
;
404 $message = $GLOBALS['LANG']->getLL('msg.schedulerUserFound');
405 $severity = t3lib_FlashMessage
::OK
;
407 $flashMessage = t3lib_div
::makeInstance(
408 't3lib_FlashMessage',
413 $content .= $flashMessage->render() . '</div>';
415 // Check if CLI script is executable or not
416 $script = PATH_typo3
. 'cli_dispatch.phpsh';
417 $isExecutable = FALSE;
418 // Skip this check if running Windows, as rights do not work the same way on this platform
419 // (i.e. the script will always appear as *not* executable)
420 if (TYPO3_OS
=== 'WIN') {
421 $isExecutable = TRUE;
423 $isExecutable = is_executable($script);
425 $content .= '<div class="info-block">';
426 $content .= '<h3>' . $GLOBALS['LANG']->getLL('hdg.cliScript') . '</h3>';
427 $content .= '<p>' . sprintf($GLOBALS['LANG']->getLL('msg.cliScript'), $script) . '</p>';
430 $message = $GLOBALS['LANG']->getLL('msg.cliScriptExecutable');
431 $severity = t3lib_FlashMessage
::OK
;
433 $message = $GLOBALS['LANG']->getLL('msg.cliScriptNotExecutable');
434 $severity = t3lib_FlashMessage
::ERROR
;
436 $flashMessage = t3lib_div
::makeInstance(
437 't3lib_FlashMessage',
442 $content .= $flashMessage->render() . '</div>';
448 * This method gathers information about all available task classes and displays it
450 * @return string HTML content to display
452 protected function displayInfoScreen() {
454 $registeredClasses = self
::getRegisteredClasses();
456 // No classes available, display information message
457 if (count($registeredClasses) == 0) {
458 /** @var t3lib_FlashMessage $flashMessage */
459 $flashMessage = t3lib_div
::makeInstance('t3lib_FlashMessage',
460 $GLOBALS['LANG']->getLL('msg.noTasksDefined'),
462 t3lib_FlashMessage
::INFO
464 $content .= $flashMessage->render();
466 // Display the list of all available classes
468 // Initialise table layout
469 $tableLayout = array (
470 'table' => array ('<table border="0" cellspacing="1" cellpadding="2" class="typo3-dblist">', '</table>'),
472 'tr' => array('<tr class="t3-row-header" valign="top">', '</tr>'),
473 'defCol' => array('<td>', '</td>')
476 'tr' => array('<tr class="db_list_normal">', '</tr>'),
477 'defCol' => array('<td>', '</td>')
484 $table[$tr][] = $GLOBALS['LANG']->getLL('label.name');
485 $table[$tr][] = $GLOBALS['LANG']->getLL('label.extension');
486 $table[$tr][] = $GLOBALS['LANG']->getLL('label.description');
490 // Display information about each service
491 foreach ($registeredClasses as $class => $classInfo) {
492 $table[$tr][] = $classInfo['title'];
493 $table[$tr][] = $classInfo['extension'];
494 $table[$tr][] = $classInfo['description'];
495 $link = $GLOBALS['MCONF']['_'] . '&SET[function]=list&CMD=add&tx_scheduler[class]=' . $class;
496 $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>';
500 // Render the table and return it
501 $content = '<div>' . $GLOBALS['LANG']->getLL('msg.infoScreenIntro') . '</div>';
502 $content .= $this->doc
->spacer(5);
503 $content .= $this->doc
->table($table, $tableLayout);
510 * Display the current server's time along with a help text about server time
511 * usage in the Scheduler
513 * @return string HTML to display
515 protected function displayServerTime() {
516 // Get the current time, formatted
517 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] . ' T (e';
518 $now = date($dateFormat) . ', GMT ' . date('P') . ')';
519 // Display the help text
520 $serverTime = '<h4>' . $GLOBALS['LANG']->getLL('label.serverTime') . '</h4>';
521 $serverTime .= '<p>' . $GLOBALS['LANG']->getLL('msg.serverTimeHelp') . '</p>';
522 $serverTime .= '<p>' . sprintf($GLOBALS['LANG']->getLL('msg.serverTime'), $now) . '</p>';
527 * Delete a task from the execution queue
531 protected function deleteTask() {
533 // Try to fetch the task and delete it
535 * @var tx_scheduler_Task
537 $task = $this->scheduler
->fetchTask($this->submittedData
['uid']);
538 // If the task is currently running, it may not be deleted
539 if ($task->isExecutionRunning()) {
540 $this->addMessage($GLOBALS['LANG']->getLL('msg.maynotDeleteRunningTask'), t3lib_FlashMessage
::ERROR
);
542 if ($this->scheduler
->removeTask($task)) {
543 $this->addMessage($GLOBALS['LANG']->getLL('msg.deleteSuccess'));
545 $this->addMessage($GLOBALS['LANG']->getLL('msg.deleteError'), t3lib_FlashMessage
::ERROR
);
548 } catch (UnexpectedValueException
$e) {
549 // The task could not be unserialized properly, simply delete the database record
550 $result = $GLOBALS['TYPO3_DB']->exec_DELETEquery('tx_scheduler_task', 'uid = ' . intval($this->submittedData
['uid']));
552 $this->addMessage($GLOBALS['LANG']->getLL('msg.deleteSuccess'));
554 $this->addMessage($GLOBALS['LANG']->getLL('msg.deleteError'), t3lib_FlashMessage
::ERROR
);
556 } catch (OutOfBoundsException
$e) {
557 // The task was not found, for some reason
558 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $this->submittedData
['uid']), t3lib_FlashMessage
::ERROR
);
563 * Clears the registered running executions from the task
564 * Note that this doesn't actually stop the running script. It just unmarks
566 * TODO: find a way to really kill the running task
570 protected function stopTask() {
572 // Try to fetch the task and stop it
574 * @var tx_scheduler_Task
576 $task = $this->scheduler
->fetchTask($this->submittedData
['uid']);
577 if ($task->isExecutionRunning()) {
578 // If the task is indeed currently running, clear marked executions
580 $result = $task->unmarkAllExecutions();
582 $this->addMessage($GLOBALS['LANG']->getLL('msg.stopSuccess'));
584 $this->addMessage($GLOBALS['LANG']->getLL('msg.stopError'), t3lib_FlashMessage
::ERROR
);
587 // The task is not running, nothing to unmark
589 $this->addMessage($GLOBALS['LANG']->getLL('msg.maynotStopNonRunningTask'), t3lib_FlashMessage
::WARNING
);
591 } catch (Exception
$e) {
592 // The task was not found, for some reason
593 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $this->submittedData
['uid']), t3lib_FlashMessage
::ERROR
);
598 * Return a form to add a new task or edit an existing one
600 * @return string HTML form to add or edit a task
602 protected function editTask() {
603 $registeredClasses = self
::getRegisteredClasses();
609 if ($this->submittedData
['uid'] > 0) {
610 // If editing, retrieve data for existing task
612 $taskRecord = $this->scheduler
->fetchTaskRecord($this->submittedData
['uid']);
613 // If there's a registered execution, the task should not be edited
614 if (!empty($taskRecord['serialized_executions'])) {
615 $this->addMessage($GLOBALS['LANG']->getLL('msg.maynotEditRunningTask'), t3lib_FlashMessage
::ERROR
);
616 throw new LogicException('Runnings tasks cannot not be edited', 1251232849);
618 // Get the task object
619 $task = unserialize($taskRecord['serialized_task_object']);
621 // Set some task information
622 $class = $taskRecord['classname'];
623 $taskInfo['disable'] = $taskRecord['disable'];
625 // Check that the task object is valid
626 if ($this->scheduler
->isValidTaskObject($task)) {
627 // The task object is valid, process with fetching current data
629 $taskInfo['class'] = $class;
631 // Get execution information
632 $taskInfo['start'] = $task->getExecution()->getStart();
633 $taskInfo['end'] = $task->getExecution()->getEnd();
634 $taskInfo['interval'] = $task->getExecution()->getInterval();
635 $taskInfo['croncmd'] = $task->getExecution()->getCronCmd();
636 $taskInfo['multiple'] = $task->getExecution()->getMultiple();
638 if (!empty($taskInfo['interval']) ||
!empty($taskInfo['croncmd'])) {
639 // Guess task type from the existing information
640 // If an interval or a cron command is defined, it's a recurring task
642 // FIXME remove magic numbers for the type, use class constants instead
643 $taskInfo['type'] = 2;
644 $taskInfo['frequency'] = (empty($taskInfo['interval'])) ?
$taskInfo['croncmd'] : $taskInfo['interval'];
646 // It's not a recurring task
647 // Make sure interval and cron command are both empty
648 $taskInfo['type'] = 1;
649 $taskInfo['frequency'] = '';
650 $taskInfo['end'] = 0;
653 // The task object is not valid
655 // Issue error message
656 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.invalidTaskClassEdit'), $class), t3lib_FlashMessage
::ERROR
);
657 // Initialize empty values
658 $taskInfo['start'] = 0;
659 $taskInfo['end'] = 0;
660 $taskInfo['frequency'] = '';
661 $taskInfo['multiple'] = false;
662 $taskInfo['type'] = 1;
664 } catch (OutOfBoundsException
$e) {
665 // Add a message and continue throwing the exception
666 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $this->submittedData
['uid']), t3lib_FlashMessage
::ERROR
);
670 // If adding a new object, set some default values
671 $taskInfo['class'] = key($registeredClasses);
672 $taskInfo['type'] = 2;
673 $taskInfo['start'] = $GLOBALS['EXEC_TIME'];
674 $taskInfo['end'] = '';
675 $taskInfo['frequency'] = '';
676 $taskInfo['multiple'] = 0;
680 if (count($this->submittedData
) > 0) {
681 // If some data was already submitted, use it to override
683 $taskInfo = t3lib_div
::array_merge_recursive_overrule($taskInfo, $this->submittedData
);
686 // Get the extra fields to display for each task that needs some
687 $allAdditionalFields = array();
688 if ($process == 'add') {
689 foreach ($registeredClasses as $class => $registrationInfo) {
690 if (!empty($registrationInfo['provider'])) {
691 $providerObject = t3lib_div
::getUserObj($registrationInfo['provider']);
692 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider
) {
693 $additionalFields = $providerObject->getAdditionalFields($taskInfo, NULL, $this);
694 $allAdditionalFields = array_merge($allAdditionalFields, array($class => $additionalFields));
699 // In case of edit, get only the extra fields for the current task class
701 if (!empty($registeredClasses[$taskInfo['class']]['provider'])) {
702 $providerObject = t3lib_div
::getUserObj($registeredClasses[$taskInfo['class']]['provider']);
703 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider
) {
704 $allAdditionalFields[$taskInfo['class']] = $providerObject->getAdditionalFields($taskInfo, $task, $this);
709 // Load necessary JavaScript
710 /** @var $pageRenderer t3lib_PageRenderer */
711 $pageRenderer = $this->doc
->getPageRenderer();
712 $pageRenderer->loadExtJS();
713 $pageRenderer->addJsFile(t3lib_extMgm
::extRelPath('scheduler') . 'res/tx_scheduler_be.js');
714 $pageRenderer->addJsFile($this->backPath
. '../t3lib/js/extjs/tceforms.js');
716 // Define settings for Date Picker
717 $typo3Settings = array(
718 'datePickerUSmode' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['USdateFormat'] ?
1 : 0,
719 'dateFormat' => array('j-n-Y', 'G:i j-n-Y'),
720 'dateFormatUS' => array('n-j-Y', 'G:i n-j-Y'),
722 $pageRenderer->addInlineSettingArray('', $typo3Settings);
724 // Define table layout for add/edit form
725 $tableLayout = array (
726 'table' => array ('<table border="0" cellspacing="0" cellpadding="0" id="edit_form" class="typo3-usersettings">', '</table>'),
729 // Define a style for hiding
730 // Some fields will be hidden when the task is not recurring
732 if ($taskInfo['type'] == 1) {
733 $style = ' style="display: none"';
736 // Start rendering the add/edit form
737 $content .= '<input type="hidden" name="tx_scheduler[uid]" value="' . $this->submittedData
['uid'] . '" />';
738 $content .= '<input type="hidden" name="previousCMD" value="' . $this->CMD
. '" />';
739 $content .= '<input type="hidden" name="CMD" value="save" />';
743 $defaultCell = array('<td class="td-input">', '</td>');
746 $label = '<label for="task_disable">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:disable') . '</label>';
747 $table[$tr][] = t3lib_BEfunc
::wrapInHelp($this->cshKey
, 'task_disable', $label);
749 '<input type="hidden" name="tx_scheduler[disable]" value="0" />
750 <input type="checkbox" name="tx_scheduler[disable]" value="1" id="task_disable"' . ($taskInfo['disable'] == 1 ?
' checked="checked"' : '') . ' />';
751 $tableLayout[$tr] = array (
752 'tr' => array('<tr id="task_disable_row">', '</tr>'),
753 'defCol' => $defaultCell,
754 '0' => array('<td class="td-label">', '</td>')
758 // Task class selector
759 $label = '<label for="task_class">' . $GLOBALS['LANG']->getLL('label.class') . '</label>';
760 $table[$tr][] = t3lib_BEfunc
::wrapInHelp($this->cshKey
, 'task_class', $label);
761 // On editing, don't allow changing of the task class, unless it was not valid
762 if ($this->submittedData
['uid'] > 0 && !empty($taskInfo['class'])) {
763 $cell = $registeredClasses[$taskInfo['class']]['title'] . ' (' . $registeredClasses[$taskInfo['class']]['extension'] . ')';
764 $cell .= '<input type="hidden" name="tx_scheduler[class]" id="task_class" value="' . $taskInfo['class'] . '" />';
766 $cell = '<select name="tx_scheduler[class]" id="task_class" class="wide" onchange="actOnChangedTaskClass(this)">';
767 // Loop on all registered classes to display a selector
768 foreach ($registeredClasses as $class => $classInfo) {
769 $selected = ($class == $taskInfo['class']) ?
' selected="selected"' : '';
770 $cell .= '<option value="' . $class . '"' . $selected . '>' . $classInfo['title'] . ' (' . $classInfo['extension'] . ')' . '</option>';
772 $cell .= '</select>';
774 $table[$tr][] = $cell;
775 // Make sure each row has a unique id, for manipulation with JS
776 $tableLayout[$tr] = array (
777 'tr' => array('<tr id="task_class_row">', '</tr>'),
778 'defCol' => $defaultCell,
779 '0' => array('<td class="td-label">', '</td>')
783 // Task type selector
784 $label = '<label for="task_type">' . $GLOBALS['LANG']->getLL('label.type') . '</label>';
785 $table[$tr][] = t3lib_BEfunc
::wrapInHelp($this->cshKey
, 'task_type', $label);
787 '<select name="tx_scheduler[type]" id="task_type" onchange="actOnChangedTaskType(this)">' .
788 '<option value="1"' . ($taskInfo['type'] == 1 ?
' selected="selected"' : '') . '>' . $GLOBALS['LANG']->getLL('label.type.single') . '</option>' .
789 '<option value="2"' . ($taskInfo['type'] == 2 ?
' selected="selected"' : '') . '>' . $GLOBALS['LANG']->getLL('label.type.recurring') . '</option>' .
791 $tableLayout[$tr] = array (
792 'tr' => array('<tr id="task_type_row">', '</tr>'),
793 'defCol' => $defaultCell,
794 '0' => array('<td class="td-label">', '</td>'),
798 // Start date/time field
799 // NOTE: datetime fields need a special id naming scheme
800 $label = '<label for="tceforms-datetimefield-task_start">' . $GLOBALS['LANG']->getLL('label.start') . '</label>';
801 $table[$tr][] = t3lib_BEfunc
::wrapInHelp($this->cshKey
, 'task_start', $label);
802 $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'])) . '" />' .
803 t3lib_iconWorks
::getSpriteIcon(
804 'actions-edit-pick-date',
806 'style' => 'cursor:pointer;',
807 'id' => 'picker-tceforms-datetimefield-task_start'
810 $tableLayout[$tr] = array (
811 'tr' => array('<tr id="task_start_row">', '</tr>'),
812 'defCol' => $defaultCell,
813 '0' => array('<td class="td-label">', '</td>')
817 // End date/time field
818 // NOTE: datetime fields need a special id naming scheme
819 $label = '<label for="tceforms-datetimefield-task_end">' . $GLOBALS['LANG']->getLL('label.end') . '</label>';
820 $table[$tr][] = t3lib_BEfunc
::wrapInHelp($this->cshKey
, 'task_end', $label);
821 $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'])) . '" />' .
822 t3lib_iconWorks
::getSpriteIcon(
823 'actions-edit-pick-date',
825 'style' => 'cursor:pointer;',
826 'id' => 'picker-tceforms-datetimefield-task_end'
829 $tableLayout[$tr] = array (
830 'tr' => array('<tr id="task_end_row"' . $style . '>', '</tr>'),
831 'defCol' => $defaultCell,
832 '0' => array('<td class="td-label">', '</td>'),
836 // Frequency input field
837 $label = '<label for="task_frequency">' . $GLOBALS['LANG']->getLL('label.frequency.long') . '</label>';
838 $table[$tr][] = t3lib_BEfunc
::wrapInHelp($this->cshKey
, 'task_frequency', $label);
839 $cell = '<input type="text" name="tx_scheduler[frequency]" id="task_frequency" value="' . $taskInfo['frequency'] . '" />';
840 $table[$tr][] = $cell;
841 $tableLayout[$tr] = array (
842 'tr' => array('<tr id="task_frequency_row"' . $style . '>', '</tr>'),
843 'defCol' => $defaultCell,
844 '0' => array('<td class="td-label">', '</td>'),
848 // Multiple execution selector
849 $label = '<label for="task_multiple">' . $GLOBALS['LANG']->getLL('label.parallel.long') . '</label>';
850 $table[$tr][] = t3lib_BEfunc
::wrapInHelp($this->cshKey
, 'task_multiple', $label);
852 '<input type="hidden" name="tx_scheduler[multiple]" value="0" />
853 <input type="checkbox" name="tx_scheduler[multiple]" value="1" id="task_multiple"' . ($taskInfo['multiple'] == 1 ?
' checked="checked"' : '') . ' />';
854 $tableLayout[$tr] = array (
855 'tr' => array('<tr id="task_multiple_row"' . $style . '>', '</tr>'),
856 'defCol' => $defaultCell,
857 '0' => array('<td class="td-label">', '</td>')
861 // Display additional fields
862 foreach ($allAdditionalFields as $class => $fields) {
863 if ($class == $taskInfo['class']) {
864 $additionalFieldsStyle = '';
866 $additionalFieldsStyle = ' style="display: none"';
869 // Add each field to the display, if there are indeed any
870 if (isset($fields) && is_array($fields)) {
871 foreach ($fields as $fieldID => $fieldInfo) {
872 $label = '<label for="' . $fieldID . '">' . $GLOBALS['LANG']->sL($fieldInfo['label']) . '</label>';
873 $table[$tr][] = t3lib_BEfunc
::wrapInHelp($fieldInfo['cshKey'], $fieldInfo['cshLabel'], $label);
874 $table[$tr][] = $fieldInfo['code'];
875 $tableLayout[$tr] = array (
876 'tr' => array('<tr id="' . $fieldID . '_row"' . $additionalFieldsStyle .' class="extraFields extra_fields_' . $class . '">', '</tr>'),
877 'defCol' => $defaultCell,
878 '0' => array('<td class="td-label">', '</td>')
885 // Render the add/edit task form
886 $content .= '<div style="float: left;"><div class="typo3-dyntabmenu-divs">';
887 $content .= $this->doc
->table($table, $tableLayout);
888 $content .= '</div></div>';
890 $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) . '" /> '
891 . '<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>';
893 // Display information about server time usage
894 $content .= $this->displayServerTime();
900 * Execute all selected tasks
904 protected function executeTasks() {
905 // Continue if some elements have been chosen for execution
906 if (isset($this->submittedData
['execute']) && count($this->submittedData
['execute']) > 0) {
908 // Get list of registered classes
909 $registeredClasses = self
::getRegisteredClasses();
911 // Loop on all selected tasks
912 foreach ($this->submittedData
['execute'] as $uid) {
915 // Try fetching the task
916 $task = $this->scheduler
->fetchTask($uid);
917 $class = get_class($task);
918 $name = $registeredClasses[$class]['title']. ' (' . $registeredClasses[$class]['extension'] . ')';
919 // Now try to execute it and report on outcome
921 $result = $this->scheduler
->executeTask($task);
923 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.executed'), $name));
925 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.notExecuted'), $name), t3lib_FlashMessage
::ERROR
);
928 catch (Exception
$e) {
929 // An exception was thrown, display its message as an error
930 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.executionFailed'), $name, $e->getMessage()), t3lib_FlashMessage
::ERROR
);
933 // The task was not found, for some reason
934 catch (OutOfBoundsException
$e) {
935 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $uid), t3lib_FlashMessage
::ERROR
);
937 // The task object was not valid
938 catch (UnexpectedValueException
$e) {
939 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.executionFailed'), $name, $e->getMessage()), t3lib_FlashMessage
::ERROR
);
942 // Record the run in the system registry
943 $this->scheduler
->recordLastRun('manual');
944 // Make sure to switch to list view after execution
950 * Assemble display of list of scheduled tasks
952 * @return string table of waiting schedulings
954 protected function listTasks() {
955 // Define display format for dates
956 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
959 // Get list of registered classes
960 $registeredClasses = self
::getRegisteredClasses();
962 // Get all registered tasks
965 'FROM' => 'tx_scheduler_task',
967 'ORDERBY' => 'nextexecution'
970 $res = $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($query);
971 $numRows = $GLOBALS['TYPO3_DB']->sql_num_rows($res);
972 // No tasks defined, display information message
974 /** @var t3lib_FlashMessage $flashMessage */
975 $flashMessage = t3lib_div
::makeInstance('t3lib_FlashMessage',
976 $GLOBALS['LANG']->getLL('msg.noTasks'),
978 t3lib_FlashMessage
::INFO
980 $content .= $flashMessage->render();
982 // Load ExtJS framework and specific JS library
983 /** @var $pageRenderer t3lib_PageRenderer */
984 $pageRenderer = $this->doc
->getPageRenderer();
985 $pageRenderer->loadExtJS();
986 $pageRenderer->addJsFile(t3lib_extMgm
::extRelPath('scheduler') . 'res/tx_scheduler_be.js');
988 // Initialise table layout
989 $tableLayout = array(
991 '<table border="0" cellspacing="1" cellpadding="2" class="typo3-dblist">', '</table>'
994 'tr' => array('<tr class="t3-row-header">', '</tr>'),
995 'defCol' => array('<td>', '</td>'),
996 '1' => array('<td style="width: 36px;">', '</td>'),
997 '3' => array('<td colspan="2">', '</td>'),
1000 'tr' => array('<tr class="db_list_normal">', '</tr>'),
1001 'defCol' => array('<td>', '</td>'),
1002 '1' => array('<td class="right">', '</td>'),
1003 '2' => array('<td class="right">', '</td>'),
1006 $disabledTaskRow = array (
1007 'tr' => array('<tr class="db_list_normal disabled">', '</tr>'),
1008 'defCol' => array('<td>', '</td>'),
1009 '1' => array('<td class="right">', '</td>'),
1010 '2' => array('<td class="right">', '</td>'),
1012 $rowWithSpan = array (
1013 'tr' => array('<tr class="db_list_normal">', '</tr>'),
1014 'defCol' => array('<td>', '</td>'),
1015 '1' => array('<td class="right">', '</td>'),
1016 '2' => array('<td class="right">', '</td>'),
1017 '3' => array('<td colspan="6">', '</td>'),
1023 $table[$tr][] = '<a href="#" onclick="toggleCheckboxes();" title="' . $GLOBALS['LANG']->getLL('label.checkAll', TRUE) . '" class="icon">' .
1024 t3lib_iconWorks
::getSpriteIcon('actions-document-select') .
1026 $table[$tr][] = ' ';
1027 $table[$tr][] = $GLOBALS['LANG']->getLL('label.id');
1028 $table[$tr][] = $GLOBALS['LANG']->getLL('task');
1029 $table[$tr][] = $GLOBALS['LANG']->getLL('label.type');
1030 $table[$tr][] = $GLOBALS['LANG']->getLL('label.frequency');
1031 $table[$tr][] = $GLOBALS['LANG']->getLL('label.parallel');
1032 $table[$tr][] = $GLOBALS['LANG']->getLL('label.lastExecution');
1033 $table[$tr][] = $GLOBALS['LANG']->getLL('label.nextExecution');
1036 // Loop on all tasks
1037 while (($schedulerRecord = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))) {
1038 // Define action icons
1039 $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>';
1040 $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>';
1041 $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>';
1042 // Define some default values
1043 $lastExecution = '-';
1045 $executionStatus = 'scheduled';
1046 $executionStatusDetail = '';
1047 $executionStatusOutput = '';
1053 $startExecutionElement = ' ';
1055 // Restore the serialized task and pass it a reference to the scheduler object
1056 $task = unserialize($schedulerRecord['serialized_task_object']);
1058 // Assemble information about last execution
1060 if (!empty($schedulerRecord['lastexecution_time'])) {
1061 $lastExecution = date($dateFormat, $schedulerRecord['lastexecution_time']);
1062 if ($schedulerRecord['lastexecution_context'] == 'CLI') {
1063 $context = $GLOBALS['LANG']->getLL('label.cron');
1065 $context = $GLOBALS['LANG']->getLL('label.manual');
1067 $lastExecution .= ' (' . $context . ')';
1070 if ($this->scheduler
->isValidTaskObject($task)) {
1071 // The task object is valid
1073 $name = htmlspecialchars($registeredClasses[$schedulerRecord['classname']]['title']. ' (' . $registeredClasses[$schedulerRecord['classname']]['extension'] . ')');
1074 $additionalInformation = $task->getAdditionalInformation();
1075 if (!empty($additionalInformation)) {
1076 $name .= '<br />[' . htmlspecialchars($additionalInformation) . ']';
1079 // Check if task currently has a running execution
1080 if (!empty($schedulerRecord['serialized_executions'])) {
1082 $executionStatus = 'running';
1085 // Prepare display of next execution date
1086 // If task is currently running, date is not displayed (as next hasn't been calculated yet)
1087 // Also hide the date if task is disabled (the information doesn't make sense, as it will not run anyway)
1088 if ($isRunning ||
$schedulerRecord['disable'] == 1) {
1092 $nextDate = date($dateFormat, $schedulerRecord['nextexecution']);
1093 if (empty($schedulerRecord['nextexecution'])) {
1094 $nextDate = $GLOBALS['LANG']->getLL('none');
1095 } elseif ($schedulerRecord['nextexecution'] < $GLOBALS['EXEC_TIME']) {
1096 // Next execution is overdue, highlight date
1097 $nextDate = '<span class="late" title="' . $GLOBALS['LANG']->getLL('status.legend.scheduled') . '">' . $nextDate . '</span>';
1098 $executionStatus = 'late';
1102 // Get execution type
1103 if ($task->getExecution()->getInterval() == 0 && $task->getExecution()->getCronCmd() == '') {
1104 $execType = $GLOBALS['LANG']->getLL('label.type.single');
1107 $execType = $GLOBALS['LANG']->getLL('label.type.recurring');
1108 if ($task->getExecution()->getCronCmd() == '') {
1109 $frequency = $task->getExecution()->getInterval();
1111 $frequency = $task->getExecution()->getCronCmd();
1115 // Get multiple executions setting
1116 if ($task->getExecution()->getMultiple()) {
1117 $multiple = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes');
1119 $multiple = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:no');
1123 $startExecutionElement = '<input type="checkbox" name="tx_scheduler[execute][]" value="' . $schedulerRecord['uid'] . '" id="task_' . $schedulerRecord['uid'] . '" class="checkboxes" />';
1125 // Show no action links (edit, delete) if task is running
1126 $actions = $editAction . $deleteAction;
1128 $actions = $stopAction;
1131 // Check the disable status
1132 // Row is shown dimmed if task is disabled, unless it is still running
1133 if ($schedulerRecord['disable'] == 1 && !$isRunning) {
1134 $tableLayout[$tr] = $disabledTaskRow;
1135 $executionStatus = 'disabled';
1138 // Check if the last run failed
1139 $failureOutput = '';
1140 if (!empty($schedulerRecord['lastexecution_failure'])) {
1141 // Try to get the stored exception object
1142 $exception = unserialize($schedulerRecord['lastexecution_failure']);
1143 // If the exception could not be unserialized, issue a default error message
1144 if ($exception === FALSE) {
1145 $failureDetail = $GLOBALS['LANG']->getLL('msg.executionFailureDefault');
1147 $failureDetail = sprintf($GLOBALS['LANG']->getLL('msg.executionFailureReport'), $exception->getCode(), $exception->getMessage());
1149 $failureOutput = ' <img ' . t3lib_iconWorks
::skinImg(t3lib_extMgm
::extRelPath('scheduler'), 'res/gfx/status_failure.png') . ' alt="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.failure')) . '" title="' . htmlspecialchars($failureDetail) . '" />';
1152 // Format the execution status,
1153 // including failure feedback, if any
1154 $executionStatusOutput = '<img ' . t3lib_iconWorks
::skinImg(t3lib_extMgm
::extRelPath('scheduler'), 'res/gfx/status_' . $executionStatus . '.png') . ' alt="' . htmlspecialchars($GLOBALS['LANG']->getLL('status.' . $executionStatus)) . '" title="' . htmlspecialchars($executionStatusDetail) . '" />' . $failureOutput;
1156 $table[$tr][] = $startExecutionElement;
1157 $table[$tr][] = $actions;
1158 $table[$tr][] = $schedulerRecord['uid'];
1159 $table[$tr][] = $executionStatusOutput;
1160 $table[$tr][] = $name;
1161 $table[$tr][] = $execType;
1162 $table[$tr][] = $frequency;
1163 $table[$tr][] = $multiple;
1164 $table[$tr][] = $lastExecution;
1165 $table[$tr][] = $nextDate;
1168 // The task object is not valid
1169 // Prepare to issue an error
1171 /** @var t3lib_FlashMessage $flashMessage */
1172 $flashMessage = t3lib_div
::makeInstance('t3lib_FlashMessage',
1173 sprintf($GLOBALS['LANG']->getLL('msg.invalidTaskClass'), $schedulerRecord['classname']),
1175 t3lib_FlashMessage
::ERROR
1177 $executionStatusOutput = $flashMessage->render();
1179 $tableLayout[$tr] = $rowWithSpan;
1180 $table[$tr][] = $startExecutionElement;
1181 $table[$tr][] = $deleteAction;
1182 $table[$tr][] = $schedulerRecord['uid'];
1183 $table[$tr][] = $executionStatusOutput;
1189 $content .= $this->doc
->table($table, $tableLayout);
1191 $content .= '<input type="submit" class="button" name="go" value="' . $GLOBALS['LANG']->getLL('label.executeSelected') . '" />';
1194 if (count($registeredClasses) > 0) {
1195 // Display add new task link
1196 $link = $GLOBALS['MCONF']['_'] . '&CMD=add';
1197 $content .= '<p><a href="' . htmlspecialchars($link) .'"><img '
1198 . t3lib_iconWorks
::skinImg($this->backPath
, 'gfx/new_el.gif')
1199 . ' alt="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:new', TRUE)
1200 . '" /> ' . $GLOBALS['LANG']->getLL('action.add') . '</a></p>';
1202 /** @var t3lib_FlashMessage $flashMessage */
1203 $flashMessage = t3lib_div
::makeInstance('t3lib_FlashMessage',
1204 $GLOBALS['LANG']->getLL('msg.noTasksDefined'),
1206 t3lib_FlashMessage
::INFO
1208 $content .= $flashMessage->render();
1211 // Display legend, if there's at least one registered task
1212 // Also display information about the usage of server time
1214 $content .= $this->doc
->spacer(20);
1215 $content .= '<h4>' . $GLOBALS['LANG']->getLL('status.legend') . '</h4>
1217 <li><img ' . t3lib_iconWorks
::skinImg(t3lib_extMgm
::extRelPath('scheduler'), 'res/gfx/status_failure.png') . ' alt="' . 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')) . '" /> ' . $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')) . '" /> ' . $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')) . '" /> ' . $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')) . '" /> ' . $GLOBALS['LANG']->getLL('status.legend.disabled') . '</li>
1223 $content .= $this->doc
->spacer(10);
1224 $content .= $this->displayServerTime();
1228 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1234 * Saves a task specified in the backend form to the database
1238 protected function saveTask() {
1240 // If a task is being edited fetch old task data
1241 if (!empty($this->submittedData
['uid'])) {
1243 $taskRecord = $this->scheduler
->fetchTaskRecord($this->submittedData
['uid']);
1245 * @var tx_scheduler_Task
1247 $task = unserialize($taskRecord['serialized_task_object']);
1248 } catch (OutOfBoundsException
$e) {
1249 // If the task could not be fetched, issue an error message
1251 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.taskNotFound'), $this->submittedData
['uid']), t3lib_FlashMessage
::ERROR
);
1255 // Register single execution
1256 if ($this->submittedData
['type'] == 1) {
1257 $task->registerSingleExecution($this->submittedData
['start']);
1259 // Else, it's a recurring task
1261 if (!empty($this->submittedData
['croncmd'])) {
1262 // Definition by cron-like syntax
1265 $cronCmd = $this->submittedData
['croncmd'];
1267 // Definition by interval
1269 $interval = $this->submittedData
['interval'];
1273 // Register recurring execution
1274 $task->registerRecurringExecution($this->submittedData
['start'], $interval, $this->submittedData
['end'], $this->submittedData
['multiple'], $cronCmd);
1278 $task->setDisabled($this->submittedData
['disable']);
1280 // Save additional input values
1281 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData
['class']]['additionalFields'])) {
1282 $providerObject = t3lib_div
::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData
['class']]['additionalFields']);
1283 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider
) {
1284 $providerObject->saveAdditionalFields($this->submittedData
, $task);
1289 $result = $this->scheduler
->saveTask($task);
1291 $this->addMessage($GLOBALS['LANG']->getLL('msg.updateSuccess'));
1293 $this->addMessage($GLOBALS['LANG']->getLL('msg.updateError'), t3lib_FlashMessage
::ERROR
);
1296 // A new task is being created
1298 // Create an instance of chosen class
1299 $task = t3lib_div
::makeInstance($this->submittedData
['class']);
1301 if ($this->submittedData
['type'] == 1) {
1302 // Set up single execution
1303 $task->registerSingleExecution($this->submittedData
['start']);
1305 // Set up recurring execution
1306 $task->registerRecurringExecution($this->submittedData
['start'], $this->submittedData
['interval'], $this->submittedData
['end'], $this->submittedData
['multiple'], $this->submittedData
['croncmd']);
1309 // Save additional input values
1310 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData
['class']]['additionalFields'])) {
1311 $providerObject = t3lib_div
::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData
['class']]['additionalFields']);
1312 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider
) {
1313 $providerObject->saveAdditionalFields($this->submittedData
, $task);
1318 $task->setDisabled($this->submittedData
['disable']);
1321 $result = $this->scheduler
->addTask($task);
1323 $this->addMessage($GLOBALS['LANG']->getLL('msg.addSuccess'));
1325 $this->addMessage($GLOBALS['LANG']->getLL('msg.addError'), t3lib_FlashMessage
::ERROR
);
1331 /*************************
1333 * INPUT PROCESSING UTILITIES
1335 *************************/
1338 * Checks the submitted data and performs some preprocessing on it
1340 * @return boolean True if everything was ok, false otherwise
1342 protected function preprocessData() {
1346 $this->submittedData
['uid'] = (empty($this->submittedData
['uid'])) ?
0 : intval($this->submittedData
['uid']);
1348 // Validate selected task class
1349 if (!class_exists($this->submittedData
['class'])) {
1350 $this->addMessage($GLOBALS['LANG']->getLL('msg.noTaskClassFound'), t3lib_FlashMessage
::ERROR
);
1354 if (empty($this->submittedData
['start'])) {
1355 $this->addMessage($GLOBALS['LANG']->getLL('msg.noStartDate'), t3lib_FlashMessage
::ERROR
);
1359 $timestamp = $this->checkDate($this->submittedData
['start']);
1360 $this->submittedData
['start'] = $timestamp;
1361 } catch (Exception
$e) {
1362 $this->addMessage($GLOBALS['LANG']->getLL('msg.invalidStartDate'), t3lib_FlashMessage
::ERROR
);
1367 // Check end date, if recurring task
1368 if ($this->submittedData
['type'] == 2 && !empty($this->submittedData
['end'])) {
1370 $timestamp = $this->checkDate($this->submittedData
['end']);
1371 $this->submittedData
['end'] = $timestamp;
1373 if ($this->submittedData
['end'] < $this->submittedData
['start']) {
1374 $this->addMessage($GLOBALS['LANG']->getLL('msg.endDateSmallerThanStartDate'), t3lib_FlashMessage
::ERROR
);
1377 } catch (Exception
$e) {
1378 $this->addMessage($GLOBALS['LANG']->getLL('msg.invalidEndDate'), t3lib_FlashMessage
::ERROR
);
1383 // Set default values for interval and cron command
1384 $this->submittedData
['interval'] = 0;
1385 $this->submittedData
['croncmd'] = '';
1387 // Check type and validity of frequency, if recurring
1388 if ($this->submittedData
['type'] == 2) {
1389 $frequency = trim($this->submittedData
['frequency']);
1391 if (empty($frequency)) {
1392 // Empty frequency, not valid
1394 $this->addMessage($GLOBALS['LANG']->getLL('msg.noFrequency'), t3lib_FlashMessage
::ERROR
);
1398 $cronErrorMessage = '';
1400 // Try interpreting the cron command
1402 tx_scheduler_CronCmd_Normalize
::normalize($frequency);
1403 $this->submittedData
['croncmd'] = $frequency;
1405 // If the cron command was invalid, we may still have a valid frequency in seconds
1406 catch (Exception
$e) {
1407 // Store the exception's result
1408 $cronErrorMessage = $e->getMessage();
1409 $cronErrorCode = $e->getCode();
1410 // Check if the frequency is a valid number
1411 // If yes, assume it is a frequency in seconds, and unset cron error code
1412 if (is_numeric($frequency)) {
1413 $this->submittedData
['interval'] = intval($frequency);
1414 unset($cronErrorCode);
1417 // If there's a cron error code, issue validation error message
1418 if (!empty($cronErrorCode)) {
1419 $this->addMessage(sprintf($GLOBALS['LANG']->getLL('msg.frequencyError'), $cronErrorMessage, $cronErrorCode), t3lib_FlashMessage
::ERROR
);
1425 // Validate additional input fields
1426 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData
['class']]['additionalFields'])) {
1427 $providerObject = t3lib_div
::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData
['class']]['additionalFields']);
1428 if ($providerObject instanceof tx_scheduler_AdditionalFieldProvider
) {
1429 // The validate method will return true if all went well, but that must not
1430 // override previous false values => AND the returned value with the existing one
1431 $result &= $providerObject->validateAdditionalFields($this->submittedData
, $this);
1439 * This method checks whether the given string can be considered a valid date or not
1440 * Allowed values are anything that matches natural language (see PHP function strtotime())
1441 * or TYPO3's date syntax: HH:ii yyyy-mm-dd
1442 * If the string is a valid date, the corresponding timestamp is returned.
1443 * Otherwise an exception is thrown
1445 * @param string $string: string to check
1446 * @return integer Unix timestamp
1448 protected function checkDate($string) {
1449 // Try with strtotime
1450 $timestamp = strtotime($string);
1452 // That failed. Try TYPO3's standard date/time input format
1453 if ($timestamp === false) {
1454 // Split time and date
1455 $dateParts = t3lib_div
::trimExplode(' ', $string, true);
1456 // Proceed if there are indeed two parts
1457 // Extract each component of date and time
1458 if (count($dateParts) == 2) {
1459 list($time, $date) = $dateParts;
1460 list($hour, $minutes) = t3lib_div
::trimExplode(':', $time, true);
1461 list($day, $month, $year) = t3lib_div
::trimExplode('-', $date, true);
1462 // Get a timestamp from all these parts
1463 $timestamp = mktime($hour, $minutes, 0, $month, $day, $year);
1465 // If the timestamp is still false, throw an exception
1466 if ($timestamp === false) {
1467 throw new InvalidArgumentException('"' . $string . '" seems not to be a correct date.', 1294587694);
1473 /*************************
1475 * APPLICATION LOGIC UTILITIES
1477 *************************/
1480 * This method is used to add a message to the internal queue
1482 * @param string the message itself
1483 * @param integer message level (-1 = success (default), 0 = info, 1 = notice, 2 = warning, 3 = error)
1486 public function addMessage($message, $severity = t3lib_FlashMessage
::OK
) {
1487 $message = t3lib_div
::makeInstance(
1488 't3lib_FlashMessage',
1494 t3lib_FlashMessageQueue
::addMessage($message);
1498 * This method a list of all classes that have been registered with the Scheduler
1499 * For each item the following information is provided, as an associative array:
1501 * ['extension'] => Key of the extension which provides the class
1502 * ['filename'] => Path to the file containing the class
1503 * ['title'] => String (possibly localized) containing a human-readable name for the class
1504 * ['provider'] => Name of class that implements the interface for additional fields, if necessary
1506 * The name of the class itself is used as the key of the list array
1508 * @return array List of registered classes
1510 protected static function getRegisteredClasses() {
1512 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'])) {
1513 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'] as $class => $registrationInformation) {
1515 $title = isset($registrationInformation['title']) ?
$GLOBALS['LANG']->sL($registrationInformation['title']) : '';
1516 $description = isset($registrationInformation['description']) ?
$GLOBALS['LANG']->sL($registrationInformation['description']) : '';
1518 $list[$class] = array(
1519 'extension' => $registrationInformation['extension'],
1521 'description' => $description,
1522 'provider' => isset($registrationInformation['additionalFields']) ?
$registrationInformation['additionalFields'] : ''
1531 /*************************
1533 * RENDERING UTILITIES
1535 *************************/
1538 * Gets the filled markers that are used in the HTML template.
1540 * @return array The filled marker array
1542 protected function getTemplateMarkers() {
1544 'CSH' => t3lib_BEfunc
::wrapInHelp('_MOD_tools_txschedulerM1', ''),
1545 'FUNC_MENU' => $this->getFunctionMenu(),
1546 'CONTENT' => $this->content
,
1547 'TITLE' => $GLOBALS['LANG']->getLL('title'),
1554 * Gets the function menu selector for this backend module.
1556 * @return string The HTML representation of the function menu selector
1558 protected function getFunctionMenu() {
1559 $functionMenu = t3lib_BEfunc
::getFuncMenu(
1562 $this->MOD_SETTINGS
['function'],
1563 $this->MOD_MENU
['function']
1566 return $functionMenu;
1570 * Gets the buttons that shall be rendered in the docHeader.
1572 * @return array Available buttons for the docHeader
1574 protected function getDocHeaderButtons() {
1577 'shortcut' => $this->getShortcutButton(),
1580 if (empty($this->CMD
) ||
$this->CMD
== 'list') {
1581 $buttons['reload'] = '<a href="' . $GLOBALS['MCONF']['_'] . '" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.reload', TRUE) . '">' .
1582 t3lib_iconWorks
::getSpriteIcon('actions-system-refresh') .
1590 * Gets the button to set a new shortcut in the backend (if current user is allowed to).
1592 * @return string HTML representiation of the shortcut button
1594 protected function getShortcutButton() {
1596 if ($GLOBALS['BE_USER']->mayMakeShortcut()) {
1597 $result = $this->doc
->makeShortcutIcon('', 'function', $this->MCONF
['name']);
1604 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE
]['XCLASS']['ext/scheduler/class.tx_scheduler_module.php'])) {
1605 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE
]['XCLASS']['ext/scheduler/class.tx_scheduler_module.php']);