user_update_import.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This tool allows platform admins to add users by uploading a CSV or XML file
  5. * @package chamilo.admin
  6. */
  7. /**
  8. * Validate the imported data.
  9. */
  10. $language_file = array ('admin', 'registration');
  11. $cidReset = true;
  12. require '../inc/global.inc.php';
  13. require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
  14. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  15. require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
  16. require_once api_get_path(LIBRARY_PATH).'usergroup.lib.php';
  17. require_once api_get_path(LIBRARY_PATH).'import.lib.php';
  18. // Set this option to true to enforce strict purification for usenames.
  19. $purification_option_for_usernames = false;
  20. function validate_data($users)
  21. {
  22. global $defined_auth_sources;
  23. $errors = array();
  24. $usernames = array();
  25. // 1. Check if mandatory fields are set.
  26. $mandatory_fields = array('LastName', 'FirstName');
  27. if (api_get_setting('registration', 'email') == 'true') {
  28. $mandatory_fields[] = 'Email';
  29. }
  30. $classExistList = array();
  31. $usergroup = new UserGroup();
  32. foreach ($users as $user) {
  33. foreach ($mandatory_fields as $field) {
  34. if (isset($user[$field])) {
  35. if (empty($user[$field])) {
  36. $user['error'] = get_lang($field.'Mandatory');
  37. $errors[] = $user;
  38. }
  39. }
  40. }
  41. // 2. Check username, first, check whether it is empty.
  42. if (isset($user['NewUserName'])) {
  43. if (!UserManager::is_username_empty($user['NewUserName'])) {
  44. // 2.1. Check whether username is too long.
  45. if (UserManager::is_username_too_long($user['NewUserName'])) {
  46. $user['error'] = get_lang('UserNameTooLong');
  47. $errors[] = $user;
  48. }
  49. // 2.2. Check whether the username was used twice in import file.
  50. if (isset($usernames[$user['NewUserName']])) {
  51. $user['error'] = get_lang('UserNameUsedTwice');
  52. $errors[] = $user;
  53. }
  54. $usernames[$user['UserName']] = 1;
  55. // 2.3. Check whether username is allready occupied.
  56. if (!UserManager::is_username_available($user['NewUserName']) && $user['NewUserName'] != $user['UserName']) {
  57. $user['error'] = get_lang('UserNameNotAvailable');
  58. $errors[] = $user;
  59. }
  60. }
  61. }
  62. // 3. Check status.
  63. if (isset($user['Status']) && !api_status_exists($user['Status'])) {
  64. $user['error'] = get_lang('WrongStatus');
  65. $errors[] = $user;
  66. }
  67. // 4. Check ClassId
  68. if (!empty($user['ClassId'])) {
  69. $classId = explode('|', trim($user['ClassId']));
  70. foreach ($classId as $id) {
  71. if (in_array($id, $classExistList)) {
  72. continue;
  73. }
  74. $info = $usergroup->get($id);
  75. if (empty($info)) {
  76. $user['error'] = sprintf(get_lang('ClassIdDoesntExists'), $id);
  77. $errors[] = $user;
  78. } else {
  79. $classExistList[] = $info['id'];
  80. }
  81. }
  82. }
  83. // 5. Check authentication source
  84. if (!empty($user['AuthSource'])) {
  85. if (!in_array($user['AuthSource'], $defined_auth_sources)) {
  86. $user['error'] = get_lang('AuthSourceNotAvailable');
  87. $errors[] = $user;
  88. }
  89. }
  90. }
  91. return $errors;
  92. }
  93. /**
  94. * Add missing user-information (which isn't required, like password, username etc).
  95. */
  96. function complete_missing_data($user)
  97. {
  98. global $purification_option_for_usernames;
  99. // 1. Create a username if necessary.
  100. if (UserManager::is_username_empty($user['UserName'])) {
  101. $user['UserName'] = UserManager::create_unique_username($user['FirstName'], $user['LastName']);
  102. } else {
  103. $user['UserName'] = UserManager::purify_username($user['UserName'], $purification_option_for_usernames);
  104. }
  105. // 2. Generate a password if necessary.
  106. if (empty($user['Password'])) {
  107. $user['Password'] = api_generate_password();
  108. }
  109. // 3. Set status if not allready set.
  110. if (empty($user['Status'])) {
  111. $user['Status'] = 'user';
  112. }
  113. // 4. Set authsource if not allready set.
  114. if (empty($user['AuthSource'])) {
  115. $user['AuthSource'] = PLATFORM_AUTH_SOURCE;
  116. }
  117. return $user;
  118. }
  119. /**
  120. * Update users from the imported data
  121. * @param array $users List of users
  122. * @return void
  123. * @uses global variable $inserted_in_course, which returns the list of courses the user was inserted in
  124. */
  125. function updateUsers($users)
  126. {
  127. global $insertedIn_course;
  128. // Not all scripts declare the $inserted_in_course array (although they should).
  129. if (!isset($inserted_in_course)) {
  130. $inserted_in_course = array();
  131. }
  132. require_once api_get_path(LIBRARY_PATH).'mail.lib.inc.php';
  133. $usergroup = new UserGroup();
  134. $send_mail = $_POST['sendMail'] ? true : false;
  135. if (is_array($users)) {
  136. foreach ($users as $user) {
  137. $user = complete_missing_data($user);
  138. $user['Status'] = api_status_key($user['Status']);
  139. $userName = $user['UserName'];
  140. $userInfo = api_get_user_info_from_username($userName);
  141. $user_id = $userInfo['user_id'];
  142. if ($user_id == 0) {
  143. return false;
  144. }
  145. $firstName = isset($user['FirstName']) ? $user['FirstName'] : $userInfo['firstname'];
  146. $lastName = isset($user['LastName']) ? $user['LastName'] : $userInfo['lastname'];
  147. $userName = isset($user['NewUserName']) ? $user['NewUserName'] : $userInfo['username'];
  148. $password = isset($user['Password']) ? $user['Password'] : $userInfo['password'];
  149. $authSource = isset($user['AuthSource']) ? $user['AuthSource'] : $userInfo['auth_source'];
  150. $email = isset($user['Email']) ? $user['Email'] : $userInfo['email'];
  151. $status = isset($user['Status']) ? $user['Status'] : $userInfo['status'];
  152. $officialCode = isset($user['OfficialCode']) ? $user['OfficialCode'] : $userInfo['official_code'];
  153. $phone = isset($user['PhoneNumber']) ? $user['PhoneNumber'] : $userInfo['phone'];
  154. $pictureUrl = isset($user['PictureUri']) ? $user['PictureUri'] : $userInfo['picture_uri'];
  155. $expirationDate = isset($user['ExpiryDate']) ? $user['ExpiryDate'] : $userInfo['expiration_date'];
  156. $active = isset($user['Active']) ? $user['Active'] : $userInfo['active'];
  157. $creatorId = $userInfo['creator_id'];
  158. $hrDeptId = $userInfo['hr_dept_id'];
  159. $language = isset($user['Language']) ? $user['Language'] : $userInfo['language'];
  160. $sendEmail = isset($user['SendEmail']) ? $user['SendEmail'] : $userInfo['language'];
  161. $userUpdated = UserManager :: update_user(
  162. $user_id,
  163. $firstName,
  164. $lastName,
  165. $userName,
  166. $password,
  167. $authSource,
  168. $email,
  169. $status,
  170. $officialCode,
  171. $phone,
  172. $pictureUrl,
  173. $expirationDate,
  174. $active,
  175. $creatorId,
  176. $hrDeptId,
  177. null,
  178. $language,
  179. '',
  180. '',
  181. ''
  182. );
  183. if (!is_array($user['Courses']) && !empty($user['Courses'])) {
  184. $user['Courses'] = array($user['Courses']);
  185. }
  186. if (is_array($user['Courses'])) {
  187. foreach ($user['Courses'] as $course) {
  188. if (CourseManager::course_exists($course)) {
  189. CourseManager::subscribe_user($user_id, $course, $user['Status']);
  190. $course_info = CourseManager::get_course_information($course);
  191. $inserted_in_course[$course] = $course_info['title'];
  192. }
  193. if (CourseManager :: course_exists($course, true)) {
  194. // Also subscribe to virtual courses through check on visual code.
  195. $list = CourseManager :: get_courses_info_from_visual_code($course);
  196. foreach ($list as $vcourse) {
  197. if ($vcourse['code'] == $course) {
  198. // Ignore, this has already been inserted.
  199. } else {
  200. CourseManager :: subscribe_user($user_id, $vcourse['code'], $user['Status']);
  201. $inserted_in_course[$vcourse['code']] = $vcourse['title'];
  202. }
  203. }
  204. }
  205. }
  206. }
  207. if (!empty($user['ClassId'])) {
  208. $classId = explode('|', trim($user['ClassId']));
  209. foreach ($classId as $id) {
  210. $usergroup->subscribe_users_to_usergroup($id, array($user_id), false);
  211. }
  212. }
  213. // Saving extra fields.
  214. global $extra_fields;
  215. // We are sure that the extra field exists.
  216. foreach ($extra_fields as $extras) {
  217. if (isset($user[$extras[1]])) {
  218. $key = $extras[1];
  219. $value = $user[$extras[1]];
  220. UserManager::update_extra_field_value($user_id, $key, $value);
  221. }
  222. }
  223. }
  224. }
  225. }
  226. /**
  227. * Read the CSV-file
  228. * @param string $file Path to the CSV-file
  229. * @return array All userinformation read from the file
  230. */
  231. function parse_csv_data($file)
  232. {
  233. $users = Import :: csv_to_array($file);
  234. foreach ($users as $index => $user) {
  235. if (isset ($user['Courses'])) {
  236. $user['Courses'] = explode('|', trim($user['Courses']));
  237. }
  238. $users[$index] = $user;
  239. }
  240. return $users;
  241. }
  242. /**
  243. * XML-parser: handle start of element
  244. * @param string $parser Deprecated?
  245. * @param string $data The data to be parsed
  246. */
  247. function element_start($parser, $data)
  248. {
  249. $data = api_utf8_decode($data);
  250. global $user;
  251. global $current_tag;
  252. switch ($data) {
  253. case 'Contact':
  254. $user = array ();
  255. break;
  256. default:
  257. $current_tag = $data;
  258. }
  259. }
  260. /**
  261. * XML-parser: handle end of element
  262. * @param string $parser Deprecated?
  263. * @param string $data The data to be parsed
  264. */
  265. function element_end($parser, $data)
  266. {
  267. $data = api_utf8_decode($data);
  268. global $user;
  269. global $users;
  270. global $current_value;
  271. switch ($data) {
  272. case 'Contact':
  273. if ($user['Status'] == '5') {
  274. $user['Status'] = STUDENT;
  275. }
  276. if ($user['Status'] == '1') {
  277. $user['Status'] = COURSEMANAGER;
  278. }
  279. $users[] = $user;
  280. break;
  281. default:
  282. $user[$data] = $current_value;
  283. break;
  284. }
  285. }
  286. /**
  287. * XML-parser: handle character data
  288. * @param string $parser Parser (deprecated?)
  289. * @param string $data The data to be parsed
  290. * @return void
  291. */
  292. function character_data($parser, $data)
  293. {
  294. $data = trim(api_utf8_decode($data));
  295. global $current_value;
  296. $current_value = $data;
  297. }
  298. /**
  299. * Read the XML-file
  300. * @param string $file Path to the XML-file
  301. * @return array All user information read from the file
  302. */
  303. function parse_xml_data($file)
  304. {
  305. global $users;
  306. $users = array();
  307. $parser = xml_parser_create('UTF-8');
  308. xml_set_element_handler($parser, 'element_start', 'element_end');
  309. xml_set_character_data_handler($parser, 'character_data');
  310. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
  311. xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
  312. xml_parser_free($parser);
  313. return $users;
  314. }
  315. $this_section = SECTION_PLATFORM_ADMIN;
  316. api_protect_admin_script(true, null, 'login');
  317. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  318. if (is_array($extAuthSource)) {
  319. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  320. }
  321. $tool_name = get_lang('ImportUserListXMLCSV');
  322. $interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
  323. set_time_limit(0);
  324. $extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
  325. $user_id_error = array();
  326. $error_message = '';
  327. if (isset($_POST['formSent']) && $_POST['formSent'] AND $_FILES['import_file']['size'] !== 0) {
  328. $file_type = 'csv';
  329. Security::clear_token();
  330. $tok = Security::get_token();
  331. $allowed_file_mimetype = array('csv', 'xml');
  332. $error_kind_file = false;
  333. $uploadInfo = pathinfo($_FILES['import_file']['name']);
  334. $ext_import_file = $uploadInfo['extension'];
  335. if (in_array($ext_import_file, $allowed_file_mimetype)) {
  336. if (strcmp($file_type, 'csv') === 0 && $ext_import_file == $allowed_file_mimetype[0]) {
  337. $users = parse_csv_data($_FILES['import_file']['tmp_name']);
  338. $errors = validate_data($users);
  339. $error_kind_file = false;
  340. } elseif (strcmp($file_type, 'xml') === 0 && $ext_import_file == $allowed_file_mimetype[1]) {
  341. $users = parse_xml_data($_FILES['import_file']['tmp_name']);
  342. $errors = validate_data($users);
  343. $error_kind_file = false;
  344. } else {
  345. $error_kind_file = true;
  346. }
  347. } else {
  348. $error_kind_file = true;
  349. }
  350. // List user id with error.
  351. $users_to_insert = $user_id_error = array();
  352. if (is_array($errors)) {
  353. foreach ($errors as $my_errors) {
  354. $user_id_error[] = $my_errors['UserName'];
  355. }
  356. }
  357. if (is_array($users)) {
  358. foreach ($users as $my_user) {
  359. if (!in_array($my_user['UserName'], $user_id_error)) {
  360. $users_to_insert[] = $my_user;
  361. }
  362. }
  363. }
  364. $inserted_in_course = array();
  365. if (strcmp($file_type, 'csv') === 0) {
  366. updateUsers($users_to_insert);
  367. } else {
  368. $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption1');
  369. }
  370. if (count($errors) > 0) {
  371. $see_message_import = get_lang('FileImportedJustUsersThatAreNotRegistered');
  372. } else {
  373. $see_message_import = get_lang('FileImported');
  374. }
  375. if (count($errors) != 0) {
  376. $warning_message = '<ul>';
  377. foreach ($errors as $index => $error_user) {
  378. $warning_message .= '<li><b>'.$error_user['error'].'</b>: ';
  379. $warning_message .=
  380. '<strong>'.$error_user['UserName'].'</strong>&nbsp;('.
  381. api_get_person_name($error_user['FirstName'], $error_user['LastName']).')';
  382. $warning_message .= '</li>';
  383. }
  384. $warning_message .= '</ul>';
  385. }
  386. // if the warning message is too long then we display the warning message trough a session
  387. $_SESSION['session_message_import_users'] = $warning_message;
  388. $warning_message = 'session_message';
  389. if ($error_kind_file) {
  390. $error_message = get_lang('YouMustImportAFileAccordingToSelectedOption');
  391. } else {
  392. header('Location: '.api_get_path(WEB_CODE_PATH).'admin/user_list.php?action=show_message&warn='.urlencode($warning_message).'&message='.urlencode($see_message_import).'&sec_token='.$tok);
  393. exit;
  394. }
  395. }
  396. Display :: display_header($tool_name);
  397. if (!empty($error_message)) {
  398. Display::display_error_message($error_message);
  399. }
  400. $form = new FormValidator('user_update_import','post','user_update_import.php');
  401. $form->addElement('header', '', $tool_name);
  402. $form->addElement('hidden', 'formSent');
  403. $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
  404. $group = array();
  405. $form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
  406. $defaults['formSent'] = 1;
  407. $defaults['sendMail'] = 0;
  408. $defaults['file_type'] = 'csv';
  409. $form->setDefaults($defaults);
  410. $form->display();
  411. $list = array();
  412. $list_reponse = array();
  413. $result_xml = '';
  414. $i = 0;
  415. $count_fields = count($extra_fields);
  416. if ($count_fields > 0) {
  417. foreach ($extra_fields as $extra) {
  418. $list[] = $extra[1];
  419. $list_reponse[] = 'xxx';
  420. $spaces = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  421. $result_xml .= $spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';
  422. if ($i != $count_fields - 1) {
  423. $result_xml .= '<br/>';
  424. }
  425. $i++;
  426. }
  427. }
  428. ?>
  429. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  430. <blockquote>
  431. <pre>
  432. <b>UserName</b>;LastName;FirstName;Email;NewUserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;ExpiryDate;Active;Language;Courses;ClassId;
  433. xxx;xxx;xxx;xxx;xxx;xxx;xxx;xxx;xxx;user/teacher/drh;0000-00-00 00:00:00;0/1;xxx;<span style="color:red;"><?php if (count($list_reponse) > 0) echo implode(';', $list_reponse).';'; ?></span>xxx1|xxx2|xxx3;1;<br />
  434. </pre>
  435. </blockquote>
  436. <p><?php
  437. Display :: display_footer();