user_update_import.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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 __DIR__.'/../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 false|null
  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. }
  187. }
  188. if (!empty($user['ClassId'])) {
  189. $classId = explode('|', trim($user['ClassId']));
  190. foreach ($classId as $id) {
  191. $usergroup->subscribe_users_to_usergroup(
  192. $id,
  193. array($user_id),
  194. false
  195. );
  196. }
  197. }
  198. // Saving extra fields.
  199. global $extra_fields;
  200. // We are sure that the extra field exists.
  201. foreach ($extra_fields as $extras) {
  202. if (isset($user[$extras[1]])) {
  203. $key = $extras[1];
  204. $value = $user[$extras[1]];
  205. UserManager::update_extra_field_value(
  206. $user_id,
  207. $key,
  208. $value
  209. );
  210. }
  211. }
  212. }
  213. }
  214. }
  215. /**
  216. * Read the CSV-file
  217. * @param string $file Path to the CSV-file
  218. * @return array All userinformation read from the file
  219. */
  220. function parse_csv_data($file)
  221. {
  222. $users = Import :: csvToArray($file);
  223. foreach ($users as $index => $user) {
  224. if (isset ($user['Courses'])) {
  225. $user['Courses'] = explode('|', trim($user['Courses']));
  226. }
  227. $users[$index] = $user;
  228. }
  229. return $users;
  230. }
  231. /**
  232. * XML-parser: handle start of element
  233. * @param string $parser Deprecated?
  234. * @param string $data The data to be parsed
  235. */
  236. function element_start($parser, $data)
  237. {
  238. $data = api_utf8_decode($data);
  239. global $user;
  240. global $current_tag;
  241. switch ($data) {
  242. case 'Contact':
  243. $user = array();
  244. break;
  245. default:
  246. $current_tag = $data;
  247. }
  248. }
  249. /**
  250. * XML-parser: handle end of element
  251. * @param string $parser Deprecated?
  252. * @param string $data The data to be parsed
  253. */
  254. function element_end($parser, $data)
  255. {
  256. $data = api_utf8_decode($data);
  257. global $user;
  258. global $users;
  259. global $current_value;
  260. switch ($data) {
  261. case 'Contact':
  262. if ($user['Status'] == '5') {
  263. $user['Status'] = STUDENT;
  264. }
  265. if ($user['Status'] == '1') {
  266. $user['Status'] = COURSEMANAGER;
  267. }
  268. $users[] = $user;
  269. break;
  270. default:
  271. $user[$data] = $current_value;
  272. break;
  273. }
  274. }
  275. /**
  276. * XML-parser: handle character data
  277. * @param string $parser Parser (deprecated?)
  278. * @param string $data The data to be parsed
  279. * @return void
  280. */
  281. function character_data($parser, $data)
  282. {
  283. $data = trim(api_utf8_decode($data));
  284. global $current_value;
  285. $current_value = $data;
  286. }
  287. /**
  288. * Read the XML-file
  289. * @param string $file Path to the XML-file
  290. * @return array All user information read from the file
  291. */
  292. function parse_xml_data($file)
  293. {
  294. global $users;
  295. $users = array();
  296. $parser = xml_parser_create('UTF-8');
  297. xml_set_element_handler($parser, 'element_start', 'element_end');
  298. xml_set_character_data_handler($parser, 'character_data');
  299. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
  300. xml_parse($parser, api_utf8_encode_xml(file_get_contents($file)));
  301. xml_parser_free($parser);
  302. return $users;
  303. }
  304. $this_section = SECTION_PLATFORM_ADMIN;
  305. api_protect_admin_script(true, null, 'login');
  306. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  307. if (isset($extAuthSource) && is_array($extAuthSource)) {
  308. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  309. }
  310. $tool_name = get_lang('ImportUserListXMLCSV');
  311. $interbreadcrumb[] = array("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
  312. set_time_limit(0);
  313. $extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
  314. $user_id_error = array();
  315. $error_message = '';
  316. if (isset($_POST['formSent']) && $_POST['formSent'] && $_FILES['import_file']['size'] !== 0) {
  317. $file_type = 'csv';
  318. Security::clear_token();
  319. $tok = Security::get_token();
  320. $allowed_file_mimetype = array('csv', 'xml');
  321. $error_kind_file = false;
  322. $uploadInfo = pathinfo($_FILES['import_file']['name']);
  323. $ext_import_file = $uploadInfo['extension'];
  324. if (in_array($ext_import_file, $allowed_file_mimetype)) {
  325. if (strcmp($file_type, 'csv') === 0 && $ext_import_file == $allowed_file_mimetype[0]) {
  326. $users = parse_csv_data($_FILES['import_file']['tmp_name']);
  327. $errors = validate_data($users);
  328. $error_kind_file = false;
  329. } elseif (strcmp($file_type, 'xml') === 0 && $ext_import_file == $allowed_file_mimetype[1]) {
  330. $users = parse_xml_data($_FILES['import_file']['tmp_name']);
  331. $errors = validate_data($users);
  332. $error_kind_file = false;
  333. } else {
  334. $error_kind_file = true;
  335. }
  336. } else {
  337. $error_kind_file = true;
  338. }
  339. // List user id with error.
  340. $users_to_insert = $user_id_error = array();
  341. if (is_array($errors)) {
  342. foreach ($errors as $my_errors) {
  343. $user_id_error[] = $my_errors['UserName'];
  344. }
  345. }
  346. if (is_array($users)) {
  347. foreach ($users as $my_user) {
  348. if (!in_array($my_user['UserName'], $user_id_error)) {
  349. $users_to_insert[] = $my_user;
  350. }
  351. }
  352. }
  353. $inserted_in_course = array();
  354. if (strcmp($file_type, 'csv') === 0) {
  355. updateUsers($users_to_insert);
  356. }
  357. if (count($errors) > 0) {
  358. $see_message_import = get_lang('FileImportedJustUsersThatAreNotRegistered');
  359. } else {
  360. $see_message_import = get_lang('FileImported');
  361. }
  362. if (count($errors) != 0) {
  363. $warning_message = '<ul>';
  364. foreach ($errors as $index => $error_user) {
  365. $warning_message .= '<li><b>'.$error_user['error'].'</b>: ';
  366. $warning_message .=
  367. '<strong>'.$error_user['UserName'].'</strong>&nbsp;('.
  368. api_get_person_name($error_user['FirstName'], $error_user['LastName']).')';
  369. $warning_message .= '</li>';
  370. }
  371. $warning_message .= '</ul>';
  372. }
  373. // if the warning message is too long then we display the warning message trough a session
  374. Display::addFlash(Display::return_message($warning_message, 'warning', false));
  375. if ($error_kind_file) {
  376. Display::addFlash(Display::return_message(get_lang('YouMustImportAFileAccordingToSelectedOption'), 'error', false));
  377. } else {
  378. header('Location: '.api_get_path(WEB_CODE_PATH).'admin/user_list.php?sec_token='.$tok);
  379. exit;
  380. }
  381. }
  382. Display :: display_header($tool_name);
  383. if (!empty($error_message)) {
  384. Display::display_error_message($error_message);
  385. }
  386. $form = new FormValidator('user_update_import', 'post', api_get_self());
  387. $form->addElement('header', $tool_name);
  388. $form->addElement('hidden', 'formSent');
  389. $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
  390. $group = array();
  391. $form->addButtonImport(get_lang('Import'));
  392. $defaults['formSent'] = 1;
  393. $defaults['sendMail'] = 0;
  394. $defaults['file_type'] = 'csv';
  395. $form->setDefaults($defaults);
  396. $form->display();
  397. $list = array();
  398. $list_reponse = array();
  399. $result_xml = '';
  400. $i = 0;
  401. $count_fields = count($extra_fields);
  402. if ($count_fields > 0) {
  403. foreach ($extra_fields as $extra) {
  404. $list[] = $extra[1];
  405. $list_reponse[] = 'xxx';
  406. $spaces = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  407. $result_xml .= $spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';
  408. if ($i != $count_fields - 1) {
  409. $result_xml .= '<br/>';
  410. }
  411. $i++;
  412. }
  413. }
  414. ?>
  415. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  416. <blockquote>
  417. <pre>
  418. <b>UserName</b>;LastName;FirstName;Email;NewUserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;ExpiryDate;Active;Language;Courses;ClassId;
  419. xxx;xxx;xxx;xxx;xxx;xxx;xxx;xxx;xxx;user/teacher/drh;YYYY-MM-DD 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 />
  420. </pre>
  421. </blockquote>
  422. <p><?php
  423. Display :: display_footer();