summaryrefslogtreecommitdiffstats
path: root/library/Icingadb/Common/CommandActions.php
blob: af7d194283657f1277e96d76dc511f5f5fdd6634 (plain)
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
<?php

/* Icinga DB Web | (c) 2020 Icinga GmbH | GPLv2 */

namespace Icinga\Module\Icingadb\Common;

use Icinga\Exception\Http\HttpNotFoundException;
use Icinga\Module\Icingadb\Forms\Command\CommandForm;
use Icinga\Module\Icingadb\Forms\Command\Object\AcknowledgeProblemForm;
use Icinga\Module\Icingadb\Forms\Command\Object\AddCommentForm;
use Icinga\Module\Icingadb\Forms\Command\Object\CheckNowForm;
use Icinga\Module\Icingadb\Forms\Command\Object\ProcessCheckResultForm;
use Icinga\Module\Icingadb\Forms\Command\Object\RemoveAcknowledgementForm;
use Icinga\Module\Icingadb\Forms\Command\Object\ScheduleCheckForm;
use Icinga\Module\Icingadb\Forms\Command\Object\ScheduleHostDowntimeForm;
use Icinga\Module\Icingadb\Forms\Command\Object\ScheduleServiceDowntimeForm;
use Icinga\Module\Icingadb\Forms\Command\Object\SendCustomNotificationForm;
use Icinga\Module\Icingadb\Forms\Command\Object\ToggleObjectFeaturesForm;
use Icinga\Security\SecurityException;
use Icinga\Web\Notification;
use ipl\Orm\Model;
use ipl\Orm\Query;
use ipl\Web\Url;

/**
 * Trait CommandActions
 */
trait CommandActions
{
    /** @var null|Query|array<Model> $commandTargets */
    protected $commandTargets;

    /** @var Model $commandTargetModel */
    protected $commandTargetModel;

    /**
     * Get url to view command targets, used as redirection target
     *
     * @return Url
     */
    abstract protected function getCommandTargetsUrl(): Url;

    /**
     * Get status of toggleable features
     *
     * @return object
     */
    protected function getFeatureStatus()
    {
    }

    /**
     * Fetch command targets
     *
     * @return Query|array<Model>
     */
    abstract protected function fetchCommandTargets();

    /**
     * Get command targets
     *
     * @return Query|array<Model>
     */
    protected function getCommandTargets()
    {
        if (! isset($this->commandTargets)) {
            $this->commandTargets = $this->fetchCommandTargets();
        }

        return $this->commandTargets;
    }

    /**
     * Get the model of the command targets
     *
     * @return Model
     * @throws HttpNotFoundException If no command targets were found
     */
    protected function getCommandTargetModel(): Model
    {
        if (! isset($this->commandTargetModel)) {
            $commandTargets = $this->getCommandTargets();
            if (empty($commandTargets) || count($commandTargets) === 0) {
                throw new HttpNotFoundException('No command targets found');
            }

            if (is_array($commandTargets)) {
                $this->commandTargetModel = $commandTargets[0];
            } elseif ($commandTargets->count() > 0) {
                $this->commandTargetModel = $commandTargets->getModel();
            }
        }

        return $this->commandTargetModel;
    }

    /**
     * Check whether the permission is granted on any of the command targets
     *
     * @param string $permission
     *
     * @return bool
     */
    protected function isGrantedOnCommandTargets(string $permission): bool
    {
        $commandTargets = $this->getCommandTargets();
        if (is_array($commandTargets)) {
            foreach ($commandTargets as $commandTarget) {
                if ($this->isGrantedOn($permission, $commandTarget)) {
                    return true;
                }
            }

            return false;
        }

        return $this->isGrantedOnType(
            $permission,
            $this->getCommandTargetModel()->getTableName(),
            $commandTargets->getFilter()
        );
    }

    /**
     * Assert that the permission is granted on any of the command targets
     *
     * @param string $permission
     *
     * @throws SecurityException
     */
    protected function assertIsGrantedOnCommandTargets(string $permission)
    {
        if (! $this->isGrantedOnCommandTargets($permission)) {
            throw new SecurityException('No permission for %s', $permission);
        }
    }

    /**
     * Handle and register the given command form
     *
     * @param string|CommandForm $form
     *
     * @return void
     */
    protected function handleCommandForm($form)
    {
        $isXhr = $this->getRequest()->isXmlHttpRequest();
        $isApi = $this->getRequest()->isApiRequest();
        if ($isXhr && $isApi) {
            // Prevents the framework already, this is just a fail-safe
            $this->httpBadRequest('Responding with JSON during a Web request is not supported');
        }

        if (is_string($form)) {
            /** @var CommandForm $form */
            $form = new $form();
        }

        $form->setObjects($this->getCommandTargets());

        if (! $isApi || $isXhr) {
            $this->handleWebRequest($form);
        } else {
            $this->handleApiRequest($form);
        }
    }

