user_import.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. <?php // $Id: user_import.php 14792 2008-04-08 20:57:53Z yannoo $
  2. /*
  3. ==============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2004-2008 Dokeos SPRL
  6. Copyright (c) 2003 Ghent University (UGent)
  7. Copyright (c) 2001 Universite catholique de Louvain (UCL)
  8. Copyright (c) Olivier Brouckaert
  9. Copyright (c) 2005 Bart Mollet <bart.mollet@hogent.be>
  10. For a full list of contributors, see "credits.txt".
  11. The full license can be read in "license.txt".
  12. This program is free software; you can redistribute it and/or
  13. modify it under the terms of the GNU General Public License
  14. as published by the Free Software Foundation; either version 2
  15. of the License, or (at your option) any later version.
  16. See the GNU General Public License for more details.
  17. Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
  18. ==============================================================================
  19. */
  20. /**
  21. ==============================================================================
  22. * This tool allows platform admins to add users by uploading a CSV or XML file
  23. * @todo Add some langvars to DLTT
  24. * @package dokeos.admin
  25. ==============================================================================
  26. */
  27. /**
  28. * validate the imported data
  29. */
  30. function validate_data($users)
  31. {
  32. global $defined_auth_sources;
  33. $errors = array ();
  34. $usernames = array ();
  35. foreach ($users as $index => $user)
  36. {
  37. //1. check if mandatory fields are set
  38. $mandatory_fields = array ('LastName', 'FirstName');
  39. if (api_get_setting('registration', 'email') == 'true')
  40. {
  41. $mandatory_fields[] = 'Email';
  42. }
  43. foreach ($mandatory_fields as $key => $field)
  44. {
  45. if (!isset ($user[$field]) || strlen($user[$field]) == 0)
  46. {
  47. $user['error'] = get_lang($field.'Mandatory');
  48. $errors[] = $user;
  49. }
  50. }
  51. //2. check username
  52. if (isset ($user['UserName']) && strlen($user['UserName']) != 0)
  53. {
  54. //2.1. check if no username was used twice in import file
  55. if (isset ($usernames[$user['UserName']]))
  56. {
  57. $user['error'] = get_lang('UserNameUsedTwice');
  58. $errors[] = $user;
  59. }
  60. $usernames[$user['UserName']] = 1;
  61. //2.2. check if username isn't allready in use in database
  62. if (!UserManager :: is_username_available($user['UserName']))
  63. {
  64. $user['error'] = get_lang('UserNameNotAvailable');
  65. $errors[] = $user;
  66. }
  67. //2.3. check if username isn't longer than the 20 allowed characters
  68. if (strlen($user['UserName']) > 20)
  69. {
  70. $user['error'] = get_lang('UserNameTooLong');
  71. $errors[] = $user;
  72. }
  73. }
  74. //3. check status
  75. if (isset ($user['Status']) && !api_status_exists($user['Status']))
  76. {
  77. $user['error'] = get_lang('WrongStatus');
  78. $errors[] = $user;
  79. }
  80. //4. Check classname
  81. if (isset ($user['ClassName']) && strlen($user['ClassName']) != 0)
  82. {
  83. if (!ClassManager :: class_name_exists($user['ClassName']))
  84. {
  85. $user['error'] = get_lang('ClassNameNotAvailable');
  86. $errors[] = $user;
  87. }
  88. }
  89. //5. Check authentication source
  90. if (isset ($user['AuthSource']) && strlen($user['AuthSource']) != 0)
  91. {
  92. if (!in_array($user['AuthSource'], $defined_auth_sources))
  93. {
  94. $user['error'] = get_lang('AuthSourceNotAvailable');
  95. $errors[] = $user;
  96. }
  97. }
  98. }
  99. return $errors;
  100. }
  101. /**
  102. * Add missing user-information (which isn't required, like password, username
  103. * etc)
  104. */
  105. function complete_missing_data($user)
  106. {
  107. //1. Create a username if necessary
  108. if (!isset ($user['UserName']) || strlen($user['UserName']) == 0)
  109. {
  110. $username = strtolower(ereg_replace('[^a-zA-Z]', '', substr($user['FirstName'], 0, 3).' '.substr($user['LastName'], 0, 4)));
  111. if (!UserManager :: is_username_available($username))
  112. {
  113. $i = 0;
  114. $temp_username = $username.$i;
  115. while (!UserManager :: is_username_available($temp_username))
  116. {
  117. $temp_username = $username.++$i;
  118. }
  119. $username = $temp_username;
  120. }
  121. $user['UserName'] = $username;
  122. }
  123. //2. generate a password if necessary
  124. if (!isset ($user['Password']) || strlen($user['Password']) == 0)
  125. {
  126. $user['Password'] = api_generate_password();
  127. }
  128. //3. set status if not allready set
  129. if (!isset ($user['Status']) || strlen($user['Status']) == 0)
  130. {
  131. $user['Status'] = 'user';
  132. }
  133. //4. set authsource if not allready set
  134. if (!isset ($user['AuthSource']) || strlen($user['AuthSource']) == 0)
  135. {
  136. $user['AuthSource'] = PLATFORM_AUTH_SOURCE;
  137. }
  138. return $user;
  139. }
  140. /**
  141. * Save the imported data
  142. */
  143. function save_data($users)
  144. {
  145. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  146. $sendMail = $_POST['sendMail'] ? 1 : 0;
  147. foreach ($users as $index => $user)
  148. {
  149. $user = complete_missing_data($user);
  150. $user['Status'] = api_status_key($user['Status']);
  151. $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']);
  152. foreach ($user['Courses'] as $index => $course)
  153. {
  154. if(CourseManager :: course_exists($course))
  155. CourseManager :: subscribe_user($user_id, $course,$user['Status']);
  156. }
  157. if (strlen($user['ClassName']) > 0)
  158. {
  159. $class_id = ClassManager :: get_class_id($user['ClassName']);
  160. ClassManager :: add_user($user_id, $class_id);
  161. }
  162. if ($sendMail)
  163. {
  164. $emailto = '"'.$user['FirstName'].' '.$user['LastName'].'" <'.$user['Email'].'>';
  165. $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('YourReg').' '.api_get_setting('siteName');
  166. $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')."";
  167. $emailheaders = 'From: '.api_get_setting('administratorName').' '.api_get_setting('administratorSurname').' <'.api_get_setting('emailAdministrator').">\n";
  168. $emailheaders .= 'Reply-To: '.api_get_setting('emailAdministrator');
  169. @ api_send_mail($emailto, $emailsubject, $emailbody, $emailheaders);
  170. }
  171. }
  172. }
  173. /**
  174. * Read the CSV-file
  175. * @param string $file Path to the CSV-file
  176. * @return array All userinformation read from the file
  177. */
  178. function parse_csv_data($file)
  179. {
  180. $users = Import :: csv_to_array($file);
  181. foreach ($users as $index => $user)
  182. {
  183. if (isset ($user['Courses']))
  184. {
  185. $user['Courses'] = explode('|', trim($user['Courses']));
  186. }
  187. $users[$index] = $user;
  188. }
  189. return $users;
  190. }
  191. /**
  192. * XML-parser: handle start of element
  193. */
  194. function element_start($parser, $data)
  195. {
  196. global $user;
  197. global $current_tag;
  198. switch ($data)
  199. {
  200. case 'Contact' :
  201. $user = array ();
  202. break;
  203. default :
  204. $current_tag = $data;
  205. }
  206. }
  207. /**
  208. * XML-parser: handle end of element
  209. */
  210. function element_end($parser, $data)
  211. {
  212. global $user;
  213. global $users;
  214. global $current_value;
  215. switch ($data)
  216. {
  217. case 'Contact' :
  218. if ($user['Status'] == '5')
  219. {
  220. $user['Status'] = STUDENT;
  221. }
  222. if ($user['Status'] == '1')
  223. {
  224. $user['Status'] = COURSEMANAGER;
  225. }
  226. $users[] = $user;
  227. break;
  228. default :
  229. $user[$data] = $current_value;
  230. break;
  231. }
  232. }
  233. /**
  234. * XML-parser: handle character data
  235. */
  236. function character_data($parser, $data)
  237. {
  238. global $current_value;
  239. $current_value = $data;
  240. }
  241. /**
  242. * Read the XML-file
  243. * @param string $file Path to the XML-file
  244. * @return array All userinformation read from the file
  245. */
  246. function parse_xml_data($file)
  247. {
  248. global $current_tag;
  249. global $current_value;
  250. global $user;
  251. global $users;
  252. $users = array ();
  253. $parser = xml_parser_create();
  254. xml_set_element_handler($parser, 'element_start', 'element_end');
  255. xml_set_character_data_handler($parser, "character_data");
  256. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
  257. xml_parse($parser, file_get_contents($file));
  258. xml_parser_free($parser);
  259. return $users;
  260. }
  261. // name of the language file that needs to be included
  262. $language_file = array ('admin', 'registration');
  263. $cidReset = true;
  264. include ('../inc/global.inc.php');
  265. $this_section = SECTION_PLATFORM_ADMIN;
  266. api_protect_admin_script();
  267. require_once (api_get_path(LIBRARY_PATH).'fileManage.lib.php');
  268. require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
  269. require_once (api_get_path(LIBRARY_PATH).'classmanager.lib.php');
  270. require_once (api_get_path(LIBRARY_PATH).'import.lib.php');
  271. require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
  272. $formSent = 0;
  273. $errorMsg = '';
  274. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  275. if (is_array($extAuthSource))
  276. {
  277. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  278. }
  279. $tool_name = get_lang('ImportUserListXMLCSV');
  280. $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
  281. set_time_limit(0);
  282. if ($_POST['formSent'] AND $_FILES['import_file']['size'] !== 0)
  283. {
  284. $file_type = $_POST['file_type'];
  285. if ($file_type == 'csv')
  286. {
  287. $users = parse_csv_data($_FILES['import_file']['tmp_name']);
  288. }
  289. else
  290. {
  291. $users = parse_xml_data($_FILES['import_file']['tmp_name']);
  292. }
  293. $errors = validate_data($users);
  294. if (count($errors) == 0)
  295. {
  296. save_data($users);
  297. header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('FileImported')));
  298. exit ();
  299. }
  300. }
  301. Display :: display_header($tool_name);
  302. //api_display_tool_title($tool_name);
  303. if($_FILES['import_file']['size'] == 0 AND $_POST)
  304. {
  305. Display::display_error_message(get_lang('ThisFieldIsRequired'));
  306. }
  307. if (count($errors) != 0)
  308. {
  309. $error_message = '<ul>';
  310. foreach ($errors as $index => $error_user)
  311. {
  312. $error_message .= '<li><b>'.$error_user['error'].'</b>: ';
  313. $error_message .= $error_user['FirstName'].' '.$error_user['LastName'];
  314. $error_message .= '</li>';
  315. }
  316. $error_message .= '</ul>';
  317. Display :: display_error_message($error_message, false);
  318. }
  319. $form = new FormValidator('user_import');
  320. $form->addElement('hidden', 'formSent');
  321. $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
  322. $form->addRule('import_file', get_lang('ThisFieldIsRequired'), 'required');
  323. $allowed_file_types = array ('xml', 'csv');
  324. $form->addRule('file', get_lang('InvalidExtension').' ('.implode(',', $allowed_file_types).')', 'filetype', $allowed_file_types);
  325. $form->addElement('radio', 'file_type', get_lang('FileType'), 'XML (<a href="exemple.xml" target="_blank">'.get_lang('ExampleXMLFile').'</a>)', 'xml');
  326. $form->addElement('radio', 'file_type', null, 'CSV (<a href="exemple.csv" target="_blank">'.get_lang('ExampleCSVFile').'</a>)', 'csv');
  327. $form->addElement('radio', 'sendMail', get_lang('SendMailToUsers'), get_lang('Yes'), 1);
  328. $form->addElement('radio', 'sendMail', null, get_lang('No'), 0);
  329. $form->addElement('submit', 'submit', get_lang('Ok'));
  330. $defaults['formSent'] = 1;
  331. $defaults['file_type'] = 'xml';
  332. $form->setDefaults($defaults);
  333. $form->display();
  334. ?>
  335. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  336. <blockquote>
  337. <pre>
  338. <b>LastName</b>;<b>FirstName</b>;<b>Email</b>;UserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;Courses;ClassName
  339. <b>xxx</b>;<b>xxx</b>;<b>xxx</b>;xxx;xxx;<?php echo implode('/',$defined_auth_sources); ?>;xxx;xxx;user/teacher/drh;xxx1|xxx2|xxx3;xxx
  340. </pre>
  341. </blockquote>
  342. <p><?php echo get_lang('XMLMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  343. <blockquote>
  344. <pre>
  345. &lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
  346. &lt;Contacts&gt;
  347. &lt;Contact&gt;
  348. <b>&lt;LastName&gt;xxx&lt;/LastName&gt;</b>
  349. <b>&lt;FirstName&gt;xxx&lt;/FirstName&gt;</b>
  350. &lt;UserName&gt;xxx&lt;/UserName&gt;
  351. &lt;Password&gt;xxx&lt;/Password&gt;
  352. &lt;AuthSource&gt;<?php echo implode('/',$defined_auth_sources); ?>&lt;/AuthSource&gt;
  353. <b>&lt;Email&gt;xxx&lt;/Email&gt;</b>
  354. &lt;OfficialCode&gt;xxx&lt;/OfficialCode&gt;
  355. &lt;PhoneNumber&gt;xxx&lt;/PhoneNumber&gt;
  356. &lt;Status&gt;user/teacher/drh&lt;/Status&gt;
  357. &lt;Courses&gt;xxx1|xxx2|xxx3&lt;/Courses&gt;
  358. &lt;ClassName&gt;class 1&lt;/ClassName&gt;
  359. &lt;/Contact&gt;
  360. &lt;/Contacts&gt;
  361. </pre>
  362. </blockquote>
  363. <?php
  364. /*
  365. ==============================================================================
  366. FOOTER
  367. ==============================================================================
  368. */
  369. Display :: display_footer();
  370. ?>