add.php 13.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 12 13
 *
 */

define('INTERNAL', 1);
define('INSTITUTIONALADMIN', 1);
14
define('MENUITEM', 'configusers/adduser');
15
require(dirname(dirname(dirname(__FILE__))) . '/init.php');
16
define('TITLE', get_string('adduser', 'admin'));
17 18 19 20 21
define('SECTION_PLUGINTYPE', 'core');
define('SECTION_PLUGINNAME', 'admin');
require_once('pieforms/pieform.php');
require_once('institution.php');

22 23
$TRANSPORTER = null;

24 25
if ($USER->get('admin')) {
    $authinstances = auth_get_auth_instances();
26 27
}
else {
28 29 30 31 32 33 34 35
    $admininstitutions = $USER->get('admininstitutions');
    $authinstances = auth_get_auth_instances_for_institutions($admininstitutions);
    if (empty($authinstances)) {
        $SESSION->add_info_msg(get_string('configureauthplugin', 'admin'));
        redirect(get_config('wwwroot').'admin/users/institutions.php?i='.key($admininstitutions).'&amp;edit=1');
    }
}

36 37 38
$authinstancecount = count($authinstances);

if ($authinstancecount) {
39 40 41 42 43 44 45 46 47 48 49
    $options = array();

    $external = false;
    foreach ($authinstances as $authinstance) {
        if ($USER->can_edit_institution($authinstance->name)) {
            $options[$authinstance->id] = $authinstance->displayname. ': '.$authinstance->instancename;
            if ($authinstance->authname != 'internal') {
                $external = true;
            }
        }
    }
50
}
51

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
$elements = array(
    'firstname' => array(
        'type'    => 'text',
        'title'   => get_string('firstname'),
        'rules'   => array('required' => true),
    ),
    'lastname' => array(
        'type'    => 'text',
        'title'   => get_string('lastname'),
        'rules'   => array('required' => true),
    ),
    'email' => array(
        'type'    => 'text',
        'title'   => get_string('email'),
        'rules'   => array('required' => true),
    ),
    'leap2afile' => array(
        'type' => 'file',
        'title' => '',
    ),
    'username' => array(
        'type' => 'text',
        'title' => get_string('username'),
75 76 77 78
        'rules' => array(
            'required' => true,
            'maxlength' => 236,
        ),
79 80
    ),
    'password' => array(
81
        'type' => 'password',
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
        'title' => get_string('password'),
        'rules' => array('required' => true),
    ),
    'staff' => array(
        'type' => 'checkbox',
        'title' => get_string('sitestaff', 'admin'),
        'ignore' => !$USER->get('admin'),
    ),
    'admin' => array(
        'type' => 'checkbox',
        'title' => get_string('siteadmin', 'admin'),
        'ignore' => !$USER->get('admin'),
    ),
    'quota' => array(
        'type'         => 'bytes',
97
        'title'        => get_string('filequota1','admin'),
98 99 100 101
        'rules'        => array('integer' => true, 'minvalue' => 0),
        'defaultvalue' => get_config_plugin('artefact', 'file', 'defaultquota'),
    ),
    'authinstance' => array(
102 103 104
        'type'         => 'select',
        'title'        => get_string('institution'),
        'options'      => $options,
105
        'defaultvalue' => 1,
106
        'rules'        => array('required' => true),
107 108 109
        'ignore'       => !$authinstancecount,
    ),
    'institutionadmin' => array(
110 111
        'type'         => 'checkbox',
        'title'        => get_string('institutionadministrator','admin'),
112 113 114 115 116 117
        'ignore'       => !$authinstancecount,
    ),
    'submit' => array(
        'type' => 'submit',
        'value' => get_string('createuser', 'admin'),
    ),
118 119
);

120 121 122
if (!$USER->get('admin')) {
    unset ($elements['authinstance']['defaultvalue']);
}
123

