2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Bulk user registration script from a comma separated file
22 * @copyright 2004 onwards Martin Dougiamas (http://dougiamas.com)
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 require('../config.php');
27 require_once($CFG->libdir.'/adminlib.php');
28 require_once($CFG->libdir.'/csvlib.class.php');
29 require_once($CFG->dirroot.'/user/profile/lib.php');
30 require_once($CFG->dirroot.'/group/lib.php');
31 require_once($CFG->dirroot.'/cohort/lib.php');
32 require_once('uploaduserlib.php');
33 require_once('uploaduser_form.php');
35 $iid = optional_param('iid', '', PARAM_INT);
36 $previewrows = optional_param('previewrows', 10, PARAM_INT);
38 @set_time_limit(60*60); // 1 hour should be enough
39 raise_memory_limit(MEMORY_HUGE);
42 admin_externalpage_setup('uploadusers');
43 require_capability('moodle/site:uploadusers', get_context_instance(CONTEXT_SYSTEM));
45 $struserrenamed = get_string('userrenamed', 'admin');
46 $strusernotrenamedexists = get_string('usernotrenamedexists', 'error');
47 $strusernotrenamedmissing = get_string('usernotrenamedmissing', 'error');
48 $strusernotrenamedoff = get_string('usernotrenamedoff', 'error');
49 $strusernotrenamedadmin = get_string('usernotrenamedadmin', 'error');
51 $struserupdated = get_string('useraccountupdated', 'admin');
52 $strusernotupdated = get_string('usernotupdatederror', 'error');
53 $strusernotupdatednotexists = get_string('usernotupdatednotexists', 'error');
54 $strusernotupdatedadmin = get_string('usernotupdatedadmin', 'error');
56 $struseruptodate = get_string('useraccountuptodate', 'admin');
58 $struseradded = get_string('newuser');
59 $strusernotadded = get_string('usernotaddedregistered', 'error');
60 $strusernotaddederror = get_string('usernotaddederror', 'error');
62 $struserdeleted = get_string('userdeleted', 'admin');
63 $strusernotdeletederror = get_string('usernotdeletederror', 'error');
64 $strusernotdeletedmissing = get_string('usernotdeletedmissing', 'error');
65 $strusernotdeletedoff = get_string('usernotdeletedoff', 'error');
66 $strusernotdeletedadmin = get_string('usernotdeletedadmin', 'error');
68 $strcannotassignrole = get_string('cannotassignrole', 'error');
70 $struserauthunsupported = get_string('userauthunsupported', 'error');
71 $stremailduplicate = get_string('useremailduplicate', 'error');
73 $strinvalidpasswordpolicy = get_string('invalidpasswordpolicy', 'error');
74 $errorstr = get_string('error');
76 $returnurl = new moodle_url('/admin/uploaduser.php');
77 $bulknurl = new moodle_url('/admin/user/user_bulk.php');
80 $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
82 // array of all valid fields for validation
83 $STD_FIELDS = array('id', 'firstname', 'lastname', 'username', 'email',
84 'city', 'country', 'lang', 'timezone', 'mailformat',
85 'maildisplay', 'maildigest', 'htmleditor', 'ajax', 'autosubscribe',
86 'institution', 'department', 'idnumber', 'skype',
87 'msn', 'aim', 'yahoo', 'icq', 'phone1', 'phone2', 'address',
88 'url', 'description', 'descriptionformat', 'password',
89 'auth', // watch out when changing auth type or using external auth plugins!
90 'oldusername', // use when renaming users - this is the original username
91 'deleted', // 1 means delete user
94 $PRF_FIELDS = array();
96 if ($prof_fields = $DB->get_records('user_info_field')) {
97 foreach ($prof_fields as $prof_field) {
98 $PRF_FIELDS[] = 'profile_field_'.$prof_field->shortname;
104 $mform1 = new admin_uploaduser_form1();
106 if ($formdata = $mform1->get_data()) {
107 $iid = csv_import_reader::get_new_iid('uploaduser');
108 $cir = new csv_import_reader($iid, 'uploaduser');
110 $content = $mform1->get_file_content('userfile');
112 $readcount = $cir->load_csv_content($content, $formdata->encoding, $formdata->delimiter_name);
115 if ($readcount === false) {
116 print_error('csvloaderror', '', $returnurl);
117 } else if ($readcount == 0) {
118 print_error('csvemptyfile', 'error', $returnurl);
120 // test if columns ok
121 $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
125 echo $OUTPUT->header();
127 echo $OUTPUT->heading_with_help(get_string('uploadusers', 'admin'), 'uploadusers', 'admin');
130 echo $OUTPUT->footer();
134 $cir = new csv_import_reader($iid, 'uploaduser');
135 $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
138 $mform2 = new admin_uploaduser_form2(null, array('columns'=>$filecolumns, 'data'=>array('iid'=>$iid, 'previewrows'=>$previewrows)));
140 // If a file has been uploaded, then process it
141 if ($formdata = $mform2->is_cancelled()) {
143 redirect($returnurl);
145 } else if ($formdata = $mform2->get_data()) {
147 echo $OUTPUT->header();
148 echo $OUTPUT->heading(get_string('uploadusersresult', 'admin'));
150 $optype = $formdata->uutype;
152 $updatetype = isset($formdata->uuupdatetype) ? $formdata->uuupdatetype : 0;
153 $createpasswords = (!empty($formdata->uupasswordnew) and $optype != UU_USER_UPDATE);
154 $updatepasswords = (!empty($formdata->uupasswordold) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC and ($updatetype == UU_UPDATE_FILEOVERRIDE or $updatetype == UU_UPDATE_ALLOVERRIDE));
155 $allowrenames = (!empty($formdata->uuallowrenames) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
156 $allowdeletes = (!empty($formdata->uuallowdeletes) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
157 $bulk = $formdata->uubulk;
158 $noemailduplicates = $formdata->uunoemailduplicates;
159 $standardusernames = $formdata->uustandardusernames;
160 $resetpasswords = isset($formdata->uuforcepasswordchange) ? $formdata->uuforcepasswordchange : UU_PWRESET_NONE;
162 // verification moved to two places: after upload and into form2
165 $usersuptodate = 0; //not printed yet anywhere
175 $ccache = array(); // course cache - do not fetch all courses here, we will not probably use them all anyway!
177 $rolecache = uu_allowed_roles_cache(); // roles lookup cache
178 $manualcache = array(); // cache of used manual enrol plugins in each course
179 $supportedauths = uu_supported_auths(); // officially supported plugins that are enabled
181 // we use only manual enrol plugin here, if it is disabled no enrol is done
182 if (enrol_is_enabled('manual')) {
183 $manual = enrol_get_plugin('manual');
188 // clear bulk selection
190 $SESSION->bulk_users = array();
193 // init csv import helper
195 $linenum = 1; //column header is first line
197 // init upload progress tracker
198 $upt = new uu_progress_tracker();
199 $upt->start(); // start table
201 while ($line = $cir->next()) {
205 $upt->track('line', $linenum);
207 $user = new stdClass();
209 // add fields to user object
210 foreach ($line as $keynum => $value) {
211 if (!isset($filecolumns[$keynum])) {
212 // this should not happen
215 $key = $filecolumns[$keynum];
216 if (strpos($key, 'profile_field_') === 0) {
217 //NOTE: bloody mega hack alert!!
218 if (isset($USER->$key) and is_array($USER->$key)) {
219 // this must be some hacky field that is abusing arrays to store content and format
220 $user->$key = array();
221 $user->$key['text'] = $value;
222 $user->$key['format'] = FORMAT_MOODLE;
224 $user->$key = $value;
227 $user->$key = $value;
230 if (in_array($key, $upt->columns)) {
231 // default value in progress tracking table, can be changed later
232 $upt->track($key, s($value), 'normal');
235 if (!isset($user->username)) {
236 // prevent warnings bellow
237 $user->username = '';
240 if ($optype == UU_USER_ADDNEW or $optype == UU_USER_ADDINC) {
241 // user creation is a special case - the username may be constructed from templates using firstname and lastname
242 // better never try this in mixed update types
244 if (!isset($user->firstname) or $user->firstname === '') {
245 $upt->track('status', get_string('missingfield', 'error', 'firstname'), 'error');
246 $upt->track('firstname', $errorstr, 'error');
249 if (!isset($user->lastname) or $user->lastname === '') {
250 $upt->track('status', get_string('missingfield', 'error', 'lastname'), 'error');
251 $upt->track('lastname', $errorstr, 'error');
258 // we require username too - we might use template for it though
259 if (empty($user->username) and !empty($formdata->username)) {
260 $user->username = uu_process_template($formdata->username, $user);
261 $upt->track('username', s($user->username));
265 // normalize username
266 $originalusername = $user->username;
267 if ($standardusernames) {
268 $user->username = clean_param($user->username, PARAM_USERNAME);
271 // make sure we really have username
272 if (empty($user->username)) {
273 $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
274 $upt->track('username', $errorstr, 'error');
277 } else if ($user->username === 'guest') {
278 $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
283 if ($existinguser = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$CFG->mnet_localhost_id))) {
284 $upt->track('id', $existinguser->id, 'normal', false);
287 // find out in username incrementing required
288 if ($existinguser and $optype == UU_USER_ADDINC) {
289 $user->username = uu_increment_username($user->username);
290 $existinguser = false;
293 // notify about nay username changes
294 if ($originalusername !== $user->username) {
295 $upt->track('username', '', 'normal', false); // clear previous
296 $upt->track('username', s($originalusername).'-->'.s($user->username), 'info');
298 $upt->track('username', s($user->username), 'normal', false);
301 // add default values for remaining fields
302 $formdefaults = array();
303 foreach ($STD_FIELDS as $field) {
304 if (isset($user->$field)) {
307 // all validation moved to form2
308 if (isset($formdata->$field)) {
310 $user->$field = uu_process_template($formdata->$field, $user);
311 $formdefaults[$field] = true;
312 if (in_array($field, $upt->columns)) {
313 $upt->track($field, s($user->$field), 'normal');
317 foreach ($PRF_FIELDS as $field) {
318 if (isset($user->$field)) {
321 if (isset($formdata->$field)) {
323 $user->$field = uu_process_template($formdata->$field, $user);
324 $formdefaults[$field] = true;
329 if (!empty($user->deleted)) {
330 if (!$allowdeletes) {
332 $upt->track('status', $strusernotdeletedoff, 'warning');
336 if (is_siteadmin($existinguser->id)) {
337 $upt->track('status', $strusernotdeletedadmin, 'error');
341 if (delete_user($existinguser)) {
342 $upt->track('status', $struserdeleted);
345 $upt->track('status', $strusernotdeletederror, 'error');
349 $upt->track('status', $strusernotdeletedmissing, 'error');
354 // we do not need the deleted flag anymore
355 unset($user->deleted);
357 // renaming requested?
358 if (!empty($user->oldusername) ) {
359 if (!$allowrenames) {
361 $upt->track('status', $strusernotrenamedoff, 'warning');
366 $upt->track('status', $strusernotrenamedexists, 'error');
371 if ($user->username === 'guest') {
372 $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
377 if ($standardusernames) {
378 $oldusername = clean_param($user->oldusername, PARAM_USERNAME);
380 $oldusername = $user->oldusername;
383 // no guessing when looking for old username, it must be exact match
384 if ($olduser = $DB->get_record('user', array('username'=>$oldusername, 'mnethostid'=>$CFG->mnet_localhost_id))) {
385 $upt->track('id', $olduser->id, 'normal', false);
386 if (is_siteadmin($olduser->id)) {
387 $upt->track('status', $strusernotrenamedadmin, 'error');
391 $DB->set_field('user', 'username', $user->username, array('id'=>$olduser->id));
392 $upt->track('username', '', 'normal', false); // clear previous
393 $upt->track('username', s($oldusername).'-->'.s($user->username), 'info');
394 $upt->track('status', $struserrenamed);
397 $upt->track('status', $strusernotrenamedmissing, 'error');
401 $existinguser = $olduser;
402 $existinguser->username = $user->username;
405 // can we process with update or insert?
411 $upt->track('status', $strusernotadded, 'warning');
418 //this should not happen!
419 $upt->track('status', $strusernotaddederror, 'error');
425 case UU_USER_ADD_UPDATE:
429 if (!$existinguser) {
431 $upt->track('status', $strusernotupdatednotexists, 'warning');
446 $user->id = $existinguser->id;
448 $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id'=>$existinguser->id)), s($existinguser->username)), 'normal', false);
450 if (is_siteadmin($user->id)) {
451 $upt->track('status', $strusernotupdatedadmin, 'error');
456 $existinguser->timemodified = time();
457 // do NOT mess with timecreated or firstaccess here!
459 //load existing profile data
460 profile_load_data($existinguser);
462 $upt->track('auth', $existinguser->auth, 'normal', false);
466 if ($updatetype != UU_UPDATE_NOCHANGES) {
467 if (!empty($user->auth) and $user->auth !== $existinguser->auth) {
468 $upt->track('auth', s($existinguser->auth).'-->'.s($user->auth), 'info', false);
469 $existinguser->auth = $user->auth;
470 if (!isset($supportedauths[$user->auth])) {
471 $upt->track('auth', $struserauthunsupported, 'warning');
475 $allcolumns = array_merge($STD_FIELDS, $PRF_FIELDS);
476 foreach ($allcolumns as $column) {
477 if ($column === 'username' or $column === 'password' or $column === 'auth') {
478 // these can not be changed here
481 if (!property_exists($user, $column) or !property_exists($existinguser, $column)) {
482 // this should never happen
485 if ($updatetype == UU_UPDATE_MISSING) {
486 if (!is_null($existinguser->$column) and $existinguser->$column !== '') {
489 } else if ($updatetype == UU_UPDATE_ALLOVERRIDE) {
490 // we override everything
492 } else if ($updatetype == UU_UPDATE_FILEOVERRIDE) {
493 if (!empty($formdefaults[$column])) {
494 // do not override with form defaults
498 if ($existinguser->$column !== $user->$column) {
499 if ($column === 'email') {
500 if ($DB->record_exists('user', array('email'=>$user->email))) {
501 if ($noemailduplicates) {
502 $upt->track('email', $stremailduplicate, 'error');
503 $upt->track('status', $strusernotupdated, 'error');
507 $upt->track('email', $stremailduplicate, 'warning');
510 if (!validate_email($user->email)) {
511 $upt->track('email', get_string('invalidemail'), 'warning');
515 if (in_array($column, $upt->columns)) {
516 $upt->track($column, s($existinguser->$column).'-->'.s($user->$column), 'info', false);
518 $existinguser->$column = $user->$column;
525 $auth = get_auth_plugin($existinguser->auth);
526 } catch (Exception $e) {
527 $upt->track('auth', get_string('userautherror', 'error', s($existinguser->auth)), 'error');
528 $upt->track('status', $strusernotupdated, 'error');
532 $isinternalauth = $auth->is_internal();
534 // changing of passwords is a special case
535 // do not force password changes for external auth plugins!
536 $oldpw = $existinguser->password;
537 if (!$isinternalauth) {
538 $existinguser->password = 'not cached';
539 $upt->track('password', '-', 'normal', false);
541 unset_user_preference('create_password', $existinguser);
542 unset_user_preference('auth_forcepasswordchange', $existinguser);
544 } else if (!empty($user->password)) {
545 if ($updatepasswords) {
547 $weak = !check_password_policy($user->password, $errmsg);
548 if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
551 $upt->track('password', $strinvalidpasswordpolicy, 'warning');
553 set_user_preference('auth_forcepasswordchange', 1, $existinguser);
555 unset_user_preference('auth_forcepasswordchange', $existinguser);
557 unset_user_preference('create_password', $existinguser); // no need to create password any more
558 $existinguser->password = hash_internal_user_password($user->password);
559 $upt->track('password', $user->password, 'normal', false);
561 // do not print password when not changed
562 $upt->track('password', '', 'normal', false);
566 if ($doupdate or $existinguser->password !== $oldpw) {
567 // we want only users that were really updated
569 $DB->update_record('user', $existinguser);
571 $upt->track('status', $struserupdated);
573 // save custom profile fields data from csv file
574 profile_save_data($existinguser);
576 events_trigger('user_updated', $existinguser);
578 if ($bulk == UU_BULK_UPDATED or $bulk == UU_BULK_ALL) {
579 if (!in_array($user->id, $SESSION->bulk_users)) {
580 $SESSION->bulk_users[] = $user->id;
585 // no user information changed
586 $upt->track('status', $struseruptodate);
589 if ($bulk == UU_BULK_ALL) {
590 if (!in_array($user->id, $SESSION->bulk_users)) {
591 $SESSION->bulk_users[] = $user->id;
597 // save the new user to the database
598 $user->confirmed = 1;
599 $user->timemodified = time();
600 $user->timecreated = time();
601 $user->mnethostid = $CFG->mnet_localhost_id; // we support ONLY local accounts here, sorry
603 if (empty($user->auth)) {
604 $user->auth = 'manual';
606 $upt->track('auth', $user->auth, 'normal', false);
608 // do not insert record if new auth plugin does not exist!
610 $auth = get_auth_plugin($user->auth);
611 } catch (Exception $e) {
612 $upt->track('auth', get_string('userautherror', 'error', s($user->auth)), 'error');
613 $upt->track('status', $strusernotaddederror, 'error');
617 if (!isset($supportedauths[$user->auth])) {
618 $upt->track('auth', $struserauthunsupported, 'warning');
621 $isinternalauth = $auth->is_internal();
623 if (empty($user->email)) {
624 $upt->track('email', get_string('invalidemail'), 'error');
625 $upt->track('status', $strusernotaddederror, 'error');
629 } else if ($DB->record_exists('user', array('email'=>$user->email))) {
630 if ($noemailduplicates) {
631 $upt->track('email', $stremailduplicate, 'error');
632 $upt->track('status', $strusernotaddederror, 'error');
636 $upt->track('email', $stremailduplicate, 'warning');
639 if (!validate_email($user->email)) {
640 $upt->track('email', get_string('invalidemail'), 'warning');
643 $forcechangepassword = false;
645 if ($isinternalauth) {
646 if (empty($user->password)) {
647 if ($createpasswords) {
648 $user->password = 'to be generated';
649 $upt->track('password', '', 'normal', false);
650 $upt->track('password', get_string('uupasswordcron', 'admin'), 'warning', false);
652 $upt->track('password', '', 'normal', false);
653 $upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
654 $upt->track('status', $strusernotaddederror, 'error');
660 $weak = !check_password_policy($user->password, $errmsg);
661 if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
664 $upt->track('password', $strinvalidpasswordpolicy, 'warning');
666 $forcechangepassword = true;
668 $user->password = hash_internal_user_password($user->password);
671 $user->password = 'not cached';
672 $upt->track('password', '-', 'normal', false);
675 // create user - insert_record ignores any extra properties
676 $user->id = $DB->insert_record('user', $user);
677 $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id'=>$user->id)), s($user->username)), 'normal', false);
679 // save custom profile fields data
680 profile_save_data($user);
682 if ($forcechangepassword) {
683 set_user_preference('auth_forcepasswordchange', 1, $user);
685 if ($user->password === 'to be generated') {
686 set_user_preference('create_password', 1, $user);
689 $upt->track('status', $struseradded);
690 $upt->track('id', $user->id, 'normal', false);
693 // make sure user context exists
694 get_context_instance(CONTEXT_USER, $user->id);
696 events_trigger('user_created', $user);
698 if ($bulk == UU_BULK_NEW or $bulk == UU_BULK_ALL) {
699 if (!in_array($user->id, $SESSION->bulk_users)) {
700 $SESSION->bulk_users[] = $user->id;
706 // add to cohort first, it might trigger enrolments indirectly - do NOT create cohorts here!
707 foreach ($filecolumns as $column) {
708 if (!preg_match('/^cohort\d+$/', $column)) {
712 if (!empty($user->$column)) {
713 $addcohort = $user->$column;
714 if (!isset($cohorts[$addcohort])) {
715 if (is_number($addcohort)) {
716 // only non-numeric idnumbers!
717 $cohort = $DB->get_record('cohort', array('id'=>$addcohort));
719 $cohort = $DB->get_record('cohort', array('idnumber'=>$addcohort));
722 if (empty($cohort)) {
723 $cohorts[$addcohort] = get_string('unknowncohort', 'core_cohort', s($addcohort));
724 } else if (!empty($cohort->component)) {
725 // cohorts synchronised with external sources must not be modified!
726 $cohorts[$addcohort] = get_string('external', 'core_cohort');
728 $cohorts[$addcohort] = $cohort;
732 if (is_object($cohorts[$addcohort])) {
733 $cohort = $cohorts[$addcohort];
734 if (!$DB->record_exists('cohort_members', array('cohortid'=>$cohort->id, 'userid'=>$user->id))) {
735 cohort_add_member($cohort->id, $user->id);
736 // we might add special column later, for now let's abuse enrolments
737 $upt->track('enrolments', get_string('useradded', 'core_cohort', s($cohort->name)));
741 $upt->track('enrolments', $cohorts[$addcohort], 'error');
747 // find course enrolments, groups, roles/types and enrol periods
748 // this is again a special case, we always do this for any updated or created users
749 foreach ($filecolumns as $column) {
750 if (!preg_match('/^course\d+$/', $column)) {
753 $i = substr($column, 6);
755 if (empty($user->{'course'.$i})) {
758 $shortname = $user->{'course'.$i};
759 if (!array_key_exists($shortname, $ccache)) {
760 if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname')) {
761 $upt->track('enrolments', get_string('unknowncourse', 'error', s($shortname)), 'error');
764 $ccache[$shortname] = $course;
765 $ccache[$shortname]->groups = null;
767 $courseid = $ccache[$shortname]->id;
768 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
769 if (!isset($manualcache[$courseid])) {
770 $manualcache[$courseid] = false;
772 if ($instances = enrol_get_instances($courseid, false)) {
773 foreach ($instances as $instance) {
774 if ($instance->enrol === 'manual') {
775 $manualcache[$courseid] = $instance;
783 if ($manual and $manualcache[$courseid]) {
787 if (!empty($user->{'role'.$i})) {
788 $addrole = $user->{'role'.$i};
789 if (array_key_exists($addrole, $rolecache)) {
790 $rid = $rolecache[$addrole]->id;
792 $upt->track('enrolments', get_string('unknownrole', 'error', s($addrole)), 'error');
796 } else if (!empty($user->{'type'.$i})) {
797 // if no role, then find "old" enrolment type
798 $addtype = $user->{'type'.$i};
799 if ($addtype < 1 or $addtype > 3) {
800 $upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
802 } else if (empty($formdata->{'uulegacy'.$addtype})) {
805 $rid = $formdata->{'uulegacy'.$addtype};
808 // no role specified, use the default from manual enrol plugin
809 $rid = $manualcache[$courseid]->roleid;
815 if (!empty($user->{'enrolperiod'.$i})) {
816 $duration = (int)$user->{'enrolperiod'.$i} * 60*60*24; // convert days to seconds
817 if ($duration > 0) { // sanity check
818 $timeend = $today + $duration;
822 $manual->enrol_user($manualcache[$courseid], $user->id, $rid, $today, $timeend);
825 $a->course = $shortname;
826 $a->role = $rolecache[$rid]->name;
827 $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
831 // find group to add to
832 if (!empty($user->{'group'.$i})) {
833 // make sure user is enrolled into course before adding into groups
834 if (!is_enrolled($coursecontext, $user->id)) {
835 $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group'.$i}), 'error');
839 if (is_null($ccache[$shortname]->groups)) {
840 $ccache[$shortname]->groups = array();
841 if ($groups = groups_get_all_groups($courseid)) {
842 foreach ($groups as $gid=>$group) {
843 $ccache[$shortname]->groups[$gid] = new stdClass();
844 $ccache[$shortname]->groups[$gid]->id = $gid;
845 $ccache[$shortname]->groups[$gid]->name = $group->name;
846 if (!is_numeric($group->name)) { // only non-numeric names are supported!!!
847 $ccache[$shortname]->groups[$group->name] = new stdClass();
848 $ccache[$shortname]->groups[$group->name]->id = $gid;
849 $ccache[$shortname]->groups[$group->name]->name = $group->name;
855 $addgroup = $user->{'group'.$i};
856 if (!array_key_exists($addgroup, $ccache[$shortname]->groups)) {
857 // if group doesn't exist, create it
858 $newgroupdata = new stdClass();
859 $newgroupdata->name = $addgroup;
860 $newgroupdata->courseid = $ccache[$shortname]->id;
861 if ($ccache[$shortname]->groups[$addgroup]->id = groups_create_group($newgroupdata)){
862 $ccache[$shortname]->groups[$addgroup]->name = $newgroupdata->name;
864 $upt->track('enrolments', get_string('unknowngroup', 'error', s($addgroup)), 'error');
868 $gid = $ccache[$shortname]->groups[$addgroup]->id;
869 $gname = $ccache[$shortname]->groups[$addgroup]->name;
872 if (groups_add_member($gid, $user->id)) {
873 $upt->track('enrolments', get_string('addedtogroup', '', s($gname)));
875 $upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
877 } catch (moodle_exception $e) {
878 $upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
884 $upt->close(); // close table
889 echo $OUTPUT->box_start('boxwidthnarrow boxaligncenter generalbox', 'uploadresults');
891 if ($optype != UU_USER_UPDATE) {
892 echo get_string('userscreated', 'admin').': '.$usersnew.'<br />';
894 if ($optype == UU_USER_UPDATE or $optype == UU_USER_ADD_UPDATE) {
895 echo get_string('usersupdated', 'admin').': '.$usersupdated.'<br />';
898 echo get_string('usersdeleted', 'admin').': '.$deletes.'<br />';
899 echo get_string('deleteerrors', 'admin').': '.$deleteerrors.'<br />';
902 echo get_string('usersrenamed', 'admin').': '.$renames.'<br />';
903 echo get_string('renameerrors', 'admin').': '.$renameerrors.'<br />';
906 echo get_string('usersskipped', 'admin').': '.$usersskipped.'<br />';
908 echo get_string('usersweakpassword', 'admin').': '.$weakpasswords.'<br />';
909 echo get_string('errors', 'admin').': '.$userserrors.'</p>';
910 echo $OUTPUT->box_end();
913 echo $OUTPUT->continue_button($bulknurl);
915 echo $OUTPUT->continue_button($returnurl);
917 echo $OUTPUT->footer();
922 echo $OUTPUT->header();
924 echo $OUTPUT->heading(get_string('uploaduserspreview', 'admin'));
926 // NOTE: this is JUST csv processing preview, we must not prevent import from here if there is something in the file!!
927 // this was intended for validation of csv formatting and encoding, not filtering the data!!!!
928 // we definitely must not process the whole file!
930 // preview table data
933 $linenum = 1; //column header is first line
934 while ($linenum <= $previewrows and $fields = $cir->next()) {
937 $rowcols['line'] = $linenum;
938 foreach($fields as $key => $field) {
939 $rowcols[$filecolumns[$key]] = s($field);
941 $rowcols['status'] = array();
943 if (isset($rowcols['username'])) {
944 $stdusername = clean_param($rowcols['username'], PARAM_USERNAME);
945 if ($rowcols['username'] !== $stdusername) {
946 $rowcols['status'][] = get_string('invalidusernameupload');
948 if ($userid = $DB->get_field('user', 'id', array('username'=>$stdusername, 'mnethostid'=>$CFG->mnet_localhost_id))) {
949 $rowcols['username'] = html_writer::link(new moodle_url('/user/profile.php', array('id'=>$userid)), $rowcols['username']);
952 $rowcols['status'][] = get_string('missingusername');
955 if (isset($rowcols['email'])) {
956 if (!validate_email($rowcols['email'])) {
957 $rowcols['status'][] = get_string('invalidemail');
959 if ($DB->record_exists('user', array('email'=>$rowcols['email']))) {
960 $rowcols['status'][] = $stremailduplicate;
964 if (isset($rowcols['city'])) {
965 $rowcols['city'] = trim($rowcols['city']);
966 if (empty($rowcols['city'])) {
967 $rowcols['status'][] = get_string('fieldrequired', 'error', 'city');
971 $rowcols['status'] = implode('<br />', $rowcols['status']);
974 if ($fields = $cir->next()) {
975 $data[] = array_fill(0, count($fields) + 2, '...');
979 $table = new html_table();
980 $table->id = "uupreview";
981 $table->attributes['class'] = 'generaltable';
982 $table->tablealign = 'center';
983 $table->summary = get_string('uploaduserspreview', 'admin');
984 $table->head = array();
985 $table->data = $data;
987 $table->head[] = get_string('uucsvline', 'admin');
988 foreach ($filecolumns as $column) {
989 $table->head[] = $column;
991 $table->head[] = get_string('status');
993 echo html_writer::tag('div', html_writer::table($table), array('class'=>'flexible-wrap'));
998 echo $OUTPUT->footer();