weekly release
[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
bb98eea1
PS
298 if (is_array($formdata->$field)) {
299 foreach ($formdata->$field as $k=>$v) {
300 $user->$field[$k] = process_template($v, $user);
301 }
302 } else {
303 $user->$field = process_template($formdata->$field, $user);
304 }
e4e38544 305 }
306 }
307
308 // delete user
309 if (!empty($user->deleted)) {
310 if (!$allowdeletes) {
311 $usersskipped++;
312 $upt->track('status', $strusernotdeletedoff, 'warning');
313 continue;
314 }
315 if ($existinguser) {
4f0c2d00 316 if (is_siteadmin($existinguser->id)) {
e4e38544 317 $upt->track('status', $strusernotdeletedadmin, 'error');
318 $deleteerrors++;
319 continue;
320 }
321 if (delete_user($existinguser)) {
322 $upt->track('status', $struserdeleted);
323 $deletes++;
324 } else {
325 $upt->track('status', $strusernotdeletederror, 'error');
326 $deleteerrors++;
6b09974b 327 }
e4e38544 328 } else {
329 $upt->track('status', $strusernotdeletedmissing, 'error');
330 $deleteerrors++;
331 }
332 continue;
333 }
334 // we do not need the deleted flag anymore
335 unset($user->deleted);
336
337 // renaming requested?
338 if (!empty($user->oldusername) ) {
339 $oldusername = $textlib->strtolower($user->oldusername);
340 if (!$allowrenames) {
341 $usersskipped++;
342 $upt->track('status', $strusernotrenamedoff, 'warning');
343 continue;
344 }
345
346 if ($existinguser) {
347 $upt->track('status', $strusernotrenamedexists, 'error');
348 $renameerrors++;
349 continue;
16a1fed4 350 }
ed22a01b 351
1d8bf5f0 352 if ($olduser = $DB->get_record('user', array('username'=>$oldusername, 'mnethostid'=>$user->mnethostid))) {
e4e38544 353 $upt->track('id', $olduser->id, 'normal', false);
4f0c2d00 354 if (is_siteadmin($olduser->id)) {
e4e38544 355 $upt->track('status', $strusernotrenamedadmin, 'error');
356 $renameerrors++;
a7db355a 357 continue;
0063abee 358 }
df997f84
PS
359 $DB->set_field('user', 'username', $user->username, array('id'=>$olduser->id));
360 $upt->track('username', '', 'normal', false); // clear previous
361 $upt->track('username', $oldusername.'-->'.$user->username, 'info');
362 $upt->track('status', $struserrenamed);
363 $renames++;
e4e38544 364 } else {
365 $upt->track('status', $strusernotrenamedmissing, 'error');
366 $renameerrors++;
367 continue;
368 }
369 $existinguser = $olduser;
370 $existinguser->username = $user->username;
371 }
372
373 // can we process with update or insert?
374 $skip = false;
375 switch ($optype) {
376 case UU_ADDNEW:
377 if ($existinguser) {
378 $usersskipped++;
379 $upt->track('status', $strusernotadded, 'warning');
3fe2cfb5 380 $skip = true;
e4e38544 381 }
382 break;
383
384 case UU_ADDINC:
385 if ($existinguser) {
386 //this should not happen!
387 $upt->track('status', $strusernotaddederror, 'error');
388 $userserrors++;
389 continue;
390 }
391 break;
392
393 case UU_ADD_UPDATE:
394 break;
395
396 case UU_UPDATE:
397 if (!$existinguser) {
398 $usersskipped++;
399 $upt->track('status', $strusernotupdatednotexists, 'warning');
400 $skip = true;
401 }
402 break;
403 }
404
405 if ($skip) {
406 continue;
407 }
408
409 if ($existinguser) {
410 $user->id = $existinguser->id;
411
4f0c2d00 412 if (is_siteadmin($user->id)) {
e4e38544 413 $upt->track('status', $strusernotupdatedadmin, 'error');
414 $userserrors++;
415 continue;
416 }
417
418 if (!$updatetype) {
419 // no updates of existing data at all
420 } else {
421 $existinguser->timemodified = time();
3fe2cfb5
RW
422 if (empty($existinguser->timecreated)) {
423 if (empty($existinguser->firstaccess)) {
424 $existinguser->timecreated = time();
425 } else {
426 $existinguser->timecreated = $existinguser->firstaccess;
427 }
428 }
429
e4e38544 430 //load existing profile data
431 profile_load_data($existinguser);
432
433 $allowed = array();
434 if ($updatetype == 1) {
435 $allowed = $columns;
436 } else if ($updatetype == 2 or $updatetype == 3) {
437 $allowed = array_merge($STD_FIELDS, $PRF_FIELDS);
438 }
439 foreach ($allowed as $column) {
3f12c146 440 $temppasswordhandler = '';
e4e38544 441 if ($column == 'username') {
442 continue;
443 }
4cc977a6 444 if ((property_exists($existinguser, $column) and property_exists($user, $column)) or in_array($column, $PRF_FIELDS)) {
3f12c146 445 if ($updatetype == 3 && $existinguser->$column !== '') {
e4e38544 446 //missing == non-empty only
447 continue;
a7db355a 448 }
e4e38544 449 if ($existinguser->$column !== $user->$column) {
0c4807ab 450 if ($column == 'email') {
1d8bf5f0 451 if ($DB->record_exists('user', array('email'=>$user->email))) {
0c4807ab 452 if ($noemailduplicates) {
453 $upt->track('email', $stremailduplicate, 'error');
454 $upt->track('status', $strusernotupdated, 'error');
455 $userserrors++;
456 continue 2;
457 } else {
458 $upt->track('email', $stremailduplicate, 'warning');
459 }
460 }
461 }
3f12c146
RW
462
463 if ($column == 'password') {
464 $temppasswordhandler = $existinguser->password;
465 }
466
467 if ($column == 'auth') {
468 if (isset($user->auth) && empty($user->auth)) {
469 $user->auth = 'manual';
470 }
471
472 $existinguserauth = get_auth_plugin($existinguser->auth);
473 $existingisinternalauth = $existinguserauth->is_internal();
474
475 $userauth = get_auth_plugin($user->auth);
476 $isinternalauth = $userauth->is_internal();
477
478 if ($isinternalauth === $existingisinternalauth) {
479 if ($updatepasswords) {
480 if (empty($user->password)) {
481 $forcechangepassword = true;
482 }
483 }
484 } else if ($isinternalauth) {
485 $existinguser->password = '';
486 $forcechangepassword = true;
487 }
488 }
489
490 $upt->track($column, '', 'normal', false); // clear previous
491 if ($column != 'password' && in_array($column, $upt->columns)) {
e4e38544 492 $upt->track($column, $existinguser->$column.'-->'.$user->$column, 'info');
493 }
494 $existinguser->$column = $user->$column;
3f12c146
RW
495
496 if (!isset($user->auth) && !$updatepasswords) {
497 $existinguser->password = $temppasswordhandler;
498 }
a7db355a 499 }
6b09974b 500 }
a7db355a 501 }
ed22a01b 502
eab8ed9f 503 // do not update record if new auth plugin does not exist!
e4e38544 504 if (!in_array($existinguser->auth, $availableauths)) {
505 $upt->track('auth', get_string('userautherror', 'error', $existinguser->auth), 'error');
506 $upt->track('status', $strusernotupdated, 'error');
507 $userserrors++;
508 continue;
509 } else if (!in_array($existinguser->auth, $allowedauths)) {
510 $upt->track('auth', $struserauthunsupported, 'warning');
066bfbfe 511 }
a7db355a 512
3f12c146
RW
513 $auth = get_auth_plugin($existinguser->auth);
514 $isinternalauth = $auth->is_internal();
515
516 if ($isinternalauth && $updatepasswords && !check_password_policy($user->password, $errmsg)) {
517 $upt->track('password', get_string('internalauthpassworderror', 'error', $existinguser->password), 'error');
518 $upt->track('status', $strusernotupdated, 'error');
519 $userserrors++;
520 continue;
521 } else {
522 $forcechangepassword = true;
523 }
524
525 if (!$isinternalauth) {
526 $existinguser->password = 'not cached';
527 $upt->track('password', 'not cached');
528 $forcechangepassword = false;
529 } else if ($updatepasswords){
530 $existinguser->password = hash_internal_user_password($existinguser->password);
531 } else {
532 $existinguser->password = $temppasswordhandler;
533 }
534
df997f84 535 $DB->update_record('user', $existinguser);
3f12c146
RW
536
537 //remove user preference
59186c92 538
3f12c146
RW
539 if (get_user_preferences('create_password', false, $existinguser)) {
540 unset_user_preference('create_password', $existinguser);
541 }
542 if (get_user_preferences('auth_forcepasswordchange', false, $existinguser)) {
543 unset_user_preference('auth_forcepasswordchange', $existinguser);
544 }
545
546 if ($isinternalauth && $updatepasswords) {
547 if (empty($existinguser->password)) {
548 set_user_preference('create_password', 1, $existinguser->id);
549 set_user_preference('auth_forcepasswordchange', 1, $existinguser->id);
550 $upt->track('password', get_string('new'));
551 } else if ($forcechangepassword) {
552 set_user_preference('auth_forcepasswordchange', 1, $existinguser->id);
553 }
554 }
df997f84
PS
555 $upt->track('status', $struserupdated);
556 $usersupdated++;
e4e38544 557 // save custom profile fields data from csv file
5d910388 558 profile_save_data($existinguser);
e6f74ba3
PS
559
560 events_trigger('user_updated', $existinguser);
e4e38544 561 }
562
563 if ($bulk == 2 or $bulk == 3) {
cd1edf9e 564 if (!in_array($user->id, $SESSION->bulk_users)) {
565 $SESSION->bulk_users[] = $user->id;
ed22a01b 566 }
066bfbfe 567 }
ed22a01b 568
e4e38544 569 } else {
a7db355a 570 // save the user to the database
571 $user->confirmed = 1;
572 $user->timemodified = time();
3fe2cfb5 573 $user->timecreated = time();
066bfbfe 574
3f12c146
RW
575 if (isset($user->auth) && empty($user->auth)) {
576 $user->auth = 'manual';
577 }
578 $auth = get_auth_plugin($user->auth);
579 $isinternalauth = $auth->is_internal();
580
581 if (!$createpasswords && $isinternalauth) {
582 if (empty($user->password)) {
583 $upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
584 $upt->track('status', $strusernotaddederror, 'error');
585 $userserrors++;
586 continue;
587 } else if ($forcechangepassword) {
588 $upt->track('password', $strinvalidpasswordpolicy);
589 $upt->track('status', $strusernotaddederror, 'error');
590 $userserrors++;
591 continue;
592 }
e4e38544 593 }
594
595 // do not insert record if new auth plguin does not exist!
596 if (isset($user->auth)) {
597 if (!in_array($user->auth, $availableauths)) {
598 $upt->track('auth', get_string('userautherror', 'error', $user->auth), 'error');
599 $upt->track('status', $strusernotaddederror, 'error');
600 $userserrors++;
066bfbfe 601 continue;
e4e38544 602 } else if (!in_array($user->auth, $allowedauths)) {
603 $upt->track('auth', $struserauthunsupported, 'warning');
066bfbfe 604 }
066bfbfe 605 }
a2ce7344 606
1d8bf5f0 607 if ($DB->record_exists('user', array('email'=>$user->email))) {
0c4807ab 608 if ($noemailduplicates) {
609 $upt->track('email', $stremailduplicate, 'error');
610 $upt->track('status', $strusernotaddederror, 'error');
611 $userserrors++;
612 continue;
613 } else {
614 $upt->track('email', $stremailduplicate, 'warning');
615 }
616 }
3f12c146
RW
617 if (!$isinternalauth) {
618 $user->password = 'not cached';
619 $upt->track('password', 'not cached');
620 } else {
621 $user->password = hash_internal_user_password($user->password);
622 }
0c4807ab 623
df997f84
PS
624 $user->id = $DB->insert_record('user', $user);
625 $info = ': ' . $user->username .' (ID = ' . $user->id . ')';
626 $upt->track('status', $struseradded);
627 $upt->track('id', $user->id, 'normal', false);
628 $usersnew++;
3f12c146
RW
629 if ($createpasswords && $isinternalauth) {
630 if (empty($user->password) || $forcechangepassword) {
631 // passwords will be created and sent out on cron
632 set_user_preference('create_password', 1, $user->id);
633 set_user_preference('auth_forcepasswordchange', 1, $user->id);
634 $upt->track('password', get_string('new'));
635 } else {
636 set_user_preference('auth_forcepasswordchange', 1, $user->id);
637 }
df997f84
PS
638 }
639
e4e38544 640 // save custom profile fields data
641 profile_save_data($user);
642
2304f629 643 // make sure user context exists
a5feb176 644 get_context_instance(CONTEXT_USER, $user->id);
2304f629 645
e6f74ba3
PS
646 events_trigger('user_created', $user);
647
e4e38544 648 if ($bulk == 1 or $bulk == 3) {
cd1edf9e 649 if (!in_array($user->id, $SESSION->bulk_users)) {
650 $SESSION->bulk_users[] = $user->id;
066bfbfe 651 }
066bfbfe 652 }
e4e38544 653 }
654
2686b6c3 655 // find course enrolments, groups, roles/types and enrol periods
e4e38544 656 foreach ($columns as $column) {
657 if (!preg_match('/^course\d+$/', $column)) {
658 continue;
659 }
660 $i = substr($column, 6);
6b09974b 661
df997f84
PS
662 if (empty($user->{'course'.$i})) {
663 continue;
664 }
e4e38544 665 $shortname = $user->{'course'.$i};
666 if (!array_key_exists($shortname, $ccache)) {
df997f84 667 if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname')) {
e4e38544 668 $upt->track('enrolments', get_string('unknowncourse', 'error', $shortname), 'error');
a7db355a 669 continue;
066bfbfe 670 }
e4e38544 671 $ccache[$shortname] = $course;
672 $ccache[$shortname]->groups = null;
673 }
674 $courseid = $ccache[$shortname]->id;
675 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
df997f84 676 if (!isset($manualcache[$courseid])) {
4cb02426
PS
677 $manualcache[$courseid] = false;
678 if ($manual) {
679 if ($instances = enrol_get_instances($courseid, false)) {
680 foreach ($instances as $instance) {
681 if ($instance->enrol === 'manual') {
682 $manualcache[$courseid] = $instance;
683 break;
684 }
685 }
686 }
e4e38544 687 }
df997f84 688 }
e4e38544 689
df997f84
PS
690 if ($manual and $manualcache[$courseid]) {
691
692 // find role
693 $rid = false;
694 if (!empty($user->{'role'.$i})) {
695 $addrole = $user->{'role'.$i};
696 if (array_key_exists($addrole, $rolecache)) {
697 $rid = $rolecache[$addrole]->id;
e4e38544 698 } else {
df997f84
PS
699 $upt->track('enrolments', get_string('unknownrole', 'error', $addrole), 'error');
700 continue;
a7db355a 701 }
e4e38544 702
df997f84
PS
703 } else if (!empty($user->{'type'.$i})) {
704 // if no role, then find "old" enrolment type
705 $addtype = $user->{'type'.$i};
706 if ($addtype < 1 or $addtype > 3) {
707 $upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
708 continue;
709 } else if (empty($formdata->{'uulegacy'.$addtype})) {
710 continue;
711 } else {
712 $rid = $formdata->{'uulegacy'.$addtype};
713 }
e4e38544 714 } else {
df997f84
PS
715 // no role specified, use the default from manual enrol plugin
716 $rid = $manualcache[$courseid]->roleid;
a7db355a 717 }
2686b6c3 718
df997f84
PS
719 if ($rid) {
720 // find duration
df997f84
PS
721 $timeend = 0;
722 if (!empty($user->{'enrolperiod'.$i})) {
723 $duration = (int)$user->{'enrolperiod'.$i} * 86400; // convert days to seconds
724 if ($duration > 0) { // sanity check
2a6dcb72 725 $timeend = $today + $duration;
df997f84
PS
726 }
727 }
2686b6c3 728
2a6dcb72 729 $manual->enrol_user($manualcache[$courseid], $user->id, $rid, $today, $timeend, true);
df997f84 730
a226a972 731 $a = new stdClass();
df997f84
PS
732 $a->course = $shortname;
733 $a->role = $rolecache[$rid]->name;
734 $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
066bfbfe 735 }
e4e38544 736 }
6b09974b 737
e4e38544 738 // find group to add to
739 if (!empty($user->{'group'.$i})) {
740 // make sure user is enrolled into course before adding into groups
4f0c2d00 741 if (!is_enrolled($coursecontext, $user->id)) {
d85f2634 742 $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group'.$i}), 'error');
e4e38544 743 continue;
744 }
745 //build group cache
746 if (is_null($ccache[$shortname]->groups)) {
747 $ccache[$shortname]->groups = array();
35987665 748 if ($groups = groups_get_all_groups($courseid)) {
e4e38544 749 foreach ($groups as $gid=>$group) {
a226a972 750 $ccache[$shortname]->groups[$gid] = new stdClass();
e4e38544 751 $ccache[$shortname]->groups[$gid]->id = $gid;
752 $ccache[$shortname]->groups[$gid]->name = $group->name;
753 if (!is_numeric($group->name)) { // only non-numeric names are supported!!!
a226a972 754 $ccache[$shortname]->groups[$group->name] = new stdClass();
e4e38544 755 $ccache[$shortname]->groups[$group->name]->id = $gid;
756 $ccache[$shortname]->groups[$group->name]->name = $group->name;
a7db355a 757 }
a5702569 758 }
0063abee 759 }
6b09974b 760 }
e4e38544 761 // group exists?
762 $addgroup = $user->{'group'.$i};
763 if (!array_key_exists($addgroup, $ccache[$shortname]->groups)) {
b225cf36 764 // if group doesn't exist, create it
a226a972 765 $newgroupdata = new stdClass();
b225cf36 766 $newgroupdata->name = $addgroup;
767 $newgroupdata->courseid = $ccache[$shortname]->id;
768 if ($ccache[$shortname]->groups[$addgroup]->id = groups_create_group($newgroupdata)){
769 $ccache[$shortname]->groups[$addgroup]->name = $newgroupdata->name;
770 } else {
771 $upt->track('enrolments', get_string('unknowngroup', 'error', $addgroup), 'error');
772 continue;
773 }
e4e38544 774 }
775 $gid = $ccache[$shortname]->groups[$addgroup]->id;
776 $gname = $ccache[$shortname]->groups[$addgroup]->name;
777
9c000a99 778 try {
779 if (groups_add_member($gid, $user->id)) {
780 $upt->track('enrolments', get_string('addedtogroup', '', $gname));
df997f84
PS
781 } else {
782 $upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
9c000a99 783 }
784 } catch (moodle_exception $e) {
e4e38544 785 $upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
786 continue;
787 }
a5702569 788 }
066bfbfe 789 }
790 }
e4e38544 791 $upt->flush();
792 $upt->close(); // close table
793
794 $cir->close();
795 $cir->cleanup(true);
796
20486a5a 797 echo $OUTPUT->box_start('boxwidthnarrow boxaligncenter generalbox', 'uploadresults');
e4e38544 798 echo '<p>';
799 if ($optype != UU_UPDATE) {
800 echo get_string('userscreated', 'admin').': '.$usersnew.'<br />';
801 }
802 if ($optype == UU_UPDATE or $optype == UU_ADD_UPDATE) {
803 echo get_string('usersupdated', 'admin').': '.$usersupdated.'<br />';
804 }
805 if ($allowdeletes) {
806 echo get_string('usersdeleted', 'admin').': '.$deletes.'<br />';
807 echo get_string('deleteerrors', 'admin').': '.$deleteerrors.'<br />';
808 }
809 if ($allowrenames) {
810 echo get_string('usersrenamed', 'admin').': '.$renames.'<br />';
811 echo get_string('renameerrors', 'admin').': '.$renameerrors.'<br />';
812 }
813 if ($usersskipped) {
814 echo get_string('usersskipped', 'admin').': '.$usersskipped.'<br />';
815 }
d6bb2d2f 816 echo get_string('usersweakpassword', 'admin').': '.$weakpasswords.'<br />';
e4e38544 817 echo get_string('errors', 'admin').': '.$userserrors.'</p>';
20486a5a 818 echo $OUTPUT->box_end();
e4e38544 819
820 if ($bulk) {
8fbce1c8 821 echo $OUTPUT->continue_button($bulknurl);
e4e38544 822 } else {
8fbce1c8 823 echo $OUTPUT->continue_button($returnurl);
e4e38544 824 }
73d6f52f 825 echo $OUTPUT->footer();
df7ecfe4 826 die;
6b09974b 827}
0a6150ca 828
df7ecfe4 829// Print the header
61ef8f9f 830echo $OUTPUT->header();
df7ecfe4 831
a5702569 832/// Print the form
9e492db0 833
6c7a5df7 834echo $OUTPUT->heading(get_string('uploaduserspreview', 'admin'));
df7ecfe4 835
e4e38544 836$cir->init();
3f12c146
RW
837$availableauths = get_plugin_list('auth');
838$availableauths = array_keys($availableauths);
3fe2cfb5 839$contents = array();
e4e38544 840while ($fields = $cir->next()) {
3fe2cfb5
RW
841 $errormsg = array();
842 $rowcols = array();
843 foreach($fields as $key =>$field) {
844 $rowcols[$columns[$key]] = $field;
845 }
846
847 $usernameexist = $DB->record_exists('user', array('username'=>$rowcols['username']));
848 $emailexist = $DB->record_exists('user', array('email'=>$rowcols['email']));
849 $cleanusername = clean_param($rowcols['username'], PARAM_USERNAME);
850 $validusername = strcmp($rowcols['username'], $cleanusername);
851 $validemail = validate_email($rowcols['email']);
852
853 if ($validusername != 0 || !$validemail) {
854 if ($validusername != 0) {
855 $errormsg['username'] = get_string('invalidusernameupload');
856 }
857 if (!$validemail) {
858 $errormsg['email'] = get_string('invalidemail');
e4e38544 859 }
df7ecfe4 860 }
07ed083e 861
3f12c146
RW
862 //check password column
863 if (array_key_exists('auth', $rowcols)) {
864 if (isset($rowcols['auth']) && empty($rowcols['auth'])) {
865 $rowcols['auth'] = 'manual';
866 }
867 $rowauth = get_auth_plugin($rowcols['auth']);
868 $rowisinternalauth = $rowauth->is_internal();
869 if (!$rowisinternalauth) {
870 if (array_key_exists('password', $rowcols) && !empty($rowcols['password'])) {
871 $errormsg['password'] = get_string('externalauthpassworderror', 'error');
872 }
873 }
874
875 if (!in_array($rowcols['auth'], $availableauths)) {
876 $errormsg['auth'] = get_string('userautherror', 'error');
877 }
878 }
879
880 if (empty($optype) ) {
881 $optype = $uploadtype;
882 }
883
3fe2cfb5
RW
884 switch($optype) {
885 case UU_ADDNEW:
886 if ($usernameexist || $emailexist ) {
887 $rowcols['action'] = 'skipped';
888 } else {
889 $rowcols['action'] = 'create';
07ed083e 890 }
3fe2cfb5
RW
891 break;
892
893 case UU_ADDINC:
894 if (!$usernameexist && !$emailexist) {
895 $rowcols['action'] = 'create';
896 } else if ($usernameexist && !$emailexist) {
897 $rowcols['action'] = 'addcountertousername';
898 $rowcols['username'] = increment_username($rowcols['username'], $CFG->mnet_localhost_id);
899 } else {
900 $rowcols['action'] = 'skipped';
901 }
902 break;
903
904 case UU_ADD_UPDATE:
905 $oldusernameexist = '';
906 if (isset($rowcols['oldusername'])) {
907 $oldusernameexist = $DB->record_exists('user', array('username'=>$rowcols['oldusername']));
908 }
909 if ($usernameexist || $emailexist || $oldusernameexist ) {
910 $rowcols['action'] = 'update';
911 } else {
912 $rowcols['action'] = 'create';
913 }
914 break;
915
916 case UU_UPDATE:
917 $oldusernameexist = '';
918 if (isset($rowcols['oldusername'])) {
919 $oldusernameexist = $DB->record_exists('user', array('username'=>$rowcols['oldusername']));
920 }
921
922 if ($usernameexist || $emailexist || !empty($oldusernameexist)) {
923 $rowcols['action'] = 'update';
924 } else {
925 $rowcols['action'] = "skipped";
926 }
927 break;
df7ecfe4 928 }
df7ecfe4 929
3fe2cfb5
RW
930 if (!empty($errormsg)){
931 $rowcols['error'] = array();
932 $rowcols['error'] = $errormsg;
933 }
934 if ($rowcols['action'] != 'skipped') {
935 $contents[] = $rowcols;
07ed083e
RW
936 }
937}
3fe2cfb5 938$cir->close();
07ed083e 939
3fe2cfb5
RW
940//get heading
941$headings = array();
942foreach ($contents as $content) {
943 foreach($content as $key => $value) {
944 if (!in_array($key, $headings)) {
945 $headings[] = $key;
946 }
947 }
07ed083e 948}
3fe2cfb5
RW
949
950$table = new html_table();
951$table->id = "uupreview";
16be8974 952$table->attributes['class'] = 'generaltable';
3fe2cfb5
RW
953$table->tablealign = 'center';
954$table->summary = get_string('uploaduserspreview', 'admin');
955$table->head = array();
956$table->data = array();
957
958//print heading
959foreach ($headings as $heading) {
960 $table->head[] = s($heading);
07ed083e 961}
07ed083e 962
3fe2cfb5 963$haserror = false;
07ed083e 964$countcontent = 0;
3fe2cfb5
RW
965if (in_array('error', $headings)) {
966 //print error
967 $haserror = true;
968
969 foreach ($contents as $content) {
970 if (array_key_exists('error', $content)) {
971 $rows = new html_table_row();
972 foreach ($content as $key => $value) {
973 $cells = new html_table_cell();
974 $errclass = '';
975 if (array_key_exists($key, $content['error'])) {
976 $errclass = 'uuerror';
977 }
978 if ($key == 'error') {
979 $value = join('<br />', $content['error']);
980 }
981 if ($key == 'action') {
982 $value = get_string($content[$key]);
983 }
984 $cells->text = $value;
16be8974 985 $cells->attributes['class'] = $errclass;
3fe2cfb5
RW
986 $rows->cells[] = $cells;
987 }
988 $countcontent++;
989 $table->data[] = $rows;
990 }
991 }
992 $mform = new admin_uploaduser_form3();
993 $mform->set_data(array('uutype'=>$uploadtype));
994} else if (empty($contents)) {
995 $mform = new admin_uploaduser_form3();
996 $mform->set_data(array('uutype'=>$uploadtype));
07ed083e 997} else {
3fe2cfb5
RW
998 //print content
999 foreach ($contents as $content) {
1000 $rows = new html_table_row();
1001 if ($countcontent >= $previewrows) {
1002 foreach ($content as $con) {
1003 $cells = new html_table_cell();
1004 $cells->text = '...';
1005 }
1006 $rows->cells[] = $cells;
1007 $table->data[] = $rows;
1008 break;
1009 }
1010 foreach ($headings as $heading) {
1011 $cells = new html_table_cell();
1012 if(array_key_exists($heading, $content)) {
1013 if ($heading == 'action') {
1014 $content[$heading] = get_string($content[$heading]);
1015 }
1016 $cells->text = $content[$heading];
1017 } else {
1018 $cells->text = '';
1019 }
1020 $rows->cells[] = $cells;
1021 }
1022 $table->data[] = $rows;
1023 $countcontent++;
1024 }
07ed083e 1025}
3f12c146 1026echo html_writer::tag('div', html_writer::table($table), array('class'=>'flexible-wrap'));
3fe2cfb5
RW
1027
1028if ($haserror) {
3fe2cfb5
RW
1029 echo $OUTPUT->container(get_string('useruploadtype', 'moodle', $choices[$uploadtype]), 'centerpara');
1030 echo $OUTPUT->container(get_string('uploadinvalidpreprocessedcount', 'moodle', $countcontent), 'centerpara');
1031 echo $OUTPUT->container(get_string('invalidusername', 'moodle'), 'centerpara');
1032 echo $OUTPUT->container(get_string('uploadfilecontainerror', 'moodle'), 'centerpara');
1033} else if (empty($contents)) {
1034 echo $OUTPUT->container(get_string('uupreprocessedcount', 'admin', $countcontent), 'centerpara');
1035 echo $OUTPUT->container(get_string('uploadfilecontentsnovaliddata'), 'centerpara');
07ed083e 1036} else {
3fe2cfb5 1037 echo $OUTPUT->container(get_string('uupreprocessedcount', 'admin', $countcontent), 'centerpara');
07ed083e
RW
1038}
1039
0a5dffcc 1040$mform->display();
73d6f52f 1041echo $OUTPUT->footer();
df7ecfe4 1042die;
1043
e4e38544 1044/////////////////////////////////////
1045/// Utility functions and classes ///
1046/////////////////////////////////////
1047
1048class uu_progress_tracker {
1049 var $_row;
1050 var $columns = array('status', 'line', 'id', 'username', 'firstname', 'lastname', 'email', 'password', 'auth', 'enrolments', 'deleted');
1051
1052 function uu_progress_tracker() {
1053 }
1054
1055 function init() {
1056 $ci = 0;
3f12c146 1057 echo '<table id="uuresults" class="generaltable boxaligncenter flexible-wrap" summary="'.get_string('uploadusersresult', 'admin').'">';
e4e38544 1058 echo '<tr class="heading r0">';
1059 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('status').'</th>';
1060 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('uucsvline', 'admin').'</th>';
1061 echo '<th class="header c'.$ci++.'" scope="col">ID</th>';
1062 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('username').'</th>';
1063 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('firstname').'</th>';
1064 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('lastname').'</th>';
1065 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('email').'</th>';
1066 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('password').'</th>';
1067 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('authentication').'</th>';
df997f84 1068 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('enrolments', 'enrol').'</th>';
e4e38544 1069 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('delete').'</th>';
1070 echo '</tr>';
1071 $this->_row = null;
1072 }
1073
1074 function flush() {
1075 if (empty($this->_row) or empty($this->_row['line']['normal'])) {
1076 $this->_row = array();
1077 foreach ($this->columns as $col) {
1078 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
1079 }
1080 return;
1081 }
1082 $ci = 0;
1083 $ri = 1;
07ed083e
RW
1084 echo '<tr class="r'.$ri.'">';
1085 foreach ($this->_row as $key=>$field) {
e4e38544 1086 foreach ($field as $type=>$content) {
1087 if ($field[$type] !== '') {
07ed083e
RW
1088 if ($key == 'username' && $type == 'normal') {
1089 $field[$type] = clean_param($field[$type], PARAM_USERNAME);
1090 }
e4e38544 1091 $field[$type] = '<span class="uu'.$type.'">'.$field[$type].'</span>';
1092 } else {
1093 unset($field[$type]);
1094 }
1095 }
1096 echo '<td class="cell c'.$ci++.'">';
1097 if (!empty($field)) {
1098 echo implode('<br />', $field);
1099 } else {
1100 echo '&nbsp;';
1101 }
1102 echo '</td>';
1103 }
1104 echo '</tr>';
1105 foreach ($this->columns as $col) {
1106 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
1107 }
1108 }
1109
1110 function track($col, $msg, $level='normal', $merge=true) {
1111 if (empty($this->_row)) {
1112 $this->flush(); //init arrays
1113 }
1114 if (!in_array($col, $this->columns)) {
1115 debugging('Incorrect column:'.$col);
1116 return;
1117 }
1118 if ($merge) {
1119 if ($this->_row[$col][$level] != '') {
1120 $this->_row[$col][$level] .='<br />';
1121 }
1122 $this->_row[$col][$level] .= s($msg);
1123 } else {
1124 $this->_row[$col][$level] = s($msg);
1125 }
1126 }
1127
1128 function close() {
1129 echo '</table>';
1130 }
1131}
df7ecfe4 1132
e4e38544 1133/**
1134 * Validation callback function - verified the column line of csv file.
1135 * Converts column names to lowercase too.
1136 */
1137function validate_user_upload_columns(&$columns) {
1138 global $STD_FIELDS, $PRF_FIELDS;
1139
1140 if (count($columns) < 2) {
1141 return get_string('csvfewcolumns', 'error');
df7ecfe4 1142 }
e4e38544 1143
1144 // test columns
1145 $processed = array();
1146 foreach ($columns as $key=>$unused) {
1147 $columns[$key] = strtolower($columns[$key]); // no unicode expected here, ignore case
1148 $field = $columns[$key];
1149 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
1150 !preg_match('/^course\d+$/', $field) && !preg_match('/^group\d+$/', $field) &&
2686b6c3 1151 !preg_match('/^type\d+$/', $field) && !preg_match('/^role\d+$/', $field) &&
1152 !preg_match('/^enrolperiod\d+$/', $field)) {
e4e38544 1153 return get_string('invalidfieldname', 'error', $field);
1154 }
1155 if (in_array($field, $processed)) {
1156 return get_string('csvcolumnduplicates', 'error');
1157 }
1158 $processed[] = $field;
df7ecfe4 1159 }
e4e38544 1160 return true;
df7ecfe4 1161}
1162
e4e38544 1163/**
1164 * Increments username - increments trailing number or adds it if not present.
1165 * Varifies that the new username does not exist yet
1166 * @param string $username
1167 * @return incremented username which does not exist yet
1168 */
1169function increment_username($username, $mnethostid) {
1d8bf5f0 1170 global $DB;
1171
e4e38544 1172 if (!preg_match_all('/(.*?)([0-9]+)$/', $username, $matches)) {
1173 $username = $username.'2';
1174 } else {
1175 $username = $matches[1][0].($matches[2][0]+1);
1176 }
1177
1d8bf5f0 1178 if ($DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$mnethostid))) {
e4e38544 1179 return increment_username($username, $mnethostid);
1180 } else {
1181 return $username;
1182 }
1183}
df7ecfe4 1184
e4e38544 1185/**
1186 * Check if default field contains templates and apply them.
1187 * @param string template - potential tempalte string
1188 * @param object user object- we need username, firstname and lastname
1189 * @return string field value
1190 */
1191function process_template($template, $user) {
1192 if (strpos($template, '%') === false) {
1193 return $template;
df7ecfe4 1194 }
e4e38544 1195
1196 // very very ugly hack!
1197 global $template_globals;
a226a972 1198 $template_globals = new stdClass();
e4e38544 1199 $template_globals->username = isset($user->username) ? $user->username : '';
1200 $template_globals->firstname = isset($user->firstname) ? $user->firstname : '';
1201 $template_globals->lastname = isset($user->lastname) ? $user->lastname : '';
1202
1203 $result = preg_replace_callback('/(?<!%)%([+-~])?(\d)*([flu])/', 'process_template_callback', $template);
1204
1205 $template_globals = null;
1206
1207 if (is_null($result)) {
1208 return $template; //error during regex processing??
1209 } else {
1210 return $result;
df7ecfe4 1211 }
e4e38544 1212}
df7ecfe4 1213
e4e38544 1214/**
1215 * Internal callback function.
1216 */
1217function process_template_callback($block) {
1218 global $template_globals;
1219 $textlib = textlib_get_instance();
1220 $repl = $block[0];
1221
1222 switch ($block[3]) {
1223 case 'u': $repl = $template_globals->username; break;
1224 case 'f': $repl = $template_globals->firstname; break;
1225 case 'l': $repl = $template_globals->lastname; break;
1226 }
1227 switch ($block[1]) {
1228 case '+': $repl = $textlib->strtoupper($repl); break;
1229 case '-': $repl = $textlib->strtolower($repl); break;
1230 case '~': $repl = $textlib->strtotitle($repl); break;
1231 }
1232 if (!empty($block[2])) {
1233 $repl = $textlib->substr($repl, 0 , $block[2]);
df7ecfe4 1234 }
e4e38544 1235
1236 return $repl;
df7ecfe4 1237}
1238
e4e38544 1239/**
1240 * Returns list of auth plugins that are enabled and known to work.
1241 */
1242function uu_allowed_auths() {
df7ecfe4 1243 global $CFG;
1244
e4e38544 1245 // only following plugins are guaranteed to work properly
df997f84 1246 // TODO: add support for more plugins in 2.0
e4e38544 1247 $whitelist = array('manual', 'nologin', 'none', 'email');
1248 $plugins = get_enabled_auth_plugins();
1249 $choices = array();
1250 foreach ($plugins as $plugin) {
370f10b7 1251 $choices[$plugin] = get_string('pluginname', "auth_{$plugin}");
df7ecfe4 1252 }
e4e38544 1253
1254 return $choices;
df7ecfe4 1255}
1256
e4e38544 1257/**
df997f84 1258 * Returns list of roles that are assignable in courses
e4e38544 1259 */
df997f84
PS
1260function uu_allowed_roles() {
1261 // let's cheat a bit, frontpage is guaranteed to exist and has the same list of roles ;-)
1262 $roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_ORIGINALANDSHORT);
1263 return array_reverse($roles, true);
1264}
e4e38544 1265
df997f84
PS
1266function uu_allowed_roles_cache() {
1267 $allowedroles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_SHORT);
1268 foreach ($allowedroles as $rid=>$rname) {
a226a972 1269 $rolecache[$rid] = new stdClass();
df997f84
PS
1270 $rolecache[$rid]->id = $rid;
1271 $rolecache[$rid]->name = $rname;
1272 if (!is_numeric($rname)) { // only non-numeric shortnames are supported!!!
a226a972 1273 $rolecache[$rname] = new stdClass();
df997f84
PS
1274 $rolecache[$rname]->id = $rid;
1275 $rolecache[$rname]->name = $rname;
e4e38544 1276 }
1277 }
df997f84 1278 return $rolecache;
df7ecfe4 1279}