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