course_import.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This tool allows platform admins to create courses by uploading a CSV file
  5. * Copyright (c) 2005 Bart Mollet <bart.mollet@hogent.be>.
  6. */
  7. /**
  8. * Validates imported data.
  9. *
  10. * @param array $courses
  11. *
  12. * @return array $errors
  13. */
  14. function validate_courses_data($courses)
  15. {
  16. $errors = [];
  17. $coursecodes = [];
  18. foreach ($courses as $index => $course) {
  19. $course['line'] = $index + 1;
  20. // 1. Check whether mandatory fields are set.
  21. $mandatory_fields = ['Code', 'Title', 'CourseCategory'];
  22. foreach ($mandatory_fields as $field) {
  23. if (empty($course[$field])) {
  24. $course['error'] = get_lang($field.'Mandatory');
  25. $errors[] = $course;
  26. }
  27. }
  28. // 2. Check current course code.
  29. if (!empty($course['Code'])) {
  30. // 2.1 Check whether code has been already used by this CVS-file.
  31. if (isset($coursecodes[$course['Code']])) {
  32. $course['error'] = get_lang('A code has been used twice in the file. This is not authorized. Courses codes should be unique.');
  33. $errors[] = $course;
  34. } else {
  35. // 2.2 Check whether course code has been occupied.
  36. $courseInfo = api_get_course_info($course['Code']);
  37. if (!empty($courseInfo)) {
  38. $course['error'] = get_lang('This code exists');
  39. $errors[] = $course;
  40. }
  41. }
  42. $coursecodes[$course['Code']] = 1;
  43. }
  44. // 3. Check whether teacher exists.
  45. $teacherList = getTeacherListInArray($course['Teacher']);
  46. if (!empty($teacherList)) {
  47. foreach ($teacherList as $teacher) {
  48. $teacherInfo = api_get_user_info_from_username($teacher);
  49. if (empty($teacherInfo)) {
  50. $course['error'] = get_lang('Unknown trainer').' ('.$teacher.')';
  51. $errors[] = $course;
  52. }
  53. }
  54. }
  55. if (!empty($course['CourseCategory'])) {
  56. $categoryInfo = CourseCategory::getCategory($course['CourseCategory']);
  57. if (empty($categoryInfo)) {
  58. CourseCategory::addNode(
  59. $course['CourseCategory'],
  60. $course['CourseCategoryName'] ? $course['CourseCategoryName'] : $course['CourseCategory'],
  61. 'TRUE',
  62. null
  63. );
  64. }
  65. } else {
  66. $course['error'] = get_lang('No course category was provided');
  67. $errors[] = $course;
  68. }
  69. }
  70. return $errors;
  71. }
  72. /**
  73. * Get the teacher list.
  74. *
  75. * @param array $teachers
  76. *
  77. * @return array
  78. */
  79. function getTeacherListInArray($teachers)
  80. {
  81. if (!empty($teachers)) {
  82. return explode('|', $teachers);
  83. }
  84. return [];
  85. }
  86. /**
  87. * Saves imported data.
  88. *
  89. * @param array $courses List of courses
  90. */
  91. function save_courses_data($courses)
  92. {
  93. $msg = '';
  94. foreach ($courses as $course) {
  95. $course_language = $course['Language'];
  96. $teachers = getTeacherListInArray($course['Teacher']);
  97. $teacherList = [];
  98. $creatorId = api_get_user_id();
  99. if (!empty($teachers)) {
  100. foreach ($teachers as $teacher) {
  101. $teacherInfo = api_get_user_info_from_username($teacher);
  102. if (!empty($teacherInfo)) {
  103. $teacherList[] = $teacherInfo;
  104. }
  105. }
  106. }
  107. $params = [];
  108. $params['title'] = $course['Title'];
  109. $params['wanted_code'] = $course['Code'];
  110. $params['tutor_name'] = null;
  111. $params['course_category'] = $course['CourseCategory'];
  112. $params['course_language'] = $course_language;
  113. $params['user_id'] = $creatorId;
  114. $addMeAsTeacher = isset($_POST['add_me_as_teacher']) ? $_POST['add_me_as_teacher'] : false;
  115. $params['add_user_as_teacher'] = $addMeAsTeacher;
  116. $courseInfo = CourseManager::create_course($params);
  117. if (!empty($courseInfo)) {
  118. if (!empty($teacherList)) {
  119. foreach ($teacherList as $teacher) {
  120. CourseManager::subscribeUser(
  121. $teacher['user_id'],
  122. $courseInfo['code'],
  123. COURSEMANAGER
  124. );
  125. }
  126. }
  127. $msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$courseInfo['directory'].'/">
  128. '.$courseInfo['title'].'</a> '.get_lang('Created').'<br />';
  129. }
  130. }
  131. if (!empty($msg)) {
  132. echo Display::return_message($msg, 'normal', false);
  133. }
  134. }
  135. /**
  136. * Read the CSV-file.
  137. *
  138. * @param string $file Path to the CSV-file
  139. *
  140. * @return array All course-information read from the file
  141. */
  142. function parse_csv_courses_data($file)
  143. {
  144. $courses = Import::csv_reader($file);
  145. return $courses;
  146. }
  147. $cidReset = true;
  148. require_once __DIR__.'/../inc/global.inc.php';
  149. $this_section = SECTION_PLATFORM_ADMIN;
  150. api_protect_admin_script();
  151. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  152. if (isset($extAuthSource) && is_array($extAuthSource)) {
  153. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  154. }
  155. $tool_name = get_lang('Import courses list').' CSV';
  156. $interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('Administration')];
  157. set_time_limit(0);
  158. Display::display_header($tool_name);
  159. if (isset($_POST['formSent']) && $_POST['formSent']) {
  160. if (empty($_FILES['import_file']['tmp_name'])) {
  161. $error_message = get_lang('The file upload has failed.');
  162. echo Display::return_message($error_message, 'error', false);
  163. } else {
  164. $allowed_file_mimetype = ['csv'];
  165. $ext_import_file = substr($_FILES['import_file']['name'], (strrpos($_FILES['import_file']['name'], '.') + 1));
  166. if (!in_array($ext_import_file, $allowed_file_mimetype)) {
  167. echo Display::return_message(get_lang('You must import a file corresponding to the selected format'), 'error');
  168. } else {
  169. $courses = parse_csv_courses_data($_FILES['import_file']['tmp_name']);
  170. $errors = validate_courses_data($courses);
  171. if (count($errors) == 0) {
  172. save_courses_data($courses);
  173. }
  174. }
  175. }
  176. }
  177. if (isset($errors) && 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 .= get_lang('Course').': '.$error_course['Title'].' ('.$error_course['Code'].')';
  182. $error_message .= '</li>';
  183. }
  184. $error_message .= '</ul>';
  185. echo Display::return_message($error_message, 'error', false);
  186. }
  187. $form = new FormValidator(
  188. 'import',
  189. 'post',
  190. api_get_self(),
  191. null,
  192. ['enctype' => 'multipart/form-data']
  193. );
  194. $form->addHeader($tool_name);
  195. $form->addElement('file', 'import_file', get_lang('CSV file import location'));
  196. $form->addElement('checkbox', 'add_me_as_teacher', null, get_lang('Add me as teacher in the imported courses.'));
  197. $form->addButtonImport(get_lang('Import'), 'save');
  198. $form->addElement('hidden', 'formSent', 1);
  199. $form->display();
  200. ?>
  201. <div style="clear: both;"></div>
  202. <p><?php echo get_lang('The CSV file must look like this').' ('.get_lang('Fields in <strong>bold</strong> are mandatory.').')'; ?> :</p>
  203. <blockquote>
  204. <pre>
  205. <strong>Code</strong>;<strong>Title</strong>;<strong>CourseCategory</strong>;<strong>CourseCategoryName</strong>;Teacher;Language
  206. BIO0015;Biology;BIO;Science;teacher1;english
  207. BIO0016;Maths;MATH;Engineerng;teacher2|teacher3;english
  208. BIO0017;Language;LANG;;;english
  209. </pre>
  210. </blockquote>
  211. <?php
  212. Display::display_footer();