course_user_import.php 8.2 KB

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