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