institutions.php 28.6 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 admin
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
 *
 */
define('INTERNAL', 1);
28
define('INSTITUTIONALADMIN', 1);
29
require(dirname(dirname(dirname(__FILE__))) . '/init.php');
Martyn Smith's avatar
Martyn Smith committed
30
define('TITLE', get_string('institutions', 'admin'));
Penny Leach's avatar
Penny Leach committed
31
32
33
define('SECTION_PLUGINTYPE', 'core');
define('SECTION_PLUGINNAME', 'admin');
define('SECTION_PAGE', 'institutions');
34
require_once('pieforms/pieform.php');
35
define('MENUITEM', 'manageinstitutions/institutions');
36
37
38

$institution = param_variable('i', '');
$add         = param_boolean('add');
39
40
$edit        = param_boolean('edit');
$delete      = param_boolean('delete');
41

42
43
44
45
$query = param_variable('query', '');
$offset = param_integer('offset', 0);
$limit  = 20;

46
47
48
49
50
51
52
53
54
55
56
if (!$USER->get('admin')) {
    // Institutional admins with only 1 institution go straight to the edit page for that institution
    // They cannot add or delete institutions, or edit an institution they don't administer
    $add = false;
    $delete = false;
    if (!empty($institution) && !$USER->is_institutional_admin($institution)) {
        $institution = '';
        $edit = false;
    }
    if (empty($institution) && count($USER->get('admininstitutions')) == 1) {
        redirect(get_config('wwwroot') . 'admin/users/institutions.php?i='
57
                 . key($USER->get('admininstitutions')));
58
59
60
    }
}

