course_user_import.php 8.2 KB

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