user.php 66 KB
Newer Older
1
2
3
4
5
<?php
/**
 *
 * @package    mahara
 * @subpackage core
6
 * @author     Catalyst IT Ltd
7
8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9
10
11
12
 *
 */

defined('INTERNAL') || die();
13
define('MAXLOGINTRIES', 5);
Donal McMullan's avatar
Donal McMullan committed
14
15
$put = array();

16
17

/**
Donal McMullan's avatar
Donal McMullan committed
18
 * The user class represents any user in the system.
19
20
21
 *
 */
class User {
Donal McMullan's avatar
Donal McMullan committed
22

23
24
25
26
27
    /**
     * Defaults for user information.
     *
     * @var array
     */
Donal McMullan's avatar
Donal McMullan committed
28
29
30
31
32
    protected $defaults;
    protected $stdclass;
    protected $authenticated = false;
    protected $changed       = false;
    protected $attributes    = array();
33
34
35
36
37

    /**
     * Sets defaults for the user object (only because PHP5 does not appear
     * to support private static const arrays), and resumes a session
     */
Donal McMullan's avatar
Donal McMullan committed
38
    public function __construct() {
39
        $this->defaults = array(
40
41
42
43
            'logout_time'      => 0,
            'id'               => 0,
            'username'         => '',
            'password'         => '',
Donal McMullan's avatar
Donal McMullan committed
44
            'salt'             => '',
Donal McMullan's avatar
Donal McMullan committed
45
            'passwordchange'   => 0,
Donal McMullan's avatar
Donal McMullan committed
46
            'active'           => 1,
Donal McMullan's avatar
Donal McMullan committed
47
            'deleted'          => 0,
48
            'expiry'           => null,
49
            'expirymailsent'   => 0,
50
            'lastlogin'        => null,
51
            'lastlastlogin'    => null,
52
            'lastaccess'       => null, /* Is not necessarily updated every request, see accesstimeupdatefrequency config variable */
53
            'inactivemailsent' => 0,
Donal McMullan's avatar
Donal McMullan committed
54
55
            'staff'            => 0,
            'admin'            => 0,
56
57
            'firstname'        => '',
            'lastname'         => '',
Donal McMullan's avatar
Donal McMullan committed
58
            'studentid'        => '',
59
60
            'preferredname'    => '',
            'email'            => '',
Donal McMullan's avatar
Donal McMullan committed
61
62
63
64
            'profileicon'      => null,
            'suspendedctime'   => null,
            'suspendedreason'  => null,
            'suspendedcusr'    => null,
65
            'quota'            => null,
Donal McMullan's avatar
Donal McMullan committed
66
67
68
            'quotaused'        => 0,
            'authinstance'     => 1,
            'sessionid'        => '', /* The real session ID that PHP knows about */
69
70
            'accountprefs'     => array(),
            'activityprefs'    => array(),
71
            'institutions'     => array(),
72
            'grouproles'       => array(),
73
            'institutiontheme' => null,
74
            'admininstitutions' => array(),
75
            'staffinstitutions' => array(),
Richard Mansfield's avatar
Richard Mansfield committed
76
            'parentuser'       => null,
77
            'loginanyway'       => false,
78
            'sesskey'          => '',
Richard Mansfield's avatar
Richard Mansfield committed
79
            'ctime'            => null,
80
            'views'            => array(),
81
82
            'showhomeinfo'     => 1,
            'unread'           => 0,
83
            'urlid'            => null,
84
            'probation'        => 0,
85
        );
Donal McMullan's avatar
Donal McMullan committed
86
87
88
89
90
        $this->attributes = array();

    }

