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
= '';
145 * Set up the field object according to data in an object. Now is the time to clean it!
149 function define_field($data) {
150 $this->field
->type
= $this->type
;
151 $this->field
->dataid
= $this->data
->id
;
153 $this->field
->name
= trim($data->name
);
154 $this->field
->description
= trim($data->description
);
156 if (isset($data->param1
)) {
157 $this->field
->param1
= trim($data->param1
);
159 if (isset($data->param2
)) {
160 $this->field
->param2
= trim($data->param2
);
162 if (isset($data->param3
)) {
163 $this->field
->param3
= trim($data->param3
);
165 if (isset($data->param4
)) {
166 $this->field
->param4
= trim($data->param4
);
168 if (isset($data->param5
)) {
169 $this->field
->param5
= trim($data->param5
);
176 * Insert a new field in the database
177 * We assume the field object is already defined as $this->field
182 function insert_field() {
185 if (empty($this->field
)) {
186 echo $OUTPUT->notification('Programmer error: Field has not been defined yet! See define_field()');
190 $this->field
->id
= $DB->insert_record('data_fields',$this->field
);
192 // Trigger an event for creating this field.
193 $event = \mod_data\event\field_created
::create(array(
194 'objectid' => $this->field
->id
,
195 'context' => $this->context
,
197 'fieldname' => $this->field
->name
,
198 'dataid' => $this->data
->id
208 * Update a field in the database
213 function update_field() {
216 $DB->update_record('data_fields', $this->field
);
218 // Trigger an event for updating this field.
219 $event = \mod_data\event\field_updated
::create(array(
220 'objectid' => $this->field
->id
,
221 'context' => $this->context
,
223 'fieldname' => $this->field
->name
,
224 'dataid' => $this->data
->id
233 * Delete a field completely
238 function delete_field() {
241 if (!empty($this->field
->id
)) {
242 // Get the field before we delete it.
243 $field = $DB->get_record('data_fields', array('id' => $this->field
->id
));
245 $this->delete_content();
246 $DB->delete_records('data_fields', array('id'=>$this->field
->id
));
248 // Trigger an event for deleting this field.
249 $event = \mod_data\event\field_deleted
::create(array(
250 'objectid' => $this->field
->id
,
251 'context' => $this->context
,
253 'fieldname' => $this->field
->name
,
254 'dataid' => $this->data
->id
257 $event->add_record_snapshot('data_fields', $field);
265 * Print the relevant form element in the ADD template for this field
268 * @param int $recordid
271 function display_add_field($recordid=0){
275 $content = $DB->get_field('data_content', 'content', array('fieldid'=>$this->field
->id
, 'recordid'=>$recordid));
280 // beware get_field returns false for new, empty records MDL-18567
281 if ($content===false) {
285 $str = '<div title="'.s($this->field
->description
).'">';
286 $str .= '<label class="accesshide" for="field_'.$this->field
->id
.'">'.$this->field
->description
.'</label>';
287 $str .= '<input class="basefieldinput" type="text" name="field_'.$this->field
->id
.'" id="field_'.$this->field
->id
.'" value="'.s($content).'" />';
294 * Print the relevant form element to define the attributes for this field
295 * viewable by teachers only.
299 * @return void Output is echo'd
301 function display_edit_field() {
302 global $CFG, $DB, $OUTPUT;
304 if (empty($this->field
)) { // No field has been defined yet, try and make one
305 $this->define_default_field();
307 echo $OUTPUT->box_start('generalbox boxaligncenter boxwidthwide');
309 echo '<form id="editfield" action="'.$CFG->wwwroot
.'/mod/data/field.php" method="post">'."\n";
310 echo '<input type="hidden" name="d" value="'.$this->data
->id
.'" />'."\n";
311 if (empty($this->field
->id
)) {
312 echo '<input type="hidden" name="mode" value="add" />'."\n";
313 $savebutton = get_string('add');
315 echo '<input type="hidden" name="fid" value="'.$this->field
->id
.'" />'."\n";
316 echo '<input type="hidden" name="mode" value="update" />'."\n";
317 $savebutton = get_string('savechanges');
319 echo '<input type="hidden" name="type" value="'.$this->type
.'" />'."\n";
320 echo '<input name="sesskey" value="'.sesskey().'" type="hidden" />'."\n";
322 echo $OUTPUT->heading($this->name(), 3);
324 require_once($CFG->dirroot
.'/mod/data/field/'.$this->type
.'/mod.html');
326 echo '<div class="mdl-align">';
327 echo '<input type="submit" value="'.$savebutton.'" />'."\n";
328 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />'."\n";
333 echo $OUTPUT->box_end();
337 * Display the content of the field in browse mode
340 * @param int $recordid
341 * @param object $template
342 * @return bool|string
344 function display_browse_field($recordid, $template) {
347 if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field
->id
, 'recordid'=>$recordid))) {
348 if (isset($content->content
)) {
349 $options = new stdClass();
350 if ($this->field
->param1
== '1') { // We are autolinking this field, so disable linking within us
351 //$content->content = '<span class="nolink">'.$content->content.'</span>';
352 //$content->content1 = FORMAT_HTML;
353 $options->filter
=false;
355 $options->para
= false;
356 $str = format_text($content->content
, $content->content1
, $options);
366 * Update the content of one data field in the data_content table
368 * @param int $recordid
369 * @param mixed $value
370 * @param string $name
373 function update_content($recordid, $value, $name=''){
376 $content = new stdClass();
377 $content->fieldid
= $this->field
->id
;
378 $content->recordid
= $recordid;
379 $content->content
= clean_param($value, PARAM_NOTAGS
);
381 if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field
->id
, 'recordid'=>$recordid))) {
382 $content->id
= $oldcontent->id
;
383 return $DB->update_record('data_content', $content);
385 return $DB->insert_record('data_content', $content);
390 * Delete all content associated with the field
393 * @param int $recordid
396 function delete_content($recordid=0) {
400 $conditions = array('fieldid'=>$this->field
->id
, 'recordid'=>$recordid);
402 $conditions = array('fieldid'=>$this->field
->id
);
405 $rs = $DB->get_recordset('data_content', $conditions);
407 $fs = get_file_storage();
408 foreach ($rs as $content) {
409 $fs->delete_area_files($this->context
->id
, 'mod_data', 'content', $content->id
);
414 return $DB->delete_records('data_content', $conditions);
418 * Check if a field from an add form is empty
420 * @param mixed $value
424 function notemptyfield($value, $name) {
425 return !empty($value);
429 * Just in case a field needs to print something before the whole form
431 function print_before_form() {
435 * Just in case a field needs to print something after the whole form
437 function print_after_form() {
442 * Returns the sortable field for the content. By default, it's just content
443 * but for some plugins, it could be content 1 - content4
447 function get_sort_field() {
452 * Returns the SQL needed to refer to the column. Some fields may need to CAST() etc.
454 * @param string $fieldname
455 * @return string $fieldname
457 function get_sort_sql($fieldname) {
462 * Returns the name/type of the field
467 return get_string('name'.$this->type
, 'data');
471 * Prints the respective type icon
479 $params = array('d'=>$this->data
->id
, 'fid'=>$this->field
->id
, 'mode'=>'display', 'sesskey'=>sesskey());
480 $link = new moodle_url('/mod/data/field.php', $params);
481 $str = '<a href="'.$link->out().'">';
482 $str .= '<img src="'.$OUTPUT->pix_url('field/'.$this->type
, 'data') . '" ';
483 $str .= 'height="'.$this->iconheight
.'" width="'.$this->iconwidth
.'" alt="'.$this->type
.'" title="'.$this->type
.'" /></a>';
488 * Per default, it is assumed that fields support text exporting.
489 * Override this (return false) on fields not supporting text exporting.
493 function text_export_supported() {
498 * Per default, return the record's text value only from the "content" field.
499 * Override this in fields class if necesarry.
501 * @param string $record
504 function export_text_value($record) {
505 if ($this->text_export_supported()) {
506 return $record->content
;
511 * @param string $relativepath
514 function file_ok($relativepath) {
521 * Given a template and a dataid, generate a default case template
524 * @param object $data
525 * @param string template [addtemplate, singletemplate, listtempalte, rsstemplate]
526 * @param int $recordid
528 * @param bool $update
529 * @return bool|string
531 function data_generate_default_template(&$data, $template, $recordid=0, $form=false, $update=true) {
534 if (!$data && !$template) {
537 if ($template == 'csstemplate' or $template == 'jstemplate' ) {
541 // get all the fields for that database
542 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id
), 'id')) {
544 $table = new html_table();
545 $table->attributes
['class'] = 'mod-data-default-template';
546 $table->colclasses
= array('template-field', 'template-token');
547 $table->data
= array();
548 foreach ($fields as $field) {
549 if ($form) { // Print forms instead of data
550 $fieldobj = data_get_field($field, $data);
551 $token = $fieldobj->display_add_field($recordid);
552 } else { // Just print the tag
553 $token = '[['.$field->name
.']]';
555 $table->data
[] = array(
560 if ($template == 'listtemplate') {
561 $cell = new html_table_cell('##edit## ##more## ##delete## ##approve## ##disapprove## ##export##');
563 $cell->attributes
['class'] = 'controls';
564 $table->data
[] = new html_table_row(array($cell));
565 } else if ($template == 'singletemplate') {
566 $cell = new html_table_cell('##edit## ##delete## ##approve## ##disapprove## ##export##');
568 $cell->attributes
['class'] = 'controls';
569 $table->data
[] = new html_table_row(array($cell));
570 } else if ($template == 'asearchtemplate') {
571 $row = new html_table_row(array(get_string('authorfirstname', 'data').': ', '##firstname##'));
572 $row->attributes
['class'] = 'searchcontrols';
573 $table->data
[] = $row;
574 $row = new html_table_row(array(get_string('authorlastname', 'data').': ', '##lastname##'));
575 $row->attributes
['class'] = 'searchcontrols';
576 $table->data
[] = $row;
580 if ($template == 'listtemplate'){
581 $str .= '##delcheck##';
582 $str .= html_writer
::empty_tag('br');
585 $str .= html_writer
::start_tag('div', array('class' => 'defaulttemplate'));
586 $str .= html_writer
::table($table);
587 $str .= html_writer
::end_tag('div');
588 if ($template == 'listtemplate'){
589 $str .= html_writer
::empty_tag('hr');
593 $newdata = new stdClass();
594 $newdata->id
= $data->id
;
595 $newdata->{$template} = $str;
596 $DB->update_record('data', $newdata);
597 $data->{$template} = $str;
606 * Search for a field name and replaces it with another one in all the
607 * form templates. Set $newfieldname as '' if you want to delete the
608 * field from the form.
611 * @param object $data
612 * @param string $searchfieldname
613 * @param string $newfieldname
616 function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
619 if (!empty($newfieldname)) {
630 $newdata = new stdClass();
631 $newdata->id
= $data->id
;
632 $newdata->singletemplate
= str_ireplace('[['.$searchfieldname.']]',
633 $prestring.$newfieldname.$poststring, $data->singletemplate
);
635 $newdata->listtemplate
= str_ireplace('[['.$searchfieldname.']]',
636 $prestring.$newfieldname.$poststring, $data->listtemplate
);
638 $newdata->addtemplate
= str_ireplace('[['.$searchfieldname.']]',
639 $prestring.$newfieldname.$poststring, $data->addtemplate
);
641 $newdata->addtemplate
= str_ireplace('[['.$searchfieldname.'#id]]',
642 $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate
);
644 $newdata->rsstemplate
= str_ireplace('[['.$searchfieldname.']]',
645 $prestring.$newfieldname.$poststring, $data->rsstemplate
);
647 return $DB->update_record('data', $newdata);
652 * Appends a new field at the end of the form template.
655 * @param object $data
656 * @param string $newfieldname
658 function data_append_new_field_to_templates($data, $newfieldname) {
661 $newdata = new stdClass();
662 $newdata->id
= $data->id
;
665 if (!empty($data->singletemplate
)) {
666 $newdata->singletemplate
= $data->singletemplate
.' [[' . $newfieldname .']]';
669 if (!empty($data->addtemplate
)) {
670 $newdata->addtemplate
= $data->addtemplate
.' [[' . $newfieldname . ']]';
673 if (!empty($data->rsstemplate
)) {
674 $newdata->rsstemplate
= $data->singletemplate
.' [[' . $newfieldname . ']]';
678 $DB->update_record('data', $newdata);
685 * this function creates an instance of the particular subfield class
688 * @param string $name
689 * @param object $data
690 * @return object|bool
692 function data_get_field_from_name($name, $data){
695 $field = $DB->get_record('data_fields', array('name'=>$name, 'dataid'=>$data->id
));
698 return data_get_field($field, $data);
706 * this function creates an instance of the particular subfield class
709 * @param int $fieldid
710 * @param object $data
711 * @return bool|object
713 function data_get_field_from_id($fieldid, $data){
716 $field = $DB->get_record('data_fields', array('id'=>$fieldid, 'dataid'=>$data->id
));
719 return data_get_field($field, $data);
727 * this function creates an instance of the particular subfield class
730 * @param string $type
731 * @param object $data
734 function data_get_field_new($type, $data) {
737 require_once($CFG->dirroot
.'/mod/data/field/'.$type.'/field.class.php');
738 $newfield = 'data_field_'.$type;
739 $newfield = new $newfield(0, $data);
744 * returns a subclass field object given a record of the field, used to
745 * invoke plugin methods
746 * input: $param $field - record from db
749 * @param object $field
750 * @param object $data
754 function data_get_field($field, $data, $cm=null) {
758 require_once('field/'.$field->type
.'/field.class.php');
759 $newfield = 'data_field_'.$field->type
;
760 $newfield = new $newfield($field, $data, $cm);
767 * Given record object (or id), returns true if the record belongs to the current user
771 * @param mixed $record record object or id
774 function data_isowner($record) {
777 if (!isloggedin()) { // perf shortcut
781 if (!is_object($record)) {
782 if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
787 return ($record->userid
== $USER->id
);
791 * has a user reached the max number of entries?
793 * @param object $data
796 function data_atmaxentries($data){
797 if (!$data->maxentries
){
801 return (data_numentries($data) >= $data->maxentries
);
806 * returns the number of entries already made by this user
810 * @param object $data
813 function data_numentries($data){
815 $sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
816 return $DB->count_records_sql($sql, array($data->id
, $USER->id
));
820 * function that takes in a dataid and adds a record
821 * this is used everytime an add template is submitted
825 * @param object $data
826 * @param int $groupid
829 function data_add_record($data, $groupid=0){
832 $cm = get_coursemodule_from_instance('data', $data->id
);
833 $context = context_module
::instance($cm->id
);
835 $record = new stdClass();
836 $record->userid
= $USER->id
;
837 $record->dataid
= $data->id
;
838 $record->groupid
= $groupid;
839 $record->timecreated
= $record->timemodified
= time();
840 if (has_capability('mod/data:approve', $context)) {
841 $record->approved
= 1;
843 $record->approved
= 0;
845 $record->id
= $DB->insert_record('data_records', $record);
847 // Trigger an event for creating this record.
848 $event = \mod_data\event\record_created
::create(array(
849 'objectid' => $record->id
,
850 'context' => $context,
852 'dataid' => $data->id
861 * check the multple existence any tag in a template
863 * check to see if there are 2 or more of the same tag being used.
866 * @param int $dataid,
867 * @param string $template
870 function data_tags_check($dataid, $template) {
873 // first get all the possible tags
874 $fields = $DB->get_records('data_fields', array('dataid'=>$dataid));
875 // then we generate strings to replace
876 $tagsok = true; // let's be optimistic
877 foreach ($fields as $field){
878 $pattern="/\[\[".$field->name
."\]\]/i";
879 if (preg_match_all($pattern, $template, $dummy)>1){
881 echo $OUTPUT->notification('[['.$field->name
.']] - '.get_string('multipletags','data'));
889 * Adds an instance of a data
891 * @param stdClass $data
892 * @param mod_data_mod_form $mform
893 * @return int intance id
895 function data_add_instance($data, $mform = null) {
898 if (empty($data->assessed
)) {
902 $data->timemodified
= time();
904 $data->id
= $DB->insert_record('data', $data);
906 data_grade_item_update($data);
912 * updates an instance of a data
915 * @param object $data
918 function data_update_instance($data) {
921 $data->timemodified
= time();
922 $data->id
= $data->instance
;
924 if (empty($data->assessed
)) {
928 if (empty($data->ratingtime
) or empty($data->assessed
)) {
929 $data->assesstimestart
= 0;
930 $data->assesstimefinish
= 0;
933 if (empty($data->notification
)) {
934 $data->notification
= 0;
937 $DB->update_record('data', $data);
939 data_grade_item_update($data);
946 * deletes an instance of a data
952 function data_delete_instance($id) { // takes the dataid
955 if (!$data = $DB->get_record('data', array('id'=>$id))) {
959 $cm = get_coursemodule_from_instance('data', $data->id
);
960 $context = context_module
::instance($cm->id
);
962 /// Delete all the associated information
965 $fs = get_file_storage();
966 $fs->delete_area_files($context->id
, 'mod_data');
968 // get all the records in this data
970 FROM {data_records} r
973 $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
975 // delete all the records and fields
976 $DB->delete_records('data_records', array('dataid'=>$id));
977 $DB->delete_records('data_fields', array('dataid'=>$id));
979 // Delete the instance itself
980 $result = $DB->delete_records('data', array('id'=>$id));
983 data_grade_item_delete($data);
989 * returns a summary of data activity of this user
992 * @param object $course
993 * @param object $user
995 * @param object $data
996 * @return object|null
998 function data_user_outline($course, $user, $mod, $data) {
1000 require_once("$CFG->libdir/gradelib.php");
1002 $grades = grade_get_grades($course->id
, 'mod', 'data', $data->id
, $user->id
);
1003 if (empty($grades->items
[0]->grades
)) {
1006 $grade = reset($grades->items
[0]->grades
);
1010 if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id
, 'userid'=>$user->id
))) {
1011 $result = new stdClass();
1012 $result->info
= get_string('numrecords', 'data', $countrecords);
1013 $lastrecord = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
1014 WHERE dataid = ? AND userid = ?
1015 ORDER BY timemodified DESC', array($data->id
, $user->id
), true);
1016 $result->time
= $lastrecord->timemodified
;
1018 $result->info
.= ', ' . get_string('grade') . ': ' . $grade->str_long_grade
;
1021 } else if ($grade) {
1022 $result = new stdClass();
1023 $result->info
= get_string('grade') . ': ' . $grade->str_long_grade
;
1025 //datesubmitted == time created. dategraded == time modified or time overridden
1026 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
1027 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
1028 if ($grade->usermodified
== $user->id ||
empty($grade->datesubmitted
)) {
1029 $result->time
= $grade->dategraded
;
1031 $result->time
= $grade->datesubmitted
;
1040 * Prints all the records uploaded by this user
1043 * @param object $course
1044 * @param object $user
1045 * @param object $mod
1046 * @param object $data
1048 function data_user_complete($course, $user, $mod, $data) {
1049 global $DB, $CFG, $OUTPUT;
1050 require_once("$CFG->libdir/gradelib.php");
1052 $grades = grade_get_grades($course->id
, 'mod', 'data', $data->id
, $user->id
);
1053 if (!empty($grades->items
[0]->grades
)) {
1054 $grade = reset($grades->items
[0]->grades
);
1055 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade
);
1056 if ($grade->str_feedback
) {
1057 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
1061 if ($records = $DB->get_records('data_records', array('dataid'=>$data->id
,'userid'=>$user->id
), 'timemodified DESC')) {
1062 data_print_template('singletemplate', $records, $data);
1067 * Return grade for given user or all users.
1070 * @param object $data
1071 * @param int $userid optional user id, 0 means all users
1072 * @return array array of grades, false if none
1074 function data_get_user_grades($data, $userid=0) {
1077 require_once($CFG->dirroot
.'/rating/lib.php');
1079 $ratingoptions = new stdClass
;
1080 $ratingoptions->component
= 'mod_data';
1081 $ratingoptions->ratingarea
= 'entry';
1082 $ratingoptions->modulename
= 'data';
1083 $ratingoptions->moduleid
= $data->id
;
1085 $ratingoptions->userid
= $userid;
1086 $ratingoptions->aggregationmethod
= $data->assessed
;
1087 $ratingoptions->scaleid
= $data->scale
;
1088 $ratingoptions->itemtable
= 'data_records';
1089 $ratingoptions->itemtableusercolumn
= 'userid';
1091 $rm = new rating_manager();
1092 return $rm->get_user_grades($ratingoptions);
1096 * Update activity grades
1099 * @param object $data
1100 * @param int $userid specific user only, 0 means all
1101 * @param bool $nullifnone
1103 function data_update_grades($data, $userid=0, $nullifnone=true) {
1105 require_once($CFG->libdir
.'/gradelib.php');
1107 if (!$data->assessed
) {
1108 data_grade_item_update($data);
1110 } else if ($grades = data_get_user_grades($data, $userid)) {
1111 data_grade_item_update($data, $grades);
1113 } else if ($userid and $nullifnone) {
1114 $grade = new stdClass();
1115 $grade->userid
= $userid;
1116 $grade->rawgrade
= NULL;
1117 data_grade_item_update($data, $grade);
1120 data_grade_item_update($data);
1125 * Update/create grade item for given data
1128 * @param stdClass $data A database instance with extra cmidnumber property
1129 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1130 * @return object grade_item
1132 function data_grade_item_update($data, $grades=NULL) {
1134 require_once($CFG->libdir
.'/gradelib.php');
1136 $params = array('itemname'=>$data->name
, 'idnumber'=>$data->cmidnumber
);
1138 if (!$data->assessed
or $data->scale
== 0) {
1139 $params['gradetype'] = GRADE_TYPE_NONE
;
1141 } else if ($data->scale
> 0) {
1142 $params['gradetype'] = GRADE_TYPE_VALUE
;
1143 $params['grademax'] = $data->scale
;
1144 $params['grademin'] = 0;
1146 } else if ($data->scale
< 0) {
1147 $params['gradetype'] = GRADE_TYPE_SCALE
;
1148 $params['scaleid'] = -$data->scale
;
1151 if ($grades === 'reset') {
1152 $params['reset'] = true;
1156 return grade_update('mod/data', $data->course
, 'mod', 'data', $data->id
, 0, $grades, $params);
1160 * Delete grade item for given data
1163 * @param object $data object
1164 * @return object grade_item
1166 function data_grade_item_delete($data) {
1168 require_once($CFG->libdir
.'/gradelib.php');
1170 return grade_update('mod/data', $data->course
, 'mod', 'data', $data->id
, 0, NULL, array('deleted'=>1));
1175 * takes a list of records, the current data, a search string,
1176 * and mode to display prints the translated template
1180 * @param string $template
1181 * @param array $records
1182 * @param object $data
1183 * @param string $search
1185 * @param bool $return
1186 * @param object $jumpurl a moodle_url by which to jump back to the record list (can be null)
1189 function data_print_template($template, $records, $data, $search='', $page=0, $return=false, moodle_url
$jumpurl=null) {
1190 global $CFG, $DB, $OUTPUT;
1192 $cm = get_coursemodule_from_instance('data', $data->id
);
1193 $context = context_module
::instance($cm->id
);
1195 static $fields = NULL;
1197 static $dataid = NULL;
1199 if (empty($dataid)) {
1200 $dataid = $data->id
;
1201 } else if ($dataid != $data->id
) {
1205 if (empty($fields)) {
1206 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id
));
1207 foreach ($fieldrecords as $fieldrecord) {
1208 $fields[]= data_get_field($fieldrecord, $data);
1210 $isteacher = has_capability('mod/data:managetemplates', $context);
1213 if (empty($records)) {
1218 $jumpurl = new moodle_url('/mod/data/view.php', array('d' => $data->id
));
1220 $jumpurl = new moodle_url($jumpurl, array('page' => $page, 'sesskey' => sesskey()));
1222 // Check whether this activity is read-only at present
1223 $readonly = data_in_readonly_period($data);
1225 foreach ($records as $record) { // Might be just one for the single template
1228 $patterns = array();
1229 $replacement = array();
1231 // Then we generate strings to replace for normal tags
1232 foreach ($fields as $field) {
1233 $patterns[]='[['.$field->field
->name
.']]';
1234 $replacement[] = highlight($search, $field->display_browse_field($record->id
, $template));
1237 $canmanageentries = has_capability('mod/data:manageentries', $context);
1239 // Replacing special tags (##Edit##, ##Delete##, ##More##)
1240 $patterns[]='##edit##';
1241 $patterns[]='##delete##';
1242 if ($canmanageentries ||
(!$readonly && data_isowner($record->id
))) {
1243 $replacement[] = '<a href="'.$CFG->wwwroot
.'/mod/data/edit.php?d='
1244 .$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>';
1245 $replacement[] = '<a href="'.$CFG->wwwroot
.'/mod/data/view.php?d='
1246 .$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>';
1248 $replacement[] = '';
1249 $replacement[] = '';
1252 $moreurl = $CFG->wwwroot
. '/mod/data/view.php?d=' . $data->id
. '&rid=' . $record->id
;
1254 $moreurl .= '&filter=1';
1256 $patterns[]='##more##';
1257 $replacement[] = '<a href="'.$moreurl.'"><img src="'.$OUTPUT->pix_url('t/preview').
1258 '" class="iconsmall" alt="'.get_string('more', 'data').'" title="'.get_string('more', 'data').
1261 $patterns[]='##moreurl##';
1262 $replacement[] = $moreurl;
1264 $patterns[]='##delcheck##';
1265 if ($canmanageentries) {
1266 $replacement[] = html_writer
::checkbox('delcheck[]', $record->id
, false, '', array('class' => 'recordcheckbox'));
1268 $replacement[] = '';
1271 $patterns[]='##user##';
1272 $replacement[] = '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.$record->userid
.
1273 '&course='.$data->course
.'">'.fullname($record).'</a>';
1275 $patterns[] = '##userpicture##';
1276 $ruser = $DB->get_record('user', array('id' => $record->userid
));
1277 $replacement[] = $OUTPUT->user_picture($ruser, array('courseid' => $cm->id
));
1279 $patterns[]='##export##';
1281 if (!empty($CFG->enableportfolios
) && ($template == 'singletemplate' ||
$template == 'listtemplate')
1282 && ((has_capability('mod/data:exportentry', $context)
1283 ||
(data_isowner($record->id
) && has_capability('mod/data:exportownentry', $context))))) {
1284 require_once($CFG->libdir
. '/portfoliolib.php');
1285 $button = new portfolio_add_button();
1286 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id
, 'recordid' => $record->id
), 'mod_data');
1287 list($formats, $files) = data_portfolio_caller
::formats($fields, $record);
1288 $button->set_formats($formats);
1289 $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK
);
1291 $replacement[] = '';
1294 $patterns[] = '##timeadded##';
1295 $replacement[] = userdate($record->timecreated
);
1297 $patterns[] = '##timemodified##';
1298 $replacement [] = userdate($record->timemodified
);
1300 $patterns[]='##approve##';
1301 if (has_capability('mod/data:approve', $context) && ($data->approval
) && (!$record->approved
)) {
1302 $approveurl = new moodle_url($jumpurl, array('approve' => $record->id
));
1303 $approveicon = new pix_icon('t/approve', get_string('approve', 'data'), '', array('class' => 'iconsmall'));
1304 $replacement[] = html_writer
::tag('span', $OUTPUT->action_icon($approveurl, $approveicon),
1305 array('class' => 'approve'));
1307 $replacement[] = '';
1310 $patterns[]='##disapprove##';
1311 if (has_capability('mod/data:approve', $context) && ($data->approval
) && ($record->approved
)) {
1312 $disapproveurl = new moodle_url($jumpurl, array('disapprove' => $record->id
));
1313 $disapproveicon = new pix_icon('t/block', get_string('disapprove', 'data'), '', array('class' => 'iconsmall'));
1314 $replacement[] = html_writer
::tag('span', $OUTPUT->action_icon($disapproveurl, $disapproveicon),
1315 array('class' => 'disapprove'));
1317 $replacement[] = '';
1320 $patterns[]='##comments##';
1321 if (($template == 'listtemplate') && ($data->comments
)) {
1323 if (!empty($CFG->usecomments
)) {
1324 require_once($CFG->dirroot
. '/comment/lib.php');
1325 list($context, $course, $cm) = get_context_info_array($context->id
);
1326 $cmt = new stdClass();
1327 $cmt->context
= $context;
1328 $cmt->course
= $course;
1330 $cmt->area
= 'database_entry';
1331 $cmt->itemid
= $record->id
;
1332 $cmt->showcount
= true;
1333 $cmt->component
= 'mod_data';
1334 $comment = new comment($cmt);
1335 $replacement[] = $comment->output(true);
1338 $replacement[] = '';
1341 // actual replacement of the tags
1342 $newtext = str_ireplace($patterns, $replacement, $data->{$template});
1344 // no more html formatting and filtering - see MDL-6635
1350 // hack alert - return is always false in singletemplate anyway ;-)
1351 /**********************************
1352 * Printing Ratings Form *
1353 *********************************/
1354 if ($template == 'singletemplate') { //prints ratings options
1355 data_print_ratings($data, $record);
1358 /**********************************
1359 * Printing Comments Form *
1360 *********************************/
1361 if (($template == 'singletemplate') && ($data->comments
)) {
1362 if (!empty($CFG->usecomments
)) {
1363 require_once($CFG->dirroot
. '/comment/lib.php');
1364 list($context, $course, $cm) = get_context_info_array($context->id
);
1365 $cmt = new stdClass();
1366 $cmt->context
= $context;
1367 $cmt->course
= $course;
1369 $cmt->area
= 'database_entry';
1370 $cmt->itemid
= $record->id
;
1371 $cmt->showcount
= true;
1372 $cmt->component
= 'mod_data';
1373 $comment = new comment($cmt);
1374 $comment->output(false);
1382 * Return rating related permissions
1384 * @param string $contextid the context id
1385 * @param string $component the component to get rating permissions for
1386 * @param string $ratingarea the rating area to get permissions for
1387 * @return array an associative array of the user's rating permissions
1389 function data_rating_permissions($contextid, $component, $ratingarea) {
1390 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1391 if ($component != 'mod_data' ||
$ratingarea != 'entry') {
1395 'view' => has_capability('mod/data:viewrating',$context),
1396 'viewany' => has_capability('mod/data:viewanyrating',$context),
1397 'viewall' => has_capability('mod/data:viewallratings',$context),
1398 'rate' => has_capability('mod/data:rate',$context)
1403 * Validates a submitted rating
1404 * @param array $params submitted data
1405 * context => object the context in which the rated items exists [required]
1406 * itemid => int the ID of the object being rated
1407 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1408 * rating => int the submitted rating
1409 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1410 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
1411 * @return boolean true if the rating is valid. Will throw rating_exception if not
1413 function data_rating_validate($params) {
1416 // Check the component is mod_data
1417 if ($params['component'] != 'mod_data') {
1418 throw new rating_exception('invalidcomponent');
1421 // Check the ratingarea is entry (the only rating area in data module)
1422 if ($params['ratingarea'] != 'entry') {
1423 throw new rating_exception('invalidratingarea');
1426 // Check the rateduserid is not the current user .. you can't rate your own entries
1427 if ($params['rateduserid'] == $USER->id
) {
1428 throw new rating_exception('nopermissiontorate');
1431 $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
1432 FROM {data_records} r
1433 JOIN {data} d ON r.dataid = d.id
1434 WHERE r.id = :itemid";
1435 $dataparams = array('itemid'=>$params['itemid']);
1436 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1437 //item doesn't exist
1438 throw new rating_exception('invaliditemid');
1441 if ($info->scale
!= $params['scaleid']) {
1442 //the scale being submitted doesnt match the one in the database
1443 throw new rating_exception('invalidscaleid');
1446 //check that the submitted rating is valid for the scale
1449 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING
) {
1450 throw new rating_exception('invalidnum');
1454 if ($info->scale
< 0) {
1455 //its a custom scale
1456 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale
));
1458 $scalearray = explode(',', $scalerecord->scale
);
1459 if ($params['rating'] > count($scalearray)) {
1460 throw new rating_exception('invalidnum');
1463 throw new rating_exception('invalidscaleid');
1465 } else if ($params['rating'] > $info->scale
) {
1466 //if its numeric and submitted rating is above maximum
1467 throw new rating_exception('invalidnum');
1470 if ($info->approval
&& !$info->approved
) {
1471 //database requires approval but this item isnt approved
1472 throw new rating_exception('nopermissiontorate');
1475 // check the item we're rating was created in the assessable time window
1476 if (!empty($info->assesstimestart
) && !empty($info->assesstimefinish
)) {
1477 if ($info->timecreated
< $info->assesstimestart ||
$info->timecreated
> $info->assesstimefinish
) {
1478 throw new rating_exception('notavailable');
1482 $course = $DB->get_record('course', array('id'=>$info->course
), '*', MUST_EXIST
);
1483 $cm = get_coursemodule_from_instance('data', $info->dataid
, $course->id
, false, MUST_EXIST
);
1484 $context = context_module
::instance($cm->id
);
1486 // if the supplied context doesnt match the item's context
1487 if ($context->id
!= $params['context']->id
) {
1488 throw new rating_exception('invalidcontext');
1491 // Make sure groups allow this user to see the item they're rating
1492 $groupid = $info->groupid
;
1493 if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
1494 if (!groups_group_exists($groupid)) { // Can't find group
1495 throw new rating_exception('cannotfindgroup');//something is wrong
1498 if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1499 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
1500 throw new rating_exception('notmemberofgroup');
1509 * function that takes in the current data, number of items per page,
1510 * a search string and prints a preference box in view.php
1512 * This preference box prints a searchable advanced search template if
1513 * a) A template is defined
1514 * b) The advanced search checkbox is checked.
1518 * @param object $data
1519 * @param int $perpage
1520 * @param string $search
1521 * @param string $sort
1522 * @param string $order
1523 * @param array $search_array
1524 * @param int $advanced
1525 * @param string $mode
1528 function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
1529 global $CFG, $DB, $PAGE, $OUTPUT;
1531 $cm = get_coursemodule_from_instance('data', $data->id
);
1532 $context = context_module
::instance($cm->id
);
1533 echo '<br /><div class="datapreferences">';
1534 echo '<form id="options" action="view.php" method="get">';
1536 echo '<input type="hidden" name="d" value="'.$data->id
.'" />';
1537 if ($mode =='asearch') {
1539 echo '<input type="hidden" name="mode" value="list" />';
1541 echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
1542 $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
1543 20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
1544 echo html_writer
::select($pagesizes, 'perpage', $perpage, false, array('id'=>'pref_perpage'));
1547 $regsearchclass = 'search_none';
1548 $advancedsearchclass = 'search_inline';
1550 $regsearchclass = 'search_inline';
1551 $advancedsearchclass = 'search_none';
1553 echo '<div id="reg_search" class="' . $regsearchclass . '" > ';
1554 echo '<label for="pref_search">'.get_string('search').'</label> <input type="text" size="16" name="search" id= "pref_search" value="'.s($search).'" /></div>';
1555 echo ' <label for="pref_sortby">'.get_string('sortby').'</label> ';
1556 // foreach field, print the option
1557 echo '<select name="sort" id="pref_sortby">';
1558 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id
), 'name')) {
1559 echo '<optgroup label="'.get_string('fields', 'data').'">';
1560 foreach ($fields as $field) {
1561 if ($field->id
== $sort) {
1562 echo '<option value="'.$field->id
.'" selected="selected">'.$field->name
.'</option>';
1564 echo '<option value="'.$field->id
.'">'.$field->name
.'</option>';
1570 $options[DATA_TIMEADDED
] = get_string('timeadded', 'data');
1571 $options[DATA_TIMEMODIFIED
] = get_string('timemodified', 'data');
1572 $options[DATA_FIRSTNAME
] = get_string('authorfirstname', 'data');
1573 $options[DATA_LASTNAME
] = get_string('authorlastname', 'data');
1574 if ($data->approval
and has_capability('mod/data:approve', $context)) {
1575 $options[DATA_APPROVED
] = get_string('approved', 'data');
1577 echo '<optgroup label="'.get_string('other', 'data').'">';
1578 foreach ($options as $key => $name) {
1579 if ($key == $sort) {
1580 echo '<option value="'.$key.'" selected="selected">'.$name.'</option>';
1582 echo '<option value="'.$key.'">'.$name.'</option>';
1587 echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
1588 echo '<select id="pref_order" name="order">';
1589 if ($order == 'ASC') {
1590 echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
1592 echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1594 if ($order == 'DESC') {
1595 echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
1597 echo '<option value="DESC">'.get_string('descending','data').'</option>';
1602 $checked = ' checked="checked" ';
1607 $PAGE->requires
->js('/mod/data/data.js');
1608 echo ' <input type="hidden" name="advanced" value="0" />';
1609 echo ' <input type="hidden" name="filter" value="1" />';
1610 echo ' <input type="checkbox" id="advancedcheckbox" name="advanced" value="1" '.$checked.' onchange="showHideAdvSearch(this.checked);" /><label for="advancedcheckbox">'.get_string('advancedsearch', 'data').'</label>';
1611 echo ' <input type="submit" value="'.get_string('savesettings','data').'" />';
1614 echo '<div class="' . $advancedsearchclass . '" id="data_adv_form">';
1615 echo '<table class="boxaligncenter">';
1617 // print ASC or DESC
1618 echo '<tr><td colspan="2"> </td></tr>';
1621 // Determine if we are printing all fields for advanced search, or the template for advanced search
1622 // If a template is not defined, use the deafault template and display all fields.
1623 if(empty($data->asearchtemplate
)) {
1624 data_generate_default_template($data, 'asearchtemplate');
1627 static $fields = NULL;
1629 static $dataid = NULL;
1631 if (empty($dataid)) {
1632 $dataid = $data->id
;
1633 } else if ($dataid != $data->id
) {
1637 if (empty($fields)) {
1638 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id
));
1639 foreach ($fieldrecords as $fieldrecord) {
1640 $fields[]= data_get_field($fieldrecord, $data);
1643 $isteacher = has_capability('mod/data:managetemplates', $context);
1647 $patterns = array();
1648 $replacement = array();
1650 // Then we generate strings to replace for normal tags
1651 foreach ($fields as $field) {
1652 $fieldname = $field->field
->name
;
1653 $fieldname = preg_quote($fieldname, '/');
1654 $patterns[] = "/\[\[$fieldname\]\]/i";
1655 $searchfield = data_get_field_from_id($field->field
->id
, $data);
1656 if (!empty($search_array[$field->field
->id
]->data
)) {
1657 $replacement[] = $searchfield->display_search_field($search_array[$field->field
->id
]->data
);
1659 $replacement[] = $searchfield->display_search_field();
1662 $fn = !empty($search_array[DATA_FIRSTNAME
]->data
) ?
$search_array[DATA_FIRSTNAME
]->data
: '';
1663 $ln = !empty($search_array[DATA_LASTNAME
]->data
) ?
$search_array[DATA_LASTNAME
]->data
: '';
1664 $patterns[] = '/##firstname##/';
1665 $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.'" />';
1666 $patterns[] = '/##lastname##/';
1667 $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.'" />';
1669 // actual replacement of the tags
1670 $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate
);
1672 $options = new stdClass();
1673 $options->para
=false;
1674 $options->noclean
=true;
1676 echo format_text($newtext, FORMAT_HTML
, $options);
1679 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>';
1690 * @param object $data
1691 * @param object $record
1692 * @return void Output echo'd
1694 function data_print_ratings($data, $record) {
1696 if (!empty($record->rating
)){
1697 echo $OUTPUT->render($record->rating
);
1702 * List the actions that correspond to a view of this module.
1703 * This is used by the participation report.
1705 * Note: This is not used by new logging system. Event with
1706 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
1707 * be considered as view action.
1711 function data_get_view_actions() {
1712 return array('view');
1716 * List the actions that correspond to a post of this module.
1717 * This is used by the participation report.
1719 * Note: This is not used by new logging system. Event with
1720 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1721 * will be considered as post action.
1725 function data_get_post_actions() {
1726 return array('add','update','record delete');
1730 * @param string $name
1731 * @param int $dataid
1732 * @param int $fieldid
1735 function data_fieldname_exists($name, $dataid, $fieldid = 0) {
1738 if (!is_numeric($name)) {
1739 $like = $DB->sql_like('df.name', ':name', false);
1741 $like = "df.name = :name";
1743 $params = array('name'=>$name);
1745 $params['dataid'] = $dataid;
1746 $params['fieldid1'] = $fieldid;
1747 $params['fieldid2'] = $fieldid;
1748 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1749 WHERE $like AND df.dataid = :dataid
1750 AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
1752 $params['dataid'] = $dataid;
1753 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1754 WHERE $like AND df.dataid = :dataid", $params);
1759 * @param array $fieldinput
1761 function data_convert_arrays_to_strings(&$fieldinput) {
1762 foreach ($fieldinput as $key => $val) {
1763 if (is_array($val)) {
1765 foreach ($val as $inner) {
1766 $str .= $inner . ',';
1768 $str = substr($str, 0, -1);
1770 $fieldinput->$key = $str;
1777 * Converts a database (module instance) to use the Roles System
1781 * @uses CONTEXT_MODULE
1784 * @param object $data a data object with the same attributes as a record
1785 * from the data database table
1786 * @param int $datamodid the id of the data module, from the modules table
1787 * @param array $teacherroles array of roles that have archetype teacher
1788 * @param array $studentroles array of roles that have archetype student
1789 * @param array $guestroles array of roles that have archetype guest
1790 * @param int $cmid the course_module id for this data instance
1791 * @return boolean data module was converted or not
1793 function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
1794 global $CFG, $DB, $OUTPUT;
1796 if (!isset($data->participants
) && !isset($data->assesspublic
)
1797 && !isset($data->groupmode
)) {
1798 // We assume that this database has already been converted to use the
1799 // Roles System. above fields get dropped the data module has been
1800 // upgraded to use Roles.
1805 // We were not given the course_module id. Try to find it.
1806 if (!$cm = get_coursemodule_from_instance('data', $data->id
)) {
1807 echo $OUTPUT->notification('Could not get the course module for the data');
1813 $context = context_module
::instance($cmid);
1816 // $data->participants:
1817 // 1 - Only teachers can add entries
1818 // 3 - Teachers and students can add entries
1819 switch ($data->participants
) {
1821 foreach ($studentroles as $studentrole) {
1822 assign_capability('mod/data:writeentry', CAP_PREVENT
, $studentrole->id
, $context->id
);
1824 foreach ($teacherroles as $teacherrole) {
1825 assign_capability('mod/data:writeentry', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1829 foreach ($studentroles as $studentrole) {
1830 assign_capability('mod/data:writeentry', CAP_ALLOW
, $studentrole->id
, $context->id
);
1832 foreach ($teacherroles as $teacherrole) {
1833 assign_capability('mod/data:writeentry', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1839 // 2 - Only teachers can rate posts
1840 // 1 - Everyone can rate posts
1841 // 0 - No one can rate posts
1842 switch ($data->assessed
) {
1844 foreach ($studentroles as $studentrole) {
1845 assign_capability('mod/data:rate', CAP_PREVENT
, $studentrole->id
, $context->id
);
1847 foreach ($teacherroles as $teacherrole) {
1848 assign_capability('mod/data:rate', CAP_PREVENT
, $teacherrole->id
, $context->id
);
1852 foreach ($studentroles as $studentrole) {
1853 assign_capability('mod/data:rate', CAP_ALLOW
, $studentrole->id
, $context->id
);
1855 foreach ($teacherroles as $teacherrole) {
1856 assign_capability('mod/data:rate', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1860 foreach ($studentroles as $studentrole) {
1861 assign_capability('mod/data:rate', CAP_PREVENT
, $studentrole->id
, $context->id
);
1863 foreach ($teacherroles as $teacherrole) {
1864 assign_capability('mod/data:rate', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1869 // $data->assesspublic:
1870 // 0 - Students can only see their own ratings
1871 // 1 - Students can see everyone's ratings
1872 switch ($data->assesspublic
) {
1874 foreach ($studentroles as $studentrole) {
1875 assign_capability('mod/data:viewrating', CAP_PREVENT
, $studentrole->id
, $context->id
);
1877 foreach ($teacherroles as $teacherrole) {
1878 assign_capability('mod/data:viewrating', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1882 foreach ($studentroles as $studentrole) {
1883 assign_capability('mod/data:viewrating', CAP_ALLOW
, $studentrole->id
, $context->id
);
1885 foreach ($teacherroles as $teacherrole) {
1886 assign_capability('mod/data:viewrating', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1892 $cm = $DB->get_record('course_modules', array('id'=>$cmid));
1895 switch ($cm->groupmode
) {
1898 case SEPARATEGROUPS
:
1899 foreach ($studentroles as $studentrole) {
1900 assign_capability('moodle/site:accessallgroups', CAP_PREVENT
, $studentrole->id
, $context->id
);
1902 foreach ($teacherroles as $teacherrole) {
1903 assign_capability('moodle/site:accessallgroups', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1907 foreach ($studentroles as $studentrole) {
1908 assign_capability('moodle/site:accessallgroups', CAP_ALLOW
, $studentrole->id
, $context->id
);
1910 foreach ($teacherroles as $teacherrole) {
1911 assign_capability('moodle/site:accessallgroups', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1919 * Returns the best name to show for a preset
1921 * @param string $shortname
1922 * @param string $path
1925 function data_preset_name($shortname, $path) {
1927 // We are looking inside the preset itself as a first choice, but also in normal data directory
1928 $string = get_string('modulename', 'datapreset_'.$shortname);
1930 if (substr($string, 0, 1) == '[') {
1938 * Returns an array of all the available presets.
1942 function data_get_available_presets($context) {
1947 // First load the ratings sub plugins that exist within the modules preset dir
1948 if ($dirs = core_component
::get_plugin_list('datapreset')) {
1949 foreach ($dirs as $dir=>$fulldir) {
1950 if (is_directory_a_preset($fulldir)) {
1951 $preset = new stdClass();
1952 $preset->path
= $fulldir;
1953 $preset->userid
= 0;
1954 $preset->shortname
= $dir;
1955 $preset->name
= data_preset_name($dir, $fulldir);
1956 if (file_exists($fulldir.'/screenshot.jpg')) {
1957 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.jpg';
1958 } else if (file_exists($fulldir.'/screenshot.png')) {
1959 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.png';
1960 } else if (file_exists($fulldir.'/screenshot.gif')) {
1961 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.gif';
1963 $presets[] = $preset;
1967 // Now add to that the site presets that people have saved
1968 $presets = data_get_available_site_presets($context, $presets);
1973 * Gets an array of all of the presets that users have saved to the site.
1975 * @param stdClass $context The context that we are looking from.
1976 * @param array $presets
1977 * @return array An array of presets
1979 function data_get_available_site_presets($context, array $presets=array()) {
1982 $fs = get_file_storage();
1983 $files = $fs->get_area_files(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
);
1984 $canviewall = has_capability('mod/data:viewalluserpresets', $context);
1985 if (empty($files)) {
1988 foreach ($files as $file) {
1989 if (($file->is_directory() && $file->get_filepath()=='/') ||
!$file->is_directory() ||
(!$canviewall && $file->get_userid() != $USER->id
)) {
1992 $preset = new stdClass
;
1993 $preset->path
= $file->get_filepath();
1994 $preset->name
= trim($preset->path
, '/');
1995 $preset->shortname
= $preset->name
;
1996 $preset->userid
= $file->get_userid();
1997 $preset->id
= $file->get_id();
1998 $preset->storedfile
= $file;
1999 $presets[] = $preset;
2005 * Deletes a saved preset.
2007 * @param string $name
2010 function data_delete_site_preset($name) {
2011 $fs = get_file_storage();
2013 $files = $fs->get_directory_files(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
, 0, '/'.$name.'/');
2014 if (!empty($files)) {
2015 foreach ($files as $file) {
2020 $dir = $fs->get_file(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
, 0, '/'.$name.'/', '.');
2028 * Prints the heads for a page
2030 * @param stdClass $course
2031 * @param stdClass $cm
2032 * @param stdClass $data
2033 * @param string $currenttab
2035 function data_print_header($course, $cm, $data, $currenttab='') {
2037 global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
2039 $PAGE->set_title($data->name
);
2040 echo $OUTPUT->header();
2041 echo $OUTPUT->heading(format_string($data->name
), 2);
2042 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id
), 'generalbox', 'intro');
2044 // Groups needed for Add entry tab
2045 $currentgroup = groups_get_activity_group($cm);
2046 $groupmode = groups_get_activity_groupmode($cm);
2051 include('tabs.php');
2054 // Print any notices
2056 if (!empty($displaynoticegood)) {
2057 echo $OUTPUT->notification($displaynoticegood, 'notifysuccess'); // good (usually green)
2058 } else if (!empty($displaynoticebad)) {
2059 echo $OUTPUT->notification($displaynoticebad); // bad (usuually red)
2064 * Can user add more entries?
2066 * @param object $data
2067 * @param mixed $currentgroup
2068 * @param int $groupmode
2069 * @param stdClass $context
2072 function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
2075 if (empty($context)) {
2076 $cm = get_coursemodule_from_instance('data', $data->id
, 0, false, MUST_EXIST
);
2077 $context = context_module
::instance($cm->id
);
2080 if (has_capability('mod/data:manageentries', $context)) {
2081 // no entry limits apply if user can manage
2083 } else if (!has_capability('mod/data:writeentry', $context)) {
2086 } else if (data_atmaxentries($data)) {
2088 } else if (data_in_readonly_period($data)) {
2089 // Check whether we're in a read-only period
2093 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2097 if ($currentgroup) {
2098 return groups_is_member($currentgroup);
2100 //else it might be group 0 in visible mode
2101 if ($groupmode == VISIBLEGROUPS
){
2110 * Check whether the specified database activity is currently in a read-only period
2112 * @param object $data
2113 * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2115 function data_in_readonly_period($data) {
2117 if (!$data->timeviewfrom
&& !$data->timeviewto
) {
2119 } else if (($data->timeviewfrom
&& $now < $data->timeviewfrom
) ||
($data->timeviewto
&& $now > $data->timeviewto
)) {
2128 function is_directory_a_preset($directory) {
2129 $directory = rtrim($directory, '/\\') . '/';
2130 $status = file_exists($directory.'singletemplate.html') &&
2131 file_exists($directory.'listtemplate.html') &&
2132 file_exists($directory.'listtemplateheader.html') &&
2133 file_exists($directory.'listtemplatefooter.html') &&
2134 file_exists($directory.'addtemplate.html') &&
2135 file_exists($directory.'rsstemplate.html') &&
2136 file_exists($directory.'rsstitletemplate.html') &&
2137 file_exists($directory.'csstemplate.css') &&
2138 file_exists($directory.'jstemplate.js') &&
2139 file_exists($directory.'preset.xml');
2145 * Abstract class used for data preset importers
2147 abstract class data_preset_importer
{
2152 protected $directory;
2157 * @param stdClass $course
2158 * @param stdClass $cm
2159 * @param stdClass $module
2160 * @param string $directory
2162 public function __construct($course, $cm, $module, $directory) {
2163 $this->course
= $course;
2165 $this->module
= $module;
2166 $this->directory
= $directory;
2170 * Returns the name of the directory the preset is located in
2173 public function get_directory() {
2174 return basename($this->directory
);
2178 * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2179 * @param file_storage $filestorage. should be null if using a conventional directory
2180 * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2181 * @param string $dir the directory to look in. null if using the Moodle file storage
2182 * @param string $filename the name of the file we want
2183 * @return string the contents of the file or null if the file doesn't exist.
2185 public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2186 if(empty($filestorage) ||
empty($fileobj)) {
2187 if (substr($dir, -1)!='/') {
2190 if (file_exists($dir.$filename)) {
2191 return file_get_contents($dir.$filename);
2196 if ($filestorage->file_exists(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
, 0, $fileobj->get_filepath(), $filename)) {
2197 $file = $filestorage->get_file(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
, 0, $fileobj->get_filepath(), $filename);
2198 return $file->get_content();
2206 * Gets the preset settings
2207 * @global moodle_database $DB
2210 public function get_preset_settings() {
2213 $fs = $fileobj = null;
2214 if (!is_directory_a_preset($this->directory
)) {
2215 //maybe the user requested a preset stored in the Moodle file storage
2217 $fs = get_file_storage();
2218 $files = $fs->get_area_files(DATA_PRESET_CONTEXT
, DATA_PRESET_COMPONENT
, DATA_PRESET_FILEAREA
);
2220 //preset name to find will be the final element of the directory
2221 $explodeddirectory = explode('/', $this->directory
);
2222 $presettofind = end($explodeddirectory);
2224 //now go through the available files available and see if we can find it
2225 foreach ($files as $file) {
2226 if (($file->is_directory() && $file->get_filepath()=='/') ||
!$file->is_directory()) {
2229 $presetname = trim($file->get_filepath(), '/');
2230 if ($presetname==$presettofind) {
2231 $this->directory
= $presetname;
2236 if (empty($fileobj)) {
2237 print_error('invalidpreset', 'data', '', $this->directory
);
2241 $allowed_settings = array(
2245 'requiredentriestoview',
2252 $result = new stdClass
;
2253 $result->settings
= new stdClass
;
2254 $result->importfields
= array();
2255 $result->currentfields
= $DB->get_records('data_fields', array('dataid'=>$this->module
->id
));
2256 if (!$result->currentfields
) {
2257 $result->currentfields
= array();
2262 $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory
,'preset.xml');
2263 $parsedxml = xmlize($presetxml, 0);
2265 /* First, do settings. Put in user friendly array. */
2266 $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
2267 $result->settings
= new StdClass();
2268 foreach ($settingsarray as $setting => $value) {
2269 if (!is_array($value) ||
!in_array($setting, $allowed_settings)) {
2270 // unsupported setting
2273 $result->settings
->$setting = $value[0]['#'];
2276 /* Now work out fields to user friendly array */
2277 $fieldsarray = $parsedxml['preset']['#']['field'];
2278 foreach ($fieldsarray as $field) {
2279 if (!is_array($field)) {
2282 $f = new StdClass();
2283 foreach ($field['#'] as $param => $value) {
2284 if (!is_array($value)) {
2287 $f->$param = $value[0]['#'];
2289 $f->dataid
= $this->module
->id
;
2290 $f->type
= clean_param($f->type
, PARAM_ALPHA
);
2291 $result->importfields
[] = $f;
2293 /* Now add the HTML templates to the settings array so we can update d */
2294 $result->settings
->singletemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"singletemplate.html");
2295 $result->settings
->listtemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"listtemplate.html");
2296 $result->settings
->listtemplateheader
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"listtemplateheader.html");
2297 $result->settings
->listtemplatefooter
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"listtemplatefooter.html");
2298 $result->settings
->addtemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"addtemplate.html");
2299 $result->settings
->rsstemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"rsstemplate.html");
2300 $result->settings
->rsstitletemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"rsstitletemplate.html");
2301 $result->settings
->csstemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"csstemplate.css");
2302 $result->settings
->jstemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"jstemplate.js");
2303 $result->settings
->asearchtemplate
= $this->data_preset_get_file_contents($fs, $fileobj,$this->directory
,"asearchtemplate.html");
2305 $result->settings
->instance
= $this->module
->id
;
2310 * Import the preset into the given database module
2313 function import($overwritesettings) {
2316 $params = $this->get_preset_settings();
2317 $settings = $params->settings
;
2318 $newfields = $params->importfields
;
2319 $currentfields = $params->currentfields
;
2320 $preservedfields = array();
2322 /* Maps fields and makes new ones */
2323 if (!empty($newfields)) {
2324 /* We require an injective mapping, and need to know what to protect */
2325 foreach ($newfields as $nid => $newfield) {
2326 $cid = optional_param("field_$nid", -1, PARAM_INT
);
2330 if (array_key_exists($cid, $preservedfields)){
2331 print_error('notinjectivemap', 'data');
2333 else $preservedfields[$cid] = true;
2336 foreach ($newfields as $nid => $newfield) {
2337 $cid = optional_param("field_$nid", -1, PARAM_INT
);
2339 /* A mapping. Just need to change field params. Data kept. */
2340 if ($cid != -1 and isset($currentfields[$cid])) {
2341 $fieldobject = data_get_field_from_id($currentfields[$cid]->id
, $this->module
);
2342 foreach ($newfield as $param => $value) {
2343 if ($param != "id") {
2344 $fieldobject->field
->$param = $value;
2347 unset($fieldobject->field
->similarfield
);
2348 $fieldobject->update_field();
2349 unset($fieldobject);
2351 /* Make a new field */
2352 include_once("field/$newfield->type/field.class.php");
2354 if (!isset($newfield->description
)) {
2355 $newfield->description
= '';
2357 $classname = 'data_field_'.$newfield->type
;
2358 $fieldclass = new $classname($newfield, $this->module
);
2359 $fieldclass->insert_field();
2365 /* Get rid of all old unused data */
2366 if (!empty($preservedfields)) {
2367 foreach ($currentfields as $cid => $currentfield) {
2368 if (!array_key_exists($cid, $preservedfields)) {
2369 /* Data not used anymore so wipe! */
2370 print "Deleting field $currentfield->name<br />";
2372 $id = $currentfield->id
;
2373 //Why delete existing data records and related comments/ratings??
2374 $DB->delete_records('data_content', array('fieldid'=>$id));
2375 $DB->delete_records('data_fields', array('id'=>$id));
2380 // handle special settings here
2381 if (!empty($settings->defaultsort
)) {
2382 if (is_numeric($settings->defaultsort
)) {
2384 $settings->defaultsort
= 0;
2386 $settings->defaultsort
= (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module
->id
, 'name'=>$settings->defaultsort
));
2389 $settings->defaultsort
= 0;
2392 // do we want to overwrite all current database settings?
2393 if ($overwritesettings) {
2394 // all supported settings
2395 $overwrite = array_keys((array)$settings);
2397 // only templates and sorting
2398 $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2399 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
2400 'asearchtemplate', 'defaultsortdir', 'defaultsort');
2403 // now overwrite current data settings
2404 foreach ($this->module
as $prop=>$unused) {
2405 if (in_array($prop, $overwrite)) {
2406 $this->module
->$prop = $settings->$prop;
2410 data_update_instance($this->module
);
2412 return $this->cleanup();
2416 * Any clean up routines should go here
2419 public function cleanup() {
2425 * Data preset importer for uploaded presets
2427 class data_preset_upload_importer
extends data_preset_importer
{
2428 public function __construct($course, $cm, $module, $filepath) {
2430 if (is_file($filepath)) {
2431 $fp = get_file_packer();
2432 if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2433 fulldelete($filepath);
2435 $filepath .= '_extracted';
2437 parent
::__construct($course, $cm, $module, $filepath);
2439 public function cleanup() {
2440 return fulldelete($this->directory
);
2445 * Data preset importer for existing presets
2447 class data_preset_existing_importer
extends data_preset_importer
{
2449 public function __construct($course, $cm, $module, $fullname) {
2451 list($userid, $shortname) = explode('/', $fullname, 2);
2452 $context = context_module
::instance($cm->id
);
2453 if ($userid && ($userid != $USER->id
) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2454 throw new coding_exception('Invalid preset provided');
2457 $this->userid
= $userid;
2458 $filepath = data_preset_path($course, $userid, $shortname);
2459 parent
::__construct($course, $cm, $module, $filepath);
2461 public function get_userid() {
2462 return $this->userid
;
2469 * @param object $course
2470 * @param int $userid
2471 * @param string $shortname
2474 function data_preset_path($course, $userid, $shortname) {
2477 $context = context_course
::instance($course->id
);
2479 $userid = (int)$userid;
2482 if ($userid > 0 && ($userid == $USER->id ||
has_capability('mod/data:viewalluserpresets', $context))) {
2483 $path = $CFG->dataroot
.'/data/preset/'.$userid.'/'.$shortname;
2484 } else if ($userid == 0) {
2485 $path = $CFG->dirroot
.'/mod/data/preset/'.$shortname;
2486 } else if ($userid < 0) {
2487 $path = $CFG->tempdir
.'/data/'.-$userid.'/'.$shortname;
2494 * Implementation of the function for printing the form elements that control
2495 * whether the course reset functionality affects the data.
2497 * @param $mform form passed by reference
2499 function data_reset_course_form_definition(&$mform) {
2500 $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2501 $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2503 $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2504 $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2506 $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2507 $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2509 $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2510 $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
2514 * Course reset form defaults.
2517 function data_reset_course_form_defaults($course) {
2518 return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2522 * Removes all grades from gradebook
2526 * @param int $courseid
2527 * @param string $type optional type
2529 function data_reset_gradebook($courseid, $type='') {
2532 $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
2533 FROM {data} d, {course_modules} cm, {modules} m
2534 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
2536 if ($datas = $DB->get_records_sql($sql, array($courseid))) {
2537 foreach ($datas as $data) {
2538 data_grade_item_update($data, 'reset');
2544 * Actual implementation of the reset course functionality, delete all the
2545 * data responses for course $data->courseid.
2549 * @param object $data the data submitted from the reset course.
2550 * @return array status array
2552 function data_reset_userdata($data) {
2554 require_once($CFG->libdir
.'/filelib.php');
2555 require_once($CFG->dirroot
.'/rating/lib.php');
2557 $componentstr = get_string('modulenameplural', 'data');
2560 $allrecordssql = "SELECT r.id
2561 FROM {data_records} r
2562 INNER JOIN {data} d ON r.dataid = d.id
2563 WHERE d.course = ?";
2565 $alldatassql = "SELECT d.id
2569 $rm = new rating_manager();
2570 $ratingdeloptions = new stdClass
;
2571 $ratingdeloptions->component
= 'mod_data';
2572 $ratingdeloptions->ratingarea
= 'entry';
2574 // Set the file storage - may need it to remove files later.
2575 $fs = get_file_storage();
2577 // delete entries if requested
2578 if (!empty($data->reset_data
)) {
2579 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid
));
2580 $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid
));
2581 $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid
));
2583 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid
))) {
2584 foreach ($datas as $dataid=>$unused) {
2585 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2588 $datacontext = context_module
::instance($cm->id
);
2590 // Delete any files that may exist.
2591 $fs->delete_area_files($datacontext->id
, 'mod_data', 'content');
2593 $ratingdeloptions->contextid
= $datacontext->id
;
2594 $rm->delete_ratings($ratingdeloptions);
2598 if (empty($data->reset_gradebook_grades
)) {
2599 // remove all grades from gradebook
2600 data_reset_gradebook($data->courseid
);
2602 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2605 // remove entries by users not enrolled into course
2606 if (!empty($data->reset_data_notenrolled
)) {
2607 $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
2608 FROM {data_records} r
2609 JOIN {data} d ON r.dataid = d.id
2610 LEFT JOIN {user} u ON r.userid = u.id
2611 WHERE d.course = ? AND r.userid > 0";
2613 $course_context = context_course
::instance($data->courseid
);
2614 $notenrolled = array();
2616 $rs = $DB->get_recordset_sql($recordssql, array($data->courseid
));
2617 foreach ($rs as $record) {
2618 if (array_key_exists($record->userid
, $notenrolled) or !$record->userexists
or $record->userdeleted
2619 or !is_enrolled($course_context, $record->userid
)) {
2621 if (!$cm = get_coursemodule_from_instance('data', $record->dataid
)) {
2624 $datacontext = context_module
::instance($cm->id
);
2625 $ratingdeloptions->contextid
= $datacontext->id
;
2626 $ratingdeloptions->itemid
= $record->id
;
2627 $rm->delete_ratings($ratingdeloptions);
2629 // Delete any files that may exist.
2630 if ($contents = $DB->get_records('data_content', array('recordid' => $record->id
), '', 'id')) {
2631 foreach ($contents as $content) {
2632 $fs->delete_area_files($datacontext->id
, 'mod_data', 'content', $content->id
);
2635 $notenrolled[$record->userid
] = true;
2637 $DB->delete_records('comments', array('itemid' => $record->id
, 'commentarea' => 'database_entry'));
2638 $DB->delete_records('data_content', array('recordid' => $record->id
));
2639 $DB->delete_records('data_records', array('id' => $record->id
));
2643 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
2646 // remove all ratings
2647 if (!empty($data->reset_data_ratings
)) {
2648 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid
))) {
2649 foreach ($datas as $dataid=>$unused) {
2650 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2653 $datacontext = context_module
::instance($cm->id
);
2655 $ratingdeloptions->contextid
= $datacontext->id
;
2656 $rm->delete_ratings($ratingdeloptions);
2660 if (empty($data->reset_gradebook_grades
)) {
2661 // remove all grades from gradebook
2662 data_reset_gradebook($data->courseid
);
2665 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2668 // remove all comments
2669 if (!empty($data->reset_data_comments
)) {
2670 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid
));
2671 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2674 // updating dates - shift may be negative too
2675 if ($data->timeshift
) {
2676 shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto'), $data->timeshift
, $data->courseid
);
2677 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2684 * Returns all other caps used in module
2688 function data_get_extra_capabilities() {
2689 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');
2693 * @param string $feature FEATURE_xx constant for requested feature
2694 * @return mixed True if module supports feature, null if doesn't know
2696 function data_supports($feature) {
2698 case FEATURE_GROUPS
: return true;
2699 case FEATURE_GROUPINGS
: return true;
2700 case FEATURE_MOD_INTRO
: return true;
2701 case FEATURE_COMPLETION_TRACKS_VIEWS
: return true;
2702 case FEATURE_GRADE_HAS_GRADE
: return true;
2703 case FEATURE_GRADE_OUTCOMES
: return true;
2704 case FEATURE_RATE
: return true;
2705 case FEATURE_BACKUP_MOODLE2
: return true;
2706 case FEATURE_SHOW_DESCRIPTION
: return true;
2708 default: return null;
2713 * @param array $export
2714 * @param string $delimiter_name
2715 * @param object $database
2717 * @param bool $return
2718 * @return string|void
2720 function data_export_csv($export, $delimiter_name, $database, $count, $return=false) {
2722 require_once($CFG->libdir
. '/csvlib.class.php');
2724 $filename = $database . '-' . $count . '-record';
2729 return csv_export_writer
::print_array($export, $delimiter_name, '"', true);
2731 csv_export_writer
::download_array($filename, $export, $delimiter_name);
2737 * @param array $export
2738 * @param string $dataname
2742 function data_export_xls($export, $dataname, $count) {
2744 require_once("$CFG->libdir/excellib.class.php");
2745 $filename = clean_filename("{$dataname}-{$count}_record");
2749 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2750 $filename .= '.xls';
2753 $workbook = new MoodleExcelWorkbook($filearg);
2754 $workbook->send($filename);
2755 $worksheet = array();
2756 $worksheet[0] = $workbook->add_worksheet('');
2758 foreach ($export as $row) {
2760 foreach($row as $col) {
2761 $worksheet[0]->write($rowno, $colno, $col);
2772 * @param array $export
2773 * @param string $dataname
2777 function data_export_ods($export, $dataname, $count) {
2779 require_once("$CFG->libdir/odslib.class.php");
2780 $filename = clean_filename("{$dataname}-{$count}_record");
2784 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2785 $filename .= '.ods';
2787 $workbook = new MoodleODSWorkbook($filearg);
2788 $workbook->send($filename);
2789 $worksheet = array();
2790 $worksheet[0] = $workbook->add_worksheet('');
2792 foreach ($export as $row) {
2794 foreach($row as $col) {
2795 $worksheet[0]->write($rowno, $colno, $col);
2806 * @param int $dataid
2807 * @param array $fields
2808 * @param array $selectedfields
2809 * @param int $currentgroup group ID of the current group. This is used for
2810 * exporting data while maintaining group divisions.
2811 * @param object $context the context in which the operation is performed (for capability checks)
2812 * @param bool $userdetails whether to include the details of the record author
2813 * @param bool $time whether to include time created/modified
2814 * @param bool $approval whether to include approval status
2817 function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0, $context=null,
2818 $userdetails=false, $time=false, $approval=false) {
2821 if (is_null($context)) {
2822 $context = context_system
::instance();
2824 // exporting user data needs special permission
2825 $userdetails = $userdetails && has_capability('mod/data:exportuserinfo', $context);
2827 $exportdata = array();
2829 // populate the header in first row of export
2830 foreach($fields as $key => $field) {
2831 if (!in_array($field->field
->id
, $selectedfields)) {
2832 // ignore values we aren't exporting
2833 unset($fields[$key]);
2835 $exportdata[0][] = $field->field
->name
;
2839 $exportdata[0][] = get_string('user');
2840 $exportdata[0][] = get_string('username');
2841 $exportdata[0][] = get_string('email');
2844 $exportdata[0][] = get_string('timeadded', 'data');
2845 $exportdata[0][] = get_string('timemodified', 'data');
2848 $exportdata[0][] = get_string('approved', 'data');
2851 $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
2852 ksort($datarecords);
2854 foreach($datarecords as $record) {
2855 // get content indexed by fieldid
2856 if ($currentgroup) {
2857 $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 = ?';
2858 $where = array($record->id
, $currentgroup);
2860 $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
2861 $where = array($record->id
);
2864 if( $content = $DB->get_records_sql($select, $where) ) {
2865 foreach($fields as $field) {
2867 if(isset($content[$field->field
->id
])) {
2868 $contents = $field->export_text_value($content[$field->field
->id
]);
2870 $exportdata[$line][] = $contents;
2872 if ($userdetails) { // Add user details to the export data
2873 $userdata = get_complete_user_data('id', $record->userid
);
2874 $exportdata[$line][] = fullname($userdata);
2875 $exportdata[$line][] = $userdata->username
;
2876 $exportdata[$line][] = $userdata->email
;
2878 if ($time) { // Add time added / modified
2879 $exportdata[$line][] = userdate($record->timecreated
);
2880 $exportdata[$line][] = userdate($record->timemodified
);
2882 if ($approval) { // Add approval status
2883 $exportdata[$line][] = (int) $record->approved
;
2892 ////////////////////////////////////////////////////////////////////////////////
2894 ////////////////////////////////////////////////////////////////////////////////
2897 * Lists all browsable file areas
2901 * @param stdClass $course course object
2902 * @param stdClass $cm course module object
2903 * @param stdClass $context context object
2906 function data_get_file_areas($course, $cm, $context) {
2907 return array('content' => get_string('areacontent', 'mod_data'));
2911 * File browsing support for data module.
2913 * @param file_browser $browser
2914 * @param array $areas
2915 * @param stdClass $course
2916 * @param cm_info $cm
2917 * @param context $context
2918 * @param string $filearea
2919 * @param int $itemid
2920 * @param string $filepath
2921 * @param string $filename
2922 * @return file_info_stored file_info_stored instance or null if not found
2924 function data_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2925 global $CFG, $DB, $USER;
2927 if ($context->contextlevel
!= CONTEXT_MODULE
) {
2931 if (!isset($areas[$filearea])) {
2935 if (is_null($itemid)) {
2936 require_once($CFG->dirroot
.'/mod/data/locallib.php');
2937 return new data_file_info_container($browser, $course, $cm, $context, $areas, $filearea);
2940 if (!$content = $DB->get_record('data_content', array('id'=>$itemid))) {
2944 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid
))) {
2948 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid
))) {
2952 if (!$data = $DB->get_record('data', array('id'=>$field->dataid
))) {
2957 if ($data->approval
and !$record->approved
and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
2962 if ($record->groupid
) {
2963 $groupmode = groups_get_activity_groupmode($cm, $course);
2964 if ($groupmode == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
2965 if (!groups_is_member($record->groupid
)) {
2971 $fieldobj = data_get_field($field, $data, $cm);
2973 $filepath = is_null($filepath) ?
'/' : $filepath;
2974 $filename = is_null($filename) ?
'.' : $filename;
2975 if (!$fieldobj->file_ok($filepath.$filename)) {
2979 $fs = get_file_storage();
2980 if (!($storedfile = $fs->get_file($context->id
, 'mod_data', $filearea, $itemid, $filepath, $filename))) {
2984 // Checks to see if the user can manage files or is the owner.
2985 // TODO MDL-33805 - Do not use userid here and move the capability check above.
2986 if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id
) {
2990 $urlbase = $CFG->wwwroot
.'/pluginfile.php';
2992 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemid, true, true, false, false);
2996 * Serves the data attachments. Implements needed access control ;-)
3000 * @param stdClass $course course object
3001 * @param stdClass $cm course module object
3002 * @param stdClass $context context object
3003 * @param string $filearea file area
3004 * @param array $args extra arguments
3005 * @param bool $forcedownload whether or not force download
3006 * @param array $options additional options affecting the file serving
3007 * @return bool false if file not found, does not return if found - justsend the file
3009 function data_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
3012 if ($context->contextlevel
!= CONTEXT_MODULE
) {
3016 require_course_login($course, true, $cm);
3018 if ($filearea === 'content') {
3019 $contentid = (int)array_shift($args);
3021 if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
3025 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid
))) {
3029 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid
))) {
3033 if (!$data = $DB->get_record('data', array('id'=>$field->dataid
))) {
3037 if ($data->id
!= $cm->instance
) {
3038 // hacker attempt - context does not match the contentid
3043 if ($data->approval
and !$record->approved
and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3048 if ($record->groupid
) {
3049 $groupmode = groups_get_activity_groupmode($cm, $course);
3050 if ($groupmode == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
3051 if (!groups_is_member($record->groupid
)) {
3057 $fieldobj = data_get_field($field, $data, $cm);
3059 $relativepath = implode('/', $args);
3060 $fullpath = "/$context->id/mod_data/content/$content->id/$relativepath";
3062 if (!$fieldobj->file_ok($relativepath)) {
3066 $fs = get_file_storage();
3067 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3071 // finally send the file
3072 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
3079 function data_extend_navigation($navigation, $course, $module, $cm) {
3080 global $CFG, $OUTPUT, $USER, $DB;
3082 $rid = optional_param('rid', 0, PARAM_INT
);
3084 $data = $DB->get_record('data', array('id'=>$cm->instance
));
3085 $currentgroup = groups_get_activity_group($cm);
3086 $groupmode = groups_get_activity_groupmode($cm);
3088 $numentries = data_numentries($data);
3089 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
3090 if ($data->requiredentries
> 0 && $numentries < $data->requiredentries
&& !has_capability('mod/data:manageentries', context_module
::instance($cm->id
))) {
3091 $data->entriesleft
= $data->requiredentries
- $numentries;
3092 $entriesnode = $navigation->add(get_string('entrieslefttoadd', 'data', $data));
3093 $entriesnode->add_class('note');
3096 $navigation->add(get_string('list', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance
)));
3098 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance
, 'rid'=>$rid)));
3100 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance
, 'mode'=>'single')));
3102 $navigation->add(get_string('search', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance
, 'mode'=>'asearch')));
3106 * Adds module specific settings to the settings block
3108 * @param settings_navigation $settings The settings navigation object
3109 * @param navigation_node $datanode The node to add module settings to
3111 function data_extend_settings_navigation(settings_navigation
$settings, navigation_node
$datanode) {
3112 global $PAGE, $DB, $CFG, $USER;
3114 $data = $DB->get_record('data', array("id" => $PAGE->cm
->instance
));
3116 $currentgroup = groups_get_activity_group($PAGE->cm
);
3117 $groupmode = groups_get_activity_groupmode($PAGE->cm
);
3119 if (data_user_can_add_entry($data, $currentgroup, $groupmode, $PAGE->cm
->context
)) { // took out participation list here!
3120 if (empty($editentry)) { //TODO: undefined
3121 $addstring = get_string('add', 'data');
3123 $addstring = get_string('editentry', 'data');
3125 $datanode->add($addstring, new moodle_url('/mod/data/edit.php', array('d'=>$PAGE->cm
->instance
)));
3128 if (has_capability(DATA_CAP_EXPORT
, $PAGE->cm
->context
)) {
3129 // The capability required to Export database records is centrally defined in 'lib.php'
3130 // and should be weaker than those required to edit Templates, Fields and Presets.
3131 $datanode->add(get_string('exportentries', 'data'), new moodle_url('/mod/data/export.php', array('d'=>$data->id
)));
3133 if (has_capability('mod/data:manageentries', $PAGE->cm
->context
)) {
3134 $datanode->add(get_string('importentries', 'data'), new moodle_url('/mod/data/import.php', array('d'=>$data->id
)));
3137 if (has_capability('mod/data:managetemplates', $PAGE->cm
->context
)) {
3139 if ($currenttab == 'list') {
3140 $defaultemplate = 'listtemplate';
3141 } else if ($currenttab == 'add') {
3142 $defaultemplate = 'addtemplate';
3143 } else if ($currenttab == 'asearch') {
3144 $defaultemplate = 'asearchtemplate';
3146 $defaultemplate = 'singletemplate';
3149 $templates = $datanode->add(get_string('templates', 'data'));
3151 $templatelist = array ('listtemplate', 'singletemplate', 'asearchtemplate', 'addtemplate', 'rsstemplate', 'csstemplate', 'jstemplate');
3152 foreach ($templatelist as $template) {
3153 $templates->add(get_string($template, 'data'), new moodle_url('/mod/data/templates.php', array('d'=>$data->id
,'mode'=>$template)));
3156 $datanode->add(get_string('fields', 'data'), new moodle_url('/mod/data/field.php', array('d'=>$data->id
)));
3157 $datanode->add(get_string('presets', 'data'), new moodle_url('/mod/data/preset.php', array('d'=>$data->id
)));
3160 if (!empty($CFG->enablerssfeeds
) && !empty($CFG->data_enablerssfeeds
) && $data->rssarticles
> 0) {
3161 require_once("$CFG->libdir/rsslib.php");
3163 $string = get_string('rsstype','forum');
3165 $url = new moodle_url(rss_get_url($PAGE->cm
->context
->id
, $USER->id
, 'mod_data', $data->id
));
3166 $datanode->add($string, $url, settings_navigation
::TYPE_SETTING
, null, null, new pix_icon('i/rss', ''));
3171 * Save the database configuration as a preset.
3173 * @param stdClass $course The course the database module belongs to.
3174 * @param stdClass $cm The course module record
3175 * @param stdClass $data The database record
3176 * @param string $path
3179 function data_presets_save($course, $cm, $data, $path) {
3181 $fs = get_file_storage();
3182 $filerecord = new stdClass
;
3183 $filerecord->contextid
= DATA_PRESET_CONTEXT
;
3184 $filerecord->component
= DATA_PRESET_COMPONENT
;
3185 $filerecord->filearea
= DATA_PRESET_FILEAREA
;
3186 $filerecord->itemid
= 0;
3187 $filerecord->filepath
= '/'.$path.'/';
3188 $filerecord->userid
= $USER->id
;
3190 $filerecord->filename
= 'preset.xml';
3191 $fs->create_file_from_string($filerecord, data_presets_generate_xml($course, $cm, $data));
3193 $filerecord->filename
= 'singletemplate.html';
3194 $fs->create_file_from_string($filerecord, $data->singletemplate
);
3196 $filerecord->filename
= 'listtemplateheader.html';
3197 $fs->create_file_from_string($filerecord, $data->listtemplateheader
);
3199 $filerecord->filename
= 'listtemplate.html';
3200 $fs->create_file_from_string($filerecord, $data->listtemplate
);
3202 $filerecord->filename
= 'listtemplatefooter.html';
3203 $fs->create_file_from_string($filerecord, $data->listtemplatefooter
);
3205 $filerecord->filename
= 'addtemplate.html';
3206 $fs->create_file_from_string($filerecord, $data->addtemplate
);
3208 $filerecord->filename
= 'rsstemplate.html';
3209 $fs->create_file_from_string($filerecord, $data->rsstemplate
);
3211 $filerecord->filename
= 'rsstitletemplate.html';
3212 $fs->create_file_from_string($filerecord, $data->rsstitletemplate
);
3214 $filerecord->filename
= 'csstemplate.css';
3215 $fs->create_file_from_string($filerecord, $data->csstemplate
);
3217 $filerecord->filename
= 'jstemplate.js';
3218 $fs->create_file_from_string($filerecord, $data->jstemplate
);
3220 $filerecord->filename
= 'asearchtemplate.html';
3221 $fs->create_file_from_string($filerecord, $data->asearchtemplate
);
3227 * Generates the XML for the database module provided
3229 * @global moodle_database $DB
3230 * @param stdClass $course The course the database module belongs to.
3231 * @param stdClass $cm The course module record
3232 * @param stdClass $data The database record
3233 * @return string The XML for the preset
3235 function data_presets_generate_xml($course, $cm, $data) {
3238 // Assemble "preset.xml":
3239 $presetxmldata = "<preset>\n\n";
3241 // Raw settings are not preprocessed during saving of presets
3242 $raw_settings = array(
3246 'requiredentriestoview',
3253 $presetxmldata .= "<settings>\n";
3254 // First, settings that do not require any conversion
3255 foreach ($raw_settings as $setting) {
3256 $presetxmldata .= "<$setting>" . htmlspecialchars($data->$setting) . "</$setting>\n";
3259 // Now specific settings
3260 if ($data->defaultsort
> 0 && $sortfield = data_get_field_from_id($data->defaultsort
, $data)) {
3261 $presetxmldata .= '<defaultsort>' . htmlspecialchars($sortfield->field
->name
) . "</defaultsort>\n";
3263 $presetxmldata .= "<defaultsort>0</defaultsort>\n";
3265 $presetxmldata .= "</settings>\n\n";
3266 // Now for the fields. Grab all that are non-empty
3267 $fields = $DB->get_records('data_fields', array('dataid'=>$data->id
));
3269 if (!empty($fields)) {
3270 foreach ($fields as $field) {
3271 $presetxmldata .= "<field>\n";
3272 foreach ($field as $key => $value) {
3273 if ($value != '' && $key != 'id' && $key != 'dataid') {
3274 $presetxmldata .= "<$key>" . htmlspecialchars($value) . "</$key>\n";
3277 $presetxmldata .= "</field>\n\n";
3280 $presetxmldata .= '</preset>';
3281 return $presetxmldata;
3284 function data_presets_export($course, $cm, $data, $tostorage=false) {
3287 $presetname = clean_filename($data->name
) . '-preset-' . gmdate("Ymd_Hi");
3288 $exportsubdir = "mod_data/presetexport/$presetname";
3289 make_temp_directory($exportsubdir);
3290 $exportdir = "$CFG->tempdir/$exportsubdir";
3292 // Assemble "preset.xml":
3293 $presetxmldata = data_presets_generate_xml($course, $cm, $data);
3295 // After opening a file in write mode, close it asap
3296 $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
3297 fwrite($presetxmlfile, $presetxmldata);
3298 fclose($presetxmlfile);
3300 // Now write the template files
3301 $singletemplate = fopen($exportdir . '/singletemplate.html', 'w');
3302 fwrite($singletemplate, $data->singletemplate
);
3303 fclose($singletemplate);
3305 $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w');
3306 fwrite($listtemplateheader, $data->listtemplateheader
);
3307 fclose($listtemplateheader);
3309 $listtemplate = fopen($exportdir . '/listtemplate.html', 'w');
3310 fwrite($listtemplate, $data->listtemplate
);
3311 fclose($listtemplate);
3313 $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w');
3314 fwrite($listtemplatefooter, $data->listtemplatefooter
);
3315 fclose($listtemplatefooter);
3317 $addtemplate = fopen($exportdir . '/addtemplate.html', 'w');
3318 fwrite($addtemplate, $data->addtemplate
);
3319 fclose($addtemplate);
3321 $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w');
3322 fwrite($rsstemplate, $data->rsstemplate
);
3323 fclose($rsstemplate);
3325 $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w');
3326 fwrite($rsstitletemplate, $data->rsstitletemplate
);
3327 fclose($rsstitletemplate);
3329 $csstemplate = fopen($exportdir . '/csstemplate.css', 'w');
3330 fwrite($csstemplate, $data->csstemplate
);
3331 fclose($csstemplate);
3333 $jstemplate = fopen($exportdir . '/jstemplate.js', 'w');
3334 fwrite($jstemplate, $data->jstemplate
);
3335 fclose($jstemplate);
3337 $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w');
3338 fwrite($asearchtemplate, $data->asearchtemplate
);
3339 fclose($asearchtemplate);
3341 // Check if all files have been generated
3342 if (! is_directory_a_preset($exportdir)) {
3343 print_error('generateerror', 'data');
3348 'singletemplate.html',
3349 'listtemplateheader.html',
3350 'listtemplate.html',
3351 'listtemplatefooter.html',
3354 'rsstitletemplate.html',
3357 'asearchtemplate.html'
3360 $filelist = array();
3361 foreach ($filenames as $filename) {
3362 $filelist[$filename] = $exportdir . '/' . $filename;
3365 $exportfile = $exportdir.'.zip';
3366 file_exists($exportfile) && unlink($exportfile);
3368 $fp = get_file_packer('application/zip');
3369 $fp->archive_to_pathname($filelist, $exportfile);
3371 foreach ($filelist as $file) {
3376 // Return the full path to the exported preset file:
3381 * Running addtional permission check on plugin, for example, plugins
3382 * may have switch to turn on/off comments option, this callback will
3383 * affect UI display, not like pluginname_comment_validate only throw
3385 * Capability check has been done in comment->check_permissions(), we
3386 * don't need to do it again here.
3391 * @param stdClass $comment_param {
3392 * context => context the context object
3393 * courseid => int course id
3394 * cm => stdClass course module object
3395 * commentarea => string comment area
3396 * itemid => int itemid
3400 function data_comment_permissions($comment_param) {
3402 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid
))) {
3403 throw new comment_exception('invalidcommentitemid');
3405 if (!$data = $DB->get_record('data', array('id'=>$record->dataid
))) {
3406 throw new comment_exception('invalidid', 'data');
3408 if ($data->comments
) {
3409 return array('post'=>true, 'view'=>true);
3411 return array('post'=>false, 'view'=>false);
3416 * Validate comment parameter before perform other comments actions
3421 * @param stdClass $comment_param {
3422 * context => context the context object
3423 * courseid => int course id
3424 * cm => stdClass course module object
3425 * commentarea => string comment area
3426 * itemid => int itemid
3430 function data_comment_validate($comment_param) {
3432 // validate comment area
3433 if ($comment_param->commentarea
!= 'database_entry') {
3434 throw new comment_exception('invalidcommentarea');
3437 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid
))) {
3438 throw new comment_exception('invalidcommentitemid');
3440 if (!$data = $DB->get_record('data', array('id'=>$record->dataid
))) {
3441 throw new comment_exception('invalidid', 'data');
3443 if (!$course = $DB->get_record('course', array('id'=>$data->course
))) {
3444 throw new comment_exception('coursemisconf');
3446 if (!$cm = get_coursemodule_from_instance('data', $data->id
, $course->id
)) {
3447 throw new comment_exception('invalidcoursemodule');
3449 if (!$data->comments
) {
3450 throw new comment_exception('commentsoff', 'data');
3452 $context = context_module
::instance($cm->id
);
3455 if ($data->approval
and !$record->approved
and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3456 throw new comment_exception('notapproved', 'data');
3460 if ($record->groupid
) {
3461 $groupmode = groups_get_activity_groupmode($cm, $course);
3462 if ($groupmode == SEPARATEGROUPS
and !has_capability('moodle/site:accessallgroups', $context)) {
3463 if (!groups_is_member($record->groupid
)) {
3464 throw new comment_exception('notmemberofgroup');
3468 // validate context id
3469 if ($context->id
!= $comment_param->context
->id
) {
3470 throw new comment_exception('invalidcontext');
3472 // validation for comment deletion
3473 if (!empty($comment_param->commentid
)) {
3474 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid
))) {
3475 if ($comment->commentarea
!= 'database_entry') {
3476 throw new comment_exception('invalidcommentarea');
3478 if ($comment->contextid
!= $comment_param->context
->id
) {
3479 throw new comment_exception('invalidcontext');
3481 if ($comment->itemid
!= $comment_param->itemid
) {
3482 throw new comment_exception('invalidcommentitemid');
3485 throw new comment_exception('invalidcommentid');
3492 * Return a list of page types
3493 * @param string $pagetype current page type
3494 * @param stdClass $parentcontext Block's parent context
3495 * @param stdClass $currentcontext Current context of block
3497 function data_page_type_list($pagetype, $parentcontext, $currentcontext) {
3498 $module_pagetype = array('mod-data-*'=>get_string('page-mod-data-x', 'data'));
3499 return $module_pagetype;
3503 * Get all of the record ids from a database activity.
3505 * @param int $dataid The dataid of the database module.
3506 * @param object $selectdata Contains an additional sql statement for the
3507 * where clause for group and approval fields.
3508 * @param array $params Parameters that coincide with the sql statement.
3509 * @return array $idarray An array of record ids
3511 function data_get_all_recordids($dataid, $selectdata = '', $params = null) {
3513 $initsql = 'SELECT r.id
3514 FROM {data_records} r
3515 WHERE r.dataid = :dataid';
3516 if ($selectdata != '') {
3517 $initsql .= $selectdata;
3518 $params = array_merge(array('dataid' => $dataid), $params);
3520 $params = array('dataid' => $dataid);
3522 $initsql .= ' GROUP BY r.id';
3523 $initrecord = $DB->get_recordset_sql($initsql, $params);
3525 foreach ($initrecord as $data) {
3526 $idarray[] = $data->id
;
3528 // Close the record set and free up resources.
3529 $initrecord->close();
3534 * Get the ids of all the records that match that advanced search criteria
3535 * This goes and loops through each criterion one at a time until it either
3536 * runs out of records or returns a subset of records.
3538 * @param array $recordids An array of record ids.
3539 * @param array $searcharray Contains information for the advanced search criteria
3540 * @param int $dataid The data id of the database.
3541 * @return array $recordids An array of record ids.
3543 function data_get_advance_search_ids($recordids, $searcharray, $dataid) {
3544 $searchcriteria = array_keys($searcharray);
3545 // Loop through and reduce the IDs one search criteria at a time.
3546 foreach ($searchcriteria as $key) {
3547 $recordids = data_get_recordids($key, $searcharray, $dataid, $recordids);
3548 // If we don't have anymore IDs then stop.
3557 * Gets the record IDs given the search criteria
3559 * @param string $alias Record alias.
3560 * @param array $searcharray Criteria for the search.
3561 * @param int $dataid Data ID for the database
3562 * @param array $recordids An array of record IDs.
3563 * @return array $nestarray An arry of record IDs
3565 function data_get_recordids($alias, $searcharray, $dataid, $recordids) {
3568 $nestsearch = $searcharray[$alias];
3569 // searching for content outside of mdl_data_content
3573 list($insql, $params) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED
);
3574 $nestselect = 'SELECT c' . $alias . '.recordid
3575 FROM {data_content} c' . $alias . ',
3579 $nestwhere = 'WHERE u.id = r.userid
3580 AND f.id = c' . $alias . '.fieldid
3581 AND r.id = c' . $alias . '.recordid
3582 AND r.dataid = :dataid
3583 AND c' . $alias .'.recordid ' . $insql . '
3586 $params['dataid'] = $dataid;
3587 if (count($nestsearch->params
) != 0) {
3588 $params = array_merge($params, $nestsearch->params
);
3589 $nestsql = $nestselect . $nestwhere . $nestsearch->sql
;
3591 $thing = $DB->sql_like($nestsearch->field
, ':search1', false);
3592 $nestsql = $nestselect . $nestwhere . $thing . ' GROUP BY c' . $alias . '.recordid';
3593 $params['search1'] = "%$nestsearch->data%";
3595 $nestrecords = $DB->get_recordset_sql($nestsql, $params);
3596 $nestarray = array();
3597 foreach ($nestrecords as $data) {
3598 $nestarray[] = $data->recordid
;
3600 // Close the record set and free up resources.
3601 $nestrecords->close();
3606 * Returns an array with an sql string for advanced searches and the parameters that go with them.
3608 * @param int $sort DATA_*
3609 * @param stdClass $data Data module object
3610 * @param array $recordids An array of record IDs.
3611 * @param string $selectdata Information for the where and select part of the sql statement.
3612 * @param string $sortorder Additional sort parameters
3613 * @return array sqlselect sqlselect['sql'] has the sql string, sqlselect['params'] contains an array of parameters.
3615 function data_get_advanced_search_sql($sort, $data, $recordids, $selectdata, $sortorder) {
3618 $namefields = get_all_user_name_fields(true, 'u');
3620 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . '
3621 FROM {data_content} c,
3624 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' . $namefields;
3626 // Sorting through 'Other' criteria
3630 $sortcontentfull = "u.lastname";
3632 case DATA_FIRSTNAME
:
3633 $sortcontentfull = "u.firstname";
3636 $sortcontentfull = "r.approved";
3638 case DATA_TIMEMODIFIED
:
3639 $sortcontentfull = "r.timemodified";
3641 case DATA_TIMEADDED
:
3643 $sortcontentfull = "r.timecreated";
3646 $sortfield = data_get_field_from_id($sort, $data);
3647 $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
3648 $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
3651 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ',
3652 ' . $sortcontentfull . '
3654 FROM {data_content} c,
3657 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ', ' .$sortcontentfull;
3660 // Default to a standard Where statement if $selectdata is empty.
3661 if ($selectdata == '') {
3662 $selectdata = 'WHERE c.recordid = r.id
3663 AND r.dataid = :dataid
3664 AND r.userid = u.id ';
3667 // Find the field we are sorting on
3668 if ($sort > 0 or data_get_field_from_id($sort, $data)) {
3669 $selectdata .= ' AND c.fieldid = :sort';
3672 // If there are no record IDs then return an sql statment that will return no rows.
3673 if (count($recordids) != 0) {
3674 list($insql, $inparam) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED
);
3676 list($insql, $inparam) = $DB->get_in_or_equal(array('-1'), SQL_PARAMS_NAMED
);
3678 $nestfromsql = $selectdata . ' AND c.recordid ' . $insql . $groupsql;
3679 $sqlselect['sql'] = "$nestselectsql $nestfromsql $sortorder";
3680 $sqlselect['params'] = $inparam;
3685 * Checks to see if the user has permission to delete the preset.
3686 * @param stdClass $context Context object.
3687 * @param stdClass $preset The preset object that we are checking for deletion.
3688 * @return bool Returns true if the user can delete, otherwise false.
3690 function data_user_can_delete_preset($context, $preset) {
3693 if (has_capability('mod/data:manageuserpresets', $context)) {
3697 if ($preset->userid
== $USER->id
) {
3705 * Delete a record entry.
3707 * @param int $recordid The ID for the record to be deleted.
3708 * @param object $data The data object for this activity.
3709 * @param int $courseid ID for the current course (for logging).
3710 * @param int $cmid The course module ID.
3711 * @return bool True if the record deleted, false if not.
3713 function data_delete_record($recordid, $data, $courseid, $cmid) {
3716 if ($deleterecord = $DB->get_record('data_records', array('id' => $recordid))) {
3717 if ($deleterecord->dataid
== $data->id
) {
3718 if ($contents = $DB->get_records('data_content', array('recordid' => $deleterecord->id
))) {
3719 foreach ($contents as $content) {
3720 if ($field = data_get_field_from_id($content->fieldid
, $data)) {
3721 $field->delete_content($content->recordid
);
3724 $DB->delete_records('data_content', array('recordid'=>$deleterecord->id
));
3725 $DB->delete_records('data_records', array('id'=>$deleterecord->id
));
3727 // Delete cached RSS feeds.
3728 if (!empty($CFG->enablerssfeeds
)) {
3729 require_once($CFG->dirroot
.'/mod/data/rsslib.php');
3730 data_rss_delete_file($data);
3733 // Trigger an event for deleting this record.
3734 $event = \mod_data\event\record_deleted
::create(array(
3735 'objectid' => $deleterecord->id
,
3736 'context' => context_module
::instance($cmid),
3737 'courseid' => $courseid,
3739 'dataid' => $deleterecord->dataid
3742 $event->add_record_snapshot('data_records', $deleterecord);