97eaa6b5f19f0a5920d672b2b84644c1aa285dd9
[Packages/TYPO3.CMS.git] / typo3 / sysext / scheduler / Classes / Controller / SchedulerModuleController.php
1 <?php
2 namespace TYPO3\CMS\Scheduler\Controller;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Psr\Http\Message\ResponseInterface;
18 use Psr\Http\Message\ServerRequestInterface;
19 use TYPO3\CMS\Backend\Template\Components\ButtonBar;
20 use TYPO3\CMS\Backend\Template\ModuleTemplate;
21 use TYPO3\CMS\Backend\Utility\BackendUtility;
22 use TYPO3\CMS\Core\Database\ConnectionPool;
23 use TYPO3\CMS\Core\Imaging\Icon;
24 use TYPO3\CMS\Core\Imaging\IconFactory;
25 use TYPO3\CMS\Core\Localization\LanguageService;
26 use TYPO3\CMS\Core\Messaging\FlashMessage;
27 use TYPO3\CMS\Core\Page\PageRenderer;
28 use TYPO3\CMS\Core\Registry;
29 use TYPO3\CMS\Core\Utility\ArrayUtility;
30 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
31 use TYPO3\CMS\Core\Utility\GeneralUtility;
32 use TYPO3\CMS\Fluid\View\StandaloneView;
33 use TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper;
34 use TYPO3\CMS\Scheduler\AdditionalFieldProviderInterface;
35 use TYPO3\CMS\Scheduler\CronCommand\NormalizeCommand;
36 use TYPO3\CMS\Scheduler\ProgressProviderInterface;
37 use TYPO3\CMS\Scheduler\Scheduler;
38 use TYPO3\CMS\Scheduler\Task\AbstractTask;
39
40 /**
41 * Module 'TYPO3 Scheduler administration module' for the 'scheduler' extension.
42 */
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()
224 {
225 $content = '';
226 $sectionTitle = '';
227 // Get submitted data
228 $this->submittedData = GeneralUtility::_GPmerged('tx_scheduler');
229 $this->submittedData['uid'] = (int)$this->submittedData['uid'];
230 // If a save command was submitted, handle saving now
231 if ($this->CMD === 'save' || $this->CMD === 'saveclose' || $this->CMD === 'savenew') {
232 $previousCMD = GeneralUtility::_GP('previousCMD');
233 // First check the submitted data
234 $result = $this->preprocessData();
235 // If result is ok, proceed with saving
236 if ($result) {
237 $this->saveTask();
238 if ($this->CMD === 'saveclose') {
239 // Unset command, so that default screen gets displayed
240 unset($this->CMD);
241 } elseif ($this->CMD === 'save') {
242 // After saving a "add form", return to edit
243 $this->CMD = 'edit';
244 } elseif ($this->CMD === 'savenew') {
245 // Unset submitted data, so that empty form gets displayed
246 unset($this->submittedData);
247 // After saving a "add/edit form", return to add
248 $this->CMD = 'add';
249 } else {
250 // Return to edit form
251 $this->CMD = $previousCMD;
252 }
253 } else {
254 $this->CMD = $previousCMD;
255 }
256 }
257
258 // Handle chosen action
259 switch ((string)$this->MOD_SETTINGS['function']) {
260 case 'scheduler':
261 $this->executeTasks();
262
263 switch ($this->CMD) {
264 case 'add':
265 case 'edit':
266 try {
267 // Try adding or editing
268 $content .= $this->editTaskAction();
269 $sectionTitle = $this->getLanguageService()->getLL('action.' . $this->CMD);
270 } catch (\Exception $e) {
271 if ($e->getCode() === 1305100019) {
272 // Invalid controller class name exception
273 $this->addMessage($e->getMessage(), FlashMessage::ERROR);
274 }
275 // An exception may also happen when the task to
276 // edit could not be found. In this case revert
277 // to displaying the list of tasks
278 // It can also happen when attempting to edit a running task
279 $content .= $this->listTasksAction();
280 }
281 break;
282 case 'delete':
283 $this->deleteTask();
284 $content .= $this->listTasksAction();
285 break;
286 case 'stop':
287 $this->stopTask();
288 $content .= $this->listTasksAction();
289 break;
290 case 'toggleHidden':
291 $this->toggleDisableAction();
292 $content .= $this->listTasksAction();
293 break;
294 case 'setNextExecutionTime':
295 $this->setNextExecutionTimeAction();
296 $content .= $this->listTasksAction();
297 break;
298 case 'list':
299
300 default:
301 $content .= $this->listTasksAction();
302 }
303 break;
304
305 // Setup check screen
306 case 'check':
307 // @todo move check to the report module
308 $content .= $this->checkScreenAction();
309 break;
310
311 // Information screen
312 case 'info':
313 $content .= $this->infoScreenAction();
314 break;
315 }
316 // Wrap the content
317 return '<h2>' . $sectionTitle . '</h2><div class="tx_scheduler_mod1">' . $content . '</div>';
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()
388 {
389 $registeredClasses = $this->getRegisteredClasses();
390 // No classes available, display information message
391 if (empty($registeredClasses)) {
392 $this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'InfoScreenNoClasses.html');
393 return $this->view->render();
394 }
395
396 $this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'InfoScreen.html');
397 $this->view->assign('registeredClasses', $registeredClasses);
398
399 return $this->view->render();
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 } else {
596 if (!empty($registeredClasses[$taskInfo['class']]['provider'])) {
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
604 // Load necessary JavaScript
605 $this->getPageRenderer()->loadJquery();
606 $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Scheduler/Scheduler');
607 $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/DateTimePicker');
608 $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Scheduler/PageBrowser');
609 $this->getPageRenderer()->addJsInlineCode('browse-button', '
610 function setFormValueFromBrowseWin(fieldReference, elValue, elName) {
611 var res = elValue.split("_");
612 var element = document.getElementById(fieldReference);
613 element.value = res[1];
614 }
615 ');
616
617 // Start rendering the add/edit form
618 $this->view->assign('uid', htmlspecialchars($this->submittedData['uid']));
619 $this->view->assign('cmd', htmlspecialchars($this->CMD));
620 $this->view->assign('csh', $this->cshKey);
621 $this->view->assign('lang', 'LLL:EXT:scheduler/Resources/Private/Language/locallang.xlf:');
622
623 $table = [];
624
625 // Disable checkbox
626 $this->view->assign('task_disable', ($taskInfo['disable'] ? ' checked="checked"' : ''));
627 $this->view->assign('task_disable_label', 'LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:disable');
628
629 // Task class selector
630 // On editing, don't allow changing of the task class, unless it was not valid
631 if ($this->submittedData['uid'] > 0 && !empty($taskInfo['class'])) {
632 $this->view->assign('task_class', $taskInfo['class']);
633 $this->view->assign('task_class_title', $registeredClasses[$taskInfo['class']]['title']);
634 $this->view->assign('task_class_extension', $registeredClasses[$taskInfo['class']]['extension']);
635 } else {
636 // Group registered classes by classname
637 $groupedClasses = [];
638 foreach ($registeredClasses as $class => $classInfo) {
639 $groupedClasses[$classInfo['extension']][$class] = $classInfo;
640 }
641 ksort($groupedClasses);
642 foreach ($groupedClasses as $extension => $class) {
643 foreach ($groupedClasses[$extension] as $class => $classInfo) {
644 $selected = $class == $taskInfo['class'] ? ' selected="selected"' : '';
645 $groupedClasses[$extension][$class]['selected'] = $selected;
646 }
647 }
648 $this->view->assign('groupedClasses', $groupedClasses);
649 }
650
651 // Task type selector
652 $this->view->assign('task_type_selected_1', ((int)$taskInfo['type'] === AbstractTask::TYPE_SINGLE ? ' selected="selected"' : ''));
653 $this->view->assign('task_type_selected_2', ((int)$taskInfo['type'] === AbstractTask::TYPE_RECURRING ? ' selected="selected"' : ''));
654
655 // Task group selector
656 foreach ($registeredTaskGroups as $key => $taskGroup) {
657 $selected = $taskGroup['uid'] == $taskInfo['task_group'] ? ' selected="selected"' : '';
658 $registeredTaskGroups[$key]['selected'] = $selected;
659 }
660 $this->view->assign('registeredTaskGroups', $registeredTaskGroups);
661
662 // Start date/time field
663 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['USdateFormat'] ? '%H:%M %m-%d-%Y' : '%H:%M %d-%m-%Y';
664 $this->view->assign('start_value_hr', ($taskInfo['start'] > 0 ? strftime($dateFormat, $taskInfo['start']) : ''));
665 $this->view->assign('start_value', $taskInfo['start']);
666
667 // End date/time field
668 // NOTE: datetime fields need a special id naming scheme
669 $this->view->assign('end_value_hr', ($taskInfo['end'] > 0 ? strftime($dateFormat, $taskInfo['end']) : ''));
670 $this->view->assign('end_value', $taskInfo['end']);
671
672 // Frequency input field
673 $this->view->assign('frequency', $taskInfo['frequency']);
674
675 // Multiple execution selector
676 $this->view->assign('multiple', ($taskInfo['multiple'] ? 'checked="checked"' : ''));
677
678 // Description
679 $this->view->assign('description', $taskInfo['description']);
680
681 // Display additional fields
682 $additionalFieldList = [];
683 foreach ($allAdditionalFields as $class => $fields) {
684 if ($class == $taskInfo['class']) {
685 $additionalFieldsStyle = '';
686 } else {
687 $additionalFieldsStyle = ' style="display: none"';
688 }
689 // Add each field to the display, if there are indeed any
690 if (isset($fields) && is_array($fields)) {
691 foreach ($fields as $fieldID => $fieldInfo) {
692 $htmlClassName = strtolower(str_replace('\\', '-', $class));
693 $field = [];
694 $field['htmlClassName'] = $htmlClassName;
695 $field['code'] = $fieldInfo['code'];
696 $field['cshKey'] = $fieldInfo['cshKey'];
697 $field['cshLabel'] = $fieldInfo['cshLabel'];
698 $field['langLabel'] = $fieldInfo['label'];
699 $field['fieldID'] = $fieldID;
700 $field['additionalFieldsStyle'] = $additionalFieldsStyle;
701 $field['browseButton'] = $this->getBrowseButton($fieldID, $fieldInfo);
702 $additionalFieldList[] = $field;
703 }
704 }
705 }
706 $this->view->assign('additionalFields', $additionalFieldList);
707
708 $this->view->assign('table', implode(LF, $table));
709 $this->view->assign('now', $this->getServerTime());
710
711 return $this->view->render();
712 }
713
714 /**
715 * @param string $fieldID The id of the field witch contains the page id
716 * @param array $fieldInfo The array with the field info, contains the page title shown beside the button
717 * @return string HTML code for the browse button
718 */
719 protected function getBrowseButton($fieldID, array $fieldInfo)
720 {
721 if (isset($fieldInfo['browser']) && ($fieldInfo['browser'] === 'page')) {
722 /** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
723 $uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
724 $url = (string)$uriBuilder->buildUriFromRoute(
725 'wizard_element_browser',
726 ['mode' => 'db', 'bparams' => $fieldID . '|||pages|']
727 );
728 $title = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.browse_db'));
729 return '
730 <div><a href="#" data-url=' . htmlspecialchars($url) . ' class="btn btn-default t3js-pageBrowser" title="' . $title . '">
731 <span class="t3js-icon icon icon-size-small icon-state-default icon-actions-insert-record" data-identifier="actions-insert-record">
732 <span class="icon-markup">' . $this->iconFactory->getIcon(
733 'actions-insert-record',
734 Icon::SIZE_SMALL
735 )->render() . '</span>
736 </span>
737 </a><span id="page_' . $fieldID . '">&nbsp;' . htmlspecialchars($fieldInfo['pageTitle']) . '</span></div>';
738 }
739 return '';
740 }
741
742 /**
743 * Execute all selected tasks
744 */
745 protected function executeTasks()
746 {
747 // Continue if some elements have been chosen for execution
748 if (isset($this->submittedData['execute']) && !empty($this->submittedData['execute'])) {
749 // Get list of registered classes
750 $registeredClasses = $this->getRegisteredClasses();
751 // Loop on all selected tasks
752 foreach ($this->submittedData['execute'] as $uid) {
753 try {
754 // Try fetching the task
755 $task = $this->scheduler->fetchTask($uid);
756 $class = get_class($task);
757 $name = $registeredClasses[$class]['title'] . ' (' . $registeredClasses[$class]['extension'] . ')';
758 if (GeneralUtility::_POST('go_cron') !== null) {
759 $task->setRunOnNextCronJob(true);
760 $task->save();
761 } else {
762 // Now try to execute it and report on outcome
763 try {
764 $result = $this->scheduler->executeTask($task);
765 if ($result) {
766 $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.executed'), $name));
767 } else {
768 $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.notExecuted'), $name), FlashMessage::ERROR);
769 }
770 } catch (\Exception $e) {
771 // An exception was thrown, display its message as an error
772 $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.executionFailed'), $name, $e->getMessage()), FlashMessage::ERROR);
773 }
774 }
775 } catch (\OutOfBoundsException $e) {
776 $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.taskNotFound'), $uid), FlashMessage::ERROR);
777 } catch (\UnexpectedValueException $e) {
778 $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.executionFailed'), $uid, $e->getMessage()), FlashMessage::ERROR);
779 }
780 }
781 // Record the run in the system registry
782 $this->scheduler->recordLastRun('manual');
783 // Make sure to switch to list view after execution
784 $this->CMD = 'list';
785 }
786 }
787
788 /**
789 * Assemble display of list of scheduled tasks
790 *
791 * @return string Table of pending tasks
792 */
793 protected function listTasksAction()
794 {
795 $this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'ListTasks.html');
796
797 // Define display format for dates
798 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
799
800 // Get list of registered task groups
801 $registeredTaskGroups = $this->getRegisteredTaskGroups();
802
803 // add an empty entry for non-grouped tasks
804 // add in front of list
805 array_unshift($registeredTaskGroups, ['uid' => 0, 'groupName' => '']);
806
807 // Get all registered tasks
808 // Just to get the number of entries
809 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
810 ->getQueryBuilderForTable('tx_scheduler_task');
811 $queryBuilder->getRestrictions()->removeAll();
812
813 $result = $queryBuilder->select('t.*')
814 ->addSelect(
815 'g.groupName AS taskGroupName',
816 'g.description AS taskGroupDescription',
817 'g.deleted AS isTaskGroupDeleted'
818 )
819 ->from('tx_scheduler_task', 't')
820 ->leftJoin(
821 't',
822 'tx_scheduler_task_group',
823 'g',
824 $queryBuilder->expr()->eq('t.task_group', $queryBuilder->quoteIdentifier('g.uid'))
825 )
826 ->where(
827 $queryBuilder->expr()->eq('t.deleted', 0)
828 )
829 ->orderBy('g.sorting')
830 ->execute();
831
832 // Loop on all tasks
833 $temporaryResult = [];
834 while ($row = $result->fetch()) {
835 if ($row['taskGroupName'] === null || $row['isTaskGroupDeleted'] === '1') {
836 $row['taskGroupName'] = '';
837 $row['taskGroupDescription'] = '';
838 $row['task_group'] = 0;
839 }
840 $temporaryResult[$row['task_group']]['groupName'] = $row['taskGroupName'];
841 $temporaryResult[$row['task_group']]['groupDescription'] = $row['taskGroupDescription'];
842 $temporaryResult[$row['task_group']]['tasks'][] = $row;
843 }
844
845 // No tasks defined, display information message
846 if (empty($temporaryResult)) {
847 $this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'ListTasksNoTasks.html');
848 return $this->view->render();
849 }
850
851 $this->getPageRenderer()->loadJquery();
852 $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Scheduler/Scheduler');
853 $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/Tooltip');
854
855 $tasks = $temporaryResult;
856
857 $registeredClasses = $this->getRegisteredClasses();
858 $missingClasses = [];
859 foreach ($temporaryResult as $taskIndex => $taskGroup) {
860 foreach ($taskGroup['tasks'] as $recordIndex => $schedulerRecord) {
861 if ((int)$schedulerRecord['disable'] === 1) {
862 $translationKey = 'enable';
863 } else {
864 $translationKey = 'disable';
865 }
866 $tasks[$taskIndex]['tasks'][$recordIndex]['translationKey'] = $translationKey;
867
868 // Define some default values
869 $lastExecution = '-';
870 $isRunning = false;
871 $showAsDisabled = false;
872 // Restore the serialized task and pass it a reference to the scheduler object
873 /** @var $task \TYPO3\CMS\Scheduler\Task\AbstractTask|ProgressProviderInterface */
874 $task = unserialize($schedulerRecord['serialized_task_object']);
875 $class = get_class($task);
876 if ($class === '__PHP_Incomplete_Class' && preg_match('/^O:[0-9]+:"(?P<classname>.+?)"/', $schedulerRecord['serialized_task_object'], $matches) === 1) {
877 $class = $matches['classname'];
878 }
879 $tasks[$taskIndex]['tasks'][$recordIndex]['class'] = $class;
880 // Assemble information about last execution
881 if (!empty($schedulerRecord['lastexecution_time'])) {
882 $lastExecution = date($dateFormat, $schedulerRecord['lastexecution_time']);
883 if ($schedulerRecord['lastexecution_context'] === 'CLI') {
884 $context = $this->getLanguageService()->getLL('label.cron');
885 } else {
886 $context = $this->getLanguageService()->getLL('label.manual');
887 }
888 $lastExecution .= ' (' . $context . ')';
889 }
890 $tasks[$taskIndex]['tasks'][$recordIndex]['lastExecution'] = $lastExecution;
891
892 if (isset($registeredClasses[get_class($task)]) && $this->scheduler->isValidTaskObject($task)) {
893 $tasks[$taskIndex]['tasks'][$recordIndex]['validClass'] = true;
894 // The task object is valid
895 $labels = [];
896 $additionalInformation = $task->getAdditionalInformation();
897 if ($task instanceof ProgressProviderInterface) {
898 $progress = round((float)$task->getProgress(), 2);
899 $tasks[$taskIndex]['tasks'][$recordIndex]['progress'] = $progress;
900 }
901 $tasks[$taskIndex]['tasks'][$recordIndex]['classTitle'] = $registeredClasses[$class]['title'];
902 $tasks[$taskIndex]['tasks'][$recordIndex]['classExtension'] = $registeredClasses[$class]['extension'];
903 $tasks[$taskIndex]['tasks'][$recordIndex]['additionalInformation'] = $additionalInformation;
904 // Check if task currently has a running execution
905 if (!empty($schedulerRecord['serialized_executions'])) {
906 $labels[] = [
907 'class' => 'success',
908 'text' => $this->getLanguageService()->getLL('status.running')
909 ];
910 $isRunning = true;
911 }
912 $tasks[$taskIndex]['tasks'][$recordIndex]['isRunning'] = $isRunning;
913
914 // Prepare display of next execution date
915 // If task is currently running, date is not displayed (as next hasn't been calculated yet)
916 // Also hide the date if task is disabled (the information doesn't make sense, as it will not run anyway)
917 if ($isRunning || $schedulerRecord['disable']) {
918 $nextDate = '-';
919 } else {
920 $nextDate = date($dateFormat, $schedulerRecord['nextexecution']);
921 if (empty($schedulerRecord['nextexecution'])) {
922 $nextDate = $this->getLanguageService()->getLL('none');
923 } elseif ($schedulerRecord['nextexecution'] < $GLOBALS['EXEC_TIME']) {
924 $labels[] = [
925 'class' => 'warning',
926 'text' => $this->getLanguageService()->getLL('status.late'),
927 'description' => $this->getLanguageService()->getLL('status.legend.scheduled')
928 ];
929 }
930 }
931 $tasks[$taskIndex]['tasks'][$recordIndex]['nextDate'] = $nextDate;
932 // Get execution type
933 if ($task->getType() === AbstractTask::TYPE_SINGLE) {
934 $execType = $this->getLanguageService()->getLL('label.type.single');
935 $frequency = '-';
936 } else {
937 $execType = $this->getLanguageService()->getLL('label.type.recurring');
938 if ($task->getExecution()->getCronCmd() == '') {
939 $frequency = $task->getExecution()->getInterval();
940 } else {
941 $frequency = $task->getExecution()->getCronCmd();
942 }
943 }
944 // Check the disable status
945 // Row is shown dimmed if task is disabled, unless it is still running
946 if ($schedulerRecord['disable'] && !$isRunning) {
947 $labels[] = [
948 'class' => 'default',
949 'text' => $this->getLanguageService()->getLL('status.disabled')
950 ];
951 $showAsDisabled = true;
952 }
953 $tasks[$taskIndex]['tasks'][$recordIndex]['execType'] = $execType;
954 $tasks[$taskIndex]['tasks'][$recordIndex]['frequency'] = $frequency;
955 // Get multiple executions setting
956 if ($task->getExecution()->getMultiple()) {
957 $multiple = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:yes');
958 } else {
959 $multiple = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:no');
960 }
961 $tasks[$taskIndex]['tasks'][$recordIndex]['multiple'] = $multiple;
962
963 // Check if the last run failed
964 if (!empty($schedulerRecord['lastexecution_failure'])) {
965 // Try to get the stored exception array
966 /** @var $exceptionArray array */
967 $exceptionArray = @unserialize($schedulerRecord['lastexecution_failure']);
968 // If the exception could not be unserialized, issue a default error message
969 if (!is_array($exceptionArray) || empty($exceptionArray)) {
970 $labelDescription = $this->getLanguageService()->getLL('msg.executionFailureDefault');
971 } else {
972 $labelDescription = sprintf($this->getLanguageService()->getLL('msg.executionFailureReport'), $exceptionArray['code'], $exceptionArray['message']);
973 }
974 $labels[] = [
975 'class' => 'danger',
976 'text' => $this->getLanguageService()->getLL('status.failure'),
977 'description' => $labelDescription
978 ];
979 }
980 $tasks[$taskIndex]['tasks'][$recordIndex]['labels'] = $labels;
981 if ($showAsDisabled) {
982 $tasks[$taskIndex]['tasks'][$recordIndex]['showAsDisabled'] = 'disabled';
983 }
984 } else {
985 $missingClasses[] = $tasks[$taskIndex]['tasks'][$recordIndex];
986 unset($tasks[$taskIndex]['tasks'][$recordIndex]);
987 }
988 }
989 }
990
991 $this->view->assign('tasks', $tasks);
992 $this->view->assign('missingClasses', $missingClasses);
993 $this->view->assign('moduleUri', $this->moduleUri);
994 $this->view->assign('now', $this->getServerTime());
995
996 return $this->view->render();
997 }
998
999 /**
1000 * Generates bootstrap labels containing the label statuses
1001 *
1002 * @param array $labels
1003 * @return string
1004 */
1005 protected function makeStatusLabel(array $labels)
1006 {
1007 $htmlLabels = [];
1008 foreach ($labels as $label) {
1009 if (empty($label['text'])) {
1010 continue;
1011 }
1012 $htmlLabels[] = '<span class="label label-' . htmlspecialchars($label['class']) . ' pull-right" title="' . htmlspecialchars($label['description']) . '">' . htmlspecialchars($label['text']) . '</span>';
1013 }
1014
1015 return implode('&nbsp;', $htmlLabels);
1016 }
1017
1018 /**
1019 * Saves a task specified in the backend form to the database
1020 */
1021 protected function saveTask()
1022 {
1023 // If a task is being edited fetch old task data
1024 if (!empty($this->submittedData['uid'])) {
1025 try {
1026 $taskRecord = $this->scheduler->fetchTaskRecord($this->submittedData['uid']);
1027 /** @var $task \TYPO3\CMS\Scheduler\Task\AbstractTask */
1028 $task = unserialize($taskRecord['serialized_task_object']);
1029 } catch (\OutOfBoundsException $e) {
1030 // If the task could not be fetched, issue an error message
1031 // and exit early
1032 $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.taskNotFound'), $this->submittedData['uid']), FlashMessage::ERROR);
1033 return;
1034 }
1035 // Register single execution
1036 if ((int)$this->submittedData['type'] === AbstractTask::TYPE_SINGLE) {
1037 $task->registerSingleExecution($this->submittedData['start']);
1038 } else {
1039 if (!empty($this->submittedData['croncmd'])) {
1040 // Definition by cron-like syntax
1041 $interval = 0;
1042 $cronCmd = $this->submittedData['croncmd'];
1043 } else {
1044 // Definition by interval
1045 $interval = $this->submittedData['interval'];
1046 $cronCmd = '';
1047 }
1048 // Register recurring execution
1049 $task->registerRecurringExecution($this->submittedData['start'], $interval, $this->submittedData['end'], $this->submittedData['multiple'], $cronCmd);
1050 }
1051 // Set disable flag
1052 $task->setDisabled($this->submittedData['disable']);
1053 // Set description
1054 $task->setDescription($this->submittedData['description']);
1055 // Set task group
1056 $task->setTaskGroup($this->submittedData['task_group']);
1057 // Save additional input values
1058 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) {
1059 /** @var $providerObject AdditionalFieldProviderInterface */
1060 $providerObject = GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']);
1061 if ($providerObject instanceof AdditionalFieldProviderInterface) {
1062 $providerObject->saveAdditionalFields($this->submittedData, $task);
1063 }
1064 }
1065 // Save to database
1066 $result = $this->scheduler->saveTask($task);
1067 if ($result) {
1068 $this->getBackendUser()->writelog(4, 0, 0, 0, 'Scheduler task "%s" (UID: %s, Class: "%s") was updated', [$task->getTaskTitle(), $task->getTaskUid(), $task->getTaskClassName()]);
1069 $this->addMessage($this->getLanguageService()->getLL('msg.updateSuccess'));
1070 } else {
1071 $this->addMessage($this->getLanguageService()->getLL('msg.updateError'), FlashMessage::ERROR);
1072 }
1073 } else {
1074 // A new task is being created
1075 // Create an instance of chosen class
1076 /** @var $task AbstractTask */
1077 $task = GeneralUtility::makeInstance($this->submittedData['class']);
1078 if ((int)$this->submittedData['type'] === AbstractTask::TYPE_SINGLE) {
1079 // Set up single execution
1080 $task->registerSingleExecution($this->submittedData['start']);
1081 } else {
1082 // Set up recurring execution
1083 $task->registerRecurringExecution($this->submittedData['start'], $this->submittedData['interval'], $this->submittedData['end'], $this->submittedData['multiple'], $this->submittedData['croncmd']);
1084 }
1085 // Save additional input values
1086 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) {
1087 /** @var $providerObject AdditionalFieldProviderInterface */
1088 $providerObject = GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']);
1089 if ($providerObject instanceof AdditionalFieldProviderInterface) {
1090 $providerObject->saveAdditionalFields($this->submittedData, $task);
1091 }
1092 }
1093 // Set disable flag
1094 $task->setDisabled($this->submittedData['disable']);
1095 // Set description
1096 $task->setDescription($this->submittedData['description']);
1097 // Set description
1098 $task->setTaskGroup($this->submittedData['task_group']);
1099 // Add to database
1100 $result = $this->scheduler->addTask($task);
1101 if ($result) {
1102 $this->getBackendUser()->writelog(4, 0, 0, 0, 'Scheduler task "%s" (UID: %s, Class: "%s") was added', [$task->getTaskTitle(), $task->getTaskUid(), $task->getTaskClassName()]);
1103 $this->addMessage($this->getLanguageService()->getLL('msg.addSuccess'));
1104
1105 // set the uid of the just created task so that we
1106 // can continue editing after initial saving
1107 $this->submittedData['uid'] = $task->getTaskUid();
1108 } else {
1109 $this->addMessage($this->getLanguageService()->getLL('msg.addError'), FlashMessage::ERROR);
1110 }
1111 }
1112 }
1113
1114 /*************************
1115 *
1116 * INPUT PROCESSING UTILITIES
1117 *
1118 *************************/
1119 /**
1120 * Checks the submitted data and performs some pre-processing on it
1121 *
1122 * @return bool true if everything was ok, false otherwise
1123 */
1124 protected function preprocessData()
1125 {
1126 $result = true;
1127 // Validate id
1128 $this->submittedData['uid'] = empty($this->submittedData['uid']) ? 0 : (int)$this->submittedData['uid'];
1129 // Validate selected task class
1130 if (!class_exists($this->submittedData['class'])) {
1131 $this->addMessage($this->getLanguageService()->getLL('msg.noTaskClassFound'), FlashMessage::ERROR);
1132 }
1133 // Check start date
1134 if (empty($this->submittedData['start'])) {
1135 $this->addMessage($this->getLanguageService()->getLL('msg.noStartDate'), FlashMessage::ERROR);
1136 $result = false;
1137 } elseif (is_string($this->submittedData['start']) && (!is_numeric($this->submittedData['start']))) {
1138 try {
1139 $this->submittedData['start'] = $this->convertToTimestamp($this->submittedData['start']);
1140 } catch (\Exception $e) {
1141 $this->addMessage($this->getLanguageService()->getLL('msg.invalidStartDate'), FlashMessage::ERROR);
1142 $result = false;
1143 }
1144 } else {
1145 $this->submittedData['start'] = (int)$this->submittedData['start'];
1146 }
1147 // Check end date, if recurring task
1148 if ((int)$this->submittedData['type'] === AbstractTask::TYPE_RECURRING && !empty($this->submittedData['end'])) {
1149 if (is_string($this->submittedData['end']) && (!is_numeric($this->submittedData['end']))) {
1150 try {
1151 $this->submittedData['end'] = $this->convertToTimestamp($this->submittedData['end']);
1152 } catch (\Exception $e) {
1153 $this->addMessage($this->getLanguageService()->getLL('msg.invalidStartDate'), FlashMessage::ERROR);
1154 $result = false;
1155 }
1156 } else {
1157 $this->submittedData['end'] = (int)$this->submittedData['end'];
1158 }
1159 if ($this->submittedData['end'] < $this->submittedData['start']) {
1160 $this->addMessage(
1161 $this->getLanguageService()->getLL('msg.endDateSmallerThanStartDate'),
1162 FlashMessage::ERROR
1163 );
1164 $result = false;
1165 }
1166 }
1167 // Set default values for interval and cron command
1168 $this->submittedData['interval'] = 0;
1169 $this->submittedData['croncmd'] = '';
1170 // Check type and validity of frequency, if recurring
1171 if ((int)$this->submittedData['type'] === AbstractTask::TYPE_RECURRING) {
1172 $frequency = trim($this->submittedData['frequency']);
1173 if (empty($frequency)) {
1174 // Empty frequency, not valid
1175 $this->addMessage($this->getLanguageService()->getLL('msg.noFrequency'), FlashMessage::ERROR);
1176 $result = false;
1177 } else {
1178 $cronErrorCode = 0;
1179 $cronErrorMessage = '';
1180 // Try interpreting the cron command
1181 try {
1182 NormalizeCommand::normalize($frequency);
1183 $this->submittedData['croncmd'] = $frequency;
1184 } catch (\Exception $e) {
1185 // Store the exception's result
1186 $cronErrorMessage = $e->getMessage();
1187 $cronErrorCode = $e->getCode();
1188 // Check if the frequency is a valid number
1189 // If yes, assume it is a frequency in seconds, and unset cron error code
1190 if (is_numeric($frequency)) {
1191 $this->submittedData['interval'] = (int)$frequency;
1192 unset($cronErrorCode);
1193 }
1194 }
1195 // If there's a cron error code, issue validation error message
1196 if (!empty($cronErrorCode)) {
1197 $this->addMessage(sprintf($this->getLanguageService()->getLL('msg.frequencyError'), $cronErrorMessage, $cronErrorCode), FlashMessage::ERROR);
1198 $result = false;
1199 }
1200 }
1201 }
1202 // Validate additional input fields
1203 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields'])) {
1204 /** @var $providerObject AdditionalFieldProviderInterface */
1205 $providerObject = GeneralUtility::makeInstance($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][$this->submittedData['class']]['additionalFields']);
1206 if ($providerObject instanceof AdditionalFieldProviderInterface) {
1207 // The validate method will return true if all went well, but that must not
1208 // override previous false values => AND the returned value with the existing one
1209 $result &= $providerObject->validateAdditionalFields($this->submittedData, $this);
1210 }
1211 }
1212 return $result;
1213 }
1214
1215 /**
1216 * Convert input to DateTime and retrieve timestamp
1217 *
1218 * @param string $input
1219 * @return int
1220 */
1221 protected function convertToTimestamp(string $input): int
1222 {
1223 // Convert to ISO 8601 dates
1224 $dateTime = new \DateTime($input);
1225 $value = $dateTime->getTimestamp();
1226 if ($value !== 0) {
1227 $value -= date('Z', $value);
1228 }
1229 return $value;
1230 }
1231
1232 /**
1233 * This method is used to add a message to the internal queue
1234 *
1235 * @param string $message The message itself
1236 * @param int $severity Message level (according to FlashMessage class constants)
1237 */
1238 public function addMessage($message, $severity = FlashMessage::OK)
1239 {
1240 $this->moduleTemplate->addFlashMessage($message, '', $severity);
1241 }
1242
1243 /**
1244 * This method fetches a list of all classes that have been registered with the Scheduler
1245 * For each item the following information is provided, as an associative array:
1246 *
1247 * ['extension'] => Key of the extension which provides the class
1248 * ['filename'] => Path to the file containing the class
1249 * ['title'] => String (possibly localized) containing a human-readable name for the class
1250 * ['provider'] => Name of class that implements the interface for additional fields, if necessary
1251 *
1252 * The name of the class itself is used as the key of the list array
1253 *
1254 * @return array List of registered classes
1255 */
1256 protected function getRegisteredClasses()
1257 {
1258 $list = [];
1259 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'] ?? [] as $class => $registrationInformation) {
1260 $title = isset($registrationInformation['title']) ? $this->getLanguageService()->sL($registrationInformation['title']) : '';
1261 $description = isset($registrationInformation['description']) ? $this->getLanguageService()->sL($registrationInformation['description']) : '';
1262 $list[$class] = [
1263 'extension' => $registrationInformation['extension'],
1264 'title' => $title,
1265 'description' => $description,
1266 'provider' => isset($registrationInformation['additionalFields']) ? $registrationInformation['additionalFields'] : ''
1267 ];
1268 }
1269 return $list;
1270 }
1271
1272 /**
1273 * This method fetches list of all group that have been registered with the Scheduler
1274 *
1275 * @return array List of registered groups
1276 */
1277 protected function getRegisteredTaskGroups()
1278 {
1279 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1280 ->getQueryBuilderForTable('tx_scheduler_task_group');
1281
1282 return $queryBuilder
1283 ->select('*')
1284 ->from('tx_scheduler_task_group')
1285 ->orderBy('sorting')
1286 ->execute()
1287 ->fetchAll();
1288 }
1289
1290 /**
1291 * Create the panel of buttons for submitting the form or otherwise perform operations.
1292 */
1293 protected function getButtons()
1294 {
1295 $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
1296 // CSH
1297 $helpButton = $buttonBar->makeHelpButton()
1298 ->setModuleName('_MOD_system_txschedulerM1')
1299 ->setFieldName('');
1300 $buttonBar->addButton($helpButton);
1301 // Add and Reload
1302 if (empty($this->CMD) || $this->CMD === 'list' || $this->CMD === 'delete' || $this->CMD === 'stop' || $this->CMD === 'toggleHidden' || $this->CMD === 'setNextExecutionTime') {
1303 $reloadButton = $buttonBar->makeLinkButton()
1304 ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.reload'))
1305 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-refresh', Icon::SIZE_SMALL))
1306 ->setHref($this->moduleUri);
1307 $buttonBar->addButton($reloadButton, ButtonBar::BUTTON_POSITION_RIGHT, 1);
1308 if ($this->MOD_SETTINGS['function'] === 'scheduler' && !empty($this->getRegisteredClasses())) {
1309 $addButton = $buttonBar->makeLinkButton()
1310 ->setTitle($this->getLanguageService()->getLL('action.add'))
1311 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-add', Icon::SIZE_SMALL))
1312 ->setHref($this->moduleUri . '&CMD=add');
1313 $buttonBar->addButton($addButton, ButtonBar::BUTTON_POSITION_LEFT, 2);
1314 }
1315 }
1316 // Close and Save
1317 if ($this->CMD === 'add' || $this->CMD === 'edit') {
1318 // Close
1319 $closeButton = $buttonBar->makeLinkButton()
1320 ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:cancel'))
1321 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-close', Icon::SIZE_SMALL))
1322 ->setOnClick('document.location=' . GeneralUtility::quoteJSvalue($this->moduleUri))
1323 ->setHref('#');
1324 $buttonBar->addButton($closeButton, ButtonBar::BUTTON_POSITION_LEFT, 2);
1325 // Save, SaveAndClose, SaveAndNew
1326 $saveButtonDropdown = $buttonBar->makeSplitButton();
1327 $saveButton = $buttonBar->makeInputButton()
1328 ->setName('CMD')
1329 ->setValue('save')
1330 ->setForm('tx_scheduler_form')
1331 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-document-save', Icon::SIZE_SMALL))
1332 ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:save'));
1333 $saveButtonDropdown->addItem($saveButton);
1334 $saveAndNewButton = $buttonBar->makeInputButton()
1335 ->setName('CMD')
1336 ->setValue('savenew')
1337 ->setForm('tx_scheduler_form')
1338 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-document-save-new', Icon::SIZE_SMALL))
1339 ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:saveAndCreateNewDoc'));
1340 $saveButtonDropdown->addItem($saveAndNewButton);
1341 $saveAndCloseButton = $buttonBar->makeInputButton()
1342 ->setName('CMD')
1343 ->setValue('saveclose')
1344 ->setForm('tx_scheduler_form')
1345 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-document-save-close', Icon::SIZE_SMALL))
1346 ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:saveAndClose'));
1347 $saveButtonDropdown->addItem($saveAndCloseButton);
1348 $buttonBar->addButton($saveButtonDropdown, ButtonBar::BUTTON_POSITION_LEFT, 3);
1349 }
1350 // Edit
1351 if ($this->CMD === 'edit') {
1352 $deleteButton = $buttonBar->makeInputButton()
1353 ->setName('CMD')
1354 ->setValue('delete')
1355 ->setForm('tx_scheduler_form')
1356 ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-edit-delete', Icon::SIZE_SMALL))
1357 ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:delete'));
1358 $buttonBar->addButton($deleteButton, ButtonBar::BUTTON_POSITION_LEFT, 4);
1359 }
1360 // Shortcut
1361 $shortcutButton = $buttonBar->makeShortcutButton()
1362 ->setModuleName('system_txschedulerM1')
1363 ->setDisplayName($this->MOD_MENU['function'][$this->MOD_SETTINGS['function']])
1364 ->setSetVariables(['function']);
1365 $buttonBar->addButton($shortcutButton);
1366 }
1367
1368 /**
1369 * @return string
1370 */
1371 protected function getServerTime()
1372 {
1373 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] . ' T (e';
1374 return date($dateFormat) . ', GMT ' . date('P') . ')';
1375 }
1376
1377 /**
1378 * Returns the Language Service
1379 * @return LanguageService
1380 */
1381 protected function getLanguageService()
1382 {
1383 return $GLOBALS['LANG'];
1384 }
1385
1386 /**
1387 * Returns the global BackendUserAuthentication object.
1388 *
1389 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
1390 */
1391 protected function getBackendUser()
1392 {
1393 return $GLOBALS['BE_USER'];
1394 }
1395
1396 /**
1397 * @return PageRenderer
1398 */
1399 protected function getPageRenderer()
1400 {
1401 return GeneralUtility::makeInstance(PageRenderer::class);
1402 }
1403 }