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