user_import.php 17 KB

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