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 = get_context_instance(CONTEXT_MODULE, $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);
196 * Update a field in the database
201 function update_field() {
204 $DB->update_record('data_fields', $this->field);
209 * Delete a field completely
214 function delete_field() {
217 if (!empty($this->field->id)) {
218 $this->delete_content();
219 $DB->delete_records('data_fields', array('id'=>$this->field->id));
225 * Print the relevant form element in the ADD template for this field
228 * @param int $recordid
231 function display_add_field($recordid=0){
235 $content = $DB->get_field('data_content', 'content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid));
240 // beware get_field returns false for new, empty records MDL-18567
241 if ($content===false) {
245 $str = '<div title="'.s($this->field->description).'">';
246 $str .= '<input style="width:300px;" type="text" name="field_'.$this->field->id.'" id="field_'.$this->field->id.'" value="'.s($content).'" />';
253 * Print the relevant form element to define the attributes for this field
254 * viewable by teachers only.
258 * @return void Output is echo'd
260 function display_edit_field() {
261 global $CFG, $DB, $OUTPUT;
263 if (empty($this->field)) { // No field has been defined yet, try and make one
264 $this->define_default_field();
266 echo $OUTPUT->box_start('generalbox boxaligncenter boxwidthwide');
268 echo '<form id="editfield" action="'.$CFG->wwwroot.'/mod/data/field.php" method="post">'."\n";
269 echo '<input type="hidden" name="d" value="'.$this->data->id.'" />'."\n";
270 if (empty($this->field->id)) {
271 echo '<input type="hidden" name="mode" value="add" />'."\n";
272 $savebutton = get_string('add');
274 echo '<input type="hidden" name="fid" value="'.$this->field->id.'" />'."\n";
275 echo '<input type="hidden" name="mode" value="update" />'."\n";
276 $savebutton = get_string('savechanges');
278 echo '<input type="hidden" name="type" value="'.$this->type.'" />'."\n";
279 echo '<input name="sesskey" value="'.sesskey().'" type="hidden" />'."\n";
281 echo $OUTPUT->heading($this->name());
283 require_once($CFG->dirroot.'/mod/data/field/'.$this->type.'/mod.html');
285 echo '<div class="mdl-align">';
286 echo '<input type="submit" value="'.$savebutton.'" />'."\n";
287 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />'."\n";
292 echo $OUTPUT->box_end();
296 * Display the content of the field in browse mode
299 * @param int $recordid
300 * @param object $template
301 * @return bool|string
303 function display_browse_field($recordid, $template) {
306 if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
307 if (isset($content->content)) {
308 $options = new stdClass();
309 if ($this->field->param1 == '1') { // We are autolinking this field, so disable linking within us
310 //$content->content = '<span class="nolink">'.$content->content.'</span>';
311 //$content->content1 = FORMAT_HTML;
312 $options->filter=false;
314 $options->para = false;
315 $str = format_text($content->content, $content->content1, $options);
325 * Update the content of one data field in the data_content table
327 * @param int $recordid
328 * @param mixed $value
329 * @param string $name
332 function update_content($recordid, $value, $name=''){
335 $content = new stdClass();
336 $content->fieldid = $this->field->id;
337 $content->recordid = $recordid;
338 $content->content = clean_param($value, PARAM_NOTAGS);
340 if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
341 $content->id = $oldcontent->id;
342 return $DB->update_record('data_content', $content);
344 return $DB->insert_record('data_content', $content);
349 * Delete all content associated with the field
352 * @param int $recordid
355 function delete_content($recordid=0) {
359 $conditions = array('fieldid'=>$this->field->id, 'recordid'=>$recordid);
361 $conditions = array('fieldid'=>$this->field->id);
364 $rs = $DB->get_recordset('data_content', $conditions);
366 $fs = get_file_storage();
367 foreach ($rs as $content) {
368 $fs->delete_area_files($this->context->id, 'mod_data', 'content', $content->id);
373 return $DB->delete_records('data_content', $conditions);
377 * Check if a field from an add form is empty
379 * @param mixed $value
383 function notemptyfield($value, $name) {
384 return !empty($value);
388 * Just in case a field needs to print something before the whole form
390 function print_before_form() {
394 * Just in case a field needs to print something after the whole form
396 function print_after_form() {
401 * Returns the sortable field for the content. By default, it's just content
402 * but for some plugins, it could be content 1 - content4
406 function get_sort_field() {
411 * Returns the SQL needed to refer to the column. Some fields may need to CAST() etc.
413 * @param string $fieldname
414 * @return string $fieldname
416 function get_sort_sql($fieldname) {
421 * Returns the name/type of the field
426 return get_string('name'.$this->type, 'data');
430 * Prints the respective type icon
438 $params = array('d'=>$this->data->id, 'fid'=>$this->field->id, 'mode'=>'display', 'sesskey'=>sesskey());
439 $link = new moodle_url('/mod/data/field.php', $params);
440 $str = '<a href="'.$link->out().'">';
441 $str .= '<img src="'.$OUTPUT->pix_url('field/'.$this->type, 'data') . '" ';
442 $str .= 'height="'.$this->iconheight.'" width="'.$this->iconwidth.'" alt="'.$this->type.'" title="'.$this->type.'" /></a>';
447 * Per default, it is assumed that fields support text exporting.
448 * Override this (return false) on fields not supporting text exporting.
452 function text_export_supported() {
457 * Per default, return the record's text value only from the "content" field.
458 * Override this in fields class if necesarry.
460 * @param string $record
463 function export_text_value($record) {
464 if ($this->text_export_supported()) {
465 return $record->content;
470 * @param string $relativepath
473 function file_ok($relativepath) {
480 * Given a template and a dataid, generate a default case template
483 * @param object $data
484 * @param string template [addtemplate, singletemplate, listtempalte, rsstemplate]
485 * @param int $recordid
487 * @param bool $update
488 * @return bool|string
490 function data_generate_default_template(&$data, $template, $recordid=0, $form=false, $update=true) {
493 if (!$data && !$template) {
496 if ($template == 'csstemplate' or $template == 'jstemplate' ) {
500 // get all the fields for that database
501 if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'id')) {
503 $table = new html_table();
504 $table->attributes['class'] = 'mod-data-default-template';
505 $table->colclasses = array('template-field', 'template-token');
506 $table->data = array();
507 foreach ($fields as $field) {
508 if ($form) { // Print forms instead of data
509 $fieldobj = data_get_field($field, $data);
510 $token = $fieldobj->display_add_field($recordid);
511 } else { // Just print the tag
512 $token = '[['.$field->name.']]';
514 $table->data[] = array(
519 if ($template == 'listtemplate') {
520 $cell = new html_table_cell('##edit## ##more## ##delete## ##approve## ##export##');
522 $cell->attributes['class'] = 'controls';
523 $table->data[] = new html_table_row(array($cell));
524 } else if ($template == 'singletemplate') {
525 $cell = new html_table_cell('##edit## ##delete## ##approve## ##export##');
527 $cell->attributes['class'] = 'controls';
528 $table->data[] = new html_table_row(array($cell));
529 } else if ($template == 'asearchtemplate') {
530 $row = new html_table_row(array(get_string('authorfirstname', 'data').': ', '##firstname##'));
531 $row->attributes['class'] = 'searchcontrols';
532 $table->data[] = $row;
533 $row = new html_table_row(array(get_string('authorlastname', 'data').': ', '##lastname##'));
534 $row->attributes['class'] = 'searchcontrols';
535 $table->data[] = $row;
538 $str = html_writer::start_tag('div', array('class' => 'defaulttemplate'));
539 $str .= html_writer::table($table);
540 $str .= html_writer::end_tag('div');
541 if ($template == 'listtemplate'){
542 $str .= html_writer::empty_tag('hr');
546 $newdata = new stdClass();
547 $newdata->id = $data->id;
548 $newdata->{$template} = $str;
549 $DB->update_record('data', $newdata);
550 $data->{$template} = $str;
559 * Search for a field name and replaces it with another one in all the
560 * form templates. Set $newfieldname as '' if you want to delete the
561 * field from the form.
564 * @param object $data
565 * @param string $searchfieldname
566 * @param string $newfieldname
569 function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
572 if (!empty($newfieldname)) {
583 $newdata = new stdClass();
584 $newdata->id = $data->id;
585 $newdata->singletemplate = str_ireplace('[['.$searchfieldname.']]',
586 $prestring.$newfieldname.$poststring, $data->singletemplate);
588 $newdata->listtemplate = str_ireplace('[['.$searchfieldname.']]',
589 $prestring.$newfieldname.$poststring, $data->listtemplate);
591 $newdata->addtemplate = str_ireplace('[['.$searchfieldname.']]',
592 $prestring.$newfieldname.$poststring, $data->addtemplate);
594 $newdata->addtemplate = str_ireplace('[['.$searchfieldname.'#id]]',
595 $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate);
597 $newdata->rsstemplate = str_ireplace('[['.$searchfieldname.']]',
598 $prestring.$newfieldname.$poststring, $data->rsstemplate);
600 return $DB->update_record('data', $newdata);
605 * Appends a new field at the end of the form template.
608 * @param object $data
609 * @param string $newfieldname
611 function data_append_new_field_to_templates($data, $newfieldname) {
614 $newdata = new stdClass();
615 $newdata->id = $data->id;
618 if (!empty($data->singletemplate)) {
619 $newdata->singletemplate = $data->singletemplate.' [[' . $newfieldname .']]';
622 if (!empty($data->addtemplate)) {
623 $newdata->addtemplate = $data->addtemplate.' [[' . $newfieldname . ']]';
626 if (!empty($data->rsstemplate)) {
627 $newdata->rsstemplate = $data->singletemplate.' [[' . $newfieldname . ']]';
631 $DB->update_record('data', $newdata);
638 * this function creates an instance of the particular subfield class
641 * @param string $name
642 * @param object $data
643 * @return object|bool
645 function data_get_field_from_name($name, $data){
648 $field = $DB->get_record('data_fields', array('name'=>$name, 'dataid'=>$data->id));
651 return data_get_field($field, $data);
659 * this function creates an instance of the particular subfield class
662 * @param int $fieldid
663 * @param object $data
664 * @return bool|object
666 function data_get_field_from_id($fieldid, $data){
669 $field = $DB->get_record('data_fields', array('id'=>$fieldid, 'dataid'=>$data->id));
672 return data_get_field($field, $data);
680 * this function creates an instance of the particular subfield class
683 * @param string $type
684 * @param object $data
687 function data_get_field_new($type, $data) {
690 require_once($CFG->dirroot.'/mod/data/field/'.$type.'/field.class.php');
691 $newfield = 'data_field_'.$type;
692 $newfield = new $newfield(0, $data);
697 * returns a subclass field object given a record of the field, used to
698 * invoke plugin methods
699 * input: $param $field - record from db
702 * @param object $field
703 * @param object $data
707 function data_get_field($field, $data, $cm=null) {
711 require_once('field/'.$field->type.'/field.class.php');
712 $newfield = 'data_field_'.$field->type;
713 $newfield = new $newfield($field, $data, $cm);
720 * Given record object (or id), returns true if the record belongs to the current user
724 * @param mixed $record record object or id
727 function data_isowner($record) {
730 if (!isloggedin()) { // perf shortcut
734 if (!is_object($record)) {
735 if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
740 return ($record->userid == $USER->id);
744 * has a user reached the max number of entries?
746 * @param object $data
749 function data_atmaxentries($data){
750 if (!$data->maxentries){
754 return (data_numentries($data) >= $data->maxentries);
759 * returns the number of entries already made by this user
763 * @param object $data
766 function data_numentries($data){
768 $sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
769 return $DB->count_records_sql($sql, array($data->id, $USER->id));
773 * function that takes in a dataid and adds a record
774 * this is used everytime an add template is submitted
778 * @param object $data
779 * @param int $groupid
782 function data_add_record($data, $groupid=0){
785 $cm = get_coursemodule_from_instance('data', $data->id);
786 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
788 $record = new stdClass();
789 $record->userid = $USER->id;
790 $record->dataid = $data->id;
791 $record->groupid = $groupid;
792 $record->timecreated = $record->timemodified = time();
793 if (has_capability('mod/data:approve', $context)) {
794 $record->approved = 1;
796 $record->approved = 0;
798 return $DB->insert_record('data_records', $record);
802 * check the multple existence any tag in a template
804 * check to see if there are 2 or more of the same tag being used.
807 * @param int $dataid,
808 * @param string $template
811 function data_tags_check($dataid, $template) {
814 // first get all the possible tags
815 $fields = $DB->get_records('data_fields', array('dataid'=>$dataid));
816 // then we generate strings to replace
817 $tagsok = true; // let's be optimistic
818 foreach ($fields as $field){
819 $pattern="/\[\[".$field->name."\]\]/i";
820 if (preg_match_all($pattern, $template, $dummy)>1){
822 echo $OUTPUT->notification('[['.$field->name.']] - '.get_string('multipletags','data'));
830 * Adds an instance of a data
832 * @param stdClass $data
833 * @param mod_data_mod_form $mform
834 * @return int intance id
836 function data_add_instance($data, $mform = null) {
839 if (empty($data->assessed)) {
843 $data->timemodified = time();
845 $data->id = $DB->insert_record('data', $data);
847 data_grade_item_update($data);
853 * updates an instance of a data
856 * @param object $data
859 function data_update_instance($data) {
862 $data->timemodified = time();
863 $data->id = $data->instance;
865 if (empty($data->assessed)) {
869 if (empty($data->ratingtime) or empty($data->assessed)) {
870 $data->assesstimestart = 0;
871 $data->assesstimefinish = 0;
874 if (empty($data->notification)) {
875 $data->notification = 0;
878 $DB->update_record('data', $data);
880 data_grade_item_update($data);
887 * deletes an instance of a data
893 function data_delete_instance($id) { // takes the dataid
896 if (!$data = $DB->get_record('data', array('id'=>$id))) {
900 $cm = get_coursemodule_from_instance('data', $data->id);
901 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
903 /// Delete all the associated information
906 $fs = get_file_storage();
907 $fs->delete_area_files($context->id, 'mod_data');
909 // get all the records in this data
911 FROM {data_records} r
914 $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
916 // delete all the records and fields
917 $DB->delete_records('data_records', array('dataid'=>$id));
918 $DB->delete_records('data_fields', array('dataid'=>$id));
920 // Delete the instance itself
921 $result = $DB->delete_records('data', array('id'=>$id));
924 data_grade_item_delete($data);
930 * returns a summary of data activity of this user
933 * @param object $course
934 * @param object $user
936 * @param object $data
937 * @return object|null
939 function data_user_outline($course, $user, $mod, $data) {
941 require_once("$CFG->libdir/gradelib.php");
943 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
944 if (empty($grades->items[0]->grades)) {
947 $grade = reset($grades->items[0]->grades);
951 if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id, 'userid'=>$user->id))) {
952 $result = new stdClass();
953 $result->info = get_string('numrecords', 'data', $countrecords);
954 $lastrecord = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
955 WHERE dataid = ? AND userid = ?
956 ORDER BY timemodified DESC', array($data->id, $user->id), true);
957 $result->time = $lastrecord->timemodified;
959 $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
963 $result = new stdClass();
964 $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
966 //datesubmitted == time created. dategraded == time modified or time overridden
967 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
968 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
969 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
970 $result->time = $grade->dategraded;
972 $result->time = $grade->datesubmitted;
981 * Prints all the records uploaded by this user
984 * @param object $course
985 * @param object $user
987 * @param object $data
989 function data_user_complete($course, $user, $mod, $data) {
990 global $DB, $CFG, $OUTPUT;
991 require_once("$CFG->libdir/gradelib.php");
993 $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
994 if (!empty($grades->items[0]->grades)) {
995 $grade = reset($grades->items[0]->grades);
996 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
997 if ($grade->str_feedback) {
998 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1002 if ($records = $DB->get_records('data_records', array('dataid'=>$data->id,'userid'=>$user->id), 'timemodified DESC')) {
1003 data_print_template('singletemplate', $records, $data);
1008 * Return grade for given user or all users.
1011 * @param object $data
1012 * @param int $userid optional user id, 0 means all users
1013 * @return array array of grades, false if none
1015 function data_get_user_grades($data, $userid=0) {
1018 require_once($CFG->dirroot.'/rating/lib.php');
1020 $ratingoptions = new stdClass;
1021 $ratingoptions->component = 'mod_data';
1022 $ratingoptions->ratingarea = 'entry';
1023 $ratingoptions->modulename = 'data';
1024 $ratingoptions->moduleid = $data->id;
1026 $ratingoptions->userid = $userid;
1027 $ratingoptions->aggregationmethod = $data->assessed;
1028 $ratingoptions->scaleid = $data->scale;
1029 $ratingoptions->itemtable = 'data_records';
1030 $ratingoptions->itemtableusercolumn = 'userid';
1032 $rm = new rating_manager();
1033 return $rm->get_user_grades($ratingoptions);
1037 * Update activity grades
1040 * @param object $data
1041 * @param int $userid specific user only, 0 means all
1042 * @param bool $nullifnone
1044 function data_update_grades($data, $userid=0, $nullifnone=true) {
1046 require_once($CFG->libdir.'/gradelib.php');
1048 if (!$data->assessed) {
1049 data_grade_item_update($data);
1051 } else if ($grades = data_get_user_grades($data, $userid)) {
1052 data_grade_item_update($data, $grades);
1054 } else if ($userid and $nullifnone) {
1055 $grade = new stdClass();
1056 $grade->userid = $userid;
1057 $grade->rawgrade = NULL;
1058 data_grade_item_update($data, $grade);
1061 data_grade_item_update($data);
1066 * Update all grades in gradebook.
1070 function data_upgrade_grades() {
1073 $sql = "SELECT COUNT('x')
1074 FROM {data} d, {course_modules} cm, {modules} m
1075 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
1076 $count = $DB->count_records_sql($sql);
1078 $sql = "SELECT d.*, cm.idnumber AS cmidnumber, d.course AS courseid
1079 FROM {data} d, {course_modules} cm, {modules} m
1080 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
1081 $rs = $DB->get_recordset_sql($sql);
1083 // too much debug output
1084 $pbar = new progress_bar('dataupgradegrades', 500, true);
1086 foreach ($rs as $data) {
1088 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
1089 data_update_grades($data, 0, false);
1090 $pbar->update($i, $count, "Updating Database grades ($i/$count).");
1097 * Update/create grade item for given data
1100 * @param stdClass $data A database instance with extra cmidnumber property
1101 * @param mixed $grades Optional array/object of grade(s); 'reset' means reset grades in gradebook
1102 * @return object grade_item
1104 function data_grade_item_update($data, $grades=NULL) {
1106 require_once($CFG->libdir.'/gradelib.php');
1108 $params = array('itemname'=>$data->name, 'idnumber'=>$data->cmidnumber);
1110 if (!$data->assessed or $data->scale == 0) {
1111 $params['gradetype'] = GRADE_TYPE_NONE;
1113 } else if ($data->scale > 0) {
1114 $params['gradetype'] = GRADE_TYPE_VALUE;
1115 $params['grademax'] = $data->scale;
1116 $params['grademin'] = 0;
1118 } else if ($data->scale < 0) {
1119 $params['gradetype'] = GRADE_TYPE_SCALE;
1120 $params['scaleid'] = -$data->scale;
1123 if ($grades === 'reset') {
1124 $params['reset'] = true;
1128 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, $grades, $params);
1132 * Delete grade item for given data
1135 * @param object $data object
1136 * @return object grade_item
1138 function data_grade_item_delete($data) {
1140 require_once($CFG->libdir.'/gradelib.php');
1142 return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, NULL, array('deleted'=>1));
1146 * returns a list of participants of this database
1148 * Returns the users with data in one data
1149 * (users with records in data_records, data_comments and ratings)
1151 * @todo: deprecated - to be deleted in 2.2
1153 * @param int $dataid
1156 function data_get_participants($dataid) {
1159 $params = array('dataid' => $dataid);
1161 $sql = "SELECT DISTINCT u.id, u.id
1164 WHERE r.dataid = :dataid AND
1166 $records = $DB->get_records_sql($sql, $params);
1168 $sql = "SELECT DISTINCT u.id, u.id
1172 WHERE r.dataid = ? AND
1175 c.commentarea = 'database_entry'";
1176 $comments = $DB->get_records_sql($sql, $params);
1178 $sql = "SELECT DISTINCT u.id, u.id
1182 WHERE r.dataid = ? AND
1185 a.component = 'mod_data' AND
1186 a.ratingarea = 'entry'";
1187 $ratings = $DB->get_records_sql($sql, $params);
1189 $participants = array();
1192 foreach ($records as $record) {
1193 $participants[$record->id] = $record;
1197 foreach ($comments as $comment) {
1198 $participants[$comment->id] = $comment;
1202 foreach ($ratings as $rating) {
1203 $participants[$rating->id] = $rating;
1207 return $participants;
1212 * takes a list of records, the current data, a search string,
1213 * and mode to display prints the translated template
1217 * @param string $template
1218 * @param array $records
1219 * @param object $data
1220 * @param string $search
1222 * @param bool $return
1225 function data_print_template($template, $records, $data, $search='', $page=0, $return=false) {
1226 global $CFG, $DB, $OUTPUT;
1227 $cm = get_coursemodule_from_instance('data', $data->id);
1228 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1230 static $fields = NULL;
1232 static $dataid = NULL;
1234 if (empty($dataid)) {
1235 $dataid = $data->id;
1236 } else if ($dataid != $data->id) {
1240 if (empty($fields)) {
1241 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1242 foreach ($fieldrecords as $fieldrecord) {
1243 $fields[]= data_get_field($fieldrecord, $data);
1245 $isteacher = has_capability('mod/data:managetemplates', $context);
1248 if (empty($records)) {
1252 // Check whether this activity is read-only at present
1253 $readonly = data_in_readonly_period($data);
1255 foreach ($records as $record) { // Might be just one for the single template
1258 $patterns = array();
1259 $replacement = array();
1261 // Then we generate strings to replace for normal tags
1262 foreach ($fields as $field) {
1263 $patterns[]='[['.$field->field->name.']]';
1264 $replacement[] = highlight($search, $field->display_browse_field($record->id, $template));
1267 // Replacing special tags (##Edit##, ##Delete##, ##More##)
1268 $patterns[]='##edit##';
1269 $patterns[]='##delete##';
1270 if (has_capability('mod/data:manageentries', $context) || (!$readonly && data_isowner($record->id))) {
1271 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d='
1272 .$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>';
1273 $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='
1274 .$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>';
1276 $replacement[] = '';
1277 $replacement[] = '';
1280 $moreurl = $CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&rid=' . $record->id;
1282 $moreurl .= '&filter=1';
1284 $patterns[]='##more##';
1285 $replacement[] = '<a href="' . $moreurl . '"><img src="' . $OUTPUT->pix_url('i/search') . '" class="iconsmall" alt="' . get_string('more', 'data') . '" title="' . get_string('more', 'data') . '" /></a>';
1287 $patterns[]='##moreurl##';
1288 $replacement[] = $moreurl;
1290 $patterns[]='##user##';
1291 $replacement[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$record->userid.
1292 '&course='.$data->course.'">'.fullname($record).'</a>';
1294 $patterns[]='##export##';
1296 if (!empty($CFG->enableportfolios) && ($template == 'singletemplate' || $template == 'listtemplate')
1297 && ((has_capability('mod/data:exportentry', $context)
1298 || (data_isowner($record->id) && has_capability('mod/data:exportownentry', $context))))) {
1299 require_once($CFG->libdir . '/portfoliolib.php');
1300 $button = new portfolio_add_button();
1301 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id, 'recordid' => $record->id), '/mod/data/locallib.php');
1302 list($formats, $files) = data_portfolio_caller::formats($fields, $record);
1303 $button->set_formats($formats);
1304 $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1306 $replacement[] = '';
1309 $patterns[] = '##timeadded##';
1310 $replacement[] = userdate($record->timecreated);
1312 $patterns[] = '##timemodified##';
1313 $replacement [] = userdate($record->timemodified);
1315 $patterns[]='##approve##';
1316 if (has_capability('mod/data:approve', $context) && ($data->approval) && (!$record->approved)){
1317 $replacement[] = '<span class="approve"><a href="'.$CFG->wwwroot.'/mod/data/view.php?d='.$data->id.'&approve='.$record->id.'&sesskey='.sesskey().'"><img src="'.$OUTPUT->pix_url('i/approve') . '" class="iconsmall" alt="'.get_string('approve').'" /></a></span>';
1319 $replacement[] = '';
1322 $patterns[]='##comments##';
1323 if (($template == 'listtemplate') && ($data->comments)) {
1325 if (!empty($CFG->usecomments)) {
1326 require_once($CFG->dirroot . '/comment/lib.php');
1327 list($context, $course, $cm) = get_context_info_array($context->id);
1328 $cmt = new stdClass();
1329 $cmt->context = $context;
1330 $cmt->course = $course;
1332 $cmt->area = 'database_entry';
1333 $cmt->itemid = $record->id;
1334 $cmt->showcount = true;
1335 $cmt->component = 'mod_data';
1336 $comment = new comment($cmt);
1337 $replacement[] = $comment->output(true);
1340 $replacement[] = '';
1343 // actual replacement of the tags
1344 $newtext = str_ireplace($patterns, $replacement, $data->{$template});
1346 // no more html formatting and filtering - see MDL-6635
1352 // hack alert - return is always false in singletemplate anyway ;-)
1353 /**********************************
1354 * Printing Ratings Form *
1355 *********************************/
1356 if ($template == 'singletemplate') { //prints ratings options
1357 data_print_ratings($data, $record);
1360 /**********************************
1361 * Printing Comments Form *
1362 *********************************/
1363 if (($template == 'singletemplate') && ($data->comments)) {
1364 if (!empty($CFG->usecomments)) {
1365 require_once($CFG->dirroot . '/comment/lib.php');
1366 list($context, $course, $cm) = get_context_info_array($context->id);
1367 $cmt = new stdClass();
1368 $cmt->context = $context;
1369 $cmt->course = $course;
1371 $cmt->area = 'database_entry';
1372 $cmt->itemid = $record->id;
1373 $cmt->showcount = true;
1374 $cmt->component = 'mod_data';
1375 $comment = new comment($cmt);
1376 $comment->output(false);
1384 * Return rating related permissions
1386 * @param string $contextid the context id
1387 * @param string $component the component to get rating permissions for
1388 * @param string $ratingarea the rating area to get permissions for
1389 * @return array an associative array of the user's rating permissions
1391 function data_rating_permissions($contextid, $component, $ratingarea) {
1392 $context = get_context_instance_by_id($contextid, MUST_EXIST);
1393 if ($component != 'mod_data' || $ratingarea != 'entry') {
1397 'view' => has_capability('mod/data:viewrating',$context),
1398 'viewany' => has_capability('mod/data:viewanyrating',$context),
1399 'viewall' => has_capability('mod/data:viewallratings',$context),
1400 'rate' => has_capability('mod/data:rate',$context)
1405 * Validates a submitted rating
1406 * @param array $params submitted data
1407 * context => object the context in which the rated items exists [required]
1408 * itemid => int the ID of the object being rated
1409 * scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1410 * rating => int the submitted rating
1411 * rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1412 * aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
1413 * @return boolean true if the rating is valid. Will throw rating_exception if not
1415 function data_rating_validate($params) {
1418 // Check the component is mod_data
1419 if ($params['component'] != 'mod_data') {
1420 throw new rating_exception('invalidcomponent');
1423 // Check the ratingarea is entry (the only rating area in data module)
1424 if ($params['ratingarea'] != 'entry') {
1425 throw new rating_exception('invalidratingarea');
1428 // Check the rateduserid is not the current user .. you can't rate your own entries
1429 if ($params['rateduserid'] == $USER->id) {
1430 throw new rating_exception('nopermissiontorate');
1433 $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
1434 FROM {data_records} r
1435 JOIN {data} d ON r.dataid = d.id
1436 WHERE r.id = :itemid";
1437 $dataparams = array('itemid'=>$params['itemid']);
1438 if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1439 //item doesn't exist
1440 throw new rating_exception('invaliditemid');
1443 if ($info->scale != $params['scaleid']) {
1444 //the scale being submitted doesnt match the one in the database
1445 throw new rating_exception('invalidscaleid');
1448 //check that the submitted rating is valid for the scale
1451 if ($params['rating'] < 0 && $params['rating'] != RATING_UNSET_RATING) {
1452 throw new rating_exception('invalidnum');
1456 if ($info->scale < 0) {
1457 //its a custom scale
1458 $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
1460 $scalearray = explode(',', $scalerecord->scale);
1461 if ($params['rating'] > count($scalearray)) {
1462 throw new rating_exception('invalidnum');
1465 throw new rating_exception('invalidscaleid');
1467 } else if ($params['rating'] > $info->scale) {
1468 //if its numeric and submitted rating is above maximum
1469 throw new rating_exception('invalidnum');
1472 if ($info->approval && !$info->approved) {
1473 //database requires approval but this item isnt approved
1474 throw new rating_exception('nopermissiontorate');
1477 // check the item we're rating was created in the assessable time window
1478 if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
1479 if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
1480 throw new rating_exception('notavailable');
1484 $course = $DB->get_record('course', array('id'=>$info->course), '*', MUST_EXIST);
1485 $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1486 $context = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
1488 // if the supplied context doesnt match the item's context
1489 if ($context->id != $params['context']->id) {
1490 throw new rating_exception('invalidcontext');
1493 // Make sure groups allow this user to see the item they're rating
1494 $groupid = $info->groupid;
1495 if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) { // Groups are being used
1496 if (!groups_group_exists($groupid)) { // Can't find group
1497 throw new rating_exception('cannotfindgroup');//something is wrong
1500 if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1501 // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
1502 throw new rating_exception('notmemberofgroup');
1511 * function that takes in the current data, number of items per page,
1512 * a search string and prints a preference box in view.php
1514 * This preference box prints a searchable advanced search template if
1515 * a) A template is defined
1516 * b) The advanced search checkbox is checked.
1520 * @param object $data
1521 * @param int $perpage
1522 * @param string $search
1523 * @param string $sort
1524 * @param string $order
1525 * @param array $search_array
1526 * @param int $advanced
1527 * @param string $mode
1530 function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
1531 global $CFG, $DB, $PAGE, $OUTPUT;
1533 $cm = get_coursemodule_from_instance('data', $data->id);
1534 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1535 echo '<br /><div class="datapreferences">';
1536 echo '<form id="options" action="view.php" method="get">';
1538 echo '<input type="hidden" name="d" value="'.$data->id.'" />';
1539 if ($mode =='asearch') {
1541 echo '<input type="hidden" name="mode" value="list" />';
1543 echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
1544 $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
1545 20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
1546 echo html_writer::select($pagesizes, 'perpage', $perpage, false, array('id'=>'pref_perpage'));
1547 echo '<div id="reg_search" style="display: ';
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="dataadvancedsearch" id="data_adv_form" style="display: ';
1622 echo ';margin-left:auto;margin-right:auto;" >';
1623 echo '<table class="boxaligncenter">';
1625 // print ASC or DESC
1626 echo '<tr><td colspan="2"> </td></tr>';
1629 // Determine if we are printing all fields for advanced search, or the template for advanced search
1630 // If a template is not defined, use the deafault template and display all fields.
1631 if(empty($data->asearchtemplate)) {
1632 data_generate_default_template($data, 'asearchtemplate');
1635 static $fields = NULL;
1637 static $dataid = NULL;
1639 if (empty($dataid)) {
1640 $dataid = $data->id;
1641 } else if ($dataid != $data->id) {
1645 if (empty($fields)) {
1646 $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1647 foreach ($fieldrecords as $fieldrecord) {
1648 $fields[]= data_get_field($fieldrecord, $data);
1651 $isteacher = has_capability('mod/data:managetemplates', $context);
1655 $patterns = array();
1656 $replacement = array();
1658 // Then we generate strings to replace for normal tags
1659 foreach ($fields as $field) {
1660 $fieldname = $field->field->name;
1661 $fieldname = preg_quote($fieldname, '/');
1662 $patterns[] = "/\[\[$fieldname\]\]/i";
1663 $searchfield = data_get_field_from_id($field->field->id, $data);
1664 if (!empty($search_array[$field->field->id]->data)) {
1665 $replacement[] = $searchfield->display_search_field($search_array[$field->field->id]->data);
1667 $replacement[] = $searchfield->display_search_field();
1670 $fn = !empty($search_array[DATA_FIRSTNAME]->data) ? $search_array[DATA_FIRSTNAME]->data : '';
1671 $ln = !empty($search_array[DATA_LASTNAME]->data) ? $search_array[DATA_LASTNAME]->data : '';
1672 $patterns[] = '/##firstname##/';
1673 $replacement[] = '<input type="text" size="16" name="u_fn" value="'.$fn.'" />';
1674 $patterns[] = '/##lastname##/';
1675 $replacement[] = '<input type="text" size="16" name="u_ln" value="'.$ln.'" />';
1677 // actual replacement of the tags
1678 $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate);
1680 $options = new stdClass();
1681 $options->para=false;
1682 $options->noclean=true;
1684 echo format_text($newtext, FORMAT_HTML, $options);
1687 echo '<tr><td colspan="4" style="text-align: center;"><br/><input type="submit" value="'.get_string('savesettings','data').'" /><input type="submit" name="resetadv" value="'.get_string('resetsettings','data').'" /></td></tr>';
1698 * @param object $data
1699 * @param object $record
1700 * @return void Output echo'd
1702 function data_print_ratings($data, $record) {
1704 if (!empty($record->rating)){
1705 echo $OUTPUT->render($record->rating);
1710 * For Participantion Reports
1714 function data_get_view_actions() {
1715 return array('view');
1721 function data_get_post_actions() {
1722 return array('add','update','record delete');
1726 * @param string $name
1727 * @param int $dataid
1728 * @param int $fieldid
1731 function data_fieldname_exists($name, $dataid, $fieldid = 0) {
1734 if (!is_numeric($name)) {
1735 $like = $DB->sql_like('df.name', ':name', false);
1737 $like = "df.name = :name";
1739 $params = array('name'=>$name);
1741 $params['dataid'] = $dataid;
1742 $params['fieldid1'] = $fieldid;
1743 $params['fieldid2'] = $fieldid;
1744 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1745 WHERE $like AND df.dataid = :dataid
1746 AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
1748 $params['dataid'] = $dataid;
1749 return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1750 WHERE $like AND df.dataid = :dataid", $params);
1755 * @param array $fieldinput
1757 function data_convert_arrays_to_strings(&$fieldinput) {
1758 foreach ($fieldinput as $key => $val) {
1759 if (is_array($val)) {
1761 foreach ($val as $inner) {
1762 $str .= $inner . ',';
1764 $str = substr($str, 0, -1);
1766 $fieldinput->$key = $str;
1773 * Converts a database (module instance) to use the Roles System
1777 * @uses CONTEXT_MODULE
1780 * @param object $data a data object with the same attributes as a record
1781 * from the data database table
1782 * @param int $datamodid the id of the data module, from the modules table
1783 * @param array $teacherroles array of roles that have archetype teacher
1784 * @param array $studentroles array of roles that have archetype student
1785 * @param array $guestroles array of roles that have archetype guest
1786 * @param int $cmid the course_module id for this data instance
1787 * @return boolean data module was converted or not
1789 function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
1790 global $CFG, $DB, $OUTPUT;
1792 if (!isset($data->participants) && !isset($data->assesspublic)
1793 && !isset($data->groupmode)) {
1794 // We assume that this database has already been converted to use the
1795 // Roles System. above fields get dropped the data module has been
1796 // upgraded to use Roles.
1801 // We were not given the course_module id. Try to find it.
1802 if (!$cm = get_coursemodule_from_instance('data', $data->id)) {
1803 echo $OUTPUT->notification('Could not get the course module for the data');
1809 $context = get_context_instance(CONTEXT_MODULE, $cmid);
1812 // $data->participants:
1813 // 1 - Only teachers can add entries
1814 // 3 - Teachers and students can add entries
1815 switch ($data->participants) {
1817 foreach ($studentroles as $studentrole) {
1818 assign_capability('mod/data:writeentry', CAP_PREVENT, $studentrole->id, $context->id);
1820 foreach ($teacherroles as $teacherrole) {
1821 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1825 foreach ($studentroles as $studentrole) {
1826 assign_capability('mod/data:writeentry', CAP_ALLOW, $studentrole->id, $context->id);
1828 foreach ($teacherroles as $teacherrole) {
1829 assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1835 // 2 - Only teachers can rate posts
1836 // 1 - Everyone can rate posts
1837 // 0 - No one can rate posts
1838 switch ($data->assessed) {
1840 foreach ($studentroles as $studentrole) {
1841 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1843 foreach ($teacherroles as $teacherrole) {
1844 assign_capability('mod/data:rate', CAP_PREVENT, $teacherrole->id, $context->id);
1848 foreach ($studentroles as $studentrole) {
1849 assign_capability('mod/data:rate', CAP_ALLOW, $studentrole->id, $context->id);
1851 foreach ($teacherroles as $teacherrole) {
1852 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1856 foreach ($studentroles as $studentrole) {
1857 assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1859 foreach ($teacherroles as $teacherrole) {
1860 assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1865 // $data->assesspublic:
1866 // 0 - Students can only see their own ratings
1867 // 1 - Students can see everyone's ratings
1868 switch ($data->assesspublic) {
1870 foreach ($studentroles as $studentrole) {
1871 assign_capability('mod/data:viewrating', CAP_PREVENT, $studentrole->id, $context->id);
1873 foreach ($teacherroles as $teacherrole) {
1874 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1878 foreach ($studentroles as $studentrole) {
1879 assign_capability('mod/data:viewrating', CAP_ALLOW, $studentrole->id, $context->id);
1881 foreach ($teacherroles as $teacherrole) {
1882 assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1888 $cm = $DB->get_record('course_modules', array('id'=>$cmid));
1891 switch ($cm->groupmode) {
1894 case SEPARATEGROUPS:
1895 foreach ($studentroles as $studentrole) {
1896 assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id);
1898 foreach ($teacherroles as $teacherrole) {
1899 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1903 foreach ($studentroles as $studentrole) {
1904 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id);
1906 foreach ($teacherroles as $teacherrole) {
1907 assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1915 * Returns the best name to show for a preset
1917 * @param string $shortname
1918 * @param string $path
1921 function data_preset_name($shortname, $path) {
1923 // We are looking inside the preset itself as a first choice, but also in normal data directory
1924 $string = get_string('modulename', 'datapreset_'.$shortname);
1926 if (substr($string, 0, 1) == '[') {
1934 * Returns an array of all the available presets.
1938 function data_get_available_presets($context) {
1943 // First load the ratings sub plugins that exist within the modules preset dir
1944 if ($dirs = get_list_of_plugins('mod/data/preset')) {
1945 foreach ($dirs as $dir) {
1946 $fulldir = $CFG->dirroot.'/mod/data/preset/'.$dir;
1947 if (is_directory_a_preset($fulldir)) {
1948 $preset = new stdClass();
1949 $preset->path = $fulldir;
1950 $preset->userid = 0;
1951 $preset->shortname = $dir;
1952 $preset->name = data_preset_name($dir, $fulldir);
1953 if (file_exists($fulldir.'/screenshot.jpg')) {
1954 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.jpg';
1955 } else if (file_exists($fulldir.'/screenshot.png')) {
1956 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.png';
1957 } else if (file_exists($fulldir.'/screenshot.gif')) {
1958 $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.gif';
1960 $presets[] = $preset;
1964 // Now add to that the site presets that people have saved
1965 $presets = data_get_available_site_presets($context, $presets);
1970 * Gets an array of all of the presets that users have saved to the site.
1972 * @param stdClass $context The context that we are looking from.
1973 * @param array $presets
1974 * @return array An array of presets
1976 function data_get_available_site_presets($context, array $presets=array()) {
1979 $fs = get_file_storage();
1980 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
1981 $canviewall = has_capability('mod/data:viewalluserpresets', $context);
1982 if (empty($files)) {
1985 foreach ($files as $file) {
1986 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory() || (!$canviewall && $file->get_userid() != $USER->id)) {
1989 $preset = new stdClass;
1990 $preset->path = $file->get_filepath();
1991 $preset->name = trim($preset->path, '/');
1992 $preset->shortname = $preset->name;
1993 $preset->userid = $file->get_userid();
1994 $preset->id = $file->get_id();
1995 $preset->storedfile = $file;
1996 $presets[] = $preset;
2002 * Deletes a saved preset.
2004 * @param string $name
2007 function data_delete_site_preset($name) {
2008 $fs = get_file_storage();
2010 $files = $fs->get_directory_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/');
2011 if (!empty($files)) {
2012 foreach ($files as $file) {
2017 $dir = $fs->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/', '.');
2025 * Prints the heads for a page
2027 * @param stdClass $course
2028 * @param stdClass $cm
2029 * @param stdClass $data
2030 * @param string $currenttab
2032 function data_print_header($course, $cm, $data, $currenttab='') {
2034 global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
2036 $PAGE->set_title($data->name);
2037 echo $OUTPUT->header();
2038 echo $OUTPUT->heading(format_string($data->name));
2040 // Groups needed for Add entry tab
2041 $currentgroup = groups_get_activity_group($cm);
2042 $groupmode = groups_get_activity_groupmode($cm);
2047 include('tabs.php');
2050 // Print any notices
2052 if (!empty($displaynoticegood)) {
2053 echo $OUTPUT->notification($displaynoticegood, 'notifysuccess'); // good (usually green)
2054 } else if (!empty($displaynoticebad)) {
2055 echo $OUTPUT->notification($displaynoticebad); // bad (usuually red)
2060 * Can user add more entries?
2062 * @param object $data
2063 * @param mixed $currentgroup
2064 * @param int $groupmode
2065 * @param stdClass $context
2068 function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
2071 if (empty($context)) {
2072 $cm = get_coursemodule_from_instance('data', $data->id, 0, false, MUST_EXIST);
2073 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2076 if (has_capability('mod/data:manageentries', $context)) {
2077 // no entry limits apply if user can manage
2079 } else if (!has_capability('mod/data:writeentry', $context)) {
2082 } else if (data_atmaxentries($data)) {
2084 } else if (data_in_readonly_period($data)) {
2085 // Check whether we're in a read-only period
2089 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2093 if ($currentgroup) {
2094 return groups_is_member($currentgroup);
2096 //else it might be group 0 in visible mode
2097 if ($groupmode == VISIBLEGROUPS){
2106 * Check whether the specified database activity is currently in a read-only period
2108 * @param object $data
2109 * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2111 function data_in_readonly_period($data) {
2113 if (!$data->timeviewfrom && !$data->timeviewto) {
2115 } else if (($data->timeviewfrom && $now < $data->timeviewfrom) || ($data->timeviewto && $now > $data->timeviewto)) {
2124 function is_directory_a_preset($directory) {
2125 $directory = rtrim($directory, '/\\') . '/';
2126 $status = file_exists($directory.'singletemplate.html') &&
2127 file_exists($directory.'listtemplate.html') &&
2128 file_exists($directory.'listtemplateheader.html') &&
2129 file_exists($directory.'listtemplatefooter.html') &&
2130 file_exists($directory.'addtemplate.html') &&
2131 file_exists($directory.'rsstemplate.html') &&
2132 file_exists($directory.'rsstitletemplate.html') &&
2133 file_exists($directory.'csstemplate.css') &&
2134 file_exists($directory.'jstemplate.js') &&
2135 file_exists($directory.'preset.xml');
2141 * Abstract class used for data preset importers
2143 abstract class data_preset_importer {
2148 protected $directory;
2153 * @param stdClass $course
2154 * @param stdClass $cm
2155 * @param stdClass $module
2156 * @param string $directory
2158 public function __construct($course, $cm, $module, $directory) {
2159 $this->course = $course;
2161 $this->module = $module;
2162 $this->directory = $directory;
2166 * Returns the name of the directory the preset is located in
2169 public function get_directory() {
2170 return basename($this->directory);
2174 * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2175 * @param file_storage $filestorage. should be null if using a conventional directory
2176 * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2177 * @param string $dir the directory to look in. null if using the Moodle file storage
2178 * @param string $filename the name of the file we want
2179 * @return string the contents of the file
2181 public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2182 if(empty($filestorage) || empty($fileobj)) {
2183 if (substr($dir, -1)!='/') {
2186 return file_get_contents($dir.$filename);
2188 $file = $filestorage->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename);
2189 return $file->get_content();
2194 * Gets the preset settings
2195 * @global moodle_database $DB
2198 public function get_preset_settings() {
2201 $fs = $fileobj = null;
2202 if (!is_directory_a_preset($this->directory)) {
2203 //maybe the user requested a preset stored in the Moodle file storage
2205 $fs = get_file_storage();
2206 $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2208 //preset name to find will be the final element of the directory
2209 $presettofind = end(explode('/',$this->directory));
2211 //now go through the available files available and see if we can find it
2212 foreach ($files as $file) {
2213 if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory()) {
2216 $presetname = trim($file->get_filepath(), '/');
2217 if ($presetname==$presettofind) {
2218 $this->directory = $presetname;
2223 if (empty($fileobj)) {
2224 print_error('invalidpreset', 'data', '', $this->directory);
2228 $allowed_settings = array(
2232 'requiredentriestoview',
2239 $result = new stdClass;
2240 $result->settings = new stdClass;
2241 $result->importfields = array();
2242 $result->currentfields = $DB->get_records('data_fields', array('dataid'=>$this->module->id));
2243 if (!$result->currentfields) {
2244 $result->currentfields = array();
2249 $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory,'preset.xml');
2250 $parsedxml = xmlize($presetxml, 0);
2252 /* First, do settings. Put in user friendly array. */
2253 $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
2254 $result->settings = new StdClass();
2255 foreach ($settingsarray as $setting => $value) {
2256 if (!is_array($value) || !in_array($setting, $allowed_settings)) {
2257 // unsupported setting
2260 $result->settings->$setting = $value[0]['#'];
2263 /* Now work out fields to user friendly array */
2264 $fieldsarray = $parsedxml['preset']['#']['field'];
2265 foreach ($fieldsarray as $field) {
2266 if (!is_array($field)) {
2269 $f = new StdClass();
2270 foreach ($field['#'] as $param => $value) {
2271 if (!is_array($value)) {
2274 $f->$param = $value[0]['#'];
2276 $f->dataid = $this->module->id;
2277 $f->type = clean_param($f->type, PARAM_ALPHA);
2278 $result->importfields[] = $f;
2280 /* Now add the HTML templates to the settings array so we can update d */
2281 $result->settings->singletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"singletemplate.html");
2282 $result->settings->listtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplate.html");
2283 $result->settings->listtemplateheader = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplateheader.html");
2284 $result->settings->listtemplatefooter = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplatefooter.html");
2285 $result->settings->addtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"addtemplate.html");
2286 $result->settings->rsstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstemplate.html");
2287 $result->settings->rsstitletemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstitletemplate.html");
2288 $result->settings->csstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"csstemplate.css");
2289 $result->settings->jstemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"jstemplate.js");
2292 if (file_exists($this->directory."/asearchtemplate.html")) {
2293 $result->settings->asearchtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"asearchtemplate.html");
2295 $result->settings->asearchtemplate = NULL;
2297 $result->settings->instance = $this->module->id;
2303 * Import the preset into the given database module
2306 function import($overwritesettings) {
2309 $params = $this->get_preset_settings();
2310 $settings = $params->settings;
2311 $newfields = $params->importfields;
2312 $currentfields = $params->currentfields;
2313 $preservedfields = array();
2315 /* Maps fields and makes new ones */
2316 if (!empty($newfields)) {
2317 /* We require an injective mapping, and need to know what to protect */
2318 foreach ($newfields as $nid => $newfield) {
2319 $cid = optional_param("field_$nid", -1, PARAM_INT);
2323 if (array_key_exists($cid, $preservedfields)){
2324 print_error('notinjectivemap', 'data');
2326 else $preservedfields[$cid] = true;
2329 foreach ($newfields as $nid => $newfield) {
2330 $cid = optional_param("field_$nid", -1, PARAM_INT);
2332 /* A mapping. Just need to change field params. Data kept. */
2333 if ($cid != -1 and isset($currentfields[$cid])) {
2334 $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->module);
2335 foreach ($newfield as $param => $value) {
2336 if ($param != "id") {
2337 $fieldobject->field->$param = $value;
2340 unset($fieldobject->field->similarfield);
2341 $fieldobject->update_field();
2342 unset($fieldobject);
2344 /* Make a new field */
2345 include_once("field/$newfield->type/field.class.php");
2347 if (!isset($newfield->description)) {
2348 $newfield->description = '';
2350 $classname = 'data_field_'.$newfield->type;
2351 $fieldclass = new $classname($newfield, $this->module);
2352 $fieldclass->insert_field();
2358 /* Get rid of all old unused data */
2359 if (!empty($preservedfields)) {
2360 foreach ($currentfields as $cid => $currentfield) {
2361 if (!array_key_exists($cid, $preservedfields)) {
2362 /* Data not used anymore so wipe! */
2363 print "Deleting field $currentfield->name<br />";
2365 $id = $currentfield->id;
2366 //Why delete existing data records and related comments/ratings??
2367 $DB->delete_records('data_content', array('fieldid'=>$id));
2368 $DB->delete_records('data_fields', array('id'=>$id));
2373 // handle special settings here
2374 if (!empty($settings->defaultsort)) {
2375 if (is_numeric($settings->defaultsort)) {
2377 $settings->defaultsort = 0;
2379 $settings->defaultsort = (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module->id, 'name'=>$settings->defaultsort));
2382 $settings->defaultsort = 0;
2385 // do we want to overwrite all current database settings?
2386 if ($overwritesettings) {
2387 // all supported settings
2388 $overwrite = array_keys((array)$settings);
2390 // only templates and sorting
2391 $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2392 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
2393 'asearchtemplate', 'defaultsortdir', 'defaultsort');
2396 // now overwrite current data settings
2397 foreach ($this->module as $prop=>$unused) {
2398 if (in_array($prop, $overwrite)) {
2399 $this->module->$prop = $settings->$prop;
2403 data_update_instance($this->module);
2405 return $this->cleanup();
2409 * Any clean up routines should go here
2412 public function cleanup() {
2418 * Data preset importer for uploaded presets
2420 class data_preset_upload_importer extends data_preset_importer {
2421 public function __construct($course, $cm, $module, $filepath) {
2423 if (is_file($filepath)) {
2424 $fp = get_file_packer();
2425 if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2426 fulldelete($filepath);
2428 $filepath .= '_extracted';
2430 parent::__construct($course, $cm, $module, $filepath);
2432 public function cleanup() {
2433 return fulldelete($this->directory);
2438 * Data preset importer for existing presets
2440 class data_preset_existing_importer extends data_preset_importer {
2442 public function __construct($course, $cm, $module, $fullname) {
2444 list($userid, $shortname) = explode('/', $fullname, 2);
2445 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2446 if ($userid && ($userid != $USER->id) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2447 throw new coding_exception('Invalid preset provided');
2450 $this->userid = $userid;
2451 $filepath = data_preset_path($course, $userid, $shortname);
2452 parent::__construct($course, $cm, $module, $filepath);
2454 public function get_userid() {
2455 return $this->userid;
2462 * @param object $course
2463 * @param int $userid
2464 * @param string $shortname
2467 function data_preset_path($course, $userid, $shortname) {
2470 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2472 $userid = (int)$userid;
2475 if ($userid > 0 && ($userid == $USER->id || has_capability('mod/data:viewalluserpresets', $context))) {
2476 $path = $CFG->dataroot.'/data/preset/'.$userid.'/'.$shortname;
2477 } else if ($userid == 0) {
2478 $path = $CFG->dirroot.'/mod/data/preset/'.$shortname;
2479 } else if ($userid < 0) {
2480 $path = $CFG->tempdir.'/data/'.-$userid.'/'.$shortname;
2487 * Implementation of the function for printing the form elements that control
2488 * whether the course reset functionality affects the data.
2490 * @param $mform form passed by reference
2492 function data_reset_course_form_definition(&$mform) {
2493 $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2494 $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2496 $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2497 $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2499 $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2500 $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2502 $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2503 $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
2507 * Course reset form defaults.
2510 function data_reset_course_form_defaults($course) {
2511 return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2515 * Removes all grades from gradebook
2519 * @param int $courseid
2520 * @param string $type optional type
2522 function data_reset_gradebook($courseid, $type='') {
2525 $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
2526 FROM {data} d, {course_modules} cm, {modules} m
2527 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
2529 if ($datas = $DB->get_records_sql($sql, array($courseid))) {
2530 foreach ($datas as $data) {
2531 data_grade_item_update($data, 'reset');
2537 * Actual implementation of the reset course functionality, delete all the
2538 * data responses for course $data->courseid.
2542 * @param object $data the data submitted from the reset course.
2543 * @return array status array
2545 function data_reset_userdata($data) {
2547 require_once($CFG->libdir.'/filelib.php');
2548 require_once($CFG->dirroot.'/rating/lib.php');
2550 $componentstr = get_string('modulenameplural', 'data');
2553 $allrecordssql = "SELECT r.id
2554 FROM {data_records} r
2555 INNER JOIN {data} d ON r.dataid = d.id
2556 WHERE d.course = ?";
2558 $alldatassql = "SELECT d.id
2562 $rm = new rating_manager();
2563 $ratingdeloptions = new stdClass;
2564 $ratingdeloptions->component = 'mod_data';
2565 $ratingdeloptions->ratingarea = 'entry';
2567 // delete entries if requested
2568 if (!empty($data->reset_data)) {
2569 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2570 $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid));
2571 $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid));
2573 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2574 foreach ($datas as $dataid=>$unused) {
2575 fulldelete("$CFG->dataroot/$data->courseid/moddata/data/$dataid");
2577 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2580 $datacontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2582 $ratingdeloptions->contextid = $datacontext->id;
2583 $rm->delete_ratings($ratingdeloptions);
2587 if (empty($data->reset_gradebook_grades)) {
2588 // remove all grades from gradebook
2589 data_reset_gradebook($data->courseid);
2591 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2594 // remove entries by users not enrolled into course
2595 if (!empty($data->reset_data_notenrolled)) {
2596 $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
2597 FROM {data_records} r
2598 JOIN {data} d ON r.dataid = d.id
2599 LEFT JOIN {user} u ON r.userid = u.id
2600 WHERE d.course = ? AND r.userid > 0";
2602 $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
2603 $notenrolled = array();
2605 $rs = $DB->get_recordset_sql($recordssql, array($data->courseid));
2606 foreach ($rs as $record) {
2607 if (array_key_exists($record->userid, $notenrolled) or !$record->userexists or $record->userdeleted
2608 or !is_enrolled($course_context, $record->userid)) {
2610 if (!$cm = get_coursemodule_from_instance('data', $record->dataid)) {
2613 $datacontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2614 $ratingdeloptions->contextid = $datacontext->id;
2615 $ratingdeloptions->itemid = $record->id;
2616 $rm->delete_ratings($ratingdeloptions);
2618 $DB->delete_records('comments', array('itemid'=>$record->id, 'commentarea'=>'database_entry'));
2619 $DB->delete_records('data_content', array('recordid'=>$record->id));
2620 $DB->delete_records('data_records', array('id'=>$record->id));
2621 // HACK: this is ugly - the recordid should be before the fieldid!
2622 if (!array_key_exists($record->dataid, $fields)) {
2623 if ($fs = $DB->get_records('data_fields', array('dataid'=>$record->dataid))) {
2624 $fields[$record->dataid] = array_keys($fs);
2626 $fields[$record->dataid] = array();
2629 foreach($fields[$record->dataid] as $fieldid) {
2630 fulldelete("$CFG->dataroot/$data->courseid/moddata/data/$record->dataid/$fieldid/$record->id");
2632 $notenrolled[$record->userid] = true;
2636 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
2639 // remove all ratings
2640 if (!empty($data->reset_data_ratings)) {
2641 if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2642 foreach ($datas as $dataid=>$unused) {
2643 if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2646 $datacontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2648 $ratingdeloptions->contextid = $datacontext->id;
2649 $rm->delete_ratings($ratingdeloptions);
2653 if (empty($data->reset_gradebook_grades)) {
2654 // remove all grades from gradebook
2655 data_reset_gradebook($data->courseid);
2658 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2661 // remove all comments
2662 if (!empty($data->reset_data_comments)) {
2663 $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2664 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2667 // updating dates - shift may be negative too
2668 if ($data->timeshift) {
2669 shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto'), $data->timeshift, $data->courseid);
2670 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2677 * Returns all other caps used in module
2681 function data_get_extra_capabilities() {
2682 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');
2686 * @param string $feature FEATURE_xx constant for requested feature
2687 * @return mixed True if module supports feature, null if doesn't know
2689 function data_supports($feature) {
2691 case FEATURE_GROUPS: return true;
2692 case FEATURE_GROUPINGS: return true;
2693 case FEATURE_GROUPMEMBERSONLY: return true;
2694 case FEATURE_MOD_INTRO: return true;
2695 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
2696 case FEATURE_GRADE_HAS_GRADE: return true;
2697 case FEATURE_GRADE_OUTCOMES: return true;
2698 case FEATURE_RATE: return true;
2699 case FEATURE_BACKUP_MOODLE2: return true;
2700 case FEATURE_SHOW_DESCRIPTION: return true;
2702 default: return null;
2707 * @param array $export
2708 * @param string $delimiter_name
2709 * @param object $database
2711 * @param bool $return
2712 * @return string|void
2714 function data_export_csv($export, $delimiter_name, $dataname, $count, $return=false) {
2716 require_once($CFG->libdir . '/csvlib.class.php');
2717 $delimiter = csv_import_reader::get_delimiter($delimiter_name);
2718 $filename = clean_filename("{$dataname}-{$count}_record");
2722 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2723 $filename .= clean_filename("-{$delimiter_name}_separated");
2724 $filename .= '.csv';
2725 if (empty($return)) {
2726 header("Content-Type: application/download\n");
2727 header("Content-Disposition: attachment; filename=$filename");
2728 header('Expires: 0');
2729 header('Cache-Control: must-revalidate,post-check=0,pre-check=0');
2730 header('Pragma: public');
2732 $encdelim = '&#' . ord($delimiter) . ';';
2734 foreach($export as $row) {
2735 foreach($row as $key => $column) {
2736 $row[$key] = str_replace($delimiter, $encdelim, $column);
2738 $returnstr .= implode($delimiter, $row) . "\n";
2740 if (empty($return)) {
2749 * @param array $export
2750 * @param string $dataname
2754 function data_export_xls($export, $dataname, $count) {
2756 require_once("$CFG->libdir/excellib.class.php");
2757 $filename = clean_filename("{$dataname}-{$count}_record");
2761 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2762 $filename .= '.xls';
2765 $workbook = new MoodleExcelWorkbook($filearg);
2766 $workbook->send($filename);
2767 $worksheet = array();
2768 $worksheet[0] =& $workbook->add_worksheet('');
2770 foreach ($export as $row) {
2772 foreach($row as $col) {
2773 $worksheet[0]->write($rowno, $colno, $col);
2784 * @param array $export
2785 * @param string $dataname
2789 function data_export_ods($export, $dataname, $count) {
2791 require_once("$CFG->libdir/odslib.class.php");
2792 $filename = clean_filename("{$dataname}-{$count}_record");
2796 $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2797 $filename .= '.ods';
2799 $workbook = new MoodleODSWorkbook($filearg);
2800 $workbook->send($filename);
2801 $worksheet = array();
2802 $worksheet[0] =& $workbook->add_worksheet('');
2804 foreach ($export as $row) {
2806 foreach($row as $col) {
2807 $worksheet[0]->write($rowno, $colno, $col);
2818 * @param int $dataid
2819 * @param array $fields
2820 * @param array $selectedfields
2821 * @param int $currentgroup group ID of the current group. This is used for
2822 * exporting data while maintaining group divisions.
2825 function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0) {
2828 $exportdata = array();
2830 // populate the header in first row of export
2831 foreach($fields as $key => $field) {
2832 if (!in_array($field->field->id, $selectedfields)) {
2833 // ignore values we aren't exporting
2834 unset($fields[$key]);
2836 $exportdata[0][] = $field->field->name;
2840 $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
2841 ksort($datarecords);
2843 foreach($datarecords as $record) {
2844 // get content indexed by fieldid
2845 if ($currentgroup) {
2846 $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 = ?';
2847 $where = array($record->id, $currentgroup);
2849 $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
2850 $where = array($record->id);
2853 if( $content = $DB->get_records_sql($select, $where) ) {
2854 foreach($fields as $field) {
2856 if(isset($content[$field->field->id])) {
2857 $contents = $field->export_text_value($content[$field->field->id]);
2859 $exportdata[$line][] = $contents;
2869 * Lists all browsable file areas
2873 * @param stdClass $course course object
2874 * @param stdClass $cm course module object
2875 * @param stdClass $context context object
2878 function data_get_file_areas($course, $cm, $context) {
2884 * File browsing support for data module.
2886 * @param file_browser $browser
2887 * @param array $areas
2888 * @param stdClass $course
2889 * @param cm_info $cm
2890 * @param context $context
2891 * @param string $filearea
2892 * @param int $itemid
2893 * @param string $filepath
2894 * @param string $filename
2895 * @return file_info_stored file_info_stored instance or null if not found
2897 function mod_data_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2900 if ($context->contextlevel != CONTEXT_MODULE) {
2904 if ($filearea === 'content') {
2905 if (!$content = $DB->get_record('data_content', array('id'=>$itemid))) {
2909 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
2913 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
2917 if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
2922 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
2927 if ($record->groupid) {
2928 $groupmode = groups_get_activity_groupmode($cm, $course);
2929 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
2930 if (!groups_is_member($record->groupid)) {
2936 $fieldobj = data_get_field($field, $data, $cm);
2938 $filepath = is_null($filepath) ? '/' : $filepath;
2939 $filename = is_null($filename) ? '.' : $filename;
2940 if (!$fieldobj->file_ok($filepath.$filename)) {
2944 $fs = get_file_storage();
2945 if (!($storedfile = $fs->get_file($context->id, 'mod_data', $filearea, $itemid, $filepath, $filename))) {
2948 $urlbase = $CFG->wwwroot.'/pluginfile.php';
2949 return new file_info_stored($browser, $context, $storedfile, $urlbase, $filearea, $itemid, true, true, false);
2956 * Serves the data attachments. Implements needed access control ;-)
2960 * @param stdClass $course course object
2961 * @param stdClass $cm course module object
2962 * @param stdClass $context context object
2963 * @param string $filearea file area
2964 * @param array $args extra arguments
2965 * @param bool $forcedownload whether or not force download
2966 * @param array $options additional options affecting the file serving
2967 * @return bool false if file not found, does not return if found - justsend the file
2969 function data_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
2972 if ($context->contextlevel != CONTEXT_MODULE) {
2976 require_course_login($course, true, $cm);
2978 if ($filearea === 'content') {
2979 $contentid = (int)array_shift($args);
2981 if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
2985 if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
2989 if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
2993 if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
2997 if ($data->id != $cm->instance) {
2998 // hacker attempt - context does not match the contentid
3003 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3008 if ($record->groupid) {
3009 $groupmode = groups_get_activity_groupmode($cm, $course);
3010 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3011 if (!groups_is_member($record->groupid)) {
3017 $fieldobj = data_get_field($field, $data, $cm);
3019 $relativepath = implode('/', $args);
3020 $fullpath = "/$context->id/mod_data/content/$content->id/$relativepath";
3022 if (!$fieldobj->file_ok($relativepath)) {
3026 $fs = get_file_storage();
3027 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3031 // finally send the file
3032 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
3039 function data_extend_navigation($navigation, $course, $module, $cm) {
3040 global $CFG, $OUTPUT, $USER, $DB;
3042 $rid = optional_param('rid', 0, PARAM_INT);
3044 $data = $DB->get_record('data', array('id'=>$cm->instance));
3045 $currentgroup = groups_get_activity_group($cm);
3046 $groupmode = groups_get_activity_groupmode($cm);
3048 $numentries = data_numentries($data);
3049 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
3050 if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !has_capability('mod/data:manageentries', get_context_instance(CONTEXT_MODULE, $cm->id))) {
3051 $data->entriesleft = $data->requiredentries - $numentries;
3052 $entriesnode = $navigation->add(get_string('entrieslefttoadd', 'data', $data));
3053 $entriesnode->add_class('note');
3056 $navigation->add(get_string('list', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance)));
3058 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'rid'=>$rid)));
3060 $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'single')));
3062 $navigation->add(get_string('search', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'asearch')));
3066 * Adds module specific settings to the settings block
3068 * @param settings_navigation $settings The settings navigation object
3069 * @param navigation_node $datanode The node to add module settings to
3071 function data_extend_settings_navigation(settings_navigation $settings, navigation_node $datanode) {
3072 global $PAGE, $DB, $CFG, $USER;
3074 $data = $DB->get_record('data', array("id" => $PAGE->cm->instance));
3076 $currentgroup = groups_get_activity_group($PAGE->cm);
3077 $groupmode = groups_get_activity_groupmode($PAGE->cm);
3079 if (data_user_can_add_entry($data, $currentgroup, $groupmode, $PAGE->cm->context)) { // took out participation list here!
3080 if (empty($editentry)) { //TODO: undefined
3081 $addstring = get_string('add', 'data');
3083 $addstring = get_string('editentry', 'data');
3085 $datanode->add($addstring, new moodle_url('/mod/data/edit.php', array('d'=>$PAGE->cm->instance)));
3088 if (has_capability(DATA_CAP_EXPORT, $PAGE->cm->context)) {
3089 // The capability required to Export database records is centrally defined in 'lib.php'
3090 // and should be weaker than those required to edit Templates, Fields and Presets.
3091 $datanode->add(get_string('exportentries', 'data'), new moodle_url('/mod/data/export.php', array('d'=>$data->id)));
3093 if (has_capability('mod/data:manageentries', $PAGE->cm->context)) {
3094 $datanode->add(get_string('importentries', 'data'), new moodle_url('/mod/data/import.php', array('d'=>$data->id)));
3097 if (has_capability('mod/data:managetemplates', $PAGE->cm->context)) {
3099 if ($currenttab == 'list') {
3100 $defaultemplate = 'listtemplate';
3101 } else if ($currenttab == 'add') {
3102 $defaultemplate = 'addtemplate';
3103 } else if ($currenttab == 'asearch') {
3104 $defaultemplate = 'asearchtemplate';
3106 $defaultemplate = 'singletemplate';
3109 $templates = $datanode->add(get_string('templates', 'data'));
3111 $templatelist = array ('listtemplate', 'singletemplate', 'asearchtemplate', 'addtemplate', 'rsstemplate', 'csstemplate', 'jstemplate');
3112 foreach ($templatelist as $template) {
3113 $templates->add(get_string($template, 'data'), new moodle_url('/mod/data/templates.php', array('d'=>$data->id,'mode'=>$template)));
3116 $datanode->add(get_string('fields', 'data'), new moodle_url('/mod/data/field.php', array('d'=>$data->id)));
3117 $datanode->add(get_string('presets', 'data'), new moodle_url('/mod/data/preset.php', array('d'=>$data->id)));
3120 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
3121 require_once("$CFG->libdir/rsslib.php");
3123 $string = get_string('rsstype','forum');
3125 $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_data', $data->id));
3126 $datanode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
3131 * Save the database configuration as a preset.
3133 * @param stdClass $course The course the database module belongs to.
3134 * @param stdClass $cm The course module record
3135 * @param stdClass $data The database record
3136 * @param string $path
3139 function data_presets_save($course, $cm, $data, $path) {
3141 $fs = get_file_storage();
3142 $filerecord = new stdClass;
3143 $filerecord->contextid = DATA_PRESET_CONTEXT;
3144 $filerecord->component = DATA_PRESET_COMPONENT;
3145 $filerecord->filearea = DATA_PRESET_FILEAREA;
3146 $filerecord->itemid = 0;
3147 $filerecord->filepath = '/'.$path.'/';
3148 $filerecord->userid = $USER->id;
3150 $filerecord->filename = 'preset.xml';
3151 $fs->create_file_from_string($filerecord, data_presets_generate_xml($course, $cm, $data));
3153 $filerecord->filename = 'singletemplate.html';
3154 $fs->create_file_from_string($filerecord, $data->singletemplate);
3156 $filerecord->filename = 'listtemplateheader.html';
3157 $fs->create_file_from_string($filerecord, $data->listtemplateheader);
3159 $filerecord->filename = 'listtemplate.html';
3160 $fs->create_file_from_string($filerecord, $data->listtemplate);
3162 $filerecord->filename = 'listtemplatefooter.html';
3163 $fs->create_file_from_string($filerecord, $data->listtemplatefooter);
3165 $filerecord->filename = 'addtemplate.html';
3166 $fs->create_file_from_string($filerecord, $data->addtemplate);
3168 $filerecord->filename = 'rsstemplate.html';
3169 $fs->create_file_from_string($filerecord, $data->rsstemplate);
3171 $filerecord->filename = 'rsstitletemplate.html';
3172 $fs->create_file_from_string($filerecord, $data->rsstitletemplate);
3174 $filerecord->filename = 'csstemplate.css';
3175 $fs->create_file_from_string($filerecord, $data->csstemplate);
3177 $filerecord->filename = 'jstemplate.js';
3178 $fs->create_file_from_string($filerecord, $data->jstemplate);
3180 $filerecord->filename = 'asearchtemplate.html';
3181 $fs->create_file_from_string($filerecord, $data->asearchtemplate);
3187 * Generates the XML for the database module provided
3189 * @global moodle_database $DB
3190 * @param stdClass $course The course the database module belongs to.
3191 * @param stdClass $cm The course module record
3192 * @param stdClass $data The database record
3193 * @return string The XML for the preset
3195 function data_presets_generate_xml($course, $cm, $data) {
3198 // Assemble "preset.xml":
3199 $presetxmldata = "<preset>\n\n";
3201 // Raw settings are not preprocessed during saving of presets
3202 $raw_settings = array(
3206 'requiredentriestoview',
3213 $presetxmldata .= "<settings>\n";
3214 // First, settings that do not require any conversion
3215 foreach ($raw_settings as $setting) {
3216 $presetxmldata .= "<$setting>" . htmlspecialchars($data->$setting) . "</$setting>\n";
3219 // Now specific settings
3220 if ($data->defaultsort > 0 && $sortfield = data_get_field_from_id($data->defaultsort, $data)) {
3221 $presetxmldata .= '<defaultsort>' . htmlspecialchars($sortfield->field->name) . "</defaultsort>\n";
3223 $presetxmldata .= "<defaultsort>0</defaultsort>\n";
3225 $presetxmldata .= "</settings>\n\n";
3226 // Now for the fields. Grab all that are non-empty
3227 $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
3229 if (!empty($fields)) {
3230 foreach ($fields as $field) {
3231 $presetxmldata .= "<field>\n";
3232 foreach ($field as $key => $value) {
3233 if ($value != '' && $key != 'id' && $key != 'dataid') {
3234 $presetxmldata .= "<$key>" . htmlspecialchars($value) . "</$key>\n";
3237 $presetxmldata .= "</field>\n\n";
3240 $presetxmldata .= '</preset>';
3241 return $presetxmldata;
3244 function data_presets_export($course, $cm, $data, $tostorage=false) {
3247 $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi");
3248 $exportsubdir = "mod_data/presetexport/$presetname";
3249 make_temp_directory($exportsubdir);
3250 $exportdir = "$CFG->tempdir/$exportsubdir";
3252 // Assemble "preset.xml":
3253 $presetxmldata = data_presets_generate_xml($course, $cm, $data);
3255 // After opening a file in write mode, close it asap
3256 $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
3257 fwrite($presetxmlfile, $presetxmldata);
3258 fclose($presetxmlfile);
3260 // Now write the template files
3261 $singletemplate = fopen($exportdir . '/singletemplate.html', 'w');
3262 fwrite($singletemplate, $data->singletemplate);
3263 fclose($singletemplate);
3265 $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w');
3266 fwrite($listtemplateheader, $data->listtemplateheader);
3267 fclose($listtemplateheader);
3269 $listtemplate = fopen($exportdir . '/listtemplate.html', 'w');
3270 fwrite($listtemplate, $data->listtemplate);
3271 fclose($listtemplate);
3273 $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w');
3274 fwrite($listtemplatefooter, $data->listtemplatefooter);
3275 fclose($listtemplatefooter);
3277 $addtemplate = fopen($exportdir . '/addtemplate.html', 'w');
3278 fwrite($addtemplate, $data->addtemplate);
3279 fclose($addtemplate);
3281 $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w');
3282 fwrite($rsstemplate, $data->rsstemplate);
3283 fclose($rsstemplate);
3285 $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w');
3286 fwrite($rsstitletemplate, $data->rsstitletemplate);
3287 fclose($rsstitletemplate);
3289 $csstemplate = fopen($exportdir . '/csstemplate.css', 'w');
3290 fwrite($csstemplate, $data->csstemplate);
3291 fclose($csstemplate);
3293 $jstemplate = fopen($exportdir . '/jstemplate.js', 'w');
3294 fwrite($jstemplate, $data->jstemplate);
3295 fclose($jstemplate);
3297 $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w');
3298 fwrite($asearchtemplate, $data->asearchtemplate);
3299 fclose($asearchtemplate);
3301 // Check if all files have been generated
3302 if (! is_directory_a_preset($exportdir)) {
3303 print_error('generateerror', 'data');
3308 'singletemplate.html',
3309 'listtemplateheader.html',
3310 'listtemplate.html',
3311 'listtemplatefooter.html',
3314 'rsstitletemplate.html',
3317 'asearchtemplate.html'
3320 $filelist = array();
3321 foreach ($filenames as $filename) {
3322 $filelist[$filename] = $exportdir . '/' . $filename;
3325 $exportfile = $exportdir.'.zip';
3326 file_exists($exportfile) && unlink($exportfile);
3328 $fp = get_file_packer('application/zip');
3329 $fp->archive_to_pathname($filelist, $exportfile);
3331 foreach ($filelist as $file) {
3336 // Return the full path to the exported preset file:
3341 * Running addtional permission check on plugin, for example, plugins
3342 * may have switch to turn on/off comments option, this callback will
3343 * affect UI display, not like pluginname_comment_validate only throw
3345 * Capability check has been done in comment->check_permissions(), we
3346 * don't need to do it again here.
3351 * @param stdClass $comment_param {
3352 * context => context the context object
3353 * courseid => int course id
3354 * cm => stdClass course module object
3355 * commentarea => string comment area
3356 * itemid => int itemid
3360 function data_comment_permissions($comment_param) {
3362 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3363 throw new comment_exception('invalidcommentitemid');
3365 if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3366 throw new comment_exception('invalidid', 'data');
3368 if ($data->comments) {
3369 return array('post'=>true, 'view'=>true);
3371 return array('post'=>false, 'view'=>false);
3376 * Validate comment parameter before perform other comments actions
3381 * @param stdClass $comment_param {
3382 * context => context the context object
3383 * courseid => int course id
3384 * cm => stdClass course module object
3385 * commentarea => string comment area
3386 * itemid => int itemid
3390 function data_comment_validate($comment_param) {
3392 // validate comment area
3393 if ($comment_param->commentarea != 'database_entry') {
3394 throw new comment_exception('invalidcommentarea');
3397 if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3398 throw new comment_exception('invalidcommentitemid');
3400 if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3401 throw new comment_exception('invalidid', 'data');
3403 if (!$course = $DB->get_record('course', array('id'=>$data->course))) {
3404 throw new comment_exception('coursemisconf');
3406 if (!$cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
3407 throw new comment_exception('invalidcoursemodule');
3409 if (!$data->comments) {
3410 throw new comment_exception('commentsoff', 'data');
3412 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3415 if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3416 throw new comment_exception('notapproved', 'data');
3420 if ($record->groupid) {
3421 $groupmode = groups_get_activity_groupmode($cm, $course);
3422 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3423 if (!groups_is_member($record->groupid)) {
3424 throw new comment_exception('notmemberofgroup');
3428 // validate context id
3429 if ($context->id != $comment_param->context->id) {
3430 throw new comment_exception('invalidcontext');
3432 // validation for comment deletion
3433 if (!empty($comment_param->commentid)) {
3434 if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
3435 if ($comment->commentarea != 'database_entry') {
3436 throw new comment_exception('invalidcommentarea');
3438 if ($comment->contextid != $comment_param->context->id) {
3439 throw new comment_exception('invalidcontext');
3441 if ($comment->itemid != $comment_param->itemid) {
3442 throw new comment_exception('invalidcommentitemid');
3445 throw new comment_exception('invalidcommentid');
3452 * Return a list of page types
3453 * @param string $pagetype current page type
3454 * @param stdClass $parentcontext Block's parent context
3455 * @param stdClass $currentcontext Current context of block
3457 function data_page_type_list($pagetype, $parentcontext, $currentcontext) {
3458 $module_pagetype = array('mod-data-*'=>get_string('page-mod-data-x', 'data'));
3459 return $module_pagetype;
3463 * Get all of the record ids from a database activity.
3465 * @param int $dataid The dataid of the database module.
3466 * @return array $idarray An array of record ids
3468 function data_get_all_recordids($dataid) {
3470 $initsql = 'SELECT c.recordid
3471 FROM {data_fields} f,
3473 WHERE f.dataid = :dataid
3474 AND f.id = c.fieldid
3475 GROUP BY c.recordid';
3476 $initrecord = $DB->get_recordset_sql($initsql, array('dataid' => $dataid));
3478 foreach ($initrecord as $data) {
3479 $idarray[] = $data->recordid;
3481 // Close the record set and free up resources.
3482 $initrecord->close();
3487 * Get the ids of all the records that match that advanced search criteria
3488 * This goes and loops through each criterion one at a time until it either
3489 * runs out of records or returns a subset of records.
3491 * @param array $recordids An array of record ids.
3492 * @param array $searcharray Contains information for the advanced search criteria
3493 * @param int $dataid The data id of the database.
3494 * @return array $recordids An array of record ids.
3496 function data_get_advance_search_ids($recordids, $searcharray, $dataid) {
3497 $searchcriteria = array_keys($searcharray);
3498 // Loop through and reduce the IDs one search criteria at a time.
3499 foreach ($searchcriteria as $key) {
3500 $recordids = data_get_recordids($key, $searcharray, $dataid, $recordids);
3501 // If we don't have anymore IDs then stop.
3510 * Gets the record IDs given the search criteria
3512 * @param string $alias record alias.
3513 * @param array $searcharray criteria for the search.
3514 * @param int $dataid Data ID for the database
3515 * @param array $recordids An array of record IDs.
3516 * @return array $nestarray An arry of record IDs
3518 function data_get_recordids($alias, $searcharray, $dataid, $recordids) {
3521 $nestsearch = $searcharray[$alias];
3522 // searching for content outside of mdl_data_content
3526 list($insql, $params) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3527 $nestselect = 'SELECT c' . $alias . '.recordid
3528 FROM {data_content} c' . $alias . ',
3532 $nestwhere = 'WHERE u.id = r.userid
3533 AND f.id = c' . $alias . '.fieldid
3534 AND r.id = c' . $alias . '.recordid
3535 AND r.dataid = :dataid
3536 AND c' . $alias .'.recordid ' . $insql . '
3539 $params['dataid'] = $dataid;
3540 if (count($nestsearch->params) != 0) {
3541 $params = array_merge($params, $nestsearch->params);
3542 $nestsql = $nestselect . $nestwhere . $nestsearch->sql;
3544 $thing = $DB->sql_like($nestsearch->field, ':search1', false);
3545 $nestsql = $nestselect . $nestwhere . $thing . ' GROUP BY c' . $alias . '.recordid';
3546 $params['search1'] = "%$nestsearch->data%";
3548 $nestrecords = $DB->get_recordset_sql($nestsql, $params);
3549 $nestarray = array();
3550 foreach ($nestrecords as $data) {
3551 $nestarray[] = $data->recordid;
3553 // Close the record set and free up resources.
3554 $nestrecords->close();
3559 * Returns an array with an sql string for advanced searches and the parameters that go with them.
3561 * @param int $sort DATA_*
3562 * @param stdClass $data data module object
3563 * @param array $recordids An array of record IDs.
3564 * @param string $selectdata information for the select part of the sql statement.
3565 * @param string $sortorder Additional sort parameters
3566 * @return array sqlselect sqlselect['sql] has the sql string, sqlselect['params'] contains an array of parameters.
3568 function data_get_advanced_search_sql($sort, $data, $recordids, $selectdata, $sortorder) {
3571 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname
3572 FROM {data_content} c,
3575 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname ';
3577 $sortfield = data_get_field_from_id($sort, $data);
3578 $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
3579 $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
3580 $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' . $sortcontentfull . '
3582 FROM {data_content} c,
3585 $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' .$sortcontentfull;
3587 $nestfromsql = 'WHERE c.recordid = r.id
3588 AND r.dataid = :dataid
3589 AND r.userid = u.id';
3591 // Find the field we are sorting on
3592 if ($sort > 0 or data_get_field_from_id($sort, $data)) {
3593 $nestfromsql .= ' AND c.fieldid = :sort';
3596 // If there are no record IDs then return an sql statment that will return no rows.
3597 if (count($recordids) != 0) {
3598 list($insql, $inparam) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3600 list($insql, $inparam) = $DB->get_in_or_equal(array('-1'), SQL_PARAMS_NAMED);
3602 $nestfromsql .= ' AND c.recordid ' . $insql . $groupsql;
3603 $nestfromsql = "$nestfromsql $selectdata";
3604 $sqlselect['sql'] = "$nestselectsql $nestfromsql $sortorder";
3605 $sqlselect['params'] = $inparam;