course_user_import_by_email.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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->course_code] = $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 $course_code) {
  92. if (CourseManager :: course_exists($course_code)) {
  93. $course_info = CourseManager::get_course_information($course_code);
  94. $inserted_in_course[$course_code] = $course_info['title'];
  95. CourseManager::subscribe_user(
  96. $user_id,
  97. $course_code,
  98. $csv_subscriptions[$course_code]
  99. );
  100. $inserted_in_course[$course_info['code']] = $course_info['title'];
  101. }
  102. }
  103. }
  104. if ($_POST['unsubscribe']) {
  105. foreach ($to_unsubscribe as $course_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 :: csv_to_array($file);
  125. return $courses;
  126. }
  127. // Language files that should be included,
  128. $language_file = array('admin', 'registration');
  129. $cidReset = true;
  130. include '../inc/global.inc.php';
  131. // Setting the section (for the tabs).
  132. $this_section = SECTION_PLATFORM_ADMIN;
  133. // Protecting the admin section.
  134. api_protect_admin_script();
  135. // Including additional libraries.
  136. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  137. require_once api_get_path(LIBRARY_PATH).'import.lib.php';
  138. $tool_name = get_lang('AddUsersToACourse').' CSV';
  139. $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
  140. set_time_limit(0);
  141. // Creating the form.
  142. $form = new FormValidator('course_user_import');
  143. $form->addElement('header', '', $tool_name);
  144. $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
  145. $form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
  146. $form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
  147. $form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
  148. $form->setDefaults(array('subscribe' => '1', 'unsubscribe' => 1));
  149. $errors = array();
  150. if ($form->validate()) {
  151. $users_courses = parse_csv_data($_FILES['import_file']['tmp_name']);
  152. $errors = validate_data($users_courses);
  153. if (count($errors) == 0) {
  154. $inserted_in_course = save_data($users_courses);
  155. // Build the alert message in case there were visual codes subscribed to.
  156. if ($_POST['subscribe']) {
  157. $warn = get_lang('UsersSubscribedToBecauseVisualCode').': ';
  158. } else {
  159. $warn = get_lang('UsersUnsubscribedFromBecauseVisualCode').': ';
  160. }
  161. if (!empty($inserted_in_course)) {
  162. $warn = $warn.' '.get_lang('FileImported');
  163. // The users have been inserted in more than one course.
  164. foreach ($inserted_in_course as $code => $info) {
  165. $warn .= ' '.$info.' ('.$code.') ';
  166. }
  167. } else {
  168. $warn = get_lang('ErrorsWhenImportingFile');
  169. }
  170. Security::clear_token();
  171. $tok = Security::get_token();
  172. header('Location: user_list.php?action=show_message&warn='.urlencode($warn).'&sec_token='.$tok);
  173. exit();
  174. }
  175. }
  176. // Displaying the header.
  177. Display :: display_header($tool_name);
  178. if (count($errors) != 0) {
  179. $error_message = '<ul>';
  180. foreach ($errors as $index => $error_course) {
  181. $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
  182. $error_message .= $error_course['Code'].' '.$error_course['Title'];
  183. $error_message .= '</li>';
  184. }
  185. $error_message .= '</ul>';
  186. Display :: display_error_message($error_message, false);
  187. }
  188. // Displaying the form.
  189. $form->display();
  190. ?>
  191. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  192. <blockquote>
  193. <pre>
  194. <b>Email</b>;<b>CourseCode</b>;<b>Status</b>
  195. example1@example.org;course01;<?php echo COURSEMANAGER; ?>
  196. example2@example.org;course01;<?php echo STUDENT; ?>
  197. </pre>
  198. <?php
  199. echo COURSEMANAGER.': '.get_lang('Teacher').'<br />';
  200. echo STUDENT.': '.get_lang('Student').'<br />';
  201. ?>
  202. </blockquote>
  203. <?php
  204. Display :: display_footer();