Completed
Branch master (1f607b)
by Agel_Nash
08:24 queued 22s
created

modManagers::getRememberTime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
1 ignored issue
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 7 and the first side effect is on line 2.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
require_once('MODx.php');
3
4
/**
5
 * Class modUsers
6
 */
7
class modManagers extends MODxAPI
1 ignored issue
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
8
{
9
    /**
10
     * @var array
11
     */
12
    protected $default_field = array(
13
        'user'      => array(
14
            'username' => '',
15
            'password' => '',
16
        ),
17
        'attribute' => array(
18
            'fullname'         => '',
19
            'role'             => 0,
20
            'email'            => '',
21
            'phone'            => '',
22
            'mobilephone'      => '',
23
            'blocked'          => 0,
24
            'blockeduntil'     => 0,
25
            'blockedafter'     => 0,
26
            'logincount'       => 0,
27
            'lastlogin'        => 0,
28
            'thislogin'        => 0,
29
            'failedlogincount' => 0,
30
            'sessionid'        => '',
31
            'dob'              => 0,
32
            'gender'           => 0,
33
            'country'          => '',
34
            'state'            => '',
35
            'city'             => '',
36
            'street'           => '',
37
            'zip'              => '',
38
            'fax'              => '',
39
            'photo'            => '',
40
            'comment'          => '',
41
            'createdon'        => 0,
42
            'editedon'         => 0
43
        ),
44
        'hidden'    => array(
45
            'internalKey'
46
        )
47
    );
48
49
    /**
50
     * @var string
51
     */
52
    protected $givenPassword = '';
53
    protected $groupIds = array();
54
    protected $mgrPermissions = 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
        $this->modx->loadExtension('phpass');
72
    }
73
74
    /**
75
     * @param $val
76
     * @return $this
77
     */
78
    protected function setRememberTime($val){
79
        $this->rememberTime = (int)$val;
80
        return $this;
81
    }
82
83
    /**
84
     * @return integer
85
     */
86
    public function getRememberTime(){
87
        return $this->rememberTime;
88
    }
89
90
    /**
91
     * @param $key
92
     * @return bool
93
     */
94
    public function issetField($key)
95
    {
96
        return (array_key_exists($key, $this->default_field['user']) || array_key_exists($key,
97
                $this->default_field['attribute']) || in_array($key, $this->default_field['hidden']));
98
    }
99
100
    /**
101
     * @param string $data
102
     * @return string|false
103
     */
104
    protected function findUser($data)
105
    {
106
        switch (true) {
107
            case (is_int($data) || ((int)$data > 0 && (string)intval($data) === $data)):
108
                $find = 'attribute.internalKey';
109
                break;
110
            case filter_var($data, FILTER_VALIDATE_EMAIL):
111
                $find = 'attribute.email';
112
                break;
113
            case is_scalar($data):
114
                $find = 'user.username';
115
                break;
116
            default:
117
                $find = false;
118
        }
119
120
        return $find;
121
    }
122
123
    /**
124
     * @param array $data
125
     * @return $this
126
     */
127
    public function create($data = array())
128
    {
129
        parent::create($data);
130
        $this->set('createdon', time());
131
132
        return $this;
133
    }
134
135
    /**
136
     * @param $id
137
     * @return $this
138
     */
139
    public function edit($id)