61
62
if ($institution || $add) {

63
64
65
66
67
    $authinstances = auth_get_auth_instances_for_institution($institution);
    if (false == $authinstances) {
        $authinstances = array();
    }

68
    if ($delete) {
69
        function delete_validate(Pieform $form, $values) {
70
            if (get_field('usr_institution', 'COUNT(*)', 'institution', $values['i'])) {
71
                throw new ConfigException('Attempt to delete an institution that has members');
72
73
74
            }
        }

75
        function delete_cancel_submit() {
76
            redirect('/admin/users/institutions.php');
77
78
        }

79
        function delete_submit(Pieform $form, $values) {
80
81
            global $SESSION;

82
            $authinstanceids = get_column('auth_instance', 'id', 'institution', $values['i']);
83
84
            $viewids = get_column('view', 'id', 'institution', $values['i']);
            $artefactids = get_column('artefact', 'id', 'institution', $values['i']);
85

86
            db_begin();
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
            if ($viewids) {
                require_once(get_config('libroot') . 'view.php');
                foreach ($viewids as $viewid) {
                    $view = new View($viewid);
                    $view->delete();
                }
            }
            if ($artefactids) {
                foreach ($artefactids as $artefactid) {
                    try {
                        $a = artefact_instance_from_id($artefactid);
                        $a->delete();
                    }
                    catch (ArtefactNotFoundException $e) {
                        // Awesome, it's already gone.
                    }
                }
            }
105
106
107
            foreach ($authinstanceids as $id) {
                delete_records('auth_instance_config', 'instance', $id);
            }
108
109
110
111
112
113

            // The institution should have been removed from favourites lists when the members were removed,
            // but make sure it's gone.
            execute_sql('DELETE FROM {favorite_usr} WHERE favorite IN (SELECT id FROM {favorite} WHERE institution = ?)', array($values['i']));
            delete_records('favorite', 'institution', $values['i']);

114
            execute_sql("UPDATE {group} SET institution = NULL, shortname = NULL WHERE institution = ?", array($values['i']));
115
116
            delete_records('auth_instance', 'institution', $values['i']);
            delete_records('host', 'institution', $values['i']);
117
            delete_records('institution_locked_profile_field', 'name', $values['i']);
118
            delete_records('usr_institution_request', 'institution', $values['i']);
119
120
121
122
            delete_records('institution', 'name', $values['i']);
            db_commit();

            $SESSION->add_ok_msg(get_string('institutiondeletedsuccessfully', 'admin'));
123
            redirect('/admin/users/institutions.php');
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
        }
        $form = array(
            'name' => 'delete',
            'elements' => array(
                'i' => array(
                    'type' => 'hidden',
                    'value' => $institution
                ),
                'delete' => array(
                    'type' => 'hidden',
                    'value' => 1
                ),
                'submit' => array(
                    'type' => 'submitcancel',
                    'value' => array(get_string('yes'), get_string('no'))
                )
            )
        );
142
143
144
        $deleteform = pieform($form);
        $smarty = smarty();
        $smarty->assign('delete_form', $deleteform);
145
        $smarty->assign('institutionname', get_field('institution', 'displayname', 'name', $institution));
146
        $smarty->display('admin/users/institutions.tpl');
147
148
149
        exit;
    }

150
151
152
    $instancearray = array();
    $instancestring = '';
    $c = count($authinstances);
153
    $inuse = '';
154

155
156
    $sitelockedfields = (array) get_column('institution_locked_profile_field', 'profilefield', 'name', 'mahara');

157
158
    if (!$add) {
        $data = get_record('institution', 'name', $institution);
159
        $lockedprofilefields = (array) get_column('institution_locked_profile_field', 'profilefield', 'name', $institution);
160

161
        // TODO: Find a better way to work around Smarty's minimal looping logic
162
163
164
165
        if (!empty($authinstances)) {
            foreach($authinstances as $key => $val) {
                $authinstances[$key]->index = $key;
                $authinstances[$key]->total = $c;
166
                $instancearray[] = (int)$val->id;
167
            }
168

169
170
            $instancestring = implode(',',$instancearray);
            $inuserecords = array();
171
172
            if ($records = get_records_sql_assoc('select authinstance, count(id) from {usr} where authinstance in ('.$instancestring.') group by authinstance', array())) {
                foreach ($records as $record) {
Richard Mansfield's avatar
Richard Mansfield committed
173
                    $inuserecords[] = $record->authinstance;
174
                }
175
176
            }
            $inuse = implode(',',$inuserecords);
177
        }
178
        $authtypes = auth_get_available_auth_types($institution);
179
180
181
182
    }
    else {
        $data = new StdClass;
        $data->displayname = '';
183
        $data->expiry = null;
184
185
186
        if (!get_config('usersuniquebyusername')) {
            $data->registerallowed = 1;
        }
187
        $data->theme = 'sitedefault';
188
        $data->defaultmembershipperiod = null;
189
        $data->showonlineusers = 2;
190
        $data->allowinstitutionpublicviews = get_config('allowpublicviews') ? 1 : 0;
191
        $lockedprofilefields = array();
192
193

        $authtypes = auth_get_available_auth_types();
194
    }
195
    $themeoptions = get_institution_themes($institution);
196
    $themeoptions['sitedefault'] = '- ' . get_string('sitedefault', 'admin') . ' (' . $themeoptions[get_config('theme')] . ') -';
197
    uksort($themeoptions, 'theme_sort');
198

199
    $showonlineusersoptions = array('0' => get_string('none'), '1' => get_string('institutiononly', 'admin'), '2' => get_string('all', 'admin'));
200
201
    $sitename = get_config('sitename');

202
    safe_require('artefact', 'internal');
203
204
    $elements = array(
        'name' => array(
205
            'type' => 'text',
206
            'title' => get_string('institutionname', 'admin'),
207
208
209
            'rules' => array(
                'required'  => true,
                'maxlength' => 255,
210
                'regex'     => '/^[a-zA-Z]+$/'
211
            ),
Penny Leach's avatar
Penny Leach committed
212
213
            'ignore' => !$add,
            'help'   => true,
214
215
216
217
218
219
        ),
        'add' => array(
            'type'   => 'hidden',
            'value'  => true,
            'ignore' => !$add
        ),
220
221
222
        'inuse' => array(
            'type'   => 'hidden',
            'value'  => $inuse,
223
224
            'id'     => 'inuse',
            'ignore' => $add
225
        ),
226
227
228
229
230
231
232
233
234
235
236
237
        'i' => array(
            'type'   => 'hidden',
            'value'  => $institution,
            'ignore' => $add
        ),
        'displayname' => array(
            'type' => 'text',
            'title' => get_string('institutiondisplayname', 'admin'),
            'defaultvalue' => $data->displayname,
            'rules' => array(
                'required'  => true,
                'maxlength' => 255
Penny Leach's avatar
Penny Leach committed
238
239
            ),
            'help'   => true,
240
        ),
241
    );
242
    if ($USER->get('admin') && $institution != 'mahara') {
243
       $elements['expiry'] = array(
244
245
            'type'         => 'date',
            'title'        => get_string('institutionexpiry', 'admin'),
246
            'description'  => get_string('institutionexpirydescription', 'admin', hsc($sitename)),
247
248
249
250
            'defaultvalue' => is_null($data->expiry) ? null : strtotime($data->expiry),
            'help'         => true,
            'minyear'      => date('Y') - 2,
            'maxyear'      => date('Y') + 10,
251
252
        );
    }
253
254
    if ($USER->get('admin')) {
        $elements['authplugin'] = array(
255
256
257
258
259
            'type'    => 'authlist',
            'title'   => get_string('authplugin', 'admin'),
            'options' => $authinstances,
            'authtypes' => $authtypes,
            'instancearray' => $instancearray,
260
            'instancestring' => $instancestring,
261
262
            'institution' => $institution,
            'help'   => true,
263
            'ignore' => count($authtypes) == 0 || $institution == ''
264
265
266
        );
    }

267
    if (!$add && empty($authinstances)) {
268
        if ($USER->get('admin')) {
269
            $SESSION->add_error_msg(get_string('adminnoauthpluginforinstitution', 'admin'));
270
271
        }
        else {
272
            $SESSION->add_error_msg(get_string('noauthpluginforinstitution', 'admin'));
273
274
275
        }
    }

276
277
278
279
280
281
282
283
284
    if (!get_config('usersuniquebyusername')) {
        $elements['registerallowed'] = array(
            'type'         => 'checkbox',
            'title'        => get_string('registrationallowed', 'admin'),
            'description'  => get_string('registrationalloweddescription2', 'admin'),
            'defaultvalue' => $data->registerallowed,
            'help'   => true,
        );
    }
285

286
    if (empty($data->name) || $data->name != 'mahara') {
287
        $elements['defaultmembershipperiod'] = array(
288
            'type'         => 'expiry',
289
290
291
            'title'        => get_string('defaultmembershipperiod', 'admin'),
            'description'  => get_string('defaultmembershipperioddescription', 'admin'),
            'defaultvalue' => $data->defaultmembershipperiod,
Penny Leach's avatar
Penny Leach committed
292
            'help'   => true,
293
294
        );
        $elements['theme'] = array(
295
            'type'         => 'select',
296
            'title'        => get_string('theme'),
297
            'description'  => get_string('sitethemedescription','admin'),
298
            'defaultvalue' => $data->theme ? $data->theme : 'sitedefault',
299
300
301
            'collapseifoneoption' => true,
            'options'      => $themeoptions,
            'help'         => true,
302
        );
303
304
305
306
307
308
309
310
        $elements['showonlineusers'] = array(
            'type'                  => 'select',
            'title'                 => get_string('showonlineusers', 'admin'),
            'description'           => get_string('showonlineusersdesc','admin'),
            'defaultvalue'          => $data->showonlineusers,
            'collapseifoneoption'   => true,
            'options'               => $showonlineusersoptions,
        );
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
        if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
            $elements['defaultquota'] = array(
               'type'         => 'bytes',
               'title'        => get_string('defaultquota', 'artefact.file'),
               'description'  => get_string('defaultinstitutionquotadescription', 'admin'),
               'defaultvalue' => !empty($data->defaultquota) ? $data->defaultquota : get_config_plugin('artefact', 'file', 'defaultquota'),
            );
        }
        else {
            $elements['defaultquota'] = array(
                'type' => 'text',
                'title' => get_string('defaultquota', 'artefact.file'),
                'value' => display_size(!empty($data->defaultquota) ? $data->defaultquota : get_config_plugin('artefact', 'file', 'defaultquota')),
                'disabled' => true,
            );
        }
327
328
329
330
331
332
333
334
335
336

        $elements['allowinstitutionpublicviews'] = array(
            'type'         => 'checkbox',
            'title'        => get_string('allowinstitutionpublicviews', 'admin'),
            'description'  => get_string('allowinstitutionpublicviewsdescription','admin'),
            'defaultvalue' => get_config('allowpublicviews') && $data->allowinstitutionpublicviews,
            'disabled'     => get_config('allowpublicviews') == false,
            'help'         => true,
        );

337
338
339
340
341
342
        if ($USER->get('admin')) {
            $elements['maxuseraccounts'] = array(
                'type'         => 'text',
                'title'        => get_string('maxuseraccounts','admin'),
                'description'  => get_string('maxuseraccountsdescription','admin'),
                'defaultvalue' => empty($data->maxuseraccounts) ? '' : $data->maxuseraccounts,
343
344
345
346
347
                'rules'        => array(
                    'regex'     => '/^\d*$/',
                    'maxlength' => 8,
                ),
                'size'         => 5,
348
349
            );
        }
350
    }
