institutions.php 57.4 KB
Newer Older
1
2
3
4
5
<?php
/**
 *
 * @package    mahara
 * @subpackage admin
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
 *
 */
define('INTERNAL', 1);
12
define('INSTITUTIONALADMIN', 1);
13
require(dirname(dirname(dirname(__FILE__))) . '/init.php');
14
define('TITLE', get_string('Institutions', 'admin'));
Penny Leach's avatar
Penny Leach committed
15
16
17
define('SECTION_PLUGINTYPE', 'core');
define('SECTION_PLUGINNAME', 'admin');
define('SECTION_PAGE', 'institutions');
18
require_once('license.php');
19
define('MENUITEM', 'manageinstitutions/institutions');
20
21
22

$institution = param_variable('i', '');
$add         = param_boolean('add');
23
24
$edit        = param_boolean('edit');
$delete      = param_boolean('delete');
25
define('SUBSECTIONHEADING', get_field('institution', 'displayname', 'name', $institution));
26

27
28
$query = param_variable('query', '');
$offset = param_integer('offset', 0);
29
$limit = param_integer('limit', 0);
30
$limit = user_preferred_limit($limit, 'itemsperpage');
31

32
$customthemedefaults = array(
33
    'background'   => array('type' => 'color', 'value' => '#530E53'),
34
    'backgroundfg' => array('type' => 'color', 'value' => '#FFFFFF'),
35
36
37
    'link'         => array('type' => 'color', 'value' => '#255ECC'),
    'headings'     => array('type' => 'color', 'value' => '#530E53'),
    'navbg'        => array('type' => 'color', 'value' => '#8A458A'),
38
39
40
    'navfg'        => array('type' => 'color', 'value' => '#FFFFFF'),
);

41
42
43
44
45
46
47
48
49
50
51
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='
52
                 . key($USER->get('admininstitutions')));
53
54
55
    }
}

