summaryrefslogtreecommitdiffstats
path: root/application/forms/Config/User/CreateMembershipForm.php
blob: 6c74c8c7ca9cdaa8acdcc4d00dbe4a0dbf49d05d (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
<?php
/* Icinga Web 2 | (c) 2015 Icinga Development Team | GPLv2+ */

namespace Icinga\Forms\Config\User;

use Exception;
use Icinga\Application\Logger;
use Icinga\Data\DataArray\ArrayDatasource;
use Icinga\Web\Form;
use Icinga\Web\Notification;

/**
 * Form for creating one or more group memberships
 */
class CreateMembershipForm extends Form
{
    /**
     * The user group backends to fetch groups from
     *
     * Each backend must implement the Icinga\Data\Extensible and Icinga\Data\Selectable interface.
     *
     * @var array
     */
    protected $backends;

    /**
     * The username to create memberships for
     *
     * @var string
     */
    protected $userName;

    /**
     * Set the user group backends to fetch groups from
     *
     * @param   array   $backends
     *
     * @return  $this
     */
    public function setBackends($backends)
    {
        $this->backends = $backends;
        return $this;
    }

    /**
     * Set the username to create memberships for
     *
     * @param   string  $userName
     *
     * @return  $this
     */
    public function setUsername($userName)
    {
        $this->userName = $userName;
        return $this;
    }

    /**
     * Create and add elements to this form
     *
     * @param   array   $formData   The data sent by the user
     */
    public function createElements(array $formData)
    {
        $query = $this->createDataSource()->select()->from('group', array('group_name', 'backend_name'));

        $options = array();
        foreach ($query as $row) {
            $options[$row->backend_name . ';' . $row->group_name] = $row->group_name . ' (' . $row->backend_name . ')';
        }

        $this->addElement(
            'multiselect',
            'groups',
            array(
                'required'      => true,
                'multiOptions'  => $options,
                'label'         => $this->translate('Groups'),
                'description'   => sprintf(
                    $this->translate('Select one or more groups where to add %s as member'),
                    $this->userName
                ),
                'class'         => 'grant-permissions'
            )
        );

        $this->setTitle(sprintf($this->translate('Create memberships for %s'), $this->userName));
        $this->setSubmitLabel($this->translate('Create'));
    }

    /**
     * Instantly redirect back in case the user is already a member of all groups
     */
    public function onRequest()
    {
        if ($this->createDataSource()->select()->from('group')->count() === 0) {
            Notification::info(sprintf($this->translate('User %s is already a member of all groups'), $this->userName));
            $this->getResponse()->redirectAndExit($this->getRedirectUrl());
        }
    }

    /**
     * Create the memberships for the user
     *
     * @return  bool
     */
    public function onSuccess()
    {
        $backendMap = array();
        foreach ($this->backends as $backend) {
            $backendMap[$backend->getName()] = $backend;
        }

        $single = null;
        $groupName = null;
        foreach ($this->getValue('groups') as $backendAndGroup) {
            list($backendName, $groupName) = explode(';', $backendAndGroup, 2);
            try {
                $backendMap[$backendName]->insert(
                    'group_membership',
                    array(
                        'group_name'    => $groupName,
                        'user_name'     => $this->userName
                    )
                );
            } catch (Exception $e) {
                Notification::error(sprintf(
                    $this->translate('Failed to add "%s" as group member for "%s"'),
                    $this->userName,
                    $groupName
                ));
                $this->error($e->getMessage());
                return false;
            }

            $single = $single === null;
        }

        if ($single) {
            Notification::success(
                sprintf($this->translate('Membership for group %s created successfully'), $groupName)
            );
        } else {
            Notification::success($this->translate('Memberships created successfully'));
        }

        return true;
    }

    /**
     * Create and return a data source to fetch all groups from all backends where the user is not already a member of
     *
     * @return  ArrayDatasource
     */
    protected function createDataSource()
    {
        $groups = $failures = array();
        foreach ($this->backends as $backend) {
            try {
                $memberships = $backend
                    ->select()
                    ->from('group_membership', array('group_name'))
                    ->where('user_name', $this->userName)
                    ->fetchColumn();
                foreach ($backend->select(array('group_name')) as $row) {
                    if (! in_array($row->group_name, $memberships)) { // TODO(jom): Apply this as native query filter
                        $row->backend_name = $backend->getName();
                        $groups[] = $row;
                    }
                }
            } catch (Exception $e) {
                $failures[] = array($backend->getName(), $e);
            }
        }

        if (empty($groups) && !empty($failures)) {
            // In case there are only failures, throw the very first exception again
            throw $failures[0][1];
        } elseif (! empty($failures)) {
            foreach ($failures as $failure) {
                Logger::error($failure[1]);
                Notification::warning(sprintf(
                    $this->translate('Failed to fetch any groups from backend %s. Please check your log'),
                    $failure[0]
                ));
            }
        }

        return new ArrayDatasource($groups);
    }
}