user_update_import.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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('UserNameTooLong');
  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('UserNameUsedTwice');
  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('UserNameNotAvailable');
  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('WrongStatus');
  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('ClassIdDoesntExists'), $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('AuthSourceNotAvailable');
  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 = $_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. $password = isset($user['Password']) ? $user['Password'] : $userInfo['password'];
  146. $authSource = isset($user['AuthSource']) ? $user['AuthSource'] : $userInfo['auth_source'];
  147. $email = isset($user['Email']) ? $user['Email'] : $userInfo['email'];
  148. $status = isset($user['Status']) ? $user['Status'] : $userInfo['status'];
  149. $officialCode = isset($user['OfficialCode']) ? $user['OfficialCode'] : $userInfo['official_code'];
  150. $phone = isset($user['PhoneNumber']) ? $user['PhoneNumber'] : $userInfo['phone'];
  151. $pictureUrl = isset($user['PictureUri']) ? $user['PictureUri'] : $userInfo['picture_uri'];
  152. $expirationDate = isset($user['ExpiryDate']) ? $user['ExpiryDate'] : $userInfo['expiration_date'];
  153. $active = isset($user['Active']) ? $user['Active'] : $userInfo['active'];
  154. $creatorId = $userInfo['creator_id'];
  155. $hrDeptId = $userInfo['hr_dept_id'];
  156. $language = isset($user['Language']) ? $user['Language'] : $userInfo['language'];
  157. $sendEmail = isset($user['SendEmail']) ? $user['SendEmail'] : $userInfo['language'];
  158. $userUpdated = UserManager :: update_user(
  159. $user_id,
  160. $firstName,
  161. $lastName,
  162. $userName,
  163. $password,
  164. $authSource,
  165. $email,
  166. $status,
  167. $officialCode,
  168. $phone,
  169. $pictureUrl,
  170. $expirationDate,
  171. $active,
  172. $creatorId,
  173. $hrDeptId,
  174. null,
  175. $language,
  176. '',
  177. '',
  178. ''
  179. );
  180. if (!is_array($user['Courses']) && !empty($user['Courses'])) {
  181. $user['Courses'] = [$user['Courses']];
  182. }
  183. if (is_array($user['Courses'])) {
  184. foreach ($user['Courses'] as $course) {
  185. if (CourseManager::course_exists($course)) {
  186. CourseManager::subscribeUser($user_id, $course, $user['Status']);
  187. $course_info = CourseManager::get_course_information($course);
  188. $inserted_in_course[$course] = $course_info['title'];
  189. }
  190. }
  191. }
  192. if (!empty($user['ClassId'])) {
  193. $classId = explode('|', trim($user['ClassId']));
  194. foreach ($classId as $id) {
  195. $usergroup->subscribe_users_to_usergroup(
  196. $id,
  197. [$user_id],
  198. false
  199. );
  200. }
  201. }
  202. // Saving extra fields.
  203. global $extra_fields;
  204. // We are sure that the extra field exists.
  205. foreach ($extra_fields as $extras) {
  206. if (isset($user[$extras[1]])) {
  207. $key = $extras[1];
  208. $value = $user[$extras[1]];
  209. UserManager::update_extra_field_value(
  210. $user_id,
  211. $key,
  212. $value
  213. );
  214. }
  215. }
  216. }
  217. }
  218. }
  219. /**
  220. * Read the CSV-file.
  221. *
  222. * @param string $file Path to the CSV-file
  223. *
  224. * @return array All userinformation read from the file
  225. */
  226. function parse_csv_data($file)
  227. {
  228. $users = Import :: csvToArray($file);
  229. foreach ($users as $index => $user) {
  230. if (isset($user['Courses'])) {
  231. $user['Courses'] = explode('|', trim($user['Courses']));
  232. }
  233. $users[$index] = $user;
  234. }
  235. return $users;
  236. }
  237. function parse_xml_data($file)
  238. {
  239. $crawler = new \Symfony\Component\DomCrawler\Crawler();
  240. $crawler->addXmlContent(file_get_contents($file));
  241. $crawler = $crawler->filter('Contacts > Contact ');
  242. $array = [];
  243. foreach ($crawler as $domElement) {
  244. $row = [];
  245. foreach ($domElement->childNodes as $node) {
  246. if ($node->nodeName != '#text') {
  247. $row[$node->nodeName] = $node->nodeValue;
  248. }
  249. }
  250. if (!empty($row)) {
  251. $array[] = $row;
  252. }
  253. }
  254. return $array;
  255. }
  256. $this_section = SECTION_PLATFORM_ADMIN;
  257. api_protect_admin_script(true, null);
  258. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  259. if (isset($extAuthSource) && is_array($extAuthSource)) {
  260. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  261. }
  262. $tool_name = get_lang('ImportUserListXMLCSV');
  263. $interbreadcrumb[] = ["url" => 'index.php', "name" => get_lang('PlatformAdmin')];
  264. set_time_limit(0);
  265. $extra_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', true);
  266. $user_id_error = [];
  267. $error_message = '';
  268. if (isset($_POST['formSent']) && $_POST['formSent'] && $_FILES['import_file']['size'] !== 0) {
  269. $file_type = 'csv';
  270. Security::clear_token();
  271. $tok = Security::get_token();
  272. $allowed_file_mimetype = ['csv', 'xml'];
  273. $error_kind_file = false;
  274. $uploadInfo = pathinfo($_FILES['import_file']['name']);
  275. $ext_import_file = $uploadInfo['extension'];
  276. if (in_array($ext_import_file, $allowed_file_mimetype)) {
  277. if (strcmp($file_type, 'csv') === 0 && $ext_import_file == $allowed_file_mimetype[0]) {
  278. $users = parse_csv_data($_FILES['import_file']['tmp_name']);
  279. $errors = validate_data($users);
  280. $error_kind_file = false;
  281. } elseif (strcmp($file_type, 'xml') === 0 && $ext_import_file == $allowed_file_mimetype[1]) {
  282. $users = parse_xml_data($_FILES['import_file']['tmp_name']);
  283. $errors = validate_data($users);
  284. $error_kind_file = false;
  285. } else {
  286. $error_kind_file = true;
  287. }
  288. } else {
  289. $error_kind_file = true;
  290. }
  291. // List user id with error.
  292. $users_to_insert = $user_id_error = [];
  293. if (is_array($errors)) {
  294. foreach ($errors as $my_errors) {
  295. $user_id_error[] = $my_errors['UserName'];
  296. }
  297. }
  298. if (is_array($users)) {
  299. foreach ($users as $my_user) {
  300. if (!in_array($my_user['UserName'], $user_id_error)) {
  301. $users_to_insert[] = $my_user;
  302. }
  303. }
  304. }
  305. $inserted_in_course = [];
  306. if (strcmp($file_type, 'csv') === 0) {
  307. updateUsers($users_to_insert);
  308. }
  309. if (count($errors) > 0) {
  310. $see_message_import = get_lang('FileImportedJustUsersThatAreNotRegistered');
  311. } else {
  312. $see_message_import = get_lang('FileImported');
  313. }
  314. if (count($errors) != 0) {
  315. $warning_message = '<ul>';
  316. foreach ($errors as $index => $error_user) {
  317. $warning_message .= '<li><b>'.$error_user['error'].'</b>: ';
  318. $warning_message .=
  319. '<strong>'.$error_user['UserName'].'</strong>&nbsp;('.
  320. api_get_person_name($error_user['FirstName'], $error_user['LastName']).')';
  321. $warning_message .= '</li>';
  322. }
  323. $warning_message .= '</ul>';
  324. }
  325. // if the warning message is too long then we display the warning message trough a session
  326. Display::addFlash(Display::return_message($warning_message, 'warning', false));
  327. if ($error_kind_file) {
  328. Display::addFlash(Display::return_message(get_lang('YouMustImportAFileAccordingToSelectedOption'), 'error', false));
  329. } else {
  330. header('Location: '.api_get_path(WEB_CODE_PATH).'admin/user_list.php?sec_token='.$tok);
  331. exit;
  332. }
  333. }
  334. Display::display_header($tool_name);
  335. if (!empty($error_message)) {
  336. echo Display::return_message($error_message, 'error');
  337. }
  338. $form = new FormValidator('user_update_import', 'post', api_get_self());
  339. $form->addElement('header', $tool_name);
  340. $form->addElement('hidden', 'formSent');
  341. $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
  342. $group = [];
  343. $form->addButtonImport(get_lang('Import'));
  344. $defaults['formSent'] = 1;
  345. $defaults['sendMail'] = 0;
  346. $defaults['file_type'] = 'csv';
  347. $form->setDefaults($defaults);
  348. $form->display();
  349. $list = [];
  350. $list_reponse = [];
  351. $result_xml = '';
  352. $i = 0;
  353. $count_fields = count($extra_fields);
  354. if ($count_fields > 0) {
  355. foreach ($extra_fields as $extra) {
  356. $list[] = $extra[1];
  357. $list_reponse[] = 'xxx';
  358. $spaces = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  359. $result_xml .= $spaces.'&lt;'.$extra[1].'&gt;xxx&lt;/'.$extra[1].'&gt;';
  360. if ($i != $count_fields - 1) {
  361. $result_xml .= '<br/>';
  362. }
  363. $i++;
  364. }
  365. }
  366. ?>
  367. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  368. <blockquote>
  369. <pre>
  370. <b>UserName</b>;LastName;FirstName;Email;NewUserName;Password;AuthSource;OfficialCode;PhoneNumber;Status;ExpiryDate;Active;Language;Courses;ClassId;
  371. 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) {
  372. echo implode(';', $list_reponse).';';
  373. } ?></span>xxx1|xxx2|xxx3;1;<br />
  374. </pre>
  375. </blockquote>
  376. <p><?php
  377. Display :: display_footer();