ExecuteSchedulableCommandAdditionalFieldProvider.php 17.5 KB
Newer Older
1
<?php
2

3
declare(strict_types=1);
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/*
 * 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!
 */

18
19
namespace TYPO3\CMS\Scheduler\Task;

20
21
22
23
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
24
use Symfony\Component\Console\Input\InputOption;
25
use TYPO3\CMS\Core\Console\CommandRegistry;
26
use TYPO3\CMS\Core\Localization\LanguageService;
27
28
29
30
31
32
33
34
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Scheduler\AdditionalFieldProviderInterface;
use TYPO3\CMS\Scheduler\Controller\SchedulerModuleController;
use TYPO3Fluid\Fluid\Core\ViewHelper\TagBuilder;

/**
35
 * @internal This class is a specific scheduler task implementation is not considered part of the Public TYPO3 API.
36
37
38
39
 */
class ExecuteSchedulableCommandAdditionalFieldProvider implements AdditionalFieldProviderInterface
{
    /**
40
     * @var Command[]
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
     */
    protected $schedulableCommands = [];

    /**
     * @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
     */
    protected $objectManager;

    /**
     * @var \TYPO3\CMS\Extbase\Reflection\ReflectionService
     */
    protected $reflectionService;

    /**
     * @var ExecuteSchedulableCommandTask
     */
    protected $task;

    public function __construct()
    {
        $commandRegistry = GeneralUtility::makeInstance(CommandRegistry::class);
62
        foreach ($commandRegistry->getSchedulableCommands() as $commandIdentifier => $command) {
63
64
65
66
67
68
69
70
71
            $this->schedulableCommands[$commandIdentifier] = $command;
        }

        ksort($this->schedulableCommands);
    }

    /**
     * Render additional information fields within the scheduler backend.
     *
72
     * @param array $taskInfo Array information of task to return
73
     * @param ExecuteSchedulableCommandTask|null $task When editing, reference to the current task. NULL when adding.
74
75
     * @param SchedulerModuleController $schedulerModule Reference to the calling object (BE module of the Scheduler)
     * @return array Additional fields
76
     * @see \TYPO3\CMS\Scheduler\AdditionalFieldProviderInterface::getAdditionalFields
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
     */
    public function getAdditionalFields(array &$taskInfo, $task, SchedulerModuleController $schedulerModule): array
    {
        $this->task = $task;
        if ($this->task !== null) {
            $this->task->setScheduler();
        }

        $fields = [];
        $fields['action'] = $this->getActionField();

        if ($this->task !== null && isset($this->schedulableCommands[$this->task->getCommandIdentifier()])) {
            $command = $this->schedulableCommands[$this->task->getCommandIdentifier()];
            $fields['description'] = $this->getCommandDescriptionField($command->getDescription());
            $argumentFields = $this->getCommandArgumentFields($command->getDefinition());
            $fields = array_merge($fields, $argumentFields);
93
94
            $optionFields = $this->getCommandOptionFields($command->getDefinition());
            $fields = array_merge($fields, $optionFields);
95
96
97
98
99
100
101
102
103
            $this->task->save(); // todo: this seems to be superfluous
        }

        return $fields;
    }

    /**
     * Validates additional selected fields
     *
104
     * @param array $submittedData
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
     * @param SchedulerModuleController $schedulerModule
     * @return bool
     */
    public function validateAdditionalFields(array &$submittedData, SchedulerModuleController $schedulerModule): bool
    {
        if (!isset($this->schedulableCommands[$submittedData['task_executeschedulablecommand']['command']])) {
            return false;
        }

        $command = $this->schedulableCommands[$submittedData['task_executeschedulablecommand']['command']];

        /** @var FlashMessageService $flashMessageService */
        $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);

