Test Failed
Push — master ( 71e77c...9acec7 )
by Agel_Nash
02:44
created

modUsers::setUserGroups()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 2 Features 0
Metric Value
dl 0
loc 23
rs 6.1403
c 3
b 2
f 0
cc 8
eloc 15
nc 6
nop 2
1
<?php
2
require_once('MODx.php');
3
4
/**
5
 * Class modUsers
6
 */
7
class modUsers extends MODxAPI
8
{
9
    /**
10
     * @var array
11
     */
12
    protected $default_field = array(
13
        'user'      => array(
14
            'username' => '',
15
            'password' => '',
16
            'cachepwd' => ''
17
        ),
18
        'attribute' => array(
19
            'fullname'         => '',
20
            'role'             => '',
21
            'email'            => '',
22
            'phone'            => '',
23
            'mobilephone'      => '',
24
            'blocked'          => 0,
25
            'blockeduntil'     => 0,
26
            'blockedafter'     => 0,
27
            'logincount'       => 0,
28
            'lastlogin'        => 0,
29
            'thislogin'        => 0,
30
            'failedlogincount' => 0,
31
            'sessionid'        => '',
32
            'dob'              => 0,
33
            'gender'           => 0,
34
            'country'          => '',
35
            'state'            => '',
36
            'city'             => '',
37
            'street'           => '',
38
            'zip'              => '',
39
            'fax'              => '',
40
            'photo'            => '',
41
            'comment'          => '',
42
            'createdon'        => 0,
43
            'editedon'         => 0
44
        ),
45
        'hidden'    => array(
46
            'internalKey'
47
        )
48
    );
49
50
    /**
51
     * @var string
52
     */
53
    protected $givenPassword = '';
54
    protected $groupIds = array();
55
56
    /**
57
     * @var integer
58
     */
59
    private $rememberTime;
60
61
    /**
62
     * MODxAPI constructor.
63
     * @param DocumentParser $modx
64
     * @param bool $debug
65
     * @throws Exception
66
     */
67
    public function __construct(DocumentParser $modx, $debug = false)
68
    {
69
        $this->setRememberTime(60 * 60 * 24 * 365 * 5);
70
        parent::__construct($modx, $debug);
71
    }
72
73
    /**
74
     * @param $val
75
     * @return $this
76
     */
77
    protected function setRememberTime($val)
78
    {
79
        $this->rememberTime = (int)$val;
80
        return $this;
81
    }
82
83
    /**
84
     * @return integer
85
     */
86
    public function getRememberTime()
87
    {
88
        return $this->rememberTime;
89
    }
90
91
    /**
92
     * @param $key
93
     * @return bool
94
     */
95
    public function issetField($key)
96
    {
97
        return (array_key_exists($key, $this->default_field['user']) || array_key_exists(
98
            $key,
99
            $this->default_field['attribute']
100
        ) || in_array($key, $this->default_field['hidden']));
101
    }
102
103
    /**
104
     * @param string $data
105
     * @return string|false
106
     */
107
    protected function findUser($data)
108
    {
109
        switch (true) {
110
            case (is_int($data) || ((int)$data > 0 && (string)intval($data) === $data)):
111
                $find = 'attribute.internalKey';
112
                break;
113
            case filter_var($data, FILTER_VALIDATE_EMAIL):
114
                $find = 'attribute.email';
115
                break;
116
            case is_scalar($data):
117
                $find = 'user.username';
118
                break;
119
            default:
120
                $find = false;
121
        }
122
123
        return $find;
124
    }
125
126
    /**
127
     * @param array $data
128
     * @return $this
129
     */
130
    public function create($data = array())
131
    {
132
        parent::create($data);
133
        $this->set('createdon', time());
134
135
        return $this;
136
    }
137
138
    /**
139
     * @param $id
140
     * @return $this
141
     */
142
    public function edit($id)
143
    {
144
        $id = is_scalar($id) ? trim($id) : '';
145
        if ($this->getID() != $id) {
146
            $this->close();
147
            $this->newDoc = false;
148
149
            if (!$find = $this->findUser($id)) {
150
                $this->id = null;
151
            } else {
152
                $this->set('editedon', time());
153
                $this->editQuery($find, $id);
154
                $this->id = empty($this->field['internalKey']) ? null : $this->get('internalKey');
155
                $this->store($this->toArray());
156
                unset($this->field['id']);
157
                unset($this->field['internalKey']);
158
            }
159
        }
160
161
        return $this;
162
    }
163
164
    /**
165
     * @param string $find
166
     * @param string $id
167
     */
168
    protected function editQuery($find, $id)
169
    {
170
        $result = $this->query("
171
            SELECT * from {$this->makeTable('web_user_attributes')} as attribute
172
            LEFT JOIN {$this->makeTable('web_users')} as user ON user.id=attribute.internalKey
173
            WHERE BINARY {$find}='{$this->escape($id)}'
174
        ");
175
        $this->field = $this->modx->db->getRow($result);
176
    }
177
178
    /**
179
     * @param string $key
180
     * @param $value
181
     * @return $this
182
     */
183
    public function set($key, $value)
184
    {
185
        if (is_scalar($value) && is_scalar($key) && !empty($key)) {
186
            switch ($key) {
187
                case 'password':
188
                    $this->givenPassword = $value;
189
                    $value = $this->getPassword($value);
190
                    break;
191
                case 'sessionid':
192
                    session_regenerate_id(false);
193
                    $value = session_id();
194
                    if ($mid = $this->modx->getLoginUserID('mgr')) {
195
                        $this->modx->db->query("UPDATE {$this->makeTable('active_user_locks')} SET `sid`='{$value}' WHERE `internalKey`={$mid}");
196
                        $this->modx->db->query("UPDATE {$this->makeTable('active_user_sessions')} SET `sid`='{$value}' WHERE `internalKey`={$mid}");
197
                        $this->modx->db->query("UPDATE {$this->makeTable('active_users')} SET `sid`='{$value}' WHERE `internalKey`={$mid}");
198
                    }
199
                    break;
200
                case 'editedon':
201
                case 'createdon':
202
                    $value = $this->getTime($value);
203
                    break;
204
            }
205
            $this->field[$key] = $value;
206
        }
207
208
        return $this;
209
    }
210
211
    /**
212
     * @param $pass
213
     * @return string
214
     */
215
    public function getPassword($pass)
216
    {
217
        return md5($pass);
218
    }
219
220
    /**
221
     * @param bool $fire_events
222
     * @param bool $clearCache
223
     * @return bool|int|null|void
224
     */
225
    public function save($fire_events = false, $clearCache = false)
226
    {
227
        if ($this->get('email') == '' || $this->get('username') == '' || $this->get('password') == '') {
228
            $this->log['EmptyPKField'] = 'Email, username or password is empty <pre>' . print_r(
229
                $this->toArray(),
230
                true
231
            ) . '</pre>';
232
233
            return false;
234
        }
235
236
        if (!$this->checkUnique('web_users', 'username')) {
237
            $this->log['UniqueUsername'] = 'username not unique <pre>' . print_r(
238
                $this->get('username'),
239
                true
240
            ) . '</pre>';
241
242
            return false;
243
        }
244
245
        if (!$this->checkUnique('web_user_attributes', 'email', 'internalKey')) {
246
            $this->log['UniqueEmail'] = 'Email not unique <pre>' . print_r($this->get('email'), true) . '</pre>';
247
248
            return false;
249
        }
250
        $this->set('sessionid', '');
251
        $fld = $this->toArray();
252
        foreach ($this->default_field['user'] as $key => $value) {
253
            $tmp = $this->get($key);
254
            if ($this->newDoc && (!is_int($tmp) && $tmp == '')) {
255
                $this->field[$key] = $value;
256
            }
257
            $this->Uset($key, 'user');
258
            unset($fld[$key]);
259
        }
260
        if (!empty($this->set['user'])) {
261
            if ($this->newDoc) {
262
                $SQL = "INSERT into {$this->makeTable('web_users')} SET " . implode(', ', $this->set['user']);
263
            } else {
264
                $SQL = "UPDATE {$this->makeTable('web_users')} SET " . implode(
265
                    ', ',
266
                    $this->set['user']
267
                ) . " WHERE id = " . $this->id;
268
            }
269
            $this->query($SQL);
270
        }
271
272
        if ($this->newDoc) {
273
            $this->id = $this->modx->db->getInsertId();
274
        }
275
276
        $this->saveQuery($fld);
277
        unset($fld['id']);
278
279
        foreach ($fld as $key => $value) {
280
            if ($value == '' || !$this->isChanged($key)) {
281
                continue;
282
            }
283
            $result = $this->query("SELECT `setting_value` FROM {$this->makeTable('web_user_settings')} WHERE `webuser` = '{$this->id}' AND `setting_name` = '{$key}'");
284
            if ($this->modx->db->getRecordCount($result) > 0) {
285
                $this->query("UPDATE {$this->makeTable('web_user_settings')} SET `setting_value` = '{$value}' WHERE `webuser` = '{$this->id}' AND `setting_name` = '{$key}';");
286
            } else {
287
                $this->query("INSERT into {$this->makeTable('web_user_settings')} SET `webuser` = {$this->id},`setting_name` = '{$key}',`setting_value` = '{$value}';");
288
            }
289
        }
290
        if (!$this->newDoc && $this->givenPassword) {
291
            $this->invokeEvent('OnWebChangePassword', array(
292
                'userObj'      => $this,
293
                'userid'       => $this->id,
294
                'user'         => $this->toArray(),
295
                'userpassword' => $this->givenPassword,
296
                'internalKey'  => $this->id,
297
                'username'     => $this->get('username')
298
            ), $fire_events);
299
        }
300
301
        if (!empty($this->groupIds)) {
302
            $this->setUserGroups($this->id, $this->groupIds);
0 ignored issues
show
Bug introduced by
It seems like $this->id can also be of type string; however, parameter $userID of modUsers::setUserGroups() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

302
            $this->setUserGroups(/** @scrutinizer ignore-type */ $this->id, $this->groupIds);
Loading history...
303
        }
304
305
        $this->invokeEvent('OnWebSaveUser', array(
306
            'userObj' => $this,
307
            'mode'    => $this->newDoc ? "new" : "upd",
308
            'id'      => $this->id,
309
            'user'    => $this->toArray()
310
        ), $fire_events);
311
312
        if ($clearCache) {
313
            $this->clearCache($fire_events);
314
        }
315
316
        return $this->id;
317
    }
318
319
    /**
320
     * @param  array  $fld
321
     */
322
    protected function saveQuery(array &$fld)
323
    {
324
        foreach ($this->default_field['attribute'] as $key => $value) {
325
            $tmp = $this->get($key);
326
            if ($this->newDoc && (!is_int($tmp) && $tmp == '')) {
327
                $this->field[$key] = $value;
328
            }
329
            $this->Uset($key, 'attribute');
330
            unset($fld[$key]);
331
        }
332
        if (!empty($this->set['attribute'])) {
333
            if ($this->newDoc) {
334
                $this->set('internalKey', $this->id)->Uset('internalKey', 'attribute');
335
                $SQL = "INSERT into {$this->makeTable('web_user_attributes')} SET " . implode(
336
                    ', ',
337
                    $this->set['attribute']
338
                );
339
            } else {
340
                $SQL = "UPDATE {$this->makeTable('web_user_attributes')} SET " . implode(
341
                    ', ',
342
                    $this->set['attribute']
343
                ) . " WHERE  internalKey = " . $this->getID();
344
            }
345
            $this->query($SQL);
346
        }
347
    }
348
349
    /**
350
     * @param $ids
351
     * @param bool $fire_events
352
     * @return bool|null|void
353
     */
354
    public function delete($ids, $fire_events = false)
355
    {
356
        if ($this->edit($ids)) {
357
            $flag = $this->deleteQuery();
358
            $this->query("DELETE FROM {$this->makeTable('web_user_settings')} WHERE webuser='{$this->getID()}'");
359
            $this->query("DELETE FROM {$this->makeTable('web_groups')} WHERE webuser='{$this->getID()}'");
360
            $this->invokeEvent('OnWebDeleteUser', array(
361
                'userObj'     => $this,
362
                'userid'      => $this->getID(),
363
                'internalKey' => $this->getID(),
364
                'username'    => $this->get('username'),
365
                'timestamp'   => time()
366
            ), $fire_events);
367
        } else {
368
            $flag = false;
369
        }
370
        $this->close();
371
372
        return $flag;
373
    }
374
375
    protected function deleteQuery()
376
    {
377
        return $this->query("
378
          DELETE user,attribute FROM {$this->makeTable('web_user_attributes')} as attribute
379
            LEFT JOIN {$this->makeTable('web_users')} as user ON user.id=attribute.internalKey
380
            WHERE attribute.internalKey='{$this->escape($this->getID())}'");
381
    }
382
383
    /**
384
     * @param int $id
385
     * @param bool|integer $fulltime
386
     * @param string $cookieName
387
     * @param bool $fire_events
388
     * @return bool
389
     */
390
    public function authUser($id = 0, $fulltime = true, $cookieName = 'WebLoginPE', $fire_events = false)
391
    {
392
        $flag = false;
393
        if (null === $this->getID() && $id) {
394
            $this->edit($id);
395
        }
396
        if (null !== $this->getID()) {
397
            $flag = true;
398
            $this->save(false);
399
            $this->SessionHandler('start', $cookieName, $fulltime);
400
            $this->invokeEvent("OnWebLogin", array(
401
                'userObj'      => $this,
402
                'userid'       => $this->getID(),
403
                'username'     => $this->get('username'),
404
                'userpassword' => $this->givenPassword,
405
                'rememberme'   => $fulltime
406
            ), $fire_events);
407
        }
408
409
        return $flag;
410
    }
411
412
    /**
413
     * @param int $id
414
     * @return bool
415
     */
416
    public function checkBlock($id = 0)
417
    {
418
        $tmp = clone $this;
419
        if ($id && $tmp->getID() != $id) {
420
            $tmp->edit($id);
421
        }
422
        $now = time();
423
424
        $b = $tmp->get('blocked');
425
        $bu = $tmp->get('blockeduntil');
426
        $ba = $tmp->get('blockedafter');
427
        $flag = (($b && !$bu && !$ba) || ($bu && $now < $bu) || ($ba && $now > $ba));
428
        unset($tmp);
429
430
        return $flag;
431
    }
432
433
    /**
434
     * @param $id
435
     * @param $password
436
     * @param $blocker
437
     * @param bool $fire_events
438
     * @return bool
439
     */
440
    public function testAuth($id, $password, $blocker, $fire_events = false)
441
    {
442
        $tmp = clone $this;
443
        if ($id && $tmp->getID() != $id) {
444
            $tmp->edit($id);
445
        }
446
447
        $flag = $pluginFlag = false;
448
        if ((null !== $tmp->getID()) && (!$blocker || ($blocker && !$tmp->checkBlock($id)))
449
        ) {
450
            $eventResult = $this->getInvokeEventResult('OnWebAuthentication', array(
451
                'userObj'       => $this,
452
                'userid'        => $tmp->getID(),
453
                'username'      => $tmp->get('username'),
454
                'userpassword'  => $password,
455
                'savedpassword' => $tmp->get('password')
456
            ), $fire_events);
457
            if (is_array($eventResult)) {
458
                foreach ($eventResult as $result) {
459
                    $pluginFlag = (bool)$result;
460
                }
461
            } else {
462
                $pluginFlag = (bool)$eventResult;
463
            }
464
            if (!$pluginFlag) {
465
                $flag = ($tmp->get('password') == $tmp->getPassword($password));
466
            }
467
        }
468
        unset($tmp);
469
470
        return $flag || $pluginFlag;
471
    }
472
473
    /**
474
     * @param bool|integer $fulltime
475
     * @param string $cookieName
476
     * @return bool
477
     */
478
    public function AutoLogin($fulltime = true, $cookieName = 'WebLoginPE', $fire_events = null)
479
    {
480
        $flag = false;
481
        if (isset($_COOKIE[$cookieName])) {
482
            $cookie = explode('|', $_COOKIE[$cookieName], 4);
483
            if (isset($cookie[0], $cookie[1], $cookie[2]) && strlen($cookie[0]) == 32 && strlen($cookie[1]) == 32) {
484
                if (!$fulltime && isset($cookie[4])) {
485
                    $fulltime = (int)$cookie[4];
486
                }
487
                $this->close();
488
                $q = $this->modx->db->query("SELECT id FROM " . $this->makeTable('web_users') . " WHERE md5(username)='{$this->escape($cookie[0])}'");
489
                $id = $this->modx->db->getValue($q);
490
                if ($this->edit($id)
491
                    && null !== $this->getID()
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getID() targeting MODxAPI::getID() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
introduced by
The condition null !== $this->getID() is always false.
Loading history...
492
                    && $this->get('password') == $cookie[1]
493
                    && $this->get('sessionid') == $cookie[2]
494
                    && !$this->checkBlock($this->getID())
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getID() targeting MODxAPI::getID() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
$this->getID() of type void is incompatible with the type integer expected by parameter $id of modUsers::checkBlock(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

494
                    && !$this->checkBlock(/** @scrutinizer ignore-type */ $this->getID())
Loading history...
495
                ) {
496
                    $flag = $this->authUser($this->getID(), $fulltime, $cookieName, $fire_events);
497
                }
498
            }
499
        }
500
501
        return $flag;
502
    }
503
504
    /**
505
     * @param string $cookieName
506
     * @param bool $fire_events
507
     */
508
    public function logOut($cookieName = 'WebLoginPE', $fire_events = false)
509
    {
510
        if (!$uid = $this->modx->getLoginUserID('web')) {
511
            return;
512
        }
513
        $params = array(
514
            'username'    => $_SESSION['webShortname'],
515
            'internalKey' => $uid,
516
            'userid'      => $uid // Bugfix by TS
517
        );
518
        $this->invokeEvent('OnBeforeWebLogout', $params, $fire_events);
519
        $this->SessionHandler('destroy', $cookieName ? $cookieName : 'WebLoginPE');
520
        $this->invokeEvent('OnWebLogout', $params, $fire_events);
521
    }
522
523
    /**
524
     * SessionHandler
525
     * Starts the user session on login success. Destroys session on error or logout.
526
     *
527
     * @param string $directive ('start' or 'destroy')
528
     * @param string $cookieName
529
     * @param bool|integer $remember
530
     * @return modUsers
531
     * @author Raymond Irving
532
     * @author Scotty Delicious
533
     *
534
     * remeber может быть числом в секундах
535
     */
536
    protected function SessionHandler($directive, $cookieName, $remember = true)
537
    {
538
        switch ($directive) {
539
            case 'start':
540
                if ($this->getID() !== null) {
541
                    $_SESSION['webShortname'] = $this->get('username');
542
                    $_SESSION['webFullname'] = $this->get('fullname');
543
                    $_SESSION['webEmail'] = $this->get('email');
544
                    $_SESSION['webValidated'] = 1;
545
                    $_SESSION['webInternalKey'] = $this->getID();
546
                    $_SESSION['webValid'] = base64_encode($this->get('password'));
547
                    $_SESSION['webUser'] = base64_encode($this->get('username'));
548
                    $_SESSION['webFailedlogins'] = $this->get('failedlogincount');
549
                    $_SESSION['webLastlogin'] = $this->get('lastlogin');
550
                    $_SESSION['webnrlogins'] = $this->get('logincount');
551
                    $_SESSION['webUsrConfigSet'] = array();
552
                    $_SESSION['webUserGroupNames'] = $this->getUserGroups();
553
                    $_SESSION['webDocgroups'] = $this->getDocumentGroups();
554
                    if (!empty($remember)) {
555
                        $this->setAutoLoginCookie($cookieName, $remember);
556
                    }
557
                }
558
                break;
559
            case 'destroy':
560
                if (isset($_SESSION['mgrValidated'])) {
561
                    unset($_SESSION['webShortname']);
562
                    unset($_SESSION['webFullname']);
563
                    unset($_SESSION['webEmail']);
564
                    unset($_SESSION['webValidated']);
565
                    unset($_SESSION['webInternalKey']);
566
                    unset($_SESSION['webValid']);
567
                    unset($_SESSION['webUser']);
568
                    unset($_SESSION['webFailedlogins']);
569
                    unset($_SESSION['webLastlogin']);
570
                    unset($_SESSION['webnrlogins']);
571
                    unset($_SESSION['webUsrConfigSet']);
572
                    unset($_SESSION['webUserGroupNames']);
573
                    unset($_SESSION['webDocgroups']);
574
575
                    setcookie($cookieName, '', time() - 60, MODX_BASE_URL);
576
                } else {
577
                    if (isset($_COOKIE[session_name()])) {
578
                        setcookie(session_name(), '', time() - 60, MODX_BASE_URL);
579
                    }
580
                    setcookie($cookieName, '', time() - 60, MODX_BASE_URL);
581
                    session_destroy();
582
                }
583
                break;
584
        }
585
586
        return $this;
587
    }
588
589
    /**
590
     * @return bool
591
     */
592
    public function isSecure()
593
    {
594
        $out = $this->modxConfig('server_protocol') == 'http' ? false : true;
595
596
        return $out;
597
    }
598
599
    /**
600
     * @param $cookieName
601
     * @param bool|integer $remember
602
     * @return $this
603
     */
604
    public function setAutoLoginCookie($cookieName, $remember = true)
605
    {
606
        if (!empty($cookieName) && $this->getID() !== null) {
607
            $secure = $this->isSecure();
608
            $remember = is_bool($remember) ? $this->getRememberTime() : (int)$remember;
609
            $cookieValue = array(md5($this->get('username')), $this->get('password'), $this->get('sessionid'), $remember);
610
            $cookieValue = implode('|', $cookieValue);
611
            $cookieExpires = time() + $remember;
612
            setcookie($cookieName, $cookieValue, $cookieExpires, MODX_BASE_URL, '', $secure, true);
613
        }
614
615
        return $this;
616
    }
617
618
    /**
619
     * @param int $userID
620
     * @return array
621
     */
622
    public function getDocumentGroups($userID = 0)
623
    {
624
        $out = array();
625
        $user = $this->switchObject($userID);
626
        if (null !== $user->getID()) {
627
            $web_groups = $this->modx->getFullTableName('web_groups');
628
            $webgroup_access = $this->modx->getFullTableName('webgroup_access');
629
630
            $sql = "SELECT `uga`.`documentgroup` FROM {$web_groups} as `ug`
631
                INNER JOIN {$webgroup_access} as `uga` ON `uga`.`webgroup`=`ug`.`webgroup`
632
                WHERE `ug`.`webuser` = " . $user->getID();
633
            $out = $this->modx->db->getColumn('documentgroup', $this->query($sql));
634
        }
635
        unset($user);
636
637
        return $out;
638
    }
639
640
    /**
641
     * @param int $userID
642
     * @return array
643
     */
644
    public function getUserGroups($userID = 0)
645
    {
646
        $out = array();
647
        $user = $this->switchObject($userID);
648
        if (null !== $user->getID()) {
649
            $web_groups = $this->makeTable('web_groups');
650
            $webgroup_names = $this->makeTable('webgroup_names');
651
652
            $rs = $this->query("SELECT `ug`.`webgroup`, `ugn`.`name` FROM {$web_groups} as `ug`
653
                INNER JOIN {$webgroup_names} as `ugn` ON `ugn`.`id`=`ug`.`webgroup`
654
                WHERE `ug`.`webuser` = " . $user->getID());
655
            while ($row = $this->modx->db->getRow($rs)) {
656
                $out[$row['webgroup']] = $row['name'];
657
            }
658
        }
659
        unset($user);
660
661
        return $out;
662
    }
663
664
    /**
665
     * @param int $userID
666
     * @param array $groupIds
667
     * @return $this
668
     */
669
    public function setUserGroups($userID = 0, $groupIds = array())
670
    {
671
        if (!is_array($groupIds)) {
0 ignored issues
show
introduced by
The condition is_array($groupIds) is always true.
Loading history...
672
            return $this;
673
        }
674
        if ($this->newDoc && $userID == 0) {
675
            $this->groupIds = $groupIds;
676
        } else {
677
            $user = $this->switchObject($userID);
678
            if ($uid = $user->getID()) {
679
                foreach ($groupIds as $gid) {
680
                    $this->query("REPLACE INTO {$this->makeTable('web_groups')} (`webgroup`, `webuser`) VALUES ('{$gid}', '{$uid}')");
681
                }
682
                if (!$this->newDoc) {
683
                    $groupIds = empty($groupIds) ? '0' : implode(',', $groupIds);
684
                    $this->query("DELETE FROM {$this->makeTable('web_groups')} WHERE `webuser`={$uid} AND `webgroup` NOT IN ({$groupIds})");
685
                }
686
            }
687
            unset($user);
688
            $this->groupIds = array();
689
        }
690
691
        return $this;
692
    }
693
}
694