351

352
    $elements['lockedfields'] = array(
353
        'type' => 'fieldset',
354
        'legend' => get_string('Lockedfields', 'admin'),
355
356
357
        'collapsible' => true,
        'collapsed' => true,
        'elements' => array(),
358
    );
359
360
361
362
363
364
    if ($institution != 'mahara') {
        $elements['lockedfields']['elements']['description'] = array(
            'type' => 'html',
            'value' => get_string('disabledlockedfieldhelp', 'admin', get_field('institution', 'displayname', 'name', 'mahara')),
        );
    }
365
    foreach (ArtefactTypeProfile::get_all_fields() as $field => $type) {
366
        $elements['lockedfields']['elements'][$field] = array(
367
            'type' => 'checkbox',
368
            'title' => get_string($field, 'artefact.internal'),
369
370
            'defaultvalue' => in_array($field, $lockedprofilefields) || ($institution != 'mahara' && in_array($field, $sitelockedfields)),
            'disabled' => $institution != 'mahara' && in_array($field, $sitelockedfields)
371
372
        );
    }
373
    $elements['lockedfieldshelp'] = array(
Evonne Cheung's avatar
Evonne Cheung committed
374
        'value' => '<tr id="lockedfieldshelp"><th colspan="2">'
375
376
377
378
        . get_help_icon('core', 'admin', 'institution', 'lockedfields') 
        . '</th></tr>'
    );

