user_update_import.php 16 KB

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