Total Complexity | 186 |
Total Lines | 1358 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like SchedulerModuleController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SchedulerModuleController, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
43 | class SchedulerModuleController |
||
44 | { |
||
45 | /** |
||
46 | * Array containing submitted data when editing or adding a task |
||
47 | * |
||
48 | * @var array |
||
49 | */ |
||
50 | protected $submittedData = []; |
||
51 | |||
52 | /** |
||
53 | * Array containing all messages issued by the application logic |
||
54 | * Contains the error's severity and the message itself |
||
55 | * |
||
56 | * @var array |
||
57 | */ |
||
58 | protected $messages = []; |
||
59 | |||
60 | /** |
||
61 | * @var string Key of the CSH file |
||
62 | */ |
||
63 | protected $cshKey = '_MOD_system_txschedulerM1'; |
||
64 | |||
65 | /** |
||
66 | * @var Scheduler Local scheduler instance |
||
67 | */ |
||
68 | protected $scheduler; |
||
69 | |||
70 | /** |
||
71 | * @var string |
||
72 | */ |
||
73 | protected $backendTemplatePath = ''; |
||
74 | |||
75 | /** |
||
76 | * @var StandaloneView |
||
77 | */ |
||
78 | protected $view; |
||
79 | |||
80 | /** |
||
81 | * @var string Base URI of scheduler module |
||
82 | */ |
||
83 | protected $moduleUri; |
||
84 | |||
85 | /** |
||
86 | * ModuleTemplate Container |
||
87 | * |
||
88 | * @var ModuleTemplate |
||
89 | */ |
||
90 | protected $moduleTemplate; |
||
91 | |||
92 | /** |
||
93 | * @var IconFactory |
||
94 | */ |
||
95 | protected $iconFactory; |
||
96 | |||
97 | /** |
||
98 | * The value of GET/POST var, 'CMD' |
||
99 | * |
||
100 | * @see init() |
||
101 | * @var mixed |
||
102 | */ |
||
103 | public $CMD; |
||
104 | |||
105 | /** |
||
106 | * The module menu items array. Each key represents a key for which values can range between the items in the array of that key. |
||
107 | * |
||
108 | * @see init() |
||
109 | * @var array |
||
110 | */ |
||
111 | protected $MOD_MENU = [ |
||
112 | 'function' => [] |
||
113 | ]; |
||
114 | |||
115 | /** |
||
116 | * Current settings for the keys of the MOD_MENU array |
||
117 | * |
||
118 | * @see $MOD_MENU |
||
119 | * @var array |
||
120 | */ |
||
121 | protected $MOD_SETTINGS = []; |
||
122 | |||
123 | /** |
||
124 | * Default constructor |
||
125 | */ |
||
126 | public function __construct() |
||
127 | { |
||
128 | $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class); |
||
129 | $this->getLanguageService()->includeLLFile('EXT:scheduler/Resources/Private/Language/locallang.xlf'); |
||
130 | $this->backendTemplatePath = ExtensionManagementUtility::extPath('scheduler') . 'Resources/Private/Templates/Backend/SchedulerModule/'; |
||
131 | $this->view = GeneralUtility::makeInstance(StandaloneView::class); |
||
132 | $this->view->getRequest()->setControllerExtensionName('scheduler'); |
||
133 | $this->view->setPartialRootPaths([ExtensionManagementUtility::extPath('scheduler') . 'Resources/Private/Partials/Backend/SchedulerModule/']); |
||
134 | /** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */ |
||
135 | $uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class); |
||
136 | $this->moduleUri = (string)$uriBuilder->buildUriFromRoute('system_txschedulerM1'); |
||
137 | $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class); |
||
138 | $this->scheduler = GeneralUtility::makeInstance(Scheduler::class); |
||
139 | |||
140 | $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/Modal'); |
||
141 | $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/SplitButtons'); |
||
142 | } |
||
143 | |||
144 | /** |
||
145 | * Injects the request object for the current request or subrequest |
||
146 | * Simply calls main() and init() and outputs the content |
||
147 | * |
||
148 | * @param ServerRequestInterface $request the current request |
||
149 | * @param ResponseInterface $response |
||
150 | * @return ResponseInterface the response with the content |
||
151 | */ |
||
152 | public function mainAction(ServerRequestInterface $request, ResponseInterface $response) |
||
|
|||
153 | { |
||
154 | $this->CMD = GeneralUtility::_GP('CMD'); |
||
155 | $this->MOD_MENU = [ |
||
156 | 'function' => [ |
||
157 | 'scheduler' => $this->getLanguageService()->getLL('function.scheduler'), |
||
158 | 'check' => $this->getLanguageService()->getLL('function.check'), |
||
159 | 'info' => $this->getLanguageService()->getLL('function.info') |
||
160 | ] |
||
161 | ]; |
||
162 | $this->MOD_SETTINGS = BackendUtility::getModuleData($this->MOD_MENU, GeneralUtility::_GP('SET'), 'system_txschedulerM1', '', '', ''); |
||
163 | // Access check! |
||
164 | // The page will show only if user has admin rights |
||
165 | if ($this->getBackendUser()->isAdmin()) { |
||
166 | // Set the form |
||
167 | $content = '<form name="tx_scheduler_form" id="tx_scheduler_form" method="post" action="">'; |
||
168 | |||
169 | // Prepare main content |
||
170 | $content .= '<h1>' . $this->getLanguageService()->getLL('function.' . $this->MOD_SETTINGS['function']) . '</h1>'; |
||
171 | $content .= $this->getModuleContent(); |
||
172 | $content .= '<div id="extraFieldsSection"></div></form><div id="extraFieldsHidden"></div>'; |
||
173 | } else { |
||
174 | // If no access, only display the module's title |
||
175 | $content = '<h1>' . $this->getLanguageService()->getLL('title.') . '</h1>'; |
||
176 | $content .='<div style="padding-top: 5px;"></div>'; |
||
177 | } |
||
178 | $this->getButtons(); |
||
179 | $this->getModuleMenu(); |
||
180 | |||
181 | $this->moduleTemplate->setContent($content); |
||
182 | $response->getBody()->write($this->moduleTemplate->renderContent()); |
||
183 | return $response; |
||
184 | } |
||
185 | |||
186 | /** |
||
187 | * Generates the action menu |
||
188 | */ |
||
189 | protected function getModuleMenu() |
||
190 | { |
||
191 | $menu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu(); |
||
192 | $menu->setIdentifier('SchedulerJumpMenu'); |
||
193 | /** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */ |
||
194 | $uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class); |
||
195 | foreach ($this->MOD_MENU['function'] as $controller => $title) { |
||
196 | $item = $menu |
||
197 | ->makeMenuItem() |
||
198 | ->setHref( |
||
199 | (string)$uriBuilder->buildUriFromRoute( |
||
200 | 'system_txschedulerM1', |
||
201 | [ |
||
202 | 'id' => 0, |
||
203 | 'SET' => [ |
||
204 | 'function' => $controller |
||
205 | ] |
||
206 | ] |
||
207 | ) |
||
208 | ) |
||
209 | ->setTitle($title); |
||
210 | if ($controller === $this->MOD_SETTINGS['function']) { |
||
211 | $item->setActive(true); |
||
212 | } |
||
213 | $menu->addMenuItem($item); |
||
214 | } |
||
215 | $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($menu); |
||
216 | } |
||
217 | |||
218 | /** |
||
219 | * Generate the module's content |
||
220 | * |
||
221 | * @return string HTML of the module's main content |
||
222 | */ |
||
223 | protected function getModuleContent() |
||
318 | } |
||
319 | |||
320 | /** |
||
321 | * This method displays the result of a number of checks |
||
322 | * on whether the Scheduler is ready to run or running properly |
||
323 | * |
||
324 | * @return string Further information |
||
325 | */ |
||
326 | protected function checkScreenAction() |
||
327 | { |
||
328 | $this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'CheckScreen.html'); |
||
329 | |||
330 | // Display information about last automated run, as stored in the system registry |
||
331 | $registry = GeneralUtility::makeInstance(Registry::class); |
||
332 | $lastRun = $registry->get('tx_scheduler', 'lastRun'); |
||
333 | if (!is_array($lastRun)) { |
||
334 | $message = $this->getLanguageService()->getLL('msg.noLastRun'); |
||
335 | $severity = InfoboxViewHelper::STATE_WARNING; |
||
336 | } else { |
||
337 | if (empty($lastRun['end']) || empty($lastRun['start']) || empty($lastRun['type'])) { |
||
338 | $message = $this->getLanguageService()->getLL('msg.incompleteLastRun'); |
||
339 | $severity = InfoboxViewHelper::STATE_WARNING; |
||
340 | } else { |
||
341 | $startDate = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $lastRun['start']); |
||
342 | $startTime = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $lastRun['start']); |
||
343 | $endDate = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $lastRun['end']); |
||
344 | $endTime = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $lastRun['end']); |
||
345 | $label = 'automatically'; |
||
346 | if ($lastRun['type'] === 'manual') { |
||
347 | $label = 'manually'; |
||
348 | } |
||
349 | $type = $this->getLanguageService()->getLL('label.' . $label); |
||
350 | $message = sprintf($this->getLanguageService()->getLL('msg.lastRun'), $type, $startDate, $startTime, $endDate, $endTime); |
||
351 | $severity = InfoboxViewHelper::STATE_INFO; |
||
352 | } |
||
353 | } |
||
354 | $this->view->assign('lastRunMessage', $message); |
||
355 | $this->view->assign('lastRunSeverity', $severity); |
||
356 | |||
357 | // Check if CLI script is executable or not |
||
358 | $script = PATH_site . 'typo3/sysext/core/bin/typo3'; |
||
359 | $this->view->assign('script', $script); |
||
360 | |||
361 | // Skip this check if running Windows, as rights do not work the same way on this platform |
||
362 | // (i.e. the script will always appear as *not* executable) |
||
363 | if (TYPO3_OS === 'WIN') { |
||
364 | $isExecutable = true; |
||
365 | } else { |
||
366 | $isExecutable = is_executable($script); |
||
367 | } |
||
368 | if ($isExecutable) { |
||
369 | $message = $this->getLanguageService()->getLL('msg.cliScriptExecutable'); |
||
370 | $severity = InfoboxViewHelper::STATE_OK; |
||
371 | } else { |
||
372 | $message = $this->getLanguageService()->getLL('msg.cliScriptNotExecutable'); |
||
373 | $severity = InfoboxViewHelper::STATE_ERROR; |
||
374 | } |
||
375 | $this->view->assign('isExecutableMessage', $message); |
||
376 | $this->view->assign('isExecutableSeverity', $severity); |
||
377 | $this->view->assign('now', $this->getServerTime()); |
||
378 | |||
379 | return $this->view->render(); |
||
380 | } |
||
381 | |||
382 | /** |
||
383 | * This method gathers information about all available task classes and displays it |
||
384 | * |
||
385 | * @return string html |
||
386 | */ |
||
387 | protected function infoScreenAction() |
||
400 | } |
||
401 | |||
402 | /** |
||
403 | * Delete a task from the execution queue |
||
404 | */ |
||
405 | protected function deleteTask() |
||
406 | { |
||
407 | try { |
||
408 | // Try to fetch the task and delete it |
||
409 | $task = $this->scheduler->fetchTask($this->submittedData['uid']); |
||
410 | // If the task is currently running, it may not be deleted |
||
411 | if ($task->isExecutionRunning()) { |
||
412 | $this->addMessage($this->getLanguageService()->getLL('msg.maynotDeleteRunningTask'), FlashMessage::ERROR); |
||
413 | } else { |
||
414 | if ($this->scheduler->removeTask($task)) { |
||
415 | $this->getBackendUser()->writelog(4, 0, 0, 0, 'Scheduler task "%s" (UID: %s, Class: "%s") was deleted', [$task->getTaskTitle(), $task->getTaskUid(), $task->getTaskClassName()]); |
||
416 | $this->addMessage($this->getLanguageService()->getLL('msg.deleteSuccess')); |
||
417 | } else { |
||
418 | $this->addMessage($this->getLanguageService()->getLL('msg.deleteError'), FlashMessage::ERROR); |
||
419 | } |
||
420 | } |
||
421 | } catch (\UnexpectedValueException $e) { |
||
422 | // The task could not be unserialized properly, simply update the database record |
||
423 | $taskUid = (int)$this->submittedData['uid']; |
||
424 | $result = GeneralUtility::makeInstance(ConnectionPool::class) |
||
425 | ->getConnectionForTable('tx_scheduler_task') |
||
426 | ->update('tx_scheduler_task', ['deleted' => 1], ['uid' => $taskUid]); |
||
427 | if ($result) { |
||
428 | $this->addMessage($this->getLanguageService()->getLL('msg.deleteSuccess')); |
||
429 | } else { |
||
430 | $this->addMessage($this->getLanguageService()->getLL('msg.deleteError'), FlashMessage::ERROR); |
||
431 | } |
||
432 | } catch (\OutOfBoundsException $e) { |
||
433 | // The task was not found, for some reason |
||
434 | $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.taskNotFound'), $this->submittedData['uid']), FlashMessage::ERROR); |
||
435 | } |
||
436 | } |
||
437 | |||
438 | /** |
||
439 | * Clears the registered running executions from the task |
||
440 | * Note that this doesn't actually stop the running script. It just unmarks |
||
441 | * all executions. |
||
442 | * @todo find a way to really kill the running task |
||
443 | */ |
||
444 | protected function stopTask() |
||
445 | { |
||
446 | try { |
||
447 | // Try to fetch the task and stop it |
||
448 | $task = $this->scheduler->fetchTask($this->submittedData['uid']); |
||
449 | if ($task->isExecutionRunning()) { |
||
450 | // If the task is indeed currently running, clear marked executions |
||
451 | $result = $task->unmarkAllExecutions(); |
||
452 | if ($result) { |
||
453 | $this->addMessage($this->getLanguageService()->getLL('msg.stopSuccess')); |
||
454 | } else { |
||
455 | $this->addMessage($this->getLanguageService()->getLL('msg.stopError'), FlashMessage::ERROR); |
||
456 | } |
||
457 | } else { |
||
458 | // The task is not running, nothing to unmark |
||
459 | $this->addMessage($this->getLanguageService()->getLL('msg.maynotStopNonRunningTask'), FlashMessage::WARNING); |
||
460 | } |
||
461 | } catch (\Exception $e) { |
||
462 | // The task was not found, for some reason |
||
463 | $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.taskNotFound'), $this->submittedData['uid']), FlashMessage::ERROR); |
||
464 | } |
||
465 | } |
||
466 | |||
467 | /** |
||
468 | * Toggles the disabled state of the submitted task |
||
469 | */ |
||
470 | protected function toggleDisableAction() |
||
471 | { |
||
472 | $task = $this->scheduler->fetchTask($this->submittedData['uid']); |
||
473 | $task->setDisabled(!$task->isDisabled()); |
||
474 | // If a disabled single task is enabled again, we register it for a |
||
475 | // single execution at next scheduler run. |
||
476 | if ($task->getType() === AbstractTask::TYPE_SINGLE) { |
||
477 | $task->registerSingleExecution(time()); |
||
478 | } |
||
479 | $task->save(); |
||
480 | } |
||
481 | |||
482 | /** |
||
483 | * Sets the next execution time of the submitted task to now |
||
484 | */ |
||
485 | protected function setNextExecutionTimeAction() |
||
486 | { |
||
487 | $task = $this->scheduler->fetchTask($this->submittedData['uid']); |
||
488 | $task->setRunOnNextCronJob(true); |
||
489 | $task->save(); |
||
490 | } |
||
491 | |||
492 | /** |
||
493 | * Return a form to add a new task or edit an existing one |
||
494 | * |
||
495 | * @return string HTML form to add or edit a task |
||
496 | */ |
||
497 | protected function editTaskAction() |
||
498 | { |
||
499 | $this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'EditTask.html'); |
||
500 | |||
501 | $registeredClasses = $this->getRegisteredClasses(); |
||
502 | $registeredTaskGroups = $this->getRegisteredTaskGroups(); |
||
503 | |||
504 | $taskInfo = []; |
||
505 | $task = null; |
||
506 | $process = 'edit'; |
||
507 | |||
508 | if ($this->submittedData['uid'] > 0) { |
||
509 | // If editing, retrieve data for existing task |
||
510 | try { |
||
511 | $taskRecord = $this->scheduler->fetchTaskRecord($this->submittedData['uid']); |
||
512 | // If there's a registered execution, the task should not be edited |
||
513 | if (!empty($taskRecord['serialized_executions'])) { |
||
514 | $this->addMessage($this->getLanguageService()->getLL('msg.maynotEditRunningTask'), FlashMessage::ERROR); |
||
515 | throw new \LogicException('Runnings tasks cannot not be edited', 1251232849); |
||
516 | } |
||
517 | |||
518 | // Get the task object |
||
519 | /** @var $task \TYPO3\CMS\Scheduler\Task\AbstractTask */ |
||
520 | $task = unserialize($taskRecord['serialized_task_object']); |
||
521 | |||
522 | // Set some task information |
||
523 | $taskInfo['disable'] = $taskRecord['disable']; |
||
524 | $taskInfo['description'] = $taskRecord['description']; |
||
525 | $taskInfo['task_group'] = $taskRecord['task_group']; |
||
526 | |||
527 | // Check that the task object is valid |
||
528 | if (isset($registeredClasses[get_class($task)]) && $this->scheduler->isValidTaskObject($task)) { |
||
529 | // The task object is valid, process with fetching current data |
||
530 | $taskInfo['class'] = get_class($task); |
||
531 | // Get execution information |
||
532 | $taskInfo['start'] = (int)$task->getExecution()->getStart(); |
||
533 | $taskInfo['end'] = (int)$task->getExecution()->getEnd(); |
||
534 | $taskInfo['interval'] = $task->getExecution()->getInterval(); |
||
535 | $taskInfo['croncmd'] = $task->getExecution()->getCronCmd(); |
||
536 | $taskInfo['multiple'] = $task->getExecution()->getMultiple(); |
||
537 | if (!empty($taskInfo['interval']) || !empty($taskInfo['croncmd'])) { |
||
538 | // Guess task type from the existing information |
||
539 | // If an interval or a cron command is defined, it's a recurring task |
||
540 | $taskInfo['type'] = AbstractTask::TYPE_RECURRING; |
||
541 | $taskInfo['frequency'] = $taskInfo['interval'] ?: $taskInfo['croncmd']; |
||
542 | } else { |
||
543 | // It's not a recurring task |
||
544 | // Make sure interval and cron command are both empty |
||
545 | $taskInfo['type'] = AbstractTask::TYPE_SINGLE; |
||
546 | $taskInfo['frequency'] = ''; |
||
547 | $taskInfo['end'] = 0; |
||
548 | } |
||
549 | } else { |
||
550 | // The task object is not valid |
||
551 | // Issue error message |
||
552 | $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.invalidTaskClassEdit'), get_class($task)), FlashMessage::ERROR); |
||
553 | // Initialize empty values |
||
554 | $taskInfo['start'] = 0; |
||
555 | $taskInfo['end'] = 0; |
||
556 | $taskInfo['frequency'] = ''; |
||
557 | $taskInfo['multiple'] = false; |
||
558 | $taskInfo['type'] = AbstractTask::TYPE_SINGLE; |
||
559 | } |
||
560 | } catch (\OutOfBoundsException $e) { |
||
561 | // Add a message and continue throwing the exception |
||
562 | $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.taskNotFound'), $this->submittedData['uid']), FlashMessage::ERROR); |
||
563 | throw $e; |
||
564 | } |
||
565 | } else { |
||
566 | // If adding a new object, set some default values |
||
567 | $taskInfo['class'] = key($registeredClasses); |
||
568 | $taskInfo['type'] = AbstractTask::TYPE_RECURRING; |
||
569 | $taskInfo['start'] = $GLOBALS['EXEC_TIME']; |
||
570 | $taskInfo['end'] = ''; |
||
571 | $taskInfo['frequency'] = ''; |
||
572 | $taskInfo['multiple'] = 0; |
||
573 | $process = 'add'; |
||
574 | } |
||
575 | |||
576 | // If some data was already submitted, use it to override |
||
577 | // existing data |
||
578 | if (!empty($this->submittedData)) { |
||
579 | ArrayUtility::mergeRecursiveWithOverrule($taskInfo, $this->submittedData); |
||
580 | } |
||
581 | |||
582 | // Get the extra fields to display for each task that needs some |
||
583 | $allAdditionalFields = []; |
||
584 | if ($process === 'add') { |
||
585 | foreach ($registeredClasses as $class => $registrationInfo) { |
||
586 | if (!empty($registrationInfo['provider'])) { |
||
587 | /** @var $providerObject AdditionalFieldProviderInterface */ |
||
588 | $providerObject = GeneralUtility::makeInstance($registrationInfo['provider']); |
||
589 | if ($providerObject instanceof AdditionalFieldProviderInterface) { |
||
590 | $additionalFields = $providerObject->getAdditionalFields($taskInfo, null, $this); |
||
591 | $allAdditionalFields = array_merge($allAdditionalFields, [$class => $additionalFields]); |
||
592 | } |
||
593 | } |
||
594 | } |
||
595 | } elseif ($task !== null && !empty($registeredClasses[$taskInfo['class']]['provider'])) { |
||
596 | // only try to fetch additionalFields if the task is valid |
||
597 | $providerObject = GeneralUtility::makeInstance($registeredClasses[$taskInfo['class']]['provider']); |
||
598 | if ($providerObject instanceof AdditionalFieldProviderInterface) { |
||
599 | $allAdditionalFields[$taskInfo['class']] = $providerObject->getAdditionalFields($taskInfo, $task, $this); |
||
600 | } |
||
601 | } |
||
602 | |||
603 | // Load necessary JavaScript |
||
604 | $this->getPageRenderer()->loadJquery(); |
||
605 | $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Scheduler/Scheduler'); |
||
606 | $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/DateTimePicker'); |
||
607 | $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Scheduler/PageBrowser'); |
||
608 | $this->getPageRenderer()->addJsInlineCode('browse-button', ' |
||
609 | function setFormValueFromBrowseWin(fieldReference, elValue, elName) { |
||
610 | var res = elValue.split("_"); |
||
611 | var element = document.getElementById(fieldReference); |
||
612 | element.value = res[1]; |
||
613 | } |
||
614 | '); |
||
615 | |||
616 | // Start rendering the add/edit form |
||
617 | $this->view->assign('uid', htmlspecialchars($this->submittedData['uid'])); |
||
618 | $this->view->assign('cmd', htmlspecialchars($this->CMD)); |
||
619 | $this->view->assign('csh', $this->cshKey); |
||
620 | $this->view->assign('lang', 'LLL:EXT:scheduler/Resources/Private/Language/locallang.xlf:'); |
||
621 | |||
622 | $table = []; |
||
623 | |||
624 | // Disable checkbox |
||
625 | $this->view->assign('task_disable', ($taskInfo['disable'] ? ' checked="checked"' : '')); |
||
626 | $this->view->assign('task_disable_label', 'LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:disable'); |
||
627 | |||
628 | // Task class selector |
||
629 | // On editing, don't allow changing of the task class, unless it was not valid |
||
630 | if ($this->submittedData['uid'] > 0 && !empty($taskInfo['class'])) { |
||
631 | $this->view->assign('task_class', $taskInfo['class']); |
||
632 | $this->view->assign('task_class_title', $registeredClasses[$taskInfo['class']]['title']); |
||
633 | $this->view->assign('task_class_extension', $registeredClasses[$taskInfo['class']]['extension']); |
||
634 | } else { |
||
635 | // Group registered classes by classname |
||
636 | $groupedClasses = []; |
||
637 | foreach ($registeredClasses as $class => $classInfo) { |
||
638 | $groupedClasses[$classInfo['extension']][$class] = $classInfo; |
||
639 | } |
||
640 | ksort($groupedClasses); |
||
641 | foreach ($groupedClasses as $extension => $class) { |
||
642 | foreach ($groupedClasses[$extension] as $class => $classInfo) { |
||
643 | $selected = $class == $taskInfo['class'] ? ' selected="selected"' : ''; |
||
644 | $groupedClasses[$extension][$class]['selected'] = $selected; |
||
645 | } |
||
646 | } |
||
647 | $this->view->assign('groupedClasses', $groupedClasses); |
||
648 | } |
||
649 | |||
650 | // Task type selector |
||
651 | $this->view->assign('task_type_selected_1', ((int)$taskInfo['type'] === AbstractTask::TYPE_SINGLE ? ' selected="selected"' : '')); |
||
652 | $this->view->assign('task_type_selected_2', ((int)$taskInfo['type'] === AbstractTask::TYPE_RECURRING ? ' selected="selected"' : '')); |
||
653 | |||
654 | // Task group selector |
||
655 | foreach ($registeredTaskGroups as $key => $taskGroup) { |
||
656 | $selected = $taskGroup['uid'] == $taskInfo['task_group'] ? ' selected="selected"' : ''; |
||
657 | $registeredTaskGroups[$key]['selected'] = $selected; |
||
658 | } |
||
659 | $this->view->assign('registeredTaskGroups', $registeredTaskGroups); |
||
660 | |||
661 | // Start date/time field |
||
662 | $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['USdateFormat'] ? '%H:%M %m-%d-%Y' : '%H:%M %d-%m-%Y'; |
||
663 | $this->view->assign('start_value_hr', ($taskInfo['start'] > 0 ? strftime($dateFormat, $taskInfo['start']) : '')); |
||
664 | $this->view->assign('start_value', $taskInfo['start']); |
||
665 | |||
666 | // End date/time field |
||
667 | // NOTE: datetime fields need a special id naming scheme |
||
668 | $this->view->assign('end_value_hr', ($taskInfo['end'] > 0 ? strftime($dateFormat, $taskInfo['end']) : '')); |
||
669 | $this->view->assign('end_value', $taskInfo['end']); |
||
670 | |||
671 | // Frequency input field |
||
672 | $this->view->assign('frequency', $taskInfo['frequency']); |
||
673 | |||
674 | // Multiple execution selector |
||
675 | $this->view->assign('multiple', ($taskInfo['multiple'] ? 'checked="checked"' : '')); |
||
676 | |||
677 | // Description |
||
678 | $this->view->assign('description', $taskInfo['description']); |
||
679 | |||
680 | // Display additional fields |
||
681 | $additionalFieldList = []; |
||
682 | foreach ($allAdditionalFields as $class => $fields) { |
||
683 | if ($class == $taskInfo['class']) { |
||
684 | $additionalFieldsStyle = ''; |
||
685 | } else { |
||
686 | $additionalFieldsStyle = ' style="display: none"'; |
||
687 | } |
||
688 | // Add each field to the display, if there are indeed any |
||
689 | if (isset($fields) && is_array($fields)) { |
||
690 | foreach ($fields as $fieldID => $fieldInfo) { |
||
691 | $htmlClassName = strtolower(str_replace('\\', '-', $class)); |
||
692 | $field = []; |
||
693 | $field['htmlClassName'] = $htmlClassName; |
||
694 | $field['code'] = $fieldInfo['code']; |
||
695 | $field['cshKey'] = $fieldInfo['cshKey']; |
||
696 | $field['cshLabel'] = $fieldInfo['cshLabel']; |
||
697 | $field['langLabel'] = $fieldInfo['label']; |
||
698 | $field['fieldID'] = $fieldID; |
||
699 | $field['additionalFieldsStyle'] = $additionalFieldsStyle; |
||
700 | $field['browseButton'] = $this->getBrowseButton($fieldID, $fieldInfo); |
||
701 | $additionalFieldList[] = $field; |
||
702 | } |
||
703 | } |
||
704 | } |
||
705 | $this->view->assign('additionalFields', $additionalFieldList); |
||
706 | |||
707 | $this->view->assign('table', implode(LF, $table)); |
||
708 | $this->view->assign('now', $this->getServerTime()); |
||
709 | |||
710 | return $this->view->render(); |
||
711 | } |
||
712 | |||
713 | /** |
||
714 | * @param string $fieldID The id of the field witch contains the page id |
||
715 | * @param array $fieldInfo The array with the field info, contains the page title shown beside the button |
||
716 | * @return string HTML code for the browse button |
||
717 | */ |
||
718 | protected function getBrowseButton($fieldID, array $fieldInfo) |
||
719 | { |
||
720 | if (isset($fieldInfo['browser']) && ($fieldInfo['browser'] === 'page')) { |
||
721 | /** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */ |
||
722 | $uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class); |
||
723 | $url = (string)$uriBuilder->buildUriFromRoute( |
||
724 | 'wizard_element_browser', |
||
725 | ['mode' => 'db', 'bparams' => $fieldID . '|||pages|'] |
||
726 | ); |
||
727 | $title = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.browse_db')); |
||
728 | return ' |
||
729 | <div><a href="#" data-url=' . htmlspecialchars($url) . ' class="btn btn-default t3js-pageBrowser" title="' . $title . '"> |
||
730 | <span class="t3js-icon icon icon-size-small icon-state-default icon-actions-insert-record" data-identifier="actions-insert-record"> |
||
731 | <span class="icon-markup">' . $this->iconFactory->getIcon( |
||
732 | 'actions-insert-record', |
||
733 | Icon::SIZE_SMALL |
||
734 | )->render() . '</span> |
||
735 | </span> |
||
736 | </a><span id="page_' . $fieldID . '"> ' . htmlspecialchars($fieldInfo['pageTitle']) . '</span></div>'; |
||
737 | } |
||
738 | return ''; |
||
739 | } |
||
740 | |||
741 | /** |
||
742 | * Execute all selected tasks |
||
743 | */ |
||
744 | protected function executeTasks() |
||
745 | { |
||
746 | // Continue if some elements have been chosen for execution |
||
747 | if (isset($this->submittedData['execute']) && !empty($this->submittedData['execute'])) { |
||
748 | // Get list of registered classes |
||
749 | $registeredClasses = $this->getRegisteredClasses(); |
||
750 | // Loop on all selected tasks |
||
751 | foreach ($this->submittedData['execute'] as $uid) { |
||
752 | try { |
||
753 | // Try fetching the task |
||
754 | $task = $this->scheduler->fetchTask($uid); |
||
755 | $class = get_class($task); |
||
756 | $name = $registeredClasses[$class]['title'] . ' (' . $registeredClasses[$class]['extension'] . ')'; |
||
757 | if (GeneralUtility::_POST('go_cron') !== null) { |
||
758 | $task->setRunOnNextCronJob(true); |
||
759 | $task->save(); |
||
760 | } else { |
||
761 | // Now try to execute it and report on outcome |
||
762 | try { |
||
763 | $result = $this->scheduler->executeTask($task); |
||
764 | if ($result) { |
||
765 | $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.executed'), $name)); |
||
766 | } else { |
||
767 | $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.notExecuted'), $name), FlashMessage::ERROR); |
||
768 | } |
||
769 | } catch (\Exception $e) { |
||
770 | // An exception was thrown, display its message as an error |
||
771 | $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.executionFailed'), $name, $e->getMessage()), FlashMessage::ERROR); |
||
772 | } |
||
773 | } |
||
774 | } catch (\OutOfBoundsException $e) { |
||
775 | $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.taskNotFound'), $uid), FlashMessage::ERROR); |
||
776 | } catch (\UnexpectedValueException $e) { |
||
777 | $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.executionFailed'), $uid, $e->getMessage()), FlashMessage::ERROR); |
||
778 | } |
||
779 | } |
||
780 | // Record the run in the system registry |
||
781 | $this->scheduler->recordLastRun('manual'); |
||
782 | // Make sure to switch to list view after execution |
||
783 | $this->CMD = 'list'; |
||
784 | } |
||
785 | } |
||
786 | |||
787 | /** |
||
788 | * Assemble display of list of scheduled tasks |
||
789 | * |
||
790 | * @return string Table of pending tasks |
||
791 | */ |
||
792 | protected function listTasksAction() |
||
793 | { |
||
794 | $this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'ListTasks.html'); |
||
795 | |||
796 | // Define display format for dates |
||
797 | $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm']; |
||
798 | |||
799 | // Get list of registered task groups |
||
800 | $registeredTaskGroups = $this->getRegisteredTaskGroups(); |
||
801 | |||
802 | // add an empty entry for non-grouped tasks |
||
803 | // add in front of list |
||
804 | array_unshift($registeredTaskGroups, ['uid' => 0, 'groupName' => '']); |
||
805 | |||
806 | // Get all registered tasks |
||
807 | // Just to get the number of entries |
||
808 | $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class) |
||
809 | ->getQueryBuilderForTable('tx_scheduler_task'); |
||
810 | $queryBuilder->getRestrictions()->removeAll(); |
||
811 | |||
812 | $result = $queryBuilder->select('t.*') |
||
813 | ->addSelect( |
||
814 | 'g.groupName AS taskGroupName', |
||
815 | 'g.description AS taskGroupDescription', |
||
816 | 'g.deleted AS isTaskGroupDeleted' |
||
817 | ) |
||
818 | ->from('tx_scheduler_task', 't') |
||
819 | ->leftJoin( |
||
820 | 't', |
||
821 | 'tx_scheduler_task_group', |
||
822 | 'g', |
||
823 | $queryBuilder->expr()->eq('t.task_group', $queryBuilder->quoteIdentifier('g.uid')) |
||
824 | ) |
||
825 | ->where( |
||
826 | $queryBuilder->expr()->eq('t.deleted', 0) |
||
827 | ) |
||
828 | ->orderBy('g.sorting') |
||
829 | ->execute(); |
||
830 | |||
831 | // Loop on all tasks |
||
832 | $temporaryResult = []; |
||
833 | while ($row = $result->fetch()) { |
||
834 | if ($row['taskGroupName'] === null || $row['isTaskGroupDeleted'] === '1') { |
||
835 | $row['taskGroupName'] = ''; |
||
836 | $row['taskGroupDescription'] = ''; |
||
837 | $row['task_group'] = 0; |
||
838 | } |
||
839 | $temporaryResult[$row['task_group']]['groupName'] = $row['taskGroupName']; |
||
840 | $temporaryResult[$row['task_group']]['groupDescription'] = $row['taskGroupDescription']; |
||
841 | $temporaryResult[$row['task_group']]['tasks'][] = $row; |
||
842 | } |
||
843 | |||
844 | // No tasks defined, display information message |
||
845 | if (empty($temporaryResult)) { |
||
846 | $this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'ListTasksNoTasks.html'); |
||
847 | return $this->view->render(); |
||
848 | } |
||
849 | |||
850 | $this->getPageRenderer()->loadJquery(); |
||
851 | $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Scheduler/Scheduler'); |
||
852 | $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/Tooltip'); |
||
853 | |||
854 | $tasks = $temporaryResult; |
||
855 | |||
856 | $registeredClasses = $this->getRegisteredClasses(); |
||
857 | $missingClasses = []; |
||
858 | foreach ($temporaryResult as $taskIndex => $taskGroup) { |
||
859 | foreach ($taskGroup['tasks'] as $recordIndex => $schedulerRecord) { |
||
860 | if ((int)$schedulerRecord['disable'] === 1) { |
||
861 | $translationKey = 'enable'; |
||
862 | } else { |
||
863 | $translationKey = 'disable'; |
||
864 | } |
||
865 | $tasks[$taskIndex]['tasks'][$recordIndex]['translationKey'] = $translationKey; |
||
866 | |||
867 | // Define some default values |
||
868 | $lastExecution = '-'; |
||
869 | $isRunning = false; |
||
870 | $showAsDisabled = false; |
||
871 | // Restore the serialized task and pass it a reference to the scheduler object |
||
872 | /** @var $task \TYPO3\CMS\Scheduler\Task\AbstractTask|ProgressProviderInterface */ |
||
873 | $task = unserialize($schedulerRecord['serialized_task_object']); |
||
874 | $class = get_class($task); |
||
875 | if ($class === '__PHP_Incomplete_Class' && preg_match('/^O:[0-9]+:"(?P<classname>.+?)"/', $schedulerRecord['serialized_task_object'], $matches) === 1) { |
||
876 | $class = $matches['classname']; |
||
877 | } |
||
878 | $tasks[$taskIndex]['tasks'][$recordIndex]['class'] = $class; |
||
879 | // Assemble information about last execution |
||
880 | if (!empty($schedulerRecord['lastexecution_time'])) { |
||
881 | $lastExecution = date($dateFormat, $schedulerRecord['lastexecution_time']); |
||
882 | if ($schedulerRecord['lastexecution_context'] === 'CLI') { |
||
883 | $context = $this->getLanguageService()->getLL('label.cron'); |
||
884 | } else { |
||
885 | $context = $this->getLanguageService()->getLL('label.manual'); |
||
886 | } |
||
887 | $lastExecution .= ' (' . $context . ')'; |
||
888 | } |
||
889 | $tasks[$taskIndex]['tasks'][$recordIndex]['lastExecution'] = $lastExecution; |
||
890 | |||
891 | if (isset($registeredClasses[get_class($task)]) && $this->scheduler->isValidTaskObject($task)) { |
||
892 | $tasks[$taskIndex]['tasks'][$recordIndex]['validClass'] = true; |
||
893 | // The task object is valid |
||
894 | $labels = []; |
||
895 | $additionalInformation = $task->getAdditionalInformation(); |
||
896 | if ($task instanceof ProgressProviderInterface) { |
||
897 | $progress = round((float)$task->getProgress(), 2); |
||
898 | $tasks[$taskIndex]['tasks'][$recordIndex]['progress'] = $progress; |
||
899 | } |
||
900 | $tasks[$taskIndex]['tasks'][$recordIndex]['classTitle'] = $registeredClasses[$class]['title']; |
||
901 | $tasks[$taskIndex]['tasks'][$recordIndex]['classExtension'] = $registeredClasses[$class]['extension']; |
||
902 | $tasks[$taskIndex]['tasks'][$recordIndex]['additionalInformation'] = $additionalInformation; |
||
903 | // Check if task currently has a running execution |
||
904 | if (!empty($schedulerRecord['serialized_executions'])) { |
||
905 | $labels[] = [ |
||
906 | 'class' => 'success', |
||
907 | 'text' => $this->getLanguageService()->getLL('status.running') |
||
908 | ]; |
||
909 | $isRunning = true; |
||
910 | } |
||
911 | $tasks[$taskIndex]['tasks'][$recordIndex]['isRunning'] = $isRunning; |
||
912 | |||
913 | // Prepare display of next execution date |
||
914 | // If task is currently running, date is not displayed (as next hasn't been calculated yet) |
||
915 | // Also hide the date if task is disabled (the information doesn't make sense, as it will not run anyway) |
||
916 | if ($isRunning || $schedulerRecord['disable']) { |
||
917 | $nextDate = '-'; |
||
918 | } else { |
||
919 | $nextDate = date($dateFormat, $schedulerRecord['nextexecution']); |
||
920 | if (empty($schedulerRecord['nextexecution'])) { |
||
921 | $nextDate = $this->getLanguageService()->getLL('none'); |
||
922 | } elseif ($schedulerRecord['nextexecution'] < $GLOBALS['EXEC_TIME']) { |
||
923 | $labels[] = [ |
||
924 | 'class' => 'warning', |
||
925 | 'text' => $this->getLanguageService()->getLL('status.late'), |
||
926 | 'description' => $this->getLanguageService()->getLL('status.legend.scheduled') |
||
927 | ]; |
||
928 | } |
||
929 | } |
||
930 | $tasks[$taskIndex]['tasks'][$recordIndex]['nextDate'] = $nextDate; |
||
931 | // Get execution type |
||
932 | if ($task->getType() === AbstractTask::TYPE_SINGLE) { |
||
933 | $execType = $this->getLanguageService()->getLL('label.type.single'); |
||
934 | $frequency = '-'; |
||
935 | } else { |
||
936 | $execType = $this->getLanguageService()->getLL('label.type.recurring'); |
||
937 | if ($task->getExecution()->getCronCmd() == '') { |
||
938 | $frequency = $task->getExecution()->getInterval(); |
||
939 | } else { |
||
940 | $frequency = $task->getExecution()->getCronCmd(); |
||
941 | } |
||
942 | } |
||
943 | // Check the disable status |
||
944 | // Row is shown dimmed if task is disabled, unless it is still running |
||
945 | if ($schedulerRecord['disable'] && !$isRunning) { |
||
946 | $labels[] = [ |
||
947 | 'class' => 'default', |
||
948 | 'text' => $this->getLanguageService()->getLL('status.disabled') |
||
949 | ]; |
||
950 | $showAsDisabled = true; |
||
951 | } |
||
952 | $tasks[$taskIndex]['tasks'][$recordIndex]['execType'] = $execType; |
||
953 | $tasks[$taskIndex]['tasks'][$recordIndex]['frequency'] = $frequency; |
||
954 | // Get multiple executions setting |
||
955 | if ($task->getExecution()->getMultiple()) { |
||
956 | $multiple = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:yes'); |
||
957 | } else { |
||
958 | $multiple = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:no'); |
||
959 | } |
||
960 | $tasks[$taskIndex]['tasks'][$recordIndex]['multiple'] = $multiple; |
||
961 | |||
962 | // Check if the last run failed |
||
963 | if (!empty($schedulerRecord['lastexecution_failure'])) { |
||
964 | // Try to get the stored exception array |
||
965 | /** @var $exceptionArray array */ |
||
966 | $exceptionArray = @unserialize($schedulerRecord['lastexecution_failure']); |
||
967 | // If the exception could not be unserialized, issue a default error message |
||
968 | if (!is_array($exceptionArray) || empty($exceptionArray)) { |
||
969 | $labelDescription = $this->getLanguageService()->getLL('msg.executionFailureDefault'); |
||
970 | } else { |
||
971 | $labelDescription = sprintf($this->getLanguageService()->getLL('msg.executionFailureReport'), $exceptionArray['code'], $exceptionArray['message']); |
||
972 | } |
||
973 | $labels[] = [ |
||
974 | 'class' => 'danger', |
||
975 | 'text' => $this->getLanguageService()->getLL('status.failure'), |
||
976 | 'description' => $labelDescription |
||
977 | ]; |
||
978 | } |
||
979 | $tasks[$taskIndex]['tasks'][$recordIndex]['labels'] = $labels; |
||
980 | if ($showAsDisabled) { |
||
981 | $tasks[$taskIndex]['tasks'][$recordIndex]['showAsDisabled'] = 'disabled'; |
||
982 | } |
||
983 | } else { |
||
984 | $missingClasses[] = $tasks[$taskIndex]['tasks'][$recordIndex]; |
||
985 | unset($tasks[$taskIndex]['tasks'][$recordIndex]); |
||
986 | } |
||
987 | } |
||
988 | } |
||
989 | |||
990 | $this->view->assign('tasks', $tasks); |
||
991 | $this->view->assign('missingClasses', $missingClasses); |
||
992 | $this->view->assign('moduleUri', $this->moduleUri); |
||
993 | $this->view->assign('now', $this->getServerTime()); |
||
994 | |||
995 | return $this->view->render(); |
||
996 | } |
||
997 | |||
998 | /** |
||
999 | * Generates bootstrap labels containing the label statuses |
||
1000 | * |
||
1001 | * @param array $labels |
||
1002 | * @return string |
||
1003 | */ |
||
1004 | protected function makeStatusLabel(array $labels) |
||
1015 | } |
||
1016 | |||
1017 | /** |
||
1018 | * Saves a task specified in the backend form to the database |
||
1019 | */ |
||
1020 | protected function saveTask() |
||
1021 | { |
||
1022 | // If a task is being edited fetch old task data |
||
1023 | if (!empty($this->submittedData['uid'])) { |
||
1024 | try { |
||
1025 | $taskRecord = $this->scheduler->fetchTaskRecord($this->submittedData['uid']); |
||
1026 | /** @var $task \TYPO3\CMS\Scheduler\Task\AbstractTask */ |
||
1027 | $task = unserialize($taskRecord['serialized_task_object']); |
||
1028 | } catch (\OutOfBoundsException $e) { |
||
1029 | // If the task could not be fetched, issue an error message |
||
1030 | // and exit early |
||
1031 | $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.taskNotFound'), $this->submittedData['uid']), FlashMessage::ERROR); |
||
1032 | return; |
||
1033 | } |
||
1034 | // Register single execution |
||
1035 | if ((int)$this->submittedData['type'] === AbstractTask::TYPE_SINGLE) { |
||
1036 | $task->registerSingleExecution($this->submittedData['start']); |
||
1037 | } else { |
||
1038 | if (!empty($this->submittedData['croncmd'])) { |
||
1039 | // Definition by cron-like syntax |
||
1040 | $interval = 0; |
||
1041 | $cronCmd = $this->submittedData['croncmd']; |
||
1042 | } else { |
||
1043 | // Definition by interval |
||
1044 | $interval = $this->submittedData['interval']; |
||
1045 | $cronCmd = ''; |
||
1046 | } |
||
1047 | // Register recurring execution |
||
1048 | $task->registerRecurringExecution($this->submittedData['start'], $interval, $this->submittedData['end'], $this->submittedData['multiple'], $cronCmd); |
||
1049 | } |
||
1050 | // Set disable flag |
||
1051 | $task->setDisabled($this->submittedData['disable']); |
||
1052 | // Set description |
||
1053 | $task->setDescription($this->submittedData['description']); |
||
1054 | // Set task group |
||
1055 | $task->setTaskGroup($this->submittedData['task_group']); |
||
1056 | // Save additional input values |
||
1057 | if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) { |
||
1058 | /** @var $providerObject AdditionalFieldProviderInterface */ |
||
1059 | $providerObject = GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']); |
||
1060 | if ($providerObject instanceof AdditionalFieldProviderInterface) { |
||
1061 | $providerObject->saveAdditionalFields($this->submittedData, $task); |
||
1062 | } |
||
1063 | } |
||
1064 | // Save to database |
||
1065 | $result = $this->scheduler->saveTask($task); |
||
1066 | if ($result) { |
||
1067 | $this->getBackendUser()->writelog(4, 0, 0, 0, 'Scheduler task "%s" (UID: %s, Class: "%s") was updated', [$task->getTaskTitle(), $task->getTaskUid(), $task->getTaskClassName()]); |
||
1068 | $this->addMessage($this->getLanguageService()->getLL('msg.updateSuccess')); |
||
1069 | } else { |
||
1070 | $this->addMessage($this->getLanguageService()->getLL('msg.updateError'), FlashMessage::ERROR); |
||
1071 | } |
||
1072 | } else { |
||
1073 | // A new task is being created |
||
1074 | // Create an instance of chosen class |
||
1075 | /** @var $task AbstractTask */ |
||
1076 | $task = GeneralUtility::makeInstance($this->submittedData['class']); |
||
1077 | if ((int)$this->submittedData['type'] === AbstractTask::TYPE_SINGLE) { |
||
1078 | // Set up single execution |
||
1079 | $task->registerSingleExecution($this->submittedData['start']); |
||
1080 | } else { |
||
1081 | // Set up recurring execution |
||
1082 | $task->registerRecurringExecution($this->submittedData['start'], $this->submittedData['interval'], $this->submittedData['end'], $this->submittedData['multiple'], $this->submittedData['croncmd']); |
||
1083 | } |
||
1084 | // Save additional input values |
||
1085 | if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) { |
||
1086 | /** @var $providerObject AdditionalFieldProviderInterface */ |
||
1087 | $providerObject = GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']); |
||
1088 | if ($providerObject instanceof AdditionalFieldProviderInterface) { |
||
1089 | $providerObject->saveAdditionalFields($this->submittedData, $task); |
||
1090 | } |
||
1091 | } |
||
1092 | // Set disable flag |
||
1093 | $task->setDisabled($this->submittedData['disable']); |
||
1094 | // Set description |
||
1095 | $task->setDescription($this->submittedData['description']); |
||
1096 | // Set description |
||
1097 | $task->setTaskGroup($this->submittedData['task_group']); |
||
1098 | // Add to database |
||
1099 | $result = $this->scheduler->addTask($task); |
||
1100 | if ($result) { |
||
1101 | $this->getBackendUser()->writelog(4, 0, 0, 0, 'Scheduler task "%s" (UID: %s, Class: "%s") was added', [$task->getTaskTitle(), $task->getTaskUid(), $task->getTaskClassName()]); |
||
1102 | $this->addMessage($this->getLanguageService()->getLL('msg.addSuccess')); |
||
1103 | |||
1104 | // set the uid of the just created task so that we |
||
1105 | // can continue editing after initial saving |
||
1106 | $this->submittedData['uid'] = $task->getTaskUid(); |
||
1107 | } else { |
||
1108 | $this->addMessage($this->getLanguageService()->getLL('msg.addError'), FlashMessage::ERROR); |
||
1109 | } |
||
1110 | } |
||
1111 | } |
||
1112 | |||
1113 | /************************* |
||
1114 | * |
||
1115 | * INPUT PROCESSING UTILITIES |
||
1116 | * |
||
1117 | *************************/ |
||
1118 | /** |
||
1119 | * Checks the submitted data and performs some pre-processing on it |
||
1120 | * |
||
1121 | * @return bool true if everything was ok, false otherwise |
||
1122 | */ |
||
1123 | protected function preprocessData() |
||
1124 | { |
||
1125 | $result = true; |
||
1126 | // Validate id |
||
1127 | $this->submittedData['uid'] = empty($this->submittedData['uid']) ? 0 : (int)$this->submittedData['uid']; |
||
1128 | // Validate selected task class |
||
1129 | if (!class_exists($this->submittedData['class'])) { |
||
1130 | $this->addMessage($this->getLanguageService()->getLL('msg.noTaskClassFound'), FlashMessage::ERROR); |
||
1131 | } |
||
1132 | // Check start date |
||
1133 | if (empty($this->submittedData['start'])) { |
||
1134 | $this->addMessage($this->getLanguageService()->getLL('msg.noStartDate'), FlashMessage::ERROR); |
||
1135 | $result = false; |
||
1136 | } elseif (is_string($this->submittedData['start']) && (!is_numeric($this->submittedData['start']))) { |
||
1137 | try { |
||
1138 | $this->submittedData['start'] = $this->convertToTimestamp($this->submittedData['start']); |
||
1139 | } catch (\Exception $e) { |
||
1140 | $this->addMessage($this->getLanguageService()->getLL('msg.invalidStartDate'), FlashMessage::ERROR); |
||
1141 | $result = false; |
||
1142 | } |
||
1143 | } else { |
||
1144 | $this->submittedData['start'] = (int)$this->submittedData['start']; |
||
1145 | } |
||
1146 | // Check end date, if recurring task |
||
1147 | if ((int)$this->submittedData['type'] === AbstractTask::TYPE_RECURRING && !empty($this->submittedData['end'])) { |
||
1148 | if (is_string($this->submittedData['end']) && (!is_numeric($this->submittedData['end']))) { |
||
1149 | try { |
||
1150 | $this->submittedData['end'] = $this->convertToTimestamp($this->submittedData['end']); |
||
1151 | } catch (\Exception $e) { |
||
1152 | $this->addMessage($this->getLanguageService()->getLL('msg.invalidStartDate'), FlashMessage::ERROR); |
||
1153 | $result = false; |
||
1154 | } |
||
1155 | } else { |
||
1156 | $this->submittedData['end'] = (int)$this->submittedData['end']; |
||
1157 | } |
||
1158 | if ($this->submittedData['end'] < $this->submittedData['start']) { |
||
1159 | $this->addMessage( |
||
1160 | $this->getLanguageService()->getLL('msg.endDateSmallerThanStartDate'), |
||
1161 | FlashMessage::ERROR |
||
1162 | ); |
||
1163 | $result = false; |
||
1164 | } |
||
1165 | } |
||
1166 | // Set default values for interval and cron command |
||
1167 | $this->submittedData['interval'] = 0; |
||
1168 | $this->submittedData['croncmd'] = ''; |
||
1169 | // Check type and validity of frequency, if recurring |
||
1170 | if ((int)$this->submittedData['type'] === AbstractTask::TYPE_RECURRING) { |
||
1171 | $frequency = trim($this->submittedData['frequency']); |
||
1172 | if (empty($frequency)) { |
||
1173 | // Empty frequency, not valid |
||
1174 | $this->addMessage($this->getLanguageService()->getLL('msg.noFrequency'), FlashMessage::ERROR); |
||
1175 | $result = false; |
||
1176 | } else { |
||
1177 | $cronErrorCode = 0; |
||
1178 | $cronErrorMessage = ''; |
||
1179 | // Try interpreting the cron command |
||
1180 | try { |
||
1181 | NormalizeCommand::normalize($frequency); |
||
1182 | $this->submittedData['croncmd'] = $frequency; |
||
1183 | } catch (\Exception $e) { |
||
1184 | // Store the exception's result |
||
1185 | $cronErrorMessage = $e->getMessage(); |
||
1186 | $cronErrorCode = $e->getCode(); |
||
1187 | // Check if the frequency is a valid number |
||
1188 | // If yes, assume it is a frequency in seconds, and unset cron error code |
||
1189 | if (is_numeric($frequency)) { |
||
1190 | $this->submittedData['interval'] = (int)$frequency; |
||
1191 | unset($cronErrorCode); |
||
1192 | } |
||
1193 | } |
||
1194 | // If there's a cron error code, issue validation error message |
||
1195 | if (!empty($cronErrorCode)) { |
||
1196 | $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.frequencyError'), $cronErrorMessage, $cronErrorCode), FlashMessage::ERROR); |
||
1197 | $result = false; |
||
1198 | } |
||
1199 | } |
||
1200 | } |
||
1201 | // Validate additional input fields |
||
1202 | if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) { |
||
1203 | /** @var $providerObject AdditionalFieldProviderInterface */ |
||
1204 | $providerObject = GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']); |
||
1205 | if ($providerObject instanceof AdditionalFieldProviderInterface) { |
||
1206 | // The validate method will return true if all went well, but that must not |
||
1207 | // override previous false values => AND the returned value with the existing one |
||
1208 | $result &= $providerObject->validateAdditionalFields($this->submittedData, $this); |
||
1209 | } |
||
1210 | } |
||
1211 | return $result; |
||
1212 | } |
||
1213 | |||
1214 | /** |
||
1215 | * Convert input to DateTime and retrieve timestamp |
||
1216 | * |
||
1217 | * @param string $input |
||
1218 | * @return int |
||
1219 | */ |
||
1220 | protected function convertToTimestamp(string $input): int |
||
1221 | { |
||
1222 | // Convert to ISO 8601 dates |
||
1223 | $dateTime = new \DateTime($input); |
||
1224 | $value = $dateTime->getTimestamp(); |
||
1225 | if ($value !== 0) { |
||
1226 | $value -= date('Z', $value); |
||
1227 | } |
||
1228 | return $value; |
||
1229 | } |
||
1230 | |||
1231 | /** |
||
1232 | * This method is used to add a message to the internal queue |
||
1233 | * |
||
1234 | * @param string $message The message itself |
||
1235 | * @param int $severity Message level (according to FlashMessage class constants) |
||
1236 | */ |
||
1237 | public function addMessage($message, $severity = FlashMessage::OK) |
||
1238 | { |
||
1239 | $this->moduleTemplate->addFlashMessage($message, '', $severity); |
||
1240 | } |
||
1241 | |||
1242 | /** |
||
1243 | * This method fetches a list of all classes that have been registered with the Scheduler |
||
1244 | * For each item the following information is provided, as an associative array: |
||
1245 | * |
||
1246 | * ['extension'] => Key of the extension which provides the class |
||
1247 | * ['filename'] => Path to the file containing the class |
||
1248 | * ['title'] => String (possibly localized) containing a human-readable name for the class |
||
1249 | * ['provider'] => Name of class that implements the interface for additional fields, if necessary |
||
1250 | * |
||
1251 | * The name of the class itself is used as the key of the list array |
||
1252 | * |
||
1253 | * @return array List of registered classes |
||
1254 | */ |
||
1255 | protected function getRegisteredClasses() |
||
1256 | { |
||
1257 | $list = []; |
||
1258 | foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'] ?? [] as $class => $registrationInformation) { |
||
1259 | $title = isset($registrationInformation['title']) ? $this->getLanguageService()->sL($registrationInformation['title']) : ''; |
||
1260 | $description = isset($registrationInformation['description']) ? $this->getLanguageService()->sL($registrationInformation['description']) : ''; |
||
1261 | $list[$class] = [ |
||
1262 | 'extension' => $registrationInformation['extension'], |
||
1263 | 'title' => $title, |
||
1264 | 'description' => $description, |
||
1265 | 'provider' => $registrationInformation['additionalFields'] ?? '' |
||
1266 | ]; |
||
1267 | } |
||
1268 | return $list; |
||
1269 | } |
||
1270 | |||
1271 | /** |
||
1272 | * This method fetches list of all group that have been registered with the Scheduler |
||
1273 | * |
||
1274 | * @return array List of registered groups |
||
1275 | */ |
||
1276 | protected function getRegisteredTaskGroups() |
||
1277 | { |
||
1278 | $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class) |
||
1279 | ->getQueryBuilderForTable('tx_scheduler_task_group'); |
||
1280 | |||
1281 | return $queryBuilder |
||
1282 | ->select('*') |
||
1283 | ->from('tx_scheduler_task_group') |
||
1284 | ->orderBy('sorting') |
||
1285 | ->execute() |
||
1286 | ->fetchAll(); |
||
1287 | } |
||
1288 | |||
1289 | /** |
||
1290 | * Create the panel of buttons for submitting the form or otherwise perform operations. |
||
1291 | */ |
||
1292 | protected function getButtons() |
||
1293 | { |
||
1294 | $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar(); |
||
1295 | // CSH |
||
1296 | $helpButton = $buttonBar->makeHelpButton() |
||
1297 | ->setModuleName('_MOD_system_txschedulerM1') |
||
1298 | ->setFieldName(''); |
||
1299 | $buttonBar->addButton($helpButton); |
||
1300 | // Add and Reload |
||
1301 | if (empty($this->CMD) || $this->CMD === 'list' || $this->CMD === 'delete' || $this->CMD === 'stop' || $this->CMD === 'toggleHidden' || $this->CMD === 'setNextExecutionTime') { |
||
1302 | $reloadButton = $buttonBar->makeLinkButton() |
||
1303 | ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.reload')) |
||
1304 | ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-refresh', Icon::SIZE_SMALL)) |
||
1305 | ->setHref($this->moduleUri); |
||
1306 | $buttonBar->addButton($reloadButton, ButtonBar::BUTTON_POSITION_RIGHT, 1); |
||
1307 | if ($this->MOD_SETTINGS['function'] === 'scheduler' && !empty($this->getRegisteredClasses())) { |
||
1308 | $addButton = $buttonBar->makeLinkButton() |
||
1309 | ->setTitle($this->getLanguageService()->getLL('action.add')) |
||
1310 | ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-add', Icon::SIZE_SMALL)) |
||
1311 | ->setHref($this->moduleUri . '&CMD=add'); |
||
1312 | $buttonBar->addButton($addButton, ButtonBar::BUTTON_POSITION_LEFT, 2); |
||
1313 | } |
||
1314 | } |
||
1315 | // Close and Save |
||
1316 | if ($this->CMD === 'add' || $this->CMD === 'edit') { |
||
1317 | // Close |
||
1318 | $closeButton = $buttonBar->makeLinkButton() |
||
1319 | ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:cancel')) |
||
1320 | ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-close', Icon::SIZE_SMALL)) |
||
1321 | ->setOnClick('document.location=' . GeneralUtility::quoteJSvalue($this->moduleUri)) |
||
1322 | ->setHref('#'); |
||
1323 | $buttonBar->addButton($closeButton, ButtonBar::BUTTON_POSITION_LEFT, 2); |
||
1324 | // Save, SaveAndClose, SaveAndNew |
||
1325 | $saveButtonDropdown = $buttonBar->makeSplitButton(); |
||
1326 | $saveButton = $buttonBar->makeInputButton() |
||
1327 | ->setName('CMD') |
||
1328 | ->setValue('save') |
||
1329 | ->setForm('tx_scheduler_form') |
||
1330 | ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-document-save', Icon::SIZE_SMALL)) |
||
1331 | ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:save')); |
||
1332 | $saveButtonDropdown->addItem($saveButton); |
||
1333 | $saveAndNewButton = $buttonBar->makeInputButton() |
||
1334 | ->setName('CMD') |
||
1335 | ->setValue('savenew') |
||
1336 | ->setForm('tx_scheduler_form') |
||
1337 | ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-document-save-new', Icon::SIZE_SMALL)) |
||
1338 | ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:saveAndCreateNewDoc')); |
||
1339 | $saveButtonDropdown->addItem($saveAndNewButton); |
||
1340 | $saveAndCloseButton = $buttonBar->makeInputButton() |
||
1341 | ->setName('CMD') |
||
1342 | ->setValue('saveclose') |
||
1343 | ->setForm('tx_scheduler_form') |
||
1344 | ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-document-save-close', Icon::SIZE_SMALL)) |
||
1345 | ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:saveAndClose')); |
||
1346 | $saveButtonDropdown->addItem($saveAndCloseButton); |
||
1347 | $buttonBar->addButton($saveButtonDropdown, ButtonBar::BUTTON_POSITION_LEFT, 3); |
||
1348 | } |
||
1349 | // Edit |
||
1350 | if ($this->CMD === 'edit') { |
||
1351 | $deleteButton = $buttonBar->makeInputButton() |
||
1352 | ->setName('CMD') |
||
1353 | ->setValue('delete') |
||
1354 | ->setForm('tx_scheduler_form') |
||
1355 | ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-edit-delete', Icon::SIZE_SMALL)) |
||
1356 | ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:delete')); |
||
1357 | $buttonBar->addButton($deleteButton, ButtonBar::BUTTON_POSITION_LEFT, 4); |
||
1358 | } |
||
1359 | // Shortcut |
||
1360 | $shortcutButton = $buttonBar->makeShortcutButton() |
||
1361 | ->setModuleName('system_txschedulerM1') |
||
1362 | ->setDisplayName($this->MOD_MENU['function'][$this->MOD_SETTINGS['function']]) |
||
1363 | ->setSetVariables(['function']); |
||
1364 | $buttonBar->addButton($shortcutButton); |
||
1365 | } |
||
1366 | |||
1367 | /** |
||
1368 | * @return string |
||
1369 | */ |
||
1370 | protected function getServerTime() |
||
1374 | } |
||
1375 | |||
1376 | /** |
||
1377 | * Returns the Language Service |
||
1378 | * @return LanguageService |
||
1379 | */ |
||
1380 | protected function getLanguageService() |
||
1381 | { |
||
1382 | return $GLOBALS['LANG']; |
||
1383 | } |
||
1384 | |||
1385 | /** |
||
1386 | * Returns the global BackendUserAuthentication object. |
||
1387 | * |
||
1388 | * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication |
||
1389 | */ |
||
1390 | protected function getBackendUser() |
||
1391 | { |
||
1392 | return $GLOBALS['BE_USER']; |
||
1393 | } |
||
1394 | |||
1395 | /** |
||
1396 | * @return PageRenderer |
||
1397 | */ |
||
1398 | protected function getPageRenderer() |
||
1401 | } |
||
1402 | } |
||
1403 |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.