summaryrefslogtreecommitdiffstats
path: root/application/controllers/ImportsourceController.php
blob: f417bf765639bd2f536d4e705f4dd90db36f7cb6 (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
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
<?php

namespace Icinga\Module\Director\Controllers;

use Exception;
use gipfl\Web\Widget\Hint;
use Icinga\Module\Director\Data\Exporter;
use Icinga\Module\Director\Db\Branch\Branch;
use Icinga\Module\Director\Forms\ImportRowModifierForm;
use Icinga\Module\Director\Forms\ImportSourceForm;
use Icinga\Module\Director\Hook\ImportSourceHook;
use Icinga\Module\Director\Web\ActionBar\AutomationObjectActionBar;
use Icinga\Module\Director\Web\Controller\ActionController;
use Icinga\Module\Director\Objects\ImportSource;
use Icinga\Module\Director\Web\Controller\BranchHelper;
use Icinga\Module\Director\Web\Form\CloneImportSourceForm;
use Icinga\Module\Director\Web\Table\ImportrunTable;
use Icinga\Module\Director\Web\Table\ImportsourceHookTable;
use Icinga\Module\Director\Web\Table\PropertymodifierTable;
use Icinga\Module\Director\Web\Tabs\ImportsourceTabs;
use Icinga\Module\Director\Web\Widget\ImportSourceDetails;
use InvalidArgumentException;
use gipfl\IcingaWeb2\Link;
use ipl\Html\Error;
use ipl\Html\Html;

class ImportsourceController extends ActionController
{
    use BranchHelper;

    /** @var ImportSource|null */
    private $importSource;

    private $id;

    /**
     * @throws \Icinga\Exception\AuthenticationException
     * @throws \Icinga\Exception\NotFoundError
     * @throws \Icinga\Security\SecurityException
     */
    public function init()
    {
        parent::init();
        $id = $this->params->get('source_id', $this->params->get('id'));
        if ($id !== null && is_numeric($id)) {
            $this->id = (int) $id;
        }

        $tabs = $this->tabs(new ImportsourceTabs($this->id));
        $action = $this->getRequest()->getActionName();
        if ($tabs->has($action)) {
            $tabs->activate($action);
        }
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     */
    protected function addMainActions()
    {
        $this->actions(new AutomationObjectActionBar(
            $this->getRequest()
        ));
        $source = $this->getImportSource();

        $this->actions()->add(Link::create(
            $this->translate('Add to Basket'),
            'director/basket/add',
            [
                'type'  => 'ImportSource',
                'names' => $source->getUniqueIdentifier()
            ],
            [
                'class' => 'icon-tag',
                'data-base-target' => '_next'
            ]
        ));
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     */
    public function indexAction()
    {
        $this->addMainActions();
        $source = $this->getImportSource();
        if ($this->params->get('format') === 'json') {
            $this->sendJson($this->getResponse(), (new Exporter($this->db()))->export($source));
            return;
        }
        $this->addTitle(
            $this->translate('Import source: %s'),
            $source->get('source_name')
        )->setAutorefreshInterval(10);
        $branch = $this->getBranch();
        if ($this->getBranch()->isBranch()) {
            $this->content()->add(Hint::info(Html::sprintf($this->translate(
                'Please note that importing data will take place in your main Branch.'
                . ' Modifications to Import Sources are not allowed while being in a Configuration Branch.'
                . ' To get the full functionality, please deactivate %s'
            ), Branch::requireHook()->linkToBranch($branch, $this->getAuth(), $branch->getName()))));
        }
        $this->content()->add(new ImportSourceDetails($source));
    }

    public function addAction()
    {
        $this->addTitle($this->translate('Add import source'));
        if ($this->showNotInBranch($this->translate('Creating Import Sources'))) {
            return;
        }

        $this->content()->add(
            ImportSourceForm::load()->setDb($this->db())
                ->setSuccessUrl('director/importsources')
                ->handleRequest()
        );
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     */
    public function editAction()
    {
        $this->addMainActions();
        $this->activateTabWithPostfix($this->translate('Modify'));
        if ($this->showNotInBranch($this->translate('Modifying Import Sources'))) {
            return;
        }
        $form = ImportSourceForm::load()
            ->setObject($this->getImportSource())
            ->setListUrl('director/importsources')
            ->handleRequest();
        $this->addTitle(
            $this->translate('Import source: %s'),
            $form->getObject()->get('source_name')
        )->setAutorefreshInterval(10);

        $this->content()->add($form);
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     */
    public function cloneAction()
    {
        $this->addMainActions();
        $this->activateTabWithPostfix($this->translate('Clone'));
        if ($this->showNotInBranch($this->translate('Cloning Import Sources'))) {
            return;
        }
        $source = $this->getImportSource();
        $this->addTitle('Clone: %s', $source->get('source_name'));
        $form = new CloneImportSourceForm($source);
        $this->content()->add($form);
        $form->on(CloneImportSourceForm::ON_SUCCESS, function (CloneImportSourceForm $form) {
            $this->getResponse()->redirectAndExit($form->getSuccessUrl());
        });
        $form->handleRequest($this->getServerRequest());
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     */
    public function previewAction()
    {
        $source = $this->getImportSource();

        $this->addTitle(
            $this->translate('Import source preview: %s'),
            $source->get('source_name')
        );
        $fetchUrl = clone($this->url());

        $this->actions()->add(Link::create(
            $this->translate('Download JSON'),
            $fetchUrl->setPath('director/importsource/fetch'),
            null,
            [
                'target' => '_blank',
                'class'  => 'icon-download',
            ]
        ));
        try {
            (new ImportsourceHookTable())->setImportSource($source)->renderTo($this);
        } catch (Exception $e) {
            $this->content()->add(Error::show($e));
        }
    }

    /**
     * @throws \Icinga\Exception\ConfigurationError
     * @throws \Icinga\Exception\NotFoundError
     * @throws \Icinga\Module\Director\Exception\DuplicateKeyException
     */
    public function fetchAction()
    {
        $response = $this->getResponse();
        try {
            $source = $this->getImportSource();
            $source->checkForChanges();
            $hook = ImportSourceHook::forImportSource($source);
            $data = $hook->fetchData();
            $source->applyModifiers($data);

            $filename = sprintf(
                "director-importsource-%d_%s.json",
                $this->getParam('id'),
                date('YmdHis')
            );
            $response->setHeader('Content-Type', 'application/json', true);
            $response->setHeader('Content-disposition', "attachment; filename=$filename", true);
            $response->sendHeaders();
            $this->sendJson($this->getResponse(), $data);
        } catch (Exception $e) {
            $this->sendJsonError($response, $e->getMessage());
        }
        // TODO: this is not clean
        if (\ob_get_level()) {
            \ob_end_flush();
        }
        exit;
    }

    /**
     * @return ImportSource
     * @throws \Icinga\Exception\NotFoundError
     */
    protected function requireImportSourceAndAddModifierTable()
    {
        $source = $this->getImportSource();
        $table = PropertymodifierTable::load($source, $this->url());
        if ($this->getBranch()->isBranch()) {
            $table->setReadOnly();
        } else {
            $table->handleSortPriorityActions($this->getRequest(), $this->getResponse());
        }
        $table->renderTo($this);

        return $source;
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     */
    public function modifierAction()
    {
        $source = $this->requireImportSourceAndAddModifierTable();
        $this->addTitle($this->translate('Property modifiers: %s'), $source->get('source_name'));
        $this->addAddLink(
            $this->translate('Add property modifier'),
            'director/importsource/addmodifier',
            ['source_id' => $source->get('id')],
            '_self'
        );
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     */
    public function historyAction()
    {
        $source = $this->getImportSource();
        $this->addTitle($this->translate('Import run history: %s'), $source->get('source_name'));

        // TODO: temporarily disabled, find a better place for stats:
        // $this->view->stats = $this->db()->fetchImportStatistics();
        ImportrunTable::load($source)->renderTo($this);
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     */
    public function addmodifierAction()
    {
        $source = $this->requireImportSourceAndAddModifierTable();
        $this->addTitle(
            $this->translate('%s: add Property Modifier'),
            $source->get('source_name')
        )->addBackToModifiersLink($source);
        $this->tabs()->activate('modifier');

        if ($this->showNotInBranch($this->translate('Modifying Import Sources'))) {
            return;
        }

        $this->content()->prepend(
            ImportRowModifierForm::load()->setDb($this->db())
                ->setSource($source)
                ->setSuccessUrl(
                    'director/importsource/modifier',
                    ['source_id' => $source->get('id')]
                )->handleRequest()
        );
    }

    /**
     * @throws \Icinga\Exception\MissingParameterException
     * @throws \Icinga\Exception\NotFoundError
     */
    public function editmodifierAction()
    {
        // We need to load the table AFTER adding the title, otherwise search
        // will not be placed next to the title
        $source = $this->getImportSource();

        $this->addTitle(
            $this->translate('%s: Property Modifier'),
            $source->get('source_name')
        )->addBackToModifiersLink($source);
        $source = $this->requireImportSourceAndAddModifierTable();
        $this->tabs()->activate('modifier');
        if ($this->showNotInBranch($this->translate('Modifying Import Sources'))) {
            return;
        }

        $listUrl = 'director/importsource/modifier?source_id='
            . (int) $source->get('id');
        $this->content()->prepend(
            ImportRowModifierForm::load()->setDb($this->db())
                ->loadObject((int) $this->params->getRequired('id'))
                ->setListUrl($listUrl)
                ->setSource($source)
                ->handleRequest()
        );
    }

    /**
     * @return ImportSource
     * @throws \Icinga\Exception\NotFoundError
     */
    protected function getImportSource()
    {
        if ($this->importSource === null) {
            if ($this->id === null) {
                throw new InvalidArgumentException('Got no ImportSource id');
            }
            $this->importSource = ImportSource::loadWithAutoIncId(
                $this->id,
                $this->db()
            );
        }

        return $this->importSource;
    }

    protected function activateTabWithPostfix($title)
    {
        /** @var ImportsourceTabs $tabs */
        $tabs = $this->tabs();
        $tabs->activateMainWithPostfix($title);

        return $this;
    }

    /**
     * @param ImportSource $source
     * @return $this
     */
    protected function addBackToModifiersLink(ImportSource $source)
    {
        $this->actions()->add(
            Link::create(
                $this->translate('back'),
                'director/importsource/modifier',
                ['source_id' => $source->get('id')],
                ['class' => 'icon-left-big']
            )
        );

        return $this;
    }
}