institutions.php 58.3 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
define('SECTION_PLUGINTYPE', 'core');
define('SECTION_PLUGINNAME', 'admin');
17

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
if ($institution || $add) {
57
    define('SECTION_PAGE', 'institutionedit');
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 185
            if (db_table_exists('usr_custom_layout')) {
                delete_records('usr_custom_layout', 'institution', $values['i']);
            }
186
            delete_records('usr_registration', 'institution', $values['i']);
Robert Lyon's avatar
Robert Lyon committed
187 188 189 190
            if ($versions = get_records_assoc('site_content_version', 'institution', $values['i'])) {
                foreach($versions as $version) {
                    delete_records('usr_agreement', 'sitecontentid', $version->id);
                }
191
            }
192 193
            delete_records('site_content_version', 'institution', $values['i']);
            delete_records('oauth_server_registry', 'institution', $values['i']);
194 195
            delete_records('institution', 'name', $values['i']);
            db_commit();
Robert Lyon's avatar
Robert Lyon committed
196
            clear_menu_cache();
197
            $SESSION->add_ok_msg(get_string('institutiondeletedsuccessfully', 'admin'));
198
            redirect('/admin/users/institutions.php');
199 200 201 202 203 204 205 206 207 208 209 210 211 212
        }
        $form = array(
            'name' => 'delete',
            'elements' => array(
                'i' => array(
                    'type' => 'hidden',
                    'value' => $institution
                ),
                'delete' => array(
                    'type' => 'hidden',
                    'value' => 1
                ),
                'submit' => array(
                    'type' => 'submitcancel',
213
                    'class' => 'btn-secondary',
214 215 216 217
                    'value' => array(get_string('yes'), get_string('no'))
                )
            )
        );
218 219 220
        $deleteform = pieform($form);
        $smarty = smarty();
        $smarty->assign('delete_form', $deleteform);
221
        $smarty->assign('institutionname', get_field('institution', 'displayname', 'name', $institution));
222
        $smarty->display('admin/users/institutions.tpl');
223 224 225
        exit;
    }

226 227 228
    $instancearray = array();
    $instancestring = '';
    $c = count($authinstances);
229
    $inuse = '';
230

231 232
    $sitelockedfields = (array) get_column('institution_locked_profile_field', 'profilefield', 'name', 'mahara');

233 234
    if (!$add) {
        $data = get_record('institution', 'name', $institution);
235
        $data->commentsortorder = get_config_institution($institution, 'commentsortorder');
Aaron Wells's avatar
Aaron Wells committed
236
        $data->commentthreaded = get_config_institution($institution, 'commentthreaded');
237
        $data->allowinstitutionsmartevidence = get_config_institution($institution, 'allowinstitutionsmartevidence');
238
        $data->reviewselfdeletion = get_config_institution($institution, 'reviewselfdeletion');
239
        $data->showonlineusers = (is_isolated() && $data->showonlineusers == 2 ? 1 : $data->showonlineusers);
240
        $lockedprofilefields = (array) get_column('institution_locked_profile_field', 'profilefield', 'name', $institution);
241

242
        // TODO: Find a better way to work around Smarty's minimal looping logic
243 244 245 246
        if (!empty($authinstances)) {
            foreach($authinstances as $key => $val) {
                $authinstances[$key]->index = $key;
                $authinstances[$key]->total = $c;
247
                $instancearray[] = (int)$val->id;
248
            }
249

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

        $authtypes = auth_get_available_auth_types();
284
    }
285
    $themeoptions = get_institution_themes($institution);
286
    $themeoptions['sitedefault'] = '- ' . get_string('sitedefault', 'admin') . ' (' . $themeoptions[get_config('theme')] . ') -';
287
    uksort($themeoptions, 'theme_sort');
288
    if (validate_theme($data->theme, $institution, $add) === false) {
289 290
        $data->theme = 'sitedefault';
    }
291 292 293 294 295 296 297 298 299
    $showonlineusersoptions = array('0' => get_string('none'),
                                    '1' => get_string('institutiononly', 'admin'),
                                    '2' => get_string('all', 'admin'));

    $isolatedinstitutions = is_isolated();
    if ($isolatedinstitutions) {
        unset($showonlineusersoptions['2']);
    }
     $sitename = get_config('sitename');
300

301
    safe_require('artefact', 'internal');
302 303 304 305 306 307
    $elements = array(
        'add' => array(
            'type'   => 'hidden',
            'value'  => true,
            'ignore' => !$add
        ),
308 309 310
        'inuse' => array(
            'type'   => 'hidden',
            'value'  => $inuse,
311 312
            'id'     => 'inuse',
            'ignore' => $add
313
        ),
314 315 316 317 318 319 320
        'i' => array(
            'type'   => 'hidden',
            'value'  => $institution,
            'ignore' => $add
        ),
        'displayname' => array(
            'type' => 'text',
321
            'title' => get_string('institutionname', 'admin'),
322 323 324 325
            'defaultvalue' => $data->displayname,
            'rules' => array(
                'required'  => true,
                'maxlength' => 255
Penny Leach's avatar
Penny Leach committed
326 327
            ),
            'help'   => true,
328
        ),
329
    );
330 331 332 333 334 335 336 337 338
    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),
        );
    }
