user_import.php 16 KB

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