course_user_import.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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->course_code] = $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 $course_code) {
  88. if (CourseManager :: course_exists($course_code)) {
  89. CourseManager::subscribe_user(
  90. $user_id,
  91. $course_code,
  92. $csv_subscriptions[$course_code]
  93. );
  94. $course_info = CourseManager::get_course_information($course_code);
  95. $inserted_in_course[$course_code] = $course_info['title'];
  96. $inserted_in_course[$course_info['code']] = $course_info['title'];
  97. }
  98. }
  99. }
  100. if ($_POST['unsubscribe']) {
  101. foreach ($to_unsubscribe as $course_code) {
  102. if (CourseManager :: course_exists($course_code)) {
  103. CourseManager::unsubscribe_user($user_id, $course_code);
  104. $course_info = CourseManager::get_course_information($course_code);
  105. CourseManager::unsubscribe_user($user_id, $course_code);
  106. $inserted_in_course[$course_info['code']] = $course_info['title'];
  107. }
  108. }
  109. }
  110. }
  111. return $inserted_in_course;
  112. }
  113. /**
  114. * Reads CSV-file.
  115. * @param string $file Path to the CSV-file
  116. * @return array All course-information read from the file
  117. */
  118. function parse_csv_data($file)
  119. {
  120. $courses = Import :: csv_to_array($file);
  121. return $courses;
  122. }
  123. // Language files that should be included,
  124. $language_file = array('admin', 'registration');
  125. $cidReset = true;
  126. include '../inc/global.inc.php';
  127. // Setting the section (for the tabs).
  128. $this_section = SECTION_PLATFORM_ADMIN;
  129. // Protecting the admin section.
  130. api_protect_admin_script();
  131. // Including additional libraries.
  132. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  133. require_once api_get_path(LIBRARY_PATH).'import.lib.php';
  134. $tool_name = get_lang('AddUsersToACourse').' CSV';
  135. $interbreadcrumb[] = array('url' => 'index.php', '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->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
  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. Security::clear_token();
  167. $tok = Security::get_token();
  168. header('Location: user_list.php?action=show_message&warn='.urlencode($warn).'&sec_token='.$tok);
  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();