3 /// Bulk user registration script from a comma separated file
4 /// Returns list of users with their user ids
6 require('../config.php');
7 require_once($CFG->libdir.'/adminlib.php');
8 require_once($CFG->libdir.'/csvlib.class.php');
9 require_once($CFG->dirroot.'/user/profile/lib.php');
10 require_once('uploaduser_form.php');
12 $iid = optional_param('iid', '', PARAM_INT);
13 $previewrows = optional_param('previewrows', 10, PARAM_INT);
14 $readcount = optional_param('readcount', 0, PARAM_INT);
15 $uploadtype = optional_param('uutype', 0, PARAM_INT);
17 define('UU_ADDNEW', 0);
18 define('UU_ADDINC', 1);
19 define('UU_ADD_UPDATE', 2);
20 define('UU_UPDATE', 3);
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'));
27 @set_time_limit(3600); // 1 hour should be enough
28 @raise_memory_limit('256M');
29 if (function_exists('apache_child_terminate')) {
30 // if we are running from Apache, give httpd a hint that
31 // it can recycle the process after it's done. Apache's
32 // memory management is truly awful but we can help it.
33 @apache_child_terminate();
37 admin_externalpage_setup('uploadusers');
38 require_capability('moodle/site:uploadusers', get_context_instance(CONTEXT_SYSTEM));
40 $textlib = textlib_get_instance();
41 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
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');
49 $struserupdated = get_string('useraccountupdated', 'admin');
50 $strusernotupdated = get_string('usernotupdatederror', 'error');
51 $strusernotupdatednotexists = get_string('usernotupdatednotexists', 'error');
52 $strusernotupdatedadmin = get_string('usernotupdatedadmin', 'error');
54 $struseradded = get_string('newuser');
55 $strusernotadded = get_string('usernotaddedregistered', 'error');
56 $strusernotaddederror = get_string('usernotaddederror', 'error');
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');
64 $strcannotassignrole = get_string('cannotassignrole', 'error');
65 $strduplicateusername = get_string('duplicateusername', 'error');
67 $struserauthunsupported = get_string('userauthunsupported', 'error');
68 $stremailduplicate = get_string('useremailduplicate', 'error');
70 $errorstr = get_string('error');
72 $returnurl = $CFG->wwwroot.'/'.$CFG->admin.'/uploaduser.php';
73 $bulknurl = $CFG->wwwroot.'/'.$CFG->admin.'/user/user_bulk.php';
76 $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
78 // array of all valid fields for validation
79 $STD_FIELDS = array('id', 'firstname', 'lastname', 'username', 'email',
80 'city', 'country', 'lang', 'auth', 'timezone', 'mailformat',
81 'maildisplay', 'maildigest', 'htmleditor', 'ajax', 'autosubscribe',
82 'mnethostid', 'institution', 'department', 'idnumber', 'skype',
83 'msn', 'aim', 'yahoo', 'icq', 'phone1', 'phone2', 'address',
84 'url', 'description', 'descriptionformat', 'oldusername', 'emailstop', 'deleted',
87 $PRF_FIELDS = array();
89 if ($prof_fields = $DB->get_records('user_info_field')) {
90 foreach ($prof_fields as $prof_field) {
91 $PRF_FIELDS[] = 'profile_field_'.$prof_field->shortname;
97 $mform = new admin_uploaduser_form1();
99 if ($formdata = $mform->get_data()) {
100 $iid = csv_import_reader::get_new_iid('uploaduser');
101 $cir = new csv_import_reader($iid, 'uploaduser');
103 $content = $mform->get_file_content('userfile');
104 $optype = $formdata->uutype;
105 $readcount = $cir->load_csv_content($content, $formdata->encoding, $formdata->delimiter_name, 'validate_user_upload_columns');
108 if ($readcount === false) {
109 //TODO: need more detailed error info
110 print_error('csvloaderror', '', $returnurl);
111 } else if ($readcount == 0) {
112 print_error('csvemptyfile', 'error', $returnurl);
117 echo $OUTPUT->header();
119 echo $OUTPUT->heading_with_help(get_string('uploadusers', 'admin'), 'uploadusers', 'admin');
122 echo $OUTPUT->footer();
126 $cir = new csv_import_reader($iid, 'uploaduser');
129 if (!$columns = $cir->get_columns()) {
130 print_error('cannotreadtmpfile', 'error', $returnurl);
132 $mform = new admin_uploaduser_form2(null, $columns);
133 // get initial date from form1
134 $mform->set_data(array('iid'=>$iid, 'previewrows'=>$previewrows, 'readcount'=>$readcount, 'uutypelabel'=>$choices[$uploadtype], 'uutype'=>$uploadtype));
136 // If a file has been uploaded, then process it
137 if ($formdata = $mform->is_cancelled()) {
139 redirect($returnurl);
141 } else if ($formdata = $mform->get_data()) {
143 echo $OUTPUT->header();
144 echo $OUTPUT->heading(get_string('uploadusersresult', 'admin'));
146 $optype = $formdata->uutype;
148 $createpasswords = (!empty($formdata->uupasswordnew) and $optype != UU_UPDATE);
149 $updatepasswords = (!empty($formdata->uupasswordold) and $optype != UU_ADDNEW and $optype != UU_ADDINC);
150 $allowrenames = (!empty($formdata->uuallowrenames) and $optype != UU_ADDNEW and $optype != UU_ADDINC);
151 $allowdeletes = (!empty($formdata->uuallowdeletes) and $optype != UU_ADDNEW and $optype != UU_ADDINC);
152 $updatetype = isset($formdata->uuupdatetype) ? $formdata->uuupdatetype : 0;
153 $bulk = $formdata->uubulk;
154 $noemailduplicates = $formdata->uunoemailduplicates;
156 // verification moved to two places: after upload and into form2
168 $ccache = array(); // course cache - do not fetch all courses here, we will not probably use them all anyway!
169 $rolecache = uu_allowed_roles_cache(); // roles lookup cache
170 $manualcache = array(); // cache of used manual enrol plugins in each course
172 $allowedauths = uu_allowed_auths();
173 $allowedauths = array_keys($allowedauths);
174 $availableauths = get_plugin_list('auth');
175 $availableauths = array_keys($availableauths);
177 // we use only manual enrol plugin here, if it is disabled no enrol is done
178 if (enrol_is_enabled('manual')) {
179 $manual = enrol_get_plugin('manual');
184 // clear bulk selection
186 $SESSION->bulk_users = array();
189 // init csv import helper
191 $linenum = 1; //column header is first line
193 // init upload progress tracker
194 $upt = new uu_progress_tracker();
195 $upt->init(); // start table
197 while ($line = $cir->next()) {
201 $upt->track('line', $linenum);
203 $forcechangepassword = false;
205 $user = new stdClass();
206 // by default, use the local mnet id (this may be changed in the file)
207 $user->mnethostid = $CFG->mnet_localhost_id;
208 // add fields to user object
209 foreach ($line as $key => $value) {
211 $key = $columns[$key];
212 // password is special field
213 if ($key == 'password') {
215 $user->password = hash_internal_user_password($value);
216 if (!empty($CFG->passwordpolicy) and !check_password_policy($value, $errmsg)) {
217 $forcechangepassword = true;
222 $user->$key = $value;
223 if (in_array($key, $upt->columns)) {
224 $upt->track($key, $value);
230 // get username, first/last name now - we need them in templates!!
231 if ($optype == UU_UPDATE) {
232 // when updating only username is required
233 if (!isset($user->username)) {
234 $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
235 $upt->track('username', $errorstr, 'error');
242 // when all other ops need firstname and lastname
243 if (!isset($user->firstname) or $user->firstname === '') {
244 $upt->track('status', get_string('missingfield', 'error', 'firstname'), 'error');
245 $upt->track('firstname', $errorstr, 'error');
248 if (!isset($user->lastname) or $user->lastname === '') {
249 $upt->track('status', get_string('missingfield', 'error', 'lastname'), 'error');
250 $upt->track('lastname', $errorstr, 'error');
257 // we require username too - we might use template for it though
258 if (!isset($user->username)) {
259 if (!isset($formdata->username) or $formdata->username === '') {
260 $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
261 $upt->track('username', $errorstr, 'error');
265 $user->username = process_template($formdata->username, $user);
266 $upt->track('username', $user->username);
271 // normalize username
272 $user->username = clean_param($user->username, PARAM_USERNAME);
274 if (empty($user->username)) {
275 $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
276 $upt->track('username', $errorstr, 'error');
281 if ($existinguser = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
282 $upt->track('id', $existinguser->id, 'normal', false);
285 // find out in username incrementing required
286 if ($existinguser and $optype == UU_ADDINC) {
287 $oldusername = $user->username;
288 $user->username = increment_username($user->username, $user->mnethostid);
289 $upt->track('username', '', 'normal', false); // clear previous
290 $upt->track('username', $oldusername.'-->'.$user->username, 'info');
291 $existinguser = false;
294 // add default values for remaining fields
295 foreach ($STD_FIELDS as $field) {
296 if (isset($user->$field)) {
299 // all validation moved to form2
300 if (isset($formdata->$field)) {
302 $user->$field = process_template($formdata->$field, $user);
305 foreach ($PRF_FIELDS as $field) {
306 if (isset($user->$field)) {
309 if (isset($formdata->$field)) {
311 $user->$field = process_template($formdata->$field, $user);
316 if (!empty($user->deleted)) {
317 if (!$allowdeletes) {
319 $upt->track('status', $strusernotdeletedoff, 'warning');
323 if (is_siteadmin($existinguser->id)) {
324 $upt->track('status', $strusernotdeletedadmin, 'error');
328 if (delete_user($existinguser)) {
329 $upt->track('status', $struserdeleted);
332 $upt->track('status', $strusernotdeletederror, 'error');
336 $upt->track('status', $strusernotdeletedmissing, 'error');
341 // we do not need the deleted flag anymore
342 unset($user->deleted);
344 // renaming requested?
345 if (!empty($user->oldusername) ) {
346 $oldusername = $textlib->strtolower($user->oldusername);
347 if (!$allowrenames) {
349 $upt->track('status', $strusernotrenamedoff, 'warning');
354 $upt->track('status', $strusernotrenamedexists, 'error');
359 if ($olduser = $DB->get_record('user', array('username'=>$oldusername, 'mnethostid'=>$user->mnethostid))) {
360 $upt->track('id', $olduser->id, 'normal', false);
361 if (is_siteadmin($olduser->id)) {
362 $upt->track('status', $strusernotrenamedadmin, 'error');
366 $DB->set_field('user', 'username', $user->username, array('id'=>$olduser->id));
367 $upt->track('username', '', 'normal', false); // clear previous
368 $upt->track('username', $oldusername.'-->'.$user->username, 'info');
369 $upt->track('status', $struserrenamed);
372 $upt->track('status', $strusernotrenamedmissing, 'error');
376 $existinguser = $olduser;
377 $existinguser->username = $user->username;
380 // can we process with update or insert?
386 $upt->track('status', $strusernotadded, 'warning');
393 //this should not happen!
394 $upt->track('status', $strusernotaddederror, 'error');
404 if (!$existinguser) {
406 $upt->track('status', $strusernotupdatednotexists, 'warning');
417 $user->id = $existinguser->id;
419 if (is_siteadmin($user->id)) {
420 $upt->track('status', $strusernotupdatedadmin, 'error');
426 // no updates of existing data at all
428 $existinguser->timemodified = time();
429 if (empty($existinguser->timecreated)) {
430 if (empty($existinguser->firstaccess)) {
431 $existinguser->timecreated = time();
433 $existinguser->timecreated = $existinguser->firstaccess;
437 //load existing profile data
438 profile_load_data($existinguser);
441 if ($updatetype == 1) {
443 } else if ($updatetype == 2 or $updatetype == 3) {
444 $allowed = array_merge($STD_FIELDS, $PRF_FIELDS);
446 foreach ($allowed as $column) {
447 if ($column == 'username') {
450 if ($column == 'password') {
451 if (!$updatepasswords or $updatetype == 3) {
453 } else if (!empty($user->password)) {
454 $upt->track('password', get_string('updated'));
455 if ($forcechangepassword) {
456 set_user_preference('auth_forcepasswordchange', 1, $existinguser->id);
460 if ((property_exists($existinguser, $column) and property_exists($user, $column)) or in_array($column, $PRF_FIELDS)) {
461 if ($updatetype == 3 and $existinguser->$column !== '') {
462 //missing == non-empty only
465 if ($existinguser->$column !== $user->$column) {
466 if ($column == 'email') {
467 if ($DB->record_exists('user', array('email'=>$user->email))) {
468 if ($noemailduplicates) {
469 $upt->track('email', $stremailduplicate, 'error');
470 $upt->track('status', $strusernotupdated, 'error');
474 $upt->track('email', $stremailduplicate, 'warning');
478 if ($column != 'password' and in_array($column, $upt->columns)) {
479 $upt->track($column, '', 'normal', false); // clear previous
480 $upt->track($column, $existinguser->$column.'-->'.$user->$column, 'info');
482 $existinguser->$column = $user->$column;
487 // do not update record if new auth plugin does not exist!
488 if (!in_array($existinguser->auth, $availableauths)) {
489 $upt->track('auth', get_string('userautherror', 'error', $existinguser->auth), 'error');
490 $upt->track('status', $strusernotupdated, 'error');
493 } else if (!in_array($existinguser->auth, $allowedauths)) {
494 $upt->track('auth', $struserauthunsupported, 'warning');
497 $DB->update_record('user', $existinguser);
498 $upt->track('status', $struserupdated);
500 // save custom profile fields data from csv file
501 profile_save_data($existinguser);
503 events_trigger('user_updated', $existinguser);
506 if ($bulk == 2 or $bulk == 3) {
507 if (!in_array($user->id, $SESSION->bulk_users)) {
508 $SESSION->bulk_users[] = $user->id;
513 // save the user to the database
514 $user->confirmed = 1;
515 $user->timemodified = time();
516 $user->timecreated = time();
518 if (!$createpasswords and empty($user->password)) {
519 $upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
520 $upt->track('status', $strusernotaddederror, 'error');
525 // do not insert record if new auth plguin does not exist!
526 if (isset($user->auth)) {
527 if (!in_array($user->auth, $availableauths)) {
528 $upt->track('auth', get_string('userautherror', 'error', $user->auth), 'error');
529 $upt->track('status', $strusernotaddederror, 'error');
532 } else if (!in_array($user->auth, $allowedauths)) {
533 $upt->track('auth', $struserauthunsupported, 'warning');
537 if ($DB->record_exists('user', array('email'=>$user->email))) {
538 if ($noemailduplicates) {
539 $upt->track('email', $stremailduplicate, 'error');
540 $upt->track('status', $strusernotaddederror, 'error');
544 $upt->track('email', $stremailduplicate, 'warning');
548 $user->id = $DB->insert_record('user', $user);
549 $info = ': ' . $user->username .' (ID = ' . $user->id . ')';
550 $upt->track('status', $struseradded);
551 $upt->track('id', $user->id, 'normal', false);
553 if ($createpasswords and empty($user->password)) {
554 // passwords will be created and sent out on cron
555 set_user_preference('create_password', 1, $user->id);
556 set_user_preference('auth_forcepasswordchange', 1, $user->id);
557 $upt->track('password', get_string('new'));
559 if ($forcechangepassword) {
560 set_user_preference('auth_forcepasswordchange', 1, $user->id);
563 // save custom profile fields data
564 profile_save_data($user);
566 // make sure user context exists
567 get_context_instance(CONTEXT_USER, $user->id);
569 events_trigger('user_created', $user);
571 if ($bulk == 1 or $bulk == 3) {
572 if (!in_array($user->id, $SESSION->bulk_users)) {
573 $SESSION->bulk_users[] = $user->id;
578 // find course enrolments, groups, roles/types and enrol periods
579 foreach ($columns as $column) {
580 if (!preg_match('/^course\d+$/', $column)) {
583 $i = substr($column, 6);
585 if (empty($user->{'course'.$i})) {
588 $shortname = $user->{'course'.$i};
589 if (!array_key_exists($shortname, $ccache)) {
590 if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname')) {
591 $upt->track('enrolments', get_string('unknowncourse', 'error', $shortname), 'error');
594 $ccache[$shortname] = $course;
595 $ccache[$shortname]->groups = null;
597 $courseid = $ccache[$shortname]->id;
598 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
599 if (!isset($manualcache[$courseid])) {
600 if ($instances = enrol_get_instances($courseid, false)) {
601 $manualcache[$courseid] = reset($instances);
603 $manualcache[$courseid] = false;
607 if ($manual and $manualcache[$courseid]) {
611 if (!empty($user->{'role'.$i})) {
612 $addrole = $user->{'role'.$i};
613 if (array_key_exists($addrole, $rolecache)) {
614 $rid = $rolecache[$addrole]->id;
616 $upt->track('enrolments', get_string('unknownrole', 'error', $addrole), 'error');
620 } else if (!empty($user->{'type'.$i})) {
621 // if no role, then find "old" enrolment type
622 $addtype = $user->{'type'.$i};
623 if ($addtype < 1 or $addtype > 3) {
624 $upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
626 } else if (empty($formdata->{'uulegacy'.$addtype})) {
629 $rid = $formdata->{'uulegacy'.$addtype};
632 // no role specified, use the default from manual enrol plugin
633 $rid = $manualcache[$courseid]->roleid;
639 if (!empty($user->{'enrolperiod'.$i})) {
640 $duration = (int)$user->{'enrolperiod'.$i} * 86400; // convert days to seconds
641 if ($duration > 0) { // sanity check
642 $timeend = $today + $duration;
646 $manual->enrol_user($manualcache[$courseid], $user->id, $rid, $today, $timeend, true);
649 $a->course = $shortname;
650 $a->role = $rolecache[$rid]->name;
651 $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
655 // find group to add to
656 if (!empty($user->{'group'.$i})) {
657 // make sure user is enrolled into course before adding into groups
658 if (!is_enrolled($coursecontext, $user->id)) {
659 $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group'.$i}), 'error');
663 if (is_null($ccache[$shortname]->groups)) {
664 $ccache[$shortname]->groups = array();
665 if ($groups = groups_get_all_groups($courseid)) {
666 foreach ($groups as $gid=>$group) {
667 $ccache[$shortname]->groups[$gid] = new stdClass();
668 $ccache[$shortname]->groups[$gid]->id = $gid;
669 $ccache[$shortname]->groups[$gid]->name = $group->name;
670 if (!is_numeric($group->name)) { // only non-numeric names are supported!!!
671 $ccache[$shortname]->groups[$group->name] = new stdClass();
672 $ccache[$shortname]->groups[$group->name]->id = $gid;
673 $ccache[$shortname]->groups[$group->name]->name = $group->name;
679 $addgroup = $user->{'group'.$i};
680 if (!array_key_exists($addgroup, $ccache[$shortname]->groups)) {
681 // if group doesn't exist, create it
682 $newgroupdata = new stdClass();
683 $newgroupdata->name = $addgroup;
684 $newgroupdata->courseid = $ccache[$shortname]->id;
685 if ($ccache[$shortname]->groups[$addgroup]->id = groups_create_group($newgroupdata)){
686 $ccache[$shortname]->groups[$addgroup]->name = $newgroupdata->name;
688 $upt->track('enrolments', get_string('unknowngroup', 'error', $addgroup), 'error');
692 $gid = $ccache[$shortname]->groups[$addgroup]->id;
693 $gname = $ccache[$shortname]->groups[$addgroup]->name;
696 if (groups_add_member($gid, $user->id)) {
697 $upt->track('enrolments', get_string('addedtogroup', '', $gname));
699 $upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
701 } catch (moodle_exception $e) {
702 $upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
709 $upt->close(); // close table
714 echo $OUTPUT->box_start('boxwidthnarrow boxaligncenter generalbox', 'uploadresults');
716 if ($optype != UU_UPDATE) {
717 echo get_string('userscreated', 'admin').': '.$usersnew.'<br />';
719 if ($optype == UU_UPDATE or $optype == UU_ADD_UPDATE) {
720 echo get_string('usersupdated', 'admin').': '.$usersupdated.'<br />';
723 echo get_string('usersdeleted', 'admin').': '.$deletes.'<br />';
724 echo get_string('deleteerrors', 'admin').': '.$deleteerrors.'<br />';
727 echo get_string('usersrenamed', 'admin').': '.$renames.'<br />';
728 echo get_string('renameerrors', 'admin').': '.$renameerrors.'<br />';
731 echo get_string('usersskipped', 'admin').': '.$usersskipped.'<br />';
733 echo get_string('usersweakpassword', 'admin').': '.$weakpasswords.'<br />';
734 echo get_string('errors', 'admin').': '.$userserrors.'</p>';
735 echo $OUTPUT->box_end();
738 echo $OUTPUT->continue_button($bulknurl);
740 echo $OUTPUT->continue_button($returnurl);
742 echo $OUTPUT->footer();
747 echo $OUTPUT->header();
751 echo $OUTPUT->heading(get_string('uploaduserspreview', 'admin'));
756 while ($fields = $cir->next()) {
759 foreach($fields as $key =>$field) {
760 $rowcols[$columns[$key]] = $field;
763 $usernameexist = $DB->record_exists('user', array('username'=>$rowcols['username']));
764 $emailexist = $DB->record_exists('user', array('email'=>$rowcols['email']));
765 $cleanusername = clean_param($rowcols['username'], PARAM_USERNAME);
766 $validusername = strcmp($rowcols['username'], $cleanusername);
767 $validemail = validate_email($rowcols['email']);
769 if ($validusername != 0 || !$validemail) {
770 if ($validusername != 0) {
771 $errormsg['username'] = get_string('invalidusernameupload');
774 $errormsg['email'] = get_string('invalidemail');
780 if ($usernameexist || $emailexist ) {
781 $rowcols['action'] = 'skipped';
783 $rowcols['action'] = 'create';
788 if (!$usernameexist && !$emailexist) {
789 $rowcols['action'] = 'create';
790 } else if ($usernameexist && !$emailexist) {
791 $rowcols['action'] = 'addcountertousername';
792 $rowcols['username'] = increment_username($rowcols['username'], $CFG->mnet_localhost_id);
794 $rowcols['action'] = 'skipped';
799 $oldusernameexist = '';
800 if (isset($rowcols['oldusername'])) {
801 $oldusernameexist = $DB->record_exists('user', array('username'=>$rowcols['oldusername']));
803 if ($usernameexist || $emailexist || $oldusernameexist ) {
804 $rowcols['action'] = 'update';
806 $rowcols['action'] = 'create';
811 $oldusernameexist = '';
812 if (isset($rowcols['oldusername'])) {
813 $oldusernameexist = $DB->record_exists('user', array('username'=>$rowcols['oldusername']));
816 if ($usernameexist || $emailexist || !empty($oldusernameexist)) {
817 $rowcols['action'] = 'update';
819 $rowcols['action'] = "skipped";
824 if (!empty($errormsg)){
825 $rowcols['error'] = array();
826 $rowcols['error'] = $errormsg;
828 if ($rowcols['action'] != 'skipped') {
829 $contents[] = $rowcols;
836 foreach ($contents as $content) {
837 foreach($content as $key => $value) {
838 if (!in_array($key, $headings)) {
844 $table = new html_table();
845 $table->id = "uupreview";
846 $table->attributes['class'] = 'generaltable';
847 $table->tablealign = 'center';
848 $table->summary = get_string('uploaduserspreview', 'admin');
849 $table->head = array();
850 $table->data = array();
853 foreach ($headings as $heading) {
854 $table->head[] = s($heading);
859 if (in_array('error', $headings)) {
863 foreach ($contents as $content) {
864 if (array_key_exists('error', $content)) {
865 $rows = new html_table_row();
866 foreach ($content as $key => $value) {
867 $cells = new html_table_cell();
869 if (array_key_exists($key, $content['error'])) {
870 $errclass = 'uuerror';
872 if ($key == 'error') {
873 $value = join('<br />', $content['error']);
875 if ($key == 'action') {
876 $value = get_string($content[$key]);
878 $cells->text = $value;
879 $cells->attributes['class'] = $errclass;
880 $rows->cells[] = $cells;
883 $table->data[] = $rows;
886 $mform = new admin_uploaduser_form3();
887 $mform->set_data(array('uutype'=>$uploadtype));
888 } else if (empty($contents)) {
889 $mform = new admin_uploaduser_form3();
890 $mform->set_data(array('uutype'=>$uploadtype));
893 foreach ($contents as $content) {
894 $rows = new html_table_row();
895 if ($countcontent >= $previewrows) {
896 foreach ($content as $con) {
897 $cells = new html_table_cell();
898 $cells->text = '...';
900 $rows->cells[] = $cells;
901 $table->data[] = $rows;
904 foreach ($headings as $heading) {
905 $cells = new html_table_cell();
906 if(array_key_exists($heading, $content)) {
907 if ($heading == 'action') {
908 $content[$heading] = get_string($content[$heading]);
910 $cells->text = $content[$heading];
914 $rows->cells[] = $cells;
916 $table->data[] = $rows;
920 echo html_writer::table($table);
924 echo $OUTPUT->container(get_string('useruploadtype', 'moodle', $choices[$uploadtype]), 'centerpara');
925 echo $OUTPUT->container(get_string('uploadinvalidpreprocessedcount', 'moodle', $countcontent), 'centerpara');
926 echo $OUTPUT->container(get_string('invalidusername', 'moodle'), 'centerpara');
927 echo $OUTPUT->container(get_string('uploadfilecontainerror', 'moodle'), 'centerpara');
928 } else if (empty($contents)) {
929 echo $OUTPUT->container(get_string('uupreprocessedcount', 'admin', $countcontent), 'centerpara');
930 echo $OUTPUT->container(get_string('uploadfilecontentsnovaliddata'), 'centerpara');
932 echo $OUTPUT->container(get_string('uupreprocessedcount', 'admin', $countcontent), 'centerpara');
936 echo $OUTPUT->footer();
939 /////////////////////////////////////
940 /// Utility functions and classes ///
941 /////////////////////////////////////
943 class uu_progress_tracker {
945 var $columns = array('status', 'line', 'id', 'username', 'firstname', 'lastname', 'email', 'password', 'auth', 'enrolments', 'deleted');
947 function uu_progress_tracker() {
952 echo '<table id="uuresults" class="generaltable boxaligncenter" summary="'.get_string('uploadusersresult', 'admin').'">';
953 echo '<tr class="heading r0">';
954 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('status').'</th>';
955 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('uucsvline', 'admin').'</th>';
956 echo '<th class="header c'.$ci++.'" scope="col">ID</th>';
957 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('username').'</th>';
958 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('firstname').'</th>';
959 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('lastname').'</th>';
960 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('email').'</th>';
961 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('password').'</th>';
962 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('authentication').'</th>';
963 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('enrolments', 'enrol').'</th>';
964 echo '<th class="header c'.$ci++.'" scope="col">'.get_string('delete').'</th>';
970 if (empty($this->_row) or empty($this->_row['line']['normal'])) {
971 $this->_row = array();
972 foreach ($this->columns as $col) {
973 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
979 echo '<tr class="r'.$ri.'">';
980 foreach ($this->_row as $key=>$field) {
981 foreach ($field as $type=>$content) {
982 if ($field[$type] !== '') {
983 if ($key == 'username' && $type == 'normal') {
984 $field[$type] = clean_param($field[$type], PARAM_USERNAME);
986 $field[$type] = '<span class="uu'.$type.'">'.$field[$type].'</span>';
988 unset($field[$type]);
991 echo '<td class="cell c'.$ci++.'">';
992 if (!empty($field)) {
993 echo implode('<br />', $field);
1000 foreach ($this->columns as $col) {
1001 $this->_row[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
1005 function track($col, $msg, $level='normal', $merge=true) {
1006 if (empty($this->_row)) {
1007 $this->flush(); //init arrays
1009 if (!in_array($col, $this->columns)) {
1010 debugging('Incorrect column:'.$col);
1014 if ($this->_row[$col][$level] != '') {
1015 $this->_row[$col][$level] .='<br />';
1017 $this->_row[$col][$level] .= s($msg);
1019 $this->_row[$col][$level] = s($msg);
1029 * Validation callback function - verified the column line of csv file.
1030 * Converts column names to lowercase too.
1032 function validate_user_upload_columns(&$columns) {
1033 global $STD_FIELDS, $PRF_FIELDS;
1035 if (count($columns) < 2) {
1036 return get_string('csvfewcolumns', 'error');
1040 $processed = array();
1041 foreach ($columns as $key=>$unused) {
1042 $columns[$key] = strtolower($columns[$key]); // no unicode expected here, ignore case
1043 $field = $columns[$key];
1044 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
1045 !preg_match('/^course\d+$/', $field) && !preg_match('/^group\d+$/', $field) &&
1046 !preg_match('/^type\d+$/', $field) && !preg_match('/^role\d+$/', $field) &&
1047 !preg_match('/^enrolperiod\d+$/', $field)) {
1048 return get_string('invalidfieldname', 'error', $field);
1050 if (in_array($field, $processed)) {
1051 return get_string('csvcolumnduplicates', 'error');
1053 $processed[] = $field;
1059 * Increments username - increments trailing number or adds it if not present.
1060 * Varifies that the new username does not exist yet
1061 * @param string $username
1062 * @return incremented username which does not exist yet
1064 function increment_username($username, $mnethostid) {
1067 if (!preg_match_all('/(.*?)([0-9]+)$/', $username, $matches)) {
1068 $username = $username.'2';
1070 $username = $matches[1][0].($matches[2][0]+1);
1073 if ($DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$mnethostid))) {
1074 return increment_username($username, $mnethostid);
1081 * Check if default field contains templates and apply them.
1082 * @param string template - potential tempalte string
1083 * @param object user object- we need username, firstname and lastname
1084 * @return string field value
1086 function process_template($template, $user) {
1087 if (strpos($template, '%') === false) {
1091 // very very ugly hack!
1092 global $template_globals;
1093 $template_globals = new stdClass();
1094 $template_globals->username = isset($user->username) ? $user->username : '';
1095 $template_globals->firstname = isset($user->firstname) ? $user->firstname : '';
1096 $template_globals->lastname = isset($user->lastname) ? $user->lastname : '';
1098 $result = preg_replace_callback('/(?<!%)%([+-~])?(\d)*([flu])/', 'process_template_callback', $template);
1100 $template_globals = null;
1102 if (is_null($result)) {
1103 return $template; //error during regex processing??
1110 * Internal callback function.
1112 function process_template_callback($block) {
1113 global $template_globals;
1114 $textlib = textlib_get_instance();
1117 switch ($block[3]) {
1118 case 'u': $repl = $template_globals->username; break;
1119 case 'f': $repl = $template_globals->firstname; break;
1120 case 'l': $repl = $template_globals->lastname; break;
1122 switch ($block[1]) {
1123 case '+': $repl = $textlib->strtoupper($repl); break;
1124 case '-': $repl = $textlib->strtolower($repl); break;
1125 case '~': $repl = $textlib->strtotitle($repl); break;
1127 if (!empty($block[2])) {
1128 $repl = $textlib->substr($repl, 0 , $block[2]);
1135 * Returns list of auth plugins that are enabled and known to work.
1137 function uu_allowed_auths() {
1140 // only following plugins are guaranteed to work properly
1141 // TODO: add support for more plugins in 2.0
1142 $whitelist = array('manual', 'nologin', 'none', 'email');
1143 $plugins = get_enabled_auth_plugins();
1145 foreach ($plugins as $plugin) {
1146 $choices[$plugin] = get_string('pluginname', "auth_{$plugin}");
1153 * Returns list of roles that are assignable in courses
1155 function uu_allowed_roles() {
1156 // let's cheat a bit, frontpage is guaranteed to exist and has the same list of roles ;-)
1157 $roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_ORIGINALANDSHORT);
1158 return array_reverse($roles, true);
1161 function uu_allowed_roles_cache() {
1162 $allowedroles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, SITEID), ROLENAME_SHORT);
1163 foreach ($allowedroles as $rid=>$rname) {
1164 $rolecache[$rid] = new stdClass();
1165 $rolecache[$rid]->id = $rid;
1166 $rolecache[$rid]->name = $rname;
1167 if (!is_numeric($rname)) { // only non-numeric shortnames are supported!!!
1168 $rolecache[$rname] = new stdClass();
1169 $rolecache[$rname]->id = $rid;
1170 $rolecache[$rname]->name = $rname;