124 125 126 127
if (!($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride'))) {
    $elements['quota'] = array(
        'type'         => 'text',
        'disabled'     => true,
128
        'title'        => get_string('filequota1', 'admin'),
129 130 131 132 133
        'description'  => get_string('filequotadescription', 'admin'),
        'value'        => display_size(get_config_plugin('artefact', 'file', 'defaultquota')),
    );
}

134 135 136 137 138 139
// Add general account options
$prefs = (object) expected_account_preferences();
$elements = array_merge($elements, general_account_prefs_form_elements($prefs));
unset($prefs);


140 141
$form = pieform(array(
    'name'       => 'adduser',
142 143 144
    'autofocus'  => false,
    'template'   => 'adduser.php',
    'templatedir' => pieform_template_dir('adduser.php'),
145 146 147 148 149 150 151
    'plugintype' => 'core',
    'pluginname' => 'admin',
    'elements'   => $elements,
));


function adduser_validate(Pieform $form, $values) {
152
    global $USER, $TRANSPORTER;
153 154 155 156 157 158 159 160 161 162 163 164 165 166

    $authobj = AuthFactory::create($values['authinstance']);

    $institution = $authobj->institution;

    // Institutional admins can only set their own institutions' authinstances
    if (!$USER->get('admin') && !$USER->is_institutional_admin($authobj->institution)) {
        $form->set_error('authinstance', get_string('notadminforinstitution', 'admin'));
        return;
    }

    $institution = new Institution($authobj->institution);

    // Don't exceed max user accounts for the institution
167
    if ($institution->isFull()) {
168
        $institution->send_admin_institution_is_full_message();
169 170
        $form->set_error('authinstance', get_string('institutionmaxusersexceeded', 'admin'));
        return;
171 172 173
    }

    $username  = $values['username'];
174 175 176
    $firstname = sanitize_firstname($values['firstname']);
    $lastname  = sanitize_lastname($values['lastname']);
    $email     = sanitize_email($values['email']);
177 178
    $password  = $values['password'];

179 180 181 182 183 184
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        $maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled');
        $maxquota = get_config_plugin('artefact', 'file', 'maxquota');
        if ($maxquotaenabled && $values['quota'] > $maxquota) {
            $form->set_error('quota', get_string('maxquotaexceededform', 'artefact.file', display_size($maxquota)));
        }
185 186
    }

187 188 189 190 191 192 193 194 195
    if (method_exists($authobj, 'is_username_valid_admin')) {
        if (!$authobj->is_username_valid_admin($username)) {
            $form->set_error('username', get_string('usernameinvalidadminform', 'auth.internal'));
        }
    }
    else if (method_exists($authobj, 'is_username_valid')) {
        if (!$authobj->is_username_valid($username)) {
            $form->set_error('username', get_string('usernameinvalidform', 'auth.internal'));
        }
196
    }
197
    if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($username)))) {
198 199 200
        $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal'));
    }

201 202
    if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) {
        $form->set_error('password', get_string('passwordinvalidform', 'auth.' . $authobj->type));
203 204
    }

205 206 207 208
    if (isset($_POST['createmethod']) && $_POST['createmethod'] == 'leap2a') {
        $form->set_error('firstname', null);
        $form->set_error('lastname', null);
        $form->set_error('email', null);
209 210 211 212 213 214 215 216
        if (!$values['leap2afile'] && ($_FILES['leap2afile']['error'] == UPLOAD_ERR_INI_SIZE || $_FILES['leap2afile']['error'] == UPLOAD_ERR_FORM_SIZE)) {
            $form->reply(PIEFORM_ERR, array(
                'message' => get_string('uploadedfiletoobig'),
                'goto'    => '/admin/users/add.php'));
            $form->set_error('leap2afile', get_string('uploadedfiletoobig'));
            return;
        }
        else if (!$values['leap2afile']) {
217 218 219 220
            $form->set_error('leap2afile', $form->i18n('rule', 'required', 'required'));
            return;
        }

221
        if ($values['leap2afile']['type'] == 'application/octet-stream') {
222 223
            require_once('file.php');
            $mimetype = file_mime_type($values['leap2afile']['tmp_name']);
224 225
        }
        else {
226
            $mimetype = trim($values['leap2afile']['type'], '"');
227
        }
228 229
        $date = time();
        $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $values['username']);
230
        safe_require('import', 'leap');
231 232 233 234 235
        $fakeimportrecord = (object)array(
            'data' => array(
                'importfile'     => $values['leap2afile']['tmp_name'],
                'importfilename' => $values['leap2afile']['name'],
                'importid'       => $niceuser . '-' . $date,
236
                'mimetype'       => $mimetype,
237 238 239 240
            )
        );

        $TRANSPORTER = new LocalImporterTransport($fakeimportrecord);
241
        try {
242
            $TRANSPORTER->extract_file();
243
            PluginImportLeap::validate_transported_data($TRANSPORTER);
244
        }
245 246
        catch (Exception $e) {
            $form->set_error('leap2afile', $e->getMessage());
247
        }
248
    }
249
    else {
250
        if (!$form->get_error('firstname') && empty($firstname)) {
251 252
            $form->set_error('firstname', $form->i18n('rule', 'required', 'required'));
        }
253
        if (!$form->get_error('lastname') && empty($lastname)) {
254 255 256 257
            $form->set_error('lastname', $form->i18n('rule', 'required', 'required'));
        }

        if (!$form->get_error('email')) {
258
            if (!$form->get_error('email') && empty($email)) {
259 260
                $form->set_error('email', get_string('invalidemailaddress', 'artefact.internal'));
            }
261

262 263 264 265 266 267
            if (record_exists('usr', 'email', $email)
                || record_exists('artefact_internal_profile_email', 'email', $email)) {
                $form->set_error('email', get_string('emailalreadytaken', 'auth.internal'));
            }
        }
    }