    /**
Aaron Wells's avatar
Aaron Wells committed
91
     *
Donal McMullan's avatar
Donal McMullan committed
92
     */
Donal McMullan's avatar
Donal McMullan committed
93
    public function find_by_id($id) {
94

Donal McMullan's avatar
Donal McMullan committed
95
96
97
        if (!is_numeric($id) || $id < 0) {
            throw new InvalidArgumentException('parameter must be a positive integer to create a User object');
        }
Donal McMullan's avatar
Donal McMullan committed
98

99
        $sql = 'SELECT
Aaron Wells's avatar
Aaron Wells committed
100
101
102
                    *,
                    ' . db_format_tsfield('expiry') . ',
                    ' . db_format_tsfield('lastlogin') . ',
103
104
                    ' . db_format_tsfield('lastlastlogin') . ',
                    ' . db_format_tsfield('lastaccess') . ',
Richard Mansfield's avatar
Richard Mansfield committed
105
106
                    ' . db_format_tsfield('suspendedctime') . ',
                    ' . db_format_tsfield('ctime') . '
107
                FROM
108
                    {usr}
109
110
111
                WHERE
                    id = ?';

112
        $user = get_record_sql($sql, array($id));
113

Donal McMullan's avatar
Donal McMullan committed
114
115
116
117
        if (false == $user) {
            throw new AuthUnknownUserException("User with id \"$id\" is not known");
        }

Donal McMullan's avatar
Donal McMullan committed
118
        $this->populate($user);
119
        $this->reset_institutions();
120
        $this->reset_grouproles();
Donal McMullan's avatar
Donal McMullan committed
121
122
        return $this;
    }
123

124
    /**
Aaron Wells's avatar
Aaron Wells committed
125
     * Populates this object with the user record identified by the given
126
127
     * username
     *
Aaron Wells's avatar
Aaron Wells committed
128
     * @throws AuthUnknownUserException If the user cannot be found. Note that
129
130
131
132
133
134
135
136
137
138
139
140
     *                                  deleted users _can_ be found
     */
    public function find_by_username($username) {

        if (!is_string($username)) {
            throw new InvalidArgumentException('username parameter must be a string to create a User object');
        }

        $sql = 'SELECT
                    *,
                    ' . db_format_tsfield('expiry') . ',
                    ' . db_format_tsfield('lastlogin') . ',
141
                    ' . db_format_tsfield('lastlastlogin') . ',
142
                    ' . db_format_tsfield('lastaccess') . ',
Richard Mansfield's avatar
Richard Mansfield committed
143
144
                    ' . db_format_tsfield('suspendedctime') . ',
                    ' . db_format_tsfield('ctime') . '
145
146
147
148
149
                FROM
                    {usr}
                WHERE
                    username = ?';

150
        $user = get_record_sql($sql, array($username));
151
152
153
154
155
156
157
158
159
160

        if (false == $user) {
            throw new AuthUnknownUserException("User with username \"$username\" is not known");
        }

        $this->populate($user);
        $this->reset_institutions();
        return $this;
    }

161
    /**
Aaron Wells's avatar
Aaron Wells committed
162
     * Finds details for a user given a username and their authentication
163
164
     * instance.
     *
Aaron Wells's avatar
Aaron Wells committed
165
     * If the authentication instance is a child or a parent, its relation is
166
     * checked too, because the user can enter the system by either method.
167
     */
168
    public function find_by_instanceid_username($instanceid, $username, $remoteuser=false) {
169
170
171
172
173

        if (!is_numeric($instanceid) || $instanceid < 0) {
            throw new InvalidArgumentException('parameter must be a positive integer to create a User object');
        }

174
        $username = strtolower($username);
175
        if ($remoteuser) {
Aaron Wells's avatar
Aaron Wells committed
176
177
178
179
180
            // See if the user has either the child or the parent authinstance.
            // Most of the time, it's the parent auth instance that is
            // stored with the user, but if they were created by (for
            // example) SSO with no parent, then it will be the child that
            // is stored. Nevertheless, a parent could be added later, and
181
182
            // that should not matter in finding the user
            $parentwhere = '';
183
            if ($parentid = get_field('auth_instance_config', 'value', 'field', 'parent', 'instance', $instanceid)) {
184
185
186
                $parentwhere = '
                            OR
                            (
187
188
                                LOWER(username) = (
                                    SELECT
189
                                        LOWER(username)
190
191
192
193
194
                                    FROM
                                        {usr} us
                                    JOIN
                                        {auth_remote_user} aru ON (us.id = aru.localusr)
                                    WHERE
195
                                        LOWER(aru.remoteusername) = ' . db_quote($username) . '
196
197
                                        AND us.authinstance = ' . db_quote($parentid) . '
                                )
198
                                AND u.authinstance = ' . db_quote($parentid) . '
199
200
                            )
                    ';
201
            }
202

203
            $sql = 'SELECT
Aaron Wells's avatar
Aaron Wells committed
204
                        u.*,
205
206
207
208
                        ' . db_format_tsfield('u.expiry', 'expiry') . ',
                        ' . db_format_tsfield('u.lastlogin', 'lastlogin') . ',
                        ' . db_format_tsfield('u.lastlastlogin', 'lastlastlogin') . ',
                        ' . db_format_tsfield('u.lastaccess', 'lastaccess') . ',
209
                        ' . db_format_tsfield('u.suspendedctime', 'suspendedctime') . ',
Richard Mansfield's avatar
Richard Mansfield committed
210
                        ' . db_format_tsfield('u.ctime', 'ctime') . '
211
                    FROM {usr} u
212
                    LEFT JOIN {auth_remote_user} r ON u.id = r.localusr
213
                    WHERE
214
215
                        (
                            (
216
                                LOWER(r.remoteusername) = ?
217
218
219
220
                                AND r.authinstance = ?
                            )'
                            . $parentwhere
                            . '
221
                        )';
222
223
224
            $user = get_record_sql($sql, array($username, $instanceid));
        }
        else {
225
            $sql = 'SELECT
Aaron Wells's avatar
Aaron Wells committed
226
                        *,
227
228
229
230
                        ' . db_format_tsfield('expiry') . ',
                        ' . db_format_tsfield('lastlogin') . ',
                        ' . db_format_tsfield('lastlastlogin') . ',
                        ' . db_format_tsfield('lastaccess') . ',
Richard Mansfield's avatar
Richard Mansfield committed
231
232
                        ' . db_format_tsfield('suspendedctime') . ',
                        ' . db_format_tsfield('ctime') . '
233
234
235
236
                    FROM
                        {usr}
                    WHERE
                        LOWER(username) = ? AND
237
238
                        authinstance = ?';
            $user = get_record_sql($sql, array($username, $instanceid));
239
240
        }

241
242
243
244
245
246
247
248
        if (false == $user) {
            throw new AuthUnknownUserException("User with username \"$username\" is not known at auth instance \"$instanceid\"");
        }

        $this->populate($user);
        return $this;
    }

249
    /**
250
     * Populates this object with the user record identified by a mobile 'token'
251
     *
Aaron Wells's avatar
Aaron Wells committed
252
     * @throws AuthUnknownUserException If the user cannot be found.
253
     */
254
    public function find_by_mobileuploadtoken($token, $username) {
255
256
257
258
259
260

        if (!is_string($token)) {
            throw new InvalidArgumentException('Input parameters must be strings to create a User object from token');
        }

        $sql = 'SELECT
261
                        u.*,
262
263
264
265
266
267
268
269
270
                        ' . db_format_tsfield('u.expiry', 'expiry') . ',
                        ' . db_format_tsfield('u.lastlogin', 'lastlogin') . ',
                        ' . db_format_tsfield('u.lastlastlogin', 'lastlastlogin') . ',
                        ' . db_format_tsfield('u.lastaccess', 'lastaccess') . ',
                        ' . db_format_tsfield('u.suspendedctime', 'suspendedctime') . ',
                        ' . db_format_tsfield('u.ctime', 'ctime') . '
                FROM
                    {usr} u
                    LEFT JOIN {usr_account_preference} p ON u.id = p.usr
271
272
                            WHERE p.field=\'mobileuploadtoken\'
                              AND p.value ' . db_ilike() . ' \'%|\' || ? || \'|%\' AND u.username = ?
273
274
		';

275
        $user = get_record_sql($sql, array($token, $username));
276
277
278
279
280
281

        if (false == $user) {
            throw new AuthUnknownUserException("User with mobile upload token \"$token\" is not known");
        }

        $this->populate($user);
282
        $this->accountprefs = load_account_preferences($user->id);
283
284
285
        return $this;
    }

286
287
288
289
    /**
     * Refreshes a users mobile 'token' and returns it
     *
     */
290
291
292
293
294
295
296
297
298
299
300
    public function refresh_mobileuploadtoken($old_token) {
        $new_token = md5(openssl_random_pseudo_bytes(8));
        $old_tokenstring = $this->get_account_preference('mobileuploadtoken');
        $tokenarray = explode('|', trim($old_tokenstring, '|'));
        foreach ($tokenarray as $k => $v) {
            if ( $v == $old_token ) {
                $tokenarray[$k] = $new_token;
            }
        }
        $new_tokenstring = empty($tokenarray) ? null : ('|' . join('|', $tokenarray) . '|');
        $this->set_account_preference('mobileuploadtoken', $new_tokenstring);
301
        $this->set('lastaccess', time());
302
303
        $this->commit();
        return $new_token;
304
    }
305

Richard Mansfield's avatar
Richard Mansfield committed
306
307
308
309
310
    /**
     * Set stuff that needs to be initialised once before a user record is created.
     */
    public function create() {
        $this->set('ctime', time());
311
312
313
314
        if (get_config('cleanurls') && is_null($this->urlid)) {
            $desiredurlid = generate_urlid($this->username, get_config('cleanurluserdefault'), 3, 30);
            $this->set('urlid', get_new_profile_urlid($desiredurlid));
        }
Richard Mansfield's avatar
Richard Mansfield committed
315
316
317
    }


Donal McMullan's avatar
Donal McMullan committed
318
319
320
321
322
323
324
325
326
327
328
329
330
    /**
     * Take a row object from the usr table and populate this object with the
     * values
     *
     * @param  object $data  The row data
     */
    protected function populate($data) {
        reset($this->defaults);
        while(list($key, ) = each($this->defaults)) {
            if (property_exists($data, $key)) {
                $this->set($key, $data->{$key});
            }
        }
331
    }
Donal McMullan's avatar
Donal McMullan committed
332

333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
    /**
     * Convert from a row object from the usr table
     *
     * @param  object $data  The row data
     */
    public function from_stdclass($data) {
        foreach (array('expiry', 'lastlogin', 'lastlastlogin', 'lastaccess', 'suspendedctime', 'ctime') as $f) {
            if (isset($data->$f) && !is_numeric($data->$f)) {
                $data->$f = strtotime($data->$f);
            }
        }
        $this->populate($data);
        return $this;
    }

348
349
350
351
352
    /**
     * Gets the user property keyed by $key.
     *
     * @param string $key The key to get the value of
     * @return mixed
Nigel McNie's avatar
Nigel McNie committed
353
     * @throws InvalidArgumentException
354
355
     */
    public function get($key) {
Donal McMullan's avatar
Donal McMullan committed
356
        if (!array_key_exists($key, $this->defaults)) {
357
            throw new InvalidArgumentException($key);
358
        }
Donal McMullan's avatar
Donal McMullan committed
359
360
        if (array_key_exists($key, $this->attributes) && null !== $this->attributes[$key]) {
            return $this->attributes[$key];
361
362
363
364
        }
        return $this->defaults[$key];
    }

Donal McMullan's avatar
Donal McMullan committed
365
366
367
368
369
370
371
372
373
374
375
    /**
     * Gets the user property keyed by $key.
     *
     * @param string $key The key to get the value of
     * @return mixed
     * @throws InvalidArgumentException
     */
    public function __get($key) {
        return $this->get($key);
    }

376
377
378
    /**
     * Sets the property keyed by $key
     */
Donal McMullan's avatar
Donal McMullan committed
379
380
381
    protected function set($key, $value) {

        if (!array_key_exists($key, $this->defaults)) {
382
            throw new InvalidArgumentException($key);
383
        }
Donal McMullan's avatar
Donal McMullan committed
384
385
386
387

        $this->attributes[$key] = $value;

        // For now, these fields are saved to the DB elsewhere
388
        if ($key != 'activityprefs' && $key != 'accountprefs' && $key != 'views') {
Donal McMullan's avatar
Donal McMullan committed
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
            $this->changed = true;
        }
        return $this;
    }

