PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/admin/uploaduser.php

https://github.com/mylescarrick/moodle
PHP | 936 lines | 724 code | 120 blank | 92 comment | 190 complexity | 070213c58311cef7467bea12ce94c928 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause
  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 core
  20. * @subpackage admin
  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.'/group/lib.php');
  29. require_once('uploaduserlib.php');
  30. require_once('uploaduser_form.php');
  31. $iid = optional_param('iid', '', PARAM_INT);
  32. $previewrows = optional_param('previewrows', 10, PARAM_INT);
  33. @set_time_limit(60*60); // 1 hour should be enough
  34. raise_memory_limit(MEMORY_HUGE);
  35. require_login();
  36. admin_externalpage_setup('uploadusers');
  37. require_capability('moodle/site:uploadusers', get_context_instance(CONTEXT_SYSTEM));
  38. $struserrenamed = get_string('userrenamed', 'admin');
  39. $strusernotrenamedexists = get_string('usernotrenamedexists', 'error');
  40. $strusernotrenamedmissing = get_string('usernotrenamedmissing', 'error');
  41. $strusernotrenamedoff = get_string('usernotrenamedoff', 'error');
  42. $strusernotrenamedadmin = get_string('usernotrenamedadmin', 'error');
  43. $struserupdated = get_string('useraccountupdated', 'admin');
  44. $strusernotupdated = get_string('usernotupdatederror', 'error');
  45. $strusernotupdatednotexists = get_string('usernotupdatednotexists', 'error');
  46. $strusernotupdatedadmin = get_string('usernotupdatedadmin', 'error');
  47. $struseruptodate = get_string('useraccountuptodate', 'admin');
  48. $struseradded = get_string('newuser');
  49. $strusernotadded = get_string('usernotaddedregistered', 'error');
  50. $strusernotaddederror = get_string('usernotaddederror', 'error');
  51. $struserdeleted = get_string('userdeleted', 'admin');
  52. $strusernotdeletederror = get_string('usernotdeletederror', 'error');
  53. $strusernotdeletedmissing = get_string('usernotdeletedmissing', 'error');
  54. $strusernotdeletedoff = get_string('usernotdeletedoff', 'error');
  55. $strusernotdeletedadmin = get_string('usernotdeletedadmin', 'error');
  56. $strcannotassignrole = get_string('cannotassignrole', 'error');
  57. $struserauthunsupported = get_string('userauthunsupported', 'error');
  58. $stremailduplicate = get_string('useremailduplicate', 'error');
  59. $strinvalidpasswordpolicy = get_string('invalidpasswordpolicy', 'error');
  60. $errorstr = get_string('error');
  61. $returnurl = new moodle_url('/admin/uploaduser.php');
  62. $bulknurl = new moodle_url('/admin/user/user_bulk.php');
  63. $today = time();
  64. $today = make_timestamp(date('Y', $today), date('m', $today), date('d', $today), 0, 0, 0);
  65. // array of all valid fields for validation
  66. $STD_FIELDS = array('id', 'firstname', 'lastname', 'username', 'email',
  67. 'city', 'country', 'lang', 'timezone', 'mailformat',
  68. 'maildisplay', 'maildigest', 'htmleditor', 'ajax', 'autosubscribe',
  69. 'institution', 'department', 'idnumber', 'skype',
  70. 'msn', 'aim', 'yahoo', 'icq', 'phone1', 'phone2', 'address',
  71. 'url', 'description', 'descriptionformat', 'password',
  72. 'auth', // watch out when changing auth type or using external auth plugins!
  73. 'oldusername', // use when renaming users - this is the original username
  74. 'deleted', // 1 means delete user
  75. );
  76. $PRF_FIELDS = array();
  77. if ($prof_fields = $DB->get_records('user_info_field')) {
  78. foreach ($prof_fields as $prof_field) {
  79. $PRF_FIELDS[] = 'profile_field_'.$prof_field->shortname;
  80. }
  81. }
  82. unset($prof_fields);
  83. if (empty($iid)) {
  84. $mform1 = new admin_uploaduser_form1();
  85. if ($formdata = $mform1->get_data()) {
  86. $iid = csv_import_reader::get_new_iid('uploaduser');
  87. $cir = new csv_import_reader($iid, 'uploaduser');
  88. $content = $mform1->get_file_content('userfile');
  89. $readcount = $cir->load_csv_content($content, $formdata->encoding, $formdata->delimiter_name);
  90. unset($content);
  91. if ($readcount === false) {
  92. print_error('csvloaderror', '', $returnurl);
  93. } else if ($readcount == 0) {
  94. print_error('csvemptyfile', 'error', $returnurl);
  95. }
  96. // test if columns ok
  97. $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
  98. // continue to form2
  99. } else {
  100. echo $OUTPUT->header();
  101. echo $OUTPUT->heading_with_help(get_string('uploadusers', 'admin'), 'uploadusers', 'admin');
  102. $mform1->display();
  103. echo $OUTPUT->footer();
  104. die;
  105. }
  106. } else {
  107. $cir = new csv_import_reader($iid, 'uploaduser');
  108. $filecolumns = uu_validate_user_upload_columns($cir, $STD_FIELDS, $PRF_FIELDS, $returnurl);
  109. }
  110. $mform2 = new admin_uploaduser_form2(null, array('columns'=>$filecolumns, 'data'=>array('iid'=>$iid, 'previewrows'=>$previewrows)));
  111. // If a file has been uploaded, then process it
  112. if ($formdata = $mform2->is_cancelled()) {
  113. $cir->cleanup(true);
  114. redirect($returnurl);
  115. } else if ($formdata = $mform2->get_data()) {
  116. // Print the header
  117. echo $OUTPUT->header();
  118. echo $OUTPUT->heading(get_string('uploadusersresult', 'admin'));
  119. $optype = $formdata->uutype;
  120. $updatetype = isset($formdata->uuupdatetype) ? $formdata->uuupdatetype : 0;
  121. $createpasswords = (!empty($formdata->uupasswordnew) and $optype != UU_USER_UPDATE);
  122. $updatepasswords = (!empty($formdata->uupasswordold) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC and ($updatetype == UU_UPDATE_FILEOVERRIDE or $updatetype == UU_UPDATE_ALLOVERRIDE));
  123. $allowrenames = (!empty($formdata->uuallowrenames) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
  124. $allowdeletes = (!empty($formdata->uuallowdeletes) and $optype != UU_USER_ADDNEW and $optype != UU_USER_ADDINC);
  125. $bulk = $formdata->uubulk;
  126. $noemailduplicates = $formdata->uunoemailduplicates;
  127. $standardusernames = $formdata->uustandardusernames;
  128. $resetpasswords = isset($formdata->uuforcepasswordchange) ? $formdata->uuforcepasswordchange : UU_PWRESET_NONE;
  129. // verification moved to two places: after upload and into form2
  130. $usersnew = 0;
  131. $usersupdated = 0;
  132. $usersuptodate = 0; //not printed yet anywhere
  133. $userserrors = 0;
  134. $deletes = 0;
  135. $deleteerrors = 0;
  136. $renames = 0;
  137. $renameerrors = 0;
  138. $usersskipped = 0;
  139. $weakpasswords = 0;
  140. // caches
  141. $ccache = array(); // course cache - do not fetch all courses here, we will not probably use them all anyway!
  142. $rolecache = uu_allowed_roles_cache(); // roles lookup cache
  143. $manualcache = array(); // cache of used manual enrol plugins in each course
  144. $supportedauths = uu_supported_auths(); // officially supported plugins that are enabled
  145. // we use only manual enrol plugin here, if it is disabled no enrol is done
  146. if (enrol_is_enabled('manual')) {
  147. $manual = enrol_get_plugin('manual');
  148. } else {
  149. $manual = NULL;
  150. }
  151. // clear bulk selection
  152. if ($bulk) {
  153. $SESSION->bulk_users = array();
  154. }
  155. // init csv import helper
  156. $cir->init();
  157. $linenum = 1; //column header is first line
  158. // init upload progress tracker
  159. $upt = new uu_progress_tracker();
  160. $upt->start(); // start table
  161. while ($line = $cir->next()) {
  162. $upt->flush();
  163. $linenum++;
  164. $upt->track('line', $linenum);
  165. $user = new stdClass();
  166. // add fields to user object
  167. foreach ($line as $keynum => $value) {
  168. if (!isset($filecolumns[$keynum])) {
  169. // this should not happen
  170. continue;
  171. }
  172. $key = $filecolumns[$keynum];
  173. if (strpos($key, 'profile_field_') === 0) {
  174. //NOTE: bloody mega hack alert!!
  175. if (isset($USER->$key) and is_array($USER->$key)) {
  176. // this must be some hacky field that is abusing arrays to store content and format
  177. $user->$key = array();
  178. $user->$key['text'] = $value;
  179. $user->$key['format'] = FORMAT_MOODLE;
  180. } else {
  181. $user->$key = $value;
  182. }
  183. } else {
  184. $user->$key = $value;
  185. }
  186. if (in_array($key, $upt->columns)) {
  187. // default value in progress tracking table, can be changed later
  188. $upt->track($key, s($value), 'normal');
  189. }
  190. }
  191. if (!isset($user->username)) {
  192. // prevent warnings bellow
  193. $user->username = '';
  194. }
  195. if ($optype == UU_USER_ADDNEW or $optype == UU_USER_ADDINC) {
  196. // user creation is a special case - the username may be constructed from templates using firstname and lastname
  197. // better never try this in mixed update types
  198. $error = false;
  199. if (!isset($user->firstname) or $user->firstname === '') {
  200. $upt->track('status', get_string('missingfield', 'error', 'firstname'), 'error');
  201. $upt->track('firstname', $errorstr, 'error');
  202. $error = true;
  203. }
  204. if (!isset($user->lastname) or $user->lastname === '') {
  205. $upt->track('status', get_string('missingfield', 'error', 'lastname'), 'error');
  206. $upt->track('lastname', $errorstr, 'error');
  207. $error = true;
  208. }
  209. if ($error) {
  210. $userserrors++;
  211. continue;
  212. }
  213. // we require username too - we might use template for it though
  214. if (empty($user->username) and !empty($formdata->username)) {
  215. $user->username = uu_process_template($formdata->username, $user);
  216. $upt->track('username', s($user->username));
  217. }
  218. }
  219. // normalize username
  220. $originalusername = $user->username;
  221. if ($standardusernames) {
  222. $user->username = clean_param($user->username, PARAM_USERNAME);
  223. }
  224. // make sure we really have username
  225. if (empty($user->username)) {
  226. $upt->track('status', get_string('missingfield', 'error', 'username'), 'error');
  227. $upt->track('username', $errorstr, 'error');
  228. $userserrors++;
  229. continue;
  230. } else if ($user->username === 'guest') {
  231. $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
  232. $userserrors++;
  233. continue;
  234. }
  235. if ($existinguser = $DB->get_record('user', array('username'=>$user->username, 'mnethostid'=>$CFG->mnet_localhost_id))) {
  236. $upt->track('id', $existinguser->id, 'normal', false);
  237. }
  238. // find out in username incrementing required
  239. if ($existinguser and $optype == UU_USER_ADDINC) {
  240. $user->username = uu_increment_username($user->username);
  241. $existinguser = false;
  242. }
  243. // notify about nay username changes
  244. if ($originalusername !== $user->username) {
  245. $upt->track('username', '', 'normal', false); // clear previous
  246. $upt->track('username', s($originalusername).'-->'.s($user->username), 'info');
  247. } else {
  248. $upt->track('username', s($user->username), 'normal', false);
  249. }
  250. // add default values for remaining fields
  251. $formdefaults = array();
  252. foreach ($STD_FIELDS as $field) {
  253. if (isset($user->$field)) {
  254. continue;
  255. }
  256. // all validation moved to form2
  257. if (isset($formdata->$field)) {
  258. // process templates
  259. $user->$field = uu_process_template($formdata->$field, $user);
  260. $formdefaults[$field] = true;
  261. }
  262. }
  263. foreach ($PRF_FIELDS as $field) {
  264. if (isset($user->$field)) {
  265. continue;
  266. }
  267. if (isset($formdata->$field)) {
  268. // process templates
  269. $user->$field = uu_process_template($formdata->$field, $user);
  270. $formdefaults[$field] = true;
  271. }
  272. }
  273. // delete user
  274. if (!empty($user->deleted)) {
  275. if (!$allowdeletes) {
  276. $usersskipped++;
  277. $upt->track('status', $strusernotdeletedoff, 'warning');
  278. continue;
  279. }
  280. if ($existinguser) {
  281. if (is_siteadmin($existinguser->id)) {
  282. $upt->track('status', $strusernotdeletedadmin, 'error');
  283. $deleteerrors++;
  284. continue;
  285. }
  286. if (delete_user($existinguser)) {
  287. $upt->track('status', $struserdeleted);
  288. $deletes++;
  289. } else {
  290. $upt->track('status', $strusernotdeletederror, 'error');
  291. $deleteerrors++;
  292. }
  293. } else {
  294. $upt->track('status', $strusernotdeletedmissing, 'error');
  295. $deleteerrors++;
  296. }
  297. continue;
  298. }
  299. // we do not need the deleted flag anymore
  300. unset($user->deleted);
  301. // renaming requested?
  302. if (!empty($user->oldusername) ) {
  303. if (!$allowrenames) {
  304. $usersskipped++;
  305. $upt->track('status', $strusernotrenamedoff, 'warning');
  306. continue;
  307. }
  308. if ($existinguser) {
  309. $upt->track('status', $strusernotrenamedexists, 'error');
  310. $renameerrors++;
  311. continue;
  312. }
  313. if ($user->username === 'guest') {
  314. $upt->track('status', get_string('guestnoeditprofileother', 'error'), 'error');
  315. $renameerrors++;
  316. continue;
  317. }
  318. if ($standardusernames) {
  319. $oldusername = clean_param($user->oldusername, PARAM_USERNAME);
  320. } else {
  321. $oldusername = $user->oldusername;
  322. }
  323. // no guessing when looking for old username, it must be exact match
  324. if ($olduser = $DB->get_record('user', array('username'=>$oldusername, 'mnethostid'=>$CFG->mnet_localhost_id))) {
  325. $upt->track('id', $olduser->id, 'normal', false);
  326. if (is_siteadmin($olduser->id)) {
  327. $upt->track('status', $strusernotrenamedadmin, 'error');
  328. $renameerrors++;
  329. continue;
  330. }
  331. $DB->set_field('user', 'username', $user->username, array('id'=>$olduser->id));
  332. $upt->track('username', '', 'normal', false); // clear previous
  333. $upt->track('username', s($oldusername).'-->'.s($user->username), 'info');
  334. $upt->track('status', $struserrenamed);
  335. $renames++;
  336. } else {
  337. $upt->track('status', $strusernotrenamedmissing, 'error');
  338. $renameerrors++;
  339. continue;
  340. }
  341. $existinguser = $olduser;
  342. $existinguser->username = $user->username;
  343. }
  344. // can we process with update or insert?
  345. $skip = false;
  346. switch ($optype) {
  347. case UU_USER_ADDNEW:
  348. if ($existinguser) {
  349. $usersskipped++;
  350. $upt->track('status', $strusernotadded, 'warning');
  351. $skip = true;
  352. }
  353. break;
  354. case UU_USER_ADDINC:
  355. if ($existinguser) {
  356. //this should not happen!
  357. $upt->track('status', $strusernotaddederror, 'error');
  358. $userserrors++;
  359. $skip = true;
  360. }
  361. break;
  362. case UU_USER_ADD_UPDATE:
  363. break;
  364. case UU_USER_UPDATE:
  365. if (!$existinguser) {
  366. $usersskipped++;
  367. $upt->track('status', $strusernotupdatednotexists, 'warning');
  368. $skip = true;
  369. }
  370. break;
  371. default:
  372. // unknown type
  373. $skip = true;
  374. }
  375. if ($skip) {
  376. continue;
  377. }
  378. if ($existinguser) {
  379. $user->id = $existinguser->id;
  380. $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id'=>$existinguser->id)), s($existinguser->username)), 'normal', false);
  381. if (is_siteadmin($user->id)) {
  382. $upt->track('status', $strusernotupdatedadmin, 'error');
  383. $userserrors++;
  384. continue;
  385. }
  386. $existinguser->timemodified = time();
  387. // do NOT mess with timecreated or firstaccess here!
  388. //load existing profile data
  389. profile_load_data($existinguser);
  390. $upt->track('auth', $existinguser->auth, 'normal', false);
  391. $doupdate = false;
  392. if ($updatetype != UU_UPDATE_NOCHANGES) {
  393. if (!empty($user->auth) and $user->auth !== $existinguser->auth) {
  394. $upt->track('auth', s($existinguser->auth).'-->'.s($user->auth), 'info', false);
  395. $existinguser->auth = $user->auth;
  396. if (!isset($supportedauths[$user->auth])) {
  397. $upt->track('auth', $struserauthunsupported, 'warning');
  398. }
  399. }
  400. $allcolumns = array_merge($STD_FIELDS, $PRF_FIELDS);
  401. foreach ($allcolumns as $column) {
  402. if ($column === 'username' or $column === 'password' or $column === 'auth') {
  403. // these can not be changed here
  404. continue;
  405. }
  406. if (!property_exists($user, $column) or !property_exists($existinguser, $column)) {
  407. // this should never happen
  408. continue;
  409. }
  410. if ($updatetype == UU_UPDATE_MISSING) {
  411. if (!is_null($existinguser->$column) and $existinguser->$column !== '') {
  412. continue;
  413. }
  414. } else if ($updatetype == UU_UPDATE_ALLOVERRIDE) {
  415. // we override everything
  416. } else if ($updatetype == UU_UPDATE_FILEOVERRIDE) {
  417. if (!empty($formdefaults[$column])) {
  418. // do not override with form defaults
  419. continue;
  420. }
  421. }
  422. if ($existinguser->$column !== $user->$column) {
  423. if ($column === 'email') {
  424. if ($DB->record_exists('user', array('email'=>$user->email))) {
  425. if ($noemailduplicates) {
  426. $upt->track('email', $stremailduplicate, 'error');
  427. $upt->track('status', $strusernotupdated, 'error');
  428. $userserrors++;
  429. continue 2;
  430. } else {
  431. $upt->track('email', $stremailduplicate, 'warning');
  432. }
  433. }
  434. if (!validate_email($user->email)) {
  435. $upt->track('email', get_string('invalidemail'), 'warning');
  436. }
  437. }
  438. if (in_array($column, $upt->columns)) {
  439. $upt->track($column, s($existinguser->$column).'-->'.s($user->$column), 'info', false);
  440. }
  441. $existinguser->$column = $user->$column;
  442. $doupdate = true;
  443. }
  444. }
  445. }
  446. try {
  447. $auth = get_auth_plugin($existinguser->auth);
  448. } catch (Exception $e) {
  449. $upt->track('auth', get_string('userautherror', 'error', s($existinguser->auth)), 'error');
  450. $upt->track('status', $strusernotupdated, 'error');
  451. $userserrors++;
  452. continue;
  453. }
  454. $isinternalauth = $auth->is_internal();
  455. // changing of passwords is a special case
  456. // do not force password changes for external auth plugins!
  457. $oldpw = $existinguser->password;
  458. if (!$isinternalauth) {
  459. $existinguser->password = 'not cached';
  460. $upt->track('password', '-', 'normal', false);
  461. // clean up prefs
  462. unset_user_preference('create_password', $existinguser);
  463. unset_user_preference('auth_forcepasswordchange', $existinguser);
  464. } else if (!empty($user->password)) {
  465. if ($updatepasswords) {
  466. $errmsg = null;
  467. $weak = !check_password_policy($user->password, $errmsg);
  468. if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
  469. if ($weak) {
  470. $weakpasswords++;
  471. $upt->track('password', $strinvalidpasswordpolicy, 'warning');
  472. }
  473. set_user_preference('auth_forcepasswordchange', 1, $existinguser);
  474. } else {
  475. unset_user_preference('auth_forcepasswordchange', $existinguser);
  476. }
  477. unset_user_preference('create_password', $existinguser); // no need to create password any more
  478. $existinguser->password = hash_internal_user_password($user->password);
  479. $upt->track('password', $user->password, 'normal', false);
  480. } else {
  481. // do not print password when not changed
  482. $upt->track('password', '', 'normal', false);
  483. }
  484. }
  485. if ($doupdate or $existinguser->password !== $oldpw) {
  486. // we want only users that were really updated
  487. $DB->update_record('user', $existinguser);
  488. $upt->track('status', $struserupdated);
  489. $usersupdated++;
  490. // save custom profile fields data from csv file
  491. profile_save_data($existinguser);
  492. events_trigger('user_updated', $existinguser);
  493. if ($bulk == UU_BULK_UPDATED or $bulk == UU_BULK_ALL) {
  494. if (!in_array($user->id, $SESSION->bulk_users)) {
  495. $SESSION->bulk_users[] = $user->id;
  496. }
  497. }
  498. } else {
  499. // no user information changed
  500. $upt->track('status', $struseruptodate);
  501. $usersuptodate++;
  502. if ($bulk == UU_BULK_ALL) {
  503. if (!in_array($user->id, $SESSION->bulk_users)) {
  504. $SESSION->bulk_users[] = $user->id;
  505. }
  506. }
  507. }
  508. } else {
  509. // save the new user to the database
  510. $user->confirmed = 1;
  511. $user->timemodified = time();
  512. $user->timecreated = time();
  513. $user->mnethostid = $CFG->mnet_localhost_id; // we support ONLY local accounts here, sorry
  514. if (empty($user->auth)) {
  515. $user->auth = 'manual';
  516. }
  517. $upt->track('auth', $user->auth, 'normal', false);
  518. // do not insert record if new auth plugin does not exist!
  519. try {
  520. $auth = get_auth_plugin($user->auth);
  521. } catch (Exception $e) {
  522. $upt->track('auth', get_string('userautherror', 'error', s($user->auth)), 'error');
  523. $upt->track('status', $strusernotaddederror, 'error');
  524. $userserrors++;
  525. continue;
  526. }
  527. if (!isset($supportedauths[$user->auth])) {
  528. $upt->track('auth', $struserauthunsupported, 'warning');
  529. }
  530. $isinternalauth = $auth->is_internal();
  531. if ($DB->record_exists('user', array('email'=>$user->email))) {
  532. if ($noemailduplicates) {
  533. $upt->track('email', $stremailduplicate, 'error');
  534. $upt->track('status', $strusernotaddederror, 'error');
  535. $userserrors++;
  536. continue;
  537. } else {
  538. $upt->track('email', $stremailduplicate, 'warning');
  539. }
  540. }
  541. if (!validate_email($user->email)) {
  542. $upt->track('email', get_string('invalidemail'), 'warning');
  543. }
  544. $forcechangepassword = false;
  545. if ($isinternalauth) {
  546. if (empty($user->password)) {
  547. if ($createpasswords) {
  548. $user->password = 'to be generated';
  549. $upt->track('password', '', 'normal', false);
  550. $upt->track('password', get_string('uupasswordcron', 'admin'), 'warning', false);
  551. } else {
  552. $upt->track('password', '', 'normal', false);
  553. $upt->track('password', get_string('missingfield', 'error', 'password'), 'error');
  554. $upt->track('status', $strusernotaddederror, 'error');
  555. $userserrors++;
  556. continue;
  557. }
  558. } else {
  559. $errmsg = null;
  560. $weak = !check_password_policy($user->password, $errmsg);
  561. if ($resetpasswords == UU_PWRESET_ALL or ($resetpasswords == UU_PWRESET_WEAK and $weak)) {
  562. if ($weak) {
  563. $weakpasswords++;
  564. $upt->track('password', $strinvalidpasswordpolicy, 'warning');
  565. }
  566. $forcechangepassword = true;
  567. }
  568. $user->password = hash_internal_user_password($user->password);
  569. }
  570. } else {
  571. $user->password = 'not cached';
  572. $upt->track('password', '-', 'normal', false);
  573. }
  574. // create user - insert_record ignores any extra properties
  575. $user->id = $DB->insert_record('user', $user);
  576. $upt->track('username', html_writer::link(new moodle_url('/user/profile.php', array('id'=>$user->id)), s($user->username)), 'normal', false);
  577. // save custom profile fields data
  578. profile_save_data($user);
  579. if ($forcechangepassword) {
  580. set_user_preference('auth_forcepasswordchange', 1, $user);
  581. }
  582. if ($user->password === 'to be generated') {
  583. set_user_preference('create_password', 1, $user);
  584. }
  585. $upt->track('status', $struseradded);
  586. $upt->track('id', $user->id, 'normal', false);
  587. $usersnew++;
  588. // make sure user context exists
  589. get_context_instance(CONTEXT_USER, $user->id);
  590. events_trigger('user_created', $user);
  591. if ($bulk == UU_BULK_NEW or $bulk == UU_BULK_ALL) {
  592. if (!in_array($user->id, $SESSION->bulk_users)) {
  593. $SESSION->bulk_users[] = $user->id;
  594. }
  595. }
  596. }
  597. // find course enrolments, groups, roles/types and enrol periods
  598. // this is again a special case, we always do this for any updated or created users
  599. foreach ($filecolumns as $column) {
  600. if (!preg_match('/^course\d+$/', $column)) {
  601. continue;
  602. }
  603. $i = substr($column, 6);
  604. if (empty($user->{'course'.$i})) {
  605. continue;
  606. }
  607. $shortname = $user->{'course'.$i};
  608. if (!array_key_exists($shortname, $ccache)) {
  609. if (!$course = $DB->get_record('course', array('shortname'=>$shortname), 'id, shortname')) {
  610. $upt->track('enrolments', get_string('unknowncourse', 'error', s($shortname)), 'error');
  611. continue;
  612. }
  613. $ccache[$shortname] = $course;
  614. $ccache[$shortname]->groups = null;
  615. }
  616. $courseid = $ccache[$shortname]->id;
  617. $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
  618. if (!isset($manualcache[$courseid])) {
  619. $manualcache[$courseid] = false;
  620. if ($manual) {
  621. if ($instances = enrol_get_instances($courseid, false)) {
  622. foreach ($instances as $instance) {
  623. if ($instance->enrol === 'manual') {
  624. $manualcache[$courseid] = $instance;
  625. break;
  626. }
  627. }
  628. }
  629. }
  630. }
  631. if ($manual and $manualcache[$courseid]) {
  632. // find role
  633. $rid = false;
  634. if (!empty($user->{'role'.$i})) {
  635. $addrole = $user->{'role'.$i};
  636. if (array_key_exists($addrole, $rolecache)) {
  637. $rid = $rolecache[$addrole]->id;
  638. } else {
  639. $upt->track('enrolments', get_string('unknownrole', 'error', s($addrole)), 'error');
  640. continue;
  641. }
  642. } else if (!empty($user->{'type'.$i})) {
  643. // if no role, then find "old" enrolment type
  644. $addtype = $user->{'type'.$i};
  645. if ($addtype < 1 or $addtype > 3) {
  646. $upt->track('enrolments', $strerror.': typeN = 1|2|3', 'error');
  647. continue;
  648. } else if (empty($formdata->{'uulegacy'.$addtype})) {
  649. continue;
  650. } else {
  651. $rid = $formdata->{'uulegacy'.$addtype};
  652. }
  653. } else {
  654. // no role specified, use the default from manual enrol plugin
  655. $rid = $manualcache[$courseid]->roleid;
  656. }
  657. if ($rid) {
  658. // find duration
  659. $timeend = 0;
  660. if (!empty($user->{'enrolperiod'.$i})) {
  661. $duration = (int)$user->{'enrolperiod'.$i} * 60*60*24; // convert days to seconds
  662. if ($duration > 0) { // sanity check
  663. $timeend = $today + $duration;
  664. }
  665. }
  666. $manual->enrol_user($manualcache[$courseid], $user->id, $rid, $today, $timeend, true);
  667. $a = new stdClass();
  668. $a->course = $shortname;
  669. $a->role = $rolecache[$rid]->name;
  670. $upt->track('enrolments', get_string('enrolledincourserole', 'enrol_manual', $a));
  671. }
  672. }
  673. // find group to add to
  674. if (!empty($user->{'group'.$i})) {
  675. // make sure user is enrolled into course before adding into groups
  676. if (!is_enrolled($coursecontext, $user->id)) {
  677. $upt->track('enrolments', get_string('addedtogroupnotenrolled', '', $user->{'group'.$i}), 'error');
  678. continue;
  679. }
  680. //build group cache
  681. if (is_null($ccache[$shortname]->groups)) {
  682. $ccache[$shortname]->groups = array();
  683. if ($groups = groups_get_all_groups($courseid)) {
  684. foreach ($groups as $gid=>$group) {
  685. $ccache[$shortname]->groups[$gid] = new stdClass();
  686. $ccache[$shortname]->groups[$gid]->id = $gid;
  687. $ccache[$shortname]->groups[$gid]->name = $group->name;
  688. if (!is_numeric($group->name)) { // only non-numeric names are supported!!!
  689. $ccache[$shortname]->groups[$group->name] = new stdClass();
  690. $ccache[$shortname]->groups[$group->name]->id = $gid;
  691. $ccache[$shortname]->groups[$group->name]->name = $group->name;
  692. }
  693. }
  694. }
  695. }
  696. // group exists?
  697. $addgroup = $user->{'group'.$i};
  698. if (!array_key_exists($addgroup, $ccache[$shortname]->groups)) {
  699. // if group doesn't exist, create it
  700. $newgroupdata = new stdClass();
  701. $newgroupdata->name = $addgroup;
  702. $newgroupdata->courseid = $ccache[$shortname]->id;
  703. if ($ccache[$shortname]->groups[$addgroup]->id = groups_create_group($newgroupdata)){
  704. $ccache[$shortname]->groups[$addgroup]->name = $newgroupdata->name;
  705. } else {
  706. $upt->track('enrolments', get_string('unknowngroup', 'error', s($addgroup)), 'error');
  707. continue;
  708. }
  709. }
  710. $gid = $ccache[$shortname]->groups[$addgroup]->id;
  711. $gname = $ccache[$shortname]->groups[$addgroup]->name;
  712. try {
  713. if (groups_add_member($gid, $user->id)) {
  714. $upt->track('enrolments', get_string('addedtogroup', '', s($gname)));
  715. } else {
  716. $upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
  717. }
  718. } catch (moodle_exception $e) {
  719. $upt->track('enrolments', get_string('addedtogroupnot', '', s($gname)), 'error');
  720. continue;
  721. }
  722. }
  723. }
  724. }
  725. $upt->close(); // close table
  726. $cir->close();
  727. $cir->cleanup(true);
  728. echo $OUTPUT->box_start('boxwidthnarrow boxaligncenter generalbox', 'uploadresults');
  729. echo '<p>';
  730. if ($optype != UU_USER_UPDATE) {
  731. echo get_string('userscreated', 'admin').': '.$usersnew.'<br />';
  732. }
  733. if ($optype == UU_USER_UPDATE or $optype == UU_USER_ADD_UPDATE) {
  734. echo get_string('usersupdated', 'admin').': '.$usersupdated.'<br />';
  735. }
  736. if ($allowdeletes) {
  737. echo get_string('usersdeleted', 'admin').': '.$deletes.'<br />';
  738. echo get_string('deleteerrors', 'admin').': '.$deleteerrors.'<br />';
  739. }
  740. if ($allowrenames) {
  741. echo get_string('usersrenamed', 'admin').': '.$renames.'<br />';
  742. echo get_string('renameerrors', 'admin').': '.$renameerrors.'<br />';
  743. }
  744. if ($usersskipped) {
  745. echo get_string('usersskipped', 'admin').': '.$usersskipped.'<br />';
  746. }
  747. echo get_string('usersweakpassword', 'admin').': '.$weakpasswords.'<br />';
  748. echo get_string('errors', 'admin').': '.$userserrors.'</p>';
  749. echo $OUTPUT->box_end();
  750. if ($bulk) {
  751. echo $OUTPUT->continue_button($bulknurl);
  752. } else {
  753. echo $OUTPUT->continue_button($returnurl);
  754. }
  755. echo $OUTPUT->footer();
  756. die;
  757. }
  758. // Print the header
  759. echo $OUTPUT->header();
  760. echo $OUTPUT->heading(get_string('uploaduserspreview', 'admin'));
  761. // NOTE: this is JUST csv processing preview, we must not prevent import from here if there is something in the file!!
  762. // this was intended for validation of csv formatting and encoding, not filtering the data!!!!
  763. // we definitely must not process the whole file!
  764. // preview table data
  765. $data = array();
  766. $cir->init();
  767. $linenum = 1; //column header is first line
  768. while ($linenum <= $previewrows and $fields = $cir->next()) {
  769. $linenum++;
  770. $rowcols = array();
  771. $rowcols['line'] = $linenum;
  772. foreach($fields as $key => $field) {
  773. $rowcols[$filecolumns[$key]] = s($field);
  774. }
  775. $rowcols['status'] = array();
  776. if (isset($rowcols['username'])) {
  777. $stdusername = clean_param($rowcols['username'], PARAM_USERNAME);
  778. if ($rowcols['username'] !== $stdusername) {
  779. $rowcols['status'][] = get_string('invalidusernameupload');
  780. }
  781. if ($userid = $DB->get_field('user', 'id', array('username'=>$stdusername, 'mnethostid'=>$CFG->mnet_localhost_id))) {
  782. $rowcols['username'] = html_writer::link(new moodle_url('/user/profile.php', array('id'=>$userid)), $rowcols['username']);
  783. }
  784. } else {
  785. $rowcols['status'][] = get_string('missingusername');
  786. }
  787. if (!validate_email($rowcols['email'])) {
  788. $rowcols['status'][] = get_string('invalidemail');
  789. }
  790. if ($DB->record_exists('user', array('email'=>$rowcols['email']))) {
  791. $rowcols['status'][] = $stremailduplicate;
  792. }
  793. $rowcols['status'] = implode('<br />', $rowcols['status']);
  794. $data[] = $rowcols;
  795. }
  796. if ($fields = $cir->next()) {
  797. $data[] = array_fill(0, count($fields) + 2, '...');
  798. }
  799. $cir->close();
  800. $table = new html_table();
  801. $table->id = "uupreview";
  802. $table->attributes['class'] = 'generaltable';
  803. $table->tablealign = 'center';
  804. $table->summary = get_string('uploaduserspreview', 'admin');
  805. $table->head = array();
  806. $table->data = $data;
  807. $table->head[] = get_string('uucsvline', 'admin');
  808. foreach ($filecolumns as $column) {
  809. $table->head[] = $column;
  810. }
  811. $table->head[] = get_string('status');
  812. echo html_writer::tag('div', html_writer::table($table), array('class'=>'flexible-wrap'));
  813. /// Print the form
  814. $mform2->display();
  815. echo $OUTPUT->footer();
  816. die;