-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScheduleForm.php
More file actions
280 lines (229 loc) · 8.64 KB
/
Copy pathScheduleForm.php
File metadata and controls
280 lines (229 loc) · 8.64 KB
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
<?php
// SPDX-FileCopyrightText: 2023 Icinga GmbH <https://icinga.com>
// SPDX-License-Identifier: GPL-3.0-or-later
namespace Icinga\Module\Notifications\Forms;
use DateTime;
use DateTimeZone;
use Icinga\Exception\Http\HttpNotFoundException;
use Icinga\Module\Notifications\Model\Rotation;
use Icinga\Module\Notifications\Model\RuleEscalationRecipient;
use Icinga\Module\Notifications\Model\Schedule;
use Icinga\Web\Session;
use IntlTimeZone;
use ipl\Html\Attributes;
use ipl\Html\HtmlDocument;
use ipl\Html\HtmlElement;
use ipl\Html\Text;
use ipl\Sql\Connection;
use ipl\Stdlib\Filter;
use ipl\Validator\CallbackValidator;
use ipl\Web\Common\CsrfCounterMeasure;
use ipl\Web\Compat\CompatForm;
use ipl\Web\Url;
use Throwable;
class ScheduleForm extends CompatForm
{
use CsrfCounterMeasure;
/** @var ?string */
protected ?string $submitLabel;
/** @var bool */
protected bool $showRemoveButton = false;
/** @var bool */
protected bool $showTimezoneSuggestionInput = false;
/** @var Connection */
private Connection $db;
/** @var ?int */
private ?int $scheduleId = null;
public function __construct(Connection $db)
{
$this->db = $db;
$this->applyDefaultElementDecorators();
}
public function setSubmitLabel(string $label): self
{
$this->submitLabel = $label;
return $this;
}
public function getSubmitLabel(): string
{
return $this->submitLabel ?? $this->translate('Create Schedule');
}
public function setShowRemoveButton(bool $state = true): self
{
$this->showRemoveButton = $state;
return $this;
}
/**
* Set whether to show the timezone dropdown or not
*
* @param bool $state If true, the timezone dropdown will be shown (defaults to true)
*
* @return $this
*/
public function setShowTimezoneSuggestionInput(bool $state = true): self
{
$this->showTimezoneSuggestionInput = $state;
return $this;
}
public function hasBeenRemoved(): bool
{
$btn = $this->getPressedSubmitElement();
$csrf = $this->getElement('CSRFToken');
return $csrf !== null && $csrf->isValid() && $btn !== null && $btn->getName() === 'delete';
}
public function loadSchedule(int $id): void
{
$this->scheduleId = $id;
$this->populate($this->fetchDbValues());
}
public function addSchedule(): int
{
return $this->db->transaction(function (Connection $db) {
$db->insert('schedule', [
'name' => $this->getValue('name'),
'changed_at' => (int) (new DateTime())->format("Uv"),
'timezone' => $this->getValue('timezone')
]);
return $db->lastInsertId();
});
}
public function editSchedule(int $id): void
{
$this->db->beginTransaction();
$values = $this->getValues();
$storedValues = $this->fetchDbValues();
if ($values === $storedValues) {
return;
}
$this->db->update('schedule', [
'name' => $values['name'],
'changed_at' => (int) (new DateTime())->format("Uv")
], ['id = ?' => $id]);
$this->db->commitTransaction();
}
public function removeSchedule(int $id): void
{
$this->db->beginTransaction();
$rotations = Rotation::on($this->db)
->columns(['id', 'schedule_id', 'priority', 'timeperiod.id'])
->filter(Filter::equal('schedule_id', $id))
->orderBy('priority', SORT_DESC);
/** @var Rotation $rotation */
foreach ($rotations as $rotation) {
$rotation->delete();
}
$markAsDeleted = ['changed_at' => (int) (new DateTime())->format("Uv"), 'deleted' => 'y'];
$escalationIds = $this->db->fetchCol(
RuleEscalationRecipient::on($this->db)
->columns('rule_escalation_id')
->filter(Filter::equal('schedule_id', $id))
->assembleSelect()
);
$this->db->update('rule_escalation_recipient', $markAsDeleted, ['schedule_id = ?' => $id]);
if (! empty($escalationIds)) {
$escalationIdsWithOtherRecipients = $this->db->fetchCol(
RuleEscalationRecipient::on($this->db)
->columns('rule_escalation_id')
->filter(Filter::all(
Filter::equal('rule_escalation_id', $escalationIds),
Filter::unequal('schedule_id', $id)
))->assembleSelect()
);
$toRemoveEscalations = array_diff($escalationIds, $escalationIdsWithOtherRecipients);
if (! empty($toRemoveEscalations)) {
$this->db->update(
'rule_escalation',
$markAsDeleted + ['position' => null],
['id IN (?)' => $toRemoveEscalations]
);
}
}
$this->db->update('schedule', $markAsDeleted, ['id = ?' => $id]);
$this->db->commitTransaction();
}
protected function assemble(): void
{
if (! $this->showRemoveButton) {
$this->addHtml(new HtmlElement(
'p',
new Attributes(['class' => 'description']),
new Text($this->translate(
'Organize contacts and contact groups in time-based schedules and let them rotate'
. ' automatically. You can define multiple rotations with different patterns to set'
. ' priorities. Schedules can also be used as recipients for event rules.'
))
));
}
$this->addElement('text', 'name', [
'required' => true,
'label' => $this->translate('Schedule Name'),
'placeholder' => $this->translate('e.g. working hours, on call, etc ...')
]);
if ($this->showTimezoneSuggestionInput) {
$this->addElement(
'suggestion',
'timezone',
[
'suggestionsUrl' => Url::fromPath('notifications/suggest/timezone', [
'showCompact' => true,
'_disableLayout' => 1
]),
'label' => $this->translate('Schedule Timezone'),
'value' => date_default_timezone_get(),
'validators' => [
new CallbackValidator(function ($value, $validator) {
// https://github.com/php/php-src/issues/11874#issuecomment-1666223477
$timezones = IntlTimeZone::createEnumeration() ?: [];
foreach ($timezones as $tz) {
try {
if (
(new DateTime('now', new DateTimeZone($tz)))->getTimezone()->getLocation()
&& $value === $tz
) {
return true;
}
} catch (Throwable) {
continue;
}
}
$validator->addMessage($this->translate('Invalid timezone'));
return false;
})
]
]
);
}
$this->addElement('submit', 'submit', [
'label' => $this->getSubmitLabel()
]);
if ($this->showRemoveButton) {
$removeBtn = $this->createElement('submit', 'delete', [
'label' => $this->translate('Delete'),
'class' => 'btn-remove',
'formnovalidate' => true
]);
$this->registerElement($removeBtn);
$this->getElement('submit')->prependWrapper((new HtmlDocument())->setHtmlContent($removeBtn));
}
$this->addCsrfCounterMeasure(Session::getSession()->getId());
}
/**
* Fetch the values from the database
*
* @return string[]
*
* @throws HttpNotFoundException
*/
private function fetchDbValues(): array
{
/** @var ?Schedule $schedule */
$schedule = Schedule::on($this->db)
->columns('name')
->filter(Filter::equal('id', $this->scheduleId))
->first();
if ($schedule === null) {
throw new HttpNotFoundException($this->translate('Schedule not found'));
}
return ['name' => $schedule->name];
}
}