379
380
381
382
383
    $elements['submit'] = array(
        'type' => 'submitcancel',
        'value' => array(get_string('submit'), get_string('cancel'))
    );

384
    $institutionform = pieform(array(
385
        'name'     => 'institution',
386
        'renderer' => 'table',
Penny Leach's avatar
Penny Leach committed
387
388
        'plugintype' => 'core',
        'pluginname' => 'admin',
389
        'elements' => $elements
390
    ));
391
392
393
394

}
else {
    // Get a list of institutions
395
    require_once(get_config('libroot') . 'institution.php');
396
    if (!$USER->get('admin')) { // Filter the list for institutional admins
397
398
        $filter      = $USER->get('admininstitutions');
        $showdefault = false;
399
400
    }
    else {
401
402
        $filter      = false;
        $showdefault = true;
403
    }
404
    $data = build_institutions_html($filter, $showdefault, $query, $limit, $offset, $count);
405
406

    $smarty = smarty(array('lib/pieforms/static/core/pieforms.js', 'paginator'));
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
    $smarty->assign('results', $data);
    $smarty->assign('countinstitutions', $count);

    /*search institution form*/
    $searchform = pieform(array(
        'name' => 'search',
        'renderer' => 'oneline',
        'elements' => array(
            'query' => array(
                'type' => 'text',
                'defaultvalue' => $query
            ),
            'submit' => array(
                'type' => 'submit',
                'value' => get_string('search')
            )
        )
    ));
    $smarty->assign('searchform', $searchform);

    $js = <<< EOF
    addLoadEvent(function () {
    p = {$data['pagination_js']}
    connect('search_submit', 'onclick', function (event) {
        replaceChildNodes('messages');
        var params = {'query': $('search_query').value};
        p.sendQuery(params);
        event.stop();
        });
    });
EOF;

    $smarty->assign('INLINEJAVASCRIPT', $js);
440
441
442
443
    $smarty->assign('siteadmin', $USER->get('admin'));
    $smarty->assign('PAGEHEADING', get_string('admininstitutions', 'admin'));
    $smarty->display('admin/users/institutions.tpl');
    exit;
444
445
}