339
    if ($USER->get('admin') && $institution != 'mahara') {
340
       $elements['expiry'] = array(
341
            'type'         => 'calendar',
342
            'title'        => get_string('institutionexpiry', 'admin'),
343
            'description'  => get_string('institutionexpirydescription', 'admin', hsc($sitename)),
344 345 346 347
            'defaultvalue' => is_null($data->expiry) ? null : strtotime($data->expiry),
            'help'         => true,
            'minyear'      => date('Y') - 2,
            'maxyear'      => date('Y') + 10,
348 349 350
            'caloptions' => array(
                'showsTime'      => false,
            ),
351 352
        );
    }
353 354
    if ($USER->get('admin')) {
        $elements['authplugin'] = array(
355 356 357 358 359
            'type'    => 'authlist',
            'title'   => get_string('authplugin', 'admin'),
            'options' => $authinstances,
            'authtypes' => $authtypes,
            'instancearray' => $instancearray,
360
            'instancestring' => $instancestring,
361 362
            'institution' => $institution,
            'help'   => true,
363
            'ignore' => count($authtypes) == 0 || $institution == ''
364 365 366
        );
    }

367
    if (!$add && empty($authinstances)) {
368
        if ($USER->get('admin')) {
369
            $SESSION->add_error_msg(get_string('adminnoauthpluginforinstitution', 'admin'));
370 371
        }
        else {
372
            $SESSION->add_error_msg(get_string('noauthpluginforinstitution', 'admin'));
373 374 375
        }
    }

376 377
    if (!get_config('usersuniquebyusername')) {
        $elements['registerallowed'] = array(
378
            'type'         => 'switchbox',
379
            'title'        => get_string('registrationallowed', 'admin'),
380
            'description'  => get_string('registrationalloweddescription5', 'admin'),
381 382 383
            'defaultvalue' => $data->registerallowed,
            'help'   => true,
        );
384
        $elements['registerconfirm'] = array(
385
            'type'         => 'switchbox',
386
            'title'        => get_string('registrationconfirm', 'admin'),
387
            'description'  => get_string('registrationconfirmdescription3', 'admin'),
388
            'disabled'     => get_config('requireregistrationconfirm') == true,
389
            'defaultvalue' => ($isolatedinstitutions ? true : $data->registerconfirm),
390
        );
391
    }
392

393
    // Some fields to hide from the default institution config screen
394
    if (empty($data->name) || $data->name != 'mahara') {
395
        $elements['defaultmembershipperiod'] = array(
396
            'type'         => 'expiry',
397 398 399
            'title'        => get_string('defaultmembershipperiod', 'admin'),
            'description'  => get_string('defaultmembershipperioddescription', 'admin'),
            'defaultvalue' => $data->defaultmembershipperiod,
Penny Leach's avatar
Penny Leach committed
400
            'help'   => true,
401
        );
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420

        $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),
        );
421
    }
422

423 424 425
    $elements['logo'] = array(
        'type'        => 'file',
        'title'       => get_string('Logo', 'admin'),
426
        'description' => get_string('logodescription1', 'admin'),
427 428 429 430 431 432 433
        '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') . '">',
