course_user_import.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. <?php // $Id: course_user_import.php 8216 2006-03-15 16:33:13Z turboke $
  2. /* For licensing terms, see /dokeos_license.txt */
  3. /**
  4. ==============================================================================
  5. * This tool allows platform admins to update course-user relations by uploading
  6. * a CSVfile
  7. * @package dokeos.admin
  8. ==============================================================================
  9. */
  10. /**
  11. * validate the imported data
  12. */
  13. function validate_data($users_courses)
  14. {
  15. $errors = array ();
  16. $coursecodes = array ();
  17. foreach ($users_courses as $index => $user_course)
  18. {
  19. $user_course['line'] = $index +1;
  20. //1. check if mandatory fields are set
  21. $mandatory_fields = array ('UserName', 'CourseCode', 'Status');
  22. foreach ($mandatory_fields as $key => $field)
  23. {
  24. if (!isset ($user_course[$field]) || strlen($user_course[$field]) == 0)
  25. {
  26. $user_course['error'] = get_lang($field.'Mandatory');
  27. $errors[] = $user_course;
  28. }
  29. }
  30. //2. check if coursecode exists
  31. if (isset ($user_course['CourseCode']) && strlen($user_course['CourseCode']) != 0)
  32. {
  33. //2.1 check if code allready used in this CVS-file
  34. if (!isset ($coursecodes[$user_course['CourseCode']]))
  35. {
  36. //2.1.1 check if code exists in DB
  37. $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
  38. $sql = "SELECT * FROM $course_table WHERE code = '".mysql_real_escape_string($user_course['CourseCode'])."'";
  39. $res = api_sql_query($sql, __FILE__, __LINE__);
  40. if (mysql_num_rows($res) == 0)
  41. {
  42. $user_course['error'] = get_lang('CodeDoesNotExists');
  43. $errors[] = $user_course;
  44. }
  45. else
  46. {
  47. $coursecodes[$user_course['CourseCode']] = 1;
  48. }
  49. }
  50. }
  51. //3. check if username exists
  52. if (isset ($user_course['UserName']) && strlen($user_course['UserName']) != 0)
  53. {
  54. if (UserManager :: is_username_available($user_course['UserName']))
  55. {
  56. $user_course['error'] = get_lang('UnknownUser');
  57. $errors[] = $user_course;
  58. }
  59. }
  60. //4. check if status is valid
  61. if (isset ($user_course['Status']) && strlen($user_course['Status']) != 0)
  62. {
  63. if ($user_course['Status'] != COURSEMANAGER && $user_course['Status'] != STUDENT)
  64. {
  65. $user_course['error'] = get_lang('UnknownStatus');
  66. $errors[] = $user_course;
  67. }
  68. }
  69. }
  70. return $errors;
  71. }
  72. /**
  73. * Save the imported data
  74. */
  75. function save_data($users_courses) {
  76. $user_table= Database::get_main_table(TABLE_MAIN_USER);
  77. $course_user_table= Database::get_main_table(TABLE_MAIN_COURSE_USER);
  78. $csv_data = array();
  79. foreach ($users_courses as $index => $user_course) {
  80. $csv_data[$user_course['UserName']][$user_course['CourseCode']] = $user_course['Status'];
  81. }
  82. foreach($csv_data as $username => $csv_subscriptions) {
  83. $user_id = 0;
  84. $sql = "SELECT * FROM $user_table u WHERE u.username = '".mysql_real_escape_string($username)."'";
  85. $res = api_sql_query($sql,__FILE__,__LINE__);
  86. $obj = mysql_fetch_object($res);
  87. $user_id = $obj->user_id;
  88. $sql = "SELECT * FROM $course_user_table cu WHERE cu.user_id = $user_id";
  89. $res = api_sql_query($sql,__FILE__,__LINE__);
  90. $db_subscriptions = array();
  91. while($obj = Database::fetch_object($res)) {
  92. $db_subscriptions[$obj->course_code] = $obj->status;
  93. }
  94. //echo '<b>User '.$username.'</b><br />';
  95. $to_subscribe = array_diff(array_keys($csv_subscriptions),array_keys($db_subscriptions));
  96. $to_unsubscribe = array_diff(array_keys($db_subscriptions),array_keys($csv_subscriptions));
  97. // echo '<pre>';
  98. // echo "CSV SUBSCRIPTION\n";
  99. // print_r($csv_subscriptions);
  100. // echo "DB SUBSCRIPTION\n";
  101. // print_r($db_subscriptions);
  102. // echo "TO SUBSCRIBE\n";
  103. // print_r($to_subscribe);
  104. // echo "TO UNSUBSCRIBE\n";
  105. // print_r($to_unsubscribe);
  106. // echo '</pre>';
  107. global $inserted_in_course;
  108. if (!isset($inserted_in_course)) { $inserted_in_course = array(); }
  109. if($_POST['subscribe']) {
  110. foreach($to_subscribe as $index => $course_code) {
  111. if(CourseManager :: course_exists($course_code)) {
  112. CourseManager::add_user_to_course($user_id,$course_code,$csv_subscriptions[$course_code]);
  113. $c_info = CourseManager::get_course_information($course_code);
  114. $inserted_in_course[$course_code] = $c_info['title'];
  115. }
  116. if (CourseManager :: course_exists($course_code,true)) {
  117. // also subscribe to virtual courses through check on visual code
  118. $list = CourseManager :: get_courses_info_from_visual_code($course_code);
  119. foreach ($list as $vcourse) {
  120. if ($vcourse['code'] == $course_code) {
  121. //ignore, this has already been inserted
  122. } else {
  123. CourseManager::add_user_to_course($user_id,$vcourse['code'],$csv_subscriptions[$course_code]);
  124. $inserted_in_course[$vcourse['code']] = $vcourse['title'];
  125. }
  126. }
  127. }
  128. //echo get_lang('Subscription').' : '.$course_code.'<br />';
  129. }
  130. }
  131. if($_POST['unsubscribe']) {
  132. foreach($to_unsubscribe as $index => $course_code) {
  133. if(CourseManager :: course_exists($course_code)) {
  134. CourseManager::unsubscribe_user($user_id,$course_code);
  135. $c_info = CourseManager::get_course_information($course_code);
  136. $inserted_in_course[$course_code] = $c_info['title'];
  137. }
  138. if (CourseManager :: course_exists($course_code,true)) {
  139. // also subscribe to virtual courses through check on visual code
  140. $list = CourseManager :: get_courses_info_from_visual_code($course_code);
  141. foreach ($list as $vcourse) {
  142. if ($vcourse['code'] == $course_code) {
  143. //ignore, this has already been inserted
  144. } else {
  145. CourseManager::unsubscribe_user($user_id,$vcourse['code']);
  146. $inserted_in_course[$vcourse['code']] = $vcourse['title'];
  147. }
  148. }
  149. }
  150. //echo get_lang('Unsubscription').' : '.$course_code.'<br />';
  151. }
  152. }
  153. }
  154. }
  155. /**
  156. * Read the CSV-file
  157. * @param string $file Path to the CSV-file
  158. * @return array All course-information read from the file
  159. */
  160. function parse_csv_data($file) {
  161. $courses = Import :: csv_to_array($file);
  162. return $courses;
  163. }
  164. // name of the language file that needs to be included
  165. $language_file = array ('admin', 'registration');
  166. $cidReset = true;
  167. // including the global Dokeos file
  168. include ('../inc/global.inc.php');
  169. // protecting the admin section
  170. api_protect_admin_script();
  171. // including additional libraries
  172. require_once (api_get_path(LIBRARY_PATH).'fileManage.lib.php');
  173. require_once (api_get_path(LIBRARY_PATH).'import.lib.php');
  174. require_once (api_get_path(LIBRARY_PATH).'usermanager.lib.php');
  175. require_once (api_get_path(LIBRARY_PATH).'course.lib.php');
  176. require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
  177. $formSent = 0;
  178. $errorMsg = '';
  179. $tool_name = get_lang('AddUsersToACourse').' CSV';
  180. $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
  181. set_time_limit(0);
  182. // creating the form
  183. $form = new FormValidator('course_user_import');
  184. $form->addElement('header', '', $tool_name);
  185. $form->addElement('file','import_file', get_lang('ImportFileLocation'));
  186. $form->addElement('checkbox','subscribe',get_lang('Action'),get_lang('SubscribeUserIfNotAllreadySubscribed'));
  187. $form->addElement('checkbox','unsubscribe','',get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
  188. $form->addElement('style_submit_button', 'submit',get_lang('Import'),'class="save"');
  189. if ($form->validate()) {
  190. $users_courses = parse_csv_data($_FILES['import_file']['tmp_name']);
  191. $errors = validate_data($users_courses);
  192. if (count($errors) == 0) {
  193. $inserted_in_course = array();
  194. save_data($users_courses);
  195. // Build the alert message in case there were visual codes subscribed to
  196. if ($_POST['subscribe']) {
  197. $warn = get_lang('UsersSubscribedToBecauseVisualCode').': ';
  198. } else {
  199. $warn = get_lang('UsersUnsubscribedFromBecauseVisualCode').': ';
  200. }
  201. if (count($inserted_in_course) > 1) {
  202. // The users have been inserted in more than one course
  203. foreach ($inserted_in_course as $code => $info) {
  204. $warn .= ' '.$info.' ('.$code.'),';
  205. }
  206. $warn = substr($warn,0,-1);
  207. }
  208. Security::clear_token();
  209. $tok = Security::get_token();
  210. header('Location: user_list.php?action=show_message&message='.urlencode(get_lang('FileImported')).'&warn='.urlencode($warn).'&sec_token='.$tok);
  211. exit ();
  212. }
  213. }
  214. // displaying the header
  215. Display :: display_header($tool_name);
  216. // displaying the tool title
  217. // api_display_tool_title($tool_name);
  218. if (count($errors) != 0) {
  219. $error_message = '<ul>';
  220. foreach ($errors as $index => $error_course) {
  221. $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <b>'.$error_course['error'].'</b>: ';
  222. $error_message .= $error_course['Code'].' '.$error_course['Title'];
  223. $error_message .= '</li>';
  224. }
  225. $error_message .= '</ul>';
  226. Display :: display_error_message($error_message);
  227. }
  228. // displaying the form
  229. $form->display();
  230. ?>
  231. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  232. <blockquote>
  233. <pre>
  234. <b>UserName</b>;<b>CourseCode</b>;<b>Status</b>
  235. jdoe;course01;<?php echo COURSEMANAGER; ?>
  236. a.dam;course01;<?php echo STUDENT; ?>
  237. </pre>
  238. <?php
  239. echo COURSEMANAGER.': '.get_lang('Teacher').'<br />';
  240. echo STUDENT.': '.get_lang('Student').'<br />';
  241. ?>
  242. </blockquote>
  243. <?php
  244. // footer
  245. Display :: display_footer();
  246. ?>