446
function institution_validate(Pieform $form, $values) {
447
448
    global $USER;

449
    if (!empty($values['name']) && !$form->get_error('name') && record_exists('institution', 'name', $values['name'])) {
450
451
        $form->set_error('name', get_string('institutionnamealreadytaken', 'admin'));
    }
452
453
454
455
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        if (get_config_plugin('artefact', 'file', 'maxquotaenabled') && get_config_plugin('artefact', 'file', 'maxquota') < $values['defaultquota']) {
            $form->set_error('defaultquota', get_string('maxquotatoolow', 'artefact.file'));
        }
456
    }
457
458
}

459
function institution_submit(Pieform $form, $values) {
460
    global $SESSION, $institution, $add, $instancearray, $USER, $authinstances;
461
462
463
464
465

    db_begin();
    // Update the basic institution record...
    $newinstitution = new StdClass;
    if ($add) {
466
        $institution = $newinstitution->name = strtolower($values['name']);
467
468
469
    }

    $newinstitution->displayname                  = $values['displayname'];
470
    $newinstitution->authplugin                   = empty($values['authplugin']) ? null : $values['authplugin'];
471
    $newinstitution->showonlineusers              = empty($values['showonlineusers']) ? 2 : $values['showonlineusers'];
472
473
474
475
476
477
478
479
480
    if (get_config('usersuniquebyusername')) {
        // Registering absolutely not allowed when this setting is on, it's a 
        // security risk. See the documentation for the usersuniquebyusername 
        // setting for more information
        $newinstitution->registerallowed = 0;
    }
    else {
        $newinstitution->registerallowed              = ($values['registerallowed']) ? 1 : 0;
    }
481
    $newinstitution->theme                        = (empty($values['theme']) || $values['theme'] == 'sitedefault') ? null : $values['theme'];
482
483

    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
484
        $newinstitution->defaultquota = empty($values['defaultquota']) ? get_config_plugin('artefact', 'file', 'defaultquota') : $values['defaultquota'];
485
    }
486
487
488
489
    if ($institution != 'mahara') {
        $newinstitution->defaultmembershipperiod  = ($values['defaultmembershipperiod']) ? intval($values['defaultmembershipperiod']) : null;
        if ($USER->get('admin')) {
            $newinstitution->maxuseraccounts      = ($values['maxuseraccounts']) ? intval($values['maxuseraccounts']) : null;
490
            $newinstitution->expiry               = db_format_timestamp($values['expiry']);
491
        }
492
493
    }

494
495
    $newinstitution->allowinstitutionpublicviews  = (isset($values['allowinstitutionpublicviews']) && $values['allowinstitutionpublicviews']) ? 1 : 0;

