MDL-31107 Fixing instaces of below where it is written as bellow (two L's)
[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.'/group/lib.php');
31 require_once($CFG->dirroot.'/cohort/lib.php');
32 require_once('locallib.php');
33 require_once('user_form.php');
35 $iid         = optional_param('iid', '', PARAM_INT);
36 $previewrows = optional_param('previewrows', 10, PARAM_INT);
38 @set_time_limit(60*60); // 1 hour should be enough
39 raise_memory_limit(MEMORY_HUGE);
41 require_login();
42 admin_externalpage_setup('tooluploaduser');
43 require_capability('moodle/site:uploadusers', get_context_instance(CONTEXT_SYSTEM));
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 $errorstr                   = get_string('error');
76 $stryes                     = get_string('yes');
77 $strno                      = get_string('no');
78 $stryesnooptions = array(0=>$strno, 1=>$stryes);
80 $returnurl = new moodle_url('/admin/tool/uploaduser/index.php');
81 $bulknurl  = new moodle_url('/admin/user/user_bulk.php');
83 $today = time();
84 $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
86 // array of all valid fields for validation
87 $STD_FIELDS = array('id', 'firstname', 'lastname', 'username', 'email',
88         'city', 'country', 'lang', 'timezone', 'mailformat',
89         'maildisplay', 'maildigest', 'htmleditor', 'ajax', 'autosubscribe',
90         'institution', 'department', 'idnumber', 'skype',
91         'msn', 'aim', 'yahoo', 'icq', 'phone1', 'phone2', 'address',
92         'url', 'description', 'descriptionformat', 'password',
93         'auth',        // watch out when changing auth type or using external auth plugins!
94         'oldusername', // use when renaming users - this is the original username
95         'suspended',   // 1 means suspend user account, 0 means activate user account, nothing means keep as is for existing users
96         'deleted',     // 1 means delete user
97     );
99 $PRF_FIELDS = array();
101 if ($prof_fields = $DB->get_records('user_info_field')) {
102     foreach ($prof_fields as $prof_field) {
103         $PRF_FIELDS[] = 'profile_field_'.$prof_field->shortname;
104     }
106 unset($prof_fields);
108 if (empty($iid)) {
109     $mform1 = new admin_uploaduser_form1();
111     if ($formdata = $mform1->get_data()) {
112         $iid = csv_import_reader::get_new_iid('uploaduser');
113         $cir = new csv_import_reader($iid, 'uploaduser');
115         $content = $mform1->get_file_content('userfile');
117         $readcount = $cir->load_csv_content($content, $formdata->encoding, $formdata->delimiter_name);
118         unset($content);
120         if ($readcount === false) {
121             print_error('csvloaderror', '', $returnurl);
122         } else if ($readcount == 0) {
123             print_error('csvemptyfile', 'error', $returnurl);
124         }
125         // test if columns ok
126         $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
127         // continue to form2
129     } else {
130         echo $OUTPUT->header();
132         echo $OUTPUT->heading_with_help(get_string('uploadusers', 'tool_uploaduser'), 'uploadusers', 'tool_uploaduser');
134         $mform1->display();
135         echo $OUTPUT->footer();
136         die;
137     }
138 } else {
139     $cir = new csv_import_reader($iid, 'uploaduser');
140     $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
143 $mform2 = new admin_uploaduser_form2(null, array('columns'=>$filecolumns, 'data'=>array('iid'=>$iid, 'previewrows'=>$previewrows)));
145 // If a file has been uploaded, then process it
146 if ($formdata = $mform2->is_cancelled()) {
147     $cir->cleanup(true);
148     redirect($returnurl);
150 } else if ($formdata = $mform2->get_data()) {
151     // Print the header
152     echo $OUTPUT->header();
153     echo $OUTPUT->heading(get_string('uploadusersresult', 'tool_uploaduser'));
155     $optype = $formdata->uutype;
157     $updatetype        = isset($formdata->uuupdatetype) ? $formdata->uuupdatetype : 0;
158     $createpasswords   = (!empty($formdata->uupasswordnew) and $optype != UU_USER_UPDATE);
159     $updatepasswords   = (!empty($formdata->uupasswordold)  and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC and ($updatetype == UU_UPDATE_FILEOVERRIDE or $updatetype == UU_UPDATE_ALLOVERRIDE));
160     $allowrenames      = (!empty($formdata->uuallowrenames) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
161     $allowdeletes      = (!empty($formdata->uuallowdeletes) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
162     $allowsuspends     = (!empty($formdata->uuallowsuspends));
163     $bulk              = $formdata->uubulk;
164     $noemailduplicates = $formdata->uunoemailduplicates;
165     $standardusernames = $formdata->uustandardusernames;
166     $resetpasswords    = isset($formdata->uuforcepasswordchange) ? $formdata->uuforcepasswordchange : UU_PWRESET_NONE;
168     // verification moved to two places: after upload and into form2
169     $usersnew      = 0;
170     $usersupdated  = 0;
171     $usersuptodate = 0; //not printed yet anywhere
172     $userserrors   = 0;
173     $deletes       = 0;
174     $deleteerrors  = 0;
175     $renames       = 0;
176     $renameerrors  = 0;
177     $usersskipped  = 0;
178     $weakpasswords = 0;
180     // caches
181     $ccache         = array(); // course cache - do not fetch all courses here, we  will not probably use them all anyway!
182     $cohorts        = array();
183     $rolecache      = uu_allowed_roles_cache(); // roles lookup cache
184     $manualcache    = array(); // cache of used manual enrol plugins in each course
185     $supportedauths = uu_supported_auths(); // officially supported plugins that are enabled
187     // we use only manual enrol plugin here, if it is disabled no enrol is done
188     if (enrol_is_enabled('manual')) {
189         $manual = enrol_get_plugin('manual');
190     } else {
191         $manual = NULL;
192     }
194     // clear bulk selection
195     if ($bulk) {
196         $SESSION->bulk_users = array();
197     }
199     // init csv import helper
200     $cir->init();
201     $linenum = 1; //column header is first line
203     // init upload progress tracker
204     $upt = new uu_progress_tracker();
205     $upt->start(); // start table
207     while ($line = $cir->next()) {
208         $upt->flush();
209         $linenum++;
211         $upt->track('line', $linenum);
213         $user = new stdClass();
215         // add fields to user object
216         foreach ($line as $keynum => $value) {
217             if (!isset($filecolumns[$keynum])) {
218                 // this should not happen
219                 continue;
220             }
221             $key = $filecolumns[$keynum];
222             if (strpos($key, 'profile_field_') === 0) {
223                 //NOTE: bloody mega hack alert!!
224                 if (isset($USER->$key) and is_array($USER->$key)) {
225                     // this must be some hacky field that is abusing arrays to store content and format
226                     $user->$key = array();
227                     $user->$key['text']   = $value;
228                     $user->$key['format'] = FORMAT_MOODLE;
229                 } else {
230                     $user->$key = $value;
231                 }
232             } else {
233                 $user->$key = $value;
234             }
236             if (in_array($key, $upt->columns)) {
237                 // default value in progress tracking table, can be changed later
238                 $upt->track($key, s($value), 'normal');
239             }
240         }
241         if (!isset($user->username)) {
242             // prevent warnings below
243             $user->username = '';
244         }
246         if ($optype == UU_USER_ADDNEW or $optype == UU_USER_ADDINC) {
247             // user creation is a special case - the username may be constructed from templates using firstname and lastname
248             // better never try this in mixed update types
249             $error = false;
250             if (!isset($user->firstname) or $user->firstname === '') {
251                 $upt->track('status', get_string('missingfield', 'error', 'firstname'), 'error');
252                 $upt->track('firstname', $errorstr, 'error');
253                 $error = true;
254             }
255             if (!isset($user->lastname) or $user->lastname === '') {
256                 $upt->track('status', get_string('missingfield', 'error', 'lastname'), 'error');
257                 $upt->track('lastname', $errorstr, 'error');
258                 $error = true;
259             }
260             if ($error) {
261                 $userserrors++;
262                 continue;
263             }
264             // we require username too - we might use template for it though
265             if (empty($user->username) and !empty($formdata->username)) {
266                 $user->username = uu_process_template($formdata->username, $user);
267                 $upt->track('username', s($user->username));
268             }
269         }
271         // normalize username
272         $originalusername = $user->username;
273         if ($standardusernames) {
274             $user->username = clean_param($user->username, PARAM_USERNAME);
275         }
277         // make sure we really have username
278         if (empty($user->username)) {
279             $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
280             $upt->track('username', $errorstr, 'error');
281             $userserrors++;
282             continue;
283         } else if ($user->username === 'guest') {
284             $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
285             $userserrors++;
286             continue;
287         }
289         if ($existinguser = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$CFG->mnet_localhost_id))) {
290             $upt->track('id', $existinguser->id, 'normal', false);
291         }
293         // find out in username incrementing required
294         if ($existinguser and $optype == UU_USER_ADDINC) {
295             $user->username = uu_increment_username($user->username);
296             $existinguser = false;
297         }
299         // notify about nay username changes
300         if ($originalusername !== $user->username) {
301             $upt->track('username', '', 'normal', false); // clear previous
302             $upt->track('username', s($originalusername).'-->'.s($user->username), 'info');
303         } else {
304             $upt->track('username', s($user->username), 'normal', false);
305         }
307         // add default values for remaining fields
308         $formdefaults = array();
309         foreach ($STD_FIELDS as $field) {
310             if (isset($user->$field)) {
311                 continue;
312             }
313             // all validation moved to form2
314             if (isset($formdata->$field)) {
315                 // process templates
316                 $user->$field = uu_process_template($formdata->$field, $user);
317                 $formdefaults[$field] = true;
318                 if (in_array($field, $upt->columns)) {
319                     $upt->track($field, s($user->$field), 'normal');
320                 }
321             }
322         }
323         foreach ($PRF_FIELDS as $field) {
324             if (isset($user->$field)) {
325                 continue;
326             }
327             if (isset($formdata->$field)) {
328                 // process templates
329                 $user->$field = uu_process_template($formdata->$field, $user);
330                 $formdefaults[$field] = true;
331             }
332         }
334         // delete user
335         if (!empty($user->deleted)) {
336             if (!$allowdeletes) {
337                 $usersskipped++;
338                 $upt->track('status', $strusernotdeletedoff, 'warning');
339                 continue;
340             }
341             if ($existinguser) {
342                 if (is_siteadmin($existinguser->id)) {
343                     $upt->track('status', $strusernotdeletedadmin, 'error');
344                     $deleteerrors++;
345                     continue;
346                 }
347                 if (delete_user($existinguser)) {
348                     $upt->track('status', $struserdeleted);
349                     $deletes++;
350                 } else {
351                     $upt->track('status', $strusernotdeletederror, 'error');
352                     $deleteerrors++;
353                 }
354             } else {
355                 $upt->track('status', $strusernotdeletedmissing, 'error');
356                 $deleteerrors++;
357             }
358             continue;
359         }
360         // we do not need the deleted flag anymore
361         unset($user->deleted);
363         // renaming requested?
364         if (!empty($user->oldusername) ) {
365             if (!$allowrenames) {
366                 $usersskipped++;
367                 $upt->track('status', $strusernotrenamedoff, 'warning');
368                 continue;
369             }
371             if ($existinguser) {
372                 $upt->track('status', $strusernotrenamedexists, 'error');
373                 $renameerrors++;
374                 continue;
375             }
377             if ($user->username === 'guest') {
378                 $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
379                 $renameerrors++;
380                 continue;
381             }
383             if ($standardusernames) {
384                 $oldusername = clean_param($user->oldusername, PARAM_USERNAME);
385             } else {
386                 $oldusername = $user->oldusername;
387             }
389             // no guessing when looking for old username, it must be exact match
390             if ($olduser = $DB->get_record('user', array('username'=>$oldusername, 'mnethostid'=>$CFG->mnet_localhost_id))) {
391                 $upt->track('id', $olduser->id, 'normal', false);
392                 if (is_siteadmin($olduser->id)) {
393                     $upt->track('status', $strusernotrenamedadmin, 'error');
394                     $renameerrors++;
395                     continue;
396                 }
397                 $DB->set_field('user', 'username', $user->username, array('id'=>$olduser->id));
398                 $upt->track('username', '', 'normal', false); // clear previous
399                 $upt->track('username', s($oldusername).'-->'.s($user->username), 'info');
400                 $upt->track('status', $struserrenamed);
401                 $renames++;
402             } else {
403                 $upt->track('status', $strusernotrenamedmissing, 'error');
404                 $renameerrors++;
405                 continue;
406             }
407             $existinguser = $olduser;
408             $existinguser->username = $user->username;
409         }
411         // can we process with update or insert?
412         $skip = false;
413         switch ($optype) {
414             case UU_USER_ADDNEW:
415                 if ($existinguser) {
416                     $usersskipped++;
417                     $upt->track('status', $strusernotadded, 'warning');
418                     $skip = true;
419                 }
420                 break;
422             case UU_USER_ADDINC:
423                 if ($existinguser) {
424                     //this should not happen!
425                     $upt->track('status', $strusernotaddederror, 'error');
426                     $userserrors++;
427                     $skip = true;
428                 }
429                 break;
431             case UU_USER_ADD_UPDATE:
432                 break;
434             case UU_USER_UPDATE:
435                 if (!$existinguser) {
436                     $usersskipped++;
437                     $upt->track('status', $strusernotupdatednotexists, 'warning');
438                     $skip = true;
439                 }
440                 break;
442             default:
443                 // unknown type
444                 $skip = true;
445         }
447         if ($skip) {
448             continue;
449         }
451         if ($existinguser) {
452             $user->id = $existinguser->id;
454             $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id'=>$existinguser->id)), s($existinguser->username)), 'normal', false);
455             $upt->track('suspended', $stryesnooptions[$existinguser->suspended] , 'normal', false);
457             if (is_siteadmin($user->id)) {
458                 $upt->track('status', $strusernotupdatedadmin, 'error');
459                 $userserrors++;
460                 continue;
461             }
463             $existinguser->timemodified = time();
464             // do NOT mess with timecreated or firstaccess here!
466             //load existing profile data
467             profile_load_data($existinguser);
469             $upt->track('auth', $existinguser->auth, 'normal', false);
471             $doupdate = false;
472             $dologout = false;
474             if ($updatetype != UU_UPDATE_NOCHANGES) {
475                 if (!empty($user->auth) and $user->auth !== $existinguser->auth) {
476                     $upt->track('auth', s($existinguser->auth).'-->'.s($user->auth), 'info', false);
477                     $existinguser->auth = $user->auth;
478                     if (!isset($supportedauths[$user->auth])) {
479                         $upt->track('auth', $struserauthunsupported, 'warning');
480                     }
481                     $doupdate = true;
482                     if ($existinguser->auth === 'nologin') {
483                         $dologout = true;
484                     }
485                 }
486                 $allcolumns = array_merge($STD_FIELDS, $PRF_FIELDS);
487                 foreach ($allcolumns as $column) {
488                     if ($column === 'username' or $column === 'password' or $column === 'auth' or $column === 'suspended') {
489                         // these can not be changed here
490                         continue;
491                     }
492                     if (!property_exists($user, $column) or !property_exists($existinguser, $column)) {
493                         // this should never happen
494                         continue;
495                     }
496                     if ($updatetype == UU_UPDATE_MISSING) {
497                         if (!is_null($existinguser->$column) and $existinguser->$column !== '') {
498                             continue;
499                         }
500                     } else if ($updatetype == UU_UPDATE_ALLOVERRIDE) {
501                         // we override everything
503                     } else if ($updatetype == UU_UPDATE_FILEOVERRIDE) {
504                         if (!empty($formdefaults[$column])) {
505                             // do not override with form defaults
506                             continue;
507                         }
508                     }
509                     if ($existinguser->$column !== $user->$column) {
510                         if ($column === 'email') {
511                             if ($DB->record_exists('user', array('email'=>$user->email))) {
512                                 if ($noemailduplicates) {
513                                     $upt->track('email', $stremailduplicate, 'error');
514                                     $upt->track('status', $strusernotupdated, 'error');
515                                     $userserrors++;
516                                     continue 2;
517                                 } else {
518                                     $upt->track('email', $stremailduplicate, 'warning');
519                                 }
520                             }
521                             if (!validate_email($user->email)) {
522                                 $upt->track('email', get_string('invalidemail'), 'warning');
523                             }
524                         }
526                         if (in_array($column, $upt->columns)) {
527                             $upt->track($column, s($existinguser->$column).'-->'.s($user->$column), 'info', false);
528                         }
529                         $existinguser->$column = $user->$column;
530                         $doupdate = true;
531                     }
532                 }
533             }
535             try {
536                 $auth = get_auth_plugin($existinguser->auth);
537             } catch (Exception $e) {
538                 $upt->track('auth', get_string('userautherror', 'error', s($existinguser->auth)), 'error');
539                 $upt->track('status', $strusernotupdated, 'error');
540                 $userserrors++;
541                 continue;
542             }
543             $isinternalauth = $auth->is_internal();
545             // deal with suspending and activating of accounts
546             if ($allowsuspends and isset($user->suspended) and $user->suspended !== '') {
547                 $user->suspended = $user->suspended ? 1 : 0;
548                 if ($existinguser->suspended != $user->suspended) {
549                     $upt->track('suspended', '', 'normal', false);
550                     $upt->track('suspended', $stryesnooptions[$existinguser->suspended].'-->'.$stryesnooptions[$user->suspended], 'info', false);
551                     $existinguser->suspended = $user->suspended;
552                     $doupdate = true;
553                     if ($existinguser->suspended) {
554                         $dologout = true;
555                     }
556                 }
557             }
559             // changing of passwords is a special case
560             // do not force password changes for external auth plugins!
561             $oldpw = $existinguser->password;
562             if (!$isinternalauth) {
563                 $existinguser->password = 'not cached';
564                 $upt->track('password', '-', 'normal', false);
565                 // clean up prefs
566                 unset_user_preference('create_password', $existinguser);
567                 unset_user_preference('auth_forcepasswordchange', $existinguser);
569             } else if (!empty($user->password)) {
570                 if ($updatepasswords) {
571                     $errmsg = null;
572                     $weak = !check_password_policy($user->password, $errmsg);
573                     if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
574                         if ($weak) {
575                             $weakpasswords++;
576                             $upt->track('password', $strinvalidpasswordpolicy, 'warning');
577                         }
578                         set_user_preference('auth_forcepasswordchange', 1, $existinguser);
579                     } else {
580                         unset_user_preference('auth_forcepasswordchange', $existinguser);
581                     }
582                     unset_user_preference('create_password', $existinguser); // no need to create password any more
583                     $existinguser->password = hash_internal_user_password($user->password);
584                     $upt->track('password', $user->password, 'normal', false);
585                 } else {
586                     // do not print password when not changed
587                     $upt->track('password', '', 'normal', false);
588                 }
589             }
591             if ($doupdate or $existinguser->password !== $oldpw) {
592                 // we want only users that were really updated
594                 $DB->update_record('user', $existinguser);
596                 $upt->track('status', $struserupdated);
597                 $usersupdated++;
598                 // save custom profile fields data from csv file
599                 profile_save_data($existinguser);
601                 events_trigger('user_updated', $existinguser);
603                 if ($bulk == UU_BULK_UPDATED or $bulk == UU_BULK_ALL) {
604                     if (!in_array($user->id, $SESSION->bulk_users)) {
605                         $SESSION->bulk_users[] = $user->id;
606                     }
607                 }
609             } else {
610                 // no user information changed
611                 $upt->track('status', $struseruptodate);
612                 $usersuptodate++;
614                 if ($bulk == UU_BULK_ALL) {
615                     if (!in_array($user->id, $SESSION->bulk_users)) {
616                         $SESSION->bulk_users[] = $user->id;
617                     }
618                 }
619             }
621             if ($dologout) {
622                 session_kill_user($existinguser->id);
623             }
625         } else {
626             // save the new user to the database
627             $user->confirmed    = 1;
628             $user->timemodified = time();
629             $user->timecreated  = time();
630             $user->mnethostid   = $CFG->mnet_localhost_id; // we support ONLY local accounts here, sorry
632             if (!isset($user->suspended) or $user->suspended === '') {
633                 $user->suspended = 0;
634             } else {
635                 $user->suspended = $user->suspended ? 1 : 0;
636             }
637             $upt->track('suspended', $stryesnooptions[$user->suspended], 'normal', false);
639             if (empty($user->auth)) {
640                 $user->auth = 'manual';
641             }
642             $upt->track('auth', $user->auth, 'normal', false);
644             // do not insert record if new auth plugin does not exist!
645             try {
646                 $auth = get_auth_plugin($user->auth);
647             } catch (Exception $e) {
648                 $upt->track('auth', get_string('userautherror', 'error', s($user->auth)), 'error');
649                 $upt->track('status', $strusernotaddederror, 'error');
650                 $userserrors++;
651                 continue;
652             }
653             if (!isset($supportedauths[$user->auth])) {
654                 $upt->track('auth', $struserauthunsupported, 'warning');
655             }
657             $isinternalauth = $auth->is_internal();
659             if (empty($user->email)) {
660                 $upt->track('email', get_string('invalidemail'), 'error');
661                 $upt->track('status', $strusernotaddederror, 'error');
662                 $userserrors++;
663                 continue;
665             } else if ($DB->record_exists('user', array('email'=>$user->email))) {
666                 if ($noemailduplicates) {
667                     $upt->track('email', $stremailduplicate, 'error');
668                     $upt->track('status', $strusernotaddederror, 'error');
669                     $userserrors++;
670                     continue;
671                 } else {
672                     $upt->track('email', $stremailduplicate, 'warning');
673                 }
674             }
675             if (!validate_email($user->email)) {
676                 $upt->track('email', get_string('invalidemail'), 'warning');
677             }
679             $forcechangepassword = false;
681             if ($isinternalauth) {
682                 if (empty($user->password)) {
683                     if ($createpasswords) {
684                         $user->password = 'to be generated';
685                         $upt->track('password', '', 'normal', false);
686                         $upt->track('password', get_string('uupasswordcron', 'tool_uploaduser'), 'warning', false);
687                     } else {
688                         $upt->track('password', '', 'normal', false);
689                         $upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
690                         $upt->track('status', $strusernotaddederror, 'error');
691                         $userserrors++;
692                         continue;
693                     }
694                 } else {
695                     $errmsg = null;
696                     $weak = !check_password_policy($user->password, $errmsg);
697                     if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
698                         if ($weak) {
699                             $weakpasswords++;
700                             $upt->track('password', $strinvalidpasswordpolicy, 'warning');
701                         }
702                         $forcechangepassword = true;
703                     }
704                     $user->password = hash_internal_user_password($user->password);
705                 }
706             } else {
707                 $user->password = 'not cached';
708                 $upt->track('password', '-', 'normal', false);
709             }
711             // create user - insert_record ignores any extra properties
712             $user->id = $DB->insert_record('user', $user);
713             $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id'=>$user->id)), s($user->username)), 'normal', false);
715             // save custom profile fields data
716             profile_save_data($user);
718             if ($forcechangepassword) {
719                 set_user_preference('auth_forcepasswordchange', 1, $user);
720             }
721             if ($user->password === 'to be generated') {
722                 set_user_preference('create_password', 1, $user);
723             }
725             $upt->track('status', $struseradded);
726             $upt->track('id', $user->id, 'normal', false);
727             $usersnew++;
729             // make sure user context exists
730             get_context_instance(CONTEXT_USER, $user->id);
732             events_trigger('user_created', $user);
734             if ($bulk == UU_BULK_NEW or $bulk == UU_BULK_ALL) {
735                 if (!in_array($user->id, $SESSION->bulk_users)) {
736                     $SESSION->bulk_users[] = $user->id;
737                 }
738             }
739         }
742         // add to cohort first, it might trigger enrolments indirectly - do NOT create cohorts here!
743         foreach ($filecolumns as $column) {
744             if (!preg_match('/^cohort\d+$/', $column)) {
745                 continue;
746             }
748             if (!empty($user->$column)) {
749                 $addcohort = $user->$column;
750                 if (!isset($cohorts[$addcohort])) {
751                     if (is_number($addcohort)) {
752                         // only non-numeric idnumbers!
753                         $cohort = $DB->get_record('cohort', array('id'=>$addcohort));
754                     } else {
755                         $cohort = $DB->get_record('cohort', array('idnumber'=>$addcohort));
756                     }
758                     if (empty($cohort)) {
759                         $cohorts[$addcohort] = get_string('unknowncohort', 'core_cohort', s($addcohort));
760                     } else if (!empty($cohort->component)) {
761                         // cohorts synchronised with external sources must not be modified!
762                         $cohorts[$addcohort] = get_string('external', 'core_cohort');
763                     } else {
764                         $cohorts[$addcohort] = $cohort;
765                     }
766                 }
768                 if (is_object($cohorts[$addcohort])) {
769                     $cohort = $cohorts[$addcohort];
770                     if (!$DB->record_exists('cohort_members', array('cohortid'=>$cohort->id, 'userid'=>$user->id))) {
771                         cohort_add_member($cohort->id, $user->id);
772                         // we might add special column later, for now let's abuse enrolments
773                         $upt->track('enrolments', get_string('useradded', 'core_cohort', s($cohort->name)));
774                     }
775                 } else {
776                     // error message
777                     $upt->track('enrolments', $cohorts[$addcohort], 'error');
778                 }
779             }
780         }
783         // find course enrolments, groups, roles/types and enrol periods
784         // this is again a special case, we always do this for any updated or created users
785         foreach ($filecolumns as $column) {
786             if (!preg_match('/^course\d+$/', $column)) {
787                 continue;
788             }
789             $i = substr($column, 6);
791             if (empty($user->{'course'.$i})) {
792                 continue;
793             }
794             $shortname = $user->{'course'.$i};
795             if (!array_key_exists($shortname, $ccache)) {
796                 if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname')) {
797                     $upt->track('enrolments', get_string('unknowncourse', 'error', s($shortname)), 'error');
798                     continue;
799                 }
800                 $ccache[$shortname] = $course;
801                 $ccache[$shortname]->groups = null;
802             }
803             $courseid      = $ccache[$shortname]->id;
804             $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
805             if (!isset($manualcache[$courseid])) {
806                 $manualcache[$courseid] = false;
807                 if ($manual) {
808                     if ($instances = enrol_get_instances($courseid, false)) {
809                         foreach ($instances as $instance) {
810                             if ($instance->enrol === 'manual') {
811                                 $manualcache[$courseid] = $instance;
812                                 break;
813                             }
814                         }
815                     }
816                 }
817             }
819             if ($manual and $manualcache[$courseid]) {
821                 // find role
822                 $rid = false;
823                 if (!empty($user->{'role'.$i})) {
824                     $addrole = $user->{'role'.$i};
825                     if (array_key_exists($addrole, $rolecache)) {
826                         $rid = $rolecache[$addrole]->id;
827                     } else {
828                         $upt->track('enrolments', get_string('unknownrole', 'error', s($addrole)), 'error');
829                         continue;
830                     }
832                 } else if (!empty($user->{'type'.$i})) {
833                     // if no role, then find "old" enrolment type
834                     $addtype = $user->{'type'.$i};
835                     if ($addtype < 1 or $addtype > 3) {
836                         $upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
837                         continue;
838                     } else if (empty($formdata->{'uulegacy'.$addtype})) {
839                         continue;
840                     } else {
841                         $rid = $formdata->{'uulegacy'.$addtype};
842                     }
843                 } else {
844                     // no role specified, use the default from manual enrol plugin
845                     $rid = $manualcache[$courseid]->roleid;
846                 }
848                 if ($rid) {
849                     // find duration
850                     $timeend   = 0;
851                     if (!empty($user->{'enrolperiod'.$i})) {
852                         $duration = (int)$user->{'enrolperiod'.$i} * 60*60*24; // convert days to seconds
853                         if ($duration > 0) { // sanity check
854                             $timeend = $today + $duration;
855                         }
856                     }
858                     $manual->enrol_user($manualcache[$courseid], $user->id, $rid, $today, $timeend);
860                     $a = new stdClass();
861                     $a->course = $shortname;
862                     $a->role   = $rolecache[$rid]->name;
863                     $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
864                 }
865             }
867             // find group to add to
868             if (!empty($user->{'group'.$i})) {
869                 // make sure user is enrolled into course before adding into groups
870                 if (!is_enrolled($coursecontext, $user->id)) {
871                     $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group'.$i}), 'error');
872                     continue;
873                 }
874                 //build group cache
875                 if (is_null($ccache[$shortname]->groups)) {
876                     $ccache[$shortname]->groups = array();
877                     if ($groups = groups_get_all_groups($courseid)) {
878                         foreach ($groups as $gid=>$group) {
879                             $ccache[$shortname]->groups[$gid] = new stdClass();
880                             $ccache[$shortname]->groups[$gid]->id   = $gid;
881                             $ccache[$shortname]->groups[$gid]->name = $group->name;
882                             if (!is_numeric($group->name)) { // only non-numeric names are supported!!!
883                                 $ccache[$shortname]->groups[$group->name] = new stdClass();
884                                 $ccache[$shortname]->groups[$group->name]->id   = $gid;
885                                 $ccache[$shortname]->groups[$group->name]->name = $group->name;
886                             }
887                         }
888                     }
889                 }
890                 // group exists?
891                 $addgroup = $user->{'group'.$i};
892                 if (!array_key_exists($addgroup, $ccache[$shortname]->groups)) {
893                     // if group doesn't exist,  create it
894                     $newgroupdata = new stdClass();
895                     $newgroupdata->name = $addgroup;
896                     $newgroupdata->courseid = $ccache[$shortname]->id;
897                     if ($ccache[$shortname]->groups[$addgroup]->id = groups_create_group($newgroupdata)){
898                         $ccache[$shortname]->groups[$addgroup]->name = $newgroupdata->name;
899                     } else {
900                         $upt->track('enrolments', get_string('unknowngroup', 'error', s($addgroup)), 'error');
901                         continue;
902                     }
903                 }
904                 $gid   = $ccache[$shortname]->groups[$addgroup]->id;
905                 $gname = $ccache[$shortname]->groups[$addgroup]->name;
907                 try {
908                     if (groups_add_member($gid, $user->id)) {
909                         $upt->track('enrolments', get_string('addedtogroup', '', s($gname)));
910                     }  else {
911                         $upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
912                     }
913                 } catch (moodle_exception $e) {
914                     $upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
915                     continue;
916                 }
917             }
918         }
919     }
920     $upt->close(); // close table
922     $cir->close();
923     $cir->cleanup(true);
925     echo $OUTPUT->box_start('boxwidthnarrow boxaligncenter generalbox', 'uploadresults');
926     echo '<p>';
927     if ($optype != UU_USER_UPDATE) {
928         echo get_string('userscreated', 'tool_uploaduser').': '.$usersnew.'<br />';
929     }
930     if ($optype == UU_USER_UPDATE or $optype == UU_USER_ADD_UPDATE) {
931         echo get_string('usersupdated', 'tool_uploaduser').': '.$usersupdated.'<br />';
932     }
933     if ($allowdeletes) {
934         echo get_string('usersdeleted', 'tool_uploaduser').': '.$deletes.'<br />';
935         echo get_string('deleteerrors', 'tool_uploaduser').': '.$deleteerrors.'<br />';
936     }
937     if ($allowrenames) {
938         echo get_string('usersrenamed', 'tool_uploaduser').': '.$renames.'<br />';
939         echo get_string('renameerrors', 'tool_uploaduser').': '.$renameerrors.'<br />';
940     }
941     if ($usersskipped) {
942         echo get_string('usersskipped', 'tool_uploaduser').': '.$usersskipped.'<br />';
943     }
944     echo get_string('usersweakpassword', 'tool_uploaduser').': '.$weakpasswords.'<br />';
945     echo get_string('errors', 'tool_uploaduser').': '.$userserrors.'</p>';
946     echo $OUTPUT->box_end();
948     if ($bulk) {
949         echo $OUTPUT->continue_button($bulknurl);
950     } else {
951         echo $OUTPUT->continue_button($returnurl);
952     }
953     echo $OUTPUT->footer();
954     die;
957 // Print the header
958 echo $OUTPUT->header();
960 echo $OUTPUT->heading(get_string('uploaduserspreview', 'tool_uploaduser'));
962 // NOTE: this is JUST csv processing preview, we must not prevent import from here if there is something in the file!!
963 //       this was intended for validation of csv formatting and encoding, not filtering the data!!!!
964 //       we definitely must not process the whole file!
966 // preview table data
967 $data = array();
968 $cir->init();
969 $linenum = 1; //column header is first line
970 while ($linenum <= $previewrows and $fields = $cir->next()) {
971     $linenum++;
972     $rowcols = array();
973     $rowcols['line'] = $linenum;
974     foreach($fields as $key => $field) {
975         $rowcols[$filecolumns[$key]] = s($field);
976     }
977     $rowcols['status'] = array();
979     if (isset($rowcols['username'])) {
980         $stdusername = clean_param($rowcols['username'], PARAM_USERNAME);
981         if ($rowcols['username'] !== $stdusername) {
982             $rowcols['status'][] = get_string('invalidusernameupload');
983         }
984         if ($userid = $DB->get_field('user', 'id', array('username'=>$stdusername, 'mnethostid'=>$CFG->mnet_localhost_id))) {
985             $rowcols['username'] = html_writer::link(new moodle_url('/user/profile.php', array('id'=>$userid)), $rowcols['username']);
986         }
987     } else {
988         $rowcols['status'][] = get_string('missingusername');
989     }
991     if (isset($rowcols['email'])) {
992         if (!validate_email($rowcols['email'])) {
993             $rowcols['status'][] = get_string('invalidemail');
994         }
995         if ($DB->record_exists('user', array('email'=>$rowcols['email']))) {
996             $rowcols['status'][] = $stremailduplicate;
997         }
998     }
1000     if (isset($rowcols['city'])) {
1001         $rowcols['city'] = trim($rowcols['city']);
1002         if (empty($rowcols['city'])) {
1003             $rowcols['status'][] = get_string('fieldrequired', 'error', 'city');
1004         }
1005     }
1007     $rowcols['status'] = implode('<br />', $rowcols['status']);
1008     $data[] = $rowcols;
1010 if ($fields = $cir->next()) {
1011     $data[] = array_fill(0, count($fields) + 2, '...');
1013 $cir->close();
1015 $table = new html_table();
1016 $table->id = "uupreview";
1017 $table->attributes['class'] = 'generaltable';
1018 $table->tablealign = 'center';
1019 $table->summary = get_string('uploaduserspreview', 'tool_uploaduser');
1020 $table->head = array();
1021 $table->data = $data;
1023 $table->head[] = get_string('uucsvline', 'tool_uploaduser');
1024 foreach ($filecolumns as $column) {
1025     $table->head[] = $column;
1027 $table->head[] = get_string('status');
1029 echo html_writer::tag('div', html_writer::table($table), array('class'=>'flexible-wrap'));
1031 /// Print the form
1033 $mform2->display();
1034 echo $OUTPUT->footer();
1035 die;