course_import.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php // $Id: course_import.php 8216 2006-03-15 16:33:13Z turboke $
  2. /*
  3. ==============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2008 Dokeos SPRL
  6. Copyright (c) 2005 Bart Mollet <bart.mollet@hogent.be>
  7. For a full list of contributors, see "credits.txt".
  8. The full license can be read in "license.txt".
  9. This program is free software; you can redistribute it and/or
  10. modify it under the terms of the GNU General Public License
  11. as published by the Free Software Foundation; either version 2
  12. of the License, or (at your option) any later version.
  13. See the GNU General Public License for more details.
  14. Contact: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
  15. ==============================================================================
  16. */
  17. /**
  18. ==============================================================================
  19. * This tool allows platform admins to create courses by uploading a CSV file
  20. * @todo Add some langvars to DLTT
  21. * @package dokeos.admin
  22. ==============================================================================
  23. */
  24. /**
  25. * Validates imported data.
  26. */
  27. function validate_data($courses) {
  28. global $_configuration;
  29. global $purification_option_for_usernames;
  30. $dbnamelength = strlen($_configuration['db_prefix']);
  31. //Ensure the prefix + database name do not get over 40 characters
  32. $maxlength = 40 - $dbnamelength;
  33. $errors = array ();
  34. $coursecodes = array ();
  35. foreach ($courses as $index => $course) {
  36. $course['line'] = $index +1;
  37. // 1. Check whether mandatory fields are set.
  38. $mandatory_fields = array ('Code', 'Title', 'CourseCategory', 'Teacher');
  39. foreach ($mandatory_fields as $key => $field) {
  40. if (!isset($course[$field]) || strlen($course[$field]) == 0) {
  41. $course['error'] = get_lang($field.'Mandatory');
  42. $errors[] = $course;
  43. }
  44. }
  45. // 2. Check current course code.
  46. if (isset ($course['Code']) && strlen($course['Code']) != 0) {
  47. // 2.1 Check whether code has been allready used by this CVS-file.
  48. if (isset ($coursecodes[$course['Code']])) {
  49. $course['error'] = get_lang('CodeTwiceInFile');
  50. $errors[] = $course;
  51. }
  52. // 2.2 Check course code length.
  53. elseif (api_strlen($course['Code']) > $maxlength) {
  54. $course['error'] = get_lang('Max');
  55. $errors[] = $course;
  56. }
  57. // 2.3 Check whether course code has been occupied.
  58. else {
  59. $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
  60. $sql = "SELECT * FROM $course_table WHERE code = '".Database::escape_string($course['Code'])."'";
  61. $res = Database::query($sql);
  62. if (Database::num_rows($res) > 0) {
  63. $course['error'] = get_lang('CodeExists');
  64. $errors[] = $course;
  65. }
  66. }
  67. $coursecodes[$course['Code']] = 1;
  68. }
  69. /*
  70. // 3. Check whether teacher exists.
  71. if (!UserManager::is_username_empty($course['Teacher'])) {
  72. $teacher = UserManager::purify_username($course['Teacher'], $purification_option_for_usernames);
  73. if (UserManager::is_username_available($teacher)) {
  74. $course['error'] = get_lang('UnknownTeacher').' ('.$teacher.')';
  75. $errors[] = $course;
  76. }
  77. }
  78. */
  79. // 4. Check whether course category exists.
  80. if (isset ($course['CourseCategory']) && strlen($course['CourseCategory']) != 0) {
  81. $category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
  82. $sql = "SELECT * FROM $category_table WHERE code = '".Database::escape_string($course['CourseCategory'])."'";
  83. $res = Database::query($sql);
  84. if (Database::num_rows($res) == 0) {
  85. $course['error'] = get_lang('UnkownCategory').' ('.$course['CourseCategory'].')';
  86. $errors[] = $course;
  87. }
  88. }
  89. }
  90. return $errors;
  91. }
  92. /**
  93. * Saves imported data.
  94. * @param array List of courses
  95. */
  96. function save_data($courses) {
  97. global $_configuration, $firstExpirationDelay;
  98. global $purification_option_for_usernames;
  99. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  100. $msg = '';
  101. foreach ($courses as $index => $course) {
  102. $course_language = api_get_valid_language($course['Language']);
  103. $keys = define_course_keys($course['Code'], '', $_configuration['db_prefix']);
  104. $titular = $uidCreator = $username = '';
  105. // get username from name (firstname lastname)
  106. if (!UserManager::is_username_empty($course['Teacher'])) {
  107. $teacher = UserManager::purify_username($course['Teacher'], $purification_option_for_usernames);
  108. if (UserManager::is_username_available($teacher)) {
  109. $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";
  110. $rs = Database::query($sql);
  111. $user = Database::fetch_object($rs);
  112. $username = $user->username;
  113. } else {
  114. $username = $teacher;
  115. }
  116. }
  117. // get name and uid creator from username
  118. if (!empty($username)) {
  119. $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))."'";
  120. $res = Database::query($sql);
  121. $teacher = Database::fetch_object($res);
  122. $titular = $teacher->name;
  123. $uidCreator = $teacher->user_id;
  124. } else {
  125. $titular = $course['Teacher'];
  126. $uidCreator = 1;
  127. }
  128. $visual_code = $keys['currentCourseCode'];
  129. $code = $keys['currentCourseId'];
  130. $db_name = $keys['currentCourseDbName'];
  131. $directory = $keys['currentCourseRepository'];
  132. $expiration_date = time() + $firstExpirationDelay;
  133. prepare_course_repository($directory, $code);
  134. update_Db_course($db_name);
  135. fill_course_repository($directory);
  136. fill_Db_course($db_name, $directory, $course_language, array());
  137. register_course($code, $visual_code, $directory, $db_name, $titular, $course['CourseCategory'], $course['Title'], $course_language, $uidCreator, $expiration_date);
  138. $msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$directory.'/">'.$code.'</a> '.get_lang('Created').'<br />';
  139. }
  140. if (!empty($msg)) {
  141. Display::display_normal_message($msg,false);
  142. }
  143. }
  144. /**
  145. * Read the CSV-file
  146. * @param string $file Path to the CSV-file
  147. * @return array All course-information read from the file
  148. */
  149. function parse_csv_data($file) {
  150. $courses = Import :: csv_to_array($file);
  151. return $courses;
  152. }
  153. $language_file = array ('admin', 'registration','create_course', 'document');
  154. $cidReset = true;
  155. include '../inc/global.inc.php';
  156. $this_section = SECTION_PLATFORM_ADMIN;
  157. api_protect_admin_script();
  158. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  159. require_once api_get_path(LIBRARY_PATH).'import.lib.php';
  160. require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
  161. require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
  162. require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
  163. require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
  164. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  165. if (is_array($extAuthSource)) {
  166. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  167. }
  168. $tool_name = get_lang('ImportCourses').' CSV';
  169. $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
  170. set_time_limit(0);
  171. Display :: display_header($tool_name);
  172. if ($_POST['formSent']) {
  173. if (empty($_FILES['import_file']['tmp_name'])) {
  174. $error_message = get_lang('UplUploadFailed');
  175. Display :: display_error_message($error_message, false);
  176. } else {
  177. $file_type = $_POST['file_type'];
  178. $courses = parse_csv_data($_FILES['import_file']['tmp_name']);
  179. $errors = validate_data($courses);
  180. if (count($errors) == 0) {
  181. //$users = complete_missing_data($courses);
  182. save_data($courses);
  183. //header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('FileImported')));
  184. //exit ();
  185. }
  186. }
  187. }
  188. if (count($errors) != 0) {
  189. $error_message = '<ul>';
  190. foreach ($errors as $index => $error_course) {
  191. $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <b>'.$error_course['error'].'</b>: ';
  192. $error_message .= $error_course['Code'].' '.$error_course['Title'];
  193. $error_message .= '</li>';
  194. }
  195. $error_message .= '</ul>';
  196. Display :: display_error_message($error_message, false);
  197. }
  198. ?>
  199. <form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" style="margin:0px;">
  200. <div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
  201. <div class="row">
  202. <div class="label"><?php echo get_lang('ImportCSVFileLocation');?></div>
  203. <div class="formw">
  204. <input type="file" name="import_file"/>
  205. </div>
  206. </div>
  207. <div class="row">
  208. <div class="label"></div>
  209. <div class="formw">
  210. <button type="submit" class="save" value="<?php echo get_lang('Import'); ?>"><?php echo get_lang('Import'); ?></button>
  211. </div>
  212. </div>
  213. <input type="hidden" name="formSent" value="1"/>
  214. </form>
  215. <div style="clear: both;"></div>
  216. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  217. <blockquote>
  218. <pre>
  219. <b>Code</b>;<b>Title</b>;<b>CourseCategory</b>;<b>Teacher</b>;Language
  220. BIO0015;Biology;BIO;username;english
  221. </pre>
  222. </blockquote>
  223. <?php
  224. Display :: display_footer();