course_import.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 $_configuration;
  16. global $purification_option_for_usernames;
  17. $dbnamelength = strlen($_configuration['db_prefix']);
  18. // Ensure the prefix + database name do not get over 40 characters.
  19. $maxlength = 40 - $dbnamelength;
  20. $errors = array ();
  21. $coursecodes = array ();
  22. foreach ($courses as $index => $course) {
  23. $course['line'] = $index +1;
  24. // 1. Check whether mandatory fields are set.
  25. $mandatory_fields = array ('Code', 'Title', 'CourseCategory', 'Teacher');
  26. foreach ($mandatory_fields as $key => $field) {
  27. if (!isset($course[$field]) || strlen($course[$field]) == 0) {
  28. $course['error'] = get_lang($field.'Mandatory');
  29. $errors[] = $course;
  30. }
  31. }
  32. // 2. Check current course code.
  33. if (isset ($course['Code']) && strlen($course['Code']) != 0) {
  34. // 2.1 Check whether code has been allready used by this CVS-file.
  35. if (isset($coursecodes[$course['Code']])) {
  36. $course['error'] = get_lang('CodeTwiceInFile');
  37. $errors[] = $course;
  38. }
  39. // 2.2 Check course code length.
  40. elseif (api_strlen($course['Code']) > $maxlength) {
  41. $course['error'] = get_lang('Max');
  42. $errors[] = $course;
  43. }
  44. // 2.3 Check whether course code has been occupied.
  45. else {
  46. $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
  47. $sql = "SELECT * FROM $course_table WHERE code = '".Database::escape_string($course['Code'])."'";
  48. $res = Database::query($sql);
  49. if (Database::num_rows($res) > 0) {
  50. $course['error'] = get_lang('CodeExists');
  51. $errors[] = $course;
  52. }
  53. }
  54. $coursecodes[$course['Code']] = 1;
  55. }
  56. /*
  57. // 3. Check whether teacher exists.
  58. if (!UserManager::is_username_empty($course['Teacher'])) {
  59. $teacher = UserManager::purify_username($course['Teacher'], $purification_option_for_usernames);
  60. if (UserManager::is_username_available($teacher)) {
  61. $course['error'] = get_lang('UnknownTeacher').' ('.$teacher.')';
  62. $errors[] = $course;
  63. }
  64. }
  65. */
  66. // 4. Check whether course category exists.
  67. if (isset($course['CourseCategory']) && strlen($course['CourseCategory']) != 0) {
  68. $category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
  69. $sql = "SELECT * FROM $category_table WHERE code = '".Database::escape_string($course['CourseCategory'])."'";
  70. $res = Database::query($sql);
  71. if (Database::num_rows($res) == 0) {
  72. //@todo this is so bad even all lang variables are wrong ...
  73. $course['error'] = get_lang('UnkownCategoryCourseCode').' ('.$course['CourseCategory'].')';
  74. $errors[] = $course;
  75. }
  76. }
  77. }
  78. return $errors;
  79. }
  80. /**
  81. * Saves imported data.
  82. * @param array List of courses
  83. */
  84. function save_data($courses) {
  85. global $purification_option_for_usernames;
  86. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  87. $msg = '';
  88. foreach ($courses as $index => $course) {
  89. $course_language = api_get_valid_language($course['Language']);
  90. $titular = $uidCreator = $username = '';
  91. // Get username from name (firstname lastname).
  92. if (!UserManager::is_username_empty($course['Teacher'])) {
  93. $teacher = UserManager::purify_username($course['Teacher'], $purification_option_for_usernames);
  94. if (UserManager::is_username_available($teacher)) {
  95. $sql = "SELECT username FROM $user_table WHERE ".(api_is_western_name_order(null, $course_language) ? "CONCAT(firstname,' ',lastname)" : "CONCAT(lastname,' ',firstname)")." = '{$course['Teacher']}' LIMIT 1";
  96. $rs = Database::query($sql);
  97. $user = Database::fetch_object($rs);
  98. $username = $user->username;
  99. } else {
  100. $username = $teacher;
  101. }
  102. }
  103. // Get name and uid creator from username.
  104. if (!empty($username)) {
  105. $sql = "SELECT user_id, ".(api_is_western_name_order(null, $course_language) ? "CONCAT(firstname,' ',lastname)" : "CONCAT(lastname,' ',firstname)")." AS name FROM $user_table WHERE username = '".Database::escape_string(UserManager::purify_username($username, $purification_option_for_usernames))."'";
  106. $res = Database::query($sql);
  107. $teacher = Database::fetch_object($res);
  108. $titular = $teacher->name;
  109. $uidCreator = $teacher->user_id;
  110. } else {
  111. $titular = $course['Teacher'];
  112. $uidCreator = 1;
  113. }
  114. $params = array();
  115. $params['title'] = $course['Title'];
  116. $params['wanted_code'] = $course['Code'];
  117. $params['tutor_name'] = $titular;
  118. $params['course_category'] = $course['CourseCategory'];
  119. $params['course_category'] = $course['CourseCategory'];
  120. $params['course_language'] = $course_language;
  121. $params['user_id'] = $uidCreator;
  122. $course_info = CourseManager::create_course($params);
  123. if (!empty($course_info)) {
  124. $msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/">'.$course_info['title'].'</a> '.get_lang('Created').'<br />';
  125. }
  126. }
  127. if (!empty($msg)) {
  128. Display::display_normal_message($msg, false);
  129. }
  130. }
  131. /**
  132. * Read the CSV-file
  133. * @param string $file Path to the CSV-file
  134. * @return array All course-information read from the file
  135. */
  136. function parse_csv_data($file) {
  137. $courses = Import :: csv_to_array($file);
  138. return $courses;
  139. }
  140. $language_file = array('admin', 'registration','create_course', 'document');
  141. $cidReset = true;
  142. require '../inc/global.inc.php';
  143. $this_section = SECTION_PLATFORM_ADMIN;
  144. api_protect_admin_script();
  145. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  146. require_once api_get_path(LIBRARY_PATH).'import.lib.php';
  147. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  148. if (is_array($extAuthSource)) {
  149. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  150. }
  151. $tool_name = get_lang('ImportCourses').' CSV';
  152. $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
  153. set_time_limit(0);
  154. Display :: display_header($tool_name);
  155. if ($_POST['formSent']) {
  156. if (empty($_FILES['import_file']['tmp_name'])) {
  157. $error_message = get_lang('UplUploadFailed');
  158. Display :: display_error_message($error_message, false);
  159. } else {
  160. $allowed_file_mimetype = array('csv');
  161. $ext_import_file = substr($_FILES['import_file']['name'], (strrpos($_FILES['import_file']['name'], '.') + 1));
  162. if (!in_array($ext_import_file, $allowed_file_mimetype)) {
  163. Display :: display_error_message(get_lang('YouMustImportAFileAccordingToSelectedOption'));
  164. } else {
  165. $courses = parse_csv_data($_FILES['import_file']['tmp_name']);
  166. $errors = validate_data($courses);
  167. if (count($errors) == 0) {
  168. save_data($courses);
  169. }
  170. }
  171. }
  172. }
  173. if (count($errors) != 0) {
  174. $error_message = '<ul>';
  175. foreach ($errors as $index => $error_course) {
  176. $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
  177. $error_message .= $error_course['Code'].' '.$error_course['Title'];
  178. $error_message .= '</li>';
  179. }
  180. $error_message .= '</ul>';
  181. Display :: display_error_message($error_message, false);
  182. }
  183. ?>
  184. <form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" style="margin: 0px;">
  185. <div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
  186. <div class="row">
  187. <div class="label"><?php echo get_lang('ImportCSVFileLocation'); ?></div>
  188. <div class="formw">
  189. <input type="file" name="import_file"/>
  190. </div>
  191. </div>
  192. <div class="row">
  193. <div class="label"></div>
  194. <div class="formw">
  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>;<strong>Teacher</strong>;Language
  205. BIO0015;Biology;BIO;username;english
  206. </pre>
  207. </blockquote>
  208. <?php
  209. Display :: display_footer();