diff --git a/admin/uploaduser.php b/admin/uploaduser.php index 4f357a84d22..6a4d5811b34 100755 --- a/admin/uploaduser.php +++ b/admin/uploaduser.php @@ -1,391 +1,363 @@ -libdir.'/adminlib.php'); -require_once($CFG->dirroot.'/group/lib.php'); +require_once($CFG->libdir.'/textlib.class.php'); require_once('uploaduser_form.php'); +define('LINE_MAX_SIZE', 1024); + +//Note: commas within a field should be encoded as , (for comma separated csv files) +//Note: semicolon within a field should be encoded as ; (for semicolon separated csv files) +$csv_delimiter = isset($CFG->CSV_DELIMITER) ? $CFG->CSV_DELIMITER : ','; +$csv_encode = '' . (isset($CFG->CSV_ENCODE) ? $CFG->CSV_ENCODE : ord($csv_delimiter)); + +@set_time_limit(0); +@raise_memory_limit('192M'); admin_externalpage_setup('uploadusers'); - require_capability('moodle/site:uploadusers', get_context_instance(CONTEXT_SYSTEM)); if (! $site = get_site()) { - error("Could not find site-level course"); + error('Could not find site-level course'); } -if (!$adminuser = get_admin()) { - error("Could not find site admin"); -} +$textlib =& textlib_get_instance(); -$struser = get_string('user'); -$strusersnew = get_string('usersnew'); +$struserrenamed = get_string('userrenamed', 'admin'); +$strusernotrenamedexists = get_string('usernotrenamedexists', 'error'); +$strusernotrenamedmissing = get_string('usernotrenamedmissing', 'error'); -$csv_encode = '/\&\#44/'; -if (isset($CFG->CSV_DELIMITER)) { - $csv_delimiter = '\\' . $CFG->CSV_DELIMITER; - $csv_delimiter2 = $CFG->CSV_DELIMITER; +$struserupdated = get_string('useraccountupdated', 'admin'); +$strusernotupdated = get_string('usernotupdatederror', 'error'); +$strusernotadded = get_string('usernotaddedregistered', 'error'); - if (isset($CFG->CSV_ENCODE)) { - $csv_encode = '/\&\#' . $CFG->CSV_ENCODE . '/'; - } -} else { - $csv_delimiter = "\,"; - $csv_delimiter2 = ","; -} - -/// Print the header - -admin_externalpage_print_header(); +$struseradded = get_string('newuser'); +$strusernotaddederror = get_string('usernotaddederror', 'error'); +$strcannotassignrole = get_string('cannotassignrole', 'error'); +$strduplicateusername = get_string('duplicateusername', 'error'); +$strindent = '-->'; $mform = new admin_uploaduser_form(); -/// If a file has been uploaded, then process it +// Print the header +admin_externalpage_print_header(); + +// If a file has been uploaded, then process it if ( $formdata = $mform->get_data() ) { - $createpassword = $formdata->createpassword; $updateaccounts = $formdata->updateaccounts; $allowrenames = $formdata->allowrenames; - - $filename = $mform->get_userfile_name(); + $skipduplicates = $formdata->duplicatehandling; - // Large files are likely to take their time and memory. Let PHP know - // that we'll take longer, and that the process should be recycled soon - // to free up memory. - @set_time_limit(0); - @raise_memory_limit("192M"); - if (function_exists('apache_child_terminate')) { - @apache_child_terminate(); + // make arrays of valid fields for error checking + // the value associated to each field is: 0 = optional field, 1 = field required either in default values or in data file + $fields = array( + 'firstname' => 1, + 'lastname' => 1, + 'username' => 1, + 'email' => 1, + 'city' => 1, + 'country' => 1, + 'lang' => 1, + 'auth' => 1, + 'timezone' => 1, + 'mailformat' => 1, + 'maildisplay' => 1, + 'htmleditor' => 1, + 'autosubscribe' => 1, + 'mnethostid' => 1, + 'institution' => 0, + 'department' => 0, + 'idnumber' => 0, + 'icq' => 0, + 'phone1' => 0, + 'phone2' => 0, + 'address' => 0, + 'url' => 0, + 'description' => 0, + 'icq' => 0, + 'oldusername' => 0, + 'emailstop' => 1, + 'password' => !$createpassword, + ); + + $fp = fopen($mform->get_userfile_name(), 'r'); + $linenum = 1; // since header is line 1 + // get header (field names) and remove Unicode BOM from first line, if any + $line = explode($csv_delimiter, $textlib->trim_utf8_bom(fgets($fp,LINE_MAX_SIZE))); + // check for valid field names + $headers = array(); + foreach ($line as $key => $value) { + $value = trim($value); // remove whitespace + if (!in_array($value, $fields) && // if not a standard field and not an enrolment field, then we have an error + !preg_match('/^course\d+$/', $value) && !preg_match('/^group\d+$/', $value) && + !preg_match('/^type\d+$/', $value) && !preg_match('/^role\d+$/', $value)) { + error(get_string('invalidfieldname', 'error', $value), 'uploaduser.php?sesskey='.$USER->sesskey); + } + $headers[$key] = $value; } - $text = my_file_get_contents($filename); - //trim utf-8 bom - $textlib = new textlib(); - $text = $textlib->trim_utf8_bom($text); - //Fix mac/dos newlines - $text = preg_replace('!\r\n?!',"\n",$text); - $fp = fopen($filename, "w"); - fwrite($fp,$text); + $usersnew = 0; + $usersupdated = 0; + $userserrors = 0; + $renames = 0; + $renameerrors = 0; + $newusernames = array(); + // We'll need courses a lot, so fetch it early and keep it in memory, indexed by their shortname + $tmp =& get_courses('all','','id,shortname,visible'); + $courses = array(); + foreach ($tmp as $c) { + $courses[$c->shortname] = $c; + } + unset($tmp); + + echo '
';
+ 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);
+ }
+ }
+ }
+ // 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;
+ }
+ 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];
+ }
+ }
+
+ 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;
+ } else {
+ ++$newusernames[$value];
+ $value .= $newusernames[$value];
+ }
+ }
+ }
+ $user->$key = $value;
+ }
+ if(!$ok) {
+ ++$userserrors;
+ continue;
+ }
+
+ $user->confirmed = 1;
+ $user->timemodified = time();
+
+ // save the user to the database
+ $username = $user->username;
+
+ // 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++;
+ } else {
+ notify($strusernotrenamedexists . $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++;
+ } else {
+ notify($strusernotupdated . $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 {
+ // 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 . '
';
+ }
+ } 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('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) . '
';
+ } else {
+ notify(get_string('addedtogroupnot','',$addgroup));
+ }
+ } else {
+ notify(get_string('addedtogroupnotenrolled','',$addgroup));
+ }
+ } else {
+ notify(get_string('groupunknown','error',$addgroup));
+ }
+ }
+ }
+ }
+ echo '
';
+ }
+ $table->head[] = '' .$strtitle . '' . $columnicon;
+ $table->align[] = 'left';
+ }
+
+ foreach($users as $user) {
+ $table->data[] = array (
+ '' . $user->fullname .'',
+ $user->username,
+ $user->email,
+ $user->city,
+ $user->country,
+ $user->lastaccess ? format_time(time() - $user->lastaccess) : $strnever
+ );
+ }
+
+ print_heading("$usercount / $usertotal ".get_string('users'));
+ print_table($table);
+
+ admin_externalpage_print_footer();
+?>
\ No newline at end of file
diff --git a/admin/user/user_bulk_form.php b/admin/user/user_bulk_form.php
index fbe812ec902..d4b40383689 100644
--- a/admin/user/user_bulk_form.php
+++ b/admin/user/user_bulk_form.php
@@ -53,7 +53,7 @@ class user_bulk_form extends moodleform {
}
$obj =& $this->_form->getElement('comment');
$obj->setLabel($comment);
- $obj->setText(get_string('usersfound', 'bulkusers', $count));
+ $obj->setText(get_string('usersfound', 'bulkusers', $count) . ' ' .get_string('usersselected', 'bulkusers', count($SESSION->bulk_susers)));
}
function definition_after_data() {
diff --git a/lang/en_utf8/admin.php b/lang/en_utf8/admin.php
index 47b71cc41be..f4a0707b8d0 100644
--- a/lang/en_utf8/admin.php
+++ b/lang/en_utf8/admin.php
@@ -1,6 +1,7 @@
The first record of the file is special, and contains a list of fieldnames. This defines the format of the rest of the file.
Required fieldnames: these fields must be included in the first record, and defined for each user
-- -
username, password, firstname, lastname, emailDefault fieldnames: these are optional - if they are not included then the values are taken from the primary admin
--
institution, department, city, country, lang, auth, timezoneOptional fieldnames: all of these are completely optional. The course names are the "shortnames" of the courses - if present then the user will be enrolled as students in those courses. Group names must be associated to the corresponding courses, i.e. group1 to course1, etc.
-+
idnumber, icq, phone1, phone2, address, url, description, mailformat, maildisplay, htmleditor, autosubscribe, course1, course2, course3, course4, course5, group1, group2, group3, group4, group5, type1, type2, type3, type4, type5, role1, role2, role3, role4, role5, emailstop+
firstname, lastnameOptional 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, emailstopEnrolment 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.
Here is an example of a valid import file:
username, password, firstname, lastname, email, lang, idnumber, maildisplay, course1, group1, type1
jonest, verysecret, Tom, Jones, jonest@someplace.edu, en, 3663737, 1, Intro101, Section 1, 1
reznort, somesecret, Trent, Reznor, reznort@someplace.edu, en_us, 6736733, 0, Advanced202, Section 3, 3
The default values are processed as templates in which the following codes are allowed:
+%l - will be replaced by the lastname%f - will be replaced by the firstname%u - will be replaced by the username%% - will be replaced by the %Between the percent sign (%) and any code letter (l, f or u) the following modifiers are allowed:
+For example, if the firstname is John and the lastname is Doe, the following values will be obtained with the specified templates:
+Template 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).
+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. +
+By 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.