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
        'title' => get_string('password'),
        'rules' => array('required' => true),
    ),
    'staff' => array(
86
        'type' => 'switchbox',
87
88
89
90
        'title' => get_string('sitestaff', 'admin'),
        'ignore' => !$USER->get('admin'),
    ),
    'admin' => array(
91
        'type' => 'switchbox',
92
93
94
95
96
        '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
        'type'         => 'switchbox',
111
        '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
    'class' => 'panel panel-body pts',
143
144
145
    'autofocus'  => false,
    'template'   => 'adduser.php',
    'templatedir' => pieform_template_dir('adduser.php'),
146
147
148
149
150
151
152
    'plugintype' => 'core',
    'pluginname' => 'admin',
    'elements'   => $elements,
));


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

    $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
168
    if ($institution->isFull()) {
169
        $institution->send_admin_institution_is_full_message();
170
171
        $form->set_error('authinstance', get_string('institutionmaxusersexceeded', 'admin'));
        return;
172
173
174
    }

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

180
181
182
183
184
185
    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)));
        }
186
187
    }

188
189
190
191
192
193
194
195
196
    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'));
        }
197
    }
198
    if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($username)))) {
199
200
201
        $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal'));
    }

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

206
207
208
209
    if (isset($_POST['createmethod']) && $_POST['createmethod'] == 'leap2a') {
        $form->set_error('firstname', null);
        $form->set_error('lastname', null);
        $form->set_error('email', null);
210
211
212
213
214
215
216
217
        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']) {
218
219
220
221
            $form->set_error('leap2afile', $form->i18n('rule', 'required', 'required'));
            return;
        }

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

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

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

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

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

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

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

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

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

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

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

315
316
    if (isset($values['leap2afile'])) {
        // And we're good to go
317
        $importdata = (object)array(
318
319
320
321
322
323
324
325
326
            '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,
327
328
        );
        $importer = PluginImport::create_importer(null, $TRANSPORTER, $importdata);
329
330
331

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

339
340
341
        // 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);
342
    }
343
344
345
346
347
348

    db_commit();

    if (!empty($user->email)) {
        try {
            email_user($user, $USER, get_string('accountcreated', 'mahara', get_config('sitename')),
349
350
                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'))
351
352
353
354
355
            );
        }
        catch (EmailException $e) {
            $SESSION->add_error_msg(get_string('newuseremailnotsent', 'admin'));
        }
356
    }
357

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

362
$smarty = smarty(array('adminadduser'));
363
setpageicon($smarty, 'icon-user-plus');
364
$smarty->assign('form', $form);
365
$smarty->assign('PAGEHEADING', TITLE);
366
$smarty->display('admin/users/add.tpl');