class_user_import.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. <?php
  2. // $Id: class_user_import.php 9018 2006-06-28 15:11:16Z evie_em $
  3. /*
  4. ==============================================================================
  5. Dokeos - elearning and course management software
  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, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
  15. ==============================================================================
  16. */
  17. /**
  18. ==============================================================================
  19. * This tool allows platform admins to update class-user relations by uploading
  20. * a CSVfile
  21. * @package dokeos.admin
  22. ==============================================================================
  23. */
  24. /**
  25. * Validates imported data.
  26. */
  27. function validate_data($user_classes) {
  28. global $purification_option_for_usernames;
  29. $errors = array ();
  30. $classcodes = array ();
  31. foreach ($user_classes as $index => $user_class) {
  32. $user_class['line'] = $index + 1;
  33. // 1. Check whether mandatory fields are set.
  34. $mandatory_fields = array ('UserName', 'ClassName');
  35. foreach ($mandatory_fields as $key => $field) {
  36. if (!isset ($user_class[$field]) || strlen($user_class[$field]) == 0) {
  37. $user_class['error'] = get_lang($field.'Mandatory');
  38. $errors[] = $user_class;
  39. }
  40. }
  41. // 2. Check whether classcode exists.
  42. if (isset ($user_class['ClassName']) && strlen($user_class['ClassName']) != 0) {
  43. // 2.1 Check whether code has been allready used in this CVS-file.
  44. if (!isset ($classcodes[$user_class['ClassName']])) {
  45. // 2.1.1 Check whether code exists in DB.
  46. $class_table = Database :: get_main_table(TABLE_MAIN_CLASS);
  47. $sql = "SELECT * FROM $class_table WHERE name = '".Database::escape_string($user_class['ClassName'])."'";
  48. $res = Database::query($sql, __FILE__, __LINE__);
  49. if (Database::num_rows($res) == 0) {
  50. $user_class['error'] = get_lang('CodeDoesNotExists');
  51. $errors[] = $user_class;
  52. } else {
  53. $classcodes[$user_class['CourseCode']] = 1;
  54. }
  55. }
  56. }
  57. // 3. Check username, first, check whether it is empty.
  58. if (!UserManager::is_username_empty($user_class['UserName'])) {
  59. // 3.1. Check whether username is too long.
  60. if (UserManager::is_username_too_long($user_class['UserName'])) {
  61. $user_class['error'] = get_lang('UserNameTooLong').': '.$user_class['UserName'];
  62. $errors[] = $user_class;
  63. }
  64. $username = UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames);
  65. // 3.2. Check whether username exists.
  66. if (UserManager::is_username_available($username)) {
  67. $user_class['error'] = get_lang('UnknownUser').': '.$username;
  68. $errors[] = $user_class;
  69. }
  70. }
  71. }
  72. return $errors;
  73. }
  74. /**
  75. * Saves imported data.
  76. */
  77. function save_data($users_classes) {
  78. global $purification_option_for_usernames;
  79. // Table definitions.
  80. $user_table = Database :: get_main_table(TABLE_MAIN_USER);
  81. $class_user_table = Database :: get_main_table(TABLE_MAIN_CLASS_USER);
  82. $class_table = Database :: get_main_table(TABLE_MAIN_CLASS);
  83. // Data parsing: purification + conversion (UserName, ClassName) --> (user_is, class_id)
  84. $csv_data = array ();
  85. foreach ($users_classes as $index => $user_class) {
  86. $sql1 = "SELECT user_id FROM $user_table WHERE username = '".Database::escape_string(UserManager::purify_username($user_class['UserName'], $purification_option_for_usernames))."'";
  87. $res1 = Database::query($sql1, __FILE__, __LINE__);
  88. $obj1 = Database::fetch_object($res1);
  89. $sql2 = "SELECT id FROM $class_table WHERE name = '".Database::escape_string(trim($user_class['ClassName']))."'";
  90. $res2 = Database::query($sql2, __FILE__, __LINE__);
  91. $obj2 = Database::fetch_object($res2);
  92. if ($obj1 && $obj2) {
  93. $csv_data[$obj1->user_id][$obj2->id] = 1;
  94. }
  95. }
  96. // Logic for processing the request (data + UI options).
  97. $db_subscriptions = array();
  98. foreach ($csv_data as $user_id => $csv_subscriptions) {
  99. $sql = "SELECT class_id FROM $class_user_table cu WHERE cu.user_id = $user_id";
  100. $res = Database::query($sql, __FILE__, __LINE__);
  101. while ($obj = Database::fetch_object($res)) {
  102. $db_subscriptions[$obj->class_id] = 1;
  103. }
  104. $to_subscribe = array_diff(array_keys($csv_subscriptions), array_keys($db_subscriptions));
  105. $to_unsubscribe = array_diff(array_keys($db_subscriptions), array_keys($csv_subscriptions));
  106. // Subscriptions for new classes.
  107. if ($_POST['subscribe']) {
  108. foreach ($to_subscribe as $class_id) {
  109. ClassManager::add_user($user_id, $class_id);
  110. }
  111. }
  112. // Unsubscription from previous classes.
  113. if ($_POST['unsubscribe']) {
  114. foreach ($to_unsubscribe as $class_id) {
  115. ClassManager::unsubscribe_user($user_id, $class_id);
  116. }
  117. }
  118. }
  119. }
  120. /**
  121. * Reads a CSV-file.
  122. * @param string $file Path to the CSV-file
  123. * @return array All course-information read from the file
  124. */
  125. function parse_csv_data($file) {
  126. $courses = Import::csv_to_array($file);
  127. return $courses;
  128. }
  129. $language_file = array('admin', 'registration');
  130. $cidReset = true;
  131. include '../inc/global.inc.php';
  132. $this_section = SECTION_PLATFORM_ADMIN;
  133. api_protect_admin_script(true);
  134. require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
  135. require_once api_get_path(LIBRARY_PATH).'import.lib.php';
  136. require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
  137. require_once api_get_path(LIBRARY_PATH).'classmanager.lib.php';
  138. require_once api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php';
  139. $tool_name = get_lang('AddUsersToAClass').' CSV';
  140. $interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
  141. // Set this option to true to enforce strict purification for usenames.
  142. $purification_option_for_usernames = false;
  143. set_time_limit(0);
  144. $form = new FormValidator('class_user_import');
  145. $form->addElement('file', 'import_file', get_lang('ImportFileLocation'));
  146. $form->addElement('checkbox', 'subscribe', get_lang('Action'), get_lang('SubscribeUserIfNotAllreadySubscribed'));
  147. $form->addElement('checkbox', 'unsubscribe', '', get_lang('UnsubscribeUserIfSubscriptionIsNotInFile'));
  148. $form->addElement('style_submit_button', 'submit', get_lang('Import'), 'class="save"');
  149. if ($form->validate()) {
  150. $users_classes = parse_csv_data($_FILES['import_file']['tmp_name']);
  151. $errors = validate_data($users_classes);
  152. if (count($errors) == 0) {
  153. save_data($users_classes);
  154. header('Location: class_list.php?action=show_message&message='.urlencode(get_lang('FileImported')));
  155. exit();
  156. }
  157. }
  158. Display :: display_header($tool_name);
  159. api_display_tool_title($tool_name);
  160. if (count($errors) != 0) {
  161. $error_message = "\n";
  162. foreach ($errors as $index => $error_class_user) {
  163. $error_message .= get_lang('Line').' '.$error_class_user['line'].': '.$error_class_user['error'].'</b>: ';
  164. $error_message .= "\n";
  165. }
  166. $error_message .= "\n";
  167. Display :: display_error_message($error_message);
  168. }
  169. $form->display();
  170. ?>
  171. <p><?php echo get_lang('CSVMustLookLike').' ('.get_lang('MandatoryFields').')'; ?> :</p>
  172. <blockquote>
  173. <pre>
  174. <b>UserName</b>;<b>ClassName</b>
  175. jdoe;class01
  176. adam;class01
  177. </pre>
  178. </blockquote>
  179. <?php
  180. /*
  181. ==============================================================================
  182. FOOTER
  183. ==============================================================================
  184. */
  185. Display :: display_footer();