user_import.php 18 KB

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