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