user_import.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. * @todo Add some langvars to DLTT
  6. * @package chamilo.admin
  7. */
  8. /**
  9. * Validate the imported data.
  10. */
  11. $language_file = array ('admin', 'registration');
  12. $cidReset = true;
  13. require '../inc/global.inc.php';
  14. require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
  15. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  16. require_once api_get_path(LIBRARY_PATH).'classmanager.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. function validate_data($users) {
  21. global $defined_auth_sources;
  22. $errors = array();
  23. $usernames = array();
  24. // 1. Check if mandatory fields are set.
  25. $mandatory_fields = array('LastName', 'FirstName');
  26. if (api_get_setting('registration', 'email') == 'true') {
  27. $mandatory_fields[] = 'Email';
  28. }
  29. foreach ($users as $index => $user) {
  30. foreach ($mandatory_fields as $field) {
  31. if (empty($user[$field])) {
  32. $user['error'] = get_lang($field.'Mandatory');
  33. $errors[] = $user;
  34. }
  35. }
  36. // 2. Check username, first, check whether it is empty.
  37. if (!UserManager::is_username_empty($user['UserName'])) {
  38. // 2.1. Check whether username is too long.
  39. if (UserManager::is_username_too_long($user['UserName'])) {
  40. $user['error'] = get_lang('UserNameTooLong');
  41. $errors[] = $user;
  42. }
  43. // 2.2. Check whether the username was used twice in import file.
  44. if (isset($usernames[$user['UserName']])) {
  45. $user['error'] = get_lang('UserNameUsedTwice');
  46. $errors[] = $user;
  47. }
  48. $usernames[$user['UserName']] = 1;
  49. // 2.3. Check whether username is allready occupied.
  50. if (!UserManager::is_username_available($user['UserName'])) {
  51. $user['error'] = get_lang('UserNameNotAvailable');
  52. $errors[] = $user;
  53. }
  54. }
  55. // 3. Check status.
  56. if (isset($user['Status']) && !api_status_exists($user['Status'])) {
  57. $user['error'] = get_lang('WrongStatus');
  58. $errors[] = $user;
  59. }
  60. // 4. Check classname
  61. if (!empty($user['ClassName'])) {
  62. if (!ClassManager :: class_name_exists($user['ClassName'])) {
  63. $user['error'] = get_lang('ClassNameNotAvailable');
  64. $errors[] = $user;
  65. }
  66. }
  67. // 5. Check authentication source
  68. if (!empty($user['AuthSource'])) {
  69. if (!in_array($user['AuthSource'], $defined_auth_sources)) {
  70. $user['error'] = get_lang('AuthSourceNotAvailable');
  71. $errors[] = $user;
  72. }
  73. }
  74. }
  75. return $errors;
  76. }
  77. /**
  78. * Add missing user-information (which isn't required, like password, username etc).
  79. */
  80. function complete_missing_data($user) {
  81. global $purification_option_for_usernames;
  82. // 1. Create a username if necessary.
  83. if (UserManager::is_username_empty($user['UserName'])) {
  84. $user['UserName'] = UserManager::create_unique_username($user['FirstName'], $user['LastName']);
  85. } else {
  86. $user['UserName'] = UserManager::purify_username($user['UserName'], $purification_option_for_usernames);
  87. }
  88. // 2. Generate a password if necessary.
  89. if (empty($user['Password'])) {
  90. $user['Password'] = api_generate_password();
  91. }
  92. // 3. Set status if not allready set.
  93. if (empty($user['Status'])) {
  94. $user['Status'] = 'user';
  95. }
  96. // 4. Set authsource if not allready set.
  97. if (empty($user['AuthSource'])) {
  98. $user['AuthSource'] = PLATFORM_AUTH_SOURCE;
  99. }
  100. return $user;
  101. }
  102. /**
  103. * Save the imported data
  104. * @param array List of users
  105. * @return void
  106. * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in
  107. */
  108. function save_data($users)
  109. {
  110. global $inserted_in_course;
  111. // Not all scripts declare the $inserted_in_course array (although they should).
  112. if (!isset($inserted_in_course)) {
  113. $inserted_in_course = array();
  114. }
  115. require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
  116. $send_mail = $_POST['sendMail'] ? true : false;
  117. if (is_array($users)) {
  118. foreach ($users as $user) {
  119. $user = complete_missing_data($user);
  120. $user['Status'] = api_status_key($user['Status']);
  121. $user_id = UserManager :: create_user(
  122. $user['FirstName'],
  123. $user['LastName'],
  124. $user['Status'],
  125. $user['Email'],
  126. $user['UserName'],
  127. $user['Password'],
  128. $user['OfficialCode'],
  129. $user['language'],
  130. $user['PhoneNumber'],
  131. '',
  132. $user['AuthSource'],
  133. null,
  134. 1,
  135. 0,
  136. null,
  137. null,
  138. $send_mail
  139. );
  140. if (!is_array($user['Courses']) && !empty($user['Courses'])) {
  141. $user['Courses'] = array($user['Courses']);
  142. }
  143. if (is_array($user['Courses'])) {
  144. foreach ($user['Courses'] as $course) {
  145. if (CourseManager::course_exists($course)) {
  146. CourseManager::subscribe_user($user_id, $course, $user['Status']);
  147. $course_info = CourseManager::get_course_information($course);
  148. $inserted_in_course[$course] = $course_info['title'];
  149. }
  150. if (CourseManager :: course_exists($course, true)) {
  151. // Also subscribe to virtual courses through check on visual code.
  152. $list = CourseManager :: get_courses_info_from_visual_code($course);
  153. foreach ($list as $vcourse) {
  154. if ($vcourse['code'] == $course) {
  155. // Ignore, this has already been inserted.
  156. } else {
  157. CourseManager :: subscribe_user($user_id, $vcourse['code'], $user['Status']);
  158. $inserted_in_course[$vcourse['code']] = $vcourse['title'];
  159. }
  160. }
  161. }
  162. }
  163. }
  164. if (!empty($user['ClassName'])) {
  165. $class_id = ClassManager :: get_class_id($user['ClassName']);
  166. ClassManager :: add_user($user_id, $class_id);
  167. }
  168. // Saving extra fields.
  169. global $extra_fields;
  170. // We are sure that the extra field exists.
  171. foreach ($extra_fields as $extras) {
  172. if (isset($user[$extras[1]])) {
  173. $key = $extras[1];
  174. $value = $user[$extras[1]];
  175. UserManager::update_extra_field_value($user_id, $key, $value);
  176. }
  177. }
  178. }
  179. }
  180. }
  181. /**
  182. * Read the CSV-file
  183. * @param string $file Path to the CSV-file
  184. * @return array All userinformation read from the file
  185. */
  186. function parse_csv_data($file) {
  187. $users = Import :: csv_to_array($file);
  188. foreach ($users as $index => $user) {
  189. if (isset ($user['Courses'])) {
  190. $user['Courses'] = explode('|', trim($user['Courses']));
  191. }
  192. $users[$index] = $user;
  193. }
  194. return $users;
  195. }
  196. /**
  197. * XML-parser: handle start of element
  198. */
  199. function element_start($parser, $data) {
  200. $data = api_utf8_decode($data);
  201. global $user;
  202. global $current_tag;
  203. switch ($data) {
  204. case 'Contact' :
  205. $user = array ();
  206. break;
  207. default :
  208. $current_tag = $data;
  209. }
  210. }
  211. /**
  212. * XML-parser: handle end of element
  213. */
  214. function element_end($parser, $data) {
  215. $data = api_utf8_decode($data);
  216. global $user;
  217. global $users;
  218. global $current_value;
  219. switch ($data) {
  220. case 'Contact' :
  221. if ($user['Status'] == '5') {
  222. $user['Status'] = STUDENT;
  223. }
  224. if ($user['Status'] == '1') {
  225. $user['Status'] = COURSEMANAGER;
  226. }
  227. $users[] = $user;
  228. break;
  229. default :
  230. $user[$data] = $current_value;
  231. break;
  232. }
  233. }
  234. /**
  235. * XML-parser: handle character data
  236. */
  237. function character_data($parser, $data) {
  238. $data = trim(api_utf8_decode($data));
  239. global $current_value;
  240. $current_value = $data;
  241. }
  242. /**
  243. * Read the XML-file
  244. * @param string $file Path to the XML-file
  245. * @return array All userinformation read from the file
  246. */
  247. function parse_xml_data($file) {
  248. global $current_tag;
  249. global $current_value;
  250. global $user;
  251. global $users;
  252. $users = array();
  253. $parser = xml_parser_create('UTF-8');
  254. xml_set_element_handler($parser, 'element_start', 'element_end');
  255. xml_set_character_data_handler($parser, 'character_data');
  256. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
  257. xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
  258. xml_parser_free($parser);
  259. return $users;
  260. }
  261. $this_section = SECTION_PLATFORM_ADMIN;
  262. api_protect_admin_script(true, null, 'login');
  263. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  264. if (is_array($extAuthSource)) {
  265. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  266. }
  267. $tool_name = get_lang('ImportUserListXMLCSV');
  268. $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
  269. set_time_limit(0);
  270. $extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
  271. $user_id_error = array();
  272. $error_message = '';
  273. if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
  274. $file_type = $_POST['file_type'];
  275. Security::clear_token();
  276. $tok = Security::get_token();
  277. $allowed_file_mimetype = array('csv', 'xml');
  278. $error_kind_file = false;
  279. $uploadInfo = pathinfo($_FILES['import_file']['name']);
  280. $ext_import_file = $uploadInfo['extension'];
  281. if (in_array($ext_import_file, $allowed_file_mimetype)) {
  282. if (strcmp($file_type, 'csv') === 0 && $ext_import_file == $allowed_file_mimetype[0]) {
  283. $users = parse_csv_data($_FILES['import_file']['tmp_name']);
  284. $errors = validate_data($users);
  285. $error_kind_file = false;
  286. } elseif (strcmp($file_type, 'xml') === 0 && $ext_import_file == $allowed_file_mimetype[1]) {
  287. $users = parse_xml_data($_FILES['import_file']['tmp_name']);
  288. $errors = validate_data($users);
  289. $error_kind_file = false;
  290. } else {
  291. $error_kind_file = true;
  292. }
  293. } else {
  294. $error_kind_file = true;
  295. }
  296. // List user id with error.
  297. $users_to_insert = $user_id_error = array();
  298. if (is_array($errors)) {
  299. foreach ($errors as $my_errors) {
  300. $user_id_error[] = $my_errors['UserName'];
  301. }
  302. }
  303. if (is_array($users)) {
  304. foreach ($users as $my_user) {
  305. if (!in_array($my_user['UserName'], $user_id_error)) {
  306. $users_to_insert[] = $my_user;
  307. }
  308. }
  309. }
  310. $inserted_in_course = array();
  311. if (strcmp($file_type, 'csv') === 0) {
  312. save_data($users_to_insert);
  313. } elseif (strcmp($file_type, 'xml') === 0) {
  314. save_data($users_to_insert);
  315. } else {
  316. $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
  317. }
  318. if (count($errors) > 0) {
  319. $see_message_import = get_lang('FileImportedJustUsersThatAreNotRegistered');
  320. } else {
  321. $see_message_import = get_lang('FileImported');
  322. }
  323. if (count($errors) != 0) {
  324. $warning_message = '<ul>';
  325. foreach ($errors as $index => $error_user) {
  326. $warning_message .= '<li><b>'.$error_user['error'].'</b>: ';
  327. $warning_message .= '<strong>'.$error_user['UserName'].'</strong>&nbsp;('.api_get_person_name($error_user['FirstName'], $error_user['LastName']).')';
  328. $warning_message .= '</li>';
  329. }
  330. $warning_message .= '</ul>';
  331. }
  332. // if the warning message is too long then we display the warning message trough a session
  333. $_SESSION['session_message_import_users'] = $warning_message;
  334. $warning_message = 'session_message';
  335. if ($error_kind_file) {
  336. $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
  337. } else {
  338. 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);
  339. exit;
  340. }
  341. }
  342. Display :: display_header($tool_name);
  343. if (!empty($error_message)) {
  344. Display::display_error_message($error_message);
  345. }
  346. $form = new FormValidator('user_import','post','user_import.php');
  347. $form->addElement('header', '', $tool_name);
  348. $form->addElement('hidden', 'formSent');
  349. $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
  350. $group = array();
  351. $group[] = $form->createElement('radio', 'file_type', '', 'CSV (<a href="example.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)', 'csv');
  352. $group[] = $form->createElement('radio', 'file_type', null, 'XML (<a href="example.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)', 'xml');
  353. $form->addGroup($group, '', get_lang('FileType'), '<br/>');
  354. $group = array();
  355. $group[] = $form->createElement('radio', 'sendMail', '', get_lang('Yes'), 1);
  356. $group[] = $form->createElement('radio', 'sendMail', null, get_lang('No'), 0);
  357. $form->addGroup($group, '', get_lang('SendMailToUsers'), '<br/>');
  358. $form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
  359. $defaults['formSent'] = 1;
  360. $defaults['sendMail'] = 0;
  361. $defaults['file_type'] = 'csv';
  362. $form->setDefaults($defaults);
  363. $form->display();
  364. $list = array();
  365. $list_reponse = array();
  366. $result_xml = '';
  367. $i = 0;
  368. $count_fields = count($extra_fields);
  369. if ($count_fields > 0) {
  370. foreach ($extra_fields as $extra) {
  371. $list[] = $extra[1];
  372. $list_reponse[] = 'xxx';
  373. $spaces = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  374. $result_xml .= $spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';
  375. if ($i != $count_fields - 1) {
  376. $result_xml .= '<br/>';
  377. }
  378. $i++;
  379. }
  380. }
  381. ?>
  382. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  383. <blockquote>
  384. <pre>
  385. <b>LastName</b>;<b>FirstName</b>;<b>Email</b>;UserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;<span style="color:red;"><?php if (count($list) > 0) echo implode(';', $list).';'; ?></span>Courses;
  386. <b>xxx</b>;<b>xxx</b>;<b>xxx</b>;xxx;xxx;<?php echo implode('/', $defined_auth_sources); ?>;xxx;xxx;user/teacher/drh;<span style="color:red;"><?php if (count($list_reponse) > 0) echo implode(';', $list_reponse).';'; ?></span>xxx1|xxx2|xxx3;<br />
  387. </pre>
  388. </blockquote>
  389. <p><?php echo get_lang('XMLMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  390. <blockquote>
  391. <pre>
  392. &lt;?xml version=&quot;1.0&quot; encoding=&quot;<?php echo api_refine_encoding_id(api_get_system_encoding()); ?>&quot;?&gt;
  393. &lt;Contacts&gt;
  394. &lt;Contact&gt;
  395. <b>&lt;LastName&gt;xxx&lt;/LastName&gt;</b>
  396. <b>&lt;FirstName&gt;xxx&lt;/FirstName&gt;</b>
  397. &lt;UserName&gt;xxx&lt;/UserName&gt;
  398. &lt;Password&gt;xxx&lt;/Password&gt;
  399. &lt;AuthSource&gt;<?php echo implode('/', $defined_auth_sources); ?>&lt;/AuthSource&gt;
  400. <b>&lt;Email&gt;xxx&lt;/Email&gt;</b>
  401. &lt;OfficialCode&gt;xxx&lt;/OfficialCode&gt;
  402. &lt;PhoneNumber&gt;xxx&lt;/PhoneNumber&gt;
  403. &lt;Status&gt;user/teacher/drh<?php if ($result_xml != '') { echo '<br /><span style="color:red;">', $result_xml; echo '</span>'; } ?>&lt;/Status&gt;
  404. &lt;Courses&gt;xxx1|xxx2|xxx3&lt;/Courses&gt;
  405. &lt;/Contact&gt;
  406. &lt;/Contacts&gt;
  407. </pre>
  408. </blockquote>
  409. <?php
  410. Display :: display_footer();