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