56
57
if ($institution || $add) {

58
59
60
61
62
    $authinstances = auth_get_auth_instances_for_institution($institution);
    if (false == $authinstances) {
        $authinstances = array();
    }

63
    if ($delete) {
64
        function delete_validate(Pieform $form, $values) {
65
66
67
68
69
70
71
72
73
74
75
76
77
78
            // Ensure the institution has no members left
            if ($members = get_field('usr_institution', 'COUNT(*)', 'institution', $values['i'])) {
                $form->set_error('submit', get_string('institutionstillhas', 'admin', get_string('nmembers', 'group', $members)));
            }

            // If some users are still using one of this institution's authinstances, it's okay if
            // we can find a default authinstance for those users, otherwise it's an error.
            if ($authinstanceids = get_column('auth_instance', 'id', 'institution', $values['i'])) {
                $badusers = count_records_select(
                    'usr',
                    'authinstance IN (' . join(',', array_fill(0, count($authinstanceids), '?')) . ')',
                    $authinstanceids
                );
                if ($badusers) {
79
                    $defaultauth = record_exists('auth_instance', 'institution', 'mahara', 'authname', 'internal', 'active', 1);
80
81
82
83
84
85
86
                    if ($values['i'] == 'mahara' || !$defaultauth) {
                        $form->set_error(
                            'submit',
                            get_string('institutionauthinuseby', 'admin', get_string('nusers', 'mahara', $badusers))
                        );
                    }
                }
87
88
89
            }
        }

90
        function delete_cancel_submit() {
91
            redirect('/admin/users/institutions.php');
92
93
        }

94
        function delete_submit(Pieform $form, $values) {
95
96
            global $SESSION;

97
            $authinstanceids = get_column('auth_instance', 'id', 'institution', $values['i']);
98
            $collectionids = get_column('collection', 'id', 'institution', $values['i']);
99
100
            $viewids = get_column('view', 'id', 'institution', $values['i']);
            $artefactids = get_column('artefact', 'id', 'institution', $values['i']);
101
            $regdataids = get_column('institution_registration', 'id', 'institution', $values['i']);
102

103
            db_begin();
104
105
106
107
108
109
110
            if ($collectionids) {
                require_once(get_config('libroot') . 'collection.php');
                foreach ($collectionids as $collectionid) {
                    $collection = new Collection($collectionid);
                    $collection->delete();
                }
            }
111
112
113
114
115
116
117
118
            if ($viewids) {
                require_once(get_config('libroot') . 'view.php');
                foreach ($viewids as $viewid) {
                    $view = new View($viewid);
                    $view->delete();
                }
            }
            if ($artefactids) {
119
                require_once(get_config('docroot') . 'artefact/lib.php');
120
121
122
123
124
125
126
127
128
129
                foreach ($artefactids as $artefactid) {
                    try {
                        $a = artefact_instance_from_id($artefactid);
                        $a->delete();
                    }
                    catch (ArtefactNotFoundException $e) {
                        // Awesome, it's already gone.
                    }
                }
            }
130
131
132
133
134
135

            // If any users are still using this institution's authinstances, change them now.
            if ($authinstanceids) {
                execute_sql("
                    UPDATE {usr}
                    SET authinstance = (
136
                        SELECT MIN(id) FROM {auth_instance} WHERE institution = 'mahara' AND authname = 'internal' AND active = 1
137
138
139
140
141
142
                    )
                    WHERE authinstance IN (" . join(',', array_fill(0, count($authinstanceids), '?')) . ')',
                    $authinstanceids
                );
            }

143
            foreach ($authinstanceids as $id) {
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
                // Check if authinstance is SAML and this is the only institution using the related idp metadata
                if ($idps = get_records_sql_array("SELECT aic.value FROM {auth_instance} ai
                                                  JOIN {auth_instance_config} aic ON aic.instance = ai.id
                                                  WHERE aic.field = 'institutionidpentityid'
                                                  AND ai.authname = 'saml' AND ai.id = ?", array($id))) {
                    foreach ($idps as $idp) {
                        if (!count_records_sql("SELECT COUNT(*) FROM {auth_instance_config} aic
                                                WHERE value = ? AND instance != ?", array($idp->value, $id))) {
                            safe_require('auth', 'saml');
                            $idpfile = AuthSaml::prepare_metadata_path($idp->value);
                            if (file_exists($idpfile)) {
                                unlink($idpfile);
                            }
                        }
                    }
                }
160
                delete_records('auth_instance_config', 'instance', $id);
161
                delete_records('auth_remote_user', 'authinstance', $id);
162
            }
163

164
165
166
167
            foreach ($regdataids as $id) {
                delete_records('institution_registration_data', 'registration_id', $id);
            }

168
169
170
171
172
            // 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']);

173
            execute_sql("UPDATE {group} SET institution = 'mahara' WHERE institution = ?", array($values['i']));
174
175
            delete_records('auth_instance', 'institution', $values['i']);
            delete_records('host', 'institution', $values['i']);
176
            delete_records('institution_locked_profile_field', 'name', $values['i']);
177
            delete_records('usr_institution_request', 'institution', $values['i']);
178
            delete_records('view_access', 'institution', $values['i']);
179
180
            delete_records('institution_data', 'institution', $values['i']);
            delete_records('institution_registration', 'institution', $values['i']);
181
182
            delete_records('site_content', 'institution', $values['i']);
            delete_records('institution_config', 'institution', $values['i']);
183
184
            delete_records('usr_custom_layout', 'institution', $values['i']);
            delete_records('usr_registration', 'institution', $values['i']);
185
186
            delete_records('site_content_version', 'institution', $values['i']);
            delete_records('oauth_server_registry', 'institution', $values['i']);
187
188
189
190
            delete_records('institution', 'name', $values['i']);
            db_commit();

            $SESSION->add_ok_msg(get_string('institutiondeletedsuccessfully', 'admin'));
191
            redirect('/admin/users/institutions.php');
192
193
194
195
196
197
198
199
200
201
202
203
204
205
        }
        $form = array(
            'name' => 'delete',
            'elements' => array(
                'i' => array(
                    'type' => 'hidden',
                    'value' => $institution
                ),
                'delete' => array(
                    'type' => 'hidden',
                    'value' => 1
                ),
                'submit' => array(
                    'type' => 'submitcancel',
206
                    'class' => 'btn-default',
207
208
209
210
                    'value' => array(get_string('yes'), get_string('no'))
                )
            )
        );
211
212
213
        $deleteform = pieform($form);
        $smarty = smarty();
        $smarty->assign('delete_form', $deleteform);
214
        $smarty->assign('institutionname', get_field('institution', 'displayname', 'name', $institution));
215
        $smarty->display('admin/users/institutions.tpl');
216
217
218
        exit;
    }

219
220
221
    $instancearray = array();
    $instancestring = '';
    $c = count($authinstances);
222
    $inuse = '';
223

224
225
    $sitelockedfields = (array) get_column('institution_locked_profile_field', 'profilefield', 'name', 'mahara');

226
227
    if (!$add) {
        $data = get_record('institution', 'name', $institution);
228
        $data->commentsortorder = get_config_institution($institution, 'commentsortorder');
Aaron Wells's avatar
Aaron Wells committed
229
        $data->commentthreaded = get_config_institution($institution, 'commentthreaded');
230
        $data->allowinstitutionsmartevidence = get_config_institution($institution, 'allowinstitutionsmartevidence');
231
        $data->reviewselfdeletion = get_config_institution($institution, 'reviewselfdeletion');
232
        $lockedprofilefields = (array) get_column('institution_locked_profile_field', 'profilefield', 'name', $institution);
233

234
        // TODO: Find a better way to work around Smarty's minimal looping logic
235
236
237
238
        if (!empty($authinstances)) {
            foreach($authinstances as $key => $val) {
                $authinstances[$key]->index = $key;
                $authinstances[$key]->total = $c;
239
                $instancearray[] = (int)$val->id;
240
            }
241

242
243
            $instancestring = implode(',',$instancearray);
            $inuserecords = array();
244
245
            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
246
                    $inuserecords[] = $record->authinstance;
247
                }
248
249
            }
            $inuse = implode(',',$inuserecords);
250
        }
251
        $authtypes = auth_get_available_auth_types($institution);
252
253
254
255
    }
    else {
        $data = new StdClass;
        $data->displayname = '';
256
        $data->expiry = null;
257
        if (!get_config('usersuniquebyusername')) {
258
            $data->registerallowed = 0;
259
            $data->registerconfirm = 1;
260
        }
261
        $data->theme = 'sitedefault';
262
        $data->defaultmembershipperiod = null;
263
        $data->showonlineusers = 2;
264
        $data->allowinstitutionpublicviews = get_config('allowpublicviews') ? 1 : 0;
265
        $data->allowinstitutionsmartevidence = 0;
266
267
        $data->licensemandatory = 0;
        $data->licensedefault = '';
268
        $data->dropdownmenu = get_config('dropdownmenu') ? 1 : 0;
269
        $data->skins = get_config('skins') ? 1 : 0;
270
        $data->commentsortorder = 'earliest';
Aaron Wells's avatar
Aaron Wells committed
271
        $data->commentthreaded = false;
272
        $lockedprofilefields = array();
273
274

        $authtypes = auth_get_available_auth_types();
275
    }
276
    $themeoptions = get_institution_themes($institution);
277
    $themeoptions['sitedefault'] = '- ' . get_string('sitedefault', 'admin') . ' (' . $themeoptions[get_config('theme')] . ') -';
278
    uksort($themeoptions, 'theme_sort');
279
    if (validate_theme($data->theme, $institution, $add) === false) {
280
281
        $data->theme = 'sitedefault';
    }
282
    $showonlineusersoptions = array('0' => get_string('none'), '1' => get_string('institutiononly', 'admin'), '2' => get_string('all', 'admin'));
283
284
    $sitename = get_config('sitename');

285
    safe_require('artefact', 'internal');
286
287
288
289
290
291
    $elements = array(
        'add' => array(
            'type'   => 'hidden',
            'value'  => true,
            'ignore' => !$add
        ),
292
293
294
        'inuse' => array(
            'type'   => 'hidden',
            'value'  => $inuse,
295
296
            'id'     => 'inuse',
            'ignore' => $add
297
        ),
298
299
300
301
302
303
304
        'i' => array(
            'type'   => 'hidden',
            'value'  => $institution,
            'ignore' => $add
        ),
        'displayname' => array(
            'type' => 'text',
305
            'title' => get_string('institutionname', 'admin'),
306
307
308
309
            'defaultvalue' => $data->displayname,
            'rules' => array(
                'required'  => true,
                'maxlength' => 255
Penny Leach's avatar
Penny Leach committed
310
311
            ),
            'help'   => true,
312
        ),
313
    );
314
315
316
317
318
319
320
321
322
    if (!$add) {
        $elements['shortname'] = array(
                'type' => 'select',
                'title' => get_string('institutionshortname', 'admin'),
                'defaultvalue' => $data->name,
                'description' => get_string('institutionshortnamedescription', 'admin'),
                'options' => array($data->name => $data->name),
        );
    }
323
    if ($USER->get('admin') && $institution != 'mahara') {
324
       $elements['expiry'] = array(
325
326
            'type'         => 'date',
            'title'        => get_string('institutionexpiry', 'admin'),
327
            'description'  => get_string('institutionexpirydescription', 'admin', hsc($sitename)),
328
329
330
331
            'defaultvalue' => is_null($data->expiry) ? null : strtotime($data->expiry),
            'help'         => true,
            'minyear'      => date('Y') - 2,
            'maxyear'      => date('Y') + 10,
332
333
        );
    }
334
335
    if ($USER->get('admin')) {
        $elements['authplugin'] = array(
336
337
338
339
340
            'type'    => 'authlist',
            'title'   => get_string('authplugin', 'admin'),
            'options' => $authinstances,
            'authtypes' => $authtypes,
            'instancearray' => $instancearray,
341
            'instancestring' => $instancestring,
342
343
            'institution' => $institution,
            'help'   => true,
344
            'ignore' => count($authtypes) == 0 || $institution == ''
345
346
347
        );
    }

348
    if (!$add && empty($authinstances)) {
349
        if ($USER->get('admin')) {
350
            $SESSION->add_error_msg(get_string('adminnoauthpluginforinstitution', 'admin'));
351
352
        }
        else {
353
            $SESSION->add_error_msg(get_string('noauthpluginforinstitution', 'admin'));
354
355
356
        }
    }

357
358
    if (!get_config('usersuniquebyusername')) {
        $elements['registerallowed'] = array(
359
            'type'         => 'switchbox',
360
            'title'        => get_string('registrationallowed', 'admin'),
361
            'description'  => get_string('registrationalloweddescription5', 'admin'),
362
363
364
            'defaultvalue' => $data->registerallowed,
            'help'   => true,
        );
365
        $elements['registerconfirm'] = array(
366
            'type'         => 'switchbox',
367
            'title'        => get_string('registrationconfirm', 'admin'),
368
            'description'  => get_string('registrationconfirmdescription3', 'admin'),
369
            'disabled'     => get_config('requireregistrationconfirm') == true,
370
371
            'defaultvalue' => $data->registerconfirm,
        );
372
    }
373

374
    // Some fields to hide from the default institution config screen
375
    if (empty($data->name) || $data->name != 'mahara') {
376
        $elements['defaultmembershipperiod'] = array(
377
            'type'         => 'expiry',
378
379
380
            'title'        => get_string('defaultmembershipperiod', 'admin'),
            'description'  => get_string('defaultmembershipperioddescription', 'admin'),
            'defaultvalue' => $data->defaultmembershipperiod,
Penny Leach's avatar
Penny Leach committed
381
            'help'   => true,
382
        );
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401

        $languages = get_languages();
        // Get the default language. If the institution has one stored, use that. Otherwise, use 'sitedefault'
        $defaultlang = false;
        if (!empty($data->name)) {
            $defaultlang = get_config_institution($data->name, 'lang');
        }
        // If the defaultlang they provided is no longer valid, use "site default"
        if (!$defaultlang || !array_key_exists($defaultlang, $languages)) {
            $defaultlang = 'sitedefault';
        }
        $elements['lang'] = array(
            'type' => 'select',
            'defaultvalue' => $defaultlang,
            'title' => get_string('institutionlanguage', 'admin'),
            'description' => get_string('institutionlanguagedescription', 'admin'),
            'options' => array_merge(array('sitedefault' => get_string('sitedefault', 'admin') . ' (' . $languages[get_config('lang')] . ')'), $languages),
            'ignore' => (count($languages) < 2),
        );
402
    }
403

404
405
406
    $elements['logo'] = array(
        'type'        => 'file',
        'title'       => get_string('Logo', 'admin'),
407
        'description' => get_string('logodescription1', 'admin'),
408
409
410
411
412
413
414
        'maxfilesize' => get_max_upload_size(false),
    );
    if (!empty($data->logo)) {
        $logourl = get_config('wwwroot') . 'thumb.php?type=logobyid&id=' . $data->logo;
        $elements['logohtml'] = array(
            'type'        => 'html',
            'value'       => '<img src="' . $logourl . '" alt="' . get_string('Logo', 'admin') . '">',
415
        );
416
        $elements['deletelogo'] = array(
417
            'type'        => 'switchbox',
418
            'title'       => get_string('deletelogo', 'admin'),
419
            'description' => get_string('deletelogodescription2', 'admin'),
420
421
        );
    }
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442

    // logo-xs
    $elements['logoxs'] = array(
        'type'        => 'file',
        'title'       => get_string('Logosmall', 'admin'),
        'description' => get_string('logoxsdescription', 'admin'),
        'maxfilesize' => get_max_upload_size(false),
    );
    if (!empty($data->logoxs)) {
        $logoxsurl = get_config('wwwroot') . 'thumb.php?type=logobyid&id=' . $data->logoxs;
        $elements['logoxshtml'] = array(
            'type'        => 'html',
            'value'       => '<img src="' . $logoxsurl . '" alt="' . get_string('Logosmall', 'admin') . '">',
        );
        $elements['deletelogoxs'] = array(
            'type'        => 'switchbox',
            'title'       => get_string('deletelogoxs', 'admin'),
            'description' => get_string('deletelogoxsdescription2', 'admin'),
        );
    }

443
    if (empty($data->name) || $data->name != 'mahara') {
444
445
446
        if (!empty($data->style)) {
            $customtheme = get_records_menu('style_property', 'style', $data->style, '', 'field,value');
        }
447
        $elements['theme'] = array(
448
            'type'         => 'select',
449
            'title'        => get_string('theme'),
450
            'description'  => get_string('sitethemedescription','admin'),
451
            'defaultvalue' => $data->theme ? $data->theme : 'sitedefault',
452
453
454
            'collapseifoneoption' => true,
            'options'      => $themeoptions,
            'help'         => true,
455
        );
456
457
458
459
460
461
462
463
464
465
466
467
468
        $elements['customthemefs'] = array(
            'type'         => 'fieldset',
            'class'        => 'customtheme' . ($elements['theme']['defaultvalue'] != 'custom' ? ' js-hidden' : ''),
            'legend'       => get_string('customtheme', 'admin'),
            'elements'     => array(),
        );
        foreach ($customthemedefaults as $name => $styledata) {
            $elements['customthemefs']['elements'][$name] = array(
                'type'         => $styledata['type'],
                'title'        => get_string('customtheme.' . $name, 'admin'),
                'defaultvalue' => isset($customtheme[$name]) ? $customtheme[$name] : $styledata['value'],
            );
        }
469
        $elements['customthemefs']['elements']['resetcustom'] = array(
470
            'type'         => 'switchbox',
471
472
            'class'        => 'nojs-hidden-inline',
            'title'        => get_string('resetcolours', 'admin'),
473
            'description'  => get_string('resetcoloursdesc2', 'admin'),
474
        );
475
476
477
478
479
480
481
482
483
        if (get_config('dropdownmenuenabled')) {
            $elements['dropdownmenu'] = array(
                'type'         => 'switchbox',
                'title'        => get_string('dropdownmenu', 'admin'),
                'description'  => get_string('dropdownmenudescriptioninstitution2','admin'),
                'defaultvalue' => $data->dropdownmenu,
                'help'         => true,
            );
        }
484
485
486
487
    }
    // The skins checkbox should be shown for the default institution
    if (get_config('skins')) {
        $elements['skins'] = array(
488
            'type' => 'switchbox',
489
            'title' => get_string('skins', 'admin'),
490
            'description' => get_string('skinsinstitutiondescription2', 'admin'),
491
492
493
            'defaultvalue' => $data->skins,
        );
    }
494
495
496
497
498
499
500
501
502
503
    $elements['commentsortorder'] = array(
        'type' => 'select',
        'title' => get_string('commentsortorder', 'admin'),
        'description' => get_string('commentsortorderdescription', 'admin'),
        'defaultvalue' => $data->commentsortorder,
        'options' => array('earliest' => get_string('earliest'),
                           'latest' => get_string('latest'),
                          ),
        'help' => true,
    );
Aaron Wells's avatar
Aaron Wells committed
504
505
506
507
508
509
    $elements['commentthreaded'] = array(
        'type' => 'switchbox',
        'title' => get_string('commentthreaded', 'admin'),
        'description' => get_string('commentthreadeddescription', 'admin'),
        'defaultvalue' => $data->commentthreaded,
    );
510
511
    // Some more fields that are hidden from the default institution
    if (empty($data->name) || $data->name != 'mahara') {
512
513
        $elements['showonlineusers'] = array(
            'type'                  => 'select',
514
            'disabled'              => get_config('showonlineuserssideblock') ? '' : 'disabled',
515
            'title'                 => get_string('showonlineusers', 'admin'),
516
            'description'           => get_string('showonlineusersdescription','admin'),
517
518
519
520
            'defaultvalue'          => $data->showonlineusers,
            'collapseifoneoption'   => true,
            'options'               => $showonlineusersoptions,
        );
521
522
        if (get_config('licensemetadata')) {
            $elements['licensemandatory'] = array(
523
                'type'         => 'switchbox',
524
                'title'        => get_string('licensemandatory', 'admin'),
525
                'description'  => get_string('licensemandatorydescription1','admin'),
526
527
528
529
530
531
532
533
534
                'defaultvalue' => $data->licensemandatory,
            );
            $elements['licensedefault'] = license_form_el_basic(null, true);
            $elements['licensedefault']['title'] = get_string('licensedefault','admin');
            $elements['licensedefault']['description'] = get_string('licensedefaultdescription','admin');
            if ($data->licensedefault) {
                $elements['licensedefault']['defaultvalue'] = $data->licensedefault;
            }
        }
535
536
537
538
539
540
541
        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'),
            );
542
            $elements['updateuserquotas'] = array(
543
                'type'         => 'switchbox',
544
                'title'        => get_string('updateuserquotas', 'artefact.file'),
545
                'description'  => get_string('updateinstitutionuserquotasdesc2', 'admin'),
546
            );
547
548
549
550
551
552
553
554
555
        }
        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,
            );
        }
