user_import.php 12 KB

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