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