Debian Codegraph @

vendor/ipl/web/src/FormElement/ScheduleElement.php

raw
1 <?php
2
3 namespace ipl\Web\FormElement;
4
5 use DateTime;
6 use InvalidArgumentException;
7 use ipl\Html\Attributes;
8 use ipl\Html\FormElement\FieldsetElement;
9 use ipl\Html\HtmlElement;
10 use ipl\Scheduler\Contract\Frequency;
11 use ipl\Scheduler\Cron;
12 use ipl\Scheduler\OneOff;
13 use ipl\Scheduler\RRule;
14 use ipl\Validator\BetweenValidator;
15 use ipl\Validator\CallbackValidator;
16 use ipl\Web\FormElement\ScheduleElement\AnnuallyFields;
17 use ipl\Web\FormElement\ScheduleElement\Common\FieldsProtector;
18 use ipl\Web\FormElement\ScheduleElement\MonthlyFields;
19 use ipl\Web\FormElement\ScheduleElement\WeeklyFields;
20 use LogicException;
21 use Psr\Http\Message\RequestInterface;
22
23 class ScheduleElement extends FieldsetElement
24 {
25 use FieldsProtector;
26
27 /** @var string Plain cron expressions */
28 protected const CRON_EXPR = 'cron_expr';
29
30 /** @var string Configure the individual expression parts manually */
31 protected const CUSTOM_EXPR = 'custom';
32
33 /** @var string Used to run a one-off task */
34 protected const NO_REPEAT = 'none';
35
36 protected $defaultAttributes = ['class' => 'schedule-element'];
37
38 /** @var array A list of allowed frequencies used to configure custom expressions */
39 protected $customFrequencies = [];
40
41 /** @var array */
42 protected $advanced = [];
43
44 /** @var array */
45 protected $regulars = [];
46
47 /** @var string Schedule frequency of this element */
48 protected $frequency = self::NO_REPEAT;
49
50 /** @var string */
51 protected $customFrequency;
52
53 /** @var DateTime */
54 protected $start;
55
56 /** @var WeeklyFields Weekly parts of this schedule element */
57 protected $weeklyField;
58
59 /** @var MonthlyFields Monthly parts of this schedule element */
60 protected $monthlyFields;
61
62 /** @var AnnuallyFields Annually parts of this schedule element */
63 protected $annuallyFields;
64
65 protected function init(): void
66 {
67 $this->addDefaultPluginLoader('element', 'ipl\\Web\\FormElement\\ScheduleElement', '');
68
69 $this->start = new DateTime();
70
71 $this->regulars = [
72 RRule::MINUTELY => $this->translate('Minutely'),
73 RRule::HOURLY => $this->translate('Hourly'),
74 RRule::DAILY => $this->translate('Daily'),
75 RRule::WEEKLY => $this->translate('Weekly'),
76 RRule::MONTHLY => $this->translate('Monthly'),
77 RRule::QUARTERLY => $this->translate('Quarterly'),
78 RRule::YEARLY => $this->translate('Annually'),
79 ];
80
81 $this->customFrequencies = array_slice($this->regulars, 2);
82 unset($this->customFrequencies[RRule::QUARTERLY]);
83
84 $this->advanced = [
85 static::CUSTOM_EXPR => $this->translate('Custom…'),
86 static::CRON_EXPR => $this->translate('Cron Expression…')
87 ];
88 }
89
90 /**
91 * Create and return the weekly fields element
92 *
93 * @return WeeklyFields
94 */
95 protected function weeklyField(): WeeklyFields
96 {
97 if ($this->weeklyField === null) {
98 $this->weeklyField = $this->createElement('weeklyFields', 'weekly-fields', [
99 'default' => $this->start->format('D'),
100 'protector' => function (string $day) {
101 return $this->protectId($day);
102 },
103 ]);
104 }
105
106 return $this->weeklyField;
107 }
108
109 /**
110 * Create and return the monthly fields element
111 *
112 * @return MonthlyFields
113 */
114 protected function monthlyFields(): MonthlyFields
115 {
116 if ($this->monthlyFields === null) {
117 $this->monthlyFields = $this->createElement('monthlyFields', 'monthly-fields', [
118 'default' => $this->start->format('j'),
119 'availableFields' => (int) $this->start->format('t'),
120 'protector' => function ($day) {
121 return $this->protectId($day);
122 }
123 ]);
124 }
125
126 return $this->monthlyFields;
127 }
128
129 /**
130 * Create and return the annually fields element
131 *
132 * @return AnnuallyFields
133 */
134 protected function annuallyFields(): AnnuallyFields
135 {
136 if ($this->annuallyFields === null) {
137 $this->annuallyFields = $this->createElement('annuallyFields', 'annually-fields', [
138 'default' => $this->start->format('M'),
139 'protector' => function ($month) {
140 return $this->protectId($month);
141 }
142 ]);
143 }
144
145 return $this->annuallyFields;
146 }
147
148 /**
149 * Get whether this element is rendering a cron expression
150 *
151 * @return bool
152 */
153 public function hasCronExpression(): bool
154 {
155 return $this->getFrequency() === static::CRON_EXPR;
156 }
157
158 /**
159 * Get the frequency of this element
160 *
161 * @return string
162 */
163 public function getFrequency(): string
164 {
165 return $this->getPopulatedValue('frequency', $this->frequency);
166 }
167
168 /**
169 * Set the custom frequency of this schedule element
170 *
171 * @param string $frequency
172 *
173 * @return $this
174 */
175 public function setFrequency(string $frequency): self
176 {
177 if (
178 $frequency !== static::NO_REPEAT
179 && ! isset($this->regulars[$frequency])
180 && ! isset($this->advanced[$frequency])
181 ) {
182 throw new InvalidArgumentException(sprintf('Invalid frequency provided: %s', $frequency));
183 }
184
185 $this->frequency = $frequency;
186
187 return $this;
188 }
189
190 /**
191 * Get custom frequency of this element
192 *
193 * @return ?string
194 */
195 public function getCustomFrequency(): ?string
196 {
197 return $this->getValue('custom-frequency', $this->customFrequency);
198 }
199
200 /**
201 * Set custom frequency of this element
202 *
203 * @param string $frequency
204 *
205 * @return $this
206 */
207 public function setCustomFrequency(string $frequency): self
208 {
209 if (! isset($this->customFrequencies[$frequency])) {
210 throw new InvalidArgumentException(sprintf('Invalid custom frequency provided: %s', $frequency));
211 }
212
213 $this->customFrequency = $frequency;
214
215 return $this;
216 }
217
218 /**
219 * Set start time of the parsed expressions
220 *
221 * @param DateTime $start
222 *
223 * @return $this
224 */
225 public function setStart(DateTime $start): self
226 {
227 $this->start = $start;
228
229 // Forward the start time update to the sub elements as well!
230 $this->weeklyField()->setDefault($start->format('D'));
231 $this->annuallyFields()->setDefault($start->format('M'));
232 $this->monthlyFields()
233 ->setDefault((int) $start->format('j'))
234 ->setAvailableFields((int) $start->format('t'));
235
236 return $this;
237 }
238
239 public function getValue($name = null, $default = null)
240 {
241 if ($name !== null || ! $this->hasBeenValidated()) {
242 return parent::getValue($name, $default);
243 }
244
245 $frequency = $this->getFrequency();
246 $start = parent::getValue('start');
247 switch ($frequency) {
248 case static::NO_REPEAT:
249 return new OneOff($start);
250 case static::CRON_EXPR:
251 $rule = new Cron(parent::getValue('cron_expression'));
252
253 break;
254 case RRule::MINUTELY:
255 case RRule::HOURLY:
256 case RRule::DAILY:
257 case RRule::WEEKLY:
258 case RRule::MONTHLY:
259 case RRule::QUARTERLY:
260 case RRule::YEARLY:
261 $rule = RRule::fromFrequency($frequency);
262
263 break;
264 default: // static::CUSTOM_EXPR
265 $interval = parent::getValue('interval', 1);
266 $customFrequency = parent::getValue('custom-frequency', RRule::DAILY);
267 switch ($customFrequency) {
268 case RRule::DAILY:
269 if ($interval === '*') {
270 $interval = 1;
271 }
272
273 $rule = new RRule("FREQ=DAILY;INTERVAL=$interval");
274
275 break;
276 case RRule::WEEKLY:
277 $byDay = implode(',', $this->weeklyField()->getSelectedWeekDays());
278
279 $rule = new RRule("FREQ=WEEKLY;INTERVAL=$interval;BYDAY=$byDay");
280
281 break;
282 /** @noinspection PhpMissingBreakStatementInspection */
283 case RRule::MONTHLY:
284 $runsOn = $this->monthlyFields()->getValue('runsOn', MonthlyFields::RUNS_EACH);
285 if ($runsOn === MonthlyFields::RUNS_EACH) {
286 $byMonth = implode(',', $this->monthlyFields()->getSelectedDays());
287
288 $rule = new RRule("FREQ=MONTHLY;INTERVAL=$interval;BYMONTHDAY=$byMonth");
289
290 break;
291 }
292 // Fall-through to the next switch case
293 case RRule::YEARLY:
294 $rule = "FREQ=MONTHLY;INTERVAL=$interval;";
295 if ($customFrequency === RRule::YEARLY) {
296 $runsOn = $this->annuallyFields()->getValue('runsOnThe', 'n');
297 $month = $this->annuallyFields()->getValue('month', (int) $this->start->format('m'));
298 if (is_string($month)) {
299 $datetime = DateTime::createFromFormat('!M', $month);
300 if (! $datetime) {
301 throw new InvalidArgumentException(sprintf('Invalid month provided: %s', $month));
302 }
303
304 $month = (int) $datetime->format('m');
305 }
306
307 $rule = "FREQ=YEARLY;INTERVAL=1;BYMONTH=$month;";
308 if ($runsOn === 'n') {
309 $rule = new RRule($rule);
310
311 break;
312 }
313 }
314
315 $element = $this->monthlyFields();
316 if ($customFrequency === RRule::YEARLY) {
317 $element = $this->annuallyFields();
318 }
319
320 $runDay = $element->getValue('day', $element::$everyDay);
321 $ordinal = $element->getValue('ordinal', $element::$first);
322 $position = $element->getOrdinalAsInteger($ordinal);
323
324 if ($runDay === $element::$everyDay) {
325 $rule .= "BYDAY=MO,TU,WE,TH,FR,SA,SU;BYSETPOS=$position";
326 } elseif ($runDay === $element::$everyWeekday) {
327 $rule .= "BYDAY=MO,TU,WE,TH,FR;BYSETPOS=$position";
328 } elseif ($runDay === $element::$everyWeekend) {
329 $rule .= "BYDAY=SA,SU;BYSETPOS=$position";
330 } else {
331 $rule .= sprintf('BYDAY=%d%s', $position, $runDay);
332 }
333
334 $rule = new RRule($rule);
335
336 break;
337 default:
338 throw new LogicException(sprintf('Custom frequency %s is not supported!', $customFrequency));
339 }
340 }
341
342 $rule->startAt($start);
343 if (parent::getValue('use-end-time', 'n') === 'y') {
344 $rule->endAt(parent::getValue('end'));
345 }
346
347 // Sync the start time and first recurrence of the rule
348 if (! $this->hasCronExpression() && $this->getFrequency() !== static::NO_REPEAT) {
349 $nextDue = $rule->getNextRecurrences($start)->current() ?? $start;
350 $rule->startAt($nextDue);
351 }
352
353 return $rule;
354 }
355
356 public function setValue($value)
357 {
358 $values = $value;
359 $rule = $value;
360 if ($rule instanceof Frequency) {
361 if ($rule->getStart()) {
362 $this->setStart($rule->getStart());
363 }
364
365 $values = [];
366 if ($rule->getEnd() && ! $rule instanceof OneOff) {
367 $values['use-end-time'] = 'y';
368 $values['end'] = $rule->getEnd();
369 }
370
371 if ($rule instanceof OneOff) {
372 $values['frequency'] = static::NO_REPEAT;
373 } elseif ($rule instanceof Cron) {
374 $values['cron_expression'] = $rule->getExpression();
375 $values['frequency'] = static::CRON_EXPR;
376
377 $this->setFrequency(static::CRON_EXPR);
378 } elseif ($rule instanceof RRule) {
379 $values['interval'] = $rule->getInterval();
380 switch ($rule->getFrequency()) {
381 case RRule::DAILY:
382 if ($rule->getInterval() <= 1 && strpos($rule->getString(), 'INTERVAL=') === false) {
383 $this->setFrequency(RRule::DAILY);
384 } else {
385 $this
386 ->setFrequency(static::CUSTOM_EXPR)
387 ->setCustomFrequency(RRule::DAILY);
388 }
389
390 break;
391 case RRule::WEEKLY:
392 if (! $rule->getByDay() || empty($rule->getByDay())) {
393 $this->setFrequency(RRule::WEEKLY);
394 } else {
395 $values['weekly-fields'] = $this->weeklyField()->loadWeekDays($rule->getByDay());
396 $this
397 ->setFrequency(static::CUSTOM_EXPR)
398 ->setCustomFrequency(RRule::WEEKLY);
399 }
400
401 break;
402 case RRule::MONTHLY:
403 case RRule::YEARLY:
404 $isMonthly = $rule->getFrequency() === RRule::MONTHLY;
405 if ($rule->getByDay() || $rule->getByMonthDay() || $rule->getByMonth()) {
406 $this->setFrequency(static::CUSTOM_EXPR);
407
408 if ($isMonthly) {
409 $values['monthly-fields'] = $this->monthlyFields()->loadRRule($rule);
410 $this->setCustomFrequency(RRule::MONTHLY);
411 } else {
412 $values['annually-fields'] = $this->annuallyFields()->loadRRule($rule);
413 $this->setCustomFrequency(RRule::YEARLY);
414 }
415 } elseif ($isMonthly && $rule->getInterval() === 3) {
416 $this->setFrequency(RRule::QUARTERLY);
417 } else {
418 $this->setFrequency($rule->getFrequency());
419 }
420
421 break;
422 default:
423 $this->setFrequency($rule->getFrequency());
424 }
425
426 $values['frequency'] = $this->getFrequency();
427 $values['custom-frequency'] = $this->getCustomFrequency();
428 }
429 }
430
431 return parent::setValue($values);
432 }
433
434 protected function assemble()
435 {
436 $start = $this->getPopulatedValue('start') ?: $this->start;
437 if (! $start instanceof DateTime) {
438 $start = new DateTime($start);
439 }
440 $this->setStart($start);
441
442 $autosubmit = ! $this->hasCronExpression() && $this->getFrequency() !== static::NO_REPEAT;
443 $this->addElement('localDateTime', 'start', [
444 'class' => $autosubmit ? 'autosubmit' : null,
445 'required' => true,
446 'label' => $this->translate('Start'),
447 'value' => $start,
448 'description' => $this->translate('Start time of this schedule')
449 ]);
450
451 $this->addElement('checkbox', 'use-end-time', [
452 'required' => false,
453 'class' => 'autosubmit',
454 'disabled' => $this->getPopulatedValue('frequency', static::NO_REPEAT) === static::NO_REPEAT ?: null,
455 'value' => $this->getPopulatedValue('use-end-time', 'n'),
456 'label' => $this->translate('Use End Time')
457 ]);
458
459 if ($this->getPopulatedValue('use-end-time', 'n') === 'y') {
460 $end = $this->getPopulatedValue('end', new DateTime());
461 if (! $end instanceof DateTime) {
462 $end = new DateTime($end);
463 }
464
465 $this->addElement('localDateTime', 'end', [
466 'class' => ! $this->hasCronExpression() ? 'autosubmit' : null,
467 'required' => true,
468 'value' => $end,
469 'label' => $this->translate('End'),
470 'description' => $this->translate('End time of this schedule')
471 ]);
472 }
473
474 $this->addElement('select', 'frequency', [
475 'required' => false,
476 'class' => 'autosubmit',
477 'label' => $this->translate('Frequency'),
478 'description' => $this->translate('Specifies how often this job run should be recurring'),
479 'options' => [
480 static::NO_REPEAT => $this->translate('None'),
481 $this->translate('Regular') => $this->regulars,
482 $this->translate('Advanced') => $this->advanced
483 ],
484 ]);
485
486 if ($this->getFrequency() === static::CUSTOM_EXPR) {
487 $this->addElement('select', 'custom-frequency', [
488 'required' => false,
489 'class' => 'autosubmit',
490 'value' => parent::getValue('custom-frequency'),
491 'options' => $this->customFrequencies,
492 'label' => $this->translate('Custom Frequency'),
493 'description' => $this->translate('Specifies how often this job run should be recurring')
494 ]);
495
496 switch (parent::getValue('custom-frequency', RRule::DAILY)) {
497 case RRule::DAILY:
498 $this->assembleCommonElements();
499
500 break;
501 case RRule::WEEKLY:
502 $this->assembleCommonElements();
503 $this->addElement($this->weeklyField());
504
505 break;
506 case RRule::MONTHLY:
507 $this->assembleCommonElements();
508 $this->addElement($this->monthlyFields());
509
510 break;
511 case RRule::YEARLY:
512 $this->addElement($this->annuallyFields());
513 }
514 } elseif ($this->hasCronExpression()) {
515 $this->addElement('text', 'cron_expression', [
516 'required' => true,
517 'label' => $this->translate('Cron Expression'),
518 'description' => $this->translate('Job cron Schedule'),
519 'validators' => [
520 new CallbackValidator(function ($value, CallbackValidator $validator) {
521 if ($value && ! Cron::isValid($value)) {
522 $validator->addMessage($this->translate('Invalid CRON expression'));
523
524 return false;
525 }
526
527 return true;
528 })
529 ]
530 ]);
531 }
532
533 if ($this->getFrequency() !== static::NO_REPEAT && ! $this->hasCronExpression()) {
534 $this->addElement(
535 'recurrence',
536 'schedule-recurrences',
537 [
538 'id' => $this->protectId('schedule-recurrences'),
539 'label' => $this->translate('Next occurrences'),
540 'validate' => function (): array {
541 $isValid = $this->isValid();
542 $reason = null;
543 if (! $isValid && $this->getFrequency() === static::CUSTOM_EXPR) {
544 if (
545 $this->getCustomFrequency() !== RRule::YEARLY
546 && ! $this->getElement('interval')->isValid()
547 ) {
548 $reason = current($this->getElement('interval')->getMessages());
549 } else {
550 $frequency = $this->getCustomFrequency();
551 switch ($frequency) {
552 case RRule::WEEKLY:
553 $reason = current($this->weeklyField()->getMessages());
554
555 break;
556 case RRule::MONTHLY:
557 $reason = current($this->monthlyFields()->getMessages());
558
559 break;
560 default: // annually
561 $reason = current($this->annuallyFields()->getMessages());
562
563 break;
564 }
565 }
566 }
567
568 return [$isValid, $reason];
569 },
570 'frequency' => function (): Frequency {
571 if ($this->getFrequency() === static::CUSTOM_EXPR) {
572 $rule = $this->getValue();
573 } else {
574 $rule = RRule::fromFrequency($this->getFrequency());
575 }
576
577 $now = new DateTime();
578 $start = $this->getValue('start');
579 if ($start < $now) {
580 $now->setTime($start->format('H'), $start->format('i'), $start->format('s'));
581 $start = $now;
582 }
583
584 $rule->startAt($start);
585 if ($this->getPopulatedValue('use-end-time') === 'y') {
586 $rule->endAt($this->getValue('end'));
587 }
588
589 return $rule;
590 }
591 ]
592 );
593 }
594 }
595
596 /**
597 * Assemble common parts for all the frequencies
598 */
599 private function assembleCommonElements(): void
600 {
601 $repeat = $this->getCustomFrequency();
602 if ($repeat === RRule::WEEKLY) {
603 $text = $this->translate('week(s) on');
604 $max = 53;
605 } elseif ($repeat === RRule::MONTHLY) {
606 $text = $this->translate('month(s)');
607 $max = 12;
608 } else {
609 $text = $this->translate('day(s)');
610 $max = 31;
611 }
612
613 $options = ['min' => 1, 'max' => $max];
614 $this->addElement('number', 'interval', [
615 'class' => 'autosubmit',
616 'value' => 1,
617 'min' => 1,
618 'max' => $max,
619 'validators' => [new BetweenValidator($options)]
620 ]);
621
622 $numberSpecifier = HtmlElement::create('div', ['class' => 'number-specifier']);
623 $element = $this->getElement('interval');
624 $element->prependWrapper($numberSpecifier);
625
626 $numberSpecifier->prependHtml(HtmlElement::create('span', null, $this->translate('Every')));
627 $numberSpecifier->addHtml($element);
628 $numberSpecifier->addHtml(HtmlElement::create('span', null, $text));
629 }
630
631 /**
632 * Get prepared multipart updates
633 *
634 * @param RequestInterface $request
635 *
636 * @return array
637 */
638 public function prepareMultipartUpdate(RequestInterface $request): array
639 {
640 $autoSubmittedBy = $request->getHeader('X-Icinga-AutoSubmittedBy');
641 $pattern = '/\[(weekly-fields|monthly-fields|annually-fields)]\[(ordinal|month|day(\d+)?|[A-Z]{2})]$/';
642
643 $partUpdates = [];
644 if (
645 $autoSubmittedBy
646 && (
647 preg_match('/\[(start|end)]$/', $autoSubmittedBy[0], $matches)
648 || preg_match($pattern, $autoSubmittedBy[0])
649 || preg_match('/\[interval]/', $autoSubmittedBy[0])
650 )
651 ) {
652 $this->ensureAssembled();
653
654 $partUpdates[] = $this->getElement('schedule-recurrences');
655 if (
656 $this->getFrequency() === static::CUSTOM_EXPR
657 && $this->getCustomFrequency() === RRule::MONTHLY
658 && isset($matches[1])
659 && $matches[1] === 'start'
660 ) {
661 // To update the available fields/days based on the provided start time
662 $partUpdates[] = $this->monthlyFields();
663 }
664 }
665
666 return $partUpdates;
667 }
668
669 protected function registerAttributeCallbacks(Attributes $attributes)
670 {
671 parent::registerAttributeCallbacks($attributes);
672
673 $attributes->registerAttributeCallback('protector', null, [$this, 'setIdProtector']);
674 }
675 }