    /**
     * Sets the property keyed by $key
     */
    public function __set($key, $value) {
        if ($key == 'quotaused') {
            throw new InvalidArgumentException('quotaused should be set via the quota_* methods');
        }

        $this->set($key, $value);
    }

    /**
     * Commit the USR record to the database
     */
    public function commit() {
        if ($this->changed == false) {
            return;
        }
Donal McMullan's avatar
Donal McMullan committed
412
        $record = $this->to_stdclass();
Donal McMullan's avatar
Donal McMullan committed
413
        if (is_numeric($this->id) && 0 < $this->id) {
Donal McMullan's avatar
Donal McMullan committed
414
415
416
417
418
419
            try {
                update_record('usr', $record, array('id' => $this->id));
            } catch (Exception $e) {
                throw $e;
                //var_dump($e);
            }
Donal McMullan's avatar
Donal McMullan committed
420
        } else {
Donal McMullan's avatar
Donal McMullan committed
421
422
            try {
                $this->set('id', insert_record('usr', $record, 'id', true));
Donal McMullan's avatar
Donal McMullan committed
423
424
            } catch (SQLException $e) {
                throw $e;
Donal McMullan's avatar
Donal McMullan committed
425
            }
Donal McMullan's avatar
Donal McMullan committed
426
427
        }
        $this->changed = false;
428
429
    }

Aaron Wells's avatar
Aaron Wells committed
430
    /**
431
432
     * This function returns a method for a particular
     * activity type, or null if it's not set.
Aaron Wells's avatar
Aaron Wells committed
433
     *
434
     * @param int $key the activity type id
435
436
437
     */
    public function get_activity_preference($key) {
        $activityprefs = $this->get('activityprefs');
438
        return array_key_exists($key, $activityprefs) ? $activityprefs[$key] : false;
439
    }
Donal McMullan's avatar
Donal McMullan committed
440

441
442
443
444
445
446
447
448
    /** @todo document this method */
    public function set_activity_preference($activity, $method) {
        set_activity_preference($this->get('id'), $activity, $method);
        $activityprefs = $this->get('activityprefs');
        $activityprefs[$activity] = $method;
        $this->set('activityprefs', $activityprefs);
    }

Aaron Wells's avatar
Aaron Wells committed
449
    /**
450
451
     * This function returns a value for a particular
     * account preference, or null if it's not set.
Aaron Wells's avatar
Aaron Wells committed
452
     *
453
454
455
456
457
458
     * @param string $key the field name
     */
    public function get_account_preference($key) {
        $accountprefs = $this->get('accountprefs');
        return isset($accountprefs[$key]) ? $accountprefs[$key] : null;
    }
Donal McMullan's avatar
Donal McMullan committed
459

460
461
    /** @todo document this method */
    public function set_account_preference($field, $value) {
462
463
464
        if ($id = $this->get('id')) {
            set_account_preference($id, $field, $value);
        }
465
466
467
        $accountprefs = $this->get('accountprefs');
        $accountprefs[$field] = $value;
        $this->set('accountprefs', $accountprefs);
468
469
    }

470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488

