3 /// Bulk user registration script from a comma separated file
4 /// Returns list of users with their user ids
6 require_once('../config.php');
7 require_once($CFG->libdir
.'/adminlib.php');
8 require_once('uploaduser_form.php');
10 admin_externalpage_setup('uploadusers');
12 require_capability('moodle/site:uploadusers', get_context_instance(CONTEXT_SYSTEM
));
14 if (! $site = get_site()) {
15 error("Could not find site-level course");
18 if (!$adminuser = get_admin()) {
19 error("Could not find site admin");
22 $struser = get_string('user');
23 $strusersnew = get_string('usersnew');
25 $csv_encode = '/\&\#44/';
26 if (isset($CFG->CSV_DELIMITER
)) {
27 $csv_delimiter = '\\' . $CFG->CSV_DELIMITER
;
28 $csv_delimiter2 = $CFG->CSV_DELIMITER
;
30 if (isset($CFG->CSV_ENCODE
)) {
31 $csv_encode = '/\&\#' . $CFG->CSV_ENCODE
. '/';
34 $csv_delimiter = "\,";
35 $csv_delimiter2 = ",";
40 admin_externalpage_print_header();
42 $mform = new admin_uploaduser_form();
44 /// If a file has been uploaded, then process it
46 if ( $formdata = $mform->get_data() ) {
48 $createpassword = $formdata->createpassword
;
49 $updateaccounts = $formdata->updateaccounts
;
50 $allowrenames = $formdata->allowrenames
;
52 $filename = $mform->get_userfile_name();
54 // Large files are likely to take their time and memory. Let PHP know
55 // that we'll take longer, and that the process should be recycled soon
58 @raise_memory_limit
("192M");
59 if (function_exists('apache_child_terminate')) {
60 @apache_child_terminate
();
63 $text = my_file_get_contents($filename);
65 $textlib = new textlib();
66 $text = $textlib->trim_utf8_bom($text);
67 //Fix mac/dos newlines
68 $text = preg_replace('!\r\n?!',"\n",$text);
69 $fp = fopen($filename, "w");
73 $fp = fopen($filename, "r");
75 // make arrays of valid fields for error checking
76 $required = array("username" => 1,
77 "password" => !$createpassword,
81 $optionalDefaults = array("mnethostid" => 1,
89 $optional = array("idnumber" => 1,
122 "password" => $createpassword,
123 "oldusername" => $allowrenames,
126 // --- get header (field names) ---
127 $header = split($csv_delimiter, fgets($fp,1024));
128 // check for valid field names
129 foreach ($header as $i => $h) {
130 $h = trim($h); $header[$i] = $h; // remove whitespace
131 if (!(isset($required[$h]) or isset($optionalDefaults[$h]) or isset($optional[$h]))) {
132 error(get_string('invalidfieldname', 'error', $h), 'uploaduser.php?sesskey='.$USER->sesskey
);
134 if (isset($required[$h])) {
138 // check for required fields
139 foreach ($required as $key => $value) {
140 if ($value) { //required field missing
141 error(get_string('fieldrequired', 'error', $key), 'uploaduser.php?sesskey='.$USER->sesskey
);
144 $linenum = 2; // since header is line 1
152 // Will use this course array a lot
153 // so fetch it early and keep it in memory
154 $courses = get_courses('all','c.sortorder','c.id,c.shortname,c.fullname,c.sortorder,c.teacher,c.visible');
156 while (!feof ($fp)) {
157 foreach ($optionalDefaults as $key => $value) {
158 $user->$key = addslashes($adminuser->$key);
160 //Note: commas within a field should be encoded as , (for comma separated csv files)
161 //Note: semicolon within a field should be encoded as ; (for semicolon separated csv files)
162 $line = split($csv_delimiter, fgets($fp,1024));
163 foreach ($line as $key => $value) {
164 //decode encoded commas
165 $record[$header[$key]] = preg_replace($csv_encode,$csv_delimiter2,trim($value));
167 if ($record[$header[0]]) {
168 // add a new user to the database
170 // add fields to object $user
171 foreach ($record as $name => $value) {
172 // check for required values
173 if (isset($required[$name]) and !$value) {
174 error(get_string('missingfield', 'error', $name). " ".
175 get_string('erroronline', 'error', $linenum) .". ".
176 get_string('processingstops', 'error'),
177 'uploaduser.php?sesskey='.$USER->sesskey
);
179 // password needs to be encrypted
180 else if ($name == "password" && !empty($value)) {
181 $user->password
= hash_internal_user_password($value);
183 else if ($name == "username") {
184 $user->username
= addslashes(moodle_strtolower($value));
188 $user->{$name} = addslashes($value);
191 $user->confirmed
= 1;
192 $user->timemodified
= time();
194 $username = $user->username
;
195 $addcourse[0] = isset($user->course1
) ?
$user->course1
: NULL;
196 $addcourse[1] = isset($user->course2
) ?
$user->course2
: NULL;
197 $addcourse[2] = isset($user->course3
) ?
$user->course3
: NULL;
198 $addcourse[3] = isset($user->course4
) ?
$user->course4
: NULL;
199 $addcourse[4] = isset($user->course5
) ?
$user->course5
: NULL;
200 $addgroup[0] = isset($user->group1
) ?
$user->group1
: NULL;
201 $addgroup[1] = isset($user->group2
) ?
$user->group2
: NULL;
202 $addgroup[2] = isset($user->group3
) ?
$user->group3
: NULL;
203 $addgroup[3] = isset($user->group4
) ?
$user->group4
: NULL;
204 $addgroup[4] = isset($user->group5
) ?
$user->group5
: NULL;
205 $addtype[0] = isset($user->type1
) ?
$user->type1
: NULL;
206 $addtype[1] = isset($user->type2
) ?
$user->type2
: NULL;
207 $addtype[2] = isset($user->type3
) ?
$user->type3
: NULL;
208 $addtype[3] = isset($user->type4
) ?
$user->type4
: NULL;
209 $addtype[4] = isset($user->type5
) ?
$user->type5
: NULL;
210 $addrole[0] = isset($user->role1
) ?
$user->role1
: NULL;
211 $addrole[1] = isset($user->role2
) ?
$user->role2
: NULL;
212 $addrole[2] = isset($user->role3
) ?
$user->role3
: NULL;
213 $addrole[3] = isset($user->role4
) ?
$user->role4
: NULL;
214 $addrole[4] = isset($user->role5
) ?
$user->role5
: NULL;
216 for ($i=0; $i<5; $i++
) {
219 foreach ($courses as $eachcourse) {
220 for ($i=0; $i<5; $i++
) {
221 if ($eachcourse->shortname
== $addcourse[$i]) {
222 $course[$i] = $eachcourse;
227 // before insert/update, check whether we should be updating
228 // an old record instead
229 if ($allowrenames && !empty($user->oldusername
) ) {
230 $user->oldusername
= moodle_strtolower($user->oldusername
);
231 if ($olduser = get_record('user', 'username', $user->oldusername
, 'mnethostid', $user->mnethostid
)) {
232 if (set_field('user', 'username', $user->username
, 'username', $user->oldusername
)) {
233 notify(get_string('userrenamed', 'admin') . " : $user->oldusername $user->username");
236 notify(get_string('usernotrenamedexists', 'error') . " : $user->oldusername $user->username");
241 notify(get_string('usernotrenamedmissing', 'error') . " : $user->oldusername $user->username");
247 if ($olduser = get_record("user", "username", $username, "mnethostid", $user->mnethostid
)) {
248 if ($updateaccounts) {
249 // Record is being updated
250 $user->id
= $olduser->id
;
251 if (update_record('user', $user)) {
252 notify("$user->id , $user->username ".get_string('useraccountupdated', 'admin'));
255 notify(get_string('usernotupdatederror', 'error', $username));
260 //Record not added - user is already registered
261 //In this case, output userid from previous registration
262 //This can be used to obtain a list of userids for existing users
263 notify("$olduser->id ".get_string('usernotaddedregistered', 'error', $username));
268 if ($user->id
= insert_record("user", $user)) {
269 notify("$struser: $user->id = $user->username");
271 if (empty($user->password
) && $createpassword) {
272 // passwords will be created and sent out on cron
273 insert_record('user_preferences', array( 'userid' => $user->id
,
274 'name' => 'create_password',
276 insert_record('user_preferences', array( 'userid' => $user->id
,
277 'name' => 'auth_forcepasswordchange',
281 // Record not added -- possibly some other error
282 notify(get_string('usernotaddederror', 'error', $username));
287 for ($i=0; $i<5; $i++
) {
288 if ($addcourse[$i] && !$course[$i]) {
289 notify(get_string('unknowncourse', 'error', $addcourse[$i]));
292 for ($i=0; $i<5; $i++
) {
296 notify(get_string('coursegroupunknown','error',$addgroup[$i]));
298 if ($gid = groups_get_group_by_name($course[$i]->id
, $addgroup[$i])) {
301 notify(get_string('groupunknown','error',$addgroup[$i]));
306 for ($i=0; $i<5; $i++
) { /// Enrol into courses if necessary
308 if (isset($addrole[$i])) {
309 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course[$i]->id
);
310 if (!user_can_assign($coursecontext, $addrole[$i])) {
311 notify('--> Can not assign role in course'); //TODO: localize
313 $ret = role_assign($addrole[$i], $user->id
, 0, $coursecontext->id
);
314 } else if (isset($addtype[$i])) {
315 switch ($addtype[$i]) {
317 $ret = add_teacher($user->id
, $course[$i]->id
, 1);
320 case 3: // non-editing teacher
321 $ret = add_teacher($user->id
, $course[$i]->id
, 0);
325 $ret = enrol_student($user->id
, $course[$i]->id
);
329 $ret = enrol_student($user->id
, $course[$i]->id
);
332 notify('-->'. get_string('enrolledincourse', '', $addcourse[$i]));
334 notify('-->'.get_string('enrolledincoursenot', '', $addcourse[$i]));
338 for ($i=0; $i<5; $i++
) { // Add user to groups if necessary
339 if ($course[$i] && $groupid[$i]) {
340 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course[$i]->id
);
341 if (count(get_user_roles($coursecontext, $user->id
))) {
342 if (groups_add_member($groupid[$i], $user->id
)) {
343 notify('-->' . get_string('addedtogroup','',$addgroup[$i]));
345 notify('-->' . get_string('addedtogroupnot','',$addgroup[$i]));
348 notify('-->' . get_string('addedtogroupnotenrolled','',$addgroup[$i]));
357 notify("$strusersnew: $usersnew");
358 notify(get_string('usersupdated', 'admin') . ": $usersupdated");
359 notify(get_string('errors', 'admin') . ": $userserrors");
361 notify(get_string('usersrenamed', 'admin') . ": $renames");
362 notify(get_string('renameerrors', 'admin') . ": $renameerrors");
368 print_heading_with_help(get_string('uploadusers'), 'uploadusers');
372 admin_externalpage_print_footer();
376 function my_file_get_contents($filename, $use_include_path = 0) {
377 /// Returns the file as one big long string
380 $file = @fopen
($filename, "rb", $use_include_path);
382 while (!feof($file)) {
383 $data .= fread($file, 1024);