    /**
     * Handle a Web request for the given form
     *
     * @param CommandForm $form
     *
     * @return void
     */
    protected function handleWebRequest(CommandForm $form): void
    {
        $actionUrl = $this->getRequest()->getUrl();
        if ($this->view->compact) {
            $actionUrl = clone $actionUrl;
            // TODO: This solves https://github.com/Icinga/icingadb-web/issues/124 but I'd like to omit this
            // entirely. I think it should be solved like https://github.com/Icinga/icingaweb2/pull/4300 so
            // that a request's url object still has params like showCompact and _dev
            $actionUrl->getParams()->add('showCompact', true);
        }

        $form->setAction($actionUrl->getAbsoluteUrl());
        $form->on($form::ON_SUCCESS, function () {
            // This forces the column to reload nearly instantly after the redirect
            // and ensures the effect of the command is visible to the user asap
            $this->getResponse()->setAutoRefreshInterval(1);

            $this->redirectNow($this->getCommandTargetsUrl());
        });

        $form->handleRequest($this->getServerRequest());

        $this->addContent($form);
    }

    /**
     * Handle an API request for the given form
     *
     * @param CommandForm $form
     *
     * @return never
     */
    protected function handleApiRequest(CommandForm $form)
    {
        $form->setIsApiTarget();
        $form->on($form::ON_SUCCESS, function () {
            $this->getResponse()
                ->json()
                ->setSuccessData(Notification::getInstance()->popMessages())
                ->sendResponse();
        });

        $form->handleRequest($this->getServerRequest());

        $errors = [];
        foreach ($form->getElements() as $element) {
            $errors[$element->getName()] = $element->getMessages();
        }

        $response = $this->getResponse()->json();
        $response->setHttpResponseCode(422);
        $response->setFailData($errors)
            ->sendResponse();
    }

    public function acknowledgeAction()
    {
        $this->assertIsGrantedOnCommandTargets('icingadb/command/acknowledge-problem');
        $this->setTitle(t('Acknowledge Problem'));
        $this->handleCommandForm(AcknowledgeProblemForm::class);
    }

    public function addCommentAction()
    {
        $this->assertIsGrantedOnCommandTargets('icingadb/command/comment/add');
        $this->setTitle(t('Add Comment'));
        $this->handleCommandForm(AddCommentForm::class);
    }

    public function checkNowAction()
    {
        if (! $this->isGrantedOnCommandTargets('icingadb/command/schedule-check/active-only')) {
            $this->assertIsGrantedOnCommandTargets('icingadb/command/schedule-check');
        }

        $this->handleCommandForm(CheckNowForm::class);
    }

    public function processCheckresultAction()
    {
        $this->assertIsGrantedOnCommandTargets('icingadb/command/process-check-result');
        $this->setTitle(t('Submit Passive Check Result'));
        $this->handleCommandForm(ProcessCheckResultForm::class);
    }

    public function removeAcknowledgementAction()
    {
        $this->assertIsGrantedOnCommandTargets('icingadb/command/remove-acknowledgement');
        $this->handleCommandForm(RemoveAcknowledgementForm::class);
    }

    public function scheduleCheckAction()
    {
        if (! $this->isGrantedOnCommandTargets('icingadb/command/schedule-check/active-only')) {
            $this->assertIsGrantedOnCommandTargets('icingadb/command/schedule-check');
        }

        $this->setTitle(t('Reschedule Check'));
        $this->handleCommandForm(ScheduleCheckForm::class);
    }

    public function scheduleDowntimeAction()
    {
        $this->assertIsGrantedOnCommandTargets('icingadb/command/downtime/schedule');

        switch ($this->getCommandTargetModel()->getTableName()) {
            case 'host':
                $this->setTitle(t('Schedule Host Downtime'));
                $this->handleCommandForm(ScheduleHostDowntimeForm::class);
                break;
            case 'service':
                $this->setTitle(t('Schedule Service Downtime'));
                $this->handleCommandForm(ScheduleServiceDowntimeForm::class);
                break;
        }
    }

    public function sendCustomNotificationAction()
    {
        $this->assertIsGrantedOnCommandTargets('icingadb/command/send-custom-notification');
        $this->setTitle(t('Send Custom Notification'));
        $this->handleCommandForm(SendCustomNotificationForm::class);
    }

    public function toggleFeaturesAction()
    {
        $commandObjects = $this->getCommandTargets();
        $form = null;
        if (count($commandObjects) > 1) {
            $this->isGrantedOnCommandTargets('i/am-only-used/to-establish/the-object-auth-cache');
            $form = new ToggleObjectFeaturesForm($this->getFeatureStatus());
        } else {
            foreach ($commandObjects as $object) {
                // There's only a single result, a foreach is the most compatible way to retrieve the object
                $form = new ToggleObjectFeaturesForm($object);
            }
        }

        $this->handleCommandForm($form);
    }
}