556
557

        $elements['allowinstitutionpublicviews'] = array(
558
            'type'         => 'switchbox',
559
            'title'        => get_string('allowinstitutionpublicviews', 'admin'),
560
            'description'  => get_string('allowinstitutionpublicviewsdescription2','admin'),
561
562
563
564
565
            'defaultvalue' => get_config('allowpublicviews') && $data->allowinstitutionpublicviews,
            'disabled'     => get_config('allowpublicviews') == false,
            'help'         => true,
        );

566
567
568
569
570
571
        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,
572
573
574
575
576
                'rules'        => array(
                    'regex'     => '/^\d*$/',
                    'maxlength' => 8,
                ),
                'size'         => 5,
577
578
            );
        }
579
    }
580
581
582
583
    $elements['allowinstitutionsmartevidence'] = array(
        'type'         => 'switchbox',
        'title'        => get_string('allowinstitutionsmartevidence', 'admin'),
        'description'  => get_string('allowinstitutionsmartevidencedescription','admin'),
584
585
        'defaultvalue' => is_plugin_active('framework', 'module') && $data->allowinstitutionsmartevidence,
        'disabled'     => is_plugin_active('framework', 'module') == false,
586
587
        'help'         => true,
    );
588
589
590
591
592
593
594
    $elements['reviewselfdeletion'] = array(
        'type'         => 'switchbox',
        'title'        => get_string('reviewselfdeletion', 'admin'),
        'description'  => get_string('reviewselfdeletiondescription','admin'),
        'disabled'     => get_config('defaultreviewselfdeletion') == true,
        'defaultvalue' => get_config('defaultreviewselfdeletion') ? get_config('defaultreviewselfdeletion') : (isset($data->reviewselfdeletion) && $data->reviewselfdeletion),
    );
