summaryrefslogtreecommitdiffstats
path: root/application/controllers/NavigationController.php
blob: b0babc3c33d6eaff5aeaaf2aa095e0049950c470 (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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
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
446
447
<?php
/* Icinga Web 2 | (c) 2015 Icinga Development Team | GPLv2+ */

namespace Icinga\Controllers;

use Exception;
use Icinga\Application\Config;
use Icinga\Exception\NotFoundError;
use Icinga\Data\DataArray\ArrayDatasource;
use Icinga\Data\Filter\FilterMatchCaseInsensitive;
use Icinga\Forms\ConfirmRemovalForm;
use Icinga\Forms\Navigation\NavigationConfigForm;
use Icinga\Web\Controller;
use Icinga\Web\Form;
use Icinga\Web\Menu;
use Icinga\Web\Navigation\Navigation;
use Icinga\Web\Notification;
use Icinga\Web\Url;

/**
 * Navigation configuration
 */
class NavigationController extends Controller
{
    /**
     * The global navigation item type configuration
     *
     * @var array
     */
    protected $itemTypeConfig;

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();
        $this->itemTypeConfig = Navigation::getItemTypeConfiguration();
    }

    /**
     * Return the label for the given navigation item type
     *
     * @param   string  $type
     *
     * @return  string          $type if no label can be found
     */
    protected function getItemLabel($type)
    {
        return isset($this->itemTypeConfig[$type]['label']) ? $this->itemTypeConfig[$type]['label'] : $type;
    }

    /**
     * Return a list of available navigation item types
     *
     * @return  array
     */
    protected function listItemTypes()
    {
        $types = array();
        foreach ($this->itemTypeConfig as $type => $options) {
            $types[$type] = isset($options['label']) ? $options['label'] : $type;
        }

        return $types;
    }

    /**
     * Return all shared navigation item configurations
     *
     * @param   string  $owner  A username if only items shared by a specific user are desired
     *
     * @return  array
     */
    protected function fetchSharedNavigationItemConfigs($owner = null)
    {
        $configs = array();
        foreach ($this->itemTypeConfig as $type => $_) {
            $config = Config::navigation($type);
            $config->getConfigObject()->setKeyColumn('name');
            $query = $config->select();
            if ($owner !== null) {
                $query->applyFilter(new FilterMatchCaseInsensitive('owner', '=', $owner));
            }

            foreach ($query as $itemConfig) {
                $configs[] = $itemConfig;
            }
        }

        return $configs;
    }

    /**
     * Return all user navigation item configurations
     *
     * @param   string  $username
     *
     * @return  array
     */
    protected function fetchUserNavigationItemConfigs($username)
    {
        $configs = array();
        foreach ($this->itemTypeConfig as $type => $_) {
            $config = Config::navigation($type, $username);
            $config->getConfigObject()->setKeyColumn('name');
            foreach ($config->select() as $itemConfig) {
                $configs[] = $itemConfig;
            }
        }

        return $configs;
    }

    /**
     * Show the current user a list of his/her navigation items
     */
    public function indexAction()
    {
        $user = $this->Auth()->getUser();
        $ds = new ArrayDatasource(array_merge(
            $this->fetchSharedNavigationItemConfigs($user->getUsername()),
            $this->fetchUserNavigationItemConfigs($user->getUsername())
        ));
        $query = $ds->select();

        $this->view->types = $this->listItemTypes();
        $this->view->items = $query;

        $this->view->title = $this->translate('Navigation');
        $this->getTabs()
        ->add(
            'account',
            array(
                'title' => $this->translate('Update your account'),
                'label' => $this->translate('My Account'),
                'url'   => 'account'
            )
        )
        ->add(
            'navigation',
            array(
                'active'    => true,
                'title'     => $this->translate('List and configure your own navigation items'),
                'label'     => $this->translate('Navigation'),
                'url'       => 'navigation'
            )
        )
        ->add(
            'devices',
            array(
                'title' => $this->translate('List of devices you are logged in'),
                'label' => $this->translate('My Devices'),
                'url'   => 'my-devices'
            )
        );
        $this->setupSortControl(
            array(
                'type'  => $this->translate('Type'),
                'owner' => $this->translate('Shared'),
                'name'  => $this->translate('Navigation')
            ),
            $query
        );
    }

    /**
     * List all shared navigation items
     */
    public function sharedAction()
    {
        $this->assertPermission('config/navigation');
        $ds = new ArrayDatasource($this->fetchSharedNavigationItemConfigs());
        $query = $ds->select();

        $removeForm = new Form();
        $removeForm->setUidDisabled();
        $removeForm->setAttrib('class', 'inline');
        $removeForm->addElement('hidden', 'name', array(
            'decorators'    => array('ViewHelper')
        ));
        $removeForm->addElement('hidden', 'redirect', array(
            'value'         => Url::fromPath('navigation/shared'),
            'decorators'    => array('ViewHelper')
        ));
        $removeForm->addElement('button', 'btn_submit', array(
            'escape'        => false,
            'type'          => 'submit',
            'class'         => 'link-button spinner',
            'value'         => 'btn_submit',
            'decorators'    => array('ViewHelper'),
            'label'         => $this->view->icon('trash'),
            'title'         => $this->translate('Unshare this navigation item')
        ));

        $this->view->removeForm = $removeForm;
        $this->view->types = $this->listItemTypes();
        $this->view->items = $query;

        $this->view->title = $this->translate('Shared Navigation');
        $this->getTabs()->add(
            'navigation/shared',
            array(
                'title'     => $this->translate('List and configure shared navigation items'),
                'label'     => $this->translate('Shared Navigation'),
                'url'       => 'navigation/shared'
            )
        )->activate('navigation/shared');
        $this->setupSortControl(
            array(
                'type'  => $this->translate('Type'),
                'owner' => $this->translate('Owner'),
                'name'  => $this->translate('Shared Navigation')
            ),
            $query
        );
    }

    /**
     * Add a navigation item
     */
    public function addAction()
    {
        $form = new NavigationConfigForm();
        $form->setRedirectUrl('navigation');
        $form->setUser($this->Auth()->getUser());
        $form->setItemTypes($this->listItemTypes());
        $form->addDescription($this->translate('Create a new navigation item, such as a menu entry or dashlet.'));

        // TODO: Fetch all "safe" parameters from the url and populate them
        $form->setDefaultUrl(rawurldecode($this->params->get('url', '')));

        $form->setOnSuccess(function (NavigationConfigForm $form) {
            $data = $form::transformEmptyValuesToNull($form->getValues());

            try {
                $form->add($data);
            } catch (Exception $e) {
                $form->error($e->getMessage());
                return false;
            }

            if ($form->save()) {
                if ($data['type'] === 'menu-item') {
                    $form->getResponse()->setRerenderLayout();
                }

                Notification::success(t('Navigation item successfully created'));
                return true;
            }

            return false;
        });
        $form->handleRequest();

        $this->view->title = $this->translate('Navigation');
        $this->renderForm($form, $this->translate('New Navigation Item'));
    }

    /**
     * Edit a navigation item
     */
    public function editAction()
    {
        $itemName = $this->params->getRequired('name');
        $itemType = $this->params->getRequired('type');
        $referrer = $this->params->get('referrer', 'index');

        $user = $this->Auth()->getUser();
        if ($user->can('config/navigation')) {
            $itemOwner = $this->params->get('owner', $user->getUsername());
        } else {
            $itemOwner = $user->getUsername();
        }

        $form = new NavigationConfigForm();
        $form->setUser($user);
        $form->setShareConfig(Config::navigation($itemType));
        $form->setUserConfig(Config::navigation($itemType, $itemOwner));
        $form->setRedirectUrl($referrer === 'shared' ? 'navigation/shared' : 'navigation');
        $form->setOnSuccess(function (NavigationConfigForm $form) use ($itemName) {
            $data = $form::transformEmptyValuesToNull($form->getValues());

            try {
                $form->edit($itemName, $data);
            } catch (NotFoundError $e) {
                throw $e;
            } catch (Exception $e) {
                $form->error($e->getMessage());
                return false;
            }

            if ($form->save()) {
                if (isset($data['type']) && $data['type'] === 'menu-item') {
                    $form->getResponse()->setRerenderLayout();
                }

                Notification::success(sprintf(t('Navigation item "%s" successfully updated'), $itemName));
                return true;
            }

            return false;
        });

        try {
            $form->load($itemName);
            $form->handleRequest();
        } catch (NotFoundError $_) {
            $this->httpNotFound(sprintf($this->translate('Navigation item "%s" not found'), $itemName));
        }

        $this->view->title = $this->translate('Navigation');
        $this->renderForm($form, $this->translate('Update Navigation Item'));
    }

    /**
     * Remove a navigation item
     */
    public function removeAction()
    {
        $itemName = $this->params->getRequired('name');
        $itemType = $this->params->getRequired('type');
        $user = $this->Auth()->getUser();

        $navigationConfigForm = new NavigationConfigForm();
        $navigationConfigForm->setUser($user);
        $navigationConfigForm->setShareConfig(Config::navigation($itemType));
        $navigationConfigForm->setUserConfig(Config::navigation($itemType, $user->getUsername()));

        $form = new ConfirmRemovalForm();
        $form->setRedirectUrl('navigation');
        $form->setOnSuccess(function (ConfirmRemovalForm $form) use ($itemName, $navigationConfigForm) {
            try {
                $itemConfig = $navigationConfigForm->delete($itemName);
            } catch (NotFoundError $e) {
                Notification::success(sprintf(t('Navigation Item "%s" not found. No action required'), $itemName));
                return true;
            } catch (Exception $e) {
                $form->error($e->getMessage());
                return false;
            }

            if ($navigationConfigForm->save()) {
                if ($itemConfig->type === 'menu-item') {
                    $form->getResponse()->setRerenderLayout();
                }

                Notification::success(sprintf(t('Navigation Item "%s" successfully removed'), $itemName));
                return true;
            }

            return false;
        });
        $form->handleRequest();

        $this->view->title = $this->translate('Navigation');
        $this->renderForm($form, $this->translate('Remove Navigation Item'));
    }

    /**
     * Unshare a navigation item
     */
    public function unshareAction()
    {
        $this->assertPermission('config/navigation');
        $this->assertHttpMethod('POST');

        // TODO: I'd like these being form fields
        $itemType = $this->params->getRequired('type');
        $itemOwner = $this->params->getRequired('owner');

        $navigationConfigForm = new NavigationConfigForm();
        $navigationConfigForm->setUser($this->Auth()->getUser());
        $navigationConfigForm->setShareConfig(Config::navigation($itemType));
        $navigationConfigForm->setUserConfig(Config::navigation($itemType, $itemOwner));

        $form = new Form(array(
            'onSuccess' => function ($form) use ($navigationConfigForm) {
                $itemName = $form->getValue('name');

                try {
                    $newConfig = $navigationConfigForm->unshare($itemName);
                    if ($navigationConfigForm->save()) {
                        if ($newConfig->getSection($itemName)->type === 'menu-item') {
                            $form->getResponse()->setRerenderLayout();
                        }

                        Notification::success(sprintf(
                            t('Navigation item "%s" has been unshared'),
                            $form->getValue('name')
                        ));
                    } else {
                        // TODO: It failed obviously to write one of the configs, so we're leaving the user in
                        //       a inconsistent state. Luckily, it's nothing lost but possibly duplicated...
                        Notification::error(sprintf(
                            t('Failed to unshare navigation item "%s"'),
                            $form->getValue('name')
                        ));
                    }
                } catch (NotFoundError $e) {
                    throw $e;
                } catch (Exception $e) {
                    Notification::error($e->getMessage());
                }

                $redirect = $form->getValue('redirect');
                if (! empty($redirect)) {
                    $form->setRedirectUrl(htmlspecialchars_decode($redirect));
                }

                return true;
            }
        ));
        $form->setUidDisabled();
        $form->setSubmitLabel('btn_submit'); // Required to ensure that isSubmitted() is called
        $form->addElement('hidden', 'name', array('required' => true));
        $form->addElement('hidden', 'redirect');

        try {
            $form->handleRequest();
        } catch (NotFoundError $_) {
            $this->httpNotFound(sprintf($this->translate('Navigation item "%s" not found'), $form->getValue('name')));
        }
    }

    public function dashboardAction()
    {
        $name = $this->params->getRequired('name');

        $this->getTabs()->add('dashboard', array(
            'active'    => true,
            'label'     => ucwords($name),
            'url'       => Url::fromRequest()
        ));

        $menu = new Menu();

        $navigation = $menu->findItem($name);

        if ($navigation === null) {
            $this->httpNotFound($this->translate('Navigation not found'));
        }

        $this->view->navigation = $navigation;
        $this->view->title = $navigation->getLabel();
    }
}