        $hasErrors = false;
        foreach ($command->getDefinition()->getArguments() as $argument) {
            foreach ((array)$submittedData['task_executeschedulablecommand']['arguments'] as $argumentName => $argumentValue) {
                /** @var string $argumentName */
                /** @var string $argumentValue */
                if ($argument->getName() !== $argumentName) {
                    continue;
                }

                if ($argument->isRequired() && trim($argumentValue) === '') {
                    // Argument is required and argument value is empty0
                    $flashMessageService->getMessageQueueByIdentifier()->addMessage(
                        new FlashMessage(
                            sprintf(
                                $this->getLanguageService()->sL('LLL:EXT:scheduler/Resources/Private/Language/locallang.xlf:msg.mandatoryArgumentMissing'),
                                $argumentName
                            ),
                            $this->getLanguageService()->sL('LLL:EXT:scheduler/Resources/Private/Language/locallang.xlf:msg.updateError'),
                            FlashMessage::ERROR
                        )
                    );
                    $hasErrors = true;
                }
            }
        }
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

        foreach ($command->getDefinition()->getOptions() as $optionDefinition) {
            $optionEnabled = $submittedData['task_executeschedulablecommand']['options'][$optionDefinition->getName()] ?? false;
            $optionValue = $submittedData['task_executeschedulablecommand']['option_values'][$optionDefinition->getName()] ?? $optionDefinition->getDefault();
            if ($optionEnabled && $optionDefinition->isValueRequired()) {
                if ($optionDefinition->isArray()) {
                    $testValues = is_array($optionValue) ? $optionValue : GeneralUtility::trimExplode(',', $optionValue, false);
                } else {
                    $testValues = [$optionValue];
                }

                foreach ($testValues as $testValue) {
                    if ($testValue === null || trim($testValue) === '') {
                        // An option that requires a value is used with an empty value
                        $flashMessageService->getMessageQueueByIdentifier()->addMessage(
                            new FlashMessage(
                                sprintf(
                                    $this->getLanguageService()->sL('LLL:EXT:scheduler/Resources/Private/Language/locallang.xlf:msg.mandatoryArgumentMissing'),
                                    $optionDefinition->getName()
                                ),
                                $this->getLanguageService()->sL('LLL:EXT:scheduler/Resources/Private/Language/locallang.xlf:msg.updateError'),
                                FlashMessage::ERROR
                            )
                        );
                        $hasErrors = true;
                    }
                }
            }
        }

174
175
176
177
178
179
180
        return $hasErrors === false;
    }

    /**
     * Saves additional field values
     *
     * @param array $submittedData
181
     * @param ExecuteSchedulableCommandTask $task
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
     * @return bool
     */
    public function saveAdditionalFields(array $submittedData, AbstractTask $task): bool
    {
        $command = $this->schedulableCommands[$submittedData['task_executeschedulablecommand']['command']];

        /** @var ExecuteSchedulableCommandTask $task */
        $task->setCommandIdentifier($submittedData['task_executeschedulablecommand']['command']);

        $arguments = [];
        foreach ((array)$submittedData['task_executeschedulablecommand']['arguments'] as $argumentName => $argumentValue) {
            try {
                $argumentDefinition = $command->getDefinition()->getArgument($argumentName);
            } catch (InvalidArgumentException $e) {
                continue;
            }

            if ($argumentDefinition->isArray()) {
                $argumentValue = GeneralUtility::trimExplode(',', $argumentValue, true);
            }

            $arguments[$argumentName] = $argumentValue;
        }

206
207
208
209
210
211
212
213
214
215
        $options = [];
        $optionValues = [];
        foreach ($command->getDefinition()->getOptions() as $optionDefinition) {
            $optionEnabled = $submittedData['task_executeschedulablecommand']['options'][$optionDefinition->getName()] ?? false;
            $options[$optionDefinition->getName()] = (bool)$optionEnabled;

            if ($optionDefinition->isValueRequired() || $optionDefinition->isValueOptional() || $optionDefinition->isArray()) {
                $optionValue = $submittedData['task_executeschedulablecommand']['option_values'][$optionDefinition->getName()] ?? $optionDefinition->getDefault();
                if ($optionDefinition->isArray() && !is_array($optionValue)) {
                    // Do not remove empty array values.
216
                    // One empty array element indicates the existence of one occurrence of an array option (InputOption::VALUE_IS_ARRAY) without a value.
217
218
219
220
221
222
223
224
225
226
                    // Empty array elements are also required for command options like "-vvv" (can be entered as ",,").
                    $optionValue = GeneralUtility::trimExplode(',', $optionValue, false);
                }
            } else {
                // boolean flag: option value must be true if option is added or false otherwise
                $optionValue = (bool)$optionEnabled;
            }
            $optionValues[$optionDefinition->getName()] = $optionValue;
        }

227
        $task->setArguments($arguments);
228
229
        $task->setOptions($options);
        $task->setOptionValues($optionValues);
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
        return true;
    }

    /**
     * Get description of selected command
     *
     * @param string $description
     * @return array
     */
    protected function getCommandDescriptionField(string $description): array
    {
        return [
            'code' => '',
            'label' => '<strong>' . $description . '</strong>'
        ];
    }

    /**
     * Gets a select field containing all possible schedulable commands
     *
     * @return array
     */
    protected function getActionField(): array
    {
        $currentlySelectedCommand = $this->task !== null ? $this->task->getCommandIdentifier() : '';
        $options = [];
        foreach ($this->schedulableCommands as $commandIdentifier => $command) {
            $options[$commandIdentifier] = $commandIdentifier . ': ' . $command->getDescription();
        }
        return [
            'code' => $this->renderSelectField($options, $currentlySelectedCommand),
            'label' => $this->getLanguageService()->sL('LLL:EXT:scheduler/Resources/Private/Language/locallang.xlf:label.schedulableCommandName')
        ];
    }

    /**
     * Gets a set of fields covering arguments which can or must be used.
     * Also registers the default values of those fields with the Task, allowing
     * them to be read upon execution.
     *
     * @param InputDefinition $inputDefinition
     * @return array
     */
    protected function getCommandArgumentFields(InputDefinition $inputDefinition): array
    {
        $fields = [];
        $argumentValues = $this->task->getArguments();
        foreach ($inputDefinition->getArguments() as $argument) {
            $name = $argument->getName();
            $defaultValue = $argument->getDefault();
            $this->task->addDefaultValue($name, $defaultValue);
            $value = $argumentValues[$name] ?? $defaultValue;

            if (is_array($value) && $argument->isArray()) {
                $value = implode(',', $value);
            }

            $fields[$name] = [
288
                'code' => $this->renderArgumentField($argument, (string)$value),
289
290
291
292
293
294
295
                'label' => $this->getArgumentLabel($argument)
            ];
        }

        return $fields;
    }

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
    /**
     * Gets a set of fields covering options which can or must be used.
     * Also registers the default values of those fields with the Task, allowing
     * them to be read upon execution.
     *
     * @param InputDefinition $inputDefinition
     * @return array
     */
    protected function getCommandOptionFields(InputDefinition $inputDefinition): array
    {
        $fields = [];
        $enabledOptions = $this->task->getOptions();
        $optionValues = $this->task->getOptionValues();
        foreach ($inputDefinition->getOptions() as $option) {
            $name = $option->getName();
            $defaultValue = $option->getDefault();
            $this->task->addDefaultValue($name, $defaultValue);
            $enabled = $enabledOptions[$name] ?? false;
            $value = $optionValues[$name] ?? $defaultValue;

            if (is_array($value) && $option->isArray()) {
                $value = implode(',', $value);
            }

            $fields[$name] = [
                'code' => $this->renderOptionField($option, (bool)$enabled, (string)$value),
                'label' => $this->getOptionLabel($option)
            ];
        }

        return $fields;
    }