    public function get_view_by_type($viewtype) {
        $views = $this->get('views');
        if (isset($views[$viewtype])) {
            $viewid = $views[$viewtype];
        }
        else {
            $viewid = get_field('view', 'id', 'type', $viewtype, 'owner', $this->get('id'));
        }
        if (!$viewid) {
            global $USER;
            if (!$USER->get('id')) {
                return null;
            }
            return $this->install_view($viewtype);
        }
        return new View($viewid);
    }

489
490
491
492
493
494
495
496
    /**
     * Return the profile view object for this user.
     *
     * If the user does not yet have a profile view, one is created for them.
     *
     * @return View
     */
    public function get_profile_view() {
497
        return $this->get_view_by_type('profile');
498
499
500
501
502
503
504
    }

    /**
     * Installs a user's profile view.
     *
     * @return View
     */
505
    protected function install_profile_view() {
506
507
        static $systemprofileviewid = null;

508
        db_begin();
509
510
511
512
513
514
515
516
        if (is_null($systemprofileviewid)) {
            $systemprofileviewid = get_field('view', 'id', 'owner', 0, 'type', 'profile');
        }

        require_once(get_config('libroot') . 'view.php');
        list($view) = View::create_from_template(array(
            'owner' => $this->get('id'),
            'title' => get_field('view', 'title', 'id', $systemprofileviewid),
517
            'description' => get_string('profiledescription'),
518
            'type'  => 'profile',
519
        ), $systemprofileviewid, $this->get('id'), false);
520

521
        // Set view access
522
523
        $access = array(
            array(
524
525
526
                'type'      => 'loggedin',
                'startdate' => null,
                'stopdate'  => null,
527
528
            ),
        );
529
530
531
532
533
534
535
536
537
538
539
540
        if ($institutions = $this->get('institutions')) {
            foreach ($institutions as $i) {
                $access[] = array(
                    'type'      => 'institution',
                    'id'        => $i->institution,
                    'startdate' => null,
                    'stopdate'  => null,
                );
            }
        }
        $view->set_access($access);

541
        db_commit();
542
543
544
545

        return $view;
    }

546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
    /**
     * Return the dashboard view object for this user.
     *
     * If the user does not yet have a dashboard view, one is created for them.
     *
     * @return View
     */

