course_user_import_by_email.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Framework\Container;
  4. exit;
  5. /**
  6. * This tool allows platform admins to update course-user relations by uploading
  7. * a CSV file
  8. * @package chamilo.admin
  9. */
  10. /**
  11. * Validates the imported data.
  12. */
  13. function validate_data($users_courses)
  14. {
  15. $errors = array();
  16. $coursecodes = array();
  17. foreach ($users_courses as $index => $user_course) {
  18. $user_course['line'] = $index + 1;
  19. // 1. Check whether mandatory fields are set.
  20. $mandatory_fields = array('Email', 'CourseCode', 'Status');
  21. foreach ($mandatory_fields as $key => $field) {
  22. if (!isset($user_course[$field]) || strlen($user_course[$field]) == 0) {
  23. $user_course['error'] = get_lang($field.'Mandatory');
  24. $errors[] = $user_course;
  25. }
  26. }
  27. // 2. Check whether coursecode exists.
  28. if (isset ($user_course['CourseCode']) && strlen($user_course['CourseCode']) != 0) {
  29. // 2.1 Check whethher code has been allready used by this CVS-file.
  30. if (!isset($coursecodes[$user_course['CourseCode']])) {
  31. // 2.1.1 Check whether course with this code exists in the system.
  32. $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
  33. $sql = "SELECT * FROM $course_table
  34. WHERE code = '".Database::escape_string($user_course['CourseCode'])."'";
  35. $res = Database::query($sql);
  36. if (Database::num_rows($res) == 0) {
  37. $user_course['error'] = get_lang('CodeDoesNotExists');
  38. $errors[] = $user_course;
  39. } else {
  40. $coursecodes[$user_course['CourseCode']] = 1;
  41. }
  42. }
  43. }
  44. // 3. Check whether Email exists.
  45. if (isset ($user_course['Email']) && strlen($user_course['Email']) !=
  46. 0) {
  47. $user = api_get_user_info_from_email($user_course['Email']);
  48. if (empty($user)) {
  49. $user_course['error'] = get_lang('UnknownUser');
  50. $errors[] = $user_course;
  51. }
  52. }
  53. // 4. Check whether status is valid.
  54. if (isset ($user_course['Status']) && strlen($user_course['Status']) != 0) {
  55. if ($user_course['Status'] != COURSEMANAGER && $user_course['Status'] != STUDENT) {
  56. $user_course['error'] = get_lang('UnknownStatus');
  57. $errors[] = $user_course;
  58. }
  59. }
  60. }
  61. return $errors;
  62. }
  63. /**
  64. * Saves imported data.
  65. */
  66. function save_data($users_courses)
  67. {
  68. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  69. $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  70. $csv_data = array();
  71. $inserted_in_course = array();
  72. foreach ($users_courses as $user_course) {
  73. $csv_data[$user_course['Email']][$user_course['CourseCode']] =
  74. $user_course['Status'];
  75. }
  76. foreach ($csv_data as $email => $csv_subscriptions) {
  77. $sql = "SELECT * FROM $user_table u
  78. WHERE u.email = '".Database::escape_string($email)."' LIMIT 1";
  79. $res = Database::query($sql);
  80. $obj = Database::fetch_object($res);
  81. $user_id = $obj->user_id;
  82. $sql = "SELECT * FROM $course_user_table cu
  83. WHERE cu.user_id = $user_id AND cu.relation_type <> ".COURSE_RELATION_TYPE_RRHH." ";
  84. $res = Database::query($sql);
  85. $db_subscriptions = array();
  86. while ($obj = Database::fetch_object($res)) {
  87. $db_subscriptions[$obj->c_id] = $obj->status;
  88. }
  89. $to_subscribe = array_diff(array_keys($csv_subscriptions), array_keys($db_subscriptions));
  90. $to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csv_subscriptions));
  91. if ($_POST['subscribe']) {
  92. foreach ($to_subscribe as $courseId) {
  93. $courseInfo = api_get_course_info_by_id($courseId);
  94. $course_code = $courseInfo['code'];
  95. if (CourseManager :: course_exists($course_code)) {
  96. $course_info = CourseManager::get_course_information($course_code);
  97. $inserted_in_course[$course_code] = $course_info['title'];
  98. CourseManager::subscribe_user(
  99. $user_id,
  100. $course_code,
  101. $csv_subscriptions[$course_code]
  102. );
  103. $inserted_in_course[$course_info['code']] = $course_info['title'];
  104. }
  105. }
  106. }
  107. if ($_POST['unsubscribe']) {
  108. foreach ($to_unsubscribe as $courseId) {
  109. $courseInfo = api_get_course_info_by_id($courseId);
  110. $course_code = $courseInfo['code'];
  111. if (CourseManager :: course_exists($course_code)) {
  112. CourseManager::unsubscribe_user($user_id, $course_code);
  113. $course_info = CourseManager::get_course_information($course_code);
  114. CourseManager::unsubscribe_user($user_id, $course_code);
  115. $inserted_in_course[$course_info['code']] = $course_info['title'];
  116. }
  117. }
  118. }
  119. }
  120. return $inserted_in_course;
  121. }
  122. /**
  123. * Reads CSV-file.
  124. * @param string $file Path to the CSV-file
  125. * @return array All course-information read from the file
  126. */
  127. function parse_csv_data($file)
  128. {
  129. $courses = Import :: csvToArray($file);
  130. return $courses;
  131. }
  132. $cidReset = true;
  133. include '../inc/global.inc.php';
  134. // Setting the section (for the tabs).
  135. $this_section = SECTION_PLATFORM_ADMIN;
  136. // Protecting the admin section.
  137. api_protect_admin_script();
  138. $tool_name = get_lang('AddUsersToACourse').' CSV';
  139. $interbreadcrumb[] = array('url' => Container::getRouter()->generate('administration'), '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->addButtonImport(get_lang('Import'));
  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. Display::addFlash(Display::return_message($warn));
  173. header('Location: user_list.php?sec_token='.$tok);
  174. exit();
  175. }
  176. }
  177. // Displaying the header.
  178. Display :: display_header($tool_name);
  179. if (count($errors) != 0) {
  180. $error_message = '<ul>';
  181. foreach ($errors as $index => $error_course) {
  182. $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
  183. $error_message .= $error_course['Code'].' '.$error_course['Title'];
  184. $error_message .= '</li>';
  185. }
  186. $error_message .= '</ul>';
  187. Display :: display_error_message($error_message, false);
  188. }
  189. // Displaying the form.
  190. $form->display();
  191. ?>
  192. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  193. <blockquote>
  194. <pre>
  195. <b>Email</b>;<b>CourseCode</b>;<b>Status</b>
  196. example1@example.org;course01;<?php echo COURSEMANAGER; ?>
  197. example2@example.org;course01;<?php echo STUDENT; ?>
  198. </pre>
  199. <?php
  200. echo COURSEMANAGER.': '.get_lang('Teacher').'<br />';
  201. echo STUDENT.': '.get_lang('Student').'<br />';
  202. ?>
  203. </blockquote>
  204. <?php
  205. Display :: display_footer();