595
    $elements['lockedfields'] = array(
596
        'type' => 'fieldset',
Pat Kira's avatar
Pat Kira committed
597
        'class' => 'last with-formgroup',
598
        'legend' => get_string('Lockedfields', 'admin'),
599
600
601
        'collapsible' => true,
        'collapsed' => true,
        'elements' => array(),
602
    );
603
604
605
    if ($institution != 'mahara') {
        $elements['lockedfields']['elements']['description'] = array(
            'type' => 'html',
606
            'value' => get_string('disabledlockedfieldhelp1', 'admin', get_field('institution', 'displayname', 'name', 'mahara')),
607
608
        );
    }
609
    foreach (ArtefactTypeProfile::get_all_fields() as $field => $type) {
610
        $elements['lockedfields']['elements'][$field] = array(
611
            'type' => 'switchbox',
612
            'title' => get_string($field, 'artefact.internal'),
613
614
            'defaultvalue' => in_array($field, $lockedprofilefields) || ($institution != 'mahara' && in_array($field, $sitelockedfields)),
            'disabled' => $institution != 'mahara' && in_array($field, $sitelockedfields)
615
616
        );
    }
617

618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
    // Check for active plugins institution settings.
    $elements['pluginsfields'] = array(
        'type' => 'fieldset',
        'legend' => get_string('pluginsfields', 'admin'),
        'collapsible' => true,
        'collapsed' => true,
        'elements' => array(),
    );

    // Get plugins institution settings.
    $instobj = null;
    if (!$add && $institution != '') {
        $instobj = new Institution();
        $instobj->findByName($institution);
    }
    $elements['pluginsfields']['elements'] = array_merge($elements['pluginsfields']['elements'],
            plugin_institution_prefs_form_elements($instobj));

    // Remove plugin fieldset if no fields.
    if (empty($elements['pluginsfields']['elements'])) {
        unset($elements['pluginsfields']);
    }

