course_import.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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, __FILE__, __LINE__);
  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. // 3. Check whether teacher exists.
  70. if (!UserManager::is_username_empty($course['Teacher'])) {
  71. $teacher = UserManager::purify_username($course['Teacher'], $purification_option_for_usernames);
  72. if (UserManager::is_username_available($teacher)) {
  73. $course['error'] = get_lang('UnknownTeacher').' ('.$teacher.')';
  74. $errors[] = $course;
  75. }
  76. }
  77. // 4. Check whether course category exists.
  78. if (isset ($course['CourseCategory']) && strlen($course['CourseCategory']) != 0) {
  79. $category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
  80. $sql = "SELECT * FROM $category_table WHERE code = '".Database::escape_string($course['CourseCategory'])."'";
  81. $res = Database::query($sql, __FILE__, __LINE__);
  82. if (Database::num_rows($res) == 0) {
  83. $course['error'] = get_lang('UnkownCategory').' ('.$course['CourseCategory'].')';
  84. $errors[] = $course;
  85. }
  86. }
  87. }
  88. return $errors;
  89. }
  90. /**
  91. * Saves imported data.
  92. * @param array List of courses
  93. */
  94. function save_data($courses) {
  95. global $_configuration, $firstExpirationDelay;
  96. global $purification_option_for_usernames;
  97. $msg = '';
  98. foreach ($courses as $index => $course) {
  99. $course_language = api_get_valid_language($course['Language']);
  100. $keys = define_course_keys($course['Code'], '', $_configuration['db_prefix']);
  101. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  102. $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($course['Teacher'], $purification_option_for_usernames))."'";
  103. $res = Database::query($sql,__FILE__,__LINE__);
  104. $teacher = Database::fetch_object($res);
  105. $visual_code = $keys['currentCourseCode'];
  106. $code = $keys['currentCourseId'];
  107. $db_name = $keys['currentCourseDbName'];
  108. $directory = $keys['currentCourseRepository'];
  109. $expiration_date = time() + $firstExpirationDelay;
  110. prepare_course_repository($directory, $code);
  111. update_Db_course($db_name);
  112. fill_course_repository($directory);
  113. fill_Db_course($db_name, $directory, $course_language, array());
  114. register_course($code, $visual_code, $directory, $db_name, $teacher->name, $course['CourseCategory'], $course['Title'], $course_language, $teacher->user_id, $expiration_date);
  115. $msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$directory.'/">'.$code.'</a> '.get_lang('Created').'<br />';
  116. }
  117. if (!empty($msg)) {
  118. Display::display_normal_message($msg,false);
  119. }
  120. }
  121. /**
  122. * Read the CSV-file
  123. * @param string $file Path to the CSV-file
  124. * @return array All course-information read from the file
  125. */
  126. function parse_csv_data($file) {
  127. $courses = Import :: csv_to_array($file);
  128. return $courses;
  129. }
  130. $language_file = array ('admin', 'registration','create_course', 'document');
  131. $cidReset = true;
  132. include '../inc/global.inc.php';
  133. $this_section = SECTION_PLATFORM_ADMIN;
  134. api_protect_admin_script();
  135. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  136. require_once api_get_path(LIBRARY_PATH).'import.lib.php';
  137. require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
  138. require_once api_get_path(CONFIGURATION_PATH).'add_course.conf.php';
  139. require_once api_get_path(LIBRARY_PATH).'add_course.lib.inc.php';
  140. require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
  141. $defined_auth_sources[] = PLATFORM_AUTH_SOURCE;
  142. if (is_array($extAuthSource)) {
  143. $defined_auth_sources = array_merge($defined_auth_sources, array_keys($extAuthSource));
  144. }
  145. $tool_name = get_lang('ImportCourses').' CSV';
  146. $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
  147. set_time_limit(0);
  148. Display :: display_header($tool_name);
  149. if ($_POST['formSent']) {
  150. if (empty($_FILES['import_file']['tmp_name'])) {
  151. $error_message = get_lang('UplUploadFailed');
  152. Display :: display_error_message($error_message, false);
  153. } else {
  154. $file_type = $_POST['file_type'];
  155. $courses = parse_csv_data($_FILES['import_file']['tmp_name']);
  156. $errors = validate_data($courses);
  157. if (count($errors) == 0) {
  158. //$users = complete_missing_data($courses);
  159. save_data($courses);
  160. //header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('FileImported')));
  161. //exit ();
  162. }
  163. }
  164. }
  165. if (count($errors) != 0) {
  166. $error_message = '<ul>';
  167. foreach ($errors as $index => $error_course) {
  168. $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <b>'.$error_course['error'].'</b>: ';
  169. $error_message .= $error_course['Code'].' '.$error_course['Title'];
  170. $error_message .= '</li>';
  171. }
  172. $error_message .= '</ul>';
  173. Display :: display_error_message($error_message, false);
  174. }
  175. ?>
  176. <form method="post" action="<?php echo api_get_self(); ?>" enctype="multipart/form-data" style="margin:0px;">
  177. <div class="row"><div class="form_header"><?php echo $tool_name; ?></div></div>
  178. <div class="row">
  179. <div class="label"><?php echo get_lang('ImportCSVFileLocation');?></div>
  180. <div class="formw">
  181. <input type="file" name="import_file"/>
  182. </div>
  183. </div>
  184. <div class="row">
  185. <div class="label"></div>
  186. <div class="formw">
  187. <button type="submit" class="save" value="<?php echo get_lang('Import'); ?>"><?php echo get_lang('Import'); ?></button>
  188. </div>
  189. </div>
  190. <input type="hidden" name="formSent" value="1"/>
  191. </form>
  192. <div style="clear: both;"></div>
  193. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  194. <blockquote>
  195. <pre>
  196. <b>Code</b>;<b>Title</b>;<b>CourseCategory</b>;<b>Teacher</b>;Language
  197. BIO0015;Biology;BIO;username;english
  198. </pre>
  199. </blockquote>
  200. <?php
  201. Display :: display_footer();