496
497
    if (!empty($values['authplugin'])) {
        $allinstances = array_merge($values['authplugin']['instancearray'], $values['authplugin']['deletearray']);
498

499
        if (array_diff($allinstances, $instancearray)) {
500
            throw new ConfigException('Attempt to delete or update another institution\'s auth instance');
501
        }
502

503
        if (array_diff($instancearray, $allinstances)) {
504
            throw new ConfigException('One of your instances is unaccounted for in this transaction');
505
506
        }

507
508
509
        foreach($values['authplugin']['instancearray'] as $priority => $instanceid) {
            if (in_array($instanceid, $values['authplugin']['deletearray'])) {
                // Should never happen:
510
                throw new SystemException('Attempt to update AND delete an auth instance');
511
512
513
514
515
516
517
518
            }
            $record = new StdClass;
            $record->priority = $priority;
            $record->id = $instanceid;
            update_record('auth_instance', $record,  array('id' => $instanceid));
        }

        foreach($values['authplugin']['deletearray'] as $instanceid) {
519
520
521
522
            // If this authinstance is the only xmlrpc authinstance that references a host, delete the host record.
            $hostwwwroot = null;
            foreach ($authinstances as $ai) {
                if ($ai->id == $instanceid && $ai->authname == 'xmlrpc') {
Francois Marier's avatar
Francois Marier committed
523
524
                    $hostwwwroot = get_field_sql("SELECT \"value\" FROM {auth_instance_config} WHERE \"instance\" = ? AND field = 'wwwroot'", array($instanceid));
                    if ($hostwwwroot && count_records_select('auth_instance_config', "field = 'wwwroot' AND \"value\" = ?", array($hostwwwroot)) == 1) {
525
526
527
528
529
530
531
532
533
                        // Unfortunately, it's possible that this host record could belong to a different institution,
                        // so specify the institution here.
                        delete_records('host', 'wwwroot', $hostwwwroot, 'institution', $institution);
                        // We really need to fix this, either by removing the institution from the host table, or refusing to allow the
                        // institution to be changed in the host record when another institution's authinstance is still pointing at it.
                    }
                    break;
                }
            }
534
535
536
537
            delete_records('auth_remote_user', 'authinstance', $instanceid);
            delete_records('auth_instance_config', 'instance', $instanceid);
            delete_records('auth_instance', 'id', $instanceid);
        }
538
539
    }

540
541
    if ($add) {
        insert_record('institution', $newinstitution);
542
543
544
545
546
547
548
549
550
551
552
        // If registration has been turned on, then we automatically insert an 
        // internal authentication authinstance
        if ($newinstitution->registerallowed) {
            $authinstance = (object)array(
                'instancename' => 'internal',
                'priority'     => 0,
                'institution'  => $newinstitution->name,
                'authname'     => 'internal',
            );
            insert_record('auth_instance', $authinstance);
        }
553
    }
554
    else {
555
556
        $where = new StdClass;
        $where->name = $institution;
557
        $oldtheme = get_field('institution', 'theme', 'name', $institution);
558
559
560
561
562
563
564
565
566
567
568
569
570
571
        update_record('institution', $newinstitution, $where);
    }

    delete_records('institution_locked_profile_field', 'name', $institution);
    foreach (ArtefactTypeProfile::get_all_fields() as $field => $type) {
        if ($values[$field]) {
            $profilefield = new StdClass;
            $profilefield->name         = $institution;
            $profilefield->profilefield = $field;
            insert_record('institution_locked_profile_field', $profilefield);
        }
    }
    db_commit();

572
    if ($add) {
573
574
575
576
577
578
        if ($newinstitution->registerallowed) {
            // If registration is not allowed, then an authinstance will not 
            // have been created, and thus cause the institution page to add 
            // its own error message on the next page load
            $SESSION->add_ok_msg(get_string('institutionaddedsuccessfully2', 'admin'));
        }
579
580
581
        $nexturl = '/admin/users/institutions.php?i='.urlencode($institution);
    }
    else {
582
        $message = get_string('institutionupdatedsuccessfully', 'admin');
583
        if (isset($values['theme']) && $oldtheme != $values['theme']
584
            && (!empty($oldtheme) || $values['theme'] != 'sitedefault')) {
585
            $USER->update_theme();
586
587
            $message .= '  ' . get_string('usersseenewthemeonlogin', 'admin');
        }
588
        $SESSION->add_ok_msg($message);
589
590
591
592
        $nexturl = '/admin/users/institutions.php';
    }

    redirect($nexturl);
593
594
595
}

function institution_cancel_submit() {
596
    redirect('/admin/users/institutions.php');
597
598
}