641
642
    $elements['submit'] = array(
        'type' => 'submitcancel',
643
        'class' => 'btn-primary',
644
645
646
        'value' => array(get_string('submit'), get_string('cancel'))
    );

647
    $institutionform = pieform(array(
648
        'name'     => 'institution',
Pat Kira's avatar
Pat Kira committed
649
        'renderer' => 'div',
Penny Leach's avatar
Penny Leach committed
650
651
        'plugintype' => 'core',
        'pluginname' => 'admin',
652
        'elements' => $elements
653
    ));
654
655
656
657

}
else {
    // Get a list of institutions
658
    require_once(get_config('libroot') . 'institution.php');
659
    if (!$USER->get('admin')) { // Filter the list for institutional admins
660
661
        $filter      = $USER->get('admininstitutions');
        $showdefault = false;
662
663
    }
    else {
664
665
        $filter      = false;
        $showdefault = true;
666
    }
667
    $data = build_institutions_html($filter, $showdefault, $query, $limit, $offset, $count);
668
669

    $smarty = smarty(array('lib/pieforms/static/core/pieforms.js', 'paginator'));
670
    setpageicon($smarty, 'icon-university');
671
672
673
674
675
    $smarty->assign('results', $data);
    $smarty->assign('countinstitutions', $count);

    /*search institution form*/
    $searchform = pieform(array(
676
677
        'name'   => 'search',
        'renderer' => 'div',
Naomi Guyer's avatar
Naomi Guyer committed
678
        'class' => 'form-inline with-heading',
679
        'autofocus' => false,
680
        'elements' => array(
681
682
683
684
685
686
687
688
            'inputgroup' => array(
                'type'  => 'fieldset',
                'title' => get_string('Query') . ': ',
                'class' => 'input-group form-inline',
                'elements'     => array(
                    'query' => array(
                        'type'  => 'text',
                        'defaultvalue' => $query,
689
                        'hiddenlabel' => true,
690
691
                        'value' => '',
                        'placeholder' => get_string('search'),
692
                        'title' => get_string('search'),
693
694
695
696
                    ),
                    'submit' => array(
                        'type'  => 'button',
                        'usebuttontag' => true,
697
                        'class' => 'btn-primary input-group-btn',
698
699
700
                        'value' => get_string('search'),
                    )
                ),
701
            ),
702
        ),
703
704
705
706
    ));
    $smarty->assign('searchform', $searchform);

    $js = <<< EOF
707
708
709
710
711
    jQuery(function($) {
      p = {$data['pagination_js']}
      $('#search_submit').on('click', function(event) {
        $('#messages').empty();
        var params = {'query': $('#search_query').val()};
712
        p.sendQuery(params);
713
714
        event.preventDefault();
      });
715
716
717
718
    });
EOF;

    $smarty->assign('INLINEJAVASCRIPT', $js);
719
720
721
722
    $smarty->assign('siteadmin', $USER->get('admin'));
    $smarty->assign('PAGEHEADING', get_string('admininstitutions', 'admin'));
    $smarty->display('admin/users/institutions.tpl');
    exit;
723
724
}

