course_import.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. $course['error'] = get_lang('UnkownCategoryCourseCode').' ('.$course['CourseCategory'].')';
  73. $errors[] = $course;
  74. }
  75. }
  76. }
  77. return $errors;
  78. }
  79. /**
  80. * Saves imported data.
  81. * @param array List of courses
  82. */
  83. function save_data($courses) {
  84. global $_configuration, $firstExpirationDelay;
  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. $keys = define_course_keys($course['Code'], '', $_configuration['db_prefix']);
  91. $titular = $uidCreator = $username = '';
  92. // Get username from name (firstname lastname).
  93. if (!UserManager::is_username_empty($course['Teacher'])) {
  94. $teacher = UserManager::purify_username($course['Teacher'], $purification_option_for_usernames);
  95. if (UserManager::is_username_available($teacher)) {
  96. $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";
  97. $rs = Database::query($sql);
  98. $user = Database::fetch_object($rs);
  99. $username = $user->username;
  100. } else {
  101. $username = $teacher;
  102. }
  103. }
  104. // Get name and uid creator from username.
  105. if (!empty($username)) {
  106. $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))."'";
  107. $res = Database::query($sql);
  108. $teacher = Database::fetch_object($res);
  109. $titular = $teacher->name;
  110. $uidCreator = $teacher->user_id;
  111. } else {
  112. $titular = $course['Teacher'];
  113. $uidCreator = 1;
  114. }
  115. $visual_code = $keys['currentCourseCode'];
  116. $code = $keys['currentCourseId'];
  117. $db_name = $keys['currentCourseDbName'];
  118. $directory = $keys['currentCourseRepository'];
  119. $expiration_date = time() + $firstExpirationDelay;
  120. prepare_course_repository($directory, $code);
  121. update_Db_course($db_name);
  122. fill_course_repository($directory);
  123. fill_Db_course($db_name, $directory, $course_language, array());
  124. register_course($code, $visual_code, $directory, $db_name, $titular, $course['CourseCategory'], $course['Title'], $course_language, $uidCreator, $expiration_date);
  125. $msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$directory.'/">'.$code.'</a> '.get_lang('Created').'<br />';
  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. require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
  148. require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
  149. require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
  150. require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
  151. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  152. if (is_array($extAuthSource)) {
  153. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  154. }
  155. $tool_name = get_lang('ImportCourses').' CSV';
  156. $interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
  157. set_time_limit(0);
  158. Display :: display_header($tool_name);
  159. if ($_POST['formSent']) {
  160. if (empty($_FILES['import_file']['tmp_name'])) {
  161. $error_message = get_lang('UplUploadFailed');
  162. Display :: display_error_message($error_message, false);
  163. } else {
  164. $allowed_file_mimetype = array('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. Display :: display_error_message(get_lang('YouMustImportAFileAccordingToSelectedOption'));
  168. } else {
  169. $courses = parse_csv_data($_FILES['import_file']['tmp_name']);
  170. $errors = validate_data($courses);
  171. if (count($errors) == 0) {
  172. save_data($courses);
  173. }
  174. }
  175. }
  176. }
  177. if (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 .= $error_course['Code'].' '.$error_course['Title'];
  182. $error_message .= '</li>';
  183. }
  184. $error_message .= '</ul>';
  185. Display :: display_error_message($error_message, false);
  186. }
  187. ?>
  188. <form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" style="margin: 0px;">
  189. <div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
  190. <div class="row">
  191. <div class="label"><?php echo get_lang('ImportCSVFileLocation'); ?></div>
  192. <div class="formw">
  193. <input type="file" name="import_file"/>
  194. </div>
  195. </div>
  196. <div class="row">
  197. <div class="label"></div>
  198. <div class="formw">
  199. <button type="submit" class="save" value="<?php echo get_lang('Import'); ?>"><?php echo get_lang('Import'); ?></button>
  200. </div>
  201. </div>
  202. <input type="hidden" name="formSent" value="1"/>
  203. </form>
  204. <div style="clear: both;"></div>
  205. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  206. <blockquote>
  207. <pre>
  208. <strong>Code</strong>;<strong>Title</strong>;<strong>CourseCategory</strong>;<strong>Teacher</strong>;Language
  209. BIO0015;Biology;BIO;username;english
  210. </pre>
  211. </blockquote>
  212. <?php
  213. Display :: display_footer();