    /**
     * Installs a user's dashboard view.
     *
     * @return View
     */
    protected function install_dashboard_view() {
        static $systemdashboardviewid = null;

        db_begin();
        if (is_null($systemdashboardviewid)) {
            $systemdashboardviewid = get_field('view', 'id', 'owner', 0, 'type', 'dashboard');
        }

        require_once(get_config('libroot') . 'view.php');
        list($view) = View::create_from_template(array(
            'owner' => $this->get('id'),
            'title' => get_field('view', 'title', 'id', $systemdashboardviewid),
571
            'description' => get_string('dashboarddescription'),
572
            'type'  => 'dashboard',
573
        ), $systemdashboardviewid, $this->get('id'), false);
574
575
576
577
578

        db_commit();

        return $view;
    }
579

580
581
582
583
    protected function install_view($viewtype) {
        $function = 'install_' . $viewtype . '_view';
        return $this->$function();
    }
584

585
586
587
588
589
590
    // Store the ids of the user's special views (profile, dashboard).  Users can have only
    // one each of these, so there really should be columns in the user table to store them.
    protected function load_views() {
        $types = array('profile', 'dashboard');
        $views = get_records_select_assoc(
            'view',
Francois Marier's avatar
Francois Marier committed
591
            '"owner" = ? AND type IN (' . join(',', array_map('db_quote', $types)) . ')',
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
            array($this->id),
            '',
            'type,id'
        );

        $specialviews = array();
        foreach ($types as $type) {
            if (!empty($views[$type])) {
                $specialviews[$type] = $views[$type]->id;
            }
            else {
                $view = $this->install_view($type);
                $specialviews[$type] = $view->get('id');
            }
        }
        $this->set('views', $specialviews);
    }
609

610
611
612
613
614
615
616
617
    /**
     * Determines if the user is currently logged in
     *
     * @return boolean
     */
    public function is_logged_in() {
        return ($this->get('logout_time') > 0 ? true : false);
    }
Donal McMullan's avatar
Donal McMullan committed
618

619
    public function to_stdclass() {
Donal McMullan's avatar
Donal McMullan committed
620
621
622
        $this->stdclass = new StdClass;
        reset($this->defaults);
        foreach (array_keys($this->defaults) as $k) {
Richard Mansfield's avatar
Richard Mansfield committed
623
            if ($k == 'expiry' || $k == 'lastlogin' || $k == 'lastlastlogin' || $k == 'lastaccess' || $k == 'suspendedctime' || $k == 'ctime') {
Donal McMullan's avatar
Donal McMullan committed
624
625
626
627
                $this->stdclass->{$k} = db_format_timestamp($this->get($k));
            } else {
                $this->stdclass->{$k} = $this->get($k);//(is_null($this->get($k))? 'NULL' : $this->get($k));
            }
628
629
630
        }
        return $this->stdclass;
    }
631

Martyn Smith's avatar
Martyn Smith committed
632
633
634
635
636
637
638
639
    public function quota_add($bytes) {
        if (!is_numeric($bytes) || $bytes < 0) {
            throw new InvalidArgumentException('parameter must be a positive integer to add to the quota');
        }
        if (!$this->quota_allowed($bytes)) {
            throw new QuotaExceededException('Adding ' . $bytes . ' bytes would exceed the user\'s quota');
        }
        $newquota = $this->get('quotaused') + $bytes;
Donal McMullan's avatar
Donal McMullan committed
640
641
        $this->set("quotaused", $newquota);
        return $this;
Martyn Smith's avatar
Martyn Smith committed
642
643
644
645
646
647
648
649
650
651
    }

    public function quota_remove($bytes) {
        if (!is_numeric($bytes) || $bytes < 0) {
            throw new InvalidArgumentException('parameter must be a positive integer to remove from the quota');
        }
        $newquota = $this->get('quotaused') - $bytes;
        if ($newquota < 0) {
            $newquota = 0;
        }
Donal McMullan's avatar
Donal McMullan committed
652
653
        $this->set("quotaused", $newquota);
        return $this;
Martyn Smith's avatar
Martyn Smith committed
654
655
656
657
658
659
660
661
662
    }

