From: toyomoyo ';
- while (!feof ($fp)) {
- $user = new object();
- // by default, use the local mnet id (this may be changed in the file)
- $user->mnethostid = $CFG->mnet_localhost_id;
- $line = explode($csv_delimiter, fgets($fp,LINE_MAX_SIZE));
- ++$linenum;
- $ok = true;
- // add fields to user object
- foreach ($line as $key => $value) {
- if($value !== '') {
- $key = $headers[$key];
- //decode encoded commas
- $value = str_replace($csv_encode,$csv_delimiter,trim($value));
- // special fields: password and username
- if ($key == 'password' && !empty($value)) {
- $user->$key = hash_internal_user_password($value);
- } else if($key == 'username') {
- $user->$key = addslashes($textlib->strtolower($value));
- } else {
- $user->$key = addslashes($value);
+ echo ' ';
+ while (!feof ($fp)) {
+ $errors = '';
+ $user = new object();
+ // by default, use the local mnet id (this may be changed in the file)
+ $user->mnethostid = $CFG->mnet_localhost_id;
+ $line = explode($csv_delimiter, fgets($fp,LINE_MAX_SIZE));
+ ++$linenum;
+ // add fields to user object
+ foreach ($line as $key => $value) {
+ if($value !== '') {
+ $key = $headers[$key];
+ //decode encoded commas
+ $value = str_replace($csv_encode,$csv_delimiter,trim($value));
+ // special fields: password and username
+ if ($key == 'password' && !empty($value)) {
+ $user->$key = hash_internal_user_password($value);
+ } else if($key == 'username') {
+ $value = $textlib->strtolower(addslashes($value));
+ if(empty($CFG->extendedusernamechars)) {
+ $value = eregi_replace('[^(-\.[:alnum:])]', '', $value);
+ }
+ @$newusernames[$value]++;
+ $user->$key = $value;
+ } else {
+ $user->$key = addslashes($value);
+ }
}
}
- }
- // add default values for remaining fields
- foreach ($fields as $key => $value) {
- if(isset($user->$key)) {
- continue;
- }
- if(!isset($formdata->$key) || $formdata->$key==='') { // no default value was submited
- if($value) { // the field is required
- notify(get_string('erroronline', 'error', $linenum). ': ' .get_string('missingfield', 'error', $key));
- $ok = false;
+
+ // add default values for remaining fields
+ foreach ($fields as $key => $required) {
+ if(isset($user->$key)) {
+ continue;
}
- continue;
- }
- // process templates
- $template = $formdata->$key;
- $templatelen = strlen($template);
- $value = '';
- for ($i = 0 ; $i < $templatelen; ++$i) {
- if($template[$i] == '%') {
- $case = 0; // 1=lowercase, 2=uppercase
- $len = 0; // number of characters to keep
- $info = null; // data to process
- for($j = $i + 1; is_null($info) && $j < $templatelen; ++$j) {
- $car = $template[$j];
- if ($car >= '0' && $car <= '9') {
- $len = $len * 10 + (int)$car;
- } else if($car == '-') {
- $case = 1;
- } else if($car == '+') {
- $case = 2;
- } else if($car == 'f') { // first name
- $info = @$user->firstname;
- } else if($car == 'l') { // last name
- $info = @$user->lastname;
- } else if($car == 'u') { // username
- $info = @$user->username;
- } else if($car == '%' && $j == $i+1) {
- $info = '%';
- } else { // invalid character
- $info = '';
- }
+ if(!isset($formdata->$key) || $formdata->$key==='') { // no default value was submited
+ // if the field is required, give an error only if we are adding the user or deleting a user with unkown username
+ if($required && (empty($user->deleted) || $key == 'username')) {
+ $errors .= get_string('missingfield', 'error', $key) . ' ';
}
- if($info==='' || is_null($info)) { // invalid template
- continue;
+ continue;
+ }
+ // process templates
+ $template = $formdata->$key;
+ $templatelen = strlen($template);
+ $value = '';
+ for ($i = 0 ; $i < $templatelen; ++$i) {
+ if($template[$i] == '%') {
+ $case = 0; // 1=lowercase, 2=uppercase
+ $len = 0; // number of characters to keep
+ $info = null; // data to process
+ for($j = $i + 1; is_null($info) && $j < $templatelen; ++$j) {
+ $car = $template[$j];
+ if ($car >= '0' && $car <= '9') {
+ $len = $len * 10 + (int)$car;
+ } else if($car == '-') {
+ $case = 1;
+ } else if($car == '+') {
+ $case = 2;
+ } else if($car == 'f') { // first name
+ $info = @$user->firstname;
+ } else if($car == 'l') { // last name
+ $info = @$user->lastname;
+ } else if($car == 'u') { // username
+ $info = @$user->username;
+ } else if($car == '%' && $j == $i+1) {
+ $info = '%';
+ } else { // invalid character
+ $info = '';
+ }
+ }
+ if($info==='' || is_null($info)) { // invalid template
+ continue;
+ }
+ $i = $j - 1;
+ // change case
+ if($case == 1) {
+ $info = $textlib->strtolower($info);
+ } else if($case == 2) {
+ $info = $textlib->strtoupper($info);
+ }
+ if($len) { // truncate data
+ $info = $textlib->substr($info, 0, $len);
+ }
+ $value .= $info;
+ } else {
+ $value .= $template[$i];
}
- $i = $j - 1;
- // change case
- if($case == 1) {
- $info = $textlib->strtolower($info);
- } else if($case == 2) {
- $info = $textlib->strtoupper($info);
+ }
+
+ if($key == 'username') {
+ $value = $textlib->strtolower($value);
+ if(empty($CFG->extendedusernamechars)) {
+ $value = eregi_replace('[^(-\.[:alnum:])]', '', $value);
}
- if($len) { // truncate data
- $info = $textlib->substr($info, 0, $len);
+ @$newusernames[$value]++;
+ // check for new username duplicates
+ if($newusernames[$value] > 1) {
+ if($skipduplicates) {
+ $errors .= $strduplicateusername . ' (' . stripslashes($value) . '). ';
+ continue;
+ } else {
+ $value .= $newusernames[$value];
+ }
}
- $value .= $info;
- } else {
- $value .= $template[$i];
}
+ $user->$key = $value;
}
-
- if($key == 'username') {
- $value = $textlib->strtolower($value);
- if(empty($CFG->extendedusernamechars)) {
- $value = eregi_replace('[^(-\.[:alnum:])]', '', $value);
- }
- // check for new username duplicates
- if(empty($newusernames[$value])) {
- $newusernames[$value] = 1;
- } else {
- if($skipduplicates) {
- notify($strduplicateusername . ': ' . $value);
- $ok = false;
- continue;
+ if($errors) {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $errors);
+ ++$userserrors;
+ continue;
+ }
+
+ // delete user
+ if(@$user->deleted) {
+ $info = ': ' . stripslashes($user->username) . '. ';
+ if($user =& get_record('user', 'username', $user->username, 'mnethostid', $user->mnethostid)) {
+ $user->timemodified = time();
+ $user->username = addslashes($user->email . $user->timemodified); // Remember it just in case
+ $user->deleted = 1;
+ $user->email = ''; // Clear this field to free it up
+ $user->idnumber = ''; // Clear this field to free it up
+ if (update_record('user', $user)) {
+ // not sure if this is needed. unenrol_student($user->id); // From all courses
+ delete_records('role_assignments', 'userid', $user->id); // unassign all roles
+ // remove all context assigned on this user?
+ echo $struserdeleted . $info . '
';
+ ++$usersdeleted;
} else {
- ++$newusernames[$value];
- $value .= $newusernames[$value];
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotdeletederror . $info);
+ ++$deleteerrors;
}
- }
+ } else {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotdeletedmissing . $info);
+ ++$deleteerrors;
+ }
+ continue;
}
- $user->$key = $value;
- }
- if(!$ok) {
- ++$userserrors;
- continue;
- }
-
- $user->confirmed = 1;
- $user->timemodified = time();
-
- // save the user to the database
- $username = $user->username;
+
+ // save the user to the database
+ $user->confirmed = 1;
+ $user->timemodified = time();
- // before insert/update, check whether we should be updating an old record instead
- if ($allowrenames && !empty($user->oldusername) ) {
- $user->oldusername = $textlib->strtolower($user->oldusername);
- $info = ': ' . $user->oldusername . '-->' . $user->username . '. ';
- if ($olduser = get_record('user', 'username', $user->oldusername, 'mnethostid', $user->mnethostid)) {
- if (set_field('user', 'username', $user->username, 'id', $olduser->id)) {
- echo $struserrenamed . $info;
- $renames++;
+ // before insert/update, check whether we should be updating an old record instead
+ if ($allowrenames && !empty($user->oldusername) ) {
+ $user->oldusername = $textlib->strtolower($user->oldusername);
+ $info = ': ' . stripslashes($user->oldusername) . '-->' . stripslashes($user->username) . '. ';
+ if ($olduser =& get_record('user', 'username', $user->oldusername, 'mnethostid', $user->mnethostid)) {
+ if (set_field('user', 'username', $user->username, 'id', $olduser->id)) {
+ echo $struserrenamed . $info;
+ $renames++;
+ } else {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotrenamedexists . $info);
+ $renameerrors++;
+ continue;
+ }
} else {
- notify($strusernotrenamedexists . $info);
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotrenamedmissing . $info);
$renameerrors++;
continue;
}
- } else {
- notify($strusernotrenamedmissing . $info);
- $renameerrors++;
- continue;
}
- }
- // save the information
- if ($olduser = get_record('user', 'username', $username, 'mnethostid', $user->mnethostid)) {
- $user->id = $olduser->id;
- $info = ': ' . $username .' (ID = ' . $user->id . ')';
- if ($updateaccounts) {
- // Record is being updated
- if (update_record('user', $user)) {
- echo $struserupdated . $info . '
';
- $usersupdated++;
+ // save the information
+ if ($olduser =& get_record('user', 'username', $user->username, 'mnethostid', $user->mnethostid)) {
+ $user->id = $olduser->id;
+ $info = ': ' . stripslashes($user->username) .' (ID = ' . $user->id . ')';
+ if ($updateaccounts) {
+ // Record is being updated
+ if (update_record('user', $user)) {
+ echo $struserupdated . $info . '
';
+ $usersupdated++;
+ } else {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotupdated . $info);
+ $userserrors++;
+ continue;
+ }
} else {
- notify($strusernotupdated . $info);
+ //Record not added - user is already registered
+ //In this case, output userid from previous registration
+ //This can be used to obtain a list of userids for existing users
+ echo $strusernotadded . $info . '
';
$userserrors++;
- continue;
}
- } else {
- //Record not added - user is already registered
- //In this case, output userid from previous registration
- //This can be used to obtain a list of userids for existing users
- echo $strusernotadded . $info . '
';
- $userserrors++;
- }
- } else { // new user
- if ($user->id = insert_record('user', $user)) {
- $info = ': ' . $username .' (ID = ' . $user->id . ')';
- echo $struseradded . $info . '
';
- $usersnew++;
- if (empty($user->password) && $createpassword) {
- // passwords will be created and sent out on cron
- insert_record('user_preferences', array( 'userid' => $user->id, 'name' => 'create_password', 'value' => 1));
- insert_record('user_preferences', array( 'userid' => $user->id, 'name' => 'auth_forcepasswordchange', 'value' => 1));
+ } else { // new user
+ if ($user->id = insert_record('user', $user)) {
+ $info = ': ' . stripslashes($user->username) .' (ID = ' . $user->id . ')';
+ echo $struseradded . $info . '
';
+ $usersnew++;
+ if (empty($user->password) && $createpassword) {
+ // passwords will be created and sent out on cron
+ insert_record('user_preferences', array( 'userid' => $user->id, 'name' => 'create_password', 'value' => 1));
+ insert_record('user_preferences', array( 'userid' => $user->id, 'name' => 'auth_forcepasswordchange', 'value' => 1));
+ }
+ } else {
+ // Record not added -- possibly some other error
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotaddederror . ': ' . stripslashes($user->username));
+ $userserrors++;
+ continue;
}
- } else {
- // Record not added -- possibly some other error
- notify($strusernotaddederror . ': ' . $username);
- $userserrors++;
- continue;
}
- }
- // find course enrolments, groups and roles/types
- for($ncourses = 1; $addcourse = @$user->{'course' . $ncourses}; ++$ncourses) {
- // find course
- if(!$course = @$courses[$addcourse]) {
- notify(get_string('unknowncourse', 'error', $addcourse));
- continue;
- }
- // find role
- if ($addrole = @$user->{'role' . $ncourses}) {
- $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
- if (!$ok = role_assign($addrole, $user->id, 0, $coursecontext->id)) {
- echo $strindent . $strcannotassignrole . '
';
+ // find course enrolments, groups and roles/types
+ for($ncourses = 1; $addcourse = @$user->{'course' . $ncourses}; ++$ncourses) {
+ // find course
+ if(!$course = @$courses[$addcourse]) {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . get_string('unknowncourse', 'error', $addcourse));
+ continue;
}
- } else {
- // if no role, then find "old" enrolment type
- switch ($addtype = @$user->{'type' . $ncourses}) {
- case 2: // teacher
- $ok = add_teacher($user->id, $course->id, 1);
- break;
- case 3: // non-editing teacher
- $ok = add_teacher($user->id, $course->id, 0);
- break;
- case 1: // student
- default:
- $ok = enrol_student($user->id, $course->id);
- break;
+ // find role
+ if ($addrole = @$user->{'role' . $ncourses}) {
+ $coursecontext =& get_context_instance(CONTEXT_COURSE, $course->id);
+ if (!$ok = role_assign($addrole, $user->id, 0, $coursecontext->id)) {
+ echo $strindent . $strcannotassignrole . '
';
+ }
+ } else {
+ // if no role, then find "old" enrolment type
+ switch ($addtype = @$user->{'type' . $ncourses}) {
+ case 2: // teacher
+ $ok = add_teacher($user->id, $course->id, 1);
+ break;
+ case 3: // non-editing teacher
+ $ok = add_teacher($user->id, $course->id, 0);
+ break;
+ case 1: // student
+ default:
+ $ok = enrol_student($user->id, $course->id);
+ break;
+ }
+ }
+ if ($ok) { // OK
+ echo $strindent . get_string('enrolledincourse', '', $addcourse) . '
';
+ } else {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . get_string('enrolledincoursenot', '', $addcourse));
}
- }
- if ($ok) { // OK
- echo $strindent . get_string('enrolledincourse', '', $addcourse) . '
';
- } else {
- notify(get_string('enrolledincoursenot', '', $addcourse));
- }
- // find group to add to
- if ($addgroup = @$user->{'group' . $ncourses}) {
- if ($gid = groups_get_group_by_name($course->id, $addgroup)) {
- $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
- if (count(get_user_roles($coursecontext, $user->id))) {
- if (groups_add_member($gid, $user->id)) {
- echo $strindent . get_string('addedtogroup','',$addgroup) . '
';
+ // find group to add to
+ if ($addgroup = @$user->{'group' . $ncourses}) {
+ if ($gid =& groups_get_group_by_name($course->id, $addgroup)) {
+ $coursecontext =& get_context_instance(CONTEXT_COURSE, $course->id);
+ if (count(get_user_roles($coursecontext, $user->id))) {
+ if (groups_add_member($gid, $user->id)) {
+ echo $strindent . get_string('addedtogroup','',$addgroup) . '
';
+ } else {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . get_string('addedtogroupnot','',$addgroup));
+ }
} else {
- notify(get_string('addedtogroupnot','',$addgroup));
+ notify(get_string('erroronline', 'error', $linenum). ': ' . get_string('addedtogroupnotenrolled','',$addgroup));
}
} else {
- notify(get_string('addedtogroupnotenrolled','',$addgroup));
+ notify(get_string('erroronline', 'error', $linenum). ': ' . get_string('groupunknown','error',$addgroup));
}
- } else {
- notify(get_string('groupunknown','error',$addgroup));
}
}
}
+ echo '
Required fieldnames: these fields must be included in the first record, and defined for each user
-+
firstname, lastname
firstname, lastname
Optional fieldnames: all of these are completely optional. If a values is present for the field in the file, then that value is used; else, the default value for that field is used.
-+
institution, department, city, country, lang, auth, timezone, idnumber, icq, phone1, phone2, address, url, description, mailformat, maildisplay, htmleditor, autosubscribe, emailstop
institution, department, city, country, lang, auth, timezone, idnumber, icq, phone1, phone2, address, url, description, mailformat, maildisplay, htmleditor, autosubscribe, emailstop, deleted
Enrolment fieldnames (optional): The course names are the "shortnames" of the courses - if present then the user will be enrolled in those courses. For groups use group name; for roles use id. Group names must be associated to the corresponding courses, i.e. group1 to course1, etc.
-+
course1, group1, type1, role1, course2, group2, type2, role2, etc.
course1, group1, type1, role1, course2, group2, type2, role2, etc.
The CSV file may contain full informations for some users and use default values for others (use extra commas to corectly associate data to headers). For example, the following file will use default values for username, city and country for user Trent Reznor:
+username, password, firstname, lastname, country, city
+jonest, verysecret, Tom, Jones, RO, Constanta
+, somesecret, Trent, Reznor, ,
+
The default values are processed as templates in which the following codes are allowed:
@@ -54,7 +59,7 @@ reznort, somesecret, Trent, Reznor, reznort@someplace.edu, en_us, 6736733, 0, AdTemplate processing is done only on default values, and not on the values retrieved from the CSV file.
In order to create corect Moodle usernames, the username is always converted to lowercase. Moreover, if the "Allow extended characters in usernames" option in the Site policies page is off, characters different to letters, digits, dash (-) and dot (.) are removed. -For example if the firstname is John Jr. and the lastname is Doe, the username %-f%-l will produce john jr.doe when Allow extended characters in usernames is on, and johnjr.doe when off (notice the extra space).
+For example if the firstname is John Jr. and the lastname is Doe, the username %-f_%-l will produce john jr._doe when Allow extended characters in usernames is on, and johnjr.doe when off.When the "New username duplicate handling" setting is set to Append counter, an auto-increment counter will be append to duplicate usernames produced by the template. For example, if the CSV file contains the users named John Doe, Jane Doe and Jenny Doe without explicit usernames, the default username is %-1f%-l and New username duplicate handling is set to Append counter, then the usernames produced will be jdoe, jdoe2 and jdoe3.
@@ -63,6 +68,14 @@ For example, if the CSV file contains the users named John Doe, Jane Doe and JenBy default Moodle assumes that you will be creating new user accounts, and skips records where the username matches an existing account. However, if you set "Update existing accounts" to Yes, the existing user account will be updated.
-When updating existing accounts you can change usernames as well. Set "Allow renames" to Yes and include in your file a field called oldusername
.
When updating existing accounts you can change usernames as well. Set "Allow renames" to Yes and include in your file a field called oldusername
.
Warning: any errors updating existing accounts can affect your users badly. Be careful when using the options to update.
+ +If the deleted
field is present, users with value 1 for it will be deleted. In this case, all the fields may be omitted, except for username
(which should be present in the CSV file, or a default value for it should be available).
Deleting and uploading accounts could be done with a single CSV file. For example, the following file will add the user Tom Jones and delete the user reznort:
+username, firstname, lastname, deleted
+jonest, Tom, Jones, 0
+reznort, , , 1
+