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