user_update_import.php 15 KB

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