user_import.php 18 KB

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