725
function institution_validate(Pieform $form, $values) {
726
    global $USER, $institution, $add;
727

728
729
730
731
    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'));
        }
732
    }
733

734
735
    if (get_config('licensemetadata') && !empty($values['licensemandatory']) &&
        (isset($values['licensedefault']) && $values['licensedefault'] == '')) {
736
737
738
        $form->set_error('licensedefault', get_string('licensedefaultmandatory', 'admin'));
    }

739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
    // Check uploaded logo
    if (!empty($values['logo'])) {
        require_once('file.php');
        require_once('uploadmanager.php');
        $um = new upload_manager('logo');
        if ($error = $um->preprocess_file()) {
            $form->set_error('logo', $error);
            return false;
        }

        $imageinfo = getimagesize($values['logo']['tmp_name']);
        if (!$imageinfo || !is_image_type($imageinfo[2])) {
            $form->set_error('logo', get_string('filenotimage'));
            return false;
        }

        // Check the file isn't greater than the max allowable size
        $width          = $imageinfo[0];
        $height         = $imageinfo[1];
        $imagemaxwidth  = get_config('imagemaxwidth');
        $imagemaxheight = get_config('imagemaxheight');
        if ($width > $imagemaxwidth || $height > $imagemaxheight) {
            $form->set_error('logo', get_string('profileiconimagetoobig', 'artefact.file', $width, $height, $imagemaxwidth, $imagemaxheight));
        }
    }
