PageRenderTime 67ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/admin/tool/uploaduser/index.php

http://github.com/moodle/moodle
PHP | 1273 lines | 991 code | 156 blank | 126 comment | 285 complexity | 0c005b7b24eecee89bf61ae82c76758a MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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/>.
  16. /**
  17. * Bulk user registration script from a comma separated file
  18. *
  19. * @package tool
  20. * @subpackage uploaduser
  21. * @copyright 2004 onwards Martin Dougiamas (http://dougiamas.com)
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. require('../../../config.php');
  25. require_once($CFG->libdir.'/adminlib.php');
  26. require_once($CFG->libdir.'/csvlib.class.php');
  27. require_once($CFG->dirroot.'/user/profile/lib.php');
  28. require_once($CFG->dirroot.'/user/lib.php');
  29. require_once($CFG->dirroot.'/group/lib.php');
  30. require_once($CFG->dirroot.'/cohort/lib.php');
  31. require_once('locallib.php');
  32. require_once('user_form.php');
  33. require_once('classes/local/field_value_validators.php');
  34. use tool_uploaduser\local\field_value_validators;
  35. $iid = optional_param('iid', '', PARAM_INT);
  36. $previewrows = optional_param('previewrows', 10, PARAM_INT);
  37. core_php_time_limit::raise(60*60); // 1 hour should be enough
  38. raise_memory_limit(MEMORY_HUGE);
  39. admin_externalpage_setup('tooluploaduser');
  40. require_capability('moodle/site:uploadusers', context_system::instance());
  41. $struserrenamed = get_string('userrenamed', 'tool_uploaduser');
  42. $strusernotrenamedexists = get_string('usernotrenamedexists', 'error');
  43. $strusernotrenamedmissing = get_string('usernotrenamedmissing', 'error');
  44. $strusernotrenamedoff = get_string('usernotrenamedoff', 'error');
  45. $strusernotrenamedadmin = get_string('usernotrenamedadmin', 'error');
  46. $struserupdated = get_string('useraccountupdated', 'tool_uploaduser');
  47. $strusernotupdated = get_string('usernotupdatederror', 'error');
  48. $strusernotupdatednotexists = get_string('usernotupdatednotexists', 'error');
  49. $strusernotupdatedadmin = get_string('usernotupdatedadmin', 'error');
  50. $struseruptodate = get_string('useraccountuptodate', 'tool_uploaduser');
  51. $struseradded = get_string('newuser');
  52. $strusernotadded = get_string('usernotaddedregistered', 'error');
  53. $strusernotaddederror = get_string('usernotaddederror', 'error');
  54. $struserdeleted = get_string('userdeleted', 'tool_uploaduser');
  55. $strusernotdeletederror = get_string('usernotdeletederror', 'error');
  56. $strusernotdeletedmissing = get_string('usernotdeletedmissing', 'error');
  57. $strusernotdeletedoff = get_string('usernotdeletedoff', 'error');
  58. $strusernotdeletedadmin = get_string('usernotdeletedadmin', 'error');
  59. $strcannotassignrole = get_string('cannotassignrole', 'error');
  60. $struserauthunsupported = get_string('userauthunsupported', 'error');
  61. $stremailduplicate = get_string('useremailduplicate', 'error');
  62. $strinvalidpasswordpolicy = get_string('invalidpasswordpolicy', 'error');
  63. $errorstr = get_string('error');
  64. $stryes = get_string('yes');
  65. $strno = get_string('no');
  66. $stryesnooptions = array(0=>$strno, 1=>$stryes);
  67. $returnurl = new moodle_url('/admin/tool/uploaduser/index.php');
  68. $bulknurl = new moodle_url('/admin/user/user_bulk.php');
  69. $today = time();
  70. $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
  71. // array of all valid fields for validation
  72. $STD_FIELDS = array('id', 'username', 'email', 'emailstop',
  73. 'city', 'country', 'lang', 'timezone', 'mailformat',
  74. 'maildisplay', 'maildigest', 'htmleditor', 'autosubscribe',
  75. 'institution', 'department', 'idnumber', 'skype',
  76. 'msn', 'aim', 'yahoo', 'icq', 'phone1', 'phone2', 'address',
  77. 'url', 'description', 'descriptionformat', 'password',
  78. 'auth', // watch out when changing auth type or using external auth plugins!
  79. 'oldusername', // use when renaming users - this is the original username
  80. 'suspended', // 1 means suspend user account, 0 means activate user account, nothing means keep as is for existing users
  81. 'theme', // Define a theme for user when 'allowuserthemes' is enabled.
  82. 'deleted', // 1 means delete user
  83. 'mnethostid', // Can not be used for adding, updating or deleting of users - only for enrolments, groups, cohorts and suspending.
  84. 'interests',
  85. );
  86. // Include all name fields.
  87. $STD_FIELDS = array_merge($STD_FIELDS, get_all_user_name_fields());
  88. $PRF_FIELDS = array();
  89. if ($proffields = $DB->get_records('user_info_field')) {
  90. foreach ($proffields as $key => $proffield) {
  91. $profilefieldname = 'profile_field_'.$proffield->shortname;
  92. $PRF_FIELDS[] = $profilefieldname;
  93. // Re-index $proffields with key as shortname. This will be
  94. // used while checking if profile data is key and needs to be converted (eg. menu profile field)
  95. $proffields[$profilefieldname] = $proffield;
  96. unset($proffields[$key]);
  97. }
  98. }
  99. if (empty($iid)) {
  100. $mform1 = new admin_uploaduser_form1();
  101. if ($formdata = $mform1->get_data()) {
  102. $iid = csv_import_reader::get_new_iid('uploaduser');
  103. $cir = new csv_import_reader($iid, 'uploaduser');
  104. $content = $mform1->get_file_content('userfile');
  105. $readcount = $cir->load_csv_content($content, $formdata->encoding, $formdata->delimiter_name);
  106. $csvloaderror = $cir->get_error();
  107. unset($content);
  108. if (!is_null($csvloaderror)) {
  109. print_error('csvloaderror', '', $returnurl, $csvloaderror);
  110. }
  111. // test if columns ok
  112. $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
  113. // continue to form2
  114. } else {
  115. echo $OUTPUT->header();
  116. echo $OUTPUT->heading_with_help(get_string('uploadusers', 'tool_uploaduser'), 'uploadusers', 'tool_uploaduser');
  117. $mform1->display();
  118. echo $OUTPUT->footer();
  119. die;
  120. }
  121. } else {
  122. $cir = new csv_import_reader($iid, 'uploaduser');
  123. $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
  124. }
  125. $mform2 = new admin_uploaduser_form2(null, array('columns'=>$filecolumns, 'data'=>array('iid'=>$iid, 'previewrows'=>$previewrows)));
  126. // If a file has been uploaded, then process it
  127. if ($formdata = $mform2->is_cancelled()) {
  128. $cir->cleanup(true);
  129. redirect($returnurl);
  130. } else if ($formdata = $mform2->get_data()) {
  131. // Print the header
  132. echo $OUTPUT->header();
  133. echo $OUTPUT->heading(get_string('uploadusersresult', 'tool_uploaduser'));
  134. $optype = $formdata->uutype;
  135. $updatetype = isset($formdata->uuupdatetype) ? $formdata->uuupdatetype : 0;
  136. $createpasswords = (!empty($formdata->uupasswordnew) and $optype != UU_USER_UPDATE);
  137. $updatepasswords = (!empty($formdata->uupasswordold) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC and ($updatetype == UU_UPDATE_FILEOVERRIDE or $updatetype == UU_UPDATE_ALLOVERRIDE));
  138. $allowrenames = (!empty($formdata->uuallowrenames) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
  139. $allowdeletes = (!empty($formdata->uuallowdeletes) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
  140. $allowsuspends = (!empty($formdata->uuallowsuspends));
  141. $bulk = $formdata->uubulk;
  142. $noemailduplicates = empty($CFG->allowaccountssameemail) ? 1 : $formdata->uunoemailduplicates;
  143. $standardusernames = $formdata->uustandardusernames;
  144. $resetpasswords = isset($formdata->uuforcepasswordchange) ? $formdata->uuforcepasswordchange : UU_PWRESET_NONE;
  145. // verification moved to two places: after upload and into form2
  146. $usersnew = 0;
  147. $usersupdated = 0;
  148. $usersuptodate = 0; //not printed yet anywhere
  149. $userserrors = 0;
  150. $deletes = 0;
  151. $deleteerrors = 0;
  152. $renames = 0;
  153. $renameerrors = 0;
  154. $usersskipped = 0;
  155. $weakpasswords = 0;
  156. // caches
  157. $ccache = array(); // course cache - do not fetch all courses here, we will not probably use them all anyway!
  158. $cohorts = array();
  159. $rolecache = uu_allowed_roles_cache(); // Course roles lookup cache.
  160. $sysrolecache = uu_allowed_sysroles_cache(); // System roles lookup cache.
  161. $manualcache = array(); // cache of used manual enrol plugins in each course
  162. $supportedauths = uu_supported_auths(); // officially supported plugins that are enabled
  163. // we use only manual enrol plugin here, if it is disabled no enrol is done
  164. if (enrol_is_enabled('manual')) {
  165. $manual = enrol_get_plugin('manual');
  166. } else {
  167. $manual = NULL;
  168. }
  169. // clear bulk selection
  170. if ($bulk) {
  171. $SESSION->bulk_users = array();
  172. }
  173. // init csv import helper
  174. $cir->init();
  175. $linenum = 1; //column header is first line
  176. // init upload progress tracker
  177. $upt = new uu_progress_tracker();
  178. $upt->start(); // start table
  179. $validation = array();
  180. while ($line = $cir->next()) {
  181. $upt->flush();
  182. $linenum++;
  183. $upt->track('line', $linenum);
  184. $user = new stdClass();
  185. // add fields to user object
  186. foreach ($line as $keynum => $value) {
  187. if (!isset($filecolumns[$keynum])) {
  188. // this should not happen
  189. continue;
  190. }
  191. $key = $filecolumns[$keynum];
  192. if (strpos($key, 'profile_field_') === 0) {
  193. //NOTE: bloody mega hack alert!!
  194. if (isset($USER->$key) and is_array($USER->$key)) {
  195. // this must be some hacky field that is abusing arrays to store content and format
  196. $user->$key = array();
  197. $user->{$key['text']} = $value;
  198. $user->{$key['format']} = FORMAT_MOODLE;
  199. } else {
  200. $user->$key = trim($value);
  201. }
  202. } else {
  203. $user->$key = trim($value);
  204. }
  205. if (in_array($key, $upt->columns)) {
  206. // default value in progress tracking table, can be changed later
  207. $upt->track($key, s($value), 'normal');
  208. }
  209. }
  210. if (!isset($user->username)) {
  211. // prevent warnings below
  212. $user->username = '';
  213. }
  214. if ($optype == UU_USER_ADDNEW or $optype == UU_USER_ADDINC) {
  215. // user creation is a special case - the username may be constructed from templates using firstname and lastname
  216. // better never try this in mixed update types
  217. $error = false;
  218. if (!isset($user->firstname) or $user->firstname === '') {
  219. $upt->track('status', get_string('missingfield', 'error', 'firstname'), 'error');
  220. $upt->track('firstname', $errorstr, 'error');
  221. $error = true;
  222. }
  223. if (!isset($user->lastname) or $user->lastname === '') {
  224. $upt->track('status', get_string('missingfield', 'error', 'lastname'), 'error');
  225. $upt->track('lastname', $errorstr, 'error');
  226. $error = true;
  227. }
  228. if ($error) {
  229. $userserrors++;
  230. continue;
  231. }
  232. // we require username too - we might use template for it though
  233. if (empty($user->username) and !empty($formdata->username)) {
  234. $user->username = uu_process_template($formdata->username, $user);
  235. $upt->track('username', s($user->username));
  236. }
  237. }
  238. // normalize username
  239. $originalusername = $user->username;
  240. if ($standardusernames) {
  241. $user->username = core_user::clean_field($user->username, 'username');
  242. }
  243. // make sure we really have username
  244. if (empty($user->username)) {
  245. $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
  246. $upt->track('username', $errorstr, 'error');
  247. $userserrors++;
  248. continue;
  249. } else if ($user->username === 'guest') {
  250. $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
  251. $userserrors++;
  252. continue;
  253. }
  254. if ($user->username !== core_user::clean_field($user->username, 'username')) {
  255. $upt->track('status', get_string('invalidusername', 'error', 'username'), 'error');
  256. $upt->track('username', $errorstr, 'error');
  257. $userserrors++;
  258. }
  259. if (empty($user->mnethostid)) {
  260. $user->mnethostid = $CFG->mnet_localhost_id;
  261. }
  262. if ($existinguser = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$user->mnethostid))) {
  263. $upt->track('id', $existinguser->id, 'normal', false);
  264. }
  265. if ($user->mnethostid == $CFG->mnet_localhost_id) {
  266. $remoteuser = false;
  267. // Find out if username incrementing required.
  268. if ($existinguser and $optype == UU_USER_ADDINC) {
  269. $user->username = uu_increment_username($user->username);
  270. $existinguser = false;
  271. }
  272. } else {
  273. if (!$existinguser or $optype == UU_USER_ADDINC) {
  274. $upt->track('status', get_string('errormnetadd', 'tool_uploaduser'), 'error');
  275. $userserrors++;
  276. continue;
  277. }
  278. $remoteuser = true;
  279. // Make sure there are no changes of existing fields except the suspended status.
  280. foreach ((array)$existinguser as $k => $v) {
  281. if ($k === 'suspended') {
  282. continue;
  283. }
  284. if (property_exists($user, $k)) {
  285. $user->$k = $v;
  286. }
  287. if (in_array($k, $upt->columns)) {
  288. if ($k === 'password' or $k === 'oldusername' or $k === 'deleted') {
  289. $upt->track($k, '', 'normal', false);
  290. } else {
  291. $upt->track($k, s($v), 'normal', false);
  292. }
  293. }
  294. }
  295. unset($user->oldusername);
  296. unset($user->password);
  297. $user->auth = $existinguser->auth;
  298. }
  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. }
  306. // Verify if the theme is valid and allowed to be set.
  307. if (isset($user->theme)) {
  308. list($status, $message) = field_value_validators::validate_theme($user->theme);
  309. if ($status !== 'normal' && !empty($message)) {
  310. $upt->track('status', $message, $status);
  311. // Unset the theme when validation fails.
  312. unset($user->theme);
  313. }
  314. }
  315. // add default values for remaining fields
  316. $formdefaults = array();
  317. if (!$existinguser || ($updatetype != UU_UPDATE_FILEOVERRIDE && $updatetype != UU_UPDATE_NOCHANGES)) {
  318. foreach ($STD_FIELDS as $field) {
  319. if (isset($user->$field)) {
  320. continue;
  321. }
  322. // all validation moved to form2
  323. if (isset($formdata->$field)) {
  324. // process templates
  325. $user->$field = uu_process_template($formdata->$field, $user);
  326. $formdefaults[$field] = true;
  327. if (in_array($field, $upt->columns)) {
  328. $upt->track($field, s($user->$field), 'normal');
  329. }
  330. }
  331. }
  332. foreach ($PRF_FIELDS as $field) {
  333. if (isset($user->$field)) {
  334. continue;
  335. }
  336. if (isset($formdata->$field)) {
  337. // process templates
  338. $user->$field = uu_process_template($formdata->$field, $user);
  339. // Form contains key and later code expects value.
  340. // Convert key to value for required profile fields.
  341. require_once($CFG->dirroot.'/user/profile/field/'.$proffields[$field]->datatype.'/field.class.php');
  342. $profilefieldclass = 'profile_field_'.$proffields[$field]->datatype;
  343. $profilefield = new $profilefieldclass($proffields[$field]->id);
  344. if (method_exists($profilefield, 'convert_external_data')) {
  345. $user->$field = $profilefield->edit_save_data_preprocess($user->$field, null);
  346. }
  347. $formdefaults[$field] = true;
  348. }
  349. }
  350. }
  351. // delete user
  352. if (!empty($user->deleted)) {
  353. if (!$allowdeletes or $remoteuser) {
  354. $usersskipped++;
  355. $upt->track('status', $strusernotdeletedoff, 'warning');
  356. continue;
  357. }
  358. if ($existinguser) {
  359. if (is_siteadmin($existinguser->id)) {
  360. $upt->track('status', $strusernotdeletedadmin, 'error');
  361. $deleteerrors++;
  362. continue;
  363. }
  364. if (delete_user($existinguser)) {
  365. $upt->track('status', $struserdeleted);
  366. $deletes++;
  367. } else {
  368. $upt->track('status', $strusernotdeletederror, 'error');
  369. $deleteerrors++;
  370. }
  371. } else {
  372. $upt->track('status', $strusernotdeletedmissing, 'error');
  373. $deleteerrors++;
  374. }
  375. continue;
  376. }
  377. // we do not need the deleted flag anymore
  378. unset($user->deleted);
  379. // renaming requested?
  380. if (!empty($user->oldusername) ) {
  381. if (!$allowrenames) {
  382. $usersskipped++;
  383. $upt->track('status', $strusernotrenamedoff, 'warning');
  384. continue;
  385. }
  386. if ($existinguser) {
  387. $upt->track('status', $strusernotrenamedexists, 'error');
  388. $renameerrors++;
  389. continue;
  390. }
  391. if ($user->username === 'guest') {
  392. $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
  393. $renameerrors++;
  394. continue;
  395. }
  396. if ($standardusernames) {
  397. $oldusername = core_user::clean_field($user->oldusername, 'username');
  398. } else {
  399. $oldusername = $user->oldusername;
  400. }
  401. // no guessing when looking for old username, it must be exact match
  402. if ($olduser = $DB->get_record('user', array('username'=>$oldusername, 'mnethostid'=>$CFG->mnet_localhost_id))) {
  403. $upt->track('id', $olduser->id, 'normal', false);
  404. if (is_siteadmin($olduser->id)) {
  405. $upt->track('status', $strusernotrenamedadmin, 'error');
  406. $renameerrors++;
  407. continue;
  408. }
  409. $DB->set_field('user', 'username', $user->username, array('id'=>$olduser->id));
  410. $upt->track('username', '', 'normal', false); // clear previous
  411. $upt->track('username', s($oldusername).'-->'.s($user->username), 'info');
  412. $upt->track('status', $struserrenamed);
  413. $renames++;
  414. } else {
  415. $upt->track('status', $strusernotrenamedmissing, 'error');
  416. $renameerrors++;
  417. continue;
  418. }
  419. $existinguser = $olduser;
  420. $existinguser->username = $user->username;
  421. }
  422. // can we process with update or insert?
  423. $skip = false;
  424. switch ($optype) {
  425. case UU_USER_ADDNEW:
  426. if ($existinguser) {
  427. $usersskipped++;
  428. $upt->track('status', $strusernotadded, 'warning');
  429. $skip = true;
  430. }
  431. break;
  432. case UU_USER_ADDINC:
  433. if ($existinguser) {
  434. //this should not happen!
  435. $upt->track('status', $strusernotaddederror, 'error');
  436. $userserrors++;
  437. $skip = true;
  438. }
  439. break;
  440. case UU_USER_ADD_UPDATE:
  441. break;
  442. case UU_USER_UPDATE:
  443. if (!$existinguser) {
  444. $usersskipped++;
  445. $upt->track('status', $strusernotupdatednotexists, 'warning');
  446. $skip = true;
  447. }
  448. break;
  449. default:
  450. // unknown type
  451. $skip = true;
  452. }
  453. if ($skip) {
  454. continue;
  455. }
  456. if ($existinguser) {
  457. $user->id = $existinguser->id;
  458. $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id'=>$existinguser->id)), s($existinguser->username)), 'normal', false);
  459. $upt->track('suspended', $stryesnooptions[$existinguser->suspended] , 'normal', false);
  460. $upt->track('auth', $existinguser->auth, 'normal', false);
  461. if (is_siteadmin($user->id)) {
  462. $upt->track('status', $strusernotupdatedadmin, 'error');
  463. $userserrors++;
  464. continue;
  465. }
  466. $existinguser->timemodified = time();
  467. // do NOT mess with timecreated or firstaccess here!
  468. //load existing profile data
  469. profile_load_data($existinguser);
  470. $doupdate = false;
  471. $dologout = false;
  472. if ($updatetype != UU_UPDATE_NOCHANGES and !$remoteuser) {
  473. if (!empty($user->auth) and $user->auth !== $existinguser->auth) {
  474. $upt->track('auth', s($existinguser->auth).'-->'.s($user->auth), 'info', false);
  475. $existinguser->auth = $user->auth;
  476. if (!isset($supportedauths[$user->auth])) {
  477. $upt->track('auth', $struserauthunsupported, 'warning');
  478. }
  479. $doupdate = true;
  480. if ($existinguser->auth === 'nologin') {
  481. $dologout = true;
  482. }
  483. }
  484. $allcolumns = array_merge($STD_FIELDS, $PRF_FIELDS);
  485. foreach ($allcolumns as $column) {
  486. if ($column === 'username' or $column === 'password' or $column === 'auth' or $column === 'suspended') {
  487. // these can not be changed here
  488. continue;
  489. }
  490. if (!property_exists($user, $column) or !property_exists($existinguser, $column)) {
  491. continue;
  492. }
  493. if ($updatetype == UU_UPDATE_MISSING) {
  494. if (!is_null($existinguser->$column) and $existinguser->$column !== '') {
  495. continue;
  496. }
  497. } else if ($updatetype == UU_UPDATE_ALLOVERRIDE) {
  498. // we override everything
  499. } else if ($updatetype == UU_UPDATE_FILEOVERRIDE) {
  500. if (!empty($formdefaults[$column])) {
  501. // do not override with form defaults
  502. continue;
  503. }
  504. }
  505. if ($existinguser->$column !== $user->$column) {
  506. if ($column === 'email') {
  507. $select = $DB->sql_like('email', ':email', false, true, false, '|');
  508. $params = array('email' => $DB->sql_like_escape($user->email, '|'));
  509. if ($DB->record_exists_select('user', $select , $params)) {
  510. $changeincase = core_text::strtolower($existinguser->$column) === core_text::strtolower(
  511. $user->$column);
  512. if ($changeincase) {
  513. // If only case is different then switch to lower case and carry on.
  514. $user->$column = core_text::strtolower($user->$column);
  515. continue;
  516. } else if ($noemailduplicates) {
  517. $upt->track('email', $stremailduplicate, 'error');
  518. $upt->track('status', $strusernotupdated, 'error');
  519. $userserrors++;
  520. continue 2;
  521. } else {
  522. $upt->track('email', $stremailduplicate, 'warning');
  523. }
  524. }
  525. if (!validate_email($user->email)) {
  526. $upt->track('email', get_string('invalidemail'), 'warning');
  527. }
  528. }
  529. if ($column === 'lang') {
  530. if (empty($user->lang)) {
  531. // Do not change to not-set value.
  532. continue;
  533. } else if (core_user::clean_field($user->lang, 'lang') === '') {
  534. $upt->track('status', get_string('cannotfindlang', 'error', $user->lang), 'warning');
  535. continue;
  536. }
  537. }
  538. if (in_array($column, $upt->columns)) {
  539. $upt->track($column, s($existinguser->$column).'-->'.s($user->$column), 'info', false);
  540. }
  541. $existinguser->$column = $user->$column;
  542. $doupdate = true;
  543. }
  544. }
  545. }
  546. try {
  547. $auth = get_auth_plugin($existinguser->auth);
  548. } catch (Exception $e) {
  549. $upt->track('auth', get_string('userautherror', 'error', s($existinguser->auth)), 'error');
  550. $upt->track('status', $strusernotupdated, 'error');
  551. $userserrors++;
  552. continue;
  553. }
  554. $isinternalauth = $auth->is_internal();
  555. // deal with suspending and activating of accounts
  556. if ($allowsuspends and isset($user->suspended) and $user->suspended !== '') {
  557. $user->suspended = $user->suspended ? 1 : 0;
  558. if ($existinguser->suspended != $user->suspended) {
  559. $upt->track('suspended', '', 'normal', false);
  560. $upt->track('suspended', $stryesnooptions[$existinguser->suspended].'-->'.$stryesnooptions[$user->suspended], 'info', false);
  561. $existinguser->suspended = $user->suspended;
  562. $doupdate = true;
  563. if ($existinguser->suspended) {
  564. $dologout = true;
  565. }
  566. }
  567. }
  568. // changing of passwords is a special case
  569. // do not force password changes for external auth plugins!
  570. $oldpw = $existinguser->password;
  571. if ($remoteuser) {
  572. // Do not mess with passwords of remote users.
  573. } else if (!$isinternalauth) {
  574. $existinguser->password = AUTH_PASSWORD_NOT_CACHED;
  575. $upt->track('password', '-', 'normal', false);
  576. // clean up prefs
  577. unset_user_preference('create_password', $existinguser);
  578. unset_user_preference('auth_forcepasswordchange', $existinguser);
  579. } else if (!empty($user->password)) {
  580. if ($updatepasswords) {
  581. // Check for passwords that we want to force users to reset next
  582. // time they log in.
  583. $errmsg = null;
  584. $weak = !check_password_policy($user->password, $errmsg, $user);
  585. if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
  586. if ($weak) {
  587. $weakpasswords++;
  588. $upt->track('password', $strinvalidpasswordpolicy, 'warning');
  589. }
  590. set_user_preference('auth_forcepasswordchange', 1, $existinguser);
  591. } else {
  592. unset_user_preference('auth_forcepasswordchange', $existinguser);
  593. }
  594. unset_user_preference('create_password', $existinguser); // no need to create password any more
  595. // Use a low cost factor when generating bcrypt hash otherwise
  596. // hashing would be slow when uploading lots of users. Hashes
  597. // will be automatically updated to a higher cost factor the first
  598. // time the user logs in.
  599. $existinguser->password = hash_internal_user_password($user->password, true);
  600. $upt->track('password', $user->password, 'normal', false);
  601. } else {
  602. // do not print password when not changed
  603. $upt->track('password', '', 'normal', false);
  604. }
  605. }
  606. if ($doupdate or $existinguser->password !== $oldpw) {
  607. // We want only users that were really updated.
  608. user_update_user($existinguser, false, false);
  609. $upt->track('status', $struserupdated);
  610. $usersupdated++;
  611. if (!$remoteuser) {
  612. // pre-process custom profile menu fields data from csv file
  613. $existinguser = uu_pre_process_custom_profile_data($existinguser);
  614. // save custom profile fields data from csv file
  615. profile_save_data($existinguser);
  616. }
  617. if ($bulk == UU_BULK_UPDATED or $bulk == UU_BULK_ALL) {
  618. if (!in_array($user->id, $SESSION->bulk_users)) {
  619. $SESSION->bulk_users[] = $user->id;
  620. }
  621. }
  622. // Trigger event.
  623. \core\event\user_updated::create_from_userid($existinguser->id)->trigger();
  624. } else {
  625. // no user information changed
  626. $upt->track('status', $struseruptodate);
  627. $usersuptodate++;
  628. if ($bulk == UU_BULK_ALL) {
  629. if (!in_array($user->id, $SESSION->bulk_users)) {
  630. $SESSION->bulk_users[] = $user->id;
  631. }
  632. }
  633. }
  634. if ($dologout) {
  635. \core\session\manager::kill_user_sessions($existinguser->id);
  636. }
  637. } else {
  638. // save the new user to the database
  639. $user->confirmed = 1;
  640. $user->timemodified = time();
  641. $user->timecreated = time();
  642. $user->mnethostid = $CFG->mnet_localhost_id; // we support ONLY local accounts here, sorry
  643. if (!isset($user->suspended) or $user->suspended === '') {
  644. $user->suspended = 0;
  645. } else {
  646. $user->suspended = $user->suspended ? 1 : 0;
  647. }
  648. $upt->track('suspended', $stryesnooptions[$user->suspended], 'normal', false);
  649. if (empty($user->auth)) {
  650. $user->auth = 'manual';
  651. }
  652. $upt->track('auth', $user->auth, 'normal', false);
  653. // do not insert record if new auth plugin does not exist!
  654. try {
  655. $auth = get_auth_plugin($user->auth);
  656. } catch (Exception $e) {
  657. $upt->track('auth', get_string('userautherror', 'error', s($user->auth)), 'error');
  658. $upt->track('status', $strusernotaddederror, 'error');
  659. $userserrors++;
  660. continue;
  661. }
  662. if (!isset($supportedauths[$user->auth])) {
  663. $upt->track('auth', $struserauthunsupported, 'warning');
  664. }
  665. $isinternalauth = $auth->is_internal();
  666. if (empty($user->email)) {
  667. $upt->track('email', get_string('invalidemail'), 'error');
  668. $upt->track('status', $strusernotaddederror, 'error');
  669. $userserrors++;
  670. continue;
  671. } else if ($DB->record_exists('user', array('email'=>$user->email))) {
  672. if ($noemailduplicates) {
  673. $upt->track('email', $stremailduplicate, 'error');
  674. $upt->track('status', $strusernotaddederror, 'error');
  675. $userserrors++;
  676. continue;
  677. } else {
  678. $upt->track('email', $stremailduplicate, 'warning');
  679. }
  680. }
  681. if (!validate_email($user->email)) {
  682. $upt->track('email', get_string('invalidemail'), 'warning');
  683. }
  684. if (empty($user->lang)) {
  685. $user->lang = '';
  686. } else if (core_user::clean_field($user->lang, 'lang') === '') {
  687. $upt->track('status', get_string('cannotfindlang', 'error', $user->lang), 'warning');
  688. $user->lang = '';
  689. }
  690. $forcechangepassword = false;
  691. if ($isinternalauth) {
  692. if (empty($user->password)) {
  693. if ($createpasswords) {
  694. $user->password = 'to be generated';
  695. $upt->track('password', '', 'normal', false);
  696. $upt->track('password', get_string('uupasswordcron', 'tool_uploaduser'), 'warning', false);
  697. } else {
  698. $upt->track('password', '', 'normal', false);
  699. $upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
  700. $upt->track('status', $strusernotaddederror, 'error');
  701. $userserrors++;
  702. continue;
  703. }
  704. } else {
  705. $errmsg = null;
  706. $weak = !check_password_policy($user->password, $errmsg, $user);
  707. if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
  708. if ($weak) {
  709. $weakpasswords++;
  710. $upt->track('password', $strinvalidpasswordpolicy, 'warning');
  711. }
  712. $forcechangepassword = true;
  713. }
  714. // Use a low cost factor when generating bcrypt hash otherwise
  715. // hashing would be slow when uploading lots of users. Hashes
  716. // will be automatically updated to a higher cost factor the first
  717. // time the user logs in.
  718. $user->password = hash_internal_user_password($user->password, true);
  719. }
  720. } else {
  721. $user->password = AUTH_PASSWORD_NOT_CACHED;
  722. $upt->track('password', '-', 'normal', false);
  723. }
  724. $user->id = user_create_user($user, false, false);
  725. $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id'=>$user->id)), s($user->username)), 'normal', false);
  726. // pre-process custom profile menu fields data from csv file
  727. $user = uu_pre_process_custom_profile_data($user);
  728. // save custom profile fields data
  729. profile_save_data($user);
  730. if ($forcechangepassword) {
  731. set_user_preference('auth_forcepasswordchange', 1, $user);
  732. }
  733. if ($user->password === 'to be generated') {
  734. set_user_preference('create_password', 1, $user);
  735. }
  736. // Trigger event.
  737. \core\event\user_created::create_from_userid($user->id)->trigger();
  738. $upt->track('status', $struseradded);
  739. $upt->track('id', $user->id, 'normal', false);
  740. $usersnew++;
  741. // make sure user context exists
  742. context_user::instance($user->id);
  743. if ($bulk == UU_BULK_NEW or $bulk == UU_BULK_ALL) {
  744. if (!in_array($user->id, $SESSION->bulk_users)) {
  745. $SESSION->bulk_users[] = $user->id;
  746. }
  747. }
  748. }
  749. // Update user interests.
  750. if (isset($user->interests) && strval($user->interests) !== '') {
  751. useredit_update_interests($user, preg_split('/\s*,\s*/', $user->interests, -1, PREG_SPLIT_NO_EMPTY));
  752. }
  753. // add to cohort first, it might trigger enrolments indirectly - do NOT create cohorts here!
  754. foreach ($filecolumns as $column) {
  755. if (!preg_match('/^cohort\d+$/', $column)) {
  756. continue;
  757. }
  758. if (!empty($user->$column)) {
  759. $addcohort = $user->$column;
  760. if (!isset($cohorts[$addcohort])) {
  761. if (is_number($addcohort)) {
  762. // only non-numeric idnumbers!
  763. $cohort = $DB->get_record('cohort', array('id'=>$addcohort));
  764. } else {
  765. $cohort = $DB->get_record('cohort', array('idnumber'=>$addcohort));
  766. if (empty($cohort) && has_capability('moodle/cohort:manage', context_system::instance())) {
  767. // Cohort was not found. Create a new one.
  768. $cohortid = cohort_add_cohort((object)array(
  769. 'idnumber' => $addcohort,
  770. 'name' => $addcohort,
  771. 'contextid' => context_system::instance()->id
  772. ));
  773. $cohort = $DB->get_record('cohort', array('id'=>$cohortid));
  774. }
  775. }
  776. if (empty($cohort)) {
  777. $cohorts[$addcohort] = get_string('unknowncohort', 'core_cohort', s($addcohort));
  778. } else if (!empty($cohort->component)) {
  779. // cohorts synchronised with external sources must not be modified!
  780. $cohorts[$addcohort] = get_string('external', 'core_cohort');
  781. } else {
  782. $cohorts[$addcohort] = $cohort;
  783. }
  784. }
  785. if (is_object($cohorts[$addcohort])) {
  786. $cohort = $cohorts[$addcohort];
  787. if (!$DB->record_exists('cohort_members', array('cohortid'=>$cohort->id, 'userid'=>$user->id))) {
  788. cohort_add_member($cohort->id, $user->id);
  789. // we might add special column later, for now let's abuse enrolments
  790. $upt->track('enrolments', get_string('useradded', 'core_cohort', s($cohort->name)));
  791. }
  792. } else {
  793. // error message
  794. $upt->track('enrolments', $cohorts[$addcohort], 'error');
  795. }
  796. }
  797. }
  798. // find course enrolments, groups, roles/types and enrol periods
  799. // this is again a special case, we always do this for any updated or created users
  800. foreach ($filecolumns as $column) {
  801. if (preg_match('/^sysrole\d+$/', $column)) {
  802. if (!empty($user->$column)) {
  803. $sysrolename = $user->$column;
  804. if ($sysrolename[0] == '-') {
  805. $removing = true;
  806. $sysrolename = substr($sysrolename, 1);
  807. } else {
  808. $removing = false;
  809. }
  810. if (array_key_exists($sysrolename, $sysrolecache)) {
  811. $sysroleid = $sysrolecache[$sysrolename]->id;
  812. } else {
  813. $upt->track('enrolments', get_string('unknownrole', 'error', s($sysrolename)), 'error');
  814. continue;
  815. }
  816. if ($removing) {
  817. if (user_has_role_assignment($user->id, $sysroleid, SYSCONTEXTID)) {
  818. role_unassign($sysroleid, $user->id, SYSCONTEXTID);
  819. $upt->track('enrolments', get_string('unassignedsysrole',
  820. 'tool_uploaduser', $sysrolecache[$sysroleid]->name));
  821. }
  822. } else {
  823. if (!user_has_role_assignment($user->id, $sysroleid, SYSCONTEXTID)) {
  824. role_assign($sysroleid, $user->id, SYSCONTEXTID);
  825. $upt->track('enrolments', get_string('assignedsysrole',
  826. 'tool_uploaduser', $sysrolecache[$sysroleid]->name));
  827. }
  828. }
  829. }
  830. continue;
  831. }
  832. if (!preg_match('/^course\d+$/', $column)) {
  833. continue;
  834. }
  835. $i = substr($column, 6);
  836. if (empty($user->{'course'.$i})) {
  837. continue;
  838. }
  839. $shortname = $user->{'course'.$i};
  840. if (!array_key_exists($shortname, $ccache)) {
  841. if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname')) {
  842. $upt->track('enrolments', get_string('unknowncourse', 'error', s($shortname)), 'error');
  843. continue;
  844. }
  845. $ccache[$shortname] = $course;
  846. $ccache[$shortname]->groups = null;
  847. }
  848. $courseid = $ccache[$shortname]->id;
  849. $coursecontext = context_course::instance($courseid);
  850. if (!isset($manualcache[$courseid])) {
  851. $manualcache[$courseid] = false;
  852. if ($manual) {
  853. if ($instances = enrol_get_instances($courseid, false)) {
  854. foreach ($instances as $instance) {
  855. if ($instance->enrol === 'manual') {
  856. $manualcache[$courseid] = $instance;
  857. break;
  858. }
  859. }
  860. }
  861. }
  862. }
  863. if ($courseid == SITEID) {
  864. // Technically frontpage does not have enrolments, but only role assignments,
  865. // let's not invent new lang strings here for this rarely used feature.
  866. if (!empty($user->{'role'.$i})) {
  867. $rolename = $user->{'role'.$i};
  868. if (array_key_exists($rolename, $rolecache)) {
  869. $roleid = $rolecache[$rolename]->id;
  870. } else {
  871. $upt->track('enrolments', get_string('unknownrole', 'error', s($rolename)), 'error');
  872. continue;
  873. }
  874. role_assign($roleid, $user->id, context_course::instance($courseid));
  875. $a = new stdClass();
  876. $a->course = $shortname;
  877. $a->role = $rolecache[$roleid]->name;
  878. $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
  879. }
  880. } else if ($manual and $manualcache[$courseid]) {
  881. // find role
  882. $roleid = false;
  883. if (!empty($user->{'role'.$i})) {
  884. $rolename = $user->{'role'.$i};
  885. if (array_key_exists($rolename, $rolecache)) {
  886. $roleid = $rolecache[$rolename]->id;
  887. } else {
  888. $upt->track('enrolments', get_string('unknownrole', 'error', s($rolename)), 'error');
  889. continue;
  890. }
  891. } else if (!empty($user->{'type'.$i})) {
  892. // if no role, then find "old" enrolment type
  893. $addtype = $user->{'type'.$i};
  894. if ($addtype < 1 or $addtype > 3) {
  895. $upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
  896. continue;
  897. } else if (empty($formdata->{'uulegacy'.$addtype})) {
  898. continue;
  899. } else {
  900. $roleid = $formdata->{'uulegacy'.$addtype};
  901. }
  902. } else {
  903. // no role specified, use the default from manual enrol plugin
  904. $roleid = $manualcache[$courseid]->roleid;
  905. }
  906. if ($roleid) {
  907. // Find duration and/or enrol status.
  908. $timeend = 0;
  909. $timestart = $today;
  910. $status = null;
  911. if (isset($user->{'enrolstatus'.$i})) {
  912. $enrolstatus = $user->{'enrolstatus'.$i};
  913. if ($enrolstatus == '') {
  914. $status = null;
  915. } else if ($enrolstatus === (string)ENROL_USER_ACTIVE) {
  916. $status = ENROL_USER_ACTIVE;
  917. } else if ($enrolstatus === (string)ENROL_USER_SUSPENDED) {
  918. $status = ENROL_USER_SUSPENDED;
  919. } else {
  920. debugging('Unknown enrolment status.');
  921. }
  922. }
  923. if (!empty($user->{'enroltimestart'.$i})) {
  924. $parsedtimestart = strtotime($user->{'enroltimestart'.$i});
  925. if ($parsedtimestart !== false) {
  926. $timestart = $parsedtimestart;
  927. }
  928. }
  929. if (!empty($user->{'enrolperiod'.$i})) {
  930. $duration = (int)$user->{'enrolperiod'.$i} * 60*60*24; // convert days to seconds
  931. if ($duration > 0) { // sanity check
  932. $timeend = $timestart + $duration;
  933. }
  934. } else if ($manualcache[$courseid]->enrolperiod > 0) {
  935. $timeend = $timestart + $manualcache[$courseid]->enrolperiod;
  936. }
  937. $manual->enrol_user($manualcache[$courseid], $user->id, $roleid, $timestart, $timeend, $status);
  938. $a = new stdClass();
  939. $a->course = $shortname;
  940. $a->role = $rolecache[$roleid]->name;
  941. $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
  942. }
  943. }
  944. // find group to add to
  945. if (!empty($user->{'group'.$i})) {
  946. // make sure user is enrolled into course before adding into groups
  947. if (!is_enrolled($coursecontext, $user->id)) {
  948. $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group'.$i}), 'error');
  949. continue;
  950. }
  951. //build group cache
  952. if (is_null($ccache[$shortname]->groups)) {
  953. $ccache[$shortname]->groups = array();
  954. if ($groups = groups_get_all_groups($courseid)) {
  955. foreach ($groups as $gid=>$group) {
  956. $ccache[$shortname]->groups[$gid] = new stdClass();
  957. $ccache[$shortname]->groups[$gid]->id = $gid;
  958. $ccache[$shortname]->groups[$gid]->name = $group->name;
  959. if (!is_numeric($group->name)) { // only non-numeric names are supported!!!
  960. $ccache[$shortname]->groups[$group->name] = new stdClass();
  961. $ccache[$shortname]->groups[$group->name]->id = $gid;
  962. $ccache[$shortname]->groups[$group->name]->name = $group->name;
  963. }
  964. }
  965. }
  966. }
  967. // group exists?
  968. $addgroup = $user->{'group'.$i};
  969. if (!array_key_exists($addgroup, $ccache[$shortname]->groups)) {
  970. // if group doesn't exist, create it
  971. $newgroupdata = new stdClass();
  972. $newgroupdata->name = $addgroup;
  973. $newgroupdata->courseid = $ccache[$shortname]->id;
  974. $newgroupdata->description = '';
  975. $gid = groups_create_group($newgroupdata);
  976. if ($gid){
  977. $ccache[$shortname]->groups[$addgroup] = new stdClass();
  978. $ccache[$shortname]->groups[$addgroup]->id = $gid;
  979. $ccache

Large files files are truncated, but you can click here to view the full file