MDL-20053 mod_data: Add userpicture tag to show profile pictures
[moodle.git] / mod / data / lib.php
blobc4dc0d5eb98f294034db6470ae84821032fd0dae
1 <?php
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.
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/>.
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
24 // Some constants
25 define ('DATA_MAX_ENTRIES', 50);
26 define ('DATA_PERPAGE_SINGLE', 1);
28 define ('DATA_FIRSTNAME', -1);
29 define ('DATA_LASTNAME', -2);
30 define ('DATA_APPROVED', -3);
31 define ('DATA_TIMEADDED', 0);
32 define ('DATA_TIMEMODIFIED', -4);
34 define ('DATA_CAP_EXPORT', 'mod/data:viewalluserpresets');
36 define('DATA_PRESET_COMPONENT', 'mod_data');
37 define('DATA_PRESET_FILEAREA', 'site_presets');
38 define('DATA_PRESET_CONTEXT', SYSCONTEXTID);
40 // Users having assigned the default role "Non-editing teacher" can export database records
41 // Using the mod/data capability "viewalluserpresets" existing in Moodle 1.9.x.
42 // In Moodle >= 2, new roles may be introduced and used instead.
44 /**
45 * @package mod_data
46 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
47 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 class data_field_base { // Base class for Database Field Types (see field/*/field.class.php)
51 /** @var string Subclasses must override the type with their name */
52 var $type = 'unknown';
53 /** @var object The database object that this field belongs to */
54 var $data = NULL;
55 /** @var object The field object itself, if we know it */
56 var $field = NULL;
57 /** @var int Width of the icon for this fieldtype */
58 var $iconwidth = 16;
59 /** @var int Width of the icon for this fieldtype */
60 var $iconheight = 16;
61 /** @var object course module or cmifno */
62 var $cm;
63 /** @var object activity context */
64 var $context;
66 /**
67 * Constructor function
69 * @global object
70 * @uses CONTEXT_MODULE
71 * @param int $field
72 * @param int $data
73 * @param int $cm
75 function __construct($field=0, $data=0, $cm=0) { // Field or data or both, each can be id or object
76 global $DB;
78 if (empty($field) && empty($data)) {
79 print_error('missingfield', 'data');
82 if (!empty($field)) {
83 if (is_object($field)) {
84 $this->field = $field; // Programmer knows what they are doing, we hope
85 } else if (!$this->field = $DB->get_record('data_fields', array('id'=>$field))) {
86 print_error('invalidfieldid', 'data');
88 if (empty($data)) {
89 if (!$this->data = $DB->get_record('data', array('id'=>$this->field->dataid))) {
90 print_error('invalidid', 'data');
95 if (empty($this->data)) { // We need to define this properly
96 if (!empty($data)) {
97 if (is_object($data)) {
98 $this->data = $data; // Programmer knows what they are doing, we hope
99 } else if (!$this->data = $DB->get_record('data', array('id'=>$data))) {
100 print_error('invalidid', 'data');
102 } else { // No way to define it!
103 print_error('missingdata', 'data');
107 if ($cm) {
108 $this->cm = $cm;
109 } else {
110 $this->cm = get_coursemodule_from_instance('data', $this->data->id);
113 if (empty($this->field)) { // We need to define some default values
114 $this->define_default_field();
117 $this->context = context_module::instance($this->cm->id);
122 * This field just sets up a default field object
124 * @return bool
126 function define_default_field() {
127 global $OUTPUT;
128 if (empty($this->data->id)) {
129 echo $OUTPUT->notification('Programmer error: dataid not defined in field class');
131 $this->field = new stdClass();
132 $this->field->id = 0;
133 $this->field->dataid = $this->data->id;
134 $this->field->type = $this->type;
135 $this->field->param1 = '';
136 $this->field->param2 = '';
137 $this->field->param3 = '';
138 $this->field->name = '';
139 $this->field->description = '';
141 return true;
145 * Set up the field object according to data in an object. Now is the time to clean it!
147 * @return bool
149 function define_field($data) {
150 $this->field->type = $this->type;
151 $this->field->dataid = $this->data->id;
153 $this->field->name = trim($data->name);
154 $this->field->description = trim($data->description);
156 if (isset($data->param1)) {
157 $this->field->param1 = trim($data->param1);
159 if (isset($data->param2)) {
160 $this->field->param2 = trim($data->param2);
162 if (isset($data->param3)) {
163 $this->field->param3 = trim($data->param3);
165 if (isset($data->param4)) {
166 $this->field->param4 = trim($data->param4);
168 if (isset($data->param5)) {
169 $this->field->param5 = trim($data->param5);
172 return true;
176 * Insert a new field in the database
177 * We assume the field object is already defined as $this->field
179 * @global object
180 * @return bool
182 function insert_field() {
183 global $DB, $OUTPUT;
185 if (empty($this->field)) {
186 echo $OUTPUT->notification('Programmer error: Field has not been defined yet! See define_field()');
187 return false;
190 $this->field->id = $DB->insert_record('data_fields',$this->field);
192 // Trigger an event for creating this field.
193 $event = \mod_data\event\field_created::create(array(
194 'objectid' => $this->field->id,
195 'context' => $this->context,
196 'other' => array(
197 'fieldname' => $this->field->name,
198 'dataid' => $this->data->id
201 $event->trigger();
203 return true;
208 * Update a field in the database
210 * @global object
211 * @return bool
213 function update_field() {
214 global $DB;
216 $DB->update_record('data_fields', $this->field);
218 // Trigger an event for updating this field.
219 $event = \mod_data\event\field_updated::create(array(
220 'objectid' => $this->field->id,
221 'context' => $this->context,
222 'other' => array(
223 'fieldname' => $this->field->name,
224 'dataid' => $this->data->id
227 $event->trigger();
229 return true;
233 * Delete a field completely
235 * @global object
236 * @return bool
238 function delete_field() {
239 global $DB;
241 if (!empty($this->field->id)) {
242 // Get the field before we delete it.
243 $field = $DB->get_record('data_fields', array('id' => $this->field->id));
245 $this->delete_content();
246 $DB->delete_records('data_fields', array('id'=>$this->field->id));
248 // Trigger an event for deleting this field.
249 $event = \mod_data\event\field_deleted::create(array(
250 'objectid' => $this->field->id,
251 'context' => $this->context,
252 'other' => array(
253 'fieldname' => $this->field->name,
254 'dataid' => $this->data->id
257 $event->add_record_snapshot('data_fields', $field);
258 $event->trigger();
261 return true;
265 * Print the relevant form element in the ADD template for this field
267 * @global object
268 * @param int $recordid
269 * @return string
271 function display_add_field($recordid=0){
272 global $DB;
274 if ($recordid){
275 $content = $DB->get_field('data_content', 'content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid));
276 } else {
277 $content = '';
280 // beware get_field returns false for new, empty records MDL-18567
281 if ($content===false) {
282 $content='';
285 $str = '<div title="'.s($this->field->description).'">';
286 $str .= '<label class="accesshide" for="field_'.$this->field->id.'">'.$this->field->description.'</label>';
287 $str .= '<input class="basefieldinput" type="text" name="field_'.$this->field->id.'" id="field_'.$this->field->id.'" value="'.s($content).'" />';
288 $str .= '</div>';
290 return $str;
294 * Print the relevant form element to define the attributes for this field
295 * viewable by teachers only.
297 * @global object
298 * @global object
299 * @return void Output is echo'd
301 function display_edit_field() {
302 global $CFG, $DB, $OUTPUT;
304 if (empty($this->field)) { // No field has been defined yet, try and make one
305 $this->define_default_field();
307 echo $OUTPUT->box_start('generalbox boxaligncenter boxwidthwide');
309 echo '<form id="editfield" action="'.$CFG->wwwroot.'/mod/data/field.php" method="post">'."\n";
310 echo '<input type="hidden" name="d" value="'.$this->data->id.'" />'."\n";
311 if (empty($this->field->id)) {
312 echo '<input type="hidden" name="mode" value="add" />'."\n";
313 $savebutton = get_string('add');
314 } else {
315 echo '<input type="hidden" name="fid" value="'.$this->field->id.'" />'."\n";
316 echo '<input type="hidden" name="mode" value="update" />'."\n";
317 $savebutton = get_string('savechanges');
319 echo '<input type="hidden" name="type" value="'.$this->type.'" />'."\n";
320 echo '<input name="sesskey" value="'.sesskey().'" type="hidden" />'."\n";
322 echo $OUTPUT->heading($this->name(), 3);
324 require_once($CFG->dirroot.'/mod/data/field/'.$this->type.'/mod.html');
326 echo '<div class="mdl-align">';
327 echo '<input type="submit" value="'.$savebutton.'" />'."\n";
328 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />'."\n";
329 echo '</div>';
331 echo '</form>';
333 echo $OUTPUT->box_end();
337 * Display the content of the field in browse mode
339 * @global object
340 * @param int $recordid
341 * @param object $template
342 * @return bool|string
344 function display_browse_field($recordid, $template) {
345 global $DB;
347 if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
348 if (isset($content->content)) {
349 $options = new stdClass();
350 if ($this->field->param1 == '1') { // We are autolinking this field, so disable linking within us
351 //$content->content = '<span class="nolink">'.$content->content.'</span>';
352 //$content->content1 = FORMAT_HTML;
353 $options->filter=false;
355 $options->para = false;
356 $str = format_text($content->content, $content->content1, $options);
357 } else {
358 $str = '';
360 return $str;
362 return false;
366 * Update the content of one data field in the data_content table
367 * @global object
368 * @param int $recordid
369 * @param mixed $value
370 * @param string $name
371 * @return bool
373 function update_content($recordid, $value, $name=''){
374 global $DB;
376 $content = new stdClass();
377 $content->fieldid = $this->field->id;
378 $content->recordid = $recordid;
379 $content->content = clean_param($value, PARAM_NOTAGS);
381 if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
382 $content->id = $oldcontent->id;
383 return $DB->update_record('data_content', $content);
384 } else {
385 return $DB->insert_record('data_content', $content);
390 * Delete all content associated with the field
392 * @global object
393 * @param int $recordid
394 * @return bool
396 function delete_content($recordid=0) {
397 global $DB;
399 if ($recordid) {
400 $conditions = array('fieldid'=>$this->field->id, 'recordid'=>$recordid);
401 } else {
402 $conditions = array('fieldid'=>$this->field->id);
405 $rs = $DB->get_recordset('data_content', $conditions);
406 if ($rs->valid()) {
407 $fs = get_file_storage();
408 foreach ($rs as $content) {
409 $fs->delete_area_files($this->context->id, 'mod_data', 'content', $content->id);
412 $rs->close();
414 return $DB->delete_records('data_content', $conditions);
418 * Check if a field from an add form is empty
420 * @param mixed $value
421 * @param mixed $name
422 * @return bool
424 function notemptyfield($value, $name) {
425 return !empty($value);
429 * Just in case a field needs to print something before the whole form
431 function print_before_form() {
435 * Just in case a field needs to print something after the whole form
437 function print_after_form() {
442 * Returns the sortable field for the content. By default, it's just content
443 * but for some plugins, it could be content 1 - content4
445 * @return string
447 function get_sort_field() {
448 return 'content';
452 * Returns the SQL needed to refer to the column. Some fields may need to CAST() etc.
454 * @param string $fieldname
455 * @return string $fieldname
457 function get_sort_sql($fieldname) {
458 return $fieldname;
462 * Returns the name/type of the field
464 * @return string
466 function name() {
467 return get_string('name'.$this->type, 'data');
471 * Prints the respective type icon
473 * @global object
474 * @return string
476 function image() {
477 global $OUTPUT;
479 $params = array('d'=>$this->data->id, 'fid'=>$this->field->id, 'mode'=>'display', 'sesskey'=>sesskey());
480 $link = new moodle_url('/mod/data/field.php', $params);
481 $str = '<a href="'.$link->out().'">';
482 $str .= '<img src="'.$OUTPUT->pix_url('field/'.$this->type, 'data') . '" ';
483 $str .= 'height="'.$this->iconheight.'" width="'.$this->iconwidth.'" alt="'.$this->type.'" title="'.$this->type.'" /></a>';
484 return $str;
488 * Per default, it is assumed that fields support text exporting.
489 * Override this (return false) on fields not supporting text exporting.
491 * @return bool true
493 function text_export_supported() {
494 return true;
498 * Per default, return the record's text value only from the "content" field.
499 * Override this in fields class if necesarry.
501 * @param string $record
502 * @return string
504 function export_text_value($record) {
505 if ($this->text_export_supported()) {
506 return $record->content;
511 * @param string $relativepath
512 * @return bool false
514 function file_ok($relativepath) {
515 return false;
521 * Given a template and a dataid, generate a default case template
523 * @global object
524 * @param object $data
525 * @param string template [addtemplate, singletemplate, listtempalte, rsstemplate]
526 * @param int $recordid
527 * @param bool $form
528 * @param bool $update
529 * @return bool|string
531 function data_generate_default_template(&$data, $template, $recordid=0, $form=false, $update=true) {
532 global $DB;
534 if (!$data && !$template) {
535 return false;
537 if ($template == 'csstemplate' or $template == 'jstemplate' ) {
538 return '';
541 // get all the fields for that database
542 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'id')) {
544 $table = new html_table();
545 $table->attributes['class'] = 'mod-data-default-template';
546 $table->colclasses = array('template-field', 'template-token');
547 $table->data = array();
548 foreach ($fields as $field) {
549 if ($form) { // Print forms instead of data
550 $fieldobj = data_get_field($field, $data);
551 $token = $fieldobj->display_add_field($recordid);
552 } else { // Just print the tag
553 $token = '[['.$field->name.']]';
555 $table->data[] = array(
556 $field->name.': ',
557 $token
560 if ($template == 'listtemplate') {
561 $cell = new html_table_cell('##edit## ##more## ##delete## ##approve## ##disapprove## ##export##');
562 $cell->colspan = 2;
563 $cell->attributes['class'] = 'controls';
564 $table->data[] = new html_table_row(array($cell));
565 } else if ($template == 'singletemplate') {
566 $cell = new html_table_cell('##edit## ##delete## ##approve## ##disapprove## ##export##');
567 $cell->colspan = 2;
568 $cell->attributes['class'] = 'controls';
569 $table->data[] = new html_table_row(array($cell));
570 } else if ($template == 'asearchtemplate') {
571 $row = new html_table_row(array(get_string('authorfirstname', 'data').': ', '##firstname##'));
572 $row->attributes['class'] = 'searchcontrols';
573 $table->data[] = $row;
574 $row = new html_table_row(array(get_string('authorlastname', 'data').': ', '##lastname##'));
575 $row->attributes['class'] = 'searchcontrols';
576 $table->data[] = $row;
579 $str = '';
580 if ($template == 'listtemplate'){
581 $str .= '##delcheck##';
582 $str .= html_writer::empty_tag('br');
585 $str .= html_writer::start_tag('div', array('class' => 'defaulttemplate'));
586 $str .= html_writer::table($table);
587 $str .= html_writer::end_tag('div');
588 if ($template == 'listtemplate'){
589 $str .= html_writer::empty_tag('hr');
592 if ($update) {
593 $newdata = new stdClass();
594 $newdata->id = $data->id;
595 $newdata->{$template} = $str;
596 $DB->update_record('data', $newdata);
597 $data->{$template} = $str;
600 return $str;
606 * Search for a field name and replaces it with another one in all the
607 * form templates. Set $newfieldname as '' if you want to delete the
608 * field from the form.
610 * @global object
611 * @param object $data
612 * @param string $searchfieldname
613 * @param string $newfieldname
614 * @return bool
616 function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
617 global $DB;
619 if (!empty($newfieldname)) {
620 $prestring = '[[';
621 $poststring = ']]';
622 $idpart = '#id';
624 } else {
625 $prestring = '';
626 $poststring = '';
627 $idpart = '';
630 $newdata = new stdClass();
631 $newdata->id = $data->id;
632 $newdata->singletemplate = str_ireplace('[['.$searchfieldname.']]',
633 $prestring.$newfieldname.$poststring, $data->singletemplate);
635 $newdata->listtemplate = str_ireplace('[['.$searchfieldname.']]',
636 $prestring.$newfieldname.$poststring, $data->listtemplate);
638 $newdata->addtemplate = str_ireplace('[['.$searchfieldname.']]',
639 $prestring.$newfieldname.$poststring, $data->addtemplate);
641 $newdata->addtemplate = str_ireplace('[['.$searchfieldname.'#id]]',
642 $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate);
644 $newdata->rsstemplate = str_ireplace('[['.$searchfieldname.']]',
645 $prestring.$newfieldname.$poststring, $data->rsstemplate);
647 return $DB->update_record('data', $newdata);
652 * Appends a new field at the end of the form template.
654 * @global object
655 * @param object $data
656 * @param string $newfieldname
658 function data_append_new_field_to_templates($data, $newfieldname) {
659 global $DB;
661 $newdata = new stdClass();
662 $newdata->id = $data->id;
663 $change = false;
665 if (!empty($data->singletemplate)) {
666 $newdata->singletemplate = $data->singletemplate.' [[' . $newfieldname .']]';
667 $change = true;
669 if (!empty($data->addtemplate)) {
670 $newdata->addtemplate = $data->addtemplate.' [[' . $newfieldname . ']]';
671 $change = true;
673 if (!empty($data->rsstemplate)) {
674 $newdata->rsstemplate = $data->singletemplate.' [[' . $newfieldname . ']]';
675 $change = true;
677 if ($change) {
678 $DB->update_record('data', $newdata);
684 * given a field name
685 * this function creates an instance of the particular subfield class
687 * @global object
688 * @param string $name
689 * @param object $data
690 * @return object|bool
692 function data_get_field_from_name($name, $data){
693 global $DB;
695 $field = $DB->get_record('data_fields', array('name'=>$name, 'dataid'=>$data->id));
697 if ($field) {
698 return data_get_field($field, $data);
699 } else {
700 return false;
705 * given a field id
706 * this function creates an instance of the particular subfield class
708 * @global object
709 * @param int $fieldid
710 * @param object $data
711 * @return bool|object
713 function data_get_field_from_id($fieldid, $data){
714 global $DB;
716 $field = $DB->get_record('data_fields', array('id'=>$fieldid, 'dataid'=>$data->id));
718 if ($field) {
719 return data_get_field($field, $data);
720 } else {
721 return false;
726 * given a field id
727 * this function creates an instance of the particular subfield class
729 * @global object
730 * @param string $type
731 * @param object $data
732 * @return object
734 function data_get_field_new($type, $data) {
735 global $CFG;
737 require_once($CFG->dirroot.'/mod/data/field/'.$type.'/field.class.php');
738 $newfield = 'data_field_'.$type;
739 $newfield = new $newfield(0, $data);
740 return $newfield;
744 * returns a subclass field object given a record of the field, used to
745 * invoke plugin methods
746 * input: $param $field - record from db
748 * @global object
749 * @param object $field
750 * @param object $data
751 * @param object $cm
752 * @return object
754 function data_get_field($field, $data, $cm=null) {
755 global $CFG;
757 if ($field) {
758 require_once('field/'.$field->type.'/field.class.php');
759 $newfield = 'data_field_'.$field->type;
760 $newfield = new $newfield($field, $data, $cm);
761 return $newfield;
767 * Given record object (or id), returns true if the record belongs to the current user
769 * @global object
770 * @global object
771 * @param mixed $record record object or id
772 * @return bool
774 function data_isowner($record) {
775 global $USER, $DB;
777 if (!isloggedin()) { // perf shortcut
778 return false;
781 if (!is_object($record)) {
782 if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
783 return false;
787 return ($record->userid == $USER->id);
791 * has a user reached the max number of entries?
793 * @param object $data
794 * @return bool
796 function data_atmaxentries($data){
797 if (!$data->maxentries){
798 return false;
800 } else {
801 return (data_numentries($data) >= $data->maxentries);
806 * returns the number of entries already made by this user
808 * @global object
809 * @global object
810 * @param object $data
811 * @return int
813 function data_numentries($data){
814 global $USER, $DB;
815 $sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
816 return $DB->count_records_sql($sql, array($data->id, $USER->id));
820 * function that takes in a dataid and adds a record
821 * this is used everytime an add template is submitted
823 * @global object
824 * @global object
825 * @param object $data
826 * @param int $groupid
827 * @return bool
829 function data_add_record($data, $groupid=0){
830 global $USER, $DB;
832 $cm = get_coursemodule_from_instance('data', $data->id);
833 $context = context_module::instance($cm->id);
835 $record = new stdClass();
836 $record->userid = $USER->id;
837 $record->dataid = $data->id;
838 $record->groupid = $groupid;
839 $record->timecreated = $record->timemodified = time();
840 if (has_capability('mod/data:approve', $context)) {
841 $record->approved = 1;
842 } else {
843 $record->approved = 0;
845 $record->id = $DB->insert_record('data_records', $record);
847 // Trigger an event for creating this record.
848 $event = \mod_data\event\record_created::create(array(
849 'objectid' => $record->id,
850 'context' => $context,
851 'other' => array(
852 'dataid' => $data->id
855 $event->trigger();
857 return $record->id;
861 * check the multple existence any tag in a template
863 * check to see if there are 2 or more of the same tag being used.
865 * @global object
866 * @param int $dataid,
867 * @param string $template
868 * @return bool
870 function data_tags_check($dataid, $template) {
871 global $DB, $OUTPUT;
873 // first get all the possible tags
874 $fields = $DB->get_records('data_fields', array('dataid'=>$dataid));
875 // then we generate strings to replace
876 $tagsok = true; // let's be optimistic
877 foreach ($fields as $field){
878 $pattern="/\[\[".$field->name."\]\]/i";
879 if (preg_match_all($pattern, $template, $dummy)>1){
880 $tagsok = false;
881 echo $OUTPUT->notification('[['.$field->name.']] - '.get_string('multipletags','data'));
884 // else return true
885 return $tagsok;
889 * Adds an instance of a data
891 * @param stdClass $data
892 * @param mod_data_mod_form $mform
893 * @return int intance id
895 function data_add_instance($data, $mform = null) {
896 global $DB;
898 if (empty($data->assessed)) {
899 $data->assessed = 0;
902 $data->timemodified = time();
904 $data->id = $DB->insert_record('data', $data);
906 data_grade_item_update($data);
908 return $data->id;
912 * updates an instance of a data
914 * @global object
915 * @param object $data
916 * @return bool
918 function data_update_instance($data) {
919 global $DB, $OUTPUT;
921 $data->timemodified = time();
922 $data->id = $data->instance;
924 if (empty($data->assessed)) {
925 $data->assessed = 0;
928 if (empty($data->ratingtime) or empty($data->assessed)) {
929 $data->assesstimestart = 0;
930 $data->assesstimefinish = 0;
933 if (empty($data->notification)) {
934 $data->notification = 0;
937 $DB->update_record('data', $data);
939 data_grade_item_update($data);
941 return true;
946 * deletes an instance of a data
948 * @global object
949 * @param int $id
950 * @return bool
952 function data_delete_instance($id) { // takes the dataid
953 global $DB, $CFG;
955 if (!$data = $DB->get_record('data', array('id'=>$id))) {
956 return false;
959 $cm = get_coursemodule_from_instance('data', $data->id);
960 $context = context_module::instance($cm->id);
962 /// Delete all the associated information
964 // files
965 $fs = get_file_storage();
966 $fs->delete_area_files($context->id, 'mod_data');
968 // get all the records in this data
969 $sql = "SELECT r.id
970 FROM {data_records} r
971 WHERE r.dataid = ?";
973 $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
975 // delete all the records and fields
976 $DB->delete_records('data_records', array('dataid'=>$id));
977 $DB->delete_records('data_fields', array('dataid'=>$id));
979 // Delete the instance itself
980 $result = $DB->delete_records('data', array('id'=>$id));
982 // cleanup gradebook
983 data_grade_item_delete($data);
985 return $result;
989 * returns a summary of data activity of this user
991 * @global object
992 * @param object $course
993 * @param object $user
994 * @param object $mod
995 * @param object $data
996 * @return object|null
998 function data_user_outline($course, $user, $mod, $data) {
999 global $DB, $CFG;
1000 require_once("$CFG->libdir/gradelib.php");
1002 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1003 if (empty($grades->items[0]->grades)) {
1004 $grade = false;
1005 } else {
1006 $grade = reset($grades->items[0]->grades);
1010 if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id, 'userid'=>$user->id))) {
1011 $result = new stdClass();
1012 $result->info = get_string('numrecords', 'data', $countrecords);
1013 $lastrecord = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
1014 WHERE dataid = ? AND userid = ?
1015 ORDER BY timemodified DESC', array($data->id, $user->id), true);
1016 $result->time = $lastrecord->timemodified;
1017 if ($grade) {
1018 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1020 return $result;
1021 } else if ($grade) {
1022 $result = new stdClass();
1023 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1025 //datesubmitted == time created. dategraded == time modified or time overridden
1026 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1027 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1028 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1029 $result->time = $grade->dategraded;
1030 } else {
1031 $result->time = $grade->datesubmitted;
1034 return $result;
1036 return NULL;
1040 * Prints all the records uploaded by this user
1042 * @global object
1043 * @param object $course
1044 * @param object $user
1045 * @param object $mod
1046 * @param object $data
1048 function data_user_complete($course, $user, $mod, $data) {
1049 global $DB, $CFG, $OUTPUT;
1050 require_once("$CFG->libdir/gradelib.php");
1052 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1053 if (!empty($grades->items[0]->grades)) {
1054 $grade = reset($grades->items[0]->grades);
1055 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1056 if ($grade->str_feedback) {
1057 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1061 if ($records = $DB->get_records('data_records', array('dataid'=>$data->id,'userid'=>$user->id), 'timemodified DESC')) {
1062 data_print_template('singletemplate', $records, $data);
1067 * Return grade for given user or all users.
1069 * @global object
1070 * @param object $data
1071 * @param int $userid optional user id, 0 means all users
1072 * @return array array of grades, false if none
1074 function data_get_user_grades($data, $userid=0) {
1075 global $CFG;
1077 require_once($CFG->dirroot.'/rating/lib.php');
1079 $ratingoptions = new stdClass;
1080 $ratingoptions->component = 'mod_data';
1081 $ratingoptions->ratingarea = 'entry';
1082 $ratingoptions->modulename = 'data';
1083 $ratingoptions->moduleid = $data->id;
1085 $ratingoptions->userid = $userid;
1086 $ratingoptions->aggregationmethod = $data->assessed;
1087 $ratingoptions->scaleid = $data->scale;
1088 $ratingoptions->itemtable = 'data_records';
1089 $ratingoptions->itemtableusercolumn = 'userid';
1091 $rm = new rating_manager();
1092 return $rm->get_user_grades($ratingoptions);
1096 * Update activity grades
1098 * @category grade
1099 * @param object $data
1100 * @param int $userid specific user only, 0 means all
1101 * @param bool $nullifnone
1103 function data_update_grades($data, $userid=0, $nullifnone=true) {
1104 global $CFG, $DB;
1105 require_once($CFG->libdir.'/gradelib.php');
1107 if (!$data->assessed) {
1108 data_grade_item_update($data);
1110 } else if ($grades = data_get_user_grades($data, $userid)) {
1111 data_grade_item_update($data, $grades);
1113 } else if ($userid and $nullifnone) {
1114 $grade = new stdClass();
1115 $grade->userid = $userid;
1116 $grade->rawgrade = NULL;
1117 data_grade_item_update($data, $grade);
1119 } else {
1120 data_grade_item_update($data);
1125 * Update/create grade item for given data
1127 * @category grade
1128 * @param stdClass $data A database instance with extra cmidnumber property
1129 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1130 * @return object grade_item
1132 function data_grade_item_update($data, $grades=NULL) {
1133 global $CFG;
1134 require_once($CFG->libdir.'/gradelib.php');
1136 $params = array('itemname'=>$data->name, 'idnumber'=>$data->cmidnumber);
1138 if (!$data->assessed or $data->scale == 0) {
1139 $params['gradetype'] = GRADE_TYPE_NONE;
1141 } else if ($data->scale > 0) {
1142 $params['gradetype'] = GRADE_TYPE_VALUE;
1143 $params['grademax'] = $data->scale;
1144 $params['grademin'] = 0;
1146 } else if ($data->scale < 0) {
1147 $params['gradetype'] = GRADE_TYPE_SCALE;
1148 $params['scaleid'] = -$data->scale;
1151 if ($grades === 'reset') {
1152 $params['reset'] = true;
1153 $grades = NULL;
1156 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, $grades, $params);
1160 * Delete grade item for given data
1162 * @category grade
1163 * @param object $data object
1164 * @return object grade_item
1166 function data_grade_item_delete($data) {
1167 global $CFG;
1168 require_once($CFG->libdir.'/gradelib.php');
1170 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, NULL, array('deleted'=>1));
1173 // junk functions
1175 * takes a list of records, the current data, a search string,
1176 * and mode to display prints the translated template
1178 * @global object
1179 * @global object
1180 * @param string $template
1181 * @param array $records
1182 * @param object $data
1183 * @param string $search
1184 * @param int $page
1185 * @param bool $return
1186 * @param object $jumpurl a moodle_url by which to jump back to the record list (can be null)
1187 * @return mixed
1189 function data_print_template($template, $records, $data, $search='', $page=0, $return=false, moodle_url $jumpurl=null) {
1190 global $CFG, $DB, $OUTPUT;
1192 $cm = get_coursemodule_from_instance('data', $data->id);
1193 $context = context_module::instance($cm->id);
1195 static $fields = NULL;
1196 static $isteacher;
1197 static $dataid = NULL;
1199 if (empty($dataid)) {
1200 $dataid = $data->id;
1201 } else if ($dataid != $data->id) {
1202 $fields = NULL;
1205 if (empty($fields)) {
1206 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1207 foreach ($fieldrecords as $fieldrecord) {
1208 $fields[]= data_get_field($fieldrecord, $data);
1210 $isteacher = has_capability('mod/data:managetemplates', $context);
1213 if (empty($records)) {
1214 return;
1217 if (!$jumpurl) {
1218 $jumpurl = new moodle_url('/mod/data/view.php', array('d' => $data->id));
1220 $jumpurl = new moodle_url($jumpurl, array('page' => $page, 'sesskey' => sesskey()));
1222 // Check whether this activity is read-only at present
1223 $readonly = data_in_readonly_period($data);
1225 foreach ($records as $record) { // Might be just one for the single template
1227 // Replacing tags
1228 $patterns = array();
1229 $replacement = array();
1231 // Then we generate strings to replace for normal tags
1232 foreach ($fields as $field) {
1233 $patterns[]='[['.$field->field->name.']]';
1234 $replacement[] = highlight($search, $field->display_browse_field($record->id, $template));
1237 $canmanageentries = has_capability('mod/data:manageentries', $context);
1239 // Replacing special tags (##Edit##, ##Delete##, ##More##)
1240 $patterns[]='##edit##';
1241 $patterns[]='##delete##';
1242 if ($canmanageentries || (!$readonly && data_isowner($record->id))) {
1243 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d='
1244 .$data->id.'&amp;rid='.$record->id.'&amp;sesskey='.sesskey().'"><img src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" alt="'.get_string('edit').'" title="'.get_string('edit').'" /></a>';
1245 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='
1246 .$data->id.'&amp;delete='.$record->id.'&amp;sesskey='.sesskey().'"><img src="'.$OUTPUT->pix_url('t/delete') . '" class="iconsmall" alt="'.get_string('delete').'" title="'.get_string('delete').'" /></a>';
1247 } else {
1248 $replacement[] = '';
1249 $replacement[] = '';
1252 $moreurl = $CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&amp;rid=' . $record->id;
1253 if ($search) {
1254 $moreurl .= '&amp;filter=1';
1256 $patterns[]='##more##';
1257 $replacement[] = '<a href="'.$moreurl.'"><img src="'.$OUTPUT->pix_url('t/preview').
1258 '" class="iconsmall" alt="'.get_string('more', 'data').'" title="'.get_string('more', 'data').
1259 '" /></a>';
1261 $patterns[]='##moreurl##';
1262 $replacement[] = $moreurl;
1264 $patterns[]='##delcheck##';
1265 if ($canmanageentries) {
1266 $replacement[] = html_writer::checkbox('delcheck[]', $record->id, false, '', array('class' => 'recordcheckbox'));
1267 } else {
1268 $replacement[] = '';
1271 $patterns[]='##user##';
1272 $replacement[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$record->userid.
1273 '&amp;course='.$data->course.'">'.fullname($record).'</a>';
1275 $patterns[] = '##userpicture##';
1276 $ruser = $DB->get_record('user', array('id' => $record->userid));
1277 $replacement[] = $OUTPUT->user_picture($ruser, array('courseid' => $cm->id));
1279 $patterns[]='##export##';
1281 if (!empty($CFG->enableportfolios) && ($template == 'singletemplate' || $template == 'listtemplate')
1282 && ((has_capability('mod/data:exportentry', $context)
1283 || (data_isowner($record->id) && has_capability('mod/data:exportownentry', $context))))) {
1284 require_once($CFG->libdir . '/portfoliolib.php');
1285 $button = new portfolio_add_button();
1286 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id, 'recordid' => $record->id), 'mod_data');
1287 list($formats, $files) = data_portfolio_caller::formats($fields, $record);
1288 $button->set_formats($formats);
1289 $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1290 } else {
1291 $replacement[] = '';
1294 $patterns[] = '##timeadded##';
1295 $replacement[] = userdate($record->timecreated);
1297 $patterns[] = '##timemodified##';
1298 $replacement [] = userdate($record->timemodified);
1300 $patterns[]='##approve##';
1301 if (has_capability('mod/data:approve', $context) && ($data->approval) && (!$record->approved)) {
1302 $approveurl = new moodle_url($jumpurl, array('approve' => $record->id));
1303 $approveicon = new pix_icon('t/approve', get_string('approve', 'data'), '', array('class' => 'iconsmall'));
1304 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($approveurl, $approveicon),
1305 array('class' => 'approve'));
1306 } else {
1307 $replacement[] = '';
1310 $patterns[]='##disapprove##';
1311 if (has_capability('mod/data:approve', $context) && ($data->approval) && ($record->approved)) {
1312 $disapproveurl = new moodle_url($jumpurl, array('disapprove' => $record->id));
1313 $disapproveicon = new pix_icon('t/block', get_string('disapprove', 'data'), '', array('class' => 'iconsmall'));
1314 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($disapproveurl, $disapproveicon),
1315 array('class' => 'disapprove'));
1316 } else {
1317 $replacement[] = '';
1320 $patterns[]='##comments##';
1321 if (($template == 'listtemplate') && ($data->comments)) {
1323 if (!empty($CFG->usecomments)) {
1324 require_once($CFG->dirroot . '/comment/lib.php');
1325 list($context, $course, $cm) = get_context_info_array($context->id);
1326 $cmt = new stdClass();
1327 $cmt->context = $context;
1328 $cmt->course = $course;
1329 $cmt->cm = $cm;
1330 $cmt->area = 'database_entry';
1331 $cmt->itemid = $record->id;
1332 $cmt->showcount = true;
1333 $cmt->component = 'mod_data';
1334 $comment = new comment($cmt);
1335 $replacement[] = $comment->output(true);
1337 } else {
1338 $replacement[] = '';
1341 // actual replacement of the tags
1342 $newtext = str_ireplace($patterns, $replacement, $data->{$template});
1344 // no more html formatting and filtering - see MDL-6635
1345 if ($return) {
1346 return $newtext;
1347 } else {
1348 echo $newtext;
1350 // hack alert - return is always false in singletemplate anyway ;-)
1351 /**********************************
1352 * Printing Ratings Form *
1353 *********************************/
1354 if ($template == 'singletemplate') { //prints ratings options
1355 data_print_ratings($data, $record);
1358 /**********************************
1359 * Printing Comments Form *
1360 *********************************/
1361 if (($template == 'singletemplate') && ($data->comments)) {
1362 if (!empty($CFG->usecomments)) {
1363 require_once($CFG->dirroot . '/comment/lib.php');
1364 list($context, $course, $cm) = get_context_info_array($context->id);
1365 $cmt = new stdClass();
1366 $cmt->context = $context;
1367 $cmt->course = $course;
1368 $cmt->cm = $cm;
1369 $cmt->area = 'database_entry';
1370 $cmt->itemid = $record->id;
1371 $cmt->showcount = true;
1372 $cmt->component = 'mod_data';
1373 $comment = new comment($cmt);
1374 $comment->output(false);
1382 * Return rating related permissions
1384 * @param string $contextid the context id
1385 * @param string $component the component to get rating permissions for
1386 * @param string $ratingarea the rating area to get permissions for
1387 * @return array an associative array of the user's rating permissions
1389 function data_rating_permissions($contextid, $component, $ratingarea) {
1390 $context = context::instance_by_id($contextid, MUST_EXIST);
1391 if ($component != 'mod_data' || $ratingarea != 'entry') {
1392 return null;
1394 return array(
1395 'view' => has_capability('mod/data:viewrating',$context),
1396 'viewany' => has_capability('mod/data:viewanyrating',$context),
1397 'viewall' => has_capability('mod/data:viewallratings',$context),
1398 'rate' => has_capability('mod/data:rate',$context)
1403 * Validates a submitted rating
1404 * @param array $params submitted data
1405 * context => object the context in which the rated items exists [required]
1406 * itemid => int the ID of the object being rated
1407 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1408 * rating => int the submitted rating
1409 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1410 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
1411 * @return boolean true if the rating is valid. Will throw rating_exception if not
1413 function data_rating_validate($params) {
1414 global $DB, $USER;
1416 // Check the component is mod_data
1417 if ($params['component'] != 'mod_data') {
1418 throw new rating_exception('invalidcomponent');
1421 // Check the ratingarea is entry (the only rating area in data module)
1422 if ($params['ratingarea'] != 'entry') {
1423 throw new rating_exception('invalidratingarea');
1426 // Check the rateduserid is not the current user .. you can't rate your own entries
1427 if ($params['rateduserid'] == $USER->id) {
1428 throw new rating_exception('nopermissiontorate');
1431 $datasql = "SELECT d.id as dataid, d.scale, d.course, r.userid as userid, d.approval, r.approved, r.timecreated, d.assesstimestart, d.assesstimefinish, r.groupid
1432 FROM {data_records} r
1433 JOIN {data} d ON r.dataid = d.id
1434 WHERE r.id = :itemid";
1435 $dataparams = array('itemid'=>$params['itemid']);
1436 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1437 //item doesn't exist
1438 throw new rating_exception('invaliditemid');
1441 if ($info->scale != $params['scaleid']) {
1442 //the scale being submitted doesnt match the one in the database
1443 throw new rating_exception('invalidscaleid');
1446 //check that the submitted rating is valid for the scale
1448 // lower limit
1449 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
1450 throw new rating_exception('invalidnum');
1453 // upper limit
1454 if ($info->scale < 0) {
1455 //its a custom scale
1456 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
1457 if ($scalerecord) {
1458 $scalearray = explode(',', $scalerecord->scale);
1459 if ($params['rating'] > count($scalearray)) {
1460 throw new rating_exception('invalidnum');
1462 } else {
1463 throw new rating_exception('invalidscaleid');
1465 } else if ($params['rating'] > $info->scale) {
1466 //if its numeric and submitted rating is above maximum
1467 throw new rating_exception('invalidnum');
1470 if ($info->approval && !$info->approved) {
1471 //database requires approval but this item isnt approved
1472 throw new rating_exception('nopermissiontorate');
1475 // check the item we're rating was created in the assessable time window
1476 if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
1477 if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
1478 throw new rating_exception('notavailable');
1482 $course = $DB->get_record('course', array('id'=>$info->course), '*', MUST_EXIST);
1483 $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1484 $context = context_module::instance($cm->id);
1486 // if the supplied context doesnt match the item's context
1487 if ($context->id != $params['context']->id) {
1488 throw new rating_exception('invalidcontext');
1491 // Make sure groups allow this user to see the item they're rating
1492 $groupid = $info->groupid;
1493 if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
1494 if (!groups_group_exists($groupid)) { // Can't find group
1495 throw new rating_exception('cannotfindgroup');//something is wrong
1498 if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1499 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
1500 throw new rating_exception('notmemberofgroup');
1504 return true;
1509 * function that takes in the current data, number of items per page,
1510 * a search string and prints a preference box in view.php
1512 * This preference box prints a searchable advanced search template if
1513 * a) A template is defined
1514 * b) The advanced search checkbox is checked.
1516 * @global object
1517 * @global object
1518 * @param object $data
1519 * @param int $perpage
1520 * @param string $search
1521 * @param string $sort
1522 * @param string $order
1523 * @param array $search_array
1524 * @param int $advanced
1525 * @param string $mode
1526 * @return void
1528 function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
1529 global $CFG, $DB, $PAGE, $OUTPUT;
1531 $cm = get_coursemodule_from_instance('data', $data->id);
1532 $context = context_module::instance($cm->id);
1533 echo '<br /><div class="datapreferences">';
1534 echo '<form id="options" action="view.php" method="get">';
1535 echo '<div>';
1536 echo '<input type="hidden" name="d" value="'.$data->id.'" />';
1537 if ($mode =='asearch') {
1538 $advanced = 1;
1539 echo '<input type="hidden" name="mode" value="list" />';
1541 echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
1542 $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
1543 20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
1544 echo html_writer::select($pagesizes, 'perpage', $perpage, false, array('id'=>'pref_perpage'));
1546 if ($advanced) {
1547 $regsearchclass = 'search_none';
1548 $advancedsearchclass = 'search_inline';
1549 } else {
1550 $regsearchclass = 'search_inline';
1551 $advancedsearchclass = 'search_none';
1553 echo '<div id="reg_search" class="' . $regsearchclass . '" >&nbsp;&nbsp;&nbsp;';
1554 echo '<label for="pref_search">'.get_string('search').'</label> <input type="text" size="16" name="search" id= "pref_search" value="'.s($search).'" /></div>';
1555 echo '&nbsp;&nbsp;&nbsp;<label for="pref_sortby">'.get_string('sortby').'</label> ';
1556 // foreach field, print the option
1557 echo '<select name="sort" id="pref_sortby">';
1558 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'name')) {
1559 echo '<optgroup label="'.get_string('fields', 'data').'">';
1560 foreach ($fields as $field) {
1561 if ($field->id == $sort) {
1562 echo '<option value="'.$field->id.'" selected="selected">'.$field->name.'</option>';
1563 } else {
1564 echo '<option value="'.$field->id.'">'.$field->name.'</option>';
1567 echo '</optgroup>';
1569 $options = array();
1570 $options[DATA_TIMEADDED] = get_string('timeadded', 'data');
1571 $options[DATA_TIMEMODIFIED] = get_string('timemodified', 'data');
1572 $options[DATA_FIRSTNAME] = get_string('authorfirstname', 'data');
1573 $options[DATA_LASTNAME] = get_string('authorlastname', 'data');
1574 if ($data->approval and has_capability('mod/data:approve', $context)) {
1575 $options[DATA_APPROVED] = get_string('approved', 'data');
1577 echo '<optgroup label="'.get_string('other', 'data').'">';
1578 foreach ($options as $key => $name) {
1579 if ($key == $sort) {
1580 echo '<option value="'.$key.'" selected="selected">'.$name.'</option>';
1581 } else {
1582 echo '<option value="'.$key.'">'.$name.'</option>';
1585 echo '</optgroup>';
1586 echo '</select>';
1587 echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
1588 echo '<select id="pref_order" name="order">';
1589 if ($order == 'ASC') {
1590 echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
1591 } else {
1592 echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1594 if ($order == 'DESC') {
1595 echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
1596 } else {
1597 echo '<option value="DESC">'.get_string('descending','data').'</option>';
1599 echo '</select>';
1601 if ($advanced) {
1602 $checked = ' checked="checked" ';
1604 else {
1605 $checked = '';
1607 $PAGE->requires->js('/mod/data/data.js');
1608 echo '&nbsp;<input type="hidden" name="advanced" value="0" />';
1609 echo '&nbsp;<input type="hidden" name="filter" value="1" />';
1610 echo '&nbsp;<input type="checkbox" id="advancedcheckbox" name="advanced" value="1" '.$checked.' onchange="showHideAdvSearch(this.checked);" /><label for="advancedcheckbox">'.get_string('advancedsearch', 'data').'</label>';
1611 echo '&nbsp;<input type="submit" value="'.get_string('savesettings','data').'" />';
1613 echo '<br />';
1614 echo '<div class="' . $advancedsearchclass . '" id="data_adv_form">';
1615 echo '<table class="boxaligncenter">';
1617 // print ASC or DESC
1618 echo '<tr><td colspan="2">&nbsp;</td></tr>';
1619 $i = 0;
1621 // Determine if we are printing all fields for advanced search, or the template for advanced search
1622 // If a template is not defined, use the deafault template and display all fields.
1623 if(empty($data->asearchtemplate)) {
1624 data_generate_default_template($data, 'asearchtemplate');
1627 static $fields = NULL;
1628 static $isteacher;
1629 static $dataid = NULL;
1631 if (empty($dataid)) {
1632 $dataid = $data->id;
1633 } else if ($dataid != $data->id) {
1634 $fields = NULL;
1637 if (empty($fields)) {
1638 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1639 foreach ($fieldrecords as $fieldrecord) {
1640 $fields[]= data_get_field($fieldrecord, $data);
1643 $isteacher = has_capability('mod/data:managetemplates', $context);
1646 // Replacing tags
1647 $patterns = array();
1648 $replacement = array();
1650 // Then we generate strings to replace for normal tags
1651 foreach ($fields as $field) {
1652 $fieldname = $field->field->name;
1653 $fieldname = preg_quote($fieldname, '/');
1654 $patterns[] = "/\[\[$fieldname\]\]/i";
1655 $searchfield = data_get_field_from_id($field->field->id, $data);
1656 if (!empty($search_array[$field->field->id]->data)) {
1657 $replacement[] = $searchfield->display_search_field($search_array[$field->field->id]->data);
1658 } else {
1659 $replacement[] = $searchfield->display_search_field();
1662 $fn = !empty($search_array[DATA_FIRSTNAME]->data) ? $search_array[DATA_FIRSTNAME]->data : '';
1663 $ln = !empty($search_array[DATA_LASTNAME]->data) ? $search_array[DATA_LASTNAME]->data : '';
1664 $patterns[] = '/##firstname##/';
1665 $replacement[] = '<label class="accesshide" for="u_fn">'.get_string('authorfirstname', 'data').'</label><input type="text" size="16" id="u_fn" name="u_fn" value="'.$fn.'" />';
1666 $patterns[] = '/##lastname##/';
1667 $replacement[] = '<label class="accesshide" for="u_ln">'.get_string('authorlastname', 'data').'</label><input type="text" size="16" id="u_ln" name="u_ln" value="'.$ln.'" />';
1669 // actual replacement of the tags
1670 $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate);
1672 $options = new stdClass();
1673 $options->para=false;
1674 $options->noclean=true;
1675 echo '<tr><td>';
1676 echo format_text($newtext, FORMAT_HTML, $options);
1677 echo '</td></tr>';
1679 echo '<tr><td colspan="4"><br/><input type="submit" value="'.get_string('savesettings','data').'" /><input type="submit" name="resetadv" value="'.get_string('resetsettings','data').'" /></td></tr>';
1680 echo '</table>';
1681 echo '</div>';
1682 echo '</div>';
1683 echo '</form>';
1684 echo '</div>';
1688 * @global object
1689 * @global object
1690 * @param object $data
1691 * @param object $record
1692 * @return void Output echo'd
1694 function data_print_ratings($data, $record) {
1695 global $OUTPUT;
1696 if (!empty($record->rating)){
1697 echo $OUTPUT->render($record->rating);
1702 * List the actions that correspond to a view of this module.
1703 * This is used by the participation report.
1705 * Note: This is not used by new logging system. Event with
1706 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1707 * be considered as view action.
1709 * @return array
1711 function data_get_view_actions() {
1712 return array('view');
1716 * List the actions that correspond to a post of this module.
1717 * This is used by the participation report.
1719 * Note: This is not used by new logging system. Event with
1720 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1721 * will be considered as post action.
1723 * @return array
1725 function data_get_post_actions() {
1726 return array('add','update','record delete');
1730 * @param string $name
1731 * @param int $dataid
1732 * @param int $fieldid
1733 * @return bool
1735 function data_fieldname_exists($name, $dataid, $fieldid = 0) {
1736 global $DB;
1738 if (!is_numeric($name)) {
1739 $like = $DB->sql_like('df.name', ':name', false);
1740 } else {
1741 $like = "df.name = :name";
1743 $params = array('name'=>$name);
1744 if ($fieldid) {
1745 $params['dataid'] = $dataid;
1746 $params['fieldid1'] = $fieldid;
1747 $params['fieldid2'] = $fieldid;
1748 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1749 WHERE $like AND df.dataid = :dataid
1750 AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
1751 } else {
1752 $params['dataid'] = $dataid;
1753 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1754 WHERE $like AND df.dataid = :dataid", $params);
1759 * @param array $fieldinput
1761 function data_convert_arrays_to_strings(&$fieldinput) {
1762 foreach ($fieldinput as $key => $val) {
1763 if (is_array($val)) {
1764 $str = '';
1765 foreach ($val as $inner) {
1766 $str .= $inner . ',';
1768 $str = substr($str, 0, -1);
1770 $fieldinput->$key = $str;
1777 * Converts a database (module instance) to use the Roles System
1779 * @global object
1780 * @global object
1781 * @uses CONTEXT_MODULE
1782 * @uses CAP_PREVENT
1783 * @uses CAP_ALLOW
1784 * @param object $data a data object with the same attributes as a record
1785 * from the data database table
1786 * @param int $datamodid the id of the data module, from the modules table
1787 * @param array $teacherroles array of roles that have archetype teacher
1788 * @param array $studentroles array of roles that have archetype student
1789 * @param array $guestroles array of roles that have archetype guest
1790 * @param int $cmid the course_module id for this data instance
1791 * @return boolean data module was converted or not
1793 function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
1794 global $CFG, $DB, $OUTPUT;
1796 if (!isset($data->participants) && !isset($data->assesspublic)
1797 && !isset($data->groupmode)) {
1798 // We assume that this database has already been converted to use the
1799 // Roles System. above fields get dropped the data module has been
1800 // upgraded to use Roles.
1801 return false;
1804 if (empty($cmid)) {
1805 // We were not given the course_module id. Try to find it.
1806 if (!$cm = get_coursemodule_from_instance('data', $data->id)) {
1807 echo $OUTPUT->notification('Could not get the course module for the data');
1808 return false;
1809 } else {
1810 $cmid = $cm->id;
1813 $context = context_module::instance($cmid);
1816 // $data->participants:
1817 // 1 - Only teachers can add entries
1818 // 3 - Teachers and students can add entries
1819 switch ($data->participants) {
1820 case 1:
1821 foreach ($studentroles as $studentrole) {
1822 assign_capability('mod/data:writeentry', CAP_PREVENT, $studentrole->id, $context->id);
1824 foreach ($teacherroles as $teacherrole) {
1825 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1827 break;
1828 case 3:
1829 foreach ($studentroles as $studentrole) {
1830 assign_capability('mod/data:writeentry', CAP_ALLOW, $studentrole->id, $context->id);
1832 foreach ($teacherroles as $teacherrole) {
1833 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1835 break;
1838 // $data->assessed:
1839 // 2 - Only teachers can rate posts
1840 // 1 - Everyone can rate posts
1841 // 0 - No one can rate posts
1842 switch ($data->assessed) {
1843 case 0:
1844 foreach ($studentroles as $studentrole) {
1845 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1847 foreach ($teacherroles as $teacherrole) {
1848 assign_capability('mod/data:rate', CAP_PREVENT, $teacherrole->id, $context->id);
1850 break;
1851 case 1:
1852 foreach ($studentroles as $studentrole) {
1853 assign_capability('mod/data:rate', CAP_ALLOW, $studentrole->id, $context->id);
1855 foreach ($teacherroles as $teacherrole) {
1856 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1858 break;
1859 case 2:
1860 foreach ($studentroles as $studentrole) {
1861 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1863 foreach ($teacherroles as $teacherrole) {
1864 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1866 break;
1869 // $data->assesspublic:
1870 // 0 - Students can only see their own ratings
1871 // 1 - Students can see everyone's ratings
1872 switch ($data->assesspublic) {
1873 case 0:
1874 foreach ($studentroles as $studentrole) {
1875 assign_capability('mod/data:viewrating', CAP_PREVENT, $studentrole->id, $context->id);
1877 foreach ($teacherroles as $teacherrole) {
1878 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1880 break;
1881 case 1:
1882 foreach ($studentroles as $studentrole) {
1883 assign_capability('mod/data:viewrating', CAP_ALLOW, $studentrole->id, $context->id);
1885 foreach ($teacherroles as $teacherrole) {
1886 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1888 break;
1891 if (empty($cm)) {
1892 $cm = $DB->get_record('course_modules', array('id'=>$cmid));
1895 switch ($cm->groupmode) {
1896 case NOGROUPS:
1897 break;
1898 case SEPARATEGROUPS:
1899 foreach ($studentroles as $studentrole) {
1900 assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id);
1902 foreach ($teacherroles as $teacherrole) {
1903 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1905 break;
1906 case VISIBLEGROUPS:
1907 foreach ($studentroles as $studentrole) {
1908 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id);
1910 foreach ($teacherroles as $teacherrole) {
1911 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1913 break;
1915 return true;
1919 * Returns the best name to show for a preset
1921 * @param string $shortname
1922 * @param string $path
1923 * @return string
1925 function data_preset_name($shortname, $path) {
1927 // We are looking inside the preset itself as a first choice, but also in normal data directory
1928 $string = get_string('modulename', 'datapreset_'.$shortname);
1930 if (substr($string, 0, 1) == '[') {
1931 return $shortname;
1932 } else {
1933 return $string;
1938 * Returns an array of all the available presets.
1940 * @return array
1942 function data_get_available_presets($context) {
1943 global $CFG, $USER;
1945 $presets = array();
1947 // First load the ratings sub plugins that exist within the modules preset dir
1948 if ($dirs = core_component::get_plugin_list('datapreset')) {
1949 foreach ($dirs as $dir=>$fulldir) {
1950 if (is_directory_a_preset($fulldir)) {
1951 $preset = new stdClass();
1952 $preset->path = $fulldir;
1953 $preset->userid = 0;
1954 $preset->shortname = $dir;
1955 $preset->name = data_preset_name($dir, $fulldir);
1956 if (file_exists($fulldir.'/screenshot.jpg')) {
1957 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.jpg';
1958 } else if (file_exists($fulldir.'/screenshot.png')) {
1959 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.png';
1960 } else if (file_exists($fulldir.'/screenshot.gif')) {
1961 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.gif';
1963 $presets[] = $preset;
1967 // Now add to that the site presets that people have saved
1968 $presets = data_get_available_site_presets($context, $presets);
1969 return $presets;
1973 * Gets an array of all of the presets that users have saved to the site.
1975 * @param stdClass $context The context that we are looking from.
1976 * @param array $presets
1977 * @return array An array of presets
1979 function data_get_available_site_presets($context, array $presets=array()) {
1980 global $USER;
1982 $fs = get_file_storage();
1983 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
1984 $canviewall = has_capability('mod/data:viewalluserpresets', $context);
1985 if (empty($files)) {
1986 return $presets;
1988 foreach ($files as $file) {
1989 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory() || (!$canviewall && $file->get_userid() != $USER->id)) {
1990 continue;
1992 $preset = new stdClass;
1993 $preset->path = $file->get_filepath();
1994 $preset->name = trim($preset->path, '/');
1995 $preset->shortname = $preset->name;
1996 $preset->userid = $file->get_userid();
1997 $preset->id = $file->get_id();
1998 $preset->storedfile = $file;
1999 $presets[] = $preset;
2001 return $presets;
2005 * Deletes a saved preset.
2007 * @param string $name
2008 * @return bool
2010 function data_delete_site_preset($name) {
2011 $fs = get_file_storage();
2013 $files = $fs->get_directory_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/');
2014 if (!empty($files)) {
2015 foreach ($files as $file) {
2016 $file->delete();
2020 $dir = $fs->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/', '.');
2021 if (!empty($dir)) {
2022 $dir->delete();
2024 return true;
2028 * Prints the heads for a page
2030 * @param stdClass $course
2031 * @param stdClass $cm
2032 * @param stdClass $data
2033 * @param string $currenttab
2035 function data_print_header($course, $cm, $data, $currenttab='') {
2037 global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
2039 $PAGE->set_title($data->name);
2040 echo $OUTPUT->header();
2041 echo $OUTPUT->heading(format_string($data->name), 2);
2042 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
2044 // Groups needed for Add entry tab
2045 $currentgroup = groups_get_activity_group($cm);
2046 $groupmode = groups_get_activity_groupmode($cm);
2048 // Print the tabs
2050 if ($currenttab) {
2051 include('tabs.php');
2054 // Print any notices
2056 if (!empty($displaynoticegood)) {
2057 echo $OUTPUT->notification($displaynoticegood, 'notifysuccess'); // good (usually green)
2058 } else if (!empty($displaynoticebad)) {
2059 echo $OUTPUT->notification($displaynoticebad); // bad (usuually red)
2064 * Can user add more entries?
2066 * @param object $data
2067 * @param mixed $currentgroup
2068 * @param int $groupmode
2069 * @param stdClass $context
2070 * @return bool
2072 function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
2073 global $USER;
2075 if (empty($context)) {
2076 $cm = get_coursemodule_from_instance('data', $data->id, 0, false, MUST_EXIST);
2077 $context = context_module::instance($cm->id);
2080 if (has_capability('mod/data:manageentries', $context)) {
2081 // no entry limits apply if user can manage
2083 } else if (!has_capability('mod/data:writeentry', $context)) {
2084 return false;
2086 } else if (data_atmaxentries($data)) {
2087 return false;
2088 } else if (data_in_readonly_period($data)) {
2089 // Check whether we're in a read-only period
2090 return false;
2093 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2094 return true;
2097 if ($currentgroup) {
2098 return groups_is_member($currentgroup);
2099 } else {
2100 //else it might be group 0 in visible mode
2101 if ($groupmode == VISIBLEGROUPS){
2102 return true;
2103 } else {
2104 return false;
2110 * Check whether the specified database activity is currently in a read-only period
2112 * @param object $data
2113 * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2115 function data_in_readonly_period($data) {
2116 $now = time();
2117 if (!$data->timeviewfrom && !$data->timeviewto) {
2118 return false;
2119 } else if (($data->timeviewfrom && $now < $data->timeviewfrom) || ($data->timeviewto && $now > $data->timeviewto)) {
2120 return false;
2122 return true;
2126 * @return bool
2128 function is_directory_a_preset($directory) {
2129 $directory = rtrim($directory, '/\\') . '/';
2130 $status = file_exists($directory.'singletemplate.html') &&
2131 file_exists($directory.'listtemplate.html') &&
2132 file_exists($directory.'listtemplateheader.html') &&
2133 file_exists($directory.'listtemplatefooter.html') &&
2134 file_exists($directory.'addtemplate.html') &&
2135 file_exists($directory.'rsstemplate.html') &&
2136 file_exists($directory.'rsstitletemplate.html') &&
2137 file_exists($directory.'csstemplate.css') &&
2138 file_exists($directory.'jstemplate.js') &&
2139 file_exists($directory.'preset.xml');
2141 return $status;
2145 * Abstract class used for data preset importers
2147 abstract class data_preset_importer {
2149 protected $course;
2150 protected $cm;
2151 protected $module;
2152 protected $directory;
2155 * Constructor
2157 * @param stdClass $course
2158 * @param stdClass $cm
2159 * @param stdClass $module
2160 * @param string $directory
2162 public function __construct($course, $cm, $module, $directory) {
2163 $this->course = $course;
2164 $this->cm = $cm;
2165 $this->module = $module;
2166 $this->directory = $directory;
2170 * Returns the name of the directory the preset is located in
2171 * @return string
2173 public function get_directory() {
2174 return basename($this->directory);
2178 * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2179 * @param file_storage $filestorage. should be null if using a conventional directory
2180 * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2181 * @param string $dir the directory to look in. null if using the Moodle file storage
2182 * @param string $filename the name of the file we want
2183 * @return string the contents of the file or null if the file doesn't exist.
2185 public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2186 if(empty($filestorage) || empty($fileobj)) {
2187 if (substr($dir, -1)!='/') {
2188 $dir .= '/';
2190 if (file_exists($dir.$filename)) {
2191 return file_get_contents($dir.$filename);
2192 } else {
2193 return null;
2195 } else {
2196 if ($filestorage->file_exists(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename)) {
2197 $file = $filestorage->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename);
2198 return $file->get_content();
2199 } else {
2200 return null;
2206 * Gets the preset settings
2207 * @global moodle_database $DB
2208 * @return stdClass
2210 public function get_preset_settings() {
2211 global $DB;
2213 $fs = $fileobj = null;
2214 if (!is_directory_a_preset($this->directory)) {
2215 //maybe the user requested a preset stored in the Moodle file storage
2217 $fs = get_file_storage();
2218 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2220 //preset name to find will be the final element of the directory
2221 $explodeddirectory = explode('/', $this->directory);
2222 $presettofind = end($explodeddirectory);
2224 //now go through the available files available and see if we can find it
2225 foreach ($files as $file) {
2226 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory()) {
2227 continue;
2229 $presetname = trim($file->get_filepath(), '/');
2230 if ($presetname==$presettofind) {
2231 $this->directory = $presetname;
2232 $fileobj = $file;
2236 if (empty($fileobj)) {
2237 print_error('invalidpreset', 'data', '', $this->directory);
2241 $allowed_settings = array(
2242 'intro',
2243 'comments',
2244 'requiredentries',
2245 'requiredentriestoview',
2246 'maxentries',
2247 'rssarticles',
2248 'approval',
2249 'defaultsortdir',
2250 'defaultsort');
2252 $result = new stdClass;
2253 $result->settings = new stdClass;
2254 $result->importfields = array();
2255 $result->currentfields = $DB->get_records('data_fields', array('dataid'=>$this->module->id));
2256 if (!$result->currentfields) {
2257 $result->currentfields = array();
2261 /* Grab XML */
2262 $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory,'preset.xml');
2263 $parsedxml = xmlize($presetxml, 0);
2265 /* First, do settings. Put in user friendly array. */
2266 $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
2267 $result->settings = new StdClass();
2268 foreach ($settingsarray as $setting => $value) {
2269 if (!is_array($value) || !in_array($setting, $allowed_settings)) {
2270 // unsupported setting
2271 continue;
2273 $result->settings->$setting = $value[0]['#'];
2276 /* Now work out fields to user friendly array */
2277 $fieldsarray = $parsedxml['preset']['#']['field'];
2278 foreach ($fieldsarray as $field) {
2279 if (!is_array($field)) {
2280 continue;
2282 $f = new StdClass();
2283 foreach ($field['#'] as $param => $value) {
2284 if (!is_array($value)) {
2285 continue;
2287 $f->$param = $value[0]['#'];
2289 $f->dataid = $this->module->id;
2290 $f->type = clean_param($f->type, PARAM_ALPHA);
2291 $result->importfields[] = $f;
2293 /* Now add the HTML templates to the settings array so we can update d */
2294 $result->settings->singletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"singletemplate.html");
2295 $result->settings->listtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplate.html");
2296 $result->settings->listtemplateheader = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplateheader.html");
2297 $result->settings->listtemplatefooter = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplatefooter.html");
2298 $result->settings->addtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"addtemplate.html");
2299 $result->settings->rsstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstemplate.html");
2300 $result->settings->rsstitletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstitletemplate.html");
2301 $result->settings->csstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"csstemplate.css");
2302 $result->settings->jstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"jstemplate.js");
2303 $result->settings->asearchtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"asearchtemplate.html");
2305 $result->settings->instance = $this->module->id;
2306 return $result;
2310 * Import the preset into the given database module
2311 * @return bool
2313 function import($overwritesettings) {
2314 global $DB, $CFG;
2316 $params = $this->get_preset_settings();
2317 $settings = $params->settings;
2318 $newfields = $params->importfields;
2319 $currentfields = $params->currentfields;
2320 $preservedfields = array();
2322 /* Maps fields and makes new ones */
2323 if (!empty($newfields)) {
2324 /* We require an injective mapping, and need to know what to protect */
2325 foreach ($newfields as $nid => $newfield) {
2326 $cid = optional_param("field_$nid", -1, PARAM_INT);
2327 if ($cid == -1) {
2328 continue;
2330 if (array_key_exists($cid, $preservedfields)){
2331 print_error('notinjectivemap', 'data');
2333 else $preservedfields[$cid] = true;
2336 foreach ($newfields as $nid => $newfield) {
2337 $cid = optional_param("field_$nid", -1, PARAM_INT);
2339 /* A mapping. Just need to change field params. Data kept. */
2340 if ($cid != -1 and isset($currentfields[$cid])) {
2341 $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->module);
2342 foreach ($newfield as $param => $value) {
2343 if ($param != "id") {
2344 $fieldobject->field->$param = $value;
2347 unset($fieldobject->field->similarfield);
2348 $fieldobject->update_field();
2349 unset($fieldobject);
2350 } else {
2351 /* Make a new field */
2352 include_once("field/$newfield->type/field.class.php");
2354 if (!isset($newfield->description)) {
2355 $newfield->description = '';
2357 $classname = 'data_field_'.$newfield->type;
2358 $fieldclass = new $classname($newfield, $this->module);
2359 $fieldclass->insert_field();
2360 unset($fieldclass);
2365 /* Get rid of all old unused data */
2366 if (!empty($preservedfields)) {
2367 foreach ($currentfields as $cid => $currentfield) {
2368 if (!array_key_exists($cid, $preservedfields)) {
2369 /* Data not used anymore so wipe! */
2370 print "Deleting field $currentfield->name<br />";
2372 $id = $currentfield->id;
2373 //Why delete existing data records and related comments/ratings??
2374 $DB->delete_records('data_content', array('fieldid'=>$id));
2375 $DB->delete_records('data_fields', array('id'=>$id));
2380 // handle special settings here
2381 if (!empty($settings->defaultsort)) {
2382 if (is_numeric($settings->defaultsort)) {
2383 // old broken value
2384 $settings->defaultsort = 0;
2385 } else {
2386 $settings->defaultsort = (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module->id, 'name'=>$settings->defaultsort));
2388 } else {
2389 $settings->defaultsort = 0;
2392 // do we want to overwrite all current database settings?
2393 if ($overwritesettings) {
2394 // all supported settings
2395 $overwrite = array_keys((array)$settings);
2396 } else {
2397 // only templates and sorting
2398 $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2399 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
2400 'asearchtemplate', 'defaultsortdir', 'defaultsort');
2403 // now overwrite current data settings
2404 foreach ($this->module as $prop=>$unused) {
2405 if (in_array($prop, $overwrite)) {
2406 $this->module->$prop = $settings->$prop;
2410 data_update_instance($this->module);
2412 return $this->cleanup();
2416 * Any clean up routines should go here
2417 * @return bool
2419 public function cleanup() {
2420 return true;
2425 * Data preset importer for uploaded presets
2427 class data_preset_upload_importer extends data_preset_importer {
2428 public function __construct($course, $cm, $module, $filepath) {
2429 global $USER;
2430 if (is_file($filepath)) {
2431 $fp = get_file_packer();
2432 if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2433 fulldelete($filepath);
2435 $filepath .= '_extracted';
2437 parent::__construct($course, $cm, $module, $filepath);
2439 public function cleanup() {
2440 return fulldelete($this->directory);
2445 * Data preset importer for existing presets
2447 class data_preset_existing_importer extends data_preset_importer {
2448 protected $userid;
2449 public function __construct($course, $cm, $module, $fullname) {
2450 global $USER;
2451 list($userid, $shortname) = explode('/', $fullname, 2);
2452 $context = context_module::instance($cm->id);
2453 if ($userid && ($userid != $USER->id) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2454 throw new coding_exception('Invalid preset provided');
2457 $this->userid = $userid;
2458 $filepath = data_preset_path($course, $userid, $shortname);
2459 parent::__construct($course, $cm, $module, $filepath);
2461 public function get_userid() {
2462 return $this->userid;
2467 * @global object
2468 * @global object
2469 * @param object $course
2470 * @param int $userid
2471 * @param string $shortname
2472 * @return string
2474 function data_preset_path($course, $userid, $shortname) {
2475 global $USER, $CFG;
2477 $context = context_course::instance($course->id);
2479 $userid = (int)$userid;
2481 $path = null;
2482 if ($userid > 0 && ($userid == $USER->id || has_capability('mod/data:viewalluserpresets', $context))) {
2483 $path = $CFG->dataroot.'/data/preset/'.$userid.'/'.$shortname;
2484 } else if ($userid == 0) {
2485 $path = $CFG->dirroot.'/mod/data/preset/'.$shortname;
2486 } else if ($userid < 0) {
2487 $path = $CFG->tempdir.'/data/'.-$userid.'/'.$shortname;
2490 return $path;
2494 * Implementation of the function for printing the form elements that control
2495 * whether the course reset functionality affects the data.
2497 * @param $mform form passed by reference
2499 function data_reset_course_form_definition(&$mform) {
2500 $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2501 $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2503 $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2504 $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2506 $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2507 $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2509 $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2510 $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
2514 * Course reset form defaults.
2515 * @return array
2517 function data_reset_course_form_defaults($course) {
2518 return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2522 * Removes all grades from gradebook
2524 * @global object
2525 * @global object
2526 * @param int $courseid
2527 * @param string $type optional type
2529 function data_reset_gradebook($courseid, $type='') {
2530 global $CFG, $DB;
2532 $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
2533 FROM {data} d, {course_modules} cm, {modules} m
2534 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
2536 if ($datas = $DB->get_records_sql($sql, array($courseid))) {
2537 foreach ($datas as $data) {
2538 data_grade_item_update($data, 'reset');
2544 * Actual implementation of the reset course functionality, delete all the
2545 * data responses for course $data->courseid.
2547 * @global object
2548 * @global object
2549 * @param object $data the data submitted from the reset course.
2550 * @return array status array
2552 function data_reset_userdata($data) {
2553 global $CFG, $DB;
2554 require_once($CFG->libdir.'/filelib.php');
2555 require_once($CFG->dirroot.'/rating/lib.php');
2557 $componentstr = get_string('modulenameplural', 'data');
2558 $status = array();
2560 $allrecordssql = "SELECT r.id
2561 FROM {data_records} r
2562 INNER JOIN {data} d ON r.dataid = d.id
2563 WHERE d.course = ?";
2565 $alldatassql = "SELECT d.id
2566 FROM {data} d
2567 WHERE d.course=?";
2569 $rm = new rating_manager();
2570 $ratingdeloptions = new stdClass;
2571 $ratingdeloptions->component = 'mod_data';
2572 $ratingdeloptions->ratingarea = 'entry';
2574 // Set the file storage - may need it to remove files later.
2575 $fs = get_file_storage();
2577 // delete entries if requested
2578 if (!empty($data->reset_data)) {
2579 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2580 $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid));
2581 $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid));
2583 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2584 foreach ($datas as $dataid=>$unused) {
2585 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2586 continue;
2588 $datacontext = context_module::instance($cm->id);
2590 // Delete any files that may exist.
2591 $fs->delete_area_files($datacontext->id, 'mod_data', 'content');
2593 $ratingdeloptions->contextid = $datacontext->id;
2594 $rm->delete_ratings($ratingdeloptions);
2598 if (empty($data->reset_gradebook_grades)) {
2599 // remove all grades from gradebook
2600 data_reset_gradebook($data->courseid);
2602 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2605 // remove entries by users not enrolled into course
2606 if (!empty($data->reset_data_notenrolled)) {
2607 $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
2608 FROM {data_records} r
2609 JOIN {data} d ON r.dataid = d.id
2610 LEFT JOIN {user} u ON r.userid = u.id
2611 WHERE d.course = ? AND r.userid > 0";
2613 $course_context = context_course::instance($data->courseid);
2614 $notenrolled = array();
2615 $fields = array();
2616 $rs = $DB->get_recordset_sql($recordssql, array($data->courseid));
2617 foreach ($rs as $record) {
2618 if (array_key_exists($record->userid, $notenrolled) or !$record->userexists or $record->userdeleted
2619 or !is_enrolled($course_context, $record->userid)) {
2620 //delete ratings
2621 if (!$cm = get_coursemodule_from_instance('data', $record->dataid)) {
2622 continue;
2624 $datacontext = context_module::instance($cm->id);
2625 $ratingdeloptions->contextid = $datacontext->id;
2626 $ratingdeloptions->itemid = $record->id;
2627 $rm->delete_ratings($ratingdeloptions);
2629 // Delete any files that may exist.
2630 if ($contents = $DB->get_records('data_content', array('recordid' => $record->id), '', 'id')) {
2631 foreach ($contents as $content) {
2632 $fs->delete_area_files($datacontext->id, 'mod_data', 'content', $content->id);
2635 $notenrolled[$record->userid] = true;
2637 $DB->delete_records('comments', array('itemid' => $record->id, 'commentarea' => 'database_entry'));
2638 $DB->delete_records('data_content', array('recordid' => $record->id));
2639 $DB->delete_records('data_records', array('id' => $record->id));
2642 $rs->close();
2643 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
2646 // remove all ratings
2647 if (!empty($data->reset_data_ratings)) {
2648 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2649 foreach ($datas as $dataid=>$unused) {
2650 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2651 continue;
2653 $datacontext = context_module::instance($cm->id);
2655 $ratingdeloptions->contextid = $datacontext->id;
2656 $rm->delete_ratings($ratingdeloptions);
2660 if (empty($data->reset_gradebook_grades)) {
2661 // remove all grades from gradebook
2662 data_reset_gradebook($data->courseid);
2665 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2668 // remove all comments
2669 if (!empty($data->reset_data_comments)) {
2670 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2671 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2674 // updating dates - shift may be negative too
2675 if ($data->timeshift) {
2676 shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto'), $data->timeshift, $data->courseid);
2677 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2680 return $status;
2684 * Returns all other caps used in module
2686 * @return array
2688 function data_get_extra_capabilities() {
2689 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate', 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete');
2693 * @param string $feature FEATURE_xx constant for requested feature
2694 * @return mixed True if module supports feature, null if doesn't know
2696 function data_supports($feature) {
2697 switch($feature) {
2698 case FEATURE_GROUPS: return true;
2699 case FEATURE_GROUPINGS: return true;
2700 case FEATURE_MOD_INTRO: return true;
2701 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
2702 case FEATURE_GRADE_HAS_GRADE: return true;
2703 case FEATURE_GRADE_OUTCOMES: return true;
2704 case FEATURE_RATE: return true;
2705 case FEATURE_BACKUP_MOODLE2: return true;
2706 case FEATURE_SHOW_DESCRIPTION: return true;
2708 default: return null;
2712 * @global object
2713 * @param array $export
2714 * @param string $delimiter_name
2715 * @param object $database
2716 * @param int $count
2717 * @param bool $return
2718 * @return string|void
2720 function data_export_csv($export, $delimiter_name, $database, $count, $return=false) {
2721 global $CFG;
2722 require_once($CFG->libdir . '/csvlib.class.php');
2724 $filename = $database . '-' . $count . '-record';
2725 if ($count > 1) {
2726 $filename .= 's';
2728 if ($return) {
2729 return csv_export_writer::print_array($export, $delimiter_name, '"', true);
2730 } else {
2731 csv_export_writer::download_array($filename, $export, $delimiter_name);
2736 * @global object
2737 * @param array $export
2738 * @param string $dataname
2739 * @param int $count
2740 * @return string
2742 function data_export_xls($export, $dataname, $count) {
2743 global $CFG;
2744 require_once("$CFG->libdir/excellib.class.php");
2745 $filename = clean_filename("{$dataname}-{$count}_record");
2746 if ($count > 1) {
2747 $filename .= 's';
2749 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2750 $filename .= '.xls';
2752 $filearg = '-';
2753 $workbook = new MoodleExcelWorkbook($filearg);
2754 $workbook->send($filename);
2755 $worksheet = array();
2756 $worksheet[0] = $workbook->add_worksheet('');
2757 $rowno = 0;
2758 foreach ($export as $row) {
2759 $colno = 0;
2760 foreach($row as $col) {
2761 $worksheet[0]->write($rowno, $colno, $col);
2762 $colno++;
2764 $rowno++;
2766 $workbook->close();
2767 return $filename;
2771 * @global object
2772 * @param array $export
2773 * @param string $dataname
2774 * @param int $count
2775 * @param string
2777 function data_export_ods($export, $dataname, $count) {
2778 global $CFG;
2779 require_once("$CFG->libdir/odslib.class.php");
2780 $filename = clean_filename("{$dataname}-{$count}_record");
2781 if ($count > 1) {
2782 $filename .= 's';
2784 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2785 $filename .= '.ods';
2786 $filearg = '-';
2787 $workbook = new MoodleODSWorkbook($filearg);
2788 $workbook->send($filename);
2789 $worksheet = array();
2790 $worksheet[0] = $workbook->add_worksheet('');
2791 $rowno = 0;
2792 foreach ($export as $row) {
2793 $colno = 0;
2794 foreach($row as $col) {
2795 $worksheet[0]->write($rowno, $colno, $col);
2796 $colno++;
2798 $rowno++;
2800 $workbook->close();
2801 return $filename;
2805 * @global object
2806 * @param int $dataid
2807 * @param array $fields
2808 * @param array $selectedfields
2809 * @param int $currentgroup group ID of the current group. This is used for
2810 * exporting data while maintaining group divisions.
2811 * @param object $context the context in which the operation is performed (for capability checks)
2812 * @param bool $userdetails whether to include the details of the record author
2813 * @param bool $time whether to include time created/modified
2814 * @param bool $approval whether to include approval status
2815 * @return array
2817 function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0, $context=null,
2818 $userdetails=false, $time=false, $approval=false) {
2819 global $DB;
2821 if (is_null($context)) {
2822 $context = context_system::instance();
2824 // exporting user data needs special permission
2825 $userdetails = $userdetails && has_capability('mod/data:exportuserinfo', $context);
2827 $exportdata = array();
2829 // populate the header in first row of export
2830 foreach($fields as $key => $field) {
2831 if (!in_array($field->field->id, $selectedfields)) {
2832 // ignore values we aren't exporting
2833 unset($fields[$key]);
2834 } else {
2835 $exportdata[0][] = $field->field->name;
2838 if ($userdetails) {
2839 $exportdata[0][] = get_string('user');
2840 $exportdata[0][] = get_string('username');
2841 $exportdata[0][] = get_string('email');
2843 if ($time) {
2844 $exportdata[0][] = get_string('timeadded', 'data');
2845 $exportdata[0][] = get_string('timemodified', 'data');
2847 if ($approval) {
2848 $exportdata[0][] = get_string('approved', 'data');
2851 $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
2852 ksort($datarecords);
2853 $line = 1;
2854 foreach($datarecords as $record) {
2855 // get content indexed by fieldid
2856 if ($currentgroup) {
2857 $select = 'SELECT c.fieldid, c.content, c.content1, c.content2, c.content3, c.content4 FROM {data_content} c, {data_records} r WHERE c.recordid = ? AND r.id = c.recordid AND r.groupid = ?';
2858 $where = array($record->id, $currentgroup);
2859 } else {
2860 $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
2861 $where = array($record->id);
2864 if( $content = $DB->get_records_sql($select, $where) ) {
2865 foreach($fields as $field) {
2866 $contents = '';
2867 if(isset($content[$field->field->id])) {
2868 $contents = $field->export_text_value($content[$field->field->id]);
2870 $exportdata[$line][] = $contents;
2872 if ($userdetails) { // Add user details to the export data
2873 $userdata = get_complete_user_data('id', $record->userid);
2874 $exportdata[$line][] = fullname($userdata);
2875 $exportdata[$line][] = $userdata->username;
2876 $exportdata[$line][] = $userdata->email;
2878 if ($time) { // Add time added / modified
2879 $exportdata[$line][] = userdate($record->timecreated);
2880 $exportdata[$line][] = userdate($record->timemodified);
2882 if ($approval) { // Add approval status
2883 $exportdata[$line][] = (int) $record->approved;
2886 $line++;
2888 $line--;
2889 return $exportdata;
2892 ////////////////////////////////////////////////////////////////////////////////
2893 // File API //
2894 ////////////////////////////////////////////////////////////////////////////////
2897 * Lists all browsable file areas
2899 * @package mod_data
2900 * @category files
2901 * @param stdClass $course course object
2902 * @param stdClass $cm course module object
2903 * @param stdClass $context context object
2904 * @return array
2906 function data_get_file_areas($course, $cm, $context) {
2907 return array('content' => get_string('areacontent', 'mod_data'));
2911 * File browsing support for data module.
2913 * @param file_browser $browser
2914 * @param array $areas
2915 * @param stdClass $course
2916 * @param cm_info $cm
2917 * @param context $context
2918 * @param string $filearea
2919 * @param int $itemid
2920 * @param string $filepath
2921 * @param string $filename
2922 * @return file_info_stored file_info_stored instance or null if not found
2924 function data_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2925 global $CFG, $DB, $USER;
2927 if ($context->contextlevel != CONTEXT_MODULE) {
2928 return null;
2931 if (!isset($areas[$filearea])) {
2932 return null;
2935 if (is_null($itemid)) {
2936 require_once($CFG->dirroot.'/mod/data/locallib.php');
2937 return new data_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
2940 if (!$content = $DB->get_record('data_content', array('id'=>$itemid))) {
2941 return null;
2944 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
2945 return null;
2948 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
2949 return null;
2952 if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
2953 return null;
2956 //check if approved
2957 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
2958 return null;
2961 // group access
2962 if ($record->groupid) {
2963 $groupmode = groups_get_activity_groupmode($cm, $course);
2964 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
2965 if (!groups_is_member($record->groupid)) {
2966 return null;
2971 $fieldobj = data_get_field($field, $data, $cm);
2973 $filepath = is_null($filepath) ? '/' : $filepath;
2974 $filename = is_null($filename) ? '.' : $filename;
2975 if (!$fieldobj->file_ok($filepath.$filename)) {
2976 return null;
2979 $fs = get_file_storage();
2980 if (!($storedfile = $fs->get_file($context->id, 'mod_data', $filearea, $itemid, $filepath, $filename))) {
2981 return null;
2984 // Checks to see if the user can manage files or is the owner.
2985 // TODO MDL-33805 - Do not use userid here and move the capability check above.
2986 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
2987 return null;
2990 $urlbase = $CFG->wwwroot.'/pluginfile.php';
2992 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
2996 * Serves the data attachments. Implements needed access control ;-)
2998 * @package mod_data
2999 * @category files
3000 * @param stdClass $course course object
3001 * @param stdClass $cm course module object
3002 * @param stdClass $context context object
3003 * @param string $filearea file area
3004 * @param array $args extra arguments
3005 * @param bool $forcedownload whether or not force download
3006 * @param array $options additional options affecting the file serving
3007 * @return bool false if file not found, does not return if found - justsend the file
3009 function data_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3010 global $CFG, $DB;
3012 if ($context->contextlevel != CONTEXT_MODULE) {
3013 return false;
3016 require_course_login($course, true, $cm);
3018 if ($filearea === 'content') {
3019 $contentid = (int)array_shift($args);
3021 if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
3022 return false;
3025 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
3026 return false;
3029 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
3030 return false;
3033 if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
3034 return false;
3037 if ($data->id != $cm->instance) {
3038 // hacker attempt - context does not match the contentid
3039 return false;
3042 //check if approved
3043 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3044 return false;
3047 // group access
3048 if ($record->groupid) {
3049 $groupmode = groups_get_activity_groupmode($cm, $course);
3050 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3051 if (!groups_is_member($record->groupid)) {
3052 return false;
3057 $fieldobj = data_get_field($field, $data, $cm);
3059 $relativepath = implode('/', $args);
3060 $fullpath = "/$context->id/mod_data/content/$content->id/$relativepath";
3062 if (!$fieldobj->file_ok($relativepath)) {
3063 return false;
3066 $fs = get_file_storage();
3067 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3068 return false;
3071 // finally send the file
3072 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
3075 return false;
3079 function data_extend_navigation($navigation, $course, $module, $cm) {
3080 global $CFG, $OUTPUT, $USER, $DB;
3082 $rid = optional_param('rid', 0, PARAM_INT);
3084 $data = $DB->get_record('data', array('id'=>$cm->instance));
3085 $currentgroup = groups_get_activity_group($cm);
3086 $groupmode = groups_get_activity_groupmode($cm);
3088 $numentries = data_numentries($data);
3089 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
3090 if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !has_capability('mod/data:manageentries', context_module::instance($cm->id))) {
3091 $data->entriesleft = $data->requiredentries - $numentries;
3092 $entriesnode = $navigation->add(get_string('entrieslefttoadd', 'data', $data));
3093 $entriesnode->add_class('note');
3096 $navigation->add(get_string('list', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance)));
3097 if (!empty($rid)) {
3098 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'rid'=>$rid)));
3099 } else {
3100 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'single')));
3102 $navigation->add(get_string('search', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'asearch')));
3106 * Adds module specific settings to the settings block
3108 * @param settings_navigation $settings The settings navigation object
3109 * @param navigation_node $datanode The node to add module settings to
3111 function data_extend_settings_navigation(settings_navigation $settings, navigation_node $datanode) {
3112 global $PAGE, $DB, $CFG, $USER;
3114 $data = $DB->get_record('data', array("id" => $PAGE->cm->instance));
3116 $currentgroup = groups_get_activity_group($PAGE->cm);
3117 $groupmode = groups_get_activity_groupmode($PAGE->cm);
3119 if (data_user_can_add_entry($data, $currentgroup, $groupmode, $PAGE->cm->context)) { // took out participation list here!
3120 if (empty($editentry)) { //TODO: undefined
3121 $addstring = get_string('add', 'data');
3122 } else {
3123 $addstring = get_string('editentry', 'data');
3125 $datanode->add($addstring, new moodle_url('/mod/data/edit.php', array('d'=>$PAGE->cm->instance)));
3128 if (has_capability(DATA_CAP_EXPORT, $PAGE->cm->context)) {
3129 // The capability required to Export database records is centrally defined in 'lib.php'
3130 // and should be weaker than those required to edit Templates, Fields and Presets.
3131 $datanode->add(get_string('exportentries', 'data'), new moodle_url('/mod/data/export.php', array('d'=>$data->id)));
3133 if (has_capability('mod/data:manageentries', $PAGE->cm->context)) {
3134 $datanode->add(get_string('importentries', 'data'), new moodle_url('/mod/data/import.php', array('d'=>$data->id)));
3137 if (has_capability('mod/data:managetemplates', $PAGE->cm->context)) {
3138 $currenttab = '';
3139 if ($currenttab == 'list') {
3140 $defaultemplate = 'listtemplate';
3141 } else if ($currenttab == 'add') {
3142 $defaultemplate = 'addtemplate';
3143 } else if ($currenttab == 'asearch') {
3144 $defaultemplate = 'asearchtemplate';
3145 } else {
3146 $defaultemplate = 'singletemplate';
3149 $templates = $datanode->add(get_string('templates', 'data'));
3151 $templatelist = array ('listtemplate', 'singletemplate', 'asearchtemplate', 'addtemplate', 'rsstemplate', 'csstemplate', 'jstemplate');
3152 foreach ($templatelist as $template) {
3153 $templates->add(get_string($template, 'data'), new moodle_url('/mod/data/templates.php', array('d'=>$data->id,'mode'=>$template)));
3156 $datanode->add(get_string('fields', 'data'), new moodle_url('/mod/data/field.php', array('d'=>$data->id)));
3157 $datanode->add(get_string('presets', 'data'), new moodle_url('/mod/data/preset.php', array('d'=>$data->id)));
3160 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
3161 require_once("$CFG->libdir/rsslib.php");
3163 $string = get_string('rsstype','forum');
3165 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_data', $data->id));
3166 $datanode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
3171 * Save the database configuration as a preset.
3173 * @param stdClass $course The course the database module belongs to.
3174 * @param stdClass $cm The course module record
3175 * @param stdClass $data The database record
3176 * @param string $path
3177 * @return bool
3179 function data_presets_save($course, $cm, $data, $path) {
3180 global $USER;
3181 $fs = get_file_storage();
3182 $filerecord = new stdClass;
3183 $filerecord->contextid = DATA_PRESET_CONTEXT;
3184 $filerecord->component = DATA_PRESET_COMPONENT;
3185 $filerecord->filearea = DATA_PRESET_FILEAREA;
3186 $filerecord->itemid = 0;
3187 $filerecord->filepath = '/'.$path.'/';
3188 $filerecord->userid = $USER->id;
3190 $filerecord->filename = 'preset.xml';
3191 $fs->create_file_from_string($filerecord, data_presets_generate_xml($course, $cm, $data));
3193 $filerecord->filename = 'singletemplate.html';
3194 $fs->create_file_from_string($filerecord, $data->singletemplate);
3196 $filerecord->filename = 'listtemplateheader.html';
3197 $fs->create_file_from_string($filerecord, $data->listtemplateheader);
3199 $filerecord->filename = 'listtemplate.html';
3200 $fs->create_file_from_string($filerecord, $data->listtemplate);
3202 $filerecord->filename = 'listtemplatefooter.html';
3203 $fs->create_file_from_string($filerecord, $data->listtemplatefooter);
3205 $filerecord->filename = 'addtemplate.html';
3206 $fs->create_file_from_string($filerecord, $data->addtemplate);
3208 $filerecord->filename = 'rsstemplate.html';
3209 $fs->create_file_from_string($filerecord, $data->rsstemplate);
3211 $filerecord->filename = 'rsstitletemplate.html';
3212 $fs->create_file_from_string($filerecord, $data->rsstitletemplate);
3214 $filerecord->filename = 'csstemplate.css';
3215 $fs->create_file_from_string($filerecord, $data->csstemplate);
3217 $filerecord->filename = 'jstemplate.js';
3218 $fs->create_file_from_string($filerecord, $data->jstemplate);
3220 $filerecord->filename = 'asearchtemplate.html';
3221 $fs->create_file_from_string($filerecord, $data->asearchtemplate);
3223 return true;
3227 * Generates the XML for the database module provided
3229 * @global moodle_database $DB
3230 * @param stdClass $course The course the database module belongs to.
3231 * @param stdClass $cm The course module record
3232 * @param stdClass $data The database record
3233 * @return string The XML for the preset
3235 function data_presets_generate_xml($course, $cm, $data) {
3236 global $DB;
3238 // Assemble "preset.xml":
3239 $presetxmldata = "<preset>\n\n";
3241 // Raw settings are not preprocessed during saving of presets
3242 $raw_settings = array(
3243 'intro',
3244 'comments',
3245 'requiredentries',
3246 'requiredentriestoview',
3247 'maxentries',
3248 'rssarticles',
3249 'approval',
3250 'defaultsortdir'
3253 $presetxmldata .= "<settings>\n";
3254 // First, settings that do not require any conversion
3255 foreach ($raw_settings as $setting) {
3256 $presetxmldata .= "<$setting>" . htmlspecialchars($data->$setting) . "</$setting>\n";
3259 // Now specific settings
3260 if ($data->defaultsort > 0 && $sortfield = data_get_field_from_id($data->defaultsort, $data)) {
3261 $presetxmldata .= '<defaultsort>' . htmlspecialchars($sortfield->field->name) . "</defaultsort>\n";
3262 } else {
3263 $presetxmldata .= "<defaultsort>0</defaultsort>\n";
3265 $presetxmldata .= "</settings>\n\n";
3266 // Now for the fields. Grab all that are non-empty
3267 $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
3268 ksort($fields);
3269 if (!empty($fields)) {
3270 foreach ($fields as $field) {
3271 $presetxmldata .= "<field>\n";
3272 foreach ($field as $key => $value) {
3273 if ($value != '' && $key != 'id' && $key != 'dataid') {
3274 $presetxmldata .= "<$key>" . htmlspecialchars($value) . "</$key>\n";
3277 $presetxmldata .= "</field>\n\n";
3280 $presetxmldata .= '</preset>';
3281 return $presetxmldata;
3284 function data_presets_export($course, $cm, $data, $tostorage=false) {
3285 global $CFG, $DB;
3287 $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi");
3288 $exportsubdir = "mod_data/presetexport/$presetname";
3289 make_temp_directory($exportsubdir);
3290 $exportdir = "$CFG->tempdir/$exportsubdir";
3292 // Assemble "preset.xml":
3293 $presetxmldata = data_presets_generate_xml($course, $cm, $data);
3295 // After opening a file in write mode, close it asap
3296 $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
3297 fwrite($presetxmlfile, $presetxmldata);
3298 fclose($presetxmlfile);
3300 // Now write the template files
3301 $singletemplate = fopen($exportdir . '/singletemplate.html', 'w');
3302 fwrite($singletemplate, $data->singletemplate);
3303 fclose($singletemplate);
3305 $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w');
3306 fwrite($listtemplateheader, $data->listtemplateheader);
3307 fclose($listtemplateheader);
3309 $listtemplate = fopen($exportdir . '/listtemplate.html', 'w');
3310 fwrite($listtemplate, $data->listtemplate);
3311 fclose($listtemplate);
3313 $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w');
3314 fwrite($listtemplatefooter, $data->listtemplatefooter);
3315 fclose($listtemplatefooter);
3317 $addtemplate = fopen($exportdir . '/addtemplate.html', 'w');
3318 fwrite($addtemplate, $data->addtemplate);
3319 fclose($addtemplate);
3321 $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w');
3322 fwrite($rsstemplate, $data->rsstemplate);
3323 fclose($rsstemplate);
3325 $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w');
3326 fwrite($rsstitletemplate, $data->rsstitletemplate);
3327 fclose($rsstitletemplate);
3329 $csstemplate = fopen($exportdir . '/csstemplate.css', 'w');
3330 fwrite($csstemplate, $data->csstemplate);
3331 fclose($csstemplate);
3333 $jstemplate = fopen($exportdir . '/jstemplate.js', 'w');
3334 fwrite($jstemplate, $data->jstemplate);
3335 fclose($jstemplate);
3337 $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w');
3338 fwrite($asearchtemplate, $data->asearchtemplate);
3339 fclose($asearchtemplate);
3341 // Check if all files have been generated
3342 if (! is_directory_a_preset($exportdir)) {
3343 print_error('generateerror', 'data');
3346 $filenames = array(
3347 'preset.xml',
3348 'singletemplate.html',
3349 'listtemplateheader.html',
3350 'listtemplate.html',
3351 'listtemplatefooter.html',
3352 'addtemplate.html',
3353 'rsstemplate.html',
3354 'rsstitletemplate.html',
3355 'csstemplate.css',
3356 'jstemplate.js',
3357 'asearchtemplate.html'
3360 $filelist = array();
3361 foreach ($filenames as $filename) {
3362 $filelist[$filename] = $exportdir . '/' . $filename;
3365 $exportfile = $exportdir.'.zip';
3366 file_exists($exportfile) && unlink($exportfile);
3368 $fp = get_file_packer('application/zip');
3369 $fp->archive_to_pathname($filelist, $exportfile);
3371 foreach ($filelist as $file) {
3372 unlink($file);
3374 rmdir($exportdir);
3376 // Return the full path to the exported preset file:
3377 return $exportfile;
3381 * Running addtional permission check on plugin, for example, plugins
3382 * may have switch to turn on/off comments option, this callback will
3383 * affect UI display, not like pluginname_comment_validate only throw
3384 * exceptions.
3385 * Capability check has been done in comment->check_permissions(), we
3386 * don't need to do it again here.
3388 * @package mod_data
3389 * @category comment
3391 * @param stdClass $comment_param {
3392 * context => context the context object
3393 * courseid => int course id
3394 * cm => stdClass course module object
3395 * commentarea => string comment area
3396 * itemid => int itemid
3398 * @return array
3400 function data_comment_permissions($comment_param) {
3401 global $CFG, $DB;
3402 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3403 throw new comment_exception('invalidcommentitemid');
3405 if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3406 throw new comment_exception('invalidid', 'data');
3408 if ($data->comments) {
3409 return array('post'=>true, 'view'=>true);
3410 } else {
3411 return array('post'=>false, 'view'=>false);
3416 * Validate comment parameter before perform other comments actions
3418 * @package mod_data
3419 * @category comment
3421 * @param stdClass $comment_param {
3422 * context => context the context object
3423 * courseid => int course id
3424 * cm => stdClass course module object
3425 * commentarea => string comment area
3426 * itemid => int itemid
3428 * @return boolean
3430 function data_comment_validate($comment_param) {
3431 global $DB;
3432 // validate comment area
3433 if ($comment_param->commentarea != 'database_entry') {
3434 throw new comment_exception('invalidcommentarea');
3436 // validate itemid
3437 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3438 throw new comment_exception('invalidcommentitemid');
3440 if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3441 throw new comment_exception('invalidid', 'data');
3443 if (!$course = $DB->get_record('course', array('id'=>$data->course))) {
3444 throw new comment_exception('coursemisconf');
3446 if (!$cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
3447 throw new comment_exception('invalidcoursemodule');
3449 if (!$data->comments) {
3450 throw new comment_exception('commentsoff', 'data');
3452 $context = context_module::instance($cm->id);
3454 //check if approved
3455 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3456 throw new comment_exception('notapproved', 'data');
3459 // group access
3460 if ($record->groupid) {
3461 $groupmode = groups_get_activity_groupmode($cm, $course);
3462 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3463 if (!groups_is_member($record->groupid)) {
3464 throw new comment_exception('notmemberofgroup');
3468 // validate context id
3469 if ($context->id != $comment_param->context->id) {
3470 throw new comment_exception('invalidcontext');
3472 // validation for comment deletion
3473 if (!empty($comment_param->commentid)) {
3474 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
3475 if ($comment->commentarea != 'database_entry') {
3476 throw new comment_exception('invalidcommentarea');
3478 if ($comment->contextid != $comment_param->context->id) {
3479 throw new comment_exception('invalidcontext');
3481 if ($comment->itemid != $comment_param->itemid) {
3482 throw new comment_exception('invalidcommentitemid');
3484 } else {
3485 throw new comment_exception('invalidcommentid');
3488 return true;
3492 * Return a list of page types
3493 * @param string $pagetype current page type
3494 * @param stdClass $parentcontext Block's parent context
3495 * @param stdClass $currentcontext Current context of block
3497 function data_page_type_list($pagetype, $parentcontext, $currentcontext) {
3498 $module_pagetype = array('mod-data-*'=>get_string('page-mod-data-x', 'data'));
3499 return $module_pagetype;
3503 * Get all of the record ids from a database activity.
3505 * @param int $dataid The dataid of the database module.
3506 * @param object $selectdata Contains an additional sql statement for the
3507 * where clause for group and approval fields.
3508 * @param array $params Parameters that coincide with the sql statement.
3509 * @return array $idarray An array of record ids
3511 function data_get_all_recordids($dataid, $selectdata = '', $params = null) {
3512 global $DB;
3513 $initsql = 'SELECT r.id
3514 FROM {data_records} r
3515 WHERE r.dataid = :dataid';
3516 if ($selectdata != '') {
3517 $initsql .= $selectdata;
3518 $params = array_merge(array('dataid' => $dataid), $params);
3519 } else {
3520 $params = array('dataid' => $dataid);
3522 $initsql .= ' GROUP BY r.id';
3523 $initrecord = $DB->get_recordset_sql($initsql, $params);
3524 $idarray = array();
3525 foreach ($initrecord as $data) {
3526 $idarray[] = $data->id;
3528 // Close the record set and free up resources.
3529 $initrecord->close();
3530 return $idarray;
3534 * Get the ids of all the records that match that advanced search criteria
3535 * This goes and loops through each criterion one at a time until it either
3536 * runs out of records or returns a subset of records.
3538 * @param array $recordids An array of record ids.
3539 * @param array $searcharray Contains information for the advanced search criteria
3540 * @param int $dataid The data id of the database.
3541 * @return array $recordids An array of record ids.
3543 function data_get_advance_search_ids($recordids, $searcharray, $dataid) {
3544 $searchcriteria = array_keys($searcharray);
3545 // Loop through and reduce the IDs one search criteria at a time.
3546 foreach ($searchcriteria as $key) {
3547 $recordids = data_get_recordids($key, $searcharray, $dataid, $recordids);
3548 // If we don't have anymore IDs then stop.
3549 if (!$recordids) {
3550 break;
3553 return $recordids;
3557 * Gets the record IDs given the search criteria
3559 * @param string $alias Record alias.
3560 * @param array $searcharray Criteria for the search.
3561 * @param int $dataid Data ID for the database
3562 * @param array $recordids An array of record IDs.
3563 * @return array $nestarray An arry of record IDs
3565 function data_get_recordids($alias, $searcharray, $dataid, $recordids) {
3566 global $DB;
3568 $nestsearch = $searcharray[$alias];
3569 // searching for content outside of mdl_data_content
3570 if ($alias < 0) {
3571 $alias = '';
3573 list($insql, $params) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3574 $nestselect = 'SELECT c' . $alias . '.recordid
3575 FROM {data_content} c' . $alias . ',
3576 {data_fields} f,
3577 {data_records} r,
3578 {user} u ';
3579 $nestwhere = 'WHERE u.id = r.userid
3580 AND f.id = c' . $alias . '.fieldid
3581 AND r.id = c' . $alias . '.recordid
3582 AND r.dataid = :dataid
3583 AND c' . $alias .'.recordid ' . $insql . '
3584 AND ';
3586 $params['dataid'] = $dataid;
3587 if (count($nestsearch->params) != 0) {
3588 $params = array_merge($params, $nestsearch->params);
3589 $nestsql = $nestselect . $nestwhere . $nestsearch->sql;
3590 } else {
3591 $thing = $DB->sql_like($nestsearch->field, ':search1', false);
3592 $nestsql = $nestselect . $nestwhere . $thing . ' GROUP BY c' . $alias . '.recordid';
3593 $params['search1'] = "%$nestsearch->data%";
3595 $nestrecords = $DB->get_recordset_sql($nestsql, $params);
3596 $nestarray = array();
3597 foreach ($nestrecords as $data) {
3598 $nestarray[] = $data->recordid;
3600 // Close the record set and free up resources.
3601 $nestrecords->close();
3602 return $nestarray;
3606 * Returns an array with an sql string for advanced searches and the parameters that go with them.
3608 * @param int $sort DATA_*
3609 * @param stdClass $data Data module object
3610 * @param array $recordids An array of record IDs.
3611 * @param string $selectdata Information for the where and select part of the sql statement.
3612 * @param string $sortorder Additional sort parameters
3613 * @return array sqlselect sqlselect['sql'] has the sql string, sqlselect['params'] contains an array of parameters.
3615 function data_get_advanced_search_sql($sort, $data, $recordids, $selectdata, $sortorder) {
3616 global $DB;
3618 $namefields = get_all_user_name_fields(true, 'u');
3619 if ($sort == 0) {
3620 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . '
3621 FROM {data_content} c,
3622 {data_records} r,
3623 {user} u ';
3624 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' . $namefields;
3625 } else {
3626 // Sorting through 'Other' criteria
3627 if ($sort <= 0) {
3628 switch ($sort) {
3629 case DATA_LASTNAME:
3630 $sortcontentfull = "u.lastname";
3631 break;
3632 case DATA_FIRSTNAME:
3633 $sortcontentfull = "u.firstname";
3634 break;
3635 case DATA_APPROVED:
3636 $sortcontentfull = "r.approved";
3637 break;
3638 case DATA_TIMEMODIFIED:
3639 $sortcontentfull = "r.timemodified";
3640 break;
3641 case DATA_TIMEADDED:
3642 default:
3643 $sortcontentfull = "r.timecreated";
3645 } else {
3646 $sortfield = data_get_field_from_id($sort, $data);
3647 $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
3648 $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
3651 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ',
3652 ' . $sortcontentfull . '
3653 AS sortorder
3654 FROM {data_content} c,
3655 {data_records} r,
3656 {user} u ';
3657 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ', ' .$sortcontentfull;
3660 // Default to a standard Where statement if $selectdata is empty.
3661 if ($selectdata == '') {
3662 $selectdata = 'WHERE c.recordid = r.id
3663 AND r.dataid = :dataid
3664 AND r.userid = u.id ';
3667 // Find the field we are sorting on
3668 if ($sort > 0 or data_get_field_from_id($sort, $data)) {
3669 $selectdata .= ' AND c.fieldid = :sort';
3672 // If there are no record IDs then return an sql statment that will return no rows.
3673 if (count($recordids) != 0) {
3674 list($insql, $inparam) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3675 } else {
3676 list($insql, $inparam) = $DB->get_in_or_equal(array('-1'), SQL_PARAMS_NAMED);
3678 $nestfromsql = $selectdata . ' AND c.recordid ' . $insql . $groupsql;
3679 $sqlselect['sql'] = "$nestselectsql $nestfromsql $sortorder";
3680 $sqlselect['params'] = $inparam;
3681 return $sqlselect;
3685 * Checks to see if the user has permission to delete the preset.
3686 * @param stdClass $context Context object.
3687 * @param stdClass $preset The preset object that we are checking for deletion.
3688 * @return bool Returns true if the user can delete, otherwise false.
3690 function data_user_can_delete_preset($context, $preset) {
3691 global $USER;
3693 if (has_capability('mod/data:manageuserpresets', $context)) {
3694 return true;
3695 } else {
3696 $candelete = false;
3697 if ($preset->userid == $USER->id) {
3698 $candelete = true;
3700 return $candelete;
3705 * Delete a record entry.
3707 * @param int $recordid The ID for the record to be deleted.
3708 * @param object $data The data object for this activity.
3709 * @param int $courseid ID for the current course (for logging).
3710 * @param int $cmid The course module ID.
3711 * @return bool True if the record deleted, false if not.
3713 function data_delete_record($recordid, $data, $courseid, $cmid) {
3714 global $DB, $CFG;
3716 if ($deleterecord = $DB->get_record('data_records', array('id' => $recordid))) {
3717 if ($deleterecord->dataid == $data->id) {
3718 if ($contents = $DB->get_records('data_content', array('recordid' => $deleterecord->id))) {
3719 foreach ($contents as $content) {
3720 if ($field = data_get_field_from_id($content->fieldid, $data)) {
3721 $field->delete_content($content->recordid);
3724 $DB->delete_records('data_content', array('recordid'=>$deleterecord->id));
3725 $DB->delete_records('data_records', array('id'=>$deleterecord->id));
3727 // Delete cached RSS feeds.
3728 if (!empty($CFG->enablerssfeeds)) {
3729 require_once($CFG->dirroot.'/mod/data/rsslib.php');
3730 data_rss_delete_file($data);
3733 // Trigger an event for deleting this record.
3734 $event = \mod_data\event\record_deleted::create(array(
3735 'objectid' => $deleterecord->id,
3736 'context' => context_module::instance($cmid),
3737 'courseid' => $courseid,
3738 'other' => array(
3739 'dataid' => $deleterecord->dataid
3742 $event->add_record_snapshot('data_records', $deleterecord);
3743 $event->trigger();
3745 return true;
3749 return false;