764

765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
    // Check uploaded small logo
    if (!empty($values['logoxs'])) {
        require_once('file.php');
        require_once('uploadmanager.php');
        $um = new upload_manager('logoxs');
        if ($error = $um->preprocess_file()) {
            $form->set_error('logoxs', $error);
            return false;
        }

        $imageinfo = getimagesize($values['logoxs']['tmp_name']);
        if (!$imageinfo || !is_image_type($imageinfo[2])) {
            $form->set_error('logoxs', get_string('filenotimage'));
            return false;
        }

        // Check the file isn't greater than the max allowable size
        $width          = $imageinfo[0];
        $height         = $imageinfo[1];
        $imagemaxwidth  = get_config('imagemaxwidth');
        $imagemaxheight = get_config('imagemaxheight');
        if ($width > $imagemaxwidth || $height > $imagemaxheight) {
            $form->set_error('logoxs', get_string('profileiconimagetoobig', 'artefact.file', $width, $height, $imagemaxwidth, $imagemaxheight));
        }
        else {
            $ratio = $width / $height;
            if ($ratio != 1) {
                $form->set_error('logoxs', get_string('profileiconxsnotsquare', 'artefact.file'));
            }
        }
    }

797
798
799
    if (!empty($values['lang']) && $values['lang'] != 'sitedefault' && !array_key_exists($values['lang'], get_languages())) {
        $form->set_error('lang', get_string('institutionlanginvalid', 'admin'));
    }
800
    if (!is_plugin_active('framework', 'module') && (!empty($values['allowinstitutionsmartevidence']))) {
801
802
        $form->set_error('allowinstitutionsmartevidence', get_string('institutionsmartevidencenotallowed', 'admin'));
    }
803
804
805

    // Validate plugins settings.
    plugin_institution_prefs_validate($form, $values);
806
807
}

808
function institution_submit(Pieform $form, $values) {
809
    global $SESSION, $institution, $add, $instancearray, $USER, $authinstances, $customthemedefaults;
810
811
812
813

    db_begin();
    // Update the basic institution record...
    if ($add) {
814
        $institution = institution_generate_name($values['displayname']);
815
        $newinstitution = new Institution();
816
        $newinstitution->initialise($institution, $values['displayname']);
817
        $institution = $newinstitution->name;
818
    }
819
    else {
820
821
        $newinstitution = new Institution($institution);
        $newinstitution->displayname = $values['displayname'];
822
        $oldinstitution = get_record('institution', 'name', $institution);
823
824
        // Clear out any cached menus for this institution
        clear_menu_cache($institution);
825
    }
826

827
    $newinstitution->showonlineusers              = !isset($values['showonlineusers']) ? 2 : $values['showonlineusers'];
828
    if (get_config('usersuniquebyusername')) {
Aaron Wells's avatar
Aaron Wells committed
829
830
        // Registering absolutely not allowed when this setting is on, it's a
        // security risk. See the documentation for the usersuniquebyusername
831
832
833
834
835
        // setting for more information
        $newinstitution->registerallowed = 0;
    }
    else {
        $newinstitution->registerallowed              = ($values['registerallowed']) ? 1 : 0;
836
        $newinstitution->registerconfirm              = ($values['registerconfirm']) ? 1 : 0;
837
    }
838
839
840
841
842
843
844
845
846
847

    if (!empty($values['lang'])) {
        if ($values['lang'] == 'sitedefault') {
            $newinstitution->lang = null;
        }
        else {
            $newinstitution->lang = $values['lang'];
        }
    }

848
849
    $newinstitution->theme                 = (empty($values['theme']) || $values['theme'] == 'sitedefault') ? null : $values['theme'];
    $newinstitution->dropdownmenu          = (!empty($values['dropdownmenu'])) ? 1 : 0;
850
    $newinstitution->skins                 = (!empty($values['skins'])) ? 1 : 0;
851
852
853
    require_once(get_config('docroot') . 'artefact/comment/lib.php');
    $commentoptions = ArtefactTypeComment::get_comment_options();
    $newinstitution->commentsortorder      = (empty($values['commentsortorder'])) ? $commentoptions->sort : $values['commentsortorder'];
Aaron Wells's avatar
Aaron Wells committed
854
    $newinstitution->commentthreaded       = (!empty($values['commentthreaded'])) ? 1 : 0;
855

856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
    if ($newinstitution->theme == 'custom') {
        if (!empty($oldinstitution->style)) {
            $styleid = $oldinstitution->style;
            delete_records('style_property', 'style', $styleid);
        }
        else {
            $record = (object) array('title' => get_string('customstylesforinstitution', 'admin', $newinstitution->displayname));
            $styleid = insert_record('style', $record, 'id', true);
        }

        $properties = array();
        $record = (object) array('style' => $styleid);
        foreach (array_keys($customthemedefaults) as $name) {
            $record->field = $name;
            $record->value = $values[$name];
            insert_record('style_property', $record);
            $properties[$name] = $values[$name];
        }

        // Cache the css
        $smarty = smarty_core();
        $smarty->assign('data', $properties);
        set_field('style', 'css', $smarty->fetch('customcss.tpl'), 'id', $styleid);

        $newinstitution->style = $styleid;
    }
    else {
        $newinstitution->style = null;
    }

886
    if (get_config('licensemetadata')) {
887
888
        $newinstitution->licensemandatory = (!empty($values['licensemandatory'])) ? 1 : 0;
        $newinstitution->licensedefault = (isset($values['licensedefault'])) ? $values['licensedefault'] : '';
889
890
    }

891
892
893
894
    if (!empty($values['resetcustom']) && !empty($oldinstitution->style)) {
        $newinstitution->style = null;
    }

895
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
896
897
898
899
900
        if (!empty($values['updateuserquotas']) && !empty($values['defaultquota'])) {
            execute_sql(
                "UPDATE {usr} SET quota = ? WHERE id IN (SELECT usr FROM {usr_institution} WHERE institution = ?)",
                array($values['defaultquota'], $institution)
            );
901
902
            // get all the users from the institution and make sure that they are still below
            // their quota threshold
903
            if ($users = get_records_sql_array('SELECT * FROM {usr} u INNER JOIN {usr_institution} ui ON u.id = ui.usr AND ui.institution = ?', array($institution))) {
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
                $quotanotifylimit = get_config_plugin('artefact', 'file', 'quotanotifylimit');
                if ($quotanotifylimit <= 0 || $quotanotifylimit >= 100) {
                    $quotanotifylimit = 100;
                }
                foreach ($users as $user) {
                    // check if the user has gone over the quota notify limit
                    $user->quotausedpercent = $user->quotaused / $user->quota * 100;
                    $overlimit = false;
                    if ($quotanotifylimit <= $user->quotausedpercent) {
                        $overlimit = true;
                    }
                    $notified = get_field('usr_account_preference', 'value', 'field', 'quota_exceeded_notified', 'usr', $user->id);
                    if ($overlimit && '1' !== $notified) {
                        require_once(get_config('docroot') . 'artefact/file/lib.php');
                        ArtefactTypeFile::notify_users_threshold_exceeded(array($user), false);
                        // no need to email admin as we can alert them right now
920
                        $SESSION->add_error_msg(get_string('useroverquotathreshold', 'artefact.file', display_name($user), ceil((int) $user->quotausedpercent), display_size($user->quota)));
921
922
923
924
925
926
                    }
                    else if ($notified && !$overlimit) {
                        set_account_preference($user->id, 'quota_exceeded_notified', false);
                    }
                }
            }
927
        }
928
        $newinstitution->defaultquota = empty($values['defaultquota']) ? get_config_plugin('artefact', 'file', 'defaultquota') : $values['defaultquota'];
929
    }
