MDL-25936 fixed user upload when manual plugin not first
[moodle.git] / admin / uploaduser.php
CommitLineData
9e492db0 1<?php
0a6150ca 2
3/// Bulk user registration script from a comma separated file
4/// Returns list of users with their user ids
5
e4e38544 6require('../config.php');
cc891abe 7require_once($CFG->libdir.'/adminlib.php');
e4e38544 8require_once($CFG->libdir.'/csvlib.class.php');
9require_once($CFG->dirroot.'/user/profile/lib.php');
59186c92 10require_once($CFG->dirroot.'/group/lib.php');
0a5dffcc 11require_once('uploaduser_form.php');
1ae083e4 12
e4e38544 13$iid = optional_param('iid', '', PARAM_INT);
df7ecfe4 14$previewrows = optional_param('previewrows', 10, PARAM_INT);
e4e38544 15$readcount = optional_param('readcount', 0, PARAM_INT);
3fe2cfb5 16$uploadtype = optional_param('uutype', 0, PARAM_INT);
df7ecfe4 17
e4e38544 18define('UU_ADDNEW', 0);
19define('UU_ADDINC', 1);
20define('UU_ADD_UPDATE', 2);
21define('UU_UPDATE', 3);
066bfbfe 22
3fe2cfb5
RW
23$choices = array(UU_ADDNEW => get_string('uuoptype_addnew', 'admin'),
24 UU_ADDINC => get_string('uuoptype_addinc', 'admin'),
25 UU_ADD_UPDATE => get_string('uuoptype_addupdate', 'admin'),
26 UU_UPDATE => get_string('uuoptype_update', 'admin'));
27
df7ecfe4 28@set_time_limit(3600); // 1 hour should be enough
c22473a2 29raise_memory_limit(MEMORY_EXTRA);
0a6150ca 30
ebff4779 31require_login();
066bfbfe 32admin_externalpage_setup('uploadusers');
1ae083e4 33require_capability('moodle/site:uploadusers', get_context_instance(CONTEXT_SYSTEM));
0a6150ca 34
1c0ccfd6 35$textlib = textlib_get_instance();
e4e38544 36$systemcontext = get_context_instance(CONTEXT_SYSTEM);
37
38$struserrenamed = get_string('userrenamed', 'admin');
39$strusernotrenamedexists = get_string('usernotrenamedexists', 'error');
40$strusernotrenamedmissing = get_string('usernotrenamedmissing', 'error');
41$strusernotrenamedoff = get_string('usernotrenamedoff', 'error');
42$strusernotrenamedadmin = get_string('usernotrenamedadmin', 'error');
43
44$struserupdated = get_string('useraccountupdated', 'admin');
45$strusernotupdated = get_string('usernotupdatederror', 'error');
46$strusernotupdatednotexists = get_string('usernotupdatednotexists', 'error');
47$strusernotupdatedadmin = get_string('usernotupdatedadmin', 'error');
48
49$struseradded = get_string('newuser');
50$strusernotadded = get_string('usernotaddedregistered', 'error');
51$strusernotaddederror = get_string('usernotaddederror', 'error');
52
53$struserdeleted = get_string('userdeleted', 'admin');
54$strusernotdeletederror = get_string('usernotdeletederror', 'error');
55$strusernotdeletedmissing = get_string('usernotdeletedmissing', 'error');
56$strusernotdeletedoff = get_string('usernotdeletedoff', 'error');
57$strusernotdeletedadmin = get_string('usernotdeletedadmin', 'error');
58
59$strcannotassignrole = get_string('cannotassignrole', 'error');
60$strduplicateusername = get_string('duplicateusername', 'error');
61
62$struserauthunsupported = get_string('userauthunsupported', 'error');
3fe2cfb5 63$stremailduplicate = get_string('useremailduplicate', 'error');
e4e38544 64
3f12c146 65$strinvalidpasswordpolicy = get_string('invalidpasswordpolicy', 'error');
e4e38544 66$errorstr = get_string('error');
ca23a9c9 67
e4e38544 68$returnurl = $CFG->wwwroot.'/'.$CFG->admin.'/uploaduser.php';
69$bulknurl = $CFG->wwwroot.'/'.$CFG->admin.'/user/user_bulk.php';
70
2a6dcb72
PS
71$today = time();
72$today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
73
e4e38544 74// array of all valid fields for validation
6dbcacee 75$STD_FIELDS = array('id', 'firstname', 'lastname', 'username', 'email',
76 'city', 'country', 'lang', 'auth', 'timezone', 'mailformat',
77 'maildisplay', 'maildigest', 'htmleditor', 'ajax', 'autosubscribe',
78 'mnethostid', 'institution', 'department', 'idnumber', 'skype',
79 'msn', 'aim', 'yahoo', 'icq', 'phone1', 'phone2', 'address',
46505ee7 80 'url', 'description', 'descriptionformat', 'oldusername', 'deleted',
c79106c4 81 'password');
e4e38544 82
83$PRF_FIELDS = array();
84
1d8bf5f0 85if ($prof_fields = $DB->get_records('user_info_field')) {
e4e38544 86 foreach ($prof_fields as $prof_field) {
87 $PRF_FIELDS[] = 'profile_field_'.$prof_field->shortname;
88 }
89 unset($prof_fields);
90}
91
92if (empty($iid)) {
df7ecfe4 93 $mform = new admin_uploaduser_form1();
0a6150ca 94
df7ecfe4 95 if ($formdata = $mform->get_data()) {
e4e38544 96 $iid = csv_import_reader::get_new_iid('uploaduser');
97 $cir = new csv_import_reader($iid, 'uploaduser');
df7ecfe4 98
e4e38544 99 $content = $mform->get_file_content('userfile');
3fe2cfb5 100 $optype = $formdata->uutype;
e4e38544 101 $readcount = $cir->load_csv_content($content, $formdata->encoding, $formdata->delimiter_name, 'validate_user_upload_columns');
102 unset($content);
df7ecfe4 103
e4e38544 104 if ($readcount === false) {
bd8ee7c1 105 //TODO: need more detailed error info
106 print_error('csvloaderror', '', $returnurl);
e4e38544 107 } else if ($readcount == 0) {
5a2a5331 108 print_error('csvemptyfile', 'error', $returnurl);
ed22a01b 109 }
e4e38544 110 // continue to form2
df7ecfe4 111
112 } else {
61ef8f9f 113 echo $OUTPUT->header();
9e492db0 114
6c7a5df7 115 echo $OUTPUT->heading_with_help(get_string('uploadusers', 'admin'), 'uploadusers', 'admin');
9e492db0 116
df7ecfe4 117 $mform->display();
73d6f52f 118 echo $OUTPUT->footer();
df7ecfe4 119 die;
120 }
e4e38544 121} else {
122 $cir = new csv_import_reader($iid, 'uploaduser');
df7ecfe4 123}
124
e4e38544 125if (!$columns = $cir->get_columns()) {
8e9d88f2 126 print_error('cannotreadtmpfile', 'error', $returnurl);
e4e38544 127}
128$mform = new admin_uploaduser_form2(null, $columns);
129// get initial date from form1
3fe2cfb5 130$mform->set_data(array('iid'=>$iid, 'previewrows'=>$previewrows, 'readcount'=>$readcount, 'uutypelabel'=>$choices[$uploadtype], 'uutype'=>$uploadtype));
df7ecfe4 131
132// If a file has been uploaded, then process it
133if ($formdata = $mform->is_cancelled()) {
e4e38544 134 $cir->cleanup(true);
135 redirect($returnurl);
df7ecfe4 136
294ce987 137} else if ($formdata = $mform->get_data()) {
df7ecfe4 138 // Print the header
61ef8f9f 139 echo $OUTPUT->header();
2fff8846 140 echo $OUTPUT->heading(get_string('uploadusersresult', 'admin'));
e4e38544 141
142 $optype = $formdata->uutype;
143
0c4807ab 144 $createpasswords = (!empty($formdata->uupasswordnew) and $optype != UU_UPDATE);
145 $updatepasswords = (!empty($formdata->uupasswordold) and $optype != UU_ADDNEW and $optype != UU_ADDINC);
146 $allowrenames = (!empty($formdata->uuallowrenames) and $optype != UU_ADDNEW and $optype != UU_ADDINC);
147 $allowdeletes = (!empty($formdata->uuallowdeletes) and $optype != UU_ADDNEW and $optype != UU_ADDINC);
148 $updatetype = isset($formdata->uuupdatetype) ? $formdata->uuupdatetype : 0;
149 $bulk = $formdata->uubulk;
150 $noemailduplicates = $formdata->uunoemailduplicates;
e4e38544 151
152 // verification moved to two places: after upload and into form2
153 $usersnew = 0;
154 $usersupdated = 0;
155 $userserrors = 0;
156 $deletes = 0;
157 $deleteerrors = 0;
158 $renames = 0;
159 $renameerrors = 0;
160 $usersskipped = 0;
d6bb2d2f 161 $weakpasswords = 0;
feecd4d6 162
e4e38544 163 // caches
df997f84
PS
164 $ccache = array(); // course cache - do not fetch all courses here, we will not probably use them all anyway!
165 $rolecache = uu_allowed_roles_cache(); // roles lookup cache
48265158 166 $manualcache = array(); // cache of used manual enrol plugins in each course
e4e38544 167
168 $allowedauths = uu_allowed_auths();
169 $allowedauths = array_keys($allowedauths);
17da2e6f 170 $availableauths = get_plugin_list('auth');
171 $availableauths = array_keys($availableauths);
e4e38544 172
df997f84
PS
173 // we use only manual enrol plugin here, if it is disabled no enrol is done
174 if (enrol_is_enabled('manual')) {
175 $manual = enrol_get_plugin('manual');
176 } else {
177 $manual = NULL;
e4e38544 178 }
df7ecfe4 179
b4bd91ce 180 // clear bulk selection
e4e38544 181 if ($bulk) {
cd1edf9e 182 $SESSION->bulk_users = array();
e4e38544 183 }
df7ecfe4 184
e4e38544 185 // init csv import helper
186 $cir->init();
187 $linenum = 1; //column header is first line
df7ecfe4 188
e4e38544 189 // init upload progress tracker
190 $upt = new uu_progress_tracker();
191 $upt->init(); // start table
a2ce7344 192
e4e38544 193 while ($line = $cir->next()) {
194 $upt->flush();
195 $linenum++;
196
197 $upt->track('line', $linenum);
198
d6bb2d2f
PS
199 $forcechangepassword = false;
200
a226a972 201 $user = new stdClass();
e4e38544 202 // by default, use the local mnet id (this may be changed in the file)
203 $user->mnethostid = $CFG->mnet_localhost_id;
204 // add fields to user object
205 foreach ($line as $key => $value) {
206 if ($value !== '') {
df997f84 207 $key = $columns[$key];
3f12c146
RW
208 $user->$key = $value;
209 if (in_array($key, $upt->columns)) {
210 $upt->track($key, $value);
e4e38544 211 }
c3231d1d
RW
212 } else {
213 $user->$columns[$key] = '';
a7db355a 214 }
215 }
e4e38544 216
217 // get username, first/last name now - we need them in templates!!
218 if ($optype == UU_UPDATE) {
219 // when updating only username is required
220 if (!isset($user->username)) {
221 $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
222 $upt->track('username', $errorstr, 'error');
223 $userserrors++;
224 continue;
225 }
226
227 } else {
228 $error = false;
229 // when all other ops need firstname and lastname
230 if (!isset($user->firstname) or $user->firstname === '') {
231 $upt->track('status', get_string('missingfield', 'error', 'firstname'), 'error');
232 $upt->track('firstname', $errorstr, 'error');
233 $error = true;
234 }
235 if (!isset($user->lastname) or $user->lastname === '') {
236 $upt->track('status', get_string('missingfield', 'error', 'lastname'), 'error');
237 $upt->track('lastname', $errorstr, 'error');
238 $error = true;
239 }
240 if ($error) {
241 $userserrors++;
242 continue;
243 }
244 // we require username too - we might use template for it though
245 if (!isset($user->username)) {
246 if (!isset($formdata->username) or $formdata->username === '') {
247 $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
248 $upt->track('username', $errorstr, 'error');
249 $userserrors++;
250 continue;
251 } else {
252 $user->username = process_template($formdata->username, $user);
253 $upt->track('username', $user->username);
254 }
255 }
a7db355a 256 }
e4e38544 257
258 // normalize username
07ed083e
RW
259 $user->username = clean_param($user->username, PARAM_USERNAME);
260
e4e38544 261 if (empty($user->username)) {
262 $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
263 $upt->track('username', $errorstr, 'error');
264 $userserrors++;
265 continue;
266 }
267
1d8bf5f0 268 if ($existinguser = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
e4e38544 269 $upt->track('id', $existinguser->id, 'normal', false);
270 }
271
272 // find out in username incrementing required
273 if ($existinguser and $optype == UU_ADDINC) {
274 $oldusername = $user->username;
275 $user->username = increment_username($user->username, $user->mnethostid);
276 $upt->track('username', '', 'normal', false); // clear previous
277 $upt->track('username', $oldusername.'-->'.$user->username, 'info');
278 $existinguser = false;
279 }
280
281 // add default values for remaining fields
282 foreach ($STD_FIELDS as $field) {
283 if (isset($user->$field)) {
284 continue;
285 }
286 // all validation moved to form2
287 if (isset($formdata->$field)) {
288 // process templates
289 $user->$field = process_template($formdata->$field, $user);
290 }
291 }
292 foreach ($PRF_FIELDS as $field) {
293 if (isset($user->$field)) {
294 continue;
295 }
296 if (isset($formdata->$field)) {
297 // process templates
298 $user->$field = process_template($formdata->$field, $user);
299 }
300 }
301
302 // delete user
303 if (!empty($user->deleted)) {
304 if (!$allowdeletes) {
305 $usersskipped++;
306 $upt->track('status', $strusernotdeletedoff, 'warning');
307 continue;
308 }
309 if ($existinguser) {
4f0c2d00 310 if (is_siteadmin($existinguser->id)) {
e4e38544 311 $upt->track('status', $strusernotdeletedadmin, 'error');
312 $deleteerrors++;
313 continue;
314 }
315 if (delete_user($existinguser)) {
316 $upt->track('status', $struserdeleted);
317 $deletes++;
318 } else {
319 $upt->track('status', $strusernotdeletederror, 'error');
320 $deleteerrors++;
6b09974b 321 }
e4e38544 322 } else {
323 $upt->track('status', $strusernotdeletedmissing, 'error');
324 $deleteerrors++;
325 }
326 continue;
327 }
328 // we do not need the deleted flag anymore
329 unset($user->deleted);
330
331 // renaming requested?
332 if (!empty($user->oldusername) ) {
333 $oldusername = $textlib->strtolower($user->oldusername);
334 if (!$allowrenames) {
335 $usersskipped++;
336 $upt->track('status', $strusernotrenamedoff, 'warning');
337 continue;
338 }
339
340 if ($existinguser) {
341 $upt->track('status', $strusernotrenamedexists, 'error');
342 $renameerrors++;
343 continue;
16a1fed4 344 }
ed22a01b 345
1d8bf5f0 346 if ($olduser = $DB->get_record('user', array('username'=>$oldusername, 'mnethostid'=>$user->mnethostid))) {
e4e38544 347 $upt->track('id', $olduser->id, 'normal', false);
4f0c2d00 348 if (is_siteadmin($olduser->id)) {
e4e38544 349 $upt->track('status', $strusernotrenamedadmin, 'error');
350 $renameerrors++;
a7db355a 351 continue;
0063abee 352 }
df997f84
PS
353 $DB->set_field('user', 'username', $user->username, array('id'=>$olduser->id));
354 $upt->track('username', '', 'normal', false); // clear previous
355 $upt->track('username', $oldusername.'-->'.$user->username, 'info');
356 $upt->track('status', $struserrenamed);
357 $renames++;
e4e38544 358 } else {
359 $upt->track('status', $strusernotrenamedmissing, 'error');
360 $renameerrors++;
361 continue;
362 }
363 $existinguser = $olduser;
364 $existinguser->username = $user->username;
365 }
366
367 // can we process with update or insert?
368 $skip = false;
369 switch ($optype) {
370 case UU_ADDNEW:
371 if ($existinguser) {
372 $usersskipped++;
373 $upt->track('status', $strusernotadded, 'warning');
3fe2cfb5 374 $skip = true;
e4e38544 375 }
376 break;
377
378 case UU_ADDINC:
379 if ($existinguser) {
380 //this should not happen!
381 $upt->track('status', $strusernotaddederror, 'error');
382 $userserrors++;
383 continue;
384 }
385 break;
386
387 case UU_ADD_UPDATE:
388 break;
389
390 case UU_UPDATE:
391 if (!$existinguser) {
392 $usersskipped++;
393 $upt->track('status', $strusernotupdatednotexists, 'warning');
394 $skip = true;
395 }
396 break;
397 }
398
399 if ($skip) {
400 continue;
401 }
402
403 if ($existinguser) {
404 $user->id = $existinguser->id;
405
4f0c2d00 406 if (is_siteadmin($user->id)) {
e4e38544 407 $upt->track('status', $strusernotupdatedadmin, 'error');
408 $userserrors++;
409 continue;
410 }
411
412 if (!$updatetype) {
413 // no updates of existing data at all
414 } else {
415 $existinguser->timemodified = time();
3fe2cfb5
RW
416 if (empty($existinguser->timecreated)) {
417 if (empty($existinguser->firstaccess)) {
418 $existinguser->timecreated = time();
419 } else {
420 $existinguser->timecreated = $existinguser->firstaccess;
421 }
422 }
423
e4e38544 424 //load existing profile data
425 profile_load_data($existinguser);
426
427 $allowed = array();
428 if ($updatetype == 1) {
429 $allowed = $columns;
430 } else if ($updatetype == 2 or $updatetype == 3) {
431 $allowed = array_merge($STD_FIELDS, $PRF_FIELDS);
432 }
433 foreach ($allowed as $column) {
3f12c146 434 $temppasswordhandler = '';
e4e38544 435 if ($column == 'username') {
436 continue;
437 }
4cc977a6 438 if ((property_exists($existinguser, $column) and property_exists($user, $column)) or in_array($column, $PRF_FIELDS)) {
3f12c146 439 if ($updatetype == 3 && $existinguser->$column !== '') {
e4e38544 440 //missing == non-empty only
441 continue;
a7db355a 442 }
e4e38544 443 if ($existinguser->$column !== $user->$column) {
0c4807ab 444 if ($column == 'email') {
1d8bf5f0 445 if ($DB->record_exists('user', array('email'=>$user->email))) {
0c4807ab 446 if ($noemailduplicates) {
447 $upt->track('email', $stremailduplicate, 'error');
448 $upt->track('status', $strusernotupdated, 'error');
449 $userserrors++;
450 continue 2;
451 } else {
452 $upt->track('email', $stremailduplicate, 'warning');
453 }
454 }
455 }
3f12c146
RW
456
457 if ($column == 'password') {
458 $temppasswordhandler = $existinguser->password;
459 }
460
461 if ($column == 'auth') {
462 if (isset($user->auth) && empty($user->auth)) {
463 $user->auth = 'manual';
464 }
465
466 $existinguserauth = get_auth_plugin($existinguser->auth);
467 $existingisinternalauth = $existinguserauth->is_internal();
468
469 $userauth = get_auth_plugin($user->auth);
470 $isinternalauth = $userauth->is_internal();
471
472 if ($isinternalauth === $existingisinternalauth) {
473 if ($updatepasswords) {
474 if (empty($user->password)) {
475 $forcechangepassword = true;
476 }
477 }
478 } else if ($isinternalauth) {
479 $existinguser->password = '';
480 $forcechangepassword = true;
481 }
482 }
483
484 $upt->track($column, '', 'normal', false); // clear previous
485 if ($column != 'password' && in_array($column, $upt->columns)) {
e4e38544 486 $upt->track($column, $existinguser->$column.'-->'.$user->$column, 'info');
487 }
488 $existinguser->$column = $user->$column;
3f12c146
RW
489
490 if (!isset($user->auth) && !$updatepasswords) {
491 $existinguser->password = $temppasswordhandler;
492 }
a7db355a 493 }
6b09974b 494 }
a7db355a 495 }
ed22a01b 496
eab8ed9f 497 // do not update record if new auth plugin does not exist!
e4e38544 498 if (!in_array($existinguser->auth, $availableauths)) {
499 $upt->track('auth', get_string('userautherror', 'error', $existinguser->auth), 'error');
500 $upt->track('status', $strusernotupdated, 'error');
501 $userserrors++;
502 continue;
503 } else if (!in_array($existinguser->auth, $allowedauths)) {
504 $upt->track('auth', $struserauthunsupported, 'warning');
066bfbfe 505 }
a7db355a 506
3f12c146
RW
507 $auth = get_auth_plugin($existinguser->auth);
508 $isinternalauth = $auth->is_internal();
509
510 if ($isinternalauth && $updatepasswords && !check_password_policy($user->password, $errmsg)) {
511 $upt->track('password', get_string('internalauthpassworderror', 'error', $existinguser->password), 'error');
512 $upt->track('status', $strusernotupdated, 'error');
513 $userserrors++;
514 continue;
515 } else {
516 $forcechangepassword = true;
517 }
518
519 if (!$isinternalauth) {
520 $existinguser->password = 'not cached';
521 $upt->track('password', 'not cached');
522 $forcechangepassword = false;
523 } else if ($updatepasswords){
524 $existinguser->password = hash_internal_user_password($existinguser->password);
525 } else {
526 $existinguser->password = $temppasswordhandler;
527 }
528
df997f84 529 $DB->update_record('user', $existinguser);
3f12c146
RW
530
531 //remove user preference
59186c92 532
3f12c146
RW
533 if (get_user_preferences('create_password', false, $existinguser)) {
534 unset_user_preference('create_password', $existinguser);
535 }
536 if (get_user_preferences('auth_forcepasswordchange', false, $existinguser)) {
537 unset_user_preference('auth_forcepasswordchange', $existinguser);
538 }
539
540 if ($isinternalauth && $updatepasswords) {
541 if (empty($existinguser->password)) {
542 set_user_preference('create_password', 1, $existinguser->id);
543 set_user_preference('auth_forcepasswordchange', 1, $existinguser->id);
544 $upt->track('password', get_string('new'));
545 } else if ($forcechangepassword) {
546 set_user_preference('auth_forcepasswordchange', 1, $existinguser->id);
547 }
548 }
df997f84
PS
549 $upt->track('status', $struserupdated);
550 $usersupdated++;
e4e38544 551 // save custom profile fields data from csv file
5d910388 552 profile_save_data($existinguser);
e6f74ba3
PS
553
554 events_trigger('user_updated', $existinguser);
e4e38544 555 }
556
557 if ($bulk == 2 or $bulk == 3) {
cd1edf9e 558 if (!in_array($user->id, $SESSION->bulk_users)) {
559 $SESSION->bulk_users[] = $user->id;
ed22a01b 560 }
066bfbfe 561 }
ed22a01b 562
e4e38544 563 } else {
a7db355a 564 // save the user to the database
565 $user->confirmed = 1;
566 $user->timemodified = time();
3fe2cfb5 567 $user->timecreated = time();
066bfbfe 568
3f12c146
RW
569 if (isset($user->auth) && empty($user->auth)) {
570 $user->auth = 'manual';
571 }
572 $auth = get_auth_plugin($user->auth);
573 $isinternalauth = $auth->is_internal();
574
575 if (!$createpasswords && $isinternalauth) {
576 if (empty($user->password)) {
577 $upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
578 $upt->track('status', $strusernotaddederror, 'error');
579 $userserrors++;
580 continue;
581 } else if ($forcechangepassword) {
582 $upt->track('password', $strinvalidpasswordpolicy);
583 $upt->track('status', $strusernotaddederror, 'error');
584 $userserrors++;
585 continue;
586 }
e4e38544 587 }
588
589 // do not insert record if new auth plguin does not exist!
590 if (isset($user->auth)) {
591 if (!in_array($user->auth, $availableauths)) {
592 $upt->track('auth', get_string('userautherror', 'error', $user->auth), 'error');
593 $upt->track('status', $strusernotaddederror, 'error');
594 $userserrors++;
066bfbfe 595 continue;
e4e38544 596 } else if (!in_array($user->auth, $allowedauths)) {
597 $upt->track('auth', $struserauthunsupported, 'warning');
066bfbfe 598 }
066bfbfe 599 }
a2ce7344 600
1d8bf5f0 601 if ($DB->record_exists('user', array('email'=>$user->email))) {
0c4807ab 602 if ($noemailduplicates) {
603 $upt->track('email', $stremailduplicate, 'error');
604 $upt->track('status', $strusernotaddederror, 'error');
605 $userserrors++;
606 continue;
607 } else {
608 $upt->track('email', $stremailduplicate, 'warning');
609 }
610 }
3f12c146
RW
611 if (!$isinternalauth) {
612 $user->password = 'not cached';
613 $upt->track('password', 'not cached');
614 } else {
615 $user->password = hash_internal_user_password($user->password);
616 }
0c4807ab 617
df997f84
PS
618 $user->id = $DB->insert_record('user', $user);
619 $info = ': ' . $user->username .' (ID = ' . $user->id . ')';
620 $upt->track('status', $struseradded);
621 $upt->track('id', $user->id, 'normal', false);
622 $usersnew++;
3f12c146
RW
623 if ($createpasswords && $isinternalauth) {
624 if (empty($user->password) || $forcechangepassword) {
625 // passwords will be created and sent out on cron
626 set_user_preference('create_password', 1, $user->id);
627 set_user_preference('auth_forcepasswordchange', 1, $user->id);
628 $upt->track('password', get_string('new'));
629 } else {
630 set_user_preference('auth_forcepasswordchange', 1, $user->id);
631 }
df997f84
PS
632 }
633
e4e38544 634 // save custom profile fields data
635 profile_save_data($user);
636
2304f629 637 // make sure user context exists
a5feb176 638 get_context_instance(CONTEXT_USER, $user->id);
2304f629 639
e6f74ba3
PS
640 events_trigger('user_created', $user);
641
e4e38544 642 if ($bulk == 1 or $bulk == 3) {
cd1edf9e 643 if (!in_array($user->id, $SESSION->bulk_users)) {
644 $SESSION->bulk_users[] = $user->id;
066bfbfe 645 }
066bfbfe 646 }
e4e38544 647 }
648
2686b6c3 649 // find course enrolments, groups, roles/types and enrol periods
e4e38544 650 foreach ($columns as $column) {
651 if (!preg_match('/^course\d+$/', $column)) {
652 continue;
653 }
654 $i = substr($column, 6);
6b09974b 655
df997f84
PS
656 if (empty($user->{'course'.$i})) {
657 continue;
658 }
e4e38544 659 $shortname = $user->{'course'.$i};
660 if (!array_key_exists($shortname, $ccache)) {
df997f84 661 if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname')) {
e4e38544 662 $upt->track('enrolments', get_string('unknowncourse', 'error', $shortname), 'error');
a7db355a 663 continue;
066bfbfe 664 }
e4e38544 665 $ccache[$shortname] = $course;
666 $ccache[$shortname]->groups = null;
667 }
668 $courseid = $ccache[$shortname]->id;
669 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
df997f84 670 if (!isset($manualcache[$courseid])) {
4cb02426
PS
671 $manualcache[$courseid] = false;
672 if ($manual) {
673 if ($instances = enrol_get_instances($courseid, false)) {
674 foreach ($instances as $instance) {
675 if ($instance->enrol === 'manual') {
676 $manualcache[$courseid] = $instance;
677 break;
678 }
679 }
680 }
e4e38544 681 }
df997f84 682 }
e4e38544 683
df997f84
PS
684 if ($manual and $manualcache[$courseid]) {
685
686 // find role
687 $rid = false;
688 if (!empty($user->{'role'.$i})) {
689 $addrole = $user->{'role'.$i};
690 if (array_key_exists($addrole, $rolecache)) {
691 $rid = $rolecache[$addrole]->id;
e4e38544 692 } else {
df997f84
PS
693 $upt->track('enrolments', get_string('unknownrole', 'error', $addrole), 'error');
694 continue;
a7db355a 695 }
e4e38544 696
df997f84
PS
697 } else if (!empty($user->{'type'.$i})) {
698 // if no role, then find "old" enrolment type
699 $addtype = $user->{'type'.$i};
700 if ($addtype < 1 or $addtype > 3) {
701 $upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
702 continue;
703 } else if (empty($formdata->{'uulegacy'.$addtype})) {
704 continue;
705 } else {
706 $rid = $formdata->{'uulegacy'.$addtype};
707 }
e4e38544 708 } else {
df997f84
PS
709 // no role specified, use the default from manual enrol plugin
710 $rid = $manualcache[$courseid]->roleid;
a7db355a 711 }
2686b6c3 712
df997f84
PS
713 if ($rid) {
714 // find duration
df997f84
PS
715 $timeend = 0;
716 if (!empty($user->{'enrolperiod'.$i})) {
717 $duration = (int)$user->{'enrolperiod'.$i} * 86400; // convert days to seconds
718 if ($duration > 0) { // sanity check
2a6dcb72 719 $timeend = $today + $duration;
df997f84
PS
720 }
721 }
2686b6c3 722
2a6dcb72 723 $manual->enrol_user($manualcache[$courseid], $user->id, $rid, $today, $timeend, true);
df997f84 724
a226a972 725 $a = new stdClass();
df997f84
PS
726 $a->course = $shortname;
727 $a->role = $rolecache[$rid]->name;
728 $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
066bfbfe 729 }
e4e38544 730 }
6b09974b 731
e4e38544 732 // find group to add to
733 if (!empty($user->{'group'.$i})) {
734 // make sure user is enrolled into course before adding into groups
4f0c2d00 735 if (!is_enrolled($coursecontext, $user->id)) {
d85f2634 736 $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group'.$i}), 'error');
e4e38544 737 continue;
738 }
739 //build group cache
740 if (is_null($ccache[$shortname]->groups)) {
741 $ccache[$shortname]->groups = array();
35987665 742 if ($groups = groups_get_all_groups($courseid)) {
e4e38544 743 foreach ($groups as $gid=>$group) {
a226a972 744 $ccache[$shortname]->groups[$gid] = new stdClass();
e4e38544 745 $ccache[$shortname]->groups[$gid]->id = $gid;
746 $ccache[$shortname]->groups[$gid]->name = $group->name;
747 if (!is_numeric($group->name)) { // only non-numeric names are supported!!!
a226a972 748 $ccache[$shortname]->groups[$group->name] = new stdClass();
e4e38544 749 $ccache[$shortname]->groups[$group->name]->id = $gid;
750 $ccache[$shortname]->groups[$group->name]->name = $group->name;
a7db355a 751 }
a5702569 752 }
0063abee 753 }
6b09974b 754 }
e4e38544 755 // group exists?
756 $addgroup = $user->{'group'.$i};
757 if (!array_key_exists($addgroup, $ccache[$shortname]->groups)) {
b225cf36 758 // if group doesn't exist, create it
a226a972 759 $newgroupdata = new stdClass();
b225cf36 760 $newgroupdata->name = $addgroup;
761 $newgroupdata->courseid = $ccache[$shortname]->id;
762 if ($ccache[$shortname]->groups[$addgroup]->id = groups_create_group($newgroupdata)){
763 $ccache[$shortname]->groups[$addgroup]->name = $newgroupdata->name;
764 } else {
765 $upt->track('enrolments', get_string('unknowngroup', 'error', $addgroup), 'error');
766 continue;
767 }
e4e38544 768 }
769 $gid = $ccache[$shortname]->groups[$addgroup]->id;
770 $gname = $ccache[$shortname]->groups[$addgroup]->name;
771
9c000a99 772 try {
773 if (groups_add_member($gid, $user->id)) {
774 $upt->track('enrolments', get_string('addedtogroup', '', $gname));
df997f84
PS
775 } else {
776 $upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
9c000a99 777 }
778 } catch (moodle_exception $e) {
e4e38544 779 $upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
780 continue;
781 }
a5702569 782 }
066bfbfe 783 }
784 }
e4e38544 785 $upt->flush();
786 $upt->close(); // close table
787
788 $cir->close();
789 $cir->cleanup(true);
790
20486a5a 791 echo $OUTPUT->box_start('boxwidthnarrow boxaligncenter generalbox', 'uploadresults');
e4e38544 792 echo '<p>';
793 if ($optype != UU_UPDATE) {
794 echo get_string('userscreated', 'admin').': '.$usersnew.'<br />';
795 }
796 if ($optype == UU_UPDATE or $optype == UU_ADD_UPDATE) {
797 echo get_string('usersupdated', 'admin').': '.$usersupdated.'<br />';
798 }
799 if ($allowdeletes) {
800 echo get_string('usersdeleted', 'admin').': '.$deletes.'<br />';
801 echo get_string('deleteerrors', 'admin').': '.$deleteerrors.'<br />';
802 }
803 if ($allowrenames) {
804 echo get_string('usersrenamed', 'admin').': '.$renames.'<br />';
805 echo get_string('renameerrors', 'admin').': '.$renameerrors.'<br />';
806 }
807 if ($usersskipped) {
808 echo get_string('usersskipped', 'admin').': '.$usersskipped.'<br />';
809 }
d6bb2d2f 810 echo get_string('usersweakpassword', 'admin').': '.$weakpasswords.'<br />';
e4e38544 811 echo get_string('errors', 'admin').': '.$userserrors.'</p>';
20486a5a 812 echo $OUTPUT->box_end();
e4e38544 813
814 if ($bulk) {
8fbce1c8 815 echo $OUTPUT->continue_button($bulknurl);
e4e38544 816 } else {
8fbce1c8 817 echo $OUTPUT->continue_button($returnurl);
e4e38544 818 }
73d6f52f 819 echo $OUTPUT->footer();
df7ecfe4 820 die;
6b09974b 821}
0a6150ca 822
df7ecfe4 823// Print the header
61ef8f9f 824echo $OUTPUT->header();
df7ecfe4 825
a5702569 826/// Print the form
9e492db0 827
6c7a5df7 828echo $OUTPUT->heading(get_string('uploaduserspreview', 'admin'));
df7ecfe4 829
e4e38544 830$cir->init();
3f12c146
RW
831$availableauths = get_plugin_list('auth');
832$availableauths = array_keys($availableauths);
3fe2cfb5 833$contents = array();
e4e38544 834while ($fields = $cir->next()) {
3fe2cfb5
RW
835 $errormsg = array();
836 $rowcols = array();
837 foreach($fields as $key =>$field) {
838 $rowcols[$columns[$key]] = $field;
839 }
840
841 $usernameexist = $DB->record_exists('user', array('username'=>$rowcols['username']));
842 $emailexist = $DB->record_exists('user', array('email'=>$rowcols['email']));
843 $cleanusername = clean_param($rowcols['username'], PARAM_USERNAME);
844 $validusername = strcmp($rowcols['username'], $cleanusername);
845 $validemail = validate_email($rowcols['email']);
846
847 if ($validusername != 0 || !$validemail) {
848 if ($validusername != 0) {
849 $errormsg['username'] = get_string('invalidusernameupload');
850 }
851 if (!$validemail) {
852 $errormsg['email'] = get_string('invalidemail');
e4e38544 853 }
df7ecfe4 854 }
07ed083e 855
3f12c146
RW
856 //check password column
857 if (array_key_exists('auth', $rowcols)) {
858 if (isset($rowcols['auth']) && empty($rowcols['auth'])) {
859 $rowcols['auth'] = 'manual';
860 }
861 $rowauth = get_auth_plugin($rowcols['auth']);
862 $rowisinternalauth = $rowauth->is_internal();
863 if (!$rowisinternalauth) {
864 if (array_key_exists('password', $rowcols) && !empty($rowcols['password'])) {
865 $errormsg['password'] = get_string('externalauthpassworderror', 'error');
866 }
867 }
868
869 if (!in_array($rowcols['auth'], $availableauths)) {
870 $errormsg['auth'] = get_string('userautherror', 'error');
871 }
872 }
873
874 if (empty($optype) ) {
875 $optype = $uploadtype;
876 }
877
3fe2cfb5
RW
878 switch($optype) {
879 case UU_ADDNEW:
880 if ($usernameexist || $emailexist ) {
881 $rowcols['action'] = 'skipped';
882 } else {
883 $rowcols['action'] = 'create';
07ed083e 884 }
3fe2cfb5
RW
885 break;
886
887 case UU_ADDINC:
888 if (!$usernameexist && !$emailexist) {
889 $rowcols['action'] = 'create';
890 } else if ($usernameexist && !$emailexist) {
891 $rowcols['action'] = 'addcountertousername';
892 $rowcols['username'] = increment_username($rowcols['username'], $CFG->mnet_localhost_id);
893 } else {
894 $rowcols['action'] = 'skipped';
895 }
896 break;
897
898 case UU_ADD_UPDATE:
899 $oldusernameexist = '';
900 if (isset($rowcols['oldusername'])) {
901 $oldusernameexist = $DB->record_exists('user', array('username'=>$rowcols['oldusername']));
902 }
903 if ($usernameexist || $emailexist || $oldusernameexist ) {
904 $rowcols['action'] = 'update';
905 } else {
906 $rowcols['action'] = 'create';
907 }
908 break;
909
910 case UU_UPDATE:
911 $oldusernameexist = '';
912 if (isset($rowcols['oldusername'])) {
913 $oldusernameexist = $DB->record_exists('user', array('username'=>$rowcols['oldusername']));
914 }
915
916 if ($usernameexist || $emailexist || !empty($oldusernameexist)) {
917 $rowcols['action'] = 'update';
918 } else {
919 $rowcols['action'] = "skipped";
920 }
921 break;
df7ecfe4 922 }
df7ecfe4 923
3fe2cfb5
RW
924 if (!empty($errormsg)){
925 $rowcols['error'] = array();
926 $rowcols['error'] = $errormsg;
927 }
928 if ($rowcols['action'] != 'skipped') {
929 $contents[] = $rowcols;
07ed083e
RW
930 }
931}
3fe2cfb5 932$cir->close();
07ed083e 933
3fe2cfb5
RW
934//get heading
935$headings = array();
936foreach ($contents as $content) {
937 foreach($content as $key => $value) {
938 if (!in_array($key, $headings)) {
939 $headings[] = $key;
940 }
941 }
07ed083e 942}
3fe2cfb5
RW
943
944$table = new html_table();
945$table->id = "uupreview";
16be8974 946$table->attributes['class'] = 'generaltable';
3fe2cfb5
RW
947$table->tablealign = 'center';
948$table->summary = get_string('uploaduserspreview', 'admin');
949$table->head = array();
950$table->data = array();
951
952//print heading
953foreach ($headings as $heading) {
954 $table->head[] = s($heading);
07ed083e 955}
07ed083e 956
3fe2cfb5 957$haserror = false;
07ed083e 958$countcontent = 0;
3fe2cfb5
RW
959if (in_array('error', $headings)) {
960 //print error
961 $haserror = true;
962
963 foreach ($contents as $content) {
964 if (array_key_exists('error', $content)) {
965 $rows = new html_table_row();
966 foreach ($content as $key => $value) {
967 $cells = new html_table_cell();
968 $errclass = '';
969 if (array_key_exists($key, $content['error'])) {
970 $errclass = 'uuerror';
971 }
972 if ($key == 'error') {
973 $value = join('<br />', $content['error']);
974 }
975 if ($key == 'action') {
976 $value = get_string($content[$key]);
977 }
978 $cells->text = $value;
16be8974 979 $cells->attributes['class'] = $errclass;
3fe2cfb5
RW
980 $rows->cells[] = $cells;
981 }
982 $countcontent++;
983 $table->data[] = $rows;
984 }
985 }
986 $mform = new admin_uploaduser_form3();
987 $mform->set_data(array('uutype'=>$uploadtype));
988} else if (empty($contents)) {
989 $mform = new admin_uploaduser_form3();
990 $mform->set_data(array('uutype'=>$uploadtype));
07ed083e 991} else {
3fe2cfb5
RW
992 //print content
993 foreach ($contents as $content) {
994 $rows = new html_table_row();
995 if ($countcontent >= $previewrows) {
996 foreach ($content as $con) {
997 $cells = new html_table_cell();
998 $cells->text = '...';
999 }
1000 $rows->cells[] = $cells;
1001 $table->data[] = $rows;
1002 break;
1003 }
1004 foreach ($headings as $heading) {
1005 $cells = new html_table_cell();
1006 if(array_key_exists($heading, $content)) {
1007 if ($heading == 'action') {
1008 $content[$heading] = get_string($content[$heading]);
1009 }
1010 $cells->text = $content[$heading];
1011 } else {
1012 $cells->text = '';
1013 }
1014 $rows->cells[] = $cells;
1015 }
1016 $table->data[] = $rows;
1017 $countcontent++;
1018 }
07ed083e 1019}
3f12c146 1020echo html_writer::tag('div', html_writer::table($table), array('class'=>'flexible-wrap'));
3fe2cfb5
RW
1021
1022if ($haserror) {
3fe2cfb5
RW
1023 echo $OUTPUT->container(get_string('useruploadtype', 'moodle', $choices[$uploadtype]), 'centerpara');
1024 echo $OUTPUT->container(get_string('uploadinvalidpreprocessedcount', 'moodle', $countcontent), 'centerpara');
1025 echo $OUTPUT->container(get_string('invalidusername', 'moodle'), 'centerpara');
1026 echo $OUTPUT->container(get_string('uploadfilecontainerror', 'moodle'), 'centerpara');
1027} else if (empty($contents)) {
1028 echo $OUTPUT->container(get_string('uupreprocessedcount', 'admin', $countcontent), 'centerpara');
1029 echo $OUTPUT->container(get_string('uploadfilecontentsnovaliddata'), 'centerpara');
07ed083e 1030} else {
3fe2cfb5 1031 echo $OUTPUT->container(get_string('uupreprocessedcount', 'admin', $countcontent), 'centerpara');
07ed083e
RW
1032}
1033
0a5dffcc 1034$mform->display();
73d6f52f 1035echo $OUTPUT->footer();
df7ecfe4 1036die;
1037
e4e38544 1038/////////////////////////////////////
1039/// Utility functions and classes ///
1040/////////////////////////////////////
1041
1042class uu_progress_tracker {
1043 var $_row;
1044 var $columns = array('status', 'line', 'id', 'username', 'firstname', 'lastname', 'email', 'password', 'auth', 'enrolments', 'deleted');
1045
1046 function uu_progress_tracker() {
1047 }
1048
1049 function init() {
1050 $ci = 0;
3f12c146 1051 echo '<table id="uuresults" class="generaltable boxaligncenter flexible-wrap" summary="'.get_string('uploadusersresult', 'admin').'">';
e4e38544 1052 echo '<tr class="heading r0">';
1053 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('status').'</th>';
1054 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('uucsvline', 'admin').'</th>';
1055 echo '<th class="header c'.$ci++.'" scope="col">ID</th>';
1056 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('username').'</th>';
1057 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('firstname').'</th>';
1058 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('lastname').'</th>';
1059 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('email').'</th>';
1060 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('password').'</th>';
1061 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('authentication').'</th>';
df997f84 1062 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('enrolments', 'enrol').'</th>';
e4e38544 1063 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('delete').'</th>';
1064 echo '</tr>';
1065 $this->_row = null;
1066 }
1067
1068 function flush() {
1069 if (empty($this->_row) or empty($this->_row['line']['normal'])) {
1070 $this->_row = array();
1071 foreach ($this->columns as $col) {
1072 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
1073 }
1074 return;
1075 }
1076 $ci = 0;
1077 $ri = 1;
07ed083e
RW
1078 echo '<tr class="r'.$ri.'">';
1079 foreach ($this->_row as $key=>$field) {
e4e38544 1080 foreach ($field as $type=>$content) {
1081 if ($field[$type] !== '') {
07ed083e
RW
1082 if ($key == 'username' && $type == 'normal') {
1083 $field[$type] = clean_param($field[$type], PARAM_USERNAME);
1084 }
e4e38544 1085 $field[$type] = '<span class="uu'.$type.'">'.$field[$type].'</span>';
1086 } else {
1087 unset($field[$type]);
1088 }
1089 }
1090 echo '<td class="cell c'.$ci++.'">';
1091 if (!empty($field)) {
1092 echo implode('<br />', $field);
1093 } else {
1094 echo '&nbsp;';
1095 }
1096 echo '</td>';
1097 }
1098 echo '</tr>';
1099 foreach ($this->columns as $col) {
1100 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
1101 }
1102 }
1103
1104 function track($col, $msg, $level='normal', $merge=true) {
1105 if (empty($this->_row)) {
1106 $this->flush(); //init arrays
1107 }
1108 if (!in_array($col, $this->columns)) {
1109 debugging('Incorrect column:'.$col);
1110 return;
1111 }
1112 if ($merge) {
1113 if ($this->_row[$col][$level] != '') {
1114 $this->_row[$col][$level] .='<br />';
1115 }
1116 $this->_row[$col][$level] .= s($msg);
1117 } else {
1118 $this->_row[$col][$level] = s($msg);
1119 }
1120 }
1121
1122 function close() {
1123 echo '</table>';
1124 }
1125}
df7ecfe4 1126
e4e38544 1127/**
1128 * Validation callback function - verified the column line of csv file.
1129 * Converts column names to lowercase too.
1130 */
1131function validate_user_upload_columns(&$columns) {
1132 global $STD_FIELDS, $PRF_FIELDS;
1133
1134 if (count($columns) < 2) {
1135 return get_string('csvfewcolumns', 'error');
df7ecfe4 1136 }
e4e38544 1137
1138 // test columns
1139 $processed = array();
1140 foreach ($columns as $key=>$unused) {
1141 $columns[$key] = strtolower($columns[$key]); // no unicode expected here, ignore case
1142 $field = $columns[$key];
1143 if (!in_array($field, $STD_FIELDS) && !in_array($field, $PRF_FIELDS) &&// if not a standard field and not an enrolment field, then we have an error
1144 !preg_match('/^course\d+$/', $field) && !preg_match('/^group\d+$/', $field) &&
2686b6c3 1145 !preg_match('/^type\d+$/', $field) && !preg_match('/^role\d+$/', $field) &&
1146 !preg_match('/^enrolperiod\d+$/', $field)) {
e4e38544 1147 return get_string('invalidfieldname', 'error', $field);
1148 }
1149 if (in_array($field, $processed)) {
1150 return get_string('csvcolumnduplicates', 'error');
1151 }
1152 $processed[] = $field;
df7ecfe4 1153 }
e4e38544 1154 return true;
df7ecfe4 1155}
1156
e4e38544 1157/**
1158 * Increments username - increments trailing number or adds it if not present.
1159 * Varifies that the new username does not exist yet
1160 * @param string $username
1161 * @return incremented username which does not exist yet
1162 */
1163function increment_username($username, $mnethostid) {
1d8bf5f0 1164 global $DB;
1165
e4e38544 1166 if (!preg_match_all('/(.*?)([0-9]+)$/', $username, $matches)) {
1167 $username = $username.'2';
1168 } else {
1169 $username = $matches[1][0].($matches[2][0]+1);
1170 }
1171
1d8bf5f0 1172 if ($DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$mnethostid))) {
e4e38544 1173 return increment_username($username, $mnethostid);
1174 } else {
1175 return $username;
1176 }
1177}
df7ecfe4 1178
e4e38544 1179/**
1180 * Check if default field contains templates and apply them.
1181 * @param string template - potential tempalte string
1182 * @param object user object- we need username, firstname and lastname
1183 * @return string field value
1184 */
1185function process_template($template, $user) {
1186 if (strpos($template, '%') === false) {
1187 return $template;
df7ecfe4 1188 }
e4e38544 1189
1190 // very very ugly hack!
1191 global $template_globals;
a226a972 1192 $template_globals = new stdClass();
e4e38544 1193 $template_globals->username = isset($user->username) ? $user->username : '';
1194 $template_globals->firstname = isset($user->firstname) ? $user->firstname : '';
1195 $template_globals->lastname = isset($user->lastname) ? $user->lastname : '';
1196
1197 $result = preg_replace_callback('/(?<!%)%([+-~])?(\d)*([flu])/', 'process_template_callback', $template);
1198
1199 $template_globals = null;
1200
1201 if (is_null($result)) {
1202 return $template; //error during regex processing??
1203 } else {
1204 return $result;
df7ecfe4 1205 }
e4e38544 1206}
df7ecfe4 1207
e4e38544 1208/**
1209 * Internal callback function.
1210 */
1211function process_template_callback($block) {
1212 global $template_globals;
1213 $textlib = textlib_get_instance();
1214 $repl = $block[0];
1215
1216 switch ($block[3]) {
1217 case 'u': $repl = $template_globals->username; break;
1218 case 'f': $repl = $template_globals->firstname; break;
1219 case 'l': $repl = $template_globals->lastname; break;
1220 }
1221 switch ($block[1]) {
1222 case '+': $repl = $textlib->strtoupper($repl); break;
1223 case '-': $repl = $textlib->strtolower($repl); break;
1224 case '~': $repl = $textlib->strtotitle($repl); break;
1225 }
1226 if (!empty($block[2])) {
1227 $repl = $textlib->substr($repl, 0 , $block[2]);
df7ecfe4 1228 }
e4e38544 1229
1230 return $repl;
df7ecfe4 1231}
1232
e4e38544 1233/**
1234 * Returns list of auth plugins that are enabled and known to work.
1235 */
1236function uu_allowed_auths() {
df7ecfe4 1237 global $CFG;
1238
e4e38544 1239 // only following plugins are guaranteed to work properly
df997f84 1240 // TODO: add support for more plugins in 2.0
e4e38544 1241 $whitelist = array('manual', 'nologin', 'none', 'email');
1242 $plugins = get_enabled_auth_plugins();
1243 $choices = array();
1244 foreach ($plugins as $plugin) {
370f10b7 1245 $choices[$plugin] = get_string('pluginname', "auth_{$plugin}");
df7ecfe4 1246 }
e4e38544 1247
1248 return $choices;
df7ecfe4 1249}
1250
e4e38544 1251/**
df997f84 1252 * Returns list of roles that are assignable in courses
e4e38544 1253 */
df997f84
PS
1254function uu_allowed_roles() {
1255 // let's cheat a bit, frontpage is guaranteed to exist and has the same list of roles ;-)
1256 $roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_ORIGINALANDSHORT);
1257 return array_reverse($roles, true);
1258}
e4e38544 1259
df997f84
PS
1260function uu_allowed_roles_cache() {
1261 $allowedroles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_SHORT);
1262 foreach ($allowedroles as $rid=>$rname) {
a226a972 1263 $rolecache[$rid] = new stdClass();
df997f84
PS
1264 $rolecache[$rid]->id = $rid;
1265 $rolecache[$rid]->name = $rname;
1266 if (!is_numeric($rname)) { // only non-numeric shortnames are supported!!!
a226a972 1267 $rolecache[$rname] = new stdClass();
df997f84
PS
1268 $rolecache[$rname]->id = $rid;
1269 $rolecache[$rname]->name = $rname;
e4e38544 1270 }
1271 }
df997f84 1272 return $rolecache;
df7ecfe4 1273}