    public function quota_allowed($bytes) {
        if ($this->get('quotaused') + $bytes > $this->get('quota')) {
            return false;
        }

        return true;
    }
663

664
665
666
667
668
669
670
671
    public function quota_init() {
        if (!$this->get('quota')) {
            if ($defaultquota = get_config_plugin('artefact', 'file', 'defaultquota')) {
                $this->set('quota', $defaultquota);
            }
        }
    }

672
673
674
675
676
677
    public function quota_refresh() {
        $quotadata = get_record_sql('SELECT quota, quotaused FROM {usr} WHERE id = ?', array($this->get('id')));
        $this->set('quota', $quotadata->quota);
        $this->set("quotaused", $quotadata->quotaused);
    }

678
    public function join_institution($institution) {
679
        if ($institution != 'mahara' && !$this->in_institution($institution)) {
680
            require_once('institution.php');
681
682
            $institution = new Institution($institution);
            $institution->addUserAsMember($this);
683
            $this->reset_institutions();
684
685
686
        }
    }

687
688
689
690
    public function leave_institution($institution) {
        if ($institution != 'mahara' && $this->in_institution($institution)) {
            require_once('institution.php');
            $institution = new Institution($institution);
691
            $institution->removeMember($this->to_stdclass());
692
693
694
        }
    }

695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
    /**
     * Get institution name by checking which 'institution theme' a user is allocated to see
     * and if that theme has sitepages set.
     * Or if a lastinstitution cookie is set. Or if an institution url parameter is set.
     * Defaults to 'mahara'.
     *
     * @return string   Institution name
     */
    public function sitepages_institutionname_by_theme($page) {
        // get institution when logged in
        if ($this->is_logged_in()) {
            if ($theme = $this->get('institutiontheme')) {
                if (!empty($theme->institutionname)) {
                    // check to see if institution is using it's own site pages or default site pages
                    if ($institution = get_record('institution', 'name', $theme->institutionname)) {
                        if (get_config_institution($institution->name, 'sitepages_' . $page)) {
                            return get_config_institution($institution->name, 'sitepages_' . $page);
                        }
                    }
                    else {
                        return $theme->institutionname;
                    }
                }
                else {
                    return 'mahara';
                }
            }
        }
        // or from url
        if ($institution = param_alphanum('institution', null)) {
            return $institution;
        }
        // or from cookie
        if ($institution = get_cookie('lastinstitution')) {
            return $institution;
        }
        return 'mahara';
    }

734
735
    public function in_institution($institution, $role = null) {
        $institutions = $this->get('institutions');
Aaron Wells's avatar
Aaron Wells committed
736
        return isset($institutions[$institution])
737
738
739
            && (is_null($role) || $institutions[$institution]->{$role});
    }

740
    public function is_institutional_admin($institution = null) {
741
        $a = $this->get('admininstitutions');
742
743
744
745
        if (is_null($institution)) {
            return !empty($a);
        }
        return isset($a[$institution]);
746
    }
747

748
749
750
751
752
753
754
755
    public function is_institutional_staff($institution = null) {
        $a = $this->get('staffinstitutions');
        if (is_null($institution)) {
            return !empty($a);
        }
        return isset($a[$institution]);
    }

756
757
758
759
    public function can_edit_institution($institution = null, $staff = false) {
        if ($staff) {
            return $this->get('admin') || $this->get('staff') || $this->is_institutional_admin($institution) || $this->is_institutional_staff($institution);
        }
760
761
762
        return $this->get('admin') || $this->is_institutional_admin($institution);
    }

763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
    public function institution_allows_public_views($institution = null) {
        $user_institutions = $this->get('institutions');
        if (empty($user_institutions)) {
            // user belongs to no institutions
            return true;
        }
        else if (is_null($institution) || !isset($user_institutions[$institution->institution])) {
            foreach ($user_institutions as $institution) {
                if ($institution->allowinstitutionpublicviews == 1) {
                    return true;
                }
            }
            return false;
        }
        return $user_institutions[$institution->institution]->allowinstitutionpublicviews == 1;
    }

780
781
782
783
784
785
786
787
    /**
     * Returns whether this user is allowed to perform administration type
     * actions on another user.
     *
     * @param mixed $user The user to check we can perform actions on. Can
     *                    either be a User object, a row from the usr table or
     *                    an ID
     */
788
789
790
791
    public function is_admin_for_user($user) {
        if ($this->get('admin')) {
            return true;
        }
792
793
794
        if (!$this->is_institutional_admin()) {
            return false;
        }
795
796

        // Check privileges for institutional admins now
797
        if ($user instanceof User) {
798
            $userobj = $user;
799
800
        }
        else if (is_numeric($user)) {
801
802
            $userobj = new User;
            $userobj->find_by_id($user);
803
804
805
        }
        else if (is_object($user)) {
            // Should be a row from the usr table
806
807
            $userobj = new User;
            $userobj->find_by_id($user->id);
808
        }
809
810
811
812
        else {
            throw new SystemException("Invalid argument pass to is_admin_for_user method");
        }

813
814
815
816
817
        if ($userobj->get('admin')) {
            return false;
        }

        foreach ($userobj->get('institutions') as $i) {
818
819
820
821
822
823
824
            if ($this->is_institutional_admin($i->institution)) {
                return true;
            }
        }
        return false;
    }

825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
    public function is_staff_for_user($user) {
        if ($this->get('admin') || $this->get('staff')) {
            return true;
        }
        if (!$this->is_institutional_admin() && !$this->is_institutional_staff()) {
            return false;
        }
        if ($user instanceof User) {
            $userinstitutions = $user->get('institutions');
        } else {
            $userinstitutions = load_user_institutions($user->id);
        }
        foreach ($userinstitutions as $i) {
            if ($this->is_institutional_admin($i->institution)
                || $this->is_institutional_staff($i->institution)) {
                return true;
            }
        }
        return false;
    }

846
    public function add_institution_request($institution, $studentid = null) {
847
848
849
        if (empty($institution) || $institution == 'mahara') {
            return;
        }
850
851
        require_once('institution.php');
        $institution = new Institution($institution);
852
        $institution->addRequestFromUser($this, $studentid);
853
854
    }

855
    public function reset_institutions($nocachecss=false) {
856
857
        $institutions             = load_user_institutions($this->id);
        $admininstitutions = array();
858
        $staffinstitutions = array();
859
860
        $themename = get_config('theme');
        $headerlogo = null;
861
        $stylesheets = array();
862
863
        $themeinstitution = null;
        foreach ($institutions as $name => $i) {
864
865
866
            if ($i->admin) {
                $admininstitutions[$i->institution] = $i->institution;
            }
867
868
869
            if ($i->staff) {
                $staffinstitutions[$i->institution] = $i->institution;
            }
870
871
            if (is_null($themeinstitution)) {
                $themeinstitution = $name;
872
            }
873
        }
874
875
876
        if ($this->authinstance) {
            $authobj = AuthFactory::create($this->authinstance);
            if (isset($institutions[$authobj->institution])) {
877
878
                if ($institutions[$authobj->institution]->theme) {
                    $themeinstitution = $authobj->institution;
879
880
881
                }
            }
        }
882
        if (!is_null($themeinstitution)) {
883
884
            $themename  = $institutions[$themeinstitution]->theme;
            $headerlogo = $institutions[$themeinstitution]->logo;
885
            if ($institutions[$themeinstitution]->style) {
886
887
888
889
890
                $stylesheet = get_config('wwwroot') . 'style.php?id=' . $institutions[$themeinstitution]->style;
                if ($nocachecss) {
                    $stylesheet .= '&time=' . time();
                }
                $stylesheets[] = $stylesheet;
891
            }
892
        }
893
894
895
896
        $this->institutiontheme = (object) array(
            'basename'    => $themename,
            'headerlogo'  => $headerlogo,
            'stylesheets' => $stylesheets,
897
            'institutionname' => $themeinstitution,
898
        );
899
900
        $this->institutions       = $institutions;
        $this->admininstitutions  = $admininstitutions;
901
        $this->staffinstitutions  = $staffinstitutions;
902
903
    }

904
    public function get_themedata() {
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
        $preftheme = $this->get_account_preference('theme');
        if (!empty($preftheme)) {
            // the format of preferred theme: <theme name>/<institution name>
            // This format is created by the function general_account_prefs_form_elements()
            $list = (explode('/', $preftheme));
            if (count($list) > 1) {
                $iid = $list[1];
                $institutions = load_user_institutions($this->id);
                if (isset($institutions[$iid])) {
                    $institution = $institutions[$iid];
                    $stylesheets = array();
                    if ($institution->style) {
                        $stylesheets[] = get_config('wwwroot') . 'style.php?id=' . $institution->style;
                    }
                    return (object) array(
                        'basename'    => $institution->theme,
                        'headerlogo'  => $institution->logo,
                        'stylesheets' => $stylesheets,
                        'institutionname' => $iid,
                    );
                }
            }
            else if (!empty($list[0]) && get_config('sitethemeprefs')) {
                return (object) array('basename' => $list[0]);
            }
930
        }
931
932
933
        // The current user has not picked a preferred theme yet
        // or his current preferred theme is not available for him
        // The system will pick one for him
934
        return $this->institutiontheme;
935
936
    }

937
938
939
940
941
942
943
944
945
946
947
    public function reset_grouproles() {
        $memberships = get_records_array('group_member', 'member', $this->get('id'));
        $roles = array();
        if ($memberships) {
            foreach ($memberships as $m) {
                $roles[$m->group] = $m->role;
            }
        }
        $this->set('grouproles', $roles);
    }

948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
    /**
     * Indicates whether the user can see the artefact *in the artefact chooser*, and use
     * it in Pages within its ownership context. In other words, if it's a group file, they
     * can use it in Pages for that group, but not in their own personal Pages. The function
     * name refers to the "view" permission for group files.
     *
     * WARNING: Despite the similarity in name to can_view_view(), this method DOESN'T
     * check for general permission to "see" an artefact, i.e. to download it or view
     * its artefact detail page. For that, you need to use artefact_in_view() followed by
     * can_view_view().
     *
     * TODO: Rename this to something less misleading?
     *
     * @param ArtefactType $a
     */
963
    public function can_view_artefact($a) {
964
965
        global $USER;

966
967
968
969
        // Files in the public site folder and its subfolders
        if ($a instanceof ArtefactTypeFileBase) {
            $publicfolderid = ArtefactTypeFolder::admin_public_folder_id();
            $fileispublic = ($a->get('id') == $publicfolderid)
970
                         || (($a->get('institution') == 'mahara') && (bool)get_field('artefact', 'id', 'id', $a->get('id'), 'parent', $publicfolderid));
971
972
973
974
975
            if ($fileispublic) {
                return true;
            }
        }

976
977
978
979
980
981
        $parent = $a->get_parent_instance();
        if ($parent) {
            if (!$this->can_view_artefact($parent)) {
                return false;
            }
        }
982
        if ($this->get('admin')
983
            || ($this->get('id') and $this->get('id') == $a->get('owner'))
984
            || ($a->get('institution') and $this->is_institutional_admin($a->get('institution')))) {
985
986
            return true;
        }
987
988
989
990
991
992
993
994
995
        // public site files
        else if ($a->get('institution') == 'mahara') {
            $thisparent = $a->get('parent');
            // if we are looking at the public folder or items in it
            if (($a->get('id') == ArtefactTypeFolder::admin_public_folder_id())
                ||  (!empty($thisparent) && $thisparent == ArtefactTypeFolder::admin_public_folder_id())) {
                return true;
            }
        }
996
        if ($a->get('group')) {
997
998
999
1000
            if ($USER->get('id') == $a->get('author')) {
                // uploader of group file should always have access to it
                return true;
            }
1001
1002
1003
            // Only group artefacts can have artefact_access_role & artefact_access_usr records
            return (bool) count_records_sql("SELECT COUNT(*) FROM {artefact_access_role} ar
                INNER JOIN {group_member} g ON ar.role = g.role
1004
                WHERE ar.artefact = ? AND g.member = ? AND ar.can_view = 1 AND g.group = ?", array($a->get('id'), $this->get('id'), $a->get('group')))
1005
1006
1007
                || record_exists('artefact_access_usr', 'usr', $this->get('id'), 'artefact', $a->get('id'));
        }
        return false;
1008
1009
    }

1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
    /**
     * Check if user can download/view an export archive. Will return true:
     * if the user is the owner of the archive, or
     * if the user is a site admin, or
     * if the user is a group admin of the group the collection/view was submitted to, or
     * if the user is an admin of the institution that the group belongs to, or
     * if the user is an institutional admin of any institutions that the submitter belongs to
     *
     * @param $data  Record containing information from the export_archive and archived_submission tables
     *
     * @return bool
     */
    function can_view_archive($data) {
        global $USER;

        require_once(get_config('docroot') . 'auth/lib.php');
        $user = new User;
        $user->find_by_id($data->usr);

        // User is the owner of the archive so is allowed to see it
        if ($USER->get('id') == $user->get('id')) {
            return true;
        }

        // User is a site admin so is allowed to access everything
        if ($USER->get('admin')) {
            return true;
        }

        if (!empty($data->group)) {
            // User is a group admin of the group the collection/view was submitted to
            $grouproles = $USER->get('grouproles');
            if (!empty($grouproles[$data->group]) && $grouproles[$data->group] == 'admin') {
                return true;
            }

            // User is an institutional admin for the institution that the group belongs to
            // Currently only groups uploaded via csv can get the institution field set.
            $currentuserinstitutions = $USER->get('institutions');
            $groupinstitution = get_field('group','institution', 'id', $data->group);
            if (!empty($groupinstitution)) {
                foreach ($currentuserinstitutions as $key => $institution) {
                    if ($USER->is_institutional_admin($key) && $key == $groupinstitution) {
                        return true;
                    }
                }
            }
        }

        // User is an institutional admin in an institution that the data->usr belongs to
        // This is a loose connection check for groups without the institution field set.
        // But seen as the User has power over the data->usr we will allow it
        $ownerinstitutions = $user->get('institutions');
        $currentuserinstitutions = $USER->get('institutions');
        foreach ($currentuserinstitutions as $key => $institution) {
            if ($USER->is_institutional_admin($key) && !empty($ownerinstitutions[$key])) {
                return true;
            }
        }

        return false;
    }

1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
    /**
     * Indicates whether the user has permission to edit an artefact's contents. The name refers
     * to the "edit" permission for group files.
     *
     * If a user has "edit" permission, it is assumed they also have "view" permission (i.e.
     * can view it in the artefact chooser -- see $USER->can_view_artefact())
     *
     * @param ArtefactType $a
     * @param boolean $viewparent Whether the user must also be able to "view" the artefact's parent
     * @return boolean
     */
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
    public function can_edit_artefact($a, $viewparent=false) {
        $parent = $a->get_parent_instance();
        if ($parent) {
            if ($viewparent) {
                if (!$this->can_view_artefact($parent)) {
                    return false;
                }
            }
            else {
                if (!$this->can_edit_artefact($parent, true)) {
                    return false;
                }
            }
        }
Richard Mansfield's avatar
Richard Mansfield committed
1098
        if ($this->get('admin')
1099
            || ($this->get('id') and $this->get('id') == $a->get('owner'))
1100
            || ($a->get('institution') and $this->is_institutional_admin($a->get('institution')))) {
Richard Mansfield's avatar
Richard Mansfield committed
1101
1102
            return true;
        }
1103
1104
1105

        if (!$group = $a->get('group')) {
            return false;
Richard Mansfield's avatar
Richard Mansfield committed
1106
        }
1107
1108
1109
1110
1111
1112
1113
1114

        require_once('group.php');
        if (!$role = group_user_access($group, $this->id)) {
            return false;
        }
        if ($role == 'admin') {
            return true;
        }
1115
1116
1117
        if (!group_within_edit_window($group)) {
            return false;
        }
1118
1119
1120
1121
1122
        if ($this->id == $a->get('author')) {
            return true;
        }

        return $a->role_has_permission($role, 'edit');
Richard Mansfield's avatar
Richard Mansfield committed
1123
1124
    }

1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
    /**
     * Indicates whether the user has permission to use the artefact in their own Pages. The name
     * refers to the "publish" permission for group files.
     *
     * If a user has "publish" permission on an artefact, it is assumed the also have "edit" and
     * "view" permission (i.e. can view it in the artefact chooser -- see $USER->can_view_artefact())
     *
     * @param ArtefactType $a
     * @return boolean
     */
1135
    public function can_publish_artefact($a) {
1136
1137
1138
1139
1140
1141
        $parent = $a->get_parent_instance();
        if ($parent) {
            if (!$this->can_view_artefact($parent)) {
                return false;
            }
        }
1142
        if (($this->get('id') and $this->get('id') == $a->get('owner'))) {
1143
1144
            return true;
        }
1145

1146
1147
1148
1149
        if ($i = $a->get('institution')) {
            if ($i == 'mahara') {
                return $this->get('admin');
            }
1150
            return $this->in_institution($i) || $this->can_edit_institution($i);
1151
1152
        }

1153
1154
        if (!$group = $a->get('group')) {
            return false;
1155
        }
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168

        require_once('group.php');
        if (!$role = group_user_access($group, $this->id)) {
            return false;
        }
        if ($role == 'admin') {
            return true;
        }
        if ($this->id == $a->get('author')) {
            return true;
        }

        return $a->role_has_permission($role, 'republish');
1169
1170
    }

1171
1172
    public function can_edit_view($v) {
        $owner = $v->get('owner');
1173
        if ($owner > 0 && $owner == $this->get('id')) {
1174
1175
            return true;
        }
1176
1177
1178
        if ($owner == "0" && $this->get('admin')) {
            return true;
        }
1179
        $institution = $v->get('institution');
1180
        if ($institution && $this->can_edit_institution($institution)) {
1181
1182
            return true;
        }
1183
1184
        $group = $v->get('group');
        if ($group) {
1185
            $this->reset_grouproles();
1186
            if (!isset($this->grouproles[$group])) {
1187
1188
                return false;
            }