434
        );
435
        $elements['deletelogo'] = array(
436
            'type'        => 'switchbox',
437
            'title'       => get_string('deletelogo', 'admin'),
438
            'description' => get_string('deletelogodescription2', 'admin'),
439 440
        );
    }
441 442 443 444

    // logo-xs
    $elements['logoxs'] = array(
        'type'        => 'file',
445
        'title'       => get_string('Logomobile', 'admin'),
446 447 448 449 450 451 452
        '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',
453
            'value'       => '<img src="' . $logoxsurl . '" alt="' . get_string('Logomobile', 'admin') . '">',
454 455 456
        );
        $elements['deletelogoxs'] = array(
            'type'        => 'switchbox',
457 458
            'title'       => get_string('deletelogoxsmobile', 'admin'),
            'description' => get_string('deletelogoxsdescription3', 'admin'),
459 460 461
        );
    }

462
    if (empty($data->name) || $data->name != 'mahara') {
463 464 465
        if (!empty($data->style)) {
            $customtheme = get_records_menu('style_property', 'style', $data->style, '', 'field,value');
        }
466
        $elements['theme'] = array(
467
            'type'         => 'select',
468
            'title'        => get_string('theme'),
469
            'description'  => get_string('sitethemedescription','admin'),
470
            'defaultvalue' => $data->theme ? $data->theme : 'sitedefault',
471 472 473
            'collapseifoneoption' => true,
            'options'      => $themeoptions,
            'help'         => true,
474
        );
475 476 477 478 479 480 481 482 483 484 485 486 487
        $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'],
            );
        }
488
        $elements['customthemefs']['elements']['resetcustom'] = array(
489
            'type'         => 'switchbox',
490 491
            'class'        => 'nojs-hidden-inline',
            'title'        => get_string('resetcolours', 'admin'),
492
            'description'  => get_string('resetcoloursdesc2', 'admin'),
493
        );
494 495 496 497 498 499 500 501 502
        if (get_config('dropdownmenuenabled')) {
            $elements['dropdownmenu'] = array(
                'type'         => 'switchbox',
                'title'        => get_string('dropdownmenu', 'admin'),
                'description'  => get_string('dropdownmenudescriptioninstitution2','admin'),
                'defaultvalue' => $data->dropdownmenu,
                'help'         => true,
            );
        }
503 504 505 506
    }
    // The skins checkbox should be shown for the default institution
    if (get_config('skins')) {
        $elements['skins'] = array(
507
            'type' => 'switchbox',
508
            'title' => get_string('skins', 'admin'),
509
            'description' => get_string('skinsinstitutiondescription2', 'admin'),
510 511 512
            'defaultvalue' => $data->skins,
        );
    }
513 514 515 516 517 518 519 520 521 522
    $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
523 524 525 526 527 528
    $elements['commentthreaded'] = array(
        'type' => 'switchbox',
        'title' => get_string('commentthreaded', 'admin'),
        'description' => get_string('commentthreadeddescription', 'admin'),
        'defaultvalue' => $data->commentthreaded,
    );
529 530
    // Some more fields that are hidden from the default institution
    if (empty($data->name) || $data->name != 'mahara') {
531 532
        $elements['showonlineusers'] = array(
            'type'                  => 'select',
533
            'disabled'              => get_config('showonlineuserssideblock') ? '' : 'disabled',
534
            'title'                 => get_string('showonlineusers', 'admin'),
535
            'description'           => get_string('showonlineusersdescription','admin'),
536 537 538 539
            'defaultvalue'          => $data->showonlineusers,
            'collapseifoneoption'   => true,
            'options'               => $showonlineusersoptions,
        );
540 541
        if (get_config('licensemetadata')) {
            $elements['licensemandatory'] = array(
542
                'type'         => 'switchbox',
543
                'title'        => get_string('licensemandatory', 'admin'),
544
                'description'  => get_string('licensemandatorydescription1','admin'),
545 546 547 548 549 550 551 552 553
                '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;
            }
        }
554 555 556 557 558 559 560
        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'),
            );