930
931
932
933
    if ($institution != 'mahara') {
        $newinstitution->defaultmembershipperiod  = ($values['defaultmembershipperiod']) ? intval($values['defaultmembershipperiod']) : null;
        if ($USER->get('admin')) {
            $newinstitution->maxuseraccounts      = ($values['maxuseraccounts']) ? intval($values['maxuseraccounts']) : null;
934
            $newinstitution->expiry               = db_format_timestamp($values['expiry']);
935
        }
936
937
    }

938
    $newinstitution->allowinstitutionpublicviews  = (isset($values['allowinstitutionpublicviews']) && $values['allowinstitutionpublicviews']) ? 1 : 0;
939
    $newinstitution->allowinstitutionsmartevidence  = (isset($values['allowinstitutionsmartevidence']) && $values['allowinstitutionsmartevidence']) ? 1 : 0;
940

941
942
943
944
945
946
    // do not set 'reviewselfdeletion' if it has never been changed at institution level
    // and the value is the same as site setting 'defaultreviewselfdeletion'
    if (get_config_institution($institution, 'reviewselfdeletion') != null || get_config('defaultreviewselfdeletion') != $values['reviewselfdeletion']) {
        $newinstitution->reviewselfdeletion  = $values['reviewselfdeletion'] ? 1 : 0;
    }

947
    // TODO: Move handling of authentication instances within the Institution class as well?
948
949
    if (!empty($values['authplugin'])) {
        $allinstances = array_merge($values['authplugin']['instancearray'], $values['authplugin']['deletearray']);
950

951
        if (array_diff($allinstances, $instancearray)) {
952
            throw new ConfigException('Attempt to delete or update another institution\'s auth instance');
953
        }
954

955
        if (array_diff($instancearray, $allinstances)) {
956
            throw new ConfigException('One of your instances is unaccounted for in this transaction');
957
958
        }

959
960
961
        foreach($values['authplugin']['instancearray'] as $priority => $instanceid) {
            if (in_array($instanceid, $values['authplugin']['deletearray'])) {
                // Should never happen:
962
                throw new SystemException('Attempt to update AND delete an auth instance');
963
964
965
966
967
968
969
970
            }
            $record = new StdClass;
            $record->priority = $priority;
            $record->id = $instanceid;
            update_record('auth_instance', $record,  array('id' => $instanceid));
        }

        foreach($values['authplugin']['deletearray'] as $instanceid) {
971
972
973
974
            // 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
975
976
                    $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) {
977
978
979
980
981
982
983
984
985
                        // 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;
                }
            }
Richard Mansfield's avatar