user.php 67.4 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
     *                                  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');
        }

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

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

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

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

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

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

175
        $username = strtolower($username);
176
        if ($remoteuser) {
Aaron Wells's avatar
Aaron Wells committed
177 178 179 180 181
            // 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
182 183
            // that should not matter in finding the user
            $parentwhere = '';
184
            if ($parentid = get_field('auth_instance_config', 'value', 'field', 'parent', 'instance', $instanceid)) {
185 186 187
                $parentwhere = '
                            OR
                            (
188 189
                                LOWER(username) = (
                                    SELECT
190
                                        LOWER(username)
191 192 193 194 195
                                    FROM
                                        {usr} us
                                    JOIN
                                        {auth_remote_user} aru ON (us.id = aru.localusr)
                                    WHERE
196
                                        LOWER(aru.remoteusername) = ' . db_quote($username) . '
197 198
                                        AND us.authinstance = ' . db_quote($parentid) . '
                                )
199
                                AND u.authinstance = ' . db_quote($parentid) . '
200 201
                            )
                    ';
202
            }
203

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

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

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

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

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

        $sql = 'SELECT
262
                        u.*,
263 264 265 266 267 268 269 270 271
                        ' . 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
272 273
                            WHERE p.field=\'mobileuploadtoken\'
                              AND p.value ' . db_ilike() . ' \'%|\' || ? || \'|%\' AND u.username = ?
274 275
		';

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

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

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

287 288 289 290
    /**
     * Refreshes a users mobile 'token' and returns it
     *
     */
291 292 293 294 295 296 297 298 299 300 301
    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);
302
        $this->set('lastaccess', time());
303 304
        $this->commit();
        return $new_token;
305
    }
306

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


Donal McMullan's avatar
Donal McMullan committed
319 320 321 322 323 324 325 326 327 328 329 330 331
    /**
     * 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});
            }
        }
332
    }
Donal McMullan's avatar
Donal McMullan committed
333

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
    /**
     * 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;
    }

349 350 351 352 353
    /**
     * 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
354
     * @throws InvalidArgumentException
355 356
     */
    public function get($key) {
Donal McMullan's avatar
Donal McMullan committed
357
        if (!array_key_exists($key, $this->defaults)) {
358
            throw new InvalidArgumentException($key);
359
        }
Donal McMullan's avatar
Donal McMullan committed
360 361
        if (array_key_exists($key, $this->attributes) && null !== $this->attributes[$key]) {
            return $this->attributes[$key];
362 363 364 365
        }
        return $this->defaults[$key];
    }