329
330
331
332
333
334
335
336
337
338
339
    /**
     * Get a human-readable label for a command argument
     *
     * @param InputArgument $argument
     * @return string
     */
    protected function getArgumentLabel(InputArgument $argument): string
    {
        return 'Argument: ' . $argument->getName() . '. <em>' . htmlspecialchars($argument->getDescription()) . '</em>';
    }

340
341
342
343
344
345
346
347
348
349
350
    /**
     * Get a human-readable label for a command option
     *
     * @param InputOption $option
     * @return string
     */
    protected function getOptionLabel(InputOption $option): string
    {
        return 'Option: ' . htmlspecialchars($option->getName()) . '. <em>' . htmlspecialchars($option->getDescription()) . '</em>';
    }

351
352
353
354
355
356
357
358
359
360
    /**
     * @param array $options
     * @param string $selectedOptionValue
     * @return string
     */
    protected function renderSelectField(array $options, string $selectedOptionValue): string
    {
        $selectTag = new TagBuilder();
        $selectTag->setTagName('select');
        $selectTag->forceClosingTag(true);
361
        $selectTag->addAttribute('class', 'form-select');
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
        $selectTag->addAttribute('name', 'tx_scheduler[task_executeschedulablecommand][command]');

        $optionsHtml = '';
        foreach ($options as $value => $label) {
            $optionTag = new TagBuilder();
            $optionTag->setTagName('option');
            $optionTag->forceClosingTag(true);
            $optionTag->addAttribute('title', (string)$label);
            $optionTag->addAttribute('value', (string)$value);
            $optionTag->setContent($label);

            if ($value === $selectedOptionValue) {
                $optionTag->addAttribute('selected', 'selected');
            }

            $optionsHtml .= $optionTag->render();
        }

        $selectTag->setContent($optionsHtml);
        return $selectTag->render();
    }

    /**
     * Renders a field for defining an argument's value
     *
     * @param InputArgument $argument
388
     * @param string $currentValue
389
390
     * @return string
     */
