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