institution.php 29.8 KB
Newer Older
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
5
 * Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
 *                         http://wiki.mahara.org/Contributors
6
 *
Francois Marier's avatar
Francois Marier committed
7
8
9
10
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
11
 *
Francois Marier's avatar
Francois Marier committed
12
13
14
15
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
16
 *
Francois Marier's avatar
Francois Marier committed
17
18
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20
21
 *
 * @package    mahara
 * @subpackage auth-internal
22
 * @author     Catalyst IT Ltd
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
24
 * @copyright  (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
25
26
27
 *
 */

Donal McMullan's avatar
Donal McMullan committed
28
29
// TODO : lib

30
31
32
33
34
35
36
37
38
39
40
41
42
defined('INTERNAL') || die();

class Institution {

    const   UNINITIALIZED  = 0;
    const   INITIALIZED    = 1;
    const   PERSISTENT     = 2;

    protected $initialized = self::UNINITIALIZED;
    protected $members = array(
        'name' => '',
        'displayname' => '',
        'registerallowed' => 1,
43
        'theme' => 'default',
44
45
        'defaultmembershipperiod' => 0,
        'maxuseraccounts' => null
46
47
48
49
50
51
52
        ); 

    function __construct($name = null) {
        if (is_null($name)) {
            return $this;
        }

53
        if (!$this->findByName($name)) {
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
            throw new ParamOutOfRangeException('No such institution');
        }
    }

    function __get($name) {
        if (array_key_exists($name, $this->members)) {
            return $this->members[$name];
        }
        return null;
    }

    public function __set($name, $value) {
        if (!is_string($name) | !array_key_exists($name, $this->members)) {
            throw new ParamOutOfRangeException();
        }
        if ($name == 'name') {
            if (!is_string($value) || empty($value) || strlen($value) > 255) {
                throw new ParamOutOfRangeException("'name' should be a string between 1 and 255 characters in length");
            }
        } elseif ($name == 'displayname') {
            if (!is_string($value) || empty($value) || strlen($value) > 255) {
                throw new ParamOutOfRangeException("'displayname' ($value) should be a string between 1 and 255 characters in length");
            }
        } elseif ($name == 'registerallowed') {
            if (!is_numeric($value) || $value < 0 || $value > 1) {
                throw new ParamOutOfRangeException("'registerallowed' should be zero or one");
            }
81
        } elseif ($name == 'theme') {
82
83
            if (!empty($value) && is_string($value) && strlen($value) > 255) {
                throw new ParamOutOfRangeException("'theme' ($value) should be less than 255 characters in length");
84
            }
85
86
87
        } elseif ($name == 'defaultmembershipperiod') {
            if (!empty($value) && (!is_numeric($value) || $value < 0 || $value > 9999999999)) {
                throw new ParamOutOfRangeException("'defaultmembershipperiod' should be a number between 1 and 9,999,999,999");
88
            }
89
90
        } elseif ($name == 'maxuseraccounts') {
            if (!empty($value) && (!is_numeric($value) || $value < 0 || $value > 9999999999)) {
91
                throw new ParamOutOfRangeException("'maxuseraccounts' should be a number between 1 and 9,999,999,999");
92
            }
93
94
95
96
97
        }
        $this->members[$name] = $value;
    }

    function findByName($name) {
98

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
        if (!is_string($name) || strlen($name) < 1 || strlen($name) > 255) {
            throw new ParamOutOfRangeException("'name' must be a string.");
        }

        $result = get_record('institution', 'name', $name);

        if (false == $result) {
            return false;
        }

        $this->initialized = self::PERSISTENT;
        $this->populate($result);

        return $this;
    }

    function initialise($name, $displayname) {
        if (empty($name) || !is_string($name)) {
            return false;
        }

        $this->name = $name;
        if (empty($displayname) || !is_string($displayname)) {
            return false;
        }

        $this->displayname = $displayname;
        $this->initialized = max(self::INITIALIZED, $this->initialized);
        return true;
    }

    function verifyReady() {
        if (empty($this->members['name']) || !is_string($this->members['name'])) {
            return false;
        }
        if (empty($this->members['displayname']) || !is_string($this->members['displayname'])) {
            return false;
        }
        $this->initialized = max(self::INITIALIZED, $this->initialized);
        return true;
    }

    function commit() {
        if (!$this->verifyReady()) {
143
            throw new SystemException('Commit failed');
144
145
146
147
148
        }

        $record = new stdClass();
        $record->name                         = $this->name;
        $record->displayname                  = $this->displayname;
149
150
        $record->theme                        = $this->theme;
        $record->defaultmembershipperiod      = $this->defaultmembershipperiod;
151
        $record->maxuseraccounts              = $this->maxuseraccounts;
152
153
154
155
156
157
158
159
160
161
162
163
164
165

        if ($this->initialized == self::INITIALIZED) {
            return insert_record('institution', $record);
        } elseif ($this->initialized == self::PERSISTENT) {
            return update_record('institution', $record, array('name' => $this->name));
        }
        // Shouldn't happen but who noes?
        return false;
    }

    protected function populate($result) {
        $this->name                         = $result->name;
        $this->displayname                  = $result->displayname;
        $this->registerallowed              = $result->registerallowed;
166
167
        $this->theme                        = $result->theme;
        $this->defaultmembershipperiod      = $result->defaultmembershipperiod;
168
        $this->maxuseraccounts              = $result->maxuseraccounts;
169
170
171
        $this->verifyReady();
    }

172
    public function addUserAsMember($user) {
173
        global $USER;
174
175
176
        if ($this->isFull()) {
            throw new SystemException('Trying to add a user to an institution that already has a full quota of members');
        }
177
178
179
        if (is_numeric($user)) {
            $user = get_record('usr', 'id', $user);
        }
180
181
182
183
184
185
186
187
188
        if ($user instanceof User) {
            $lang = $user->get_account_preference('lang');
            if (empty($lang) || $lang == 'default') {
                $lang = get_config('lang');
            }
        }
        else { // stdclass object
            $lang = get_user_language($user->id);
        }
189
190
        $userinst = new StdClass;
        $userinst->institution = $this->name;
191
192
193
194
195
196
        $studentid = get_field('usr_institution_request', 'studentid', 'usr', $user->id, 
                               'institution', $this->name);
        if (!empty($studentid)) {
            $userinst->studentid = $studentid;
        }
        else if (!empty($user->studentid)) {
197
            $userinst->studentid = $user->studentid;
198
        }
199
        $userinst->usr = $user->id;
200
201
        $now = time();
        $userinst->ctime = db_format_timestamp($now);
202
203
204
        $defaultexpiry = $this->defaultmembershipperiod;
        if (!empty($defaultexpiry)) {
            $userinst->expiry = db_format_timestamp($now + $defaultexpiry);
205
        }
206
207
        $message = (object) array(
            'users' => array($user->id),
208
209
            'subject' => get_string_from_language($lang, 'institutionmemberconfirmsubject'),
            'message' => get_string_from_language($lang, 'institutionmemberconfirmmessage', 'mahara', $this->displayname),
210
        );
211
        db_begin();
212
213
        if (!get_config('usersallowedmultipleinstitutions')) {
            delete_records('usr_institution', 'usr', $user->id);
214
            delete_records('usr_institution_request', 'usr', $user->id);
215
        }
216
217
        insert_record('usr_institution', $userinst);
        delete_records('usr_institution_request', 'usr', $userinst->usr, 'institution', $this->name);
218
219
220
221
222
        execute_sql("
            DELETE FROM {usr_tag}
            WHERE usr = ? AND tag " . db_ilike() . " 'lastinstitution:%'",
            array($user->id)
        );
223
        // Copy institution views to the user's portfolio
224
        $checkviewaccess = empty($user->newuser) && !$USER->get('admin');
225
226
        $userobj = new User();
        $userobj->find_by_id($user->id);
227
        $userobj->copy_views(get_column('view', 'id', 'institution', $this->name, 'copynewuser', 1), $checkviewaccess);
228
        require_once('activity.php');
229
        activity_occurred('maharamessage', $message);
230
        handle_event('updateuser', $userinst->usr);
231
        db_commit();
232
233
    }

234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
    public function add_members($userids) {
        global $USER;

        if (empty($userids)) {
            return;
        }

        if (!$USER->can_edit_institution($this->name)) {
            throw new AccessDeniedException("Institution::add_members: access denied");
        }

        $values = array_map('intval', $userids);
        array_unshift($values, $this->name);
        $users = get_records_sql_array('
            SELECT u.*, r.confirmedusr
            FROM {usr} u LEFT JOIN {usr_institution_request} r ON u.id = r.usr AND r.institution = ?
            WHERE u.id IN (' . join(',', array_fill(0, count($values) - 1, '?')) . ') AND u.deleted = 0',
            $values
        );

        if (empty($users)) {
            return;
        }

        db_begin();
        foreach ($users as $user) {
            // If the user hasn't requested membership, allow them to be added to
            // the institution anyway so long as the logged-in user is a site admin
            // or institutional admin for the user (in some other institution).
            if (!$user->confirmedusr) {
                $userobj = new User;
                $userobj->from_stdclass($user);
                if (!$USER->is_admin_for_user($userobj)) {
                    continue;
                }
            }
            $this->addUserAsMember($user);
        }
        db_commit();
    }

275
    public function addRequestFromUser($user, $studentid = null) {
276
277
278
279
280
281
        $request = get_record('usr_institution_request', 'usr', $user->id, 'institution', $this->name);
        if (!$request) {
            $request = (object) array(
                'usr'          => $user->id,
                'institution'  => $this->name,
                'confirmedusr' => 1,
282
                'studentid'    => empty($studentid) ? $user->studentid : $studentid,
283
284
                'ctime'        => db_format_timestamp(time())
            );
285
286
287
288
289
290
291
            $message = (object) array(
                'messagetype' => 'request',
                'username' => $user->username,
                'fullname' => $user->firstname . ' ' . $user->lastname,
                'institution' => (object)array('name' => $this->name, 'displayname' => $this->displayname),
            );
            db_begin();
292
293
294
            if (!get_config('usersallowedmultipleinstitutions')) {
                delete_records('usr_institution_request', 'usr', $user->id);
            }
295
            insert_record('usr_institution_request', $request);
296
            require_once('activity.php');
297
298
299
            activity_occurred('institutionmessage', $message);
            handle_event('updateuser', $user->id);
            db_commit();
300
301
302
303
304
        } else if ($request->confirmedinstitution) {
            $this->addUserAsMember($user);
        }
    }

305
306
307
308
309
310
311
312
313
314
    public function declineRequestFromUser($userid) {
        $lang = get_user_language($userid);
        $message = (object) array(
            'users' => array($userid),
            'subject' => get_string_from_language($lang, 'institutionmemberrejectsubject'),
            'message' => get_string_from_language($lang, 'institutionmemberrejectmessage', 'mahara', $this->displayname),
        );
        db_begin();
        delete_records('usr_institution_request', 'usr', $userid, 'institution', $this->name,
                       'confirmedusr', 1);
315
        require_once('activity.php');
316
317
318
319
320
        activity_occurred('maharamessage', $message);
        handle_event('updateuser', $userid);
        db_commit();
    }

321
322
323
324
325
326
327
328
329
330
331
332
333
334
    public function decline_requests($userids) {
        global $USER;

        if (!$USER->can_edit_institution($this->name)) {
            throw new AccessDeniedException("Institution::decline_requests: access denied");
        }

        db_begin();
        foreach ($userids as $id) {
            $this->declineRequestFromUser($id);
        }
        db_commit();
    }

335
336
    public function inviteUser($user) {
        $userid = is_object($user) ? $user->id : $user;
337
        db_begin();
338
339
340
341
342
343
        insert_record('usr_institution_request', (object) array(
            'usr' => $userid,
            'institution' => $this->name,
            'confirmedinstitution' => 1,
            'ctime' => db_format_timestamp(time())
        ));
344
        require_once('activity.php');
345
346
347
348
349
        activity_occurred('institutionmessage', (object) array(
            'messagetype' => 'invite',
            'users' => array($userid),
            'institution' => (object)array('name' => $this->name, 'displayname' => $this->displayname),
        ));
350
        handle_event('updateuser', $userid);
351
        db_commit();
352
353
    }

354
355
356
357
358
359
360
361
362
363
364
365
366
367
    public function invite_users($userids) {
        global $USER;

        if (!$USER->can_edit_institution($this->name)) {
            throw new AccessDeniedException("Institution::invite_users: access denied");
        }

        db_begin();
        foreach ($userids as $id) {
            $this->inviteUser($id);
        }
        db_commit();
    }

368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
    public function uninvite_users($userids) {
        global $USER;

        if (!$USER->can_edit_institution($this->name)) {
            throw new AccessDeniedException("Institution::uninvite_users: access denied");
        }

        if (!is_array($userids) || empty($userids)) {
            return;
        }

        $ph = array_map('intval', $userids);
        $ph[] = $this->name;

        delete_records_select(
            'usr_institution_request',
            'usr IN (' . join(',', array_fill(0, count($userids), '?')) . ') AND institution = ? AND confirmedinstitution = 1',
            $ph
        );
    }

389
390
391
    public function removeMembers($userids) {
        // Remove self last.
        global $USER;
392
393
394
395
396

        if (!$USER->can_edit_institution($this->name)) {
            throw new AccessDeniedException("Institution::removeMembers: access denied");
        }

397
        $users = get_records_select_array('usr', 'id IN (' . join(',', array_map('intval', $userids)) . ')');
398
        $removeself = false;
399
        db_begin();
400
401
402
403
404
405
406
407
408
409
        foreach ($users as $user) {
            if ($user->id == $USER->id) {
                $removeself = true;
                continue;
            }
            $this->removeMember($user);
        }
        if ($removeself) {
            $USER->leave_institution($this->name);
        }
410
        db_commit();
411
412
    }

413
    public function removeMember($user) {
414
415
416
417
418
        if (is_numeric($user)) {
            $user = get_record('usr', 'id', $user);
        }
        db_begin();
        // If the user is being authed by the institution they are
419
420
421
422
423
424
425
426
        // being removed from, change them to internal auth, or if
        // we can't find that, some other no institution auth.
        $authinstances = get_records_select_assoc(
            'auth_instance',
            "institution IN ('mahara', ?)",
            array($this->name),
            "institution = 'mahara' DESC, authname = 'internal' DESC"
        );
427
428
429
        $oldauth = $user->authinstance;
        if (isset($authinstances[$oldauth]) && $authinstances[$oldauth]->institution == $this->name) {
            foreach ($authinstances as $ai) {
430
                if ($ai->authname == 'internal' && $ai->institution == 'mahara') {
431
432
433
                    $user->authinstance = $ai->id;
                    break;
                }
434
435
436
437
                else if ($ai->institution == 'mahara') {
                    $user->authinstance = $ai->id;
                    break;
                }
438
439
440
441
442
443
444
445
            }
            delete_records('auth_remote_user', 'authinstance', $oldauth, 'localusr', $user->id);
            // If the old authinstance was external, the user may need
            // to set a password
            if ($user->password == '') {
                log_debug('resetting pw for '.$user->id);
                $this->removeMemberSetPassword($user);
            }
446
447
448
449
450
451
452
453
            else if ($authinstances[$oldauth]->authname != 'internal') {
                $sitename = get_config('sitename');
                $fullname = display_name($user, null, true);
                email_user($user, null,
                    get_string('noinstitutionoldpassemailsubject', 'mahara', $sitename, $this->displayname),
                    get_string('noinstitutionoldpassemailmessagetext', 'mahara', $fullname, $this->displayname, $sitename, $user->username, get_config('wwwroot'), get_config('wwwroot'), $sitename, get_config('wwwroot')),
                    get_string('noinstitutionoldpassemailmessagehtml', 'mahara', hsc($fullname), hsc($this->displayname), hsc($sitename), hsc($user->username), get_config('wwwroot'), get_config('wwwroot'), get_config('wwwroot'), hsc($sitename), get_config('wwwroot'), get_config('wwwroot')));
            }
454
455
            update_record('usr', $user);
        }
456
457
458
459
460
461
462
463
464
465
466
467

        // If this user has a favourites list which is updated by this institution, remove it
        // from this institution's control.
        // Don't delete it in case the user wants to keep it, but move it out of the way, so
        // another institution can create a new faves list with the same name.
        execute_sql("
            UPDATE {favorite}
            SET institution = NULL, shortname = substring(shortname from 1 for 100) || '.' || ?
            WHERE owner = ? AND institution = ?",
            array(substr($this->name, 0, 100) . '.' . get_random_key(), $user->id, $this->name)
        );

468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
        execute_sql("
            DELETE FROM {usr_tag}
            WHERE usr = ? AND tag " . db_ilike() . " 'lastinstitution:%'",
            array($user->id)
        );

        insert_record(
            'usr_tag',
            (object) array(
                'usr' => $user->id,
                'tag' => 'lastinstitution:' . strtolower($this->displayname),
            )
        );
        insert_record(
            'usr_tag',
            (object) array(
                'usr' => $user->id,
                'tag' => 'lastinstitution:' . strtolower($this->name),
            )
        );

489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
        delete_records('usr_institution', 'usr', $user->id, 'institution', $this->name);
        handle_event('updateuser', $user->id);
        db_commit();
    }

    /**
     * Reset user's password, and send them a password change email
     */
    private function removeMemberSetPassword(&$user) {
        global $SESSION, $USER;
        if ($user->id == $USER->id) {
            $user->passwordchange = 1;
            return;
        }
        try {
            $pwrequest = new StdClass;
            $pwrequest->usr = $user->id;
            $pwrequest->expiry = db_format_timestamp(time() + 86400);
            $pwrequest->key = get_random_key();
            $sitename = get_config('sitename');
            $fullname = display_name($user, null, true);
            email_user($user, null,
                get_string('noinstitutionsetpassemailsubject', 'mahara', $sitename, $this->displayname),
512
                get_string('noinstitutionsetpassemailmessagetext', 'mahara', $fullname, $this->displayname, $sitename, $user->username, get_config('wwwroot'), $pwrequest->key, get_config('wwwroot'), $sitename, get_config('wwwroot'), $pwrequest->key),
513
                get_string('noinstitutionsetpassemailmessagehtml', 'mahara', hsc($fullname), hsc($this->displayname), hsc($sitename), hsc($user->username), get_config('wwwroot'), hsc($pwrequest->key), get_config('wwwroot'), hsc($pwrequest->key), get_config('wwwroot'), hsc($sitename), get_config('wwwroot'), hsc($pwrequest->key), get_config('wwwroot'), hsc($pwrequest->key)));
514
515
516
517
518
519
520
521
            insert_record('usr_password_request', $pwrequest);
        }
        catch (SQLException $e) {
            $SESSION->add_error_msg(get_string('forgotpassemailsendunsuccessful'));
        }
        catch (EmailException $e) {
            $SESSION->add_error_msg(get_string('forgotpassemailsendunsuccessful'));
        }
522
    }
523
524
525
526
527
528
529
530
531
532
533
534
535

    public function countMembers() {
        return count_records_sql('
            SELECT COUNT(*) FROM {usr} u INNER JOIN {usr_institution} i ON u.id = i.usr
            WHERE i.institution = ? AND u.deleted = 0', array($this->name));
    }

    public function countInvites() {
        return count_records_sql('
            SELECT COUNT(*) FROM {usr} u INNER JOIN {usr_institution_request} r ON u.id = r.usr
            WHERE r.institution = ? AND u.deleted = 0 AND r.confirmedinstitution = 1',
            array($this->name));
    }
536
537
538
539
540
541
542
543
544
545

    /**
     * Returns true if the institution already has its full quota of users 
     * assigned to it.
     *
     * @return bool
     */
    public function isFull() {
        return ($this->maxuseraccounts != '') && ($this->countMembers() >= $this->maxuseraccounts);
    }
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
571
572
573
574
    /**
     * Returns the current institution admin member records
     *
     * @return array  A data structure containing admins
     */
    public function admins() {
        if ($results = get_records_sql_array('
            SELECT u.id FROM {usr} u INNER JOIN {usr_institution} i ON u.id = i.usr
            WHERE i.institution = ? AND u.deleted = 0 AND i.admin = 1', array($this->name))) {
            return array_map(create_function('$a', 'return $a->id;'), $results);
        }
        return array();
    }

    /**
     * Returns the current institution staff member records
     *
     * @return array  A data structure containing staff
     */
    public function staff() {
        if ($results = get_records_sql_array('
            SELECT u.id FROM {usr} u INNER JOIN {usr_institution} i ON u.id = i.usr
            WHERE i.institution = ? AND u.deleted = 0 AND i.staff = 1', array($this->name))) {
            return array_map(create_function('$a', 'return $a->id;'), $results);
        }
        return array();
    }

575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
    /**
     * Returns the list of institutions, implements institution searching
     *
     * @param array   Limit the output to only institutions in this array (used for institution admins).
     * @param bool    Whether default institution should be listed in results.
     * @param string  Searching query string.
     * @param int     Limit of results (used for pagination).
     * @param int     Offset of results (used for pagination).
     * @param int     Returns the total number of results.
     * @return array  A data structure containing results looking like ...
     *   $institutions = array(
     *                       name => array(
     *                           displayname     => string
     *                           maxuseraccounts => integer
     *                           members         => integer
     *                           staff           => integer
     *                           admins          => integer
     *                           name            => string
     *                       ),
     *                       name => array(...),
     *                   );
     */
    public static function count_members($filter, $showdefault, $query='', $limit=null, $offset=null, &$count=null) {
598
599
        if ($filter) {
            $where = '
600
            AND ii.name IN (' . join(',', array_map('db_quote', $filter)) . ')';
601
602
603
604
        }
        else {
            $where = '';
        }
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623

        $querydata = split(' ', preg_replace('/\s\s+/', ' ', strtolower(trim($query))));
        $namesql = '(
                ii.name ' . db_ilike() . ' \'%\' || ? || \'%\'
            )
            OR (
                ii.displayname ' . db_ilike() . ' \'%\' || ? || \'%\'
            )';
        $namesql = join(' OR ', array_fill(0, count($querydata), $namesql));
        $queryvalues = array();
        foreach ($querydata as $w) {
            $queryvalues = array_pad($queryvalues, count($queryvalues) + 2, $w);
        }

        $count = count_records_sql('SELECT COUNT(ii.name)
            FROM {institution} ii
            WHERE' . $namesql, $queryvalues
        );

624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
        $institutions = get_records_sql_assoc('
            SELECT
                ii.name,
                ii.displayname,
                ii.maxuseraccounts,
                ii.suspended,
                COALESCE(a.members, 0) AS members,
                COALESCE(a.staff, 0) AS staff,
                COALESCE(a.admins, 0) AS admins
            FROM
                {institution} ii
                LEFT JOIN
                    (SELECT
                        i.name, i.displayname, i.maxuseraccounts,
                        COUNT(ui.usr) AS members, SUM(ui.staff) AS staff, SUM(ui.admin) AS admins
                    FROM
                        {institution} i
                        LEFT OUTER JOIN {usr_institution} ui ON (ui.institution = i.name)
                        LEFT OUTER JOIN {usr} u ON (u.id = ui.usr)
                    WHERE
                        (u.deleted = 0 OR u.id IS NULL)
                    GROUP BY
                        i.name, i.displayname, i.maxuseraccounts
647
648
                    ) a ON (a.name = ii.name)
                    WHERE (' . $namesql . ')' . $where . '
649
                    ORDER BY
650
                        ii.name = \'mahara\', ii.displayname', $queryvalues, $offset, $limit);
651

652
        if ($showdefault && $institutions && array_key_exists('mahara', $institutions)) {
653
654
655
656
657
658
659
660
661
662
            $defaultinstmembers = count_records_sql('
                SELECT COUNT(u.id) FROM {usr} u LEFT OUTER JOIN {usr_institution} i ON u.id = i.usr
                WHERE u.deleted = 0 AND i.usr IS NULL AND u.id != 0
            ');
            $institutions['mahara']->members = $defaultinstmembers;
            $institutions['mahara']->staff   = '';
            $institutions['mahara']->admins  = '';
        }
        return $institutions;
    }
663
}
Richard Mansfield's avatar
Richard Mansfield committed
664

665
function get_institution_selector($includedefault = true) {
Richard Mansfield's avatar
Richard Mansfield committed
666
667
668
    global $USER;

    if ($USER->get('admin')) {
669
        if ($includedefault) {
670
            $institutions = get_records_array('institution', '', '', 'displayname');
671
672
        }
        else {
673
            $institutions = get_records_select_array('institution', "name != 'mahara'", null, 'displayname');
674
        }
Richard Mansfield's avatar
Richard Mansfield committed
675
    } else if ($USER->is_institutional_admin()) {
676
677
678
679
680
        $institutions = get_records_select_array(
            'institution',
            'name IN (' . join(',', array_map('db_quote',$USER->get('admininstitutions'))) . ')',
            null, 'displayname'
        );
Richard Mansfield's avatar
Richard Mansfield committed
681
682
683
684
    } else {
        return null;
    }

685
686
687
688
    if (empty($institutions)) {
        return null;
    }

689
690
691
    $options = array();
    foreach ($institutions as $i) {
        $options[$i->name] = $i->displayname;
Richard Mansfield's avatar
Richard Mansfield committed
692
    }
693
694
695
696
697
698
699
700
    $institution = key($options);
    $institutionelement = array(
        'type' => 'select',
        'title' => get_string('institution'),
        'defaultvalue' => $institution,
        'options' => $options,
        'rules' => array('regex' => '/^[a-zA-Z0-9]+$/')
    );
Richard Mansfield's avatar
Richard Mansfield committed
701
702
703
704

    return $institutionelement;
}

705
706
/* The institution selector does exactly the same thing in both
   institutionadmins.php and institutionstaff.php (in /admin/users/).
Richard Mansfield's avatar
Richard Mansfield committed
707
708
   This function creates the form for the page. */
function institution_selector_for_page($institution, $page) {
709
710
711
    require_once('pieforms/pieform.php');
    $institutionelement = get_institution_selector(false);

712
    if (empty($institutionelement)) {
Richard Mansfield's avatar
Richard Mansfield committed
713
        return array('institution' => false, 'institutionselector' => null, 'institutionselectorjs' => '');
714
715
    }

716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
    global $USER;
    if (empty($institution) || !$USER->can_edit_institution($institution)) {
        $institution = empty($institutionelement['value']) ? $institutionelement['defaultvalue'] : $institutionelement['value'];
    }
    else {
        $institutionelement['defaultvalue'] = $institution;
    }
    
    $institutionselector = pieform(array(
        'name' => 'institutionselect',
        'elements' => array(
            'institution' => $institutionelement,
        )
    ));
    
    $js = <<< EOF
function reloadUsers() {
    var inst = '';
    if ($('institutionselect_institution')) {
        inst = '?institution='+$('institutionselect_institution').value;
    }
    window.location.href = '{$page}'+inst;
}
addLoadEvent(function() {
    if ($('institutionselect_institution')) {
        connect($('institutionselect_institution'), 'onchange', reloadUsers);
    }
});
EOF;
    
Richard Mansfield's avatar
Richard Mansfield committed
746
747
748
749
750
    return array(
        'institution'           => $institution,
        'institutionselector'   => $institutionselector,
        'institutionselectorjs' => $js
    );
751
}
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779

function build_institutions_html($filter, $showdefault, $query, $limit, $offset, &$count=null) {
    global $USER;

    $institutions = Institution::count_members($filter, $showdefault, $query, $limit, $offset, $count);

    $smarty = smarty_core();
    $smarty->assign('institutions', $institutions);
    $smarty->assign('siteadmin', $USER->get('admin'));
    $data['tablerows'] = $smarty->fetch('admin/users/institutionsresults.tpl');

    $pagination = build_pagination(array(
                'id' => 'adminstitutionslist_pagination',
                'datatable' => 'adminstitutionslist',
                'url' => get_config('wwwroot') . 'admin/users/institutions.php' . (!empty($query) ? '?query=' . urlencode($query) : ''),
                'jsonscript' => 'admin/users/institutions.json.php',
                'count' => $count,
                'limit' => $limit,
                'offset' => $offset,
                'resultcounttextsingular' => get_string('institution', 'admin'),
                'resultcounttextplural' => get_string('institutions', 'admin'),
            ));

    $data['pagination'] = $pagination['html'];
    $data['pagination_js'] = $pagination['javascript'];

    return $data;
}