d6641073566974cac8e1f4242d2f3a59cb069d04
[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     // Check whether this activity is read-only at present
1234     $readonly = data_in_readonly_period($data);
1236     foreach ($records as $record) {   // Might be just one for the single template
1238     // Replacing tags
1239         $patterns = array();
1240         $replacement = array();
1242     // Then we generate strings to replace for normal tags
1243         foreach ($fields as $field) {
1244             $patterns[]='[['.$field->field->name.']]';
1245             $replacement[] = highlight($search, $field->display_browse_field($record->id, $template));
1246         }
1248         $canmanageentries = has_capability('mod/data:manageentries', $context);
1250     // Replacing special tags (##Edit##, ##Delete##, ##More##)
1251         $patterns[]='##edit##';
1252         $patterns[]='##delete##';
1253         if ($canmanageentries || (!$readonly && data_isowner($record->id))) {
1254             $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d='
1255                              .$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>';
1256             $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='
1257                              .$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>';
1258         } else {
1259             $replacement[] = '';
1260             $replacement[] = '';
1261         }
1263         $moreurl = $CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&amp;rid=' . $record->id;
1264         if ($search) {
1265             $moreurl .= '&amp;filter=1';
1266         }
1267         $patterns[]='##more##';
1268         $replacement[] = '<a href="'.$moreurl.'"><img src="'.$OUTPUT->pix_url('t/preview').
1269                         '" class="iconsmall" alt="'.get_string('more', 'data').'" title="'.get_string('more', 'data').
1270                         '" /></a>';
1272         $patterns[]='##moreurl##';
1273         $replacement[] = $moreurl;
1275         $patterns[]='##delcheck##';
1276         if ($canmanageentries) {
1277             $replacement[] = html_writer::checkbox('delcheck[]', $record->id, false, '', array('class' => 'recordcheckbox'));
1278         } else {
1279             $replacement[] = '';
1280         }
1282         $patterns[]='##user##';
1283         $replacement[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$record->userid.
1284                                '&amp;course='.$data->course.'">'.fullname($record).'</a>';
1286         $patterns[] = '##userpicture##';
1287         $ruser = user_picture::unalias($record, null, 'userid');
1288         $replacement[] = $OUTPUT->user_picture($ruser, array('courseid' => $data->course));
1290         $patterns[]='##export##';
1292         if (!empty($CFG->enableportfolios) && ($template == 'singletemplate' || $template == 'listtemplate')
1293             && ((has_capability('mod/data:exportentry', $context)
1294                 || (data_isowner($record->id) && has_capability('mod/data:exportownentry', $context))))) {
1295             require_once($CFG->libdir . '/portfoliolib.php');
1296             $button = new portfolio_add_button();
1297             $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id, 'recordid' => $record->id), 'mod_data');
1298             list($formats, $files) = data_portfolio_caller::formats($fields, $record);
1299             $button->set_formats($formats);
1300             $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1301         } else {
1302             $replacement[] = '';
1303         }
1305         $patterns[] = '##timeadded##';
1306         $replacement[] = userdate($record->timecreated);
1308         $patterns[] = '##timemodified##';
1309         $replacement [] = userdate($record->timemodified);
1311         $patterns[]='##approve##';
1312         if (has_capability('mod/data:approve', $context) && ($data->approval) && (!$record->approved)) {
1313             $approveurl = new moodle_url($jumpurl, array('approve' => $record->id));
1314             $approveicon = new pix_icon('t/approve', get_string('approve', 'data'), '', array('class' => 'iconsmall'));
1315             $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($approveurl, $approveicon),
1316                     array('class' => 'approve'));
1317         } else {
1318             $replacement[] = '';
1319         }
1321         $patterns[]='##disapprove##';
1322         if (has_capability('mod/data:approve', $context) && ($data->approval) && ($record->approved)) {
1323             $disapproveurl = new moodle_url($jumpurl, array('disapprove' => $record->id));
1324             $disapproveicon = new pix_icon('t/block', get_string('disapprove', 'data'), '', array('class' => 'iconsmall'));
1325             $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($disapproveurl, $disapproveicon),
1326                     array('class' => 'disapprove'));
1327         } else {
1328             $replacement[] = '';
1329         }
1331         $patterns[] = '##approvalstatus##';
1332         if (!$data->approval) {
1333             $replacement[] = '';
1334         } else if ($record->approved) {
1335             $replacement[] = 'approved';
1336         } else {
1337             $replacement[] = 'notapproved';
1338         }
1340         $patterns[]='##comments##';
1341         if (($template == 'listtemplate') && ($data->comments)) {
1343             if (!empty($CFG->usecomments)) {
1344                 require_once($CFG->dirroot  . '/comment/lib.php');
1345                 list($context, $course, $cm) = get_context_info_array($context->id);
1346                 $cmt = new stdClass();
1347                 $cmt->context = $context;
1348                 $cmt->course  = $course;
1349                 $cmt->cm      = $cm;
1350                 $cmt->area    = 'database_entry';
1351                 $cmt->itemid  = $record->id;
1352                 $cmt->showcount = true;
1353                 $cmt->component = 'mod_data';
1354                 $comment = new comment($cmt);
1355                 $replacement[] = $comment->output(true);
1356             }
1357         } else {
1358             $replacement[] = '';
1359         }
1361         // actual replacement of the tags
1362         $newtext = str_ireplace($patterns, $replacement, $data->{$template});
1364         // no more html formatting and filtering - see MDL-6635
1365         if ($return) {
1366             return $newtext;
1367         } else {
1368             echo $newtext;
1370             // hack alert - return is always false in singletemplate anyway ;-)
1371             /**********************************
1372              *    Printing Ratings Form       *
1373              *********************************/
1374             if ($template == 'singletemplate') {    //prints ratings options
1375                 data_print_ratings($data, $record);
1376             }
1378             /**********************************
1379              *    Printing Comments Form       *
1380              *********************************/
1381             if (($template == 'singletemplate') && ($data->comments)) {
1382                 if (!empty($CFG->usecomments)) {
1383                     require_once($CFG->dirroot . '/comment/lib.php');
1384                     list($context, $course, $cm) = get_context_info_array($context->id);
1385                     $cmt = new stdClass();
1386                     $cmt->context = $context;
1387                     $cmt->course  = $course;
1388                     $cmt->cm      = $cm;
1389                     $cmt->area    = 'database_entry';
1390                     $cmt->itemid  = $record->id;
1391                     $cmt->showcount = true;
1392                     $cmt->component = 'mod_data';
1393                     $comment = new comment($cmt);
1394                     $comment->output(false);
1395                 }
1396             }
1397         }
1398     }
1401 /**
1402  * Return rating related permissions
1403  *
1404  * @param string $contextid the context id
1405  * @param string $component the component to get rating permissions for
1406  * @param string $ratingarea the rating area to get permissions for
1407  * @return array an associative array of the user's rating permissions
1408  */
1409 function data_rating_permissions($contextid, $component, $ratingarea) {
1410     $context = context::instance_by_id($contextid, MUST_EXIST);
1411     if ($component != 'mod_data' || $ratingarea != 'entry') {
1412         return null;
1413     }
1414     return array(
1415         'view'    => has_capability('mod/data:viewrating',$context),
1416         'viewany' => has_capability('mod/data:viewanyrating',$context),
1417         'viewall' => has_capability('mod/data:viewallratings',$context),
1418         'rate'    => has_capability('mod/data:rate',$context)
1419     );
1422 /**
1423  * Validates a submitted rating
1424  * @param array $params submitted data
1425  *            context => object the context in which the rated items exists [required]
1426  *            itemid => int the ID of the object being rated
1427  *            scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1428  *            rating => int the submitted rating
1429  *            rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1430  *            aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
1431  * @return boolean true if the rating is valid. Will throw rating_exception if not
1432  */
1433 function data_rating_validate($params) {
1434     global $DB, $USER;
1436     // Check the component is mod_data
1437     if ($params['component'] != 'mod_data') {
1438         throw new rating_exception('invalidcomponent');
1439     }
1441     // Check the ratingarea is entry (the only rating area in data module)
1442     if ($params['ratingarea'] != 'entry') {
1443         throw new rating_exception('invalidratingarea');
1444     }
1446     // Check the rateduserid is not the current user .. you can't rate your own entries
1447     if ($params['rateduserid'] == $USER->id) {
1448         throw new rating_exception('nopermissiontorate');
1449     }
1451     $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
1452                   FROM {data_records} r
1453                   JOIN {data} d ON r.dataid = d.id
1454                  WHERE r.id = :itemid";
1455     $dataparams = array('itemid'=>$params['itemid']);
1456     if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1457         //item doesn't exist
1458         throw new rating_exception('invaliditemid');
1459     }
1461     if ($info->scale != $params['scaleid']) {
1462         //the scale being submitted doesnt match the one in the database
1463         throw new rating_exception('invalidscaleid');
1464     }
1466     //check that the submitted rating is valid for the scale
1468     // lower limit
1469     if ($params['rating'] < 0  && $params['rating'] != RATING_UNSET_RATING) {
1470         throw new rating_exception('invalidnum');
1471     }
1473     // upper limit
1474     if ($info->scale < 0) {
1475         //its a custom scale
1476         $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
1477         if ($scalerecord) {
1478             $scalearray = explode(',', $scalerecord->scale);
1479             if ($params['rating'] > count($scalearray)) {
1480                 throw new rating_exception('invalidnum');
1481             }
1482         } else {
1483             throw new rating_exception('invalidscaleid');
1484         }
1485     } else if ($params['rating'] > $info->scale) {
1486         //if its numeric and submitted rating is above maximum
1487         throw new rating_exception('invalidnum');
1488     }
1490     if ($info->approval && !$info->approved) {
1491         //database requires approval but this item isnt approved
1492         throw new rating_exception('nopermissiontorate');
1493     }
1495     // check the item we're rating was created in the assessable time window
1496     if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
1497         if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
1498             throw new rating_exception('notavailable');
1499         }
1500     }
1502     $course = $DB->get_record('course', array('id'=>$info->course), '*', MUST_EXIST);
1503     $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1504     $context = context_module::instance($cm->id);
1506     // if the supplied context doesnt match the item's context
1507     if ($context->id != $params['context']->id) {
1508         throw new rating_exception('invalidcontext');
1509     }
1511     // Make sure groups allow this user to see the item they're rating
1512     $groupid = $info->groupid;
1513     if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {   // Groups are being used
1514         if (!groups_group_exists($groupid)) { // Can't find group
1515             throw new rating_exception('cannotfindgroup');//something is wrong
1516         }
1518         if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1519             // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
1520             throw new rating_exception('notmemberofgroup');
1521         }
1522     }
1524     return true;
1527 /**
1528  * Can the current user see ratings for a given itemid?
1529  *
1530  * @param array $params submitted data
1531  *            contextid => int contextid [required]
1532  *            component => The component for this module - should always be mod_data [required]
1533  *            ratingarea => object the context in which the rated items exists [required]
1534  *            itemid => int the ID of the object being rated [required]
1535  *            scaleid => int scale id [optional]
1536  * @return bool
1537  * @throws coding_exception
1538  * @throws rating_exception
1539  */
1540 function mod_data_rating_can_see_item_ratings($params) {
1541     global $DB;
1543     // Check the component is mod_data.
1544     if (!isset($params['component']) || $params['component'] != 'mod_data') {
1545         throw new rating_exception('invalidcomponent');
1546     }
1548     // Check the ratingarea is entry (the only rating area in data).
1549     if (!isset($params['ratingarea']) || $params['ratingarea'] != 'entry') {
1550         throw new rating_exception('invalidratingarea');
1551     }
1553     if (!isset($params['itemid'])) {
1554         throw new rating_exception('invaliditemid');
1555     }
1557     $datasql = "SELECT d.id as dataid, d.course, r.groupid
1558                   FROM {data_records} r
1559                   JOIN {data} d ON r.dataid = d.id
1560                  WHERE r.id = :itemid";
1561     $dataparams = array('itemid' => $params['itemid']);
1562     if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1563         // Item doesn't exist.
1564         throw new rating_exception('invaliditemid');
1565     }
1567     $course = $DB->get_record('course', array('id' => $info->course), '*', MUST_EXIST);
1568     $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1570     // Make sure groups allow this user to see the item they're rating.
1571     return groups_group_visible($info->groupid, $course, $cm);
1575 /**
1576  * function that takes in the current data, number of items per page,
1577  * a search string and prints a preference box in view.php
1578  *
1579  * This preference box prints a searchable advanced search template if
1580  *     a) A template is defined
1581  *  b) The advanced search checkbox is checked.
1582  *
1583  * @global object
1584  * @global object
1585  * @param object $data
1586  * @param int $perpage
1587  * @param string $search
1588  * @param string $sort
1589  * @param string $order
1590  * @param array $search_array
1591  * @param int $advanced
1592  * @param string $mode
1593  * @return void
1594  */
1595 function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
1596     global $CFG, $DB, $PAGE, $OUTPUT;
1598     $cm = get_coursemodule_from_instance('data', $data->id);
1599     $context = context_module::instance($cm->id);
1600     echo '<br /><div class="datapreferences">';
1601     echo '<form id="options" action="view.php" method="get">';
1602     echo '<div>';
1603     echo '<input type="hidden" name="d" value="'.$data->id.'" />';
1604     if ($mode =='asearch') {
1605         $advanced = 1;
1606         echo '<input type="hidden" name="mode" value="list" />';
1607     }
1608     echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
1609     $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
1610                        20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
1611     echo html_writer::select($pagesizes, 'perpage', $perpage, false, array('id'=>'pref_perpage'));
1613     if ($advanced) {
1614         $regsearchclass = 'search_none';
1615         $advancedsearchclass = 'search_inline';
1616     } else {
1617         $regsearchclass = 'search_inline';
1618         $advancedsearchclass = 'search_none';
1619     }
1620     echo '<div id="reg_search" class="' . $regsearchclass . '" >&nbsp;&nbsp;&nbsp;';
1621     echo '<label for="pref_search">'.get_string('search').'</label> <input type="text" size="16" name="search" id= "pref_search" value="'.s($search).'" /></div>';
1622     echo '&nbsp;&nbsp;&nbsp;<label for="pref_sortby">'.get_string('sortby').'</label> ';
1623     // foreach field, print the option
1624     echo '<select name="sort" id="pref_sortby">';
1625     if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'name')) {
1626         echo '<optgroup label="'.get_string('fields', 'data').'">';
1627         foreach ($fields as $field) {
1628             if ($field->id == $sort) {
1629                 echo '<option value="'.$field->id.'" selected="selected">'.$field->name.'</option>';
1630             } else {
1631                 echo '<option value="'.$field->id.'">'.$field->name.'</option>';
1632             }
1633         }
1634         echo '</optgroup>';
1635     }
1636     $options = array();
1637     $options[DATA_TIMEADDED]    = get_string('timeadded', 'data');
1638     $options[DATA_TIMEMODIFIED] = get_string('timemodified', 'data');
1639     $options[DATA_FIRSTNAME]    = get_string('authorfirstname', 'data');
1640     $options[DATA_LASTNAME]     = get_string('authorlastname', 'data');
1641     if ($data->approval and has_capability('mod/data:approve', $context)) {
1642         $options[DATA_APPROVED] = get_string('approved', 'data');
1643     }
1644     echo '<optgroup label="'.get_string('other', 'data').'">';
1645     foreach ($options as $key => $name) {
1646         if ($key == $sort) {
1647             echo '<option value="'.$key.'" selected="selected">'.$name.'</option>';
1648         } else {
1649             echo '<option value="'.$key.'">'.$name.'</option>';
1650         }
1651     }
1652     echo '</optgroup>';
1653     echo '</select>';
1654     echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
1655     echo '<select id="pref_order" name="order">';
1656     if ($order == 'ASC') {
1657         echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
1658     } else {
1659         echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1660     }
1661     if ($order == 'DESC') {
1662         echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
1663     } else {
1664         echo '<option value="DESC">'.get_string('descending','data').'</option>';
1665     }
1666     echo '</select>';
1668     if ($advanced) {
1669         $checked = ' checked="checked" ';
1670     }
1671     else {
1672         $checked = '';
1673     }
1674     $PAGE->requires->js('/mod/data/data.js');
1675     echo '&nbsp;<input type="hidden" name="advanced" value="0" />';
1676     echo '&nbsp;<input type="hidden" name="filter" value="1" />';
1677     echo '&nbsp;<input type="checkbox" id="advancedcheckbox" name="advanced" value="1" '.$checked.' onchange="showHideAdvSearch(this.checked);" /><label for="advancedcheckbox">'.get_string('advancedsearch', 'data').'</label>';
1678     echo '&nbsp;<input type="submit" value="'.get_string('savesettings','data').'" />';
1680     echo '<br />';
1681     echo '<div class="' . $advancedsearchclass . '" id="data_adv_form">';
1682     echo '<table class="boxaligncenter">';
1684     // print ASC or DESC
1685     echo '<tr><td colspan="2">&nbsp;</td></tr>';
1686     $i = 0;
1688     // Determine if we are printing all fields for advanced search, or the template for advanced search
1689     // If a template is not defined, use the deafault template and display all fields.
1690     if(empty($data->asearchtemplate)) {
1691         data_generate_default_template($data, 'asearchtemplate');
1692     }
1694     static $fields = NULL;
1695     static $isteacher;
1696     static $dataid = NULL;
1698     if (empty($dataid)) {
1699         $dataid = $data->id;
1700     } else if ($dataid != $data->id) {
1701         $fields = NULL;
1702     }
1704     if (empty($fields)) {
1705         $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1706         foreach ($fieldrecords as $fieldrecord) {
1707             $fields[]= data_get_field($fieldrecord, $data);
1708         }
1710         $isteacher = has_capability('mod/data:managetemplates', $context);
1711     }
1713     // Replacing tags
1714     $patterns = array();
1715     $replacement = array();
1717     // Then we generate strings to replace for normal tags
1718     foreach ($fields as $field) {
1719         $fieldname = $field->field->name;
1720         $fieldname = preg_quote($fieldname, '/');
1721         $patterns[] = "/\[\[$fieldname\]\]/i";
1722         $searchfield = data_get_field_from_id($field->field->id, $data);
1723         if (!empty($search_array[$field->field->id]->data)) {
1724             $replacement[] = $searchfield->display_search_field($search_array[$field->field->id]->data);
1725         } else {
1726             $replacement[] = $searchfield->display_search_field();
1727         }
1728     }
1729     $fn = !empty($search_array[DATA_FIRSTNAME]->data) ? $search_array[DATA_FIRSTNAME]->data : '';
1730     $ln = !empty($search_array[DATA_LASTNAME]->data) ? $search_array[DATA_LASTNAME]->data : '';
1731     $patterns[]    = '/##firstname##/';
1732     $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.'" />';
1733     $patterns[]    = '/##lastname##/';
1734     $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.'" />';
1736     // actual replacement of the tags
1737     $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate);
1739     $options = new stdClass();
1740     $options->para=false;
1741     $options->noclean=true;
1742     echo '<tr><td>';
1743     echo format_text($newtext, FORMAT_HTML, $options);
1744     echo '</td></tr>';
1746     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>';
1747     echo '</table>';
1748     echo '</div>';
1749     echo '</div>';
1750     echo '</form>';
1751     echo '</div>';
1754 /**
1755  * @global object
1756  * @global object
1757  * @param object $data
1758  * @param object $record
1759  * @return void Output echo'd
1760  */
1761 function data_print_ratings($data, $record) {
1762     global $OUTPUT;
1763     if (!empty($record->rating)){
1764         echo $OUTPUT->render($record->rating);
1765     }
1768 /**
1769  * List the actions that correspond to a view of this module.
1770  * This is used by the participation report.
1771  *
1772  * Note: This is not used by new logging system. Event with
1773  *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1774  *       be considered as view action.
1775  *
1776  * @return array
1777  */
1778 function data_get_view_actions() {
1779     return array('view');
1782 /**
1783  * List the actions that correspond to a post of this module.
1784  * This is used by the participation report.
1785  *
1786  * Note: This is not used by new logging system. Event with
1787  *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1788  *       will be considered as post action.
1789  *
1790  * @return array
1791  */
1792 function data_get_post_actions() {
1793     return array('add','update','record delete');
1796 /**
1797  * @param string $name
1798  * @param int $dataid
1799  * @param int $fieldid
1800  * @return bool
1801  */
1802 function data_fieldname_exists($name, $dataid, $fieldid = 0) {
1803     global $DB;
1805     if (!is_numeric($name)) {
1806         $like = $DB->sql_like('df.name', ':name', false);
1807     } else {
1808         $like = "df.name = :name";
1809     }
1810     $params = array('name'=>$name);
1811     if ($fieldid) {
1812         $params['dataid']   = $dataid;
1813         $params['fieldid1'] = $fieldid;
1814         $params['fieldid2'] = $fieldid;
1815         return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1816                                         WHERE $like AND df.dataid = :dataid
1817                                               AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
1818     } else {
1819         $params['dataid']   = $dataid;
1820         return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1821                                         WHERE $like AND df.dataid = :dataid", $params);
1822     }
1825 /**
1826  * @param array $fieldinput
1827  */
1828 function data_convert_arrays_to_strings(&$fieldinput) {
1829     foreach ($fieldinput as $key => $val) {
1830         if (is_array($val)) {
1831             $str = '';
1832             foreach ($val as $inner) {
1833                 $str .= $inner . ',';
1834             }
1835             $str = substr($str, 0, -1);
1837             $fieldinput->$key = $str;
1838         }
1839     }
1843 /**
1844  * Converts a database (module instance) to use the Roles System
1845  *
1846  * @global object
1847  * @global object
1848  * @uses CONTEXT_MODULE
1849  * @uses CAP_PREVENT
1850  * @uses CAP_ALLOW
1851  * @param object $data a data object with the same attributes as a record
1852  *                     from the data database table
1853  * @param int $datamodid the id of the data module, from the modules table
1854  * @param array $teacherroles array of roles that have archetype teacher
1855  * @param array $studentroles array of roles that have archetype student
1856  * @param array $guestroles array of roles that have archetype guest
1857  * @param int $cmid the course_module id for this data instance
1858  * @return boolean data module was converted or not
1859  */
1860 function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
1861     global $CFG, $DB, $OUTPUT;
1863     if (!isset($data->participants) && !isset($data->assesspublic)
1864             && !isset($data->groupmode)) {
1865         // We assume that this database has already been converted to use the
1866         // Roles System. above fields get dropped the data module has been
1867         // upgraded to use Roles.
1868         return false;
1869     }
1871     if (empty($cmid)) {
1872         // We were not given the course_module id. Try to find it.
1873         if (!$cm = get_coursemodule_from_instance('data', $data->id)) {
1874             echo $OUTPUT->notification('Could not get the course module for the data');
1875             return false;
1876         } else {
1877             $cmid = $cm->id;
1878         }
1879     }
1880     $context = context_module::instance($cmid);
1883     // $data->participants:
1884     // 1 - Only teachers can add entries
1885     // 3 - Teachers and students can add entries
1886     switch ($data->participants) {
1887         case 1:
1888             foreach ($studentroles as $studentrole) {
1889                 assign_capability('mod/data:writeentry', CAP_PREVENT, $studentrole->id, $context->id);
1890             }
1891             foreach ($teacherroles as $teacherrole) {
1892                 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1893             }
1894             break;
1895         case 3:
1896             foreach ($studentroles as $studentrole) {
1897                 assign_capability('mod/data:writeentry', CAP_ALLOW, $studentrole->id, $context->id);
1898             }
1899             foreach ($teacherroles as $teacherrole) {
1900                 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1901             }
1902             break;
1903     }
1905     // $data->assessed:
1906     // 2 - Only teachers can rate posts
1907     // 1 - Everyone can rate posts
1908     // 0 - No one can rate posts
1909     switch ($data->assessed) {
1910         case 0:
1911             foreach ($studentroles as $studentrole) {
1912                 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1913             }
1914             foreach ($teacherroles as $teacherrole) {
1915                 assign_capability('mod/data:rate', CAP_PREVENT, $teacherrole->id, $context->id);
1916             }
1917             break;
1918         case 1:
1919             foreach ($studentroles as $studentrole) {
1920                 assign_capability('mod/data:rate', CAP_ALLOW, $studentrole->id, $context->id);
1921             }
1922             foreach ($teacherroles as $teacherrole) {
1923                 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1924             }
1925             break;
1926         case 2:
1927             foreach ($studentroles as $studentrole) {
1928                 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1929             }
1930             foreach ($teacherroles as $teacherrole) {
1931                 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1932             }
1933             break;
1934     }
1936     // $data->assesspublic:
1937     // 0 - Students can only see their own ratings
1938     // 1 - Students can see everyone's ratings
1939     switch ($data->assesspublic) {
1940         case 0:
1941             foreach ($studentroles as $studentrole) {
1942                 assign_capability('mod/data:viewrating', CAP_PREVENT, $studentrole->id, $context->id);
1943             }
1944             foreach ($teacherroles as $teacherrole) {
1945                 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1946             }
1947             break;
1948         case 1:
1949             foreach ($studentroles as $studentrole) {
1950                 assign_capability('mod/data:viewrating', CAP_ALLOW, $studentrole->id, $context->id);
1951             }
1952             foreach ($teacherroles as $teacherrole) {
1953                 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1954             }
1955             break;
1956     }
1958     if (empty($cm)) {
1959         $cm = $DB->get_record('course_modules', array('id'=>$cmid));
1960     }
1962     switch ($cm->groupmode) {
1963         case NOGROUPS:
1964             break;
1965         case SEPARATEGROUPS:
1966             foreach ($studentroles as $studentrole) {
1967                 assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id);
1968             }
1969             foreach ($teacherroles as $teacherrole) {
1970                 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1971             }
1972             break;
1973         case VISIBLEGROUPS:
1974             foreach ($studentroles as $studentrole) {
1975                 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id);
1976             }
1977             foreach ($teacherroles as $teacherrole) {
1978                 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1979             }
1980             break;
1981     }
1982     return true;
1985 /**
1986  * Returns the best name to show for a preset
1987  *
1988  * @param string $shortname
1989  * @param  string $path
1990  * @return string
1991  */
1992 function data_preset_name($shortname, $path) {
1994     // We are looking inside the preset itself as a first choice, but also in normal data directory
1995     $string = get_string('modulename', 'datapreset_'.$shortname);
1997     if (substr($string, 0, 1) == '[') {
1998         return $shortname;
1999     } else {
2000         return $string;
2001     }
2004 /**
2005  * Returns an array of all the available presets.
2006  *
2007  * @return array
2008  */
2009 function data_get_available_presets($context) {
2010     global $CFG, $USER;
2012     $presets = array();
2014     // First load the ratings sub plugins that exist within the modules preset dir
2015     if ($dirs = core_component::get_plugin_list('datapreset')) {
2016         foreach ($dirs as $dir=>$fulldir) {
2017             if (is_directory_a_preset($fulldir)) {
2018                 $preset = new stdClass();
2019                 $preset->path = $fulldir;
2020                 $preset->userid = 0;
2021                 $preset->shortname = $dir;
2022                 $preset->name = data_preset_name($dir, $fulldir);
2023                 if (file_exists($fulldir.'/screenshot.jpg')) {
2024                     $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.jpg';
2025                 } else if (file_exists($fulldir.'/screenshot.png')) {
2026                     $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.png';
2027                 } else if (file_exists($fulldir.'/screenshot.gif')) {
2028                     $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.gif';
2029                 }
2030                 $presets[] = $preset;
2031             }
2032         }
2033     }
2034     // Now add to that the site presets that people have saved
2035     $presets = data_get_available_site_presets($context, $presets);
2036     return $presets;
2039 /**
2040  * Gets an array of all of the presets that users have saved to the site.
2041  *
2042  * @param stdClass $context The context that we are looking from.
2043  * @param array $presets
2044  * @return array An array of presets
2045  */
2046 function data_get_available_site_presets($context, array $presets=array()) {
2047     global $USER;
2049     $fs = get_file_storage();
2050     $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2051     $canviewall = has_capability('mod/data:viewalluserpresets', $context);
2052     if (empty($files)) {
2053         return $presets;
2054     }
2055     foreach ($files as $file) {
2056         if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory() || (!$canviewall && $file->get_userid() != $USER->id)) {
2057             continue;
2058         }
2059         $preset = new stdClass;
2060         $preset->path = $file->get_filepath();
2061         $preset->name = trim($preset->path, '/');
2062         $preset->shortname = $preset->name;
2063         $preset->userid = $file->get_userid();
2064         $preset->id = $file->get_id();
2065         $preset->storedfile = $file;
2066         $presets[] = $preset;
2067     }
2068     return $presets;
2071 /**
2072  * Deletes a saved preset.
2073  *
2074  * @param string $name
2075  * @return bool
2076  */
2077 function data_delete_site_preset($name) {
2078     $fs = get_file_storage();
2080     $files = $fs->get_directory_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/');
2081     if (!empty($files)) {
2082         foreach ($files as $file) {
2083             $file->delete();
2084         }
2085     }
2087     $dir = $fs->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/', '.');
2088     if (!empty($dir)) {
2089         $dir->delete();
2090     }
2091     return true;
2094 /**
2095  * Prints the heads for a page
2096  *
2097  * @param stdClass $course
2098  * @param stdClass $cm
2099  * @param stdClass $data
2100  * @param string $currenttab
2101  */
2102 function data_print_header($course, $cm, $data, $currenttab='') {
2104     global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
2106     $PAGE->set_title($data->name);
2107     echo $OUTPUT->header();
2108     echo $OUTPUT->heading(format_string($data->name), 2);
2109     echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
2111     // Groups needed for Add entry tab
2112     $currentgroup = groups_get_activity_group($cm);
2113     $groupmode = groups_get_activity_groupmode($cm);
2115     // Print the tabs
2117     if ($currenttab) {
2118         include('tabs.php');
2119     }
2121     // Print any notices
2123     if (!empty($displaynoticegood)) {
2124         echo $OUTPUT->notification($displaynoticegood, 'notifysuccess');    // good (usually green)
2125     } else if (!empty($displaynoticebad)) {
2126         echo $OUTPUT->notification($displaynoticebad);                     // bad (usuually red)
2127     }
2130 /**
2131  * Can user add more entries?
2132  *
2133  * @param object $data
2134  * @param mixed $currentgroup
2135  * @param int $groupmode
2136  * @param stdClass $context
2137  * @return bool
2138  */
2139 function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
2140     global $USER;
2142     if (empty($context)) {
2143         $cm = get_coursemodule_from_instance('data', $data->id, 0, false, MUST_EXIST);
2144         $context = context_module::instance($cm->id);
2145     }
2147     if (has_capability('mod/data:manageentries', $context)) {
2148         // no entry limits apply if user can manage
2150     } else if (!has_capability('mod/data:writeentry', $context)) {
2151         return false;
2153     } else if (data_atmaxentries($data)) {
2154         return false;
2155     } else if (data_in_readonly_period($data)) {
2156         // Check whether we're in a read-only period
2157         return false;
2158     }
2160     if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2161         return true;
2162     }
2164     if ($currentgroup) {
2165         return groups_is_member($currentgroup);
2166     } else {
2167         //else it might be group 0 in visible mode
2168         if ($groupmode == VISIBLEGROUPS){
2169             return true;
2170         } else {
2171             return false;
2172         }
2173     }
2176 /**
2177  * Check whether the specified database activity is currently in a read-only period
2178  *
2179  * @param object $data
2180  * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2181  */
2182 function data_in_readonly_period($data) {
2183     $now = time();
2184     if (!$data->timeviewfrom && !$data->timeviewto) {
2185         return false;
2186     } else if (($data->timeviewfrom && $now < $data->timeviewfrom) || ($data->timeviewto && $now > $data->timeviewto)) {
2187         return false;
2188     }
2189     return true;
2192 /**
2193  * @return bool
2194  */
2195 function is_directory_a_preset($directory) {
2196     $directory = rtrim($directory, '/\\') . '/';
2197     $status = file_exists($directory.'singletemplate.html') &&
2198               file_exists($directory.'listtemplate.html') &&
2199               file_exists($directory.'listtemplateheader.html') &&
2200               file_exists($directory.'listtemplatefooter.html') &&
2201               file_exists($directory.'addtemplate.html') &&
2202               file_exists($directory.'rsstemplate.html') &&
2203               file_exists($directory.'rsstitletemplate.html') &&
2204               file_exists($directory.'csstemplate.css') &&
2205               file_exists($directory.'jstemplate.js') &&
2206               file_exists($directory.'preset.xml');
2208     return $status;
2211 /**
2212  * Abstract class used for data preset importers
2213  */
2214 abstract class data_preset_importer {
2216     protected $course;
2217     protected $cm;
2218     protected $module;
2219     protected $directory;
2221     /**
2222      * Constructor
2223      *
2224      * @param stdClass $course
2225      * @param stdClass $cm
2226      * @param stdClass $module
2227      * @param string $directory
2228      */
2229     public function __construct($course, $cm, $module, $directory) {
2230         $this->course = $course;
2231         $this->cm = $cm;
2232         $this->module = $module;
2233         $this->directory = $directory;
2234     }
2236     /**
2237      * Returns the name of the directory the preset is located in
2238      * @return string
2239      */
2240     public function get_directory() {
2241         return basename($this->directory);
2242     }
2244     /**
2245      * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2246      * @param file_storage $filestorage. should be null if using a conventional directory
2247      * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2248      * @param string $dir the directory to look in. null if using the Moodle file storage
2249      * @param string $filename the name of the file we want
2250      * @return string the contents of the file or null if the file doesn't exist.
2251      */
2252     public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2253         if(empty($filestorage) || empty($fileobj)) {
2254             if (substr($dir, -1)!='/') {
2255                 $dir .= '/';
2256             }
2257             if (file_exists($dir.$filename)) {
2258                 return file_get_contents($dir.$filename);
2259             } else {
2260                 return null;
2261             }
2262         } else {
2263             if ($filestorage->file_exists(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename)) {
2264                 $file = $filestorage->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename);
2265                 return $file->get_content();
2266             } else {
2267                 return null;
2268             }
2269         }
2271     }
2272     /**
2273      * Gets the preset settings
2274      * @global moodle_database $DB
2275      * @return stdClass
2276      */
2277     public function get_preset_settings() {
2278         global $DB;
2280         $fs = $fileobj = null;
2281         if (!is_directory_a_preset($this->directory)) {
2282             //maybe the user requested a preset stored in the Moodle file storage
2284             $fs = get_file_storage();
2285             $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2287             //preset name to find will be the final element of the directory
2288             $explodeddirectory = explode('/', $this->directory);
2289             $presettofind = end($explodeddirectory);
2291             //now go through the available files available and see if we can find it
2292             foreach ($files as $file) {
2293                 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory()) {
2294                     continue;
2295                 }
2296                 $presetname = trim($file->get_filepath(), '/');
2297                 if ($presetname==$presettofind) {
2298                     $this->directory = $presetname;
2299                     $fileobj = $file;
2300                 }
2301             }
2303             if (empty($fileobj)) {
2304                 print_error('invalidpreset', 'data', '', $this->directory);
2305             }
2306         }
2308         $allowed_settings = array(
2309             'intro',
2310             'comments',
2311             'requiredentries',
2312             'requiredentriestoview',
2313             'maxentries',
2314             'rssarticles',
2315             'approval',
2316             'defaultsortdir',
2317             'defaultsort');
2319         $result = new stdClass;
2320         $result->settings = new stdClass;
2321         $result->importfields = array();
2322         $result->currentfields = $DB->get_records('data_fields', array('dataid'=>$this->module->id));
2323         if (!$result->currentfields) {
2324             $result->currentfields = array();
2325         }
2328         /* Grab XML */
2329         $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory,'preset.xml');
2330         $parsedxml = xmlize($presetxml, 0);
2332         /* First, do settings. Put in user friendly array. */
2333         $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
2334         $result->settings = new StdClass();
2335         foreach ($settingsarray as $setting => $value) {
2336             if (!is_array($value) || !in_array($setting, $allowed_settings)) {
2337                 // unsupported setting
2338                 continue;
2339             }
2340             $result->settings->$setting = $value[0]['#'];
2341         }
2343         /* Now work out fields to user friendly array */
2344         $fieldsarray = $parsedxml['preset']['#']['field'];
2345         foreach ($fieldsarray as $field) {
2346             if (!is_array($field)) {
2347                 continue;
2348             }
2349             $f = new StdClass();
2350             foreach ($field['#'] as $param => $value) {
2351                 if (!is_array($value)) {
2352                     continue;
2353                 }
2354                 $f->$param = $value[0]['#'];
2355             }
2356             $f->dataid = $this->module->id;
2357             $f->type = clean_param($f->type, PARAM_ALPHA);
2358             $result->importfields[] = $f;
2359         }
2360         /* Now add the HTML templates to the settings array so we can update d */
2361         $result->settings->singletemplate     = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"singletemplate.html");
2362         $result->settings->listtemplate       = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplate.html");
2363         $result->settings->listtemplateheader = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplateheader.html");
2364         $result->settings->listtemplatefooter = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplatefooter.html");
2365         $result->settings->addtemplate        = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"addtemplate.html");
2366         $result->settings->rsstemplate        = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstemplate.html");
2367         $result->settings->rsstitletemplate   = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstitletemplate.html");
2368         $result->settings->csstemplate        = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"csstemplate.css");
2369         $result->settings->jstemplate         = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"jstemplate.js");
2370         $result->settings->asearchtemplate    = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"asearchtemplate.html");
2372         $result->settings->instance = $this->module->id;
2373         return $result;
2374     }
2376     /**
2377      * Import the preset into the given database module
2378      * @return bool
2379      */
2380     function import($overwritesettings) {
2381         global $DB, $CFG;
2383         $params = $this->get_preset_settings();
2384         $settings = $params->settings;
2385         $newfields = $params->importfields;
2386         $currentfields = $params->currentfields;
2387         $preservedfields = array();
2389         /* Maps fields and makes new ones */
2390         if (!empty($newfields)) {
2391             /* We require an injective mapping, and need to know what to protect */
2392             foreach ($newfields as $nid => $newfield) {
2393                 $cid = optional_param("field_$nid", -1, PARAM_INT);
2394                 if ($cid == -1) {
2395                     continue;
2396                 }
2397                 if (array_key_exists($cid, $preservedfields)){
2398                     print_error('notinjectivemap', 'data');
2399                 }
2400                 else $preservedfields[$cid] = true;
2401             }
2403             foreach ($newfields as $nid => $newfield) {
2404                 $cid = optional_param("field_$nid", -1, PARAM_INT);
2406                 /* A mapping. Just need to change field params. Data kept. */
2407                 if ($cid != -1 and isset($currentfields[$cid])) {
2408                     $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->module);
2409                     foreach ($newfield as $param => $value) {
2410                         if ($param != "id") {
2411                             $fieldobject->field->$param = $value;
2412                         }
2413                     }
2414                     unset($fieldobject->field->similarfield);
2415                     $fieldobject->update_field();
2416                     unset($fieldobject);
2417                 } else {
2418                     /* Make a new field */
2419                     include_once("field/$newfield->type/field.class.php");
2421                     if (!isset($newfield->description)) {
2422                         $newfield->description = '';
2423                     }
2424                     $classname = 'data_field_'.$newfield->type;
2425                     $fieldclass = new $classname($newfield, $this->module);
2426                     $fieldclass->insert_field();
2427                     unset($fieldclass);
2428                 }
2429             }
2430         }
2432         /* Get rid of all old unused data */
2433         if (!empty($preservedfields)) {
2434             foreach ($currentfields as $cid => $currentfield) {
2435                 if (!array_key_exists($cid, $preservedfields)) {
2436                     /* Data not used anymore so wipe! */
2437                     print "Deleting field $currentfield->name<br />";
2439                     $id = $currentfield->id;
2440                     //Why delete existing data records and related comments/ratings??
2441                     $DB->delete_records('data_content', array('fieldid'=>$id));
2442                     $DB->delete_records('data_fields', array('id'=>$id));
2443                 }
2444             }
2445         }
2447         // handle special settings here
2448         if (!empty($settings->defaultsort)) {
2449             if (is_numeric($settings->defaultsort)) {
2450                 // old broken value
2451                 $settings->defaultsort = 0;
2452             } else {
2453                 $settings->defaultsort = (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module->id, 'name'=>$settings->defaultsort));
2454             }
2455         } else {
2456             $settings->defaultsort = 0;
2457         }
2459         // do we want to overwrite all current database settings?
2460         if ($overwritesettings) {
2461             // all supported settings
2462             $overwrite = array_keys((array)$settings);
2463         } else {
2464             // only templates and sorting
2465             $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2466                                'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
2467                                'asearchtemplate', 'defaultsortdir', 'defaultsort');
2468         }
2470         // now overwrite current data settings
2471         foreach ($this->module as $prop=>$unused) {
2472             if (in_array($prop, $overwrite)) {
2473                 $this->module->$prop = $settings->$prop;
2474             }
2475         }
2477         data_update_instance($this->module);
2479         return $this->cleanup();
2480     }
2482     /**
2483      * Any clean up routines should go here
2484      * @return bool
2485      */
2486     public function cleanup() {
2487         return true;
2488     }
2491 /**
2492  * Data preset importer for uploaded presets
2493  */
2494 class data_preset_upload_importer extends data_preset_importer {
2495     public function __construct($course, $cm, $module, $filepath) {
2496         global $USER;
2497         if (is_file($filepath)) {
2498             $fp = get_file_packer();
2499             if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2500                 fulldelete($filepath);
2501             }
2502             $filepath .= '_extracted';
2503         }
2504         parent::__construct($course, $cm, $module, $filepath);
2505     }
2506     public function cleanup() {
2507         return fulldelete($this->directory);
2508     }
2511 /**
2512  * Data preset importer for existing presets
2513  */
2514 class data_preset_existing_importer extends data_preset_importer {
2515     protected $userid;
2516     public function __construct($course, $cm, $module, $fullname) {
2517         global $USER;
2518         list($userid, $shortname) = explode('/', $fullname, 2);
2519         $context = context_module::instance($cm->id);
2520         if ($userid && ($userid != $USER->id) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2521            throw new coding_exception('Invalid preset provided');
2522         }
2524         $this->userid = $userid;
2525         $filepath = data_preset_path($course, $userid, $shortname);
2526         parent::__construct($course, $cm, $module, $filepath);
2527     }
2528     public function get_userid() {
2529         return $this->userid;
2530     }
2533 /**
2534  * @global object
2535  * @global object
2536  * @param object $course
2537  * @param int $userid
2538  * @param string $shortname
2539  * @return string
2540  */
2541 function data_preset_path($course, $userid, $shortname) {
2542     global $USER, $CFG;
2544     $context = context_course::instance($course->id);
2546     $userid = (int)$userid;
2548     $path = null;
2549     if ($userid > 0 && ($userid == $USER->id || has_capability('mod/data:viewalluserpresets', $context))) {
2550         $path = $CFG->dataroot.'/data/preset/'.$userid.'/'.$shortname;
2551     } else if ($userid == 0) {
2552         $path = $CFG->dirroot.'/mod/data/preset/'.$shortname;
2553     } else if ($userid < 0) {
2554         $path = $CFG->tempdir.'/data/'.-$userid.'/'.$shortname;
2555     }
2557     return $path;
2560 /**
2561  * Implementation of the function for printing the form elements that control
2562  * whether the course reset functionality affects the data.
2563  *
2564  * @param $mform form passed by reference
2565  */
2566 function data_reset_course_form_definition(&$mform) {
2567     $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2568     $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2570     $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2571     $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2573     $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2574     $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2576     $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2577     $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
2580 /**
2581  * Course reset form defaults.
2582  * @return array
2583  */
2584 function data_reset_course_form_defaults($course) {
2585     return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2588 /**
2589  * Removes all grades from gradebook
2590  *
2591  * @global object
2592  * @global object
2593  * @param int $courseid
2594  * @param string $type optional type
2595  */
2596 function data_reset_gradebook($courseid, $type='') {
2597     global $CFG, $DB;
2599     $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
2600               FROM {data} d, {course_modules} cm, {modules} m
2601              WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
2603     if ($datas = $DB->get_records_sql($sql, array($courseid))) {
2604         foreach ($datas as $data) {
2605             data_grade_item_update($data, 'reset');
2606         }
2607     }
2610 /**
2611  * Actual implementation of the reset course functionality, delete all the
2612  * data responses for course $data->courseid.
2613  *
2614  * @global object
2615  * @global object
2616  * @param object $data the data submitted from the reset course.
2617  * @return array status array
2618  */
2619 function data_reset_userdata($data) {
2620     global $CFG, $DB;
2621     require_once($CFG->libdir.'/filelib.php');
2622     require_once($CFG->dirroot.'/rating/lib.php');
2624     $componentstr = get_string('modulenameplural', 'data');
2625     $status = array();
2627     $allrecordssql = "SELECT r.id
2628                         FROM {data_records} r
2629                              INNER JOIN {data} d ON r.dataid = d.id
2630                        WHERE d.course = ?";
2632     $alldatassql = "SELECT d.id
2633                       FROM {data} d
2634                      WHERE d.course=?";
2636     $rm = new rating_manager();
2637     $ratingdeloptions = new stdClass;
2638     $ratingdeloptions->component = 'mod_data';
2639     $ratingdeloptions->ratingarea = 'entry';
2641     // Set the file storage - may need it to remove files later.
2642     $fs = get_file_storage();
2644     // delete entries if requested
2645     if (!empty($data->reset_data)) {
2646         $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2647         $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid));
2648         $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid));
2650         if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2651             foreach ($datas as $dataid=>$unused) {
2652                 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2653                     continue;
2654                 }
2655                 $datacontext = context_module::instance($cm->id);
2657                 // Delete any files that may exist.
2658                 $fs->delete_area_files($datacontext->id, 'mod_data', 'content');
2660                 $ratingdeloptions->contextid = $datacontext->id;
2661                 $rm->delete_ratings($ratingdeloptions);
2662             }
2663         }
2665         if (empty($data->reset_gradebook_grades)) {
2666             // remove all grades from gradebook
2667             data_reset_gradebook($data->courseid);
2668         }
2669         $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2670     }
2672     // remove entries by users not enrolled into course
2673     if (!empty($data->reset_data_notenrolled)) {
2674         $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
2675                          FROM {data_records} r
2676                               JOIN {data} d ON r.dataid = d.id
2677                               LEFT JOIN {user} u ON r.userid = u.id
2678                         WHERE d.course = ? AND r.userid > 0";
2680         $course_context = context_course::instance($data->courseid);
2681         $notenrolled = array();
2682         $fields = array();
2683         $rs = $DB->get_recordset_sql($recordssql, array($data->courseid));
2684         foreach ($rs as $record) {
2685             if (array_key_exists($record->userid, $notenrolled) or !$record->userexists or $record->userdeleted
2686               or !is_enrolled($course_context, $record->userid)) {
2687                 //delete ratings
2688                 if (!$cm = get_coursemodule_from_instance('data', $record->dataid)) {
2689                     continue;
2690                 }
2691                 $datacontext = context_module::instance($cm->id);
2692                 $ratingdeloptions->contextid = $datacontext->id;
2693                 $ratingdeloptions->itemid = $record->id;
2694                 $rm->delete_ratings($ratingdeloptions);
2696                 // Delete any files that may exist.
2697                 if ($contents = $DB->get_records('data_content', array('recordid' => $record->id), '', 'id')) {
2698                     foreach ($contents as $content) {
2699                         $fs->delete_area_files($datacontext->id, 'mod_data', 'content', $content->id);
2700                     }
2701                 }
2702                 $notenrolled[$record->userid] = true;
2704                 $DB->delete_records('comments', array('itemid' => $record->id, 'commentarea' => 'database_entry'));
2705                 $DB->delete_records('data_content', array('recordid' => $record->id));
2706                 $DB->delete_records('data_records', array('id' => $record->id));
2707             }
2708         }
2709         $rs->close();
2710         $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
2711     }
2713     // remove all ratings
2714     if (!empty($data->reset_data_ratings)) {
2715         if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2716             foreach ($datas as $dataid=>$unused) {
2717                 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2718                     continue;
2719                 }
2720                 $datacontext = context_module::instance($cm->id);
2722                 $ratingdeloptions->contextid = $datacontext->id;
2723                 $rm->delete_ratings($ratingdeloptions);
2724             }
2725         }
2727         if (empty($data->reset_gradebook_grades)) {
2728             // remove all grades from gradebook
2729             data_reset_gradebook($data->courseid);
2730         }
2732         $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2733     }
2735     // remove all comments
2736     if (!empty($data->reset_data_comments)) {
2737         $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2738         $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2739     }
2741     // updating dates - shift may be negative too
2742     if ($data->timeshift) {
2743         shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto'), $data->timeshift, $data->courseid);
2744         $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2745     }
2747     return $status;
2750 /**
2751  * Returns all other caps used in module
2752  *
2753  * @return array
2754  */
2755 function data_get_extra_capabilities() {
2756     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');
2759 /**
2760  * @param string $feature FEATURE_xx constant for requested feature
2761  * @return mixed True if module supports feature, null if doesn't know
2762  */
2763 function data_supports($feature) {
2764     switch($feature) {
2765         case FEATURE_GROUPS:                  return true;
2766         case FEATURE_GROUPINGS:               return true;
2767         case FEATURE_MOD_INTRO:               return true;
2768         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
2769         case FEATURE_GRADE_HAS_GRADE:         return true;
2770         case FEATURE_GRADE_OUTCOMES:          return true;
2771         case FEATURE_RATE:                    return true;
2772         case FEATURE_BACKUP_MOODLE2:          return true;
2773         case FEATURE_SHOW_DESCRIPTION:        return true;
2775         default: return null;
2776     }
2778 /**
2779  * @global object
2780  * @param array $export
2781  * @param string $delimiter_name
2782  * @param object $database
2783  * @param int $count
2784  * @param bool $return
2785  * @return string|void
2786  */
2787 function data_export_csv($export, $delimiter_name, $database, $count, $return=false) {
2788     global $CFG;
2789     require_once($CFG->libdir . '/csvlib.class.php');
2791     $filename = $database . '-' . $count . '-record';
2792     if ($count > 1) {
2793         $filename .= 's';
2794     }
2795     if ($return) {
2796         return csv_export_writer::print_array($export, $delimiter_name, '"', true);
2797     } else {
2798         csv_export_writer::download_array($filename, $export, $delimiter_name);
2799     }
2802 /**
2803  * @global object
2804  * @param array $export
2805  * @param string $dataname
2806  * @param int $count
2807  * @return string
2808  */
2809 function data_export_xls($export, $dataname, $count) {
2810     global $CFG;
2811     require_once("$CFG->libdir/excellib.class.php");
2812     $filename = clean_filename("{$dataname}-{$count}_record");
2813     if ($count > 1) {
2814         $filename .= 's';
2815     }
2816     $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2817     $filename .= '.xls';
2819     $filearg = '-';
2820     $workbook = new MoodleExcelWorkbook($filearg);
2821     $workbook->send($filename);
2822     $worksheet = array();
2823     $worksheet[0] = $workbook->add_worksheet('');
2824     $rowno = 0;
2825     foreach ($export as $row) {
2826         $colno = 0;
2827         foreach($row as $col) {
2828             $worksheet[0]->write($rowno, $colno, $col);
2829             $colno++;
2830         }
2831         $rowno++;
2832     }
2833     $workbook->close();
2834     return $filename;
2837 /**
2838  * @global object
2839  * @param array $export
2840  * @param string $dataname
2841  * @param int $count
2842  * @param string
2843  */
2844 function data_export_ods($export, $dataname, $count) {
2845     global $CFG;
2846     require_once("$CFG->libdir/odslib.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 .= '.ods';
2853     $filearg = '-';
2854     $workbook = new MoodleODSWorkbook($filearg);
2855     $workbook->send($filename);
2856     $worksheet = array();
2857     $worksheet[0] = $workbook->add_worksheet('');
2858     $rowno = 0;
2859     foreach ($export as $row) {
2860         $colno = 0;
2861         foreach($row as $col) {
2862             $worksheet[0]->write($rowno, $colno, $col);
2863             $colno++;
2864         }
2865         $rowno++;
2866     }
2867     $workbook->close();
2868     return $filename;
2871 /**
2872  * @global object
2873  * @param int $dataid
2874  * @param array $fields
2875  * @param array $selectedfields
2876  * @param int $currentgroup group ID of the current group. This is used for
2877  * exporting data while maintaining group divisions.
2878  * @param object $context the context in which the operation is performed (for capability checks)
2879  * @param bool $userdetails whether to include the details of the record author
2880  * @param bool $time whether to include time created/modified
2881  * @param bool $approval whether to include approval status
2882  * @return array
2883  */
2884 function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0, $context=null,
2885                              $userdetails=false, $time=false, $approval=false) {
2886     global $DB;
2888     if (is_null($context)) {
2889         $context = context_system::instance();
2890     }
2891     // exporting user data needs special permission
2892     $userdetails = $userdetails && has_capability('mod/data:exportuserinfo', $context);
2894     $exportdata = array();
2896     // populate the header in first row of export
2897     foreach($fields as $key => $field) {
2898         if (!in_array($field->field->id, $selectedfields)) {
2899             // ignore values we aren't exporting
2900             unset($fields[$key]);
2901         } else {
2902             $exportdata[0][] = $field->field->name;
2903         }
2904     }
2905     if ($userdetails) {
2906         $exportdata[0][] = get_string('user');
2907         $exportdata[0][] = get_string('username');
2908         $exportdata[0][] = get_string('email');
2909     }
2910     if ($time) {
2911         $exportdata[0][] = get_string('timeadded', 'data');
2912         $exportdata[0][] = get_string('timemodified', 'data');
2913     }
2914     if ($approval) {
2915         $exportdata[0][] = get_string('approved', 'data');
2916     }
2918     $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
2919     ksort($datarecords);
2920     $line = 1;
2921     foreach($datarecords as $record) {
2922         // get content indexed by fieldid
2923         if ($currentgroup) {
2924             $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 = ?';
2925             $where = array($record->id, $currentgroup);
2926         } else {
2927             $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
2928             $where = array($record->id);
2929         }
2931         if( $content = $DB->get_records_sql($select, $where) ) {
2932             foreach($fields as $field) {
2933                 $contents = '';
2934                 if(isset($content[$field->field->id])) {
2935                     $contents = $field->export_text_value($content[$field->field->id]);
2936                 }
2937                 $exportdata[$line][] = $contents;
2938             }
2939             if ($userdetails) { // Add user details to the export data
2940                 $userdata = get_complete_user_data('id', $record->userid);
2941                 $exportdata[$line][] = fullname($userdata);
2942                 $exportdata[$line][] = $userdata->username;
2943                 $exportdata[$line][] = $userdata->email;
2944             }
2945             if ($time) { // Add time added / modified
2946                 $exportdata[$line][] = userdate($record->timecreated);
2947                 $exportdata[$line][] = userdate($record->timemodified);
2948             }
2949             if ($approval) { // Add approval status
2950                 $exportdata[$line][] = (int) $record->approved;
2951             }
2952         }
2953         $line++;
2954     }
2955     $line--;
2956     return $exportdata;
2959 ////////////////////////////////////////////////////////////////////////////////
2960 // File API                                                                   //
2961 ////////////////////////////////////////////////////////////////////////////////
2963 /**
2964  * Lists all browsable file areas
2965  *
2966  * @package  mod_data
2967  * @category files
2968  * @param stdClass $course course object
2969  * @param stdClass $cm course module object
2970  * @param stdClass $context context object
2971  * @return array
2972  */
2973 function data_get_file_areas($course, $cm, $context) {
2974     return array('content' => get_string('areacontent', 'mod_data'));
2977 /**
2978  * File browsing support for data module.
2979  *
2980  * @param file_browser $browser
2981  * @param array $areas
2982  * @param stdClass $course
2983  * @param cm_info $cm
2984  * @param context $context
2985  * @param string $filearea
2986  * @param int $itemid
2987  * @param string $filepath
2988  * @param string $filename
2989  * @return file_info_stored file_info_stored instance or null if not found
2990  */
2991 function data_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2992     global $CFG, $DB, $USER;
2994     if ($context->contextlevel != CONTEXT_MODULE) {
2995         return null;
2996     }
2998     if (!isset($areas[$filearea])) {
2999         return null;
3000     }
3002     if (is_null($itemid)) {
3003         require_once($CFG->dirroot.'/mod/data/locallib.php');
3004         return new data_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
3005     }
3007     if (!$content = $DB->get_record('data_content', array('id'=>$itemid))) {
3008         return null;
3009     }
3011     if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
3012         return null;
3013     }
3015     if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
3016         return null;
3017     }
3019     if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
3020         return null;
3021     }
3023     //check if approved
3024     if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3025         return null;
3026     }
3028     // group access
3029     if ($record->groupid) {
3030         $groupmode = groups_get_activity_groupmode($cm, $course);
3031         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3032             if (!groups_is_member($record->groupid)) {
3033                 return null;
3034             }
3035         }
3036     }
3038     $fieldobj = data_get_field($field, $data, $cm);
3040     $filepath = is_null($filepath) ? '/' : $filepath;
3041     $filename = is_null($filename) ? '.' : $filename;
3042     if (!$fieldobj->file_ok($filepath.$filename)) {
3043         return null;
3044     }
3046     $fs = get_file_storage();
3047     if (!($storedfile = $fs->get_file($context->id, 'mod_data', $filearea, $itemid, $filepath, $filename))) {
3048         return null;
3049     }
3051     // Checks to see if the user can manage files or is the owner.
3052     // TODO MDL-33805 - Do not use userid here and move the capability check above.
3053     if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
3054         return null;
3055     }
3057     $urlbase = $CFG->wwwroot.'/pluginfile.php';
3059     return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
3062 /**
3063  * Serves the data attachments. Implements needed access control ;-)
3064  *
3065  * @package  mod_data
3066  * @category files
3067  * @param stdClass $course course object
3068  * @param stdClass $cm course module object
3069  * @param stdClass $context context object
3070  * @param string $filearea file area
3071  * @param array $args extra arguments
3072  * @param bool $forcedownload whether or not force download
3073  * @param array $options additional options affecting the file serving
3074  * @return bool false if file not found, does not return if found - justsend the file
3075  */
3076 function data_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3077     global $CFG, $DB;
3079     if ($context->contextlevel != CONTEXT_MODULE) {
3080         return false;
3081     }
3083     require_course_login($course, true, $cm);
3085     if ($filearea === 'content') {
3086         $contentid = (int)array_shift($args);
3088         if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
3089             return false;
3090         }
3092         if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
3093             return false;
3094         }
3096         if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
3097             return false;
3098         }
3100         if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
3101             return false;
3102         }
3104         if ($data->id != $cm->instance) {
3105             // hacker attempt - context does not match the contentid
3106             return false;
3107         }
3109         //check if approved
3110         if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3111             return false;
3112         }
3114         // group access
3115         if ($record->groupid) {
3116             $groupmode = groups_get_activity_groupmode($cm, $course);
3117             if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3118                 if (!groups_is_member($record->groupid)) {
3119                     return false;
3120                 }
3121             }
3122         }
3124         $fieldobj = data_get_field($field, $data, $cm);
3126         $relativepath = implode('/', $args);
3127         $fullpath = "/$context->id/mod_data/content/$content->id/$relativepath";
3129         if (!$fieldobj->file_ok($relativepath)) {
3130             return false;
3131         }
3133         $fs = get_file_storage();
3134         if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3135             return false;
3136         }
3138         // finally send the file
3139         send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
3140     }
3142     return false;
3146 function data_extend_navigation($navigation, $course, $module, $cm) {
3147     global $CFG, $OUTPUT, $USER, $DB;
3149     $rid = optional_param('rid', 0, PARAM_INT);
3151     $data = $DB->get_record('data', array('id'=>$cm->instance));
3152     $currentgroup = groups_get_activity_group($cm);
3153     $groupmode = groups_get_activity_groupmode($cm);
3155      $numentries = data_numentries($data);
3156     /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
3157     if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !has_capability('mod/data:manageentries', context_module::instance($cm->id))) {
3158         $data->entriesleft = $data->requiredentries - $numentries;
3159         $entriesnode = $navigation->add(get_string('entrieslefttoadd', 'data', $data));
3160         $entriesnode->add_class('note');
3161     }
3163     $navigation->add(get_string('list', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance)));
3164     if (!empty($rid)) {
3165         $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'rid'=>$rid)));
3166     } else {
3167         $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'single')));
3168     }
3169     $navigation->add(get_string('search', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'asearch')));
3172 /**
3173  * Adds module specific settings to the settings block
3174  *
3175  * @param settings_navigation $settings The settings navigation object
3176  * @param navigation_node $datanode The node to add module settings to
3177  */
3178 function data_extend_settings_navigation(settings_navigation $settings, navigation_node $datanode) {
3179     global $PAGE, $DB, $CFG, $USER;
3181     $data = $DB->get_record('data', array("id" => $PAGE->cm->instance));
3183     $currentgroup = groups_get_activity_group($PAGE->cm);
3184     $groupmode = groups_get_activity_groupmode($PAGE->cm);
3186     if (data_user_can_add_entry($data, $currentgroup, $groupmode, $PAGE->cm->context)) { // took out participation list here!
3187         if (empty($editentry)) { //TODO: undefined
3188             $addstring = get_string('add', 'data');
3189         } else {
3190             $addstring = get_string('editentry', 'data');
3191         }
3192         $datanode->add($addstring, new moodle_url('/mod/data/edit.php', array('d'=>$PAGE->cm->instance)));
3193     }
3195     if (has_capability(DATA_CAP_EXPORT, $PAGE->cm->context)) {
3196         // The capability required to Export database records is centrally defined in 'lib.php'
3197         // and should be weaker than those required to edit Templates, Fields and Presets.
3198         $datanode->add(get_string('exportentries', 'data'), new moodle_url('/mod/data/export.php', array('d'=>$data->id)));
3199     }
3200     if (has_capability('mod/data:manageentries', $PAGE->cm->context)) {
3201         $datanode->add(get_string('importentries', 'data'), new moodle_url('/mod/data/import.php', array('d'=>$data->id)));
3202     }
3204     if (has_capability('mod/data:managetemplates', $PAGE->cm->context)) {
3205         $currenttab = '';
3206         if ($currenttab == 'list') {
3207             $defaultemplate = 'listtemplate';
3208         } else if ($currenttab == 'add') {
3209             $defaultemplate = 'addtemplate';
3210         } else if ($currenttab == 'asearch') {
3211             $defaultemplate = 'asearchtemplate';
3212         } else {
3213             $defaultemplate = 'singletemplate';
3214         }
3216         $templates = $datanode->add(get_string('templates', 'data'));
3218         $templatelist = array ('listtemplate', 'singletemplate', 'asearchtemplate', 'addtemplate', 'rsstemplate', 'csstemplate', 'jstemplate');
3219         foreach ($templatelist as $template) {
3220             $templates->add(get_string($template, 'data'), new moodle_url('/mod/data/templates.php', array('d'=>$data->id,'mode'=>$template)));
3221         }
3223         $datanode->add(get_string('fields', 'data'), new moodle_url('/mod/data/field.php', array('d'=>$data->id)));
3224         $datanode->add(get_string('presets', 'data'), new moodle_url('/mod/data/preset.php', array('d'=>$data->id)));
3225     }
3227     if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
3228         require_once("$CFG->libdir/rsslib.php");
3230         $string = get_string('rsstype','forum');
3232         $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_data', $data->id));
3233         $datanode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
3234     }
3237 /**
3238  * Save the database configuration as a preset.
3239  *
3240  * @param stdClass $course The course the database module belongs to.
3241  * @param stdClass $cm The course module record
3242  * @param stdClass $data The database record
3243  * @param string $path
3244  * @return bool
3245  */
3246 function data_presets_save($course, $cm, $data, $path) {
3247     global $USER;
3248     $fs = get_file_storage();
3249     $filerecord = new stdClass;
3250     $filerecord->contextid = DATA_PRESET_CONTEXT;
3251     $filerecord->component = DATA_PRESET_COMPONENT;
3252     $filerecord->filearea = DATA_PRESET_FILEAREA;
3253     $filerecord->itemid = 0;
3254     $filerecord->filepath = '/'.$path.'/';
3255     $filerecord->userid = $USER->id;
3257     $filerecord->filename = 'preset.xml';
3258     $fs->create_file_from_string($filerecord, data_presets_generate_xml($course, $cm, $data));
3260     $filerecord->filename = 'singletemplate.html';
3261     $fs->create_file_from_string($filerecord, $data->singletemplate);
3263     $filerecord->filename = 'listtemplateheader.html';
3264     $fs->create_file_from_string($filerecord, $data->listtemplateheader);
3266     $filerecord->filename = 'listtemplate.html';
3267     $fs->create_file_from_string($filerecord, $data->listtemplate);
3269     $filerecord->filename = 'listtemplatefooter.html';
3270     $fs->create_file_from_string($filerecord, $data->listtemplatefooter);
3272     $filerecord->filename = 'addtemplate.html';
3273     $fs->create_file_from_string($filerecord, $data->addtemplate);
3275     $filerecord->filename = 'rsstemplate.html';
3276     $fs->create_file_from_string($filerecord, $data->rsstemplate);
3278     $filerecord->filename = 'rsstitletemplate.html';
3279     $fs->create_file_from_string($filerecord, $data->rsstitletemplate);
3281     $filerecord->filename = 'csstemplate.css';
3282     $fs->create_file_from_string($filerecord, $data->csstemplate);
3284     $filerecord->filename = 'jstemplate.js';
3285     $fs->create_file_from_string($filerecord, $data->jstemplate);
3287     $filerecord->filename = 'asearchtemplate.html';
3288     $fs->create_file_from_string($filerecord, $data->asearchtemplate);
3290     return true;
3293 /**
3294  * Generates the XML for the database module provided
3295  *
3296  * @global moodle_database $DB
3297  * @param stdClass $course The course the database module belongs to.
3298  * @param stdClass $cm The course module record
3299  * @param stdClass $data The database record
3300  * @return string The XML for the preset
3301  */
3302 function data_presets_generate_xml($course, $cm, $data) {
3303     global $DB;
3305     // Assemble "preset.xml":
3306     $presetxmldata = "<preset>\n\n";
3308     // Raw settings are not preprocessed during saving of presets
3309     $raw_settings = array(
3310         'intro',
3311         'comments',
3312         'requiredentries',
3313         'requiredentriestoview',
3314         'maxentries',
3315         'rssarticles',
3316         'approval',
3317         'defaultsortdir'
3318     );
3320     $presetxmldata .= "<settings>\n";
3321     // First, settings that do not require any conversion
3322     foreach ($raw_settings as $setting) {
3323         $presetxmldata .= "<$setting>" . htmlspecialchars($data->$setting) . "</$setting>\n";
3324     }
3326     // Now specific settings
3327     if ($data->defaultsort > 0 && $sortfield = data_get_field_from_id($data->defaultsort, $data)) {
3328         $presetxmldata .= '<defaultsort>' . htmlspecialchars($sortfield->field->name) . "</defaultsort>\n";
3329     } else {
3330         $presetxmldata .= "<defaultsort>0</defaultsort>\n";
3331     }
3332     $presetxmldata .= "</settings>\n\n";
3333     // Now for the fields. Grab all that are non-empty
3334     $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
3335     ksort($fields);
3336     if (!empty($fields)) {
3337         foreach ($fields as $field) {
3338             $presetxmldata .= "<field>\n";
3339             foreach ($field as $key => $value) {
3340                 if ($value != '' && $key != 'id' && $key != 'dataid') {
3341                     $presetxmldata .= "<$key>" . htmlspecialchars($value) . "</$key>\n";
3342                 }
3343             }
3344             $presetxmldata .= "</field>\n\n";
3345         }
3346     }
3347     $presetxmldata .= '</preset>';
3348     return $presetxmldata;
3351 function data_presets_export($course, $cm, $data, $tostorage=false) {
3352     global $CFG, $DB;
3354     $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi");
3355     $exportsubdir = "mod_data/presetexport/$presetname";
3356     make_temp_directory($exportsubdir);
3357     $exportdir = "$CFG->tempdir/$exportsubdir";
3359     // Assemble "preset.xml":
3360     $presetxmldata = data_presets_generate_xml($course, $cm, $data);
3362     // After opening a file in write mode, close it asap
3363     $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
3364     fwrite($presetxmlfile, $presetxmldata);
3365     fclose($presetxmlfile);
3367     // Now write the template files
3368     $singletemplate = fopen($exportdir . '/singletemplate.html', 'w');
3369     fwrite($singletemplate, $data->singletemplate);
3370     fclose($singletemplate);
3372     $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w');
3373     fwrite($listtemplateheader, $data->listtemplateheader);
3374     fclose($listtemplateheader);
3376     $listtemplate = fopen($exportdir . '/listtemplate.html', 'w');
3377     fwrite($listtemplate, $data->listtemplate);
3378     fclose($listtemplate);
3380     $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w');
3381     fwrite($listtemplatefooter, $data->listtemplatefooter);
3382     fclose($listtemplatefooter);
3384     $addtemplate = fopen($exportdir . '/addtemplate.html', 'w');
3385     fwrite($addtemplate, $data->addtemplate);
3386     fclose($addtemplate);
3388     $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w');
3389     fwrite($rsstemplate, $data->rsstemplate);
3390     fclose($rsstemplate);
3392     $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w');
3393     fwrite($rsstitletemplate, $data->rsstitletemplate);
3394     fclose($rsstitletemplate);
3396     $csstemplate = fopen($exportdir . '/csstemplate.css', 'w');
3397     fwrite($csstemplate, $data->csstemplate);
3398     fclose($csstemplate);
3400     $jstemplate = fopen($exportdir . '/jstemplate.js', 'w');
3401     fwrite($jstemplate, $data->jstemplate);
3402     fclose($jstemplate);
3404     $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w');
3405     fwrite($asearchtemplate, $data->asearchtemplate);
3406     fclose($asearchtemplate);
3408     // Check if all files have been generated
3409     if (! is_directory_a_preset($exportdir)) {
3410         print_error('generateerror', 'data');
3411     }
3413     $filenames = array(
3414         'preset.xml',
3415         'singletemplate.html',
3416         'listtemplateheader.html',
3417         'listtemplate.html',
3418         'listtemplatefooter.html',
3419         'addtemplate.html',
3420         'rsstemplate.html',
3421         'rsstitletemplate.html',
3422         'csstemplate.css',
3423         'jstemplate.js',
3424         'asearchtemplate.html'
3425     );
3427     $filelist = array();
3428     foreach ($filenames as $filename) {
3429         $filelist[$filename] = $exportdir . '/' . $filename;
3430     }
3432     $exportfile = $exportdir.'.zip';
3433     file_exists($exportfile) && unlink($exportfile);
3435     $fp = get_file_packer('application/zip');
3436     $fp->archive_to_pathname($filelist, $exportfile);
3438     foreach ($filelist as $file) {
3439         unlink($file);
3440     }
3441     rmdir($exportdir);
3443     // Return the full path to the exported preset file:
3444     return $exportfile;
3447 /**
3448  * Running addtional permission check on plugin, for example, plugins
3449  * may have switch to turn on/off comments option, this callback will
3450  * affect UI display, not like pluginname_comment_validate only throw
3451  * exceptions.
3452  * Capability check has been done in comment->check_permissions(), we
3453  * don't need to do it again here.
3454  *
3455  * @package  mod_data
3456  * @category comment
3457  *
3458  * @param stdClass $comment_param {
3459  *              context  => context the context object
3460  *              courseid => int course id
3461  *              cm       => stdClass course module object
3462  *              commentarea => string comment area
3463  *              itemid      => int itemid
3464  * }
3465  * @return array
3466  */
3467 function data_comment_permissions($comment_param) {
3468     global $CFG, $DB;
3469     if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3470         throw new comment_exception('invalidcommentitemid');
3471     }
3472     if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3473         throw new comment_exception('invalidid', 'data');
3474     }
3475     if ($data->comments) {
3476         return array('post'=>true, 'view'=>true);
3477     } else {
3478         return array('post'=>false, 'view'=>false);
3479     }
3482 /**
3483  * Validate comment parameter before perform other comments actions
3484  *
3485  * @package  mod_data
3486  * @category comment
3487  *
3488  * @param stdClass $comment_param {
3489  *              context  => context the context object
3490  *              courseid => int course id
3491  *              cm       => stdClass course module object
3492  *              commentarea => string comment area
3493  *              itemid      => int itemid
3494  * }
3495  * @return boolean
3496  */
3497 function data_comment_validate($comment_param) {
3498     global $DB;
3499     // validate comment area
3500     if ($comment_param->commentarea != 'database_entry') {
3501         throw new comment_exception('invalidcommentarea');
3502     }
3503     // validate itemid
3504     if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3505         throw new comment_exception('invalidcommentitemid');
3506     }
3507     if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3508         throw new comment_exception('invalidid', 'data');
3509     }
3510     if (!$course = $DB->get_record('course', array('id'=>$data->course))) {
3511         throw new comment_exception('coursemisconf');
3512     }
3513     if (!$cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
3514         throw new comment_exception('invalidcoursemodule');
3515     }
3516     if (!$data->comments) {
3517         throw new comment_exception('commentsoff', 'data');
3518     }
3519     $context = context_module::instance($cm->id);
3521     //check if approved
3522     if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3523         throw new comment_exception('notapproved', 'data');
3524     }
3526     // group access
3527     if ($record->groupid) {
3528         $groupmode = groups_get_activity_groupmode($cm, $course);
3529         if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3530             if (!groups_is_member($record->groupid)) {
3531                 throw new comment_exception('notmemberofgroup');
3532             }
3533         }
3534     }
3535     // validate context id
3536     if ($context->id != $comment_param->context->id) {
3537         throw new comment_exception('invalidcontext');
3538     }
3539     // validation for comment deletion
3540     if (!empty($comment_param->commentid)) {
3541         if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
3542             if ($comment->commentarea != 'database_entry') {
3543                 throw new comment_exception('invalidcommentarea');
3544             }
3545             if ($comment->contextid != $comment_param->context->id) {
3546                 throw new comment_exception('invalidcontext');
3547             }
3548             if ($comment->itemid != $comment_param->itemid) {
3549                 throw new comment_exception('invalidcommentitemid');
3550             }
3551         } else {
3552             throw new comment_exception('invalidcommentid');
3553         }
3554     }
3555     return true;
3558 /**
3559  * Return a list of page types
3560  * @param string $pagetype current page type
3561  * @param stdClass $parentcontext Block's parent context
3562  * @param stdClass $currentcontext Current context of block
3563  */
3564 function data_page_type_list($pagetype, $parentcontext, $currentcontext) {
3565     $module_pagetype = array('mod-data-*'=>get_string('page-mod-data-x', 'data'));
3566     return $module_pagetype;
3569 /**
3570  * Get all of the record ids from a database activity.
3571  *
3572  * @param int    $dataid      The dataid of the database module.
3573  * @param object $selectdata  Contains an additional sql statement for the
3574  *                            where clause for group and approval fields.
3575  * @param array  $params      Parameters that coincide with the sql statement.
3576  * @return array $idarray     An array of record ids
3577  */
3578 function data_get_all_recordids($dataid, $selectdata = '', $params = null) {
3579     global $DB;
3580     $initsql = 'SELECT r.id
3581                   FROM {data_records} r
3582                  WHERE r.dataid = :dataid';
3583     if ($selectdata != '') {
3584         $initsql .= $selectdata;
3585         $params = array_merge(array('dataid' => $dataid), $params);
3586     } else {
3587         $params = array('dataid' => $dataid);
3588     }
3589     $initsql .= ' GROUP BY r.id';
3590     $initrecord = $DB->get_recordset_sql($initsql, $params);
3591     $idarray = array();
3592     foreach ($initrecord as $data) {
3593         $idarray[] = $data->id;
3594     }
3595     // Close the record set and free up resources.
3596     $initrecord->close();
3597     return $idarray;
3600 /**
3601  * Get the ids of all the records that match that advanced search criteria
3602  * This goes and loops through each criterion one at a time until it either
3603  * runs out of records or returns a subset of records.
3604  *
3605  * @param array $recordids    An array of record ids.
3606  * @param array $searcharray  Contains information for the advanced search criteria
3607  * @param int $dataid         The data id of the database.
3608  * @return array $recordids   An array of record ids.
3609  */
3610 function data_get_advance_search_ids($recordids, $searcharray, $dataid) {
3611     $searchcriteria = array_keys($searcharray);
3612     // Loop through and reduce the IDs one search criteria at a time.
3613     foreach ($searchcriteria as $key) {
3614         $recordids = data_get_recordids($key, $searcharray, $dataid, $recordids);
3615         // If we don't have anymore IDs then stop.
3616         if (!$recordids) {
3617             break;
3618         }
3619     }
3620     return $recordids;
3623 /**
3624  * Gets the record IDs given the search criteria
3625  *
3626  * @param string $alias       Record alias.
3627  * @param array $searcharray  Criteria for the search.
3628  * @param int $dataid         Data ID for the database
3629  * @param array $recordids    An array of record IDs.
3630  * @return array $nestarray   An arry of record IDs
3631  */
3632 function data_get_recordids($alias, $searcharray, $dataid, $recordids) {
3633     global $DB;
3635     $nestsearch = $searcharray[$alias];
3636     // searching for content outside of mdl_data_content
3637     if ($alias < 0) {
3638         $alias = '';
3639     }
3640     list($insql, $params) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3641     $nestselect = 'SELECT c' . $alias . '.recordid
3642                      FROM {data_content} c' . $alias . ',
3643                           {data_fields} f,
3644                           {data_records} r,
3645                           {user} u ';
3646     $nestwhere = 'WHERE u.id = r.userid
3647                     AND f.id = c' . $alias . '.fieldid
3648                     AND r.id = c' . $alias . '.recordid
3649                     AND r.dataid = :dataid
3650                     AND c' . $alias .'.recordid ' . $insql . '
3651                     AND ';
3653     $params['dataid'] = $dataid;
3654     if (count($nestsearch->params) != 0) {
3655         $params = array_merge($params, $nestsearch->params);
3656         $nestsql = $nestselect . $nestwhere . $nestsearch->sql;
3657     } else {
3658         $thing = $DB->sql_like($nestsearch->field, ':search1', false);
3659         $nestsql = $nestselect . $nestwhere . $thing . ' GROUP BY c' . $alias . '.recordid';
3660         $params['search1'] = "%$nestsearch->data%";
3661     }
3662     $nestrecords = $DB->get_recordset_sql($nestsql, $params);
3663     $nestarray = array();
3664     foreach ($nestrecords as $data) {
3665         $nestarray[] = $data->recordid;
3666     }
3667     // Close the record set and free up resources.
3668     $nestrecords->close();
3669     return $nestarray;
3672 /**
3673  * Returns an array with an sql string for advanced searches and the parameters that go with them.
3674  *
3675  * @param int $sort            DATA_*
3676  * @param stdClass $data       Data module object
3677  * @param array $recordids     An array of record IDs.
3678  * @param string $selectdata   Information for the where and select part of the sql statement.
3679  * @param string $sortorder    Additional sort parameters
3680  * @return array sqlselect     sqlselect['sql'] has the sql string, sqlselect['params'] contains an array of parameters.
3681  */
3682 function data_get_advanced_search_sql($sort, $data, $recordids, $selectdata, $sortorder) {
3683     global $DB;
3685     $namefields = user_picture::fields('u');
3686     // Remove the id from the string. This already exists in the sql statement.
3687     $namefields = str_replace('u.id,', '', $namefields);
3689     if ($sort == 0) {
3690         $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . '
3691                         FROM {data_content} c,
3692                              {data_records} r,
3693                              {user} u ';
3694         $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' . $namefields;
3695     } else {
3696         // Sorting through 'Other' criteria
3697         if ($sort <= 0) {
3698             switch ($sort) {
3699                 case DATA_LASTNAME:
3700                     $sortcontentfull = "u.lastname";
3701                     break;
3702                 case DATA_FIRSTNAME:
3703                     $sortcontentfull = "u.firstname";
3704                     break;
3705                 case DATA_APPROVED:
3706                     $sortcontentfull = "r.approved";
3707                     break;
3708                 case DATA_TIMEMODIFIED:
3709                     $sortcontentfull = "r.timemodified";
3710                     break;
3711                 case DATA_TIMEADDED:
3712                 default:
3713                     $sortcontentfull = "r.timecreated";
3714             }
3715         } else {
3716             $sortfield = data_get_field_from_id($sort, $data);
3717             $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
3718             $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
3719         }
3721         $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ',
3722                                  ' . $sortcontentfull . '
3723                               AS sortorder
3724                             FROM {data_content} c,
3725                                  {data_records} r,
3726                                  {user} u ';
3727         $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ', ' .$sortcontentfull;
3728     }
3730     // Default to a standard Where statement if $selectdata is empty.
3731     if ($selectdata == '') {
3732         $selectdata = 'WHERE c.recordid = r.id
3733                          AND r.dataid = :dataid
3734                          AND r.userid = u.id ';
3735     }
3737     // Find the field we are sorting on
3738     if ($sort > 0 or data_get_field_from_id($sort, $data)) {
3739         $selectdata .= ' AND c.fieldid = :sort';
3740     }
3742     // If there are no record IDs then return an sql statment that will return no rows.
3743     if (count($recordids) != 0) {
3744         list($insql, $inparam) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3745     } else {
3746         list($insql, $inparam) = $DB->get_in_or_equal(array('-1'), SQL_PARAMS_NAMED);
3747     }
3748     $nestfromsql = $selectdata . ' AND c.recordid ' . $insql . $groupsql;
3749     $sqlselect['sql'] = "$nestselectsql $nestfromsql $sortorder";
3750     $sqlselect['params'] = $inparam;
3751     return $sqlselect;
3754 /**
3755  * Checks to see if the user has permission to delete the preset.
3756  * @param stdClass $context  Context object.
3757  * @param stdClass $preset  The preset object that we are checking for deletion.
3758  * @return bool  Returns true if the user can delete, otherwise false.
3759  */
3760 function data_user_can_delete_preset($context, $preset) {
3761     global $USER;
3763     if (has_capability('mod/data:manageuserpresets', $context)) {
3764         return true;
3765     } else {
3766         $candelete = false;
3767         if ($preset->userid == $USER->id) {
3768             $candelete = true;
3769         }
3770         return $candelete;
3771     }
3774 /**
3775  * Delete a record entry.
3776  *
3777  * @param int $recordid The ID for the record to be deleted.
3778  * @param object $data The data object for this activity.
3779  * @param int $courseid ID for the current course (for logging).
3780  * @param int $cmid The course module ID.
3781  * @return bool True if the record deleted, false if not.
3782  */
3783 function data_delete_record($recordid, $data, $courseid, $cmid) {
3784     global $DB, $CFG;
3786     if ($deleterecord = $DB->get_record('data_records', array('id' => $recordid))) {
3787         if ($deleterecord->dataid == $data->id) {
3788             if ($contents = $DB->get_records('data_content', array('recordid' => $deleterecord->id))) {
3789                 foreach ($contents as $content) {
3790                     if ($field = data_get_field_from_id($content->fieldid, $data)) {
3791                         $field->delete_content($content->recordid);
3792                     }
3793                 }
3794                 $DB->delete_records('data_content', array('recordid'=>$deleterecord->id));
3795                 $DB->delete_records('data_records', array('id'=>$deleterecord->id));
3797                 // Delete cached RSS feeds.
3798                 if (!empty($CFG->enablerssfeeds)) {
3799                     require_once($CFG->dirroot.'/mod/data/rsslib.php');
3800                     data_rss_delete_file($data);
3801                 }
3803                 // Trigger an event for deleting this record.
3804                 $event = \mod_data\event\record_deleted::create(array(
3805                     'objectid' => $deleterecord->id,
3806                     'context' => context_module::instance($cmid),
3807                     'courseid' => $courseid,
3808                     'other' => array(
3809                         'dataid' => $deleterecord->dataid
3810                     )
3811                 ));
3812                 $event->add_record_snapshot('data_records', $deleterecord);
3813                 $event->trigger();
3815                 return true;
3816             }
3817         }
3818     }
3819     return false;
3822 /**
3823  * Check for required fields, and build a list of fields to be updated in a
3824  * submission.
3825  *
3826  * @param $mod stdClass The current recordid - provided as an optimisation.
3827  * @param $fields array The field data
3828  * @param $datarecord stdClass The submitted data.
3829  * @return stdClass containing:
3830  * * string[] generalnotifications Notifications for the form as a whole.
3831  * * string[] fieldnotifications Notifications for a specific field.
3832  * * bool validated Whether the field was validated successfully.
3833  * * data_field_base[] fields The field objects to be update.
3834  */
3835 function data_process_submission(stdClass $mod, $fields, stdClass $datarecord) {
3836     $result = new stdClass();
3838     // Empty form checking - you can't submit an empty form.
3839     $emptyform = true;
3840     $requiredfieldsfilled = true;
3842     // Store the notifications.
3843     $result->generalnotifications = array();
3844     $result->fieldnotifications = array();
3846     // Store the instantiated classes as an optimisation when processing the result.
3847     // This prevents the fields being re-initialised when updating.
3848     $result->fields = array();
3850     $submitteddata = array();
3851     foreach ($datarecord as $fieldname => $fieldvalue) {
3852         if (strpos($fieldname, '_')) {
3853             $namearray = explode('_', $fieldname, 3);
3854             $fieldid = $namearray[1];
3855             if (!isset($submitteddata[$fieldid])) {
3856                 $submitteddata[$fieldid] = array();
3857             }
3858             if (count($namearray) === 2) {
3859                 $subfieldid = 0;
3860             } else {
3861                 $subfieldid = $namearray[2];
3862             }
3864             $fielddata = new stdClass();
3865             $fielddata->fieldname = $fieldname;
3866             $fielddata->value = $fieldvalue;
3867             $submitteddata[$fieldid][$subfieldid] = $fielddata;
3868         }
3869     }
3871     // Check all form fields which have the required are filled.
3872     foreach ($fields as $fieldrecord) {
3873         // Check whether the field has any data.
3874         $fieldhascontent = false;
3876         $field = data_get_field($fieldrecord, $mod);
3877         if (isset($submitteddata[$fieldrecord->id])) {
3878             foreach ($submitteddata[$fieldrecord->id] as $fieldname => $value) {
3879                 if ($field->notemptyfield($value->value, $value->fieldname)) {
3880                     // The field has content and the form is not empty.
3881                     $fieldhascontent = true;
3882                     $emptyform = false;
3883                 }
3884             }
3885         }
3887         // If the field is required, add a notification to that effect.
3888         if ($field->field->required && !$fieldhascontent) {
3889             if (!isset($result->fieldnotifications[$field->field->name])) {
3890                 $result->fieldnotifications[$field->field->name] = array();
3891             }
3892             $result->fieldnotifications[$field->field->name][] = get_string('errormustsupplyvalue', 'data');
3893             $requiredfieldsfilled = false;
3894         }
3896         // Update the field.
3897         if (isset($submitteddata[$fieldrecord->id])) {
3898             foreach ($submitteddata[$fieldrecord->id] as $value) {
3899                 $result->fields[$value->fieldname] = $field;
3900             }
3901         }
3902     }
3904     if ($emptyform) {
3905         // The form is empty.
3906         $result->generalnotifications[] = get_string('emptyaddform', 'data');
3907     }
3909     $result->validated = $requiredfieldsfilled && !$emptyform;
3911     return $result;