course_import.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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) 2010 Chamilo Association
  6. * Copyright (c) 2008 Dokeos SPRL
  7. * Copyright (c) 2005 Bart Mollet <bart.mollet@hogent.be>
  8. * @todo Add some language variables to Chamilo Translation Application
  9. * @package chamilo.admin
  10. */
  11. /**
  12. * Validates imported data.
  13. */
  14. function validate_data($courses) {
  15. global $purification_option_for_usernames;
  16. // Ensure the prefix + database name do not get over 40 characters.
  17. $maxlength = 40;
  18. $errors = array ();
  19. $coursecodes = array ();
  20. foreach ($courses as $index => $course) {
  21. $course['line'] = $index +1;
  22. // 1. Check whether mandatory fields are set.
  23. $mandatory_fields = array ('Code', 'Title', 'CourseCategory', 'Teacher');
  24. foreach ($mandatory_fields as $key => $field) {
  25. if (!isset($course[$field]) || strlen($course[$field]) == 0) {
  26. $course['error'] = get_lang($field.'Mandatory');
  27. $errors[] = $course;
  28. }
  29. }
  30. // 2. Check current course code.
  31. if (isset ($course['Code']) && strlen($course['Code']) != 0) {
  32. // 2.1 Check whether code has been allready used by this CVS-file.
  33. if (isset($coursecodes[$course['Code']])) {
  34. $course['error'] = get_lang('CodeTwiceInFile');
  35. $errors[] = $course;
  36. }
  37. // 2.2 Check course code length.
  38. elseif (api_strlen($course['Code']) > $maxlength) {
  39. $course['error'] = get_lang('Max');
  40. $errors[] = $course;
  41. }
  42. // 2.3 Check whether course code has been occupied.
  43. else {
  44. $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
  45. $sql = "SELECT * FROM $course_table WHERE code = '".Database::escape_string($course['Code'])."'";
  46. $res = Database::query($sql);
  47. if (Database::num_rows($res) > 0) {
  48. $course['error'] = get_lang('CodeExists');
  49. $errors[] = $course;
  50. }
  51. }
  52. $coursecodes[$course['Code']] = 1;
  53. }
  54. // 3. Check whether teacher exists.
  55. $teacherList = getTeacherListInArray($course['Teacher']);
  56. if (!empty($teacherList)) {
  57. foreach ($teacherList as $teacher) {
  58. $teacherInfo = api_get_user_info_from_username($teacher);
  59. if (empty($teacherInfo)) {
  60. $course['error'] = get_lang('UnknownTeacher').' ('.$teacher.')';
  61. $errors[] = $course;
  62. } else {
  63. if ($teacherInfo['status'] != COURSEMANAGER) {
  64. $course['error'] = get_lang('UserIsNotATeacher').' ('.$teacher.')';
  65. $errors[] = $course;
  66. }
  67. }
  68. }
  69. }
  70. // 4. Check whether course category exists.
  71. if (isset($course['CourseCategory']) && strlen($course['CourseCategory']) != 0) {
  72. $category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
  73. $sql = "SELECT * FROM $category_table WHERE code = '".Database::escape_string($course['CourseCategory'])."'";
  74. $res = Database::query($sql);
  75. if (Database::num_rows($res) == 0) {
  76. //@todo this is so bad even all lang variables are wrong ...
  77. $course['error'] = get_lang('UnkownCategoryCourseCode').' ('.$course['CourseCategory'].')';
  78. $errors[] = $course;
  79. }
  80. }
  81. }
  82. return $errors;
  83. }
  84. function getTeacherListInArray($teachers)
  85. {
  86. if (!empty($teachers)) {
  87. return explode('|', $teachers);
  88. }
  89. return array();
  90. }
  91. /**
  92. * Saves imported data.
  93. * @param array List of courses
  94. */
  95. function save_data($courses) {
  96. global $purification_option_for_usernames;
  97. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  98. $msg = '';
  99. foreach ($courses as $index => $course) {
  100. $course_language = api_get_valid_language($course['Language']);
  101. $username = '';
  102. $teachers = getTeacherListInArray($course['Teacher']);
  103. $teacherList = array();
  104. $creatorId = api_get_user_id();
  105. if (!empty($teachers)) {
  106. foreach ($teachers as $teacher) {
  107. $teacherInfo = api_get_user_info_from_username($teacher);
  108. if (!empty($teacherInfo)) {
  109. $teacherList[] = $teacherInfo;
  110. }
  111. }
  112. }
  113. $params = array();
  114. $params['title'] = $course['Title'];
  115. $params['wanted_code'] = $course['Code'];
  116. $params['tutor_name'] = null;
  117. $params['course_category'] = $course['CourseCategory'];
  118. $params['course_language'] = $course_language;
  119. $params['user_id'] = $creatorId;
  120. $course_info = CourseManager::create_course($params);
  121. if (!empty($course_info)) {
  122. if (!empty($teacherList)) {
  123. foreach ($teacherList as $teacher) {
  124. CourseManager::add_user_to_course($teacher['user_id'], $course_info['code'], COURSEMANAGER);
  125. }
  126. }
  127. $msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/">
  128. '.$course_info['title'].'</a> '.get_lang('Created').'<br />';
  129. }
  130. }
  131. if (!empty($msg)) {
  132. Display::display_normal_message($msg, false);
  133. }
  134. }
  135. /**
  136. * Read the CSV-file
  137. * @param string $file Path to the CSV-file
  138. * @return array All course-information read from the file
  139. */
  140. function parse_csv_data($file) {
  141. $courses = Import :: csv_to_array($file);
  142. return $courses;
  143. }
  144. $language_file = array('admin', 'registration','create_course', 'document');
  145. $cidReset = true;
  146. $this_section = SECTION_PLATFORM_ADMIN;
  147. api_protect_admin_script();
  148. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  149. if (isset($extAuthSource) && is_array($extAuthSource)) {
  150. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  151. }
  152. $tool_name = get_lang('ImportCourses').' CSV';
  153. $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
  154. set_time_limit(0);
  155. Display :: display_header($tool_name);
  156. if (isset($_POST['formSent']) && $_POST['formSent']) {
  157. if (empty($_FILES['import_file']['tmp_name'])) {
  158. $error_message = get_lang('UplUploadFailed');
  159. Display :: display_error_message($error_message, false);
  160. } else {
  161. $allowed_file_mimetype = array('csv');
  162. $ext_import_file = substr($_FILES['import_file']['name'], (strrpos($_FILES['import_file']['name'], '.') + 1));
  163. if (!in_array($ext_import_file, $allowed_file_mimetype)) {
  164. Display :: display_error_message(get_lang('YouMustImportAFileAccordingToSelectedOption'));
  165. } else {
  166. $courses = parse_csv_data($_FILES['import_file']['tmp_name']);
  167. $errors = validate_data($courses);
  168. if (count($errors) == 0) {
  169. save_data($courses);
  170. }
  171. }
  172. }
  173. }
  174. if (isset($errors) && count($errors) != 0) {
  175. $error_message = '<ul>';
  176. foreach ($errors as $index => $error_course) {
  177. $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
  178. $error_message .= get_lang('Course').': '.$error_course['Title'].' ('.$error_course['Code'].')';
  179. $error_message .= '</li>';
  180. }
  181. $error_message .= '</ul>';
  182. Display :: display_error_message($error_message, false);
  183. }
  184. ?>
  185. <form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" style="margin: 0px;">
  186. <legend><?php echo $tool_name; ?></legend>
  187. <div class="control-group">
  188. <label><?php echo get_lang('ImportCSVFileLocation'); ?></label>
  189. <div class="control">
  190. <input type="file" name="import_file"/>
  191. </div>
  192. </div>
  193. <div class="control-group">
  194. <div class="control">
  195. <button type="submit" class="save" value="<?php echo get_lang('Import'); ?>"><?php echo get_lang('Import'); ?></button>
  196. </div>
  197. </div>
  198. <input type="hidden" name="formSent" value="1"/>
  199. </form>
  200. <div style="clear: both;"></div>
  201. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  202. <blockquote>
  203. <pre>
  204. <strong>Code</strong>;<strong>Title</strong>;<strong>CourseCategory</strong>;Teacher;Language
  205. BIO0015;Biology;BIO;teacher1;english
  206. BIO0016;Maths;MATH;teacher2|teacher3;english
  207. BIO0017;Language;LANG;;english
  208. </pre>
  209. </blockquote>
  210. <?php
  211. Display :: display_footer();