user_import.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This tool allows platform admins to add users by uploading a CSV or XML file.
  5. *
  6. * @package chamilo.admin
  7. */
  8. $cidReset = true;
  9. require_once __DIR__.'/../inc/global.inc.php';
  10. // Set this option to true to enforce strict purification for usenames.
  11. $purification_option_for_usernames = false;
  12. /**
  13. * @param array $users
  14. * @param bool $checkUniqueEmail
  15. *
  16. * @return array
  17. */
  18. function validate_data($users, $checkUniqueEmail = false)
  19. {
  20. global $defined_auth_sources;
  21. $errors = [];
  22. $usernames = [];
  23. // 1. Check if mandatory fields are set.
  24. $mandatory_fields = ['LastName', 'FirstName'];
  25. if (api_get_setting('registration', 'email') == 'true' || $checkUniqueEmail) {
  26. $mandatory_fields[] = 'Email';
  27. }
  28. $classExistList = [];
  29. $usergroup = new UserGroup();
  30. foreach ($users as $user) {
  31. foreach ($mandatory_fields as $field) {
  32. if (empty($user[$field])) {
  33. $user['error'] = get_lang($field.'Mandatory');
  34. $errors[] = $user;
  35. }
  36. }
  37. $username = $user['UserName'];
  38. // 2. Check username, first, check whether it is empty.
  39. if (!UserManager::is_username_empty($username)) {
  40. // 2.1. Check whether username is too long.
  41. if (UserManager::is_username_too_long($username)) {
  42. $user['error'] = get_lang('UserNameTooLong');
  43. $errors[] = $user;
  44. }
  45. // 2.1.1
  46. $hasDash = strpos($username, '-');
  47. if ($hasDash !== false) {
  48. $user['error'] = get_lang('UserNameHasDash');
  49. $errors[] = $user;
  50. }
  51. // 2.2. Check whether the username was used twice in import file.
  52. if (isset($usernames[$username])) {
  53. $user['error'] = get_lang('UserNameUsedTwice');
  54. $errors[] = $user;
  55. }
  56. $usernames[$username] = 1;
  57. // 2.3. Check whether username is already occupied.
  58. if (!UserManager::is_username_available($username)) {
  59. $user['error'] = get_lang('UserNameNotAvailable');
  60. $errors[] = $user;
  61. }
  62. }
  63. if ($checkUniqueEmail) {
  64. if (isset($user['Email'])) {
  65. $userFromEmail = api_get_user_info_from_email($user['Email']);
  66. if (!empty($userFromEmail)) {
  67. $user['error'] = get_lang('EmailUsedTwice');
  68. $errors[] = $user;
  69. }
  70. }
  71. }
  72. // 3. Check status.
  73. if (isset($user['Status']) && !api_status_exists($user['Status'])) {
  74. $user['error'] = get_lang('WrongStatus');
  75. $errors[] = $user;
  76. }
  77. // 4. Check ClassId
  78. if (!empty($user['ClassId'])) {
  79. $classId = explode('|', trim($user['ClassId']));
  80. foreach ($classId as $id) {
  81. if (in_array($id, $classExistList)) {
  82. continue;
  83. }
  84. $info = $usergroup->get($id);
  85. if (empty($info)) {
  86. $user['error'] = sprintf(get_lang('ClassIdDoesntExists'), $id);
  87. $errors[] = $user;
  88. } else {
  89. $classExistList[] = $info['id'];
  90. }
  91. }
  92. }
  93. // 5. Check authentication source
  94. if (!empty($user['AuthSource'])) {
  95. if (!in_array($user['AuthSource'], $defined_auth_sources)) {
  96. $user['error'] = get_lang('AuthSourceNotAvailable');
  97. $errors[] = $user;
  98. }
  99. }
  100. }
  101. return $errors;
  102. }
  103. /**
  104. * Add missing user-information (which isn't required, like password, username etc).
  105. */
  106. function complete_missing_data($user)
  107. {
  108. global $purification_option_for_usernames;
  109. // 1. Create a username if necessary.
  110. if (UserManager::is_username_empty($user['UserName'])) {
  111. $user['UserName'] = UserManager::create_unique_username(
  112. $user['FirstName'],
  113. $user['LastName']
  114. );
  115. } else {
  116. $user['UserName'] = UserManager::purify_username(
  117. $user['UserName'],
  118. $purification_option_for_usernames
  119. );
  120. }
  121. // 2. Generate a password if necessary.
  122. if (empty($user['Password'])) {
  123. $user['Password'] = api_generate_password();
  124. }
  125. // 3. Set status if not allready set.
  126. if (empty($user['Status'])) {
  127. $user['Status'] = 'user';
  128. }
  129. // 4. Set authsource if not allready set.
  130. if (empty($user['AuthSource'])) {
  131. $user['AuthSource'] = PLATFORM_AUTH_SOURCE;
  132. }
  133. if (empty($user['ExpiryDate'])) {
  134. $user['ExpiryDate'] = '';
  135. }
  136. if (!isset($user['OfficialCode'])) {
  137. $user['OfficialCode'] = '';
  138. }
  139. if (!isset($user['language'])) {
  140. $user['language'] = '';
  141. }
  142. if (!isset($user['PhoneNumber'])) {
  143. $user['PhoneNumber'] = '';
  144. }
  145. if (!isset($user['OfficialCode'])) {
  146. $user['OfficialCode'] = '';
  147. }
  148. return $user;
  149. }
  150. /**
  151. * Save the imported data.
  152. *
  153. * @param array $users List of users
  154. *
  155. * @uses \global variable $inserted_in_course, which returns the list of
  156. * courses the user was inserted in
  157. */
  158. function save_data($users)
  159. {
  160. global $inserted_in_course;
  161. // Not all scripts declare the $inserted_in_course array (although they should).
  162. if (!isset($inserted_in_course)) {
  163. $inserted_in_course = [];
  164. }
  165. $usergroup = new UserGroup();
  166. $send_mail = $_POST['sendMail'] ? true : false;
  167. if (is_array($users)) {
  168. foreach ($users as $user) {
  169. $user = complete_missing_data($user);
  170. $user['Status'] = api_status_key($user['Status']);
  171. $user_id = UserManager::create_user(
  172. $user['FirstName'],
  173. $user['LastName'],
  174. $user['Status'],
  175. $user['Email'],
  176. $user['UserName'],
  177. $user['Password'],
  178. $user['OfficialCode'],
  179. $user['language'],
  180. $user['PhoneNumber'],
  181. '',
  182. $user['AuthSource'],
  183. $user['ExpiryDate'],
  184. 1,
  185. 0,
  186. null,
  187. null,
  188. $send_mail
  189. );
  190. if (isset($user['Courses']) && is_array($user['Courses'])) {
  191. foreach ($user['Courses'] as $course) {
  192. if (CourseManager::course_exists($course)) {
  193. CourseManager::subscribe_user($user_id, $course, $user['Status']);
  194. $course_info = CourseManager::get_course_information($course);
  195. $inserted_in_course[$course] = $course_info['title'];
  196. }
  197. }
  198. }
  199. if (isset($user['Sessions']) && is_array($user['Sessions'])) {
  200. foreach ($user['Sessions'] as $sessionId) {
  201. $sessionInfo = api_get_session_info($sessionId);
  202. if (!empty($sessionInfo)) {
  203. SessionManager::subscribeUsersToSession(
  204. $sessionId,
  205. [$user_id],
  206. SESSION_VISIBLE_READ_ONLY,
  207. false
  208. );
  209. }
  210. }
  211. }
  212. if (!empty($user['ClassId'])) {
  213. $classId = explode('|', trim($user['ClassId']));
  214. foreach ($classId as $id) {
  215. $usergroup->subscribe_users_to_usergroup($id, [$user_id], false);
  216. }
  217. }
  218. // Saving extra fields.
  219. global $extra_fields;
  220. // We are sure that the extra field exists.
  221. foreach ($extra_fields as $extras) {
  222. if (isset($user[$extras[1]])) {
  223. $key = $extras[1];
  224. $value = $user[$extras[1]];
  225. UserManager::update_extra_field_value($user_id, $key, $value);
  226. }
  227. }
  228. }
  229. }
  230. }
  231. /**
  232. * Read the CSV-file.
  233. *
  234. * @param string $file Path to the CSV-file
  235. *
  236. * @return array All userinformation read from the file
  237. */
  238. function parse_csv_data($file)
  239. {
  240. $users = Import::csvToArray($file);
  241. $allowRandom = api_get_configuration_value('generate_random_login');
  242. if ($allowRandom) {
  243. $factory = new RandomLib\Factory();
  244. $generator = $factory->getLowStrengthGenerator();
  245. $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  246. }
  247. foreach ($users as $index => $user) {
  248. if (isset($user['UserName'])) {
  249. if ($allowRandom) {
  250. $username = $generator->generateString(10, $chars);
  251. $user['UserName'] = $username;
  252. }
  253. }
  254. if (isset($user['Courses'])) {
  255. $user['Courses'] = explode('|', trim($user['Courses']));
  256. }
  257. if (isset($user['Sessions'])) {
  258. $user['Sessions'] = explode('|', trim($user['Sessions']));
  259. }
  260. // Lastname is needed.
  261. if (!isset($user['LastName']) || (isset($user['LastName']) && empty($user['LastName']))) {
  262. unset($users[$index]);
  263. continue;
  264. }
  265. // FirstName is needed.
  266. if (!isset($user['FirstName']) || (isset($user['FirstName']) && empty($user['FirstName']))) {
  267. unset($users[$index]);
  268. continue;
  269. }
  270. $users[$index] = $user;
  271. }
  272. return $users;
  273. }
  274. /**
  275. * XML-parser: handle start of element.
  276. *
  277. * @param string $parser Deprecated?
  278. * @param string $data The data to be parsed
  279. */
  280. function element_start($parser, $data)
  281. {
  282. $data = api_utf8_decode($data);
  283. global $user;
  284. global $current_tag;
  285. switch ($data) {
  286. case 'Contact':
  287. $user = [];
  288. break;
  289. default:
  290. $current_tag = $data;
  291. }
  292. }
  293. /**
  294. * XML-parser: handle end of element.
  295. *
  296. * @param string $parser Deprecated?
  297. * @param string $data The data to be parsed
  298. */
  299. function element_end($parser, $data)
  300. {
  301. $data = api_utf8_decode($data);
  302. global $user;
  303. global $users;
  304. global $current_value;
  305. switch ($data) {
  306. case 'Contact':
  307. if ($user['Status'] == '5') {
  308. $user['Status'] = STUDENT;
  309. }
  310. if ($user['Status'] == '1') {
  311. $user['Status'] = COURSEMANAGER;
  312. }
  313. $users[] = $user;
  314. break;
  315. default:
  316. $user[$data] = $current_value;
  317. break;
  318. }
  319. }
  320. /**
  321. * XML-parser: handle character data.
  322. *
  323. * @param string $parser Parser (deprecated?)
  324. * @param string $data The data to be parsed
  325. */
  326. function character_data($parser, $data)
  327. {
  328. $data = trim(api_utf8_decode($data));
  329. global $current_value;
  330. $current_value = $data;
  331. }
  332. /**
  333. * Read the XML-file.
  334. *
  335. * @param string $file Path to the XML-file
  336. *
  337. * @return array All user information read from the file
  338. */
  339. function parse_xml_data($file)
  340. {
  341. global $users;
  342. $users = [];
  343. $parser = xml_parser_create('UTF-8');
  344. xml_set_element_handler($parser, 'element_start', 'element_end');
  345. xml_set_character_data_handler($parser, 'character_data');
  346. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
  347. xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
  348. xml_parser_free($parser);
  349. return $users;
  350. }
  351. $this_section = SECTION_PLATFORM_ADMIN;
  352. api_protect_admin_script(true, null);
  353. api_protect_limit_for_session_admin();
  354. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  355. if (isset($extAuthSource) && is_array($extAuthSource)) {
  356. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  357. }
  358. $tool_name = get_lang('ImportUserListXMLCSV');
  359. $interbreadcrumb[] = ["url" => 'index.php', "name" => get_lang('PlatformAdmin')];
  360. set_time_limit(0);
  361. $extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
  362. $user_id_error = [];
  363. $error_message = '';
  364. if (isset($_POST['formSent']) && $_POST['formSent'] && $_FILES['import_file']['size'] !== 0) {
  365. $file_type = $_POST['file_type'];
  366. Security::clear_token();
  367. $tok = Security::get_token();
  368. $allowed_file_mimetype = ['csv', 'xml'];
  369. $error_kind_file = false;
  370. $checkUniqueEmail = isset($_POST['check_unique_email']) ? $_POST['check_unique_email'] : null;
  371. $uploadInfo = pathinfo($_FILES['import_file']['name']);
  372. $ext_import_file = $uploadInfo['extension'];
  373. $users = [];
  374. if (in_array($ext_import_file, $allowed_file_mimetype)) {
  375. if (strcmp($file_type, 'csv') === 0 &&
  376. $ext_import_file == $allowed_file_mimetype[0]
  377. ) {
  378. $users = parse_csv_data($_FILES['import_file']['tmp_name']);
  379. $errors = validate_data($users, $checkUniqueEmail);
  380. $error_kind_file = false;
  381. } elseif (strcmp($file_type, 'xml') === 0 && $ext_import_file == $allowed_file_mimetype[1]) {
  382. $users = parse_xml_data($_FILES['import_file']['tmp_name']);
  383. $errors = validate_data($users, $checkUniqueEmail);
  384. $error_kind_file = false;
  385. } else {
  386. $error_kind_file = true;
  387. }
  388. } else {
  389. $error_kind_file = true;
  390. }
  391. // List user id with error.
  392. $users_to_insert = [];
  393. $keyToCheck = 'UserName';
  394. if ($checkUniqueEmail || api_get_setting('registration', 'email') == 'true') {
  395. $keyToCheck = 'Email';
  396. }
  397. if (is_array($errors)) {
  398. foreach ($errors as $my_errors) {
  399. $user_id_error[] = $my_errors[$keyToCheck];
  400. }
  401. }
  402. if (is_array($users)) {
  403. foreach ($users as $my_user) {
  404. if (!in_array($my_user[$keyToCheck], $user_id_error)) {
  405. $users_to_insert[] = $my_user;
  406. }
  407. }
  408. }
  409. $inserted_in_course = [];
  410. if (strcmp($file_type, 'csv') === 0) {
  411. save_data($users_to_insert);
  412. } elseif (strcmp($file_type, 'xml') === 0) {
  413. save_data($users_to_insert);
  414. } else {
  415. $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
  416. }
  417. if (count($errors) > 0) {
  418. $see_message_import = get_lang('FileImportedJustUsersThatAreNotRegistered');
  419. } else {
  420. $see_message_import = get_lang('FileImported');
  421. }
  422. $warning_message = '';
  423. if (count($errors) != 0) {
  424. $warning_message = '<ul>';
  425. foreach ($errors as $index => $error_user) {
  426. $email = isset($error_user['Email']) ? ' - '.$error_user['Email'] : null;
  427. $warning_message .= '<li><b>'.$error_user['error'].'</b>: ';
  428. $warning_message .=
  429. '<strong>'.$error_user['UserName'].'</strong> - '.
  430. api_get_person_name(
  431. $error_user['FirstName'],
  432. $error_user['LastName']
  433. ).' '.$email;
  434. $warning_message .= '</li>';
  435. }
  436. $warning_message .= '</ul>';
  437. }
  438. // if the warning message is too long then we display the warning message trough a session
  439. Display::addFlash(Display::return_message($warning_message, 'warning', false));
  440. Display::addFlash(Display::return_message($see_message_import, 'confirmation', false));
  441. if ($error_kind_file) {
  442. Display::addFlash(
  443. Display::return_message(
  444. get_lang('YouMustImportAFileAccordingToSelectedOption'),
  445. 'error',
  446. false
  447. )
  448. );
  449. } else {
  450. header('Location: '.api_get_path(WEB_CODE_PATH).'admin/user_list.php?sec_token='.$tok);
  451. exit;
  452. }
  453. }
  454. Display::display_header($tool_name);
  455. $form = new FormValidator('user_import', 'post', api_get_self());
  456. $form->addElement('header', '', $tool_name);
  457. $form->addElement('hidden', 'formSent');
  458. $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
  459. $group = [
  460. $form->createElement(
  461. 'radio',
  462. 'file_type',
  463. '',
  464. 'CSV (<a href="example.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)',
  465. 'csv'
  466. ),
  467. $form->createElement(
  468. 'radio',
  469. 'file_type',
  470. null,
  471. 'XML (<a href="example.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)',
  472. 'xml'
  473. ),
  474. ];
  475. $form->addGroup($group, '', get_lang('FileType'));
  476. $group = [
  477. $form->createElement('radio', 'sendMail', '', get_lang('Yes'), 1),
  478. $form->createElement('radio', 'sendMail', null, get_lang('No'), 0),
  479. ];
  480. $form->addGroup($group, '', get_lang('SendMailToUsers'));
  481. $form->addElement(
  482. 'checkbox',
  483. 'check_unique_email',
  484. '',
  485. get_lang('CheckUniqueEmail')
  486. );
  487. $form->addButtonImport(get_lang('Import'));
  488. $defaults['formSent'] = 1;
  489. $defaults['sendMail'] = 0;
  490. $defaults['file_type'] = 'csv';
  491. $form->setDefaults($defaults);
  492. $form->display();
  493. $list = [];
  494. $list_reponse = [];
  495. $result_xml = '';
  496. $i = 0;
  497. $count_fields = count($extra_fields);
  498. if ($count_fields > 0) {
  499. foreach ($extra_fields as $extra) {
  500. $list[] = $extra[1];
  501. $list_reponse[] = 'xxx';
  502. $spaces = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  503. $result_xml .= $spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';
  504. if ($i != $count_fields - 1) {
  505. $result_xml .= '<br/>';
  506. }
  507. $i++;
  508. }
  509. }
  510. ?>
  511. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  512. <blockquote>
  513. <pre>
  514. <b>LastName</b>;<b>FirstName</b>;<b>Email</b>;UserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;ExpiryDate;<span style="color:red;"><?php if (count($list) > 0) {
  515. echo implode(';', $list).';';
  516. } ?></span>Courses;Sessions;ClassId;
  517. <b>xxx</b>;<b>xxx</b>;<b>xxx</b>;xxx;xxx;<?php echo implode('/', $defined_auth_sources); ?>;xxx;xxx;user/teacher/drh;0000-00-00 00:00:00;<span style="color:red;"><?php if (count($list_reponse) > 0) {
  518. echo implode(';', $list_reponse).';';
  519. } ?></span>xxx1|xxx2|xxx3;sessionId|sessionId|sessionId;1;<br />
  520. </pre>
  521. </blockquote>
  522. <p><?php echo get_lang('XMLMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  523. <blockquote>
  524. <pre>
  525. &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
  526. &lt;Contacts&gt;
  527. &lt;Contact&gt;
  528. <b>&lt;LastName&gt;xxx&lt;/LastName&gt;</b>
  529. <b>&lt;FirstName&gt;xxx&lt;/FirstName&gt;</b>
  530. &lt;UserName&gt;xxx&lt;/UserName&gt;
  531. &lt;Password&gt;xxx&lt;/Password&gt;
  532. &lt;AuthSource&gt;<?php echo implode('/', $defined_auth_sources); ?>&lt;/AuthSource&gt;
  533. <b>&lt;Email&gt;xxx&lt;/Email&gt;</b>
  534. &lt;OfficialCode&gt;xxx&lt;/OfficialCode&gt;
  535. &lt;PhoneNumber&gt;xxx&lt;/PhoneNumber&gt;
  536. &lt;Status&gt;user/teacher/drh<?php if ($result_xml != '') {
  537. echo '<br /><span style="color:red;">', $result_xml;
  538. echo '</span>';
  539. } ?>&lt;/Status&gt;
  540. &lt;Courses&gt;xxx1|xxx2|xxx3&lt;/Courses&gt;
  541. &lt;Sessions&gt;sessionId|sessionId|sessionId&lt;/Sessions&gt;
  542. &lt;ClassId&gt;1&lt;/ClassId&gt;
  543. &lt;/Contact&gt;
  544. &lt;/Contacts&gt;
  545. </pre>
  546. </blockquote>
  547. <?php
  548. Display :: display_footer();