course_user_import_by_email.php 8.4 KB

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