course_user_import_by_email.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. *
  8. * @package chamilo.admin
  9. */
  10. /**
  11. * Validates the imported data.
  12. */
  13. function validate_data($users_courses)
  14. {
  15. $errors = [];
  16. $coursecodes = [];
  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 = ['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('This code does not exist');
  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']) != 0) {
  46. $user = api_get_user_info_from_email($user_course['Email']);
  47. if (empty($user)) {
  48. $user_course['error'] = get_lang('Unknown user');
  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('Unknown status');
  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 = [];
  70. $inserted_in_course = [];
  71. foreach ($users_courses as $user_course) {
  72. $csv_data[$user_course['Email']][$user_course['CourseCode']] = $user_course['Status'];
  73. }
  74. foreach ($csv_data as $email => $csv_subscriptions) {
  75. $sql = "SELECT * FROM $user_table u
  76. WHERE u.email = '".Database::escape_string($email)."'
  77. 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 = [];
  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 (isset($_POST['subscribe']) && $_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 = api_get_course_info($course_code);
  96. $inserted_in_course[$course_code] = $course_info['title'];
  97. CourseManager::subscribeUser(
  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 (isset($_POST['unsubscribe']) && $_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 = api_get_course_info($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. *
  124. * @param string $file Path to the CSV-file
  125. *
  126. * @return array All course-information read from the file
  127. */
  128. function parse_csv_data($file)
  129. {
  130. $courses = Import::csv_reader($file);
  131. return $courses;
  132. }
  133. $cidReset = true;
  134. require_once __DIR__.'/../inc/global.inc.php';
  135. // Setting the section (for the tabs).
  136. $this_section = SECTION_PLATFORM_ADMIN;
  137. // Protecting the admin section.
  138. api_protect_admin_script();
  139. $tool_name = get_lang('Add users to course').' CSV';
  140. $interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('Administration')];
  141. set_time_limit(0);
  142. // Creating the form.
  143. $form = new FormValidator('course_user_import');
  144. $form->addElement('header', '', $tool_name);
  145. $form->addElement('file', 'import_file', get_lang('Import marks in an assessment'));
  146. $form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('Add user in the course only if not yet in'));
  147. $form->addElement('checkbox', 'unsubscribe', '', get_lang('Remove user from course if his name is not in the list'));
  148. $form->addButtonImport(get_lang('Import'));
  149. $form->setDefaults(['subscribe' => '1', 'unsubscribe' => 1]);
  150. $errors = [];
  151. if ($form->validate()) {
  152. $users_courses = parse_csv_data($_FILES['import_file']['tmp_name']);
  153. $errors = validate_data($users_courses);
  154. if (count($errors) == 0) {
  155. $inserted_in_course = save_data($users_courses);
  156. // Build the alert message in case there were visual codes subscribed to.
  157. if ($_POST['subscribe']) {
  158. $warn = get_lang('The users have been subscribed to the following courses because several courses share the same visual code').': ';
  159. } else {
  160. $warn = get_lang('The users have been unsubscribed from the following courses because several courses share the same visual code').': ';
  161. }
  162. if (!empty($inserted_in_course)) {
  163. $warn = $warn.' '.get_lang('File imported');
  164. // The users have been inserted in more than one course.
  165. foreach ($inserted_in_course as $code => $info) {
  166. $warn .= ' '.$info.' ('.$code.') ';
  167. }
  168. } else {
  169. $warn = get_lang('Errors when importing file');
  170. }
  171. Security::clear_token();
  172. $tok = Security::get_token();
  173. Display::addFlash(Display::return_message($warn));
  174. header('Location: user_list.php?sec_token='.$tok);
  175. exit();
  176. }
  177. }
  178. // Displaying the header.
  179. Display::display_header($tool_name);
  180. if (count($errors) != 0) {
  181. $error_message = '<ul>';
  182. foreach ($errors as $index => $error_course) {
  183. $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
  184. $error_message .= $error_course['Code'].' '.$error_course['Title'];
  185. $error_message .= '</li>';
  186. }
  187. $error_message .= '</ul>';
  188. echo Display::return_message($error_message, 'error', false);
  189. }
  190. // Displaying the form.
  191. $form->display();
  192. ?>
  193. <p><?php echo get_lang('The CSV file must look like this').' ('.get_lang('Fields in <strong>bold</strong> are mandatory.').')'; ?> :</p>
  194. <blockquote>
  195. <pre>
  196. <b>Email</b>;<b>CourseCode</b>;<b>Status</b>
  197. example1@example.org;course01;<?php echo COURSEMANAGER; ?>
  198. example2@example.org;course01;<?php echo STUDENT; ?>
  199. </pre>
  200. <?php
  201. echo COURSEMANAGER.': '.get_lang('Trainer').'<br />';
  202. echo STUDENT.': '.get_lang('Learner').'<br />';
  203. ?>
  204. </blockquote>
  205. <?php
  206. Display::display_footer();