140
    {
141
        $id = is_scalar($id) ? trim($id) : '';
142
        if ($this->getID() != $id) {
143
            $this->close();
144
            $this->newDoc = false;
145
146
            if (!$find = $this->findUser($id)) {
147
                $this->id = null;
148
            } else {
149
                $this->set('editedon', time());
150
                $result = $this->query("
151
                    SELECT * from {$this->makeTable('user_attributes')} as attribute
152
                    LEFT JOIN {$this->makeTable('manager_users')} as user ON user.id=attribute.internalKey
153
                    WHERE BINARY {$find}='{$this->escape($id)}'
154
                ");
155
                $this->field = $this->modx->db->getRow($result);
156
157
                $this->id = empty($this->field['internalKey']) ? null : $this->get('internalKey');
158
                $this->store($this->toArray());
159
                $result = $this->query("SELECT * FROM {$this->makeTable('user_roles')} WHERE `id`={$this->get('role')}");
160
                $permissions = $this->modx->db->getRow($result);
161
                unset($permissions['id'], $permissions['name'], $permissions['description']);
162
                $this->mgrPermissions = $permissions;
163
                unset($this->field['id']);
164
                unset($this->field['internalKey']);
165
            }
166
        }
167
168
        return $this;
169
    }
170
171
    /**
172
     * @param string $key
173
     * @param $value
174
     * @return $this
175
     */
176
    public function set($key, $value)
177
    {
178
        if (is_scalar($value) && is_scalar($key) && !empty($key)) {
179
            switch ($key) {
180
                case 'password':
181
                    $this->givenPassword = $value;
182
                    $value = $this->getPassword($value);
183
                    break;
184
                case 'sessionid':
185
                    session_regenerate_id(false);
186
                    $value = session_id();
187
                    if ($mid = $this->modx->getLoginUserID('mgr')) {
188
                        $this->modx->db->query("UPDATE {$this->makeTable('active_user_locks')} SET `sid`='{$value}' WHERE `internalKey`={$mid}");
189
                        $this->modx->db->query("UPDATE {$this->makeTable('active_user_sessions')} SET `sid`='{$value}' WHERE `internalKey`={$mid}");
190
                        $this->modx->db->query("UPDATE {$this->makeTable('active_users')} SET `sid`='{$value}' WHERE `internalKey`={$mid}");
191
                    }
192
                    break;
193
                case 'editedon':
194
                case 'createdon':
195
                    $value = $this->getTime($value);
196
                    break;
197
            }
198
            $this->field[$key] = $value;
199
        }
200
201
        return $this;
202
    }
203
204
    /**
205
     * @param $pass
206
     * @return string
207
     */
208
    public function getPassword($pass)
209
    {
210
        return $this->modx->phpass->HashPassword($pass);
211
    }
212
213
    /**
214
     * @param string $name
215
     * @return bool
216
     */
217
    public function hasPermission($name)
218
    {
219
        return (is_string($name) && $name && isset($this->mgrPermissions[$name]));
220
    }
221
222
    /**
223
     * @param bool $fire_events
224
     * @param bool $clearCache
225
     * @return bool|int|null|void
226
     */
227
    public function save($fire_events = false, $clearCache = false)
228
    {
229
        if ($this->get('email') == '' || $this->get('username') == '' || $this->get('password') == '') {
230
            $this->log['EmptyPKField'] = 'Email, username or password is empty <pre>' . print_r($this->toArray(),
231
                    true) . '</pre>';
232
233
            return false;
234
        }
235
236
        if (!$this->checkUnique('manager_users', 'username')) {
237
            $this->log['UniqueUsername'] = 'username not unique <pre>' . print_r($this->get('username'),
238
                    true) . '</pre>';
239
240
            return false;
241
        }
242
243
        if (!$this->checkUnique('user_attributes', 'email', 'internalKey')) {
244
            $this->log['UniqueEmail'] = 'Email not unique <pre>' . print_r($this->get('email'), true) . '</pre>';
245
246
            return false;
247
        }
248
249
        if(!$this->get('role')) {
250
            $this->log['UniqueEmail'] = 'Wrong manager role <pre>' . print_r($this->get('role'), true) . '</pre>';
251
        }
252
253
        $this->set('sessionid', '');
254
        $fld = $this->toArray();
255
        foreach ($this->default_field['user'] as $key => $value) {
256
            $tmp = $this->get($key);
257
            if ($this->newDoc && (!is_int($tmp) && $tmp == '')) {
258
                $this->field[$key] = $value;
259
            }
260
            $this->Uset($key, 'user');
261
            unset($fld[$key]);
262
        }
263
        if (!empty($this->set['user'])) {
264
            if ($this->newDoc) {
265
                $SQL = "INSERT into {$this->makeTable('manager_users')} SET " . implode(', ', $this->set['user']);
266
            } else {
267
                $SQL = "UPDATE {$this->makeTable('manager_users')} SET " . implode(', ',
268
                        $this->set['user']) . " WHERE id = " . $this->id;
269
            }
270
            $this->query($SQL);
271
        }
272
273
        if ($this->newDoc) {
274
            $this->id = $this->modx->db->getInsertId();
275
        }
276
277
        foreach ($this->default_field['attribute'] as $key => $value) {
278
            $tmp = $this->get($key);
279
            if ($this->newDoc && (!is_int($tmp) && $tmp == '')) {
280
                $this->field[$key] = $value;
281
            }
282
            $this->Uset($key, 'attribute');
283
            unset($fld[$key]);
284
        }
285
        if (!empty($this->set['attribute'])) {
286
            if ($this->newDoc) {
287
                $this->set('internalKey', $this->id)->Uset('internalKey', 'attribute');
288
                $SQL = "INSERT into {$this->makeTable('user_attributes')} SET " . implode(', ',
289
                        $this->set['attribute']);
290
            } else {
291
                $SQL = "UPDATE {$this->makeTable('user_attributes')} SET " . implode(', ',
292
                        $this->set['attribute']) . " WHERE  internalKey = " . $this->getID();
293
            }
294
            $this->query($SQL);
295
        }
296
        unset($fld['id']);
297
        foreach ($fld as $key => $value) {
298
            if ($value == '' || !$this->isChanged($key)) {
299
                continue;
300
            }
301
            $result = $this->query("SELECT `setting_value` FROM {$this->makeTable('user_settings')} WHERE `user` = '{$this->id}' AND `setting_name` = '{$key}'");
302
            if ($this->modx->db->getRecordCount($result) > 0) {
303
                $this->query("UPDATE {$this->makeTable('user_settings')} SET `setting_value` = '{$value}' WHERE `user` = '{$this->id}' AND `setting_name` = '{$key}';");
304
            } else {
305
                $this->query("INSERT into {$this->makeTable('user_settings')} SET `user` = {$this->id},`setting_name` = '{$key}',`setting_value` = '{$value}';");
306
            }
307
        }
308
        // TODO
309
        if (!$this->newDoc && $this->givenPassword) {
310
            $this->invokeEvent('OnManagerChangePassword', array(
311
                'userObj'      => $this,
312
                'userid'       => $this->id,
313
                'user'         => $this->toArray(),
314
                'userpassword' => $this->givenPassword,
315
                'username'     => $this->get('username')
316
            ), $fire_events);
317
        }
318
319
        if (!empty($this->groupIds)) {
320
            $this->setUserGroups($this->id, $this->groupIds);
321
        }
322
        // TODO
323
        $this->invokeEvent('OnManagerSaveUser', array(
324
            'userObj'      => $this,
325
            'mode'         => $this->newDoc ? "new" : "upd",
326
            'user'         => $this->toArray(),
327
            "userid"       => $this->getID(),
328
            "username"     => $this->get('username'),
329
            "userpassword" => $this->givenPassword,
330
            "useremail"    => $this->get('email'),
331
            "userfullname" => $this->get('fullname'),
332
            "userroleid"   => $this->get('role')
333
        ), $fire_events);
334
335
        if ($clearCache) {
336
            $this->clearCache($fire_events);
337
        }
338
339
        return $this->id;
340
    }
341
342
    /**
343
     * @param $ids
344
     * @param bool $fire_events
345
     * @return bool|null|void
346
     */
347
    public function delete($ids, $fire_events = false)
348
    {
349
        if ($this->edit($ids)) {
350
            $flag = $this->query("
351
          DELETE user,attribute FROM {$this->makeTable('user_attributes')} as attribute
352
            LEFT JOIN {$this->makeTable('manager_users')} as user ON user.id=attribute.internalKey
353
            WHERE attribute.internalKey='{$this->escape($this->getID())}'");
354
            $this->query("DELETE FROM {$this->makeTable('user_settings')} WHERE user='{$this->getID()}'");
355
            $this->query("DELETE FROM {$this->makeTable('member_groups')} WHERE member='{$this->getID()}'");
356
            $this->invokeEvent('OnManagerDeleteUser', array(
357
                'userObj'     => $this,
358
                'userid'      => $this->getID(),
359
                'internalKey' => $this->getID(),
360
                'username'    => $this->get('username'),
361
                'timestamp'   => time()
362
            ), $fire_events);
363
        } else {
364
            $flag = false;
365
        }
366
        $this->close();
367
368
        return $flag;
369
    }
370
371
    /**
372
     * @param int $id
373
     * @param bool|integer $fulltime
374
     * @param string $cookieName
375
     * @param bool $fire_events
376
     * @return bool
377
     */
378
    public function authUser($id = 0, $fulltime = true, $cookieName = 'modx_remember_manager', $fire_events = false)
379
    {
380
        $flag = false;
381
        if (null === $this->getID() && $id) {
382
            $this->edit($id);
383
        }
384
        if (null !== $this->getID()) {
385
            $flag = true;
386
            $this->save(false);
387
            $this->SessionHandler('start', $cookieName, $fulltime);
388
            $this->invokeEvent("OnManagerLogin", array(
389
                'userObj'      => $this,
390
                'userid'       => $this->getID(),
391
                'username'     => $this->get('username'),
392
                'userpassword' => $this->givenPassword,
393
                'rememberme'   => $fulltime
394
            ), $fire_events);
395
        }
396
397
        return $flag;
398
    }
399
400
    /**
401
     * @param int $id
402
     * @return bool
403
     */
404
    public function checkBlock($id = 0)
405
    {
406
        $tmp = clone $this;
407
        if ($id && $tmp->getID() != $id) {
408
            $tmp->edit($id);
409
        }
410
        $now = time();
411
412
        $b = $tmp->get('blocked');
413
        $bu = $tmp->get('blockeduntil');
414
        $ba = $tmp->get('blockedafter');
415
        $flag = (($b && !$bu && !$ba) || ($bu && $now < $bu) || ($ba && $now > $ba));
416
        unset($tmp);
417
418
        return $flag;
419
    }
420
421
    /**
422
     * @param $id
423
     * @param $password
424
     * @param $blocker
425
     * @param bool $fire_events
426
     * @return bool
427
     */
428
    public function testAuth($id, $password, $blocker, $fire_events = false)
429
    {
430
        $tmp = clone $this;
431
        if ($id && $tmp->getID() != $id) {
432
            $tmp->edit($id);
433
        }
434
435
        $flag = $pluginFlag = false;
436
        if (
437
            (null !== $tmp->getID()) && (!$blocker || ($blocker && !$tmp->checkBlock($id)))
438
        ) {
439
            $_password = $tmp->get('password');
440
            $eventResult = $this->getInvokeEventResult('OnManagerAuthentication', array(
441
                'userObj'       => $this,
442
                'userid'        => $tmp->getID(),
443
                'username'      => $tmp->get('username'),
444
                'userpassword'  => $password,
445
                'savedpassword' => $_password
446
            ), $fire_events);
447
            if (is_array($eventResult)) {
448
                foreach ($eventResult as $result) {
449
                    $pluginFlag = (bool)$result;
450
                }
451
            } else {
452
                $pluginFlag = (bool)$eventResult;
453
            }
454
            if (!$pluginFlag) {
455
                $hashType = $this->getPasswordHashType($_password);
456
                switch ($hashType) {
457
                    case 'phpass':
458
                        $flag = $this->modx->phpass->CheckPassword($password, $_password);
459
                        break;
460
                    case 'md5':
461
                        $flag = $_password == md5($password);
462
                        break;
463
                    case 'v1':
464
                        $algorithm = \APIhelpers::getkey($this->modx->config, 'pwd_hash_algo', 'UNCRYPT');
465
                        $userAlgorithm = $this->getPasswordHashAlgorithm($_password);
466
                        if ($algorithm !== $userAlgorithm) {
467
                            $algorithm = $userAlgorithm;
468
                        }
469
                        $flag = $_password == $this->makeHash($password, $tmp->getID(), $algorithm);
470
                        break;
471
                }
472
                if ($flag && $hashType == 'md5' || $hashType == 'v1') {
473
                    $tmp->set('password', $password)->save();
474
                    if ($id == $this->getID()) {
475
                        $this->field['password'] = $tmp->get('password');
476
                    }
477
                }
478
            }
479
        }
480
        unset($tmp);
481
482
        return $flag || $pluginFlag;
483
    }
484
485
    /**
486
     * @param string $cookieName
487
     * @param bool $fire_events
488
     */
489
    public function logOut($cookieName = 'modx_remember_manager', $fire_events = false)
1 ignored issue
show
Coding Style introduced by
logOut uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
490
    {
491
        if (!$uid = $this->modx->getLoginUserID('mgr')) {
492
            return;
493
        }
494
        $params = array(
495
            'username'    => $_SESSION['mgrShortname'],
496
            'internalKey' => $uid
497
        );
498
        $this->invokeEvent('OnBeforeManagerLogout', $params, $fire_events);
499
        $this->SessionHandler('destroy', $cookieName ? $cookieName : 'modx_remember_manager');
500
        $this->modx->db->delete($this->modx->getFullTableName('active_user_locks'), "sid = '{$this->modx->sid}'");
501
        // Clean up active_user_sessions
502
        $this->modx->db->delete($this->modx->getFullTableName('active_user_sessions'), "sid = '{$this->modx->sid}'");
503
        $this->invokeEvent('OnManagerLogout', $params, $fire_events);
504
    }
505
506
    /**
507
     * SessionHandler
508
     * Starts the user session on login success. Destroys session on error or logout.
509
     *
510
     * @param string $directive ('start' or 'destroy')
511
     * @param string $cookieName
512
     * @param bool|integer $remember
513
     * @return modUsers
514
     * @author Raymond Irving
515
     * @author Scotty Delicious
516
     *
517
     * remeber может быть числом в секундах
518
     */
519
    protected function SessionHandler($directive, $cookieName, $remember = true)
2 ignored issues
show
Coding Style introduced by
SessionHandler uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
SessionHandler uses the super-global variable $_COOKIE which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
520
    {
521
        switch ($directive) {
522
            case 'start':
523
                if ($this->getID() !== null) {
524
                    $_SESSION['usertype'] = 'manager';
525
                    $_SESSION['mgrShortname'] = $this->get('username');
526
                    $_SESSION['mgrFullname'] = $this->get('fullname');
527
                    $_SESSION['mgrEmail'] = $this->get('email');
528
                    $_SESSION['mgrValidated'] = 1;
529
                    $_SESSION['mgrInternalKey'] = $this->getID();
530
                    $_SESSION['mgrFailedlogins'] = $this->get('failedlogincount');
531
                    $_SESSION['mgrLastlogin'] = $this->get('lastlogin');
532
                    $_SESSION['mgrLogincount'] = $this->get('logincount');
533
                    $_SESSION['mgrRole'] = $this->get('role');
534
                    $_SESSION['mgrPermissions'] = $this->mgrPermissions;
535
                    $_SESSION['mgrDocgroups'] = $this->getDocumentGroups();
536
                    $_SESSION['mgrToken'] = md5($this->get('sessionid'));
537
                    if (!empty($remember)) {
538
                        $this->setAutoLoginCookie($cookieName, $remember);
539
                    }
540
                }
541
                break;
542
            case 'destroy':
543
                if (isset($_SESSION['mgrValidated'])) {
544
                    unset($_SESSION['usertype']);
545
                    unset($_SESSION['mgrShortname']);
546
                    unset($_SESSION['mgrFullname']);
547
                    unset($_SESSION['mgrEmail']);
548
                    unset($_SESSION['mgrValidated']);
549
                    unset($_SESSION['mgrInternalKey']);
550
                    unset($_SESSION['mgrFailedlogins']);
551
                    unset($_SESSION['mgrLastlogin']);
552
                    unset($_SESSION['mgrLogincount']);
553
                    unset($_SESSION['mgrDocgroups']);
554
                    unset($_SESSION['mgrPermissions']);
555
                    unset($_SESSION['mgrToken']);
556
                    setcookie($cookieName, '', time() - 60, MODX_BASE_URL);
557
                } else {
558
                    if (isset($_COOKIE[session_name()])) {
559
                        setcookie(session_name(), '', time() - 60, MODX_BASE_URL);
560
                    }
561
                    setcookie($cookieName, '', time() - 60, MODX_BASE_URL);
562
                    session_destroy();
563
                }
564
                break;
565
        }
566
567
        return $this;
568
    }
569
570
    /**
571
     * @return bool
572
     */
573
    public function isSecure()
574
    {
575
        $out = $this->modxConfig('server_protocol') == 'http' ? false : true;
576
577
        return $out;
578
    }
579
580
    /**
581
     * @param $cookieName
582
     * @param bool|integer $remember
583
     * @return $this
584
     */
585
    public function setAutoLoginCookie($cookieName, $remember = true)
586
    {
587
        if (!empty($cookieName) && $this->getID() !== null) {
588
            $secure = $this->isSecure();
589
            $remember = is_bool($remember) ? $this->getRememberTime() : (int)$remember;
590
            $cookieValue = $this->get('username');
591
            $cookieExpires = time() + $remember;
592
            setcookie($cookieName, $cookieValue, $cookieExpires, MODX_BASE_URL, '', $secure, true);
593
        }
594
595
        return $this;
596
    }
597
598
    /**
599
     * @param int $userID
600
     * @return array
601
     */
602
    public function getDocumentGroups($userID = 0)
603
    {
604
        $out = array();
605
        $user = $this->switchObject($userID);
606
        if (null !== $user->getID()) {
607
            $member_groups = $this->modx->getFullTableName('member_groups');
608
            $membergroup_access = $this->modx->getFullTableName('membergroup_access');
609
610
            $sql = "SELECT `uga`.`documentgroup` FROM {$member_groups} as `ug`
611
                INNER JOIN {$membergroup_access} as `uga` ON `uga`.`membergroup`=`ug`.`user_group` WHERE `ug`.`member` = " . $user->getID();
612
            $out = $this->modx->db->getColumn('documentgroup', $this->query($sql));
613
614
        }
615
        unset($user);
616
617
        return $out;
618
    }
619
620
    /**
621
     * @param int $userID
622
     * @return array
623
     */
624
    public function getUserGroups($userID = 0)
625
    {
626
        $out = array();
627
        $user = $this->switchObject($userID);
628
        if (null !== $user->getID()) {
629
            $member_groups = $this->makeTable('member_groups');
630
            $membergroup_names = $this->makeTable('membergroup_names');
631
632
            $rs = $this->query("SELECT `ug`.`user_group`, `ugn`.`name` FROM {$member_groups} as `ug`
633
                INNER JOIN {$membergroup_names} as `ugn` ON `ugn`.`id`=`ug`.`user_group`
634
                WHERE `ug`.`member` = " . $user->getID());
635
            while ($row = $this->modx->db->getRow($rs)) {
636
                $out[$row['user_group']] = $row['name'];
637
            }
638
        }
639
        unset($user);
640
641
        return $out;
642
    }
643
644
    /**
645
     * @param int $userID
646
     * @param array $groupIds
647
     * @return $this
648
     */
649
    public function setUserGroups($userID = 0, $groupIds = array())
650
    {
651
        if (!is_array($groupIds)) {
652
            return $this;
653
        }
654
        if ($this->newDoc && $userID == 0) {
655
            $this->groupIds = $groupIds;
656
        } else {
657
            $user = $this->switchObject($userID);
658
            if ($uid = $user->getID()) {
659
                foreach ($groupIds as $gid) {
660
                    $this->query("REPLACE INTO {$this->makeTable('member_groups')} (`user_group`, `member`) VALUES ('{$gid}', '{$uid}')");
661
                }
662
                if (!$this->newDoc) {
663
                    $groupIds = empty($groupIds) ? '0' : implode(',', $groupIds);
664
                    $this->query("DELETE FROM {$this->makeTable('member_groups')} WHERE `member`={$uid} AND `user_group` NOT IN ({$groupIds})");
665
                }
666
            }
667
            unset($user);
668
            $this->groupIds = array();
669
        }
670
671
        return $this;
672
    }
673
674
    /**
675
     * @param string $pass
676
     * @return string
677
     */
678
    public function getPasswordHashType($pass)
679
    {
680
        $out = 'unknown';
681
        if (substr($pass, 0, 1) === '$') {
682
            $out = 'phpass';
683
        } elseif (strpos($pass, '>') !== false) {
684
            $out = 'v1';
685
        } elseif (strlen($pass) === 32) {
686
            $out = 'md5';
687
        }
688
689
        return $out;
690
    }
691
692
    /**
693
     * @param string $pass
694
     * @return string
695
     */
696
    public function getPasswordHashAlgorithm($pass)
697
    {
698
        $pointer = strpos($pass, '>');
699
        $out = $pointer === false ? 'NOSALT' : substr($pass, 0, $pointer);
700
701
        return strtoupper($out);
702
    }
703
704
    /**
705
     * @param string $pass
706
     * @param int $seed
707
     * @param string $algorithm
708
     * @return string
709
     */
710
    public function makeHash($pass, $seed, $algorithm)
711
    {
712
        $salt = md5($pass . $seed);
713
714
        switch ($algorithm) {
715
            case 'BLOWFISH_Y':
716
                $salt = '$2y$07$' . substr($salt, 0, 22);
717
                break;
718
            case 'BLOWFISH_A':
719
                $salt = '$2a$07$' . substr($salt, 0, 22);
720
                break;
721
            case 'SHA512':
722
                $salt = '$6$' . substr($salt, 0, 16);
723
                break;
724
            case 'SHA256':
725
                $salt = '$5$' . substr($salt, 0, 16);
726
                break;
727
            case 'MD5':
728
                $salt = '$1$' . substr($salt, 0, 8);
729
                break;
730
            default:
731
                $algorithm = 'UNCRYPT';
732
                break;
733
        }
734
735
        $pass = $algorithm !== 'UNCRYPT' ? sha1($pass) . crypt($pass, $salt) : sha1($salt . $pass);
736
        $out = strtolower($algorithm) . '>' . md5($salt . $pass) . substr(md5($salt), 0, 8);
737
738
        return $out;
739
    }
740
741
742
}
743