user_import.php 18 KB

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