course_user_import.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This tool allows platform admins to update course-user relations by uploading
  5. * a CSV file.
  6. *
  7. * @package chamilo.admin
  8. */
  9. /**
  10. * Validates the imported data.
  11. */
  12. function validate_data($users_courses)
  13. {
  14. $errors = [];
  15. $coursecodes = [];
  16. foreach ($users_courses as $index => $user_course) {
  17. $user_course['line'] = $index + 1;
  18. // 1. Check whether mandatory fields are set.
  19. $mandatory_fields = ['UserName', 'CourseCode', 'Status'];
  20. foreach ($mandatory_fields as $key => $field) {
  21. if (!isset($user_course[$field]) || strlen($user_course[$field]) == 0) {
  22. $user_course['error'] = get_lang($field.'Mandatory');
  23. $errors[] = $user_course;
  24. }
  25. }
  26. // 2. Check whether coursecode exists.
  27. if (isset($user_course['CourseCode']) && strlen($user_course['CourseCode']) != 0) {
  28. // 2.1 Check whethher code has been allready used by this CVS-file.
  29. if (!isset($coursecodes[$user_course['CourseCode']])) {
  30. // 2.1.1 Check whether course with this code exists in the system.
  31. $courseInfo = api_get_course_info($user_course['CourseCode']);
  32. if (empty($courseInfo)) {
  33. $user_course['error'] = get_lang('CodeDoesNotExists');
  34. $errors[] = $user_course;
  35. } else {
  36. $coursecodes[$user_course['CourseCode']] = 1;
  37. }
  38. }
  39. }
  40. // 3. Check whether username exists.
  41. if (isset($user_course['UserName']) && strlen($user_course['UserName']) != 0) {
  42. if (UserManager::is_username_available($user_course['UserName'])) {
  43. $user_course['error'] = get_lang('UnknownUser');
  44. $errors[] = $user_course;
  45. }
  46. }
  47. // 4. Check whether status is valid.
  48. if (isset($user_course['Status']) && strlen($user_course['Status']) != 0) {
  49. if ($user_course['Status'] != COURSEMANAGER && $user_course['Status'] != STUDENT) {
  50. $user_course['error'] = get_lang('UnknownStatus');
  51. $errors[] = $user_course;
  52. }
  53. }
  54. }
  55. return $errors;
  56. }
  57. /**
  58. * Saves imported data.
  59. */
  60. function save_data($users_courses)
  61. {
  62. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  63. $csv_data = [];
  64. $inserted_in_course = [];
  65. $courseListCache = [];
  66. $courseListById = [];
  67. foreach ($users_courses as $user_course) {
  68. if (!in_array($user_course['CourseCode'], array_keys($courseListCache))) {
  69. $courseInfo = api_get_course_info($user_course['CourseCode']);
  70. if ($courseInfo) {
  71. $courseListCache[$user_course['CourseCode']] = $courseInfo;
  72. }
  73. } else {
  74. $courseInfo = $courseListCache[$user_course['CourseCode']];
  75. }
  76. $courseListById[$courseInfo['real_id']] = $courseInfo;
  77. $csv_data[$user_course['UserName']][$courseInfo['real_id']] = $user_course['Status'];
  78. }
  79. foreach ($csv_data as $username => $csv_subscriptions) {
  80. $userInfo = api_get_user_info_from_username($username);
  81. if (empty($userInfo)) {
  82. continue;
  83. }
  84. $user_id = $userInfo['user_id'];
  85. $sql = "SELECT * FROM $course_user_table cu
  86. WHERE cu.user_id = $user_id AND cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." ";
  87. $res = Database::query($sql);
  88. $db_subscriptions = [];
  89. while ($obj = Database::fetch_object($res)) {
  90. $db_subscriptions[$obj->c_id] = $obj->status;
  91. }
  92. $to_subscribe = array_diff(array_keys($csv_subscriptions), array_keys($db_subscriptions));
  93. $to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csv_subscriptions));
  94. if (isset($_POST['subscribe']) && $_POST['subscribe']) {
  95. foreach ($to_subscribe as $courseId) {
  96. $courseInfo = $courseListById[$courseId];
  97. $courseCode = $courseInfo['code'];
  98. $result = CourseManager::subscribeUser(
  99. $user_id,
  100. $courseCode,
  101. $csv_subscriptions[$courseId]
  102. );
  103. if ($result) {
  104. $inserted_in_course[$courseInfo['code']] = $courseInfo['title'];
  105. }
  106. }
  107. }
  108. if (isset($_POST['unsubscribe']) && $_POST['unsubscribe']) {
  109. foreach ($to_unsubscribe as $courseId) {
  110. if (isset($courseListById[$courseId])) {
  111. $courseInfo = $courseListById[$courseId];
  112. } else {
  113. $courseInfo = api_get_course_info_by_id($courseId);
  114. }
  115. $courseCode = $courseInfo['code'];
  116. CourseManager::unsubscribe_user($user_id, $courseCode);
  117. }
  118. }
  119. }
  120. return $inserted_in_course;
  121. }
  122. /**
  123. * Reads CSV-file.
  124. *
  125. * @param string $file Path to the CSV-file
  126. *
  127. * @return array All course-information read from the file
  128. */
  129. function parse_csv_data($file)
  130. {
  131. $courses = Import::csvToArray($file);
  132. return $courses;
  133. }
  134. $cidReset = true;
  135. require_once __DIR__.'/../inc/global.inc.php';
  136. // Setting the section (for the tabs).
  137. $this_section = SECTION_PLATFORM_ADMIN;
  138. // Protecting the admin section.
  139. api_protect_admin_script();
  140. $tool_name = get_lang('AddUsersToACourse').' CSV';
  141. $interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('PlatformAdmin')];
  142. set_time_limit(0);
  143. // Creating the form.
  144. $form = new FormValidator('course_user_import');
  145. $form->addElement('header', '', $tool_name);
  146. $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
  147. $form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
  148. $form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
  149. $form->addButtonImport(get_lang('Import'));
  150. $form->setDefaults(['subscribe' => '1', 'unsubscribe' => 1]);
  151. $errors = [];
  152. if ($form->validate()) {
  153. $users_courses = parse_csv_data($_FILES['import_file']['tmp_name']);
  154. $errors = validate_data($users_courses);
  155. if (count($errors) == 0) {
  156. $inserted_in_course = save_data($users_courses);
  157. // Build the alert message in case there were visual codes subscribed to.
  158. if ($_POST['subscribe']) {
  159. //$warn = get_lang('UsersSubscribedToBecauseVisualCode').': ';
  160. } else {
  161. $warn = get_lang('UsersUnsubscribedFromBecauseVisualCode').': ';
  162. }
  163. if (!empty($inserted_in_course)) {
  164. $warn = get_lang('FileImported');
  165. } else {
  166. $warn = get_lang('ErrorsWhenImportingFile');
  167. }
  168. Display::addFlash(Display::return_message($warn));
  169. Security::clear_token();
  170. $tok = Security::get_token();
  171. header('Location: '.api_get_self());
  172. exit();
  173. }
  174. }
  175. // Displaying the header.
  176. Display :: display_header($tool_name);
  177. if (count($errors) != 0) {
  178. $error_message = '<ul>';
  179. foreach ($errors as $index => $error_course) {
  180. $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
  181. $error_message .= $error_course['Code'].' '.$error_course['Title'];
  182. $error_message .= '</li>';
  183. }
  184. $error_message .= '</ul>';
  185. echo Display::return_message($error_message, 'error', false);
  186. }
  187. // Displaying the form.
  188. $form->display();
  189. ?>
  190. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  191. <blockquote>
  192. <pre>
  193. <b>UserName</b>;<b>CourseCode</b>;<b>Status</b>
  194. jdoe;course01;<?php echo COURSEMANAGER; ?>
  195. adam;course01;<?php echo STUDENT; ?>
  196. </pre>
  197. <?php
  198. echo COURSEMANAGER.': '.get_lang('Teacher').'<br />';
  199. echo STUDENT.': '.get_lang('Student').'<br />';
  200. ?>
  201. </blockquote>
  202. <?php
  203. Display :: display_footer();