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