course_import.php 7.5 KB

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