user_import.php 14 KB

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