3 // This file is part of Moodle - http://moodle.org/
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.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
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.
46 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
47 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 class data_field_base { // Base class for Database Field Types (see field/*/field.class.php)
51 /** @var string Subclasses must override the type with their name */
52 var $type = 'unknown';
53 /** @var object The database object that this field belongs to */
55 /** @var object The field object itself, if we know it */
57 /** @var int Width of the icon for this fieldtype */
59 /** @var int Width of the icon for this fieldtype */
61 /** @var object course module or cmifno */
63 /** @var object activity context */
67 * Constructor function
70 * @uses CONTEXT_MODULE
75 function __construct($field=0, $data=0, $cm=0) { // Field or data or both, each can be id or object
78 if (empty($field) && empty($data)) {
79 print_error('missingfield', 'data');
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');
89 if (!$this->data = $DB->get_record('data', array('id'=>$this->field->dataid))) {
90 print_error('invalidid', 'data');
95 if (empty($this->data)) { // We need to define this properly
97 if (is_object($data)) {
98 $this->data = $data; // Programmer knows what they are doing, we hope
99 } else if (!$this->data = $DB->get_record('data', array('id'=>$data))) {
100 print_error('invalidid', 'data');
102 } else { // No way to define it!
103 print_error('missingdata', 'data');
110 $this->cm = get_coursemodule_from_instance('data', $this->data->id);
113 if (empty($this->field)) { // We need to define some default values
114 $this->define_default_field();
117 $this->context = context_module::instance($this->cm->id);
122 * This field just sets up a default field object
126 function define_default_field() {
128 if (empty($this->data->id)) {
129 echo $OUTPUT->notification('Programmer error: dataid not defined in field class');
131 $this->field = new stdClass();
132 $this->field->id = 0;
133 $this->field->dataid = $this->data->id;
134 $this->field->type = $this->type;
135 $this->field->param1 = '';
136 $this->field->param2 = '';
137 $this->field->param3 = '';
138 $this->field->name = '';
139 $this->field->description = '';
140 $this->field->required = false;
146 * Set up the field object according to data in an object. Now is the time to clean it!
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);
161 if (isset($data->param2)) {
162 $this->field->param2 = trim($data->param2);
164 if (isset($data->param3)) {
165 $this->field->param3 = trim($data->param3);
167 if (isset($data->param4)) {
168 $this->field->param4 = trim($data->param4);
170 if (isset($data->param5)) {
171 $this->field->param5 = trim($data->param5);
178 * Insert a new field in the database
179 * We assume the field object is already defined as $this->field
184 function insert_field() {
187 if (empty($this->field)) {
188 echo $OUTPUT->notification('Programmer error: Field has not been defined yet! See define_field()');
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,
199 'fieldname' => $this->field->name,
200 'dataid' => $this->data->id
210 * Update a field in the database
215 function update_field() {
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,
225 'fieldname' => $this->field->name,
226 'dataid' => $this->data->id
235 * Delete a field completely
240 function delete_field() {
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,
255 'fieldname' => $this->field->name,
256 'dataid' => $this->data->id
259 $event->add_record_snapshot('data_fields', $field);
267 * Print the relevant form element in the ADD template for this field
270 * @param int $recordid
273 function display_add_field($recordid=0, $formdata=null) {
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));
285 // beware get_field returns false for new, empty records MDL-18567
286 if ($content===false) {
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');
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).'" />';
305 * Print the relevant form element to define the attributes for this field
306 * viewable by teachers only.
310 * @return void Output is echo'd
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();
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');
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');
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";
344 echo $OUTPUT->box_end();
348 * Display the content of the field in browse mode
351 * @param int $recordid
352 * @param object $template
353 * @return bool|string
355 function display_browse_field($recordid, $template) {
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;
366 $options->para = false;
367 $str = format_text($content->content, $content->content1, $options);
377 * Update the content of one data field in the data_content table
379 * @param int $recordid
380 * @param mixed $value
381 * @param string $name
384 function update_content($recordid, $value, $name=''){
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);
396 return $DB->insert_record('data_content', $content);
401 * Delete all content associated with the field
404 * @param int $recordid
407 function delete_content($recordid=0) {
411 $conditions = array('fieldid'=>$this->field->id, 'recordid'=>$recordid);
413 $conditions = array('fieldid'=>$this->field->id);
416 $rs = $DB->get_recordset('data_content', $conditions);
418 $fs = get_file_storage();
419 foreach ($rs as $content) {
420 $fs->delete_area_files($this->context->id, 'mod_data', 'content', $content->id);
425 return $DB->delete_records('data_content', $conditions);
429 * Check if a field from an add form is empty
431 * @param mixed $value
435 function notemptyfield($value, $name) {
436 return !empty($value);
440 * Just in case a field needs to print something before the whole form
442 function print_before_form() {
446 * Just in case a field needs to print something after the whole form
448 function print_after_form() {
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
458 function get_sort_field() {
463 * Returns the SQL needed to refer to the column. Some fields may need to CAST() etc.
465 * @param string $fieldname
466 * @return string $fieldname
468 function get_sort_sql($fieldname) {
473 * Returns the name/type of the field
478 return get_string('name'.$this->type, 'data');
482 * Prints the respective type icon
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>';
499 * Per default, it is assumed that fields support text exporting.
500 * Override this (return false) on fields not supporting text exporting.
504 function text_export_supported() {
509 * Per default, return the record's text value only from the "content" field.
510 * Override this in fields class if necesarry.
512 * @param string $record
515 function export_text_value($record) {
516 if ($this->text_export_supported()) {
517 return $record->content;
522 * @param string $relativepath
525 function file_ok($relativepath) {
532 * Given a template and a dataid, generate a default case template
535 * @param object $data
536 * @param string template [addtemplate, singletemplate, listtempalte, rsstemplate]
537 * @param int $recordid
539 * @param bool $update
540 * @return bool|string
542 function data_generate_default_template(&$data, $template, $recordid=0, $form=false, $update=true) {
545 if (!$data && !$template) {
548 if ($template == 'csstemplate' or $template == 'jstemplate' ) {
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.']]';
566 $table->data[] = array(
571 if ($template == 'listtemplate') {
572 $cell = new html_table_cell('##edit## ##more## ##delete## ##approve## ##disapprove## ##export##');
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##');
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;
591 if ($template == 'listtemplate'){
592 $str .= '##delcheck##';
593 $str .= html_writer::empty_tag('br');
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');
604 $newdata = new stdClass();
605 $newdata->id = $data->id;
606 $newdata->{$template} = $str;
607 $DB->update_record('data', $newdata);
608 $data->{$template} = $str;
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.
622 * @param object $data
623 * @param string $searchfieldname
624 * @param string $newfieldname
627 function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
630 if (!empty($newfieldname)) {
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);
663 * Appends a new field at the end of the form template.
666 * @param object $data
667 * @param string $newfieldname
669 function data_append_new_field_to_templates($data, $newfieldname) {
672 $newdata = new stdClass();
673 $newdata->id = $data->id;
676 if (!empty($data->singletemplate)) {
677 $newdata->singletemplate = $data->singletemplate.' [[' . $newfieldname .']]';
680 if (!empty($data->addtemplate)) {
681 $newdata->addtemplate = $data->addtemplate.' [[' . $newfieldname . ']]';
684 if (!empty($data->rsstemplate)) {
685 $newdata->rsstemplate = $data->singletemplate.' [[' . $newfieldname . ']]';
689 $DB->update_record('data', $newdata);
696 * this function creates an instance of the particular subfield class
699 * @param string $name
700 * @param object $data
701 * @return object|bool
703 function data_get_field_from_name($name, $data){
706 $field = $DB->get_record('data_fields', array('name'=>$name, 'dataid'=>$data->id));
709 return data_get_field($field, $data);
717 * this function creates an instance of the particular subfield class
720 * @param int $fieldid
721 * @param object $data
722 * @return bool|object
724 function data_get_field_from_id($fieldid, $data){
727 $field = $DB->get_record('data_fields', array('id'=>$fieldid, 'dataid'=>$data->id));
730 return data_get_field($field, $data);
738 * this function creates an instance of the particular subfield class
741 * @param string $type
742 * @param object $data
745 function data_get_field_new($type, $data) {
748 require_once($CFG->dirroot.'/mod/data/field/'.$type.'/field.class.php');
749 $newfield = 'data_field_'.$type;
750 $newfield = new $newfield(0, $data);
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
760 * @param object $field
761 * @param object $data
765 function data_get_field($field, $data, $cm=null) {
769 require_once('field/'.$field->type.'/field.class.php');
770 $newfield = 'data_field_'.$field->type;
771 $newfield = new $newfield($field, $data, $cm);
778 * Given record object (or id), returns true if the record belongs to the current user
782 * @param mixed $record record object or id
785 function data_isowner($record) {
788 if (!isloggedin()) { // perf shortcut
792 if (!is_object($record)) {
793 if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
798 return ($record->userid == $USER->id);
802 * has a user reached the max number of entries?
804 * @param object $data
807 function data_atmaxentries($data){
808 if (!$data->maxentries){
812 return (data_numentries($data) >= $data->maxentries);
817 * returns the number of entries already made by this user
821 * @param object $data
824 function data_numentries($data){
826 $sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
827 return $DB->count_records_sql($sql, array($data->id, $USER->id));
831 * function that takes in a dataid and adds a record
832 * this is used everytime an add template is submitted
836 * @param object $data
837 * @param int $groupid
840 function data_add_record($data, $groupid=0){
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;
854 $record->approved = 0;
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,
863 'dataid' => $data->id
872 * check the multple existence any tag in a template
874 * check to see if there are 2 or more of the same tag being used.
877 * @param int $dataid,
878 * @param string $template
881 function data_tags_check($dataid, $template) {
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){
892 echo $OUTPUT->notification('[['.$field->name.']] - '.get_string('multipletags','data'));
900 * Adds an instance of a data
902 * @param stdClass $data
903 * @param mod_data_mod_form $mform
904 * @return int intance id
906 function data_add_instance($data, $mform = null) {
909 if (empty($data->assessed)) {
913 if (empty($data->ratingtime) || empty($data->assessed)) {
914 $data->assesstimestart = 0;
915 $data->assesstimefinish = 0;
918 $data->timemodified = time();
920 $data->id = $DB->insert_record('data', $data);
922 data_grade_item_update($data);
928 * updates an instance of a data
931 * @param object $data
934 function data_update_instance($data) {
937 $data->timemodified = time();
938 $data->id = $data->instance;
940 if (empty($data->assessed)) {
944 if (empty($data->ratingtime) or empty($data->assessed)) {
945 $data->assesstimestart = 0;
946 $data->assesstimefinish = 0;
949 if (empty($data->notification)) {
950 $data->notification = 0;
953 $DB->update_record('data', $data);
955 data_grade_item_update($data);
962 * deletes an instance of a data
968 function data_delete_instance($id) { // takes the dataid
971 if (!$data = $DB->get_record('data', array('id'=>$id))) {
975 $cm = get_coursemodule_from_instance('data', $data->id);
976 $context = context_module::instance($cm->id);
978 /// Delete all the associated information
981 $fs = get_file_storage();
982 $fs->delete_area_files($context->id, 'mod_data');
984 // get all the records in this data
986 FROM {data_records} r
989 $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
991 // delete all the records and fields
992 $DB->delete_records('data_records', array('dataid'=>$id));
993 $DB->delete_records('data_fields', array('dataid'=>$id));
995 // Delete the instance itself
996 $result = $DB->delete_records('data', array('id'=>$id));
999 data_grade_item_delete($data);
1005 * returns a summary of data activity of this user
1008 * @param object $course
1009 * @param object $user
1010 * @param object $mod
1011 * @param object $data
1012 * @return object|null
1014 function data_user_outline($course, $user, $mod, $data) {
1016 require_once("$CFG->libdir/gradelib.php");
1018 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1019 if (empty($grades->items[0]->grades)) {
1022 $grade = reset($grades->items[0]->grades);
1026 if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id, 'userid'=>$user->id))) {
1027 $result = new stdClass();
1028 $result->info = get_string('numrecords', 'data', $countrecords);
1029 $lastrecord = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
1030 WHERE dataid = ? AND userid = ?
1031 ORDER BY timemodified DESC', array($data->id, $user->id), true);
1032 $result->time = $lastrecord->timemodified;
1034 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1037 } else if ($grade) {
1038 $result = new stdClass();
1039 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1041 //datesubmitted == time created. dategraded == time modified or time overridden
1042 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1043 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1044 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1045 $result->time = $grade->dategraded;
1047 $result->time = $grade->datesubmitted;
1056 * Prints all the records uploaded by this user
1059 * @param object $course
1060 * @param object $user
1061 * @param object $mod
1062 * @param object $data
1064 function data_user_complete($course, $user, $mod, $data) {
1065 global $DB, $CFG, $OUTPUT;
1066 require_once("$CFG->libdir/gradelib.php");
1068 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1069 if (!empty($grades->items[0]->grades)) {
1070 $grade = reset($grades->items[0]->grades);
1071 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1072 if ($grade->str_feedback) {
1073 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1077 if ($records = $DB->get_records('data_records', array('dataid'=>$data->id,'userid'=>$user->id), 'timemodified DESC')) {
1078 data_print_template('singletemplate', $records, $data);
1083 * Return grade for given user or all users.
1086 * @param object $data
1087 * @param int $userid optional user id, 0 means all users
1088 * @return array array of grades, false if none
1090 function data_get_user_grades($data, $userid=0) {
1093 require_once($CFG->dirroot.'/rating/lib.php');
1095 $ratingoptions = new stdClass;
1096 $ratingoptions->component = 'mod_data';
1097 $ratingoptions->ratingarea = 'entry';
1098 $ratingoptions->modulename = 'data';
1099 $ratingoptions->moduleid = $data->id;
1101 $ratingoptions->userid = $userid;
1102 $ratingoptions->aggregationmethod = $data->assessed;
1103 $ratingoptions->scaleid = $data->scale;
1104 $ratingoptions->itemtable = 'data_records';
1105 $ratingoptions->itemtableusercolumn = 'userid';
1107 $rm = new rating_manager();
1108 return $rm->get_user_grades($ratingoptions);
1112 * Update activity grades
1115 * @param object $data
1116 * @param int $userid specific user only, 0 means all
1117 * @param bool $nullifnone
1119 function data_update_grades($data, $userid=0, $nullifnone=true) {
1121 require_once($CFG->libdir.'/gradelib.php');
1123 if (!$data->assessed) {
1124 data_grade_item_update($data);
1126 } else if ($grades = data_get_user_grades($data, $userid)) {
1127 data_grade_item_update($data, $grades);
1129 } else if ($userid and $nullifnone) {
1130 $grade = new stdClass();
1131 $grade->userid = $userid;
1132 $grade->rawgrade = NULL;
1133 data_grade_item_update($data, $grade);
1136 data_grade_item_update($data);
1141 * Update/create grade item for given data
1144 * @param stdClass $data A database instance with extra cmidnumber property
1145 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1146 * @return object grade_item
1148 function data_grade_item_update($data, $grades=NULL) {
1150 require_once($CFG->libdir.'/gradelib.php');
1152 $params = array('itemname'=>$data->name, 'idnumber'=>$data->cmidnumber);
1154 if (!$data->assessed or $data->scale == 0) {
1155 $params['gradetype'] = GRADE_TYPE_NONE;
1157 } else if ($data->scale > 0) {
1158 $params['gradetype'] = GRADE_TYPE_VALUE;
1159 $params['grademax'] = $data->scale;
1160 $params['grademin'] = 0;
1162 } else if ($data->scale < 0) {
1163 $params['gradetype'] = GRADE_TYPE_SCALE;
1164 $params['scaleid'] = -$data->scale;
1167 if ($grades === 'reset') {
1168 $params['reset'] = true;
1172 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, $grades, $params);
1176 * Delete grade item for given data
1179 * @param object $data object
1180 * @return object grade_item
1182 function data_grade_item_delete($data) {
1184 require_once($CFG->libdir.'/gradelib.php');
1186 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, NULL, array('deleted'=>1));
1191 * takes a list of records, the current data, a search string,
1192 * and mode to display prints the translated template
1196 * @param string $template
1197 * @param array $records
1198 * @param object $data
1199 * @param string $search
1201 * @param bool $return
1202 * @param object $jumpurl a moodle_url by which to jump back to the record list (can be null)
1205 function data_print_template($template, $records, $data, $search='', $page=0, $return=false, moodle_url $jumpurl=null) {
1206 global $CFG, $DB, $OUTPUT;
1208 $cm = get_coursemodule_from_instance('data', $data->id);
1209 $context = context_module::instance($cm->id);
1211 static $fields = NULL;
1213 static $dataid = NULL;
1215 if (empty($dataid)) {
1216 $dataid = $data->id;
1217 } else if ($dataid != $data->id) {
1221 if (empty($fields)) {
1222 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1223 foreach ($fieldrecords as $fieldrecord) {
1224 $fields[]= data_get_field($fieldrecord, $data);
1226 $isteacher = has_capability('mod/data:managetemplates', $context);
1229 if (empty($records)) {
1234 $jumpurl = new moodle_url('/mod/data/view.php', array('d' => $data->id));
1236 $jumpurl = new moodle_url($jumpurl, array('page' => $page, 'sesskey' => sesskey()));
1238 foreach ($records as $record) { // Might be just one for the single template
1241 $patterns = array();
1242 $replacement = array();
1244 // Then we generate strings to replace for normal tags
1245 foreach ($fields as $field) {
1246 $patterns[]='[['.$field->field->name.']]';
1247 $replacement[] = highlight($search, $field->display_browse_field($record->id, $template));
1250 $canmanageentries = has_capability('mod/data:manageentries', $context);
1252 // Replacing special tags (##Edit##, ##Delete##, ##More##)
1253 $patterns[]='##edit##';
1254 $patterns[]='##delete##';
1255 if (data_user_can_manage_entry($record, $data, $context)) {
1256 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d='
1257 .$data->id.'&rid='.$record->id.'&sesskey='.sesskey().'"><img src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" alt="'.get_string('edit').'" title="'.get_string('edit').'" /></a>';
1258 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='
1259 .$data->id.'&delete='.$record->id.'&sesskey='.sesskey().'"><img src="'.$OUTPUT->pix_url('t/delete') . '" class="iconsmall" alt="'.get_string('delete').'" title="'.get_string('delete').'" /></a>';
1261 $replacement[] = '';
1262 $replacement[] = '';
1265 $moreurl = $CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&rid=' . $record->id;
1267 $moreurl .= '&filter=1';
1269 $patterns[]='##more##';
1270 $replacement[] = '<a href="'.$moreurl.'"><img src="'.$OUTPUT->pix_url('t/preview').
1271 '" class="iconsmall" alt="'.get_string('more', 'data').'" title="'.get_string('more', 'data').
1274 $patterns[]='##moreurl##';
1275 $replacement[] = $moreurl;
1277 $patterns[]='##delcheck##';
1278 if ($canmanageentries) {
1279 $replacement[] = html_writer::checkbox('delcheck[]', $record->id, false, '', array('class' => 'recordcheckbox'));
1281 $replacement[] = '';
1284 $patterns[]='##user##';
1285 $replacement[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$record->userid.
1286 '&course='.$data->course.'">'.fullname($record).'</a>';
1288 $patterns[] = '##userpicture##';
1289 $ruser = user_picture::unalias($record, null, 'userid');
1290 $replacement[] = $OUTPUT->user_picture($ruser, array('courseid' => $data->course));
1292 $patterns[]='##export##';
1294 if (!empty($CFG->enableportfolios) && ($template == 'singletemplate' || $template == 'listtemplate')
1295 && ((has_capability('mod/data:exportentry', $context)
1296 || (data_isowner($record->id) && has_capability('mod/data:exportownentry', $context))))) {
1297 require_once($CFG->libdir . '/portfoliolib.php');
1298 $button = new portfolio_add_button();
1299 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id, 'recordid' => $record->id), 'mod_data');
1300 list($formats, $files) = data_portfolio_caller::formats($fields, $record);
1301 $button->set_formats($formats);
1302 $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1304 $replacement[] = '';
1307 $patterns[] = '##timeadded##';
1308 $replacement[] = userdate($record->timecreated);
1310 $patterns[] = '##timemodified##';
1311 $replacement [] = userdate($record->timemodified);
1313 $patterns[]='##approve##';
1314 if (has_capability('mod/data:approve', $context) && ($data->approval) && (!$record->approved)) {
1315 $approveurl = new moodle_url($jumpurl, array('approve' => $record->id));
1316 $approveicon = new pix_icon('t/approve', get_string('approve', 'data'), '', array('class' => 'iconsmall'));
1317 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($approveurl, $approveicon),
1318 array('class' => 'approve'));
1320 $replacement[] = '';
1323 $patterns[]='##disapprove##';
1324 if (has_capability('mod/data:approve', $context) && ($data->approval) && ($record->approved)) {
1325 $disapproveurl = new moodle_url($jumpurl, array('disapprove' => $record->id));
1326 $disapproveicon = new pix_icon('t/block', get_string('disapprove', 'data'), '', array('class' => 'iconsmall'));
1327 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($disapproveurl, $disapproveicon),
1328 array('class' => 'disapprove'));
1330 $replacement[] = '';
1333 $patterns[] = '##approvalstatus##';
1334 if (!$data->approval) {
1335 $replacement[] = '';
1336 } else if ($record->approved) {
1337 $replacement[] = 'approved';
1339 $replacement[] = 'notapproved';
1342 $patterns[]='##comments##';
1343 if (($template == 'listtemplate') && ($data->comments)) {
1345 if (!empty($CFG->usecomments)) {
1346 require_once($CFG->dirroot . '/comment/lib.php');
1347 list($context, $course, $cm) = get_context_info_array($context->id);
1348 $cmt = new stdClass();
1349 $cmt->context = $context;
1350 $cmt->course = $course;
1352 $cmt->area = 'database_entry';
1353 $cmt->itemid = $record->id;
1354 $cmt->showcount = true;
1355 $cmt->component = 'mod_data';
1356 $comment = new comment($cmt);
1357 $replacement[] = $comment->output(true);
1360 $replacement[] = '';
1363 // actual replacement of the tags
1364 $newtext = str_ireplace($patterns, $replacement, $data->{$template});
1366 // no more html formatting and filtering - see MDL-6635
1372 // hack alert - return is always false in singletemplate anyway ;-)
1373 /**********************************
1374 * Printing Ratings Form *
1375 *********************************/
1376 if ($template == 'singletemplate') { //prints ratings options
1377 data_print_ratings($data, $record);
1380 /**********************************
1381 * Printing Comments Form *
1382 *********************************/
1383 if (($template == 'singletemplate') && ($data->comments)) {
1384 if (!empty($CFG->usecomments)) {
1385 require_once($CFG->dirroot . '/comment/lib.php');
1386 list($context, $course, $cm) = get_context_info_array($context->id);
1387 $cmt = new stdClass();
1388 $cmt->context = $context;
1389 $cmt->course = $course;
1391 $cmt->area = 'database_entry';
1392 $cmt->itemid = $record->id;
1393 $cmt->showcount = true;
1394 $cmt->component = 'mod_data';
1395 $comment = new comment($cmt);
1396 $comment->output(false);
1404 * Return rating related permissions
1406 * @param string $contextid the context id
1407 * @param string $component the component to get rating permissions for
1408 * @param string $ratingarea the rating area to get permissions for
1409 * @return array an associative array of the user's rating permissions
1411 function data_rating_permissions($contextid, $component, $ratingarea) {
1412 $context = context::instance_by_id($contextid, MUST_EXIST);
1413 if ($component != 'mod_data' || $ratingarea != 'entry') {
1417 'view' => has_capability('mod/data:viewrating',$context),
1418 'viewany' => has_capability('mod/data:viewanyrating',$context),
1419 'viewall' => has_capability('mod/data:viewallratings',$context),
1420 'rate' => has_capability('mod/data:rate',$context)
1425 * Validates a submitted rating
1426 * @param array $params submitted data
1427 * context => object the context in which the rated items exists [required]
1428 * itemid => int the ID of the object being rated
1429 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1430 * rating => int the submitted rating
1431 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1432 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
1433 * @return boolean true if the rating is valid. Will throw rating_exception if not
1435 function data_rating_validate($params) {
1438 // Check the component is mod_data
1439 if ($params['component'] != 'mod_data') {
1440 throw new rating_exception('invalidcomponent');
1443 // Check the ratingarea is entry (the only rating area in data module)
1444 if ($params['ratingarea'] != 'entry') {
1445 throw new rating_exception('invalidratingarea');
1448 // Check the rateduserid is not the current user .. you can't rate your own entries
1449 if ($params['rateduserid'] == $USER->id) {
1450 throw new rating_exception('nopermissiontorate');
1453 $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
1454 FROM {data_records} r
1455 JOIN {data} d ON r.dataid = d.id
1456 WHERE r.id = :itemid";
1457 $dataparams = array('itemid'=>$params['itemid']);
1458 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1459 //item doesn't exist
1460 throw new rating_exception('invaliditemid');
1463 if ($info->scale != $params['scaleid']) {
1464 //the scale being submitted doesnt match the one in the database
1465 throw new rating_exception('invalidscaleid');
1468 //check that the submitted rating is valid for the scale
1471 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
1472 throw new rating_exception('invalidnum');
1476 if ($info->scale < 0) {
1477 //its a custom scale
1478 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
1480 $scalearray = explode(',', $scalerecord->scale);
1481 if ($params['rating'] > count($scalearray)) {
1482 throw new rating_exception('invalidnum');
1485 throw new rating_exception('invalidscaleid');
1487 } else if ($params['rating'] > $info->scale) {
1488 //if its numeric and submitted rating is above maximum
1489 throw new rating_exception('invalidnum');
1492 if ($info->approval && !$info->approved) {
1493 //database requires approval but this item isnt approved
1494 throw new rating_exception('nopermissiontorate');
1497 // check the item we're rating was created in the assessable time window
1498 if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
1499 if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
1500 throw new rating_exception('notavailable');
1504 $course = $DB->get_record('course', array('id'=>$info->course), '*', MUST_EXIST);
1505 $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1506 $context = context_module::instance($cm->id);
1508 // if the supplied context doesnt match the item's context
1509 if ($context->id != $params['context']->id) {
1510 throw new rating_exception('invalidcontext');
1513 // Make sure groups allow this user to see the item they're rating
1514 $groupid = $info->groupid;
1515 if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
1516 if (!groups_group_exists($groupid)) { // Can't find group
1517 throw new rating_exception('cannotfindgroup');//something is wrong
1520 if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1521 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
1522 throw new rating_exception('notmemberofgroup');
1530 * Can the current user see ratings for a given itemid?
1532 * @param array $params submitted data
1533 * contextid => int contextid [required]
1534 * component => The component for this module - should always be mod_data [required]
1535 * ratingarea => object the context in which the rated items exists [required]
1536 * itemid => int the ID of the object being rated [required]
1537 * scaleid => int scale id [optional]
1539 * @throws coding_exception
1540 * @throws rating_exception
1542 function mod_data_rating_can_see_item_ratings($params) {
1545 // Check the component is mod_data.
1546 if (!isset($params['component']) || $params['component'] != 'mod_data') {
1547 throw new rating_exception('invalidcomponent');
1550 // Check the ratingarea is entry (the only rating area in data).
1551 if (!isset($params['ratingarea']) || $params['ratingarea'] != 'entry') {
1552 throw new rating_exception('invalidratingarea');
1555 if (!isset($params['itemid'])) {
1556 throw new rating_exception('invaliditemid');
1559 $datasql = "SELECT d.id as dataid, d.course, r.groupid
1560 FROM {data_records} r
1561 JOIN {data} d ON r.dataid = d.id
1562 WHERE r.id = :itemid";
1563 $dataparams = array('itemid' => $params['itemid']);
1564 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1565 // Item doesn't exist.
1566 throw new rating_exception('invaliditemid');
1569 // User can see ratings of all participants.
1570 if ($info->groupid == 0) {
1574 $course = $DB->get_record('course', array('id' => $info->course), '*', MUST_EXIST);
1575 $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1577 // Make sure groups allow this user to see the item they're rating.
1578 return groups_group_visible($info->groupid, $course, $cm);
1583 * function that takes in the current data, number of items per page,
1584 * a search string and prints a preference box in view.php
1586 * This preference box prints a searchable advanced search template if
1587 * a) A template is defined
1588 * b) The advanced search checkbox is checked.
1592 * @param object $data
1593 * @param int $perpage
1594 * @param string $search
1595 * @param string $sort
1596 * @param string $order
1597 * @param array $search_array
1598 * @param int $advanced
1599 * @param string $mode
1602 function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
1603 global $CFG, $DB, $PAGE, $OUTPUT;
1605 $cm = get_coursemodule_from_instance('data', $data->id);
1606 $context = context_module::instance($cm->id);
1607 echo '<br /><div class="datapreferences">';
1608 echo '<form id="options" action="view.php" method="get">';
1610 echo '<input type="hidden" name="d" value="'.$data->id.'" />';
1611 if ($mode =='asearch') {
1613 echo '<input type="hidden" name="mode" value="list" />';
1615 echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
1616 $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
1617 20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
1618 echo html_writer::select($pagesizes, 'perpage', $perpage, false, array('id'=>'pref_perpage'));
1621 $regsearchclass = 'search_none';
1622 $advancedsearchclass = 'search_inline';
1624 $regsearchclass = 'search_inline';
1625 $advancedsearchclass = 'search_none';
1627 echo '<div id="reg_search" class="' . $regsearchclass . '" > ';
1628 echo '<label for="pref_search">'.get_string('search').'</label> <input type="text" size="16" name="search" id= "pref_search" value="'.s($search).'" /></div>';
1629 echo ' <label for="pref_sortby">'.get_string('sortby').'</label> ';
1630 // foreach field, print the option
1631 echo '<select name="sort" id="pref_sortby">';
1632 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'name')) {
1633 echo '<optgroup label="'.get_string('fields', 'data').'">';
1634 foreach ($fields as $field) {
1635 if ($field->id == $sort) {
1636 echo '<option value="'.$field->id.'" selected="selected">'.$field->name.'</option>';
1638 echo '<option value="'.$field->id.'">'.$field->name.'</option>';
1644 $options[DATA_TIMEADDED] = get_string('timeadded', 'data');
1645 $options[DATA_TIMEMODIFIED] = get_string('timemodified', 'data');
1646 $options[DATA_FIRSTNAME] = get_string('authorfirstname', 'data');
1647 $options[DATA_LASTNAME] = get_string('authorlastname', 'data');
1648 if ($data->approval and has_capability('mod/data:approve', $context)) {
1649 $options[DATA_APPROVED] = get_string('approved', 'data');
1651 echo '<optgroup label="'.get_string('other', 'data').'">';
1652 foreach ($options as $key => $name) {
1653 if ($key == $sort) {
1654 echo '<option value="'.$key.'" selected="selected">'.$name.'</option>';
1656 echo '<option value="'.$key.'">'.$name.'</option>';
1661 echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
1662 echo '<select id="pref_order" name="order">';
1663 if ($order == 'ASC') {
1664 echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
1666 echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1668 if ($order == 'DESC') {
1669 echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
1671 echo '<option value="DESC">'.get_string('descending','data').'</option>';
1676 $checked = ' checked="checked" ';
1681 $PAGE->requires->js('/mod/data/data.js');
1682 echo ' <input type="hidden" name="advanced" value="0" />';
1683 echo ' <input type="hidden" name="filter" value="1" />';
1684 echo ' <input type="checkbox" id="advancedcheckbox" name="advanced" value="1" '.$checked.' onchange="showHideAdvSearch(this.checked);" /><label for="advancedcheckbox">'.get_string('advancedsearch', 'data').'</label>';
1685 echo ' <input type="submit" value="'.get_string('savesettings','data').'" />';
1688 echo '<div class="' . $advancedsearchclass . '" id="data_adv_form">';
1689 echo '<table class="boxaligncenter">';
1691 // print ASC or DESC
1692 echo '<tr><td colspan="2"> </td></tr>';
1695 // Determine if we are printing all fields for advanced search, or the template for advanced search
1696 // If a template is not defined, use the deafault template and display all fields.
1697 if(empty($data->asearchtemplate)) {
1698 data_generate_default_template($data, 'asearchtemplate');
1701 static $fields = NULL;
1703 static $dataid = NULL;
1705 if (empty($dataid)) {
1706 $dataid = $data->id;
1707 } else if ($dataid != $data->id) {
1711 if (empty($fields)) {
1712 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1713 foreach ($fieldrecords as $fieldrecord) {
1714 $fields[]= data_get_field($fieldrecord, $data);
1717 $isteacher = has_capability('mod/data:managetemplates', $context);
1721 $patterns = array();
1722 $replacement = array();
1724 // Then we generate strings to replace for normal tags
1725 foreach ($fields as $field) {
1726 $fieldname = $field->field->name;
1727 $fieldname = preg_quote($fieldname, '/');
1728 $patterns[] = "/\[\[$fieldname\]\]/i";
1729 $searchfield = data_get_field_from_id($field->field->id, $data);
1730 if (!empty($search_array[$field->field->id]->data)) {
1731 $replacement[] = $searchfield->display_search_field($search_array[$field->field->id]->data);
1733 $replacement[] = $searchfield->display_search_field();
1736 $fn = !empty($search_array[DATA_FIRSTNAME]->data) ? $search_array[DATA_FIRSTNAME]->data : '';
1737 $ln = !empty($search_array[DATA_LASTNAME]->data) ? $search_array[DATA_LASTNAME]->data : '';
1738 $patterns[] = '/##firstname##/';
1739 $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.'" />';
1740 $patterns[] = '/##lastname##/';
1741 $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.'" />';
1743 // actual replacement of the tags
1744 $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate);
1746 $options = new stdClass();
1747 $options->para=false;
1748 $options->noclean=true;
1750 echo format_text($newtext, FORMAT_HTML, $options);
1753 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>';
1764 * @param object $data
1765 * @param object $record
1766 * @return void Output echo'd
1768 function data_print_ratings($data, $record) {
1770 if (!empty($record->rating)){
1771 echo $OUTPUT->render($record->rating);
1776 * List the actions that correspond to a view of this module.
1777 * This is used by the participation report.
1779 * Note: This is not used by new logging system. Event with
1780 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1781 * be considered as view action.
1785 function data_get_view_actions() {
1786 return array('view');
1790 * List the actions that correspond to a post of this module.
1791 * This is used by the participation report.
1793 * Note: This is not used by new logging system. Event with
1794 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1795 * will be considered as post action.
1799 function data_get_post_actions() {
1800 return array('add','update','record delete');
1804 * @param string $name
1805 * @param int $dataid
1806 * @param int $fieldid
1809 function data_fieldname_exists($name, $dataid, $fieldid = 0) {
1812 if (!is_numeric($name)) {
1813 $like = $DB->sql_like('df.name', ':name', false);
1815 $like = "df.name = :name";
1817 $params = array('name'=>$name);
1819 $params['dataid'] = $dataid;
1820 $params['fieldid1'] = $fieldid;
1821 $params['fieldid2'] = $fieldid;
1822 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1823 WHERE $like AND df.dataid = :dataid
1824 AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
1826 $params['dataid'] = $dataid;
1827 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1828 WHERE $like AND df.dataid = :dataid", $params);
1833 * @param array $fieldinput
1835 function data_convert_arrays_to_strings(&$fieldinput) {
1836 foreach ($fieldinput as $key => $val) {
1837 if (is_array($val)) {
1839 foreach ($val as $inner) {
1840 $str .= $inner . ',';
1842 $str = substr($str, 0, -1);
1844 $fieldinput->$key = $str;
1851 * Converts a database (module instance) to use the Roles System
1855 * @uses CONTEXT_MODULE
1858 * @param object $data a data object with the same attributes as a record
1859 * from the data database table
1860 * @param int $datamodid the id of the data module, from the modules table
1861 * @param array $teacherroles array of roles that have archetype teacher
1862 * @param array $studentroles array of roles that have archetype student
1863 * @param array $guestroles array of roles that have archetype guest
1864 * @param int $cmid the course_module id for this data instance
1865 * @return boolean data module was converted or not
1867 function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
1868 global $CFG, $DB, $OUTPUT;
1870 if (!isset($data->participants) && !isset($data->assesspublic)
1871 && !isset($data->groupmode)) {
1872 // We assume that this database has already been converted to use the
1873 // Roles System. above fields get dropped the data module has been
1874 // upgraded to use Roles.
1879 // We were not given the course_module id. Try to find it.
1880 if (!$cm = get_coursemodule_from_instance('data', $data->id)) {
1881 echo $OUTPUT->notification('Could not get the course module for the data');
1887 $context = context_module::instance($cmid);
1890 // $data->participants:
1891 // 1 - Only teachers can add entries
1892 // 3 - Teachers and students can add entries
1893 switch ($data->participants) {
1895 foreach ($studentroles as $studentrole) {
1896 assign_capability('mod/data:writeentry', CAP_PREVENT, $studentrole->id, $context->id);
1898 foreach ($teacherroles as $teacherrole) {
1899 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1903 foreach ($studentroles as $studentrole) {
1904 assign_capability('mod/data:writeentry', CAP_ALLOW, $studentrole->id, $context->id);
1906 foreach ($teacherroles as $teacherrole) {
1907 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1913 // 2 - Only teachers can rate posts
1914 // 1 - Everyone can rate posts
1915 // 0 - No one can rate posts
1916 switch ($data->assessed) {
1918 foreach ($studentroles as $studentrole) {
1919 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1921 foreach ($teacherroles as $teacherrole) {
1922 assign_capability('mod/data:rate', CAP_PREVENT, $teacherrole->id, $context->id);
1926 foreach ($studentroles as $studentrole) {
1927 assign_capability('mod/data:rate', CAP_ALLOW, $studentrole->id, $context->id);
1929 foreach ($teacherroles as $teacherrole) {
1930 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1934 foreach ($studentroles as $studentrole) {
1935 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1937 foreach ($teacherroles as $teacherrole) {
1938 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1943 // $data->assesspublic:
1944 // 0 - Students can only see their own ratings
1945 // 1 - Students can see everyone's ratings
1946 switch ($data->assesspublic) {
1948 foreach ($studentroles as $studentrole) {
1949 assign_capability('mod/data:viewrating', CAP_PREVENT, $studentrole->id, $context->id);
1951 foreach ($teacherroles as $teacherrole) {
1952 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1956 foreach ($studentroles as $studentrole) {
1957 assign_capability('mod/data:viewrating', CAP_ALLOW, $studentrole->id, $context->id);
1959 foreach ($teacherroles as $teacherrole) {
1960 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1966 $cm = $DB->get_record('course_modules', array('id'=>$cmid));
1969 switch ($cm->groupmode) {
1972 case SEPARATEGROUPS:
1973 foreach ($studentroles as $studentrole) {
1974 assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id);
1976 foreach ($teacherroles as $teacherrole) {
1977 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1981 foreach ($studentroles as $studentrole) {
1982 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id);
1984 foreach ($teacherroles as $teacherrole) {
1985 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1993 * Returns the best name to show for a preset
1995 * @param string $shortname
1996 * @param string $path
1999 function data_preset_name($shortname, $path) {
2001 // We are looking inside the preset itself as a first choice, but also in normal data directory
2002 $string = get_string('modulename', 'datapreset_'.$shortname);
2004 if (substr($string, 0, 1) == '[') {
2012 * Returns an array of all the available presets.
2016 function data_get_available_presets($context) {
2021 // First load the ratings sub plugins that exist within the modules preset dir
2022 if ($dirs = core_component::get_plugin_list('datapreset')) {
2023 foreach ($dirs as $dir=>$fulldir) {
2024 if (is_directory_a_preset($fulldir)) {
2025 $preset = new stdClass();
2026 $preset->path = $fulldir;
2027 $preset->userid = 0;
2028 $preset->shortname = $dir;
2029 $preset->name = data_preset_name($dir, $fulldir);
2030 if (file_exists($fulldir.'/screenshot.jpg')) {
2031 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.jpg';
2032 } else if (file_exists($fulldir.'/screenshot.png')) {
2033 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.png';
2034 } else if (file_exists($fulldir.'/screenshot.gif')) {
2035 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.gif';
2037 $presets[] = $preset;
2041 // Now add to that the site presets that people have saved
2042 $presets = data_get_available_site_presets($context, $presets);
2047 * Gets an array of all of the presets that users have saved to the site.
2049 * @param stdClass $context The context that we are looking from.
2050 * @param array $presets
2051 * @return array An array of presets
2053 function data_get_available_site_presets($context, array $presets=array()) {
2056 $fs = get_file_storage();
2057 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2058 $canviewall = has_capability('mod/data:viewalluserpresets', $context);
2059 if (empty($files)) {
2062 foreach ($files as $file) {
2063 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory() || (!$canviewall && $file->get_userid() != $USER->id)) {
2066 $preset = new stdClass;
2067 $preset->path = $file->get_filepath();
2068 $preset->name = trim($preset->path, '/');
2069 $preset->shortname = $preset->name;
2070 $preset->userid = $file->get_userid();
2071 $preset->id = $file->get_id();
2072 $preset->storedfile = $file;
2073 $presets[] = $preset;
2079 * Deletes a saved preset.
2081 * @param string $name
2084 function data_delete_site_preset($name) {
2085 $fs = get_file_storage();
2087 $files = $fs->get_directory_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/');
2088 if (!empty($files)) {
2089 foreach ($files as $file) {
2094 $dir = $fs->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/', '.');
2102 * Prints the heads for a page
2104 * @param stdClass $course
2105 * @param stdClass $cm
2106 * @param stdClass $data
2107 * @param string $currenttab
2109 function data_print_header($course, $cm, $data, $currenttab='') {
2111 global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
2113 $PAGE->set_title($data->name);
2114 echo $OUTPUT->header();
2115 echo $OUTPUT->heading(format_string($data->name), 2);
2116 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
2118 // Groups needed for Add entry tab
2119 $currentgroup = groups_get_activity_group($cm);
2120 $groupmode = groups_get_activity_groupmode($cm);
2125 include('tabs.php');
2128 // Print any notices
2130 if (!empty($displaynoticegood)) {
2131 echo $OUTPUT->notification($displaynoticegood, 'notifysuccess'); // good (usually green)
2132 } else if (!empty($displaynoticebad)) {
2133 echo $OUTPUT->notification($displaynoticebad); // bad (usuually red)
2138 * Can user add more entries?
2140 * @param object $data
2141 * @param mixed $currentgroup
2142 * @param int $groupmode
2143 * @param stdClass $context
2146 function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
2149 if (empty($context)) {
2150 $cm = get_coursemodule_from_instance('data', $data->id, 0, false, MUST_EXIST);
2151 $context = context_module::instance($cm->id);
2154 if (has_capability('mod/data:manageentries', $context)) {
2155 // no entry limits apply if user can manage
2157 } else if (!has_capability('mod/data:writeentry', $context)) {
2160 } else if (data_atmaxentries($data)) {
2162 } else if (data_in_readonly_period($data)) {
2163 // Check whether we're in a read-only period
2167 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2171 if ($currentgroup) {
2172 return groups_is_member($currentgroup);
2174 //else it might be group 0 in visible mode
2175 if ($groupmode == VISIBLEGROUPS){
2184 * Check whether the current user is allowed to manage the given record considering manageentries capability,
2185 * data_in_readonly_period() result, ownership (determined by data_isowner()) and manageapproved setting.
2186 * @param mixed $record record object or id
2187 * @param object $data data object
2188 * @param object $context context object
2189 * @return bool returns true if the user is allowd to edit the entry, false otherwise
2191 function data_user_can_manage_entry($record, $data, $context) {
2194 if (has_capability('mod/data:manageentries', $context)) {
2198 // Check whether this activity is read-only at present.
2199 $readonly = data_in_readonly_period($data);
2202 // Get record object from db if just id given like in data_isowner.
2203 // ...done before calling data_isowner() to avoid querying db twice.
2204 if (!is_object($record)) {
2205 if (!$record = $DB->get_record('data_records', array('id' => $record))) {
2209 if (data_isowner($record)) {
2210 if ($data->approval && $record->approved) {
2211 return $data->manageapproved == 1;
2222 * Check whether the specified database activity is currently in a read-only period
2224 * @param object $data
2225 * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2227 function data_in_readonly_period($data) {
2229 if (!$data->timeviewfrom && !$data->timeviewto) {
2231 } else if (($data->timeviewfrom && $now < $data->timeviewfrom) || ($data->timeviewto && $now > $data->timeviewto)) {
2240 function is_directory_a_preset($directory) {
2241 $directory = rtrim($directory, '/\\') . '/';
2242 $status = file_exists($directory.'singletemplate.html') &&
2243 file_exists($directory.'listtemplate.html') &&
2244 file_exists($directory.'listtemplateheader.html') &&
2245 file_exists($directory.'listtemplatefooter.html') &&
2246 file_exists($directory.'addtemplate.html') &&
2247 file_exists($directory.'rsstemplate.html') &&
2248 file_exists($directory.'rsstitletemplate.html') &&
2249 file_exists($directory.'csstemplate.css') &&
2250 file_exists($directory.'jstemplate.js') &&
2251 file_exists($directory.'preset.xml');
2257 * Abstract class used for data preset importers
2259 abstract class data_preset_importer {
2264 protected $directory;
2269 * @param stdClass $course
2270 * @param stdClass $cm
2271 * @param stdClass $module
2272 * @param string $directory
2274 public function __construct($course, $cm, $module, $directory) {
2275 $this->course = $course;
2277 $this->module = $module;
2278 $this->directory = $directory;
2282 * Returns the name of the directory the preset is located in
2285 public function get_directory() {
2286 return basename($this->directory);
2290 * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2291 * @param file_storage $filestorage. should be null if using a conventional directory
2292 * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2293 * @param string $dir the directory to look in. null if using the Moodle file storage
2294 * @param string $filename the name of the file we want
2295 * @return string the contents of the file or null if the file doesn't exist.
2297 public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2298 if(empty($filestorage) || empty($fileobj)) {
2299 if (substr($dir, -1)!='/') {
2302 if (file_exists($dir.$filename)) {
2303 return file_get_contents($dir.$filename);
2308 if ($filestorage->file_exists(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename)) {
2309 $file = $filestorage->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename);
2310 return $file->get_content();
2318 * Gets the preset settings
2319 * @global moodle_database $DB
2322 public function get_preset_settings() {
2325 $fs = $fileobj = null;
2326 if (!is_directory_a_preset($this->directory)) {
2327 //maybe the user requested a preset stored in the Moodle file storage
2329 $fs = get_file_storage();
2330 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2332 //preset name to find will be the final element of the directory
2333 $explodeddirectory = explode('/', $this->directory);
2334 $presettofind = end($explodeddirectory);
2336 //now go through the available files available and see if we can find it
2337 foreach ($files as $file) {
2338 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory()) {
2341 $presetname = trim($file->get_filepath(), '/');
2342 if ($presetname==$presettofind) {
2343 $this->directory = $presetname;
2348 if (empty($fileobj)) {
2349 print_error('invalidpreset', 'data', '', $this->directory);
2353 $allowed_settings = array(
2357 'requiredentriestoview',
2364 $result = new stdClass;
2365 $result->settings = new stdClass;
2366 $result->importfields = array();
2367 $result->currentfields = $DB->get_records('data_fields', array('dataid'=>$this->module->id));
2368 if (!$result->currentfields) {
2369 $result->currentfields = array();
2374 $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory,'preset.xml');
2375 $parsedxml = xmlize($presetxml, 0);
2377 /* First, do settings. Put in user friendly array. */
2378 $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
2379 $result->settings = new StdClass();
2380 foreach ($settingsarray as $setting => $value) {
2381 if (!is_array($value) || !in_array($setting, $allowed_settings)) {
2382 // unsupported setting
2385 $result->settings->$setting = $value[0]['#'];
2388 /* Now work out fields to user friendly array */
2389 $fieldsarray = $parsedxml['preset']['#']['field'];
2390 foreach ($fieldsarray as $field) {
2391 if (!is_array($field)) {
2394 $f = new StdClass();
2395 foreach ($field['#'] as $param => $value) {
2396 if (!is_array($value)) {
2399 $f->$param = $value[0]['#'];
2401 $f->dataid = $this->module->id;
2402 $f->type = clean_param($f->type, PARAM_ALPHA);
2403 $result->importfields[] = $f;
2405 /* Now add the HTML templates to the settings array so we can update d */
2406 $result->settings->singletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"singletemplate.html");
2407 $result->settings->listtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplate.html");
2408 $result->settings->listtemplateheader = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplateheader.html");
2409 $result->settings->listtemplatefooter = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplatefooter.html");
2410 $result->settings->addtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"addtemplate.html");
2411 $result->settings->rsstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstemplate.html");
2412 $result->settings->rsstitletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstitletemplate.html");
2413 $result->settings->csstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"csstemplate.css");
2414 $result->settings->jstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"jstemplate.js");
2415 $result->settings->asearchtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"asearchtemplate.html");
2417 $result->settings->instance = $this->module->id;
2422 * Import the preset into the given database module
2425 function import($overwritesettings) {
2428 $params = $this->get_preset_settings();
2429 $settings = $params->settings;
2430 $newfields = $params->importfields;
2431 $currentfields = $params->currentfields;
2432 $preservedfields = array();
2434 /* Maps fields and makes new ones */
2435 if (!empty($newfields)) {
2436 /* We require an injective mapping, and need to know what to protect */
2437 foreach ($newfields as $nid => $newfield) {
2438 $cid = optional_param("field_$nid", -1, PARAM_INT);
2442 if (array_key_exists($cid, $preservedfields)){
2443 print_error('notinjectivemap', 'data');
2445 else $preservedfields[$cid] = true;
2448 foreach ($newfields as $nid => $newfield) {
2449 $cid = optional_param("field_$nid", -1, PARAM_INT);
2451 /* A mapping. Just need to change field params. Data kept. */
2452 if ($cid != -1 and isset($currentfields[$cid])) {
2453 $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->module);
2454 foreach ($newfield as $param => $value) {
2455 if ($param != "id") {
2456 $fieldobject->field->$param = $value;
2459 unset($fieldobject->field->similarfield);
2460 $fieldobject->update_field();
2461 unset($fieldobject);
2463 /* Make a new field */
2464 include_once("field/$newfield->type/field.class.php");
2466 if (!isset($newfield->description)) {
2467 $newfield->description = '';
2469 $classname = 'data_field_'.$newfield->type;
2470 $fieldclass = new $classname($newfield, $this->module);
2471 $fieldclass->insert_field();
2477 /* Get rid of all old unused data */
2478 if (!empty($preservedfields)) {
2479 foreach ($currentfields as $cid => $currentfield) {
2480 if (!array_key_exists($cid, $preservedfields)) {
2481 /* Data not used anymore so wipe! */
2482 print "Deleting field $currentfield->name<br />";
2484 $id = $currentfield->id;
2485 //Why delete existing data records and related comments/ratings??
2486 $DB->delete_records('data_content', array('fieldid'=>$id));
2487 $DB->delete_records('data_fields', array('id'=>$id));
2492 // handle special settings here
2493 if (!empty($settings->defaultsort)) {
2494 if (is_numeric($settings->defaultsort)) {
2496 $settings->defaultsort = 0;
2498 $settings->defaultsort = (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module->id, 'name'=>$settings->defaultsort));
2501 $settings->defaultsort = 0;
2504 // do we want to overwrite all current database settings?
2505 if ($overwritesettings) {
2506 // all supported settings
2507 $overwrite = array_keys((array)$settings);
2509 // only templates and sorting
2510 $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2511 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
2512 'asearchtemplate', 'defaultsortdir', 'defaultsort');
2515 // now overwrite current data settings
2516 foreach ($this->module as $prop=>$unused) {
2517 if (in_array($prop, $overwrite)) {
2518 $this->module->$prop = $settings->$prop;
2522 data_update_instance($this->module);
2524 return $this->cleanup();
2528 * Any clean up routines should go here
2531 public function cleanup() {
2537 * Data preset importer for uploaded presets
2539 class data_preset_upload_importer extends data_preset_importer {
2540 public function __construct($course, $cm, $module, $filepath) {
2542 if (is_file($filepath)) {
2543 $fp = get_file_packer();
2544 if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2545 fulldelete($filepath);
2547 $filepath .= '_extracted';
2549 parent::__construct($course, $cm, $module, $filepath);
2551 public function cleanup() {
2552 return fulldelete($this->directory);
2557 * Data preset importer for existing presets
2559 class data_preset_existing_importer extends data_preset_importer {
2561 public function __construct($course, $cm, $module, $fullname) {
2563 list($userid, $shortname) = explode('/', $fullname, 2);
2564 $context = context_module::instance($cm->id);
2565 if ($userid && ($userid != $USER->id) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2566 throw new coding_exception('Invalid preset provided');
2569 $this->userid = $userid;
2570 $filepath = data_preset_path($course, $userid, $shortname);
2571 parent::__construct($course, $cm, $module, $filepath);
2573 public function get_userid() {
2574 return $this->userid;
2581 * @param object $course
2582 * @param int $userid
2583 * @param string $shortname
2586 function data_preset_path($course, $userid, $shortname) {
2589 $context = context_course::instance($course->id);
2591 $userid = (int)$userid;
2594 if ($userid > 0 && ($userid == $USER->id || has_capability('mod/data:viewalluserpresets', $context))) {
2595 $path = $CFG->dataroot.'/data/preset/'.$userid.'/'.$shortname;
2596 } else if ($userid == 0) {
2597 $path = $CFG->dirroot.'/mod/data/preset/'.$shortname;
2598 } else if ($userid < 0) {
2599 $path = $CFG->tempdir.'/data/'.-$userid.'/'.$shortname;
2606 * Implementation of the function for printing the form elements that control
2607 * whether the course reset functionality affects the data.
2609 * @param $mform form passed by reference
2611 function data_reset_course_form_definition(&$mform) {
2612 $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2613 $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2615 $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2616 $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2618 $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2619 $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2621 $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2622 $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
2626 * Course reset form defaults.
2629 function data_reset_course_form_defaults($course) {
2630 return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2634 * Removes all grades from gradebook
2638 * @param int $courseid
2639 * @param string $type optional type
2641 function data_reset_gradebook($courseid, $type='') {
2644 $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
2645 FROM {data} d, {course_modules} cm, {modules} m
2646 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
2648 if ($datas = $DB->get_records_sql($sql, array($courseid))) {
2649 foreach ($datas as $data) {
2650 data_grade_item_update($data, 'reset');
2656 * Actual implementation of the reset course functionality, delete all the
2657 * data responses for course $data->courseid.
2661 * @param object $data the data submitted from the reset course.
2662 * @return array status array
2664 function data_reset_userdata($data) {
2666 require_once($CFG->libdir.'/filelib.php');
2667 require_once($CFG->dirroot.'/rating/lib.php');
2669 $componentstr = get_string('modulenameplural', 'data');
2672 $allrecordssql = "SELECT r.id
2673 FROM {data_records} r
2674 INNER JOIN {data} d ON r.dataid = d.id
2675 WHERE d.course = ?";
2677 $alldatassql = "SELECT d.id
2681 $rm = new rating_manager();
2682 $ratingdeloptions = new stdClass;
2683 $ratingdeloptions->component = 'mod_data';
2684 $ratingdeloptions->ratingarea = 'entry';
2686 // Set the file storage - may need it to remove files later.
2687 $fs = get_file_storage();
2689 // delete entries if requested
2690 if (!empty($data->reset_data)) {
2691 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2692 $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid));
2693 $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid));
2695 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2696 foreach ($datas as $dataid=>$unused) {
2697 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2700 $datacontext = context_module::instance($cm->id);
2702 // Delete any files that may exist.
2703 $fs->delete_area_files($datacontext->id, 'mod_data', 'content');
2705 $ratingdeloptions->contextid = $datacontext->id;
2706 $rm->delete_ratings($ratingdeloptions);
2710 if (empty($data->reset_gradebook_grades)) {
2711 // remove all grades from gradebook
2712 data_reset_gradebook($data->courseid);
2714 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2717 // remove entries by users not enrolled into course
2718 if (!empty($data->reset_data_notenrolled)) {
2719 $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
2720 FROM {data_records} r
2721 JOIN {data} d ON r.dataid = d.id
2722 LEFT JOIN {user} u ON r.userid = u.id
2723 WHERE d.course = ? AND r.userid > 0";
2725 $course_context = context_course::instance($data->courseid);
2726 $notenrolled = array();
2728 $rs = $DB->get_recordset_sql($recordssql, array($data->courseid));
2729 foreach ($rs as $record) {
2730 if (array_key_exists($record->userid, $notenrolled) or !$record->userexists or $record->userdeleted
2731 or !is_enrolled($course_context, $record->userid)) {
2733 if (!$cm = get_coursemodule_from_instance('data', $record->dataid)) {
2736 $datacontext = context_module::instance($cm->id);
2737 $ratingdeloptions->contextid = $datacontext->id;
2738 $ratingdeloptions->itemid = $record->id;
2739 $rm->delete_ratings($ratingdeloptions);
2741 // Delete any files that may exist.
2742 if ($contents = $DB->get_records('data_content', array('recordid' => $record->id), '', 'id')) {
2743 foreach ($contents as $content) {
2744 $fs->delete_area_files($datacontext->id, 'mod_data', 'content', $content->id);
2747 $notenrolled[$record->userid] = true;
2749 $DB->delete_records('comments', array('itemid' => $record->id, 'commentarea' => 'database_entry'));
2750 $DB->delete_records('data_content', array('recordid' => $record->id));
2751 $DB->delete_records('data_records', array('id' => $record->id));
2755 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
2758 // remove all ratings
2759 if (!empty($data->reset_data_ratings)) {
2760 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2761 foreach ($datas as $dataid=>$unused) {
2762 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2765 $datacontext = context_module::instance($cm->id);
2767 $ratingdeloptions->contextid = $datacontext->id;
2768 $rm->delete_ratings($ratingdeloptions);
2772 if (empty($data->reset_gradebook_grades)) {
2773 // remove all grades from gradebook
2774 data_reset_gradebook($data->courseid);
2777 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2780 // remove all comments
2781 if (!empty($data->reset_data_comments)) {
2782 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2783 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2786 // updating dates - shift may be negative too
2787 if ($data->timeshift) {
2788 shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto'), $data->timeshift, $data->courseid);
2789 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2796 * Returns all other caps used in module
2800 function data_get_extra_capabilities() {
2801 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');
2805 * @param string $feature FEATURE_xx constant for requested feature
2806 * @return mixed True if module supports feature, null if doesn't know
2808 function data_supports($feature) {
2810 case FEATURE_GROUPS: return true;
2811 case FEATURE_GROUPINGS: return true;
2812 case FEATURE_MOD_INTRO: return true;
2813 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
2814 case FEATURE_GRADE_HAS_GRADE: return true;
2815 case FEATURE_GRADE_OUTCOMES: return true;
2816 case FEATURE_RATE: return true;
2817 case FEATURE_BACKUP_MOODLE2: return true;
2818 case FEATURE_SHOW_DESCRIPTION: return true;
2820 default: return null;
2825 * @param array $export
2826 * @param string $delimiter_name
2827 * @param object $database
2829 * @param bool $return
2830 * @return string|void
2832 function data_export_csv($export, $delimiter_name, $database, $count, $return=false) {
2834 require_once($CFG->libdir . '/csvlib.class.php');
2836 $filename = $database . '-' . $count . '-record';
2841 return csv_export_writer::print_array($export, $delimiter_name, '"', true);
2843 csv_export_writer::download_array($filename, $export, $delimiter_name);
2849 * @param array $export
2850 * @param string $dataname
2854 function data_export_xls($export, $dataname, $count) {
2856 require_once("$CFG->libdir/excellib.class.php");
2857 $filename = clean_filename("{$dataname}-{$count}_record");
2861 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2862 $filename .= '.xls';
2865 $workbook = new MoodleExcelWorkbook($filearg);
2866 $workbook->send($filename);
2867 $worksheet = array();
2868 $worksheet[0] = $workbook->add_worksheet('');
2870 foreach ($export as $row) {
2872 foreach($row as $col) {
2873 $worksheet[0]->write($rowno, $colno, $col);
2884 * @param array $export
2885 * @param string $dataname
2889 function data_export_ods($export, $dataname, $count) {
2891 require_once("$CFG->libdir/odslib.class.php");
2892 $filename = clean_filename("{$dataname}-{$count}_record");
2896 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2897 $filename .= '.ods';
2899 $workbook = new MoodleODSWorkbook($filearg);
2900 $workbook->send($filename);
2901 $worksheet = array();
2902 $worksheet[0] = $workbook->add_worksheet('');
2904 foreach ($export as $row) {
2906 foreach($row as $col) {
2907 $worksheet[0]->write($rowno, $colno, $col);
2918 * @param int $dataid
2919 * @param array $fields
2920 * @param array $selectedfields
2921 * @param int $currentgroup group ID of the current group. This is used for
2922 * exporting data while maintaining group divisions.
2923 * @param object $context the context in which the operation is performed (for capability checks)
2924 * @param bool $userdetails whether to include the details of the record author
2925 * @param bool $time whether to include time created/modified
2926 * @param bool $approval whether to include approval status
2929 function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0, $context=null,
2930 $userdetails=false, $time=false, $approval=false) {
2933 if (is_null($context)) {
2934 $context = context_system::instance();
2936 // exporting user data needs special permission
2937 $userdetails = $userdetails && has_capability('mod/data:exportuserinfo', $context);
2939 $exportdata = array();
2941 // populate the header in first row of export
2942 foreach($fields as $key => $field) {
2943 if (!in_array($field->field->id, $selectedfields)) {
2944 // ignore values we aren't exporting
2945 unset($fields[$key]);
2947 $exportdata[0][] = $field->field->name;
2951 $exportdata[0][] = get_string('user');
2952 $exportdata[0][] = get_string('username');
2953 $exportdata[0][] = get_string('email');
2956 $exportdata[0][] = get_string('timeadded', 'data');
2957 $exportdata[0][] = get_string('timemodified', 'data');
2960 $exportdata[0][] = get_string('approved', 'data');
2963 $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
2964 ksort($datarecords);
2966 foreach($datarecords as $record) {
2967 // get content indexed by fieldid
2968 if ($currentgroup) {
2969 $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 = ?';
2970 $where = array($record->id, $currentgroup);
2972 $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
2973 $where = array($record->id);
2976 if( $content = $DB->get_records_sql($select, $where) ) {
2977 foreach($fields as $field) {
2979 if(isset($content[$field->field->id])) {
2980 $contents = $field->export_text_value($content[$field->field->id]);
2982 $exportdata[$line][] = $contents;
2984 if ($userdetails) { // Add user details to the export data
2985 $userdata = get_complete_user_data('id', $record->userid);
2986 $exportdata[$line][] = fullname($userdata);
2987 $exportdata[$line][] = $userdata->username;
2988 $exportdata[$line][] = $userdata->email;
2990 if ($time) { // Add time added / modified
2991 $exportdata[$line][] = userdate($record->timecreated);
2992 $exportdata[$line][] = userdate($record->timemodified);
2994 if ($approval) { // Add approval status
2995 $exportdata[$line][] = (int) $record->approved;
3004 ////////////////////////////////////////////////////////////////////////////////
3006 ////////////////////////////////////////////////////////////////////////////////
3009 * Lists all browsable file areas
3013 * @param stdClass $course course object
3014 * @param stdClass $cm course module object
3015 * @param stdClass $context context object
3018 function data_get_file_areas($course, $cm, $context) {
3019 return array('content' => get_string('areacontent', 'mod_data'));
3023 * File browsing support for data module.
3025 * @param file_browser $browser
3026 * @param array $areas
3027 * @param stdClass $course
3028 * @param cm_info $cm
3029 * @param context $context
3030 * @param string $filearea
3031 * @param int $itemid
3032 * @param string $filepath
3033 * @param string $filename
3034 * @return file_info_stored file_info_stored instance or null if not found
3036 function data_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
3037 global $CFG, $DB, $USER;
3039 if ($context->contextlevel != CONTEXT_MODULE) {
3043 if (!isset($areas[$filearea])) {
3047 if (is_null($itemid)) {
3048 require_once($CFG->dirroot.'/mod/data/locallib.php');
3049 return new data_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
3052 if (!$content = $DB->get_record('data_content', array('id'=>$itemid))) {
3056 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
3060 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
3064 if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
3069 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3074 if ($record->groupid) {
3075 $groupmode = groups_get_activity_groupmode($cm, $course);
3076 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3077 if (!groups_is_member($record->groupid)) {
3083 $fieldobj = data_get_field($field, $data, $cm);
3085 $filepath = is_null($filepath) ? '/' : $filepath;
3086 $filename = is_null($filename) ? '.' : $filename;
3087 if (!$fieldobj->file_ok($filepath.$filename)) {
3091 $fs = get_file_storage();
3092 if (!($storedfile = $fs->get_file($context->id, 'mod_data', $filearea, $itemid, $filepath, $filename))) {
3096 // Checks to see if the user can manage files or is the owner.
3097 // TODO MDL-33805 - Do not use userid here and move the capability check above.
3098 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
3102 $urlbase = $CFG->wwwroot.'/pluginfile.php';
3104 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
3108 * Serves the data attachments. Implements needed access control ;-)
3112 * @param stdClass $course course object
3113 * @param stdClass $cm course module object
3114 * @param stdClass $context context object
3115 * @param string $filearea file area
3116 * @param array $args extra arguments
3117 * @param bool $forcedownload whether or not force download
3118 * @param array $options additional options affecting the file serving
3119 * @return bool false if file not found, does not return if found - justsend the file
3121 function data_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3124 if ($context->contextlevel != CONTEXT_MODULE) {
3128 require_course_login($course, true, $cm);
3130 if ($filearea === 'content') {
3131 $contentid = (int)array_shift($args);
3133 if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
3137 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
3141 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
3145 if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
3149 if ($data->id != $cm->instance) {
3150 // hacker attempt - context does not match the contentid
3155 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3160 if ($record->groupid) {
3161 $groupmode = groups_get_activity_groupmode($cm, $course);
3162 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3163 if (!groups_is_member($record->groupid)) {
3169 $fieldobj = data_get_field($field, $data, $cm);
3171 $relativepath = implode('/', $args);
3172 $fullpath = "/$context->id/mod_data/content/$content->id/$relativepath";
3174 if (!$fieldobj->file_ok($relativepath)) {
3178 $fs = get_file_storage();
3179 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3183 // finally send the file
3184 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
3191 function data_extend_navigation($navigation, $course, $module, $cm) {
3192 global $CFG, $OUTPUT, $USER, $DB;
3194 $rid = optional_param('rid', 0, PARAM_INT);
3196 $data = $DB->get_record('data', array('id'=>$cm->instance));
3197 $currentgroup = groups_get_activity_group($cm);
3198 $groupmode = groups_get_activity_groupmode($cm);
3200 $numentries = data_numentries($data);
3201 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
3202 if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !has_capability('mod/data:manageentries', context_module::instance($cm->id))) {
3203 $data->entriesleft = $data->requiredentries - $numentries;
3204 $entriesnode = $navigation->add(get_string('entrieslefttoadd', 'data', $data));
3205 $entriesnode->add_class('note');
3208 $navigation->add(get_string('list', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance)));
3210 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'rid'=>$rid)));
3212 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'single')));
3214 $navigation->add(get_string('search', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'asearch')));
3218 * Adds module specific settings to the settings block
3220 * @param settings_navigation $settings The settings navigation object
3221 * @param navigation_node $datanode The node to add module settings to
3223 function data_extend_settings_navigation(settings_navigation $settings, navigation_node $datanode) {
3224 global $PAGE, $DB, $CFG, $USER;
3226 $data = $DB->get_record('data', array("id" => $PAGE->cm->instance));
3228 $currentgroup = groups_get_activity_group($PAGE->cm);
3229 $groupmode = groups_get_activity_groupmode($PAGE->cm);
3231 if (data_user_can_add_entry($data, $currentgroup, $groupmode, $PAGE->cm->context)) { // took out participation list here!
3232 if (empty($editentry)) { //TODO: undefined
3233 $addstring = get_string('add', 'data');
3235 $addstring = get_string('editentry', 'data');
3237 $datanode->add($addstring, new moodle_url('/mod/data/edit.php', array('d'=>$PAGE->cm->instance)));
3240 if (has_capability(DATA_CAP_EXPORT, $PAGE->cm->context)) {
3241 // The capability required to Export database records is centrally defined in 'lib.php'
3242 // and should be weaker than those required to edit Templates, Fields and Presets.
3243 $datanode->add(get_string('exportentries', 'data'), new moodle_url('/mod/data/export.php', array('d'=>$data->id)));
3245 if (has_capability('mod/data:manageentries', $PAGE->cm->context)) {
3246 $datanode->add(get_string('importentries', 'data'), new moodle_url('/mod/data/import.php', array('d'=>$data->id)));
3249 if (has_capability('mod/data:managetemplates', $PAGE->cm->context)) {
3251 if ($currenttab == 'list') {
3252 $defaultemplate = 'listtemplate';
3253 } else if ($currenttab == 'add') {
3254 $defaultemplate = 'addtemplate';
3255 } else if ($currenttab == 'asearch') {
3256 $defaultemplate = 'asearchtemplate';
3258 $defaultemplate = 'singletemplate';
3261 $templates = $datanode->add(get_string('templates', 'data'));
3263 $templatelist = array ('listtemplate', 'singletemplate', 'asearchtemplate', 'addtemplate', 'rsstemplate', 'csstemplate', 'jstemplate');
3264 foreach ($templatelist as $template) {
3265 $templates->add(get_string($template, 'data'), new moodle_url('/mod/data/templates.php', array('d'=>$data->id,'mode'=>$template)));
3268 $datanode->add(get_string('fields', 'data'), new moodle_url('/mod/data/field.php', array('d'=>$data->id)));
3269 $datanode->add(get_string('presets', 'data'), new moodle_url('/mod/data/preset.php', array('d'=>$data->id)));
3272 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
3273 require_once("$CFG->libdir/rsslib.php");
3275 $string = get_string('rsstype','forum');
3277 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_data', $data->id));
3278 $datanode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
3283 * Save the database configuration as a preset.
3285 * @param stdClass $course The course the database module belongs to.
3286 * @param stdClass $cm The course module record
3287 * @param stdClass $data The database record
3288 * @param string $path
3291 function data_presets_save($course, $cm, $data, $path) {
3293 $fs = get_file_storage();
3294 $filerecord = new stdClass;
3295 $filerecord->contextid = DATA_PRESET_CONTEXT;
3296 $filerecord->component = DATA_PRESET_COMPONENT;
3297 $filerecord->filearea = DATA_PRESET_FILEAREA;
3298 $filerecord->itemid = 0;
3299 $filerecord->filepath = '/'.$path.'/';
3300 $filerecord->userid = $USER->id;
3302 $filerecord->filename = 'preset.xml';
3303 $fs->create_file_from_string($filerecord, data_presets_generate_xml($course, $cm, $data));
3305 $filerecord->filename = 'singletemplate.html';
3306 $fs->create_file_from_string($filerecord, $data->singletemplate);
3308 $filerecord->filename = 'listtemplateheader.html';
3309 $fs->create_file_from_string($filerecord, $data->listtemplateheader);
3311 $filerecord->filename = 'listtemplate.html';
3312 $fs->create_file_from_string($filerecord, $data->listtemplate);
3314 $filerecord->filename = 'listtemplatefooter.html';
3315 $fs->create_file_from_string($filerecord, $data->listtemplatefooter);
3317 $filerecord->filename = 'addtemplate.html';
3318 $fs->create_file_from_string($filerecord, $data->addtemplate);
3320 $filerecord->filename = 'rsstemplate.html';
3321 $fs->create_file_from_string($filerecord, $data->rsstemplate);
3323 $filerecord->filename = 'rsstitletemplate.html';
3324 $fs->create_file_from_string($filerecord, $data->rsstitletemplate);
3326 $filerecord->filename = 'csstemplate.css';
3327 $fs->create_file_from_string($filerecord, $data->csstemplate);
3329 $filerecord->filename = 'jstemplate.js';
3330 $fs->create_file_from_string($filerecord, $data->jstemplate);
3332 $filerecord->filename = 'asearchtemplate.html';
3333 $fs->create_file_from_string($filerecord, $data->asearchtemplate);
3339 * Generates the XML for the database module provided
3341 * @global moodle_database $DB
3342 * @param stdClass $course The course the database module belongs to.
3343 * @param stdClass $cm The course module record
3344 * @param stdClass $data The database record
3345 * @return string The XML for the preset
3347 function data_presets_generate_xml($course, $cm, $data) {
3350 // Assemble "preset.xml":
3351 $presetxmldata = "<preset>\n\n";
3353 // Raw settings are not preprocessed during saving of presets
3354 $raw_settings = array(
3358 'requiredentriestoview',
3366 $presetxmldata .= "<settings>\n";
3367 // First, settings that do not require any conversion
3368 foreach ($raw_settings as $setting) {
3369 $presetxmldata .= "<$setting>" . htmlspecialchars($data->$setting) . "</$setting>\n";
3372 // Now specific settings
3373 if ($data->defaultsort > 0 && $sortfield = data_get_field_from_id($data->defaultsort, $data)) {
3374 $presetxmldata .= '<defaultsort>' . htmlspecialchars($sortfield->field->name) . "</defaultsort>\n";
3376 $presetxmldata .= "<defaultsort>0</defaultsort>\n";
3378 $presetxmldata .= "</settings>\n\n";
3379 // Now for the fields. Grab all that are non-empty
3380 $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
3382 if (!empty($fields)) {
3383 foreach ($fields as $field) {
3384 $presetxmldata .= "<field>\n";
3385 foreach ($field as $key => $value) {
3386 if ($value != '' && $key != 'id' && $key != 'dataid') {
3387 $presetxmldata .= "<$key>" . htmlspecialchars($value) . "</$key>\n";
3390 $presetxmldata .= "</field>\n\n";
3393 $presetxmldata .= '</preset>';
3394 return $presetxmldata;
3397 function data_presets_export($course, $cm, $data, $tostorage=false) {
3400 $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi");
3401 $exportsubdir = "mod_data/presetexport/$presetname";
3402 make_temp_directory($exportsubdir);
3403 $exportdir = "$CFG->tempdir/$exportsubdir";
3405 // Assemble "preset.xml":
3406 $presetxmldata = data_presets_generate_xml($course, $cm, $data);
3408 // After opening a file in write mode, close it asap
3409 $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
3410 fwrite($presetxmlfile, $presetxmldata);
3411 fclose($presetxmlfile);
3413 // Now write the template files
3414 $singletemplate = fopen($exportdir . '/singletemplate.html', 'w');
3415 fwrite($singletemplate, $data->singletemplate);
3416 fclose($singletemplate);
3418 $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w');
3419 fwrite($listtemplateheader, $data->listtemplateheader);
3420 fclose($listtemplateheader);
3422 $listtemplate = fopen($exportdir . '/listtemplate.html', 'w');
3423 fwrite($listtemplate, $data->listtemplate);
3424 fclose($listtemplate);
3426 $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w');
3427 fwrite($listtemplatefooter, $data->listtemplatefooter);
3428 fclose($listtemplatefooter);
3430 $addtemplate = fopen($exportdir . '/addtemplate.html', 'w');
3431 fwrite($addtemplate, $data->addtemplate);
3432 fclose($addtemplate);
3434 $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w');
3435 fwrite($rsstemplate, $data->rsstemplate);
3436 fclose($rsstemplate);
3438 $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w');
3439 fwrite($rsstitletemplate, $data->rsstitletemplate);
3440 fclose($rsstitletemplate);
3442 $csstemplate = fopen($exportdir . '/csstemplate.css', 'w');
3443 fwrite($csstemplate, $data->csstemplate);
3444 fclose($csstemplate);
3446 $jstemplate = fopen($exportdir . '/jstemplate.js', 'w');
3447 fwrite($jstemplate, $data->jstemplate);
3448 fclose($jstemplate);
3450 $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w');
3451 fwrite($asearchtemplate, $data->asearchtemplate);
3452 fclose($asearchtemplate);
3454 // Check if all files have been generated
3455 if (! is_directory_a_preset($exportdir)) {
3456 print_error('generateerror', 'data');
3461 'singletemplate.html',
3462 'listtemplateheader.html',
3463 'listtemplate.html',
3464 'listtemplatefooter.html',
3467 'rsstitletemplate.html',
3470 'asearchtemplate.html'
3473 $filelist = array();
3474 foreach ($filenames as $filename) {
3475 $filelist[$filename] = $exportdir . '/' . $filename;
3478 $exportfile = $exportdir.'.zip';
3479 file_exists($exportfile) && unlink($exportfile);
3481 $fp = get_file_packer('application/zip');
3482 $fp->archive_to_pathname($filelist, $exportfile);
3484 foreach ($filelist as $file) {
3489 // Return the full path to the exported preset file:
3494 * Running addtional permission check on plugin, for example, plugins
3495 * may have switch to turn on/off comments option, this callback will
3496 * affect UI display, not like pluginname_comment_validate only throw
3498 * Capability check has been done in comment->check_permissions(), we
3499 * don't need to do it again here.
3504 * @param stdClass $comment_param {
3505 * context => context the context object
3506 * courseid => int course id
3507 * cm => stdClass course module object
3508 * commentarea => string comment area
3509 * itemid => int itemid
3513 function data_comment_permissions($comment_param) {
3515 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3516 throw new comment_exception('invalidcommentitemid');
3518 if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3519 throw new comment_exception('invalidid', 'data');
3521 if ($data->comments) {
3522 return array('post'=>true, 'view'=>true);
3524 return array('post'=>false, 'view'=>false);
3529 * Validate comment parameter before perform other comments actions
3534 * @param stdClass $comment_param {
3535 * context => context the context object
3536 * courseid => int course id
3537 * cm => stdClass course module object
3538 * commentarea => string comment area
3539 * itemid => int itemid
3543 function data_comment_validate($comment_param) {
3545 // validate comment area
3546 if ($comment_param->commentarea != 'database_entry') {
3547 throw new comment_exception('invalidcommentarea');
3550 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3551 throw new comment_exception('invalidcommentitemid');
3553 if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3554 throw new comment_exception('invalidid', 'data');
3556 if (!$course = $DB->get_record('course', array('id'=>$data->course))) {
3557 throw new comment_exception('coursemisconf');
3559 if (!$cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
3560 throw new comment_exception('invalidcoursemodule');
3562 if (!$data->comments) {
3563 throw new comment_exception('commentsoff', 'data');
3565 $context = context_module::instance($cm->id);
3568 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3569 throw new comment_exception('notapproved', 'data');
3573 if ($record->groupid) {
3574 $groupmode = groups_get_activity_groupmode($cm, $course);
3575 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3576 if (!groups_is_member($record->groupid)) {
3577 throw new comment_exception('notmemberofgroup');
3581 // validate context id
3582 if ($context->id != $comment_param->context->id) {
3583 throw new comment_exception('invalidcontext');
3585 // validation for comment deletion
3586 if (!empty($comment_param->commentid)) {
3587 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
3588 if ($comment->commentarea != 'database_entry') {
3589 throw new comment_exception('invalidcommentarea');
3591 if ($comment->contextid != $comment_param->context->id) {
3592 throw new comment_exception('invalidcontext');
3594 if ($comment->itemid != $comment_param->itemid) {
3595 throw new comment_exception('invalidcommentitemid');
3598 throw new comment_exception('invalidcommentid');
3605 * Return a list of page types
3606 * @param string $pagetype current page type
3607 * @param stdClass $parentcontext Block's parent context
3608 * @param stdClass $currentcontext Current context of block
3610 function data_page_type_list($pagetype, $parentcontext, $currentcontext) {
3611 $module_pagetype = array('mod-data-*'=>get_string('page-mod-data-x', 'data'));
3612 return $module_pagetype;
3616 * Get all of the record ids from a database activity.
3618 * @param int $dataid The dataid of the database module.
3619 * @param object $selectdata Contains an additional sql statement for the
3620 * where clause for group and approval fields.
3621 * @param array $params Parameters that coincide with the sql statement.
3622 * @return array $idarray An array of record ids
3624 function data_get_all_recordids($dataid, $selectdata = '', $params = null) {
3626 $initsql = 'SELECT r.id
3627 FROM {data_records} r
3628 WHERE r.dataid = :dataid';
3629 if ($selectdata != '') {
3630 $initsql .= $selectdata;
3631 $params = array_merge(array('dataid' => $dataid), $params);
3633 $params = array('dataid' => $dataid);
3635 $initsql .= ' GROUP BY r.id';
3636 $initrecord = $DB->get_recordset_sql($initsql, $params);
3638 foreach ($initrecord as $data) {
3639 $idarray[] = $data->id;
3641 // Close the record set and free up resources.
3642 $initrecord->close();
3647 * Get the ids of all the records that match that advanced search criteria
3648 * This goes and loops through each criterion one at a time until it either
3649 * runs out of records or returns a subset of records.
3651 * @param array $recordids An array of record ids.
3652 * @param array $searcharray Contains information for the advanced search criteria
3653 * @param int $dataid The data id of the database.
3654 * @return array $recordids An array of record ids.
3656 function data_get_advance_search_ids($recordids, $searcharray, $dataid) {
3657 $searchcriteria = array_keys($searcharray);
3658 // Loop through and reduce the IDs one search criteria at a time.
3659 foreach ($searchcriteria as $key) {
3660 $recordids = data_get_recordids($key, $searcharray, $dataid, $recordids);
3661 // If we don't have anymore IDs then stop.
3670 * Gets the record IDs given the search criteria
3672 * @param string $alias Record alias.
3673 * @param array $searcharray Criteria for the search.
3674 * @param int $dataid Data ID for the database
3675 * @param array $recordids An array of record IDs.
3676 * @return array $nestarray An arry of record IDs
3678 function data_get_recordids($alias, $searcharray, $dataid, $recordids) {
3681 $nestsearch = $searcharray[$alias];
3682 // searching for content outside of mdl_data_content
3686 list($insql, $params) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3687 $nestselect = 'SELECT c' . $alias . '.recordid
3688 FROM {data_content} c' . $alias . ',
3692 $nestwhere = 'WHERE u.id = r.userid
3693 AND f.id = c' . $alias . '.fieldid
3694 AND r.id = c' . $alias . '.recordid
3695 AND r.dataid = :dataid
3696 AND c' . $alias .'.recordid ' . $insql . '
3699 $params['dataid'] = $dataid;
3700 if (count($nestsearch->params) != 0) {
3701 $params = array_merge($params, $nestsearch->params);
3702 $nestsql = $nestselect . $nestwhere . $nestsearch->sql;
3704 $thing = $DB->sql_like($nestsearch->field, ':search1', false);
3705 $nestsql = $nestselect . $nestwhere . $thing . ' GROUP BY c' . $alias . '.recordid';
3706 $params['search1'] = "%$nestsearch->data%";
3708 $nestrecords = $DB->get_recordset_sql($nestsql, $params);
3709 $nestarray = array();
3710 foreach ($nestrecords as $data) {
3711 $nestarray[] = $data->recordid;
3713 // Close the record set and free up resources.
3714 $nestrecords->close();
3719 * Returns an array with an sql string for advanced searches and the parameters that go with them.
3721 * @param int $sort DATA_*
3722 * @param stdClass $data Data module object
3723 * @param array $recordids An array of record IDs.
3724 * @param string $selectdata Information for the where and select part of the sql statement.
3725 * @param string $sortorder Additional sort parameters
3726 * @return array sqlselect sqlselect['sql'] has the sql string, sqlselect['params'] contains an array of parameters.
3728 function data_get_advanced_search_sql($sort, $data, $recordids, $selectdata, $sortorder) {
3731 $namefields = user_picture::fields('u');
3732 // Remove the id from the string. This already exists in the sql statement.
3733 $namefields = str_replace('u.id,', '', $namefields);
3736 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . '
3737 FROM {data_content} c,
3740 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' . $namefields;
3742 // Sorting through 'Other' criteria
3746 $sortcontentfull = "u.lastname";
3748 case DATA_FIRSTNAME:
3749 $sortcontentfull = "u.firstname";
3752 $sortcontentfull = "r.approved";
3754 case DATA_TIMEMODIFIED:
3755 $sortcontentfull = "r.timemodified";
3757 case DATA_TIMEADDED:
3759 $sortcontentfull = "r.timecreated";
3762 $sortfield = data_get_field_from_id($sort, $data);
3763 $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
3764 $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
3767 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ',
3768 ' . $sortcontentfull . '
3770 FROM {data_content} c,
3773 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ', ' .$sortcontentfull;
3776 // Default to a standard Where statement if $selectdata is empty.
3777 if ($selectdata == '') {
3778 $selectdata = 'WHERE c.recordid = r.id
3779 AND r.dataid = :dataid
3780 AND r.userid = u.id ';
3783 // Find the field we are sorting on
3784 if ($sort > 0 or data_get_field_from_id($sort, $data)) {
3785 $selectdata .= ' AND c.fieldid = :sort';
3788 // If there are no record IDs then return an sql statment that will return no rows.
3789 if (count($recordids) != 0) {
3790 list($insql, $inparam) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3792 list($insql, $inparam) = $DB->get_in_or_equal(array('-1'), SQL_PARAMS_NAMED);
3794 $nestfromsql = $selectdata . ' AND c.recordid ' . $insql . $groupsql;
3795 $sqlselect['sql'] = "$nestselectsql $nestfromsql $sortorder";
3796 $sqlselect['params'] = $inparam;
3801 * Checks to see if the user has permission to delete the preset.
3802 * @param stdClass $context Context object.
3803 * @param stdClass $preset The preset object that we are checking for deletion.
3804 * @return bool Returns true if the user can delete, otherwise false.
3806 function data_user_can_delete_preset($context, $preset) {
3809 if (has_capability('mod/data:manageuserpresets', $context)) {
3813 if ($preset->userid == $USER->id) {
3821 * Delete a record entry.
3823 * @param int $recordid The ID for the record to be deleted.
3824 * @param object $data The data object for this activity.
3825 * @param int $courseid ID for the current course (for logging).
3826 * @param int $cmid The course module ID.
3827 * @return bool True if the record deleted, false if not.
3829 function data_delete_record($recordid, $data, $courseid, $cmid) {
3832 if ($deleterecord = $DB->get_record('data_records', array('id' => $recordid))) {
3833 if ($deleterecord->dataid == $data->id) {
3834 if ($contents = $DB->get_records('data_content', array('recordid' => $deleterecord->id))) {
3835 foreach ($contents as $content) {
3836 if ($field = data_get_field_from_id($content->fieldid, $data)) {
3837 $field->delete_content($content->recordid);
3840 $DB->delete_records('data_content', array('recordid'=>$deleterecord->id));
3841 $DB->delete_records('data_records', array('id'=>$deleterecord->id));
3843 // Delete cached RSS feeds.
3844 if (!empty($CFG->enablerssfeeds)) {
3845 require_once($CFG->dirroot.'/mod/data/rsslib.php');
3846 data_rss_delete_file($data);
3849 // Trigger an event for deleting this record.
3850 $event = \mod_data\event\record_deleted::create(array(
3851 'objectid' => $deleterecord->id,
3852 'context' => context_module::instance($cmid),
3853 'courseid' => $courseid,
3855 'dataid' => $deleterecord->dataid
3858 $event->add_record_snapshot('data_records', $deleterecord);
3869 * Check for required fields, and build a list of fields to be updated in a
3872 * @param $mod stdClass The current recordid - provided as an optimisation.
3873 * @param $fields array The field data
3874 * @param $datarecord stdClass The submitted data.
3875 * @return stdClass containing:
3876 * * string[] generalnotifications Notifications for the form as a whole.
3877 * * string[] fieldnotifications Notifications for a specific field.
3878 * * bool validated Whether the field was validated successfully.
3879 * * data_field_base[] fields The field objects to be update.
3881 function data_process_submission(stdClass $mod, $fields, stdClass $datarecord) {
3882 $result = new stdClass();
3884 // Empty form checking - you can't submit an empty form.
3886 $requiredfieldsfilled = true;
3887 $fieldsvalidated = true;
3889 // Store the notifications.
3890 $result->generalnotifications = array();
3891 $result->fieldnotifications = array();
3893 // Store the instantiated classes as an optimisation when processing the result.
3894 // This prevents the fields being re-initialised when updating.
3895 $result->fields = array();
3897 $submitteddata = array();
3898 foreach ($datarecord as $fieldname => $fieldvalue) {
3899 if (strpos($fieldname, '_')) {
3900 $namearray = explode('_', $fieldname, 3);
3901 $fieldid = $namearray[1];
3902 if (!isset($submitteddata[$fieldid])) {
3903 $submitteddata[$fieldid] = array();
3905 if (count($namearray) === 2) {
3908 $subfieldid = $namearray[2];
3911 $fielddata = new stdClass();
3912 $fielddata->fieldname = $fieldname;
3913 $fielddata->value = $fieldvalue;
3914 $submitteddata[$fieldid][$subfieldid] = $fielddata;
3918 // Check all form fields which have the required are filled.
3919 foreach ($fields as $fieldrecord) {
3920 // Check whether the field has any data.
3921 $fieldhascontent = false;
3923 $field = data_get_field($fieldrecord, $mod);
3924 if (isset($submitteddata[$fieldrecord->id])) {
3925 // Field validation check.
3926 if (method_exists($field, 'field_validation')) {
3927 $errormessage = $field->field_validation($submitteddata[$fieldrecord->id]);
3928 if ($errormessage) {
3929 $result->fieldnotifications[$field->field->name][] = $errormessage;
3930 $fieldsvalidated = false;
3933 foreach ($submitteddata[$fieldrecord->id] as $fieldname => $value) {
3934 if ($field->notemptyfield($value->value, $value->fieldname)) {
3935 // The field has content and the form is not empty.
3936 $fieldhascontent = true;
3942 // If the field is required, add a notification to that effect.
3943 if ($field->field->required && !$fieldhascontent) {
3944 if (!isset($result->fieldnotifications[$field->field->name])) {
3945 $result->fieldnotifications[$field->field->name] = array();
3947 $result->fieldnotifications[$field->field->name][] = get_string('errormustsupplyvalue', 'data');
3948 $requiredfieldsfilled = false;
3951 // Update the field.
3952 if (isset($submitteddata[$fieldrecord->id])) {
3953 foreach ($submitteddata[$fieldrecord->id] as $value) {
3954 $result->fields[$value->fieldname] = $field;
3960 // The form is empty.
3961 $result->generalnotifications[] = get_string('emptyaddform', 'data');
3964 $result->validated = $requiredfieldsfilled && !$emptyform && $fieldsvalidated;