599
600
601
602
603
604
605
606
607
608
609
610
611
612
if ($institution && $institution != 'mahara') {
    $_institution = get_record('institution', 'name', $institution);
    $suspended = $_institution->suspended;
    if ($USER->get('admin')) {
        function institution_suspend_submit(Pieform $form, $values) {
            global $SESSION, $USER;
            if (!$USER->get('admin')) {
                $SESSION->add_error_msg(get_string('errorwhilesuspending', 'admin'));
            }
            else {
                set_field('institution', 'suspended', 1, 'name', $values['i']);
                $SESSION->add_ok_msg(get_string('institutionsuspended', 'admin'));
            }
            redirect('/admin/users/institutions.php?i=' . $values['i']);
613
        }
614
615
616
617
618
619
620
621
622
623
624

        function institution_unsuspend_submit(Pieform $form, $values) {
            global $SESSION, $USER;
            if (!$USER->get('admin')) {
                $SESSION->add_error_msg(get_string('errorwhileunsuspending', 'admin'));
            }
            else {
                set_field('institution', 'suspended', 0, 'name', $values['i']);
                $SESSION->add_ok_msg(get_string('institutionunsuspended', 'admin'));
            }
            redirect('/admin/users/institutions.php?i=' . $values['i']);
625
        }
626

627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
        // Suspension controls
        if (empty($suspended)) {
            $suspendformdef = array(
                'name'       => 'institution_suspend',
                'plugintype' => 'core',
                'pluginname' => 'admin',
                'elements'   => array(
                    'i' => array(
                        'type'    => 'hidden',
                        'value'   => $institution,
                    ),
                    'submit' => array(
                        'type'        => 'submit',
                        'value'       => get_string('suspendinstitution','admin'),
                        'description' => get_string('suspendinstitutiondescription','admin'),
                    ),
                )
            );

            $suspendform  = pieform($suspendformdef);
647
648
        }
        else {
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
            $suspendformdef = array(
                'name'       => 'institution_unsuspend',
                'plugintype' => 'core',
                'pluginname' => 'admin',
                'elements'   => array(
                    'i' => array(
                        'type'    => 'hidden',
                        'value'   => $institution,
                    ),
                    'submit' => array(
                        'type'        => 'submit',
                        'value'       => get_string('unsuspendinstitution','admin'),
                        'description' => get_string('unsuspendinstitutiondescription','admin'),
                    ),
                )
            );
            $suspendform  = pieform($suspendformdef);

            // Create a second forms for unsuspension to go in the suspend message.
            // This keeps the HTML IDs unique
            $suspendformdef['name'] = 'institution_unsuspend_top';
            $suspendformdef['renderer'] = 'oneline';
            $suspendformdef['successcallback'] = 'institution_unsuspend_submit';
            $suspendform_top = pieform($suspendformdef);
        }
674
675
676
    }
}

677
678
679
680
function search_submit(Pieform $form, $values) {
    redirect('/admin/users/institutions.php' . (!empty($values['query']) ? '?query=' . urlencode($values['query']) : ''));
}

681
682
683
684
$smarty = smarty();
$smarty->assign('institution_form', $institutionform);
$smarty->assign('instancestring', $instancestring);
$smarty->assign('add', $add);
685
686
687
688
689
690

if (isset($suspended)) {
    if ($suspended) {
        $smarty->assign('suspended', get_string('suspendedinstitutionmessage', 'admin'));
    }
    if (isset($suspendform)) {
691
692
693
        $smarty->assign('suspendform', $suspendform);
        if (isset($suspendform_top)) {
            $smarty->assign('suspendform_top', $suspendform_top);
694
        }
695
696
697
    }
}

698
$smarty->assign('PAGEHEADING', get_string('admininstitutions', 'admin'));
699
$smarty->display('admin/users/institutions.tpl');
700

701
702
703
704
705
706
707
708
709
function theme_sort($a, $b) {
    if ($a == 'sitedefault') {
        return -1;
    }
    if ($b == 'sitedefault') {
        return 1;
    }
    return $a > $b;
}