Merge branch 'MDL-42411-master' of git://github.com/damyon/moodle
[moodle.git] / mod / data / lib.php
blob8123cc85c5079ced279fc7f2acf887cbd218917f
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);
191 return true;
196 * Update a field in the database
198 * @global object
199 * @return bool
201 function update_field() {
202 global $DB;
204 $DB->update_record('data_fields', $this->field);
205 return true;
209 * Delete a field completely
211 * @global object
212 * @return bool
214 function delete_field() {
215 global $DB;
217 if (!empty($this->field->id)) {
218 $this->delete_content();
219 $DB->delete_records('data_fields', array('id'=>$this->field->id));
221 return true;
225 * Print the relevant form element in the ADD template for this field
227 * @global object
228 * @param int $recordid
229 * @return string
231 function display_add_field($recordid=0){
232 global $DB;
234 if ($recordid){
235 $content = $DB->get_field('data_content', 'content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid));
236 } else {
237 $content = '';
240 // beware get_field returns false for new, empty records MDL-18567
241 if ($content===false) {
242 $content='';
245 $str = '<div title="'.s($this->field->description).'">';
246 $str .= '<label class="accesshide" for="field_'.$this->field->id.'">'.$this->field->description.'</label>';
247 $str .= '<input class="basefieldinput" type="text" name="field_'.$this->field->id.'" id="field_'.$this->field->id.'" value="'.s($content).'" />';
248 $str .= '</div>';
250 return $str;
254 * Print the relevant form element to define the attributes for this field
255 * viewable by teachers only.
257 * @global object
258 * @global object
259 * @return void Output is echo'd
261 function display_edit_field() {
262 global $CFG, $DB, $OUTPUT;
264 if (empty($this->field)) { // No field has been defined yet, try and make one
265 $this->define_default_field();
267 echo $OUTPUT->box_start('generalbox boxaligncenter boxwidthwide');
269 echo '<form id="editfield" action="'.$CFG->wwwroot.'/mod/data/field.php" method="post">'."\n";
270 echo '<input type="hidden" name="d" value="'.$this->data->id.'" />'."\n";
271 if (empty($this->field->id)) {
272 echo '<input type="hidden" name="mode" value="add" />'."\n";
273 $savebutton = get_string('add');
274 } else {
275 echo '<input type="hidden" name="fid" value="'.$this->field->id.'" />'."\n";
276 echo '<input type="hidden" name="mode" value="update" />'."\n";
277 $savebutton = get_string('savechanges');
279 echo '<input type="hidden" name="type" value="'.$this->type.'" />'."\n";
280 echo '<input name="sesskey" value="'.sesskey().'" type="hidden" />'."\n";
282 echo $OUTPUT->heading($this->name(), 3);
284 require_once($CFG->dirroot.'/mod/data/field/'.$this->type.'/mod.html');
286 echo '<div class="mdl-align">';
287 echo '<input type="submit" value="'.$savebutton.'" />'."\n";
288 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />'."\n";
289 echo '</div>';
291 echo '</form>';
293 echo $OUTPUT->box_end();
297 * Display the content of the field in browse mode
299 * @global object
300 * @param int $recordid
301 * @param object $template
302 * @return bool|string
304 function display_browse_field($recordid, $template) {
305 global $DB;
307 if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
308 if (isset($content->content)) {
309 $options = new stdClass();
310 if ($this->field->param1 == '1') { // We are autolinking this field, so disable linking within us
311 //$content->content = '<span class="nolink">'.$content->content.'</span>';
312 //$content->content1 = FORMAT_HTML;
313 $options->filter=false;
315 $options->para = false;
316 $str = format_text($content->content, $content->content1, $options);
317 } else {
318 $str = '';
320 return $str;
322 return false;
326 * Update the content of one data field in the data_content table
327 * @global object
328 * @param int $recordid
329 * @param mixed $value
330 * @param string $name
331 * @return bool
333 function update_content($recordid, $value, $name=''){
334 global $DB;
336 $content = new stdClass();
337 $content->fieldid = $this->field->id;
338 $content->recordid = $recordid;
339 $content->content = clean_param($value, PARAM_NOTAGS);
341 if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
342 $content->id = $oldcontent->id;
343 return $DB->update_record('data_content', $content);
344 } else {
345 return $DB->insert_record('data_content', $content);
350 * Delete all content associated with the field
352 * @global object
353 * @param int $recordid
354 * @return bool
356 function delete_content($recordid=0) {
357 global $DB;
359 if ($recordid) {
360 $conditions = array('fieldid'=>$this->field->id, 'recordid'=>$recordid);
361 } else {
362 $conditions = array('fieldid'=>$this->field->id);
365 $rs = $DB->get_recordset('data_content', $conditions);
366 if ($rs->valid()) {
367 $fs = get_file_storage();
368 foreach ($rs as $content) {
369 $fs->delete_area_files($this->context->id, 'mod_data', 'content', $content->id);
372 $rs->close();
374 return $DB->delete_records('data_content', $conditions);
378 * Check if a field from an add form is empty
380 * @param mixed $value
381 * @param mixed $name
382 * @return bool
384 function notemptyfield($value, $name) {
385 return !empty($value);
389 * Just in case a field needs to print something before the whole form
391 function print_before_form() {
395 * Just in case a field needs to print something after the whole form
397 function print_after_form() {
402 * Returns the sortable field for the content. By default, it's just content
403 * but for some plugins, it could be content 1 - content4
405 * @return string
407 function get_sort_field() {
408 return 'content';
412 * Returns the SQL needed to refer to the column. Some fields may need to CAST() etc.
414 * @param string $fieldname
415 * @return string $fieldname
417 function get_sort_sql($fieldname) {
418 return $fieldname;
422 * Returns the name/type of the field
424 * @return string
426 function name() {
427 return get_string('name'.$this->type, 'data');
431 * Prints the respective type icon
433 * @global object
434 * @return string
436 function image() {
437 global $OUTPUT;
439 $params = array('d'=>$this->data->id, 'fid'=>$this->field->id, 'mode'=>'display', 'sesskey'=>sesskey());
440 $link = new moodle_url('/mod/data/field.php', $params);
441 $str = '<a href="'.$link->out().'">';
442 $str .= '<img src="'.$OUTPUT->pix_url('field/'.$this->type, 'data') . '" ';
443 $str .= 'height="'.$this->iconheight.'" width="'.$this->iconwidth.'" alt="'.$this->type.'" title="'.$this->type.'" /></a>';
444 return $str;
448 * Per default, it is assumed that fields support text exporting.
449 * Override this (return false) on fields not supporting text exporting.
451 * @return bool true
453 function text_export_supported() {
454 return true;
458 * Per default, return the record's text value only from the "content" field.
459 * Override this in fields class if necesarry.
461 * @param string $record
462 * @return string
464 function export_text_value($record) {
465 if ($this->text_export_supported()) {
466 return $record->content;
471 * @param string $relativepath
472 * @return bool false
474 function file_ok($relativepath) {
475 return false;
481 * Given a template and a dataid, generate a default case template
483 * @global object
484 * @param object $data
485 * @param string template [addtemplate, singletemplate, listtempalte, rsstemplate]
486 * @param int $recordid
487 * @param bool $form
488 * @param bool $update
489 * @return bool|string
491 function data_generate_default_template(&$data, $template, $recordid=0, $form=false, $update=true) {
492 global $DB;
494 if (!$data && !$template) {
495 return false;
497 if ($template == 'csstemplate' or $template == 'jstemplate' ) {
498 return '';
501 // get all the fields for that database
502 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'id')) {
504 $table = new html_table();
505 $table->attributes['class'] = 'mod-data-default-template';
506 $table->colclasses = array('template-field', 'template-token');
507 $table->data = array();
508 foreach ($fields as $field) {
509 if ($form) { // Print forms instead of data
510 $fieldobj = data_get_field($field, $data);
511 $token = $fieldobj->display_add_field($recordid);
512 } else { // Just print the tag
513 $token = '[['.$field->name.']]';
515 $table->data[] = array(
516 $field->name.': ',
517 $token
520 if ($template == 'listtemplate') {
521 $cell = new html_table_cell('##edit## ##more## ##delete## ##approve## ##disapprove## ##export##');
522 $cell->colspan = 2;
523 $cell->attributes['class'] = 'controls';
524 $table->data[] = new html_table_row(array($cell));
525 } else if ($template == 'singletemplate') {
526 $cell = new html_table_cell('##edit## ##delete## ##approve## ##disapprove## ##export##');
527 $cell->colspan = 2;
528 $cell->attributes['class'] = 'controls';
529 $table->data[] = new html_table_row(array($cell));
530 } else if ($template == 'asearchtemplate') {
531 $row = new html_table_row(array(get_string('authorfirstname', 'data').': ', '##firstname##'));
532 $row->attributes['class'] = 'searchcontrols';
533 $table->data[] = $row;
534 $row = new html_table_row(array(get_string('authorlastname', 'data').': ', '##lastname##'));
535 $row->attributes['class'] = 'searchcontrols';
536 $table->data[] = $row;
539 $str = '';
540 if ($template == 'listtemplate'){
541 $str .= '##delcheck##';
542 $str .= html_writer::empty_tag('br');
545 $str .= html_writer::start_tag('div', array('class' => 'defaulttemplate'));
546 $str .= html_writer::table($table);
547 $str .= html_writer::end_tag('div');
548 if ($template == 'listtemplate'){
549 $str .= html_writer::empty_tag('hr');
552 if ($update) {
553 $newdata = new stdClass();
554 $newdata->id = $data->id;
555 $newdata->{$template} = $str;
556 $DB->update_record('data', $newdata);
557 $data->{$template} = $str;
560 return $str;
566 * Search for a field name and replaces it with another one in all the
567 * form templates. Set $newfieldname as '' if you want to delete the
568 * field from the form.
570 * @global object
571 * @param object $data
572 * @param string $searchfieldname
573 * @param string $newfieldname
574 * @return bool
576 function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
577 global $DB;
579 if (!empty($newfieldname)) {
580 $prestring = '[[';
581 $poststring = ']]';
582 $idpart = '#id';
584 } else {
585 $prestring = '';
586 $poststring = '';
587 $idpart = '';
590 $newdata = new stdClass();
591 $newdata->id = $data->id;
592 $newdata->singletemplate = str_ireplace('[['.$searchfieldname.']]',
593 $prestring.$newfieldname.$poststring, $data->singletemplate);
595 $newdata->listtemplate = str_ireplace('[['.$searchfieldname.']]',
596 $prestring.$newfieldname.$poststring, $data->listtemplate);
598 $newdata->addtemplate = str_ireplace('[['.$searchfieldname.']]',
599 $prestring.$newfieldname.$poststring, $data->addtemplate);
601 $newdata->addtemplate = str_ireplace('[['.$searchfieldname.'#id]]',
602 $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate);
604 $newdata->rsstemplate = str_ireplace('[['.$searchfieldname.']]',
605 $prestring.$newfieldname.$poststring, $data->rsstemplate);
607 return $DB->update_record('data', $newdata);
612 * Appends a new field at the end of the form template.
614 * @global object
615 * @param object $data
616 * @param string $newfieldname
618 function data_append_new_field_to_templates($data, $newfieldname) {
619 global $DB;
621 $newdata = new stdClass();
622 $newdata->id = $data->id;
623 $change = false;
625 if (!empty($data->singletemplate)) {
626 $newdata->singletemplate = $data->singletemplate.' [[' . $newfieldname .']]';
627 $change = true;
629 if (!empty($data->addtemplate)) {
630 $newdata->addtemplate = $data->addtemplate.' [[' . $newfieldname . ']]';
631 $change = true;
633 if (!empty($data->rsstemplate)) {
634 $newdata->rsstemplate = $data->singletemplate.' [[' . $newfieldname . ']]';
635 $change = true;
637 if ($change) {
638 $DB->update_record('data', $newdata);
644 * given a field name
645 * this function creates an instance of the particular subfield class
647 * @global object
648 * @param string $name
649 * @param object $data
650 * @return object|bool
652 function data_get_field_from_name($name, $data){
653 global $DB;
655 $field = $DB->get_record('data_fields', array('name'=>$name, 'dataid'=>$data->id));
657 if ($field) {
658 return data_get_field($field, $data);
659 } else {
660 return false;
665 * given a field id
666 * this function creates an instance of the particular subfield class
668 * @global object
669 * @param int $fieldid
670 * @param object $data
671 * @return bool|object
673 function data_get_field_from_id($fieldid, $data){
674 global $DB;
676 $field = $DB->get_record('data_fields', array('id'=>$fieldid, 'dataid'=>$data->id));
678 if ($field) {
679 return data_get_field($field, $data);
680 } else {
681 return false;
686 * given a field id
687 * this function creates an instance of the particular subfield class
689 * @global object
690 * @param string $type
691 * @param object $data
692 * @return object
694 function data_get_field_new($type, $data) {
695 global $CFG;
697 require_once($CFG->dirroot.'/mod/data/field/'.$type.'/field.class.php');
698 $newfield = 'data_field_'.$type;
699 $newfield = new $newfield(0, $data);
700 return $newfield;
704 * returns a subclass field object given a record of the field, used to
705 * invoke plugin methods
706 * input: $param $field - record from db
708 * @global object
709 * @param object $field
710 * @param object $data
711 * @param object $cm
712 * @return object
714 function data_get_field($field, $data, $cm=null) {
715 global $CFG;
717 if ($field) {
718 require_once('field/'.$field->type.'/field.class.php');
719 $newfield = 'data_field_'.$field->type;
720 $newfield = new $newfield($field, $data, $cm);
721 return $newfield;
727 * Given record object (or id), returns true if the record belongs to the current user
729 * @global object
730 * @global object
731 * @param mixed $record record object or id
732 * @return bool
734 function data_isowner($record) {
735 global $USER, $DB;
737 if (!isloggedin()) { // perf shortcut
738 return false;
741 if (!is_object($record)) {
742 if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
743 return false;
747 return ($record->userid == $USER->id);
751 * has a user reached the max number of entries?
753 * @param object $data
754 * @return bool
756 function data_atmaxentries($data){
757 if (!$data->maxentries){
758 return false;
760 } else {
761 return (data_numentries($data) >= $data->maxentries);
766 * returns the number of entries already made by this user
768 * @global object
769 * @global object
770 * @param object $data
771 * @return int
773 function data_numentries($data){
774 global $USER, $DB;
775 $sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
776 return $DB->count_records_sql($sql, array($data->id, $USER->id));
780 * function that takes in a dataid and adds a record
781 * this is used everytime an add template is submitted
783 * @global object
784 * @global object
785 * @param object $data
786 * @param int $groupid
787 * @return bool
789 function data_add_record($data, $groupid=0){
790 global $USER, $DB;
792 $cm = get_coursemodule_from_instance('data', $data->id);
793 $context = context_module::instance($cm->id);
795 $record = new stdClass();
796 $record->userid = $USER->id;
797 $record->dataid = $data->id;
798 $record->groupid = $groupid;
799 $record->timecreated = $record->timemodified = time();
800 if (has_capability('mod/data:approve', $context)) {
801 $record->approved = 1;
802 } else {
803 $record->approved = 0;
805 return $DB->insert_record('data_records', $record);
809 * check the multple existence any tag in a template
811 * check to see if there are 2 or more of the same tag being used.
813 * @global object
814 * @param int $dataid,
815 * @param string $template
816 * @return bool
818 function data_tags_check($dataid, $template) {
819 global $DB, $OUTPUT;
821 // first get all the possible tags
822 $fields = $DB->get_records('data_fields', array('dataid'=>$dataid));
823 // then we generate strings to replace
824 $tagsok = true; // let's be optimistic
825 foreach ($fields as $field){
826 $pattern="/\[\[".$field->name."\]\]/i";
827 if (preg_match_all($pattern, $template, $dummy)>1){
828 $tagsok = false;
829 echo $OUTPUT->notification('[['.$field->name.']] - '.get_string('multipletags','data'));
832 // else return true
833 return $tagsok;
837 * Adds an instance of a data
839 * @param stdClass $data
840 * @param mod_data_mod_form $mform
841 * @return int intance id
843 function data_add_instance($data, $mform = null) {
844 global $DB;
846 if (empty($data->assessed)) {
847 $data->assessed = 0;
850 $data->timemodified = time();
852 $data->id = $DB->insert_record('data', $data);
854 data_grade_item_update($data);
856 return $data->id;
860 * updates an instance of a data
862 * @global object
863 * @param object $data
864 * @return bool
866 function data_update_instance($data) {
867 global $DB, $OUTPUT;
869 $data->timemodified = time();
870 $data->id = $data->instance;
872 if (empty($data->assessed)) {
873 $data->assessed = 0;
876 if (empty($data->ratingtime) or empty($data->assessed)) {
877 $data->assesstimestart = 0;
878 $data->assesstimefinish = 0;
881 if (empty($data->notification)) {
882 $data->notification = 0;
885 $DB->update_record('data', $data);
887 data_grade_item_update($data);
889 return true;
894 * deletes an instance of a data
896 * @global object
897 * @param int $id
898 * @return bool
900 function data_delete_instance($id) { // takes the dataid
901 global $DB, $CFG;
903 if (!$data = $DB->get_record('data', array('id'=>$id))) {
904 return false;
907 $cm = get_coursemodule_from_instance('data', $data->id);
908 $context = context_module::instance($cm->id);
910 /// Delete all the associated information
912 // files
913 $fs = get_file_storage();
914 $fs->delete_area_files($context->id, 'mod_data');
916 // get all the records in this data
917 $sql = "SELECT r.id
918 FROM {data_records} r
919 WHERE r.dataid = ?";
921 $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
923 // delete all the records and fields
924 $DB->delete_records('data_records', array('dataid'=>$id));
925 $DB->delete_records('data_fields', array('dataid'=>$id));
927 // Delete the instance itself
928 $result = $DB->delete_records('data', array('id'=>$id));
930 // cleanup gradebook
931 data_grade_item_delete($data);
933 return $result;
937 * returns a summary of data activity of this user
939 * @global object
940 * @param object $course
941 * @param object $user
942 * @param object $mod
943 * @param object $data
944 * @return object|null
946 function data_user_outline($course, $user, $mod, $data) {
947 global $DB, $CFG;
948 require_once("$CFG->libdir/gradelib.php");
950 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
951 if (empty($grades->items[0]->grades)) {
952 $grade = false;
953 } else {
954 $grade = reset($grades->items[0]->grades);
958 if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id, 'userid'=>$user->id))) {
959 $result = new stdClass();
960 $result->info = get_string('numrecords', 'data', $countrecords);
961 $lastrecord = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
962 WHERE dataid = ? AND userid = ?
963 ORDER BY timemodified DESC', array($data->id, $user->id), true);
964 $result->time = $lastrecord->timemodified;
965 if ($grade) {
966 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
968 return $result;
969 } else if ($grade) {
970 $result = new stdClass();
971 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
973 //datesubmitted == time created. dategraded == time modified or time overridden
974 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
975 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
976 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
977 $result->time = $grade->dategraded;
978 } else {
979 $result->time = $grade->datesubmitted;
982 return $result;
984 return NULL;
988 * Prints all the records uploaded by this user
990 * @global object
991 * @param object $course
992 * @param object $user
993 * @param object $mod
994 * @param object $data
996 function data_user_complete($course, $user, $mod, $data) {
997 global $DB, $CFG, $OUTPUT;
998 require_once("$CFG->libdir/gradelib.php");
1000 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1001 if (!empty($grades->items[0]->grades)) {
1002 $grade = reset($grades->items[0]->grades);
1003 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1004 if ($grade->str_feedback) {
1005 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1009 if ($records = $DB->get_records('data_records', array('dataid'=>$data->id,'userid'=>$user->id), 'timemodified DESC')) {
1010 data_print_template('singletemplate', $records, $data);
1015 * Return grade for given user or all users.
1017 * @global object
1018 * @param object $data
1019 * @param int $userid optional user id, 0 means all users
1020 * @return array array of grades, false if none
1022 function data_get_user_grades($data, $userid=0) {
1023 global $CFG;
1025 require_once($CFG->dirroot.'/rating/lib.php');
1027 $ratingoptions = new stdClass;
1028 $ratingoptions->component = 'mod_data';
1029 $ratingoptions->ratingarea = 'entry';
1030 $ratingoptions->modulename = 'data';
1031 $ratingoptions->moduleid = $data->id;
1033 $ratingoptions->userid = $userid;
1034 $ratingoptions->aggregationmethod = $data->assessed;
1035 $ratingoptions->scaleid = $data->scale;
1036 $ratingoptions->itemtable = 'data_records';
1037 $ratingoptions->itemtableusercolumn = 'userid';
1039 $rm = new rating_manager();
1040 return $rm->get_user_grades($ratingoptions);
1044 * Update activity grades
1046 * @category grade
1047 * @param object $data
1048 * @param int $userid specific user only, 0 means all
1049 * @param bool $nullifnone
1051 function data_update_grades($data, $userid=0, $nullifnone=true) {
1052 global $CFG, $DB;
1053 require_once($CFG->libdir.'/gradelib.php');
1055 if (!$data->assessed) {
1056 data_grade_item_update($data);
1058 } else if ($grades = data_get_user_grades($data, $userid)) {
1059 data_grade_item_update($data, $grades);
1061 } else if ($userid and $nullifnone) {
1062 $grade = new stdClass();
1063 $grade->userid = $userid;
1064 $grade->rawgrade = NULL;
1065 data_grade_item_update($data, $grade);
1067 } else {
1068 data_grade_item_update($data);
1073 * Update all grades in gradebook.
1075 * @global object
1077 function data_upgrade_grades() {
1078 global $DB;
1080 $sql = "SELECT COUNT('x')
1081 FROM {data} d, {course_modules} cm, {modules} m
1082 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
1083 $count = $DB->count_records_sql($sql);
1085 $sql = "SELECT d.*, cm.idnumber AS cmidnumber, d.course AS courseid
1086 FROM {data} d, {course_modules} cm, {modules} m
1087 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
1088 $rs = $DB->get_recordset_sql($sql);
1089 if ($rs->valid()) {
1090 // too much debug output
1091 $pbar = new progress_bar('dataupgradegrades', 500, true);
1092 $i=0;
1093 foreach ($rs as $data) {
1094 $i++;
1095 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
1096 data_update_grades($data, 0, false);
1097 $pbar->update($i, $count, "Updating Database grades ($i/$count).");
1100 $rs->close();
1104 * Update/create grade item for given data
1106 * @category grade
1107 * @param stdClass $data A database instance with extra cmidnumber property
1108 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1109 * @return object grade_item
1111 function data_grade_item_update($data, $grades=NULL) {
1112 global $CFG;
1113 require_once($CFG->libdir.'/gradelib.php');
1115 $params = array('itemname'=>$data->name, 'idnumber'=>$data->cmidnumber);
1117 if (!$data->assessed or $data->scale == 0) {
1118 $params['gradetype'] = GRADE_TYPE_NONE;
1120 } else if ($data->scale > 0) {
1121 $params['gradetype'] = GRADE_TYPE_VALUE;
1122 $params['grademax'] = $data->scale;
1123 $params['grademin'] = 0;
1125 } else if ($data->scale < 0) {
1126 $params['gradetype'] = GRADE_TYPE_SCALE;
1127 $params['scaleid'] = -$data->scale;
1130 if ($grades === 'reset') {
1131 $params['reset'] = true;
1132 $grades = NULL;
1135 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, $grades, $params);
1139 * Delete grade item for given data
1141 * @category grade
1142 * @param object $data object
1143 * @return object grade_item
1145 function data_grade_item_delete($data) {
1146 global $CFG;
1147 require_once($CFG->libdir.'/gradelib.php');
1149 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, NULL, array('deleted'=>1));
1152 // junk functions
1154 * takes a list of records, the current data, a search string,
1155 * and mode to display prints the translated template
1157 * @global object
1158 * @global object
1159 * @param string $template
1160 * @param array $records
1161 * @param object $data
1162 * @param string $search
1163 * @param int $page
1164 * @param bool $return
1165 * @return mixed
1167 function data_print_template($template, $records, $data, $search='', $page=0, $return=false) {
1168 global $CFG, $DB, $OUTPUT;
1170 $cm = get_coursemodule_from_instance('data', $data->id);
1171 $context = context_module::instance($cm->id);
1173 static $fields = NULL;
1174 static $isteacher;
1175 static $dataid = NULL;
1177 if (empty($dataid)) {
1178 $dataid = $data->id;
1179 } else if ($dataid != $data->id) {
1180 $fields = NULL;
1183 if (empty($fields)) {
1184 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1185 foreach ($fieldrecords as $fieldrecord) {
1186 $fields[]= data_get_field($fieldrecord, $data);
1188 $isteacher = has_capability('mod/data:managetemplates', $context);
1191 if (empty($records)) {
1192 return;
1195 // Check whether this activity is read-only at present
1196 $readonly = data_in_readonly_period($data);
1198 foreach ($records as $record) { // Might be just one for the single template
1200 // Replacing tags
1201 $patterns = array();
1202 $replacement = array();
1204 // Then we generate strings to replace for normal tags
1205 foreach ($fields as $field) {
1206 $patterns[]='[['.$field->field->name.']]';
1207 $replacement[] = highlight($search, $field->display_browse_field($record->id, $template));
1210 $canmanageentries = has_capability('mod/data:manageentries', $context);
1212 // Replacing special tags (##Edit##, ##Delete##, ##More##)
1213 $patterns[]='##edit##';
1214 $patterns[]='##delete##';
1215 if ($canmanageentries || (!$readonly && data_isowner($record->id))) {
1216 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d='
1217 .$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>';
1218 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='
1219 .$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>';
1220 } else {
1221 $replacement[] = '';
1222 $replacement[] = '';
1225 $moreurl = $CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&amp;rid=' . $record->id;
1226 if ($search) {
1227 $moreurl .= '&amp;filter=1';
1229 $patterns[]='##more##';
1230 $replacement[] = '<a href="'.$moreurl.'"><img src="'.$OUTPUT->pix_url('t/preview').
1231 '" class="iconsmall" alt="'.get_string('more', 'data').'" title="'.get_string('more', 'data').
1232 '" /></a>';
1234 $patterns[]='##moreurl##';
1235 $replacement[] = $moreurl;
1237 $patterns[]='##delcheck##';
1238 if ($canmanageentries) {
1239 $replacement[] = html_writer::checkbox('delcheck[]', $record->id, false, '', array('class' => 'recordcheckbox'));
1240 } else {
1241 $replacement[] = '';
1244 $patterns[]='##user##';
1245 $replacement[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$record->userid.
1246 '&amp;course='.$data->course.'">'.fullname($record).'</a>';
1248 $patterns[]='##export##';
1250 if (!empty($CFG->enableportfolios) && ($template == 'singletemplate' || $template == 'listtemplate')
1251 && ((has_capability('mod/data:exportentry', $context)
1252 || (data_isowner($record->id) && has_capability('mod/data:exportownentry', $context))))) {
1253 require_once($CFG->libdir . '/portfoliolib.php');
1254 $button = new portfolio_add_button();
1255 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id, 'recordid' => $record->id), 'mod_data');
1256 list($formats, $files) = data_portfolio_caller::formats($fields, $record);
1257 $button->set_formats($formats);
1258 $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1259 } else {
1260 $replacement[] = '';
1263 $patterns[] = '##timeadded##';
1264 $replacement[] = userdate($record->timecreated);
1266 $patterns[] = '##timemodified##';
1267 $replacement [] = userdate($record->timemodified);
1269 $patterns[]='##approve##';
1270 if (has_capability('mod/data:approve', $context) && ($data->approval) && (!$record->approved)) {
1271 $approveurl = new moodle_url('/mod/data/view.php',
1272 array('d' => $data->id, 'approve' => $record->id, 'sesskey' => sesskey()));
1273 $approveicon = new pix_icon('t/approve', get_string('approve', 'data'), '', array('class' => 'iconsmall'));
1274 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($approveurl, $approveicon),
1275 array('class' => 'approve'));
1276 } else {
1277 $replacement[] = '';
1280 $patterns[]='##disapprove##';
1281 if (has_capability('mod/data:approve', $context) && ($data->approval) && ($record->approved)) {
1282 $disapproveurl = new moodle_url('/mod/data/view.php',
1283 array('d' => $data->id, 'disapprove' => $record->id, 'sesskey' => sesskey()));
1284 $disapproveicon = new pix_icon('t/block', get_string('disapprove', 'data'), '', array('class' => 'iconsmall'));
1285 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($disapproveurl, $disapproveicon),
1286 array('class' => 'disapprove'));
1287 } else {
1288 $replacement[] = '';
1291 $patterns[]='##comments##';
1292 if (($template == 'listtemplate') && ($data->comments)) {
1294 if (!empty($CFG->usecomments)) {
1295 require_once($CFG->dirroot . '/comment/lib.php');
1296 list($context, $course, $cm) = get_context_info_array($context->id);
1297 $cmt = new stdClass();
1298 $cmt->context = $context;
1299 $cmt->course = $course;
1300 $cmt->cm = $cm;
1301 $cmt->area = 'database_entry';
1302 $cmt->itemid = $record->id;
1303 $cmt->showcount = true;
1304 $cmt->component = 'mod_data';
1305 $comment = new comment($cmt);
1306 $replacement[] = $comment->output(true);
1308 } else {
1309 $replacement[] = '';
1312 // actual replacement of the tags
1313 $newtext = str_ireplace($patterns, $replacement, $data->{$template});
1315 // no more html formatting and filtering - see MDL-6635
1316 if ($return) {
1317 return $newtext;
1318 } else {
1319 echo $newtext;
1321 // hack alert - return is always false in singletemplate anyway ;-)
1322 /**********************************
1323 * Printing Ratings Form *
1324 *********************************/
1325 if ($template == 'singletemplate') { //prints ratings options
1326 data_print_ratings($data, $record);
1329 /**********************************
1330 * Printing Comments Form *
1331 *********************************/
1332 if (($template == 'singletemplate') && ($data->comments)) {
1333 if (!empty($CFG->usecomments)) {
1334 require_once($CFG->dirroot . '/comment/lib.php');
1335 list($context, $course, $cm) = get_context_info_array($context->id);
1336 $cmt = new stdClass();
1337 $cmt->context = $context;
1338 $cmt->course = $course;
1339 $cmt->cm = $cm;
1340 $cmt->area = 'database_entry';
1341 $cmt->itemid = $record->id;
1342 $cmt->showcount = true;
1343 $cmt->component = 'mod_data';
1344 $comment = new comment($cmt);
1345 $comment->output(false);
1353 * Return rating related permissions
1355 * @param string $contextid the context id
1356 * @param string $component the component to get rating permissions for
1357 * @param string $ratingarea the rating area to get permissions for
1358 * @return array an associative array of the user's rating permissions
1360 function data_rating_permissions($contextid, $component, $ratingarea) {
1361 $context = context::instance_by_id($contextid, MUST_EXIST);
1362 if ($component != 'mod_data' || $ratingarea != 'entry') {
1363 return null;
1365 return array(
1366 'view' => has_capability('mod/data:viewrating',$context),
1367 'viewany' => has_capability('mod/data:viewanyrating',$context),
1368 'viewall' => has_capability('mod/data:viewallratings',$context),
1369 'rate' => has_capability('mod/data:rate',$context)
1374 * Validates a submitted rating
1375 * @param array $params submitted data
1376 * context => object the context in which the rated items exists [required]
1377 * itemid => int the ID of the object being rated
1378 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1379 * rating => int the submitted rating
1380 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1381 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
1382 * @return boolean true if the rating is valid. Will throw rating_exception if not
1384 function data_rating_validate($params) {
1385 global $DB, $USER;
1387 // Check the component is mod_data
1388 if ($params['component'] != 'mod_data') {
1389 throw new rating_exception('invalidcomponent');
1392 // Check the ratingarea is entry (the only rating area in data module)
1393 if ($params['ratingarea'] != 'entry') {
1394 throw new rating_exception('invalidratingarea');
1397 // Check the rateduserid is not the current user .. you can't rate your own entries
1398 if ($params['rateduserid'] == $USER->id) {
1399 throw new rating_exception('nopermissiontorate');
1402 $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
1403 FROM {data_records} r
1404 JOIN {data} d ON r.dataid = d.id
1405 WHERE r.id = :itemid";
1406 $dataparams = array('itemid'=>$params['itemid']);
1407 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1408 //item doesn't exist
1409 throw new rating_exception('invaliditemid');
1412 if ($info->scale != $params['scaleid']) {
1413 //the scale being submitted doesnt match the one in the database
1414 throw new rating_exception('invalidscaleid');
1417 //check that the submitted rating is valid for the scale
1419 // lower limit
1420 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
1421 throw new rating_exception('invalidnum');
1424 // upper limit
1425 if ($info->scale < 0) {
1426 //its a custom scale
1427 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
1428 if ($scalerecord) {
1429 $scalearray = explode(',', $scalerecord->scale);
1430 if ($params['rating'] > count($scalearray)) {
1431 throw new rating_exception('invalidnum');
1433 } else {
1434 throw new rating_exception('invalidscaleid');
1436 } else if ($params['rating'] > $info->scale) {
1437 //if its numeric and submitted rating is above maximum
1438 throw new rating_exception('invalidnum');
1441 if ($info->approval && !$info->approved) {
1442 //database requires approval but this item isnt approved
1443 throw new rating_exception('nopermissiontorate');
1446 // check the item we're rating was created in the assessable time window
1447 if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
1448 if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
1449 throw new rating_exception('notavailable');
1453 $course = $DB->get_record('course', array('id'=>$info->course), '*', MUST_EXIST);
1454 $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1455 $context = context_module::instance($cm->id);
1457 // if the supplied context doesnt match the item's context
1458 if ($context->id != $params['context']->id) {
1459 throw new rating_exception('invalidcontext');
1462 // Make sure groups allow this user to see the item they're rating
1463 $groupid = $info->groupid;
1464 if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
1465 if (!groups_group_exists($groupid)) { // Can't find group
1466 throw new rating_exception('cannotfindgroup');//something is wrong
1469 if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1470 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
1471 throw new rating_exception('notmemberofgroup');
1475 return true;
1480 * function that takes in the current data, number of items per page,
1481 * a search string and prints a preference box in view.php
1483 * This preference box prints a searchable advanced search template if
1484 * a) A template is defined
1485 * b) The advanced search checkbox is checked.
1487 * @global object
1488 * @global object
1489 * @param object $data
1490 * @param int $perpage
1491 * @param string $search
1492 * @param string $sort
1493 * @param string $order
1494 * @param array $search_array
1495 * @param int $advanced
1496 * @param string $mode
1497 * @return void
1499 function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
1500 global $CFG, $DB, $PAGE, $OUTPUT;
1502 $cm = get_coursemodule_from_instance('data', $data->id);
1503 $context = context_module::instance($cm->id);
1504 echo '<br /><div class="datapreferences">';
1505 echo '<form id="options" action="view.php" method="get">';
1506 echo '<div>';
1507 echo '<input type="hidden" name="d" value="'.$data->id.'" />';
1508 if ($mode =='asearch') {
1509 $advanced = 1;
1510 echo '<input type="hidden" name="mode" value="list" />';
1512 echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
1513 $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
1514 20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
1515 echo html_writer::select($pagesizes, 'perpage', $perpage, false, array('id'=>'pref_perpage'));
1517 if ($advanced) {
1518 $regsearchclass = 'search_none';
1519 $advancedsearchclass = 'search_inline';
1520 } else {
1521 $regsearchclass = 'search_inline';
1522 $advancedsearchclass = 'search_none';
1524 echo '<div id="reg_search" class="' . $regsearchclass . '" >&nbsp;&nbsp;&nbsp;';
1525 echo '<label for="pref_search">'.get_string('search').'</label> <input type="text" size="16" name="search" id= "pref_search" value="'.s($search).'" /></div>';
1526 echo '&nbsp;&nbsp;&nbsp;<label for="pref_sortby">'.get_string('sortby').'</label> ';
1527 // foreach field, print the option
1528 echo '<select name="sort" id="pref_sortby">';
1529 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'name')) {
1530 echo '<optgroup label="'.get_string('fields', 'data').'">';
1531 foreach ($fields as $field) {
1532 if ($field->id == $sort) {
1533 echo '<option value="'.$field->id.'" selected="selected">'.$field->name.'</option>';
1534 } else {
1535 echo '<option value="'.$field->id.'">'.$field->name.'</option>';
1538 echo '</optgroup>';
1540 $options = array();
1541 $options[DATA_TIMEADDED] = get_string('timeadded', 'data');
1542 $options[DATA_TIMEMODIFIED] = get_string('timemodified', 'data');
1543 $options[DATA_FIRSTNAME] = get_string('authorfirstname', 'data');
1544 $options[DATA_LASTNAME] = get_string('authorlastname', 'data');
1545 if ($data->approval and has_capability('mod/data:approve', $context)) {
1546 $options[DATA_APPROVED] = get_string('approved', 'data');
1548 echo '<optgroup label="'.get_string('other', 'data').'">';
1549 foreach ($options as $key => $name) {
1550 if ($key == $sort) {
1551 echo '<option value="'.$key.'" selected="selected">'.$name.'</option>';
1552 } else {
1553 echo '<option value="'.$key.'">'.$name.'</option>';
1556 echo '</optgroup>';
1557 echo '</select>';
1558 echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
1559 echo '<select id="pref_order" name="order">';
1560 if ($order == 'ASC') {
1561 echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
1562 } else {
1563 echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1565 if ($order == 'DESC') {
1566 echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
1567 } else {
1568 echo '<option value="DESC">'.get_string('descending','data').'</option>';
1570 echo '</select>';
1572 if ($advanced) {
1573 $checked = ' checked="checked" ';
1575 else {
1576 $checked = '';
1578 $PAGE->requires->js('/mod/data/data.js');
1579 echo '&nbsp;<input type="hidden" name="advanced" value="0" />';
1580 echo '&nbsp;<input type="hidden" name="filter" value="1" />';
1581 echo '&nbsp;<input type="checkbox" id="advancedcheckbox" name="advanced" value="1" '.$checked.' onchange="showHideAdvSearch(this.checked);" /><label for="advancedcheckbox">'.get_string('advancedsearch', 'data').'</label>';
1582 echo '&nbsp;<input type="submit" value="'.get_string('savesettings','data').'" />';
1584 echo '<br />';
1585 echo '<div class="' . $advancedsearchclass . '" id="data_adv_form">';
1586 echo '<table class="boxaligncenter">';
1588 // print ASC or DESC
1589 echo '<tr><td colspan="2">&nbsp;</td></tr>';
1590 $i = 0;
1592 // Determine if we are printing all fields for advanced search, or the template for advanced search
1593 // If a template is not defined, use the deafault template and display all fields.
1594 if(empty($data->asearchtemplate)) {
1595 data_generate_default_template($data, 'asearchtemplate');
1598 static $fields = NULL;
1599 static $isteacher;
1600 static $dataid = NULL;
1602 if (empty($dataid)) {
1603 $dataid = $data->id;
1604 } else if ($dataid != $data->id) {
1605 $fields = NULL;
1608 if (empty($fields)) {
1609 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1610 foreach ($fieldrecords as $fieldrecord) {
1611 $fields[]= data_get_field($fieldrecord, $data);
1614 $isteacher = has_capability('mod/data:managetemplates', $context);
1617 // Replacing tags
1618 $patterns = array();
1619 $replacement = array();
1621 // Then we generate strings to replace for normal tags
1622 foreach ($fields as $field) {
1623 $fieldname = $field->field->name;
1624 $fieldname = preg_quote($fieldname, '/');
1625 $patterns[] = "/\[\[$fieldname\]\]/i";
1626 $searchfield = data_get_field_from_id($field->field->id, $data);
1627 if (!empty($search_array[$field->field->id]->data)) {
1628 $replacement[] = $searchfield->display_search_field($search_array[$field->field->id]->data);
1629 } else {
1630 $replacement[] = $searchfield->display_search_field();
1633 $fn = !empty($search_array[DATA_FIRSTNAME]->data) ? $search_array[DATA_FIRSTNAME]->data : '';
1634 $ln = !empty($search_array[DATA_LASTNAME]->data) ? $search_array[DATA_LASTNAME]->data : '';
1635 $patterns[] = '/##firstname##/';
1636 $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.'" />';
1637 $patterns[] = '/##lastname##/';
1638 $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.'" />';
1640 // actual replacement of the tags
1641 $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate);
1643 $options = new stdClass();
1644 $options->para=false;
1645 $options->noclean=true;
1646 echo '<tr><td>';
1647 echo format_text($newtext, FORMAT_HTML, $options);
1648 echo '</td></tr>';
1650 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>';
1651 echo '</table>';
1652 echo '</div>';
1653 echo '</div>';
1654 echo '</form>';
1655 echo '</div>';
1659 * @global object
1660 * @global object
1661 * @param object $data
1662 * @param object $record
1663 * @return void Output echo'd
1665 function data_print_ratings($data, $record) {
1666 global $OUTPUT;
1667 if (!empty($record->rating)){
1668 echo $OUTPUT->render($record->rating);
1673 * For Participantion Reports
1675 * @return array
1677 function data_get_view_actions() {
1678 return array('view');
1682 * @return array
1684 function data_get_post_actions() {
1685 return array('add','update','record delete');
1689 * @param string $name
1690 * @param int $dataid
1691 * @param int $fieldid
1692 * @return bool
1694 function data_fieldname_exists($name, $dataid, $fieldid = 0) {
1695 global $DB;
1697 if (!is_numeric($name)) {
1698 $like = $DB->sql_like('df.name', ':name', false);
1699 } else {
1700 $like = "df.name = :name";
1702 $params = array('name'=>$name);
1703 if ($fieldid) {
1704 $params['dataid'] = $dataid;
1705 $params['fieldid1'] = $fieldid;
1706 $params['fieldid2'] = $fieldid;
1707 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1708 WHERE $like AND df.dataid = :dataid
1709 AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
1710 } else {
1711 $params['dataid'] = $dataid;
1712 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1713 WHERE $like AND df.dataid = :dataid", $params);
1718 * @param array $fieldinput
1720 function data_convert_arrays_to_strings(&$fieldinput) {
1721 foreach ($fieldinput as $key => $val) {
1722 if (is_array($val)) {
1723 $str = '';
1724 foreach ($val as $inner) {
1725 $str .= $inner . ',';
1727 $str = substr($str, 0, -1);
1729 $fieldinput->$key = $str;
1736 * Converts a database (module instance) to use the Roles System
1738 * @global object
1739 * @global object
1740 * @uses CONTEXT_MODULE
1741 * @uses CAP_PREVENT
1742 * @uses CAP_ALLOW
1743 * @param object $data a data object with the same attributes as a record
1744 * from the data database table
1745 * @param int $datamodid the id of the data module, from the modules table
1746 * @param array $teacherroles array of roles that have archetype teacher
1747 * @param array $studentroles array of roles that have archetype student
1748 * @param array $guestroles array of roles that have archetype guest
1749 * @param int $cmid the course_module id for this data instance
1750 * @return boolean data module was converted or not
1752 function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
1753 global $CFG, $DB, $OUTPUT;
1755 if (!isset($data->participants) && !isset($data->assesspublic)
1756 && !isset($data->groupmode)) {
1757 // We assume that this database has already been converted to use the
1758 // Roles System. above fields get dropped the data module has been
1759 // upgraded to use Roles.
1760 return false;
1763 if (empty($cmid)) {
1764 // We were not given the course_module id. Try to find it.
1765 if (!$cm = get_coursemodule_from_instance('data', $data->id)) {
1766 echo $OUTPUT->notification('Could not get the course module for the data');
1767 return false;
1768 } else {
1769 $cmid = $cm->id;
1772 $context = context_module::instance($cmid);
1775 // $data->participants:
1776 // 1 - Only teachers can add entries
1777 // 3 - Teachers and students can add entries
1778 switch ($data->participants) {
1779 case 1:
1780 foreach ($studentroles as $studentrole) {
1781 assign_capability('mod/data:writeentry', CAP_PREVENT, $studentrole->id, $context->id);
1783 foreach ($teacherroles as $teacherrole) {
1784 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1786 break;
1787 case 3:
1788 foreach ($studentroles as $studentrole) {
1789 assign_capability('mod/data:writeentry', CAP_ALLOW, $studentrole->id, $context->id);
1791 foreach ($teacherroles as $teacherrole) {
1792 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1794 break;
1797 // $data->assessed:
1798 // 2 - Only teachers can rate posts
1799 // 1 - Everyone can rate posts
1800 // 0 - No one can rate posts
1801 switch ($data->assessed) {
1802 case 0:
1803 foreach ($studentroles as $studentrole) {
1804 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1806 foreach ($teacherroles as $teacherrole) {
1807 assign_capability('mod/data:rate', CAP_PREVENT, $teacherrole->id, $context->id);
1809 break;
1810 case 1:
1811 foreach ($studentroles as $studentrole) {
1812 assign_capability('mod/data:rate', CAP_ALLOW, $studentrole->id, $context->id);
1814 foreach ($teacherroles as $teacherrole) {
1815 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1817 break;
1818 case 2:
1819 foreach ($studentroles as $studentrole) {
1820 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1822 foreach ($teacherroles as $teacherrole) {
1823 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1825 break;
1828 // $data->assesspublic:
1829 // 0 - Students can only see their own ratings
1830 // 1 - Students can see everyone's ratings
1831 switch ($data->assesspublic) {
1832 case 0:
1833 foreach ($studentroles as $studentrole) {
1834 assign_capability('mod/data:viewrating', CAP_PREVENT, $studentrole->id, $context->id);
1836 foreach ($teacherroles as $teacherrole) {
1837 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1839 break;
1840 case 1:
1841 foreach ($studentroles as $studentrole) {
1842 assign_capability('mod/data:viewrating', CAP_ALLOW, $studentrole->id, $context->id);
1844 foreach ($teacherroles as $teacherrole) {
1845 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1847 break;
1850 if (empty($cm)) {
1851 $cm = $DB->get_record('course_modules', array('id'=>$cmid));
1854 switch ($cm->groupmode) {
1855 case NOGROUPS:
1856 break;
1857 case SEPARATEGROUPS:
1858 foreach ($studentroles as $studentrole) {
1859 assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id);
1861 foreach ($teacherroles as $teacherrole) {
1862 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1864 break;
1865 case VISIBLEGROUPS:
1866 foreach ($studentroles as $studentrole) {
1867 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id);
1869 foreach ($teacherroles as $teacherrole) {
1870 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1872 break;
1874 return true;
1878 * Returns the best name to show for a preset
1880 * @param string $shortname
1881 * @param string $path
1882 * @return string
1884 function data_preset_name($shortname, $path) {
1886 // We are looking inside the preset itself as a first choice, but also in normal data directory
1887 $string = get_string('modulename', 'datapreset_'.$shortname);
1889 if (substr($string, 0, 1) == '[') {
1890 return $shortname;
1891 } else {
1892 return $string;
1897 * Returns an array of all the available presets.
1899 * @return array
1901 function data_get_available_presets($context) {
1902 global $CFG, $USER;
1904 $presets = array();
1906 // First load the ratings sub plugins that exist within the modules preset dir
1907 if ($dirs = core_component::get_plugin_list('datapreset')) {
1908 foreach ($dirs as $dir=>$fulldir) {
1909 if (is_directory_a_preset($fulldir)) {
1910 $preset = new stdClass();
1911 $preset->path = $fulldir;
1912 $preset->userid = 0;
1913 $preset->shortname = $dir;
1914 $preset->name = data_preset_name($dir, $fulldir);
1915 if (file_exists($fulldir.'/screenshot.jpg')) {
1916 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.jpg';
1917 } else if (file_exists($fulldir.'/screenshot.png')) {
1918 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.png';
1919 } else if (file_exists($fulldir.'/screenshot.gif')) {
1920 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.gif';
1922 $presets[] = $preset;
1926 // Now add to that the site presets that people have saved
1927 $presets = data_get_available_site_presets($context, $presets);
1928 return $presets;
1932 * Gets an array of all of the presets that users have saved to the site.
1934 * @param stdClass $context The context that we are looking from.
1935 * @param array $presets
1936 * @return array An array of presets
1938 function data_get_available_site_presets($context, array $presets=array()) {
1939 global $USER;
1941 $fs = get_file_storage();
1942 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
1943 $canviewall = has_capability('mod/data:viewalluserpresets', $context);
1944 if (empty($files)) {
1945 return $presets;
1947 foreach ($files as $file) {
1948 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory() || (!$canviewall && $file->get_userid() != $USER->id)) {
1949 continue;
1951 $preset = new stdClass;
1952 $preset->path = $file->get_filepath();
1953 $preset->name = trim($preset->path, '/');
1954 $preset->shortname = $preset->name;
1955 $preset->userid = $file->get_userid();
1956 $preset->id = $file->get_id();
1957 $preset->storedfile = $file;
1958 $presets[] = $preset;
1960 return $presets;
1964 * Deletes a saved preset.
1966 * @param string $name
1967 * @return bool
1969 function data_delete_site_preset($name) {
1970 $fs = get_file_storage();
1972 $files = $fs->get_directory_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/');
1973 if (!empty($files)) {
1974 foreach ($files as $file) {
1975 $file->delete();
1979 $dir = $fs->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/', '.');
1980 if (!empty($dir)) {
1981 $dir->delete();
1983 return true;
1987 * Prints the heads for a page
1989 * @param stdClass $course
1990 * @param stdClass $cm
1991 * @param stdClass $data
1992 * @param string $currenttab
1994 function data_print_header($course, $cm, $data, $currenttab='') {
1996 global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
1998 $PAGE->set_title($data->name);
1999 echo $OUTPUT->header();
2000 echo $OUTPUT->heading(format_string($data->name), 2);
2001 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
2003 // Groups needed for Add entry tab
2004 $currentgroup = groups_get_activity_group($cm);
2005 $groupmode = groups_get_activity_groupmode($cm);
2007 // Print the tabs
2009 if ($currenttab) {
2010 include('tabs.php');
2013 // Print any notices
2015 if (!empty($displaynoticegood)) {
2016 echo $OUTPUT->notification($displaynoticegood, 'notifysuccess'); // good (usually green)
2017 } else if (!empty($displaynoticebad)) {
2018 echo $OUTPUT->notification($displaynoticebad); // bad (usuually red)
2023 * Can user add more entries?
2025 * @param object $data
2026 * @param mixed $currentgroup
2027 * @param int $groupmode
2028 * @param stdClass $context
2029 * @return bool
2031 function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
2032 global $USER;
2034 if (empty($context)) {
2035 $cm = get_coursemodule_from_instance('data', $data->id, 0, false, MUST_EXIST);
2036 $context = context_module::instance($cm->id);
2039 if (has_capability('mod/data:manageentries', $context)) {
2040 // no entry limits apply if user can manage
2042 } else if (!has_capability('mod/data:writeentry', $context)) {
2043 return false;
2045 } else if (data_atmaxentries($data)) {
2046 return false;
2047 } else if (data_in_readonly_period($data)) {
2048 // Check whether we're in a read-only period
2049 return false;
2052 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2053 return true;
2056 if ($currentgroup) {
2057 return groups_is_member($currentgroup);
2058 } else {
2059 //else it might be group 0 in visible mode
2060 if ($groupmode == VISIBLEGROUPS){
2061 return true;
2062 } else {
2063 return false;
2069 * Check whether the specified database activity is currently in a read-only period
2071 * @param object $data
2072 * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2074 function data_in_readonly_period($data) {
2075 $now = time();
2076 if (!$data->timeviewfrom && !$data->timeviewto) {
2077 return false;
2078 } else if (($data->timeviewfrom && $now < $data->timeviewfrom) || ($data->timeviewto && $now > $data->timeviewto)) {
2079 return false;
2081 return true;
2085 * @return bool
2087 function is_directory_a_preset($directory) {
2088 $directory = rtrim($directory, '/\\') . '/';
2089 $status = file_exists($directory.'singletemplate.html') &&
2090 file_exists($directory.'listtemplate.html') &&
2091 file_exists($directory.'listtemplateheader.html') &&
2092 file_exists($directory.'listtemplatefooter.html') &&
2093 file_exists($directory.'addtemplate.html') &&
2094 file_exists($directory.'rsstemplate.html') &&
2095 file_exists($directory.'rsstitletemplate.html') &&
2096 file_exists($directory.'csstemplate.css') &&
2097 file_exists($directory.'jstemplate.js') &&
2098 file_exists($directory.'preset.xml');
2100 return $status;
2104 * Abstract class used for data preset importers
2106 abstract class data_preset_importer {
2108 protected $course;
2109 protected $cm;
2110 protected $module;
2111 protected $directory;
2114 * Constructor
2116 * @param stdClass $course
2117 * @param stdClass $cm
2118 * @param stdClass $module
2119 * @param string $directory
2121 public function __construct($course, $cm, $module, $directory) {
2122 $this->course = $course;
2123 $this->cm = $cm;
2124 $this->module = $module;
2125 $this->directory = $directory;
2129 * Returns the name of the directory the preset is located in
2130 * @return string
2132 public function get_directory() {
2133 return basename($this->directory);
2137 * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2138 * @param file_storage $filestorage. should be null if using a conventional directory
2139 * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2140 * @param string $dir the directory to look in. null if using the Moodle file storage
2141 * @param string $filename the name of the file we want
2142 * @return string the contents of the file or null if the file doesn't exist.
2144 public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2145 if(empty($filestorage) || empty($fileobj)) {
2146 if (substr($dir, -1)!='/') {
2147 $dir .= '/';
2149 if (file_exists($dir.$filename)) {
2150 return file_get_contents($dir.$filename);
2151 } else {
2152 return null;
2154 } else {
2155 if ($filestorage->file_exists(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename)) {
2156 $file = $filestorage->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename);
2157 return $file->get_content();
2158 } else {
2159 return null;
2165 * Gets the preset settings
2166 * @global moodle_database $DB
2167 * @return stdClass
2169 public function get_preset_settings() {
2170 global $DB;
2172 $fs = $fileobj = null;
2173 if (!is_directory_a_preset($this->directory)) {
2174 //maybe the user requested a preset stored in the Moodle file storage
2176 $fs = get_file_storage();
2177 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2179 //preset name to find will be the final element of the directory
2180 $explodeddirectory = explode('/', $this->directory);
2181 $presettofind = end($explodeddirectory);
2183 //now go through the available files available and see if we can find it
2184 foreach ($files as $file) {
2185 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory()) {
2186 continue;
2188 $presetname = trim($file->get_filepath(), '/');
2189 if ($presetname==$presettofind) {
2190 $this->directory = $presetname;
2191 $fileobj = $file;
2195 if (empty($fileobj)) {
2196 print_error('invalidpreset', 'data', '', $this->directory);
2200 $allowed_settings = array(
2201 'intro',
2202 'comments',
2203 'requiredentries',
2204 'requiredentriestoview',
2205 'maxentries',
2206 'rssarticles',
2207 'approval',
2208 'defaultsortdir',
2209 'defaultsort');
2211 $result = new stdClass;
2212 $result->settings = new stdClass;
2213 $result->importfields = array();
2214 $result->currentfields = $DB->get_records('data_fields', array('dataid'=>$this->module->id));
2215 if (!$result->currentfields) {
2216 $result->currentfields = array();
2220 /* Grab XML */
2221 $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory,'preset.xml');
2222 $parsedxml = xmlize($presetxml, 0);
2224 /* First, do settings. Put in user friendly array. */
2225 $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
2226 $result->settings = new StdClass();
2227 foreach ($settingsarray as $setting => $value) {
2228 if (!is_array($value) || !in_array($setting, $allowed_settings)) {
2229 // unsupported setting
2230 continue;
2232 $result->settings->$setting = $value[0]['#'];
2235 /* Now work out fields to user friendly array */
2236 $fieldsarray = $parsedxml['preset']['#']['field'];
2237 foreach ($fieldsarray as $field) {
2238 if (!is_array($field)) {
2239 continue;
2241 $f = new StdClass();
2242 foreach ($field['#'] as $param => $value) {
2243 if (!is_array($value)) {
2244 continue;
2246 $f->$param = $value[0]['#'];
2248 $f->dataid = $this->module->id;
2249 $f->type = clean_param($f->type, PARAM_ALPHA);
2250 $result->importfields[] = $f;
2252 /* Now add the HTML templates to the settings array so we can update d */
2253 $result->settings->singletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"singletemplate.html");
2254 $result->settings->listtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplate.html");
2255 $result->settings->listtemplateheader = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplateheader.html");
2256 $result->settings->listtemplatefooter = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplatefooter.html");
2257 $result->settings->addtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"addtemplate.html");
2258 $result->settings->rsstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstemplate.html");
2259 $result->settings->rsstitletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstitletemplate.html");
2260 $result->settings->csstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"csstemplate.css");
2261 $result->settings->jstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"jstemplate.js");
2262 $result->settings->asearchtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"asearchtemplate.html");
2264 $result->settings->instance = $this->module->id;
2265 return $result;
2269 * Import the preset into the given database module
2270 * @return bool
2272 function import($overwritesettings) {
2273 global $DB, $CFG;
2275 $params = $this->get_preset_settings();
2276 $settings = $params->settings;
2277 $newfields = $params->importfields;
2278 $currentfields = $params->currentfields;
2279 $preservedfields = array();
2281 /* Maps fields and makes new ones */
2282 if (!empty($newfields)) {
2283 /* We require an injective mapping, and need to know what to protect */
2284 foreach ($newfields as $nid => $newfield) {
2285 $cid = optional_param("field_$nid", -1, PARAM_INT);
2286 if ($cid == -1) {
2287 continue;
2289 if (array_key_exists($cid, $preservedfields)){
2290 print_error('notinjectivemap', 'data');
2292 else $preservedfields[$cid] = true;
2295 foreach ($newfields as $nid => $newfield) {
2296 $cid = optional_param("field_$nid", -1, PARAM_INT);
2298 /* A mapping. Just need to change field params. Data kept. */
2299 if ($cid != -1 and isset($currentfields[$cid])) {
2300 $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->module);
2301 foreach ($newfield as $param => $value) {
2302 if ($param != "id") {
2303 $fieldobject->field->$param = $value;
2306 unset($fieldobject->field->similarfield);
2307 $fieldobject->update_field();
2308 unset($fieldobject);
2309 } else {
2310 /* Make a new field */
2311 include_once("field/$newfield->type/field.class.php");
2313 if (!isset($newfield->description)) {
2314 $newfield->description = '';
2316 $classname = 'data_field_'.$newfield->type;
2317 $fieldclass = new $classname($newfield, $this->module);
2318 $fieldclass->insert_field();
2319 unset($fieldclass);
2324 /* Get rid of all old unused data */
2325 if (!empty($preservedfields)) {
2326 foreach ($currentfields as $cid => $currentfield) {
2327 if (!array_key_exists($cid, $preservedfields)) {
2328 /* Data not used anymore so wipe! */
2329 print "Deleting field $currentfield->name<br />";
2331 $id = $currentfield->id;
2332 //Why delete existing data records and related comments/ratings??
2333 $DB->delete_records('data_content', array('fieldid'=>$id));
2334 $DB->delete_records('data_fields', array('id'=>$id));
2339 // handle special settings here
2340 if (!empty($settings->defaultsort)) {
2341 if (is_numeric($settings->defaultsort)) {
2342 // old broken value
2343 $settings->defaultsort = 0;
2344 } else {
2345 $settings->defaultsort = (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module->id, 'name'=>$settings->defaultsort));
2347 } else {
2348 $settings->defaultsort = 0;
2351 // do we want to overwrite all current database settings?
2352 if ($overwritesettings) {
2353 // all supported settings
2354 $overwrite = array_keys((array)$settings);
2355 } else {
2356 // only templates and sorting
2357 $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2358 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
2359 'asearchtemplate', 'defaultsortdir', 'defaultsort');
2362 // now overwrite current data settings
2363 foreach ($this->module as $prop=>$unused) {
2364 if (in_array($prop, $overwrite)) {
2365 $this->module->$prop = $settings->$prop;
2369 data_update_instance($this->module);
2371 return $this->cleanup();
2375 * Any clean up routines should go here
2376 * @return bool
2378 public function cleanup() {
2379 return true;
2384 * Data preset importer for uploaded presets
2386 class data_preset_upload_importer extends data_preset_importer {
2387 public function __construct($course, $cm, $module, $filepath) {
2388 global $USER;
2389 if (is_file($filepath)) {
2390 $fp = get_file_packer();
2391 if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2392 fulldelete($filepath);
2394 $filepath .= '_extracted';
2396 parent::__construct($course, $cm, $module, $filepath);
2398 public function cleanup() {
2399 return fulldelete($this->directory);
2404 * Data preset importer for existing presets
2406 class data_preset_existing_importer extends data_preset_importer {
2407 protected $userid;
2408 public function __construct($course, $cm, $module, $fullname) {
2409 global $USER;
2410 list($userid, $shortname) = explode('/', $fullname, 2);
2411 $context = context_module::instance($cm->id);
2412 if ($userid && ($userid != $USER->id) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2413 throw new coding_exception('Invalid preset provided');
2416 $this->userid = $userid;
2417 $filepath = data_preset_path($course, $userid, $shortname);
2418 parent::__construct($course, $cm, $module, $filepath);
2420 public function get_userid() {
2421 return $this->userid;
2426 * @global object
2427 * @global object
2428 * @param object $course
2429 * @param int $userid
2430 * @param string $shortname
2431 * @return string
2433 function data_preset_path($course, $userid, $shortname) {
2434 global $USER, $CFG;
2436 $context = context_course::instance($course->id);
2438 $userid = (int)$userid;
2440 $path = null;
2441 if ($userid > 0 && ($userid == $USER->id || has_capability('mod/data:viewalluserpresets', $context))) {
2442 $path = $CFG->dataroot.'/data/preset/'.$userid.'/'.$shortname;
2443 } else if ($userid == 0) {
2444 $path = $CFG->dirroot.'/mod/data/preset/'.$shortname;
2445 } else if ($userid < 0) {
2446 $path = $CFG->tempdir.'/data/'.-$userid.'/'.$shortname;
2449 return $path;
2453 * Implementation of the function for printing the form elements that control
2454 * whether the course reset functionality affects the data.
2456 * @param $mform form passed by reference
2458 function data_reset_course_form_definition(&$mform) {
2459 $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2460 $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2462 $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2463 $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2465 $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2466 $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2468 $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2469 $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
2473 * Course reset form defaults.
2474 * @return array
2476 function data_reset_course_form_defaults($course) {
2477 return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2481 * Removes all grades from gradebook
2483 * @global object
2484 * @global object
2485 * @param int $courseid
2486 * @param string $type optional type
2488 function data_reset_gradebook($courseid, $type='') {
2489 global $CFG, $DB;
2491 $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
2492 FROM {data} d, {course_modules} cm, {modules} m
2493 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
2495 if ($datas = $DB->get_records_sql($sql, array($courseid))) {
2496 foreach ($datas as $data) {
2497 data_grade_item_update($data, 'reset');
2503 * Actual implementation of the reset course functionality, delete all the
2504 * data responses for course $data->courseid.
2506 * @global object
2507 * @global object
2508 * @param object $data the data submitted from the reset course.
2509 * @return array status array
2511 function data_reset_userdata($data) {
2512 global $CFG, $DB;
2513 require_once($CFG->libdir.'/filelib.php');
2514 require_once($CFG->dirroot.'/rating/lib.php');
2516 $componentstr = get_string('modulenameplural', 'data');
2517 $status = array();
2519 $allrecordssql = "SELECT r.id
2520 FROM {data_records} r
2521 INNER JOIN {data} d ON r.dataid = d.id
2522 WHERE d.course = ?";
2524 $alldatassql = "SELECT d.id
2525 FROM {data} d
2526 WHERE d.course=?";
2528 $rm = new rating_manager();
2529 $ratingdeloptions = new stdClass;
2530 $ratingdeloptions->component = 'mod_data';
2531 $ratingdeloptions->ratingarea = 'entry';
2533 // delete entries if requested
2534 if (!empty($data->reset_data)) {
2535 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2536 $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid));
2537 $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid));
2539 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2540 foreach ($datas as $dataid=>$unused) {
2541 fulldelete("$CFG->dataroot/$data->courseid/moddata/data/$dataid");
2543 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2544 continue;
2546 $datacontext = context_module::instance($cm->id);
2548 $ratingdeloptions->contextid = $datacontext->id;
2549 $rm->delete_ratings($ratingdeloptions);
2553 if (empty($data->reset_gradebook_grades)) {
2554 // remove all grades from gradebook
2555 data_reset_gradebook($data->courseid);
2557 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2560 // remove entries by users not enrolled into course
2561 if (!empty($data->reset_data_notenrolled)) {
2562 $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
2563 FROM {data_records} r
2564 JOIN {data} d ON r.dataid = d.id
2565 LEFT JOIN {user} u ON r.userid = u.id
2566 WHERE d.course = ? AND r.userid > 0";
2568 $course_context = context_course::instance($data->courseid);
2569 $notenrolled = array();
2570 $fields = array();
2571 $rs = $DB->get_recordset_sql($recordssql, array($data->courseid));
2572 foreach ($rs as $record) {
2573 if (array_key_exists($record->userid, $notenrolled) or !$record->userexists or $record->userdeleted
2574 or !is_enrolled($course_context, $record->userid)) {
2575 //delete ratings
2576 if (!$cm = get_coursemodule_from_instance('data', $record->dataid)) {
2577 continue;
2579 $datacontext = context_module::instance($cm->id);
2580 $ratingdeloptions->contextid = $datacontext->id;
2581 $ratingdeloptions->itemid = $record->id;
2582 $rm->delete_ratings($ratingdeloptions);
2584 $DB->delete_records('comments', array('itemid'=>$record->id, 'commentarea'=>'database_entry'));
2585 $DB->delete_records('data_content', array('recordid'=>$record->id));
2586 $DB->delete_records('data_records', array('id'=>$record->id));
2587 // HACK: this is ugly - the recordid should be before the fieldid!
2588 if (!array_key_exists($record->dataid, $fields)) {
2589 if ($fs = $DB->get_records('data_fields', array('dataid'=>$record->dataid))) {
2590 $fields[$record->dataid] = array_keys($fs);
2591 } else {
2592 $fields[$record->dataid] = array();
2595 foreach($fields[$record->dataid] as $fieldid) {
2596 fulldelete("$CFG->dataroot/$data->courseid/moddata/data/$record->dataid/$fieldid/$record->id");
2598 $notenrolled[$record->userid] = true;
2601 $rs->close();
2602 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
2605 // remove all ratings
2606 if (!empty($data->reset_data_ratings)) {
2607 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2608 foreach ($datas as $dataid=>$unused) {
2609 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2610 continue;
2612 $datacontext = context_module::instance($cm->id);
2614 $ratingdeloptions->contextid = $datacontext->id;
2615 $rm->delete_ratings($ratingdeloptions);
2619 if (empty($data->reset_gradebook_grades)) {
2620 // remove all grades from gradebook
2621 data_reset_gradebook($data->courseid);
2624 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2627 // remove all comments
2628 if (!empty($data->reset_data_comments)) {
2629 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2630 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2633 // updating dates - shift may be negative too
2634 if ($data->timeshift) {
2635 shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto'), $data->timeshift, $data->courseid);
2636 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2639 return $status;
2643 * Returns all other caps used in module
2645 * @return array
2647 function data_get_extra_capabilities() {
2648 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');
2652 * @param string $feature FEATURE_xx constant for requested feature
2653 * @return mixed True if module supports feature, null if doesn't know
2655 function data_supports($feature) {
2656 switch($feature) {
2657 case FEATURE_GROUPS: return true;
2658 case FEATURE_GROUPINGS: return true;
2659 case FEATURE_GROUPMEMBERSONLY: return true;
2660 case FEATURE_MOD_INTRO: return true;
2661 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
2662 case FEATURE_GRADE_HAS_GRADE: return true;
2663 case FEATURE_GRADE_OUTCOMES: return true;
2664 case FEATURE_RATE: return true;
2665 case FEATURE_BACKUP_MOODLE2: return true;
2666 case FEATURE_SHOW_DESCRIPTION: return true;
2668 default: return null;
2672 * @global object
2673 * @param array $export
2674 * @param string $delimiter_name
2675 * @param object $database
2676 * @param int $count
2677 * @param bool $return
2678 * @return string|void
2680 function data_export_csv($export, $delimiter_name, $database, $count, $return=false) {
2681 global $CFG;
2682 require_once($CFG->libdir . '/csvlib.class.php');
2684 $filename = $database . '-' . $count . '-record';
2685 if ($count > 1) {
2686 $filename .= 's';
2688 if ($return) {
2689 return csv_export_writer::print_array($export, $delimiter_name, '"', true);
2690 } else {
2691 csv_export_writer::download_array($filename, $export, $delimiter_name);
2696 * @global object
2697 * @param array $export
2698 * @param string $dataname
2699 * @param int $count
2700 * @return string
2702 function data_export_xls($export, $dataname, $count) {
2703 global $CFG;
2704 require_once("$CFG->libdir/excellib.class.php");
2705 $filename = clean_filename("{$dataname}-{$count}_record");
2706 if ($count > 1) {
2707 $filename .= 's';
2709 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2710 $filename .= '.xls';
2712 $filearg = '-';
2713 $workbook = new MoodleExcelWorkbook($filearg);
2714 $workbook->send($filename);
2715 $worksheet = array();
2716 $worksheet[0] = $workbook->add_worksheet('');
2717 $rowno = 0;
2718 foreach ($export as $row) {
2719 $colno = 0;
2720 foreach($row as $col) {
2721 $worksheet[0]->write($rowno, $colno, $col);
2722 $colno++;
2724 $rowno++;
2726 $workbook->close();
2727 return $filename;
2731 * @global object
2732 * @param array $export
2733 * @param string $dataname
2734 * @param int $count
2735 * @param string
2737 function data_export_ods($export, $dataname, $count) {
2738 global $CFG;
2739 require_once("$CFG->libdir/odslib.class.php");
2740 $filename = clean_filename("{$dataname}-{$count}_record");
2741 if ($count > 1) {
2742 $filename .= 's';
2744 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2745 $filename .= '.ods';
2746 $filearg = '-';
2747 $workbook = new MoodleODSWorkbook($filearg);
2748 $workbook->send($filename);
2749 $worksheet = array();
2750 $worksheet[0] = $workbook->add_worksheet('');
2751 $rowno = 0;
2752 foreach ($export as $row) {
2753 $colno = 0;
2754 foreach($row as $col) {
2755 $worksheet[0]->write($rowno, $colno, $col);
2756 $colno++;
2758 $rowno++;
2760 $workbook->close();
2761 return $filename;
2765 * @global object
2766 * @param int $dataid
2767 * @param array $fields
2768 * @param array $selectedfields
2769 * @param int $currentgroup group ID of the current group. This is used for
2770 * exporting data while maintaining group divisions.
2771 * @param object $context the context in which the operation is performed (for capability checks)
2772 * @param bool $userdetails whether to include the details of the record author
2773 * @param bool $time whether to include time created/modified
2774 * @param bool $approval whether to include approval status
2775 * @return array
2777 function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0, $context=null,
2778 $userdetails=false, $time=false, $approval=false) {
2779 global $DB;
2781 if (is_null($context)) {
2782 $context = context_system::instance();
2784 // exporting user data needs special permission
2785 $userdetails = $userdetails && has_capability('mod/data:exportuserinfo', $context);
2787 $exportdata = array();
2789 // populate the header in first row of export
2790 foreach($fields as $key => $field) {
2791 if (!in_array($field->field->id, $selectedfields)) {
2792 // ignore values we aren't exporting
2793 unset($fields[$key]);
2794 } else {
2795 $exportdata[0][] = $field->field->name;
2798 if ($userdetails) {
2799 $exportdata[0][] = get_string('user');
2800 $exportdata[0][] = get_string('username');
2801 $exportdata[0][] = get_string('email');
2803 if ($time) {
2804 $exportdata[0][] = get_string('timeadded', 'data');
2805 $exportdata[0][] = get_string('timemodified', 'data');
2807 if ($approval) {
2808 $exportdata[0][] = get_string('approved', 'data');
2811 $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
2812 ksort($datarecords);
2813 $line = 1;
2814 foreach($datarecords as $record) {
2815 // get content indexed by fieldid
2816 if ($currentgroup) {
2817 $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 = ?';
2818 $where = array($record->id, $currentgroup);
2819 } else {
2820 $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
2821 $where = array($record->id);
2824 if( $content = $DB->get_records_sql($select, $where) ) {
2825 foreach($fields as $field) {
2826 $contents = '';
2827 if(isset($content[$field->field->id])) {
2828 $contents = $field->export_text_value($content[$field->field->id]);
2830 $exportdata[$line][] = $contents;
2832 if ($userdetails) { // Add user details to the export data
2833 $userdata = get_complete_user_data('id', $record->userid);
2834 $exportdata[$line][] = fullname($userdata);
2835 $exportdata[$line][] = $userdata->username;
2836 $exportdata[$line][] = $userdata->email;
2838 if ($time) { // Add time added / modified
2839 $exportdata[$line][] = userdate($record->timecreated);
2840 $exportdata[$line][] = userdate($record->timemodified);
2842 if ($approval) { // Add approval status
2843 $exportdata[$line][] = (int) $record->approved;
2846 $line++;
2848 $line--;
2849 return $exportdata;
2852 ////////////////////////////////////////////////////////////////////////////////
2853 // File API //
2854 ////////////////////////////////////////////////////////////////////////////////
2857 * Lists all browsable file areas
2859 * @package mod_data
2860 * @category files
2861 * @param stdClass $course course object
2862 * @param stdClass $cm course module object
2863 * @param stdClass $context context object
2864 * @return array
2866 function data_get_file_areas($course, $cm, $context) {
2867 return array('content' => get_string('areacontent', 'mod_data'));
2871 * File browsing support for data module.
2873 * @param file_browser $browser
2874 * @param array $areas
2875 * @param stdClass $course
2876 * @param cm_info $cm
2877 * @param context $context
2878 * @param string $filearea
2879 * @param int $itemid
2880 * @param string $filepath
2881 * @param string $filename
2882 * @return file_info_stored file_info_stored instance or null if not found
2884 function data_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2885 global $CFG, $DB, $USER;
2887 if ($context->contextlevel != CONTEXT_MODULE) {
2888 return null;
2891 if (!isset($areas[$filearea])) {
2892 return null;
2895 if (is_null($itemid)) {
2896 require_once($CFG->dirroot.'/mod/data/locallib.php');
2897 return new data_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
2900 if (!$content = $DB->get_record('data_content', array('id'=>$itemid))) {
2901 return null;
2904 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
2905 return null;
2908 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
2909 return null;
2912 if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
2913 return null;
2916 //check if approved
2917 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
2918 return null;
2921 // group access
2922 if ($record->groupid) {
2923 $groupmode = groups_get_activity_groupmode($cm, $course);
2924 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
2925 if (!groups_is_member($record->groupid)) {
2926 return null;
2931 $fieldobj = data_get_field($field, $data, $cm);
2933 $filepath = is_null($filepath) ? '/' : $filepath;
2934 $filename = is_null($filename) ? '.' : $filename;
2935 if (!$fieldobj->file_ok($filepath.$filename)) {
2936 return null;
2939 $fs = get_file_storage();
2940 if (!($storedfile = $fs->get_file($context->id, 'mod_data', $filearea, $itemid, $filepath, $filename))) {
2941 return null;
2944 // Checks to see if the user can manage files or is the owner.
2945 // TODO MDL-33805 - Do not use userid here and move the capability check above.
2946 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
2947 return null;
2950 $urlbase = $CFG->wwwroot.'/pluginfile.php';
2952 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
2956 * Serves the data attachments. Implements needed access control ;-)
2958 * @package mod_data
2959 * @category files
2960 * @param stdClass $course course object
2961 * @param stdClass $cm course module object
2962 * @param stdClass $context context object
2963 * @param string $filearea file area
2964 * @param array $args extra arguments
2965 * @param bool $forcedownload whether or not force download
2966 * @param array $options additional options affecting the file serving
2967 * @return bool false if file not found, does not return if found - justsend the file
2969 function data_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
2970 global $CFG, $DB;
2972 if ($context->contextlevel != CONTEXT_MODULE) {
2973 return false;
2976 require_course_login($course, true, $cm);
2978 if ($filearea === 'content') {
2979 $contentid = (int)array_shift($args);
2981 if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
2982 return false;
2985 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
2986 return false;
2989 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
2990 return false;
2993 if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
2994 return false;
2997 if ($data->id != $cm->instance) {
2998 // hacker attempt - context does not match the contentid
2999 return false;
3002 //check if approved
3003 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3004 return false;
3007 // group access
3008 if ($record->groupid) {
3009 $groupmode = groups_get_activity_groupmode($cm, $course);
3010 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3011 if (!groups_is_member($record->groupid)) {
3012 return false;
3017 $fieldobj = data_get_field($field, $data, $cm);
3019 $relativepath = implode('/', $args);
3020 $fullpath = "/$context->id/mod_data/content/$content->id/$relativepath";
3022 if (!$fieldobj->file_ok($relativepath)) {
3023 return false;
3026 $fs = get_file_storage();
3027 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3028 return false;
3031 // finally send the file
3032 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
3035 return false;
3039 function data_extend_navigation($navigation, $course, $module, $cm) {
3040 global $CFG, $OUTPUT, $USER, $DB;
3042 $rid = optional_param('rid', 0, PARAM_INT);
3044 $data = $DB->get_record('data', array('id'=>$cm->instance));
3045 $currentgroup = groups_get_activity_group($cm);
3046 $groupmode = groups_get_activity_groupmode($cm);
3048 $numentries = data_numentries($data);
3049 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
3050 if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !has_capability('mod/data:manageentries', context_module::instance($cm->id))) {
3051 $data->entriesleft = $data->requiredentries - $numentries;
3052 $entriesnode = $navigation->add(get_string('entrieslefttoadd', 'data', $data));
3053 $entriesnode->add_class('note');
3056 $navigation->add(get_string('list', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance)));
3057 if (!empty($rid)) {
3058 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'rid'=>$rid)));
3059 } else {
3060 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'single')));
3062 $navigation->add(get_string('search', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'asearch')));
3066 * Adds module specific settings to the settings block
3068 * @param settings_navigation $settings The settings navigation object
3069 * @param navigation_node $datanode The node to add module settings to
3071 function data_extend_settings_navigation(settings_navigation $settings, navigation_node $datanode) {
3072 global $PAGE, $DB, $CFG, $USER;
3074 $data = $DB->get_record('data', array("id" => $PAGE->cm->instance));
3076 $currentgroup = groups_get_activity_group($PAGE->cm);
3077 $groupmode = groups_get_activity_groupmode($PAGE->cm);
3079 if (data_user_can_add_entry($data, $currentgroup, $groupmode, $PAGE->cm->context)) { // took out participation list here!
3080 if (empty($editentry)) { //TODO: undefined
3081 $addstring = get_string('add', 'data');
3082 } else {
3083 $addstring = get_string('editentry', 'data');
3085 $datanode->add($addstring, new moodle_url('/mod/data/edit.php', array('d'=>$PAGE->cm->instance)));
3088 if (has_capability(DATA_CAP_EXPORT, $PAGE->cm->context)) {
3089 // The capability required to Export database records is centrally defined in 'lib.php'
3090 // and should be weaker than those required to edit Templates, Fields and Presets.
3091 $datanode->add(get_string('exportentries', 'data'), new moodle_url('/mod/data/export.php', array('d'=>$data->id)));
3093 if (has_capability('mod/data:manageentries', $PAGE->cm->context)) {
3094 $datanode->add(get_string('importentries', 'data'), new moodle_url('/mod/data/import.php', array('d'=>$data->id)));
3097 if (has_capability('mod/data:managetemplates', $PAGE->cm->context)) {
3098 $currenttab = '';
3099 if ($currenttab == 'list') {
3100 $defaultemplate = 'listtemplate';
3101 } else if ($currenttab == 'add') {
3102 $defaultemplate = 'addtemplate';
3103 } else if ($currenttab == 'asearch') {
3104 $defaultemplate = 'asearchtemplate';
3105 } else {
3106 $defaultemplate = 'singletemplate';
3109 $templates = $datanode->add(get_string('templates', 'data'));
3111 $templatelist = array ('listtemplate', 'singletemplate', 'asearchtemplate', 'addtemplate', 'rsstemplate', 'csstemplate', 'jstemplate');
3112 foreach ($templatelist as $template) {
3113 $templates->add(get_string($template, 'data'), new moodle_url('/mod/data/templates.php', array('d'=>$data->id,'mode'=>$template)));
3116 $datanode->add(get_string('fields', 'data'), new moodle_url('/mod/data/field.php', array('d'=>$data->id)));
3117 $datanode->add(get_string('presets', 'data'), new moodle_url('/mod/data/preset.php', array('d'=>$data->id)));
3120 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
3121 require_once("$CFG->libdir/rsslib.php");
3123 $string = get_string('rsstype','forum');
3125 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_data', $data->id));
3126 $datanode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
3131 * Save the database configuration as a preset.
3133 * @param stdClass $course The course the database module belongs to.
3134 * @param stdClass $cm The course module record
3135 * @param stdClass $data The database record
3136 * @param string $path
3137 * @return bool
3139 function data_presets_save($course, $cm, $data, $path) {
3140 global $USER;
3141 $fs = get_file_storage();
3142 $filerecord = new stdClass;
3143 $filerecord->contextid = DATA_PRESET_CONTEXT;
3144 $filerecord->component = DATA_PRESET_COMPONENT;
3145 $filerecord->filearea = DATA_PRESET_FILEAREA;
3146 $filerecord->itemid = 0;
3147 $filerecord->filepath = '/'.$path.'/';
3148 $filerecord->userid = $USER->id;
3150 $filerecord->filename = 'preset.xml';
3151 $fs->create_file_from_string($filerecord, data_presets_generate_xml($course, $cm, $data));
3153 $filerecord->filename = 'singletemplate.html';
3154 $fs->create_file_from_string($filerecord, $data->singletemplate);
3156 $filerecord->filename = 'listtemplateheader.html';
3157 $fs->create_file_from_string($filerecord, $data->listtemplateheader);
3159 $filerecord->filename = 'listtemplate.html';
3160 $fs->create_file_from_string($filerecord, $data->listtemplate);
3162 $filerecord->filename = 'listtemplatefooter.html';
3163 $fs->create_file_from_string($filerecord, $data->listtemplatefooter);
3165 $filerecord->filename = 'addtemplate.html';
3166 $fs->create_file_from_string($filerecord, $data->addtemplate);
3168 $filerecord->filename = 'rsstemplate.html';
3169 $fs->create_file_from_string($filerecord, $data->rsstemplate);
3171 $filerecord->filename = 'rsstitletemplate.html';
3172 $fs->create_file_from_string($filerecord, $data->rsstitletemplate);
3174 $filerecord->filename = 'csstemplate.css';
3175 $fs->create_file_from_string($filerecord, $data->csstemplate);
3177 $filerecord->filename = 'jstemplate.js';
3178 $fs->create_file_from_string($filerecord, $data->jstemplate);
3180 $filerecord->filename = 'asearchtemplate.html';
3181 $fs->create_file_from_string($filerecord, $data->asearchtemplate);
3183 return true;
3187 * Generates the XML for the database module provided
3189 * @global moodle_database $DB
3190 * @param stdClass $course The course the database module belongs to.
3191 * @param stdClass $cm The course module record
3192 * @param stdClass $data The database record
3193 * @return string The XML for the preset
3195 function data_presets_generate_xml($course, $cm, $data) {
3196 global $DB;
3198 // Assemble "preset.xml":
3199 $presetxmldata = "<preset>\n\n";
3201 // Raw settings are not preprocessed during saving of presets
3202 $raw_settings = array(
3203 'intro',
3204 'comments',
3205 'requiredentries',
3206 'requiredentriestoview',
3207 'maxentries',
3208 'rssarticles',
3209 'approval',
3210 'defaultsortdir'
3213 $presetxmldata .= "<settings>\n";
3214 // First, settings that do not require any conversion
3215 foreach ($raw_settings as $setting) {
3216 $presetxmldata .= "<$setting>" . htmlspecialchars($data->$setting) . "</$setting>\n";
3219 // Now specific settings
3220 if ($data->defaultsort > 0 && $sortfield = data_get_field_from_id($data->defaultsort, $data)) {
3221 $presetxmldata .= '<defaultsort>' . htmlspecialchars($sortfield->field->name) . "</defaultsort>\n";
3222 } else {
3223 $presetxmldata .= "<defaultsort>0</defaultsort>\n";
3225 $presetxmldata .= "</settings>\n\n";
3226 // Now for the fields. Grab all that are non-empty
3227 $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
3228 ksort($fields);
3229 if (!empty($fields)) {
3230 foreach ($fields as $field) {
3231 $presetxmldata .= "<field>\n";
3232 foreach ($field as $key => $value) {
3233 if ($value != '' && $key != 'id' && $key != 'dataid') {
3234 $presetxmldata .= "<$key>" . htmlspecialchars($value) . "</$key>\n";
3237 $presetxmldata .= "</field>\n\n";
3240 $presetxmldata .= '</preset>';
3241 return $presetxmldata;
3244 function data_presets_export($course, $cm, $data, $tostorage=false) {
3245 global $CFG, $DB;
3247 $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi");
3248 $exportsubdir = "mod_data/presetexport/$presetname";
3249 make_temp_directory($exportsubdir);
3250 $exportdir = "$CFG->tempdir/$exportsubdir";
3252 // Assemble "preset.xml":
3253 $presetxmldata = data_presets_generate_xml($course, $cm, $data);
3255 // After opening a file in write mode, close it asap
3256 $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
3257 fwrite($presetxmlfile, $presetxmldata);
3258 fclose($presetxmlfile);
3260 // Now write the template files
3261 $singletemplate = fopen($exportdir . '/singletemplate.html', 'w');
3262 fwrite($singletemplate, $data->singletemplate);
3263 fclose($singletemplate);
3265 $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w');
3266 fwrite($listtemplateheader, $data->listtemplateheader);
3267 fclose($listtemplateheader);
3269 $listtemplate = fopen($exportdir . '/listtemplate.html', 'w');
3270 fwrite($listtemplate, $data->listtemplate);
3271 fclose($listtemplate);
3273 $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w');
3274 fwrite($listtemplatefooter, $data->listtemplatefooter);
3275 fclose($listtemplatefooter);
3277 $addtemplate = fopen($exportdir . '/addtemplate.html', 'w');
3278 fwrite($addtemplate, $data->addtemplate);
3279 fclose($addtemplate);
3281 $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w');
3282 fwrite($rsstemplate, $data->rsstemplate);
3283 fclose($rsstemplate);
3285 $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w');
3286 fwrite($rsstitletemplate, $data->rsstitletemplate);
3287 fclose($rsstitletemplate);
3289 $csstemplate = fopen($exportdir . '/csstemplate.css', 'w');
3290 fwrite($csstemplate, $data->csstemplate);
3291 fclose($csstemplate);
3293 $jstemplate = fopen($exportdir . '/jstemplate.js', 'w');
3294 fwrite($jstemplate, $data->jstemplate);
3295 fclose($jstemplate);
3297 $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w');
3298 fwrite($asearchtemplate, $data->asearchtemplate);
3299 fclose($asearchtemplate);
3301 // Check if all files have been generated
3302 if (! is_directory_a_preset($exportdir)) {
3303 print_error('generateerror', 'data');
3306 $filenames = array(
3307 'preset.xml',
3308 'singletemplate.html',
3309 'listtemplateheader.html',
3310 'listtemplate.html',
3311 'listtemplatefooter.html',
3312 'addtemplate.html',
3313 'rsstemplate.html',
3314 'rsstitletemplate.html',
3315 'csstemplate.css',
3316 'jstemplate.js',
3317 'asearchtemplate.html'
3320 $filelist = array();
3321 foreach ($filenames as $filename) {
3322 $filelist[$filename] = $exportdir . '/' . $filename;
3325 $exportfile = $exportdir.'.zip';
3326 file_exists($exportfile) && unlink($exportfile);
3328 $fp = get_file_packer('application/zip');
3329 $fp->archive_to_pathname($filelist, $exportfile);
3331 foreach ($filelist as $file) {
3332 unlink($file);
3334 rmdir($exportdir);
3336 // Return the full path to the exported preset file:
3337 return $exportfile;
3341 * Running addtional permission check on plugin, for example, plugins
3342 * may have switch to turn on/off comments option, this callback will
3343 * affect UI display, not like pluginname_comment_validate only throw
3344 * exceptions.
3345 * Capability check has been done in comment->check_permissions(), we
3346 * don't need to do it again here.
3348 * @package mod_data
3349 * @category comment
3351 * @param stdClass $comment_param {
3352 * context => context the context object
3353 * courseid => int course id
3354 * cm => stdClass course module object
3355 * commentarea => string comment area
3356 * itemid => int itemid
3358 * @return array
3360 function data_comment_permissions($comment_param) {
3361 global $CFG, $DB;
3362 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3363 throw new comment_exception('invalidcommentitemid');
3365 if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3366 throw new comment_exception('invalidid', 'data');
3368 if ($data->comments) {
3369 return array('post'=>true, 'view'=>true);
3370 } else {
3371 return array('post'=>false, 'view'=>false);
3376 * Validate comment parameter before perform other comments actions
3378 * @package mod_data
3379 * @category comment
3381 * @param stdClass $comment_param {
3382 * context => context the context object
3383 * courseid => int course id
3384 * cm => stdClass course module object
3385 * commentarea => string comment area
3386 * itemid => int itemid
3388 * @return boolean
3390 function data_comment_validate($comment_param) {
3391 global $DB;
3392 // validate comment area
3393 if ($comment_param->commentarea != 'database_entry') {
3394 throw new comment_exception('invalidcommentarea');
3396 // validate itemid
3397 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3398 throw new comment_exception('invalidcommentitemid');
3400 if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3401 throw new comment_exception('invalidid', 'data');
3403 if (!$course = $DB->get_record('course', array('id'=>$data->course))) {
3404 throw new comment_exception('coursemisconf');
3406 if (!$cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
3407 throw new comment_exception('invalidcoursemodule');
3409 if (!$data->comments) {
3410 throw new comment_exception('commentsoff', 'data');
3412 $context = context_module::instance($cm->id);
3414 //check if approved
3415 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3416 throw new comment_exception('notapproved', 'data');
3419 // group access
3420 if ($record->groupid) {
3421 $groupmode = groups_get_activity_groupmode($cm, $course);
3422 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3423 if (!groups_is_member($record->groupid)) {
3424 throw new comment_exception('notmemberofgroup');
3428 // validate context id
3429 if ($context->id != $comment_param->context->id) {
3430 throw new comment_exception('invalidcontext');
3432 // validation for comment deletion
3433 if (!empty($comment_param->commentid)) {
3434 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
3435 if ($comment->commentarea != 'database_entry') {
3436 throw new comment_exception('invalidcommentarea');
3438 if ($comment->contextid != $comment_param->context->id) {
3439 throw new comment_exception('invalidcontext');
3441 if ($comment->itemid != $comment_param->itemid) {
3442 throw new comment_exception('invalidcommentitemid');
3444 } else {
3445 throw new comment_exception('invalidcommentid');
3448 return true;
3452 * Return a list of page types
3453 * @param string $pagetype current page type
3454 * @param stdClass $parentcontext Block's parent context
3455 * @param stdClass $currentcontext Current context of block
3457 function data_page_type_list($pagetype, $parentcontext, $currentcontext) {
3458 $module_pagetype = array('mod-data-*'=>get_string('page-mod-data-x', 'data'));
3459 return $module_pagetype;
3463 * Get all of the record ids from a database activity.
3465 * @param int $dataid The dataid of the database module.
3466 * @param object $selectdata Contains an additional sql statement for the
3467 * where clause for group and approval fields.
3468 * @param array $params Parameters that coincide with the sql statement.
3469 * @return array $idarray An array of record ids
3471 function data_get_all_recordids($dataid, $selectdata = '', $params = null) {
3472 global $DB;
3473 $initsql = 'SELECT r.id
3474 FROM {data_records} r
3475 WHERE r.dataid = :dataid';
3476 if ($selectdata != '') {
3477 $initsql .= $selectdata;
3478 $params = array_merge(array('dataid' => $dataid), $params);
3479 } else {
3480 $params = array('dataid' => $dataid);
3482 $initsql .= ' GROUP BY r.id';
3483 $initrecord = $DB->get_recordset_sql($initsql, $params);
3484 $idarray = array();
3485 foreach ($initrecord as $data) {
3486 $idarray[] = $data->id;
3488 // Close the record set and free up resources.
3489 $initrecord->close();
3490 return $idarray;
3494 * Get the ids of all the records that match that advanced search criteria
3495 * This goes and loops through each criterion one at a time until it either
3496 * runs out of records or returns a subset of records.
3498 * @param array $recordids An array of record ids.
3499 * @param array $searcharray Contains information for the advanced search criteria
3500 * @param int $dataid The data id of the database.
3501 * @return array $recordids An array of record ids.
3503 function data_get_advance_search_ids($recordids, $searcharray, $dataid) {
3504 $searchcriteria = array_keys($searcharray);
3505 // Loop through and reduce the IDs one search criteria at a time.
3506 foreach ($searchcriteria as $key) {
3507 $recordids = data_get_recordids($key, $searcharray, $dataid, $recordids);
3508 // If we don't have anymore IDs then stop.
3509 if (!$recordids) {
3510 break;
3513 return $recordids;
3517 * Gets the record IDs given the search criteria
3519 * @param string $alias Record alias.
3520 * @param array $searcharray Criteria for the search.
3521 * @param int $dataid Data ID for the database
3522 * @param array $recordids An array of record IDs.
3523 * @return array $nestarray An arry of record IDs
3525 function data_get_recordids($alias, $searcharray, $dataid, $recordids) {
3526 global $DB;
3528 $nestsearch = $searcharray[$alias];
3529 // searching for content outside of mdl_data_content
3530 if ($alias < 0) {
3531 $alias = '';
3533 list($insql, $params) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3534 $nestselect = 'SELECT c' . $alias . '.recordid
3535 FROM {data_content} c' . $alias . ',
3536 {data_fields} f,
3537 {data_records} r,
3538 {user} u ';
3539 $nestwhere = 'WHERE u.id = r.userid
3540 AND f.id = c' . $alias . '.fieldid
3541 AND r.id = c' . $alias . '.recordid
3542 AND r.dataid = :dataid
3543 AND c' . $alias .'.recordid ' . $insql . '
3544 AND ';
3546 $params['dataid'] = $dataid;
3547 if (count($nestsearch->params) != 0) {
3548 $params = array_merge($params, $nestsearch->params);
3549 $nestsql = $nestselect . $nestwhere . $nestsearch->sql;
3550 } else {
3551 $thing = $DB->sql_like($nestsearch->field, ':search1', false);
3552 $nestsql = $nestselect . $nestwhere . $thing . ' GROUP BY c' . $alias . '.recordid';
3553 $params['search1'] = "%$nestsearch->data%";
3555 $nestrecords = $DB->get_recordset_sql($nestsql, $params);
3556 $nestarray = array();
3557 foreach ($nestrecords as $data) {
3558 $nestarray[] = $data->recordid;
3560 // Close the record set and free up resources.
3561 $nestrecords->close();
3562 return $nestarray;
3566 * Returns an array with an sql string for advanced searches and the parameters that go with them.
3568 * @param int $sort DATA_*
3569 * @param stdClass $data Data module object
3570 * @param array $recordids An array of record IDs.
3571 * @param string $selectdata Information for the where and select part of the sql statement.
3572 * @param string $sortorder Additional sort parameters
3573 * @return array sqlselect sqlselect['sql'] has the sql string, sqlselect['params'] contains an array of parameters.
3575 function data_get_advanced_search_sql($sort, $data, $recordids, $selectdata, $sortorder) {
3576 global $DB;
3578 $namefields = get_all_user_name_fields(true, 'u');
3579 if ($sort == 0) {
3580 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . '
3581 FROM {data_content} c,
3582 {data_records} r,
3583 {user} u ';
3584 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' . $namefields;
3585 } else {
3586 // Sorting through 'Other' criteria
3587 if ($sort <= 0) {
3588 switch ($sort) {
3589 case DATA_LASTNAME:
3590 $sortcontentfull = "u.lastname";
3591 break;
3592 case DATA_FIRSTNAME:
3593 $sortcontentfull = "u.firstname";
3594 break;
3595 case DATA_APPROVED:
3596 $sortcontentfull = "r.approved";
3597 break;
3598 case DATA_TIMEMODIFIED:
3599 $sortcontentfull = "r.timemodified";
3600 break;
3601 case DATA_TIMEADDED:
3602 default:
3603 $sortcontentfull = "r.timecreated";
3605 } else {
3606 $sortfield = data_get_field_from_id($sort, $data);
3607 $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
3608 $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
3611 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ',
3612 ' . $sortcontentfull . '
3613 AS sortorder
3614 FROM {data_content} c,
3615 {data_records} r,
3616 {user} u ';
3617 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ', ' .$sortcontentfull;
3620 // Default to a standard Where statement if $selectdata is empty.
3621 if ($selectdata == '') {
3622 $selectdata = 'WHERE c.recordid = r.id
3623 AND r.dataid = :dataid
3624 AND r.userid = u.id ';
3627 // Find the field we are sorting on
3628 if ($sort > 0 or data_get_field_from_id($sort, $data)) {
3629 $selectdata .= ' AND c.fieldid = :sort';
3632 // If there are no record IDs then return an sql statment that will return no rows.
3633 if (count($recordids) != 0) {
3634 list($insql, $inparam) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3635 } else {
3636 list($insql, $inparam) = $DB->get_in_or_equal(array('-1'), SQL_PARAMS_NAMED);
3638 $nestfromsql = $selectdata . ' AND c.recordid ' . $insql . $groupsql;
3639 $sqlselect['sql'] = "$nestselectsql $nestfromsql $sortorder";
3640 $sqlselect['params'] = $inparam;
3641 return $sqlselect;
3645 * Checks to see if the user has permission to delete the preset.
3646 * @param stdClass $context Context object.
3647 * @param stdClass $preset The preset object that we are checking for deletion.
3648 * @return bool Returns true if the user can delete, otherwise false.
3650 function data_user_can_delete_preset($context, $preset) {
3651 global $USER;
3653 if (has_capability('mod/data:manageuserpresets', $context)) {
3654 return true;
3655 } else {
3656 $candelete = false;
3657 if ($preset->userid == $USER->id) {
3658 $candelete = true;
3660 return $candelete;
3665 * Delete a record entry.
3667 * @param int $recordid The ID for the record to be deleted.
3668 * @param object $data The data object for this activity.
3669 * @param int $courseid ID for the current course (for logging).
3670 * @param int $cmid The course module ID.
3671 * @return bool True if the record deleted, false if not.
3673 function data_delete_record($recordid, $data, $courseid, $cmid) {
3674 global $DB;
3676 if ($deleterecord = $DB->get_record('data_records', array('id' => $recordid))) {
3677 if ($deleterecord->dataid == $data->id) {
3678 if ($contents = $DB->get_records('data_content', array('recordid' => $deleterecord->id))) {
3679 foreach ($contents as $content) {
3680 if ($field = data_get_field_from_id($content->fieldid, $data)) {
3681 $field->delete_content($content->recordid);
3684 $DB->delete_records('data_content', array('recordid'=>$deleterecord->id));
3685 $DB->delete_records('data_records', array('id'=>$deleterecord->id));
3687 add_to_log($courseid, 'data', 'record delete', "view.php?id=$cmid", $data->id, $cmid);
3688 return true;
3692 return false;