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