561
            $elements['updateuserquotas'] = array(
562
                'type'         => 'switchbox',
563
                'title'        => get_string('updateuserquotas', 'artefact.file'),
564
                'description'  => get_string('updateinstitutionuserquotasdesc2', 'admin'),
565
            );
566 567 568 569 570 571 572 573 574
        }
        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,
            );
        }
575 576

        $elements['allowinstitutionpublicviews'] = array(
577
            'type'         => 'switchbox',
578
            'title'        => get_string('allowinstitutionpublicviews', 'admin'),
579
            'description'  => get_string('allowinstitutionpublicviewsdescription2','admin'),
580 581 582 583 584
            'defaultvalue' => get_config('allowpublicviews') && $data->allowinstitutionpublicviews,
            'disabled'     => get_config('allowpublicviews') == false,
            'help'         => true,
        );

585 586 587 588 589 590
        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,
591 592 593 594 595
                'rules'        => array(
                    'regex'     => '/^\d*$/',
                    'maxlength' => 8,
                ),
                'size'         => 5,
596 597
            );
        }
598
    }
599 600 601 602
    $elements['allowinstitutionsmartevidence'] = array(
        'type'         => 'switchbox',
        'title'        => get_string('allowinstitutionsmartevidence', 'admin'),
        'description'  => get_string('allowinstitutionsmartevidencedescription','admin'),
603 604
        'defaultvalue' => is_plugin_active('framework', 'module') && $data->allowinstitutionsmartevidence,
        'disabled'     => is_plugin_active('framework', 'module') == false,
605 606
        'help'         => true,
    );
607 608 609 610 611 612
    $elements['allowinstitutiontags'] = array(
        'type'         => 'switchbox',
        'title'        => get_string('allowinstitutiontags'),
        'description'  => get_string('allowinstitutiontagsdescription'),
        'defaultvalue' => $data->tags,
    );
613 614
    $elements['reviewselfdeletion'] = array(
        'type'         => 'switchbox',
615 616
        'title'        => get_string('reviewsselfdeletion', 'admin'),
        'description'  => get_string('reviewsselfdeletiondescription','admin'),
617 618 619
        'disabled'     => get_config('defaultreviewselfdeletion') == true,
        'defaultvalue' => get_config('defaultreviewselfdeletion') ? get_config('defaultreviewselfdeletion') : (isset($data->reviewselfdeletion) && $data->reviewselfdeletion),
    );
620
    $elements['lockedfields'] = array(
621
        'type' => 'fieldset',
Pat Kira's avatar
Pat Kira committed
622
        'class' => 'last with-formgroup',
623
        'legend' => get_string('Lockedfields', 'admin'),
624 625 626
        'collapsible' => true,
        'collapsed' => true,
        'elements' => array(),
627
    );
628 629 630
    if ($institution != 'mahara') {
        $elements['lockedfields']['elements']['description'] = array(
            'type' => 'html',
631
            'value' => get_string('disabledlockedfieldhelp1', 'admin', get_field('institution', 'displayname', 'name', 'mahara')),
632 633
        );
    }
634
    foreach (ArtefactTypeProfile::get_all_fields() as $field => $type) {
635
        $elements['lockedfields']['elements'][$field] = array(
636
            'type' => 'switchbox',
637
            'title' => get_string($field, 'artefact.internal'),
638 639
            'defaultvalue' => in_array($field, $lockedprofilefields) || ($institution != 'mahara' && in_array($field, $sitelockedfields)),
            'disabled' => $institution != 'mahara' && in_array($field, $sitelockedfields)
640 641
        );
    }
642

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
    // 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']);
    }

666 667
    $elements['submit'] = array(
        'type' => 'submitcancel',
668
        'class' => 'btn-primary',
669 670 671
        'value' => array(get_string('submit'), get_string('cancel'))
    );

672
    $institutionform = pieform(array(
673
        'name'     => 'institution',
Pat Kira's avatar
Pat Kira committed
674
        'renderer' => 'div',
Penny Leach's avatar
Penny Leach committed
675 676
        'plugintype' => 'core',
        'pluginname' => 'admin',
677
        'elements' => $elements
678
    ));
