user_import.php 18 KB

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