user_import.php 16 KB

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