course_user_import.php 7.2 KB

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