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