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