weekly version bump
[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
PS
670 if (!isset($manualcache[$courseid])) {
671 if ($instances = enrol_get_instances($courseid, false)) {
672 $manualcache[$courseid] = reset($instances);
a7db355a 673 } else {
df997f84 674 $manualcache[$courseid] = false;
e4e38544 675 }
df997f84 676 }
e4e38544 677
df997f84
PS
678 if ($manual and $manualcache[$courseid]) {
679
680 // find role
681 $rid = false;
682 if (!empty($user->{'role'.$i})) {
683 $addrole = $user->{'role'.$i};
684 if (array_key_exists($addrole, $rolecache)) {
685 $rid = $rolecache[$addrole]->id;
e4e38544 686 } else {
df997f84
PS
687 $upt->track('enrolments', get_string('unknownrole', 'error', $addrole), 'error');
688 continue;
a7db355a 689 }
e4e38544 690
df997f84
PS
691 } else if (!empty($user->{'type'.$i})) {
692 // if no role, then find "old" enrolment type
693 $addtype = $user->{'type'.$i};
694 if ($addtype < 1 or $addtype > 3) {
695 $upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
696 continue;
697 } else if (empty($formdata->{'uulegacy'.$addtype})) {
698 continue;
699 } else {
700 $rid = $formdata->{'uulegacy'.$addtype};
701 }
e4e38544 702 } else {
df997f84
PS
703 // no role specified, use the default from manual enrol plugin
704 $rid = $manualcache[$courseid]->roleid;
a7db355a 705 }
2686b6c3 706
df997f84
PS
707 if ($rid) {
708 // find duration
df997f84
PS
709 $timeend = 0;
710 if (!empty($user->{'enrolperiod'.$i})) {
711 $duration = (int)$user->{'enrolperiod'.$i} * 86400; // convert days to seconds
712 if ($duration > 0) { // sanity check
2a6dcb72 713 $timeend = $today + $duration;
df997f84
PS
714 }
715 }
2686b6c3 716
2a6dcb72 717 $manual->enrol_user($manualcache[$courseid], $user->id, $rid, $today, $timeend, true);
df997f84 718
a226a972 719 $a = new stdClass();
df997f84
PS
720 $a->course = $shortname;
721 $a->role = $rolecache[$rid]->name;
722 $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
066bfbfe 723 }
e4e38544 724 }
6b09974b 725
e4e38544 726 // find group to add to
727 if (!empty($user->{'group'.$i})) {
728 // make sure user is enrolled into course before adding into groups
4f0c2d00 729 if (!is_enrolled($coursecontext, $user->id)) {
d85f2634 730 $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group'.$i}), 'error');
e4e38544 731 continue;
732 }
733 //build group cache
734 if (is_null($ccache[$shortname]->groups)) {
735 $ccache[$shortname]->groups = array();
35987665 736 if ($groups = groups_get_all_groups($courseid)) {
e4e38544 737 foreach ($groups as $gid=>$group) {
a226a972 738 $ccache[$shortname]->groups[$gid] = new stdClass();
e4e38544 739 $ccache[$shortname]->groups[$gid]->id = $gid;
740 $ccache[$shortname]->groups[$gid]->name = $group->name;
741 if (!is_numeric($group->name)) { // only non-numeric names are supported!!!
a226a972 742 $ccache[$shortname]->groups[$group->name] = new stdClass();
e4e38544 743 $ccache[$shortname]->groups[$group->name]->id = $gid;
744 $ccache[$shortname]->groups[$group->name]->name = $group->name;
a7db355a 745 }
a5702569 746 }
0063abee 747 }
6b09974b 748 }
e4e38544 749 // group exists?
750 $addgroup = $user->{'group'.$i};
751 if (!array_key_exists($addgroup, $ccache[$shortname]->groups)) {
b225cf36 752 // if group doesn't exist, create it
a226a972 753 $newgroupdata = new stdClass();
b225cf36 754 $newgroupdata->name = $addgroup;
755 $newgroupdata->courseid = $ccache[$shortname]->id;
756 if ($ccache[$shortname]->groups[$addgroup]->id = groups_create_group($newgroupdata)){
757 $ccache[$shortname]->groups[$addgroup]->name = $newgroupdata->name;
758 } else {
759 $upt->track('enrolments', get_string('unknowngroup', 'error', $addgroup), 'error');
760 continue;
761 }
e4e38544 762 }
763 $gid = $ccache[$shortname]->groups[$addgroup]->id;
764 $gname = $ccache[$shortname]->groups[$addgroup]->name;
765
9c000a99 766 try {
767 if (groups_add_member($gid, $user->id)) {
768 $upt->track('enrolments', get_string('addedtogroup', '', $gname));
df997f84
PS
769 } else {
770 $upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
9c000a99 771 }
772 } catch (moodle_exception $e) {
e4e38544 773 $upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
774 continue;
775 }
a5702569 776 }
066bfbfe 777 }
778 }
e4e38544 779 $upt->flush();
780 $upt->close(); // close table
781
782 $cir->close();
783 $cir->cleanup(true);
784
20486a5a 785 echo $OUTPUT->box_start('boxwidthnarrow boxaligncenter generalbox', 'uploadresults');
e4e38544 786 echo '<p>';
787 if ($optype != UU_UPDATE) {
788 echo get_string('userscreated', 'admin').': '.$usersnew.'<br />';
789 }
790 if ($optype == UU_UPDATE or $optype == UU_ADD_UPDATE) {
791 echo get_string('usersupdated', 'admin').': '.$usersupdated.'<br />';
792 }
793 if ($allowdeletes) {
794 echo get_string('usersdeleted', 'admin').': '.$deletes.'<br />';
795 echo get_string('deleteerrors', 'admin').': '.$deleteerrors.'<br />';
796 }
797 if ($allowrenames) {
798 echo get_string('usersrenamed', 'admin').': '.$renames.'<br />';
799 echo get_string('renameerrors', 'admin').': '.$renameerrors.'<br />';
800 }
801 if ($usersskipped) {
802 echo get_string('usersskipped', 'admin').': '.$usersskipped.'<br />';
803 }
d6bb2d2f 804 echo get_string('usersweakpassword', 'admin').': '.$weakpasswords.'<br />';
e4e38544 805 echo get_string('errors', 'admin').': '.$userserrors.'</p>';
20486a5a 806 echo $OUTPUT->box_end();
e4e38544 807
808 if ($bulk) {
8fbce1c8 809 echo $OUTPUT->continue_button($bulknurl);
e4e38544 810 } else {
8fbce1c8 811 echo $OUTPUT->continue_button($returnurl);
e4e38544 812 }
73d6f52f 813 echo $OUTPUT->footer();
df7ecfe4 814 die;
6b09974b 815}
0a6150ca 816
df7ecfe4 817// Print the header
61ef8f9f 818echo $OUTPUT->header();
df7ecfe4 819
a5702569 820/// Print the form
9e492db0 821
6c7a5df7 822echo $OUTPUT->heading(get_string('uploaduserspreview', 'admin'));
df7ecfe4 823
e4e38544 824$cir->init();
3f12c146
RW
825$availableauths = get_plugin_list('auth');
826$availableauths = array_keys($availableauths);
3fe2cfb5 827$contents = array();
e4e38544 828while ($fields = $cir->next()) {
3fe2cfb5
RW
829 $errormsg = array();
830 $rowcols = array();
831 foreach($fields as $key =>$field) {
832 $rowcols[$columns[$key]] = $field;
833 }
834
835 $usernameexist = $DB->record_exists('user', array('username'=>$rowcols['username']));
836 $emailexist = $DB->record_exists('user', array('email'=>$rowcols['email']));
837 $cleanusername = clean_param($rowcols['username'], PARAM_USERNAME);
838 $validusername = strcmp($rowcols['username'], $cleanusername);
839 $validemail = validate_email($rowcols['email']);
840
841 if ($validusername != 0 || !$validemail) {
842 if ($validusername != 0) {
843 $errormsg['username'] = get_string('invalidusernameupload');
844 }
845 if (!$validemail) {
846 $errormsg['email'] = get_string('invalidemail');
e4e38544 847 }
df7ecfe4 848 }
07ed083e 849
3f12c146
RW
850 //check password column
851 if (array_key_exists('auth', $rowcols)) {
852 if (isset($rowcols['auth']) && empty($rowcols['auth'])) {
853 $rowcols['auth'] = 'manual';
854 }
855 $rowauth = get_auth_plugin($rowcols['auth']);
856 $rowisinternalauth = $rowauth->is_internal();
857 if (!$rowisinternalauth) {
858 if (array_key_exists('password', $rowcols) && !empty($rowcols['password'])) {
859 $errormsg['password'] = get_string('externalauthpassworderror', 'error');
860 }
861 }
862
863 if (!in_array($rowcols['auth'], $availableauths)) {
864 $errormsg['auth'] = get_string('userautherror', 'error');
865 }
866 }
867
868 if (empty($optype) ) {
869 $optype = $uploadtype;
870 }
871
3fe2cfb5
RW
872 switch($optype) {
873 case UU_ADDNEW:
874 if ($usernameexist || $emailexist ) {
875 $rowcols['action'] = 'skipped';
876 } else {
877 $rowcols['action'] = 'create';
07ed083e 878 }
3fe2cfb5
RW
879 break;
880
881 case UU_ADDINC:
882 if (!$usernameexist && !$emailexist) {
883 $rowcols['action'] = 'create';
884 } else if ($usernameexist && !$emailexist) {
885 $rowcols['action'] = 'addcountertousername';
886 $rowcols['username'] = increment_username($rowcols['username'], $CFG->mnet_localhost_id);
887 } else {
888 $rowcols['action'] = 'skipped';
889 }
890 break;
891
892 case UU_ADD_UPDATE:
893 $oldusernameexist = '';
894 if (isset($rowcols['oldusername'])) {
895 $oldusernameexist = $DB->record_exists('user', array('username'=>$rowcols['oldusername']));
896 }
897 if ($usernameexist || $emailexist || $oldusernameexist ) {
898 $rowcols['action'] = 'update';
899 } else {
900 $rowcols['action'] = 'create';
901 }
902 break;
903
904 case UU_UPDATE:
905 $oldusernameexist = '';
906 if (isset($rowcols['oldusername'])) {
907 $oldusernameexist = $DB->record_exists('user', array('username'=>$rowcols['oldusername']));
908 }
909
910 if ($usernameexist || $emailexist || !empty($oldusernameexist)) {
911 $rowcols['action'] = 'update';
912 } else {
913 $rowcols['action'] = "skipped";
914 }
915 break;
df7ecfe4 916 }
df7ecfe4 917
3fe2cfb5
RW
918 if (!empty($errormsg)){
919 $rowcols['error'] = array();
920 $rowcols['error'] = $errormsg;
921 }
922 if ($rowcols['action'] != 'skipped') {
923 $contents[] = $rowcols;
07ed083e
RW
924 }
925}
3fe2cfb5 926$cir->close();
07ed083e 927
3fe2cfb5
RW
928//get heading
929$headings = array();
930foreach ($contents as $content) {
931 foreach($content as $key => $value) {
932 if (!in_array($key, $headings)) {
933 $headings[] = $key;
934 }
935 }
07ed083e 936}
3fe2cfb5
RW
937
938$table = new html_table();
939$table->id = "uupreview";
16be8974 940$table->attributes['class'] = 'generaltable';
3fe2cfb5
RW
941$table->tablealign = 'center';
942$table->summary = get_string('uploaduserspreview', 'admin');
943$table->head = array();
944$table->data = array();
945
946//print heading
947foreach ($headings as $heading) {
948 $table->head[] = s($heading);
07ed083e 949}
07ed083e 950
3fe2cfb5 951$haserror = false;
07ed083e 952$countcontent = 0;
3fe2cfb5
RW
953if (in_array('error', $headings)) {
954 //print error
955 $haserror = true;
956
957 foreach ($contents as $content) {
958 if (array_key_exists('error', $content)) {
959 $rows = new html_table_row();
960 foreach ($content as $key => $value) {
961 $cells = new html_table_cell();
962 $errclass = '';
963 if (array_key_exists($key, $content['error'])) {
964 $errclass = 'uuerror';
965 }
966 if ($key == 'error') {
967 $value = join('<br />', $content['error']);
968 }
969 if ($key == 'action') {
970 $value = get_string($content[$key]);
971 }
972 $cells->text = $value;
16be8974 973 $cells->attributes['class'] = $errclass;
3fe2cfb5
RW
974 $rows->cells[] = $cells;
975 }
976 $countcontent++;
977 $table->data[] = $rows;
978 }
979 }
980 $mform = new admin_uploaduser_form3();
981 $mform->set_data(array('uutype'=>$uploadtype));
982} else if (empty($contents)) {
983 $mform = new admin_uploaduser_form3();
984 $mform->set_data(array('uutype'=>$uploadtype));
07ed083e 985} else {
3fe2cfb5
RW
986 //print content
987 foreach ($contents as $content) {
988 $rows = new html_table_row();
989 if ($countcontent >= $previewrows) {
990 foreach ($content as $con) {
991 $cells = new html_table_cell();
992 $cells->text = '...';
993 }
994 $rows->cells[] = $cells;
995 $table->data[] = $rows;
996 break;
997 }
998 foreach ($headings as $heading) {
999 $cells = new html_table_cell();
1000 if(array_key_exists($heading, $content)) {
1001 if ($heading == 'action') {
1002 $content[$heading] = get_string($content[$heading]);
1003 }
1004 $cells->text = $content[$heading];
1005 } else {
1006 $cells->text = '';
1007 }
1008 $rows->cells[] = $cells;
1009 }
1010 $table->data[] = $rows;
1011 $countcontent++;
1012 }
07ed083e 1013}
3f12c146 1014echo html_writer::tag('div', html_writer::table($table), array('class'=>'flexible-wrap'));
3fe2cfb5
RW
1015
1016if ($haserror) {
3fe2cfb5
RW
1017 echo $OUTPUT->container(get_string('useruploadtype', 'moodle', $choices[$uploadtype]), 'centerpara');
1018 echo $OUTPUT->container(get_string('uploadinvalidpreprocessedcount', 'moodle', $countcontent), 'centerpara');
1019 echo $OUTPUT->container(get_string('invalidusername', 'moodle'), 'centerpara');
1020 echo $OUTPUT->container(get_string('uploadfilecontainerror', 'moodle'), 'centerpara');
1021} else if (empty($contents)) {
1022 echo $OUTPUT->container(get_string('uupreprocessedcount', 'admin', $countcontent), 'centerpara');
1023 echo $OUTPUT->container(get_string('uploadfilecontentsnovaliddata'), 'centerpara');
07ed083e 1024} else {
3fe2cfb5 1025 echo $OUTPUT->container(get_string('uupreprocessedcount', 'admin', $countcontent), 'centerpara');
07ed083e
RW
1026}
1027
0a5dffcc 1028$mform->display();
73d6f52f 1029echo $OUTPUT->footer();
df7ecfe4 1030die;
1031
e4e38544 1032/////////////////////////////////////
1033/// Utility functions and classes ///
1034/////////////////////////////////////
1035
1036class uu_progress_tracker {
1037 var $_row;
1038 var $columns = array('status', 'line', 'id', 'username', 'firstname', 'lastname', 'email', 'password', 'auth', 'enrolments', 'deleted');
1039
1040 function uu_progress_tracker() {
1041 }
1042
1043 function init() {
1044 $ci = 0;
3f12c146 1045 echo '<table id="uuresults" class="generaltable boxaligncenter flexible-wrap" summary="'.get_string('uploadusersresult', 'admin').'">';
e4e38544 1046 echo '<tr class="heading r0">';
1047 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('status').'</th>';
1048 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('uucsvline', 'admin').'</th>';
1049 echo '<th class="header c'.$ci++.'" scope="col">ID</th>';
1050 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('username').'</th>';
1051 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('firstname').'</th>';
1052 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('lastname').'</th>';
1053 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('email').'</th>';
1054 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('password').'</th>';
1055 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('authentication').'</th>';
df997f84 1056 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('enrolments', 'enrol').'</th>';
e4e38544 1057 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('delete').'</th>';
1058 echo '</tr>';
1059 $this->_row = null;
1060 }
1061
1062 function flush() {
1063 if (empty($this->_row) or empty($this->_row['line']['normal'])) {
1064 $this->_row = array();
1065 foreach ($this->columns as $col) {
1066 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
1067 }
1068 return;
1069 }
1070 $ci = 0;
1071 $ri = 1;
07ed083e
RW
1072 echo '<tr class="r'.$ri.'">';
1073 foreach ($this->_row as $key=>$field) {
e4e38544 1074 foreach ($field as $type=>$content) {
1075 if ($field[$type] !== '') {
07ed083e
RW
1076 if ($key == 'username' && $type == 'normal') {
1077 $field[$type] = clean_param($field[$type], PARAM_USERNAME);
1078 }
e4e38544 1079 $field[$type] = '<span class="uu'.$type.'">'.$field[$type].'</span>';
1080 } else {
1081 unset($field[$type]);
1082 }
1083 }
1084 echo '<td class="cell c'.$ci++.'">';
1085 if (!empty($field)) {
1086 echo implode('<br />', $field);
1087 } else {
1088 echo '&nbsp;';
1089 }
1090 echo '</td>';
1091 }
1092 echo '</tr>';
1093 foreach ($this->columns as $col) {
1094 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
1095 }
1096 }
1097
1098 function track($col, $msg, $level='normal', $merge=true) {
1099 if (empty($this->_row)) {
1100 $this->flush(); //init arrays
1101 }
1102 if (!in_array($col, $this->columns)) {
1103 debugging('Incorrect column:'.$col);
1104 return;
1105 }
1106 if ($merge) {
1107 if ($this->_row[$col][$level] != '') {
1108 $this->_row[$col][$level] .='<br />';
1109 }
1110 $this->_row[$col][$level] .= s($msg);
1111 } else {
1112 $this->_row[$col][$level] = s($msg);
1113 }
1114 }
1115
1116 function close() {
1117 echo '</table>';
1118 }
1119}
df7ecfe4 1120
e4e38544 1121/**
1122 * Validation callback function - verified the column line of csv file.
1123 * Converts column names to lowercase too.
1124 */
1125function validate_user_upload_columns(&$columns) {
1126 global $STD_FIELDS, $PRF_FIELDS;
1127
1128 if (count($columns) < 2) {
1129 return get_string('csvfewcolumns', 'error');
df7ecfe4 1130 }
e4e38544 1131
1132 // test columns
1133 $processed = array();
1134 foreach ($columns as $key=>$unused) {
1135 $columns[$key] = strtolower($columns[$key]); // no unicode expected here, ignore case
1136 $field = $columns[$key];
1137 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
1138 !preg_match('/^course\d+$/', $field) && !preg_match('/^group\d+$/', $field) &&
2686b6c3 1139 !preg_match('/^type\d+$/', $field) && !preg_match('/^role\d+$/', $field) &&
1140 !preg_match('/^enrolperiod\d+$/', $field)) {
e4e38544 1141 return get_string('invalidfieldname', 'error', $field);
1142 }
1143 if (in_array($field, $processed)) {
1144 return get_string('csvcolumnduplicates', 'error');
1145 }
1146 $processed[] = $field;
df7ecfe4 1147 }
e4e38544 1148 return true;
df7ecfe4 1149}
1150
e4e38544 1151/**
1152 * Increments username - increments trailing number or adds it if not present.
1153 * Varifies that the new username does not exist yet
1154 * @param string $username
1155 * @return incremented username which does not exist yet
1156 */
1157function increment_username($username, $mnethostid) {
1d8bf5f0 1158 global $DB;
1159
e4e38544 1160 if (!preg_match_all('/(.*?)([0-9]+)$/', $username, $matches)) {
1161 $username = $username.'2';
1162 } else {
1163 $username = $matches[1][0].($matches[2][0]+1);
1164 }
1165
1d8bf5f0 1166 if ($DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$mnethostid))) {
e4e38544 1167 return increment_username($username, $mnethostid);
1168 } else {
1169 return $username;
1170 }
1171}
df7ecfe4 1172
e4e38544 1173/**
1174 * Check if default field contains templates and apply them.
1175 * @param string template - potential tempalte string
1176 * @param object user object- we need username, firstname and lastname
1177 * @return string field value
1178 */
1179function process_template($template, $user) {
1180 if (strpos($template, '%') === false) {
1181 return $template;
df7ecfe4 1182 }
e4e38544 1183
1184 // very very ugly hack!
1185 global $template_globals;
a226a972 1186 $template_globals = new stdClass();
e4e38544 1187 $template_globals->username = isset($user->username) ? $user->username : '';
1188 $template_globals->firstname = isset($user->firstname) ? $user->firstname : '';
1189 $template_globals->lastname = isset($user->lastname) ? $user->lastname : '';
1190
1191 $result = preg_replace_callback('/(?<!%)%([+-~])?(\d)*([flu])/', 'process_template_callback', $template);
1192
1193 $template_globals = null;
1194
1195 if (is_null($result)) {
1196 return $template; //error during regex processing??
1197 } else {
1198 return $result;
df7ecfe4 1199 }
e4e38544 1200}
df7ecfe4 1201
e4e38544 1202/**
1203 * Internal callback function.
1204 */
1205function process_template_callback($block) {
1206 global $template_globals;
1207 $textlib = textlib_get_instance();
1208 $repl = $block[0];
1209
1210 switch ($block[3]) {
1211 case 'u': $repl = $template_globals->username; break;
1212 case 'f': $repl = $template_globals->firstname; break;
1213 case 'l': $repl = $template_globals->lastname; break;
1214 }
1215 switch ($block[1]) {
1216 case '+': $repl = $textlib->strtoupper($repl); break;
1217 case '-': $repl = $textlib->strtolower($repl); break;
1218 case '~': $repl = $textlib->strtotitle($repl); break;
1219 }
1220 if (!empty($block[2])) {
1221 $repl = $textlib->substr($repl, 0 , $block[2]);
df7ecfe4 1222 }
e4e38544 1223
1224 return $repl;
df7ecfe4 1225}
1226
e4e38544 1227/**
1228 * Returns list of auth plugins that are enabled and known to work.
1229 */
1230function uu_allowed_auths() {
df7ecfe4 1231 global $CFG;
1232
e4e38544 1233 // only following plugins are guaranteed to work properly
df997f84 1234 // TODO: add support for more plugins in 2.0
e4e38544 1235 $whitelist = array('manual', 'nologin', 'none', 'email');
1236 $plugins = get_enabled_auth_plugins();
1237 $choices = array();
1238 foreach ($plugins as $plugin) {
370f10b7 1239 $choices[$plugin] = get_string('pluginname', "auth_{$plugin}");
df7ecfe4 1240 }
e4e38544 1241
1242 return $choices;
df7ecfe4 1243}
1244
e4e38544 1245/**
df997f84 1246 * Returns list of roles that are assignable in courses
e4e38544 1247 */
df997f84
PS
1248function uu_allowed_roles() {
1249 // let's cheat a bit, frontpage is guaranteed to exist and has the same list of roles ;-)
1250 $roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_ORIGINALANDSHORT);
1251 return array_reverse($roles, true);
1252}
e4e38544 1253
df997f84
PS
1254function uu_allowed_roles_cache() {
1255 $allowedroles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_SHORT);
1256 foreach ($allowedroles as $rid=>$rname) {
a226a972 1257 $rolecache[$rid] = new stdClass();
df997f84
PS
1258 $rolecache[$rid]->id = $rid;
1259 $rolecache[$rid]->name = $rname;
1260 if (!is_numeric($rname)) { // only non-numeric shortnames are supported!!!
a226a972 1261 $rolecache[$rname] = new stdClass();
df997f84
PS
1262 $rolecache[$rname]->id = $rid;
1263 $rolecache[$rname]->name = $rname;
e4e38544 1264 }
1265 }
df997f84 1266 return $rolecache;
df7ecfe4 1267}