MDL-10870 A few more fixes to the file.php page's navigation
[moodle-pu.git] / admin / uploaduser.php
blob8a2c91af3e7684eeee067ab222df865f516724dc
1 <?php // $Id$
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 . '/';
33 } else {
34 $csv_delimiter = "\,";
35 $csv_delimiter2 = ",";
38 /// Print the header
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
56 // to free up memory.
57 @set_time_limit(0);
58 @raise_memory_limit("192M");
59 if (function_exists('apache_child_terminate')) {
60 @apache_child_terminate();
63 $text = my_file_get_contents($filename);
64 //trim utf-8 bom
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");
70 fwrite($fp,$text);
71 fclose($fp);
73 $fp = fopen($filename, "r");
75 // make arrays of valid fields for error checking
76 $required = array("username" => 1,
77 "password" => !$createpassword,
78 "firstname" => 1,
79 "lastname" => 1,
80 "email" => 1);
81 $optionalDefaults = array("mnethostid" => 1,
82 "institution" => 1,
83 "department" => 1,
84 "city" => 1,
85 "country" => 1,
86 "lang" => 1,
87 "auth" => 1,
88 "timezone" => 1);
89 $optional = array("idnumber" => 1,
90 "icq" => 1,
91 "phone1" => 1,
92 "phone2" => 1,
93 "address" => 1,
94 "url" => 1,
95 "description" => 1,
96 "mailformat" => 1,
97 "maildisplay" => 1,
98 "htmleditor" => 1,
99 "autosubscribe" => 1,
100 "idnumber" => 1,
101 "icq" => 1,
102 "course1" => 1,
103 "course2" => 1,
104 "course3" => 1,
105 "course4" => 1,
106 "course5" => 1,
107 "group1" => 1,
108 "group2" => 1,
109 "group3" => 1,
110 "group4" => 1,
111 "group5" => 1,
112 "type1" => 1,
113 "type2" => 1,
114 "type3" => 1,
115 "type4" => 1,
116 "type5" => 1,
117 "role1" => 1,
118 "role2" => 1,
119 "role3" => 1,
120 "role4" => 1,
121 "role5" => 1,
122 "password" => $createpassword,
123 "oldusername" => $allowrenames,
124 "emailstop" => 1);
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])) {
135 $required[$h] = 0;
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
146 $usersnew = 0;
147 $usersupdated = 0;
148 $userserrors = 0;
149 $renames = 0;
150 $renameerrors = 0;
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 &#44 (for comma separated csv files)
161 //Note: semicolon within a field should be encoded as &#59 (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));
186 // normal entry
187 else {
188 $user->{$name} = addslashes($value);
191 $user->confirmed = 1;
192 $user->timemodified = time();
193 $linenum++;
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++) {
217 $course[$i]=NULL;
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");
234 $renames++;
235 } else {
236 notify(get_string('usernotrenamedexists', 'error') . " : $user->oldusername $user->username");
237 $renameerrors++;
238 continue;
240 } else {
241 notify(get_string('usernotrenamedmissing', 'error') . " : $user->oldusername $user->username");
242 $renameerrors++;
243 continue;
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'));
253 $usersupdated++;
254 } else {
255 notify(get_string('usernotupdatederror', 'error', $username));
256 $userserrors++;
257 continue;
259 } else {
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));
264 $userserrors++;
267 } else { // new user
268 if ($user->id = insert_record("user", $user)) {
269 notify("$struser: $user->id = $user->username");
270 $usersnew++;
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',
275 'value' => 1));
276 insert_record('user_preferences', array( 'userid' => $user->id,
277 'name' => 'auth_forcepasswordchange',
278 'value' => 1));
280 } else {
281 // Record not added -- possibly some other error
282 notify(get_string('usernotaddederror', 'error', $username));
283 $userserrors++;
284 continue;
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++) {
293 $groupid[$i] = 0;
294 if ($addgroup[$i]) {
295 if (!$course[$i]) {
296 notify(get_string('coursegroupunknown','error',$addgroup[$i]));
297 } else {
298 if ($gid = groups_get_group_by_name($course[$i]->id, $addgroup[$i])) {
299 $groupid[$i] = $gid;
300 } else {
301 notify(get_string('groupunknown','error',$addgroup[$i]));
306 for ($i=0; $i<5; $i++) { /// Enrol into courses if necessary
307 if ($course[$i]) {
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]) {
316 case 2: // teacher
317 $ret = add_teacher($user->id, $course[$i]->id, 1);
318 break;
320 case 3: // non-editing teacher
321 $ret = add_teacher($user->id, $course[$i]->id, 0);
322 break;
324 default: // student
325 $ret = enrol_student($user->id, $course[$i]->id);
326 break;
328 } else {
329 $ret = enrol_student($user->id, $course[$i]->id);
331 if ($ret) { // OK
332 notify('-->'. get_string('enrolledincourse', '', $addcourse[$i]));
333 } else {
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]));
344 } else {
345 notify('-->' . get_string('addedtogroupnot','',$addgroup[$i]));
347 } else {
348 notify('-->' . get_string('addedtogroupnotenrolled','',$addgroup[$i]));
353 unset ($user);
356 fclose($fp);
357 notify("$strusersnew: $usersnew");
358 notify(get_string('usersupdated', 'admin') . ": $usersupdated");
359 notify(get_string('errors', 'admin') . ": $userserrors");
360 if ($allowrenames) {
361 notify(get_string('usersrenamed', 'admin') . ": $renames");
362 notify(get_string('renameerrors', 'admin') . ": $renameerrors");
364 echo '<hr />';
367 /// Print the form
368 print_heading_with_help(get_string('uploadusers'), 'uploadusers');
370 $mform->display();
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
379 $data = "";
380 $file = @fopen($filename, "rb", $use_include_path);
381 if ($file) {
382 while (!feof($file)) {
383 $data .= fread($file, 1024);
385 fclose($file);
387 return $data;