user_import.php 18 KB

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