PageRenderTime 45ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/grade/edit/outcome/import.php

https://github.com/raymanuk/moodle
PHP | 247 lines | 161 code | 38 blank | 48 comment | 37 complexity | fab0840a5f9cfd7e00b42fb46f01162e MD5 | raw file
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Import outcomes from a file
  18. *
  19. * @package core_grades
  20. * @copyright 2008 Moodle Pty Ltd (http://moodle.com)
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. require_once(dirname(__FILE__).'/../../../config.php');
  24. require_once($CFG->dirroot.'/lib/formslib.php');
  25. require_once($CFG->dirroot.'/grade/lib.php');
  26. require_once($CFG->libdir.'/gradelib.php');
  27. require_once('import_outcomes_form.php');
  28. $courseid = optional_param('courseid', 0, PARAM_INT);
  29. $action = optional_param('action', '', PARAM_ALPHA);
  30. $scope = optional_param('scope', 'custom', PARAM_ALPHA);
  31. $PAGE->set_url('/grade/edit/outcome/import.php', array('courseid' => $courseid));
  32. $PAGE->set_pagelayout('admin');
  33. /// Make sure they can even access this course
  34. if ($courseid) {
  35. if (!$course = $DB->get_record('course', array('id' => $courseid))) {
  36. print_error('nocourseid');
  37. }
  38. require_login($course);
  39. $context = context_course::instance($course->id);
  40. if (empty($CFG->enableoutcomes)) {
  41. redirect('../../index.php?id='.$courseid);
  42. }
  43. } else {
  44. require_once $CFG->libdir.'/adminlib.php';
  45. admin_externalpage_setup('outcomes');
  46. $context = context_system::instance();
  47. }
  48. require_capability('moodle/grade:manageoutcomes', $context);
  49. $navigation = grade_build_nav(__FILE__, get_string('outcomes', 'grades'), $courseid);
  50. $upload_form = new import_outcomes_form();
  51. // display import form
  52. if (!$upload_form->get_data()) {
  53. print_grade_page_head($courseid, 'outcome', 'import', get_string('importoutcomes', 'grades'));
  54. $upload_form->display();
  55. echo $OUTPUT->footer();
  56. die;
  57. }
  58. print_grade_page_head($courseid, 'outcome', 'import', get_string('importoutcomes', 'grades'));
  59. $imported_file = $CFG->tempdir . '/outcomeimport/importedfile_'.time().'.csv';
  60. make_temp_directory('outcomeimport');
  61. // copying imported file
  62. if (!$upload_form->save_file('userfile', $imported_file, true)) {
  63. redirect('import.php'. ($courseid ? "?courseid=$courseid" : ''), get_string('importfilemissing', 'grades'));
  64. }
  65. /// which scope are we importing the outcomes in?
  66. if (isset($courseid) && ($scope == 'custom')) {
  67. // custom scale
  68. $local_scope = true;
  69. } elseif (($scope == 'global') && has_capability('moodle/grade:manage', context_system::instance())) {
  70. // global scale
  71. $local_scope = false;
  72. } else {
  73. // shouldn't happen .. user might be trying to access this script without the right permissions.
  74. redirect('index.php', get_string('importerror', 'grades'));
  75. }
  76. // open the file, start importing data
  77. if ($handle = fopen($imported_file, 'r')) {
  78. $line = 0; // will keep track of current line, to give better error messages.
  79. $file_headers = '';
  80. // $csv_data needs to have at least these columns, the value is the default position in the data file.
  81. $headers = array('outcome_name' => 0, 'outcome_shortname' => 1, 'scale_name' => 3, 'scale_items' => 4);
  82. $optional_headers = array('outcome_description'=>2, 'scale_description' => 5);
  83. $imported_headers = array(); // will later be initialized with the values found in the file
  84. $fatal_error = false;
  85. // data should be separated by a ';'. *NOT* by a comma! TODO: version 2.0
  86. // or whenever we can depend on PHP5, set the second parameter (8192) to 0 (unlimited line length) : the database can store over 128k per line.
  87. while ( $csv_data = fgetcsv($handle, 8192, ';', '"')) { // if the line is over 8k, it won't work...
  88. $line++;
  89. // be tolerant on input, as fgetcsv returns "an array comprising a single null field" on blank lines
  90. if ($csv_data == array(null)) {
  91. continue;
  92. }
  93. // on first run, grab and analyse the header
  94. if ($file_headers == '') {
  95. $file_headers = array_flip($csv_data); // save the header line ... TODO: use the header line to let import work with columns in arbitrary order
  96. $error = false;
  97. foreach($headers as $key => $value) {
  98. // sanity check #1: make sure the file contains all the mandatory headers
  99. if (!array_key_exists($key, $file_headers)) {
  100. $error = true;
  101. break;
  102. }
  103. }
  104. if ($error) {
  105. echo $OUTPUT->box_start('generalbox importoutcomenofile buttons');
  106. echo get_string('importoutcomenofile', 'grades', $line);
  107. echo $OUTPUT->single_button(new moodle_url('/grade/edit/outcome/import.php', array('courseid'=> $courseid)), get_string('back'), 'get');
  108. echo $OUTPUT->box_end();
  109. $fatal_error = true;
  110. break;
  111. }
  112. foreach(array_merge($headers, $optional_headers) as $header => $position) {
  113. // match given columns to expected columns *into* $headers
  114. $imported_headers[$header] = $file_headers[$header];
  115. }
  116. continue; // we don't import headers
  117. }
  118. // sanity check #2: every line must have the same number of columns as there are
  119. // headers. If not, processing stops.
  120. if ( count($csv_data) != count($file_headers) ) {
  121. echo $OUTPUT->box_start('generalbox importoutcomenofile');
  122. echo get_string('importoutcomenofile', 'grades', $line);
  123. echo $OUTPUT->single_button(new moodle_url('/grade/edit/outcome/import.php', array('courseid'=> $courseid)), get_string('back'), 'get');
  124. echo $OUTPUT->box_end();
  125. $fatal_error = true;
  126. //echo $OUTPUT->box(var_export($csv_data, true) ."<br />". var_export($header, true));
  127. break;
  128. }
  129. // sanity check #3: all required fields must be present on the current line.
  130. foreach ($headers as $header => $position) {
  131. if ($csv_data[$imported_headers[$header]] == '') {
  132. echo $OUTPUT->box_start('generalbox importoutcomenofile');
  133. echo get_string('importoutcomenofile', 'grades', $line);
  134. echo $OUTPUT->single_button(new moodle_url('/grade/edit/outcome/import.php', array('courseid'=> $courseid)), get_string('back'), 'get');
  135. echo $OUTPUT->box_end();
  136. $fatal_error = true;
  137. break;
  138. }
  139. }
  140. // MDL-17273 errors in csv are not preventing import from happening. We break from the while loop here
  141. if ($fatal_error) {
  142. break;
  143. }
  144. $params = array($csv_data[$imported_headers['outcome_shortname']]);
  145. $wheresql = 'shortname = ? ';
  146. if ($local_scope) {
  147. $params[] = $courseid;
  148. $wheresql .= ' AND courseid = ?';
  149. } else {
  150. $wheresql .= ' AND courseid IS NULL';
  151. }
  152. $outcome = $DB->get_records_select('grade_outcomes', $wheresql, $params);
  153. if ($outcome) {
  154. // already exists, print a message and skip.
  155. echo $OUTPUT->box(get_string('importskippedoutcome', 'grades', $csv_data[$imported_headers['outcome_shortname']]));
  156. continue;
  157. }
  158. // new outcome will be added, search for compatible existing scale...
  159. $params = array($csv_data[$imported_headers['scale_name']], $csv_data[$imported_headers['scale_items']], $courseid);
  160. $wheresql = 'name = ? AND scale = ? AND (courseid = ? OR courseid = 0)';
  161. $scale = $DB->get_records_select('scale', $wheresql, $params);
  162. if ($scale) {
  163. // already exists in the right scope: use it.
  164. $scale_id = key($scale);
  165. } else {
  166. if (!has_capability('moodle/course:managescales', $context)) {
  167. echo $OUTPUT->box(get_string('importskippednomanagescale', 'grades', $csv_data[$imported_headers['outcome_shortname']]));
  168. continue;
  169. } else {
  170. // scale doesn't exists : create it.
  171. $scale_data = array('name' => $csv_data[$imported_headers['scale_name']],
  172. 'scale' => $csv_data[$imported_headers['scale_items']],
  173. 'description' => $csv_data[$imported_headers['scale_description']],
  174. 'userid' => $USER->id);
  175. if ($local_scope) {
  176. $scale_data['courseid'] = $courseid;
  177. } else {
  178. $scale_data['courseid'] = 0; // 'global' : scale use '0', outcomes use null
  179. }
  180. $scale = new grade_scale($scale_data);
  181. $scale_id = $scale->insert();
  182. }
  183. }
  184. // add outcome
  185. $outcome_data = array('shortname' => $csv_data[$imported_headers['outcome_shortname']],
  186. 'fullname' => $csv_data[$imported_headers['outcome_name']],
  187. 'scaleid' => $scale_id,
  188. 'description' => $csv_data[$imported_headers['outcome_description']],
  189. 'usermodified' => $USER->id);
  190. if ($local_scope) {
  191. $outcome_data['courseid'] = $courseid;
  192. } else {
  193. $outcome_data['courseid'] = null; // 'global' : scale use '0', outcomes use null
  194. }
  195. $outcome = new grade_outcome($outcome_data);
  196. $outcome_id = $outcome->insert();
  197. $outcome_success_strings = new StdClass();
  198. $outcome_success_strings->name = $outcome_data['fullname'];
  199. $outcome_success_strings->id = $outcome_id;
  200. echo $OUTPUT->box(get_string('importoutcomesuccess', 'grades', $outcome_success_strings));
  201. }
  202. } else {
  203. echo $OUTPUT->box(get_string('importoutcomenofile', 'grades', 0));
  204. }
  205. // finish
  206. fclose($handle);
  207. // delete temp file
  208. unlink($imported_file);
  209. echo $OUTPUT->footer();