user_import.php 16 KB

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