course_user_import.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. foreach ($users_courses as $user_course) {
  69. $csv_data[$user_course['UserName']][$user_course['CourseCode']] = $user_course['Status'];
  70. }
  71. foreach ($csv_data as $username => $csv_subscriptions) {
  72. $sql = "SELECT * FROM $user_table u
  73. WHERE u.username = '".Database::escape_string($username)."'";
  74. $res = Database::query($sql);
  75. $obj = Database::fetch_object($res);
  76. $user_id = $obj->user_id;
  77. $sql = "SELECT * FROM $course_user_table cu
  78. WHERE cu.user_id = $user_id AND cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." ";
  79. $res = Database::query($sql);
  80. $db_subscriptions = array();
  81. while ($obj = Database::fetch_object($res)) {
  82. $db_subscriptions[$obj->c_id] = $obj->status;
  83. }
  84. $to_subscribe = array_diff(array_keys($csv_subscriptions), array_keys($db_subscriptions));
  85. $to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csv_subscriptions));
  86. if ($_POST['subscribe']) {
  87. foreach ($to_subscribe as $courseId) {
  88. $courseInfo = api_get_course_info_by_id($courseId);
  89. $course_code = $courseInfo['code'];
  90. if (CourseManager :: course_exists($course_code)) {
  91. CourseManager::subscribe_user(
  92. $user_id,
  93. $course_code,
  94. $csv_subscriptions[$course_code]
  95. );
  96. $course_info = CourseManager::get_course_information($course_code);
  97. $inserted_in_course[$course_code] = $course_info['title'];
  98. $inserted_in_course[$course_info['code']] = $course_info['title'];
  99. }
  100. }
  101. }
  102. if ($_POST['unsubscribe']) {
  103. foreach ($to_unsubscribe as $courseId) {
  104. $courseInfo = api_get_course_info_by_id($courseId);
  105. $course_code = $courseInfo['code'];
  106. if (CourseManager :: course_exists($course_code)) {
  107. CourseManager::unsubscribe_user($user_id, $course_code);
  108. $course_info = CourseManager::get_course_information($course_code);
  109. CourseManager::unsubscribe_user($user_id, $course_code);
  110. $inserted_in_course[$course_info['code']] = $course_info['title'];
  111. }
  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. include '../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. Security::clear_token();
  166. $tok = Security::get_token();
  167. header('Location: user_list.php?action=show_message&warn='.urlencode($warn).'&sec_token='.$tok);
  168. exit();
  169. }
  170. }
  171. // Displaying the header.
  172. Display :: display_header($tool_name);
  173. if (count($errors) != 0) {
  174. $error_message = '<ul>';
  175. foreach ($errors as $index => $error_course) {
  176. $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
  177. $error_message .= $error_course['Code'].' '.$error_course['Title'];
  178. $error_message .= '</li>';
  179. }
  180. $error_message .= '</ul>';
  181. Display :: display_error_message($error_message, false);
  182. }
  183. // Displaying the form.
  184. $form->display();
  185. ?>
  186. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  187. <blockquote>
  188. <pre>
  189. <b>UserName</b>;<b>CourseCode</b>;<b>Status</b>
  190. jdoe;course01;<?php echo COURSEMANAGER; ?>
  191. adam;course01;<?php echo STUDENT; ?>
  192. </pre>
  193. <?php
  194. echo COURSEMANAGER.': '.get_lang('Teacher').'<br />';
  195. echo STUDENT.': '.get_lang('Student').'<br />';
  196. ?>
  197. </blockquote>
  198. <?php
  199. Display :: display_footer();