Donal McMullan's avatar
Donal McMullan committed
366 367 368 369 370 371 372 373 374 375 376
    /**
     * 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);
    }

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

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

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

        // For now, these fields are saved to the DB elsewhere
389
        if ($key != 'activityprefs' && $key != 'accountprefs' && $key != 'views') {
Donal McMullan's avatar
Donal McMullan committed
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
            $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
413
        $record = $this->to_stdclass();
Donal McMullan's avatar
Donal McMullan committed
414
        if (is_numeric($this->id) && 0 < $this->id) {
Donal McMullan's avatar
Donal McMullan committed
415 416 417 418 419 420
            try {
                update_record('usr', $record, array('id' => $this->id));
            } catch (Exception $e) {
                throw $e;
                //var_dump($e);
            }
Donal McMullan's avatar
Donal McMullan committed
421
        } else {
Donal McMullan's avatar
Donal McMullan committed
422 423
            try {
                $this->set('id', insert_record('usr', $record, 'id', true));
Donal McMullan's avatar
Donal McMullan committed
424 425
            } catch (SQLException $e) {
                throw $e;
Donal McMullan's avatar
Donal McMullan committed
426
            }
Donal McMullan's avatar
Donal McMullan committed
427 428
        }
        $this->changed = false;
429 430
    }

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

442 443 444 445 446 447 448 449
    /** @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
450
    /**
451 452
     * This function returns a value for a particular
     * account preference, or null if it's not set.
Aaron Wells's avatar
Aaron Wells committed
453
     *
454 455 456 457 458 459
     * @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
460

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

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

    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);
    }

490 491 492 493 494 495 496 497
    /**
     * 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() {
498
        return $this->get_view_by_type('profile');
499 500 501 502 503 504 505
    }

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

509
        db_begin();
510
        require_once(get_config('libroot') . 'view.php');
511
        if (is_null($systemprofileviewid)) {
512
            $systemprofileviewid = get_field('view', 'id', 'institution', 'mahara', 'template', View::SITE_TEMPLATE, 'type', 'profile');
513
        }
514
        $artefactcopies = array();
515 516 517
        list($view) = View::create_from_template(array(
            'owner' => $this->get('id'),
            'title' => get_field('view', 'title', 'id', $systemprofileviewid),
518
            'description' => get_string('profiledescription'),
519
            'type'  => 'profile',
520
        ), $systemprofileviewid, $this->get('id'), false, false, $artefactcopies);
521

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

542
        db_commit();
543 544 545 546

        return $view;
    }

547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    /**
     * 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();
564
        require_once(get_config('libroot') . 'view.php');
565
        if (is_null($systemdashboardviewid)) {
566
            $systemdashboardviewid = get_field('view', 'id', 'institution', 'mahara', 'template', View::SITE_TEMPLATE, 'type', 'dashboard');
567
        }
568
        $artefactcopies = array();
569 570 571
        list($view) = View::create_from_template(array(
            'owner' => $this->get('id'),
            'title' => get_field('view', 'title', 'id', $systemdashboardviewid),
572
            'description' => get_string('dashboarddescription'),
573
            'type'  => 'dashboard',
574
        ), $systemdashboardviewid, $this->get('id'), false, false, $artefactcopies);
575 576 577 578 579

        db_commit();

        return $view;
    }
580

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

586 587 588 589 590 591
    // 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
592
            '"owner" = ? AND type IN (' . join(',', array_map('db_quote', $types)) . ')',
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
            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);
    }
610

611 612 613 614 615 616 617 618
    /**
     * 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
619

620
    public function to_stdclass() {
Donal McMullan's avatar
Donal McMullan committed
621 622 623
        $this->stdclass = new StdClass;
        reset($this->defaults);
        foreach (array_keys($this->defaults) as $k) {
Richard Mansfield's avatar
Richard Mansfield committed
624
            if ($k == 'expiry' || $k == 'lastlogin' || $k == 'lastlastlogin' || $k == 'lastaccess' || $k == 'suspendedctime' || $k == 'ctime') {
Donal McMullan's avatar
Donal McMullan committed
625 626 627 628
                $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));
            }
629 630 631
        }
        return $this->stdclass;
    }
632

Martyn Smith's avatar
Martyn Smith committed
633 634 635 636 637 638 639 640
    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
641 642
        $this->set("quotaused", $newquota);
        return $this;
Martyn Smith's avatar
Martyn Smith committed
643 644 645 646 647 648 649 650 651 652
    }

    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
653 654
        $this->set("quotaused", $newquota);
        return $this;
Martyn Smith's avatar
Martyn Smith committed
655 656 657 658 659 660 661 662 663
    }

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

        return true;
    }
664

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

673 674 675 676 677 678
    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);
    }

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

688 689 690 691
    public function leave_institution($institution) {
        if ($institution != 'mahara' && $this->in_institution($institution)) {
            require_once('institution.php');
            $institution = new Institution($institution);
692
            $institution->removeMember($this->to_stdclass());
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 734
    /**
     * 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';
    }

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

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

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

757 758 759 760
    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);
        }
761 762 763
        return $this->get('admin') || $this->is_institutional_admin($institution);
    }

764 765 766 767 768 769 770 771 772 773 774 775
    public function can_edit_group_shortname(stdClass $group) {
        if (!isset($group->id) || empty($group->id)) {
            return false;
        }

        if ($this->get('admin')) {
            return true;
        }

        return false;
    }

776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
    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;
    }

793 794 795 796 797 798 799 800
    /**
     * 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
     */
801 802 803 804
    public function is_admin_for_user($user) {
        if ($this->get('admin')) {
            return true;
        }
805 806 807
        if (!$this->is_institutional_admin()) {
            return false;
        }
808 809

        // Check privileges for institutional admins now
810
        if ($user instanceof User) {
811
            $userobj = $user;
812 813
        }
        else if (is_numeric($user)) {
814 815
            $userobj = new User;
            $userobj->find_by_id($user);
816 817 818
        }
        else if (is_object($user)) {
            // Should be a row from the usr table
819 820
            $userobj = new User;
            $userobj->find_by_id($user->id);
821
        }
822 823 824 825
        else {
            throw new SystemException("Invalid argument pass to is_admin_for_user method");
        }

826 827 828 829 830
        if ($userobj->get('admin')) {
            return false;
        }

        foreach ($userobj->get('institutions') as $i) {
831 832 833 834 835 836 837
            if ($this->is_institutional_admin($i->institution)) {
                return true;
            }
        }
        return false;
    }