268 269 270
}

function adduser_submit(Pieform $form, $values) {
271
    global $USER, $SESSION, $TRANSPORTER;
272
    db_begin();
273

274
    raise_time_limit(180);
275 276 277 278 279 280 281

    // Create user
    $user = (object)array(
        'authinstance'   => $values['authinstance'],
        'username'       => $values['username'],
        'firstname'      => ($values['firstname']) ? $values['firstname'] : 'Imported',
        'lastname'       => ($values['lastname']) ? $values['lastname'] : 'User',
282
        'email'          => $values['email'],
283 284 285
        'password'       => $values['password'],
        'passwordchange' => 1,
    );
286 287 288 289
    if ($USER->get('admin')) {  // Not editable by institutional admins
        $user->staff = (int) ($values['staff'] == 'on');
        $user->admin = (int) ($values['admin'] == 'on');
    }
290 291 292
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        $user->quota = $values['quota'];
    }
293 294

    $authinstance = get_record('auth_instance', 'id', $values['authinstance']);
295 296 297 298
    $remoteauth = false;
    if ($authinstance->authname != 'internal') {
        $remoteauth = true;
    }
299
    if (!isset($values['remoteusername'])){
300 301 302
        $values['remoteusername'] = null;
    }

303
    $user->id = create_user($user, array(), $authinstance->institution, $remoteauth, $values['remoteusername'], $values);
304 305

    if (isset($user->admin) && $user->admin) {
306
        require_once('activity.php');
307 308 309
        activity_add_admin_defaults(array($user->id));
    }

310 311
    if ($values['institutionadmin']) {
        set_field('usr_institution', 'admin', 1, 'usr', $user->id, 'institution', $authinstance->institution);
312 313
    }

314 315
    if (isset($values['leap2afile'])) {
        // And we're good to go
316
        $importdata = (object)array(
317 318 319 320 321 322 323 324 325
            'token'      => '',
            'usr'        => $user->id,
            'queue'      => (int)!(PluginImport::import_immediately_allowed()), // import allowed straight away? Then don't queue
            'ready'      => 0, // maybe 1?
            'expirytime' => db_format_timestamp(time()+(60*60*24)),
            'format'     => 'leap',
            'loglevel'   => PluginImportLeap::LOG_LEVEL_VERBOSE,
            'logtargets' => LOG_TARGET_FILE,
            'profile'    => true,
326 327
        );
        $importer = PluginImport::create_importer(null, $TRANSPORTER, $importdata);
328 329 330

        try {
            $importer->process();
Francois Marier's avatar
Francois Marier committed
331
            log_info("Imported user account $user->id from Leap2A file, see " . $importer->get('logfile') . ' for a full log');
332 333
        }
        catch (ImportException $e) {
Francois Marier's avatar
Francois Marier committed
334
            log_info("Leap2A import failed: " . $e->getMessage());
335 336
            die_info(get_string('leap2aimportfailed', 'admin'));
        }
337

338 339 340
        // Reload the user details, as various fields are changed by the
        // importer when importing (e.g. firstname/lastname)
        $user = get_record('usr', 'id', $user->id);
341
    }
342 343 344 345 346 347

    db_commit();

    if (!empty($user->email)) {
        try {
            email_user($user, $USER, get_string('accountcreated', 'mahara', get_config('sitename')),
348 349
                get_string('accountcreatedchangepasswordtext', 'mahara', $user->firstname, get_config('sitename'), $user->username, $values['password'], get_config('wwwroot'), get_config('sitename')),
                get_string('accountcreatedchangepasswordhtml', 'mahara', $user->firstname, get_config('wwwroot'), get_config('sitename'), $user->username, $values['password'], get_config('wwwroot'), get_config('wwwroot'), get_config('sitename'))
350 351 352 353 354
            );
        }
        catch (EmailException $e) {
            $SESSION->add_error_msg(get_string('newuseremailnotsent', 'admin'));
        }
355
    }
356

357 358
    $SESSION->add_ok_msg(get_string('newusercreated', 'admin'));
    redirect('/admin/users/edit.php?id=' . $user->id);
359 360
}

361
$smarty = smarty(array('adminadduser'));
362
$smarty->assign('form', $form);
363
$smarty->assign('PAGEHEADING', TITLE);
364
$smarty->display('admin/users/add.tpl');