user_update_import.php 15 KB

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