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