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