institution.php 15 KB
Newer Older
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
4
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
 * Copyright (C) 2006-2007 Catalyst IT Ltd (http://www.catalyst.net.nz)
5
 *
Francois Marier's avatar
Francois Marier committed
6
7
8
9
 * 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.
10
 *
Francois Marier's avatar
Francois Marier committed
11
12
13
14
 * 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.
15
 *
Francois Marier's avatar
Francois Marier committed
16
17
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19
20
21
22
23
24
25
26
 *
 * @package    mahara
 * @subpackage auth-internal
 * @author     Nigel McNie <nigel@catalyst.net.nz>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2006,2007 Catalyst IT Ltd http://catalyst.net.nz
 *
 */

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

29
defined('INTERNAL') || die();
Donal McMullan's avatar
Donal McMullan committed
30
require_once(get_config('libroot') .'hostset.php');
31
32
33
34
35
36
37
38
39
40
41
42
43
44

class Institution {

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

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

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

55
        if (!$this->findByName($name)) {
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
81
82
83
84
85
86
87
88
89
90
91
            throw new ParamOutOfRangeException('No such institution');
        }
    }

    function __get($name) {
        if ($name == 'hosts') {
            if (count($this->hosts) == 0 && $this->ready) {
                $this->getHostData();
            }
        }
        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");
            }
        } elseif ($name == 'updateuserinfoonlogin') {
            if (!is_numeric($value) || $value < 0 || $value > 1) {
                throw new ParamOutOfRangeException("'updateuserinfoonlogin' should be zero or one");
            }
92
93
94
        } elseif ($name == 'theme') {
            if (!is_string($value) || empty($value) || strlen($value) > 255) {
                throw new ParamOutOfRangeException("'theme' ($value) should be a string between 1 and 255 characters in length");
95
            }
96
97
98
        } 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");
99
            }
100
101
        } elseif ($name == 'maxuseraccounts') {
            if (!empty($value) && (!is_numeric($value) || $value < 0 || $value > 9999999999)) {
102
                throw new ParamOutOfRangeException("'maxuseraccounts' should be a number between 1 and 9,999,999,999");
103
            }
104
105
106
107
108
        }
        $this->members[$name] = $value;
    }

    function findByName($name) {
109

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
        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 findByWwwroot($wwwroot) {
127

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
        if (!is_string($wwwroot) || strlen($wwwroot) < 1 || strlen($wwwroot) > 255) {
            throw new SystemException();
        }

        $this->hostset = new HostSet();
        $this->hostset->findByWwwroot($wwwroot);
        if (false == $a_host = $this->hostset->current()) {
            return false;
        }
        $institution = $a_host->institution;

        $result = get_record('institution', 'name', $institution);
        if (false == $result) {
            throw new SystemException('Invalid Institution name');
        }

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

    function getHostData() {
        $this->hostset = new HostSet();
        $this->hostset->findByInstitution($this->name);
    }

    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()) {
            throw new Exception();
        }

        $record = new stdClass();
        $record->name                         = $this->name;
        $record->displayname                  = $this->displayname;
        $record->updateuserinfoonlogin        = $this->updateuserinfoonlogin;
188
189
        $record->theme                        = $this->theme;
        $record->defaultmembershipperiod      = $this->defaultmembershipperiod;
190
        $record->maxuseraccounts              = $this->maxuseraccounts;
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217

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

    function findByHostset(HostSet $hostset) {

        // get the first host record:
        $host = reset($hostset);

        $result = get_record('institution', 'name', $host->institution);
        if (false == $result) {
            throw new SystemException('No institution for hostset '.addslashes($host->institution));
        }
        $this->populate($result);
    }

    protected function populate($result) {
        $this->name                         = $result->name;
        $this->displayname                  = $result->displayname;
        $this->registerallowed              = $result->registerallowed;
        $this->updateuserinfoonlogin        = $result->updateuserinfoonlogin;
218
219
        $this->theme                        = $result->theme;
        $this->defaultmembershipperiod      = $result->defaultmembershipperiod;
220
        $this->maxuseraccounts              = $result->maxuseraccounts;
221
222
223
        $this->verifyReady();
    }

224
    public function addUserAsMember($user) {
225
226
227
        if (is_numeric($user)) {
            $user = get_record('usr', 'id', $user);
        }
228
229
        $userinst = new StdClass;
        $userinst->institution = $this->name;
230
231
232
233
234
235
        $studentid = get_field('usr_institution_request', 'studentid', 'usr', $user->id, 
                               'institution', $this->name);
        if (!empty($studentid)) {
            $userinst->studentid = $studentid;
        }
        else if (!empty($user->studentid)) {
236
            $userinst->studentid = $user->studentid;
237
        }
238
        $userinst->usr = $user->id;
239
240
        $now = time();
        $userinst->ctime = db_format_timestamp($now);
241
242
243
        $defaultexpiry = $this->defaultmembershipperiod;
        if (!empty($defaultexpiry)) {
            $userinst->expiry = db_format_timestamp($now + $defaultexpiry);
244
        }
245
246
247
248
249
        $message = (object) array(
            'users' => array($user->id),
            'subject' => get_string('institutionmemberconfirmsubject'),
            'message' => get_string('institutionmemberconfirmmessage', 'mahara', $this->displayname),
        );
250
        db_begin();
251
252
        if (!get_config('usersallowedmultipleinstitutions')) {
            delete_records('usr_institution', 'usr', $user->id);
253
            delete_records('usr_institution_request', 'usr', $user->id);
254
        }
255
256
        insert_record('usr_institution', $userinst);
        delete_records('usr_institution_request', 'usr', $userinst->usr, 'institution', $this->name);
257
        activity_occurred('maharamessage', $message);
258
        handle_event('updateuser', $userinst->usr);
259
        db_commit();
260
261
    }

262
    public function addRequestFromUser($user, $studentid = null) {
263
264
265
266
267
268
        $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,
269
                'studentid'    => empty($studentid) ? $user->studentid : $studentid,
270
271
                'ctime'        => db_format_timestamp(time())
            );
272
273
274
275
276
277
278
            $message = (object) array(
                'messagetype' => 'request',
                'username' => $user->username,
                'fullname' => $user->firstname . ' ' . $user->lastname,
                'institution' => (object)array('name' => $this->name, 'displayname' => $this->displayname),
            );
            db_begin();
279
280
281
            if (!get_config('usersallowedmultipleinstitutions')) {
                delete_records('usr_institution_request', 'usr', $user->id);
            }
282
            insert_record('usr_institution_request', $request);
283
284
285
            activity_occurred('institutionmessage', $message);
            handle_event('updateuser', $user->id);
            db_commit();
286
287
288
289
290
        } else if ($request->confirmedinstitution) {
            $this->addUserAsMember($user);
        }
    }

