weekly release 3.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/**
002a2a44 19 * @package mod_data
24ba58ee
PL
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
c4b70cfc
SB
24defined('MOODLE_INTERNAL') || die();
25
c3e1b5bd 26require_once($CFG->dirroot . '/mod/data/lib.php');
ee314f40 27require_once($CFG->libdir . '/portfolio/caller.php');
b63084a5 28require_once($CFG->libdir . '/filelib.php');
c3e1b5bd 29
24ba58ee 30/**
c3e1b5bd 31 * The class to handle entry exports of a database module
24ba58ee 32 */
24ba58ee
PL
33class data_portfolio_caller extends portfolio_module_caller_base {
34
c3e1b5bd 35 /** @var int the single record to export */
24ba58ee 36 protected $recordid;
24ba58ee 37
c3e1b5bd 38 /** @var object the record from the data table */
24ba58ee 39 private $data;
c3e1b5bd
PL
40
41 /**#@+ @var array the fields used and their fieldtypes */
24ba58ee
PL
42 private $fields;
43 private $fieldtypes;
c3e1b5bd
PL
44
45 /** @var object the records to export */
46 private $records;
47
48 /** @var int how many records are 'mine' */
49 private $minecount;
50
24ba58ee 51 /**
c3e1b5bd
PL
52 * the required callback arguments for a single-record export
53 *
24ba58ee
PL
54 * @return array
55 */
56 public static function expected_callbackargs() {
57 return array(
c3e1b5bd
PL
58 'id' => true,
59 'recordid' => false,
24ba58ee
PL
60 );
61 }
c3e1b5bd 62
24ba58ee 63 /**
c3e1b5bd 64 * @param array $callbackargs the arguments passed through
24ba58ee
PL
65 */
66 public function __construct($callbackargs) {
67 parent::__construct($callbackargs);
c3e1b5bd 68 // set up the list of fields to export
24ba58ee
PL
69 $this->selectedfields = array();
70 foreach ($callbackargs as $key => $value) {
71 if (strpos($key, 'field_') === 0) {
72 $this->selectedfields[] = substr($key, 6);
73 }
74 }
75 }
76
77 /**
c3e1b5bd
PL
78 * load up the data needed for the export
79 *
80 * @global object $DB
24ba58ee
PL
81 */
82 public function load_data() {
c3e1b5bd 83 global $DB, $USER;
24ba58ee
PL
84 if (!$this->cm = get_coursemodule_from_id('data', $this->id)) {
85 throw new portfolio_caller_exception('invalidid', 'data');
86 }
c3e1b5bd
PL
87 if (!$this->data = $DB->get_record('data', array('id' => $this->cm->instance))) {
88 throw new portfolio_caller_exception('invalidid', 'data');
89 }
90 $fieldrecords = $DB->get_records('data_fields', array('dataid' => $this->cm->instance), 'id');
24ba58ee
PL
91 // populate objets for this databases fields
92 $this->fields = array();
93 foreach ($fieldrecords as $fieldrecord) {
94 $tmp = data_get_field($fieldrecord, $this->data);
95 $this->fields[] = $tmp;
96 $this->fieldtypes[] = $tmp->type;
97 }
98
c3e1b5bd 99 $this->records = array();
24ba58ee 100 if ($this->recordid) {
c3e1b5bd
PL
101 $tmp = $DB->get_record('data_records', array('id' => $this->recordid));
102 $tmp->content = $DB->get_records('data_content', array('recordid' => $this->recordid));
103 $this->records[] = $tmp;
24ba58ee 104 } else {
c3e1b5bd 105 $where = array('dataid' => $this->data->id);
0b3b8c30 106 if (!has_capability('mod/data:exportallentries', context_module::instance($this->cm->id))) {
c3e1b5bd
PL
107 $where['userid'] = $USER->id; // get them all in case, we'll unset ones that aren't ours later if necessary
108 }
109 $tmp = $DB->get_records('data_records', $where);
110 foreach ($tmp as $t) {
111 $t->content = $DB->get_records('data_content', array('recordid' => $t->id));
112 $this->records[] = $t;
113 }
114 $this->minecount = $DB->count_records('data_records', array('dataid' => $this->data->id, 'userid' => $USER->id));
24ba58ee 115 }
24ba58ee 116
c3e1b5bd
PL
117 if ($this->recordid) {
118 list($formats, $files) = self::formats($this->fields, $this->records[0]);
119 $this->set_file_and_format_data($files);
120 }
24ba58ee
PL
121 }
122
123 /**
c3e1b5bd
PL
124 * How long we think the export will take
125 * Single entry is probably not too long.
126 * But we check for filesizes
127 * Else base it on the number of records
128 *
129 * @return one of PORTFOLIO_TIME_XX constants
24ba58ee
PL
130 */
131 public function expected_time() {
c3e1b5bd
PL
132 if ($this->recordid) {
133 return $this->expected_time_file();
134 } else {
135 return portfolio_expected_time_db(count($this->records));
24ba58ee 136 }
24ba58ee
PL
137 }
138
139 /**
c3e1b5bd
PL
140 * Calculate the shal1 of this export
141 * Dependent on the export format.
24ba58ee
PL
142 * @return string
143 */
144 public function get_sha1() {
c3e1b5bd
PL
145 // in the case that we're exporting a subclass of 'file' and we have a singlefile,
146 // then we're not exporting any metadata, just the file by itself by mimetype.
147 if ($this->exporter->get('format') instanceof portfolio_format_file && $this->singlefile) {
148 return $this->get_sha1_file();
24ba58ee 149 }
c3e1b5bd 150 // otherwise we're exporting some sort of multipart content so use the data
24ba58ee 151 $str = '';
c3e1b5bd
PL
152 foreach ($this->records as $record) {
153 foreach ($record as $data) {
154 if (is_array($data) || is_object($data)) {
6498b619
PS
155 $keys = array_keys($data);
156 $testkey = array_pop($keys);
c3e1b5bd
PL
157 if (is_array($data[$testkey]) || is_object($data[$testkey])) {
158 foreach ($data as $d) {
159 $str .= implode(',', (array)$d);
160 }
161 } else {
162 $str .= implode(',', (array)$data);
24ba58ee
PL
163 }
164 } else {
c3e1b5bd 165 $str .= $data;
24ba58ee 166 }
24ba58ee
PL
167 }
168 }
c3e1b5bd 169 return sha1($str . ',' . $this->exporter->get('formatclass'));
24ba58ee 170 }
c3e1b5bd 171
24ba58ee 172 /**
c3e1b5bd
PL
173 * Prepare the package for export
174 *
175 * @return stored_file object
24ba58ee
PL
176 */
177 public function prepare_package() {
178 global $DB;
c3e1b5bd 179 $leapwriter = null;
24ba58ee
PL
180 $content = '';
181 $filename = '';
c3e1b5bd
PL
182 $uid = $this->exporter->get('user')->id;
183 $users = array(); //cache
184 $onlymine = $this->get_export_config('mineonly');
185 if ($this->exporter->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
186 $leapwriter = $this->exporter->get('format')->leap2a_writer();
187 $ids = array();
188 }
189
190 if ($this->exporter->get('format') instanceof portfolio_format_file && $this->singlefile) {
191 return $this->get('exporter')->copy_existing_file($this->singlefile);
192 }
193 foreach ($this->records as $key => $record) {
194 if ($onlymine && $record->userid != $uid) {
195 unset($this->records[$key]); // sha1
196 continue;
197 }
198 list($tmpcontent, $files) = $this->exportentry($record);
199 $content .= $tmpcontent;
200 if ($leapwriter) {
201 $entry = new portfolio_format_leap2a_entry('dataentry' . $record->id, $this->data->name, 'resource', $tmpcontent);
202 $entry->published = $record->timecreated;
203 $entry->updated = $record->timemodified;
204 if ($record->userid != $uid) {
205 if (!array_key_exists($record->userid, $users)) {
206 $users[$record->userid] = $DB->get_record('user', array('id' => $record->userid), 'id,firstname,lastname');
207 }
208 $entry->author = $users[$record->userid];
209 }
210 $ids[] = $entry->id;
ebb7e782 211 $leapwriter->link_files($entry, $files, 'dataentry' . $record->id . 'file');
c3e1b5bd
PL
212 $leapwriter->add_entry($entry);
213 }
214 }
215 if ($leapwriter) {
216 if (count($this->records) > 1) { // make a selection element to tie them all together
217 $selection = new portfolio_format_leap2a_entry('datadb' . $this->data->id,
218 get_string('entries', 'data') . ': ' . $this->data->name, 'selection');
219 $leapwriter->add_entry($selection);
220 $leapwriter->make_selection($selection, $ids, 'Grouping');
221 }
222 $filename = $this->exporter->get('format')->manifest_name();
223 $content = $leapwriter->to_xml();
224 } else {
225 if (count($this->records) == 1) {
24ba58ee 226 $filename = clean_filename($this->cm->name . '-entry.html');
c3e1b5bd
PL
227 } else {
228 $filename = clean_filename($this->cm->name . '-full.html');
229 }
24ba58ee
PL
230 }
231 return $this->exporter->write_new_file(
232 $content,
233 $filename,
234 ($this->exporter->get('format') instanceof PORTFOLIO_FORMAT_RICH) // if we have associate files, this is a 'manifest'
235 );
236 }
237
238 /**
c3e1b5bd
PL
239 * Verify the user can still export this entry
240 *
24ba58ee
PL
241 * @return bool
242 */
243 public function check_permissions() {
c3e1b5bd
PL
244 if ($this->recordid) {
245 if (data_isowner($this->recordid)) {
0b3b8c30 246 return has_capability('mod/data:exportownentry', context_module::instance($this->cm->id));
c3e1b5bd 247 }
0b3b8c30 248 return has_capability('mod/data:exportentry', context_module::instance($this->cm->id));
c3e1b5bd
PL
249 }
250 if ($this->has_export_config() && !$this->get_export_config('mineonly')) {
0b3b8c30 251 return has_capability('mod/data:exportallentries', context_module::instance($this->cm->id));
c3e1b5bd 252 }
0b3b8c30 253 return has_capability('mod/data:exportownentry', context_module::instance($this->cm->id));
24ba58ee
PL
254 }
255
256 /**
257 * @return string
258 */
259 public static function display_name() {
260 return get_string('modulename', 'data');
261 }
262
263 /**
264 * @global object
265 * @return bool|void
266 */
267 public function __wakeup() {
268 global $CFG;
269 if (empty($CFG)) {
270 return true; // too early yet
271 }
272 foreach ($this->fieldtypes as $key => $field) {
273 require_once($CFG->dirroot . '/mod/data/field/' . $field .'/field.class.php');
274 $this->fields[$key] = unserialize(serialize($this->fields[$key]));
275 }
276 }
277
278 /**
c3e1b5bd
PL
279 * Prepare a single entry for export, replacing all the content etc
280 *
281 * @param stdclass $record the entry to export
282 *
283 * @return array with key 0 = the html content, key 1 = array of attachments
24ba58ee 284 */
c3e1b5bd 285 private function exportentry($record) {
24ba58ee
PL
286 // Replacing tags
287 $patterns = array();
288 $replacement = array();
24ba58ee 289
c3e1b5bd 290 $files = array();
24ba58ee
PL
291 // Then we generate strings to replace for normal tags
292 $format = $this->get('exporter')->get('format');
293 foreach ($this->fields as $field) {
294 $patterns[]='[['.$field->field->name.']]';
295 if (is_callable(array($field, 'get_file'))) {
c3e1b5bd 296 if (!$file = $field->get_file($record->id)) {
24ba58ee
PL
297 $replacement[] = '';
298 continue; // probably left empty
299 }
300 $replacement[] = $format->file_output($file);
301 $this->get('exporter')->copy_existing_file($file);
c3e1b5bd 302 $files[] = $file;
24ba58ee 303 } else {
c3e1b5bd 304 $replacement[] = $field->display_browse_field($record->id, 'singletemplate');
24ba58ee
PL
305 }
306 }
307
308 // Replacing special tags (##Edit##, ##Delete##, ##More##)
309 $patterns[]='##edit##';
310 $patterns[]='##delete##';
311 $patterns[]='##export##';
312 $patterns[]='##more##';
313 $patterns[]='##moreurl##';
314 $patterns[]='##user##';
315 $patterns[]='##approve##';
d0372ed6 316 $patterns[]='##disapprove##';
24ba58ee
PL
317 $patterns[]='##comments##';
318 $patterns[] = '##timeadded##';
319 $patterns[] = '##timemodified##';
320 $replacement[] = '';
321 $replacement[] = '';
322 $replacement[] = '';
323 $replacement[] = '';
324 $replacement[] = '';
325 $replacement[] = '';
326 $replacement[] = '';
327 $replacement[] = '';
d0372ed6 328 $replacement[] = '';
c3e1b5bd
PL
329 $replacement[] = userdate($record->timecreated);
330 $replacement[] = userdate($record->timemodified);
24ba58ee
PL
331
332 // actual replacement of the tags
c3e1b5bd 333 return array(str_ireplace($patterns, $replacement, $this->data->singletemplate), $files);
24ba58ee
PL
334 }
335
336 /**
c3e1b5bd
PL
337 * Given the fields being exported, and the single record,
338 * work out which export format(s) we can use
339 *
340 * @param array $fields array of field objects
341 * @param object $record The data record object
342 *
24ba58ee
PL
343 * @uses PORTFOLIO_FORMAT_PLAINHTML
344 * @uses PORTFOLIO_FORMAT_RICHHTML
c3e1b5bd
PL
345 *
346 * @return array of PORTFOLIO_XX constants
24ba58ee
PL
347 */
348 public static function formats($fields, $record) {
349 $formats = array(PORTFOLIO_FORMAT_PLAINHTML);
350 $includedfiles = array();
351 foreach ($fields as $singlefield) {
352 if (is_callable(array($singlefield, 'get_file'))) {
f3998ce4
AG
353 if ($file = $singlefield->get_file($record->id)) {
354 $includedfiles[] = $file;
355 }
24ba58ee
PL
356 }
357 }
358 if (count($includedfiles) == 1 && count($fields) == 1) {
c3e1b5bd 359 $formats = array(portfolio_format_from_mimetype($includedfiles[0]->get_mimetype()));
24ba58ee
PL
360 } else if (count($includedfiles) > 0) {
361 $formats = array(PORTFOLIO_FORMAT_RICHHTML);
362 }
363 return array($formats, $includedfiles);
364 }
365
c3e1b5bd
PL
366 public static function has_files($data) {
367 global $DB;
368 $fieldrecords = $DB->get_records('data_fields', array('dataid' => $data->id), 'id');
369 // populate objets for this databases fields
370 foreach ($fieldrecords as $fieldrecord) {
371 $field = data_get_field($fieldrecord, $data);
372 if (is_callable(array($field, 'get_file'))) {
373 return true;
374 }
375 }
376 return false;
377 }
378
379 /**
380 * base supported formats before we know anything about the export
381 */
24ba58ee 382 public static function base_supported_formats() {
c3e1b5bd
PL
383 return array(PORTFOLIO_FORMAT_RICHHTML, PORTFOLIO_FORMAT_PLAINHTML, PORTFOLIO_FORMAT_LEAP2A);
384 }
385
386 public function has_export_config() {
387 // if we're exporting more than just a single entry,
388 // and we have the capability to export all entries,
389 // then ask whether we want just our own, or all of them
390 return (empty($this->recordid) // multi-entry export
391 && $this->minecount > 0 // some of them are mine
392 && $this->minecount != count($this->records) // not all of them are mine
0b3b8c30 393 && has_capability('mod/data:exportallentries', context_module::instance($this->cm->id))); // they actually have a choice in the matter
c3e1b5bd
PL
394 }
395
396 public function export_config_form(&$mform, $instance) {
397 if (!$this->has_export_config()) {
398 return;
399 }
400 $mform->addElement('selectyesno', 'mineonly', get_string('exportownentries', 'data', (object)array('mine' => $this->minecount, 'all' => count($this->records))));
401 $mform->setDefault('mineonly', 1);
402 }
403
404 public function get_allowed_export_config() {
405 return array('mineonly');
24ba58ee
PL
406 }
407}
386b67d1
DM
408
409
410/**
411 * Class representing the virtual node with all itemids in the file browser
412 *
413 * @category files
414 * @copyright 2012 David Mudrak <david@moodle.com>
415 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
416 */
417class data_file_info_container extends file_info {
418 /** @var file_browser */
419 protected $browser;
420 /** @var stdClass */
421 protected $course;
422 /** @var stdClass */
423 protected $cm;
424 /** @var string */
425 protected $component;
426 /** @var stdClass */
427 protected $context;
428 /** @var array */
429 protected $areas;
430 /** @var string */
431 protected $filearea;
432
433 /**
434 * Constructor (in case you did not realize it ;-)
435 *
436 * @param file_browser $browser
437 * @param stdClass $course
438 * @param stdClass $cm
439 * @param stdClass $context
440 * @param array $areas
441 * @param string $filearea
442 */
443 public function __construct($browser, $course, $cm, $context, $areas, $filearea) {
444 parent::__construct($browser, $context);
445 $this->browser = $browser;
446 $this->course = $course;
447 $this->cm = $cm;
448 $this->component = 'mod_data';
449 $this->context = $context;
450 $this->areas = $areas;
451 $this->filearea = $filearea;
452 }
453
454 /**
455 * @return array with keys contextid, filearea, itemid, filepath and filename
456 */
457 public function get_params() {
458 return array(
459 'contextid' => $this->context->id,
460 'component' => $this->component,
461 'filearea' => $this->filearea,
462 'itemid' => null,
463 'filepath' => null,
464 'filename' => null,
465 );
466 }
467
468 /**
469 * Can new files or directories be added via the file browser
470 *
471 * @return bool
472 */
473 public function is_writable() {
474 return false;
475 }
476
477 /**
478 * Should this node be considered as a folder in the file browser
479 *
480 * @return bool
481 */
482 public function is_directory() {
483 return true;
484 }
485
486 /**
487 * Returns localised visible name of this node
488 *
489 * @return string
490 */
491 public function get_visible_name() {
492 return $this->areas[$this->filearea];
493 }
494
495 /**
496 * Returns list of children nodes
497 *
498 * @return array of file_info instances
499 */
500 public function get_children() {
b8de2621
MG
501 return $this->get_filtered_children('*', false, true);
502 }
503
504 /**
505 * Help function to return files matching extensions or their count
506 *
507 * @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg')
43aadf04
MG
508 * @param bool|int $countonly if false returns the children, if an int returns just the
509 * count of children but stops counting when $countonly number of children is reached
b8de2621
MG
510 * @param bool $returnemptyfolders if true returns items that don't have matching files inside
511 * @return array|int array of file_info instances or the count
512 */
513 private function get_filtered_children($extensions = '*', $countonly = false, $returnemptyfolders = false) {
386b67d1 514 global $DB;
b8de2621
MG
515 $params = array('contextid' => $this->context->id,
516 'component' => $this->component,
517 'filearea' => $this->filearea);
518 $sql = 'SELECT DISTINCT itemid
519 FROM {files}
520 WHERE contextid = :contextid
521 AND component = :component
522 AND filearea = :filearea';
523 if (!$returnemptyfolders) {
524 $sql .= ' AND filename <> :emptyfilename';
525 $params['emptyfilename'] = '.';
526 }
527 list($sql2, $params2) = $this->build_search_files_sql($extensions);
528 $sql .= ' '.$sql2;
529 $params = array_merge($params, $params2);
43aadf04 530 if ($countonly === false) {
b8de2621
MG
531 $sql .= ' ORDER BY itemid DESC';
532 }
386b67d1 533
b8de2621 534 $rs = $DB->get_recordset_sql($sql, $params);
386b67d1 535 $children = array();
b8de2621
MG
536 foreach ($rs as $record) {
537 if ($child = $this->browser->get_file_info($this->context, 'mod_data', $this->filearea, $record->itemid)) {
386b67d1
DM
538 $children[] = $child;
539 }
43aadf04 540 if ($countonly !== false && count($children) >= $countonly) {
b8de2621
MG
541 break;
542 }
543 }
544 $rs->close();
43aadf04 545 if ($countonly !== false) {
b8de2621 546 return count($children);
386b67d1 547 }
386b67d1
DM
548 return $children;
549 }
550
b8de2621
MG
551 /**
552 * Returns list of children which are either files matching the specified extensions
553 * or folders that contain at least one such file.
554 *
555 * @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg')
556 * @return array of file_info instances
557 */
558 public function get_non_empty_children($extensions = '*') {
559 return $this->get_filtered_children($extensions, false);
560 }
561
562 /**
563 * Returns the number of children which are either files matching the specified extensions
564 * or folders containing at least one such file.
565 *
b8de2621 566 * @param string|array $extensions, for example '*' or array('.gif','.jpg')
43aadf04 567 * @param int $limit stop counting after at least $limit non-empty children are found
b8de2621
MG
568 * @return int
569 */
43aadf04
MG
570 public function count_non_empty_children($extensions = '*', $limit = 1) {
571 return $this->get_filtered_children($extensions, $limit);
b8de2621
MG
572 }
573
386b67d1
DM
574 /**
575 * Returns parent file_info instance
576 *
577 * @return file_info or null for root
578 */
579 public function get_parent() {
580 return $this->browser->get_file_info($this->context);
581 }
582}
87d6e85a
SB
583
584/**
585 * This creates new calendar events given as timeavailablefrom and timeclose by $data.
586 *
587 * @param stdClass $data
588 * @return void
589 */
590function data_set_events($data) {
591 global $DB, $CFG;
592
593 require_once($CFG->dirroot.'/calendar/lib.php');
594
595 // Get CMID if not sent as part of $data.
596 if (!isset($data->coursemodule)) {
597 $cm = get_coursemodule_from_instance('data', $data->id, $data->course);
598 $data->coursemodule = $cm->id;
599 }
600 // Data start calendar events.
601 $event = new stdClass();
7c6f961b
MN
602 $event->eventtype = DATA_EVENT_TYPE_OPEN;
603 // The DATA_EVENT_TYPE_OPEN event should only be an action event if no close time was specified.
604 $event->type = empty($data->timeavailableto) ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
87d6e85a 605 if ($event->id = $DB->get_field('event', 'id',
7c6f961b 606 array('modulename' => 'data', 'instance' => $data->id, 'eventtype' => $event->eventtype))) {
87d6e85a
SB
607 if ($data->timeavailablefrom > 0) {
608 // Calendar event exists so update it.
609 $event->name = get_string('calendarstart', 'data', $data->name);
610 $event->description = format_module_intro('data', $data, $data->coursemodule);
611 $event->timestart = $data->timeavailablefrom;
7c6f961b 612 $event->timesort = $data->timeavailablefrom;
87d6e85a
SB
613 $event->visible = instance_is_visible('data', $data);
614 $event->timeduration = 0;
e1cd93ce 615 $calendarevent = calendar_event::load($event->id);
87d6e85a
SB
616 $calendarevent->update($event);
617 } else {
618 // Calendar event is on longer needed.
e1cd93ce 619 $calendarevent = calendar_event::load($event->id);
87d6e85a
SB
620 $calendarevent->delete();
621 }
622 } else {
623 // Event doesn't exist so create one.
624 if (isset($data->timeavailablefrom) && $data->timeavailablefrom > 0) {
625 $event->name = get_string('calendarstart', 'data', $data->name);
626 $event->description = format_module_intro('data', $data, $data->coursemodule);
627 $event->courseid = $data->course;
628 $event->groupid = 0;
629 $event->userid = 0;
630 $event->modulename = 'data';
631 $event->instance = $data->id;
87d6e85a 632 $event->timestart = $data->timeavailablefrom;
7c6f961b 633 $event->timesort = $data->timeavailablefrom;
87d6e85a
SB
634 $event->visible = instance_is_visible('data', $data);
635 $event->timeduration = 0;
e1cd93ce 636 calendar_event::create($event);
87d6e85a
SB
637 }
638 }
639
640 // Data end calendar events.
641 $event = new stdClass();
7c6f961b
MN
642 $event->type = CALENDAR_EVENT_TYPE_ACTION;
643 $event->eventtype = DATA_EVENT_TYPE_CLOSE;
87d6e85a 644 if ($event->id = $DB->get_field('event', 'id',
7c6f961b 645 array('modulename' => 'data', 'instance' => $data->id, 'eventtype' => $event->eventtype))) {
87d6e85a
SB
646 if ($data->timeavailableto > 0) {
647 // Calendar event exists so update it.
648 $event->name = get_string('calendarend', 'data', $data->name);
649 $event->description = format_module_intro('data', $data, $data->coursemodule);
650 $event->timestart = $data->timeavailableto;
7c6f961b 651 $event->timesort = $data->timeavailableto;
87d6e85a
SB
652 $event->visible = instance_is_visible('data', $data);
653 $event->timeduration = 0;
e1cd93ce 654 $calendarevent = calendar_event::load($event->id);
87d6e85a
SB
655 $calendarevent->update($event);
656 } else {
657 // Calendar event is on longer needed.
e1cd93ce 658 $calendarevent = calendar_event::load($event->id);
87d6e85a
SB
659 $calendarevent->delete();
660 }
661 } else {
662 // Event doesn't exist so create one.
663 if (isset($data->timeavailableto) && $data->timeavailableto > 0) {
87d6e85a
SB
664 $event->name = get_string('calendarend', 'data', $data->name);
665 $event->description = format_module_intro('data', $data, $data->coursemodule);
666 $event->courseid = $data->course;
667 $event->groupid = 0;
668 $event->userid = 0;
669 $event->modulename = 'data';
670 $event->instance = $data->id;
87d6e85a 671 $event->timestart = $data->timeavailableto;
7c6f961b 672 $event->timesort = $data->timeavailableto;
87d6e85a
SB
673 $event->visible = instance_is_visible('data', $data);
674 $event->timeduration = 0;
e1cd93ce 675 calendar_event::create($event);
87d6e85a
SB
676 }
677 }
678}
a99c13af
JL
679
680/**
681 * Check if a database is available for the current user.
682 *
683 * @param stdClass $data database record
684 * @param boolean $canmanageentries optional, if the user can manage entries
685 * @param stdClass $context Module context, required if $canmanageentries is not set
686 * @return array status (available or not and possible warnings)
687 * @since Moodle 3.3
688 */
689function data_get_time_availability_status($data, $canmanageentries = null, $context = null) {
690 $open = true;
691 $closed = false;
692 $warnings = array();
693
694 if ($canmanageentries === null) {
695 $canmanageentries = has_capability('mod/data:manageentries', $context);
696 }
697
698 if (!$canmanageentries) {
699 $timenow = time();
700
701 if (!empty($data->timeavailablefrom) and $data->timeavailablefrom > $timenow) {
702 $open = false;
703 }
704 if (!empty($data->timeavailableto) and $timenow > $data->timeavailableto) {
705 $closed = true;
706 }
707
708 if (!$open or $closed) {
709 if (!$open) {
710 $warnings['notopenyet'] = userdate($data->timeavailablefrom);
711 }
712 if ($closed) {
713 $warnings['expired'] = userdate($data->timeavailableto);
714 }
715 return array(false, $warnings);
716 }
717 }
718
719 // Database is available.
720 return array(true, $warnings);
721}
722
723/**
724 * Requires a database to be available for the current user.
725 *
726 * @param stdClass $data database record
727 * @param boolean $canmanageentries optional, if the user can manage entries
728 * @param stdClass $context Module context, required if $canmanageentries is not set
729 * @throws moodle_exception
730 * @since Moodle 3.3
731 */
732function data_require_time_available($data, $canmanageentries = null, $context = null) {
733
734 list($available, $warnings) = data_get_time_availability_status($data, $canmanageentries, $context);
735
736 if (!$available) {
737 $reason = current(array_keys($warnings));
738 throw new moodle_exception($reason, 'data', '', $warnings[$reason]);
739 }
740}
741
742/**
743 * Return the number of entries left to add to complete the activity.
744 *
745 * @param stdClass $data database object
746 * @param int $numentries the number of entries the current user has created
747 * @param bool $canmanageentries whether the user can manage entries (teachers, managers)
748 * @return int the number of entries left, 0 if no entries left or if is not required
749 * @since Moodle 3.3
750 */
751function data_get_entries_left_to_add($data, $numentries, $canmanageentries) {
752 if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !$canmanageentries) {
753 return $data->requiredentries - $numentries;
754 }
755 return 0;
756}
757
758/**
759 * Return the number of entires left to add to view other users entries..
760 *
761 * @param stdClass $data database object
762 * @param int $numentries the number of entries the current user has created
763 * @param bool $canmanageentries whether the user can manage entries (teachers, managers)
764 * @return int the number of entries left, 0 if no entries left or if is not required
765 * @since Moodle 3.3
766 */
767function data_get_entries_left_to_view($data, $numentries, $canmanageentries) {
768 if ($data->requiredentriestoview > 0 && $numentries < $data->requiredentriestoview && !$canmanageentries) {
769 return $data->requiredentriestoview - $numentries;
770 }
771 return 0;
772}
31aae5d4
JL
773
774/**
775 * Search entries in a database.
776 *
777 * @param stdClass $data database object
778 * @param stdClass $cm course module object
779 * @param stdClass $context context object
780 * @param stdClass $mode in which mode we are viewing the database (list, single)
781 * @param int $currentgroup the current group being used
782 * @param str $search search for this text in the entry data
783 * @param str $sort the field to sort by
784 * @param str $order the order to use when sorting
785 * @param int $page for pagination, the current page
786 * @param int $perpage entries per page
787 * @param bool $advanced whether we are using or not advanced search
788 * @param array $searcharray when using advanced search, the advanced data to use
789 * @param stdClass $record if we jsut want this record after doing all the access checks
790 * @return array the entries found among other data related to the search
791 * @since Moodle 3.3
792 */
793function data_search_entries($data, $cm, $context, $mode, $currentgroup, $search = '', $sort = null, $order = null, $page = 0,
794 $perpage = 0, $advanced = null, $searcharray = null, $record = null) {
795 global $DB, $USER;
796
797 if ($sort === null) {
798 $sort = $data->defaultsort;
799 }
800 if ($order === null) {
801 $order = ($data->defaultsortdir == 0) ? 'ASC' : 'DESC';
802 }
803 if ($searcharray === null) {
804 $searcharray = array();
805 }
806
c8a804ff
JL
807 if (core_text::strlen($search) < 2) {
808 $search = '';
809 }
810
31aae5d4
JL
811 $approvecap = has_capability('mod/data:approve', $context);
812 $canmanageentries = has_capability('mod/data:manageentries', $context);
813
814 // If a student is not part of a group and seperate groups is enabled, we don't
815 // want them seeing all records.
816 $groupmode = groups_get_activity_groupmode($cm);
817 if ($currentgroup == 0 && $groupmode == 1 && !$canmanageentries) {
818 $canviewallrecords = false;
819 } else {
820 $canviewallrecords = true;
821 }
822
823 $numentries = data_numentries($data);
824 $requiredentriesallowed = true;
825 if (data_get_entries_left_to_view($data, $numentries, $canmanageentries)) {
826 $requiredentriesallowed = false;
827 }
828
829 // Initialise the first group of params for advanced searches.
830 $initialparams = array();
831 $params = array(); // Named params array.
832
833 // Setup group and approve restrictions.
834 if (!$approvecap && $data->approval) {
835 if (isloggedin()) {
836 $approveselect = ' AND (r.approved=1 OR r.userid=:myid1) ';
837 $params['myid1'] = $USER->id;
838 $initialparams['myid1'] = $params['myid1'];
839 } else {
840 $approveselect = ' AND r.approved=1 ';
841 }
842 } else {
843 $approveselect = ' ';
844 }
845
846 if ($currentgroup) {
847 $groupselect = " AND (r.groupid = :currentgroup OR r.groupid = 0)";
848 $params['currentgroup'] = $currentgroup;
849 $initialparams['currentgroup'] = $params['currentgroup'];
850 } else {
851 if ($canviewallrecords) {
852 $groupselect = ' ';
853 } else {
854 // If separate groups are enabled and the user isn't in a group or
855 // a teacher, manager, admin etc, then just show them entries for 'All participants'.
856 $groupselect = " AND r.groupid = 0";
857 }
858 }
859
860 // Init some variables to be used by advanced search.
861 $advsearchselect = '';
862 $advwhere = '';
863 $advtables = '';
864 $advparams = array();
865 // This is used for the initial reduction of advanced search results with required entries.
866 $entrysql = '';
867 $namefields = user_picture::fields('u');
868 // Remove the id from the string. This already exists in the sql statement.
869 $namefields = str_replace('u.id,', '', $namefields);
870
871 // Find the field we are sorting on.
872 if ($sort <= 0 or !$sortfield = data_get_field_from_id($sort, $data)) {
873
874 switch ($sort) {
875 case DATA_LASTNAME:
876 $ordering = "u.lastname $order, u.firstname $order";
877 break;
878 case DATA_FIRSTNAME:
879 $ordering = "u.firstname $order, u.lastname $order";
880 break;
881 case DATA_APPROVED:
882 $ordering = "r.approved $order, r.timecreated $order";
883 break;
884 case DATA_TIMEMODIFIED:
885 $ordering = "r.timemodified $order";
886 break;
887 case DATA_TIMEADDED:
888 default:
889 $sort = 0;
890 $ordering = "r.timecreated $order";
891 }
892
893 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, r.groupid, r.dataid, ' . $namefields;
894 $count = ' COUNT(DISTINCT c.recordid) ';
895 $tables = '{data_content} c,{data_records} r, {user} u ';
896 $where = 'WHERE c.recordid = r.id
897 AND r.dataid = :dataid
898 AND r.userid = u.id ';
899 $params['dataid'] = $data->id;
900 $sortorder = " ORDER BY $ordering, r.id $order";
901 $searchselect = '';
902
903 // If requiredentries is not reached, only show current user's entries.
904 if (!$requiredentriesallowed) {
905 $where .= ' AND u.id = :myid2 ';
906 $entrysql = ' AND r.userid = :myid3 ';
907 $params['myid2'] = $USER->id;
908 $initialparams['myid3'] = $params['myid2'];
909 }
910
911 if (!empty($advanced)) { // If advanced box is checked.
912 $i = 0;
913 foreach ($searcharray as $key => $val) { // what does $searcharray hold?
914 if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
915 $i++;
916 $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
917 $params['search_flname_'.$i] = "%$val->data%";
918 continue;
919 }
01b7ec36
JL
920 if ($key == DATA_TIMEMODIFIED) {
921 $searchselect .= " AND $val->field >= :timemodified";
922 $params['timemodified'] = $val->data;
923 continue;
924 }
31aae5d4
JL
925 $advtables .= ', {data_content} c'.$key.' ';
926 $advwhere .= ' AND c'.$key.'.recordid = r.id';
927 $advsearchselect .= ' AND ('.$val->sql.') ';
928 $advparams = array_merge($advparams, $val->params);
929 }
930 } else if ($search) {
931 $searchselect = " AND (".$DB->sql_like('c.content', ':search1', false)."
932 OR ".$DB->sql_like('u.firstname', ':search2', false)."
933 OR ".$DB->sql_like('u.lastname', ':search3', false)." ) ";
934 $params['search1'] = "%$search%";
935 $params['search2'] = "%$search%";
936 $params['search3'] = "%$search%";
937 } else {
938 $searchselect = ' ';
939 }
940
941 } else {
942
943 $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
944 $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
945
946 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, r.groupid, r.dataid, ' . $namefields . ',
947 ' . $sortcontentfull . ' AS sortorder ';
948 $count = ' COUNT(DISTINCT c.recordid) ';
949 $tables = '{data_content} c, {data_records} r, {user} u ';
950 $where = 'WHERE c.recordid = r.id
951 AND r.dataid = :dataid
952 AND r.userid = u.id ';
953 if (!$advanced) {
954 $where .= 'AND c.fieldid = :sort';
955 }
956 $params['dataid'] = $data->id;
957 $params['sort'] = $sort;
958 $sortorder = ' ORDER BY sortorder '.$order.' , r.id ASC ';
959 $searchselect = '';
960
961 // If requiredentries is not reached, only show current user's entries.
962 if (!$requiredentriesallowed) {
963 $where .= ' AND u.id = :myid2';
964 $entrysql = ' AND r.userid = :myid3';
965 $params['myid2'] = $USER->id;
966 $initialparams['myid3'] = $params['myid2'];
967 }
968 $i = 0;
969 if (!empty($advanced)) { // If advanced box is checked.
970 foreach ($searcharray as $key => $val) { // what does $searcharray hold?
971 if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
972 $i++;
973 $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
974 $params['search_flname_'.$i] = "%$val->data%";
975 continue;
976 }
01b7ec36
JL
977 if ($key == DATA_TIMEMODIFIED) {
978 $searchselect .= " AND $val->field >= :timemodified";
979 $params['timemodified'] = $val->data;
980 continue;
981 }
31aae5d4
JL
982 $advtables .= ', {data_content} c'.$key.' ';
983 $advwhere .= ' AND c'.$key.'.recordid = r.id AND c'.$key.'.fieldid = '.$key;
984 $advsearchselect .= ' AND ('.$val->sql.') ';
985 $advparams = array_merge($advparams, $val->params);
986 }
987 } else if ($search) {
988 $searchselect = " AND (".$DB->sql_like('c.content', ':search1', false)." OR
989 ".$DB->sql_like('u.firstname', ':search2', false)." OR
990 ".$DB->sql_like('u.lastname', ':search3', false)." ) ";
991 $params['search1'] = "%$search%";
992 $params['search2'] = "%$search%";
993 $params['search3'] = "%$search%";
994 } else {
995 $searchselect = ' ';
996 }
997 }
998
999 // To actually fetch the records.
1000
1001 $fromsql = "FROM $tables $advtables $where $advwhere $groupselect $approveselect $searchselect $advsearchselect";
1002 $allparams = array_merge($params, $advparams);
1003
1004 // Provide initial sql statements and parameters to reduce the number of total records.
1005 $initialselect = $groupselect . $approveselect . $entrysql;
1006
1007 $recordids = data_get_all_recordids($data->id, $initialselect, $initialparams);
1008 $newrecordids = data_get_advance_search_ids($recordids, $searcharray, $data->id);
31aae5d4
JL
1009 $selectdata = $where . $groupselect . $approveselect;
1010
1011 if (!empty($advanced)) {
1012 $advancedsearchsql = data_get_advanced_search_sql($sort, $data, $newrecordids, $selectdata, $sortorder);
1013 $sqlselect = $advancedsearchsql['sql'];
1014 $allparams = array_merge($allparams, $advancedsearchsql['params']);
6cf2ab73 1015 $totalcount = count($newrecordids);
31aae5d4
JL
1016 } else {
1017 $sqlselect = "SELECT $what $fromsql $sortorder";
c2c941b6 1018 $sqlcountselect = "SELECT $count $fromsql";
6cf2ab73 1019 $totalcount = $DB->count_records_sql($sqlcountselect, $allparams);
31aae5d4
JL
1020 }
1021
1022 // Work out the paging numbers and counts.
1023 if (empty($searchselect) && empty($advsearchselect)) {
1024 $maxcount = $totalcount;
1025 } else {
1026 $maxcount = count($recordids);
1027 }
1028
1029 if ($record) { // We need to just show one, so where is it in context?
1030 $nowperpage = 1;
1031 $mode = 'single';
1032 $page = 0;
1033 // TODO MDL-33797 - Reduce this or consider redesigning the paging system.
1034 if ($allrecordids = $DB->get_fieldset_sql($sqlselect, $allparams)) {
1035 $page = (int)array_search($record->id, $allrecordids);
1036 unset($allrecordids);
1037 }
1038 } else if ($mode == 'single') { // We rely on ambient $page settings
1039 $nowperpage = 1;
1040
1041 } else {
1042 $nowperpage = $perpage;
1043 }
1044
1045 // Get the actual records.
1046 if (!$records = $DB->get_records_sql($sqlselect, $allparams, $page * $nowperpage, $nowperpage)) {
1047 // Nothing to show!
1048 if ($record) { // Something was requested so try to show that at least (bug 5132)
80771075
JL
1049 if (data_can_view_record($data, $record, $currentgroup, $canmanageentries)) {
1050 // OK, we can show this one
1051 $records = array($record->id => $record);
1052 $totalcount = 1;
31aae5d4
JL
1053 }
1054 }
1055
1056 }
1057
1058 return [$records, $maxcount, $totalcount, $page, $nowperpage, $sort, $mode];
1059}
80771075
JL
1060
1061/**
1062 * Check if the current user can view the given record.
1063 *
1064 * @param stdClass $data database record
1065 * @param stdClass $record the record (entry) to check
1066 * @param int $currentgroup current group
1067 * @param bool $canmanageentries if the user can manage entries
1068 * @return bool true if the user can view the entry
1069 * @since Moodle 3.3
1070 */
1071function data_can_view_record($data, $record, $currentgroup, $canmanageentries) {
1072 global $USER;
1073
1074 if ($canmanageentries || empty($data->approval) ||
1075 $record->approved || (isloggedin() && $record->userid == $USER->id)) {
1076
1077 if (!$currentgroup || $record->groupid == $currentgroup || $record->groupid == 0) {
1078 return true;
1079 }
1080 }
1081 return false;
1082}
aefe9c5f
JL
1083
1084/**
1085 * Return all the field instances for a given database.
1086 *
1087 * @param stdClass $data database object
1088 * @return array field instances
1089 * @since Moodle 3.3
1090 */
1091function data_get_field_instances($data) {
1092 global $DB;
1093
1094 $instances = [];
1095 if ($fields = $DB->get_records('data_fields', array('dataid' => $data->id), 'id')) {
1096 foreach ($fields as $field) {
1097 $instances[] = data_get_field($field, $data);
1098 }
1099 }
1100 return $instances;
1101}
c8a804ff
JL
1102
1103/**
1104 * Build the search array.
1105 *
1106 * @param stdClass $data the database object
1107 * @param bool $paging if paging is being used
1108 * @param array $searcharray the current search array (saved by session)
1109 * @param array $defaults default values for the searchable fields
1110 * @param str $fn the first name to search (optional)
1111 * @param str $ln the last name to search (optional)
1112 * @return array the search array and plain search build based on the different elements
1113 * @since Moodle 3.3
1114 */
1115function data_build_search_array($data, $paging, $searcharray, $defaults = null, $fn = '', $ln = '') {
1116 global $DB;
1117
1118 $search = '';
1119 $vals = array();
1120 $fields = $DB->get_records('data_fields', array('dataid' => $data->id));
1121
1122 if (!empty($fields)) {
1123 foreach ($fields as $field) {
1124 $searchfield = data_get_field_from_id($field->id, $data);
1125 // Get field data to build search sql with. If paging is false, get from user.
1126 // If paging is true, get data from $searcharray which is obtained from the $SESSION (see line 116).
1127 if (!$paging) {
1128 $val = $searchfield->parse_search_field($defaults);
1129 } else {
1130 // Set value from session if there is a value @ the required index.
1131 if (isset($searcharray[$field->id])) {
1132 $val = $searcharray[$field->id]->data;
1133 } else { // If there is not an entry @ the required index, set value to blank.
1134 $val = '';
1135 }
1136 }
1137 if (!empty($val)) {
1138 $searcharray[$field->id] = new stdClass();
1139 list($searcharray[$field->id]->sql, $searcharray[$field->id]->params) = $searchfield->generate_sql('c'.$field->id, $val);
1140 $searcharray[$field->id]->data = $val;
1141 $vals[] = $val;
1142 } else {
1143 // Clear it out.
1144 unset($searcharray[$field->id]);
1145 }
1146 }
1147 }
1148
1149 if (!$paging) {
1150 // Name searching.
1151 $fn = optional_param('u_fn', $fn, PARAM_NOTAGS);
1152 $ln = optional_param('u_ln', $ln, PARAM_NOTAGS);
1153 } else {
1154 $fn = isset($searcharray[DATA_FIRSTNAME]) ? $searcharray[DATA_FIRSTNAME]->data : '';
1155 $ln = isset($searcharray[DATA_LASTNAME]) ? $searcharray[DATA_LASTNAME]->data : '';
1156 }
1157 if (!empty($fn)) {
1158 $searcharray[DATA_FIRSTNAME] = new stdClass();
1159 $searcharray[DATA_FIRSTNAME]->sql = '';
1160 $searcharray[DATA_FIRSTNAME]->params = array();
1161 $searcharray[DATA_FIRSTNAME]->field = 'u.firstname';
1162 $searcharray[DATA_FIRSTNAME]->data = $fn;
1163 $vals[] = $fn;
1164 } else {
1165 unset($searcharray[DATA_FIRSTNAME]);
1166 }
1167 if (!empty($ln)) {
1168 $searcharray[DATA_LASTNAME] = new stdClass();
1169 $searcharray[DATA_LASTNAME]->sql = '';
1170 $searcharray[DATA_LASTNAME]->params = array();
1171 $searcharray[DATA_LASTNAME]->field = 'u.lastname';
1172 $searcharray[DATA_LASTNAME]->data = $ln;
1173 $vals[] = $ln;
1174 } else {
1175 unset($searcharray[DATA_LASTNAME]);
1176 }
1177
1178 // In case we want to switch to simple search later - there might be multiple values there ;-).
1179 if ($vals) {
1180 $val = reset($vals);
1181 if (is_string($val)) {
1182 $search = $val;
1183 }
1184 }
1185 return [$searcharray, $search];
1186}
b8e0e644
JL
1187
1188/**
1189 * Approves or unapproves an entry.
1190 *
1191 * @param int $entryid the entry to approve or unapprove.
1192 * @param bool $approve Whether to approve or unapprove (true for approve false otherwise).
1193 * @since Moodle 3.3
1194 */
1195function data_approve_entry($entryid, $approve) {
1196 global $DB;
1197
1198 $newrecord = new stdClass();
1199 $newrecord->id = $entryid;
1200 $newrecord->approved = $approve ? 1 : 0;
1201 $DB->update_record('data_records', $newrecord);
1202}
b376f55e
JL
1203
1204/**
1205 * Populate the field contents of a new record with the submitted data.
1206 *
1207 * @param stdClass $data database object
1208 * @param stdClass $context context object
1209 * @param int $recordid the new record id
1210 * @param array $fields list of fields of the database
1211 * @param stdClass $datarecord the submitted data
1212 * @param stdClass $processeddata pre-processed submitted fields
1213 * @since Moodle 3.3
1214 */
1215function data_add_fields_contents_to_new_record($data, $context, $recordid, $fields, $datarecord, $processeddata) {
1216 global $DB;
1217
1218 // Insert a whole lot of empty records to make sure we have them.
1219 $records = array();
1220 foreach ($fields as $field) {
1221 $content = new stdClass();
1222 $content->recordid = $recordid;
1223 $content->fieldid = $field->id;
1224 $records[] = $content;
1225 }
1226
1227 // Bulk insert the records now. Some records may have no data but all must exist.
1228 $DB->insert_records('data_content', $records);
1229
1230 // Add all provided content.
1231 foreach ($processeddata->fields as $fieldname => $field) {
1232 $field->update_content($recordid, $datarecord->$fieldname, $fieldname);
1233 }
1234
1235 // Trigger an event for updating this record.
1236 $event = \mod_data\event\record_created::create(array(
1237 'objectid' => $recordid,
1238 'context' => $context,
1239 'courseid' => $data->course,
1240 'other' => array(
1241 'dataid' => $data->id
1242 )
1243 ));
1244 $event->add_record_snapshot('data', $data);
1245 $event->trigger();
1246}
df0c549f
JL
1247
1248/**
1249 * Updates the fields contents of an existing record.
1250 *
1251 * @param stdClass $data database object
1252 * @param stdClass $record record to update object
1253 * @param stdClass $context context object
1254 * @param stdClass $datarecord the submitted data
1255 * @param stdClass $processeddata pre-processed submitted fields
1256 * @since Moodle 3.3
1257 */
1258function data_update_record_fields_contents($data, $record, $context, $datarecord, $processeddata) {
1259 global $DB;
1260
1261 // Reset the approved flag after edit if the user does not have permission to approve their own entries.
1262 if (!has_capability('mod/data:approve', $context)) {
1263 $record->approved = 0;
1264 }
1265
1266 // Update the parent record.
1267 $record->timemodified = time();
1268 $DB->update_record('data_records', $record);
1269
1270 // Update all content.
1271 foreach ($processeddata->fields as $fieldname => $field) {
1272 $field->update_content($record->id, $datarecord->$fieldname, $fieldname);
1273 }
1274
1275 // Trigger an event for updating this record.
1276 $event = \mod_data\event\record_updated::create(array(
1277 'objectid' => $record->id,
1278 'context' => $context,
1279 'courseid' => $data->course,
1280 'other' => array(
1281 'dataid' => $data->id
1282 )
1283 ));
1284 $event->add_record_snapshot('data', $data);
1285 $event->trigger();
1286}