PageRenderTime 48ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/mod/data/import.php

https://github.com/cwaclawik/moodle
PHP | 246 lines | 163 code | 41 blank | 42 comment | 33 complexity | a4a81b7e11c3243b3c97ce4fd4fc0bac MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, LGPL-2.1
  1. <?php // $Id$
  2. ///////////////////////////////////////////////////////////////////////////
  3. // //
  4. // NOTICE OF COPYRIGHT //
  5. // //
  6. // Moodle - Modular Object-Oriented Dynamic Learning Environment //
  7. // http://moodle.org //
  8. // //
  9. // Copyright (C) 2005 Martin Dougiamas http://dougiamas.com //
  10. // //
  11. // This program is free software; you can redistribute it and/or modify //
  12. // it under the terms of the GNU General Public License as published by //
  13. // the Free Software Foundation; either version 2 of the License, or //
  14. // (at your option) any later version. //
  15. // //
  16. // This program is distributed in the hope that it will be useful, //
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of //
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
  19. // GNU General Public License for more details: //
  20. // //
  21. // http://www.gnu.org/copyleft/gpl.html //
  22. // //
  23. ///////////////////////////////////////////////////////////////////////////
  24. require_once('../../config.php');
  25. require_once('lib.php');
  26. require_once($CFG->libdir.'/uploadlib.php');
  27. require_login();
  28. $id = optional_param('id', 0, PARAM_INT); // course module id
  29. $d = optional_param('d', 0, PARAM_INT); // database id
  30. $rid = optional_param('rid', 0, PARAM_INT); // record id
  31. $fielddelimiter = optional_param('fielddelimiter', ',', PARAM_CLEANHTML); // characters used as field delimiters for csv file import
  32. $fieldenclosure = optional_param('fieldenclosure', '', PARAM_CLEANHTML); // characters used as record delimiters for csv file import
  33. if ($id) {
  34. if (! $cm = get_coursemodule_from_id('data', $id)) {
  35. print_error('invalidcoursemodule');
  36. }
  37. if (! $course = $DB->get_record('course', array('id'=>$cm->course))) {
  38. print_error('coursemisconf');
  39. }
  40. if (! $data = $DB->get_record('data', array('id'=>$cm->instance))) {
  41. print_error('invalidcoursemodule');
  42. }
  43. } else {
  44. if (! $data = $DB->get_record('data', array('id'=>$d))) {
  45. print_error('invalidid', 'data');
  46. }
  47. if (! $course = $DB->get_record('course', array('id'=>$data->course))) {
  48. print_error('coursemisconf');
  49. }
  50. if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
  51. print_error('coursemisconf');
  52. }
  53. }
  54. require_login($course, false, $cm);
  55. $context = get_context_instance(CONTEXT_MODULE, $cm->id);
  56. require_capability('mod/data:manageentries', $context);
  57. /// Print the page header
  58. $strdata = get_string('modulenameplural','data');
  59. $navigation = build_navigation('', $cm);
  60. print_header_simple($data->name, "", $navigation, "", "", true, "", navmenu($course));
  61. print_heading(format_string($data->name));
  62. /// Groups needed for Add entry tab
  63. $currentgroup = groups_get_activity_group($cm);
  64. $groupmode = groups_get_activity_groupmode($cm);
  65. /// Print the tabs
  66. $currenttab = 'add';
  67. include('tabs.php');
  68. $um = new upload_manager('recordsfile', false, false, null, false, 0);
  69. if ($um->preprocess_files() && confirm_sesskey()) {
  70. $filename = $um->files['recordsfile']['tmp_name'];
  71. // Large files are likely to take their time and memory. Let PHP know
  72. // that we'll take longer, and that the process should be recycled soon
  73. // to free up memory.
  74. @set_time_limit(0);
  75. @raise_memory_limit("96M");
  76. if (function_exists('apache_child_terminate')) {
  77. @apache_child_terminate();
  78. }
  79. //Fix mac/dos newlines
  80. $text = my_file_get_contents($filename);
  81. $text = preg_replace('!\r\n?!',"\n",$text);
  82. $fp = fopen($filename, "w");
  83. fwrite($fp, $text);
  84. fclose($fp);
  85. $recordsadded = 0;
  86. if (!$records = data_get_records_csv($filename, $fielddelimiter, $fieldenclosure)) {
  87. print_error('csvfailed','data',"{$CFG->wwwroot}/mod/data/edit.php?d={$data->id}");
  88. } else {
  89. $fieldnames = array_shift($records);
  90. // check the fieldnames are valid
  91. $fields = $DB->get_records('data_fields', array('dataid'=>$data->id), '', 'name, id, type');
  92. $errorfield = '';
  93. foreach ($fieldnames as $name) {
  94. if (!isset($fields[$name])) {
  95. $errorfield .= "'$name' ";
  96. }
  97. }
  98. if (!empty($errorfield)) {
  99. print_error('fieldnotmatched','data',"{$CFG->wwwroot}/mod/data/edit.php?d={$data->id}",$errorfield);
  100. }
  101. foreach ($records as $record) {
  102. if ($recordid = data_add_record($data, 0)) { // add instance to data_record
  103. $fields = $DB->get_records('data_fields', array('dataid'=>$data->id), '', 'name, id, type');
  104. // Insert new data_content fields with NULL contents:
  105. foreach ($fields as $field) {
  106. $content = new object();
  107. $content->recordid = $recordid;
  108. $content->fieldid = $field->id;
  109. if (! $DB->insert_record('data_content', $content)) {
  110. print_error('cannotinsertrecord', '', '', $recordid);
  111. }
  112. }
  113. // Fill data_content with the values imported from the CSV file:
  114. foreach ($record as $key => $value) {
  115. $name = $fieldnames[$key];
  116. $field = $fields[$name];
  117. $content = new object();
  118. $content->fieldid = $field->id;
  119. $content->recordid = $recordid;
  120. if ($field->type == 'textarea') {
  121. // the only field type where HTML is possible
  122. $value = clean_param($value, PARAM_CLEANHTML);
  123. } else {
  124. // remove potential HTML:
  125. $patterns[] = '/</';
  126. $replacements[] = '&lt;';
  127. $patterns[] = '/>/';
  128. $replacements[] = '&gt;';
  129. $value = preg_replace($patterns, $replacements, $value);
  130. }
  131. // for now, only for "latlong" and "url" fields, but that should better be looked up from
  132. // $CFG->dirroot . '/mod/data/field/' . $field->type . '/field.class.php'
  133. // once there is stored how many contents the field can have.
  134. if (preg_match("/^(latlong|url)$/", $field->type)) {
  135. $values = explode(" ", $value, 2);
  136. $content->content = $values[0];
  137. $content->content1 = $values[1];
  138. } else {
  139. $content->content = $value;
  140. }
  141. $oldcontent = $DB->get_record('data_content', array('fieldid'=>$field->id, 'recordid'=>$recordid));
  142. $content->id = $oldcontent->id;
  143. if (! $DB->update_record('data_content', $content)) {
  144. print_error('cannotupdaterecord', '', '', $recordid);
  145. }
  146. }
  147. $recordsadded++;
  148. print get_string('added', 'moodle', $recordsadded) . ". " . get_string('entry', 'data') . " (ID $recordid)<br />\n";
  149. }
  150. }
  151. }
  152. }
  153. if ($recordsadded > 0) {
  154. notify($recordsadded. ' '. get_string('recordssaved', 'data'));
  155. } else {
  156. notify(get_string('recordsnotsaved', 'data'));
  157. }
  158. echo '<p />';
  159. /// Finish the page
  160. print_footer($course);
  161. function my_file_get_contents($filename, $use_include_path = 0) {
  162. /// Returns the file as one big long string
  163. $data = "";
  164. $file = @fopen($filename, "rb", $use_include_path);
  165. if ($file) {
  166. while (!feof($file)) {
  167. $data .= fread($file, 1024);
  168. }
  169. fclose($file);
  170. }
  171. return $data;
  172. }
  173. // Read the records from the given file.
  174. // Perform a simple field count check for each record.
  175. function data_get_records_csv($filename, $fielddelimiter=',', $fieldenclosure="\n") {
  176. global $DB;
  177. if (empty($fielddelimiter)) {
  178. $fielddelimiter = ',';
  179. }
  180. if (empty($fieldenclosure)) {
  181. $fieldenclosure = "\n";
  182. }
  183. if (!$fp = fopen($filename, "r")) {
  184. print_error('get_records_csv failed to open '.$filename);
  185. }
  186. $fieldnames = array();
  187. $rows = array();
  188. $fieldnames = fgetcsv($fp, 4096, $fielddelimiter, $fieldenclosure);
  189. if (empty($fieldnames)) {
  190. fclose($fp);
  191. return false;
  192. }
  193. $rows[] = $fieldnames;
  194. while (($data = fgetcsv($fp, 4096, $fielddelimiter, $fieldenclosure)) !== false) {
  195. if (count($data) > count($fieldnames)) {
  196. // For any given record, we can't have more data entities than the number of fields.
  197. fclose($fp);
  198. return false;
  199. }
  200. $rows[] = $data;
  201. }
  202. fclose($fp);
  203. return $rows;
  204. }
  205. ?>