391
    protected function renderArgumentField(InputArgument $argument, string $currentValue): string
392
393
394
395
396
397
398
399
400
401
402
403
404
405
    {
        $name = $argument->getName();
        $fieldName = 'tx_scheduler[task_executeschedulablecommand][arguments][' . $name . ']';

        $inputTag = new TagBuilder();
        $inputTag->setTagName('input');
        $inputTag->addAttribute('type', 'text');
        $inputTag->addAttribute('name', $fieldName);
        $inputTag->addAttribute('value', $currentValue);
        $inputTag->addAttribute('class', 'form-control');

        return $inputTag->render();
    }

406
407
408
409
    /**
     * Renders a field for defining an option's value
     *
     * @param InputOption $option
410
     * @param string $currentValue
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
     * @return string
     */
    protected function renderOptionField(InputOption $option, bool $enabled, string $currentValue): string
    {
        $name = $option->getName();

        $checkboxFieldName = 'tx_scheduler[task_executeschedulablecommand][options][' . $name . ']';
        $checkboxId = 'tx_scheduler_task_executeschedulablecommand_options_' . $name;
        $checkboxTag = new TagBuilder();
        $checkboxTag->setTagName('input');
        $checkboxTag->addAttribute('id', $checkboxId);
        $checkboxTag->addAttribute('name', $checkboxFieldName);
        $checkboxTag->addAttribute('type', 'checkbox');
        if ($enabled) {
            $checkboxTag->addAttribute('checked', 'checked');
        }
        $html = '<label for="' . $checkboxId . '">'
            . $checkboxTag->render()
            . ' ' . $this->getLanguageService()->sL('LLL:EXT:scheduler/Resources/Private/Language/locallang.xlf:label.addOptionToCommand')
            . '</label>';

        if ($option->isValueRequired() || $option->isValueOptional() || $option->isArray()) {
            $valueFieldName = 'tx_scheduler[task_executeschedulablecommand][option_values][' . $name . ']';
            $inputTag = new TagBuilder();
            $inputTag->setTagName('input');
            $inputTag->addAttribute('name', $valueFieldName);
            $inputTag->addAttribute('type', 'text');
            $inputTag->addAttribute('value', $currentValue);
            $inputTag->addAttribute('class', 'form-control');
            $html .=  $inputTag->render();
        }

        return $html;
    }

446
447
448
449
450
451
452
453
    /**
     * @return LanguageService
     */
    public function getLanguageService(): LanguageService
    {
        return $GLOBALS['LANG'];
    }
}