679 680 681 682

}
else {
    // Get a list of institutions
683
    define('SECTION_PAGE', 'institutions');
684
    require_once(get_config('libroot') . 'institution.php');
685
    if (!$USER->get('admin')) { // Filter the list for institutional admins
686 687
        $filter      = $USER->get('admininstitutions');
        $showdefault = false;
688 689
    }
    else {
690 691
        $filter      = false;
        $showdefault = true;
692
    }
693
    $data = build_institutions_html($filter, $showdefault, $query, $limit, $offset, $count);
694 695

    $smarty = smarty(array('lib/pieforms/static/core/pieforms.js', 'paginator'));
696
    setpageicon($smarty, 'icon-university');
697 698 699 700 701
    $smarty->assign('results', $data);
    $smarty->assign('countinstitutions', $count);

    /*search institution form*/
    $searchform = pieform(array(
702 703
        'name'   => 'search',
        'renderer' => 'div',
Naomi Guyer's avatar
Naomi Guyer committed
704
        'class' => 'form-inline with-heading',
705
        'autofocus' => false,
706
        'elements' => array(
707 708 709 710 711 712 713 714
            'inputgroup' => array(
                'type'  => 'fieldset',
                'title' => get_string('Query') . ': ',
                'class' => 'input-group form-inline',
                'elements'     => array(
                    'query' => array(
                        'type'  => 'text',
                        'defaultvalue' => $query,
715
                        'hiddenlabel' => true,
716 717
                        'value' => '',
                        'placeholder' => get_string('search'),
718
                        'title' => get_string('search'),
719 720 721 722
                    ),
                    'submit' => array(
                        'type'  => 'button',
                        'usebuttontag' => true,
723
                        'class' => 'btn-primary input-group-append',
724 725 726
                        'value' => get_string('search'),
                    )
                ),
727
            ),
728
        ),
729 730 731 732
    ));
    $smarty->assign('searchform', $searchform);

    $js = <<< EOF
733 734 735 736 737
    jQuery(function($) {
      p = {$data['pagination_js']}
      $('#search_submit').on('click', function(event) {
        $('#messages').empty();
        var params = {'query': $('#search_query').val()};
738
        p.sendQuery(params);
739 740
        event.preventDefault();
      });
741 742 743 744
    });
EOF;

    $smarty->assign('INLINEJAVASCRIPT', $js);
745 746 747 748
    $smarty->assign('siteadmin', $USER->get('admin'));
    $smarty->assign('PAGEHEADING', get_string('admininstitutions', 'admin'));
    $smarty->display('admin/users/institutions.tpl');
    exit;
749 750
}

751
function institution_validate(Pieform $form, $values) {
752
    global $USER, $institution, $add;
753

754 755 756 757
    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'));
        }
758
    }
759

760 761
    if (get_config('licensemetadata') && !empty($values['licensemandatory']) &&
        (isset($values['licensedefault']) && $values['licensedefault'] == '')) {
762 763 764
        $form->set_error('licensedefault', get_string('licensedefaultmandatory', 'admin'));
    }

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

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    // 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'));
            }
        }
    }

823 824 825
    if (!empty($values['lang']) && $values['lang'] != 'sitedefault' && !array_key_exists($values['lang'], get_languages())) {
        $form->set_error('lang', get_string('institutionlanginvalid', 'admin'));
    }
826
    if (!is_plugin_active('framework', 'module') && (!empty($values['allowinstitutionsmartevidence']))) {
827 828
        $form->set_error('allowinstitutionsmartevidence', get_string('institutionsmartevidencenotallowed', 'admin'));
    }
829 830 831

    // Validate plugins settings.
    plugin_institution_prefs_validate($form, $values);
832 833
}

834
function institution_submit(Pieform $form, $values) {
835
    global $SESSION, $institution, $add, $instancearray, $USER, $authinstances, $customthemedefaults;
836 837 838 839

    db_begin();
    // Update the basic institution record...
    if ($add) {
840
        $institution = institution_generate_name($values['displayname']);
841
        $newinstitution = new Institution();
842
        $newinstitution->initialise($institution, $values['displayname']);
843
        $institution = $newinstitution->name;
844
    }
845
    else {
846 847
        $newinstitution = new Institution($institution);
        $newinstitution->displayname = $values['displayname'];
848 849
        $oldinstitution = get_record(