aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/WidgetHelper.php
blob: ff4d7a61268e663f4a33fe43e1f2eab50489a21f (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
<?php
/**
 * WidgetHelper.php - utility functions for Widget-Parameter Handling
 * @deprecated since Stud.IP 5.5
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * @author   Nadine Werner <nadine.werner@uni-osnabrueck.de>
 * @author   André Klaßen <klassen@elan-ev.de>
 * @license  http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
 * @category Stud.IP
 * @package  index
 * @since    3.1
 */

class WidgetHelper
{
    /**
     * array of submitted widget parameter values
     */
    private static $params = [];

    /**
     * array of submitted widget parameter values
     */
    private static $activeWidget;

    /**
     * Saves the widget data of a user
     */
    private static $userWidgets = [];

    /**
     * Set the last active Widget
     * @param string $activeWidget
     */
    public static function setActiveWidget($activeWidget)
    {
        self::$activeWidget = $activeWidget;
    }

    /**
     * Returns the position in the two column layout on the Startpage
     * If no position is stored in UserConfig, the widget will be displayed on the right side.
     *
     * @param string $pluginid
     *
     * @return the position as array matrix
     */
    public static function getWidgetPosition($pluginid)
    {
        $query = "SELECT position FROM widget_user where id = ?";
        $statement = DBManager::get()->prepare($query);
        $statement->execute([$pluginid]);
        $pos = $statement->fetchColumn();

        return $pos;
    }

    /**
     * storeNewPositions - stores new Widget positions for a given user
     *
     * @param array $lanes array with column as index and ids array as value
     *
     * @return void
     */
    public static function storeNewPositions(array $lanes): void
    {
        // Query not displayed widgets to sort them to the bottom of a lane
        $query = "SELECT `col`, `id`
                  FROM `widget_user`
                  WHERE `range_id` = ?
                    AND `id` NOT IN (?)
                  ORDER BY `col`, `position`";
        $undisplayed = DBManager::get()->fetchGrouped($query, [
            User::findCurrent()->id,
            array_merge(...$lanes)
        ], function ($row) {
            return array_column($row, 'id');
        });

        // Set new positions
        $query = "UPDATE `widget_user`
                  SET `col` = :column,
                      `position` = :position
                  WHERE `id` = :id
                    AND `range_id` = :user_id";
        $statement = DBManager::get()->prepare($query);
        $statement->bindValue(':user_id', User::findCurrent()->id);

        foreach ([0, 1] as $column) {
            $statement->bindValue(':column', $column);

            $ids = array_merge(
                $lanes[$column] ?? [],
                $undisplayed[$column] ?? []
            );

            $position = 0;
            foreach ($ids as $id) {
                $statement->bindValue(':position', $position++);
                $statement->bindValue(':id', $id);
                $statement->execute();
            }
        }
    }

    /**
     * addInitialPositons - adds the global widget default settings to an user setting
     *
     * @param string $col
     * @param array $ids of widgets
     * @param string $range_id
     *
     * @return void
     */
    public static function addInitialPositions($col, $ids, $range_id)
    {
        if(is_array($ids)) {
             foreach ($ids as $pos => $id) {
                  $pos = intVal($pos);
                  $query = "REPLACE INTO widget_user (`pluginid`, `position`, `range_id`) VALUES (?,?,?);";
                  $statement = DBManager::get()->prepare($query);
                  $statement->execute([$id, $pos, $range_id]);
             }
        }
    }

    /**
     * storeInitialPositions - stores the global widget default for a given perm
     *
     * @param string $col
     * @param array $ids of widgets
     * @param string $perm
     *
     * @return boolean success
     */
    public static function storeInitialPositions($col, $ids, $perm)
    {
        $stmt = DBManager::get()->prepare('DELETE FROM widget_default WHERE `perm` = ? AND `col` = ?;');
        $stmt->execute([$perm, $col]);

        if (is_array($ids)) {
            foreach ($ids as $id => $pos) {
                if ($id) {
                    $pos = intVal($pos);
                    $stmt = DBManager::get()->prepare("REPLACE INTO widget_default (`pluginid`,`col`, `position`, `perm`) VALUES (?,?,?,?);");
                    $stmt->execute([$id, $col, $pos, $perm]);
                }
            }

            return true;
        }

        return false;
    }

    public static function getInitialPositions($perm)
    {
        return DBManager::get()->fetchGroupedPairs("SELECT col, pluginid, position FROM widget_default "
                . "WHERE perm = ? "
                . "ORDER BY col ASC, position ASC", [$perm]);
    }

    /**
     * Sets the current setting of a user as the default for a usergroup
     *
     * @param string $range_id The range id of the user that defines the setting
     * @param string $group The usergroup
     */
    public static function setAsInitialPositions($range_id, $group)
    {
        DBManager::get()->execute("DELETE FROM widget_default WHERE `perm` = ?", [$group]);
        DBManager::get()->execute('INSERT INTO widget_default (SELECT pluginid, col, position, ? as perm  FROM widget_user WHERE range_id = ?)', [$group, $range_id]);
    }

    /**
     * setInitialPositions - copies the default to the logged on user
     */
    public static function setInitialPositions()
    {
        $query = "INSERT INTO widget_user (pluginid, position, range_id, col)
                  SELECT pluginid, position, :user_id, col
                  AS perm
                  FROM widget_default
                  WHERE perm = :perm

                  UNION

                  -- Dummy entry to allow no widgets
                  SELECT -1, 0, :user_id, 2";
        DBManager::get()->execute($query, [
            ':user_id' => $GLOBALS['user']->id,
            ':perm'    => $GLOBALS['perm']->get_perm(),
        ]);
    }

    /**
     * getUserWidgets - retrieves the widget settings for a given user
     *
     * @param string $id
     *
     * @return array $widgets
     */
    public static function getUserWidgets($id, $col = 0)
    {
        $plugin_manager = PluginManager::getInstance();
        $query = "SELECT * FROM widget_user WHERE range_id=? AND col = ? ORDER BY position";
        $statement = DBManager::get()->prepare($query);
        $statement->execute([$id, $col]);
        $widgets = [];
        while ($db_widget = $statement->fetch(PDO::FETCH_ASSOC)) {
            if(!is_null($plugin_manager->getPluginById($db_widget['pluginid']))){
                $widget = clone $plugin_manager->getPluginById($db_widget['pluginid']);
                $widget->widget_id = $db_widget['id'];
                $widgets[$db_widget['position']] = $widget;
            }
        }
        return $widgets;
    }

    /**
     * Returns whether a user has any defined widgets.
     * @param  string  $user_id User id
     * @return boolean
     */
    public static function hasUserWidgets($user_id)
    {
        $query = "SELECT 1 FROM `widget_user` WHERE `range_id` = ?";
        return (bool) DBManager::get()->fetchColumn($query, [$user_id]);
    }

    /**
     * addWidgetUserConfig - creates user_config entry for widget newly added by a user
     *
     * @param string $id - user_id
     * @param string $pluginName
     * @param array $confArray
     *
     * @return void
     */
    public static function addWidgetUserConfig($id, $pluginName, $confArray )
    {
        UserConfig::get($id)->store($pluginName, $confArray );
    }


    /**
     * getWidgetUserConfig - retrieves user_config entry for widget newly added by a user
     *
     * @param string $id user_id
     * @param string $pluginName
     *
     * @return object UserConfig
     */
    public static function getWidgetUserConfig($id, $pluginName)
    {
        return UserConfig::get($id)->getValue($pluginName);

    }

    /**
     * removeWidget - removes a widget for a user
     *
     * @param string $id - widget_id
     * @param string $pluginName
     * @param string $range_id e.g. user_id
     *
     * @return bool success
     */
    public static function removeWidget($id, $pluginName, $range_id)
    {
        UserConfig::get($range_id)->delete($pluginName);

        $query = "DELETE FROM widget_user WHERE id = ? AND range_id = ?";
        $statement = DBManager::get()->prepare($query);

        return $statement->execute([$id, $range_id]);
    }

    /**
     * addWidget - adds a widget for a given user
     *
     * @param string $id - widget_id
     * @param string $range_id e.g. user_id
     *
     * @return bool|int false on error, id of inserted widget otherwise
     */
    public static function addWidget($id, $range_id)
    {
        $db = DBManager::get();
        $statement = $db->prepare('SELECT MAX(position) + 1 FROM widget_user WHERE range_id = :range_id');
        $statement->bindValue(':range_id', $range_id);
        $statement->execute();
        $position = $statement->fetchColumn() ?: 0;

        $statement = $db->prepare('INSERT INTO widget_user (pluginid, position, range_id) VALUES (:id, :position, :range_id)');
        $statement->bindValue(':id', $id);
        $statement->bindValue(':position', $position);
        $statement->bindValue(':range_id', $range_id);
        $result = $statement->execute();

        return $result ? $db->lastInsertId() : false;
    }

    /**
     * getWidgetName - retrieves the name of a given widget
     *
     * @param string $id - widget_id
     *
     * @return string widget_name
     */
    public static function getWidgetName($id)
    {
        $query = "SELECT `pluginid` FROM `widget_user` WHERE `id`=?";
        $statement = DBManager::get()->prepare($query);
        $statement->execute([$id]);
        $pid = $statement->fetch(PDO::FETCH_ASSOC);

        $plugin_manager = PluginManager::getInstance();
        $plugin_info = $plugin_manager->getPluginById($pid['pluginid']);
        return $plugin_info ? $plugin_info->getPluginName() : false;

    }


    /**
     * getWidget - retrieves an instance of a given widget / portal plugin
     *
     * @param string $pluginid
     *
     * @return object widget
     */
    public static function getWidget($pluginid)
    {
        return PluginManager::getInstance()->getPluginById($pluginid);
    }

    /**
     * getAvailableWidgets - fetches all widgets that are not already in use.
     *
     * @param string $user_id the user to check
     *
     * @return array All available widgets.
     */
    public static function getAvailableWidgets($user_id = null)
    {
        $all_widgets = PluginEngine::getPlugins(PortalPlugin::class);

        $used_widgets = is_null($user_id)
                ? []
                : DBManager::get()->fetchFirst("SELECT `pluginid` FROM `widget_user` WHERE `range_id`=? ORDER BY `pluginid`", [$user_id]);

        $available = [];
        foreach ($all_widgets as $widget) {
            if (!in_array($widget->getPluginId(), $used_widgets)) {
                $available[$widget->getPluginId()] = $widget;
            }
        }
        return $available;
    }

    /**
     * hasWidget - returns whether has a certain widget activated
     *
     * @param string $user_id Id of the user
     * @param mixed  $widget  Id or name of the widget (you may omit the
     *                        'Widget' in the name)
     * @return bool indicating whether the widget is activated
     */
    public static function hasWidget($user_id, $widget)
    {
        if (!isset(self::$userWidgets[$user_id])) {
            $statement = DBManager::get()->prepare("
                SELECT *
                FROM widget_user
                WHERE range_id = :user_id
            ");
            $statement->execute(['user_id' => $user_id]);
            self::$userWidgets[$user_id] = $statement->fetchAll(PDO::FETCH_ASSOC);
        }

        if (!ctype_digit($widget)) {
            $plugin = PluginManager::getInstance()->getPlugin($widget) ?: PluginManager::getInstance()->getPlugin($widget . "Widget");
            if ($plugin) {
                $widget = $plugin->getPluginId();
            } else {
                return false;
            }
        }

        foreach (self::$userWidgets[$user_id] as $widget_user) {
            if ($widget_user['pluginid'] == $widget) {
                return true;
            }
        }
        return false;
    }
}