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 $str .= html_writer
::img($OUTPUT->pix_url('req'), get_string('requiredelement', 'form'),
294 array('class' => 'req', 'title' => get_string('requiredelement', 'form')));
296 $str .= '</label><input class="basefieldinput" type="text" name="field_'.$this->field
->id
.'" id="field_'.$this->field
->id
;
297 $str .= '" value="'.s($content).'" />';
304 * Print the relevant form element to define the attributes for this field
305 * viewable by teachers only.
309 * @return void Output is echo'd
311 function display_edit_field() {
312 global $CFG, $DB, $OUTPUT;
314 if (empty($this->field
)) { // No field has been defined yet, try and make one
315 $this->define_default_field();
317 echo $OUTPUT->box_start('generalbox boxaligncenter boxwidthwide');
319 echo '<form id="editfield" action="'.$CFG->wwwroot
.'/mod/data/field.php" method="post">'."\n";
320 echo '<input type="hidden" name="d" value="'.$this->data
->id
.'" />'."\n";
321 if (empty($this->field
->id
)) {
322 echo '<input type="hidden" name="mode" value="add" />'."\n";
323 $savebutton = get_string('add');
325 echo '<input type="hidden" name="fid" value="'.$this->field
->id
.'" />'."\n";
326 echo '<input type="hidden" name="mode" value="update" />'."\n";
327 $savebutton = get_string('savechanges');
329 echo '<input type="hidden" name="type" value="'.$this->type
.'" />'."\n";
330 echo '<input name="sesskey" value="'.sesskey().'" type="hidden" />'."\n";
332 echo $OUTPUT->heading($this->name(), 3);
334 require_once($CFG->dirroot
.'/mod/data/field/'.$this->type
.'/mod.html');
336 echo '<div class="mdl-align">';
337 echo '<input type="submit" value="'.$savebutton.'" />'."\n";
338 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />'."\n";
343 echo $OUTPUT->box_end();
347 * Display the content of the field in browse mode
350 * @param int $recordid
351 * @param object $template
352 * @return bool|string
354 function display_browse_field($recordid, $template) {
357 if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field
->id
, 'recordid'=>$recordid))) {
358 if (isset($content->content
)) {
359 $options = new stdClass();
360 if ($this->field
->param1
== '1') { // We are autolinking this field, so disable linking within us
361 //$content->content = '<span class="nolink">'.$content->content.'</span>';
362 //$content->content1 = FORMAT_HTML;
363 $options->filter
=false;
365 $options->para
= false;
366 $str = format_text($content->content
, $content->content1
, $options);
376 * Update the content of one data field in the data_content table
378 * @param int $recordid
379 * @param mixed $value
380 * @param string $name
383 function update_content($recordid, $value, $name=''){
386 $content = new stdClass();
387 $content->fieldid
= $this->field
->id
;
388 $content->recordid
= $recordid;
389 $content->content
= clean_param($value, PARAM_NOTAGS
);
391 if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field
->id
, 'recordid'=>$recordid))) {
392 $content->id
= $oldcontent->id
;
393 return $DB->update_record('data_content', $content);
395 return $DB->insert_record('data_content', $content);
400 * Delete all content associated with the field
403 * @param int $recordid
406 function delete_content($recordid=0) {
410 $conditions = array('fieldid'=>$this->field
->id
, 'recordid'=>$recordid);
412 $conditions = array('fieldid'=>$this->field
->id
);
415 $rs = $DB->get_recordset('data_content', $conditions);
417 $fs = get_file_storage();
418 foreach ($rs as $content) {
419 $fs->delete_area_files($this->context
->id
, 'mod_data', 'content', $content->id
);
424 return $DB->delete_records('data_content', $conditions);
428 * Check if a field from an add form is empty
430 * @param mixed $value
434 function notemptyfield($value, $name) {
435 return !empty($value);
439 * Just in case a field needs to print something before the whole form
441 function print_before_form() {
445 * Just in case a field needs to print something after the whole form
447 function print_after_form() {
452 * Returns the sortable field for the content. By default, it's just content
453 * but for some plugins, it could be content 1 - content4
457 function get_sort_field() {
462 * Returns the SQL needed to refer to the column. Some fields may need to CAST() etc.
464 * @param string $fieldname
465 * @return string $fieldname
467 function get_sort_sql($fieldname) {
472 * Returns the name/type of the field
477 return get_string('name'.$this->type
, 'data');
481 * Prints the respective type icon
489 $params = array('d'=>$this->data
->id
, 'fid'=>$this->field
->id
, 'mode'=>'display', 'sesskey'=>sesskey());
490 $link = new moodle_url('/mod/data/field.php', $params);
491 $str = '<a href="'.$link->out().'">';
492 $str .= '<img src="'.$OUTPUT->pix_url('field/'.$this->type
, 'data') . '" ';
493 $str .= 'height="'.$this->iconheight
.'" width="'.$this->iconwidth
.'" alt="'.$this->type
.'" title="'.$this->type
.'" /></a>';
498 * Per default, it is assumed that fields support text exporting.
499 * Override this (return false) on fields not supporting text exporting.
503 function text_export_supported() {
508 * Per default, return the record's text value only from the "content" field.
509 * Override this in fields class if necesarry.
511 * @param string $record
514 function export_text_value($record) {
515 if ($this->text_export_supported()) {
516 return $record->content
;
521 * @param string $relativepath
524 function file_ok($relativepath) {
531 * Given a template and a dataid, generate a default case template
534 * @param object $data
535 * @param string template [addtemplate, singletemplate, listtempalte, rsstemplate]
536 * @param int $recordid
538 * @param bool $update
539 * @return bool|string
541 function data_generate_default_template(&$data, $template, $recordid=0, $form=false, $update=true) {
544 if (!$data && !$template) {
547 if ($template == 'csstemplate' or $template == 'jstemplate' ) {
551 // get all the fields for that database
552 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id
), 'id')) {
554 $table = new html_table();
555 $table->attributes
['class'] = 'mod-data-default-template';
556 $table->colclasses
= array('template-field', 'template-token');
557 $table->data
= array();
558 foreach ($fields as $field) {
559 if ($form) { // Print forms instead of data
560 $fieldobj = data_get_field($field, $data);
561 $token = $fieldobj->display_add_field($recordid, null);
562 } else { // Just print the tag
563 $token = '[['.$field->name
.']]';
565 $table->data
[] = array(
570 if ($template == 'listtemplate') {
571 $cell = new html_table_cell('##edit## ##more## ##delete## ##approve## ##disapprove## ##export##');
573 $cell->attributes
['class'] = 'controls';
574 $table->data
[] = new html_table_row(array($cell));
575 } else if ($template == 'singletemplate') {
576 $cell = new html_table_cell('##edit## ##delete## ##approve## ##disapprove## ##export##');
578 $cell->attributes
['class'] = 'controls';
579 $table->data
[] = new html_table_row(array($cell));
580 } else if ($template == 'asearchtemplate') {
581 $row = new html_table_row(array(get_string('authorfirstname', 'data').': ', '##firstname##'));
582 $row->attributes
['class'] = 'searchcontrols';
583 $table->data
[] = $row;
584 $row = new html_table_row(array(get_string('authorlastname', 'data').': ', '##lastname##'));
585 $row->attributes
['class'] = 'searchcontrols';
586 $table->data
[] = $row;
590 if ($template == 'listtemplate'){
591 $str .= '##delcheck##';
592 $str .= html_writer
::empty_tag('br');
595 $str .= html_writer
::start_tag('div', array('class' => 'defaulttemplate'));
596 $str .= html_writer
::table($table);
597 $str .= html_writer
::end_tag('div');
598 if ($template == 'listtemplate'){
599 $str .= html_writer
::empty_tag('hr');
603 $newdata = new stdClass();
604 $newdata->id
= $data->id
;
605 $newdata->{$template} = $str;
606 $DB->update_record('data', $newdata);
607 $data->{$template} = $str;
616 * Search for a field name and replaces it with another one in all the
617 * form templates. Set $newfieldname as '' if you want to delete the
618 * field from the form.
621 * @param object $data
622 * @param string $searchfieldname
623 * @param string $newfieldname
626 function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
629 if (!empty($newfieldname)) {
640 $newdata = new stdClass();
641 $newdata->id
= $data->id
;
642 $newdata->singletemplate
= str_ireplace('[['.$searchfieldname.']]',
643 $prestring.$newfieldname.$poststring, $data->singletemplate
);
645 $newdata->listtemplate
= str_ireplace('[['.$searchfieldname.']]',
646 $prestring.$newfieldname.$poststring, $data->listtemplate
);
648 $newdata->addtemplate
= str_ireplace('[['.$searchfieldname.']]',
649 $prestring.$newfieldname.$poststring, $data->addtemplate
);
651 $newdata->addtemplate
= str_ireplace('[['.$searchfieldname.'#id]]',
652 $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate
);
654 $newdata->rsstemplate
= str_ireplace('[['.$searchfieldname.']]',
655 $prestring.$newfieldname.$poststring, $data->rsstemplate
);
657 return $DB->update_record('data', $newdata);
662 * Appends a new field at the end of the form template.
665 * @param object $data
666 * @param string $newfieldname
668 function data_append_new_field_to_templates($data, $newfieldname) {
671 $newdata = new stdClass();
672 $newdata->id
= $data->id
;
675 if (!empty($data->singletemplate
)) {
676 $newdata->singletemplate
= $data->singletemplate
.' [[' . $newfieldname .']]';
679 if (!empty($data->addtemplate
)) {
680 $newdata->addtemplate
= $data->addtemplate
.' [[' . $newfieldname . ']]';
683 if (!empty($data->rsstemplate
)) {
684 $newdata->rsstemplate
= $data->singletemplate
.' [[' . $newfieldname . ']]';
688 $DB->update_record('data', $newdata);
695 * this function creates an instance of the particular subfield class
698 * @param string $name
699 * @param object $data
700 * @return object|bool
702 function data_get_field_from_name($name, $data){
705 $field = $DB->get_record('data_fields', array('name'=>$name, 'dataid'=>$data->id
));
708 return data_get_field($field, $data);
716 * this function creates an instance of the particular subfield class
719 * @param int $fieldid
720 * @param object $data
721 * @return bool|object
723 function data_get_field_from_id($fieldid, $data){
726 $field = $DB->get_record('data_fields', array('id'=>$fieldid, 'dataid'=>$data->id
));
729 return data_get_field($field, $data);
737 * this function creates an instance of the particular subfield class
740 * @param string $type
741 * @param object $data
744 function data_get_field_new($type, $data) {
747 require_once($CFG->dirroot
.'/mod/data/field/'.$type.'/field.class.php');
748 $newfield = 'data_field_'.$type;
749 $newfield = new $newfield(0, $data);
754 * returns a subclass field object given a record of the field, used to
755 * invoke plugin methods
756 * input: $param $field - record from db
759 * @param object $field
760 * @param object $data
764 function data_get_field($field, $data, $cm=null) {
768 require_once('field/'.$field->type
.'/field.class.php');
769 $newfield = 'data_field_'.$field->type
;
770 $newfield = new $newfield($field, $data, $cm);
777 * Given record object (or id), returns true if the record belongs to the current user
781 * @param mixed $record record object or id
784 function data_isowner($record) {
787 if (!isloggedin()) { // perf shortcut
791 if (!is_object($record)) {
792 if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
797 return ($record->userid
== $USER->id
);
801 * has a user reached the max number of entries?
803 * @param object $data
806 function data_atmaxentries($data){
807 if (!$data->maxentries
){
811 return (data_numentries($data) >= $data->maxentries
);
816 * returns the number of entries already made by this user
820 * @param object $data
823 function data_numentries($data){
825 $sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
826 return $DB->count_records_sql($sql, array($data->id
, $USER->id
));
830 * function that takes in a dataid and adds a record
831 * this is used everytime an add template is submitted
835 * @param object $data
836 * @param int $groupid
839 function data_add_record($data, $groupid=0){
842 $cm = get_coursemodule_from_instance('data', $data->id
);
843 $context = context_module
::instance($cm->id
);
845 $record = new stdClass();
846 $record->userid
= $USER->id
;
847 $record->dataid
= $data->id
;
848 $record->groupid
= $groupid;
849 $record->timecreated
= $record->timemodified
= time();
850 if (has_capability('mod/data:approve', $context)) {
851 $record->approved
= 1;
853 $record->approved
= 0;
855 $record->id
= $DB->insert_record('data_records', $record);
857 // Trigger an event for creating this record.
858 $event = \mod_data\event\record_created
::create(array(
859 'objectid' => $record->id
,
860 'context' => $context,
862 'dataid' => $data->id
871 * check the multple existence any tag in a template
873 * check to see if there are 2 or more of the same tag being used.
876 * @param int $dataid,
877 * @param string $template
880 function data_tags_check($dataid, $template) {
883 // first get all the possible tags
884 $fields = $DB->get_records('data_fields', array('dataid'=>$dataid));
885 // then we generate strings to replace
886 $tagsok = true; // let's be optimistic
887 foreach ($fields as $field){
888 $pattern="/\[\[" . preg_quote($field->name
, '/') . "\]\]/i";
889 if (preg_match_all($pattern, $template, $dummy)>1){
891 echo $OUTPUT->notification('[['.$field->name
.']] - '.get_string('multipletags','data'));
899 * Adds an instance of a data
901 * @param stdClass $data
902 * @param mod_data_mod_form $mform
903 * @return int intance id
905 function data_add_instance($data, $mform = null) {
908 if (empty($data->assessed
)) {
912 $data->timemodified
= time();
914 $data->id
= $DB->insert_record('data', $data);
916 data_grade_item_update($data);
922 * updates an instance of a data
925 * @param object $data
928 function data_update_instance($data) {
931 $data->timemodified
= time();
932 $data->id
= $data->instance
;
934 if (empty($data->assessed
)) {
938 if (empty($data->ratingtime
) or empty($data->assessed
)) {
939 $data->assesstimestart
= 0;
940 $data->assesstimefinish
= 0;
943 if (empty($data->notification
)) {
944 $data->notification
= 0;
947 $DB->update_record('data', $data);
949 data_grade_item_update($data);
956 * deletes an instance of a data
962 function data_delete_instance($id) { // takes the dataid
965 if (!$data = $DB->get_record('data', array('id'=>$id))) {
969 $cm = get_coursemodule_from_instance('data', $data->id
);
970 $context = context_module
::instance($cm->id
);
972 /// Delete all the associated information
975 $fs = get_file_storage();
976 $fs->delete_area_files($context->id
, 'mod_data');
978 // get all the records in this data
980 FROM {data_records} r
983 $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
985 // delete all the records and fields
986 $DB->delete_records('data_records', array('dataid'=>$id));
987 $DB->delete_records('data_fields', array('dataid'=>$id));
989 // Delete the instance itself
990 $result = $DB->delete_records('data', array('id'=>$id));
993 data_grade_item_delete($data);
999 * returns a summary of data activity of this user
1002 * @param object $course
1003 * @param object $user
1004 * @param object $mod
1005 * @param object $data
1006 * @return object|null
1008 function data_user_outline($course, $user, $mod, $data) {
1010 require_once("$CFG->libdir/gradelib.php");
1012 $grades = grade_get_grades($course->id
, 'mod', 'data', $data->id
, $user->id
);
1013 if (empty($grades->items
[0]->grades
)) {
1016 $grade = reset($grades->items
[0]->grades
);
1020 if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id
, 'userid'=>$user->id
))) {
1021 $result = new stdClass();
1022 $result->info
= get_string('numrecords', 'data', $countrecords);
1023 $lastrecord = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
1024 WHERE dataid = ? AND userid = ?
1025 ORDER BY timemodified DESC', array($data->id
, $user->id
), true);
1026 $result->time
= $lastrecord->timemodified
;
1028 $result->info
.= ', ' . get_string('grade') . ': ' . $grade->str_long_grade
;
1031 } else if ($grade) {
1032 $result = new stdClass();
1033 $result->info
= get_string('grade') . ': ' . $grade->str_long_grade
;
1035 //datesubmitted == time created. dategraded == time modified or time overridden
1036 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1037 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1038 if ($grade->usermodified
== $user->id ||
empty($grade->datesubmitted
)) {
1039 $result->time
= $grade->dategraded
;
1041 $result->time
= $grade->datesubmitted
;
1050 * Prints all the records uploaded by this user
1053 * @param object $course
1054 * @param object $user
1055 * @param object $mod
1056 * @param object $data
1058 function data_user_complete($course, $user, $mod, $data) {
1059 global $DB, $CFG, $OUTPUT;
1060 require_once("$CFG->libdir/gradelib.php");
1062 $grades = grade_get_grades($course->id
, 'mod', 'data', $data->id
, $user->id
);
1063 if (!empty($grades->items
[0]->grades
)) {
1064 $grade = reset($grades->items
[0]->grades
);
1065 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade
);
1066 if ($grade->str_feedback
) {
1067 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
1071 if ($records = $DB->get_records('data_records', array('dataid'=>$data->id
,'userid'=>$user->id
), 'timemodified DESC')) {
1072 data_print_template('singletemplate', $records, $data);
1077 * Return grade for given user or all users.
1080 * @param object $data
1081 * @param int $userid optional user id, 0 means all users
1082 * @return array array of grades, false if none
1084 function data_get_user_grades($data, $userid=0) {
1087 require_once($CFG->dirroot
.'/rating/lib.php');
1089 $ratingoptions = new stdClass
;
1090 $ratingoptions->component
= 'mod_data';
1091 $ratingoptions->ratingarea
= 'entry';
1092 $ratingoptions->modulename
= 'data';
1093 $ratingoptions->moduleid
= $data->id
;
1095 $ratingoptions->userid
= $userid;
1096 $ratingoptions->aggregationmethod
= $data->assessed
;
1097 $ratingoptions->scaleid
= $data->scale
;
1098 $ratingoptions->itemtable
= 'data_records';
1099 $ratingoptions->itemtableusercolumn
= 'userid';
1101 $rm = new rating_manager();
1102 return $rm->get_user_grades($ratingoptions);
1106 * Update activity grades
1109 * @param object $data
1110 * @param int $userid specific user only, 0 means all
1111 * @param bool $nullifnone
1113 function data_update_grades($data, $userid=0, $nullifnone=true) {
1115 require_once($CFG->libdir
.'/gradelib.php');
1117 if (!$data->assessed
) {
1118 data_grade_item_update($data);
1120 } else if ($grades = data_get_user_grades($data, $userid)) {
1121 data_grade_item_update($data, $grades);
1123 } else if ($userid and $nullifnone) {
1124 $grade = new stdClass();
1125 $grade->userid
= $userid;
1126 $grade->rawgrade
= NULL;
1127 data_grade_item_update($data, $grade);
1130 data_grade_item_update($data);
1135 * Update/create grade item for given data
1138 * @param stdClass $data A database instance with extra cmidnumber property
1139 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1140 * @return object grade_item
1142 function data_grade_item_update($data, $grades=NULL) {
1144 require_once($CFG->libdir
.'/gradelib.php');
1146 $params = array('itemname'=>$data->name
, 'idnumber'=>$data->cmidnumber
);
1148 if (!$data->assessed
or $data->scale
== 0) {
1149 $params['gradetype'] = GRADE_TYPE_NONE
;
1151 } else if ($data->scale
> 0) {
1152 $params['gradetype'] = GRADE_TYPE_VALUE
;
1153 $params['grademax'] = $data->scale
;
1154 $params['grademin'] = 0;
1156 } else if ($data->scale
< 0) {
1157 $params['gradetype'] = GRADE_TYPE_SCALE
;
1158 $params['scaleid'] = -$data->scale
;
1161 if ($grades === 'reset') {
1162 $params['reset'] = true;
1166 return grade_update('mod/data', $data->course
, 'mod', 'data', $data->id
, 0, $grades, $params);
1170 * Delete grade item for given data
1173 * @param object $data object
1174 * @return object grade_item
1176 function data_grade_item_delete($data) {
1178 require_once($CFG->libdir
.'/gradelib.php');
1180 return grade_update('mod/data', $data->course
, 'mod', 'data', $data->id
, 0, NULL, array('deleted'=>1));
1185 * takes a list of records, the current data, a search string,
1186 * and mode to display prints the translated template
1190 * @param string $template
1191 * @param array $records
1192 * @param object $data
1193 * @param string $search
1195 * @param bool $return
1196 * @param object $jumpurl a moodle_url by which to jump back to the record list (can be null)
1199 function data_print_template($template, $records, $data, $search='', $page=0, $return=false, moodle_url
$jumpurl=null) {
1200 global $CFG, $DB, $OUTPUT;
1202 $cm = get_coursemodule_from_instance('data', $data->id
);
1203 $context = context_module
::instance($cm->id
);
1205 static $fields = NULL;
1207 static $dataid = NULL;
1209 if (empty($dataid)) {
1210 $dataid = $data->id
;
1211 } else if ($dataid != $data->id
) {
1215 if (empty($fields)) {
1216 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id
));
1217 foreach ($fieldrecords as $fieldrecord) {
1218 $fields[]= data_get_field($fieldrecord, $data);
1220 $isteacher = has_capability('mod/data:managetemplates', $context);
1223 if (empty($records)) {
1228 $jumpurl = new moodle_url('/mod/data/view.php', array('d' => $data->id
));
1230 $jumpurl = new moodle_url($jumpurl, array('page' => $page, 'sesskey' => sesskey()));
1232 // Check whether this activity is read-only at present
1233 $readonly = data_in_readonly_period($data);
1235 foreach ($records as $record) { // Might be just one for the single template
1238 $patterns = array();
1239 $replacement = array();
1241 // Then we generate strings to replace for normal tags
1242 foreach ($fields as $field) {
1243 $patterns[]='[['.$field->field
->name
.']]';
1244 $replacement[] = highlight($search, $field->display_browse_field($record->id
, $template));
1247 $canmanageentries = has_capability('mod/data:manageentries', $context);
1249 // Replacing special tags (##Edit##, ##Delete##, ##More##)
1250 $patterns[]='##edit##';
1251 $patterns[]='##delete##';
1252 if ($canmanageentries ||
(!$readonly && data_isowner($record->id
))) {
1253 $replacement[] = '<a href="'.$CFG->wwwroot
.'/mod/data/edit.php?d='
1254 .$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>';
1255 $replacement[] = '<a href="'.$CFG->wwwroot
.'/mod/data/view.php?d='
1256 .$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>';
1258 $replacement[] = '';
1259 $replacement[] = '';
1262 $moreurl = $CFG->wwwroot
. '/mod/data/view.php?d=' . $data->id
. '&rid=' . $record->id
;
1264 $moreurl .= '&filter=1';
1266 $patterns[]='##more##';
1267 $replacement[] = '<a href="'.$moreurl.'"><img src="'.$OUTPUT->pix_url('t/preview').
1268 '" class="iconsmall" alt="'.get_string('more', 'data').'" title="'.get_string('more', 'data').
1271 $patterns[]='##moreurl##';
1272 $replacement[] = $moreurl;
1274 $patterns[]='##delcheck##';
1275 if ($canmanageentries) {
1276 $replacement[] = html_writer
::checkbox('delcheck[]', $record->id
, false, '', array('class' => 'recordcheckbox'));
1278 $replacement[] = '';
1281 $patterns[]='##user##';
1282 $replacement[] = '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.$record->userid
.
1283 '&course='.$data->course
.'">'.fullname($record).'</a>';
1285 $patterns[] = '##userpicture##';
1286 $ruser = user_picture
::unalias($record, null, 'userid');
1287 $replacement[] = $OUTPUT->user_picture($ruser, array('courseid' => $data->course
));
1289 $patterns[]='##export##';
1291 if (!empty($CFG->enableportfolios
) && ($template == 'singletemplate' ||
$template == 'listtemplate')
1292 && ((has_capability('mod/data:exportentry', $context)
1293 ||
(data_isowner($record->id
) && has_capability('mod/data:exportownentry', $context))))) {
1294 require_once($CFG->libdir
. '/portfoliolib.php');
1295 $button = new portfolio_add_button();
1296 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id
, 'recordid' => $record->id
), 'mod_data');
1297 list($formats, $files) = data_portfolio_caller
::formats($fields, $record);
1298 $button->set_formats($formats);
1299 $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
1301 $replacement[] = '';
1304 $patterns[] = '##timeadded##';
1305 $replacement[] = userdate($record->timecreated
);
1307 $patterns[] = '##timemodified##';
1308 $replacement [] = userdate($record->timemodified
);
1310 $patterns[]='##approve##';
1311 if (has_capability('mod/data:approve', $context) && ($data->approval
) && (!$record->approved
)) {
1312 $approveurl = new moodle_url($jumpurl, array('approve' => $record->id
));
1313 $approveicon = new pix_icon('t/approve', get_string('approve', 'data'), '', array('class' => 'iconsmall'));
1314 $replacement[] = html_writer
::tag('span', $OUTPUT->action_icon($approveurl, $approveicon),
1315 array('class' => 'approve'));
1317 $replacement[] = '';
1320 $patterns[]='##disapprove##';
1321 if (has_capability('mod/data:approve', $context) && ($data->approval
) && ($record->approved
)) {
1322 $disapproveurl = new moodle_url($jumpurl, array('disapprove' => $record->id
));
1323 $disapproveicon = new pix_icon('t/block', get_string('disapprove', 'data'), '', array('class' => 'iconsmall'));
1324 $replacement[] = html_writer
::tag('span', $OUTPUT->action_icon($disapproveurl, $disapproveicon),
1325 array('class' => 'disapprove'));
1327 $replacement[] = '';
1330 $patterns[]='##comments##';
1331 if (($template == 'listtemplate') && ($data->comments
)) {
1333 if (!empty($CFG->usecomments
)) {
1334 require_once($CFG->dirroot
. '/comment/lib.php');
1335 list($context, $course, $cm) = get_context_info_array($context->id
);
1336 $cmt = new stdClass();
1337 $cmt->context
= $context;
1338 $cmt->course
= $course;
1340 $cmt->area
= 'database_entry';
1341 $cmt->itemid
= $record->id
;
1342 $cmt->showcount
= true;
1343 $cmt->component
= 'mod_data';
1344 $comment = new comment($cmt);
1345 $replacement[] = $comment->output(true);
1348 $replacement[] = '';
1351 // actual replacement of the tags
1352 $newtext = str_ireplace($patterns, $replacement, $data->{$template});
1354 // no more html formatting and filtering - see MDL-6635
1360 // hack alert - return is always false in singletemplate anyway ;-)
1361 /**********************************
1362 * Printing Ratings Form *
1363 *********************************/
1364 if ($template == 'singletemplate') { //prints ratings options
1365 data_print_ratings($data, $record);
1368 /**********************************
1369 * Printing Comments Form *
1370 *********************************/
1371 if (($template == 'singletemplate') && ($data->comments
)) {
1372 if (!empty($CFG->usecomments
)) {
1373 require_once($CFG->dirroot
. '/comment/lib.php');
1374 list($context, $course, $cm) = get_context_info_array($context->id
);
1375 $cmt = new stdClass();
1376 $cmt->context
= $context;
1377 $cmt->course
= $course;
1379 $cmt->area
= 'database_entry';
1380 $cmt->itemid
= $record->id
;
1381 $cmt->showcount
= true;
1382 $cmt->component
= 'mod_data';
1383 $comment = new comment($cmt);
1384 $comment->output(false);
1392 * Return rating related permissions
1394 * @param string $contextid the context id
1395 * @param string $component the component to get rating permissions for
1396 * @param string $ratingarea the rating area to get permissions for
1397 * @return array an associative array of the user's rating permissions
1399 function data_rating_permissions($contextid, $component, $ratingarea) {
1400 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1401 if ($component != 'mod_data' ||
$ratingarea != 'entry') {
1405 'view' => has_capability('mod/data:viewrating',$context),
1406 'viewany' => has_capability('mod/data:viewanyrating',$context),
1407 'viewall' => has_capability('mod/data:viewallratings',$context),
1408 'rate' => has_capability('mod/data:rate',$context)
1413 * Validates a submitted rating
1414 * @param array $params submitted data
1415 * context => object the context in which the rated items exists [required]
1416 * itemid => int the ID of the object being rated
1417 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1418 * rating => int the submitted rating
1419 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1420 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
1421 * @return boolean true if the rating is valid. Will throw rating_exception if not
1423 function data_rating_validate($params) {
1426 // Check the component is mod_data
1427 if ($params['component'] != 'mod_data') {
1428 throw new rating_exception('invalidcomponent');
1431 // Check the ratingarea is entry (the only rating area in data module)
1432 if ($params['ratingarea'] != 'entry') {
1433 throw new rating_exception('invalidratingarea');
1436 // Check the rateduserid is not the current user .. you can't rate your own entries
1437 if ($params['rateduserid'] == $USER->id
) {
1438 throw new rating_exception('nopermissiontorate');
1441 $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
1442 FROM {data_records} r
1443 JOIN {data} d ON r.dataid = d.id
1444 WHERE r.id = :itemid";
1445 $dataparams = array('itemid'=>$params['itemid']);
1446 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1447 //item doesn't exist
1448 throw new rating_exception('invaliditemid');
1451 if ($info->scale
!= $params['scaleid']) {
1452 //the scale being submitted doesnt match the one in the database
1453 throw new rating_exception('invalidscaleid');
1456 //check that the submitted rating is valid for the scale
1459 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING
) {
1460 throw new rating_exception('invalidnum');
1464 if ($info->scale
< 0) {
1465 //its a custom scale
1466 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale
));
1468 $scalearray = explode(',', $scalerecord->scale
);
1469 if ($params['rating'] > count($scalearray)) {
1470 throw new rating_exception('invalidnum');
1473 throw new rating_exception('invalidscaleid');
1475 } else if ($params['rating'] > $info->scale
) {
1476 //if its numeric and submitted rating is above maximum
1477 throw new rating_exception('invalidnum');
1480 if ($info->approval
&& !$info->approved
) {
1481 //database requires approval but this item isnt approved
1482 throw new rating_exception('nopermissiontorate');
1485 // check the item we're rating was created in the assessable time window
1486 if (!empty($info->assesstimestart
) && !empty($info->assesstimefinish
)) {
1487 if ($info->timecreated
< $info->assesstimestart ||
$info->timecreated
> $info->assesstimefinish
) {
1488 throw new rating_exception('notavailable');
1492 $course = $DB->get_record('course', array('id'=>$info->course
), '*', MUST_EXIST
);
1493 $cm = get_coursemodule_from_instance('data', $info->dataid
, $course->id
, false, MUST_EXIST
);
1494 $context = context_module
::instance($cm->id
);
1496 // if the supplied context doesnt match the item's context
1497 if ($context->id
!= $params['context']->id
) {
1498 throw new rating_exception('invalidcontext');
1501 // Make sure groups allow this user to see the item they're rating
1502 $groupid = $info->groupid
;
1503 if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
1504 if (!groups_group_exists($groupid)) { // Can't find group
1505 throw new rating_exception('cannotfindgroup');//something is wrong
1508 if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1509 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
1510 throw new rating_exception('notmemberofgroup');
1519 * function that takes in the current data, number of items per page,
1520 * a search string and prints a preference box in view.php
1522 * This preference box prints a searchable advanced search template if
1523 * a) A template is defined
1524 * b) The advanced search checkbox is checked.
1528 * @param object $data
1529 * @param int $perpage
1530 * @param string $search
1531 * @param string $sort
1532 * @param string $order
1533 * @param array $search_array
1534 * @param int $advanced
1535 * @param string $mode
1538 function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
1539 global $CFG, $DB, $PAGE, $OUTPUT;
1541 $cm = get_coursemodule_from_instance('data', $data->id
);
1542 $context = context_module
::instance($cm->id
);
1543 echo '<br /><div class="datapreferences">';
1544 echo '<form id="options" action="view.php" method="get">';
1546 echo '<input type="hidden" name="d" value="'.$data->id
.'" />';
1547 if ($mode =='asearch') {
1549 echo '<input type="hidden" name="mode" value="list" />';
1551 echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
1552 $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
1553 20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
1554 echo html_writer
::select($pagesizes, 'perpage', $perpage, false, array('id'=>'pref_perpage'));
1557 $regsearchclass = 'search_none';
1558 $advancedsearchclass = 'search_inline';
1560 $regsearchclass = 'search_inline';
1561 $advancedsearchclass = 'search_none';
1563 echo '<div id="reg_search" class="' . $regsearchclass . '" > ';
1564 echo '<label for="pref_search">'.get_string('search').'</label> <input type="text" size="16" name="search" id= "pref_search" value="'.s($search).'" /></div>';
1565 echo ' <label for="pref_sortby">'.get_string('sortby').'</label> ';
1566 // foreach field, print the option
1567 echo '<select name="sort" id="pref_sortby">';
1568 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id
), 'name')) {
1569 echo '<optgroup label="'.get_string('fields', 'data').'">';
1570 foreach ($fields as $field) {
1571 if ($field->id
== $sort) {
1572 echo '<option value="'.$field->id
.'" selected="selected">'.$field->name
.'</option>';
1574 echo '<option value="'.$field->id
.'">'.$field->name
.'</option>';
1580 $options[DATA_TIMEADDED
] = get_string('timeadded', 'data');
1581 $options[DATA_TIMEMODIFIED
] = get_string('timemodified', 'data');
1582 $options[DATA_FIRSTNAME
] = get_string('authorfirstname', 'data');
1583 $options[DATA_LASTNAME
] = get_string('authorlastname', 'data');
1584 if ($data->approval
and has_capability('mod/data:approve', $context)) {
1585 $options[DATA_APPROVED
] = get_string('approved', 'data');
1587 echo '<optgroup label="'.get_string('other', 'data').'">';
1588 foreach ($options as $key => $name) {
1589 if ($key == $sort) {
1590 echo '<option value="'.$key.'" selected="selected">'.$name.'</option>';
1592 echo '<option value="'.$key.'">'.$name.'</option>';
1597 echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
1598 echo '<select id="pref_order" name="order">';
1599 if ($order == 'ASC') {
1600 echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
1602 echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1604 if ($order == 'DESC') {
1605 echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
1607 echo '<option value="DESC">'.get_string('descending','data').'</option>';
1612 $checked = ' checked="checked" ';
1617 $PAGE->requires
->js('/mod/data/data.js');
1618 echo ' <input type="hidden" name="advanced" value="0" />';
1619 echo ' <input type="hidden" name="filter" value="1" />';
1620 echo ' <input type="checkbox" id="advancedcheckbox" name="advanced" value="1" '.$checked.' onchange="showHideAdvSearch(this.checked);" /><label for="advancedcheckbox">'.get_string('advancedsearch', 'data').'</label>';
1621 echo ' <input type="submit" value="'.get_string('savesettings','data').'" />';
1624 echo '<div class="' . $advancedsearchclass . '" id="data_adv_form">';
1625 echo '<table class="boxaligncenter">';
1627 // print ASC or DESC
1628 echo '<tr><td colspan="2"> </td></tr>';
1631 // Determine if we are printing all fields for advanced search, or the template for advanced search
1632 // If a template is not defined, use the deafault template and display all fields.
1633 if(empty($data->asearchtemplate
)) {
1634 data_generate_default_template($data, 'asearchtemplate');
1637 static $fields = NULL;
1639 static $dataid = NULL;
1641 if (empty($dataid)) {
1642 $dataid = $data->id
;
1643 } else if ($dataid != $data->id
) {
1647 if (empty($fields)) {
1648 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id
));
1649 foreach ($fieldrecords as $fieldrecord) {
1650 $fields[]= data_get_field($fieldrecord, $data);
1653 $isteacher = has_capability('mod/data:managetemplates', $context);
1657 $patterns = array();
1658 $replacement = array();
1660 // Then we generate strings to replace for normal tags
1661 foreach ($fields as $field) {
1662 $fieldname = $field->field
->name
;
1663 $fieldname = preg_quote($fieldname, '/');
1664 $patterns[] = "/\[\[$fieldname\]\]/i";
1665 $searchfield = data_get_field_from_id($field->field
->id
, $data);
1666 if (!empty($search_array[$field->field
->id
]->data
)) {
1667 $replacement[] = $searchfield->display_search_field($search_array[$field->field
->id
]->data
);
1669 $replacement[] = $searchfield->display_search_field();
1672 $fn = !empty($search_array[DATA_FIRSTNAME
]->data
) ?
$search_array[DATA_FIRSTNAME
]->data
: '';
1673 $ln = !empty($search_array[DATA_LASTNAME
]->data
) ?
$search_array[DATA_LASTNAME
]->data
: '';
1674 $patterns[] = '/##firstname##/';
1675 $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.'" />';
1676 $patterns[] = '/##lastname##/';
1677 $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.'" />';
1679 // actual replacement of the tags
1680 $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate
);
1682 $options = new stdClass();
1683 $options->para
=false;
1684 $options->noclean
=true;
1686 echo format_text($newtext, FORMAT_HTML
, $options);
1689 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>';
1700 * @param object $data
1701 * @param object $record
1702 * @return void Output echo'd
1704 function data_print_ratings($data, $record) {
1706 if (!empty($record->rating
)){
1707 echo $OUTPUT->render($record->rating
);
1712 * List the actions that correspond to a view of this module.
1713 * This is used by the participation report.
1715 * Note: This is not used by new logging system. Event with
1716 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1717 * be considered as view action.
1721 function data_get_view_actions() {
1722 return array('view');
1726 * List the actions that correspond to a post of this module.
1727 * This is used by the participation report.
1729 * Note: This is not used by new logging system. Event with
1730 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1731 * will be considered as post action.
1735 function data_get_post_actions() {
1736 return array('add','update','record delete');
1740 * @param string $name
1741 * @param int $dataid
1742 * @param int $fieldid
1745 function data_fieldname_exists($name, $dataid, $fieldid = 0) {
1748 if (!is_numeric($name)) {
1749 $like = $DB->sql_like('df.name', ':name', false);
1751 $like = "df.name = :name";
1753 $params = array('name'=>$name);
1755 $params['dataid'] = $dataid;
1756 $params['fieldid1'] = $fieldid;
1757 $params['fieldid2'] = $fieldid;
1758 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1759 WHERE $like AND df.dataid = :dataid
1760 AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
1762 $params['dataid'] = $dataid;
1763 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1764 WHERE $like AND df.dataid = :dataid", $params);
1769 * @param array $fieldinput
1771 function data_convert_arrays_to_strings(&$fieldinput) {
1772 foreach ($fieldinput as $key => $val) {
1773 if (is_array($val)) {
1775 foreach ($val as $inner) {
1776 $str .= $inner . ',';
1778 $str = substr($str, 0, -1);
1780 $fieldinput->$key = $str;
1787 * Converts a database (module instance) to use the Roles System
1791 * @uses CONTEXT_MODULE
1794 * @param object $data a data object with the same attributes as a record
1795 * from the data database table
1796 * @param int $datamodid the id of the data module, from the modules table
1797 * @param array $teacherroles array of roles that have archetype teacher
1798 * @param array $studentroles array of roles that have archetype student
1799 * @param array $guestroles array of roles that have archetype guest
1800 * @param int $cmid the course_module id for this data instance
1801 * @return boolean data module was converted or not
1803 function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
1804 global $CFG, $DB, $OUTPUT;
1806 if (!isset($data->participants
) && !isset($data->assesspublic
)
1807 && !isset($data->groupmode
)) {
1808 // We assume that this database has already been converted to use the
1809 // Roles System. above fields get dropped the data module has been
1810 // upgraded to use Roles.
1815 // We were not given the course_module id. Try to find it.
1816 if (!$cm = get_coursemodule_from_instance('data', $data->id
)) {
1817 echo $OUTPUT->notification('Could not get the course module for the data');
1823 $context = context_module
::instance($cmid);
1826 // $data->participants:
1827 // 1 - Only teachers can add entries
1828 // 3 - Teachers and students can add entries
1829 switch ($data->participants
) {
1831 foreach ($studentroles as $studentrole) {
1832 assign_capability('mod/data:writeentry', CAP_PREVENT
, $studentrole->id
, $context->id
);
1834 foreach ($teacherroles as $teacherrole) {
1835 assign_capability('mod/data:writeentry', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1839 foreach ($studentroles as $studentrole) {
1840 assign_capability('mod/data:writeentry', CAP_ALLOW
, $studentrole->id
, $context->id
);
1842 foreach ($teacherroles as $teacherrole) {
1843 assign_capability('mod/data:writeentry', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1849 // 2 - Only teachers can rate posts
1850 // 1 - Everyone can rate posts
1851 // 0 - No one can rate posts
1852 switch ($data->assessed
) {
1854 foreach ($studentroles as $studentrole) {
1855 assign_capability('mod/data:rate', CAP_PREVENT
, $studentrole->id
, $context->id
);
1857 foreach ($teacherroles as $teacherrole) {
1858 assign_capability('mod/data:rate', CAP_PREVENT
, $teacherrole->id
, $context->id
);
1862 foreach ($studentroles as $studentrole) {
1863 assign_capability('mod/data:rate', CAP_ALLOW
, $studentrole->id
, $context->id
);
1865 foreach ($teacherroles as $teacherrole) {
1866 assign_capability('mod/data:rate', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1870 foreach ($studentroles as $studentrole) {
1871 assign_capability('mod/data:rate', CAP_PREVENT
, $studentrole->id
, $context->id
);
1873 foreach ($teacherroles as $teacherrole) {
1874 assign_capability('mod/data:rate', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1879 // $data->assesspublic:
1880 // 0 - Students can only see their own ratings
1881 // 1 - Students can see everyone's ratings
1882 switch ($data->assesspublic
) {
1884 foreach ($studentroles as $studentrole) {
1885 assign_capability('mod/data:viewrating', CAP_PREVENT
, $studentrole->id
, $context->id
);
1887 foreach ($teacherroles as $teacherrole) {
1888 assign_capability('mod/data:viewrating', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1892 foreach ($studentroles as $studentrole) {
1893 assign_capability('mod/data:viewrating', CAP_ALLOW
, $studentrole->id
, $context->id
);
1895 foreach ($teacherroles as $teacherrole) {
1896 assign_capability('mod/data:viewrating', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1902 $cm = $DB->get_record('course_modules', array('id'=>$cmid));
1905 switch ($cm->groupmode
) {
1908 case SEPARATEGROUPS
:
1909 foreach ($studentroles as $studentrole) {
1910 assign_capability('moodle/site:accessallgroups', CAP_PREVENT
, $studentrole->id
, $context->id
);
1912 foreach ($teacherroles as $teacherrole) {
1913 assign_capability('moodle/site:accessallgroups', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1917 foreach ($studentroles as $studentrole) {
1918 assign_capability('moodle/site:accessallgroups', CAP_ALLOW
, $studentrole->id
, $context->id
);
1920 foreach ($teacherroles as $teacherrole) {
1921 assign_capability('moodle/site:accessallgroups', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1929 * Returns the best name to show for a preset
1931 * @param string $shortname
1932 * @param string $path
1935 function data_preset_name($shortname, $path) {
1937 // We are looking inside the preset itself as a first choice, but also in normal data directory
1938 $string = get_string('modulename', 'datapreset_'.$shortname);
1940 if (substr($string, 0, 1) == '[') {
1948 * Returns an array of all the available presets.
1952 function data_get_available_presets($context) {
1957 // First load the ratings sub plugins that exist within the modules preset dir
1958 if ($dirs = core_component
::get_plugin_list('datapreset')) {
1959 foreach ($dirs as $dir=>$fulldir) {
1960 if (is_directory_a_preset($fulldir)) {
1961 $preset = new stdClass();
1962 $preset->path
= $fulldir;
1963 $preset->userid
= 0;
1964 $preset->shortname
= $dir;
1965 $preset->name
= data_preset_name($dir, $fulldir);
1966 if (file_exists($fulldir.'/screenshot.jpg')) {
1967 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.jpg';
1968 } else if (file_exists($fulldir.'/screenshot.png')) {
1969 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.png';
1970 } else if (file_exists($fulldir.'/screenshot.gif')) {
1971 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.gif';
1973 $presets[] = $preset;
1977 // Now add to that the site presets that people have saved
1978 $presets = data_get_available_site_presets($context, $presets);
1983 * Gets an array of all of the presets that users have saved to the site.
1985 * @param stdClass $context The context that we are looking from.
1986 * @param array $presets
1987 * @return array An array of presets
1989 function data_get_available_site_presets($context, array $presets=array()) {
1992 $fs = get_file_storage();
1993 $files = $fs->get_area_files(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
);
1994 $canviewall = has_capability('mod/data:viewalluserpresets', $context);
1995 if (empty($files)) {
1998 foreach ($files as $file) {
1999 if (($file->is_directory() && $file->get_filepath()=='/') ||
!$file->is_directory() ||
(!$canviewall && $file->get_userid() != $USER->id
)) {
2002 $preset = new stdClass
;
2003 $preset->path
= $file->get_filepath();
2004 $preset->name
= trim($preset->path
, '/');
2005 $preset->shortname
= $preset->name
;
2006 $preset->userid
= $file->get_userid();
2007 $preset->id
= $file->get_id();
2008 $preset->storedfile
= $file;
2009 $presets[] = $preset;
2015 * Deletes a saved preset.
2017 * @param string $name
2020 function data_delete_site_preset($name) {
2021 $fs = get_file_storage();
2023 $files = $fs->get_directory_files(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
, 0, '/'.$name.'/');
2024 if (!empty($files)) {
2025 foreach ($files as $file) {
2030 $dir = $fs->get_file(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
, 0, '/'.$name.'/', '.');
2038 * Prints the heads for a page
2040 * @param stdClass $course
2041 * @param stdClass $cm
2042 * @param stdClass $data
2043 * @param string $currenttab
2045 function data_print_header($course, $cm, $data, $currenttab='') {
2047 global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
2049 $PAGE->set_title($data->name
);
2050 echo $OUTPUT->header();
2051 echo $OUTPUT->heading(format_string($data->name
), 2);
2052 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id
), 'generalbox', 'intro');
2054 // Groups needed for Add entry tab
2055 $currentgroup = groups_get_activity_group($cm);
2056 $groupmode = groups_get_activity_groupmode($cm);
2061 include('tabs.php');
2064 // Print any notices
2066 if (!empty($displaynoticegood)) {
2067 echo $OUTPUT->notification($displaynoticegood, 'notifysuccess'); // good (usually green)
2068 } else if (!empty($displaynoticebad)) {
2069 echo $OUTPUT->notification($displaynoticebad); // bad (usuually red)
2074 * Can user add more entries?
2076 * @param object $data
2077 * @param mixed $currentgroup
2078 * @param int $groupmode
2079 * @param stdClass $context
2082 function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
2085 if (empty($context)) {
2086 $cm = get_coursemodule_from_instance('data', $data->id
, 0, false, MUST_EXIST
);
2087 $context = context_module
::instance($cm->id
);
2090 if (has_capability('mod/data:manageentries', $context)) {
2091 // no entry limits apply if user can manage
2093 } else if (!has_capability('mod/data:writeentry', $context)) {
2096 } else if (data_atmaxentries($data)) {
2098 } else if (data_in_readonly_period($data)) {
2099 // Check whether we're in a read-only period
2103 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2107 if ($currentgroup) {
2108 return groups_is_member($currentgroup);
2110 //else it might be group 0 in visible mode
2111 if ($groupmode == VISIBLEGROUPS
){
2120 * Check whether the specified database activity is currently in a read-only period
2122 * @param object $data
2123 * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2125 function data_in_readonly_period($data) {
2127 if (!$data->timeviewfrom
&& !$data->timeviewto
) {
2129 } else if (($data->timeviewfrom
&& $now < $data->timeviewfrom
) ||
($data->timeviewto
&& $now > $data->timeviewto
)) {
2138 function is_directory_a_preset($directory) {
2139 $directory = rtrim($directory, '/\\') . '/';
2140 $status = file_exists($directory.'singletemplate.html') &&
2141 file_exists($directory.'listtemplate.html') &&
2142 file_exists($directory.'listtemplateheader.html') &&
2143 file_exists($directory.'listtemplatefooter.html') &&
2144 file_exists($directory.'addtemplate.html') &&
2145 file_exists($directory.'rsstemplate.html') &&
2146 file_exists($directory.'rsstitletemplate.html') &&
2147 file_exists($directory.'csstemplate.css') &&
2148 file_exists($directory.'jstemplate.js') &&
2149 file_exists($directory.'preset.xml');
2155 * Abstract class used for data preset importers
2157 abstract class data_preset_importer
{
2162 protected $directory;
2167 * @param stdClass $course
2168 * @param stdClass $cm
2169 * @param stdClass $module
2170 * @param string $directory
2172 public function __construct($course, $cm, $module, $directory) {
2173 $this->course
= $course;
2175 $this->module
= $module;
2176 $this->directory
= $directory;
2180 * Returns the name of the directory the preset is located in
2183 public function get_directory() {
2184 return basename($this->directory
);
2188 * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2189 * @param file_storage $filestorage. should be null if using a conventional directory
2190 * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2191 * @param string $dir the directory to look in. null if using the Moodle file storage
2192 * @param string $filename the name of the file we want
2193 * @return string the contents of the file or null if the file doesn't exist.
2195 public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2196 if(empty($filestorage) ||
empty($fileobj)) {
2197 if (substr($dir, -1)!='/') {
2200 if (file_exists($dir.$filename)) {
2201 return file_get_contents($dir.$filename);
2206 if ($filestorage->file_exists(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
, 0, $fileobj->get_filepath(), $filename)) {
2207 $file = $filestorage->get_file(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
, 0, $fileobj->get_filepath(), $filename);
2208 return $file->get_content();
2216 * Gets the preset settings
2217 * @global moodle_database $DB
2220 public function get_preset_settings() {
2223 $fs = $fileobj = null;
2224 if (!is_directory_a_preset($this->directory
)) {
2225 //maybe the user requested a preset stored in the Moodle file storage
2227 $fs = get_file_storage();
2228 $files = $fs->get_area_files(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
);
2230 //preset name to find will be the final element of the directory
2231 $explodeddirectory = explode('/', $this->directory
);
2232 $presettofind = end($explodeddirectory);
2234 //now go through the available files available and see if we can find it
2235 foreach ($files as $file) {
2236 if (($file->is_directory() && $file->get_filepath()=='/') ||
!$file->is_directory()) {
2239 $presetname = trim($file->get_filepath(), '/');
2240 if ($presetname==$presettofind) {
2241 $this->directory
= $presetname;
2246 if (empty($fileobj)) {
2247 print_error('invalidpreset', 'data', '', $this->directory
);
2251 $allowed_settings = array(
2255 'requiredentriestoview',
2262 $result = new stdClass
;
2263 $result->settings
= new stdClass
;
2264 $result->importfields
= array();
2265 $result->currentfields
= $DB->get_records('data_fields', array('dataid'=>$this->module
->id
));
2266 if (!$result->currentfields
) {
2267 $result->currentfields
= array();
2272 $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory
,'preset.xml');
2273 $parsedxml = xmlize($presetxml, 0);
2275 /* First, do settings. Put in user friendly array. */
2276 $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
2277 $result->settings
= new StdClass();
2278 foreach ($settingsarray as $setting => $value) {
2279 if (!is_array($value) ||
!in_array($setting, $allowed_settings)) {
2280 // unsupported setting
2283 $result->settings
->$setting = $value[0]['#'];
2286 /* Now work out fields to user friendly array */
2287 $fieldsarray = $parsedxml['preset']['#']['field'];
2288 foreach ($fieldsarray as $field) {
2289 if (!is_array($field)) {
2292 $f = new StdClass();
2293 foreach ($field['#'] as $param => $value) {
2294 if (!is_array($value)) {
2297 $f->$param = $value[0]['#'];
2299 $f->dataid
= $this->module
->id
;
2300 $f->type
= clean_param($f->type
, PARAM_ALPHA
);
2301 $result->importfields
[] = $f;
2303 /* Now add the HTML templates to the settings array so we can update d */
2304 $result->settings
->singletemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"singletemplate.html");
2305 $result->settings
->listtemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"listtemplate.html");
2306 $result->settings
->listtemplateheader
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"listtemplateheader.html");
2307 $result->settings
->listtemplatefooter
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"listtemplatefooter.html");
2308 $result->settings
->addtemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"addtemplate.html");
2309 $result->settings
->rsstemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"rsstemplate.html");
2310 $result->settings
->rsstitletemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"rsstitletemplate.html");
2311 $result->settings
->csstemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"csstemplate.css");
2312 $result->settings
->jstemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"jstemplate.js");
2313 $result->settings
->asearchtemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"asearchtemplate.html");
2315 $result->settings
->instance
= $this->module
->id
;
2320 * Import the preset into the given database module
2323 function import($overwritesettings) {
2326 $params = $this->get_preset_settings();
2327 $settings = $params->settings
;
2328 $newfields = $params->importfields
;
2329 $currentfields = $params->currentfields
;
2330 $preservedfields = array();
2332 /* Maps fields and makes new ones */
2333 if (!empty($newfields)) {
2334 /* We require an injective mapping, and need to know what to protect */
2335 foreach ($newfields as $nid => $newfield) {
2336 $cid = optional_param("field_$nid", -1, PARAM_INT
);
2340 if (array_key_exists($cid, $preservedfields)){
2341 print_error('notinjectivemap', 'data');
2343 else $preservedfields[$cid] = true;
2346 foreach ($newfields as $nid => $newfield) {
2347 $cid = optional_param("field_$nid", -1, PARAM_INT
);
2349 /* A mapping. Just need to change field params. Data kept. */
2350 if ($cid != -1 and isset($currentfields[$cid])) {
2351 $fieldobject = data_get_field_from_id($currentfields[$cid]->id
, $this->module
);
2352 foreach ($newfield as $param => $value) {
2353 if ($param != "id") {
2354 $fieldobject->field
->$param = $value;
2357 unset($fieldobject->field
->similarfield
);
2358 $fieldobject->update_field();
2359 unset($fieldobject);
2361 /* Make a new field */
2362 include_once("field/$newfield->type/field.class.php");
2364 if (!isset($newfield->description
)) {
2365 $newfield->description
= '';
2367 $classname = 'data_field_'.$newfield->type
;
2368 $fieldclass = new $classname($newfield, $this->module
);
2369 $fieldclass->insert_field();
2375 /* Get rid of all old unused data */
2376 if (!empty($preservedfields)) {
2377 foreach ($currentfields as $cid => $currentfield) {
2378 if (!array_key_exists($cid, $preservedfields)) {
2379 /* Data not used anymore so wipe! */
2380 print "Deleting field $currentfield->name<br />";
2382 $id = $currentfield->id
;
2383 //Why delete existing data records and related comments/ratings??
2384 $DB->delete_records('data_content', array('fieldid'=>$id));
2385 $DB->delete_records('data_fields', array('id'=>$id));
2390 // handle special settings here
2391 if (!empty($settings->defaultsort
)) {
2392 if (is_numeric($settings->defaultsort
)) {
2394 $settings->defaultsort
= 0;
2396 $settings->defaultsort
= (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module
->id
, 'name'=>$settings->defaultsort
));
2399 $settings->defaultsort
= 0;
2402 // do we want to overwrite all current database settings?
2403 if ($overwritesettings) {
2404 // all supported settings
2405 $overwrite = array_keys((array)$settings);
2407 // only templates and sorting
2408 $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2409 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
2410 'asearchtemplate', 'defaultsortdir', 'defaultsort');
2413 // now overwrite current data settings
2414 foreach ($this->module
as $prop=>$unused) {
2415 if (in_array($prop, $overwrite)) {
2416 $this->module
->$prop = $settings->$prop;
2420 data_update_instance($this->module
);
2422 return $this->cleanup();
2426 * Any clean up routines should go here
2429 public function cleanup() {
2435 * Data preset importer for uploaded presets
2437 class data_preset_upload_importer
extends data_preset_importer
{
2438 public function __construct($course, $cm, $module, $filepath) {
2440 if (is_file($filepath)) {
2441 $fp = get_file_packer();
2442 if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2443 fulldelete($filepath);
2445 $filepath .= '_extracted';
2447 parent
::__construct($course, $cm, $module, $filepath);
2449 public function cleanup() {
2450 return fulldelete($this->directory
);
2455 * Data preset importer for existing presets
2457 class data_preset_existing_importer
extends data_preset_importer
{
2459 public function __construct($course, $cm, $module, $fullname) {
2461 list($userid, $shortname) = explode('/', $fullname, 2);
2462 $context = context_module
::instance($cm->id
);
2463 if ($userid && ($userid != $USER->id
) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2464 throw new coding_exception('Invalid preset provided');
2467 $this->userid
= $userid;
2468 $filepath = data_preset_path($course, $userid, $shortname);
2469 parent
::__construct($course, $cm, $module, $filepath);
2471 public function get_userid() {
2472 return $this->userid
;
2479 * @param object $course
2480 * @param int $userid
2481 * @param string $shortname
2484 function data_preset_path($course, $userid, $shortname) {
2487 $context = context_course
::instance($course->id
);
2489 $userid = (int)$userid;
2492 if ($userid > 0 && ($userid == $USER->id ||
has_capability('mod/data:viewalluserpresets', $context))) {
2493 $path = $CFG->dataroot
.'/data/preset/'.$userid.'/'.$shortname;
2494 } else if ($userid == 0) {
2495 $path = $CFG->dirroot
.'/mod/data/preset/'.$shortname;
2496 } else if ($userid < 0) {
2497 $path = $CFG->tempdir
.'/data/'.-$userid.'/'.$shortname;
2504 * Implementation of the function for printing the form elements that control
2505 * whether the course reset functionality affects the data.
2507 * @param $mform form passed by reference
2509 function data_reset_course_form_definition(&$mform) {
2510 $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2511 $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2513 $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2514 $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2516 $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2517 $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2519 $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2520 $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
2524 * Course reset form defaults.
2527 function data_reset_course_form_defaults($course) {
2528 return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2532 * Removes all grades from gradebook
2536 * @param int $courseid
2537 * @param string $type optional type
2539 function data_reset_gradebook($courseid, $type='') {
2542 $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
2543 FROM {data} d, {course_modules} cm, {modules} m
2544 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
2546 if ($datas = $DB->get_records_sql($sql, array($courseid))) {
2547 foreach ($datas as $data) {
2548 data_grade_item_update($data, 'reset');
2554 * Actual implementation of the reset course functionality, delete all the
2555 * data responses for course $data->courseid.
2559 * @param object $data the data submitted from the reset course.
2560 * @return array status array
2562 function data_reset_userdata($data) {
2564 require_once($CFG->libdir
.'/filelib.php');
2565 require_once($CFG->dirroot
.'/rating/lib.php');
2567 $componentstr = get_string('modulenameplural', 'data');
2570 $allrecordssql = "SELECT r.id
2571 FROM {data_records} r
2572 INNER JOIN {data} d ON r.dataid = d.id
2573 WHERE d.course = ?";
2575 $alldatassql = "SELECT d.id
2579 $rm = new rating_manager();
2580 $ratingdeloptions = new stdClass
;
2581 $ratingdeloptions->component
= 'mod_data';
2582 $ratingdeloptions->ratingarea
= 'entry';
2584 // Set the file storage - may need it to remove files later.
2585 $fs = get_file_storage();
2587 // delete entries if requested
2588 if (!empty($data->reset_data
)) {
2589 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid
));
2590 $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid
));
2591 $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid
));
2593 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid
))) {
2594 foreach ($datas as $dataid=>$unused) {
2595 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2598 $datacontext = context_module
::instance($cm->id
);
2600 // Delete any files that may exist.
2601 $fs->delete_area_files($datacontext->id
, 'mod_data', 'content');
2603 $ratingdeloptions->contextid
= $datacontext->id
;
2604 $rm->delete_ratings($ratingdeloptions);
2608 if (empty($data->reset_gradebook_grades
)) {
2609 // remove all grades from gradebook
2610 data_reset_gradebook($data->courseid
);
2612 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2615 // remove entries by users not enrolled into course
2616 if (!empty($data->reset_data_notenrolled
)) {
2617 $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
2618 FROM {data_records} r
2619 JOIN {data} d ON r.dataid = d.id
2620 LEFT JOIN {user} u ON r.userid = u.id
2621 WHERE d.course = ? AND r.userid > 0";
2623 $course_context = context_course
::instance($data->courseid
);
2624 $notenrolled = array();
2626 $rs = $DB->get_recordset_sql($recordssql, array($data->courseid
));
2627 foreach ($rs as $record) {
2628 if (array_key_exists($record->userid
, $notenrolled) or !$record->userexists
or $record->userdeleted
2629 or !is_enrolled($course_context, $record->userid
)) {
2631 if (!$cm = get_coursemodule_from_instance('data', $record->dataid
)) {
2634 $datacontext = context_module
::instance($cm->id
);
2635 $ratingdeloptions->contextid
= $datacontext->id
;
2636 $ratingdeloptions->itemid
= $record->id
;
2637 $rm->delete_ratings($ratingdeloptions);
2639 // Delete any files that may exist.
2640 if ($contents = $DB->get_records('data_content', array('recordid' => $record->id
), '', 'id')) {
2641 foreach ($contents as $content) {
2642 $fs->delete_area_files($datacontext->id
, 'mod_data', 'content', $content->id
);
2645 $notenrolled[$record->userid
] = true;
2647 $DB->delete_records('comments', array('itemid' => $record->id
, 'commentarea' => 'database_entry'));
2648 $DB->delete_records('data_content', array('recordid' => $record->id
));
2649 $DB->delete_records('data_records', array('id' => $record->id
));
2653 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
2656 // remove all ratings
2657 if (!empty($data->reset_data_ratings
)) {
2658 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid
))) {
2659 foreach ($datas as $dataid=>$unused) {
2660 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2663 $datacontext = context_module
::instance($cm->id
);
2665 $ratingdeloptions->contextid
= $datacontext->id
;
2666 $rm->delete_ratings($ratingdeloptions);
2670 if (empty($data->reset_gradebook_grades
)) {
2671 // remove all grades from gradebook
2672 data_reset_gradebook($data->courseid
);
2675 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2678 // remove all comments
2679 if (!empty($data->reset_data_comments
)) {
2680 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid
));
2681 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2684 // updating dates - shift may be negative too
2685 if ($data->timeshift
) {
2686 shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto'), $data->timeshift
, $data->courseid
);
2687 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2694 * Returns all other caps used in module
2698 function data_get_extra_capabilities() {
2699 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');
2703 * @param string $feature FEATURE_xx constant for requested feature
2704 * @return mixed True if module supports feature, null if doesn't know
2706 function data_supports($feature) {
2708 case FEATURE_GROUPS
: return true;
2709 case FEATURE_GROUPINGS
: return true;
2710 case FEATURE_MOD_INTRO
: return true;
2711 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
2712 case FEATURE_GRADE_HAS_GRADE
: return true;
2713 case FEATURE_GRADE_OUTCOMES
: return true;
2714 case FEATURE_RATE
: return true;
2715 case FEATURE_BACKUP_MOODLE2
: return true;
2716 case FEATURE_SHOW_DESCRIPTION
: return true;
2718 default: return null;
2723 * @param array $export
2724 * @param string $delimiter_name
2725 * @param object $database
2727 * @param bool $return
2728 * @return string|void
2730 function data_export_csv($export, $delimiter_name, $database, $count, $return=false) {
2732 require_once($CFG->libdir
. '/csvlib.class.php');
2734 $filename = $database . '-' . $count . '-record';
2739 return csv_export_writer
::print_array($export, $delimiter_name, '"', true);
2741 csv_export_writer
::download_array($filename, $export, $delimiter_name);
2747 * @param array $export
2748 * @param string $dataname
2752 function data_export_xls($export, $dataname, $count) {
2754 require_once("$CFG->libdir/excellib.class.php");
2755 $filename = clean_filename("{$dataname}-{$count}_record");
2759 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2760 $filename .= '.xls';
2763 $workbook = new MoodleExcelWorkbook($filearg);
2764 $workbook->send($filename);
2765 $worksheet = array();
2766 $worksheet[0] = $workbook->add_worksheet('');
2768 foreach ($export as $row) {
2770 foreach($row as $col) {
2771 $worksheet[0]->write($rowno, $colno, $col);
2782 * @param array $export
2783 * @param string $dataname
2787 function data_export_ods($export, $dataname, $count) {
2789 require_once("$CFG->libdir/odslib.class.php");
2790 $filename = clean_filename("{$dataname}-{$count}_record");
2794 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2795 $filename .= '.ods';
2797 $workbook = new MoodleODSWorkbook($filearg);
2798 $workbook->send($filename);
2799 $worksheet = array();
2800 $worksheet[0] = $workbook->add_worksheet('');
2802 foreach ($export as $row) {
2804 foreach($row as $col) {
2805 $worksheet[0]->write($rowno, $colno, $col);
2816 * @param int $dataid
2817 * @param array $fields
2818 * @param array $selectedfields
2819 * @param int $currentgroup group ID of the current group. This is used for
2820 * exporting data while maintaining group divisions.
2821 * @param object $context the context in which the operation is performed (for capability checks)
2822 * @param bool $userdetails whether to include the details of the record author
2823 * @param bool $time whether to include time created/modified
2824 * @param bool $approval whether to include approval status
2827 function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0, $context=null,
2828 $userdetails=false, $time=false, $approval=false) {
2831 if (is_null($context)) {
2832 $context = context_system
::instance();
2834 // exporting user data needs special permission
2835 $userdetails = $userdetails && has_capability('mod/data:exportuserinfo', $context);
2837 $exportdata = array();
2839 // populate the header in first row of export
2840 foreach($fields as $key => $field) {
2841 if (!in_array($field->field
->id
, $selectedfields)) {
2842 // ignore values we aren't exporting
2843 unset($fields[$key]);
2845 $exportdata[0][] = $field->field
->name
;
2849 $exportdata[0][] = get_string('user');
2850 $exportdata[0][] = get_string('username');
2851 $exportdata[0][] = get_string('email');
2854 $exportdata[0][] = get_string('timeadded', 'data');
2855 $exportdata[0][] = get_string('timemodified', 'data');
2858 $exportdata[0][] = get_string('approved', 'data');
2861 $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
2862 ksort($datarecords);
2864 foreach($datarecords as $record) {
2865 // get content indexed by fieldid
2866 if ($currentgroup) {
2867 $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 = ?';
2868 $where = array($record->id
, $currentgroup);
2870 $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
2871 $where = array($record->id
);
2874 if( $content = $DB->get_records_sql($select, $where) ) {
2875 foreach($fields as $field) {
2877 if(isset($content[$field->field
->id
])) {
2878 $contents = $field->export_text_value($content[$field->field
->id
]);
2880 $exportdata[$line][] = $contents;
2882 if ($userdetails) { // Add user details to the export data
2883 $userdata = get_complete_user_data('id', $record->userid
);
2884 $exportdata[$line][] = fullname($userdata);
2885 $exportdata[$line][] = $userdata->username
;
2886 $exportdata[$line][] = $userdata->email
;
2888 if ($time) { // Add time added / modified
2889 $exportdata[$line][] = userdate($record->timecreated
);
2890 $exportdata[$line][] = userdate($record->timemodified
);
2892 if ($approval) { // Add approval status
2893 $exportdata[$line][] = (int) $record->approved
;
2902 ////////////////////////////////////////////////////////////////////////////////
2904 ////////////////////////////////////////////////////////////////////////////////
2907 * Lists all browsable file areas
2911 * @param stdClass $course course object
2912 * @param stdClass $cm course module object
2913 * @param stdClass $context context object
2916 function data_get_file_areas($course, $cm, $context) {
2917 return array('content' => get_string('areacontent', 'mod_data'));
2921 * File browsing support for data module.
2923 * @param file_browser $browser
2924 * @param array $areas
2925 * @param stdClass $course
2926 * @param cm_info $cm
2927 * @param context $context
2928 * @param string $filearea
2929 * @param int $itemid
2930 * @param string $filepath
2931 * @param string $filename
2932 * @return file_info_stored file_info_stored instance or null if not found
2934 function data_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2935 global $CFG, $DB, $USER;
2937 if ($context->contextlevel
!= CONTEXT_MODULE
) {
2941 if (!isset($areas[$filearea])) {
2945 if (is_null($itemid)) {
2946 require_once($CFG->dirroot
.'/mod/data/locallib.php');
2947 return new data_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
2950 if (!$content = $DB->get_record('data_content', array('id'=>$itemid))) {
2954 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid
))) {
2958 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid
))) {
2962 if (!$data = $DB->get_record('data', array('id'=>$field->dataid
))) {
2967 if ($data->approval
and !$record->approved
and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
2972 if ($record->groupid
) {
2973 $groupmode = groups_get_activity_groupmode($cm, $course);
2974 if ($groupmode == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
2975 if (!groups_is_member($record->groupid
)) {
2981 $fieldobj = data_get_field($field, $data, $cm);
2983 $filepath = is_null($filepath) ?
'/' : $filepath;
2984 $filename = is_null($filename) ?
'.' : $filename;
2985 if (!$fieldobj->file_ok($filepath.$filename)) {
2989 $fs = get_file_storage();
2990 if (!($storedfile = $fs->get_file($context->id
, 'mod_data', $filearea, $itemid, $filepath, $filename))) {
2994 // Checks to see if the user can manage files or is the owner.
2995 // TODO MDL-33805 - Do not use userid here and move the capability check above.
2996 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id
) {
3000 $urlbase = $CFG->wwwroot
.'/pluginfile.php';
3002 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
3006 * Serves the data attachments. Implements needed access control ;-)
3010 * @param stdClass $course course object
3011 * @param stdClass $cm course module object
3012 * @param stdClass $context context object
3013 * @param string $filearea file area
3014 * @param array $args extra arguments
3015 * @param bool $forcedownload whether or not force download
3016 * @param array $options additional options affecting the file serving
3017 * @return bool false if file not found, does not return if found - justsend the file
3019 function data_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3022 if ($context->contextlevel
!= CONTEXT_MODULE
) {
3026 require_course_login($course, true, $cm);
3028 if ($filearea === 'content') {
3029 $contentid = (int)array_shift($args);
3031 if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
3035 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid
))) {
3039 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid
))) {
3043 if (!$data = $DB->get_record('data', array('id'=>$field->dataid
))) {
3047 if ($data->id
!= $cm->instance
) {
3048 // hacker attempt - context does not match the contentid
3053 if ($data->approval
and !$record->approved
and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3058 if ($record->groupid
) {
3059 $groupmode = groups_get_activity_groupmode($cm, $course);
3060 if ($groupmode == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
3061 if (!groups_is_member($record->groupid
)) {
3067 $fieldobj = data_get_field($field, $data, $cm);
3069 $relativepath = implode('/', $args);
3070 $fullpath = "/$context->id/mod_data/content/$content->id/$relativepath";
3072 if (!$fieldobj->file_ok($relativepath)) {
3076 $fs = get_file_storage();
3077 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3081 // finally send the file
3082 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
3089 function data_extend_navigation($navigation, $course, $module, $cm) {
3090 global $CFG, $OUTPUT, $USER, $DB;
3092 $rid = optional_param('rid', 0, PARAM_INT
);
3094 $data = $DB->get_record('data', array('id'=>$cm->instance
));
3095 $currentgroup = groups_get_activity_group($cm);
3096 $groupmode = groups_get_activity_groupmode($cm);
3098 $numentries = data_numentries($data);
3099 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
3100 if ($data->requiredentries
> 0 && $numentries < $data->requiredentries
&& !has_capability('mod/data:manageentries', context_module
::instance($cm->id
))) {
3101 $data->entriesleft
= $data->requiredentries
- $numentries;
3102 $entriesnode = $navigation->add(get_string('entrieslefttoadd', 'data', $data));
3103 $entriesnode->add_class('note');
3106 $navigation->add(get_string('list', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance
)));
3108 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance
, 'rid'=>$rid)));
3110 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance
, 'mode'=>'single')));
3112 $navigation->add(get_string('search', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance
, 'mode'=>'asearch')));
3116 * Adds module specific settings to the settings block
3118 * @param settings_navigation $settings The settings navigation object
3119 * @param navigation_node $datanode The node to add module settings to
3121 function data_extend_settings_navigation(settings_navigation
$settings, navigation_node
$datanode) {
3122 global $PAGE, $DB, $CFG, $USER;
3124 $data = $DB->get_record('data', array("id" => $PAGE->cm
->instance
));
3126 $currentgroup = groups_get_activity_group($PAGE->cm
);
3127 $groupmode = groups_get_activity_groupmode($PAGE->cm
);
3129 if (data_user_can_add_entry($data, $currentgroup, $groupmode, $PAGE->cm
->context
)) { // took out participation list here!
3130 if (empty($editentry)) { //TODO: undefined
3131 $addstring = get_string('add', 'data');
3133 $addstring = get_string('editentry', 'data');
3135 $datanode->add($addstring, new moodle_url('/mod/data/edit.php', array('d'=>$PAGE->cm
->instance
)));
3138 if (has_capability(DATA_CAP_EXPORT
, $PAGE->cm
->context
)) {
3139 // The capability required to Export database records is centrally defined in 'lib.php'
3140 // and should be weaker than those required to edit Templates, Fields and Presets.
3141 $datanode->add(get_string('exportentries', 'data'), new moodle_url('/mod/data/export.php', array('d'=>$data->id
)));
3143 if (has_capability('mod/data:manageentries', $PAGE->cm
->context
)) {
3144 $datanode->add(get_string('importentries', 'data'), new moodle_url('/mod/data/import.php', array('d'=>$data->id
)));
3147 if (has_capability('mod/data:managetemplates', $PAGE->cm
->context
)) {
3149 if ($currenttab == 'list') {
3150 $defaultemplate = 'listtemplate';
3151 } else if ($currenttab == 'add') {
3152 $defaultemplate = 'addtemplate';
3153 } else if ($currenttab == 'asearch') {
3154 $defaultemplate = 'asearchtemplate';
3156 $defaultemplate = 'singletemplate';
3159 $templates = $datanode->add(get_string('templates', 'data'));
3161 $templatelist = array ('listtemplate', 'singletemplate', 'asearchtemplate', 'addtemplate', 'rsstemplate', 'csstemplate', 'jstemplate');
3162 foreach ($templatelist as $template) {
3163 $templates->add(get_string($template, 'data'), new moodle_url('/mod/data/templates.php', array('d'=>$data->id
,'mode'=>$template)));
3166 $datanode->add(get_string('fields', 'data'), new moodle_url('/mod/data/field.php', array('d'=>$data->id
)));
3167 $datanode->add(get_string('presets', 'data'), new moodle_url('/mod/data/preset.php', array('d'=>$data->id
)));
3170 if (!empty($CFG->enablerssfeeds
) && !empty($CFG->data_enablerssfeeds
) && $data->rssarticles
> 0) {
3171 require_once("$CFG->libdir/rsslib.php");
3173 $string = get_string('rsstype','forum');
3175 $url = new moodle_url(rss_get_url($PAGE->cm
->context
->id
, $USER->id
, 'mod_data', $data->id
));
3176 $datanode->add($string, $url, settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
3181 * Save the database configuration as a preset.
3183 * @param stdClass $course The course the database module belongs to.
3184 * @param stdClass $cm The course module record
3185 * @param stdClass $data The database record
3186 * @param string $path
3189 function data_presets_save($course, $cm, $data, $path) {
3191 $fs = get_file_storage();
3192 $filerecord = new stdClass
;
3193 $filerecord->contextid
= DATA_PRESET_CONTEXT
;
3194 $filerecord->component
= DATA_PRESET_COMPONENT
;
3195 $filerecord->filearea
= DATA_PRESET_FILEAREA
;
3196 $filerecord->itemid
= 0;
3197 $filerecord->filepath
= '/'.$path.'/';
3198 $filerecord->userid
= $USER->id
;
3200 $filerecord->filename
= 'preset.xml';
3201 $fs->create_file_from_string($filerecord, data_presets_generate_xml($course, $cm, $data));
3203 $filerecord->filename
= 'singletemplate.html';
3204 $fs->create_file_from_string($filerecord, $data->singletemplate
);
3206 $filerecord->filename
= 'listtemplateheader.html';
3207 $fs->create_file_from_string($filerecord, $data->listtemplateheader
);
3209 $filerecord->filename
= 'listtemplate.html';
3210 $fs->create_file_from_string($filerecord, $data->listtemplate
);
3212 $filerecord->filename
= 'listtemplatefooter.html';
3213 $fs->create_file_from_string($filerecord, $data->listtemplatefooter
);
3215 $filerecord->filename
= 'addtemplate.html';
3216 $fs->create_file_from_string($filerecord, $data->addtemplate
);
3218 $filerecord->filename
= 'rsstemplate.html';
3219 $fs->create_file_from_string($filerecord, $data->rsstemplate
);
3221 $filerecord->filename
= 'rsstitletemplate.html';
3222 $fs->create_file_from_string($filerecord, $data->rsstitletemplate
);
3224 $filerecord->filename
= 'csstemplate.css';
3225 $fs->create_file_from_string($filerecord, $data->csstemplate
);
3227 $filerecord->filename
= 'jstemplate.js';
3228 $fs->create_file_from_string($filerecord, $data->jstemplate
);
3230 $filerecord->filename
= 'asearchtemplate.html';
3231 $fs->create_file_from_string($filerecord, $data->asearchtemplate
);
3237 * Generates the XML for the database module provided
3239 * @global moodle_database $DB
3240 * @param stdClass $course The course the database module belongs to.
3241 * @param stdClass $cm The course module record
3242 * @param stdClass $data The database record
3243 * @return string The XML for the preset
3245 function data_presets_generate_xml($course, $cm, $data) {
3248 // Assemble "preset.xml":
3249 $presetxmldata = "<preset>\n\n";
3251 // Raw settings are not preprocessed during saving of presets
3252 $raw_settings = array(
3256 'requiredentriestoview',
3263 $presetxmldata .= "<settings>\n";
3264 // First, settings that do not require any conversion
3265 foreach ($raw_settings as $setting) {
3266 $presetxmldata .= "<$setting>" . htmlspecialchars($data->$setting) . "</$setting>\n";
3269 // Now specific settings
3270 if ($data->defaultsort
> 0 && $sortfield = data_get_field_from_id($data->defaultsort
, $data)) {
3271 $presetxmldata .= '<defaultsort>' . htmlspecialchars($sortfield->field
->name
) . "</defaultsort>\n";
3273 $presetxmldata .= "<defaultsort>0</defaultsort>\n";
3275 $presetxmldata .= "</settings>\n\n";
3276 // Now for the fields. Grab all that are non-empty
3277 $fields = $DB->get_records('data_fields', array('dataid'=>$data->id
));
3279 if (!empty($fields)) {
3280 foreach ($fields as $field) {
3281 $presetxmldata .= "<field>\n";
3282 foreach ($field as $key => $value) {
3283 if ($value != '' && $key != 'id' && $key != 'dataid') {
3284 $presetxmldata .= "<$key>" . htmlspecialchars($value) . "</$key>\n";
3287 $presetxmldata .= "</field>\n\n";
3290 $presetxmldata .= '</preset>';
3291 return $presetxmldata;
3294 function data_presets_export($course, $cm, $data, $tostorage=false) {
3297 $presetname = clean_filename($data->name
) . '-preset-' . gmdate("Ymd_Hi");
3298 $exportsubdir = "mod_data/presetexport/$presetname";
3299 make_temp_directory($exportsubdir);
3300 $exportdir = "$CFG->tempdir/$exportsubdir";
3302 // Assemble "preset.xml":
3303 $presetxmldata = data_presets_generate_xml($course, $cm, $data);
3305 // After opening a file in write mode, close it asap
3306 $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
3307 fwrite($presetxmlfile, $presetxmldata);
3308 fclose($presetxmlfile);
3310 // Now write the template files
3311 $singletemplate = fopen($exportdir . '/singletemplate.html', 'w');
3312 fwrite($singletemplate, $data->singletemplate
);
3313 fclose($singletemplate);
3315 $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w');
3316 fwrite($listtemplateheader, $data->listtemplateheader
);
3317 fclose($listtemplateheader);
3319 $listtemplate = fopen($exportdir . '/listtemplate.html', 'w');
3320 fwrite($listtemplate, $data->listtemplate
);
3321 fclose($listtemplate);
3323 $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w');
3324 fwrite($listtemplatefooter, $data->listtemplatefooter
);
3325 fclose($listtemplatefooter);
3327 $addtemplate = fopen($exportdir . '/addtemplate.html', 'w');
3328 fwrite($addtemplate, $data->addtemplate
);
3329 fclose($addtemplate);
3331 $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w');
3332 fwrite($rsstemplate, $data->rsstemplate
);
3333 fclose($rsstemplate);
3335 $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w');
3336 fwrite($rsstitletemplate, $data->rsstitletemplate
);
3337 fclose($rsstitletemplate);
3339 $csstemplate = fopen($exportdir . '/csstemplate.css', 'w');
3340 fwrite($csstemplate, $data->csstemplate
);
3341 fclose($csstemplate);
3343 $jstemplate = fopen($exportdir . '/jstemplate.js', 'w');
3344 fwrite($jstemplate, $data->jstemplate
);
3345 fclose($jstemplate);
3347 $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w');
3348 fwrite($asearchtemplate, $data->asearchtemplate
);
3349 fclose($asearchtemplate);
3351 // Check if all files have been generated
3352 if (! is_directory_a_preset($exportdir)) {
3353 print_error('generateerror', 'data');
3358 'singletemplate.html',
3359 'listtemplateheader.html',
3360 'listtemplate.html',
3361 'listtemplatefooter.html',
3364 'rsstitletemplate.html',
3367 'asearchtemplate.html'
3370 $filelist = array();
3371 foreach ($filenames as $filename) {
3372 $filelist[$filename] = $exportdir . '/' . $filename;
3375 $exportfile = $exportdir.'.zip';
3376 file_exists($exportfile) && unlink($exportfile);
3378 $fp = get_file_packer('application/zip');
3379 $fp->archive_to_pathname($filelist, $exportfile);
3381 foreach ($filelist as $file) {
3386 // Return the full path to the exported preset file:
3391 * Running addtional permission check on plugin, for example, plugins
3392 * may have switch to turn on/off comments option, this callback will
3393 * affect UI display, not like pluginname_comment_validate only throw
3395 * Capability check has been done in comment->check_permissions(), we
3396 * don't need to do it again here.
3401 * @param stdClass $comment_param {
3402 * context => context the context object
3403 * courseid => int course id
3404 * cm => stdClass course module object
3405 * commentarea => string comment area
3406 * itemid => int itemid
3410 function data_comment_permissions($comment_param) {
3412 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid
))) {
3413 throw new comment_exception('invalidcommentitemid');
3415 if (!$data = $DB->get_record('data', array('id'=>$record->dataid
))) {
3416 throw new comment_exception('invalidid', 'data');
3418 if ($data->comments
) {
3419 return array('post'=>true, 'view'=>true);
3421 return array('post'=>false, 'view'=>false);
3426 * Validate comment parameter before perform other comments actions
3431 * @param stdClass $comment_param {
3432 * context => context the context object
3433 * courseid => int course id
3434 * cm => stdClass course module object
3435 * commentarea => string comment area
3436 * itemid => int itemid
3440 function data_comment_validate($comment_param) {
3442 // validate comment area
3443 if ($comment_param->commentarea
!= 'database_entry') {
3444 throw new comment_exception('invalidcommentarea');
3447 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid
))) {
3448 throw new comment_exception('invalidcommentitemid');
3450 if (!$data = $DB->get_record('data', array('id'=>$record->dataid
))) {
3451 throw new comment_exception('invalidid', 'data');
3453 if (!$course = $DB->get_record('course', array('id'=>$data->course
))) {
3454 throw new comment_exception('coursemisconf');
3456 if (!$cm = get_coursemodule_from_instance('data', $data->id
, $course->id
)) {
3457 throw new comment_exception('invalidcoursemodule');
3459 if (!$data->comments
) {
3460 throw new comment_exception('commentsoff', 'data');
3462 $context = context_module
::instance($cm->id
);
3465 if ($data->approval
and !$record->approved
and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3466 throw new comment_exception('notapproved', 'data');
3470 if ($record->groupid
) {
3471 $groupmode = groups_get_activity_groupmode($cm, $course);
3472 if ($groupmode == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
3473 if (!groups_is_member($record->groupid
)) {
3474 throw new comment_exception('notmemberofgroup');
3478 // validate context id
3479 if ($context->id
!= $comment_param->context
->id
) {
3480 throw new comment_exception('invalidcontext');
3482 // validation for comment deletion
3483 if (!empty($comment_param->commentid
)) {
3484 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid
))) {
3485 if ($comment->commentarea
!= 'database_entry') {
3486 throw new comment_exception('invalidcommentarea');
3488 if ($comment->contextid
!= $comment_param->context
->id
) {
3489 throw new comment_exception('invalidcontext');
3491 if ($comment->itemid
!= $comment_param->itemid
) {
3492 throw new comment_exception('invalidcommentitemid');
3495 throw new comment_exception('invalidcommentid');
3502 * Return a list of page types
3503 * @param string $pagetype current page type
3504 * @param stdClass $parentcontext Block's parent context
3505 * @param stdClass $currentcontext Current context of block
3507 function data_page_type_list($pagetype, $parentcontext, $currentcontext) {
3508 $module_pagetype = array('mod-data-*'=>get_string('page-mod-data-x', 'data'));
3509 return $module_pagetype;
3513 * Get all of the record ids from a database activity.
3515 * @param int $dataid The dataid of the database module.
3516 * @param object $selectdata Contains an additional sql statement for the
3517 * where clause for group and approval fields.
3518 * @param array $params Parameters that coincide with the sql statement.
3519 * @return array $idarray An array of record ids
3521 function data_get_all_recordids($dataid, $selectdata = '', $params = null) {
3523 $initsql = 'SELECT r.id
3524 FROM {data_records} r
3525 WHERE r.dataid = :dataid';
3526 if ($selectdata != '') {
3527 $initsql .= $selectdata;
3528 $params = array_merge(array('dataid' => $dataid), $params);
3530 $params = array('dataid' => $dataid);
3532 $initsql .= ' GROUP BY r.id';
3533 $initrecord = $DB->get_recordset_sql($initsql, $params);
3535 foreach ($initrecord as $data) {
3536 $idarray[] = $data->id
;
3538 // Close the record set and free up resources.
3539 $initrecord->close();
3544 * Get the ids of all the records that match that advanced search criteria
3545 * This goes and loops through each criterion one at a time until it either
3546 * runs out of records or returns a subset of records.
3548 * @param array $recordids An array of record ids.
3549 * @param array $searcharray Contains information for the advanced search criteria
3550 * @param int $dataid The data id of the database.
3551 * @return array $recordids An array of record ids.
3553 function data_get_advance_search_ids($recordids, $searcharray, $dataid) {
3554 $searchcriteria = array_keys($searcharray);
3555 // Loop through and reduce the IDs one search criteria at a time.
3556 foreach ($searchcriteria as $key) {
3557 $recordids = data_get_recordids($key, $searcharray, $dataid, $recordids);
3558 // If we don't have anymore IDs then stop.
3567 * Gets the record IDs given the search criteria
3569 * @param string $alias Record alias.
3570 * @param array $searcharray Criteria for the search.
3571 * @param int $dataid Data ID for the database
3572 * @param array $recordids An array of record IDs.
3573 * @return array $nestarray An arry of record IDs
3575 function data_get_recordids($alias, $searcharray, $dataid, $recordids) {
3578 $nestsearch = $searcharray[$alias];
3579 // searching for content outside of mdl_data_content
3583 list($insql, $params) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED
);
3584 $nestselect = 'SELECT c' . $alias . '.recordid
3585 FROM {data_content} c' . $alias . ',
3589 $nestwhere = 'WHERE u.id = r.userid
3590 AND f.id = c' . $alias . '.fieldid
3591 AND r.id = c' . $alias . '.recordid
3592 AND r.dataid = :dataid
3593 AND c' . $alias .'.recordid ' . $insql . '
3596 $params['dataid'] = $dataid;
3597 if (count($nestsearch->params
) != 0) {
3598 $params = array_merge($params, $nestsearch->params
);
3599 $nestsql = $nestselect . $nestwhere . $nestsearch->sql
;
3601 $thing = $DB->sql_like($nestsearch->field
, ':search1', false);
3602 $nestsql = $nestselect . $nestwhere . $thing . ' GROUP BY c' . $alias . '.recordid';
3603 $params['search1'] = "%$nestsearch->data%";
3605 $nestrecords = $DB->get_recordset_sql($nestsql, $params);
3606 $nestarray = array();
3607 foreach ($nestrecords as $data) {
3608 $nestarray[] = $data->recordid
;
3610 // Close the record set and free up resources.
3611 $nestrecords->close();
3616 * Returns an array with an sql string for advanced searches and the parameters that go with them.
3618 * @param int $sort DATA_*
3619 * @param stdClass $data Data module object
3620 * @param array $recordids An array of record IDs.
3621 * @param string $selectdata Information for the where and select part of the sql statement.
3622 * @param string $sortorder Additional sort parameters
3623 * @return array sqlselect sqlselect['sql'] has the sql string, sqlselect['params'] contains an array of parameters.
3625 function data_get_advanced_search_sql($sort, $data, $recordids, $selectdata, $sortorder) {
3628 $namefields = user_picture
::fields('u');
3629 // Remove the id from the string. This already exists in the sql statement.
3630 $namefields = str_replace('u.id,', '', $namefields);
3633 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . '
3634 FROM {data_content} c,
3637 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' . $namefields;
3639 // Sorting through 'Other' criteria
3643 $sortcontentfull = "u.lastname";
3645 case DATA_FIRSTNAME
:
3646 $sortcontentfull = "u.firstname";
3649 $sortcontentfull = "r.approved";
3651 case DATA_TIMEMODIFIED
:
3652 $sortcontentfull = "r.timemodified";
3654 case DATA_TIMEADDED
:
3656 $sortcontentfull = "r.timecreated";
3659 $sortfield = data_get_field_from_id($sort, $data);
3660 $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
3661 $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
3664 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ',
3665 ' . $sortcontentfull . '
3667 FROM {data_content} c,
3670 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ', ' .$sortcontentfull;
3673 // Default to a standard Where statement if $selectdata is empty.
3674 if ($selectdata == '') {
3675 $selectdata = 'WHERE c.recordid = r.id
3676 AND r.dataid = :dataid
3677 AND r.userid = u.id ';
3680 // Find the field we are sorting on
3681 if ($sort > 0 or data_get_field_from_id($sort, $data)) {
3682 $selectdata .= ' AND c.fieldid = :sort';
3685 // If there are no record IDs then return an sql statment that will return no rows.
3686 if (count($recordids) != 0) {
3687 list($insql, $inparam) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED
);
3689 list($insql, $inparam) = $DB->get_in_or_equal(array('-1'), SQL_PARAMS_NAMED
);
3691 $nestfromsql = $selectdata . ' AND c.recordid ' . $insql . $groupsql;
3692 $sqlselect['sql'] = "$nestselectsql $nestfromsql $sortorder";
3693 $sqlselect['params'] = $inparam;
3698 * Checks to see if the user has permission to delete the preset.
3699 * @param stdClass $context Context object.
3700 * @param stdClass $preset The preset object that we are checking for deletion.
3701 * @return bool Returns true if the user can delete, otherwise false.
3703 function data_user_can_delete_preset($context, $preset) {
3706 if (has_capability('mod/data:manageuserpresets', $context)) {
3710 if ($preset->userid
== $USER->id
) {
3718 * Delete a record entry.
3720 * @param int $recordid The ID for the record to be deleted.
3721 * @param object $data The data object for this activity.
3722 * @param int $courseid ID for the current course (for logging).
3723 * @param int $cmid The course module ID.
3724 * @return bool True if the record deleted, false if not.
3726 function data_delete_record($recordid, $data, $courseid, $cmid) {
3729 if ($deleterecord = $DB->get_record('data_records', array('id' => $recordid))) {
3730 if ($deleterecord->dataid
== $data->id
) {
3731 if ($contents = $DB->get_records('data_content', array('recordid' => $deleterecord->id
))) {
3732 foreach ($contents as $content) {
3733 if ($field = data_get_field_from_id($content->fieldid
, $data)) {
3734 $field->delete_content($content->recordid
);
3737 $DB->delete_records('data_content', array('recordid'=>$deleterecord->id
));
3738 $DB->delete_records('data_records', array('id'=>$deleterecord->id
));
3740 // Delete cached RSS feeds.
3741 if (!empty($CFG->enablerssfeeds
)) {
3742 require_once($CFG->dirroot
.'/mod/data/rsslib.php');
3743 data_rss_delete_file($data);
3746 // Trigger an event for deleting this record.
3747 $event = \mod_data\event\record_deleted
::create(array(
3748 'objectid' => $deleterecord->id
,
3749 'context' => context_module
::instance($cmid),
3750 'courseid' => $courseid,
3752 'dataid' => $deleterecord->dataid
3755 $event->add_record_snapshot('data_records', $deleterecord);
3766 * Check for required fields, and build a list of fields to be updated in a
3769 * @param $mod stdClass The current recordid - provided as an optimisation.
3770 * @param $fields array The field data
3771 * @param $datarecord stdClass The submitted data.
3772 * @return stdClass containing:
3773 * * string[] generalnotifications Notifications for the form as a whole.
3774 * * string[] fieldnotifications Notifications for a specific field.
3775 * * bool validated Whether the field was validated successfully.
3776 * * data_field_base[] fields The field objects to be update.
3778 function data_process_submission(stdClass
$mod, $fields, stdClass
$datarecord) {
3779 $result = new stdClass();
3781 // Empty form checking - you can't submit an empty form.
3783 $requiredfieldsfilled = true;
3785 // Store the notifications.
3786 $result->generalnotifications
= array();
3787 $result->fieldnotifications
= array();
3789 // Store the instantiated classes as an optimisation when processing the result.
3790 // This prevents the fields being re-initialised when updating.
3791 $result->fields
= array();
3793 $submitteddata = array();
3794 foreach ($datarecord as $fieldname => $fieldvalue) {
3795 if (strpos($fieldname, '_')) {
3796 $namearray = explode('_', $fieldname, 3);
3797 $fieldid = $namearray[1];
3798 if (!isset($submitteddata[$fieldid])) {
3799 $submitteddata[$fieldid] = array();
3801 if (count($namearray) === 2) {
3804 $subfieldid = $namearray[2];
3807 $fielddata = new stdClass();
3808 $fielddata->fieldname
= $fieldname;
3809 $fielddata->value
= $fieldvalue;
3810 $submitteddata[$fieldid][$subfieldid] = $fielddata;
3814 // Check all form fields which have the required are filled.
3815 foreach ($fields as $fieldrecord) {
3816 // Check whether the field has any data.
3817 $fieldhascontent = false;
3819 $field = data_get_field($fieldrecord, $mod);
3820 if (isset($submitteddata[$fieldrecord->id
])) {
3821 foreach ($submitteddata[$fieldrecord->id
] as $fieldname => $value) {
3822 if ($field->notemptyfield($value->value
, $value->fieldname
)) {
3823 // The field has content and the form is not empty.
3824 $fieldhascontent = true;
3830 // If the field is required, add a notification to that effect.
3831 if ($field->field
->required
&& !$fieldhascontent) {
3832 if (!isset($result->fieldnotifications
[$field->field
->name
])) {
3833 $result->fieldnotifications
[$field->field
->name
] = array();
3835 $result->fieldnotifications
[$field->field
->name
][] = get_string('errormustsupplyvalue', 'data');
3836 $requiredfieldsfilled = false;
3839 // Update the field.
3840 if (isset($submitteddata[$fieldrecord->id
])) {
3841 foreach ($submitteddata[$fieldrecord->id
] as $value) {
3842 $result->fields
[$value->fieldname
] = $field;
3848 // The form is empty.
3849 $result->generalnotifications
[] = get_string('emptyaddform', 'data');
3852 $result->validated
= $requiredfieldsfilled && !$emptyform;