838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
    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;
    }

859
    public function add_institution_request($institution, $studentid = null) {
860 861 862
        if (empty($institution) || $institution == 'mahara') {
            return;
        }
863 864
        require_once('institution.php');
        $institution = new Institution($institution);
865
        $institution->addRequestFromUser($this, $studentid);
866 867
    }

868
    public function reset_institutions($nocachecss=false) {
869 870
        $institutions             = load_user_institutions($this->id);
        $admininstitutions = array();
871
        $staffinstitutions = array();
872 873
        $themename = get_config('theme');
        $headerlogo = null;
874
        $stylesheets = array();
875 876
        $themeinstitution = null;
        foreach ($institutions as $name => $i) {
877 878 879
            if ($i->admin) {
                $admininstitutions[$i->institution] = $i->institution;
            }
880 881 882
            if ($i->staff) {
                $staffinstitutions[$i->institution] = $i->institution;
            }
883 884
            if (is_null($themeinstitution)) {
                $themeinstitution = $name;
885
            }
886
        }
887 888 889
        if ($this->authinstance) {
            $authobj = AuthFactory::create($this->authinstance);
            if (isset($institutions[$authobj->institution])) {
890 891
                if ($institutions[$authobj->institution]->theme) {
                    $themeinstitution = $authobj->institution;
892 893 894
                }
            }
        }
895
        if (!is_null($themeinstitution)) {
896 897
            $themename  = $institutions[$themeinstitution]->theme;
            $headerlogo = $institutions[$themeinstitution]->logo;
898
            if ($institutions[$themeinstitution]->style) {
899 900 901 902 903
                $stylesheet = get_config('wwwroot') . 'style.php?id=' . $institutions[$themeinstitution]->style;
                if ($nocachecss) {
                    $stylesheet .= '&time=' . time();
                }
                $stylesheets[] = $stylesheet;
904
            }
905
        }
906 907 908 909
        $this->institutiontheme = (object) array(
            'basename'    => $themename,
            'headerlogo'  => $headerlogo,
            'stylesheets' => $stylesheets,
910
            'institutionname' => $themeinstitution,
911
        );
912 913
        $this->institutions       = $institutions;
        $this->admininstitutions  = $admininstitutions;
914
        $this->staffinstitutions  = $staffinstitutions;
915 916
    }

917
    public function get_themedata() {
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
        $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]);
            }
943 944 945 946 947 948 949
            // Or the current preferred theme is not available
            // The system will pick one
            return $this->institutiontheme;
        }
        if ($this->institutiontheme) {
            // No theme set so use 'sitedefault'
            $this->institutiontheme->altname = 'sitedefault';
950
        }
951
        return $this->institutiontheme;
952 953
    }

954
    public function reset_grouproles() {
955 956 957 958
        $sql = "SELECT gm.* FROM {group_member} gm
                JOIN {group} g ON g.id = gm.group
                WHERE gm.member = ? AND g.deleted = 0";
        $memberships = get_records_sql_array($sql, array($this->get('id')));
959 960 961 962 963 964 965 966 967
        $roles = array();
        if ($memberships) {
            foreach ($memberships as $m) {
                $roles[$m->group] = $m->role;
            }
        }
        $this->set('grouproles', $roles);
    }

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
    /**
     * 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
     */
983
    public function can_view_artefact($a) {
984
        global $USER;
985
        safe_require('artefact', 'file');
986 987 988 989
        // Files in the public site folder and its subfolders
        if ($a instanceof ArtefactTypeFileBase) {
            $publicfolderid = ArtefactTypeFolder::admin_public_folder_id();
            $fileispublic = ($a->get('id') == $publicfolderid)
990
                         || (($a->get('institution') == 'mahara') && (bool)get_field('artefact', 'id', 'id', $a->get('id'), 'parent', $publicfolderid));
991 992 993 994 995
            if ($fileispublic) {
                return true;
            }
        }

996 997 998 999 1000 1001
        $parent = $a->get_parent_instance();
        if ($parent) {
            if (!$this->can_view_artefact($parent)) {
                return false;
            }
        }
1002
        if ($this->get('admin')
1003
            || ($this->get('id') and $this->get('id') == $a->get('owner'))
1004 1005 1006 1007
            || ($a->get('institution') and $this->is_institutional_admin($a->get('institution')))
            || ($a->get('institution') && $this->in_institution($a->get('institution'))
                && in_array($a->get('artefacttype'), array('blog', 'blogpost')))
            ) {
1008 1009
            return true;
        }
1010 1011 1012 1013 1014 1015 1016 1017
        // 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;
            }
