course_user_import_by_email.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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']) !=
  45. 0) {
  46. $user = api_get_user_info_from_email($user_course['Email']);
  47. if (empty($user)) {
  48. $user_course['error'] = get_lang('UnknownUser');
  49. $errors[] = $user_course;
  50. }
  51. }
  52. // 4. Check whether status is valid.
  53. if (isset ($user_course['Status']) && strlen($user_course['Status']) != 0) {
  54. if ($user_course['Status'] != COURSEMANAGER && $user_course['Status'] != STUDENT) {
  55. $user_course['error'] = get_lang('UnknownStatus');
  56. $errors[] = $user_course;
  57. }
  58. }
  59. }
  60. return $errors;
  61. }
  62. /**
  63. * Saves imported data.
  64. */
  65. function save_data($users_courses)
  66. {
  67. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  68. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  69. $csv_data = array();
  70. $inserted_in_course = array();
  71. foreach ($users_courses as $user_course) {
  72. $csv_data[$user_course['Email']][$user_course['CourseCode']] =
  73. $user_course['Status'];
  74. }
  75. foreach ($csv_data as $email => $csv_subscriptions) {
  76. $sql = "SELECT * FROM $user_table u
  77. WHERE u.email = '".Database::escape_string($email)."' LIMIT 1";
  78. $res = Database::query($sql);
  79. $obj = Database::fetch_object($res);
  80. $user_id = $obj->user_id;
  81. $sql = "SELECT * FROM $course_user_table cu
  82. WHERE cu.user_id = $user_id AND cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." ";
  83. $res = Database::query($sql);
  84. $db_subscriptions = array();
  85. while ($obj = Database::fetch_object($res)) {
  86. $db_subscriptions[$obj->c_id] = $obj->status;
  87. }
  88. $to_subscribe = array_diff(array_keys($csv_subscriptions), array_keys($db_subscriptions));
  89. $to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csv_subscriptions));
  90. if ($_POST['subscribe']) {
  91. foreach ($to_subscribe as $courseId) {
  92. $courseInfo = api_get_course_info_by_id($courseId);
  93. $course_code = $courseInfo['code'];
  94. if (CourseManager :: course_exists($course_code)) {
  95. $course_info = CourseManager::get_course_information($course_code);
  96. $inserted_in_course[$course_code] = $course_info['title'];
  97. CourseManager::subscribe_user(
  98. $user_id,
  99. $course_code,
  100. $csv_subscriptions[$course_code]
  101. );
  102. $inserted_in_course[$course_info['code']] = $course_info['title'];
  103. }
  104. }
  105. }
  106. if ($_POST['unsubscribe']) {
  107. foreach ($to_unsubscribe as $courseId) {
  108. $courseInfo = api_get_course_info_by_id($courseId);
  109. $course_code = $courseInfo['code'];
  110. if (CourseManager :: course_exists($course_code)) {
  111. CourseManager::unsubscribe_user($user_id, $course_code);
  112. $course_info = CourseManager::get_course_information($course_code);
  113. CourseManager::unsubscribe_user($user_id, $course_code);
  114. $inserted_in_course[$course_info['code']] = $course_info['title'];
  115. }
  116. }
  117. }
  118. }
  119. return $inserted_in_course;
  120. }
  121. /**
  122. * Reads CSV-file.
  123. * @param string $file Path to the CSV-file
  124. * @return array All course-information read from the file
  125. */
  126. function parse_csv_data($file)
  127. {
  128. $courses = Import :: csvToArray($file);
  129. return $courses;
  130. }
  131. $cidReset = true;
  132. include '../inc/global.inc.php';
  133. // Setting the section (for the tabs).
  134. $this_section = SECTION_PLATFORM_ADMIN;
  135. // Protecting the admin section.
  136. api_protect_admin_script();
  137. $tool_name = get_lang('AddUsersToACourse').' CSV';
  138. $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
  139. set_time_limit(0);
  140. // Creating the form.
  141. $form = new FormValidator('course_user_import');
  142. $form->addElement('header', '', $tool_name);
  143. $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
  144. $form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
  145. $form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
  146. $form->addButtonImport(get_lang('Import'));
  147. $form->setDefaults(array('subscribe' => '1', 'unsubscribe' => 1));
  148. $errors = array();
  149. if ($form->validate()) {
  150. $users_courses = parse_csv_data($_FILES['import_file']['tmp_name']);
  151. $errors = validate_data($users_courses);
  152. if (count($errors) == 0) {
  153. $inserted_in_course = save_data($users_courses);
  154. // Build the alert message in case there were visual codes subscribed to.
  155. if ($_POST['subscribe']) {
  156. $warn = get_lang('UsersSubscribedToBecauseVisualCode').': ';
  157. } else {
  158. $warn = get_lang('UsersUnsubscribedFromBecauseVisualCode').': ';
  159. }
  160. if (!empty($inserted_in_course)) {
  161. $warn = $warn.' '.get_lang('FileImported');
  162. // The users have been inserted in more than one course.
  163. foreach ($inserted_in_course as $code => $info) {
  164. $warn .= ' '.$info.' ('.$code.') ';
  165. }
  166. } else {
  167. $warn = get_lang('ErrorsWhenImportingFile');
  168. }
  169. Security::clear_token();
  170. $tok = Security::get_token();
  171. header('Location: user_list.php?action=show_message&warn='.urlencode($warn).'&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. Display :: display_error_message($error_message, 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();