user_import.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Framework\Container;
  4. /**
  5. * This tool allows platform admins to add users by uploading a CSV or XML file
  6. * @package chamilo.admin
  7. */
  8. $cidReset = true;
  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. if (!isset($user['LastName']) || (isset($user['LastName']) && empty($user['LastName']))) {
  227. unset($users[$index]);
  228. continue;
  229. }
  230. // FirstName is needed.
  231. if (!isset($user['FirstName']) || (isset($user['FirstName']) && empty($user['FirstName']))) {
  232. unset($users[$index]);
  233. continue;
  234. }
  235. $users[$index] = $user;
  236. }
  237. return $users;
  238. }
  239. /**
  240. * XML-parser: handle start of element
  241. * @param string $parser Deprecated?
  242. * @param string $data The data to be parsed
  243. */
  244. function element_start($parser, $data)
  245. {
  246. $data = api_utf8_decode($data);
  247. global $user;
  248. global $current_tag;
  249. switch ($data) {
  250. case 'Contact':
  251. $user = array ();
  252. break;
  253. default:
  254. $current_tag = $data;
  255. }
  256. }
  257. /**
  258. * XML-parser: handle end of element
  259. * @param string $parser Deprecated?
  260. * @param string $data The data to be parsed
  261. */
  262. function element_end($parser, $data)
  263. {
  264. $data = api_utf8_decode($data);
  265. global $user;
  266. global $users;
  267. global $current_value;
  268. switch ($data) {
  269. case 'Contact':
  270. if ($user['Status'] == '5') {
  271. $user['Status'] = STUDENT;
  272. }
  273. if ($user['Status'] == '1') {
  274. $user['Status'] = COURSEMANAGER;
  275. }
  276. $users[] = $user;
  277. break;
  278. default:
  279. $user[$data] = $current_value;
  280. break;
  281. }
  282. }
  283. /**
  284. * XML-parser: handle character data
  285. * @param string $parser Parser (deprecated?)
  286. * @param string $data The data to be parsed
  287. * @return void
  288. */
  289. function character_data($parser, $data)
  290. {
  291. $data = trim(api_utf8_decode($data));
  292. global $current_value;
  293. $current_value = $data;
  294. }
  295. /**
  296. * Read the XML-file
  297. * @param string $file Path to the XML-file
  298. * @return array All user information read from the file
  299. */
  300. function parse_xml_data($file)
  301. {
  302. global $users;
  303. $users = array();
  304. $parser = xml_parser_create('UTF-8');
  305. xml_set_element_handler($parser, 'element_start', 'element_end');
  306. xml_set_character_data_handler($parser, 'character_data');
  307. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
  308. xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
  309. xml_parser_free($parser);
  310. return $users;
  311. }
  312. $this_section = SECTION_PLATFORM_ADMIN;
  313. api_protect_admin_script(true, null, 'login');
  314. api_protect_limit_for_session_admin();
  315. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  316. if (isset($extAuthSource) && is_array($extAuthSource)) {
  317. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  318. }
  319. $tool_name = get_lang('ImportUserListXMLCSV');
  320. $interbreadcrumb[] = array('url' => Container::getRouter()->generate('administration') , "name" => get_lang('PlatformAdmin'));
  321. set_time_limit(0);
  322. $extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
  323. $user_id_error = array();
  324. $error_message = '';
  325. if (isset($_POST['formSent']) && $_POST['formSent'] AND
  326. $_FILES['import_file']['size'] !== 0
  327. ) {
  328. $file_type = $_POST['file_type'];
  329. Security::clear_token();
  330. $tok = Security::get_token();
  331. $allowed_file_mimetype = array('csv', 'xml');
  332. $error_kind_file = false;
  333. $checkUniqueEmail = isset($_POST['check_unique_email']) ? $_POST['check_unique_email'] :null;
  334. $uploadInfo = pathinfo($_FILES['import_file']['name']);
  335. $ext_import_file = $uploadInfo['extension'];
  336. $users = array();
  337. if (in_array($ext_import_file, $allowed_file_mimetype)) {
  338. if (strcmp($file_type, 'csv') === 0 &&
  339. $ext_import_file == $allowed_file_mimetype[0]
  340. ) {
  341. $users = parse_csv_data($_FILES['import_file']['tmp_name']);
  342. $errors = validate_data($users, $checkUniqueEmail);
  343. $error_kind_file = false;
  344. } elseif (strcmp($file_type, 'xml') === 0 && $ext_import_file == $allowed_file_mimetype[1]) {
  345. $users = parse_xml_data($_FILES['import_file']['tmp_name']);
  346. $errors = validate_data($users, $checkUniqueEmail);
  347. $error_kind_file = false;
  348. } else {
  349. $error_kind_file = true;
  350. }
  351. } else {
  352. $error_kind_file = true;
  353. }
  354. // List user id with error.
  355. $users_to_insert = array();
  356. $keyToCheck = 'Username';
  357. if ($checkUniqueEmail || api_get_setting('registration', 'email') == 'true') {
  358. $keyToCheck = 'Email';
  359. }
  360. if (is_array($errors)) {
  361. foreach ($errors as $my_errors) {
  362. $user_id_error[] = $my_errors[$keyToCheck];
  363. }
  364. }
  365. if (is_array($users)) {
  366. foreach ($users as $my_user) {
  367. if (!in_array($my_user[$keyToCheck], $user_id_error)) {
  368. $users_to_insert[] = $my_user;
  369. }
  370. }
  371. }
  372. $inserted_in_course = array();
  373. if (strcmp($file_type, 'csv') === 0) {
  374. save_data($users_to_insert);
  375. } elseif (strcmp($file_type, 'xml') === 0) {
  376. save_data($users_to_insert);
  377. } else {
  378. $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
  379. }
  380. if (count($errors) > 0) {
  381. $see_message_import = get_lang('FileImportedJustUsersThatAreNotRegistered');
  382. } else {
  383. $see_message_import = get_lang('FileImported');
  384. }
  385. if (count($errors) != 0) {
  386. $warning_message = '<ul>';
  387. foreach ($errors as $index => $error_user) {
  388. $email = isset($error_user['Email']) ? ' - '.$error_user['Email'] : null;
  389. $warning_message .= '<li><b>'.$error_user['error'].'</b>: ';
  390. $warning_message .=
  391. '<strong>'.$error_user['UserName'].'</strong> - '.
  392. api_get_person_name(
  393. $error_user['FirstName'],
  394. $error_user['LastName']
  395. ).' '.$email;
  396. $warning_message .= '</li>';
  397. }
  398. $warning_message .= '</ul>';
  399. }
  400. // if the warning message is too long then we display the warning message trough a session
  401. Display::addFlash(Display::return_message($warning_message, 'warning', false));
  402. Display::addFlash(Display::return_message($see_message_import, 'confirmation', false));
  403. if ($error_kind_file) {
  404. Display::addFlash(
  405. Display::return_message(
  406. get_lang('YouMustImportAFileAccordingToSelectedOption'),
  407. 'error',
  408. false
  409. )
  410. );
  411. } else {
  412. header('Location: '.api_get_path(WEB_CODE_PATH).'admin/user_list.php?sec_token='.$tok);
  413. exit;
  414. }
  415. }
  416. Display :: display_header($tool_name);
  417. $form = new FormValidator('user_import', 'post', api_get_self());
  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'));
  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'));
  443. $form->addElement(
  444. 'checkbox',
  445. 'check_unique_email',
  446. '',
  447. get_lang('CheckUniqueEmail')
  448. );
  449. $form->addButtonImport(get_lang('Import'));
  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;UTF-8&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();