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