PageRenderTime 26ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/main/admin/user_import.php

https://bitbucket.org/hanutimes/hanutimes
PHP | 438 lines | 330 code | 40 blank | 68 comment | 67 complexity | 0e36e2396e2e9bd8e5ad45441ccf7c9a MD5 | raw file
  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. */
  175. function element_start($parser, $data) {
  176. $data = api_utf8_decode($data);
  177. global $user;
  178. global $current_tag;
  179. switch ($data) {
  180. case 'Contact' :
  181. $user = array ();
  182. break;
  183. default :
  184. $current_tag = $data;
  185. }
  186. }
  187. /**
  188. * XML-parser: handle end of element
  189. */
  190. function element_end($parser, $data) {
  191. $data = api_utf8_decode($data);
  192. global $user;
  193. global $users;
  194. global $current_value;
  195. switch ($data) {
  196. case 'Contact' :
  197. if ($user['Status'] == '5') {
  198. $user['Status'] = STUDENT;
  199. }
  200. if ($user['Status'] == '1') {
  201. $user['Status'] = COURSEMANAGER;
  202. }
  203. $users[] = $user;
  204. break;
  205. default :
  206. $user[$data] = $current_value;
  207. break;
  208. }
  209. }
  210. /**
  211. * XML-parser: handle character data
  212. */
  213. function character_data($parser, $data) {
  214. $data = trim(api_utf8_decode($data));
  215. global $current_value;
  216. $current_value = $data;
  217. }
  218. /**
  219. * Read the XML-file
  220. * @param string $file Path to the XML-file
  221. * @return array All userinformation read from the file
  222. */
  223. function parse_xml_data($file) {
  224. global $current_tag;
  225. global $current_value;
  226. global $user;
  227. global $users;
  228. $users = array();
  229. $parser = xml_parser_create('UTF-8');
  230. xml_set_element_handler($parser, 'element_start', 'element_end');
  231. xml_set_character_data_handler($parser, 'character_data');
  232. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
  233. xml_parse($parser, Text::api_utf8_encode_xml(file_get_contents($file)));
  234. xml_parser_free($parser);
  235. return $users;
  236. }
  237. $this_section = SECTION_PLATFORM_ADMIN;
  238. api_protect_admin_script(true);
  239. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  240. if (is_array($extAuthSource)) {
  241. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  242. }
  243. $tool_name = get_lang('ImportUserListXMLCSV');
  244. $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
  245. set_time_limit(0);
  246. $extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
  247. $user_id_error = array();
  248. $error_message = '';
  249. if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
  250. $file_type = $_POST['file_type'];
  251. Security::clear_token();
  252. $tok = Security::get_token();
  253. $allowed_file_mimetype = array('csv','xml');
  254. $error_kind_file = false;
  255. $ext_import_file = substr($_FILES['import_file']['name'],(strrpos($_FILES['import_file']['name'],'.')+1));
  256. if (in_array($ext_import_file,$allowed_file_mimetype)) {
  257. if (strcmp($file_type, 'csv') === 0 && $ext_import_file == $allowed_file_mimetype[0]) {
  258. $users = parse_csv_data($_FILES['import_file']['tmp_name']);
  259. $errors = validate_data($users);
  260. $error_kind_file = false;
  261. } elseif (strcmp($file_type, 'xml') === 0 && $ext_import_file == $allowed_file_mimetype[1]) {
  262. $users = parse_xml_data($_FILES['import_file']['tmp_name']);
  263. $errors = validate_data($users);
  264. $error_kind_file = false;
  265. } else {
  266. $error_kind_file = true;
  267. }
  268. } else {
  269. $error_kind_file = true;
  270. }
  271. // List user id whith error.
  272. $users_to_insert = $user_id_error = array();
  273. if (is_array($errors)) {
  274. foreach ($errors as $my_errors) {
  275. $user_id_error[] = $my_errors['UserName'];
  276. }
  277. }
  278. if (is_array($users)) {
  279. foreach ($users as $my_user) {
  280. if (!in_array($my_user['UserName'], $user_id_error)) {
  281. $users_to_insert[] = $my_user;
  282. }
  283. }
  284. }
  285. $inserted_in_course = array();
  286. if (strcmp($file_type, 'csv') === 0) {
  287. save_data($users_to_insert);
  288. } elseif (strcmp($file_type, 'xml') === 0) {
  289. save_data($users_to_insert);
  290. } else {
  291. $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
  292. }
  293. if (count($errors) > 0) {
  294. $see_message_import = get_lang('FileImportedJustUsersThatAreNotRegistered');
  295. } else {
  296. $see_message_import = get_lang('FileImported');
  297. }
  298. /*
  299. $msg2 = '';
  300. if (count($inserted_in_course) > 1) {
  301. $msg2 .= '<br>'.get_lang('UsersSubscribedToSeveralCoursesBecauseOfVirtualCourses').':';
  302. foreach ($inserted_in_course as $course) {
  303. $msg2 .= ' '.$course.',';
  304. }
  305. $msg2 = substr($msg2, 0, -1);
  306. $msg2 .= '</br>';
  307. }
  308. */
  309. if (count($errors) != 0) {
  310. $warning_message = '<ul>';
  311. foreach ($errors as $index => $error_user) {
  312. $warning_message .= '<li><b>'.$error_user['error'].'</b>: ';
  313. $warning_message .= '<strong>'.$error_user['UserName'].'</strong>&nbsp;('.api_get_person_name($error_user['FirstName'], $error_user['LastName']).')';
  314. $warning_message .= '</li>';
  315. }
  316. $warning_message .= '</ul>';
  317. }
  318. // if the warning message is too long then we display the warning message trough a session
  319. if (api_strlen($warning_message) > 150) {
  320. $_SESSION['session_message_import_users'] = $warning_message;
  321. $warning_message = 'session_message';
  322. }
  323. if ($error_kind_file) {
  324. $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
  325. } else {
  326. 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);
  327. exit;
  328. }
  329. }
  330. Display :: display_header($tool_name);
  331. if (!empty($error_message)) {
  332. Display::display_error_message($error_message);
  333. }
  334. $form = new FormValidator('user_import','post','user_import.php');
  335. $form->addElement('header', '', $tool_name);
  336. $form->addElement('hidden', 'formSent');
  337. $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
  338. $group = array();
  339. $group[] = $form->createElement('radio', 'file_type', '', 'CSV (<a href="example.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)', 'csv');
  340. $group[] = $form->createElement('radio', 'file_type', null, 'XML (<a href="example.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)', 'xml');
  341. $form->addGroup($group, '', get_lang('FileType'), '<br/>');
  342. $group = array();
  343. $group[] = $form->createElement('radio', 'sendMail', '', get_lang('Yes'), 1);
  344. $group[] = $form->createElement('radio', 'sendMail', null, get_lang('No'), 0);
  345. $form->addGroup($group, '', get_lang('SendMailToUsers'), '<br/>');
  346. $form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
  347. $defaults['formSent'] = 1;
  348. $defaults['sendMail'] = 0;
  349. $defaults['file_type'] = 'csv';
  350. $form->setDefaults($defaults);
  351. $form->display();
  352. $list = array();
  353. $list_reponse = array();
  354. $result_xml = '';
  355. $i = 0;
  356. $count_fields = count($extra_fields);
  357. if ($count_fields > 0) {
  358. foreach ($extra_fields as $extra) {
  359. $list[] = $extra[1];
  360. $list_reponse[] = 'xxx';
  361. $spaces = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  362. $result_xml .= $spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';
  363. if ($i != $count_fields - 1) {
  364. $result_xml .= '<br/>';
  365. }
  366. $i++;
  367. }
  368. }
  369. ?>
  370. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  371. <blockquote>
  372. <pre>
  373. <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;
  374. <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 />
  375. </pre>
  376. </blockquote>
  377. <p><?php echo get_lang('XMLMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  378. <blockquote>
  379. <pre>
  380. &lt;?xml version=&quot;1.0&quot; encoding=&quot;<?php echo api_refine_encoding_id(api_get_system_encoding()); ?>&quot;?&gt;
  381. &lt;Contacts&gt;
  382. &lt;Contact&gt;
  383. <b>&lt;LastName&gt;xxx&lt;/LastName&gt;</b>
  384. <b>&lt;FirstName&gt;xxx&lt;/FirstName&gt;</b>
  385. &lt;UserName&gt;xxx&lt;/UserName&gt;
  386. &lt;Password&gt;xxx&lt;/Password&gt;
  387. &lt;AuthSource&gt;<?php echo implode('/', $defined_auth_sources); ?>&lt;/AuthSource&gt;
  388. <b>&lt;Email&gt;xxx&lt;/Email&gt;</b>
  389. &lt;OfficialCode&gt;xxx&lt;/OfficialCode&gt;
  390. &lt;PhoneNumber&gt;xxx&lt;/PhoneNumber&gt;
  391. &lt;Status&gt;user/teacher/drh<?php if ($result_xml != '') { echo '<br /><font style="color:red;">', $result_xml; echo '</font>'; } ?>&lt;/Status&gt;
  392. &lt;Courses&gt;xxx1|xxx2|xxx3&lt;/Courses&gt;
  393. &lt;/Contact&gt;
  394. &lt;/Contacts&gt;
  395. </pre>
  396. </blockquote>
  397. <?php
  398. Display :: display_footer();