MDL-41744 Users: Convert key to value in bulk upload
[moodle.git] / admin / tool / uploaduser / index.php
CommitLineData
9e492db0 1<?php
8bdb31ed
PS
2// This file is part of Moodle - http://moodle.org/
3//
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.
8//
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.
13//
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/>.
0a6150ca 16
8bdb31ed
PS
17/**
18 * Bulk user registration script from a comma separated file
19 *
ce15d56d
PS
20 * @package tool
21 * @subpackage uploaduser
8bdb31ed
PS
22 * @copyright 2004 onwards Martin Dougiamas (http://dougiamas.com)
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
0a6150ca 25
ce15d56d 26require('../../../config.php');
cc891abe 27require_once($CFG->libdir.'/adminlib.php');
e4e38544 28require_once($CFG->libdir.'/csvlib.class.php');
29require_once($CFG->dirroot.'/user/profile/lib.php');
bb78e249 30require_once($CFG->dirroot.'/user/lib.php');
59186c92 31require_once($CFG->dirroot.'/group/lib.php');
92b59a56 32require_once($CFG->dirroot.'/cohort/lib.php');
ce15d56d
PS
33require_once('locallib.php');
34require_once('user_form.php');
1ae083e4 35
e4e38544 36$iid = optional_param('iid', '', PARAM_INT);
df7ecfe4 37$previewrows = optional_param('previewrows', 10, PARAM_INT);
066bfbfe 38
8bdb31ed
PS
39@set_time_limit(60*60); // 1 hour should be enough
40raise_memory_limit(MEMORY_HUGE);
0a6150ca 41
ebff4779 42require_login();
ce15d56d 43admin_externalpage_setup('tooluploaduser');
bf006d2c 44require_capability('moodle/site:uploadusers', context_system::instance());
0a6150ca 45
ce15d56d 46$struserrenamed = get_string('userrenamed', 'tool_uploaduser');
e4e38544 47$strusernotrenamedexists = get_string('usernotrenamedexists', 'error');
48$strusernotrenamedmissing = get_string('usernotrenamedmissing', 'error');
49$strusernotrenamedoff = get_string('usernotrenamedoff', 'error');
50$strusernotrenamedadmin = get_string('usernotrenamedadmin', 'error');
51
ce15d56d 52$struserupdated = get_string('useraccountupdated', 'tool_uploaduser');
e4e38544 53$strusernotupdated = get_string('usernotupdatederror', 'error');
54$strusernotupdatednotexists = get_string('usernotupdatednotexists', 'error');
55$strusernotupdatedadmin = get_string('usernotupdatedadmin', 'error');
56
ce15d56d 57$struseruptodate = get_string('useraccountuptodate', 'tool_uploaduser');
8bdb31ed 58
e4e38544 59$struseradded = get_string('newuser');
60$strusernotadded = get_string('usernotaddedregistered', 'error');
61$strusernotaddederror = get_string('usernotaddederror', 'error');
62
ce15d56d 63$struserdeleted = get_string('userdeleted', 'tool_uploaduser');
e4e38544 64$strusernotdeletederror = get_string('usernotdeletederror', 'error');
65$strusernotdeletedmissing = get_string('usernotdeletedmissing', 'error');
66$strusernotdeletedoff = get_string('usernotdeletedoff', 'error');
67$strusernotdeletedadmin = get_string('usernotdeletedadmin', 'error');
68
69$strcannotassignrole = get_string('cannotassignrole', 'error');
e4e38544 70
71$struserauthunsupported = get_string('userauthunsupported', 'error');
3fe2cfb5 72$stremailduplicate = get_string('useremailduplicate', 'error');
e4e38544 73
3f12c146 74$strinvalidpasswordpolicy = get_string('invalidpasswordpolicy', 'error');
e4e38544 75$errorstr = get_string('error');
ca23a9c9 76
08157bfe
PS
77$stryes = get_string('yes');
78$strno = get_string('no');
79$stryesnooptions = array(0=>$strno, 1=>$stryes);
80
ce15d56d 81$returnurl = new moodle_url('/admin/tool/uploaduser/index.php');
8bdb31ed 82$bulknurl = new moodle_url('/admin/user/user_bulk.php');
e4e38544 83
2a6dcb72
PS
84$today = time();
85$today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
86
e4e38544 87// array of all valid fields for validation
6dbcacee 88$STD_FIELDS = array('id', 'firstname', 'lastname', 'username', 'email',
8bdb31ed 89 'city', 'country', 'lang', 'timezone', 'mailformat',
a80b5a0c 90 'maildisplay', 'maildigest', 'htmleditor', 'autosubscribe',
8bdb31ed 91 'institution', 'department', 'idnumber', 'skype',
6dbcacee 92 'msn', 'aim', 'yahoo', 'icq', 'phone1', 'phone2', 'address',
8bdb31ed
PS
93 'url', 'description', 'descriptionformat', 'password',
94 'auth', // watch out when changing auth type or using external auth plugins!
95 'oldusername', // use when renaming users - this is the original username
08157bfe 96 'suspended', // 1 means suspend user account, 0 means activate user account, nothing means keep as is for existing users
8bdb31ed 97 'deleted', // 1 means delete user
9dcae46d 98 'mnethostid', // Can not be used for adding, updating or deleting of users - only for enrolments, groups, cohorts and suspending.
8bdb31ed 99 );
e4e38544 100
101$PRF_FIELDS = array();
102
b650fe6a
RT
103if ($proffields = $DB->get_records('user_info_field')) {
104 foreach ($proffields as $key => $proffield) {
105 $profilefieldname = 'profile_field_'.$proffield->shortname;
106 $PRF_FIELDS[] = $profilefieldname;
107 // Re-index $proffields with key as shortname. This will be
108 // used while checking if profile data is key and needs to be converted (eg. menu profile field)
109 $proffields[$profilefieldname] = $proffield;
110 unset($proffields[$key]);
e4e38544 111 }
e4e38544 112}
113
114if (empty($iid)) {
8bdb31ed 115 $mform1 = new admin_uploaduser_form1();
0a6150ca 116
8bdb31ed 117 if ($formdata = $mform1->get_data()) {
e4e38544 118 $iid = csv_import_reader::get_new_iid('uploaduser');
119 $cir = new csv_import_reader($iid, 'uploaduser');
df7ecfe4 120
8bdb31ed
PS
121 $content = $mform1->get_file_content('userfile');
122
123 $readcount = $cir->load_csv_content($content, $formdata->encoding, $formdata->delimiter_name);
e4e38544 124 unset($content);
df7ecfe4 125
e4e38544 126 if ($readcount === false) {
bd8ee7c1 127 print_error('csvloaderror', '', $returnurl);
e4e38544 128 } else if ($readcount == 0) {
5a2a5331 129 print_error('csvemptyfile', 'error', $returnurl);
ed22a01b 130 }
8bdb31ed
PS
131 // test if columns ok
132 $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
e4e38544 133 // continue to form2
df7ecfe4 134
135 } else {
61ef8f9f 136 echo $OUTPUT->header();
9e492db0 137
ce15d56d 138 echo $OUTPUT->heading_with_help(get_string('uploadusers', 'tool_uploaduser'), 'uploadusers', 'tool_uploaduser');
9e492db0 139
8bdb31ed 140 $mform1->display();
73d6f52f 141 echo $OUTPUT->footer();
df7ecfe4 142 die;
143 }
e4e38544 144} else {
145 $cir = new csv_import_reader($iid, 'uploaduser');
8bdb31ed 146 $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
df7ecfe4 147}
148
8bdb31ed 149$mform2 = new admin_uploaduser_form2(null, array('columns'=>$filecolumns, 'data'=>array('iid'=>$iid, 'previewrows'=>$previewrows)));
df7ecfe4 150
151// If a file has been uploaded, then process it
8bdb31ed 152if ($formdata = $mform2->is_cancelled()) {
e4e38544 153 $cir->cleanup(true);
154 redirect($returnurl);
df7ecfe4 155
8bdb31ed 156} else if ($formdata = $mform2->get_data()) {
df7ecfe4 157 // Print the header
61ef8f9f 158 echo $OUTPUT->header();
ce15d56d 159 echo $OUTPUT->heading(get_string('uploadusersresult', 'tool_uploaduser'));
e4e38544 160
161 $optype = $formdata->uutype;
162
0c4807ab 163 $updatetype = isset($formdata->uuupdatetype) ? $formdata->uuupdatetype : 0;
8bdb31ed
PS
164 $createpasswords = (!empty($formdata->uupasswordnew) and $optype != UU_USER_UPDATE);
165 $updatepasswords = (!empty($formdata->uupasswordold) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC and ($updatetype == UU_UPDATE_FILEOVERRIDE or $updatetype == UU_UPDATE_ALLOVERRIDE));
166 $allowrenames = (!empty($formdata->uuallowrenames) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
167 $allowdeletes = (!empty($formdata->uuallowdeletes) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
08157bfe 168 $allowsuspends = (!empty($formdata->uuallowsuspends));
0c4807ab 169 $bulk = $formdata->uubulk;
170 $noemailduplicates = $formdata->uunoemailduplicates;
8bdb31ed
PS
171 $standardusernames = $formdata->uustandardusernames;
172 $resetpasswords = isset($formdata->uuforcepasswordchange) ? $formdata->uuforcepasswordchange : UU_PWRESET_NONE;
e4e38544 173
174 // verification moved to two places: after upload and into form2
8bdb31ed
PS
175 $usersnew = 0;
176 $usersupdated = 0;
177 $usersuptodate = 0; //not printed yet anywhere
178 $userserrors = 0;
179 $deletes = 0;
180 $deleteerrors = 0;
181 $renames = 0;
182 $renameerrors = 0;
183 $usersskipped = 0;
d6bb2d2f 184 $weakpasswords = 0;
feecd4d6 185
e4e38544 186 // caches
8bdb31ed 187 $ccache = array(); // course cache - do not fetch all courses here, we will not probably use them all anyway!
92b59a56 188 $cohorts = array();
8bdb31ed
PS
189 $rolecache = uu_allowed_roles_cache(); // roles lookup cache
190 $manualcache = array(); // cache of used manual enrol plugins in each course
191 $supportedauths = uu_supported_auths(); // officially supported plugins that are enabled
e4e38544 192
df997f84
PS
193 // we use only manual enrol plugin here, if it is disabled no enrol is done
194 if (enrol_is_enabled('manual')) {
195 $manual = enrol_get_plugin('manual');
196 } else {
197 $manual = NULL;
e4e38544 198 }
df7ecfe4 199
b4bd91ce 200 // clear bulk selection
e4e38544 201 if ($bulk) {
cd1edf9e 202 $SESSION->bulk_users = array();
e4e38544 203 }
df7ecfe4 204
e4e38544 205 // init csv import helper
206 $cir->init();
207 $linenum = 1; //column header is first line
df7ecfe4 208
e4e38544 209 // init upload progress tracker
210 $upt = new uu_progress_tracker();
8bdb31ed 211 $upt->start(); // start table
a2ce7344 212
e4e38544 213 while ($line = $cir->next()) {
214 $upt->flush();
215 $linenum++;
216
217 $upt->track('line', $linenum);
218
a226a972 219 $user = new stdClass();
8bdb31ed 220
e4e38544 221 // add fields to user object
8bdb31ed
PS
222 foreach ($line as $keynum => $value) {
223 if (!isset($filecolumns[$keynum])) {
224 // this should not happen
225 continue;
226 }
227 $key = $filecolumns[$keynum];
228 if (strpos($key, 'profile_field_') === 0) {
229 //NOTE: bloody mega hack alert!!
230 if (isset($USER->$key) and is_array($USER->$key)) {
231 // this must be some hacky field that is abusing arrays to store content and format
232 $user->$key = array();
233 $user->$key['text'] = $value;
234 $user->$key['format'] = FORMAT_MOODLE;
235 } else {
236 $user->$key = $value;
e4e38544 237 }
c3231d1d 238 } else {
8bdb31ed 239 $user->$key = $value;
a7db355a 240 }
e4e38544 241
8bdb31ed
PS
242 if (in_array($key, $upt->columns)) {
243 // default value in progress tracking table, can be changed later
244 $upt->track($key, s($value), 'normal');
e4e38544 245 }
8bdb31ed
PS
246 }
247 if (!isset($user->username)) {
ce8df92d 248 // prevent warnings below
8bdb31ed
PS
249 $user->username = '';
250 }
e4e38544 251
8bdb31ed
PS
252 if ($optype == UU_USER_ADDNEW or $optype == UU_USER_ADDINC) {
253 // user creation is a special case - the username may be constructed from templates using firstname and lastname
254 // better never try this in mixed update types
e4e38544 255 $error = false;
e4e38544 256 if (!isset($user->firstname) or $user->firstname === '') {
257 $upt->track('status', get_string('missingfield', 'error', 'firstname'), 'error');
258 $upt->track('firstname', $errorstr, 'error');
259 $error = true;
260 }
261 if (!isset($user->lastname) or $user->lastname === '') {
262 $upt->track('status', get_string('missingfield', 'error', 'lastname'), 'error');
263 $upt->track('lastname', $errorstr, 'error');
264 $error = true;
265 }
266 if ($error) {
267 $userserrors++;
268 continue;
269 }
270 // we require username too - we might use template for it though
8bdb31ed
PS
271 if (empty($user->username) and !empty($formdata->username)) {
272 $user->username = uu_process_template($formdata->username, $user);
273 $upt->track('username', s($user->username));
e4e38544 274 }
a7db355a 275 }
e4e38544 276
277 // normalize username
8bdb31ed
PS
278 $originalusername = $user->username;
279 if ($standardusernames) {
280 $user->username = clean_param($user->username, PARAM_USERNAME);
281 }
07ed083e 282
8bdb31ed 283 // make sure we really have username
e4e38544 284 if (empty($user->username)) {
285 $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
286 $upt->track('username', $errorstr, 'error');
287 $userserrors++;
288 continue;
8bdb31ed
PS
289 } else if ($user->username === 'guest') {
290 $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
291 $userserrors++;
292 continue;
e4e38544 293 }
9dcae46d 294
7bf99ee5
AA
295 if ($user->username !== clean_param($user->username, PARAM_USERNAME)) {
296 $upt->track('status', get_string('invalidusername', 'error', 'username'), 'error');
297 $upt->track('username', $errorstr, 'error');
298 $userserrors++;
299 }
397ccf13 300
9dcae46d
PS
301 if (empty($user->mnethostid)) {
302 $user->mnethostid = $CFG->mnet_localhost_id;
303 }
304
305 if ($existinguser = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
e4e38544 306 $upt->track('id', $existinguser->id, 'normal', false);
307 }
308
9dcae46d
PS
309 if ($user->mnethostid == $CFG->mnet_localhost_id) {
310 $remoteuser = false;
311
312 // Find out if username incrementing required.
313 if ($existinguser and $optype == UU_USER_ADDINC) {
314 $user->username = uu_increment_username($user->username);
315 $existinguser = false;
316 }
317
318 } else {
319 if (!$existinguser or $optype == UU_USER_ADDINC) {
320 $upt->track('status', get_string('errormnetadd', 'tool_uploaduser'), 'error');
321 $userserrors++;
322 continue;
323 }
324
325 $remoteuser = true;
326
327 // Make sure there are no changes of existing fields except the suspended status.
328 foreach ((array)$existinguser as $k => $v) {
329 if ($k === 'suspended') {
330 continue;
331 }
332 if (property_exists($user, $k)) {
333 $user->$k = $v;
334 }
335 if (in_array($k, $upt->columns)) {
336 if ($k === 'password' or $k === 'oldusername' or $k === 'deleted') {
337 $upt->track($k, '', 'normal', false);
338 } else {
339 $upt->track($k, s($v), 'normal', false);
340 }
341 }
342 }
343 unset($user->oldusername);
344 unset($user->password);
345 $user->auth = $existinguser->auth;
e4e38544 346 }
347
8bdb31ed
PS
348 // notify about nay username changes
349 if ($originalusername !== $user->username) {
350 $upt->track('username', '', 'normal', false); // clear previous
351 $upt->track('username', s($originalusername).'-->'.s($user->username), 'info');
352 } else {
353 $upt->track('username', s($user->username), 'normal', false);
354 }
355
e4e38544 356 // add default values for remaining fields
8bdb31ed 357 $formdefaults = array();
e4e38544 358 foreach ($STD_FIELDS as $field) {
359 if (isset($user->$field)) {
360 continue;
361 }
362 // all validation moved to form2
363 if (isset($formdata->$field)) {
364 // process templates
8bdb31ed
PS
365 $user->$field = uu_process_template($formdata->$field, $user);
366 $formdefaults[$field] = true;
43070e61
PS
367 if (in_array($field, $upt->columns)) {
368 $upt->track($field, s($user->$field), 'normal');
369 }
e4e38544 370 }
371 }
372 foreach ($PRF_FIELDS as $field) {
373 if (isset($user->$field)) {
374 continue;
375 }
376 if (isset($formdata->$field)) {
377 // process templates
8bdb31ed 378 $user->$field = uu_process_template($formdata->$field, $user);
b650fe6a
RT
379
380 // Form contains key and later code expects value.
381 // Convert key to value for required profile fields.
382 require_once($CFG->dirroot.'/user/profile/field/'.$proffields[$field]->datatype.'/field.class.php');
383 $profilefieldclass = 'profile_field_'.$proffields[$field]->datatype;
384 $profilefield = new $profilefieldclass($proffields[$field]->id);
385 if (method_exists($profilefield, 'convert_external_data')) {
386 $user->$field = $profilefield->edit_save_data_preprocess($user->$field, null);
387 }
388
8bdb31ed 389 $formdefaults[$field] = true;
e4e38544 390 }
391 }
392
393 // delete user
394 if (!empty($user->deleted)) {
9dcae46d 395 if (!$allowdeletes or $remoteuser) {
e4e38544 396 $usersskipped++;
397 $upt->track('status', $strusernotdeletedoff, 'warning');
398 continue;
399 }
400 if ($existinguser) {
4f0c2d00 401 if (is_siteadmin($existinguser->id)) {
e4e38544 402 $upt->track('status', $strusernotdeletedadmin, 'error');
403 $deleteerrors++;
404 continue;
405 }
406 if (delete_user($existinguser)) {
407 $upt->track('status', $struserdeleted);
408 $deletes++;
409 } else {
410 $upt->track('status', $strusernotdeletederror, 'error');
411 $deleteerrors++;
6b09974b 412 }
e4e38544 413 } else {
414 $upt->track('status', $strusernotdeletedmissing, 'error');
415 $deleteerrors++;
416 }
417 continue;
418 }
419 // we do not need the deleted flag anymore
420 unset($user->deleted);
421
422 // renaming requested?
423 if (!empty($user->oldusername) ) {
e4e38544 424 if (!$allowrenames) {
425 $usersskipped++;
426 $upt->track('status', $strusernotrenamedoff, 'warning');
427 continue;
428 }
429
430 if ($existinguser) {
431 $upt->track('status', $strusernotrenamedexists, 'error');
432 $renameerrors++;
433 continue;
16a1fed4 434 }
ed22a01b 435
8bdb31ed
PS
436 if ($user->username === 'guest') {
437 $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
438 $renameerrors++;
439 continue;
440 }
441
442 if ($standardusernames) {
443 $oldusername = clean_param($user->oldusername, PARAM_USERNAME);
444 } else {
445 $oldusername = $user->oldusername;
446 }
447
448 // no guessing when looking for old username, it must be exact match
449 if ($olduser = $DB->get_record('user', array('username'=>$oldusername, 'mnethostid'=>$CFG->mnet_localhost_id))) {
e4e38544 450 $upt->track('id', $olduser->id, 'normal', false);
4f0c2d00 451 if (is_siteadmin($olduser->id)) {
e4e38544 452 $upt->track('status', $strusernotrenamedadmin, 'error');
453 $renameerrors++;
a7db355a 454 continue;
0063abee 455 }
df997f84
PS
456 $DB->set_field('user', 'username', $user->username, array('id'=>$olduser->id));
457 $upt->track('username', '', 'normal', false); // clear previous
8bdb31ed 458 $upt->track('username', s($oldusername).'-->'.s($user->username), 'info');
df997f84
PS
459 $upt->track('status', $struserrenamed);
460 $renames++;
e4e38544 461 } else {
462 $upt->track('status', $strusernotrenamedmissing, 'error');
463 $renameerrors++;
464 continue;
465 }
466 $existinguser = $olduser;
467 $existinguser->username = $user->username;
468 }
469
470 // can we process with update or insert?
471 $skip = false;
472 switch ($optype) {
8bdb31ed 473 case UU_USER_ADDNEW:
e4e38544 474 if ($existinguser) {
475 $usersskipped++;
476 $upt->track('status', $strusernotadded, 'warning');
3fe2cfb5 477 $skip = true;
e4e38544 478 }
479 break;
480
8bdb31ed 481 case UU_USER_ADDINC:
e4e38544 482 if ($existinguser) {
483 //this should not happen!
484 $upt->track('status', $strusernotaddederror, 'error');
485 $userserrors++;
8bdb31ed 486 $skip = true;
e4e38544 487 }
488 break;
489
8bdb31ed 490 case UU_USER_ADD_UPDATE:
e4e38544 491 break;
492
8bdb31ed 493 case UU_USER_UPDATE:
e4e38544 494 if (!$existinguser) {
495 $usersskipped++;
496 $upt->track('status', $strusernotupdatednotexists, 'warning');
497 $skip = true;
498 }
499 break;
8bdb31ed
PS
500
501 default:
502 // unknown type
503 $skip = true;
e4e38544 504 }
505
506 if ($skip) {
507 continue;
508 }
509
510 if ($existinguser) {
511 $user->id = $existinguser->id;
512
8bdb31ed 513 $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id'=>$existinguser->id)), s($existinguser->username)), 'normal', false);
08157bfe 514 $upt->track('suspended', $stryesnooptions[$existinguser->suspended] , 'normal', false);
628e9b20 515 $upt->track('auth', $existinguser->auth, 'normal', false);
8bdb31ed 516
4f0c2d00 517 if (is_siteadmin($user->id)) {
e4e38544 518 $upt->track('status', $strusernotupdatedadmin, 'error');
519 $userserrors++;
520 continue;
521 }
522
8bdb31ed
PS
523 $existinguser->timemodified = time();
524 // do NOT mess with timecreated or firstaccess here!
525
526 //load existing profile data
527 profile_load_data($existinguser);
3fe2cfb5 528
8bdb31ed 529 $doupdate = false;
08157bfe 530 $dologout = false;
8bdb31ed 531
9dcae46d 532 if ($updatetype != UU_UPDATE_NOCHANGES and !$remoteuser) {
8bdb31ed
PS
533 if (!empty($user->auth) and $user->auth !== $existinguser->auth) {
534 $upt->track('auth', s($existinguser->auth).'-->'.s($user->auth), 'info', false);
535 $existinguser->auth = $user->auth;
536 if (!isset($supportedauths[$user->auth])) {
537 $upt->track('auth', $struserauthunsupported, 'warning');
538 }
df833016 539 $doupdate = true;
08157bfe
PS
540 if ($existinguser->auth === 'nologin') {
541 $dologout = true;
542 }
e4e38544 543 }
8bdb31ed
PS
544 $allcolumns = array_merge($STD_FIELDS, $PRF_FIELDS);
545 foreach ($allcolumns as $column) {
08157bfe 546 if ($column === 'username' or $column === 'password' or $column === 'auth' or $column === 'suspended') {
8bdb31ed 547 // these can not be changed here
e4e38544 548 continue;
549 }
8bdb31ed
PS
550 if (!property_exists($user, $column) or !property_exists($existinguser, $column)) {
551 // this should never happen
c90e6b46 552 debugging("Could not find $column on the user objects", DEBUG_DEVELOPER);
8bdb31ed
PS
553 continue;
554 }
555 if ($updatetype == UU_UPDATE_MISSING) {
556 if (!is_null($existinguser->$column) and $existinguser->$column !== '') {
e4e38544 557 continue;
a7db355a 558 }
8bdb31ed
PS
559 } else if ($updatetype == UU_UPDATE_ALLOVERRIDE) {
560 // we override everything
3f12c146 561
8bdb31ed
PS
562 } else if ($updatetype == UU_UPDATE_FILEOVERRIDE) {
563 if (!empty($formdefaults[$column])) {
564 // do not override with form defaults
565 continue;
566 }
567 }
568 if ($existinguser->$column !== $user->$column) {
569 if ($column === 'email') {
570 if ($DB->record_exists('user', array('email'=>$user->email))) {
571 if ($noemailduplicates) {
572 $upt->track('email', $stremailduplicate, 'error');
573 $upt->track('status', $strusernotupdated, 'error');
574 $userserrors++;
575 continue 2;
576 } else {
577 $upt->track('email', $stremailduplicate, 'warning');
3f12c146
RW
578 }
579 }
8bdb31ed
PS
580 if (!validate_email($user->email)) {
581 $upt->track('email', get_string('invalidemail'), 'warning');
e4e38544 582 }
8bdb31ed 583 }
3f12c146 584
4d3cd148
PS
585 if ($column === 'lang') {
586 if (empty($user->lang)) {
587 // Do not change to not-set value.
588 continue;
589 } else if (clean_param($user->lang, PARAM_LANG) === '') {
590 $upt->track('status', get_string('cannotfindlang', 'error', $user->lang), 'warning');
591 continue;
592 }
593 }
594
8bdb31ed
PS
595 if (in_array($column, $upt->columns)) {
596 $upt->track($column, s($existinguser->$column).'-->'.s($user->$column), 'info', false);
a7db355a 597 }
8bdb31ed
PS
598 $existinguser->$column = $user->$column;
599 $doupdate = true;
6b09974b 600 }
a7db355a 601 }
8bdb31ed 602 }
ed22a01b 603
8bdb31ed 604 try {
3f12c146 605 $auth = get_auth_plugin($existinguser->auth);
8bdb31ed
PS
606 } catch (Exception $e) {
607 $upt->track('auth', get_string('userautherror', 'error', s($existinguser->auth)), 'error');
608 $upt->track('status', $strusernotupdated, 'error');
609 $userserrors++;
610 continue;
611 }
612 $isinternalauth = $auth->is_internal();
3f12c146 613
08157bfe
PS
614 // deal with suspending and activating of accounts
615 if ($allowsuspends and isset($user->suspended) and $user->suspended !== '') {
616 $user->suspended = $user->suspended ? 1 : 0;
617 if ($existinguser->suspended != $user->suspended) {
618 $upt->track('suspended', '', 'normal', false);
619 $upt->track('suspended', $stryesnooptions[$existinguser->suspended].'-->'.$stryesnooptions[$user->suspended], 'info', false);
620 $existinguser->suspended = $user->suspended;
621 $doupdate = true;
622 if ($existinguser->suspended) {
623 $dologout = true;
624 }
625 }
626 }
627
8bdb31ed
PS
628 // changing of passwords is a special case
629 // do not force password changes for external auth plugins!
630 $oldpw = $existinguser->password;
9dcae46d
PS
631
632 if ($remoteuser) {
633 // Do not mess with passwords of remote users.
634
635 } else if (!$isinternalauth) {
ec2d8ceb 636 $existinguser->password = AUTH_PASSWORD_NOT_CACHED;
8bdb31ed
PS
637 $upt->track('password', '-', 'normal', false);
638 // clean up prefs
639 unset_user_preference('create_password', $existinguser);
640 unset_user_preference('auth_forcepasswordchange', $existinguser);
641
642 } else if (!empty($user->password)) {
643 if ($updatepasswords) {
ec2d8ceb
SC
644 // Check for passwords that we want to force users to reset next
645 // time they log in.
8bdb31ed 646 $errmsg = null;
faceca91 647 $weak = !check_password_policy($user->password, $errmsg);
8bdb31ed
PS
648 if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
649 if ($weak) {
650 $weakpasswords++;
651 $upt->track('password', $strinvalidpasswordpolicy, 'warning');
652 }
653 set_user_preference('auth_forcepasswordchange', 1, $existinguser);
654 } else {
655 unset_user_preference('auth_forcepasswordchange', $existinguser);
656 }
657 unset_user_preference('create_password', $existinguser); // no need to create password any more
ec2d8ceb
SC
658
659 // Use a low cost factor when generating bcrypt hash otherwise
660 // hashing would be slow when uploading lots of users. Hashes
661 // will be automatically updated to a higher cost factor the first
662 // time the user logs in.
663 $existinguser->password = hash_internal_user_password($user->password, true);
2197b642 664 $upt->track('password', $user->password, 'normal', false);
3f12c146 665 } else {
8bdb31ed
PS
666 // do not print password when not changed
667 $upt->track('password', '', 'normal', false);
3f12c146 668 }
8bdb31ed 669 }
3f12c146 670
8bdb31ed 671 if ($doupdate or $existinguser->password !== $oldpw) {
bb78e249
RT
672 // We want only users that were really updated.
673 user_update_user($existinguser, false);
3f12c146 674
df997f84
PS
675 $upt->track('status', $struserupdated);
676 $usersupdated++;
9dcae46d
PS
677
678 if (!$remoteuser) {
679 // pre-process custom profile menu fields data from csv file
680 $existinguser = uu_pre_process_custom_profile_data($existinguser);
681 // save custom profile fields data from csv file
682 profile_save_data($existinguser);
683 }
e6f74ba3 684
8bdb31ed
PS
685 if ($bulk == UU_BULK_UPDATED or $bulk == UU_BULK_ALL) {
686 if (!in_array($user->id, $SESSION->bulk_users)) {
687 $SESSION->bulk_users[] = $user->id;
688 }
689 }
690
691 } else {
692 // no user information changed
693 $upt->track('status', $struseruptodate);
694 $usersuptodate++;
695
696 if ($bulk == UU_BULK_ALL) {
697 if (!in_array($user->id, $SESSION->bulk_users)) {
698 $SESSION->bulk_users[] = $user->id;
699 }
ed22a01b 700 }
066bfbfe 701 }
ed22a01b 702
08157bfe 703 if ($dologout) {
d79d5ac2 704 \core\session\manager::kill_user_sessions($existinguser->id);
08157bfe
PS
705 }
706
e4e38544 707 } else {
8bdb31ed
PS
708 // save the new user to the database
709 $user->confirmed = 1;
a7db355a 710 $user->timemodified = time();
8bdb31ed
PS
711 $user->timecreated = time();
712 $user->mnethostid = $CFG->mnet_localhost_id; // we support ONLY local accounts here, sorry
066bfbfe 713
08157bfe
PS
714 if (!isset($user->suspended) or $user->suspended === '') {
715 $user->suspended = 0;
716 } else {
717 $user->suspended = $user->suspended ? 1 : 0;
718 }
719 $upt->track('suspended', $stryesnooptions[$user->suspended], 'normal', false);
720
8bdb31ed 721 if (empty($user->auth)) {
3f12c146
RW
722 $user->auth = 'manual';
723 }
8bdb31ed 724 $upt->track('auth', $user->auth, 'normal', false);
3f12c146 725
8bdb31ed
PS
726 // do not insert record if new auth plugin does not exist!
727 try {
728 $auth = get_auth_plugin($user->auth);
729 } catch (Exception $e) {
730 $upt->track('auth', get_string('userautherror', 'error', s($user->auth)), 'error');
731 $upt->track('status', $strusernotaddederror, 'error');
732 $userserrors++;
733 continue;
e4e38544 734 }
8bdb31ed
PS
735 if (!isset($supportedauths[$user->auth])) {
736 $upt->track('auth', $struserauthunsupported, 'warning');
066bfbfe 737 }
a2ce7344 738
8bdb31ed
PS
739 $isinternalauth = $auth->is_internal();
740
43070e61
PS
741 if (empty($user->email)) {
742 $upt->track('email', get_string('invalidemail'), 'error');
743 $upt->track('status', $strusernotaddederror, 'error');
744 $userserrors++;
745 continue;
746
747 } else if ($DB->record_exists('user', array('email'=>$user->email))) {
0c4807ab 748 if ($noemailduplicates) {
749 $upt->track('email', $stremailduplicate, 'error');
750 $upt->track('status', $strusernotaddederror, 'error');
751 $userserrors++;
752 continue;
753 } else {
754 $upt->track('email', $stremailduplicate, 'warning');
755 }
756 }
8bdb31ed
PS
757 if (!validate_email($user->email)) {
758 $upt->track('email', get_string('invalidemail'), 'warning');
3f12c146 759 }
0c4807ab 760
4d3cd148
PS
761 if (empty($user->lang)) {
762 $user->lang = '';
763 } else if (clean_param($user->lang, PARAM_LANG) === '') {
764 $upt->track('status', get_string('cannotfindlang', 'error', $user->lang), 'warning');
765 $user->lang = '';
766 }
767
8bdb31ed
PS
768 $forcechangepassword = false;
769
770 if ($isinternalauth) {
771 if (empty($user->password)) {
772 if ($createpasswords) {
773 $user->password = 'to be generated';
774 $upt->track('password', '', 'normal', false);
ce15d56d 775 $upt->track('password', get_string('uupasswordcron', 'tool_uploaduser'), 'warning', false);
8bdb31ed
PS
776 } else {
777 $upt->track('password', '', 'normal', false);
778 $upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
779 $upt->track('status', $strusernotaddederror, 'error');
780 $userserrors++;
781 continue;
782 }
3f12c146 783 } else {
8bdb31ed 784 $errmsg = null;
faceca91 785 $weak = !check_password_policy($user->password, $errmsg);
8bdb31ed
PS
786 if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
787 if ($weak) {
788 $weakpasswords++;
789 $upt->track('password', $strinvalidpasswordpolicy, 'warning');
790 }
791 $forcechangepassword = true;
792 }
ec2d8ceb
SC
793 // Use a low cost factor when generating bcrypt hash otherwise
794 // hashing would be slow when uploading lots of users. Hashes
795 // will be automatically updated to a higher cost factor the first
796 // time the user logs in.
797 $user->password = hash_internal_user_password($user->password, true);
3f12c146 798 }
8bdb31ed 799 } else {
ec2d8ceb 800 $user->password = AUTH_PASSWORD_NOT_CACHED;
8bdb31ed 801 $upt->track('password', '-', 'normal', false);
df997f84
PS
802 }
803
bb78e249 804 $user->id = user_create_user($user, false);
8bdb31ed
PS
805 $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id'=>$user->id)), s($user->username)), 'normal', false);
806
d6aea4cc 807 // pre-process custom profile menu fields data from csv file
bd8dc9ba 808 $user = uu_pre_process_custom_profile_data($user);
e4e38544 809 // save custom profile fields data
810 profile_save_data($user);
811
8bdb31ed
PS
812 if ($forcechangepassword) {
813 set_user_preference('auth_forcepasswordchange', 1, $user);
814 }
815 if ($user->password === 'to be generated') {
816 set_user_preference('create_password', 1, $user);
817 }
818
819 $upt->track('status', $struseradded);
820 $upt->track('id', $user->id, 'normal', false);
821 $usersnew++;
822
2304f629 823 // make sure user context exists
bf006d2c 824 context_user::instance($user->id);
2304f629 825
8bdb31ed 826 if ($bulk == UU_BULK_NEW or $bulk == UU_BULK_ALL) {
cd1edf9e 827 if (!in_array($user->id, $SESSION->bulk_users)) {
828 $SESSION->bulk_users[] = $user->id;
066bfbfe 829 }
066bfbfe 830 }
e4e38544 831 }
832
92b59a56
PS
833
834 // add to cohort first, it might trigger enrolments indirectly - do NOT create cohorts here!
835 foreach ($filecolumns as $column) {
836 if (!preg_match('/^cohort\d+$/', $column)) {
837 continue;
838 }
839
840 if (!empty($user->$column)) {
841 $addcohort = $user->$column;
842 if (!isset($cohorts[$addcohort])) {
843 if (is_number($addcohort)) {
844 // only non-numeric idnumbers!
845 $cohort = $DB->get_record('cohort', array('id'=>$addcohort));
846 } else {
847 $cohort = $DB->get_record('cohort', array('idnumber'=>$addcohort));
848 }
849
850 if (empty($cohort)) {
851 $cohorts[$addcohort] = get_string('unknowncohort', 'core_cohort', s($addcohort));
852 } else if (!empty($cohort->component)) {
853 // cohorts synchronised with external sources must not be modified!
854 $cohorts[$addcohort] = get_string('external', 'core_cohort');
855 } else {
856 $cohorts[$addcohort] = $cohort;
857 }
858 }
859
860 if (is_object($cohorts[$addcohort])) {
861 $cohort = $cohorts[$addcohort];
862 if (!$DB->record_exists('cohort_members', array('cohortid'=>$cohort->id, 'userid'=>$user->id))) {
863 cohort_add_member($cohort->id, $user->id);
864 // we might add special column later, for now let's abuse enrolments
865 $upt->track('enrolments', get_string('useradded', 'core_cohort', s($cohort->name)));
866 }
867 } else {
868 // error message
869 $upt->track('enrolments', $cohorts[$addcohort], 'error');
870 }
871 }
872 }
873
874
2686b6c3 875 // find course enrolments, groups, roles/types and enrol periods
8bdb31ed
PS
876 // this is again a special case, we always do this for any updated or created users
877 foreach ($filecolumns as $column) {
e4e38544 878 if (!preg_match('/^course\d+$/', $column)) {
879 continue;
880 }
881 $i = substr($column, 6);
6b09974b 882
df997f84
PS
883 if (empty($user->{'course'.$i})) {
884 continue;
885 }
e4e38544 886 $shortname = $user->{'course'.$i};
887 if (!array_key_exists($shortname, $ccache)) {
df997f84 888 if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname')) {
8bdb31ed 889 $upt->track('enrolments', get_string('unknowncourse', 'error', s($shortname)), 'error');
a7db355a 890 continue;
066bfbfe 891 }
e4e38544 892 $ccache[$shortname] = $course;
893 $ccache[$shortname]->groups = null;
894 }
895 $courseid = $ccache[$shortname]->id;
bf006d2c 896 $coursecontext = context_course::instance($courseid);
df997f84 897 if (!isset($manualcache[$courseid])) {
4cb02426
PS
898 $manualcache[$courseid] = false;
899 if ($manual) {
900 if ($instances = enrol_get_instances($courseid, false)) {
901 foreach ($instances as $instance) {
902 if ($instance->enrol === 'manual') {
903 $manualcache[$courseid] = $instance;
904 break;
905 }
906 }
907 }
e4e38544 908 }
df997f84 909 }
e4e38544 910
968083cd
PS
911 if ($courseid == SITEID) {
912 // Technically frontpage does not have enrolments, but only role assignments,
913 // let's not invent new lang strings here for this rarely used feature.
914
915 if (!empty($user->{'role'.$i})) {
916 $addrole = $user->{'role'.$i};
917 if (array_key_exists($addrole, $rolecache)) {
918 $rid = $rolecache[$addrole]->id;
919 } else {
920 $upt->track('enrolments', get_string('unknownrole', 'error', s($addrole)), 'error');
921 continue;
922 }
923
924 role_assign($rid, $user->id, context_course::instance($courseid));
925
926 $a = new stdClass();
927 $a->course = $shortname;
928 $a->role = $rolecache[$rid]->name;
929 $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
930 }
931
932 } else if ($manual and $manualcache[$courseid]) {
df997f84
PS
933
934 // find role
935 $rid = false;
936 if (!empty($user->{'role'.$i})) {
937 $addrole = $user->{'role'.$i};
938 if (array_key_exists($addrole, $rolecache)) {
939 $rid = $rolecache[$addrole]->id;
e4e38544 940 } else {
8bdb31ed 941 $upt->track('enrolments', get_string('unknownrole', 'error', s($addrole)), 'error');
df997f84 942 continue;
a7db355a 943 }
e4e38544 944
df997f84
PS
945 } else if (!empty($user->{'type'.$i})) {
946 // if no role, then find "old" enrolment type
947 $addtype = $user->{'type'.$i};
948 if ($addtype < 1 or $addtype > 3) {
949 $upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
950 continue;
951 } else if (empty($formdata->{'uulegacy'.$addtype})) {
952 continue;
953 } else {
954 $rid = $formdata->{'uulegacy'.$addtype};
955 }
e4e38544 956 } else {
df997f84
PS
957 // no role specified, use the default from manual enrol plugin
958 $rid = $manualcache[$courseid]->roleid;
a7db355a 959 }
2686b6c3 960
df997f84
PS
961 if ($rid) {
962 // find duration
df997f84
PS
963 $timeend = 0;
964 if (!empty($user->{'enrolperiod'.$i})) {
8bdb31ed 965 $duration = (int)$user->{'enrolperiod'.$i} * 60*60*24; // convert days to seconds
df997f84 966 if ($duration > 0) { // sanity check
8bdb31ed 967 $timeend = $today + $duration;
df997f84 968 }
b1d76077
AO
969 } else if ($manualcache[$courseid]->enrolperiod > 0) {
970 $timeend = $today + $manualcache[$courseid]->enrolperiod;
df997f84 971 }
2686b6c3 972
02c97e65 973 $manual->enrol_user($manualcache[$courseid], $user->id, $rid, $today, $timeend);
df997f84 974
a226a972 975 $a = new stdClass();
df997f84
PS
976 $a->course = $shortname;
977 $a->role = $rolecache[$rid]->name;
978 $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
066bfbfe 979 }
e4e38544 980 }
6b09974b 981
e4e38544 982 // find group to add to
983 if (!empty($user->{'group'.$i})) {
984 // make sure user is enrolled into course before adding into groups
4f0c2d00 985 if (!is_enrolled($coursecontext, $user->id)) {
d85f2634 986 $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group'.$i}), 'error');
e4e38544 987 continue;
988 }
989 //build group cache
990 if (is_null($ccache[$shortname]->groups)) {
991 $ccache[$shortname]->groups = array();
35987665 992 if ($groups = groups_get_all_groups($courseid)) {
e4e38544 993 foreach ($groups as $gid=>$group) {
a226a972 994 $ccache[$shortname]->groups[$gid] = new stdClass();
e4e38544 995 $ccache[$shortname]->groups[$gid]->id = $gid;
996 $ccache[$shortname]->groups[$gid]->name = $group->name;
997 if (!is_numeric($group->name)) { // only non-numeric names are supported!!!
8bdb31ed
PS
998 $ccache[$shortname]->groups[$group->name] = new stdClass();
999 $ccache[$shortname]->groups[$group->name]->id = $gid;
1000 $ccache[$shortname]->groups[$group->name]->name = $group->name;
a7db355a 1001 }
a5702569 1002 }
0063abee 1003 }
6b09974b 1004 }
e4e38544 1005 // group exists?
1006 $addgroup = $user->{'group'.$i};
1007 if (!array_key_exists($addgroup, $ccache[$shortname]->groups)) {
b225cf36 1008 // if group doesn't exist, create it
a226a972 1009 $newgroupdata = new stdClass();
b225cf36 1010 $newgroupdata->name = $addgroup;
1011 $newgroupdata->courseid = $ccache[$shortname]->id;
e95bf5b5
PS
1012 $newgroupdata->description = '';
1013 $gid = groups_create_group($newgroupdata);
1014 if ($gid){
1015 $ccache[$shortname]->groups[$addgroup] = new stdClass();
1016 $ccache[$shortname]->groups[$addgroup]->id = $gid;
b225cf36 1017 $ccache[$shortname]->groups[$addgroup]->name = $newgroupdata->name;
1018 } else {
8bdb31ed 1019 $upt->track('enrolments', get_string('unknowngroup', 'error', s($addgroup)), 'error');
b225cf36 1020 continue;
1021 }
e4e38544 1022 }
1023 $gid = $ccache[$shortname]->groups[$addgroup]->id;
1024 $gname = $ccache[$shortname]->groups[$addgroup]->name;
1025
9c000a99 1026 try {
1027 if (groups_add_member($gid, $user->id)) {
8bdb31ed 1028 $upt->track('enrolments', get_string('addedtogroup', '', s($gname)));
df997f84 1029 } else {
8bdb31ed 1030 $upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
9c000a99 1031 }
1032 } catch (moodle_exception $e) {
8bdb31ed 1033 $upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
e4e38544 1034 continue;
1035 }
a5702569 1036 }
066bfbfe 1037 }
1038 }
e4e38544 1039 $upt->close(); // close table
1040
1041 $cir->close();
1042 $cir->cleanup(true);
1043
20486a5a 1044 echo $OUTPUT->box_start('boxwidthnarrow boxaligncenter generalbox', 'uploadresults');
e4e38544 1045 echo '<p>';
8bdb31ed 1046 if ($optype != UU_USER_UPDATE) {
ce15d56d 1047 echo get_string('userscreated', 'tool_uploaduser').': '.$usersnew.'<br />';
e4e38544 1048 }
8bdb31ed 1049 if ($optype == UU_USER_UPDATE or $optype == UU_USER_ADD_UPDATE) {
ce15d56d 1050 echo get_string('usersupdated', 'tool_uploaduser').': '.$usersupdated.'<br />';
e4e38544 1051 }
1052 if ($allowdeletes) {
ce15d56d
PS
1053 echo get_string('usersdeleted', 'tool_uploaduser').': '.$deletes.'<br />';
1054 echo get_string('deleteerrors', 'tool_uploaduser').': '.$deleteerrors.'<br />';
e4e38544 1055 }
1056 if ($allowrenames) {
ce15d56d
PS
1057 echo get_string('usersrenamed', 'tool_uploaduser').': '.$renames.'<br />';
1058 echo get_string('renameerrors', 'tool_uploaduser').': '.$renameerrors.'<br />';
e4e38544 1059 }
1060 if ($usersskipped) {
ce15d56d 1061 echo get_string('usersskipped', 'tool_uploaduser').': '.$usersskipped.'<br />';
e4e38544 1062 }
ce15d56d
PS
1063 echo get_string('usersweakpassword', 'tool_uploaduser').': '.$weakpasswords.'<br />';
1064 echo get_string('errors', 'tool_uploaduser').': '.$userserrors.'</p>';
20486a5a 1065 echo $OUTPUT->box_end();
e4e38544 1066
1067 if ($bulk) {
8fbce1c8 1068 echo $OUTPUT->continue_button($bulknurl);
e4e38544 1069 } else {
8fbce1c8 1070 echo $OUTPUT->continue_button($returnurl);
e4e38544 1071 }
73d6f52f 1072 echo $OUTPUT->footer();
df7ecfe4 1073 die;
6b09974b 1074}
0a6150ca 1075
df7ecfe4 1076// Print the header
61ef8f9f 1077echo $OUTPUT->header();
df7ecfe4 1078
ce15d56d 1079echo $OUTPUT->heading(get_string('uploaduserspreview', 'tool_uploaduser'));
df7ecfe4 1080
8bdb31ed
PS
1081// NOTE: this is JUST csv processing preview, we must not prevent import from here if there is something in the file!!
1082// this was intended for validation of csv formatting and encoding, not filtering the data!!!!
1083// we definitely must not process the whole file!
1084
1085// preview table data
1086$data = array();
e4e38544 1087$cir->init();
8bdb31ed 1088$linenum = 1; //column header is first line
1b4d2d56 1089$noerror = true; // Keep status of any error.
8bdb31ed
PS
1090while ($linenum <= $previewrows and $fields = $cir->next()) {
1091 $linenum++;
3fe2cfb5 1092 $rowcols = array();
8bdb31ed
PS
1093 $rowcols['line'] = $linenum;
1094 foreach($fields as $key => $field) {
1095 $rowcols[$filecolumns[$key]] = s($field);
3fe2cfb5 1096 }
8bdb31ed 1097 $rowcols['status'] = array();
3fe2cfb5 1098
8bdb31ed
PS
1099 if (isset($rowcols['username'])) {
1100 $stdusername = clean_param($rowcols['username'], PARAM_USERNAME);
1101 if ($rowcols['username'] !== $stdusername) {
1102 $rowcols['status'][] = get_string('invalidusernameupload');
3fe2cfb5 1103 }
8bdb31ed
PS
1104 if ($userid = $DB->get_field('user', 'id', array('username'=>$stdusername, 'mnethostid'=>$CFG->mnet_localhost_id))) {
1105 $rowcols['username'] = html_writer::link(new moodle_url('/user/profile.php', array('id'=>$userid)), $rowcols['username']);
e4e38544 1106 }
8bdb31ed
PS
1107 } else {
1108 $rowcols['status'][] = get_string('missingusername');
df7ecfe4 1109 }
07ed083e 1110
43070e61
PS
1111 if (isset($rowcols['email'])) {
1112 if (!validate_email($rowcols['email'])) {
1113 $rowcols['status'][] = get_string('invalidemail');
1114 }
1115 if ($DB->record_exists('user', array('email'=>$rowcols['email']))) {
1116 $rowcols['status'][] = $stremailduplicate;
1117 }
07ed083e 1118 }
fd9672ac
RW
1119
1120 if (isset($rowcols['city'])) {
1121 $rowcols['city'] = trim($rowcols['city']);
fd9672ac 1122 }
1b4d2d56
RT
1123 // Check if rowcols have custom profile field with correct data and update error state.
1124 $noerror = uu_check_custom_profile_data($rowcols) && $noerror;
8bdb31ed
PS
1125 $rowcols['status'] = implode('<br />', $rowcols['status']);
1126 $data[] = $rowcols;
07ed083e 1127}
8bdb31ed
PS
1128if ($fields = $cir->next()) {
1129 $data[] = array_fill(0, count($fields) + 2, '...');
07ed083e 1130}
8bdb31ed 1131$cir->close();
3fe2cfb5
RW
1132
1133$table = new html_table();
1134$table->id = "uupreview";
16be8974 1135$table->attributes['class'] = 'generaltable';
3fe2cfb5 1136$table->tablealign = 'center';
ce15d56d 1137$table->summary = get_string('uploaduserspreview', 'tool_uploaduser');
3fe2cfb5 1138$table->head = array();
8bdb31ed 1139$table->data = $data;
3fe2cfb5 1140
ce15d56d 1141$table->head[] = get_string('uucsvline', 'tool_uploaduser');
8bdb31ed
PS
1142foreach ($filecolumns as $column) {
1143 $table->head[] = $column;
07ed083e 1144}
8bdb31ed 1145$table->head[] = get_string('status');
07ed083e 1146
3f12c146 1147echo html_writer::tag('div', html_writer::table($table), array('class'=>'flexible-wrap'));
3fe2cfb5 1148
1b4d2d56
RT
1149// Print the form if valid values are available
1150if ($noerror) {
1151 $mform2->display();
1152}
73d6f52f 1153echo $OUTPUT->footer();
df7ecfe4 1154die;
1155