-
Notifications
You must be signed in to change notification settings - Fork 638
/
SchedulerModuleController.php
1396 lines (1298 loc) · 64.9 KB
/
SchedulerModuleController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace TYPO3\CMS\Scheduler\Controller;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Template\ModuleTemplate;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Http\HtmlResponse;
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Registry;
use TYPO3\CMS\Core\Utility\ArrayUtility;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Fluid\View\StandaloneView;
use TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper;
use TYPO3\CMS\Scheduler\AdditionalFieldProviderInterface;
use TYPO3\CMS\Scheduler\CronCommand\NormalizeCommand;
use TYPO3\CMS\Scheduler\ProgressProviderInterface;
use TYPO3\CMS\Scheduler\Scheduler;
use TYPO3\CMS\Scheduler\Task\AbstractTask;
/**
* Module 'TYPO3 Scheduler administration module' for the 'scheduler' extension.
*/
class SchedulerModuleController
{
/**
* Array containing submitted data when editing or adding a task
*
* @var array
*/
protected $submittedData = [];
/**
* Array containing all messages issued by the application logic
* Contains the error's severity and the message itself
*
* @var array
*/
protected $messages = [];
/**
* @var string Key of the CSH file
*/
protected $cshKey = '_MOD_system_txschedulerM1';
/**
* @var Scheduler Local scheduler instance
*/
protected $scheduler;
/**
* @var string
*/
protected $backendTemplatePath = '';
/**
* @var StandaloneView
*/
protected $view;
/**
* @var string Base URI of scheduler module
*/
protected $moduleUri;
/**
* ModuleTemplate Container
*
* @var ModuleTemplate
*/
protected $moduleTemplate;
/**
* @var IconFactory
*/
protected $iconFactory;
/**
* The value of GET/POST var, 'CMD'
*
* @see init()
* @var mixed
*/
public $CMD;
/**
* The module menu items array. Each key represents a key for which values can range between the items in the array of that key.
*
* @see init()
* @var array
*/
protected $MOD_MENU = [
'function' => []
];
/**
* Current settings for the keys of the MOD_MENU array
*
* @see $MOD_MENU
* @var array
*/
protected $MOD_SETTINGS = [];
/**
* Default constructor
*/
public function __construct()
{
$this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
$this->getLanguageService()->includeLLFile('EXT:scheduler/Resources/Private/Language/locallang.xlf');
$this->backendTemplatePath = ExtensionManagementUtility::extPath('scheduler') . 'Resources/Private/Templates/Backend/SchedulerModule/';
$this->view = GeneralUtility::makeInstance(StandaloneView::class);
$this->view->getRequest()->setControllerExtensionName('scheduler');
$this->view->setPartialRootPaths([ExtensionManagementUtility::extPath('scheduler') . 'Resources/Private/Partials/Backend/SchedulerModule/']);
/** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
$uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
$this->moduleUri = (string)$uriBuilder->buildUriFromRoute('system_txschedulerM1');
$this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
$this->scheduler = GeneralUtility::makeInstance(Scheduler::class);
$this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/Modal');
$this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/SplitButtons');
}
/**
* Injects the request object for the current request or subrequest
* Simply calls main() and init() and outputs the content
*
* @param ServerRequestInterface $request the current request
* @return ResponseInterface the response with the content
*/
public function mainAction(ServerRequestInterface $request): ResponseInterface
{
$this->CMD = GeneralUtility::_GP('CMD');
$this->MOD_MENU = [
'function' => [
'scheduler' => $this->getLanguageService()->getLL('function.scheduler'),
'check' => $this->getLanguageService()->getLL('function.check'),
'info' => $this->getLanguageService()->getLL('function.info')
]
];
$this->MOD_SETTINGS = BackendUtility::getModuleData($this->MOD_MENU, GeneralUtility::_GP('SET'), 'system_txschedulerM1', '', '', '');
// Set the form
$content = '<form name="tx_scheduler_form" id="tx_scheduler_form" method="post" action="">';
// Prepare main content
$content .= '<h1>' . $this->getLanguageService()->getLL('function.' . $this->MOD_SETTINGS['function']) . '</h1>';
$content .= $this->getModuleContent();
$content .= '<div id="extraFieldsSection"></div></form><div id="extraFieldsHidden"></div>';
$this->getButtons();
$this->getModuleMenu();
$this->moduleTemplate->setContent($content);
return new HtmlResponse($this->moduleTemplate->renderContent());
}
/**
* Generates the action menu
*/
protected function getModuleMenu()
{
$menu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
$menu->setIdentifier('SchedulerJumpMenu');
/** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
$uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
foreach ($this->MOD_MENU['function'] as $controller => $title) {
$item = $menu
->makeMenuItem()
->setHref(
(string)$uriBuilder->buildUriFromRoute(
'system_txschedulerM1',
[
'id' => 0,
'SET' => [
'function' => $controller
]
]
)
)
->setTitle($title);
if ($controller === $this->MOD_SETTINGS['function']) {
$item->setActive(true);
}
$menu->addMenuItem($item);
}
$this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($menu);
}
/**
* Generate the module's content
*
* @return string HTML of the module's main content
*/
protected function getModuleContent()
{
$content = '';
$sectionTitle = '';
// Get submitted data
$this->submittedData = GeneralUtility::_GPmerged('tx_scheduler');
$this->submittedData['uid'] = (int)$this->submittedData['uid'];
// If a save command was submitted, handle saving now
if ($this->CMD === 'save' || $this->CMD === 'saveclose' || $this->CMD === 'savenew') {
$previousCMD = GeneralUtility::_GP('previousCMD');
// First check the submitted data
$result = $this->preprocessData();
// If result is ok, proceed with saving
if ($result) {
$this->saveTask();
if ($this->CMD === 'saveclose') {
// Unset command, so that default screen gets displayed
unset($this->CMD);
} elseif ($this->CMD === 'save') {
// After saving a "add form", return to edit
$this->CMD = 'edit';
} elseif ($this->CMD === 'savenew') {
// Unset submitted data, so that empty form gets displayed
unset($this->submittedData);
// After saving a "add/edit form", return to add
$this->CMD = 'add';
} else {
// Return to edit form
$this->CMD = $previousCMD;
}
} else {
$this->CMD = $previousCMD;
}
}
// Handle chosen action
switch ((string)$this->MOD_SETTINGS['function']) {
case 'scheduler':
$this->executeTasks();
switch ($this->CMD) {
case 'add':
case 'edit':
try {
// Try adding or editing
$content .= $this->editTaskAction();
$sectionTitle = $this->getLanguageService()->getLL('action.' . $this->CMD);
} catch (\Exception $e) {
if ($e->getCode() === 1305100019) {
// Invalid controller class name exception
$this->addMessage($e->getMessage(), FlashMessage::ERROR);
}
// An exception may also happen when the task to
// edit could not be found. In this case revert
// to displaying the list of tasks
// It can also happen when attempting to edit a running task
$content .= $this->listTasksAction();
}
break;
case 'delete':
$this->deleteTask();
$content .= $this->listTasksAction();
break;
case 'stop':
$this->stopTask();
$content .= $this->listTasksAction();
break;
case 'toggleHidden':
$this->toggleDisableAction();
$content .= $this->listTasksAction();
break;
case 'setNextExecutionTime':
$this->setNextExecutionTimeAction();
$content .= $this->listTasksAction();
break;
case 'list':
default:
$content .= $this->listTasksAction();
}
break;
// Setup check screen
case 'check':
// @todo move check to the report module
$content .= $this->checkScreenAction();
break;
// Information screen
case 'info':
$content .= $this->infoScreenAction();
break;
}
// Wrap the content
return '<h2>' . $sectionTitle . '</h2><div class="tx_scheduler_mod1">' . $content . '</div>';
}
/**
* This method displays the result of a number of checks
* on whether the Scheduler is ready to run or running properly
*
* @return string Further information
*/
protected function checkScreenAction()
{
$this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'CheckScreen.html');
// Display information about last automated run, as stored in the system registry
$registry = GeneralUtility::makeInstance(Registry::class);
$lastRun = $registry->get('tx_scheduler', 'lastRun');
if (!is_array($lastRun)) {
$message = $this->getLanguageService()->getLL('msg.noLastRun');
$severity = InfoboxViewHelper::STATE_WARNING;
} else {
if (empty($lastRun['end']) || empty($lastRun['start']) || empty($lastRun['type'])) {
$message = $this->getLanguageService()->getLL('msg.incompleteLastRun');
$severity = InfoboxViewHelper::STATE_WARNING;
} else {
$startDate = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $lastRun['start']);
$startTime = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $lastRun['start']);
$endDate = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $lastRun['end']);
$endTime = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $lastRun['end']);
$label = 'automatically';
if ($lastRun['type'] === 'manual') {
$label = 'manually';
}
$type = $this->getLanguageService()->getLL('label.' . $label);
$message = sprintf($this->getLanguageService()->getLL('msg.lastRun'), $type, $startDate, $startTime, $endDate, $endTime);
$severity = InfoboxViewHelper::STATE_INFO;
}
}
$this->view->assign('lastRunMessage', $message);
$this->view->assign('lastRunSeverity', $severity);
// Check if CLI script is executable or not
$script = PATH_site . 'typo3/sysext/core/bin/typo3';
$this->view->assign('script', $script);
// Skip this check if running Windows, as rights do not work the same way on this platform
// (i.e. the script will always appear as *not* executable)
if (TYPO3_OS === 'WIN') {
$isExecutable = true;
} else {
$isExecutable = is_executable($script);
}
if ($isExecutable) {
$message = $this->getLanguageService()->getLL('msg.cliScriptExecutable');
$severity = InfoboxViewHelper::STATE_OK;
} else {
$message = $this->getLanguageService()->getLL('msg.cliScriptNotExecutable');
$severity = InfoboxViewHelper::STATE_ERROR;
}
$this->view->assign('isExecutableMessage', $message);
$this->view->assign('isExecutableSeverity', $severity);
$this->view->assign('now', $this->getServerTime());
return $this->view->render();
}
/**
* This method gathers information about all available task classes and displays it
*
* @return string html
*/
protected function infoScreenAction()
{
$registeredClasses = $this->getRegisteredClasses();
// No classes available, display information message
if (empty($registeredClasses)) {
$this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'InfoScreenNoClasses.html');
return $this->view->render();
}
$this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'InfoScreen.html');
$this->view->assign('registeredClasses', $registeredClasses);
return $this->view->render();
}
/**
* Delete a task from the execution queue
*/
protected function deleteTask()
{
try {
// Try to fetch the task and delete it
$task = $this->scheduler->fetchTask($this->submittedData['uid']);
// If the task is currently running, it may not be deleted
if ($task->isExecutionRunning()) {
$this->addMessage($this->getLanguageService()->getLL('msg.maynotDeleteRunningTask'), FlashMessage::ERROR);
} else {
if ($this->scheduler->removeTask($task)) {
$this->getBackendUser()->writelog(4, 0, 0, 0, 'Scheduler task "%s" (UID: %s, Class: "%s") was deleted', [$task->getTaskTitle(), $task->getTaskUid(), $task->getTaskClassName()]);
$this->addMessage($this->getLanguageService()->getLL('msg.deleteSuccess'));
} else {
$this->addMessage($this->getLanguageService()->getLL('msg.deleteError'), FlashMessage::ERROR);
}
}
} catch (\UnexpectedValueException $e) {
// The task could not be unserialized properly, simply update the database record
$taskUid = (int)$this->submittedData['uid'];
$result = GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionForTable('tx_scheduler_task')
->update('tx_scheduler_task', ['deleted' => 1], ['uid' => $taskUid]);
if ($result) {
$this->addMessage($this->getLanguageService()->getLL('msg.deleteSuccess'));
} else {
$this->addMessage($this->getLanguageService()->getLL('msg.deleteError'), FlashMessage::ERROR);
}
} catch (\OutOfBoundsException $e) {
// The task was not found, for some reason
$this->addMessage(sprintf($this->getLanguageService()->getLL('msg.taskNotFound'), $this->submittedData['uid']), FlashMessage::ERROR);
}
}
/**
* Clears the registered running executions from the task
* Note that this doesn't actually stop the running script. It just unmarks
* all executions.
* @todo find a way to really kill the running task
*/
protected function stopTask()
{
try {
// Try to fetch the task and stop it
$task = $this->scheduler->fetchTask($this->submittedData['uid']);
if ($task->isExecutionRunning()) {
// If the task is indeed currently running, clear marked executions
$result = $task->unmarkAllExecutions();
if ($result) {
$this->addMessage($this->getLanguageService()->getLL('msg.stopSuccess'));
} else {
$this->addMessage($this->getLanguageService()->getLL('msg.stopError'), FlashMessage::ERROR);
}
} else {
// The task is not running, nothing to unmark
$this->addMessage($this->getLanguageService()->getLL('msg.maynotStopNonRunningTask'), FlashMessage::WARNING);
}
} catch (\Exception $e) {
// The task was not found, for some reason
$this->addMessage(sprintf($this->getLanguageService()->getLL('msg.taskNotFound'), $this->submittedData['uid']), FlashMessage::ERROR);
}
}
/**
* Toggles the disabled state of the submitted task
*/
protected function toggleDisableAction()
{
$task = $this->scheduler->fetchTask($this->submittedData['uid']);
$task->setDisabled(!$task->isDisabled());
// If a disabled single task is enabled again, we register it for a
// single execution at next scheduler run.
if ($task->getType() === AbstractTask::TYPE_SINGLE) {
$task->registerSingleExecution(time());
}
$task->save();
}
/**
* Sets the next execution time of the submitted task to now
*/
protected function setNextExecutionTimeAction()
{
$task = $this->scheduler->fetchTask($this->submittedData['uid']);
$task->setRunOnNextCronJob(true);
$task->save();
}
/**
* Return a form to add a new task or edit an existing one
*
* @return string HTML form to add or edit a task
*/
protected function editTaskAction()
{
$this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'EditTask.html');
$registeredClasses = $this->getRegisteredClasses();
$registeredTaskGroups = $this->getRegisteredTaskGroups();
$taskInfo = [];
$task = null;
$process = 'edit';
if ($this->submittedData['uid'] > 0) {
// If editing, retrieve data for existing task
try {
$taskRecord = $this->scheduler->fetchTaskRecord($this->submittedData['uid']);
// If there's a registered execution, the task should not be edited
if (!empty($taskRecord['serialized_executions'])) {
$this->addMessage($this->getLanguageService()->getLL('msg.maynotEditRunningTask'), FlashMessage::ERROR);
throw new \LogicException('Runnings tasks cannot not be edited', 1251232849);
}
// Get the task object
/** @var $task \TYPO3\CMS\Scheduler\Task\AbstractTask */
$task = unserialize($taskRecord['serialized_task_object']);
// Set some task information
$taskInfo['disable'] = $taskRecord['disable'];
$taskInfo['description'] = $taskRecord['description'];
$taskInfo['task_group'] = $taskRecord['task_group'];
// Check that the task object is valid
if (isset($registeredClasses[get_class($task)]) && $this->scheduler->isValidTaskObject($task)) {
// The task object is valid, process with fetching current data
$taskInfo['class'] = get_class($task);
// Get execution information
$taskInfo['start'] = (int)$task->getExecution()->getStart();
$taskInfo['end'] = (int)$task->getExecution()->getEnd();
$taskInfo['interval'] = $task->getExecution()->getInterval();
$taskInfo['croncmd'] = $task->getExecution()->getCronCmd();
$taskInfo['multiple'] = $task->getExecution()->getMultiple();
if (!empty($taskInfo['interval']) || !empty($taskInfo['croncmd'])) {
// Guess task type from the existing information
// If an interval or a cron command is defined, it's a recurring task
$taskInfo['type'] = AbstractTask::TYPE_RECURRING;
$taskInfo['frequency'] = $taskInfo['interval'] ?: $taskInfo['croncmd'];
} else {
// It's not a recurring task
// Make sure interval and cron command are both empty
$taskInfo['type'] = AbstractTask::TYPE_SINGLE;
$taskInfo['frequency'] = '';
$taskInfo['end'] = 0;
}
} else {
// The task object is not valid
// Issue error message
$this->addMessage(sprintf($this->getLanguageService()->getLL('msg.invalidTaskClassEdit'), get_class($task)), FlashMessage::ERROR);
// Initialize empty values
$taskInfo['start'] = 0;
$taskInfo['end'] = 0;
$taskInfo['frequency'] = '';
$taskInfo['multiple'] = false;
$taskInfo['type'] = AbstractTask::TYPE_SINGLE;
}
} catch (\OutOfBoundsException $e) {
// Add a message and continue throwing the exception
$this->addMessage(sprintf($this->getLanguageService()->getLL('msg.taskNotFound'), $this->submittedData['uid']), FlashMessage::ERROR);
throw $e;
}
} else {
// If adding a new object, set some default values
$taskInfo['class'] = key($registeredClasses);
$taskInfo['type'] = AbstractTask::TYPE_RECURRING;
$taskInfo['start'] = $GLOBALS['EXEC_TIME'];
$taskInfo['end'] = '';
$taskInfo['frequency'] = '';
$taskInfo['multiple'] = 0;
$process = 'add';
}
// If some data was already submitted, use it to override
// existing data
if (!empty($this->submittedData)) {
ArrayUtility::mergeRecursiveWithOverrule($taskInfo, $this->submittedData);
}
// Get the extra fields to display for each task that needs some
$allAdditionalFields = [];
if ($process === 'add') {
foreach ($registeredClasses as $class => $registrationInfo) {
if (!empty($registrationInfo['provider'])) {
/** @var $providerObject AdditionalFieldProviderInterface */
$providerObject = GeneralUtility::makeInstance($registrationInfo['provider']);
if ($providerObject instanceof AdditionalFieldProviderInterface) {
$additionalFields = $providerObject->getAdditionalFields($taskInfo, null, $this);
$allAdditionalFields = array_merge($allAdditionalFields, [$class => $additionalFields]);
}
}
}
} elseif ($task !== null && !empty($registeredClasses[$taskInfo['class']]['provider'])) {
// only try to fetch additionalFields if the task is valid
$providerObject = GeneralUtility::makeInstance($registeredClasses[$taskInfo['class']]['provider']);
if ($providerObject instanceof AdditionalFieldProviderInterface) {
$allAdditionalFields[$taskInfo['class']] = $providerObject->getAdditionalFields($taskInfo, $task, $this);
}
}
// Load necessary JavaScript
$this->getPageRenderer()->loadJquery();
$this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Scheduler/Scheduler');
$this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/DateTimePicker');
$this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Scheduler/PageBrowser');
$this->getPageRenderer()->addJsInlineCode('browse-button', '
function setFormValueFromBrowseWin(fieldReference, elValue, elName) {
var res = elValue.split("_");
var element = document.getElementById(fieldReference);
element.value = res[1];
}
');
// Start rendering the add/edit form
$this->view->assign('uid', htmlspecialchars($this->submittedData['uid']));
$this->view->assign('cmd', htmlspecialchars($this->CMD));
$this->view->assign('csh', $this->cshKey);
$this->view->assign('lang', 'LLL:EXT:scheduler/Resources/Private/Language/locallang.xlf:');
$table = [];
// Disable checkbox
$this->view->assign('task_disable', ($taskInfo['disable'] ? ' checked="checked"' : ''));
$this->view->assign('task_disable_label', 'LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:disable');
// Task class selector
// On editing, don't allow changing of the task class, unless it was not valid
if ($this->submittedData['uid'] > 0 && !empty($taskInfo['class'])) {
$this->view->assign('task_class', $taskInfo['class']);
$this->view->assign('task_class_title', $registeredClasses[$taskInfo['class']]['title']);
$this->view->assign('task_class_extension', $registeredClasses[$taskInfo['class']]['extension']);
} else {
// Group registered classes by classname
$groupedClasses = [];
foreach ($registeredClasses as $class => $classInfo) {
$groupedClasses[$classInfo['extension']][$class] = $classInfo;
}
ksort($groupedClasses);
foreach ($groupedClasses as $extension => $class) {
foreach ($groupedClasses[$extension] as $class => $classInfo) {
$selected = $class == $taskInfo['class'] ? ' selected="selected"' : '';
$groupedClasses[$extension][$class]['selected'] = $selected;
}
}
$this->view->assign('groupedClasses', $groupedClasses);
}
// Task type selector
$this->view->assign('task_type_selected_1', ((int)$taskInfo['type'] === AbstractTask::TYPE_SINGLE ? ' selected="selected"' : ''));
$this->view->assign('task_type_selected_2', ((int)$taskInfo['type'] === AbstractTask::TYPE_RECURRING ? ' selected="selected"' : ''));
// Task group selector
foreach ($registeredTaskGroups as $key => $taskGroup) {
$selected = $taskGroup['uid'] == $taskInfo['task_group'] ? ' selected="selected"' : '';
$registeredTaskGroups[$key]['selected'] = $selected;
}
$this->view->assign('registeredTaskGroups', $registeredTaskGroups);
// Start date/time field
$dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['USdateFormat'] ? '%H:%M %m-%d-%Y' : '%H:%M %d-%m-%Y';
$this->view->assign('start_value_hr', ($taskInfo['start'] > 0 ? strftime($dateFormat, $taskInfo['start']) : ''));
$this->view->assign('start_value', $taskInfo['start']);
// End date/time field
// NOTE: datetime fields need a special id naming scheme
$this->view->assign('end_value_hr', ($taskInfo['end'] > 0 ? strftime($dateFormat, $taskInfo['end']) : ''));
$this->view->assign('end_value', $taskInfo['end']);
// Frequency input field
$this->view->assign('frequency', $taskInfo['frequency']);
// Multiple execution selector
$this->view->assign('multiple', ($taskInfo['multiple'] ? 'checked="checked"' : ''));
// Description
$this->view->assign('description', $taskInfo['description']);
// Display additional fields
$additionalFieldList = [];
foreach ($allAdditionalFields as $class => $fields) {
if ($class == $taskInfo['class']) {
$additionalFieldsStyle = '';
} else {
$additionalFieldsStyle = ' style="display: none"';
}
// Add each field to the display, if there are indeed any
if (isset($fields) && is_array($fields)) {
foreach ($fields as $fieldID => $fieldInfo) {
$htmlClassName = strtolower(str_replace('\\', '-', $class));
$field = [];
$field['htmlClassName'] = $htmlClassName;
$field['code'] = $fieldInfo['code'];
$field['cshKey'] = $fieldInfo['cshKey'];
$field['cshLabel'] = $fieldInfo['cshLabel'];
$field['langLabel'] = $fieldInfo['label'];
$field['fieldID'] = $fieldID;
$field['additionalFieldsStyle'] = $additionalFieldsStyle;
$field['browseButton'] = $this->getBrowseButton($fieldID, $fieldInfo);
$additionalFieldList[] = $field;
}
}
}
$this->view->assign('additionalFields', $additionalFieldList);
$this->view->assign('returnUrl', rawurlencode((string)GeneralUtility::getIndpEnv('REQUEST_URI')));
$this->view->assign('table', implode(LF, $table));
$this->view->assign('now', $this->getServerTime());
return $this->view->render();
}
/**
* @param string $fieldID The id of the field witch contains the page id
* @param array $fieldInfo The array with the field info, contains the page title shown beside the button
* @return string HTML code for the browse button
*/
protected function getBrowseButton($fieldID, array $fieldInfo)
{
if (isset($fieldInfo['browser']) && ($fieldInfo['browser'] === 'page')) {
/** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
$uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
$url = (string)$uriBuilder->buildUriFromRoute(
'wizard_element_browser',
['mode' => 'db', 'bparams' => $fieldID . '|||pages|']
);
$title = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.browse_db'));
return '
<div><a href="#" data-url=' . htmlspecialchars($url) . ' class="btn btn-default t3js-pageBrowser" title="' . $title . '">
<span class="t3js-icon icon icon-size-small icon-state-default icon-actions-insert-record" data-identifier="actions-insert-record">
<span class="icon-markup">' . $this->iconFactory->getIcon(
'actions-insert-record',
Icon::SIZE_SMALL
)->render() . '</span>
</span>
</a><span id="page_' . $fieldID . '"> ' . htmlspecialchars($fieldInfo['pageTitle']) . '</span></div>';
}
return '';
}
/**
* Execute all selected tasks
*/
protected function executeTasks()
{
// Continue if some elements have been chosen for execution
if (isset($this->submittedData['execute']) && !empty($this->submittedData['execute'])) {
// Get list of registered classes
$registeredClasses = $this->getRegisteredClasses();
// Loop on all selected tasks
foreach ($this->submittedData['execute'] as $uid) {
try {
// Try fetching the task
$task = $this->scheduler->fetchTask($uid);
$class = get_class($task);
$name = $registeredClasses[$class]['title'] . ' (' . $registeredClasses[$class]['extension'] . ')';
if (GeneralUtility::_POST('go_cron') !== null) {
$task->setRunOnNextCronJob(true);
$task->save();
} else {
// Now try to execute it and report on outcome
try {
$result = $this->scheduler->executeTask($task);
if ($result) {
$this->addMessage(sprintf($this->getLanguageService()->getLL('msg.executed'), $name));
} else {
$this->addMessage(sprintf($this->getLanguageService()->getLL('msg.notExecuted'), $name), FlashMessage::ERROR);
}
} catch (\Exception $e) {
// An exception was thrown, display its message as an error
$this->addMessage(sprintf($this->getLanguageService()->getLL('msg.executionFailed'), $name, $e->getMessage()), FlashMessage::ERROR);
}
}
} catch (\OutOfBoundsException $e) {
$this->addMessage(sprintf($this->getLanguageService()->getLL('msg.taskNotFound'), $uid), FlashMessage::ERROR);
} catch (\UnexpectedValueException $e) {
$this->addMessage(sprintf($this->getLanguageService()->getLL('msg.executionFailed'), $uid, $e->getMessage()), FlashMessage::ERROR);
}
}
// Record the run in the system registry
$this->scheduler->recordLastRun('manual');
// Make sure to switch to list view after execution
$this->CMD = 'list';
}
}
/**
* Assemble display of list of scheduled tasks
*
* @return string Table of pending tasks
*/
protected function listTasksAction()
{
$this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'ListTasks.html');
// Define display format for dates
$dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
// Get list of registered task groups
$registeredTaskGroups = $this->getRegisteredTaskGroups();
// add an empty entry for non-grouped tasks
// add in front of list
array_unshift($registeredTaskGroups, ['uid' => 0, 'groupName' => '']);
// Get all registered tasks
// Just to get the number of entries
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_scheduler_task');
$queryBuilder->getRestrictions()->removeAll();
$result = $queryBuilder->select('t.*')
->addSelect(
'g.groupName AS taskGroupName',
'g.description AS taskGroupDescription',
'g.deleted AS isTaskGroupDeleted'
)
->from('tx_scheduler_task', 't')
->leftJoin(
't',
'tx_scheduler_task_group',
'g',
$queryBuilder->expr()->eq('t.task_group', $queryBuilder->quoteIdentifier('g.uid'))
)
->where(
$queryBuilder->expr()->eq('t.deleted', 0)
)
->orderBy('g.sorting')
->execute();
// Loop on all tasks
$temporaryResult = [];
while ($row = $result->fetch()) {
if ($row['taskGroupName'] === null || $row['isTaskGroupDeleted'] === '1') {
$row['taskGroupName'] = '';
$row['taskGroupDescription'] = '';
$row['task_group'] = 0;
}
$temporaryResult[$row['task_group']]['groupName'] = $row['taskGroupName'];
$temporaryResult[$row['task_group']]['groupDescription'] = $row['taskGroupDescription'];
$temporaryResult[$row['task_group']]['tasks'][] = $row;
}
// No tasks defined, display information message
if (empty($temporaryResult)) {
$this->view->setTemplatePathAndFilename($this->backendTemplatePath . 'ListTasksNoTasks.html');
return $this->view->render();
}
$this->getPageRenderer()->loadJquery();
$this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Scheduler/Scheduler');
$this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/Tooltip');
$tasks = $temporaryResult;
$registeredClasses = $this->getRegisteredClasses();
$missingClasses = [];
foreach ($temporaryResult as $taskIndex => $taskGroup) {
foreach ($taskGroup['tasks'] as $recordIndex => $schedulerRecord) {
if ((int)$schedulerRecord['disable'] === 1) {
$translationKey = 'enable';
} else {
$translationKey = 'disable';
}
$tasks[$taskIndex]['tasks'][$recordIndex]['translationKey'] = $translationKey;
// Define some default values
$lastExecution = '-';
$isRunning = false;
$showAsDisabled = false;
// Restore the serialized task and pass it a reference to the scheduler object
/** @var $task \TYPO3\CMS\Scheduler\Task\AbstractTask|ProgressProviderInterface */
$task = unserialize($schedulerRecord['serialized_task_object']);
$class = get_class($task);
if ($class === '__PHP_Incomplete_Class' && preg_match('/^O:[0-9]+:"(?P<classname>.+?)"/', $schedulerRecord['serialized_task_object'], $matches) === 1) {
$class = $matches['classname'];
}
$tasks[$taskIndex]['tasks'][$recordIndex]['class'] = $class;
// Assemble information about last execution
if (!empty($schedulerRecord['lastexecution_time'])) {
$lastExecution = date($dateFormat, $schedulerRecord['lastexecution_time']);
if ($schedulerRecord['lastexecution_context'] === 'CLI') {
$context = $this->getLanguageService()->getLL('label.cron');
} else {
$context = $this->getLanguageService()->getLL('label.manual');
}
$lastExecution .= ' (' . $context . ')';
}
$tasks[$taskIndex]['tasks'][$recordIndex]['lastExecution'] = $lastExecution;
if (isset($registeredClasses[get_class($task)]) && $this->scheduler->isValidTaskObject($task)) {
$tasks[$taskIndex]['tasks'][$recordIndex]['validClass'] = true;
// The task object is valid
$labels = [];
$additionalInformation = $task->getAdditionalInformation();
if ($task instanceof ProgressProviderInterface) {
$progress = round((float)$task->getProgress(), 2);
$tasks[$taskIndex]['tasks'][$recordIndex]['progress'] = $progress;
}
$tasks[$taskIndex]['tasks'][$recordIndex]['classTitle'] = $registeredClasses[$class]['title'];
$tasks[$taskIndex]['tasks'][$recordIndex]['classExtension'] = $registeredClasses[$class]['extension'];
$tasks[$taskIndex]['tasks'][$recordIndex]['additionalInformation'] = $additionalInformation;
// Check if task currently has a running execution
if (!empty($schedulerRecord['serialized_executions'])) {
$labels[] = [
'class' => 'success',
'text' => $this->getLanguageService()->getLL('status.running')
];
$isRunning = true;
}
$tasks[$taskIndex]['tasks'][$recordIndex]['isRunning'] = $isRunning;
// Prepare display of next execution date
// If task is currently running, date is not displayed (as next hasn't been calculated yet)
// Also hide the date if task is disabled (the information doesn't make sense, as it will not run anyway)
if ($isRunning || $schedulerRecord['disable']) {
$nextDate = '-';
} else {
$nextDate = date($dateFormat, $schedulerRecord['nextexecution']);
if (empty($schedulerRecord['nextexecution'])) {
$nextDate = $this->getLanguageService()->getLL('none');
} elseif ($schedulerRecord['nextexecution'] < $GLOBALS['EXEC_TIME']) {
$labels[] = [
'class' => 'warning',
'text' => $this->getLanguageService()->getLL('status.late'),
'description' => $this->getLanguageService()->getLL('status.legend.scheduled')
];
}
}
$tasks[$taskIndex]['tasks'][$recordIndex]['nextDate'] = $nextDate;
// Get execution type
if ($task->getType() === AbstractTask::TYPE_SINGLE) {
$execType = $this->getLanguageService()->getLL('label.type.single');
$frequency = '-';
} else {
$execType = $this->getLanguageService()->getLL('label.type.recurring');
if ($task->getExecution()->getCronCmd() == '') {
$frequency = $task->getExecution()->getInterval();
} else {
$frequency = $task->getExecution()->getCronCmd();
}
}
// Check the disable status
// Row is shown dimmed if task is disabled, unless it is still running
if ($schedulerRecord['disable'] && !$isRunning) {
$labels[] = [
'class' => 'default',
'text' => $this->getLanguageService()->getLL('status.disabled')
];
$showAsDisabled = true;
}
$tasks[$taskIndex]['tasks'][$recordIndex]['execType'] = $execType;
$tasks[$taskIndex]['tasks'][$recordIndex]['frequency'] = $frequency;
// Get multiple executions setting
if ($task->getExecution()->getMultiple()) {
$multiple = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:yes');
} else {
$multiple = $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:no');
}
$tasks[$taskIndex]['tasks'][$recordIndex]['multiple'] = $multiple;
// Check if the last run failed
if (!empty($schedulerRecord['lastexecution_failure'])) {
// Try to get the stored exception array
/** @var $exceptionArray array */
$exceptionArray = @unserialize($schedulerRecord['lastexecution_failure']);
// If the exception could not be unserialized, issue a default error message
if (!is_array($exceptionArray) || empty($exceptionArray)) {
$labelDescription = $this->getLanguageService()->getLL('msg.executionFailureDefault');
} else {
$labelDescription = sprintf($this->getLanguageService()->getLL('msg.executionFailureReport'), $exceptionArray['code'], $exceptionArray['message']);
}
$labels[] = [
'class' => 'danger',
'text' => $this->getLanguageService()->getLL('status.failure'),
'description' => $labelDescription
];
}
$tasks[$taskIndex]['tasks'][$recordIndex]['labels'] = $labels;
if ($showAsDisabled) {
$tasks[$taskIndex]['tasks'][$recordIndex]['showAsDisabled'] = 'disabled';
}
} else {
$missingClasses[] = $tasks[$taskIndex]['tasks'][$recordIndex];
unset($tasks[$taskIndex]['tasks'][$recordIndex]);
}
}
}
$this->view->assign('tasks', $tasks);
$this->view->assign('missingClasses', $missingClasses);
$this->view->assign('moduleUri', $this->moduleUri);
$this->view->assign('now', $this->getServerTime());
return $this->view->render();
}
/**
* Generates bootstrap labels containing the label statuses
*
* @param array $labels
* @return string
*/
protected function makeStatusLabel(array $labels)
{
$htmlLabels = [];