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