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 $manualcacche = 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 object();
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 ((array_key_exists($column, $existinguser) and array_key_exists($column, $user)) 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 plguin 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);
504 if ($bulk == 2 or $bulk == 3) {
505 if (!in_array($user->id
, $SESSION->bulk_users
)) {
506 $SESSION->bulk_users
[] = $user->id
;
511 // save the user to the database
512 $user->confirmed
= 1;
513 $user->timemodified
= time();
514 $user->timecreated
= time();
516 if (!$createpasswords and empty($user->password
)) {
517 $upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
518 $upt->track('status', $strusernotaddederror, 'error');
523 // do not insert record if new auth plguin does not exist!
524 if (isset($user->auth
)) {
525 if (!in_array($user->auth
, $availableauths)) {
526 $upt->track('auth', get_string('userautherror', 'error', $user->auth
), 'error');
527 $upt->track('status', $strusernotaddederror, 'error');
530 } else if (!in_array($user->auth
, $allowedauths)) {
531 $upt->track('auth', $struserauthunsupported, 'warning');
535 if ($DB->record_exists('user', array('email'=>$user->email
))) {
536 if ($noemailduplicates) {
537 $upt->track('email', $stremailduplicate, 'error');
538 $upt->track('status', $strusernotaddederror, 'error');
542 $upt->track('email', $stremailduplicate, 'warning');
546 $user->id
= $DB->insert_record('user', $user);
547 $info = ': ' . $user->username
.' (ID = ' . $user->id
. ')';
548 $upt->track('status', $struseradded);
549 $upt->track('id', $user->id
, 'normal', false);
551 if ($createpasswords and empty($user->password
)) {
552 // passwords will be created and sent out on cron
553 set_user_preference('create_password', 1, $user->id
);
554 set_user_preference('auth_forcepasswordchange', 1, $user->id
);
555 $upt->track('password', get_string('new'));
557 if ($forcechangepassword) {
558 set_user_preference('auth_forcepasswordchange', 1, $user->id
);
561 // save custom profile fields data
562 profile_save_data($user);
564 // make sure user context exists
565 get_context_instance(CONTEXT_USER
, $user->id
);
567 if ($bulk == 1 or $bulk == 3) {
568 if (!in_array($user->id
, $SESSION->bulk_users
)) {
569 $SESSION->bulk_users
[] = $user->id
;
574 // find course enrolments, groups, roles/types and enrol periods
575 foreach ($columns as $column) {
576 if (!preg_match('/^course\d+$/', $column)) {
579 $i = substr($column, 6);
581 if (empty($user->{'course'.$i})) {
584 $shortname = $user->{'course'.$i};
585 if (!array_key_exists($shortname, $ccache)) {
586 if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname')) {
587 $upt->track('enrolments', get_string('unknowncourse', 'error', $shortname), 'error');
590 $ccache[$shortname] = $course;
591 $ccache[$shortname]->groups
= null;
593 $courseid = $ccache[$shortname]->id
;
594 $coursecontext = get_context_instance(CONTEXT_COURSE
, $courseid);
595 if (!isset($manualcache[$courseid])) {
596 if ($instances = enrol_get_instances($courseid, false)) {
597 $manualcache[$courseid] = reset($instances);
599 $manualcache[$courseid] = false;
603 if ($manual and $manualcache[$courseid]) {
607 if (!empty($user->{'role'.$i})) {
608 $addrole = $user->{'role'.$i};
609 if (array_key_exists($addrole, $rolecache)) {
610 $rid = $rolecache[$addrole]->id
;
612 $upt->track('enrolments', get_string('unknownrole', 'error', $addrole), 'error');
616 } else if (!empty($user->{'type'.$i})) {
617 // if no role, then find "old" enrolment type
618 $addtype = $user->{'type'.$i};
619 if ($addtype < 1 or $addtype > 3) {
620 $upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
622 } else if (empty($formdata->{'uulegacy'.$addtype})) {
625 $rid = $formdata->{'uulegacy'.$addtype};
628 // no role specified, use the default from manual enrol plugin
629 $rid = $manualcache[$courseid]->roleid
;
635 if (!empty($user->{'enrolperiod'.$i})) {
636 $duration = (int)$user->{'enrolperiod'.$i} * 86400; // convert days to seconds
637 if ($duration > 0) { // sanity check
638 $timeend = $today +
$duration;
642 $manual->enrol_user($manualcache[$courseid], $user->id
, $rid, $today, $timeend, true);
645 $a->course
= $shortname;
646 $a->role
= $rolecache[$rid]->name
;
647 $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
651 // find group to add to
652 if (!empty($user->{'group'.$i})) {
653 // make sure user is enrolled into course before adding into groups
654 if (!is_enrolled($coursecontext, $user->id
)) {
655 $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $gname), 'error');
659 if (is_null($ccache[$shortname]->groups
)) {
660 $ccache[$shortname]->groups
= array();
661 if ($groups = groups_get_all_groups($courseid)) {
662 foreach ($groups as $gid=>$group) {
663 $ccache[$shortname]->groups
[$gid] = new object();
664 $ccache[$shortname]->groups
[$gid]->id
= $gid;
665 $ccache[$shortname]->groups
[$gid]->name
= $group->name
;
666 if (!is_numeric($group->name
)) { // only non-numeric names are supported!!!
667 $ccache[$shortname]->groups
[$group->name
] = new object();
668 $ccache[$shortname]->groups
[$group->name
]->id
= $gid;
669 $ccache[$shortname]->groups
[$group->name
]->name
= $group->name
;
675 $addgroup = $user->{'group'.$i};
676 if (!array_key_exists($addgroup, $ccache[$shortname]->groups
)) {
677 // if group doesn't exist, create it
678 $newgroupdata = new object();
679 $newgroupdata->name
= $addgroup;
680 $newgroupdata->courseid
= $ccache[$shortname]->id
;
681 if ($ccache[$shortname]->groups
[$addgroup]->id
= groups_create_group($newgroupdata)){
682 $ccache[$shortname]->groups
[$addgroup]->name
= $newgroupdata->name
;
684 $upt->track('enrolments', get_string('unknowngroup', 'error', $addgroup), 'error');
688 $gid = $ccache[$shortname]->groups
[$addgroup]->id
;
689 $gname = $ccache[$shortname]->groups
[$addgroup]->name
;
692 if (groups_add_member($gid, $user->id
)) {
693 $upt->track('enrolments', get_string('addedtogroup', '', $gname));
695 $upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
697 } catch (moodle_exception
$e) {
698 $upt->track('enrolments', get_string('addedtogroupnot', '', $gname), 'error');
705 $upt->close(); // close table
710 echo $OUTPUT->box_start('boxwidthnarrow boxaligncenter generalbox', 'uploadresults');
712 if ($optype != UU_UPDATE
) {
713 echo get_string('userscreated', 'admin').': '.$usersnew.'<br />';
715 if ($optype == UU_UPDATE
or $optype == UU_ADD_UPDATE
) {
716 echo get_string('usersupdated', 'admin').': '.$usersupdated.'<br />';
719 echo get_string('usersdeleted', 'admin').': '.$deletes.'<br />';
720 echo get_string('deleteerrors', 'admin').': '.$deleteerrors.'<br />';
723 echo get_string('usersrenamed', 'admin').': '.$renames.'<br />';
724 echo get_string('renameerrors', 'admin').': '.$renameerrors.'<br />';
727 echo get_string('usersskipped', 'admin').': '.$usersskipped.'<br />';
729 echo get_string('usersweakpassword', 'admin').': '.$weakpasswords.'<br />';
730 echo get_string('errors', 'admin').': '.$userserrors.'</p>';
731 echo $OUTPUT->box_end();
734 echo $OUTPUT->continue_button($bulknurl);
736 echo $OUTPUT->continue_button($returnurl);
738 echo $OUTPUT->footer();
743 echo $OUTPUT->header();
747 echo $OUTPUT->heading(get_string('uploaduserspreview', 'admin'));
752 while ($fields = $cir->next()) {
755 foreach($fields as $key =>$field) {
756 $rowcols[$columns[$key]] = $field;
759 $usernameexist = $DB->record_exists('user', array('username'=>$rowcols['username']));
760 $emailexist = $DB->record_exists('user', array('email'=>$rowcols['email']));
761 $cleanusername = clean_param($rowcols['username'], PARAM_USERNAME
);
762 $validusername = strcmp($rowcols['username'], $cleanusername);
763 $validemail = validate_email($rowcols['email']);
765 if ($validusername != 0 ||
!$validemail) {
766 if ($validusername != 0) {
767 $errormsg['username'] = get_string('invalidusernameupload');
770 $errormsg['email'] = get_string('invalidemail');
776 if ($usernameexist ||
$emailexist ) {
777 $rowcols['action'] = 'skipped';
779 $rowcols['action'] = 'create';
784 if (!$usernameexist && !$emailexist) {
785 $rowcols['action'] = 'create';
786 } else if ($usernameexist && !$emailexist) {
787 $rowcols['action'] = 'addcountertousername';
788 $rowcols['username'] = increment_username($rowcols['username'], $CFG->mnet_localhost_id
);
790 $rowcols['action'] = 'skipped';
795 $oldusernameexist = '';
796 if (isset($rowcols['oldusername'])) {
797 $oldusernameexist = $DB->record_exists('user', array('username'=>$rowcols['oldusername']));
799 if ($usernameexist ||
$emailexist ||
$oldusernameexist ) {
800 $rowcols['action'] = 'update';
802 $rowcols['action'] = 'create';
807 $oldusernameexist = '';
808 if (isset($rowcols['oldusername'])) {
809 $oldusernameexist = $DB->record_exists('user', array('username'=>$rowcols['oldusername']));
812 if ($usernameexist ||
$emailexist ||
!empty($oldusernameexist)) {
813 $rowcols['action'] = 'update';
815 $rowcols['action'] = "skipped";
820 if (!empty($errormsg)){
821 $rowcols['error'] = array();
822 $rowcols['error'] = $errormsg;
824 if ($rowcols['action'] != 'skipped') {
825 $contents[] = $rowcols;
832 foreach ($contents as $content) {
833 foreach($content as $key => $value) {
834 if (!in_array($key, $headings)) {
840 $table = new html_table();
841 $table->id
= "uupreview";
842 $table->attributes
['class'] = 'generaltable';
843 $table->tablealign
= 'center';
844 $table->summary
= get_string('uploaduserspreview', 'admin');
845 $table->head
= array();
846 $table->data
= array();
849 foreach ($headings as $heading) {
850 $table->head
[] = s($heading);
855 if (in_array('error', $headings)) {
859 foreach ($contents as $content) {
860 if (array_key_exists('error', $content)) {
861 $rows = new html_table_row();
862 foreach ($content as $key => $value) {
863 $cells = new html_table_cell();
865 if (array_key_exists($key, $content['error'])) {
866 $errclass = 'uuerror';
868 if ($key == 'error') {
869 $value = join('<br />', $content['error']);
871 if ($key == 'action') {
872 $value = get_string($content[$key]);
874 $cells->text
= $value;
875 $cells->attributes
['class'] = $errclass;
876 $rows->cells
[] = $cells;
879 $table->data
[] = $rows;
882 $mform = new admin_uploaduser_form3();
883 $mform->set_data(array('uutype'=>$uploadtype));
884 } else if (empty($contents)) {
885 $mform = new admin_uploaduser_form3();
886 $mform->set_data(array('uutype'=>$uploadtype));
889 foreach ($contents as $content) {
890 $rows = new html_table_row();
891 if ($countcontent >= $previewrows) {
892 foreach ($content as $con) {
893 $cells = new html_table_cell();
894 $cells->text
= '...';
896 $rows->cells
[] = $cells;
897 $table->data
[] = $rows;
900 foreach ($headings as $heading) {
901 $cells = new html_table_cell();
902 if(array_key_exists($heading, $content)) {
903 if ($heading == 'action') {
904 $content[$heading] = get_string($content[$heading]);
906 $cells->text
= $content[$heading];
910 $rows->cells
[] = $cells;
912 $table->data
[] = $rows;
916 echo html_writer
::table($table);
920 echo $OUTPUT->container(get_string('useruploadtype', 'moodle', $choices[$uploadtype]), 'centerpara');
921 echo $OUTPUT->container(get_string('uploadinvalidpreprocessedcount', 'moodle', $countcontent), 'centerpara');
922 echo $OUTPUT->container(get_string('invalidusername', 'moodle'), 'centerpara');
923 echo $OUTPUT->container(get_string('uploadfilecontainerror', 'moodle'), 'centerpara');
924 } else if (empty($contents)) {
925 echo $OUTPUT->container(get_string('uupreprocessedcount', 'admin', $countcontent), 'centerpara');
926 echo $OUTPUT->container(get_string('uploadfilecontentsnovaliddata'), 'centerpara');
928 echo $OUTPUT->container(get_string('uupreprocessedcount', 'admin', $countcontent), 'centerpara');
932 echo $OUTPUT->footer();
935 /////////////////////////////////////
936 /// Utility functions and classes ///
937 /////////////////////////////////////
939 class uu_progress_tracker
{
941 var $columns = array('status', 'line', 'id', 'username', 'firstname', 'lastname', 'email', 'password', 'auth', 'enrolments', 'deleted');
943 function uu_progress_tracker() {
948 echo '<table id="uuresults" class="generaltable boxaligncenter" summary="'.get_string('uploadusersresult', 'admin').'">';
949 echo '<tr class="heading r0">';
950 echo '<th class="header c'.$ci++
.'" scope="col">'.get_string('status').'</th>';
951 echo '<th class="header c'.$ci++
.'" scope="col">'.get_string('uucsvline', 'admin').'</th>';
952 echo '<th class="header c'.$ci++
.'" scope="col">ID</th>';
953 echo '<th class="header c'.$ci++
.'" scope="col">'.get_string('username').'</th>';
954 echo '<th class="header c'.$ci++
.'" scope="col">'.get_string('firstname').'</th>';
955 echo '<th class="header c'.$ci++
.'" scope="col">'.get_string('lastname').'</th>';
956 echo '<th class="header c'.$ci++
.'" scope="col">'.get_string('email').'</th>';
957 echo '<th class="header c'.$ci++
.'" scope="col">'.get_string('password').'</th>';
958 echo '<th class="header c'.$ci++
.'" scope="col">'.get_string('authentication').'</th>';
959 echo '<th class="header c'.$ci++
.'" scope="col">'.get_string('enrolments', 'enrol').'</th>';
960 echo '<th class="header c'.$ci++
.'" scope="col">'.get_string('delete').'</th>';
966 if (empty($this->_row
) or empty($this->_row
['line']['normal'])) {
967 $this->_row
= array();
968 foreach ($this->columns
as $col) {
969 $this->_row
[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
975 echo '<tr class="r'.$ri.'">';
976 foreach ($this->_row
as $key=>$field) {
977 foreach ($field as $type=>$content) {
978 if ($field[$type] !== '') {
979 if ($key == 'username' && $type == 'normal') {
980 $field[$type] = clean_param($field[$type], PARAM_USERNAME
);
982 $field[$type] = '<span class="uu'.$type.'">'.$field[$type].'</span>';
984 unset($field[$type]);
987 echo '<td class="cell c'.$ci++
.'">';
988 if (!empty($field)) {
989 echo implode('<br />', $field);
996 foreach ($this->columns
as $col) {
997 $this->_row
[$col] = array('normal'=>'', 'info'=>'', 'warning'=>'', 'error'=>'');
1001 function track($col, $msg, $level='normal', $merge=true) {
1002 if (empty($this->_row
)) {
1003 $this->flush(); //init arrays
1005 if (!in_array($col, $this->columns
)) {
1006 debugging('Incorrect column:'.$col);
1010 if ($this->_row
[$col][$level] != '') {
1011 $this->_row
[$col][$level] .='<br />';
1013 $this->_row
[$col][$level] .= s($msg);
1015 $this->_row
[$col][$level] = s($msg);
1025 * Validation callback function - verified the column line of csv file.
1026 * Converts column names to lowercase too.
1028 function validate_user_upload_columns(&$columns) {
1029 global $STD_FIELDS, $PRF_FIELDS;
1031 if (count($columns) < 2) {
1032 return get_string('csvfewcolumns', 'error');
1036 $processed = array();
1037 foreach ($columns as $key=>$unused) {
1038 $columns[$key] = strtolower($columns[$key]); // no unicode expected here, ignore case
1039 $field = $columns[$key];
1040 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
1041 !preg_match('/^course\d+$/', $field) && !preg_match('/^group\d+$/', $field) &&
1042 !preg_match('/^type\d+$/', $field) && !preg_match('/^role\d+$/', $field) &&
1043 !preg_match('/^enrolperiod\d+$/', $field)) {
1044 return get_string('invalidfieldname', 'error', $field);
1046 if (in_array($field, $processed)) {
1047 return get_string('csvcolumnduplicates', 'error');
1049 $processed[] = $field;
1055 * Increments username - increments trailing number or adds it if not present.
1056 * Varifies that the new username does not exist yet
1057 * @param string $username
1058 * @return incremented username which does not exist yet
1060 function increment_username($username, $mnethostid) {
1063 if (!preg_match_all('/(.*?)([0-9]+)$/', $username, $matches)) {
1064 $username = $username.'2';
1066 $username = $matches[1][0].($matches[2][0]+
1);
1069 if ($DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$mnethostid))) {
1070 return increment_username($username, $mnethostid);
1077 * Check if default field contains templates and apply them.
1078 * @param string template - potential tempalte string
1079 * @param object user object- we need username, firstname and lastname
1080 * @return string field value
1082 function process_template($template, $user) {
1083 if (strpos($template, '%') === false) {
1087 // very very ugly hack!
1088 global $template_globals;
1089 $template_globals = new object();
1090 $template_globals->username
= isset($user->username
) ?
$user->username
: '';
1091 $template_globals->firstname
= isset($user->firstname
) ?
$user->firstname
: '';
1092 $template_globals->lastname
= isset($user->lastname
) ?
$user->lastname
: '';
1094 $result = preg_replace_callback('/(?<!%)%([+-~])?(\d)*([flu])/', 'process_template_callback', $template);
1096 $template_globals = null;
1098 if (is_null($result)) {
1099 return $template; //error during regex processing??
1106 * Internal callback function.
1108 function process_template_callback($block) {
1109 global $template_globals;
1110 $textlib = textlib_get_instance();
1113 switch ($block[3]) {
1114 case 'u': $repl = $template_globals->username
; break;
1115 case 'f': $repl = $template_globals->firstname
; break;
1116 case 'l': $repl = $template_globals->lastname
; break;
1118 switch ($block[1]) {
1119 case '+': $repl = $textlib->strtoupper($repl); break;
1120 case '-': $repl = $textlib->strtolower($repl); break;
1121 case '~': $repl = $textlib->strtotitle($repl); break;
1123 if (!empty($block[2])) {
1124 $repl = $textlib->substr($repl, 0 , $block[2]);
1131 * Returns list of auth plugins that are enabled and known to work.
1133 function uu_allowed_auths() {
1136 // only following plugins are guaranteed to work properly
1137 // TODO: add support for more plugins in 2.0
1138 $whitelist = array('manual', 'nologin', 'none', 'email');
1139 $plugins = get_enabled_auth_plugins();
1141 foreach ($plugins as $plugin) {
1142 $choices[$plugin] = get_string('pluginname', "auth_{$plugin}");
1149 * Returns list of roles that are assignable in courses
1151 function uu_allowed_roles() {
1152 // let's cheat a bit, frontpage is guaranteed to exist and has the same list of roles ;-)
1153 $roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE
, SITEID
), ROLENAME_ORIGINALANDSHORT
);
1154 return array_reverse($roles, true);
1157 function uu_allowed_roles_cache() {
1158 $allowedroles = get_assignable_roles(get_context_instance(CONTEXT_COURSE
, SITEID
), ROLENAME_SHORT
);
1159 foreach ($allowedroles as $rid=>$rname) {
1160 $rolecache[$rid] = new object();
1161 $rolecache[$rid]->id
= $rid;
1162 $rolecache[$rid]->name
= $rname;
1163 if (!is_numeric($rname)) { // only non-numeric shortnames are supported!!!
1164 $rolecache[$rname] = new object();
1165 $rolecache[$rname]->id
= $rid;
1166 $rolecache[$rname]->name
= $rname;