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 $data->timemodified = time();
915 $data->id = $DB->insert_record('data', $data);
917 data_grade_item_update($data);
923 * updates an instance of a data
926 * @param object $data
929 function data_update_instance($data) {
932 $data->timemodified = time();
933 $data->id = $data->instance;
935 if (empty($data->assessed)) {
939 if (empty($data->ratingtime) or empty($data->assessed)) {
940 $data->assesstimestart = 0;
941 $data->assesstimefinish = 0;
944 if (empty($data->notification)) {
945 $data->notification = 0;
948 $DB->update_record('data', $data);
950 data_grade_item_update($data);
957 * deletes an instance of a data
963 function data_delete_instance($id) { // takes the dataid
966 if (!$data = $DB->get_record('data', array('id'=>$id))) {
970 $cm = get_coursemodule_from_instance('data', $data->id);
971 $context = context_module::instance($cm->id);
973 /// Delete all the associated information
976 $fs = get_file_storage();
977 $fs->delete_area_files($context->id, 'mod_data');
979 // get all the records in this data
981 FROM {data_records} r
984 $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
986 // delete all the records and fields
987 $DB->delete_records('data_records', array('dataid'=>$id));
988 $DB->delete_records('data_fields', array('dataid'=>$id));
990 // Delete the instance itself
991 $result = $DB->delete_records('data', array('id'=>$id));
994 data_grade_item_delete($data);
1000 * returns a summary of data activity of this user
1003 * @param object $course
1004 * @param object $user
1005 * @param object $mod
1006 * @param object $data
1007 * @return object|null
1009 function data_user_outline($course, $user, $mod, $data) {
1011 require_once("$CFG->libdir/gradelib.php");
1013 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1014 if (empty($grades->items[0]->grades)) {
1017 $grade = reset($grades->items[0]->grades);
1021 if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id, 'userid'=>$user->id))) {
1022 $result = new stdClass();
1023 $result->info = get_string('numrecords', 'data', $countrecords);
1024 $lastrecord = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
1025 WHERE dataid = ? AND userid = ?
1026 ORDER BY timemodified DESC', array($data->id, $user->id), true);
1027 $result->time = $lastrecord->timemodified;
1029 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
1032 } else if ($grade) {
1033 $result = new stdClass();
1034 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
1036 //datesubmitted == time created. dategraded == time modified or time overridden
1037 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1038 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1039 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
1040 $result->time = $grade->dategraded;
1042 $result->time = $grade->datesubmitted;
1051 * Prints all the records uploaded by this user
1054 * @param object $course
1055 * @param object $user
1056 * @param object $mod
1057 * @param object $data
1059 function data_user_complete($course, $user, $mod, $data) {
1060 global $DB, $CFG, $OUTPUT;
1061 require_once("$CFG->libdir/gradelib.php");
1063 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
1064 if (!empty($grades->items[0]->grades)) {
1065 $grade = reset($grades->items[0]->grades);
1066 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1067 if ($grade->str_feedback) {
1068 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1072 if ($records = $DB->get_records('data_records', array('dataid'=>$data->id,'userid'=>$user->id), 'timemodified DESC')) {
1073 data_print_template('singletemplate', $records, $data);
1078 * Return grade for given user or all users.
1081 * @param object $data
1082 * @param int $userid optional user id, 0 means all users
1083 * @return array array of grades, false if none
1085 function data_get_user_grades($data, $userid=0) {
1088 require_once($CFG->dirroot.'/rating/lib.php');
1090 $ratingoptions = new stdClass;
1091 $ratingoptions->component = 'mod_data';
1092 $ratingoptions->ratingarea = 'entry';
1093 $ratingoptions->modulename = 'data';
1094 $ratingoptions->moduleid = $data->id;
1096 $ratingoptions->userid = $userid;
1097 $ratingoptions->aggregationmethod = $data->assessed;
1098 $ratingoptions->scaleid = $data->scale;
1099 $ratingoptions->itemtable = 'data_records';
1100 $ratingoptions->itemtableusercolumn = 'userid';
1102 $rm = new rating_manager();
1103 return $rm->get_user_grades($ratingoptions);
1107 * Update activity grades
1110 * @param object $data
1111 * @param int $userid specific user only, 0 means all
1112 * @param bool $nullifnone
1114 function data_update_grades($data, $userid=0, $nullifnone=true) {
1116 require_once($CFG->libdir.'/gradelib.php');
1118 if (!$data->assessed) {
1119 data_grade_item_update($data);
1121 } else if ($grades = data_get_user_grades($data, $userid)) {
1122 data_grade_item_update($data, $grades);
1124 } else if ($userid and $nullifnone) {
1125 $grade = new stdClass();
1126 $grade->userid = $userid;
1127 $grade->rawgrade = NULL;
1128 data_grade_item_update($data, $grade);
1131 data_grade_item_update($data);
1136 * Update/create grade item for given data
1139 * @param stdClass $data A database instance with extra cmidnumber property
1140 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1141 * @return object grade_item
1143 function data_grade_item_update($data, $grades=NULL) {
1145 require_once($CFG->libdir.'/gradelib.php');
1147 $params = array('itemname'=>$data->name, 'idnumber'=>$data->cmidnumber);
1149 if (!$data->assessed or $data->scale == 0) {
1150 $params['gradetype'] = GRADE_TYPE_NONE;
1152 } else if ($data->scale > 0) {
1153 $params['gradetype'] = GRADE_TYPE_VALUE;
1154 $params['grademax'] = $data->scale;
1155 $params['grademin'] = 0;
1157 } else if ($data->scale < 0) {
1158 $params['gradetype'] = GRADE_TYPE_SCALE;
1159 $params['scaleid'] = -$data->scale;
1162 if ($grades === 'reset') {
1163 $params['reset'] = true;
1167 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, $grades, $params);
1171 * Delete grade item for given data
1174 * @param object $data object
1175 * @return object grade_item
1177 function data_grade_item_delete($data) {
1179 require_once($CFG->libdir.'/gradelib.php');
1181 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, NULL, array('deleted'=>1));
1186 * takes a list of records, the current data, a search string,
1187 * and mode to display prints the translated template
1191 * @param string $template
1192 * @param array $records
1193 * @param object $data
1194 * @param string $search
1196 * @param bool $return
1197 * @param object $jumpurl a moodle_url by which to jump back to the record list (can be null)
1200 function data_print_template($template, $records, $data, $search='', $page=0, $return=false, moodle_url $jumpurl=null) {
1201 global $CFG, $DB, $OUTPUT;
1203 $cm = get_coursemodule_from_instance('data', $data->id);
1204 $context = context_module::instance($cm->id);
1206 static $fields = NULL;
1208 static $dataid = NULL;
1210 if (empty($dataid)) {
1211 $dataid = $data->id;
1212 } else if ($dataid != $data->id) {
1216 if (empty($fields)) {
1217 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1218 foreach ($fieldrecords as $fieldrecord) {
1219 $fields[]= data_get_field($fieldrecord, $data);
1221 $isteacher = has_capability('mod/data:managetemplates', $context);
1224 if (empty($records)) {
1229 $jumpurl = new moodle_url('/mod/data/view.php', array('d' => $data->id));
1231 $jumpurl = new moodle_url($jumpurl, array('page' => $page, 'sesskey' => sesskey()));
1233 foreach ($records as $record) { // Might be just one for the single template
1236 $patterns = array();
1237 $replacement = array();
1239 // Then we generate strings to replace for normal tags
1240 foreach ($fields as $field) {
1241 $patterns[]='[['.$field->field->name.']]';
1242 $replacement[] = highlight($search, $field->display_browse_field($record->id, $template));
1245 $canmanageentries = has_capability('mod/data:manageentries', $context);
1247 // Replacing special tags (##Edit##, ##Delete##, ##More##)
1248 $patterns[]='##edit##';
1249 $patterns[]='##delete##';
1250 if (data_user_can_manage_entry($record, $data, $context)) {
1251 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d='
1252 .$data->id.'&rid='.$record->id.'&sesskey='.sesskey().'"><img src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" alt="'.get_string('edit').'" title="'.get_string('edit').'" /></a>';
1253 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='
1254 .$data->id.'&delete='.$record->id.'&sesskey='.sesskey().'"><img src="'.$OUTPUT->pix_url('t/delete') . '" class="iconsmall" alt="'.get_string('delete').'" title="'.get_string('delete').'" /></a>';
1256 $replacement[] = '';
1257 $replacement[] = '';
1260 $moreurl = $CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&rid=' . $record->id;
1262 $moreurl .= '&filter=1';
1264 $patterns[]='##more##';
1265 $replacement[] = '<a href="'.$moreurl.'"><img src="'.$OUTPUT->pix_url('t/preview').
1266 '" class="iconsmall" alt="'.get_string('more', 'data').'" title="'.get_string('more', 'data').
1269 $patterns[]='##moreurl##';
1270 $replacement[] = $moreurl;
1272 $patterns[]='##delcheck##';
1273 if ($canmanageentries) {
1274 $replacement[] = html_writer::checkbox('delcheck[]', $record->id, false, '', array('class' => 'recordcheckbox'));
1276 $replacement[] = '';
1279 $patterns[]='##user##';
1280 $replacement[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$record->userid.
1281 '&course='.$data->course.'">'.fullname($record).'</a>';
1283 $patterns[] = '##userpicture##';
1284 $ruser = user_picture::unalias($record, null, 'userid');
1285 $replacement[] = $OUTPUT->user_picture($ruser, array('courseid' => $data->course));
1287 $patterns[]='##export##';
1289 if (!empty($CFG->enableportfolios) && ($template == 'singletemplate' || $template == 'listtemplate')
1290 && ((has_capability('mod/data:exportentry', $context)
1291 || (data_isowner($record->id) && has_capability('mod/data:exportownentry', $context))))) {
1292 require_once($CFG->libdir . '/portfoliolib.php');
1293 $button = new portfolio_add_button();
1294 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id, 'recordid' => $record->id), 'mod_data');
1295 list($formats, $files) = data_portfolio_caller::formats($fields, $record);
1296 $button->set_formats($formats);
1297 $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1299 $replacement[] = '';
1302 $patterns[] = '##timeadded##';
1303 $replacement[] = userdate($record->timecreated);
1305 $patterns[] = '##timemodified##';
1306 $replacement [] = userdate($record->timemodified);
1308 $patterns[]='##approve##';
1309 if (has_capability('mod/data:approve', $context) && ($data->approval) && (!$record->approved)) {
1310 $approveurl = new moodle_url($jumpurl, array('approve' => $record->id));
1311 $approveicon = new pix_icon('t/approve', get_string('approve', 'data'), '', array('class' => 'iconsmall'));
1312 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($approveurl, $approveicon),
1313 array('class' => 'approve'));
1315 $replacement[] = '';
1318 $patterns[]='##disapprove##';
1319 if (has_capability('mod/data:approve', $context) && ($data->approval) && ($record->approved)) {
1320 $disapproveurl = new moodle_url($jumpurl, array('disapprove' => $record->id));
1321 $disapproveicon = new pix_icon('t/block', get_string('disapprove', 'data'), '', array('class' => 'iconsmall'));
1322 $replacement[] = html_writer::tag('span', $OUTPUT->action_icon($disapproveurl, $disapproveicon),
1323 array('class' => 'disapprove'));
1325 $replacement[] = '';
1328 $patterns[] = '##approvalstatus##';
1329 if (!$data->approval) {
1330 $replacement[] = '';
1331 } else if ($record->approved) {
1332 $replacement[] = 'approved';
1334 $replacement[] = 'notapproved';
1337 $patterns[]='##comments##';
1338 if (($template == 'listtemplate') && ($data->comments)) {
1340 if (!empty($CFG->usecomments)) {
1341 require_once($CFG->dirroot . '/comment/lib.php');
1342 list($context, $course, $cm) = get_context_info_array($context->id);
1343 $cmt = new stdClass();
1344 $cmt->context = $context;
1345 $cmt->course = $course;
1347 $cmt->area = 'database_entry';
1348 $cmt->itemid = $record->id;
1349 $cmt->showcount = true;
1350 $cmt->component = 'mod_data';
1351 $comment = new comment($cmt);
1352 $replacement[] = $comment->output(true);
1355 $replacement[] = '';
1358 // actual replacement of the tags
1359 $newtext = str_ireplace($patterns, $replacement, $data->{$template});
1361 // no more html formatting and filtering - see MDL-6635
1367 // hack alert - return is always false in singletemplate anyway ;-)
1368 /**********************************
1369 * Printing Ratings Form *
1370 *********************************/
1371 if ($template == 'singletemplate') { //prints ratings options
1372 data_print_ratings($data, $record);
1375 /**********************************
1376 * Printing Comments Form *
1377 *********************************/
1378 if (($template == 'singletemplate') && ($data->comments)) {
1379 if (!empty($CFG->usecomments)) {
1380 require_once($CFG->dirroot . '/comment/lib.php');
1381 list($context, $course, $cm) = get_context_info_array($context->id);
1382 $cmt = new stdClass();
1383 $cmt->context = $context;
1384 $cmt->course = $course;
1386 $cmt->area = 'database_entry';
1387 $cmt->itemid = $record->id;
1388 $cmt->showcount = true;
1389 $cmt->component = 'mod_data';
1390 $comment = new comment($cmt);
1391 $comment->output(false);
1399 * Return rating related permissions
1401 * @param string $contextid the context id
1402 * @param string $component the component to get rating permissions for
1403 * @param string $ratingarea the rating area to get permissions for
1404 * @return array an associative array of the user's rating permissions
1406 function data_rating_permissions($contextid, $component, $ratingarea) {
1407 $context = context::instance_by_id($contextid, MUST_EXIST);
1408 if ($component != 'mod_data' || $ratingarea != 'entry') {
1412 'view' => has_capability('mod/data:viewrating',$context),
1413 'viewany' => has_capability('mod/data:viewanyrating',$context),
1414 'viewall' => has_capability('mod/data:viewallratings',$context),
1415 'rate' => has_capability('mod/data:rate',$context)
1420 * Validates a submitted rating
1421 * @param array $params submitted data
1422 * context => object the context in which the rated items exists [required]
1423 * itemid => int the ID of the object being rated
1424 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1425 * rating => int the submitted rating
1426 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1427 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
1428 * @return boolean true if the rating is valid. Will throw rating_exception if not
1430 function data_rating_validate($params) {
1433 // Check the component is mod_data
1434 if ($params['component'] != 'mod_data') {
1435 throw new rating_exception('invalidcomponent');
1438 // Check the ratingarea is entry (the only rating area in data module)
1439 if ($params['ratingarea'] != 'entry') {
1440 throw new rating_exception('invalidratingarea');
1443 // Check the rateduserid is not the current user .. you can't rate your own entries
1444 if ($params['rateduserid'] == $USER->id) {
1445 throw new rating_exception('nopermissiontorate');
1448 $datasql = "SELECT d.id as dataid, d.scale, d.course, r.userid as userid, d.approval, r.approved, r.timecreated, d.assesstimestart, d.assesstimefinish, r.groupid
1449 FROM {data_records} r
1450 JOIN {data} d ON r.dataid = d.id
1451 WHERE r.id = :itemid";
1452 $dataparams = array('itemid'=>$params['itemid']);
1453 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1454 //item doesn't exist
1455 throw new rating_exception('invaliditemid');
1458 if ($info->scale != $params['scaleid']) {
1459 //the scale being submitted doesnt match the one in the database
1460 throw new rating_exception('invalidscaleid');
1463 //check that the submitted rating is valid for the scale
1466 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
1467 throw new rating_exception('invalidnum');
1471 if ($info->scale < 0) {
1472 //its a custom scale
1473 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
1475 $scalearray = explode(',', $scalerecord->scale);
1476 if ($params['rating'] > count($scalearray)) {
1477 throw new rating_exception('invalidnum');
1480 throw new rating_exception('invalidscaleid');
1482 } else if ($params['rating'] > $info->scale) {
1483 //if its numeric and submitted rating is above maximum
1484 throw new rating_exception('invalidnum');
1487 if ($info->approval && !$info->approved) {
1488 //database requires approval but this item isnt approved
1489 throw new rating_exception('nopermissiontorate');
1492 // check the item we're rating was created in the assessable time window
1493 if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
1494 if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
1495 throw new rating_exception('notavailable');
1499 $course = $DB->get_record('course', array('id'=>$info->course), '*', MUST_EXIST);
1500 $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1501 $context = context_module::instance($cm->id);
1503 // if the supplied context doesnt match the item's context
1504 if ($context->id != $params['context']->id) {
1505 throw new rating_exception('invalidcontext');
1508 // Make sure groups allow this user to see the item they're rating
1509 $groupid = $info->groupid;
1510 if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
1511 if (!groups_group_exists($groupid)) { // Can't find group
1512 throw new rating_exception('cannotfindgroup');//something is wrong
1515 if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1516 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
1517 throw new rating_exception('notmemberofgroup');
1525 * Can the current user see ratings for a given itemid?
1527 * @param array $params submitted data
1528 * contextid => int contextid [required]
1529 * component => The component for this module - should always be mod_data [required]
1530 * ratingarea => object the context in which the rated items exists [required]
1531 * itemid => int the ID of the object being rated [required]
1532 * scaleid => int scale id [optional]
1534 * @throws coding_exception
1535 * @throws rating_exception
1537 function mod_data_rating_can_see_item_ratings($params) {
1540 // Check the component is mod_data.
1541 if (!isset($params['component']) || $params['component'] != 'mod_data') {
1542 throw new rating_exception('invalidcomponent');
1545 // Check the ratingarea is entry (the only rating area in data).
1546 if (!isset($params['ratingarea']) || $params['ratingarea'] != 'entry') {
1547 throw new rating_exception('invalidratingarea');
1550 if (!isset($params['itemid'])) {
1551 throw new rating_exception('invaliditemid');
1554 $datasql = "SELECT d.id as dataid, d.course, r.groupid
1555 FROM {data_records} r
1556 JOIN {data} d ON r.dataid = d.id
1557 WHERE r.id = :itemid";
1558 $dataparams = array('itemid' => $params['itemid']);
1559 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1560 // Item doesn't exist.
1561 throw new rating_exception('invaliditemid');
1564 $course = $DB->get_record('course', array('id' => $info->course), '*', MUST_EXIST);
1565 $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1567 // Make sure groups allow this user to see the item they're rating.
1568 return groups_group_visible($info->groupid, $course, $cm);
1573 * function that takes in the current data, number of items per page,
1574 * a search string and prints a preference box in view.php
1576 * This preference box prints a searchable advanced search template if
1577 * a) A template is defined
1578 * b) The advanced search checkbox is checked.
1582 * @param object $data
1583 * @param int $perpage
1584 * @param string $search
1585 * @param string $sort
1586 * @param string $order
1587 * @param array $search_array
1588 * @param int $advanced
1589 * @param string $mode
1592 function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
1593 global $CFG, $DB, $PAGE, $OUTPUT;
1595 $cm = get_coursemodule_from_instance('data', $data->id);
1596 $context = context_module::instance($cm->id);
1597 echo '<br /><div class="datapreferences">';
1598 echo '<form id="options" action="view.php" method="get">';
1600 echo '<input type="hidden" name="d" value="'.$data->id.'" />';
1601 if ($mode =='asearch') {
1603 echo '<input type="hidden" name="mode" value="list" />';
1605 echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
1606 $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
1607 20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
1608 echo html_writer::select($pagesizes, 'perpage', $perpage, false, array('id'=>'pref_perpage'));
1611 $regsearchclass = 'search_none';
1612 $advancedsearchclass = 'search_inline';
1614 $regsearchclass = 'search_inline';
1615 $advancedsearchclass = 'search_none';
1617 echo '<div id="reg_search" class="' . $regsearchclass . '" > ';
1618 echo '<label for="pref_search">'.get_string('search').'</label> <input type="text" size="16" name="search" id= "pref_search" value="'.s($search).'" /></div>';
1619 echo ' <label for="pref_sortby">'.get_string('sortby').'</label> ';
1620 // foreach field, print the option
1621 echo '<select name="sort" id="pref_sortby">';
1622 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'name')) {
1623 echo '<optgroup label="'.get_string('fields', 'data').'">';
1624 foreach ($fields as $field) {
1625 if ($field->id == $sort) {
1626 echo '<option value="'.$field->id.'" selected="selected">'.$field->name.'</option>';
1628 echo '<option value="'.$field->id.'">'.$field->name.'</option>';
1634 $options[DATA_TIMEADDED] = get_string('timeadded', 'data');
1635 $options[DATA_TIMEMODIFIED] = get_string('timemodified', 'data');
1636 $options[DATA_FIRSTNAME] = get_string('authorfirstname', 'data');
1637 $options[DATA_LASTNAME] = get_string('authorlastname', 'data');
1638 if ($data->approval and has_capability('mod/data:approve', $context)) {
1639 $options[DATA_APPROVED] = get_string('approved', 'data');
1641 echo '<optgroup label="'.get_string('other', 'data').'">';
1642 foreach ($options as $key => $name) {
1643 if ($key == $sort) {
1644 echo '<option value="'.$key.'" selected="selected">'.$name.'</option>';
1646 echo '<option value="'.$key.'">'.$name.'</option>';
1651 echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
1652 echo '<select id="pref_order" name="order">';
1653 if ($order == 'ASC') {
1654 echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
1656 echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1658 if ($order == 'DESC') {
1659 echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
1661 echo '<option value="DESC">'.get_string('descending','data').'</option>';
1666 $checked = ' checked="checked" ';
1671 $PAGE->requires->js('/mod/data/data.js');
1672 echo ' <input type="hidden" name="advanced" value="0" />';
1673 echo ' <input type="hidden" name="filter" value="1" />';
1674 echo ' <input type="checkbox" id="advancedcheckbox" name="advanced" value="1" '.$checked.' onchange="showHideAdvSearch(this.checked);" /><label for="advancedcheckbox">'.get_string('advancedsearch', 'data').'</label>';
1675 echo ' <input type="submit" value="'.get_string('savesettings','data').'" />';
1678 echo '<div class="' . $advancedsearchclass . '" id="data_adv_form">';
1679 echo '<table class="boxaligncenter">';
1681 // print ASC or DESC
1682 echo '<tr><td colspan="2"> </td></tr>';
1685 // Determine if we are printing all fields for advanced search, or the template for advanced search
1686 // If a template is not defined, use the deafault template and display all fields.
1687 if(empty($data->asearchtemplate)) {
1688 data_generate_default_template($data, 'asearchtemplate');
1691 static $fields = NULL;
1693 static $dataid = NULL;
1695 if (empty($dataid)) {
1696 $dataid = $data->id;
1697 } else if ($dataid != $data->id) {
1701 if (empty($fields)) {
1702 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1703 foreach ($fieldrecords as $fieldrecord) {
1704 $fields[]= data_get_field($fieldrecord, $data);
1707 $isteacher = has_capability('mod/data:managetemplates', $context);
1711 $patterns = array();
1712 $replacement = array();
1714 // Then we generate strings to replace for normal tags
1715 foreach ($fields as $field) {
1716 $fieldname = $field->field->name;
1717 $fieldname = preg_quote($fieldname, '/');
1718 $patterns[] = "/\[\[$fieldname\]\]/i";
1719 $searchfield = data_get_field_from_id($field->field->id, $data);
1720 if (!empty($search_array[$field->field->id]->data)) {
1721 $replacement[] = $searchfield->display_search_field($search_array[$field->field->id]->data);
1723 $replacement[] = $searchfield->display_search_field();
1726 $fn = !empty($search_array[DATA_FIRSTNAME]->data) ? $search_array[DATA_FIRSTNAME]->data : '';
1727 $ln = !empty($search_array[DATA_LASTNAME]->data) ? $search_array[DATA_LASTNAME]->data : '';
1728 $patterns[] = '/##firstname##/';
1729 $replacement[] = '<label class="accesshide" for="u_fn">'.get_string('authorfirstname', 'data').'</label><input type="text" size="16" id="u_fn" name="u_fn" value="'.$fn.'" />';
1730 $patterns[] = '/##lastname##/';
1731 $replacement[] = '<label class="accesshide" for="u_ln">'.get_string('authorlastname', 'data').'</label><input type="text" size="16" id="u_ln" name="u_ln" value="'.$ln.'" />';
1733 // actual replacement of the tags
1734 $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate);
1736 $options = new stdClass();
1737 $options->para=false;
1738 $options->noclean=true;
1740 echo format_text($newtext, FORMAT_HTML, $options);
1743 echo '<tr><td colspan="4"><br/><input type="submit" value="'.get_string('savesettings','data').'" /><input type="submit" name="resetadv" value="'.get_string('resetsettings','data').'" /></td></tr>';
1754 * @param object $data
1755 * @param object $record
1756 * @return void Output echo'd
1758 function data_print_ratings($data, $record) {
1760 if (!empty($record->rating)){
1761 echo $OUTPUT->render($record->rating);
1766 * List the actions that correspond to a view of this module.
1767 * This is used by the participation report.
1769 * Note: This is not used by new logging system. Event with
1770 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1771 * be considered as view action.
1775 function data_get_view_actions() {
1776 return array('view');
1780 * List the actions that correspond to a post of this module.
1781 * This is used by the participation report.
1783 * Note: This is not used by new logging system. Event with
1784 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1785 * will be considered as post action.
1789 function data_get_post_actions() {
1790 return array('add','update','record delete');
1794 * @param string $name
1795 * @param int $dataid
1796 * @param int $fieldid
1799 function data_fieldname_exists($name, $dataid, $fieldid = 0) {
1802 if (!is_numeric($name)) {
1803 $like = $DB->sql_like('df.name', ':name', false);
1805 $like = "df.name = :name";
1807 $params = array('name'=>$name);
1809 $params['dataid'] = $dataid;
1810 $params['fieldid1'] = $fieldid;
1811 $params['fieldid2'] = $fieldid;
1812 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1813 WHERE $like AND df.dataid = :dataid
1814 AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
1816 $params['dataid'] = $dataid;
1817 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1818 WHERE $like AND df.dataid = :dataid", $params);
1823 * @param array $fieldinput
1825 function data_convert_arrays_to_strings(&$fieldinput) {
1826 foreach ($fieldinput as $key => $val) {
1827 if (is_array($val)) {
1829 foreach ($val as $inner) {
1830 $str .= $inner . ',';
1832 $str = substr($str, 0, -1);
1834 $fieldinput->$key = $str;
1841 * Converts a database (module instance) to use the Roles System
1845 * @uses CONTEXT_MODULE
1848 * @param object $data a data object with the same attributes as a record
1849 * from the data database table
1850 * @param int $datamodid the id of the data module, from the modules table
1851 * @param array $teacherroles array of roles that have archetype teacher
1852 * @param array $studentroles array of roles that have archetype student
1853 * @param array $guestroles array of roles that have archetype guest
1854 * @param int $cmid the course_module id for this data instance
1855 * @return boolean data module was converted or not
1857 function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
1858 global $CFG, $DB, $OUTPUT;
1860 if (!isset($data->participants) && !isset($data->assesspublic)
1861 && !isset($data->groupmode)) {
1862 // We assume that this database has already been converted to use the
1863 // Roles System. above fields get dropped the data module has been
1864 // upgraded to use Roles.
1869 // We were not given the course_module id. Try to find it.
1870 if (!$cm = get_coursemodule_from_instance('data', $data->id)) {
1871 echo $OUTPUT->notification('Could not get the course module for the data');
1877 $context = context_module::instance($cmid);
1880 // $data->participants:
1881 // 1 - Only teachers can add entries
1882 // 3 - Teachers and students can add entries
1883 switch ($data->participants) {
1885 foreach ($studentroles as $studentrole) {
1886 assign_capability('mod/data:writeentry', CAP_PREVENT, $studentrole->id, $context->id);
1888 foreach ($teacherroles as $teacherrole) {
1889 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1893 foreach ($studentroles as $studentrole) {
1894 assign_capability('mod/data:writeentry', CAP_ALLOW, $studentrole->id, $context->id);
1896 foreach ($teacherroles as $teacherrole) {
1897 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1903 // 2 - Only teachers can rate posts
1904 // 1 - Everyone can rate posts
1905 // 0 - No one can rate posts
1906 switch ($data->assessed) {
1908 foreach ($studentroles as $studentrole) {
1909 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1911 foreach ($teacherroles as $teacherrole) {
1912 assign_capability('mod/data:rate', CAP_PREVENT, $teacherrole->id, $context->id);
1916 foreach ($studentroles as $studentrole) {
1917 assign_capability('mod/data:rate', CAP_ALLOW, $studentrole->id, $context->id);
1919 foreach ($teacherroles as $teacherrole) {
1920 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1924 foreach ($studentroles as $studentrole) {
1925 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1927 foreach ($teacherroles as $teacherrole) {
1928 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1933 // $data->assesspublic:
1934 // 0 - Students can only see their own ratings
1935 // 1 - Students can see everyone's ratings
1936 switch ($data->assesspublic) {
1938 foreach ($studentroles as $studentrole) {
1939 assign_capability('mod/data:viewrating', CAP_PREVENT, $studentrole->id, $context->id);
1941 foreach ($teacherroles as $teacherrole) {
1942 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1946 foreach ($studentroles as $studentrole) {
1947 assign_capability('mod/data:viewrating', CAP_ALLOW, $studentrole->id, $context->id);
1949 foreach ($teacherroles as $teacherrole) {
1950 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1956 $cm = $DB->get_record('course_modules', array('id'=>$cmid));
1959 switch ($cm->groupmode) {
1962 case SEPARATEGROUPS:
1963 foreach ($studentroles as $studentrole) {
1964 assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id);
1966 foreach ($teacherroles as $teacherrole) {
1967 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1971 foreach ($studentroles as $studentrole) {
1972 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id);
1974 foreach ($teacherroles as $teacherrole) {
1975 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1983 * Returns the best name to show for a preset
1985 * @param string $shortname
1986 * @param string $path
1989 function data_preset_name($shortname, $path) {
1991 // We are looking inside the preset itself as a first choice, but also in normal data directory
1992 $string = get_string('modulename', 'datapreset_'.$shortname);
1994 if (substr($string, 0, 1) == '[') {
2002 * Returns an array of all the available presets.
2006 function data_get_available_presets($context) {
2011 // First load the ratings sub plugins that exist within the modules preset dir
2012 if ($dirs = core_component::get_plugin_list('datapreset')) {
2013 foreach ($dirs as $dir=>$fulldir) {
2014 if (is_directory_a_preset($fulldir)) {
2015 $preset = new stdClass();
2016 $preset->path = $fulldir;
2017 $preset->userid = 0;
2018 $preset->shortname = $dir;
2019 $preset->name = data_preset_name($dir, $fulldir);
2020 if (file_exists($fulldir.'/screenshot.jpg')) {
2021 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.jpg';
2022 } else if (file_exists($fulldir.'/screenshot.png')) {
2023 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.png';
2024 } else if (file_exists($fulldir.'/screenshot.gif')) {
2025 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.gif';
2027 $presets[] = $preset;
2031 // Now add to that the site presets that people have saved
2032 $presets = data_get_available_site_presets($context, $presets);
2037 * Gets an array of all of the presets that users have saved to the site.
2039 * @param stdClass $context The context that we are looking from.
2040 * @param array $presets
2041 * @return array An array of presets
2043 function data_get_available_site_presets($context, array $presets=array()) {
2046 $fs = get_file_storage();
2047 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2048 $canviewall = has_capability('mod/data:viewalluserpresets', $context);
2049 if (empty($files)) {
2052 foreach ($files as $file) {
2053 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory() || (!$canviewall && $file->get_userid() != $USER->id)) {
2056 $preset = new stdClass;
2057 $preset->path = $file->get_filepath();
2058 $preset->name = trim($preset->path, '/');
2059 $preset->shortname = $preset->name;
2060 $preset->userid = $file->get_userid();
2061 $preset->id = $file->get_id();
2062 $preset->storedfile = $file;
2063 $presets[] = $preset;
2069 * Deletes a saved preset.
2071 * @param string $name
2074 function data_delete_site_preset($name) {
2075 $fs = get_file_storage();
2077 $files = $fs->get_directory_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/');
2078 if (!empty($files)) {
2079 foreach ($files as $file) {
2084 $dir = $fs->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/', '.');
2092 * Prints the heads for a page
2094 * @param stdClass $course
2095 * @param stdClass $cm
2096 * @param stdClass $data
2097 * @param string $currenttab
2099 function data_print_header($course, $cm, $data, $currenttab='') {
2101 global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
2103 $PAGE->set_title($data->name);
2104 echo $OUTPUT->header();
2105 echo $OUTPUT->heading(format_string($data->name), 2);
2106 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
2108 // Groups needed for Add entry tab
2109 $currentgroup = groups_get_activity_group($cm);
2110 $groupmode = groups_get_activity_groupmode($cm);
2115 include('tabs.php');
2118 // Print any notices
2120 if (!empty($displaynoticegood)) {
2121 echo $OUTPUT->notification($displaynoticegood, 'notifysuccess'); // good (usually green)
2122 } else if (!empty($displaynoticebad)) {
2123 echo $OUTPUT->notification($displaynoticebad); // bad (usuually red)
2128 * Can user add more entries?
2130 * @param object $data
2131 * @param mixed $currentgroup
2132 * @param int $groupmode
2133 * @param stdClass $context
2136 function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
2139 if (empty($context)) {
2140 $cm = get_coursemodule_from_instance('data', $data->id, 0, false, MUST_EXIST);
2141 $context = context_module::instance($cm->id);
2144 if (has_capability('mod/data:manageentries', $context)) {
2145 // no entry limits apply if user can manage
2147 } else if (!has_capability('mod/data:writeentry', $context)) {
2150 } else if (data_atmaxentries($data)) {
2152 } else if (data_in_readonly_period($data)) {
2153 // Check whether we're in a read-only period
2157 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2161 if ($currentgroup) {
2162 return groups_is_member($currentgroup);
2164 //else it might be group 0 in visible mode
2165 if ($groupmode == VISIBLEGROUPS){
2174 * Check whether the current user is allowed to manage the given record considering manageentries capability,
2175 * data_in_readonly_period() result, ownership (determined by data_isowner()) and manageapproved setting.
2176 * @param mixed $record record object or id
2177 * @param object $data data object
2178 * @param object $context context object
2179 * @return bool returns true if the user is allowd to edit the entry, false otherwise
2181 function data_user_can_manage_entry($record, $data, $context) {
2184 if (has_capability('mod/data:manageentries', $context)) {
2188 // Check whether this activity is read-only at present.
2189 $readonly = data_in_readonly_period($data);
2192 // Get record object from db if just id given like in data_isowner.
2193 // ...done before calling data_isowner() to avoid querying db twice.
2194 if (!is_object($record)) {
2195 if (!$record = $DB->get_record('data_records', array('id' => $record))) {
2199 if (data_isowner($record)) {
2200 if ($data->approval && $record->approved) {
2201 return $data->manageapproved == 1;
2212 * Check whether the specified database activity is currently in a read-only period
2214 * @param object $data
2215 * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2217 function data_in_readonly_period($data) {
2219 if (!$data->timeviewfrom && !$data->timeviewto) {
2221 } else if (($data->timeviewfrom && $now < $data->timeviewfrom) || ($data->timeviewto && $now > $data->timeviewto)) {
2230 function is_directory_a_preset($directory) {
2231 $directory = rtrim($directory, '/\\') . '/';
2232 $status = file_exists($directory.'singletemplate.html') &&
2233 file_exists($directory.'listtemplate.html') &&
2234 file_exists($directory.'listtemplateheader.html') &&
2235 file_exists($directory.'listtemplatefooter.html') &&
2236 file_exists($directory.'addtemplate.html') &&
2237 file_exists($directory.'rsstemplate.html') &&
2238 file_exists($directory.'rsstitletemplate.html') &&
2239 file_exists($directory.'csstemplate.css') &&
2240 file_exists($directory.'jstemplate.js') &&
2241 file_exists($directory.'preset.xml');
2247 * Abstract class used for data preset importers
2249 abstract class data_preset_importer {
2254 protected $directory;
2259 * @param stdClass $course
2260 * @param stdClass $cm
2261 * @param stdClass $module
2262 * @param string $directory
2264 public function __construct($course, $cm, $module, $directory) {
2265 $this->course = $course;
2267 $this->module = $module;
2268 $this->directory = $directory;
2272 * Returns the name of the directory the preset is located in
2275 public function get_directory() {
2276 return basename($this->directory);
2280 * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2281 * @param file_storage $filestorage. should be null if using a conventional directory
2282 * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2283 * @param string $dir the directory to look in. null if using the Moodle file storage
2284 * @param string $filename the name of the file we want
2285 * @return string the contents of the file or null if the file doesn't exist.
2287 public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2288 if(empty($filestorage) || empty($fileobj)) {
2289 if (substr($dir, -1)!='/') {
2292 if (file_exists($dir.$filename)) {
2293 return file_get_contents($dir.$filename);
2298 if ($filestorage->file_exists(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename)) {
2299 $file = $filestorage->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename);
2300 return $file->get_content();
2308 * Gets the preset settings
2309 * @global moodle_database $DB
2312 public function get_preset_settings() {
2315 $fs = $fileobj = null;
2316 if (!is_directory_a_preset($this->directory)) {
2317 //maybe the user requested a preset stored in the Moodle file storage
2319 $fs = get_file_storage();
2320 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2322 //preset name to find will be the final element of the directory
2323 $explodeddirectory = explode('/', $this->directory);
2324 $presettofind = end($explodeddirectory);
2326 //now go through the available files available and see if we can find it
2327 foreach ($files as $file) {
2328 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory()) {
2331 $presetname = trim($file->get_filepath(), '/');
2332 if ($presetname==$presettofind) {
2333 $this->directory = $presetname;
2338 if (empty($fileobj)) {
2339 print_error('invalidpreset', 'data', '', $this->directory);
2343 $allowed_settings = array(
2347 'requiredentriestoview',
2354 $result = new stdClass;
2355 $result->settings = new stdClass;
2356 $result->importfields = array();
2357 $result->currentfields = $DB->get_records('data_fields', array('dataid'=>$this->module->id));
2358 if (!$result->currentfields) {
2359 $result->currentfields = array();
2364 $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory,'preset.xml');
2365 $parsedxml = xmlize($presetxml, 0);
2367 /* First, do settings. Put in user friendly array. */
2368 $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
2369 $result->settings = new StdClass();
2370 foreach ($settingsarray as $setting => $value) {
2371 if (!is_array($value) || !in_array($setting, $allowed_settings)) {
2372 // unsupported setting
2375 $result->settings->$setting = $value[0]['#'];
2378 /* Now work out fields to user friendly array */
2379 $fieldsarray = $parsedxml['preset']['#']['field'];
2380 foreach ($fieldsarray as $field) {
2381 if (!is_array($field)) {
2384 $f = new StdClass();
2385 foreach ($field['#'] as $param => $value) {
2386 if (!is_array($value)) {
2389 $f->$param = $value[0]['#'];
2391 $f->dataid = $this->module->id;
2392 $f->type = clean_param($f->type, PARAM_ALPHA);
2393 $result->importfields[] = $f;
2395 /* Now add the HTML templates to the settings array so we can update d */
2396 $result->settings->singletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"singletemplate.html");
2397 $result->settings->listtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplate.html");
2398 $result->settings->listtemplateheader = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplateheader.html");
2399 $result->settings->listtemplatefooter = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplatefooter.html");
2400 $result->settings->addtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"addtemplate.html");
2401 $result->settings->rsstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstemplate.html");
2402 $result->settings->rsstitletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstitletemplate.html");
2403 $result->settings->csstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"csstemplate.css");
2404 $result->settings->jstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"jstemplate.js");
2405 $result->settings->asearchtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"asearchtemplate.html");
2407 $result->settings->instance = $this->module->id;
2412 * Import the preset into the given database module
2415 function import($overwritesettings) {
2418 $params = $this->get_preset_settings();
2419 $settings = $params->settings;
2420 $newfields = $params->importfields;
2421 $currentfields = $params->currentfields;
2422 $preservedfields = array();
2424 /* Maps fields and makes new ones */
2425 if (!empty($newfields)) {
2426 /* We require an injective mapping, and need to know what to protect */
2427 foreach ($newfields as $nid => $newfield) {
2428 $cid = optional_param("field_$nid", -1, PARAM_INT);
2432 if (array_key_exists($cid, $preservedfields)){
2433 print_error('notinjectivemap', 'data');
2435 else $preservedfields[$cid] = true;
2438 foreach ($newfields as $nid => $newfield) {
2439 $cid = optional_param("field_$nid", -1, PARAM_INT);
2441 /* A mapping. Just need to change field params. Data kept. */
2442 if ($cid != -1 and isset($currentfields[$cid])) {
2443 $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->module);
2444 foreach ($newfield as $param => $value) {
2445 if ($param != "id") {
2446 $fieldobject->field->$param = $value;
2449 unset($fieldobject->field->similarfield);
2450 $fieldobject->update_field();
2451 unset($fieldobject);
2453 /* Make a new field */
2454 include_once("field/$newfield->type/field.class.php");
2456 if (!isset($newfield->description)) {
2457 $newfield->description = '';
2459 $classname = 'data_field_'.$newfield->type;
2460 $fieldclass = new $classname($newfield, $this->module);
2461 $fieldclass->insert_field();
2467 /* Get rid of all old unused data */
2468 if (!empty($preservedfields)) {
2469 foreach ($currentfields as $cid => $currentfield) {
2470 if (!array_key_exists($cid, $preservedfields)) {
2471 /* Data not used anymore so wipe! */
2472 print "Deleting field $currentfield->name<br />";
2474 $id = $currentfield->id;
2475 //Why delete existing data records and related comments/ratings??
2476 $DB->delete_records('data_content', array('fieldid'=>$id));
2477 $DB->delete_records('data_fields', array('id'=>$id));
2482 // handle special settings here
2483 if (!empty($settings->defaultsort)) {
2484 if (is_numeric($settings->defaultsort)) {
2486 $settings->defaultsort = 0;
2488 $settings->defaultsort = (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module->id, 'name'=>$settings->defaultsort));
2491 $settings->defaultsort = 0;
2494 // do we want to overwrite all current database settings?
2495 if ($overwritesettings) {
2496 // all supported settings
2497 $overwrite = array_keys((array)$settings);
2499 // only templates and sorting
2500 $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2501 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
2502 'asearchtemplate', 'defaultsortdir', 'defaultsort');
2505 // now overwrite current data settings
2506 foreach ($this->module as $prop=>$unused) {
2507 if (in_array($prop, $overwrite)) {
2508 $this->module->$prop = $settings->$prop;
2512 data_update_instance($this->module);
2514 return $this->cleanup();
2518 * Any clean up routines should go here
2521 public function cleanup() {
2527 * Data preset importer for uploaded presets
2529 class data_preset_upload_importer extends data_preset_importer {
2530 public function __construct($course, $cm, $module, $filepath) {
2532 if (is_file($filepath)) {
2533 $fp = get_file_packer();
2534 if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2535 fulldelete($filepath);
2537 $filepath .= '_extracted';
2539 parent::__construct($course, $cm, $module, $filepath);
2541 public function cleanup() {
2542 return fulldelete($this->directory);
2547 * Data preset importer for existing presets
2549 class data_preset_existing_importer extends data_preset_importer {
2551 public function __construct($course, $cm, $module, $fullname) {
2553 list($userid, $shortname) = explode('/', $fullname, 2);
2554 $context = context_module::instance($cm->id);
2555 if ($userid && ($userid != $USER->id) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2556 throw new coding_exception('Invalid preset provided');
2559 $this->userid = $userid;
2560 $filepath = data_preset_path($course, $userid, $shortname);
2561 parent::__construct($course, $cm, $module, $filepath);
2563 public function get_userid() {
2564 return $this->userid;
2571 * @param object $course
2572 * @param int $userid
2573 * @param string $shortname
2576 function data_preset_path($course, $userid, $shortname) {
2579 $context = context_course::instance($course->id);
2581 $userid = (int)$userid;
2584 if ($userid > 0 && ($userid == $USER->id || has_capability('mod/data:viewalluserpresets', $context))) {
2585 $path = $CFG->dataroot.'/data/preset/'.$userid.'/'.$shortname;
2586 } else if ($userid == 0) {
2587 $path = $CFG->dirroot.'/mod/data/preset/'.$shortname;
2588 } else if ($userid < 0) {
2589 $path = $CFG->tempdir.'/data/'.-$userid.'/'.$shortname;
2596 * Implementation of the function for printing the form elements that control
2597 * whether the course reset functionality affects the data.
2599 * @param $mform form passed by reference
2601 function data_reset_course_form_definition(&$mform) {
2602 $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2603 $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2605 $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2606 $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2608 $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2609 $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2611 $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2612 $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
2616 * Course reset form defaults.
2619 function data_reset_course_form_defaults($course) {
2620 return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2624 * Removes all grades from gradebook
2628 * @param int $courseid
2629 * @param string $type optional type
2631 function data_reset_gradebook($courseid, $type='') {
2634 $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
2635 FROM {data} d, {course_modules} cm, {modules} m
2636 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
2638 if ($datas = $DB->get_records_sql($sql, array($courseid))) {
2639 foreach ($datas as $data) {
2640 data_grade_item_update($data, 'reset');
2646 * Actual implementation of the reset course functionality, delete all the
2647 * data responses for course $data->courseid.
2651 * @param object $data the data submitted from the reset course.
2652 * @return array status array
2654 function data_reset_userdata($data) {
2656 require_once($CFG->libdir.'/filelib.php');
2657 require_once($CFG->dirroot.'/rating/lib.php');
2659 $componentstr = get_string('modulenameplural', 'data');
2662 $allrecordssql = "SELECT r.id
2663 FROM {data_records} r
2664 INNER JOIN {data} d ON r.dataid = d.id
2665 WHERE d.course = ?";
2667 $alldatassql = "SELECT d.id
2671 $rm = new rating_manager();
2672 $ratingdeloptions = new stdClass;
2673 $ratingdeloptions->component = 'mod_data';
2674 $ratingdeloptions->ratingarea = 'entry';
2676 // Set the file storage - may need it to remove files later.
2677 $fs = get_file_storage();
2679 // delete entries if requested
2680 if (!empty($data->reset_data)) {
2681 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2682 $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid));
2683 $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid));
2685 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2686 foreach ($datas as $dataid=>$unused) {
2687 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2690 $datacontext = context_module::instance($cm->id);
2692 // Delete any files that may exist.
2693 $fs->delete_area_files($datacontext->id, 'mod_data', 'content');
2695 $ratingdeloptions->contextid = $datacontext->id;
2696 $rm->delete_ratings($ratingdeloptions);
2700 if (empty($data->reset_gradebook_grades)) {
2701 // remove all grades from gradebook
2702 data_reset_gradebook($data->courseid);
2704 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2707 // remove entries by users not enrolled into course
2708 if (!empty($data->reset_data_notenrolled)) {
2709 $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
2710 FROM {data_records} r
2711 JOIN {data} d ON r.dataid = d.id
2712 LEFT JOIN {user} u ON r.userid = u.id
2713 WHERE d.course = ? AND r.userid > 0";
2715 $course_context = context_course::instance($data->courseid);
2716 $notenrolled = array();
2718 $rs = $DB->get_recordset_sql($recordssql, array($data->courseid));
2719 foreach ($rs as $record) {
2720 if (array_key_exists($record->userid, $notenrolled) or !$record->userexists or $record->userdeleted
2721 or !is_enrolled($course_context, $record->userid)) {
2723 if (!$cm = get_coursemodule_from_instance('data', $record->dataid)) {
2726 $datacontext = context_module::instance($cm->id);
2727 $ratingdeloptions->contextid = $datacontext->id;
2728 $ratingdeloptions->itemid = $record->id;
2729 $rm->delete_ratings($ratingdeloptions);
2731 // Delete any files that may exist.
2732 if ($contents = $DB->get_records('data_content', array('recordid' => $record->id), '', 'id')) {
2733 foreach ($contents as $content) {
2734 $fs->delete_area_files($datacontext->id, 'mod_data', 'content', $content->id);
2737 $notenrolled[$record->userid] = true;
2739 $DB->delete_records('comments', array('itemid' => $record->id, 'commentarea' => 'database_entry'));
2740 $DB->delete_records('data_content', array('recordid' => $record->id));
2741 $DB->delete_records('data_records', array('id' => $record->id));
2745 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
2748 // remove all ratings
2749 if (!empty($data->reset_data_ratings)) {
2750 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2751 foreach ($datas as $dataid=>$unused) {
2752 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2755 $datacontext = context_module::instance($cm->id);
2757 $ratingdeloptions->contextid = $datacontext->id;
2758 $rm->delete_ratings($ratingdeloptions);
2762 if (empty($data->reset_gradebook_grades)) {
2763 // remove all grades from gradebook
2764 data_reset_gradebook($data->courseid);
2767 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2770 // remove all comments
2771 if (!empty($data->reset_data_comments)) {
2772 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2773 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2776 // updating dates - shift may be negative too
2777 if ($data->timeshift) {
2778 shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto'), $data->timeshift, $data->courseid);
2779 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2786 * Returns all other caps used in module
2790 function data_get_extra_capabilities() {
2791 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate', 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete');
2795 * @param string $feature FEATURE_xx constant for requested feature
2796 * @return mixed True if module supports feature, null if doesn't know
2798 function data_supports($feature) {
2800 case FEATURE_GROUPS: return true;
2801 case FEATURE_GROUPINGS: return true;
2802 case FEATURE_MOD_INTRO: return true;
2803 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
2804 case FEATURE_GRADE_HAS_GRADE: return true;
2805 case FEATURE_GRADE_OUTCOMES: return true;
2806 case FEATURE_RATE: return true;
2807 case FEATURE_BACKUP_MOODLE2: return true;
2808 case FEATURE_SHOW_DESCRIPTION: return true;
2810 default: return null;
2815 * @param array $export
2816 * @param string $delimiter_name
2817 * @param object $database
2819 * @param bool $return
2820 * @return string|void
2822 function data_export_csv($export, $delimiter_name, $database, $count, $return=false) {
2824 require_once($CFG->libdir . '/csvlib.class.php');
2826 $filename = $database . '-' . $count . '-record';
2831 return csv_export_writer::print_array($export, $delimiter_name, '"', true);
2833 csv_export_writer::download_array($filename, $export, $delimiter_name);
2839 * @param array $export
2840 * @param string $dataname
2844 function data_export_xls($export, $dataname, $count) {
2846 require_once("$CFG->libdir/excellib.class.php");
2847 $filename = clean_filename("{$dataname}-{$count}_record");
2851 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2852 $filename .= '.xls';
2855 $workbook = new MoodleExcelWorkbook($filearg);
2856 $workbook->send($filename);
2857 $worksheet = array();
2858 $worksheet[0] = $workbook->add_worksheet('');
2860 foreach ($export as $row) {
2862 foreach($row as $col) {
2863 $worksheet[0]->write($rowno, $colno, $col);
2874 * @param array $export
2875 * @param string $dataname
2879 function data_export_ods($export, $dataname, $count) {
2881 require_once("$CFG->libdir/odslib.class.php");
2882 $filename = clean_filename("{$dataname}-{$count}_record");
2886 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2887 $filename .= '.ods';
2889 $workbook = new MoodleODSWorkbook($filearg);
2890 $workbook->send($filename);
2891 $worksheet = array();
2892 $worksheet[0] = $workbook->add_worksheet('');
2894 foreach ($export as $row) {
2896 foreach($row as $col) {
2897 $worksheet[0]->write($rowno, $colno, $col);
2908 * @param int $dataid
2909 * @param array $fields
2910 * @param array $selectedfields
2911 * @param int $currentgroup group ID of the current group. This is used for
2912 * exporting data while maintaining group divisions.
2913 * @param object $context the context in which the operation is performed (for capability checks)
2914 * @param bool $userdetails whether to include the details of the record author
2915 * @param bool $time whether to include time created/modified
2916 * @param bool $approval whether to include approval status
2919 function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0, $context=null,
2920 $userdetails=false, $time=false, $approval=false) {
2923 if (is_null($context)) {
2924 $context = context_system::instance();
2926 // exporting user data needs special permission
2927 $userdetails = $userdetails && has_capability('mod/data:exportuserinfo', $context);
2929 $exportdata = array();
2931 // populate the header in first row of export
2932 foreach($fields as $key => $field) {
2933 if (!in_array($field->field->id, $selectedfields)) {
2934 // ignore values we aren't exporting
2935 unset($fields[$key]);
2937 $exportdata[0][] = $field->field->name;
2941 $exportdata[0][] = get_string('user');
2942 $exportdata[0][] = get_string('username');
2943 $exportdata[0][] = get_string('email');
2946 $exportdata[0][] = get_string('timeadded', 'data');
2947 $exportdata[0][] = get_string('timemodified', 'data');
2950 $exportdata[0][] = get_string('approved', 'data');
2953 $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
2954 ksort($datarecords);
2956 foreach($datarecords as $record) {
2957 // get content indexed by fieldid
2958 if ($currentgroup) {
2959 $select = 'SELECT c.fieldid, c.content, c.content1, c.content2, c.content3, c.content4 FROM {data_content} c, {data_records} r WHERE c.recordid = ? AND r.id = c.recordid AND r.groupid = ?';
2960 $where = array($record->id, $currentgroup);
2962 $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
2963 $where = array($record->id);
2966 if( $content = $DB->get_records_sql($select, $where) ) {
2967 foreach($fields as $field) {
2969 if(isset($content[$field->field->id])) {
2970 $contents = $field->export_text_value($content[$field->field->id]);
2972 $exportdata[$line][] = $contents;
2974 if ($userdetails) { // Add user details to the export data
2975 $userdata = get_complete_user_data('id', $record->userid);
2976 $exportdata[$line][] = fullname($userdata);
2977 $exportdata[$line][] = $userdata->username;
2978 $exportdata[$line][] = $userdata->email;
2980 if ($time) { // Add time added / modified
2981 $exportdata[$line][] = userdate($record->timecreated);
2982 $exportdata[$line][] = userdate($record->timemodified);
2984 if ($approval) { // Add approval status
2985 $exportdata[$line][] = (int) $record->approved;
2994 ////////////////////////////////////////////////////////////////////////////////
2996 ////////////////////////////////////////////////////////////////////////////////
2999 * Lists all browsable file areas
3003 * @param stdClass $course course object
3004 * @param stdClass $cm course module object
3005 * @param stdClass $context context object
3008 function data_get_file_areas($course, $cm, $context) {
3009 return array('content' => get_string('areacontent', 'mod_data'));
3013 * File browsing support for data module.
3015 * @param file_browser $browser
3016 * @param array $areas
3017 * @param stdClass $course
3018 * @param cm_info $cm
3019 * @param context $context
3020 * @param string $filearea
3021 * @param int $itemid
3022 * @param string $filepath
3023 * @param string $filename
3024 * @return file_info_stored file_info_stored instance or null if not found
3026 function data_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
3027 global $CFG, $DB, $USER;
3029 if ($context->contextlevel != CONTEXT_MODULE) {
3033 if (!isset($areas[$filearea])) {
3037 if (is_null($itemid)) {
3038 require_once($CFG->dirroot.'/mod/data/locallib.php');
3039 return new data_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
3042 if (!$content = $DB->get_record('data_content', array('id'=>$itemid))) {
3046 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
3050 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
3054 if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
3059 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3064 if ($record->groupid) {
3065 $groupmode = groups_get_activity_groupmode($cm, $course);
3066 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3067 if (!groups_is_member($record->groupid)) {
3073 $fieldobj = data_get_field($field, $data, $cm);
3075 $filepath = is_null($filepath) ? '/' : $filepath;
3076 $filename = is_null($filename) ? '.' : $filename;
3077 if (!$fieldobj->file_ok($filepath.$filename)) {
3081 $fs = get_file_storage();
3082 if (!($storedfile = $fs->get_file($context->id, 'mod_data', $filearea, $itemid, $filepath, $filename))) {
3086 // Checks to see if the user can manage files or is the owner.
3087 // TODO MDL-33805 - Do not use userid here and move the capability check above.
3088 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
3092 $urlbase = $CFG->wwwroot.'/pluginfile.php';
3094 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
3098 * Serves the data attachments. Implements needed access control ;-)
3102 * @param stdClass $course course object
3103 * @param stdClass $cm course module object
3104 * @param stdClass $context context object
3105 * @param string $filearea file area
3106 * @param array $args extra arguments
3107 * @param bool $forcedownload whether or not force download
3108 * @param array $options additional options affecting the file serving
3109 * @return bool false if file not found, does not return if found - justsend the file
3111 function data_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3114 if ($context->contextlevel != CONTEXT_MODULE) {
3118 require_course_login($course, true, $cm);
3120 if ($filearea === 'content') {
3121 $contentid = (int)array_shift($args);
3123 if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
3127 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
3131 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
3135 if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
3139 if ($data->id != $cm->instance) {
3140 // hacker attempt - context does not match the contentid
3145 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3150 if ($record->groupid) {
3151 $groupmode = groups_get_activity_groupmode($cm, $course);
3152 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3153 if (!groups_is_member($record->groupid)) {
3159 $fieldobj = data_get_field($field, $data, $cm);
3161 $relativepath = implode('/', $args);
3162 $fullpath = "/$context->id/mod_data/content/$content->id/$relativepath";
3164 if (!$fieldobj->file_ok($relativepath)) {
3168 $fs = get_file_storage();
3169 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3173 // finally send the file
3174 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
3181 function data_extend_navigation($navigation, $course, $module, $cm) {
3182 global $CFG, $OUTPUT, $USER, $DB;
3184 $rid = optional_param('rid', 0, PARAM_INT);
3186 $data = $DB->get_record('data', array('id'=>$cm->instance));
3187 $currentgroup = groups_get_activity_group($cm);
3188 $groupmode = groups_get_activity_groupmode($cm);
3190 $numentries = data_numentries($data);
3191 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
3192 if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !has_capability('mod/data:manageentries', context_module::instance($cm->id))) {
3193 $data->entriesleft = $data->requiredentries - $numentries;
3194 $entriesnode = $navigation->add(get_string('entrieslefttoadd', 'data', $data));
3195 $entriesnode->add_class('note');
3198 $navigation->add(get_string('list', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance)));
3200 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'rid'=>$rid)));
3202 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'single')));
3204 $navigation->add(get_string('search', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'asearch')));
3208 * Adds module specific settings to the settings block
3210 * @param settings_navigation $settings The settings navigation object
3211 * @param navigation_node $datanode The node to add module settings to
3213 function data_extend_settings_navigation(settings_navigation $settings, navigation_node $datanode) {
3214 global $PAGE, $DB, $CFG, $USER;
3216 $data = $DB->get_record('data', array("id" => $PAGE->cm->instance));
3218 $currentgroup = groups_get_activity_group($PAGE->cm);
3219 $groupmode = groups_get_activity_groupmode($PAGE->cm);
3221 if (data_user_can_add_entry($data, $currentgroup, $groupmode, $PAGE->cm->context)) { // took out participation list here!
3222 if (empty($editentry)) { //TODO: undefined
3223 $addstring = get_string('add', 'data');
3225 $addstring = get_string('editentry', 'data');
3227 $datanode->add($addstring, new moodle_url('/mod/data/edit.php', array('d'=>$PAGE->cm->instance)));
3230 if (has_capability(DATA_CAP_EXPORT, $PAGE->cm->context)) {
3231 // The capability required to Export database records is centrally defined in 'lib.php'
3232 // and should be weaker than those required to edit Templates, Fields and Presets.
3233 $datanode->add(get_string('exportentries', 'data'), new moodle_url('/mod/data/export.php', array('d'=>$data->id)));
3235 if (has_capability('mod/data:manageentries', $PAGE->cm->context)) {
3236 $datanode->add(get_string('importentries', 'data'), new moodle_url('/mod/data/import.php', array('d'=>$data->id)));
3239 if (has_capability('mod/data:managetemplates', $PAGE->cm->context)) {
3241 if ($currenttab == 'list') {
3242 $defaultemplate = 'listtemplate';
3243 } else if ($currenttab == 'add') {
3244 $defaultemplate = 'addtemplate';
3245 } else if ($currenttab == 'asearch') {
3246 $defaultemplate = 'asearchtemplate';
3248 $defaultemplate = 'singletemplate';
3251 $templates = $datanode->add(get_string('templates', 'data'));
3253 $templatelist = array ('listtemplate', 'singletemplate', 'asearchtemplate', 'addtemplate', 'rsstemplate', 'csstemplate', 'jstemplate');
3254 foreach ($templatelist as $template) {
3255 $templates->add(get_string($template, 'data'), new moodle_url('/mod/data/templates.php', array('d'=>$data->id,'mode'=>$template)));
3258 $datanode->add(get_string('fields', 'data'), new moodle_url('/mod/data/field.php', array('d'=>$data->id)));
3259 $datanode->add(get_string('presets', 'data'), new moodle_url('/mod/data/preset.php', array('d'=>$data->id)));
3262 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
3263 require_once("$CFG->libdir/rsslib.php");
3265 $string = get_string('rsstype','forum');
3267 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_data', $data->id));
3268 $datanode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
3273 * Save the database configuration as a preset.
3275 * @param stdClass $course The course the database module belongs to.
3276 * @param stdClass $cm The course module record
3277 * @param stdClass $data The database record
3278 * @param string $path
3281 function data_presets_save($course, $cm, $data, $path) {
3283 $fs = get_file_storage();
3284 $filerecord = new stdClass;
3285 $filerecord->contextid = DATA_PRESET_CONTEXT;
3286 $filerecord->component = DATA_PRESET_COMPONENT;
3287 $filerecord->filearea = DATA_PRESET_FILEAREA;
3288 $filerecord->itemid = 0;
3289 $filerecord->filepath = '/'.$path.'/';
3290 $filerecord->userid = $USER->id;
3292 $filerecord->filename = 'preset.xml';
3293 $fs->create_file_from_string($filerecord, data_presets_generate_xml($course, $cm, $data));
3295 $filerecord->filename = 'singletemplate.html';
3296 $fs->create_file_from_string($filerecord, $data->singletemplate);
3298 $filerecord->filename = 'listtemplateheader.html';
3299 $fs->create_file_from_string($filerecord, $data->listtemplateheader);
3301 $filerecord->filename = 'listtemplate.html';
3302 $fs->create_file_from_string($filerecord, $data->listtemplate);
3304 $filerecord->filename = 'listtemplatefooter.html';
3305 $fs->create_file_from_string($filerecord, $data->listtemplatefooter);
3307 $filerecord->filename = 'addtemplate.html';
3308 $fs->create_file_from_string($filerecord, $data->addtemplate);
3310 $filerecord->filename = 'rsstemplate.html';
3311 $fs->create_file_from_string($filerecord, $data->rsstemplate);
3313 $filerecord->filename = 'rsstitletemplate.html';
3314 $fs->create_file_from_string($filerecord, $data->rsstitletemplate);
3316 $filerecord->filename = 'csstemplate.css';
3317 $fs->create_file_from_string($filerecord, $data->csstemplate);
3319 $filerecord->filename = 'jstemplate.js';
3320 $fs->create_file_from_string($filerecord, $data->jstemplate);
3322 $filerecord->filename = 'asearchtemplate.html';
3323 $fs->create_file_from_string($filerecord, $data->asearchtemplate);
3329 * Generates the XML for the database module provided
3331 * @global moodle_database $DB
3332 * @param stdClass $course The course the database module belongs to.
3333 * @param stdClass $cm The course module record
3334 * @param stdClass $data The database record
3335 * @return string The XML for the preset
3337 function data_presets_generate_xml($course, $cm, $data) {
3340 // Assemble "preset.xml":
3341 $presetxmldata = "<preset>\n\n";
3343 // Raw settings are not preprocessed during saving of presets
3344 $raw_settings = array(
3348 'requiredentriestoview',
3356 $presetxmldata .= "<settings>\n";
3357 // First, settings that do not require any conversion
3358 foreach ($raw_settings as $setting) {
3359 $presetxmldata .= "<$setting>" . htmlspecialchars($data->$setting) . "</$setting>\n";
3362 // Now specific settings
3363 if ($data->defaultsort > 0 && $sortfield = data_get_field_from_id($data->defaultsort, $data)) {
3364 $presetxmldata .= '<defaultsort>' . htmlspecialchars($sortfield->field->name) . "</defaultsort>\n";
3366 $presetxmldata .= "<defaultsort>0</defaultsort>\n";
3368 $presetxmldata .= "</settings>\n\n";
3369 // Now for the fields. Grab all that are non-empty
3370 $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
3372 if (!empty($fields)) {
3373 foreach ($fields as $field) {
3374 $presetxmldata .= "<field>\n";
3375 foreach ($field as $key => $value) {
3376 if ($value != '' && $key != 'id' && $key != 'dataid') {
3377 $presetxmldata .= "<$key>" . htmlspecialchars($value) . "</$key>\n";
3380 $presetxmldata .= "</field>\n\n";
3383 $presetxmldata .= '</preset>';
3384 return $presetxmldata;
3387 function data_presets_export($course, $cm, $data, $tostorage=false) {
3390 $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi");
3391 $exportsubdir = "mod_data/presetexport/$presetname";
3392 make_temp_directory($exportsubdir);
3393 $exportdir = "$CFG->tempdir/$exportsubdir";
3395 // Assemble "preset.xml":
3396 $presetxmldata = data_presets_generate_xml($course, $cm, $data);
3398 // After opening a file in write mode, close it asap
3399 $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
3400 fwrite($presetxmlfile, $presetxmldata);
3401 fclose($presetxmlfile);
3403 // Now write the template files
3404 $singletemplate = fopen($exportdir . '/singletemplate.html', 'w');
3405 fwrite($singletemplate, $data->singletemplate);
3406 fclose($singletemplate);
3408 $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w');
3409 fwrite($listtemplateheader, $data->listtemplateheader);
3410 fclose($listtemplateheader);
3412 $listtemplate = fopen($exportdir . '/listtemplate.html', 'w');
3413 fwrite($listtemplate, $data->listtemplate);
3414 fclose($listtemplate);
3416 $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w');
3417 fwrite($listtemplatefooter, $data->listtemplatefooter);
3418 fclose($listtemplatefooter);
3420 $addtemplate = fopen($exportdir . '/addtemplate.html', 'w');
3421 fwrite($addtemplate, $data->addtemplate);
3422 fclose($addtemplate);
3424 $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w');
3425 fwrite($rsstemplate, $data->rsstemplate);
3426 fclose($rsstemplate);
3428 $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w');
3429 fwrite($rsstitletemplate, $data->rsstitletemplate);
3430 fclose($rsstitletemplate);
3432 $csstemplate = fopen($exportdir . '/csstemplate.css', 'w');
3433 fwrite($csstemplate, $data->csstemplate);
3434 fclose($csstemplate);
3436 $jstemplate = fopen($exportdir . '/jstemplate.js', 'w');
3437 fwrite($jstemplate, $data->jstemplate);
3438 fclose($jstemplate);
3440 $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w');
3441 fwrite($asearchtemplate, $data->asearchtemplate);
3442 fclose($asearchtemplate);
3444 // Check if all files have been generated
3445 if (! is_directory_a_preset($exportdir)) {
3446 print_error('generateerror', 'data');
3451 'singletemplate.html',
3452 'listtemplateheader.html',
3453 'listtemplate.html',
3454 'listtemplatefooter.html',
3457 'rsstitletemplate.html',
3460 'asearchtemplate.html'
3463 $filelist = array();
3464 foreach ($filenames as $filename) {
3465 $filelist[$filename] = $exportdir . '/' . $filename;
3468 $exportfile = $exportdir.'.zip';
3469 file_exists($exportfile) && unlink($exportfile);
3471 $fp = get_file_packer('application/zip');
3472 $fp->archive_to_pathname($filelist, $exportfile);
3474 foreach ($filelist as $file) {
3479 // Return the full path to the exported preset file:
3484 * Running addtional permission check on plugin, for example, plugins
3485 * may have switch to turn on/off comments option, this callback will
3486 * affect UI display, not like pluginname_comment_validate only throw
3488 * Capability check has been done in comment->check_permissions(), we
3489 * don't need to do it again here.
3494 * @param stdClass $comment_param {
3495 * context => context the context object
3496 * courseid => int course id
3497 * cm => stdClass course module object
3498 * commentarea => string comment area
3499 * itemid => int itemid
3503 function data_comment_permissions($comment_param) {
3505 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3506 throw new comment_exception('invalidcommentitemid');
3508 if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3509 throw new comment_exception('invalidid', 'data');
3511 if ($data->comments) {
3512 return array('post'=>true, 'view'=>true);
3514 return array('post'=>false, 'view'=>false);
3519 * Validate comment parameter before perform other comments actions
3524 * @param stdClass $comment_param {
3525 * context => context the context object
3526 * courseid => int course id
3527 * cm => stdClass course module object
3528 * commentarea => string comment area
3529 * itemid => int itemid
3533 function data_comment_validate($comment_param) {
3535 // validate comment area
3536 if ($comment_param->commentarea != 'database_entry') {
3537 throw new comment_exception('invalidcommentarea');
3540 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3541 throw new comment_exception('invalidcommentitemid');
3543 if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3544 throw new comment_exception('invalidid', 'data');
3546 if (!$course = $DB->get_record('course', array('id'=>$data->course))) {
3547 throw new comment_exception('coursemisconf');
3549 if (!$cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
3550 throw new comment_exception('invalidcoursemodule');
3552 if (!$data->comments) {
3553 throw new comment_exception('commentsoff', 'data');
3555 $context = context_module::instance($cm->id);
3558 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3559 throw new comment_exception('notapproved', 'data');
3563 if ($record->groupid) {
3564 $groupmode = groups_get_activity_groupmode($cm, $course);
3565 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3566 if (!groups_is_member($record->groupid)) {
3567 throw new comment_exception('notmemberofgroup');
3571 // validate context id
3572 if ($context->id != $comment_param->context->id) {
3573 throw new comment_exception('invalidcontext');
3575 // validation for comment deletion
3576 if (!empty($comment_param->commentid)) {
3577 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
3578 if ($comment->commentarea != 'database_entry') {
3579 throw new comment_exception('invalidcommentarea');
3581 if ($comment->contextid != $comment_param->context->id) {
3582 throw new comment_exception('invalidcontext');
3584 if ($comment->itemid != $comment_param->itemid) {
3585 throw new comment_exception('invalidcommentitemid');
3588 throw new comment_exception('invalidcommentid');
3595 * Return a list of page types
3596 * @param string $pagetype current page type
3597 * @param stdClass $parentcontext Block's parent context
3598 * @param stdClass $currentcontext Current context of block
3600 function data_page_type_list($pagetype, $parentcontext, $currentcontext) {
3601 $module_pagetype = array('mod-data-*'=>get_string('page-mod-data-x', 'data'));
3602 return $module_pagetype;
3606 * Get all of the record ids from a database activity.
3608 * @param int $dataid The dataid of the database module.
3609 * @param object $selectdata Contains an additional sql statement for the
3610 * where clause for group and approval fields.
3611 * @param array $params Parameters that coincide with the sql statement.
3612 * @return array $idarray An array of record ids
3614 function data_get_all_recordids($dataid, $selectdata = '', $params = null) {
3616 $initsql = 'SELECT r.id
3617 FROM {data_records} r
3618 WHERE r.dataid = :dataid';
3619 if ($selectdata != '') {
3620 $initsql .= $selectdata;
3621 $params = array_merge(array('dataid' => $dataid), $params);
3623 $params = array('dataid' => $dataid);
3625 $initsql .= ' GROUP BY r.id';
3626 $initrecord = $DB->get_recordset_sql($initsql, $params);
3628 foreach ($initrecord as $data) {
3629 $idarray[] = $data->id;
3631 // Close the record set and free up resources.
3632 $initrecord->close();
3637 * Get the ids of all the records that match that advanced search criteria
3638 * This goes and loops through each criterion one at a time until it either
3639 * runs out of records or returns a subset of records.
3641 * @param array $recordids An array of record ids.
3642 * @param array $searcharray Contains information for the advanced search criteria
3643 * @param int $dataid The data id of the database.
3644 * @return array $recordids An array of record ids.
3646 function data_get_advance_search_ids($recordids, $searcharray, $dataid) {
3647 $searchcriteria = array_keys($searcharray);
3648 // Loop through and reduce the IDs one search criteria at a time.
3649 foreach ($searchcriteria as $key) {
3650 $recordids = data_get_recordids($key, $searcharray, $dataid, $recordids);
3651 // If we don't have anymore IDs then stop.
3660 * Gets the record IDs given the search criteria
3662 * @param string $alias Record alias.
3663 * @param array $searcharray Criteria for the search.
3664 * @param int $dataid Data ID for the database
3665 * @param array $recordids An array of record IDs.
3666 * @return array $nestarray An arry of record IDs
3668 function data_get_recordids($alias, $searcharray, $dataid, $recordids) {
3671 $nestsearch = $searcharray[$alias];
3672 // searching for content outside of mdl_data_content
3676 list($insql, $params) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3677 $nestselect = 'SELECT c' . $alias . '.recordid
3678 FROM {data_content} c' . $alias . ',