weekly release 2.4dev
[moodle.git] / mod / data / locallib.php
CommitLineData
24ba58ee
PL
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * @package mod-data
20 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22 */
23
c3e1b5bd 24require_once($CFG->dirroot . '/mod/data/lib.php');
ee314f40 25require_once($CFG->libdir . '/portfolio/caller.php');
b63084a5 26require_once($CFG->libdir . '/filelib.php');
c3e1b5bd 27
24ba58ee 28/**
c3e1b5bd 29 * The class to handle entry exports of a database module
24ba58ee 30 */
24ba58ee
PL
31class data_portfolio_caller extends portfolio_module_caller_base {
32
c3e1b5bd 33 /** @var int the single record to export */
24ba58ee 34 protected $recordid;
24ba58ee 35
c3e1b5bd 36 /** @var object the record from the data table */
24ba58ee 37 private $data;
c3e1b5bd
PL
38
39 /**#@+ @var array the fields used and their fieldtypes */
24ba58ee
PL
40 private $fields;
41 private $fieldtypes;
c3e1b5bd
PL
42
43 /** @var object the records to export */
44 private $records;
45
46 /** @var int how many records are 'mine' */
47 private $minecount;
48
24ba58ee 49 /**
c3e1b5bd
PL
50 * the required callback arguments for a single-record export
51 *
24ba58ee
PL
52 * @return array
53 */
54 public static function expected_callbackargs() {
55 return array(
c3e1b5bd
PL
56 'id' => true,
57 'recordid' => false,
24ba58ee
PL
58 );
59 }
c3e1b5bd 60
24ba58ee 61 /**
c3e1b5bd 62 * @param array $callbackargs the arguments passed through
24ba58ee
PL
63 */
64 public function __construct($callbackargs) {
65 parent::__construct($callbackargs);
c3e1b5bd 66 // set up the list of fields to export
24ba58ee
PL
67 $this->selectedfields = array();
68 foreach ($callbackargs as $key => $value) {
69 if (strpos($key, 'field_') === 0) {
70 $this->selectedfields[] = substr($key, 6);
71 }
72 }
73 }
74
75 /**
c3e1b5bd
PL
76 * load up the data needed for the export
77 *
78 * @global object $DB
24ba58ee
PL
79 */
80 public function load_data() {
c3e1b5bd 81 global $DB, $USER;
24ba58ee
PL
82 if (!$this->cm = get_coursemodule_from_id('data', $this->id)) {
83 throw new portfolio_caller_exception('invalidid', 'data');
84 }
c3e1b5bd
PL
85 if (!$this->data = $DB->get_record('data', array('id' => $this->cm->instance))) {
86 throw new portfolio_caller_exception('invalidid', 'data');
87 }
88 $fieldrecords = $DB->get_records('data_fields', array('dataid' => $this->cm->instance), 'id');
24ba58ee
PL
89 // populate objets for this databases fields
90 $this->fields = array();
91 foreach ($fieldrecords as $fieldrecord) {
92 $tmp = data_get_field($fieldrecord, $this->data);
93 $this->fields[] = $tmp;
94 $this->fieldtypes[] = $tmp->type;
95 }
96
c3e1b5bd 97 $this->records = array();
24ba58ee 98 if ($this->recordid) {
c3e1b5bd
PL
99 $tmp = $DB->get_record('data_records', array('id' => $this->recordid));
100 $tmp->content = $DB->get_records('data_content', array('recordid' => $this->recordid));
101 $this->records[] = $tmp;
24ba58ee 102 } else {
c3e1b5bd 103 $where = array('dataid' => $this->data->id);
0b3b8c30 104 if (!has_capability('mod/data:exportallentries', context_module::instance($this->cm->id))) {
c3e1b5bd
PL
105 $where['userid'] = $USER->id; // get them all in case, we'll unset ones that aren't ours later if necessary
106 }
107 $tmp = $DB->get_records('data_records', $where);
108 foreach ($tmp as $t) {
109 $t->content = $DB->get_records('data_content', array('recordid' => $t->id));
110 $this->records[] = $t;
111 }
112 $this->minecount = $DB->count_records('data_records', array('dataid' => $this->data->id, 'userid' => $USER->id));
24ba58ee 113 }
24ba58ee 114
c3e1b5bd
PL
115 if ($this->recordid) {
116 list($formats, $files) = self::formats($this->fields, $this->records[0]);
117 $this->set_file_and_format_data($files);
118 }
24ba58ee
PL
119 }
120
121 /**
c3e1b5bd
PL
122 * How long we think the export will take
123 * Single entry is probably not too long.
124 * But we check for filesizes
125 * Else base it on the number of records
126 *
127 * @return one of PORTFOLIO_TIME_XX constants
24ba58ee
PL
128 */
129 public function expected_time() {
c3e1b5bd
PL
130 if ($this->recordid) {
131 return $this->expected_time_file();
132 } else {
133 return portfolio_expected_time_db(count($this->records));
24ba58ee 134 }
24ba58ee
PL
135 }
136
137 /**
c3e1b5bd
PL
138 * Calculate the shal1 of this export
139 * Dependent on the export format.
24ba58ee
PL
140 * @return string
141 */
142 public function get_sha1() {
c3e1b5bd
PL
143 // in the case that we're exporting a subclass of 'file' and we have a singlefile,
144 // then we're not exporting any metadata, just the file by itself by mimetype.
145 if ($this->exporter->get('format') instanceof portfolio_format_file && $this->singlefile) {
146 return $this->get_sha1_file();
24ba58ee 147 }
c3e1b5bd 148 // otherwise we're exporting some sort of multipart content so use the data
24ba58ee 149 $str = '';
c3e1b5bd
PL
150 foreach ($this->records as $record) {
151 foreach ($record as $data) {
152 if (is_array($data) || is_object($data)) {
6498b619
PS
153 $keys = array_keys($data);
154 $testkey = array_pop($keys);
c3e1b5bd
PL
155 if (is_array($data[$testkey]) || is_object($data[$testkey])) {
156 foreach ($data as $d) {
157 $str .= implode(',', (array)$d);
158 }
159 } else {
160 $str .= implode(',', (array)$data);
24ba58ee
PL
161 }
162 } else {
c3e1b5bd 163 $str .= $data;
24ba58ee 164 }
24ba58ee
PL
165 }
166 }
c3e1b5bd 167 return sha1($str . ',' . $this->exporter->get('formatclass'));
24ba58ee 168 }
c3e1b5bd 169
24ba58ee 170 /**
c3e1b5bd
PL
171 * Prepare the package for export
172 *
173 * @return stored_file object
24ba58ee
PL
174 */
175 public function prepare_package() {
176 global $DB;
c3e1b5bd 177 $leapwriter = null;
24ba58ee
PL
178 $content = '';
179 $filename = '';
c3e1b5bd
PL
180 $uid = $this->exporter->get('user')->id;
181 $users = array(); //cache
182 $onlymine = $this->get_export_config('mineonly');
183 if ($this->exporter->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
184 $leapwriter = $this->exporter->get('format')->leap2a_writer();
185 $ids = array();
186 }
187
188 if ($this->exporter->get('format') instanceof portfolio_format_file && $this->singlefile) {
189 return $this->get('exporter')->copy_existing_file($this->singlefile);
190 }
191 foreach ($this->records as $key => $record) {
192 if ($onlymine && $record->userid != $uid) {
193 unset($this->records[$key]); // sha1
194 continue;
195 }
196 list($tmpcontent, $files) = $this->exportentry($record);
197 $content .= $tmpcontent;
198 if ($leapwriter) {
199 $entry = new portfolio_format_leap2a_entry('dataentry' . $record->id, $this->data->name, 'resource', $tmpcontent);
200 $entry->published = $record->timecreated;
201 $entry->updated = $record->timemodified;
202 if ($record->userid != $uid) {
203 if (!array_key_exists($record->userid, $users)) {
204 $users[$record->userid] = $DB->get_record('user', array('id' => $record->userid), 'id,firstname,lastname');
205 }
206 $entry->author = $users[$record->userid];
207 }
208 $ids[] = $entry->id;
ebb7e782 209 $leapwriter->link_files($entry, $files, 'dataentry' . $record->id . 'file');
c3e1b5bd
PL
210 $leapwriter->add_entry($entry);
211 }
212 }
213 if ($leapwriter) {
214 if (count($this->records) > 1) { // make a selection element to tie them all together
215 $selection = new portfolio_format_leap2a_entry('datadb' . $this->data->id,
216 get_string('entries', 'data') . ': ' . $this->data->name, 'selection');
217 $leapwriter->add_entry($selection);
218 $leapwriter->make_selection($selection, $ids, 'Grouping');
219 }
220 $filename = $this->exporter->get('format')->manifest_name();
221 $content = $leapwriter->to_xml();
222 } else {
223 if (count($this->records) == 1) {
24ba58ee 224 $filename = clean_filename($this->cm->name . '-entry.html');
c3e1b5bd
PL
225 } else {
226 $filename = clean_filename($this->cm->name . '-full.html');
227 }
24ba58ee
PL
228 }
229 return $this->exporter->write_new_file(
230 $content,
231 $filename,
232 ($this->exporter->get('format') instanceof PORTFOLIO_FORMAT_RICH) // if we have associate files, this is a 'manifest'
233 );
234 }
235
236 /**
c3e1b5bd
PL
237 * Verify the user can still export this entry
238 *
24ba58ee
PL
239 * @return bool
240 */
241 public function check_permissions() {
c3e1b5bd
PL
242 if ($this->recordid) {
243 if (data_isowner($this->recordid)) {
0b3b8c30 244 return has_capability('mod/data:exportownentry', context_module::instance($this->cm->id));
c3e1b5bd 245 }
0b3b8c30 246 return has_capability('mod/data:exportentry', context_module::instance($this->cm->id));
c3e1b5bd
PL
247 }
248 if ($this->has_export_config() && !$this->get_export_config('mineonly')) {
0b3b8c30 249 return has_capability('mod/data:exportallentries', context_module::instance($this->cm->id));
c3e1b5bd 250 }
0b3b8c30 251 return has_capability('mod/data:exportownentry', context_module::instance($this->cm->id));
24ba58ee
PL
252 }
253
254 /**
255 * @return string
256 */
257 public static function display_name() {
258 return get_string('modulename', 'data');
259 }
260
261 /**
262 * @global object
263 * @return bool|void
264 */
265 public function __wakeup() {
266 global $CFG;
267 if (empty($CFG)) {
268 return true; // too early yet
269 }
270 foreach ($this->fieldtypes as $key => $field) {
271 require_once($CFG->dirroot . '/mod/data/field/' . $field .'/field.class.php');
272 $this->fields[$key] = unserialize(serialize($this->fields[$key]));
273 }
274 }
275
276 /**
c3e1b5bd
PL
277 * Prepare a single entry for export, replacing all the content etc
278 *
279 * @param stdclass $record the entry to export
280 *
281 * @return array with key 0 = the html content, key 1 = array of attachments
24ba58ee 282 */
c3e1b5bd 283 private function exportentry($record) {
24ba58ee
PL
284 // Replacing tags
285 $patterns = array();
286 $replacement = array();
24ba58ee 287
c3e1b5bd 288 $files = array();
24ba58ee
PL
289 // Then we generate strings to replace for normal tags
290 $format = $this->get('exporter')->get('format');
291 foreach ($this->fields as $field) {
292 $patterns[]='[['.$field->field->name.']]';
293 if (is_callable(array($field, 'get_file'))) {
c3e1b5bd 294 if (!$file = $field->get_file($record->id)) {
24ba58ee
PL
295 $replacement[] = '';
296 continue; // probably left empty
297 }
298 $replacement[] = $format->file_output($file);
299 $this->get('exporter')->copy_existing_file($file);
c3e1b5bd 300 $files[] = $file;
24ba58ee 301 } else {
c3e1b5bd 302 $replacement[] = $field->display_browse_field($record->id, 'singletemplate');
24ba58ee
PL
303 }
304 }
305
306 // Replacing special tags (##Edit##, ##Delete##, ##More##)
307 $patterns[]='##edit##';
308 $patterns[]='##delete##';
309 $patterns[]='##export##';
310 $patterns[]='##more##';
311 $patterns[]='##moreurl##';
312 $patterns[]='##user##';
313 $patterns[]='##approve##';
314 $patterns[]='##comments##';
315 $patterns[] = '##timeadded##';
316 $patterns[] = '##timemodified##';
317 $replacement[] = '';
318 $replacement[] = '';
319 $replacement[] = '';
320 $replacement[] = '';
321 $replacement[] = '';
322 $replacement[] = '';
323 $replacement[] = '';
324 $replacement[] = '';
c3e1b5bd
PL
325 $replacement[] = userdate($record->timecreated);
326 $replacement[] = userdate($record->timemodified);
24ba58ee
PL
327
328 // actual replacement of the tags
c3e1b5bd 329 return array(str_ireplace($patterns, $replacement, $this->data->singletemplate), $files);
24ba58ee
PL
330 }
331
332 /**
c3e1b5bd
PL
333 * Given the fields being exported, and the single record,
334 * work out which export format(s) we can use
335 *
336 * @param array $fields array of field objects
337 * @param object $record The data record object
338 *
24ba58ee
PL
339 * @uses PORTFOLIO_FORMAT_PLAINHTML
340 * @uses PORTFOLIO_FORMAT_RICHHTML
c3e1b5bd
PL
341 *
342 * @return array of PORTFOLIO_XX constants
24ba58ee
PL
343 */
344 public static function formats($fields, $record) {
345 $formats = array(PORTFOLIO_FORMAT_PLAINHTML);
346 $includedfiles = array();
347 foreach ($fields as $singlefield) {
348 if (is_callable(array($singlefield, 'get_file'))) {
349 $includedfiles[] = $singlefield->get_file($record->id);
350 }
351 }
352 if (count($includedfiles) == 1 && count($fields) == 1) {
c3e1b5bd 353 $formats = array(portfolio_format_from_mimetype($includedfiles[0]->get_mimetype()));
24ba58ee
PL
354 } else if (count($includedfiles) > 0) {
355 $formats = array(PORTFOLIO_FORMAT_RICHHTML);
356 }
357 return array($formats, $includedfiles);
358 }
359
c3e1b5bd
PL
360 public static function has_files($data) {
361 global $DB;
362 $fieldrecords = $DB->get_records('data_fields', array('dataid' => $data->id), 'id');
363 // populate objets for this databases fields
364 foreach ($fieldrecords as $fieldrecord) {
365 $field = data_get_field($fieldrecord, $data);
366 if (is_callable(array($field, 'get_file'))) {
367 return true;
368 }
369 }
370 return false;
371 }
372
373 /**
374 * base supported formats before we know anything about the export
375 */
24ba58ee 376 public static function base_supported_formats() {
c3e1b5bd
PL
377 return array(PORTFOLIO_FORMAT_RICHHTML, PORTFOLIO_FORMAT_PLAINHTML, PORTFOLIO_FORMAT_LEAP2A);
378 }
379
380 public function has_export_config() {
381 // if we're exporting more than just a single entry,
382 // and we have the capability to export all entries,
383 // then ask whether we want just our own, or all of them
384 return (empty($this->recordid) // multi-entry export
385 && $this->minecount > 0 // some of them are mine
386 && $this->minecount != count($this->records) // not all of them are mine
0b3b8c30 387 && has_capability('mod/data:exportallentries', context_module::instance($this->cm->id))); // they actually have a choice in the matter
c3e1b5bd
PL
388 }
389
390 public function export_config_form(&$mform, $instance) {
391 if (!$this->has_export_config()) {
392 return;
393 }
394 $mform->addElement('selectyesno', 'mineonly', get_string('exportownentries', 'data', (object)array('mine' => $this->minecount, 'all' => count($this->records))));
395 $mform->setDefault('mineonly', 1);
396 }
397
398 public function get_allowed_export_config() {
399 return array('mineonly');
24ba58ee
PL
400 }
401}
386b67d1
DM
402
403
404/**
405 * Class representing the virtual node with all itemids in the file browser
406 *
407 * @category files
408 * @copyright 2012 David Mudrak <david@moodle.com>
409 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
410 */
411class data_file_info_container extends file_info {
412 /** @var file_browser */
413 protected $browser;
414 /** @var stdClass */
415 protected $course;
416 /** @var stdClass */
417 protected $cm;
418 /** @var string */
419 protected $component;
420 /** @var stdClass */
421 protected $context;
422 /** @var array */
423 protected $areas;
424 /** @var string */
425 protected $filearea;
426
427 /**
428 * Constructor (in case you did not realize it ;-)
429 *
430 * @param file_browser $browser
431 * @param stdClass $course
432 * @param stdClass $cm
433 * @param stdClass $context
434 * @param array $areas
435 * @param string $filearea
436 */
437 public function __construct($browser, $course, $cm, $context, $areas, $filearea) {
438 parent::__construct($browser, $context);
439 $this->browser = $browser;
440 $this->course = $course;
441 $this->cm = $cm;
442 $this->component = 'mod_data';
443 $this->context = $context;
444 $this->areas = $areas;
445 $this->filearea = $filearea;
446 }
447
448 /**
449 * @return array with keys contextid, filearea, itemid, filepath and filename
450 */
451 public function get_params() {
452 return array(
453 'contextid' => $this->context->id,
454 'component' => $this->component,
455 'filearea' => $this->filearea,
456 'itemid' => null,
457 'filepath' => null,
458 'filename' => null,
459 );
460 }
461
462 /**
463 * Can new files or directories be added via the file browser
464 *
465 * @return bool
466 */
467 public function is_writable() {
468 return false;
469 }
470
471 /**
472 * Should this node be considered as a folder in the file browser
473 *
474 * @return bool
475 */
476 public function is_directory() {
477 return true;
478 }
479
480 /**
481 * Returns localised visible name of this node
482 *
483 * @return string
484 */
485 public function get_visible_name() {
486 return $this->areas[$this->filearea];
487 }
488
489 /**
490 * Returns list of children nodes
491 *
492 * @return array of file_info instances
493 */
494 public function get_children() {
495 global $DB;
496
497 $children = array();
498 $itemids = $DB->get_records('files', array('contextid' => $this->context->id, 'component' => $this->component,
499 'filearea' => $this->filearea), 'itemid DESC', "DISTINCT itemid");
500 foreach ($itemids as $itemid => $unused) {
501 if ($child = $this->browser->get_file_info($this->context, 'mod_data', $this->filearea, $itemid)) {
502 $children[] = $child;
503 }
504 }
505
506 return $children;
507 }
508
509 /**
510 * Returns parent file_info instance
511 *
512 * @return file_info or null for root
513 */
514 public function get_parent() {
515 return $this->browser->get_file_info($this->context);
516 }
517}