291
292
    public function inviteUser($user) {
        $userid = is_object($user) ? $user->id : $user;
293
        db_begin();
294
295
296
297
298
299
        insert_record('usr_institution_request', (object) array(
            'usr' => $userid,
            'institution' => $this->name,
            'confirmedinstitution' => 1,
            'ctime' => db_format_timestamp(time())
        ));
300
301
302
303
304
        activity_occurred('institutionmessage', (object) array(
            'messagetype' => 'invite',
            'users' => array($userid),
            'institution' => (object)array('name' => $this->name, 'displayname' => $this->displayname),
        ));
305
        handle_event('updateuser', $userid);
306
        db_commit();
307
308
    }

309
310
    public function removeMember($user) {
        $userid = is_object($user) ? $user->id : $user;
311
312
313
        delete_records('usr_institution', 'usr', $userid, 'institution', $this->name);
        handle_event('updateuser', $userid);
    }
314
315
316
317
318
319
320
321
322
323
324
325
326

    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));
    }
327
}
Richard Mansfield's avatar
Richard Mansfield committed
328

329
function get_institution_selector($includedefault = true) {
Richard Mansfield's avatar
Richard Mansfield committed
330
331
332
    global $USER;

    if ($USER->get('admin')) {
333
334
335
336
337
338
        if ($includedefault) {
            $institutions = get_records_array('institution');
        }
        else {
            $institutions = get_records_select_array('institution', "name != 'mahara'");
        }
Richard Mansfield's avatar
Richard Mansfield committed
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    } else if ($USER->is_institutional_admin()) {
        $institutions = get_records_select_array('institution', 'name IN (' 
            . join(',', array_map('db_quote',$USER->get('admininstitutions'))) . ')');
    } else {
        return null;
    }

    if (count($institutions) > 1) {
        $options = array();
        foreach ($institutions as $i) {
            $options[$i->name] = $i->displayname;
        }
        $institution = key($options);
        $institutionelement = array(
            'type' => 'select',
            'title' => get_string('institution'),
            'defaultvalue' => $institution,
356
357
            'options' => $options,
            'rules' => array('regex' => '/^[a-zA-Z0-9]+$/')
Richard Mansfield's avatar
Richard Mansfield committed
358
359
360
361
362
363
        );
    } else {
        $institution = $institutions[0]->name;
        $institutionelement = array(
            'type' => 'hidden',
            'value' => $institution,
364
            'rules' => array('regex' => '/^[a-zA-Z0-9]+$/')
Richard Mansfield's avatar
Richard Mansfield committed
365
366
367
368
369
370
        );
    }

    return $institutionelement;
}

371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/* The institution selector does exactly the same thing in both
   institutionadmins.php and institutionstaff.php (in /admin/users/).
   This function creates the form for the page, setting
   $institutionselector and $INLINEJAVASCRIPT in the smarty object. */
function add_institution_selector_to_page($smarty, $institution, $page) {
    require_once('pieforms/pieform.php');
    $institutionelement = get_institution_selector(false);

    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;
    
    $smarty->assign('institutionselector', $institutionselector);
    $smarty->assign('INLINEJAVASCRIPT', $js);

    return $institution;
}
414
?>