1018 1019 1020 1021 1022 1023 1024 1025 1026
            //  Journals
            if ($a instanceof ArtefactTypeBlog) {
                $views = $a->get_views_instances();
                foreach ($views as $view) {
                    if (can_view_view($view->get('id'))) {
                        return true;
                    }
                }
            }
1027
        }
1028
        if ($a->get('group')) {
1029 1030 1031 1032
            if ($USER->get('id') == $a->get('author')) {
                // uploader of group file should always have access to it
                return true;
            }
1033 1034 1035
            // 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
1036
                WHERE ar.artefact = ? AND g.member = ? AND ar.can_view = 1 AND g.group = ?", array($a->get('id'), $this->get('id'), $a->get('group')))
1037 1038 1039
                || record_exists('artefact_access_usr', 'usr', $this->get('id'), 'artefact', $a->get('id'));
        }
        return false;
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 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    /**
     * 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;
    }

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
    /**
     * 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
     */
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
    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
1130
        if ($this->get('admin')
1131
            || ($this->get('id') and $this->get('id') == $a->get('owner'))
1132
            || ($a->get('institution') and $this->is_institutional_admin($a->get('institution')))) {
Richard Mansfield's avatar
Richard Mansfield committed
1133 1134
            return true;
        }
1135 1136 1137

        if (!$group = $a->get('group')) {
            return false;
Richard Mansfield's avatar
Richard Mansfield committed
1138
        }
1139 1140 1141 1142 1143 1144 1145 1146

        require_once('group.php');
        if (!$role = group_user_access($group, $this->id)) {
            return false;
        }
        if ($role == 'admin') {
            return true;
        }
1147 1148 1149
        if (!group_within_edit_window($group)) {
            return false;
        }
1150 1151 1152 1153 1154
        if ($this->id == $a->get('author')) {
            return true;
        }

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

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    /**
     * 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
     */
1167
    public function can_publish_artefact($a) {
1168 1169 1170 1171 1172 1173
        $parent = $a->get_parent_instance();
        if ($parent) {
            if (!$this->can_view_artefact($parent)) {
                return false;
            }
        }
1174
        if (($this->get('id') and $this->get('id') == $a->get('owner'))) {
1175 1176
            return true;
        }
1177

1178 1179 1180 1181
        if ($i = $a->get('institution')) {
            if ($i == 'mahara') {
                return $this->get('admin');
            }
1182
            return $this->in_institution($i) || $this->can_edit_institution($i);
1183 1184
        }

1185 1186
        if (!$group = $a->get('group')) {
            return false;
1187
        }
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200

        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');
1201 1202
    }

1203 1204
    public function can_edit_view($v) {
        $owner = $v->get('owner');
1205
        if ($owner > 0 && $owner == $this->get('id')) {
1206 1207
            return true;
        }
1208
        $institution = $v->get('institution');
1209
        if ($institution && $this->can_edit_institution($institution)) {
1210 1211
            return true;
        }
1212 1213
        $group = $v->get('group');
        if ($group) {
1214
            $this->reset_grouproles();
1215
            if (!isset($this->grouproles[$group])) {
1216 1217
                return false;
            }
1218
            if (($v->get('type') == 'grouphomepage' || $v->get('locked')) && $this->grouproles[$group] != 'admin') {
1219 1220
                return false;
            }
1221
            require_once('group.php');
1222
            return group_role_can_edit_views($group, $this->grouproles[$group]);
1223 1224 1225 1226
        }
        return false;
    }

1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
    /**
     * Function to check if user can moderate (ie; delete) comments in a view
     */
    public function can_moderate_view($v) {
        $owner = $v->get('owner');
        if ($owner > 0 && $owner == $this->get('id')) {
            return true;
        }
        $institution = $v->get('institution');
        if ($institution && $this->can_edit_institution($institution)) {
            return true;
        }
        $group = $v->get('group');
        if ($group) {
            $this->reset_grouproles();
1242 1243 1244 1245 1246 1247 1248 1249
            if (!isset($this->grouproles[$group])) {
                return false;
            }
            if (($v->get('type') == 'grouphomepage' || $v->get('locked')) && $this->grouproles[$group] != 'admin') {
                return false;
            }
            require_once('group.php');
            return group_role_can_moderate_views($group, $this->grouproles[$group]);