0fe4a2309b344484e7d78f4075c5d8e4cae04729
[moodle.git] / mod / data / lib.php
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.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * @package   mod_data
20  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
21  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22  */
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
48  */
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
68      *
69      * @global object
70      * @uses CONTEXT_MODULE
71      * @param int $field
72      * @param int $data
73      * @param int $cm
74      */
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');
80         }
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');
87             }
88             if (empty($data)) {
89                 if (!$this->data = $DB->get_record('data', array('id'=>$this->field->dataid))) {
90                     print_error('invalidid', 'data');
91                 }
92             }
93         }
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');
101                 }
102             } else {                      // No way to define it!
103                 print_error('missingdata', 'data');
104             }
105         }
107         if ($cm) {
108             $this->cm = $cm;
109         } else {
110             $this->cm = get_coursemodule_from_instance('data', $this->data->id);
111         }
113         if (empty($this->field)) {         // We need to define some default values
114             $this->define_default_field();
115         }
117         $this->context = context_module::instance($this->cm->id);
118     }
121     /**
122      * This field just sets up a default field object
123      *
124      * @return bool
125      */
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');
130         }
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 = '';
140         $this->field->required = false;
142         return true;
143     }
145     /**
146      * Set up the field object according to data in an object.  Now is the time to clean it!
147      *
148      * @return bool
149      */
150     function define_field($data) {
151         $this->field->type        = $this->type;
152         $this->field->dataid      = $this->data->id;
154         $this->field->name        = trim($data->name);
155         $this->field->description = trim($data->description);
156         $this->field->required    = !empty($data->required) ? 1 : 0;
158         if (isset($data->param1)) {
159             $this->field->param1 = trim($data->param1);
160         }
161         if (isset($data->param2)) {
162             $this->field->param2 = trim($data->param2);
163         }
164         if (isset($data->param3)) {
165             $this->field->param3 = trim($data->param3);
166         }
167         if (isset($data->param4)) {
168             $this->field->param4 = trim($data->param4);
169         }
170         if (isset($data->param5)) {
171             $this->field->param5 = trim($data->param5);
172         }
174         return true;
175     }
177     /**
178      * Insert a new field in the database
179      * We assume the field object is already defined as $this->field
180      *
181      * @global object
182      * @return bool
183      */
184     function insert_field() {
185         global $DB, $OUTPUT;
187         if (empty($this->field)) {
188             echo $OUTPUT->notification('Programmer error: Field has not been defined yet!  See define_field()');
189             return false;
190         }
192         $this->field->id = $DB->insert_record('data_fields',$this->field);
194         // Trigger an event for creating this field.
195         $event = \mod_data\event\field_created::create(array(
196             'objectid' => $this->field->id,
197             'context' => $this->context,
198             'other' => array(
199                 'fieldname' => $this->field->name,
200                 'dataid' => $this->data->id
201             )
202         ));
203         $event->trigger();
205         return true;
206     }
209     /**
210      * Update a field in the database
211      *
212      * @global object
213      * @return bool
214      */
215     function update_field() {
216         global $DB;
218         $DB->update_record('data_fields', $this->field);
220         // Trigger an event for updating this field.
221         $event = \mod_data\event\field_updated::create(array(
222             'objectid' => $this->field->id,
223             'context' => $this->context,
224             'other' => array(
225                 'fieldname' => $this->field->name,
226                 'dataid' => $this->data->id
227             )
228         ));
229         $event->trigger();
231         return true;
232     }
234     /**
235      * Delete a field completely
236      *
237      * @global object
238      * @return bool
239      */
240     function delete_field() {
241         global $DB;
243         if (!empty($this->field->id)) {
244             // Get the field before we delete it.
245             $field = $DB->get_record('data_fields', array('id' => $this->field->id));
247             $this->delete_content();
248             $DB->delete_records('data_fields', array('id'=>$this->field->id));
250             // Trigger an event for deleting this field.
251             $event = \mod_data\event\field_deleted::create(array(
252                 'objectid' => $this->field->id,
253                 'context' => $this->context,
254                 'other' => array(
255                     'fieldname' => $this->field->name,
256                     'dataid' => $this->data->id
257                  )
258             ));
259             $event->add_record_snapshot('data_fields', $field);
260             $event->trigger();
261         }
263         return true;
264     }
266     /**
267      * Print the relevant form element in the ADD template for this field
268      *
269      * @global object
270      * @param int $recordid
271      * @return string
272      */
273     function display_add_field($recordid=0, $formdata=null) {
274         global $DB, $OUTPUT;
276         if ($formdata) {
277             $fieldname = 'field_' . $this->field->id;
278             $content = $formdata->$fieldname;
279         } else if ($recordid) {
280             $content = $DB->get_field('data_content', 'content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid));
281         } else {
282             $content = '';
283         }
285         // beware get_field returns false for new, empty records MDL-18567
286         if ($content===false) {
287             $content='';
288         }
290         $str = '<div title="' . s($this->field->description) . '">';
291         $str .= '<label for="field_'.$this->field->id.'"><span class="accesshide">'.$this->field->name.'</span>';
292         if ($this->field->required) {
293             $image = html_writer::img($OUTPUT->pix_url('req'), get_string('requiredelement', 'form'),
294                                      array('class' => 'req', 'title' => get_string('requiredelement', 'form')));
295             $str .= html_writer::div($image, 'inline-req');
296         }
297         $str .= '</label><input class="basefieldinput mod-data-input" type="text" name="field_'.$this->field->id.'"';
298         $str .= ' id="field_' . $this->field->id . '" value="'.s($content).'" />';
299         $str .= '</div>';
301         return $str;
302     }
304     /**
305      * Print the relevant form element to define the attributes for this field
306      * viewable by teachers only.
307      *
308      * @global object
309      * @global object
310      * @return void Output is echo'd
311      */
312     function display_edit_field() {
313         global $CFG, $DB, $OUTPUT;
315         if (empty($this->field)) {   // No field has been defined yet, try and make one
316             $this->define_default_field();
317         }
318         echo $OUTPUT->box_start('generalbox boxaligncenter boxwidthwide');
320         echo '<form id="editfield" action="'.$CFG->wwwroot.'/mod/data/field.php" method="post">'."\n";
321         echo '<input type="hidden" name="d" value="'.$this->data->id.'" />'."\n";
322         if (empty($this->field->id)) {
323             echo '<input type="hidden" name="mode" value="add" />'."\n";
324             $savebutton = get_string('add');
325         } else {
326             echo '<input type="hidden" name="fid" value="'.$this->field->id.'" />'."\n";
327             echo '<input type="hidden" name="mode" value="update" />'."\n";
328             $savebutton = get_string('savechanges');
329         }
330         echo '<input type="hidden" name="type" value="'.$this->type.'" />'."\n";
331         echo '<input name="sesskey" value="'.sesskey().'" type="hidden" />'."\n";
333         echo $OUTPUT->heading($this->name(), 3);
335         require_once($CFG->dirroot.'/mod/data/field/'.$this->type.'/mod.html');
337         echo '<div class="mdl-align">';
338         echo '<input type="submit" value="'.$savebutton.'" />'."\n";
339         echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />'."\n";
340         echo '</div>';
342         echo '</form>';
344         echo $OUTPUT->box_end();
345     }
347     /**
348      * Display the content of the field in browse mode
349      *
350      * @global object
351      * @param int $recordid
352      * @param object $template
353      * @return bool|string
354      */
355     function display_browse_field($recordid, $template) {
356         global $DB;
358         if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
359             if (isset($content->content)) {
360                 $options = new stdClass();
361                 if ($this->field->param1 == '1') {  // We are autolinking this field, so disable linking within us
362                     //$content->content = '<span class="nolink">'.$content->content.'</span>';
363                     //$content->content1 = FORMAT_HTML;
364                     $options->filter=false;
365                 }
366                 $options->para = false;
367                 $str = format_text($content->content, $content->content1, $options);
368             } else {
369                 $str = '';
370             }
371             return $str;
372         }
373         return false;
374     }
376     /**
377      * Update the content of one data field in the data_content table
378      * @global object
379      * @param int $recordid
380      * @param mixed $value
381      * @param string $name
382      * @return bool
383      */
384     function update_content($recordid, $value, $name=''){
385         global $DB;
387         $content = new stdClass();
388         $content->fieldid = $this->field->id;
389         $content->recordid = $recordid;
390         $content->content = clean_param($value, PARAM_NOTAGS);
392         if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
393             $content->id = $oldcontent->id;
394             return $DB->update_record('data_content', $content);
395         } else {
396             return $DB->insert_record('data_content', $content);
397         }
398     }
400     /**
401      * Delete all content associated with the field
402      *
403      * @global object
404      * @param int $recordid
405      * @return bool
406      */
407     function delete_content($recordid=0) {
408         global $DB;
410         if ($recordid) {
411             $conditions = array('fieldid'=>$this->field->id, 'recordid'=>$recordid);
412         } else {
413             $conditions = array('fieldid'=>$this->field->id);
414         }
416         $rs = $DB->get_recordset('data_content', $conditions);
417         if ($rs->valid()) {
418             $fs = get_file_storage();
419             foreach ($rs as $content) {
420                 $fs->delete_area_files($this->context->id, 'mod_data', 'content', $content->id);
421             }
422         }
423         $rs->close();
425         return $DB->delete_records('data_content', $conditions);
426     }
428     /**
429      * Check if a field from an add form is empty
430      *
431      * @param mixed $value
432      * @param mixed $name
433      * @return bool
434      */
435     function notemptyfield($value, $name) {
436         return !empty($value);
437     }
439     /**
440      * Just in case a field needs to print something before the whole form
441      */
442     function print_before_form() {
443     }
445     /**
446      * Just in case a field needs to print something after the whole form
447      */
448     function print_after_form() {
449     }
452     /**
453      * Returns the sortable field for the content. By default, it's just content
454      * but for some plugins, it could be content 1 - content4
455      *
456      * @return string
457      */
458     function get_sort_field() {
459         return 'content';
460     }
462     /**
463      * Returns the SQL needed to refer to the column.  Some fields may need to CAST() etc.
464      *
465      * @param string $fieldname
466      * @return string $fieldname
467      */
468     function get_sort_sql($fieldname) {
469         return $fieldname;
470     }
472     /**
473      * Returns the name/type of the field
474      *
475      * @return string
476      */
477     function name() {
478         return get_string('name'.$this->type, 'data');
479     }
481     /**
482      * Prints the respective type icon
483      *
484      * @global object
485      * @return string
486      */
487     function image() {
488         global $OUTPUT;
490         $params = array('d'=>$this->data->id, 'fid'=>$this->field->id, 'mode'=>'display', 'sesskey'=>sesskey());
491         $link = new moodle_url('/mod/data/field.php', $params);
492         $str = '<a href="'.$link->out().'">';
493         $str .= '<img src="'.$OUTPUT->pix_url('field/'.$this->type, 'data') . '" ';
494         $str .= 'height="'.$this->iconheight.'" width="'.$this->iconwidth.'" alt="'.$this->type.'" title="'.$this->type.'" /></a>';
495         return $str;
496     }
498     /**
499      * Per default, it is assumed that fields support text exporting.
500      * Override this (return false) on fields not supporting text exporting.
501      *
502      * @return bool true
503      */
504     function text_export_supported() {
505         return true;
506     }
508     /**
509      * Per default, return the record's text value only from the "content" field.
510      * Override this in fields class if necesarry.
511      *
512      * @param string $record
513      * @return string
514      */
515     function export_text_value($record) {
516         if ($this->text_export_supported()) {
517             return $record->content;
518         }
519     }
521     /**
522      * @param string $relativepath
523      * @return bool false
524      */
525     function file_ok($relativepath) {
526         return false;
527     }
531 /**
532  * Given a template and a dataid, generate a default case template
533  *
534  * @global object
535  * @param object $data
536  * @param string template [addtemplate, singletemplate, listtempalte, rsstemplate]
537  * @param int $recordid
538  * @param bool $form
539  * @param bool $update
540  * @return bool|string
541  */
542 function data_generate_default_template(&$data, $template, $recordid=0, $form=false, $update=true) {
543     global $DB;
545     if (!$data && !$template) {
546         return false;
547     }
548     if ($template == 'csstemplate' or $template == 'jstemplate' ) {
549         return '';
550     }
552     // get all the fields for that database
553     if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'id')) {
555         $table = new html_table();
556         $table->attributes['class'] = 'mod-data-default-template ##approvalstatus##';
557         $table->colclasses = array('template-field', 'template-token');
558         $table->data = array();
559         foreach ($fields as $field) {
560             if ($form) {   // Print forms instead of data
561                 $fieldobj = data_get_field($field, $data);
562                 $token = $fieldobj->display_add_field($recordid, null);
563             } else {           // Just print the tag
564                 $token = '[['.$field->name.']]';
565             }
566             $table->data[] = array(
567                 $field->name.': ',
568                 $token
569             );
570         }
571         if ($template == 'listtemplate') {
572             $cell = new html_table_cell('##edit##  ##more##  ##delete##  ##approve##  ##disapprove##  ##export##');
573             $cell->colspan = 2;
574             $cell->attributes['class'] = 'controls';
575             $table->data[] = new html_table_row(array($cell));
576         } else if ($template == 'singletemplate') {
577             $cell = new html_table_cell('##edit##  ##delete##  ##approve##  ##disapprove##  ##export##');
578             $cell->colspan = 2;
579             $cell->attributes['class'] = 'controls';
580             $table->data[] = new html_table_row(array($cell));
581         } else if ($template == 'asearchtemplate') {
582             $row = new html_table_row(array(get_string('authorfirstname', 'data').': ', '##firstname##'));
583             $row->attributes['class'] = 'searchcontrols';
584             $table->data[] = $row;
585             $row = new html_table_row(array(get_string('authorlastname', 'data').': ', '##lastname##'));
586             $row->attributes['class'] = 'searchcontrols';
587             $table->data[] = $row;
588         }
590         $str = '';
591         if ($template == 'listtemplate'){
592             $str .= '##delcheck##';
593             $str .= html_writer::empty_tag('br');
594         }
596         $str .= html_writer::start_tag('div', array('class' => 'defaulttemplate'));
597         $str .= html_writer::table($table);
598         $str .= html_writer::end_tag('div');
599         if ($template == 'listtemplate'){
600             $str .= html_writer::empty_tag('hr');
601         }
603         if ($update) {
604             $newdata = new stdClass();
605             $newdata->id = $data->id;
606             $newdata->{$template} = $str;
607             $DB->update_record('data', $newdata);
608             $data->{$template} = $str;
609         }
611         return $str;
612     }
616 /**
617  * Search for a field name and replaces it with another one in all the
618  * form templates. Set $newfieldname as '' if you want to delete the
619  * field from the form.
620  *
621  * @global object
622  * @param object $data
623  * @param string $searchfieldname
624  * @param string $newfieldname
625  * @return bool
626  */
627 function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
628     global $DB;
630     if (!empty($newfieldname)) {
631         $prestring = '[[';
632         $poststring = ']]';
633         $idpart = '#id';
635     } else {
636         $prestring = '';
637         $poststring = '';
638         $idpart = '';
639     }
641     $newdata = new stdClass();
642     $newdata->id = $data->id;
643     $newdata->singletemplate = str_ireplace('[['.$searchfieldname.']]',
644             $prestring.$newfieldname.$poststring, $data->singletemplate);
646     $newdata->listtemplate = str_ireplace('[['.$searchfieldname.']]',
647             $prestring.$newfieldname.$poststring, $data->listtemplate);
649     $newdata->addtemplate = str_ireplace('[['.$searchfieldname.']]',
650             $prestring.$newfieldname.$poststring, $data->addtemplate);
652     $newdata->addtemplate = str_ireplace('[['.$searchfieldname.'#id]]',
653             $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate);
655     $newdata->rsstemplate = str_ireplace('[['.$searchfieldname.']]',
656             $prestring.$newfieldname.$poststring, $data->rsstemplate);
658     return $DB->update_record('data', $newdata);
662 /**
663  * Appends a new field at the end of the form template.
664  *
665  * @global object
666  * @param object $data
667  * @param string $newfieldname
668  */
669 function data_append_new_field_to_templates($data, $newfieldname) {
670     global $DB;
672     $newdata = new stdClass();
673     $newdata->id = $data->id;
674     $change = false;
676     if (!empty($data->singletemplate)) {
677         $newdata->singletemplate = $data->singletemplate.' [[' . $newfieldname .']]';
678         $change = true;
679     }
680     if (!empty($data->addtemplate)) {
681         $newdata->addtemplate = $data->addtemplate.' [[' . $newfieldname . ']]';
682         $change = true;
683     }
684     if (!empty($data->rsstemplate)) {
685         $newdata->rsstemplate = $data->singletemplate.' [[' . $newfieldname . ']]';
686         $change = true;
687     }
688     if ($change) {
689         $DB->update_record('data', $newdata);
690     }
694 /**
695  * given a field name
696  * this function creates an instance of the particular subfield class
697  *
698  * @global object
699  * @param string $name
700  * @param object $data
701  * @return object|bool
702  */
703 function data_get_field_from_name($name, $data){
704     global $DB;
706     $field = $DB->get_record('data_fields', array('name'=>$name, 'dataid'=>$data->id));
708     if ($field) {
709         return data_get_field($field, $data);
710     } else {
711         return false;
712     }
715 /**
716  * given a field id
717  * this function creates an instance of the particular subfield class
718  *
719  * @global object
720  * @param int $fieldid
721  * @param object $data
722  * @return bool|object
723  */
724 function data_get_field_from_id($fieldid, $data){
725     global $DB;
727     $field = $DB->get_record('data_fields', array('id'=>$fieldid, 'dataid'=>$data->id));
729     if ($field) {
730         return data_get_field($field, $data);
731     } else {
732         return false;
733     }
736 /**
737  * given a field id
738  * this function creates an instance of the particular subfield class
739  *
740  * @global object
741  * @param string $type
742  * @param object $data
743  * @return object
744  */
745 function data_get_field_new($type, $data) {
746     global $CFG;
748     require_once($CFG->dirroot.'/mod/data/field/'.$type.'/field.class.php');
749     $newfield = 'data_field_'.$type;
750     $newfield = new $newfield(0, $data);
751     return $newfield;
754 /**
755  * returns a subclass field object given a record of the field, used to
756  * invoke plugin methods
757  * input: $param $field - record from db
758  *
759  * @global object
760  * @param object $field
761  * @param object $data
762  * @param object $cm
763  * @return object
764  */
765 function data_get_field($field, $data, $cm=null) {
766     global $CFG;
768     if ($field) {
769         require_once('field/'.$field->type.'/field.class.php');
770         $newfield = 'data_field_'.$field->type;
771         $newfield = new $newfield($field, $data, $cm);
772         return $newfield;
773     }
777 /**
778  * Given record object (or id), returns true if the record belongs to the current user
779  *
780  * @global object
781  * @global object
782  * @param mixed $record record object or id
783  * @return bool
784  */
785 function data_isowner($record) {
786     global $USER, $DB;
788     if (!isloggedin()) { // perf shortcut
789         return false;
790     }
792     if (!is_object($record)) {
793         if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
794             return false;
795         }
796     }
798     return ($record->userid == $USER->id);
801 /**
802  * has a user reached the max number of entries?
803  *
804  * @param object $data
805  * @return bool
806  */
807 function data_atmaxentries($data){
808     if (!$data->maxentries){
809         return false;
811     } else {
812         return (data_numentries($data) >= $data->maxentries);
813     }
816 /**
817  * returns the number of entries already made by this user
818  *
819  * @global object
820  * @global object
821  * @param object $data
822  * @return int
823  */
824 function data_numentries($data){
825     global $USER, $DB;
826     $sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
827     return $DB->count_records_sql($sql, array($data->id, $USER->id));
830 /**
831  * function that takes in a dataid and adds a record
832  * this is used everytime an add template is submitted
833  *
834  * @global object
835  * @global object
836  * @param object $data
837  * @param int $groupid
838  * @return bool
839  */
840 function data_add_record($data, $groupid=0){
841     global $USER, $DB;
843     $cm = get_coursemodule_from_instance('data', $data->id);
844     $context = context_module::instance($cm->id);
846     $record = new stdClass();
847     $record->userid = $USER->id;
848     $record->dataid = $data->id;
849     $record->groupid = $groupid;
850     $record->timecreated = $record->timemodified = time();
851     if (has_capability('mod/data:approve', $context)) {
852         $record->approved = 1;
853     } else {
854         $record->approved = 0;
855     }
856     $record->id = $DB->insert_record('data_records', $record);
858     // Trigger an event for creating this record.
859     $event = \mod_data\event\record_created::create(array(
860         'objectid' => $record->id,
861         'context' => $context,
862         'other' => array(
863             'dataid' => $data->id
864         )
865     ));
866     $event->trigger();
868     return $record->id;
871 /**
872  * check the multple existence any tag in a template
873  *
874  * check to see if there are 2 or more of the same tag being used.
875  *
876  * @global object
877  * @param int $dataid,
878  * @param string $template
879  * @return bool
880  */
881 function data_tags_check($dataid, $template) {
882     global $DB, $OUTPUT;
884     // first get all the possible tags
885     $fields = $DB->get_records('data_fields', array('dataid'=>$dataid));
886     // then we generate strings to replace
887     $tagsok = true; // let's be optimistic
888     foreach ($fields as $field){
889         $pattern="/\[\[" . preg_quote($field->name, '/') . "\]\]/i";
890         if (preg_match_all($pattern, $template, $dummy)>1){
891             $tagsok = false;
892             echo $OUTPUT->notification('[['.$field->name.']] - '.get_string('multipletags','data'));
893         }
894     }
895     // else return true
896     return $tagsok;
899 /**
900  * Adds an instance of a data
901  *
902  * @param stdClass $data
903  * @param mod_data_mod_form $mform
904  * @return int intance id
905  */
906 function data_add_instance($data, $mform = null) {
907     global $DB;
909     if (empty($data->assessed)) {
910         $data->assessed = 0;
911     }
913     $data->timemodified = time();
915     $data->id = $DB->insert_record('data', $data);
917     data_grade_item_update($data);
919     return $data->id;
922 /**
923  * updates an instance of a data
924  *
925  * @global object
926  * @param object $data
927  * @return bool
928  */
929 function data_update_instance($data) {
930     global $DB, $OUTPUT;
932     $data->timemodified = time();
933     $data->id           = $data->instance;
935     if (empty($data->assessed)) {
936         $data->assessed = 0;
937     }
939     if (empty($data->ratingtime) or empty($data->assessed)) {
940         $data->assesstimestart  = 0;
941         $data->assesstimefinish = 0;
942     }
944     if (empty($data->notification)) {
945         $data->notification = 0;
946     }
948     $DB->update_record('data', $data);
950     data_grade_item_update($data);
952     return true;
956 /**
957  * deletes an instance of a data
958  *
959  * @global object
960  * @param int $id
961  * @return bool
962  */
963 function data_delete_instance($id) {    // takes the dataid
964     global $DB, $CFG;
966     if (!$data = $DB->get_record('data', array('id'=>$id))) {
967         return false;
968     }
970     $cm = get_coursemodule_from_instance('data', $data->id);
971     $context = context_module::instance($cm->id);
973 /// Delete all the associated information
975     // files
976     $fs = get_file_storage();
977     $fs->delete_area_files($context->id, 'mod_data');
979     // get all the records in this data
980     $sql = "SELECT r.id
981               FROM {data_records} r
982              WHERE r.dataid = ?";
984     $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
986     // delete all the records and fields
987     $DB->delete_records('data_records', array('dataid'=>$id));
988     $DB->delete_records('data_fields', array('dataid'=>$id));
990     // Delete the instance itself
991     $result = $DB->delete_records('data', array('id'=>$id));
993     // cleanup gradebook
994     data_grade_item_delete($data);
996     return $result;
999 /**
1000  * returns a summary of data activity of this user
1001  *
1002  * @global object
1003  * @param object $course
1004  * @param object $user
1005  * @param object $mod
1006  * @param object $data
1007  * @return object|null
1008  */
1009 function data_user_outline($course, $user, $mod, $data) {
1010     global $DB, $CFG;
1011     require_once("$CFG->libdir/gradelib.php");
1013     $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1014     if (empty($grades->items[0]->grades)) {
1015         $grade = false;
1016     } else {
1017         $grade = reset($grades->items[0]->grades);
1018     }
1021     if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id, 'userid'=>$user->id))) {
1022         $result = new stdClass();
1023         $result->info = get_string('numrecords', 'data', $countrecords);
1024         $lastrecord   = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
1025                                               WHERE dataid = ? AND userid = ?
1026                                            ORDER BY timemodified DESC', array($data->id, $user->id), true);
1027         $result->time = $lastrecord->timemodified;
1028         if ($grade) {
1029             $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1030         }
1031         return $result;
1032     } else if ($grade) {
1033         $result = new stdClass();
1034         $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1036         //datesubmitted == time created. dategraded == time modified or time overridden
1037         //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1038         //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1039         if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1040             $result->time = $grade->dategraded;
1041         } else {
1042             $result->time = $grade->datesubmitted;
1043         }
1045         return $result;
1046     }
1047     return NULL;
1050 /**
1051  * Prints all the records uploaded by this user
1052  *
1053  * @global object
1054  * @param object $course
1055  * @param object $user
1056  * @param object $mod
1057  * @param object $data
1058  */
1059 function data_user_complete($course, $user, $mod, $data) {
1060     global $DB, $CFG, $OUTPUT;
1061     require_once("$CFG->libdir/gradelib.php");
1063     $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1064     if (!empty($grades->items[0]->grades)) {
1065         $grade = reset($grades->items[0]->grades);
1066         echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1067         if ($grade->str_feedback) {
1068             echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1069         }
1070     }
1072     if ($records = $DB->get_records('data_records', array('dataid'=>$data->id,'userid'=>$user->id), 'timemodified DESC')) {
1073         data_print_template('singletemplate', $records, $data);
1074     }
1077 /**
1078  * Return grade for given user or all users.
1079  *
1080  * @global object
1081  * @param object $data
1082  * @param int $userid optional user id, 0 means all users
1083  * @return array array of grades, false if none
1084  */
1085 function data_get_user_grades($data, $userid=0) {
1086     global $CFG;
1088     require_once($CFG->dirroot.'/rating/lib.php');
1090     $ratingoptions = new stdClass;
1091     $ratingoptions->component = 'mod_data';
1092     $ratingoptions->ratingarea = 'entry';
1093     $ratingoptions->modulename = 'data';
1094     $ratingoptions->moduleid   = $data->id;
1096     $ratingoptions->userid = $userid;
1097     $ratingoptions->aggregationmethod = $data->assessed;
1098     $ratingoptions->scaleid = $data->scale;
1099     $ratingoptions->itemtable = 'data_records';
1100     $ratingoptions->itemtableusercolumn = 'userid';
1102     $rm = new rating_manager();
1103     return $rm->get_user_grades($ratingoptions);
1106 /**
1107  * Update activity grades
1108  *
1109  * @category grade
1110  * @param object $data
1111  * @param int $userid specific user only, 0 means all
1112  * @param bool $nullifnone
1113  */
1114 function data_update_grades($data, $userid=0, $nullifnone=true) {
1115     global $CFG, $DB;
1116     require_once($CFG->libdir.'/gradelib.php');
1118     if (!$data->assessed) {
1119         data_grade_item_update($data);
1121     } else if ($grades = data_get_user_grades($data, $userid)) {
1122         data_grade_item_update($data, $grades);
1124     } else if ($userid and $nullifnone) {
1125         $grade = new stdClass();
1126         $grade->userid   = $userid;
1127         $grade->rawgrade = NULL;
1128         data_grade_item_update($data, $grade);
1130     } else {
1131         data_grade_item_update($data);
1132     }
1135 /**
1136  * Update/create grade item for given data
1137  *
1138  * @category grade
1139  * @param stdClass $data A database instance with extra cmidnumber property
1140  * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1141  * @return object grade_item
1142  */
1143 function data_grade_item_update($data, $grades=NULL) {
1144     global $CFG;
1145     require_once($CFG->libdir.'/gradelib.php');
1147     $params = array('itemname'=>$data->name, 'idnumber'=>$data->cmidnumber);
1149     if (!$data->assessed or $data->scale == 0) {
1150         $params['gradetype'] = GRADE_TYPE_NONE;
1152     } else if ($data->scale > 0) {
1153         $params['gradetype'] = GRADE_TYPE_VALUE;
1154         $params['grademax']  = $data->scale;
1155         $params['grademin']  = 0;
1157     } else if ($data->scale < 0) {
1158         $params['gradetype'] = GRADE_TYPE_SCALE;
1159         $params['scaleid']   = -$data->scale;
1160     }
1162     if ($grades  === 'reset') {
1163         $params['reset'] = true;
1164         $grades = NULL;
1165     }
1167     return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, $grades, $params);
1170 /**
1171  * Delete grade item for given data
1172  *
1173  * @category grade
1174  * @param object $data object
1175  * @return object grade_item
1176  */
1177 function data_grade_item_delete($data) {
1178     global $CFG;
1179     require_once($CFG->libdir.'/gradelib.php');
1181     return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, NULL, array('deleted'=>1));
1184 // junk functions
1185 /**
1186  * takes a list of records, the current data, a search string,
1187  * and mode to display prints the translated template
1188  *
1189  * @global object
1190  * @global object
1191  * @param string $template
1192  * @param array $records
1193  * @param object $data
1194  * @param string $search
1195  * @param int $page
1196  * @param bool $return
1197  * @param object $jumpurl a moodle_url by which to jump back to the record list (can be null)
1198  * @return mixed
1199  */
1200 function data_print_template($template, $records, $data, $search='', $page=0, $return=false, moodle_url $jumpurl=null) {
1201     global $CFG, $DB, $OUTPUT;
1203     $cm = get_coursemodule_from_instance('data', $data->id);
1204     $context = context_module::instance($cm->id);
1206     static $fields = NULL;
1207     static $isteacher;
1208     static $dataid = NULL;
1210     if (empty($dataid)) {
1211         $dataid = $data->id;
1212     } else if ($dataid != $data->id) {
1213         $fields = NULL;
1214     }
1216     if (empty($fields)) {
1217         $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1218         foreach ($fieldrecords as $fieldrecord) {
1219             $fields[]= data_get_field($fieldrecord, $data);
1220         }
1221         $isteacher = has_capability('mod/data:managetemplates', $context);
1222     }
1224     if (empty($records)) {
1225         return;
1226     }
1228     if (!$jumpurl) {
1229         $jumpurl = new moodle_url('/mod/data/view.php', array('d' => $data->id));
1230     }
1231     $jumpurl = new moodle_url($jumpurl, array('page' => $page, 'sesskey' => sesskey()));
1233     foreach ($records as $record) {   // Might be just one for the single template
1235     // Replacing tags
1236         $patterns = array();
1237         $replacement = array();
1239     // Then we generate strings to replace for normal tags
1240         foreach ($fields as $field) {
1241             $patterns[]='[['.$field->field->name.']]';
1242             $replacement[] = highlight($search, $field->display_browse_field($record->id, $template));
1243         }
1245         $canmanageentries = has_capability('mod/data:manageentries', $context);
1247     // Replacing special tags (##Edit##, ##Delete##, ##More##)
1248         $patterns[]='##edit##';
1249         $patterns[]='##delete##';
1250         if (data_user_can_manage_entry($record, $data, $context)) {
1251             $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d='
1252                              .$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>';
1253             $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='
1254                              .$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>';
1255         } else {
1256             $replacement[] = '';
1257             $replacement[] = '';
1258         }
1260         $moreurl = $CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&amp;rid=' . $record->id;
1261         if ($search) {
1262             $moreurl .= '&amp;filter=1';
1263         }
1264         $patterns[]='##more##';
1265         $replacement[] = '<a href="'.$moreurl.'"><img src="'.$OUTPUT->pix_url('t/preview').
1266                         '" class="iconsmall" alt="'.get_string('more', 'data').'" title="'.get_string('more', 'data').
1267                         '" /></a>';
1269         $patterns[]='##moreurl##';
1270         $replacement[] = $moreurl;
1272         $patterns[]='##delcheck##';
1273         if ($canmanageentries) {
1274             $replacement[] = html_writer::checkbox('delcheck[]', $record->id, false, '', array('class' => 'recordcheckbox'));
1275         } else {
1276             $replacement[] = '';
1277         }
1279         $patterns[]='##user##';
1280         $replacement[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$record->userid.
1281                                '&amp;course='.$data->course.'">'.fullname($record).'</a>';
1283         $patterns[] = '##userpicture##';
1284         $ruser = user_picture::unalias($record, null, 'userid');
1285         $replacement[] = $OUTPUT->user_picture($ruser, array('courseid' => $data->course));
1287         $patterns[]='##export##';
1289         if (!empty($CFG->enableportfolios) && ($template == 'singletemplate' || $template == 'listtemplate')
1290             && ((has_capability('mod/data:exportentry', $context)
1291                 || (data_isowner($record->id) && has_capability('mod/data:exportownentry', $context))))) {
1292             require_once($CFG->libdir . '/portfoliolib.php');
1293             $button = new portfolio_add_button();
1294             $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id, 'recordid' => $record->id), 'mod_data');
1295             list($formats, $files) = data_portfolio_caller::formats($fields, $record);
1296             $button->set_formats($formats);
1297             $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1298         } else {
1299             $replacement[] = '';
1300         }
1302         $patterns[] = '##timeadded##';
1303         $replacement[] = userdate($record->timecreated);
1305         $patterns[] = '##timemodified##';
1306         $replacement [] = userdate($record->timemodified);
1308         $patterns[]='##approve##';
1309         if (has_capability('mod/data:approve', $context) && ($data->approval) && (!$record->approved)) {
1310             $approveurl = new moodle_url($jumpurl, array('approve' => $record->id));
1311             $approveicon = new pix_icon('t/approve', get_string('approve', 'data'), '', array('class' => 'iconsmall'));
1312             $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($approveurl, $approveicon),
1313                     array('class' => 'approve'));
1314         } else {
1315             $replacement[] = '';
1316         }
1318         $patterns[]='##disapprove##';
1319         if (has_capability('mod/data:approve', $context) && ($data->approval) && ($record->approved)) {
1320             $disapproveurl = new moodle_url($jumpurl, array('disapprove' => $record->id));
1321             $disapproveicon = new pix_icon('t/block', get_string('disapprove', 'data'), '', array('class' => 'iconsmall'));
1322             $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($disapproveurl, $disapproveicon),
1323                     array('class' => 'disapprove'));
1324         } else {
1325             $replacement[] = '';
1326         }
1328         $patterns[] = '##approvalstatus##';
1329         if (!$data->approval) {
1330             $replacement[] = '';
1331         } else if ($record->approved) {
1332             $replacement[] = 'approved';
1333         } else {
1334             $replacement[] = 'notapproved';
1335         }
1337         $patterns[]='##comments##';
1338         if (($template == 'listtemplate') && ($data->comments)) {
1340             if (!empty($CFG->usecomments)) {
1341                 require_once($CFG->dirroot  . '/comment/lib.php');
1342                 list($context, $course, $cm) = get_context_info_array($context->id);
1343                 $cmt = new stdClass();
1344                 $cmt->context = $context;
1345                 $cmt->course  = $course;
1346                 $cmt->cm      = $cm;
1347                 $cmt->area    = 'database_entry';
1348                 $cmt->itemid  = $record->id;
1349                 $cmt->showcount = true;
1350                 $cmt->component = 'mod_data';
1351                 $comment = new comment($cmt);
1352                 $replacement[] = $comment->output(true);
1353             }
1354         } else {
1355             $replacement[] = '';
1356         }
1358         // actual replacement of the tags
1359         $newtext = str_ireplace($patterns, $replacement, $data->{$template});
1361         // no more html formatting and filtering - see MDL-6635
1362         if ($return) {
1363             return $newtext;
1364         } else {
1365             echo $newtext;
1367             // hack alert - return is always false in singletemplate anyway ;-)
1368             /**********************************
1369              *    Printing Ratings Form       *
1370              *********************************/
1371             if ($template == 'singletemplate') {    //prints ratings options
1372                 data_print_ratings($data, $record);
1373             }
1375             /**********************************
1376              *    Printing Comments Form       *
1377              *********************************/
1378             if (($template == 'singletemplate') && ($data->comments)) {
1379                 if (!empty($CFG->usecomments)) {
1380                     require_once($CFG->dirroot . '/comment/lib.php');
1381                     list($context, $course, $cm) = get_context_info_array($context->id);
1382                     $cmt = new stdClass();
1383                     $cmt->context = $context;
1384                     $cmt->course  = $course;
1385                     $cmt->cm      = $cm;
1386                     $cmt->area    = 'database_entry';
1387                     $cmt->itemid  = $record->id;
1388                     $cmt->showcount = true;
1389                     $cmt->component = 'mod_data';
1390                     $comment = new comment($cmt);
1391                     $comment->output(false);
1392                 }
1393             }
1394         }
1395     }
1398 /**
1399  * Return rating related permissions
1400  *
1401  * @param string $contextid the context id
1402  * @param string $component the component to get rating permissions for
1403  * @param string $ratingarea the rating area to get permissions for
1404  * @return array an associative array of the user's rating permissions
1405  */
1406 function data_rating_permissions($contextid, $component, $ratingarea) {
1407     $context = context::instance_by_id($contextid, MUST_EXIST);
1408     if ($component != 'mod_data' || $ratingarea != 'entry') {
1409         return null;
1410     }
1411     return array(
1412         'view'    => has_capability('mod/data:viewrating',$context),
1413         'viewany' => has_capability('mod/data:viewanyrating',$context),
1414         'viewall' => has_capability('mod/data:viewallratings',$context),
1415         'rate'    => has_capability('mod/data:rate',$context)
1416     );
1419 /**
1420  * Validates a submitted rating
1421  * @param array $params submitted data
1422  *            context => object the context in which the rated items exists [required]
1423  *            itemid => int the ID of the object being rated
1424  *            scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1425  *            rating => int the submitted rating
1426  *            rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1427  *            aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
1428  * @return boolean true if the rating is valid. Will throw rating_exception if not
1429  */
1430 function data_rating_validate($params) {
1431     global $DB, $USER;
1433     // Check the component is mod_data
1434     if ($params['component'] != 'mod_data') {
1435         throw new rating_exception('invalidcomponent');
1436     }
1438     // Check the ratingarea is entry (the only rating area in data module)
1439     if ($params['ratingarea'] != 'entry') {
1440         throw new rating_exception('invalidratingarea');
1441     }
1443     // Check the rateduserid is not the current user .. you can't rate your own entries
1444     if ($params['rateduserid'] == $USER->id) {
1445         throw new rating_exception('nopermissiontorate');
1446     }
1448     $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
1449                   FROM {data_records} r
1450                   JOIN {data} d ON r.dataid = d.id
1451                  WHERE r.id = :itemid";
1452     $dataparams = array('itemid'=>$params['itemid']);
1453     if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1454         //item doesn't exist
1455         throw new rating_exception('invaliditemid');
1456     }
1458     if ($info->scale != $params['scaleid']) {
1459         //the scale being submitted doesnt match the one in the database
1460         throw new rating_exception('invalidscaleid');
1461     }
1463     //check that the submitted rating is valid for the scale
1465     // lower limit
1466     if ($params['rating'] < 0  && $params['rating'] != RATING_UNSET_RATING) {
1467         throw new rating_exception('invalidnum');
1468     }
1470     // upper limit
1471     if ($info->scale < 0) {
1472         //its a custom scale
1473         $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
1474         if ($scalerecord) {
1475             $scalearray = explode(',', $scalerecord->scale);
1476             if ($params['rating'] > count($scalearray)) {
1477                 throw new rating_exception('invalidnum');
1478             }
1479         } else {
1480             throw new rating_exception('invalidscaleid');
1481         }
1482     } else if ($params['rating'] > $info->scale) {
1483         //if its numeric and submitted rating is above maximum
1484         throw new rating_exception('invalidnum');
1485     }
1487     if ($info->approval && !$info->approved) {
1488         //database requires approval but this item isnt approved
1489         throw new rating_exception('nopermissiontorate');
1490     }
1492     // check the item we're rating was created in the assessable time window
1493     if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
1494         if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
1495             throw new rating_exception('notavailable');
1496         }
1497     }
1499     $course = $DB->get_record('course', array('id'=>$info->course), '*', MUST_EXIST);
1500     $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1501     $context = context_module::instance($cm->id);
1503     // if the supplied context doesnt match the item's context
1504     if ($context->id != $params['context']->id) {
1505         throw new rating_exception('invalidcontext');
1506     }
1508     // Make sure groups allow this user to see the item they're rating
1509     $groupid = $info->groupid;
1510     if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {   // Groups are being used
1511         if (!groups_group_exists($groupid)) { // Can't find group
1512             throw new rating_exception('cannotfindgroup');//something is wrong
1513         }
1515         if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1516             // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
1517             throw new rating_exception('notmemberofgroup');
1518         }
1519     }
1521     return true;
1524 /**
1525  * Can the current user see ratings for a given itemid?
1526  *
1527  * @param array $params submitted data
1528  *            contextid => int contextid [required]
1529  *            component => The component for this module - should always be mod_data [required]
1530  *            ratingarea => object the context in which the rated items exists [required]
1531  *            itemid => int the ID of the object being rated [required]
1532  *            scaleid => int scale id [optional]
1533  * @return bool
1534  * @throws coding_exception
1535  * @throws rating_exception
1536  */
1537 function mod_data_rating_can_see_item_ratings($params) {
1538     global $DB;
1540     // Check the component is mod_data.
1541     if (!isset($params['component']) || $params['component'] != 'mod_data') {
1542         throw new rating_exception('invalidcomponent');
1543     }
1545     // Check the ratingarea is entry (the only rating area in data).
1546     if (!isset($params['ratingarea']) || $params['ratingarea'] != 'entry') {
1547         throw new rating_exception('invalidratingarea');
1548     }
1550     if (!isset($params['itemid'])) {
1551         throw new rating_exception('invaliditemid');
1552     }
1554     $datasql = "SELECT d.id as dataid, d.course, r.groupid
1555                   FROM {data_records} r
1556                   JOIN {data} d ON r.dataid = d.id
1557                  WHERE r.id = :itemid";
1558     $dataparams = array('itemid' => $params['itemid']);
1559     if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1560         // Item doesn't exist.
1561         throw new rating_exception('invaliditemid');
1562     }
1564     $course = $DB->get_record('course', array('id' => $info->course), '*', MUST_EXIST);
1565     $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1567     // Make sure groups allow this user to see the item they're rating.
1568     return groups_group_visible($info->groupid, $course, $cm);
1572 /**
1573  * function that takes in the current data, number of items per page,
1574  * a search string and prints a preference box in view.php
1575  *
1576  * This preference box prints a searchable advanced search template if
1577  *     a) A template is defined
1578  *  b) The advanced search checkbox is checked.
1579  *
1580  * @global object
1581  * @global object
1582  * @param object $data
1583  * @param int $perpage
1584  * @param string $search
1585  * @param string $sort
1586  * @param string $order
1587  * @param array $search_array
1588  * @param int $advanced
1589  * @param string $mode
1590  * @return void
1591  */
1592 function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
1593     global $CFG, $DB, $PAGE, $OUTPUT;
1595     $cm = get_coursemodule_from_instance('data', $data->id);
1596     $context = context_module::instance($cm->id);
1597     echo '<br /><div class="datapreferences">';
1598     echo '<form id="options" action="view.php" method="get">';
1599     echo '<div>';
1600     echo '<input type="hidden" name="d" value="'.$data->id.'" />';
1601     if ($mode =='asearch') {
1602         $advanced = 1;
1603         echo '<input type="hidden" name="mode" value="list" />';
1604     }
1605     echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
1606     $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
1607                        20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
1608     echo html_writer::select($pagesizes, 'perpage', $perpage, false, array('id'=>'pref_perpage'));
1610     if ($advanced) {
1611         $regsearchclass = 'search_none';
1612         $advancedsearchclass = 'search_inline';
1613     } else {
1614         $regsearchclass = 'search_inline';
1615         $advancedsearchclass = 'search_none';
1616     }
1617     echo '<div id="reg_search" class="' . $regsearchclass . '" >&nbsp;&nbsp;&nbsp;';
1618     echo '<label for="pref_search">'.get_string('search').'</label> <input type="text" size="16" name="search" id= "pref_search" value="'.s($search).'" /></div>';
1619     echo '&nbsp;&nbsp;&nbsp;<label for="pref_sortby">'.get_string('sortby').'</label> ';
1620     // foreach field, print the option
1621     echo '<select name="sort" id="pref_sortby">';
1622     if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'name')) {
1623         echo '<optgroup label="'.get_string('fields', 'data').'">';
1624         foreach ($fields as $field) {
1625             if ($field->id == $sort) {
1626                 echo '<option value="'.$field->id.'" selected="selected">'.$field->name.'</option>';
1627             } else {
1628                 echo '<option value="'.$field->id.'">'.$field->name.'</option>';
1629             }
1630         }
1631         echo '</optgroup>';
1632     }
1633     $options = array();
1634     $options[DATA_TIMEADDED]    = get_string('timeadded', 'data');
1635     $options[DATA_TIMEMODIFIED] = get_string('timemodified', 'data');
1636     $options[DATA_FIRSTNAME]    = get_string('authorfirstname', 'data');
1637     $options[DATA_LASTNAME]     = get_string('authorlastname', 'data');
1638     if ($data->approval and has_capability('mod/data:approve', $context)) {
1639         $options[DATA_APPROVED] = get_string('approved', 'data');
1640     }
1641     echo '<optgroup label="'.get_string('other', 'data').'">';
1642     foreach ($options as $key => $name) {
1643         if ($key == $sort) {
1644             echo '<option value="'.$key.'" selected="selected">'.$name.'</option>';
1645         } else {
1646             echo '<option value="'.$key.'">'.$name.'</option>';
1647         }
1648     }
1649     echo '</optgroup>';
1650     echo '</select>';
1651     echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
1652     echo '<select id="pref_order" name="order">';
1653     if ($order == 'ASC') {
1654         echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
1655     } else {
1656         echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1657     }
1658     if ($order == 'DESC') {
1659         echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
1660     } else {
1661         echo '<option value="DESC">'.get_string('descending','data').'</option>';
1662     }
1663     echo '</select>';
1665     if ($advanced) {
1666         $checked = ' checked="checked" ';
1667     }
1668     else {
1669         $checked = '';
1670     }
1671     $PAGE->requires->js('/mod/data/data.js');
1672     echo '&nbsp;<input type="hidden" name="advanced" value="0" />';
1673     echo '&nbsp;<input type="hidden" name="filter" value="1" />';
1674     echo '&nbsp;<input type="checkbox" id="advancedcheckbox" name="advanced" value="1" '.$checked.' onchange="showHideAdvSearch(this.checked);" /><label for="advancedcheckbox">'.get_string('advancedsearch', 'data').'</label>';
1675     echo '&nbsp;<input type="submit" value="'.get_string('savesettings','data').'" />';
1677     echo '<br />';
1678     echo '<div class="' . $advancedsearchclass . '" id="data_adv_form">';
1679     echo '<table class="boxaligncenter">';
1681     // print ASC or DESC
1682     echo '<tr><td colspan="2">&nbsp;</td></tr>';
1683     $i = 0;
1685     // Determine if we are printing all fields for advanced search, or the template for advanced search
1686     // If a template is not defined, use the deafault template and display all fields.
1687     if(empty($data->asearchtemplate)) {
1688         data_generate_default_template($data, 'asearchtemplate');
1689     }
1691     static $fields = NULL;
1692     static $isteacher;
1693     static $dataid = NULL;
1695     if (empty($dataid)) {
1696         $dataid = $data->id;
1697     } else if ($dataid != $data->id) {
1698         $fields = NULL;
1699     }
1701     if (empty($fields)) {
1702         $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1703         foreach ($fieldrecords as $fieldrecord) {
1704             $fields[]= data_get_field($fieldrecord, $data);
1705         }
1707         $isteacher = has_capability('mod/data:managetemplates', $context);
1708     }
1710     // Replacing tags
1711     $patterns = array();
1712     $replacement = array();
1714     // Then we generate strings to replace for normal tags
1715     foreach ($fields as $field) {
1716         $fieldname = $field->field->name;
1717         $fieldname = preg_quote($fieldname, '/');
1718         $patterns[] = "/\[\[$fieldname\]\]/i";
1719         $searchfield = data_get_field_from_id($field->field->id, $data);
1720         if (!empty($search_array[$field->field->id]->data)) {
1721             $replacement[] = $searchfield->display_search_field($search_array[$field->field->id]->data);
1722         } else {
1723             $replacement[] = $searchfield->display_search_field();
1724         }
1725     }
1726     $fn = !empty($search_array[DATA_FIRSTNAME]->data) ? $search_array[DATA_FIRSTNAME]->data : '';
1727     $ln = !empty($search_array[DATA_LASTNAME]->data) ? $search_array[DATA_LASTNAME]->data : '';
1728     $patterns[]    = '/##firstname##/';
1729     $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.'" />';
1730     $patterns[]    = '/##lastname##/';
1731     $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.'" />';
1733     // actual replacement of the tags
1734     $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate);
1736     $options = new stdClass();
1737     $options->para=false;
1738     $options->noclean=true;
1739     echo '<tr><td>';
1740     echo format_text($newtext, FORMAT_HTML, $options);
1741     echo '</td></tr>';
1743     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>';
1744     echo '</table>';
1745     echo '</div>';
1746     echo '</div>';
1747     echo '</form>';
1748     echo '</div>';
1751 /**
1752  * @global object
1753  * @global object
1754  * @param object $data
1755  * @param object $record
1756  * @return void Output echo'd
1757  */
1758 function data_print_ratings($data, $record) {
1759     global $OUTPUT;
1760     if (!empty($record->rating)){
1761         echo $OUTPUT->render($record->rating);
1762     }
1765 /**
1766  * List the actions that correspond to a view of this module.
1767  * This is used by the participation report.
1768  *
1769  * Note: This is not used by new logging system. Event with
1770  *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1771  *       be considered as view action.
1772  *
1773  * @return array
1774  */
1775 function data_get_view_actions() {
1776     return array('view');
1779 /**
1780  * List the actions that correspond to a post of this module.
1781  * This is used by the participation report.
1782  *
1783  * Note: This is not used by new logging system. Event with
1784  *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1785  *       will be considered as post action.
1786  *
1787  * @return array
1788  */
1789 function data_get_post_actions() {
1790     return array('add','update','record delete');
1793 /**
1794  * @param string $name
1795  * @param int $dataid
1796  * @param int $fieldid
1797  * @return bool
1798  */
1799 function data_fieldname_exists($name, $dataid, $fieldid = 0) {
1800     global $DB;
1802     if (!is_numeric($name)) {
1803         $like = $DB->sql_like('df.name', ':name', false);
1804     } else {
1805         $like = "df.name = :name";
1806     }
1807     $params = array('name'=>$name);
1808     if ($fieldid) {
1809         $params['dataid']   = $dataid;
1810         $params['fieldid1'] = $fieldid;
1811         $params['fieldid2'] = $fieldid;
1812         return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1813                                         WHERE $like AND df.dataid = :dataid
1814                                               AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
1815     } else {
1816         $params['dataid']   = $dataid;
1817         return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1818                                         WHERE $like AND df.dataid = :dataid", $params);
1819     }
1822 /**
1823  * @param array $fieldinput
1824  */
1825 function data_convert_arrays_to_strings(&$fieldinput) {
1826     foreach ($fieldinput as $key => $val) {
1827         if (is_array($val)) {
1828             $str = '';
1829             foreach ($val as $inner) {
1830                 $str .= $inner . ',';
1831             }
1832             $str = substr($str, 0, -1);
1834             $fieldinput->$key = $str;
1835         }
1836     }
1840 /**
1841  * Converts a database (module instance) to use the Roles System
1842  *
1843  * @global object
1844  * @global object
1845  * @uses CONTEXT_MODULE
1846  * @uses CAP_PREVENT
1847  * @uses CAP_ALLOW
1848  * @param object $data a data object with the same attributes as a record
1849  *                     from the data database table
1850  * @param int $datamodid the id of the data module, from the modules table
1851  * @param array $teacherroles array of roles that have archetype teacher
1852  * @param array $studentroles array of roles that have archetype student
1853  * @param array $guestroles array of roles that have archetype guest
1854  * @param int $cmid the course_module id for this data instance
1855  * @return boolean data module was converted or not
1856  */
1857 function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
1858     global $CFG, $DB, $OUTPUT;
1860     if (!isset($data->participants) && !isset($data->assesspublic)
1861             && !isset($data->groupmode)) {
1862         // We assume that this database has already been converted to use the
1863         // Roles System. above fields get dropped the data module has been
1864         // upgraded to use Roles.
1865         return false;
1866     }
1868     if (empty($cmid)) {
1869         // We were not given the course_module id. Try to find it.
1870         if (!$cm = get_coursemodule_from_instance('data', $data->id)) {
1871             echo $OUTPUT->notification('Could not get the course module for the data');
1872             return false;
1873         } else {
1874             $cmid = $cm->id;
1875         }
1876     }
1877     $context = context_module::instance($cmid);
1880     // $data->participants:
1881     // 1 - Only teachers can add entries
1882     // 3 - Teachers and students can add entries
1883     switch ($data->participants) {
1884         case 1:
1885             foreach ($studentroles as $studentrole) {
1886                 assign_capability('mod/data:writeentry', CAP_PREVENT, $studentrole->id, $context->id);
1887             }
1888             foreach ($teacherroles as $teacherrole) {
1889                 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1890             }
1891             break;
1892         case 3:
1893             foreach ($studentroles as $studentrole) {
1894                 assign_capability('mod/data:writeentry', CAP_ALLOW, $studentrole->id, $context->id);
1895             }
1896             foreach ($teacherroles as $teacherrole) {
1897                 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1898             }
1899             break;
1900     }
1902     // $data->assessed:
1903     // 2 - Only teachers can rate posts
1904     // 1 - Everyone can rate posts
1905     // 0 - No one can rate posts
1906     switch ($data->assessed) {
1907         case 0:
1908             foreach ($studentroles as $studentrole) {
1909                 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1910             }
1911             foreach ($teacherroles as $teacherrole) {
1912                 assign_capability('mod/data:rate', CAP_PREVENT, $teacherrole->id, $context->id);
1913             }
1914             break;
1915         case 1:
1916             foreach ($studentroles as $studentrole) {
1917                 assign_capability('mod/data:rate', CAP_ALLOW, $studentrole->id, $context->id);
1918             }
1919             foreach ($teacherroles as $teacherrole) {
1920                 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1921             }
1922             break;
1923         case 2:
1924             foreach ($studentroles as $studentrole) {
1925                 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1926             }
1927             foreach ($teacherroles as $teacherrole) {
1928                 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1929             }
1930             break;
1931     }
1933     // $data->assesspublic:
1934     // 0 - Students can only see their own ratings
1935     // 1 - Students can see everyone's ratings
1936     switch ($data->assesspublic) {
1937         case 0:
1938             foreach ($studentroles as $studentrole) {
1939                 assign_capability('mod/data:viewrating', CAP_PREVENT, $studentrole->id, $context->id);
1940             }
1941             foreach ($teacherroles as $teacherrole) {
1942                 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1943             }
1944             break;
1945         case 1:
1946             foreach ($studentroles as $studentrole) {
1947                 assign_capability('mod/data:viewrating', CAP_ALLOW, $studentrole->id, $context->id);
1948             }
1949             foreach ($teacherroles as $teacherrole) {
1950                 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1951             }
1952             break;
1953     }
1955     if (empty($cm)) {
1956         $cm = $DB->get_record('course_modules', array('id'=>$cmid));
1957     }
1959     switch ($cm->groupmode) {
1960         case NOGROUPS:
1961             break;
1962         case SEPARATEGROUPS:
1963             foreach ($studentroles as $studentrole) {
1964                 assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id);
1965             }
1966             foreach ($teacherroles as $teacherrole) {
1967                 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1968             }
1969             break;
1970         case VISIBLEGROUPS:
1971             foreach ($studentroles as $studentrole) {
1972                 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id);
1973             }
1974             foreach ($teacherroles as $teacherrole) {
1975                 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1976             }
1977             break;
1978     }
1979     return true;
1982 /**
1983  * Returns the best name to show for a preset
1984  *
1985  * @param string $shortname
1986  * @param  string $path
1987  * @return string
1988  */
1989 function data_preset_name($shortname, $path) {
1991     // We are looking inside the preset itself as a first choice, but also in normal data directory
1992     $string = get_string('modulename', 'datapreset_'.$shortname);
1994     if (substr($string, 0, 1) == '[') {
1995         return $shortname;
1996     } else {
1997         return $string;
1998     }
2001 /**
2002  * Returns an array of all the available presets.
2003  *
2004  * @return array
2005  */
2006 function data_get_available_presets($context) {
2007     global $CFG, $USER;
2009     $presets = array();
2011     // First load the ratings sub plugins that exist within the modules preset dir
2012     if ($dirs = core_component::get_plugin_list('datapreset')) {
2013         foreach ($dirs as $dir=>$fulldir) {
2014             if (is_directory_a_preset($fulldir)) {
2015                 $preset = new stdClass();
2016                 $preset->path = $fulldir;
2017                 $preset->userid = 0;
2018                 $preset->shortname = $dir;
2019                 $preset->name = data_preset_name($dir, $fulldir);
2020                 if (file_exists($fulldir.'/screenshot.jpg')) {
2021                     $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.jpg';
2022                 } else if (file_exists($fulldir.'/screenshot.png')) {
2023                     $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.png';
2024                 } else if (file_exists($fulldir.'/screenshot.gif')) {
2025                     $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.gif';
2026                 }
2027                 $presets[] = $preset;
2028             }
2029         }
2030     }
2031     // Now add to that the site presets that people have saved
2032     $presets = data_get_available_site_presets($context, $presets);
2033     return $presets;
2036 /**
2037  * Gets an array of all of the presets that users have saved to the site.
2038  *
2039  * @param stdClass $context The context that we are looking from.
2040  * @param array $presets
2041  * @return array An array of presets
2042  */
2043 function data_get_available_site_presets($context, array $presets=array()) {
2044     global $USER;
2046     $fs = get_file_storage();
2047     $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2048     $canviewall = has_capability('mod/data:viewalluserpresets', $context);
2049     if (empty($files)) {
2050         return $presets;
2051     }
2052     foreach ($files as $file) {
2053         if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory() || (!$canviewall && $file->get_userid() != $USER->id)) {
2054             continue;
2055         }
2056         $preset = new stdClass;
2057         $preset->path = $file->get_filepath();
2058         $preset->name = trim($preset->path, '/');
2059         $preset->shortname = $preset->name;
2060         $preset->userid = $file->get_userid();
2061         $preset->id = $file->get_id();
2062         $preset->storedfile = $file;
2063         $presets[] = $preset;
2064     }
2065     return $presets;
2068 /**
2069  * Deletes a saved preset.
2070  *
2071  * @param string $name
2072  * @return bool
2073  */
2074 function data_delete_site_preset($name) {
2075     $fs = get_file_storage();
2077     $files = $fs->get_directory_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/');
2078     if (!empty($files)) {
2079         foreach ($files as $file) {
2080             $file->delete();
2081         }
2082     }
2084     $dir = $fs->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/', '.');
2085     if (!empty($dir)) {
2086         $dir->delete();
2087     }
2088     return true;
2091 /**
2092  * Prints the heads for a page
2093  *
2094  * @param stdClass $course
2095  * @param stdClass $cm
2096  * @param stdClass $data
2097  * @param string $currenttab
2098  */
2099 function data_print_header($course, $cm, $data, $currenttab='') {
2101     global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
2103     $PAGE->set_title($data->name);
2104     echo $OUTPUT->header();
2105     echo $OUTPUT->heading(format_string($data->name), 2);
2106     echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
2108     // Groups needed for Add entry tab
2109     $currentgroup = groups_get_activity_group($cm);
2110     $groupmode = groups_get_activity_groupmode($cm);
2112     // Print the tabs
2114     if ($currenttab) {
2115         include('tabs.php');
2116     }
2118     // Print any notices
2120     if (!empty($displaynoticegood)) {
2121         echo $OUTPUT->notification($displaynoticegood, 'notifysuccess');    // good (usually green)
2122     } else if (!empty($displaynoticebad)) {
2123         echo $OUTPUT->notification($displaynoticebad);                     // bad (usuually red)
2124     }
2127 /**
2128  * Can user add more entries?
2129  *
2130  * @param object $data
2131  * @param mixed $currentgroup
2132  * @param int $groupmode
2133  * @param stdClass $context
2134  * @return bool
2135  */
2136 function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
2137     global $USER;
2139     if (empty($context)) {
2140         $cm = get_coursemodule_from_instance('data', $data->id, 0, false, MUST_EXIST);
2141         $context = context_module::instance($cm->id);
2142     }
2144     if (has_capability('mod/data:manageentries', $context)) {
2145         // no entry limits apply if user can manage
2147     } else if (!has_capability('mod/data:writeentry', $context)) {
2148         return false;
2150     } else if (data_atmaxentries($data)) {
2151         return false;
2152     } else if (data_in_readonly_period($data)) {
2153         // Check whether we're in a read-only period
2154         return false;
2155     }
2157     if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2158         return true;
2159     }
2161     if ($currentgroup) {
2162         return groups_is_member($currentgroup);
2163     } else {
2164         //else it might be group 0 in visible mode
2165         if ($groupmode == VISIBLEGROUPS){
2166             return true;
2167         } else {
2168             return false;
2169         }
2170     }
2173 /**
2174  * Check whether the current user is allowed to manage the given record considering manageentries capability,
2175  * data_in_readonly_period() result, ownership (determined by data_isowner()) and manageapproved setting.
2176  * @param mixed $record record object or id
2177  * @param object $data data object
2178  * @param object $context context object
2179  * @return bool returns true if the user is allowd to edit the entry, false otherwise
2180  */
2181 function data_user_can_manage_entry($record, $data, $context) {
2182     global $DB;
2184     if (has_capability('mod/data:manageentries', $context)) {
2185         return true;
2186     }
2188     // Check whether this activity is read-only at present.
2189     $readonly = data_in_readonly_period($data);
2191     if (!$readonly) {
2192         // Get record object from db if just id given like in data_isowner.
2193         // ...done before calling data_isowner() to avoid querying db twice.
2194         if (!is_object($record)) {
2195             if (!$record = $DB->get_record('data_records', array('id' => $record))) {
2196                 return false;
2197             }
2198         }
2199         if (data_isowner($record)) {
2200             if ($data->approval && $record->approved) {
2201                 return $data->manageapproved == 1;
2202             } else {
2203                 return true;
2204             }
2205         }
2206     }
2208     return false;
2211 /**
2212  * Check whether the specified database activity is currently in a read-only period
2213  *
2214  * @param object $data
2215  * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2216  */
2217 function data_in_readonly_period($data) {
2218     $now = time();
2219     if (!$data->timeviewfrom && !$data->timeviewto) {
2220         return false;
2221     } else if (($data->timeviewfrom && $now < $data->timeviewfrom) || ($data->timeviewto && $now > $data->timeviewto)) {
2222         return false;
2223     }
2224     return true;
2227 /**
2228  * @return bool
2229  */
2230 function is_directory_a_preset($directory) {
2231     $directory = rtrim($directory, '/\\') . '/';
2232     $status = file_exists($directory.'singletemplate.html') &&
2233               file_exists($directory.'listtemplate.html') &&
2234               file_exists($directory.'listtemplateheader.html') &&
2235               file_exists($directory.'listtemplatefooter.html') &&
2236               file_exists($directory.'addtemplate.html') &&
2237               file_exists($directory.'rsstemplate.html') &&
2238               file_exists($directory.'rsstitletemplate.html') &&
2239               file_exists($directory.'csstemplate.css') &&
2240               file_exists($directory.'jstemplate.js') &&
2241               file_exists($directory.'preset.xml');
2243     return $status;
2246 /**
2247  * Abstract class used for data preset importers
2248  */
2249 abstract class data_preset_importer {
2251     protected $course;
2252     protected $cm;
2253     protected $module;
2254     protected $directory;
2256     /**
2257      * Constructor
2258      *
2259      * @param stdClass $course
2260      * @param stdClass $cm
2261      * @param stdClass $module
2262      * @param string $directory
2263      */
2264     public function __construct($course, $cm, $module, $directory) {
2265         $this->course = $course;
2266         $this->cm = $cm;
2267         $this->module = $module;
2268         $this->directory = $directory;
2269     }
2271     /**
2272      * Returns the name of the directory the preset is located in
2273      * @return string
2274      */
2275     public function get_directory() {
2276         return basename($this->directory);
2277     }
2279     /**
2280      * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2281      * @param file_storage $filestorage. should be null if using a conventional directory
2282      * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2283      * @param string $dir the directory to look in. null if using the Moodle file storage
2284      * @param string $filename the name of the file we want
2285      * @return string the contents of the file or null if the file doesn't exist.
2286      */
2287     public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2288         if(empty($filestorage) || empty($fileobj)) {
2289             if (substr($dir, -1)!='/') {
2290                 $dir .= '/';
2291             }
2292             if (file_exists($dir.$filename)) {
2293                 return file_get_contents($dir.$filename);
2294             } else {
2295                 return null;
2296             }
2297         } else {
2298             if ($filestorage->file_exists(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename)) {
2299                 $file = $filestorage->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename);
2300                 return $file->get_content();
2301             } else {
2302                 return null;
2303             }
2304         }
2306     }
2307     /**
2308      * Gets the preset settings
2309      * @global moodle_database $DB
2310      * @return stdClass
2311      */
2312     public function get_preset_settings() {
2313         global $DB;
2315         $fs = $fileobj = null;
2316         if (!is_directory_a_preset($this->directory)) {
2317             //maybe the user requested a preset stored in the Moodle file storage
2319             $fs = get_file_storage();
2320             $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2322             //preset name to find will be the final element of the directory
2323             $explodeddirectory = explode('/', $this->directory);
2324             $presettofind = end($explodeddirectory);
2326             //now go through the available files available and see if we can find it
2327             foreach ($files as $file) {
2328                 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory()) {
2329                     continue;
2330                 }
2331                 $presetname = trim($file->get_filepath(), '/');
2332                 if ($presetname==$presettofind) {
2333                     $this->directory = $presetname;
2334                     $fileobj = $file;
2335                 }
2336             }
2338             if (empty($fileobj)) {
2339                 print_error('invalidpreset', 'data', '', $this->directory);
2340             }
2341         }
2343         $allowed_settings = array(
2344             'intro',
2345             'comments',
2346             'requiredentries',
2347             'requiredentriestoview',
2348             'maxentries',
2349             'rssarticles',
2350             'approval',
2351             'defaultsortdir',
2352             'defaultsort');
2354         $result = new stdClass;
2355         $result->settings = new stdClass;
2356         $result->importfields = array();
2357         $result->currentfields = $DB->get_records('data_fields', array('dataid'=>$this->module->id));
2358         if (!$result->currentfields) {
2359             $result->currentfields = array();
2360         }
2363         /* Grab XML */
2364         $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory,'preset.xml');
2365         $parsedxml = xmlize($presetxml, 0);
2367         /* First, do settings. Put in user friendly array. */
2368         $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
2369         $result->settings = new StdClass();
2370         foreach ($settingsarray as $setting => $value) {
2371             if (!is_array($value) || !in_array($setting, $allowed_settings)) {
2372                 // unsupported setting
2373                 continue;
2374             }
2375             $result->settings->$setting = $value[0]['#'];
2376         }
2378         /* Now work out fields to user friendly array */
2379         $fieldsarray = $parsedxml['preset']['#']['field'];
2380         foreach ($fieldsarray as $field) {
2381             if (!is_array($field)) {
2382                 continue;
2383             }
2384             $f = new StdClass();
2385             foreach ($field['#'] as $param => $value) {
2386                 if (!is_array($value)) {
2387                     continue;
2388                 }
2389                 $f->$param = $value[0]['#'];
2390             }
2391             $f->dataid = $this->module->id;
2392             $f->type = clean_param($f->type, PARAM_ALPHA);
2393             $result->importfields[] = $f;
2394         }
2395         /* Now add the HTML templates to the settings array so we can update d */
2396         $result->settings->singletemplate     = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"singletemplate.html");
2397         $result->settings->listtemplate       = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplate.html");
2398         $result->settings->listtemplateheader = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplateheader.html");
2399         $result->settings->listtemplatefooter = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplatefooter.html");
2400         $result->settings->addtemplate        = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"addtemplate.html");
2401         $result->settings->rsstemplate        = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstemplate.html");
2402         $result->settings->rsstitletemplate   = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstitletemplate.html");
2403         $result->settings->csstemplate        = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"csstemplate.css");
2404         $result->settings->jstemplate         = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"jstemplate.js");
2405         $result->settings->asearchtemplate    = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"asearchtemplate.html");
2407         $result->settings->instance = $this->module->id;
2408         return $result;
2409     }
2411     /**
2412      * Import the preset into the given database module
2413      * @return bool
2414      */
2415     function import($overwritesettings) {
2416         global $DB, $CFG;
2418         $params = $this->get_preset_settings();
2419         $settings = $params->settings;
2420         $newfields = $params->importfields;
2421         $currentfields = $params->currentfields;
2422         $preservedfields = array();
2424         /* Maps fields and makes new ones */
2425         if (!empty($newfields)) {
2426             /* We require an injective mapping, and need to know what to protect */
2427             foreach ($newfields as $nid => $newfield) {
2428                 $cid = optional_param("field_$nid", -1, PARAM_INT);
2429                 if ($cid == -1) {
2430                     continue;
2431                 }
2432                 if (array_key_exists($cid, $preservedfields)){
2433                     print_error('notinjectivemap', 'data');
2434                 }
2435                 else $preservedfields[$cid] = true;
2436             }
2438             foreach ($newfields as $nid => $newfield) {
2439                 $cid = optional_param("field_$nid", -1, PARAM_INT);
2441                 /* A mapping. Just need to change field params. Data kept. */
2442                 if ($cid != -1 and isset($currentfields[$cid])) {
2443                     $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->module);
2444                     foreach ($newfield as $param => $value) {
2445                         if ($param != "id") {
2446                             $fieldobject->field->$param = $value;
2447                         }
2448                     }
2449                     unset($fieldobject->field->similarfield);
2450                     $fieldobject->update_field();
2451                     unset($fieldobject);
2452                 } else {
2453                     /* Make a new field */
2454                     include_once("field/$newfield->type/field.class.php");
2456                     if (!isset($newfield->description)) {
2457                         $newfield->description = '';
2458                     }
2459                     $classname = 'data_field_'.$newfield->type;
2460                     $fieldclass = new $classname($newfield, $this->module);
2461                     $fieldclass->insert_field();
2462                     unset($fieldclass);
2463                 }
2464             }
2465         }
2467         /* Get rid of all old unused data */
2468         if (!empty($preservedfields)) {
2469             foreach ($currentfields as $cid => $currentfield) {
2470                 if (!array_key_exists($cid, $preservedfields)) {
2471                     /* Data not used anymore so wipe! */
2472                     print "Deleting field $currentfield->name<br />";
2474                     $id = $currentfield->id;
2475                     //Why delete existing data records and related comments/ratings??
2476                     $DB->delete_records('data_content', array('fieldid'=>$id));
2477                     $DB->delete_records('data_fields', array('id'=>$id));
2478                 }
2479             }
2480         }
2482         // handle special settings here
2483         if (!empty($settings->defaultsort)) {
2484             if (is_numeric($settings->defaultsort)) {
2485                 // old broken value
2486                 $settings->defaultsort = 0;
2487             } else {
2488                 $settings->defaultsort = (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module->id, 'name'=>$settings->defaultsort));
2489             }
2490         } else {
2491             $settings->defaultsort = 0;
2492         }
2494         // do we want to overwrite all current database settings?
2495         if ($overwritesettings) {
2496             // all supported settings
2497             $overwrite = array_keys((array)$settings);
2498         } else {
2499             // only templates and sorting
2500             $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2501                                'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
2502                                'asearchtemplate', 'defaultsortdir', 'defaultsort');
2503         }
2505         // now overwrite current data settings
2506         foreach ($this->module as $prop=>$unused) {
2507             if (in_array($prop, $overwrite)) {
2508                 $this->module->$prop = $settings->$prop;
2509             }
2510         }
2512         data_update_instance($this->module);
2514         return $this->cleanup();
2515     }
2517     /**
2518      * Any clean up routines should go here
2519      * @return bool
2520      */
2521     public function cleanup() {
2522         return true;
2523     }
2526 /**
2527  * Data preset importer for uploaded presets
2528  */
2529 class data_preset_upload_importer extends data_preset_importer {
2530     public function __construct($course, $cm, $module, $filepath) {
2531         global $USER;
2532         if (is_file($filepath)) {
2533             $fp = get_file_packer();
2534             if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2535                 fulldelete($filepath);
2536             }
2537             $filepath .= '_extracted';
2538         }
2539         parent::__construct($course, $cm, $module, $filepath);
2540     }
2541     public function cleanup() {
2542         return fulldelete($this->directory);
2543     }
2546 /**
2547  * Data preset importer for existing presets
2548  */
2549 class data_preset_existing_importer extends data_preset_importer {
2550     protected $userid;
2551     public function __construct($course, $cm, $module, $fullname) {
2552         global $USER;
2553         list($userid, $shortname) = explode('/', $fullname, 2);
2554         $context = context_module::instance($cm->id);
2555         if ($userid && ($userid != $USER->id) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2556            throw new coding_exception('Invalid preset provided');
2557         }
2559         $this->userid = $userid;
2560         $filepath = data_preset_path($course, $userid, $shortname);
2561         parent::__construct($course, $cm, $module, $filepath);
2562     }
2563     public function get_userid() {
2564         return $this->userid;
2565     }
2568 /**
2569  * @global object
2570  * @global object
2571  * @param object $course
2572  * @param int $userid
2573  * @param string $shortname
2574  * @return string
2575  */
2576 function data_preset_path($course, $userid, $shortname) {
2577     global $USER, $CFG;
2579     $context = context_course::instance($course->id);
2581     $userid = (int)$userid;
2583     $path = null;
2584     if ($userid > 0 && ($userid == $USER->id || has_capability('mod/data:viewalluserpresets', $context))) {
2585         $path = $CFG->dataroot.'/data/preset/'.$userid.'/'.$shortname;
2586     } else if ($userid == 0) {
2587         $path = $CFG->dirroot.'/mod/data/preset/'.$shortname;
2588     } else if ($userid < 0) {
2589         $path = $CFG->tempdir.'/data/'.-$userid.'/'.$shortname;
2590     }
2592     return $path;
2595 /**
2596  * Implementation of the function for printing the form elements that control
2597  * whether the course reset functionality affects the data.
2598  *
2599  * @param $mform form passed by reference
2600  */
2601 function data_reset_course_form_definition(&$mform) {
2602     $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2603     $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2605     $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2606     $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2608     $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2609     $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2611     $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2612     $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
2615 /**
2616  * Course reset form defaults.
2617  * @return array
2618  */
2619 function data_reset_course_form_defaults($course) {
2620     return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2623 /**
2624  * Removes all grades from gradebook
2625  *
2626  * @global object
2627  * @global object
2628  * @param int $courseid
2629  * @param string $type optional type
2630  */
2631 function data_reset_gradebook($courseid, $type='') {
2632     global $CFG, $DB;
2634     $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
2635               FROM {data} d, {course_modules} cm, {modules} m
2636              WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
2638     if ($datas = $DB->get_records_sql($sql, array($courseid))) {
2639         foreach ($datas as $data) {
2640             data_grade_item_update($data, 'reset');
2641         }
2642     }
2645 /**
2646  * Actual implementation of the reset course functionality, delete all the
2647  * data responses for course $data->courseid.
2648  *
2649  * @global object
2650  * @global object
2651  * @param object $data the data submitted from the reset course.
2652  * @return array status array
2653  */
2654 function data_reset_userdata($data) {
2655     global $CFG, $DB;
2656     require_once($CFG->libdir.'/filelib.php');
2657     require_once($CFG->dirroot.'/rating/lib.php');
2659     $componentstr = get_string('modulenameplural', 'data');
2660     $status = array();
2662     $allrecordssql = "SELECT r.id
2663                         FROM {data_records} r
2664                              INNER JOIN {data} d ON r.dataid = d.id
2665                        WHERE d.course = ?";
2667     $alldatassql = "SELECT d.id
2668                       FROM {data} d
2669                      WHERE d.course=?";
2671     $rm = new rating_manager();
2672     $ratingdeloptions = new stdClass;
2673     $ratingdeloptions->component = 'mod_data';
2674     $ratingdeloptions->ratingarea = 'entry';
2676     // Set the file storage - may need it to remove files later.
2677     $fs = get_file_storage();
2679     // delete entries if requested
2680     if (!empty($data->reset_data)) {
2681         $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2682         $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid));
2683         $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid));
2685         if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2686             foreach ($datas as $dataid=>$unused) {
2687                 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2688                     continue;
2689                 }
2690                 $datacontext = context_module::instance($cm->id);
2692                 // Delete any files that may exist.
2693                 $fs->delete_area_files($datacontext->id, 'mod_data', 'content');
2695                 $ratingdeloptions->contextid = $datacontext->id;
2696                 $rm->delete_ratings($ratingdeloptions);
2697             }
2698         }
2700         if (empty($data->reset_gradebook_grades)) {
2701             // remove all grades from gradebook
2702             data_reset_gradebook($data->courseid);
2703         }
2704         $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2705     }
2707     // remove entries by users not enrolled into course
2708     if (!empty($data->reset_data_notenrolled)) {
2709         $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
2710                          FROM {data_records} r
2711                               JOIN {data} d ON r.dataid = d.id
2712                               LEFT JOIN {user} u ON r.userid = u.id
2713                         WHERE d.course = ? AND r.userid > 0";
2715         $course_context = context_course::instance($data->courseid);
2716         $notenrolled = array();
2717         $fields = array();
2718         $rs = $DB->get_recordset_sql($recordssql, array($data->courseid));
2719         foreach ($rs as $record) {
2720             if (array_key_exists($record->userid, $notenrolled) or !$record->userexists or $record->userdeleted
2721               or !is_enrolled($course_context, $record->userid)) {
2722                 //delete ratings
2723                 if (!$cm = get_coursemodule_from_instance('data', $record->dataid)) {
2724                     continue;
2725                 }
2726                 $datacontext = context_module::instance($cm->id);
2727                 $ratingdeloptions->contextid = $datacontext->id;
2728                 $ratingdeloptions->itemid = $record->id;
2729                 $rm->delete_ratings($ratingdeloptions);
2731                 // Delete any files that may exist.
2732                 if ($contents = $DB->get_records('data_content', array('recordid' => $record->id), '', 'id')) {
2733                     foreach ($contents as $content) {
2734                         $fs->delete_area_files($datacontext->id, 'mod_data', 'content', $content->id);
2735                     }
2736                 }
2737                 $notenrolled[$record->userid] = true;
2739                 $DB->delete_records('comments', array('itemid' => $record->id, 'commentarea' => 'database_entry'));
2740                 $DB->delete_records('data_content', array('recordid' => $record->id));
2741                 $DB->delete_records('data_records', array('id' => $record->id));
2742             }
2743         }
2744         $rs->close();
2745         $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
2746     }
2748     // remove all ratings
2749     if (!empty($data->reset_data_ratings)) {
2750         if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2751             foreach ($datas as $dataid=>$unused) {
2752                 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2753                     continue;
2754                 }
2755                 $datacontext = context_module::instance($cm->id);
2757                 $ratingdeloptions->contextid = $datacontext->id;
2758                 $rm->delete_ratings($ratingdeloptions);
2759             }
2760         }
2762         if (empty($data->reset_gradebook_grades)) {
2763             // remove all grades from gradebook
2764             data_reset_gradebook($data->courseid);
2765         }
2767         $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2768     }
2770     // remove all comments
2771     if (!empty($data->reset_data_comments)) {
2772         $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2773         $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2774     }
2776     // updating dates - shift may be negative too
2777     if ($data->timeshift) {
2778         shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto'), $data->timeshift, $data->courseid);
2779         $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2780     }
2782     return $status;
2785 /**
2786  * Returns all other caps used in module
2787  *
2788  * @return array
2789  */
2790 function data_get_extra_capabilities() {
2791     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');
2794 /**
2795  * @param string $feature FEATURE_xx constant for requested feature
2796  * @return mixed True if module supports feature, null if doesn't know
2797  */
2798 function data_supports($feature) {
2799     switch($feature) {
2800         case FEATURE_GROUPS:                  return true;
2801         case FEATURE_GROUPINGS:               return true;
2802         case FEATURE_MOD_INTRO:               return true;
2803         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
2804         case FEATURE_GRADE_HAS_GRADE:         return true;
2805         case FEATURE_GRADE_OUTCOMES:          return true;
2806         case FEATURE_RATE:                    return true;
2807         case FEATURE_BACKUP_MOODLE2:          return true;
2808         case FEATURE_SHOW_DESCRIPTION:        return true;
2810         default: return null;
2811     }
2813 /**
2814  * @global object
2815  * @param array $export
2816  * @param string $delimiter_name
2817  * @param object $database
2818  * @param int $count
2819  * @param bool $return
2820  * @return string|void
2821  */
2822 function data_export_csv($export, $delimiter_name, $database, $count, $return=false) {
2823     global $CFG;
2824     require_once($CFG->libdir . '/csvlib.class.php');
2826     $filename = $database . '-' . $count . '-record';
2827     if ($count > 1) {
2828         $filename .= 's';
2829     }
2830     if ($return) {
2831         return csv_export_writer::print_array($export, $delimiter_name, '"', true);
2832     } else {
2833         csv_export_writer::download_array($filename, $export, $delimiter_name);
2834     }
2837 /**
2838  * @global object
2839  * @param array $export
2840  * @param string $dataname
2841  * @param int $count
2842  * @return string
2843  */
2844 function data_export_xls($export, $dataname, $count) {
2845     global $CFG;
2846     require_once("$CFG->libdir/excellib.class.php");
2847     $filename = clean_filename("{$dataname}-{$count}_record");
2848     if ($count > 1) {
2849         $filename .= 's';
2850     }
2851     $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2852     $filename .= '.xls';
2854     $filearg = '-';
2855     $workbook = new MoodleExcelWorkbook($filearg);
2856     $workbook->send($filename);
2857     $worksheet = array();
2858     $worksheet[0] = $workbook->add_worksheet('');
2859     $rowno = 0;
2860     foreach ($export as $row) {
2861         $colno = 0;
2862         foreach($row as $col) {
2863             $worksheet[0]->write($rowno, $colno, $col);
2864             $colno++;
2865         }
2866         $rowno++;
2867     }
2868     $workbook->close();
2869     return $filename;
2872 /**
2873  * @global object
2874  * @param array $export
2875  * @param string $dataname
2876  * @param int $count
2877  * @param string
2878  */
2879 function data_export_ods($export, $dataname, $count) {
2880     global $CFG;
2881     require_once("$CFG->libdir/odslib.class.php");
2882     $filename = clean_filename("{$dataname}-{$count}_record");
2883     if ($count > 1) {
2884         $filename .= 's';
2885     }
2886     $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2887     $filename .= '.ods';
2888     $filearg = '-';
2889     $workbook = new MoodleODSWorkbook($filearg);
2890     $workbook->send($filename);
2891     $worksheet = array();
2892     $worksheet[0] = $workbook->add_worksheet('');
2893     $rowno = 0;
2894     foreach ($export as $row) {
2895         $colno = 0;
2896         foreach($row as $col) {
2897             $worksheet[0]->write($rowno, $colno, $col);
2898             $colno++;
2899         }
2900         $rowno++;
2901     }
2902     $workbook->close();
2903     return $filename;
2906 /**
2907  * @global object
2908  * @param int $dataid
2909  * @param array $fields
2910  * @param array $selectedfields
2911  * @param int $currentgroup group ID of the current group. This is used for
2912  * exporting data while maintaining group divisions.
2913  * @param object $context the context in which the operation is performed (for capability checks)
2914  * @param bool $userdetails whether to include the details of the record author
2915  * @param bool $time whether to include time created/modified
2916  * @param bool $approval whether to include approval status
2917  * @return array
2918  */
2919 function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0, $context=null,
2920                              $userdetails=false, $time=false, $approval=false) {
2921     global $DB;
2923     if (is_null($context)) {
2924         $context = context_system::instance();
2925     }
2926     // exporting user data needs special permission
2927     $userdetails = $userdetails && has_capability('mod/data:exportuserinfo', $context);
2929     $exportdata = array();
2931     // populate the header in first row of export
2932     foreach($fields as $key => $field) {
2933         if (!in_array($field->field->id, $selectedfields)) {
2934             // ignore values we aren't exporting
2935             unset($fields[$key]);
2936         } else {
2937             $exportdata[0][] = $field->field->name;
2938         }
2939     }
2940     if ($userdetails) {
2941         $exportdata[0][] = get_string('user');
2942         $exportdata[0][] = get_string('username');
2943         $exportdata[0][] = get_string('email');
2944     }
2945     if ($time) {
2946         $exportdata[0][] = get_string('timeadded', 'data');
2947         $exportdata[0][] = get_string('timemodified', 'data');
2948     }
2949     if ($approval) {
2950         $exportdata[0][] = get_string('approved', 'data');
2951     }
2953     $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
2954     ksort($datarecords);
2955     $line = 1;
2956     foreach($datarecords as $record) {
2957         // get content indexed by fieldid
2958         if ($currentgroup) {
2959             $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 = ?';
2960             $where = array($record->id, $currentgroup);
2961         } else {
2962             $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
2963             $where = array($record->id);
2964         }
2966         if( $content = $DB->get_records_sql($select, $where) ) {
2967             foreach($fields as $field) {
2968                 $contents = '';
2969                 if(isset($content[$field->field->id])) {
2970                     $contents = $field->export_text_value($content[$field->field->id]);
2971                 }
2972                 $exportdata[$line][] = $contents;
2973             }
2974             if ($userdetails) { // Add user details to the export data
2975                 $userdata = get_complete_user_data('id', $record->userid);
2976                 $exportdata[$line][] = fullname($userdata);
2977                 $exportdata[$line][] = $userdata->username;
2978                 $exportdata[$line][] = $userdata->email;
2979             }
2980             if ($time) { // Add time added / modified
2981                 $exportdata[$line][] = userdate($record->timecreated);
2982                 $exportdata[$line][] = userdate($record->timemodified);
2983             }
2984             if ($approval) { // Add approval status
2985                 $exportdata[$line][] = (int) $record->approved;
2986             }
2987         }
2988         $line++;
2989     }
2990     $line--;
2991     return $exportdata;
2994 ////////////////////////////////////////////////////////////////////////////////
2995 // File API                                                                   //
2996 ////////////////////////////////////////////////////////////////////////////////
2998 /**
2999  * Lists all browsable file areas
3000  *
3001  * @package  mod_data
3002  * @category files
3003  * @param stdClass $course course object
3004  * @param stdClass $cm course module object
3005  * @param stdClass $context context object
3006  * @return array
3007  */
3008 function data_get_file_areas($course, $cm, $context) {
3009     return array('content' => get_string('areacontent', 'mod_data'));
3012 /**
3013  * File browsing support for data module.
3014  *
3015  * @param file_browser $browser
3016  * @param array $areas
3017  * @param stdClass $course
3018  * @param cm_info $cm
3019  * @param context $context
3020  * @param string $filearea
3021  * @param int $itemid
3022  * @param string $filepath
3023  * @param string $filename
3024  * @return file_info_stored file_info_stored instance or null if not found
3025  */
3026 function data_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
3027     global $CFG, $DB, $USER;
3029     if ($context->contextlevel != CONTEXT_MODULE) {
3030         return null;
3031     }
3033     if (!isset($areas[$filearea])) {
3034         return null;
3035     }
3037     if (is_null($itemid)) {
3038         require_once($CFG->dirroot.'/mod/data/locallib.php');
3039         return new data_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
3040     }
3042     if (!$content = $DB->get_record('data_content', array('id'=>$itemid))) {
3043         return null;
3044     }
3046     if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
3047         return null;
3048     }
3050     if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
3051         return null;
3052     }
3054     if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
3055         return null;
3056     }
3058     //check if approved
3059     if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3060         return null;
3061     }
3063     // group access
3064     if ($record->groupid) {
3065         $groupmode = groups_get_activity_groupmode($cm, $course);
3066         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3067             if (!groups_is_member($record->groupid)) {
3068                 return null;
3069             }
3070         }
3071     }
3073     $fieldobj = data_get_field($field, $data, $cm);
3075     $filepath = is_null($filepath) ? '/' : $filepath;
3076     $filename = is_null($filename) ? '.' : $filename;
3077     if (!$fieldobj->file_ok($filepath.$filename)) {
3078         return null;
3079     }
3081     $fs = get_file_storage();
3082     if (!($storedfile = $fs->get_file($context->id, 'mod_data', $filearea, $itemid, $filepath, $filename))) {
3083         return null;
3084     }
3086     // Checks to see if the user can manage files or is the owner.
3087     // TODO MDL-33805 - Do not use userid here and move the capability check above.
3088     if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
3089         return null;
3090     }
3092     $urlbase = $CFG->wwwroot.'/pluginfile.php';
3094     return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
3097 /**
3098  * Serves the data attachments. Implements needed access control ;-)
3099  *
3100  * @package  mod_data
3101  * @category files
3102  * @param stdClass $course course object
3103  * @param stdClass $cm course module object
3104  * @param stdClass $context context object
3105  * @param string $filearea file area
3106  * @param array $args extra arguments
3107  * @param bool $forcedownload whether or not force download
3108  * @param array $options additional options affecting the file serving
3109  * @return bool false if file not found, does not return if found - justsend the file
3110  */
3111 function data_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3112     global $CFG, $DB;
3114     if ($context->contextlevel != CONTEXT_MODULE) {
3115         return false;
3116     }
3118     require_course_login($course, true, $cm);
3120     if ($filearea === 'content') {
3121         $contentid = (int)array_shift($args);
3123         if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
3124             return false;
3125         }
3127         if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
3128             return false;
3129         }
3131         if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
3132             return false;
3133         }
3135         if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
3136             return false;
3137         }
3139         if ($data->id != $cm->instance) {
3140             // hacker attempt - context does not match the contentid
3141             return false;
3142         }
3144         //check if approved
3145         if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3146             return false;
3147         }
3149         // group access
3150         if ($record->groupid) {
3151             $groupmode = groups_get_activity_groupmode($cm, $course);
3152             if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3153                 if (!groups_is_member($record->groupid)) {
3154                     return false;
3155                 }
3156             }
3157         }
3159         $fieldobj = data_get_field($field, $data, $cm);
3161         $relativepath = implode('/', $args);
3162         $fullpath = "/$context->id/mod_data/content/$content->id/$relativepath";
3164         if (!$fieldobj->file_ok($relativepath)) {
3165             return false;
3166         }
3168         $fs = get_file_storage();
3169         if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3170             return false;
3171         }
3173         // finally send the file
3174         send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
3175     }
3177     return false;
3181 function data_extend_navigation($navigation, $course, $module, $cm) {
3182     global $CFG, $OUTPUT, $USER, $DB;
3184     $rid = optional_param('rid', 0, PARAM_INT);
3186     $data = $DB->get_record('data', array('id'=>$cm->instance));
3187     $currentgroup = groups_get_activity_group($cm);
3188     $groupmode = groups_get_activity_groupmode($cm);
3190      $numentries = data_numentries($data);
3191     /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
3192     if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !has_capability('mod/data:manageentries', context_module::instance($cm->id))) {
3193         $data->entriesleft = $data->requiredentries - $numentries;
3194         $entriesnode = $navigation->add(get_string('entrieslefttoadd', 'data', $data));
3195         $entriesnode->add_class('note');
3196     }
3198     $navigation->add(get_string('list', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance)));
3199     if (!empty($rid)) {
3200         $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'rid'=>$rid)));
3201     } else {
3202         $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'single')));
3203     }
3204     $navigation->add(get_string('search', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'asearch')));
3207 /**
3208  * Adds module specific settings to the settings block
3209  *
3210  * @param settings_navigation $settings The settings navigation object
3211  * @param navigation_node $datanode The node to add module settings to
3212  */
3213 function data_extend_settings_navigation(settings_navigation $settings, navigation_node $datanode) {
3214     global $PAGE, $DB, $CFG, $USER;
3216     $data = $DB->get_record('data', array("id" => $PAGE->cm->instance));
3218     $currentgroup = groups_get_activity_group($PAGE->cm);
3219     $groupmode = groups_get_activity_groupmode($PAGE->cm);
3221     if (data_user_can_add_entry($data, $currentgroup, $groupmode, $PAGE->cm->context)) { // took out participation list here!
3222         if (empty($editentry)) { //TODO: undefined
3223             $addstring = get_string('add', 'data');
3224         } else {
3225             $addstring = get_string('editentry', 'data');
3226         }
3227         $datanode->add($addstring, new moodle_url('/mod/data/edit.php', array('d'=>$PAGE->cm->instance)));
3228     }
3230     if (has_capability(DATA_CAP_EXPORT, $PAGE->cm->context)) {
3231         // The capability required to Export database records is centrally defined in 'lib.php'
3232         // and should be weaker than those required to edit Templates, Fields and Presets.
3233         $datanode->add(get_string('exportentries', 'data'), new moodle_url('/mod/data/export.php', array('d'=>$data->id)));
3234     }
3235     if (has_capability('mod/data:manageentries', $PAGE->cm->context)) {
3236         $datanode->add(get_string('importentries', 'data'), new moodle_url('/mod/data/import.php', array('d'=>$data->id)));
3237     }
3239     if (has_capability('mod/data:managetemplates', $PAGE->cm->context)) {
3240         $currenttab = '';
3241         if ($currenttab == 'list') {
3242             $defaultemplate = 'listtemplate';
3243         } else if ($currenttab == 'add') {
3244             $defaultemplate = 'addtemplate';
3245         } else if ($currenttab == 'asearch') {
3246             $defaultemplate = 'asearchtemplate';
3247         } else {
3248             $defaultemplate = 'singletemplate';
3249         }
3251         $templates = $datanode->add(get_string('templates', 'data'));
3253         $templatelist = array ('listtemplate', 'singletemplate', 'asearchtemplate', 'addtemplate', 'rsstemplate', 'csstemplate', 'jstemplate');
3254         foreach ($templatelist as $template) {
3255             $templates->add(get_string($template, 'data'), new moodle_url('/mod/data/templates.php', array('d'=>$data->id,'mode'=>$template)));
3256         }
3258         $datanode->add(get_string('fields', 'data'), new moodle_url('/mod/data/field.php', array('d'=>$data->id)));
3259         $datanode->add(get_string('presets', 'data'), new moodle_url('/mod/data/preset.php', array('d'=>$data->id)));
3260     }
3262     if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
3263         require_once("$CFG->libdir/rsslib.php");
3265         $string = get_string('rsstype','forum');
3267         $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_data', $data->id));
3268         $datanode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
3269     }
3272 /**
3273  * Save the database configuration as a preset.
3274  *
3275  * @param stdClass $course The course the database module belongs to.
3276  * @param stdClass $cm The course module record
3277  * @param stdClass $data The database record
3278  * @param string $path
3279  * @return bool
3280  */
3281 function data_presets_save($course, $cm, $data, $path) {
3282     global $USER;
3283     $fs = get_file_storage();
3284     $filerecord = new stdClass;
3285     $filerecord->contextid = DATA_PRESET_CONTEXT;
3286     $filerecord->component = DATA_PRESET_COMPONENT;
3287     $filerecord->filearea = DATA_PRESET_FILEAREA;
3288     $filerecord->itemid = 0;
3289     $filerecord->filepath = '/'.$path.'/';
3290     $filerecord->userid = $USER->id;
3292     $filerecord->filename = 'preset.xml';
3293     $fs->create_file_from_string($filerecord, data_presets_generate_xml($course, $cm, $data));
3295     $filerecord->filename = 'singletemplate.html';
3296     $fs->create_file_from_string($filerecord, $data->singletemplate);
3298     $filerecord->filename = 'listtemplateheader.html';
3299     $fs->create_file_from_string($filerecord, $data->listtemplateheader);
3301     $filerecord->filename = 'listtemplate.html';
3302     $fs->create_file_from_string($filerecord, $data->listtemplate);
3304     $filerecord->filename = 'listtemplatefooter.html';
3305     $fs->create_file_from_string($filerecord, $data->listtemplatefooter);
3307     $filerecord->filename = 'addtemplate.html';
3308     $fs->create_file_from_string($filerecord, $data->addtemplate);
3310     $filerecord->filename = 'rsstemplate.html';
3311     $fs->create_file_from_string($filerecord, $data->rsstemplate);
3313     $filerecord->filename = 'rsstitletemplate.html';
3314     $fs->create_file_from_string($filerecord, $data->rsstitletemplate);
3316     $filerecord->filename = 'csstemplate.css';
3317     $fs->create_file_from_string($filerecord, $data->csstemplate);
3319     $filerecord->filename = 'jstemplate.js';
3320     $fs->create_file_from_string($filerecord, $data->jstemplate);
3322     $filerecord->filename = 'asearchtemplate.html';
3323     $fs->create_file_from_string($filerecord, $data->asearchtemplate);
3325     return true;
3328 /**
3329  * Generates the XML for the database module provided
3330  *
3331  * @global moodle_database $DB
3332  * @param stdClass $course The course the database module belongs to.
3333  * @param stdClass $cm The course module record
3334  * @param stdClass $data The database record
3335  * @return string The XML for the preset
3336  */
3337 function data_presets_generate_xml($course, $cm, $data) {
3338     global $DB;
3340     // Assemble "preset.xml":
3341     $presetxmldata = "<preset>\n\n";
3343     // Raw settings are not preprocessed during saving of presets
3344     $raw_settings = array(
3345         'intro',
3346         'comments',
3347         'requiredentries',
3348         'requiredentriestoview',
3349         'maxentries',
3350         'rssarticles',
3351         'approval',
3352         'manageapproved',
3353         'defaultsortdir'
3354     );
3356     $presetxmldata .= "<settings>\n";
3357     // First, settings that do not require any conversion
3358     foreach ($raw_settings as $setting) {
3359         $presetxmldata .= "<$setting>" . htmlspecialchars($data->$setting) . "</$setting>\n";
3360     }
3362     // Now specific settings
3363     if ($data->defaultsort > 0 && $sortfield = data_get_field_from_id($data->defaultsort, $data)) {
3364         $presetxmldata .= '<defaultsort>' . htmlspecialchars($sortfield->field->name) . "</defaultsort>\n";
3365     } else {
3366         $presetxmldata .= "<defaultsort>0</defaultsort>\n";
3367     }
3368     $presetxmldata .= "</settings>\n\n";
3369     // Now for the fields. Grab all that are non-empty
3370     $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
3371     ksort($fields);
3372     if (!empty($fields)) {
3373         foreach ($fields as $field) {
3374             $presetxmldata .= "<field>\n";
3375             foreach ($field as $key => $value) {
3376                 if ($value != '' && $key != 'id' && $key != 'dataid') {
3377                     $presetxmldata .= "<$key>" . htmlspecialchars($value) . "</$key>\n";
3378                 }
3379             }
3380             $presetxmldata .= "</field>\n\n";
3381         }
3382     }
3383     $presetxmldata .= '</preset>';
3384     return $presetxmldata;
3387 function data_presets_export($course, $cm, $data, $tostorage=false) {
3388     global $CFG, $DB;
3390     $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi");
3391     $exportsubdir = "mod_data/presetexport/$presetname";
3392     make_temp_directory($exportsubdir);
3393     $exportdir = "$CFG->tempdir/$exportsubdir";
3395     // Assemble "preset.xml":
3396     $presetxmldata = data_presets_generate_xml($course, $cm, $data);
3398     // After opening a file in write mode, close it asap
3399     $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
3400     fwrite($presetxmlfile, $presetxmldata);
3401     fclose($presetxmlfile);
3403     // Now write the template files
3404     $singletemplate = fopen($exportdir . '/singletemplate.html', 'w');
3405     fwrite($singletemplate, $data->singletemplate);
3406     fclose($singletemplate);
3408     $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w');
3409     fwrite($listtemplateheader, $data->listtemplateheader);
3410     fclose($listtemplateheader);
3412     $listtemplate = fopen($exportdir . '/listtemplate.html', 'w');
3413     fwrite($listtemplate, $data->listtemplate);
3414     fclose($listtemplate);
3416     $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w');
3417     fwrite($listtemplatefooter, $data->listtemplatefooter);
3418     fclose($listtemplatefooter);
3420     $addtemplate = fopen($exportdir . '/addtemplate.html', 'w');
3421     fwrite($addtemplate, $data->addtemplate);
3422     fclose($addtemplate);
3424     $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w');
3425     fwrite($rsstemplate, $data->rsstemplate);
3426     fclose($rsstemplate);
3428     $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w');
3429     fwrite($rsstitletemplate, $data->rsstitletemplate);
3430     fclose($rsstitletemplate);
3432     $csstemplate = fopen($exportdir . '/csstemplate.css', 'w');
3433     fwrite($csstemplate, $data->csstemplate);
3434     fclose($csstemplate);
3436     $jstemplate = fopen($exportdir . '/jstemplate.js', 'w');
3437     fwrite($jstemplate, $data->jstemplate);
3438     fclose($jstemplate);
3440     $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w');
3441     fwrite($asearchtemplate, $data->asearchtemplate);
3442     fclose($asearchtemplate);
3444     // Check if all files have been generated
3445     if (! is_directory_a_preset($exportdir)) {
3446         print_error('generateerror', 'data');
3447     }
3449     $filenames = array(
3450         'preset.xml',
3451         'singletemplate.html',
3452         'listtemplateheader.html',
3453         'listtemplate.html',
3454         'listtemplatefooter.html',
3455         'addtemplate.html',
3456         'rsstemplate.html',
3457         'rsstitletemplate.html',
3458         'csstemplate.css',
3459         'jstemplate.js',
3460         'asearchtemplate.html'
3461     );
3463     $filelist = array();
3464     foreach ($filenames as $filename) {
3465         $filelist[$filename] = $exportdir . '/' . $filename;
3466     }
3468     $exportfile = $exportdir.'.zip';
3469     file_exists($exportfile) && unlink($exportfile);
3471     $fp = get_file_packer('application/zip');
3472     $fp->archive_to_pathname($filelist, $exportfile);
3474     foreach ($filelist as $file) {
3475         unlink($file);
3476     }
3477     rmdir($exportdir);
3479     // Return the full path to the exported preset file:
3480     return $exportfile;
3483 /**
3484  * Running addtional permission check on plugin, for example, plugins
3485  * may have switch to turn on/off comments option, this callback will
3486  * affect UI display, not like pluginname_comment_validate only throw
3487  * exceptions.
3488  * Capability check has been done in comment->check_permissions(), we
3489  * don't need to do it again here.
3490  *
3491  * @package  mod_data
3492  * @category comment
3493  *
3494  * @param stdClass $comment_param {
3495  *              context  => context the context object
3496  *              courseid => int course id
3497  *              cm       => stdClass course module object
3498  *              commentarea => string comment area
3499  *              itemid      => int itemid
3500  * }
3501  * @return array
3502  */
3503 function data_comment_permissions($comment_param) {
3504     global $CFG, $DB;
3505     if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3506         throw new comment_exception('invalidcommentitemid');
3507     }
3508     if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3509         throw new comment_exception('invalidid', 'data');
3510     }
3511     if ($data->comments) {
3512         return array('post'=>true, 'view'=>true);
3513     } else {
3514         return array('post'=>false, 'view'=>false);
3515     }
3518 /**
3519  * Validate comment parameter before perform other comments actions
3520  *
3521  * @package  mod_data
3522  * @category comment
3523  *
3524  * @param stdClass $comment_param {
3525  *              context  => context the context object
3526  *              courseid => int course id
3527  *              cm       => stdClass course module object
3528  *              commentarea => string comment area
3529  *              itemid      => int itemid
3530  * }
3531  * @return boolean
3532  */
3533 function data_comment_validate($comment_param) {
3534     global $DB;
3535     // validate comment area
3536     if ($comment_param->commentarea != 'database_entry') {
3537         throw new comment_exception('invalidcommentarea');
3538     }
3539     // validate itemid
3540     if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3541         throw new comment_exception('invalidcommentitemid');
3542     }
3543     if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3544         throw new comment_exception('invalidid', 'data');
3545     }
3546     if (!$course = $DB->get_record('course', array('id'=>$data->course))) {
3547         throw new comment_exception('coursemisconf');
3548     }
3549     if (!$cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
3550         throw new comment_exception('invalidcoursemodule');
3551     }
3552     if (!$data->comments) {
3553         throw new comment_exception('commentsoff', 'data');
3554     }
3555     $context = context_module::instance($cm->id);
3557     //check if approved
3558     if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3559         throw new comment_exception('notapproved', 'data');
3560     }
3562     // group access
3563     if ($record->groupid) {
3564         $groupmode = groups_get_activity_groupmode($cm, $course);
3565         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3566             if (!groups_is_member($record->groupid)) {
3567                 throw new comment_exception('notmemberofgroup');
3568             }
3569         }
3570     }
3571     // validate context id
3572     if ($context->id != $comment_param->context->id) {
3573         throw new comment_exception('invalidcontext');
3574     }
3575     // validation for comment deletion
3576     if (!empty($comment_param->commentid)) {
3577         if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
3578             if ($comment->commentarea != 'database_entry') {
3579                 throw new comment_exception('invalidcommentarea');
3580             }
3581             if ($comment->contextid != $comment_param->context->id) {
3582                 throw new comment_exception('invalidcontext');
3583             }
3584             if ($comment->itemid != $comment_param->itemid) {
3585                 throw new comment_exception('invalidcommentitemid');
3586             }
3587         } else {
3588             throw new comment_exception('invalidcommentid');
3589         }
3590     }
3591     return true;
3594 /**
3595  * Return a list of page types
3596  * @param string $pagetype current page type
3597  * @param stdClass $parentcontext Block's parent context
3598  * @param stdClass $currentcontext Current context of block
3599  */
3600 function data_page_type_list($pagetype, $parentcontext, $currentcontext) {
3601     $module_pagetype = array('mod-data-*'=>get_string('page-mod-data-x', 'data'));
3602     return $module_pagetype;
3605 /**
3606  * Get all of the record ids from a database activity.
3607  *
3608  * @param int    $dataid      The dataid of the database module.
3609  * @param object $selectdata  Contains an additional sql statement for the
3610  *                            where clause for group and approval fields.
3611  * @param array  $params      Parameters that coincide with the sql statement.
3612  * @return array $idarray     An array of record ids
3613  */
3614 function data_get_all_recordids($dataid, $selectdata = '', $params = null) {
3615     global $DB;
3616     $initsql = 'SELECT r.id
3617                   FROM {data_records} r
3618                  WHERE r.dataid = :dataid';
3619     if ($selectdata != '') {
3620         $initsql .= $selectdata;
3621         $params = array_merge(array('dataid' => $dataid), $params);
3622     } else {
3623         $params = array('dataid' => $dataid);
3624     }
3625     $initsql .= ' GROUP BY r.id';
3626     $initrecord = $DB->get_recordset_sql($initsql, $params);
3627     $idarray = array();
3628     foreach ($initrecord as $data) {
3629         $idarray[] = $data->id;
3630     }
3631     // Close the record set and free up resources.
3632     $initrecord->close();
3633     return $idarray;
3636 /**
3637  * Get the ids of all the records that match that advanced search criteria
3638  * This goes and loops through each criterion one at a time until it either
3639  * runs out of records or returns a subset of records.
3640  *
3641  * @param array $recordids    An array of record ids.
3642  * @param array $searcharray  Contains information for the advanced search criteria
3643  * @param int $dataid         The data id of the database.
3644  * @return array $recordids   An array of record ids.
3645  */
3646 function data_get_advance_search_ids($recordids, $searcharray, $dataid) {
3647     $searchcriteria = array_keys($searcharray);
3648     // Loop through and reduce the IDs one search criteria at a time.
3649     foreach ($searchcriteria as $key) {
3650         $recordids = data_get_recordids($key, $searcharray, $dataid, $recordids);
3651         // If we don't have anymore IDs then stop.
3652         if (!$recordids) {
3653             break;
3654         }
3655     }
3656     return $recordids;
3659 /**
3660  * Gets the record IDs given the search criteria
3661  *
3662  * @param string $alias       Record alias.
3663  * @param array $searcharray  Criteria for the search.
3664  * @param int $dataid         Data ID for the database
3665  * @param array $recordids    An array of record IDs.
3666  * @return array $nestarray   An arry of record IDs
3667  */
3668 function data_get_recordids($alias, $searcharray, $dataid, $recordids) {
3669     global $DB;
3671     $nestsearch = $searcharray[$alias];
3672     // searching for content outside of mdl_data_content
3673     if ($alias < 0) {
3674         $alias = '';
3675     }
3676     list($insql, $params) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3677     $nestselect = 'SELECT c' . $alias . '.recordid
3678                      FROM {data_content} c' . $alias . ',
3679                           {data_fields} f,
3680                           {data_records} r,
3681                           {user} u ';