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