user_import.php 15 KB

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