2 ///////////////////////////////////////////////////////////////////////////
4 // NOTICE OF COPYRIGHT //
6 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
7 // http://moodle.org //
9 // Copyright (C) 2005 Moodle Pty Ltd http://moodle.com //
11 // This program is free software; you can redistribute it and/or modify //
12 // it under the terms of the GNU General Public License as published by //
13 // the Free Software Foundation; either version 2 of the License, or //
14 // (at your option) any later version. //
16 // This program is distributed in the hope that it will be useful, //
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
19 // GNU General Public License for more details: //
21 // http://www.gnu.org/copyleft/gpl.html //
23 ///////////////////////////////////////////////////////////////////////////
26 define ('DATA_MAX_ENTRIES', 50);
27 define ('DATA_PERPAGE_SINGLE', 1);
29 class data_field_base
{ /// Base class for Database Field Types (see field/*/field.class.php)
31 var $type = 'unknown'; /// Subclasses must override the type with their name
32 var $data = NULL; /// The database object that this field belongs to
33 var $field = NULL; /// The field object itself, if we know it
35 var $iconwidth = 16; /// Width of the icon for this fieldtype
36 var $iconheight = 16; /// Width of the icon for this fieldtype
39 /// Constructor function
40 function data_field_base($field=0, $data=0) { // Field or data or both, each can be id or object
42 if (empty($field) && empty($data)) {
43 error('Programmer error: You must specify field and/or data when defining field class. ');
47 if (is_object($field)) {
48 $this->field
= $field; // Programmer knows what they are doing, we hope
49 } else if (!$this->field
= get_record('data_fields','id',$field)) {
50 error('Bad field ID encountered: '.$field);
53 if (!$this->data
= get_record('data','id',$this->field
->dataid
)) {
54 error('Bad data ID encountered in field data');
59 if (empty($this->data
)) { // We need to define this properly
61 if (is_object($data)) {
62 $this->data
= $data; // Programmer knows what they are doing, we hope
63 } else if (!$this->data
= get_record('data','id',$data)) {
64 error('Bad data ID encountered: '.$data);
66 } else { // No way to define it!
67 error('Data id or object must be provided to field class');
71 if (empty($this->field
)) { // We need to define some default values
72 $this->define_default_field();
77 /// This field just sets up a default field object
78 function define_default_field() {
79 if (empty($this->data
->id
)) {
80 notify('Programmer error: dataid not defined in field class');
82 $this->field
= new object;
84 $this->field
->dataid
= $this->data
->id
;
85 $this->field
->type
= $this->type
;
86 $this->field
->param1
= '';
87 $this->field
->param2
= '';
88 $this->field
->param3
= '';
89 $this->field
->name
= '';
90 $this->field
->description
= '';
95 /// Set up the field object according to data in an object. Now is the time to clean it!
96 function define_field($data) {
97 $this->field
->type
= $this->type
;
98 $this->field
->dataid
= $this->data
->id
;
100 $this->field
->name
= trim($data->name
);
101 $this->field
->description
= trim($data->description
);
103 if (isset($data->param1
)) {
104 $this->field
->param1
= trim($data->param1
);
106 if (isset($data->param2
)) {
107 $this->field
->param2
= trim($data->param2
);
109 if (isset($data->param3
)) {
110 $this->field
->param3
= trim($data->param3
);
112 if (isset($data->param4
)) {
113 $this->field
->param4
= trim($data->param4
);
115 if (isset($data->param5
)) {
116 $this->field
->param5
= trim($data->param5
);
122 /// Insert a new field in the database
123 /// We assume the field object is already defined as $this->field
124 function insert_field() {
125 if (empty($this->field
)) {
126 notify('Programmer error: Field has not been defined yet! See define_field()');
130 if (!$this->field
->id
= insert_record('data_fields',$this->field
)){
131 notify('Insertion of new field failed!');
138 /// Update a field in the database
139 function update_field() {
140 if (!update_record('data_fields', $this->field
)) {
141 notify('updating of new field failed!');
147 /// Delete a field completely
148 function delete_field() {
149 if (!empty($this->field
->id
)) {
150 delete_records('data_fields', 'id', $this->field
->id
);
151 $this->delete_content();
156 /// Print the relevant form element in the ADD template for this field
157 function display_add_field($recordid=0){
159 $content = get_field('data_content', 'content', 'fieldid', $this->field
->id
, 'recordid', $recordid);
164 $str = '<div title="'.s($this->field
->description
).'">';
165 $str .= '<input style="width:300px;" type="text" name="field_'.$this->field
->id
.'" id="field_'.$this->field
->id
.'" value="'.s($content).'" />';
171 /// Print the relevant form element to define the attributes for this field
172 /// viewable by teachers only.
173 function display_edit_field() {
176 if (empty($this->field
)) { // No field has been defined yet, try and make one
177 $this->define_default_field();
179 print_simple_box_start('center','80%');
181 echo '<form id="editfield" action="'.$CFG->wwwroot
.'/mod/data/field.php" method="post">'."\n";
182 echo '<input type="hidden" name="d" value="'.$this->data
->id
.'" />'."\n";
183 if (empty($this->field
->id
)) {
184 echo '<input type="hidden" name="mode" value="add" />'."\n";
185 $savebutton = get_string('add');
187 echo '<input type="hidden" name="fid" value="'.$this->field
->id
.'" />'."\n";
188 echo '<input type="hidden" name="mode" value="update" />'."\n";
189 $savebutton = get_string('savechanges');
191 echo '<input type="hidden" name="type" value="'.$this->type
.'" />'."\n";
192 echo '<input name="sesskey" value="'.sesskey().'" type="hidden" />'."\n";
194 print_heading($this->name());
196 require_once($CFG->dirroot
.'/mod/data/field/'.$this->type
.'/mod.html');
198 echo '<div align="center">';
199 echo '<input type="submit" value="'.$savebutton.'" />'."\n";
200 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />'."\n";
205 print_simple_box_end();
208 /// Display the content of the field in browse mode
209 function display_browse_field($recordid, $template) {
210 if ($content = get_record('data_content','fieldid', $this->field
->id
, 'recordid', $recordid)) {
211 if (isset($content->content
)) {
212 $options = new object();
213 if ($this->field
->param1
== '1') { // We are autolinking this field, so disable linking within us
214 //$content->content = '<span class="nolink">'.$content->content.'</span>';
215 //$content->content1 = FORMAT_HTML;
216 $options->filter
=false;
218 $options->para
= false;
219 $str = format_text($content->content
, $content->content1
, $options);
228 /// Update the content of one data field in the data_content table
229 function update_content($recordid, $value, $name=''){
230 $content = new object();
231 $content->fieldid
= $this->field
->id
;
232 $content->recordid
= $recordid;
233 $content->content
= clean_param($value, PARAM_NOTAGS
);
235 if ($oldcontent = get_record('data_content','fieldid', $this->field
->id
, 'recordid', $recordid)) {
236 $content->id
= $oldcontent->id
;
237 return update_record('data_content', $content);
239 return insert_record('data_content', $content);
243 /// Delete all content associated with the field
244 function delete_content($recordid=0) {
246 $this->delete_content_files($recordid);
249 return delete_records('data_content', 'fieldid', $this->field
->id
, 'recordid', $recordid);
251 return delete_records('data_content', 'fieldid', $this->field
->id
);
255 /// Deletes any files associated with this field
256 function delete_content_files($recordid='') {
259 require_once($CFG->libdir
.'/filelib.php');
261 $dir = $CFG->dataroot
.'/'.$this->data
->course
.'/'.$CFG->moddata
.'/data/'.$this->data
->id
.'/'.$this->field
->id
;
263 $dir .= '/'.$recordid;
266 return fulldelete($dir);
270 /// Check if a field from an add form is empty
271 function notemptyfield($value, $name) {
272 return !empty($value);
275 /// Just in case a field needs to print something before the whole form
276 function print_before_form() {
279 /// Just in case a field needs to print something after the whole form
280 function print_after_form() {
284 /// Returns the sortable field for the content. By default, it's just content
285 /// but for some plugins, it could be content 1 - content4
286 function get_sort_field() {
290 /// Returns the SQL needed to refer to the column. Some fields may need to CAST() etc.
291 function get_sort_sql($fieldname) {
295 /// Returns the name/type of the field
297 return get_string('name'.$this->type
, 'data');
300 /// Prints the respective type icon
304 $str = '<a href="field.php?d='.$this->data
->id
.'&fid='.$this->field
->id
.'&mode=display&sesskey='.sesskey().'">';
305 $str .= '<img src="'.$CFG->modpixpath
.'/data/field/'.$this->type
.'/icon.gif" ';
306 $str .= 'height="'.$this->iconheight
.'" width="'.$this->iconwidth
.'" alt="'.$this->type
.'" title="'.$this->type
.'" /></a>';
311 } //end of major class data_field_base
315 /*****************************************************************************
316 /* Given a template and a dataid, generate a default case template *
317 * input @param template - addtemplate, singletemplate, listtempalte, rsstemplate*
320 *****************************************************************************/
321 function data_generate_default_template(&$data, $template, $recordid=0, $form=false, $update=true) {
323 if (!$data && !$template) {
326 if ($template == 'csstemplate' or $template == 'jstemplate' ) {
330 //get all the fields for that database
331 if ($fields = get_records('data_fields', 'dataid', $data->id
, 'id')) {
333 $str = '<div class="defaulttemplate">';
334 $str .= '<table cellpadding="5">';
336 foreach ($fields as $field) {
338 $str .= '<tr><td valign="top" align="right">';
339 // Yu: commenting this out, the id was wrong and will fix later
340 //if ($template == 'addtemplate') {
342 //if (!in_array($field->type, array('picture', 'checkbox', 'date', 'latlong', 'radiobutton'))) {
343 // $str .= ' for="[['.$field->name.'#id]]"';
345 //$str .= '>'.$field->name.'</label>';
348 $str .= $field->name
.': ';
353 if ($form) { /// Print forms instead of data
354 $fieldobj = data_get_field($field, $data);
355 $str .= $fieldobj->display_add_field($recordid);
357 } else { /// Just print the tag
358 $str .= '[['.$field->name
.']]';
360 $str .= '</td></tr>';
363 if ($template == 'listtemplate') {
364 $str .= '<tr><td align="center" colspan="2">##edit## ##more## ##delete## ##approve##</td></tr>';
365 } else if ($template == 'singletemplate') {
366 $str .= '<tr><td align="center" colspan="2">##edit## ##delete## ##approve##</td></tr>';
372 if ($template == 'listtemplate'){
377 $newdata = new object();
378 $newdata->id
= $data->id
;
379 $newdata->{$template} = $str;
380 if (!update_record('data', $newdata)) {
381 notify('Error updating template');
383 $data->{$template} = $str;
392 /***********************************************************************
393 * Search for a field name and replaces it with another one in all the *
394 * form templates. Set $newfieldname as '' if you want to delete the *
395 * field from the form. *
396 ***********************************************************************/
397 function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
398 if (!empty($newfieldname)) {
409 $newdata = new object();
410 $newdata->id
= $data->id
;
411 $newdata->singletemplate
= addslashes(str_ireplace('[['.$searchfieldname.']]',
412 $prestring.$newfieldname.$poststring, $data->singletemplate
));
414 $newdata->listtemplate
= addslashes(str_ireplace('[['.$searchfieldname.']]',
415 $prestring.$newfieldname.$poststring, $data->listtemplate
));
417 $newdata->addtemplate
= addslashes(str_ireplace('[['.$searchfieldname.']]',
418 $prestring.$newfieldname.$poststring, $data->addtemplate
));
420 $newdata->addtemplate
= addslashes(str_ireplace('[['.$searchfieldname.'#id]]',
421 $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate
));
423 $newdata->rsstemplate
= addslashes(str_ireplace('[['.$searchfieldname.']]',
424 $prestring.$newfieldname.$poststring, $data->rsstemplate
));
426 return update_record('data', $newdata);
430 /********************************************************
431 * Appends a new field at the end of the form template. *
432 ********************************************************/
433 function data_append_new_field_to_templates($data, $newfieldname) {
435 $newdata = new object();
436 $newdata->id
= $data->id
;
439 if (!empty($data->singletemplate
)) {
440 $newdata->singletemplate
= addslashes($data->singletemplate
.' [[' . $newfieldname .']]');
443 if (!empty($data->addtemplate
)) {
444 $newdata->addtemplate
= addslashes($data->addtemplate
.' [[' . $newfieldname . ']]');
447 if (!empty($data->rsstemplate
)) {
448 $newdata->rsstemplate
= addslashes($data->singletemplate
.' [[' . $newfieldname . ']]');
452 update_record('data', $newdata);
457 /************************************************************************
458 * given a field name *
459 * this function creates an instance of the particular subfield class *
460 ************************************************************************/
461 function data_get_field_from_name($name, $data){
462 $field = get_record('data_fields','name',$name);
465 return data_get_field($field, $data);
471 /************************************************************************
473 * this function creates an instance of the particular subfield class *
474 ************************************************************************/
475 function data_get_field_from_id($fieldid, $data){
476 $field = get_record('data_fields','id',$fieldid);
479 return data_get_field($field, $data);
485 /************************************************************************
487 * this function creates an instance of the particular subfield class *
488 ************************************************************************/
489 function data_get_field_new($type, $data) {
492 require_once($CFG->dirroot
.'/mod/data/field/'.$type.'/field.class.php');
493 $newfield = 'data_field_'.$type;
494 $newfield = new $newfield(0, $data);
498 /************************************************************************
499 * returns a subclass field object given a record of the field, used to *
500 * invoke plugin methods *
501 * input: $param $field - record from db *
502 ************************************************************************/
503 function data_get_field($field, $data) {
507 require_once('field/'.$field->type
.'/field.class.php');
508 $newfield = 'data_field_'.$field->type
;
509 $newfield = new $newfield($field, $data);
515 /***************************************************************************
516 * given record id, returns true if the record belongs to the current user *
517 * input @param $rid - record id *
519 ***************************************************************************/
520 function data_isowner($rid){
523 if (empty($USER->id
)) {
527 if ($record = get_record('data_records','id',$rid)) {
528 return ($record->userid
== $USER->id
);
534 /***********************************************************************
535 * has a user reached the max number of entries? *
536 * input object $data *
538 ***********************************************************************/
539 function data_atmaxentries($data){
540 if (!$data->maxentries
){
544 return (data_numentries($data) >= $data->maxentries
);
548 /**********************************************************************
549 * returns the number of entries already made by this user *
550 * input @param object $data *
551 * uses global $CFG, $USER *
553 **********************************************************************/
554 function data_numentries($data){
557 $sql = 'SELECT COUNT(*) FROM '.$CFG->prefix
.'data_records WHERE dataid='.$data->id
.' AND userid='.$USER->id
;
558 return count_records_sql($sql);
561 /****************************************************************
562 * function that takes in a dataid and adds a record *
563 * this is used everytime an add template is submitted *
564 * input @param int $dataid, $groupid *
566 ****************************************************************/
567 function data_add_record($data, $groupid=0){
570 $cm = get_coursemodule_from_instance('data', $data->id
);
571 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
573 $record = new object();
574 $record->userid
= $USER->id
;
575 $record->dataid
= $data->id
;
576 $record->groupid
= $groupid;
577 $record->timecreated
= $record->timemodified
= time();
578 if (has_capability('mod/data:approve', $context)) {
579 $record->approved
= 1;
581 $record->approved
= 0;
583 return insert_record('data_records',$record);
586 /*******************************************************************
587 * check the multple existence any tag in a template *
588 * input @param string *
589 * output true-valid, false-invalid *
590 * check to see if there are 2 or more of the same tag being used. *
591 * input @param int $dataid, *
592 * @param string $template *
594 *******************************************************************/
595 function data_tags_check($dataid, $template){
596 //first get all the possible tags
597 $fields = get_records('data_fields','dataid',$dataid);
598 ///then we generate strings to replace
599 $tagsok = true; //let's be optimistic
600 foreach ($fields as $field){
601 $pattern="/\[\[".$field->name
."\]\]/i";
602 if (preg_match_all($pattern, $template, $dummy)>1){
604 notify ('[['.$field->name
.']] - '.get_string('multipletags','data'));
611 /************************************************************************
612 * Adds an instance of a data *
613 ************************************************************************/
614 function data_add_instance($data) {
617 if (empty($data->assessed
)) {
621 $data->timemodified
= time();
623 if (! $data->id
= insert_record('data', $data)) {
627 $data = stripslashes_recursive($data);
628 data_grade_item_update($data);
633 /************************************************************************
634 * updates an instance of a data *
635 ************************************************************************/
636 function data_update_instance($data) {
639 $data->timemodified
= time();
640 $data->id
= $data->instance
;
642 if (empty($data->assessed
)) {
646 if (! update_record('data', $data)) {
650 $data = stripslashes_recursive($data);
651 data_grade_item_update($data);
657 /************************************************************************
658 * deletes an instance of a data *
659 ************************************************************************/
660 function data_delete_instance($id) { //takes the dataid
664 if (! $data = get_record('data', 'id', $id)) {
668 /// Delete all the associated information
670 // get all the records in this data
671 $sql = 'SELECT c.* FROM '.$CFG->prefix
.'data_records r LEFT JOIN '.
672 $CFG->prefix
.'data_content c ON c.recordid = r.id WHERE r.dataid = '.$id;
674 if ($contents = get_records_sql($sql)){
676 foreach($contents as $content){
678 $field = get_record('data_fields','id',$content->fieldid
);
679 if ($g = data_get_field($field, $data)){
680 $g->delete_content_files($id, $content->recordid
, $content->content
);
682 //delete the content itself
683 delete_records('data_content','id', $content->id
);
687 // delete all the records and fields
688 delete_records('data_records', 'dataid', $id);
689 delete_records('data_fields','dataid',$id);
691 // Delete the instance itself
693 $result = delete_records('data', 'id', $id);
695 data_grade_item_delete($data);
700 /************************************************************************
701 * returns a summary of data activity of this user *
702 ************************************************************************/
703 function data_user_outline($course, $user, $mod, $data) {
707 if ($countrecords = count_records('data_records', 'dataid', $data->id
, 'userid', $user->id
)) {
708 $result = new object();
709 $result->info
= get_string('numrecords', 'data', $countrecords);
710 $lastrecord = get_record_sql('SELECT id,timemodified FROM '.$CFG->prefix
.'data_records
711 WHERE dataid = '.$data->id
.' AND userid = '.$user->id
.'
712 ORDER BY timemodified DESC', true);
713 $result->time
= $lastrecord->timemodified
;
720 /************************************************************************
721 * Prints all the records uploaded by this user *
722 ************************************************************************/
723 function data_user_complete($course, $user, $mod, $data) {
725 if ($records = get_records_select('data_records', 'dataid = '.$data->id
.' AND userid = '.$user->id
,
726 'timemodified DESC')) {
728 data_print_template('singletemplate', $records, $data);
734 * Return grade for given user or all users.
736 * @param int $dataid id of data
737 * @param int $userid optional user id, 0 means all users
738 * @return array array of grades, false if none
740 function data_get_user_grades($data, $userid=0) {
743 $user = $userid ?
"AND u.id = $userid" : "";
745 $sql = "SELECT u.id, u.id AS userid, avg(drt.rating) AS rawgrade
746 FROM {$CFG->prefix}user u, {$CFG->prefix}data_records dr,
747 {$CFG->prefix}data_ratings drt
748 WHERE u.id = dr.userid AND dr.id = drt.recordid
749 AND drt.userid != u.id AND dr.dataid = $data->id
753 return get_records_sql($sql);
757 * Update grades by firing grade_updated event
759 * @param object $data null means all databases
760 * @param int $userid specific user only, 0 mean all
762 function data_update_grades($data=null, $userid=0, $nullifnone=true) {
764 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
765 require_once($CFG->libdir
.'/gradelib.php');
769 if ($grades = data_get_user_grades($data, $userid)) {
770 grade_update('mod/data', $data->course
, 'mod', 'data', $data->id
, 0, $grades);
772 } else if ($userid and $nullifnone) {
773 $grade = new object();
774 $grade->itemid
= $data->id
;
775 $grade->userid
= $userid;
776 $grade->rawgrade
= NULL;
777 grade_update('mod/data', $data->course
, 'mod', 'data', $data->id
, 0, $grade);
781 $sql = "SELECT d.*, cm.idnumber as cmidnumber
782 FROM {$CFG->prefix}data d, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
783 WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
784 if ($rs = get_recordset_sql($sql)) {
785 if ($rs->RecordCount() > 0) {
786 while ($data = rs_fetch_next_record($rs)) {
787 data_grade_item_update($data);
788 if ($data->assessed
) {
789 data_update_grades($data, 0, false);
799 * Update/create grade item for given data
801 * @param object $data object with extra cmidnumber
802 * @return object grade_item
804 function data_grade_item_update($data) {
806 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
807 require_once($CFG->libdir
.'/gradelib.php');
810 $params = array('itemname' =>$data->name
, 'idnumber' =>$data->cmidnumber
);
812 if (!$data->assessed
or $data->scale
== 0) {
813 $params['gradetype'] = GRADE_TYPE_NONE
;
815 } else if ($data->scale
> 0) {
816 $params['gradetype'] = GRADE_TYPE_VALUE
;
817 $params['grademax'] = $data->scale
;
818 $params['grademin'] = 0;
820 } else if ($data->scale
< 0) {
821 $params['gradetype'] = GRADE_TYPE_SCALE
;
822 $params['scaleid'] = -$data->scale
;
825 return grade_update('mod/data', $data->course
, 'mod', 'data', $data->id
, 0, NULL, $params);
829 * Delete grade item for given data
831 * @param object $data object
832 * @return object grade_item
834 function data_grade_item_delete($data) {
836 require_once($CFG->libdir
.'/gradelib.php');
838 return grade_update('mod/data', $data->course
, 'mod', 'data', $data->id
, 0, NULL, array('deleted'=>1));
841 /************************************************************************
842 * returns a list of participants of this database *
843 ************************************************************************/
844 function data_get_participants($dataid) {
845 //Returns the users with data in one data
846 //(users with records in data_records, data_comments and data_ratings)
849 $records = get_records_sql("SELECT DISTINCT u.id, u.id
850 FROM {$CFG->prefix}user u,
851 {$CFG->prefix}data_records r
852 WHERE r.dataid = '$dataid'
853 AND u.id = r.userid");
855 $comments = get_records_sql("SELECT DISTINCT u.id, u.id
856 FROM {$CFG->prefix}user u,
857 {$CFG->prefix}data_records r,
858 {$CFG->prefix}data_comments c
859 WHERE r.dataid = '$dataid'
861 AND r.id = c.recordid");
863 $ratings = get_records_sql("SELECT DISTINCT u.id, u.id
864 FROM {$CFG->prefix}user u,
865 {$CFG->prefix}data_records r,
866 {$CFG->prefix}data_ratings a
867 WHERE r.dataid = '$dataid'
869 AND r.id = a.recordid");
870 $participants = array();
873 foreach ($records as $record) {
874 $participants[$record->id
] = $record;
878 foreach ($comments as $comment) {
879 $participants[$comment->id
] = $comment;
883 foreach ($ratings as $rating) {
884 $participants[$rating->id
] = $rating;
888 return $participants;
891 function data_get_coursemodule_info($coursemodule) {
892 /// Given a course_module object, this function returns any
893 /// "extra" information that may be needed when printing
894 /// this activity in a course listing.
896 /// See get_array_of_activities() in course/lib.php
907 /************************************************************************
908 * takes a list of records, the current data, a search string, *
909 * and mode to display prints the translated template *
910 * input @param array $records *
911 * @param object $data *
912 * @param string $search *
913 * @param string $template *
915 ************************************************************************/
916 function data_print_template($template, $records, $data, $search='',$page=0, $return=false) {
919 $cm = get_coursemodule_from_instance('data', $data->id
);
920 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
922 static $fields = NULL;
924 static $dataid = NULL;
926 if (empty($dataid)) {
928 } else if ($dataid != $data->id
) {
932 if (empty($fields)) {
933 $fieldrecords = get_records('data_fields','dataid', $data->id
);
934 foreach ($fieldrecords as $fieldrecord) {
935 $fields[]= data_get_field($fieldrecord, $data);
937 $isteacher = has_capability('mod/data:managetemplates', $context);
940 if (empty($records)) {
944 foreach ($records as $record) { /// Might be just one for the single template
948 $replacement = array();
950 /// Then we generate strings to replace for normal tags
951 foreach ($fields as $field) {
952 $patterns[]='[['.$field->field
->name
.']]';
953 $replacement[] = highlight($search, $field->display_browse_field($record->id
, $template));
956 /// Replacing special tags (##Edit##, ##Delete##, ##More##)
957 $patterns[]='##edit##';
958 $patterns[]='##delete##';
959 if (has_capability('mod/data:manageentries', $context) or data_isowner($record->id
)) {
960 $replacement[] = '<a href="'.$CFG->wwwroot
.'/mod/data/edit.php?d='
961 .$data->id
.'&rid='.$record->id
.'&sesskey='.sesskey().'"><img src="'.$CFG->pixpath
.'/t/edit.gif" class="iconsmall" alt="'.get_string('edit').'" title="'.get_string('edit').'" /></a>';
962 $replacement[] = '<a href="'.$CFG->wwwroot
.'/mod/data/view.php?d='
963 .$data->id
.'&delete='.$record->id
.'&sesskey='.sesskey().'"><img src="'.$CFG->pixpath
.'/t/delete.gif" class="iconsmall" alt="'.get_string('delete').'" title="'.get_string('delete').'" /></a>';
968 $patterns[]='##more##';
969 $replacement[] = '<a href="'.$CFG->wwwroot
.'/mod/data/view.php?d='.$data->id
.'&rid='.$record->id
.'"><img src="'.$CFG->pixpath
.'/i/search.gif" class="iconsmall" alt="'.get_string('more', 'data').'" title="'.get_string('more', 'data').'" /></a>';
971 $patterns[]='##moreurl##';
972 $replacement[] = $CFG->wwwroot
.'/mod/data/view.php?d='.$data->id
.'&rid='.$record->id
;
974 $patterns[]='##user##';
975 $replacement[] = '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.$record->userid
.
976 '&course='.$data->course
.'">'.fullname($record).'</a>';
978 $patterns[]='##approve##';
979 if (has_capability('mod/data:approve', $context) && ($data->approval
) && (!$record->approved
)){
980 $replacement[] = '<a href="'.$CFG->wwwroot
.'/mod/data/view.php?d='.$data->id
.'&approve='.$record->id
.'&sesskey='.sesskey().'"><img src="'.$CFG->pixpath
.'/i/approve.gif" class="iconsmall" alt="'.get_string('approve').'" /></a>';
985 $patterns[]='##comments##';
986 if (($template == 'listtemplate') && ($data->comments
)) {
987 $comments = count_records('data_comments','recordid',$record->id
);
988 $replacement[] = '<a href="view.php?rid='.$record->id
.'#comments">'.get_string('commentsn','data', $comments).'</a>';
993 ///actual replacement of the tags
994 $newtext = str_ireplace($patterns, $replacement, $data->{$template});
996 /// no more html formatting and filtering - see MDL-6635
1002 // hack alert - return is always false in singletemplate anyway ;-)
1003 /**********************************
1004 * Printing Ratings Form *
1005 *********************************/
1006 if ($template == 'singletemplate') { //prints ratings options
1007 data_print_ratings($data, $record);
1010 /**********************************
1011 * Printing Ratings Form *
1012 *********************************/
1013 if (($template == 'singletemplate') && ($data->comments
)) { //prints ratings options
1015 data_print_comments($data, $record, $page);
1022 /************************************************************************
1023 * function that takes in the current data, number of items per page, *
1024 * a search string and prints a preference box in view.php *
1026 * This preference box prints a searchable advanced search template if *
1027 * a) A template is defined *
1028 * b) The advanced search checkbox is checked. *
1030 * input @param object $data *
1031 * @param int $perpage *
1032 * @param string $search *
1034 ************************************************************************/
1035 function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
1038 $cm = get_coursemodule_from_instance('data', $data->id
);
1039 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1040 echo '<br /><div class="datapreferences">';
1041 echo '<form id="options" action="view.php" method="get">';
1043 echo '<input type="hidden" name="d" value="'.$data->id
.'" />';
1044 if ($mode =='asearch') {
1046 echo '<input type="hidden" name="mode" value="list" />';
1048 echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
1049 $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
1050 20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
1051 choose_from_menu($pagesizes, 'perpage', $perpage, '', '', '0', false, false, 0, 'pref_perpage');
1052 echo '<div id="reg_search" style="display: ';
1059 echo ';" > <label for="pref_search">'.get_string('search').'</label> <input type="text" size="16" name="search" id= "pref_search" value="'.s($search).'" /></div>';
1060 echo ' <label for="pref_sortby">'.get_string('sortby').'</label> ';
1061 //foreach field, print the option
1062 $fields = get_records('data_fields','dataid',$data->id
, 'name');
1063 echo '<select name="sort" id="pref_sortby"><option value="0">'.get_string('dateentered','data').'</option>';
1064 foreach ($fields as $field) {
1065 if ($field->id
== $sort) {
1066 echo '<option value="'.$field->id
.'" selected="selected">'.$field->name
.'</option>';
1068 echo '<option value="'.$field->id
.'">'.$field->name
.'</option>';
1072 echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
1073 echo '<select id="pref_order" name="order">';
1074 if ($order == 'ASC') {
1075 echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
1077 echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1079 if ($order == 'DESC') {
1080 echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
1082 echo '<option value="DESC">'.get_string('descending','data').'</option>';
1087 $checked = ' checked="checked" ';
1094 <script type="text/javascript">
1097 // javascript for hiding/displaying advanced search form
1099 function showHideAdvSearch(checked) {
1100 var divs = document.getElementsByTagName(\'div\');
1101 for(i=0;i<divs.length;i++) {
1102 if(divs[i].id.match(\'data_adv_form\')) {
1104 divs[i].style.display = \'inline\';
1107 divs[i].style.display = \'none\';
1110 else if (divs[i].id.match(\'reg_search\')) {
1112 divs[i].style.display = \'inline\';
1115 divs[i].style.display = \'none\';
1123 echo ' <input type="checkbox" name="advanced" value="1" '.$checked.' onchange="showHideAdvSearch(this.checked);" />'.get_string('advancedsearch', 'data');
1124 echo ' <input type="submit" value="'.get_string('savesettings','data').'" />';
1127 echo '<div class="dataadvancedsearch" id="data_adv_form" style="display: ';
1135 echo ';margin-left:auto;margin-right:auto;" >';
1136 echo '<table class="boxaligncenter">';
1138 // print ASC or DESC
1139 echo '<tr><td colspan="2"> </td></tr>';
1142 // Determine if we are printing all fields for advanced search, or the template for advanced search
1143 // If a template is not defined, use the deafault template and display all fields.
1144 if(empty($data->asearchtemplate
)) {
1145 data_generate_default_template($data, 'asearchtemplate');
1148 static $fields = NULL;
1150 static $dataid = NULL;
1152 if (empty($dataid)) {
1153 $dataid = $data->id
;
1154 } else if ($dataid != $data->id
) {
1158 if (empty($fields)) {
1159 $fieldrecords = get_records('data_fields','dataid', $data->id
);
1160 foreach ($fieldrecords as $fieldrecord) {
1161 $fields[]= data_get_field($fieldrecord, $data);
1164 $isteacher = has_capability('mod/data:managetemplates', $context);
1168 $patterns = array();
1169 $replacement = array();
1171 /// Then we generate strings to replace for normal tags
1172 foreach ($fields as $field) {
1173 $patterns[]='/\[\['.$field->field
->name
.'\]\]/i';
1174 $searchfield = data_get_field_from_id($field->field
->id
, $data);
1175 if (!empty($search_array[$field->field
->id
]->data
)) {
1176 $replacement[] = $searchfield->display_search_field($search_array[$field->field
->id
]->data
);
1178 $replacement[] = $searchfield->display_search_field();
1182 ///actual replacement of the tags
1183 $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate
);
1184 $options->para
=false;
1185 $options->noclean
=true;
1187 echo format_text($newtext, FORMAT_HTML
, $options);
1190 echo '<tr><td colspan="4" style="text-align: center;"><br/><input type="submit" value="'.get_string('savesettings','data').'" /><input type="reset" value="'.get_string('resetsettings','data').'" /></td></tr>';
1200 function data_print_ratings($data, $record) {
1203 $cm = get_coursemodule_from_instance('data', $data->id
);
1204 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1206 if ($data->assessed
and !empty($USER->id
) and (has_capability('mod/data:rate', $context) or has_capability('mod/data:viewrating', $context) or data_isowner($record->id
))) {
1207 if ($ratingsscale = make_grades_menu($data->scale
)) {
1208 $ratingsmenuused = false;
1210 echo '<div class="ratings" style="text-align:center">';
1211 echo '<form id="form" method="post" action="rate.php">';
1212 echo '<input type="hidden" name="dataid" value="'.$data->id
.'" />';
1214 if (has_capability('mod/data:rate', $context) and !data_isowner($record->id
)) {
1215 data_print_ratings_mean($record->id
, $ratingsscale, has_capability('mod/data:viewrating', $context));
1217 data_print_rating_menu($record->id
, $USER->id
, $ratingsscale);
1218 $ratingsmenuused = true;
1221 data_print_ratings_mean($record->id
, $ratingsscale, true);
1224 if ($data->scale
< 0) {
1225 if ($scale = get_record('scale', 'id', abs($data->scale
))) {
1226 print_scale_menu_helpbutton($data->course
, $scale );
1230 if ($ratingsmenuused) {
1231 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1232 echo '<input type="submit" value="'.get_string('sendinratings', 'data').'" />';
1240 function data_print_ratings_mean($recordid, $scale, $link=true) {
1241 /// Print the multiple ratings on a post given to the current user by others.
1242 /// Scale is an array of ratings
1246 $mean = data_get_ratings_mean($recordid, $scale);
1250 if (empty($strratings)) {
1251 $strratings = get_string("ratings", "data");
1254 echo "$strratings: ";
1256 link_to_popup_window ("/mod/data/report.php?id=$recordid", "ratings", $mean, 400, 600);
1264 function data_get_ratings_mean($recordid, $scale, $ratings=NULL) {
1265 /// Return the mean rating of a post given to the current user by others.
1266 /// Scale is an array of possible ratings in the scale
1267 /// Ratings is an optional simple array of actual ratings (just integers)
1271 if ($rates = get_records("data_ratings", "recordid", $recordid)) {
1272 foreach ($rates as $rate) {
1273 $ratings[] = $rate->rating
;
1278 $count = count($ratings);
1283 } else if ($count == 1) {
1284 return $scale[$ratings[0]];
1288 foreach ($ratings as $rating) {
1291 $mean = round( ((float)$total/(float)$count) +
0.001); // Little fudge factor so that 0.5 goes UP
1293 if (isset($scale[$mean])) {
1294 return $scale[$mean]." ($count)";
1296 return "$mean ($count)"; // Should never happen, hopefully
1302 function data_print_rating_menu($recordid, $userid, $scale) {
1303 /// Print the menu of ratings as part of a larger form.
1304 /// If the post has already been - set that value.
1305 /// Scale is an array of ratings
1309 if (!$rating = get_record("data_ratings", "userid", $userid, "recordid", $recordid)) {
1310 $rating->rating
= -999;
1313 if (empty($strrate)) {
1314 $strrate = get_string("rate", "data");
1317 choose_from_menu($scale, $recordid, $rating->rating
, "$strrate...", '', -999);
1321 function data_get_ratings($recordid, $sort="u.firstname ASC") {
1322 /// Returns a list of ratings for a particular post - sorted.
1324 return get_records_sql("SELECT u.*, r.rating
1325 FROM {$CFG->prefix}data_ratings r,
1326 {$CFG->prefix}user u
1327 WHERE r.recordid = $recordid
1334 //prints all comments + a text box for adding additional comment
1335 function data_print_comments($data, $record, $page=0, $mform=false) {
1339 echo '<a name="comments"></a>';
1341 if ($comments = get_records('data_comments','recordid',$record->id
)) {
1342 foreach ($comments as $comment) {
1343 data_print_comment($data, $comment, $page);
1348 if (!isloggedin() or isguest()) {
1352 $editor = optional_param('addcomment', 0, PARAM_BOOL
);
1354 if (!$mform and !$editor) {
1355 echo '<div class="newcomment" style="text-align:center">';
1356 echo '<a href="view.php?d='.$data->id
.'&page='.$page.'&mode=single&addcomment=1">'.get_string('addcomment', 'data').'</a>';
1360 require_once('comment_form.php');
1361 $mform = new mod_data_comment_form('comment.php');
1362 $mform->set_data(array('mode'=>'add', 'page'=>$page, 'rid'=>$record->id
));
1364 echo '<div class="newcomment" style="text-align:center">';
1370 //prints a single comment entry
1371 function data_print_comment($data, $comment, $page=0) {
1375 $cm = get_coursemodule_from_instance('data', $data->id
);
1376 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1378 $stredit = get_string('edit');
1379 $strdelete = get_string('delete');
1381 $user = get_record('user','id',$comment->userid
);
1383 echo '<table cellspacing="0" align="center" width="50%" class="datacomment forumpost">';
1385 echo '<tr class="header"><td class="picture left">';
1386 print_user_picture($comment->userid
, $data->course
, $user->picture
);
1389 echo '<td class="topic starter" align="left"><div class="author">';
1390 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $context));
1392 $by->name
= '<a href="'.$CFG->wwwroot
.'/user/view.php?id='.
1393 $user->id
.'&course='.$data->course
.'">'.$fullname.'</a>';
1394 $by->date
= userdate($comment->modified
);
1395 print_string('bynameondate', 'data', $by);
1396 echo '</div></td></tr>';
1398 echo '<tr><td class="left side">';
1399 if ($groups = user_group($data->course
, $comment->userid
)) {
1400 print_group_picture($groups, $data->course
, false, false, true);
1407 echo '</td><td class="content" align="left">'."\n";
1409 // Print whole message
1410 echo format_text($comment->content
, $comment->format
);
1414 echo '<div class="commands">';
1415 if (data_isowner($comment->recordid
) or has_capability('mod/data:managecomments', $context)) {
1416 echo '<a href="'.$CFG->wwwroot
.'/mod/data/comment.php?rid='.$comment->recordid
.'&mode=edit&commentid='.$comment->id
.'&page='.$page.'">'.$stredit.'</a>';
1417 echo '| <a href="'.$CFG->wwwroot
.'/mod/data/comment.php?rid='.$comment->recordid
.'&mode=delete&commentid='.$comment->id
.'&page='.$page.'">'.$strdelete.'</a>';
1422 echo '</td></tr></table>'."\n\n";
1426 // For Participantion Reports
1427 function data_get_view_actions() {
1428 return array('view');
1431 function data_get_post_actions() {
1432 return array('add','update','record delete');
1435 function data_fieldname_exists($name, $dataid, $fieldid=0) {
1438 $LIKE = sql_ilike();
1440 return record_exists_sql("SELECT * from {$CFG->prefix}data_fields df
1441 WHERE df.name $LIKE '$name' AND df.dataid = $dataid
1442 AND ((df.id < $fieldid) OR (df.id > $fieldid))");
1444 return record_exists_sql("SELECT * from {$CFG->prefix}data_fields df
1445 WHERE df.name $LIKE '$name' AND df.dataid = $dataid");
1449 function data_convert_arrays_to_strings(&$fieldinput) {
1450 foreach ($fieldinput as $key => $val) {
1451 if (is_array($val)) {
1453 foreach ($val as $inner) {
1454 $str .= $inner . ',';
1456 $str = substr($str, 0, -1);
1458 $fieldinput->$key = $str;
1465 * Converts a database (module instance) to use the Roles System
1466 * @param $data - a data object with the same attributes as a record
1467 * from the data database table
1468 * @param $datamodid - the id of the data module, from the modules table
1469 * @param $teacherroles - array of roles that have moodle/legacy:teacher
1470 * @param $studentroles - array of roles that have moodle/legacy:student
1471 * @param $guestroles - array of roles that have moodle/legacy:guest
1472 * @param $cmid - the course_module id for this data instance
1473 * @return boolean - data module was converted or not
1475 function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
1479 if (!isset($data->participants
) && !isset($data->assesspublic
)
1480 && !isset($data->groupmode
)) {
1481 // We assume that this database has already been converted to use the
1482 // Roles System. above fields get dropped the data module has been
1483 // upgraded to use Roles.
1488 // We were not given the course_module id. Try to find it.
1489 if (!$cm = get_coursemodule_from_instance('data', $data->id
)) {
1490 notify('Could not get the course module for the data');
1496 $context = get_context_instance(CONTEXT_MODULE
, $cmid);
1499 // $data->participants:
1500 // 1 - Only teachers can add entries
1501 // 3 - Teachers and students can add entries
1502 switch ($data->participants
) {
1504 foreach ($studentroles as $studentrole) {
1505 assign_capability('mod/data:writeentry', CAP_PREVENT
, $studentrole->id
, $context->id
);
1507 foreach ($teacherroles as $teacherrole) {
1508 assign_capability('mod/data:writeentry', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1512 foreach ($studentroles as $studentrole) {
1513 assign_capability('mod/data:writeentry', CAP_ALLOW
, $studentrole->id
, $context->id
);
1515 foreach ($teacherroles as $teacherrole) {
1516 assign_capability('mod/data:writeentry', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1522 // 2 - Only teachers can rate posts
1523 // 1 - Everyone can rate posts
1524 // 0 - No one can rate posts
1525 switch ($data->assessed
) {
1527 foreach ($studentroles as $studentrole) {
1528 assign_capability('mod/data:rate', CAP_PREVENT
, $studentrole->id
, $context->id
);
1530 foreach ($teacherroles as $teacherrole) {
1531 assign_capability('mod/data:rate', CAP_PREVENT
, $teacherrole->id
, $context->id
);
1535 foreach ($studentroles as $studentrole) {
1536 assign_capability('mod/data:rate', CAP_ALLOW
, $studentrole->id
, $context->id
);
1538 foreach ($teacherroles as $teacherrole) {
1539 assign_capability('mod/data:rate', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1543 foreach ($studentroles as $studentrole) {
1544 assign_capability('mod/data:rate', CAP_PREVENT
, $studentrole->id
, $context->id
);
1546 foreach ($teacherroles as $teacherrole) {
1547 assign_capability('mod/data:rate', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1552 // $data->assesspublic:
1553 // 0 - Students can only see their own ratings
1554 // 1 - Students can see everyone's ratings
1555 switch ($data->assesspublic
) {
1557 foreach ($studentroles as $studentrole) {
1558 assign_capability('mod/data:viewrating', CAP_PREVENT
, $studentrole->id
, $context->id
);
1560 foreach ($teacherroles as $teacherrole) {
1561 assign_capability('mod/data:viewrating', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1565 foreach ($studentroles as $studentrole) {
1566 assign_capability('mod/data:viewrating', CAP_ALLOW
, $studentrole->id
, $context->id
);
1568 foreach ($teacherroles as $teacherrole) {
1569 assign_capability('mod/data:viewrating', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1575 $cm = get_record('course_modules', 'id', $cmid);
1580 // 1 - Separate groups
1581 // 2 - Visible groups
1582 switch ($cm->groupmode
) {
1586 foreach ($studentroles as $studentrole) {
1587 assign_capability('moodle/site:accessallgroups', CAP_PREVENT
, $studentrole->id
, $context->id
);
1589 foreach ($teacherroles as $teacherrole) {
1590 assign_capability('moodle/site:accessallgroups', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1594 foreach ($studentroles as $studentrole) {
1595 assign_capability('moodle/site:accessallgroups', CAP_ALLOW
, $studentrole->id
, $context->id
);
1597 foreach ($teacherroles as $teacherrole) {
1598 assign_capability('moodle/site:accessallgroups', CAP_ALLOW
, $teacherrole->id
, $context->id
);
1606 * Returns the best name to show for a preset
1608 function data_preset_name($shortname, $path) {
1610 /// We are looking inside the preset itself as a first choice, but also in normal data directory
1611 $string = get_string('presetname'.$shortname, 'data', NULL, $path.'/lang/');
1613 if (substr($string, 0, 1) == '[') {
1621 * Returns an array of all the available presets
1623 function data_get_available_presets($context) {
1628 if ($dirs = get_list_of_plugins('mod/data/preset')) {
1629 foreach ($dirs as $dir) {
1630 $fulldir = $CFG->dirroot
.'/mod/data/preset/'.$dir;
1632 if (is_directory_a_preset($fulldir)) {
1633 $preset = new object;
1634 $preset->path
= $fulldir;
1635 $preset->userid
= 0;
1636 $preset->shortname
= $dir;
1637 $preset->name
= data_preset_name($dir, $fulldir);
1638 if (file_exists($fulldir.'/screenshot.jpg')) {
1639 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.jpg';
1640 } else if (file_exists($fulldir.'/screenshot.png')) {
1641 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.png';
1642 } else if (file_exists($fulldir.'/screenshot.gif')) {
1643 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.gif';
1645 $presets[] = $preset;
1650 if ($userids = get_list_of_plugins('data/preset', '', $CFG->dataroot
)) {
1651 foreach ($userids as $userid) {
1652 $fulldir = $CFG->dataroot
.'/data/preset/'.$userid;
1654 if ($userid == 0 ||
$USER->id
== $userid ||
has_capability('mod/data:viewalluserpresets', $context)) {
1656 if ($dirs = get_list_of_plugins('data/preset/'.$userid, '', $CFG->dataroot
)) {
1657 foreach ($dirs as $dir) {
1658 $fulldir = $CFG->dataroot
.'/data/preset/'.$userid.'/'.$dir;
1660 if (is_directory_a_preset($fulldir)) {
1661 $preset = new object;
1662 $preset->path
= $fulldir;
1663 $preset->userid
= $userid;
1664 $preset->shortname
= $dir;
1665 $preset->name
= data_preset_name($dir, $fulldir);
1666 if (file_exists($fulldir.'/screenshot.jpg')) {
1667 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.jpg';
1668 } else if (file_exists($fulldir.'/screenshot.png')) {
1669 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.png';
1670 } else if (file_exists($fulldir.'/screenshot.gif')) {
1671 $preset->screenshot
= $CFG->wwwroot
.'/mod/data/preset/'.$dir.'/screenshot.gif';
1673 $presets[] = $preset;
1685 function data_print_header($course, $cm, $data, $currenttab='') {
1687 global $CFG, $displaynoticegood, $displaynoticebad;
1689 $strdata = get_string('modulenameplural','data');
1691 $navlinks = array();
1692 $navlinks[] = array('name' => $strdata, 'link' => "index.php?id=$course->id", 'type' => 'activity');
1693 $navlinks[] = array('name' => $data->name
, 'link' => '', 'type' => 'activityinstance');
1695 $navigation = build_navigation($navlinks);
1697 print_header_simple($data->name
, '', $navigation,
1698 '', '', true, update_module_button($cm->id
, $course->id
, get_string('modulename', 'data')),
1699 navmenu($course, $cm));
1701 print_heading(format_string($data->name
));
1703 /// Groups needed for Add entry tab
1704 $groupmode = groupmode($course, $cm);
1705 $currentgroup = get_and_set_current_group($course, $groupmode);
1710 include_once('tabs.php');
1713 /// Print any notices
1715 if (!empty($displaynoticegood)) {
1716 notify($displaynoticegood, 'notifysuccess'); // good (usually green)
1717 } else if (!empty($displaynoticebad)) {
1718 notify($displaynoticebad); // bad (usuually red)
1722 function data_user_can_add_entry($data, $currentgroup, $groupmode) {
1725 if (!$cm = get_coursemodule_from_instance('data', $data->id
)) {
1726 error('Course Module ID was incorrect');
1728 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
1730 if (!has_capability('mod/data:writeentry', $context) and !has_capability('mod/data:manageentries',$context)) {
1734 if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
1738 if ($currentgroup) {
1739 return ismember($currentgroup);
1741 //else it might be group 0 in visible mode
1742 if ($groupmode == VISIBLEGROUPS
){
1750 // pulled directly out of preset.php Penny 20070426
1752 function is_directory_a_preset($directory) {
1753 $directory = rtrim($directory, '/\\') . '/';
1754 if (file_exists($directory.'singletemplate.html') &&
1755 file_exists($directory.'listtemplate.html') &&
1756 file_exists($directory.'listtemplateheader.html') &&
1757 file_exists($directory.'listtemplatefooter.html') &&
1758 file_exists($directory.'addtemplate.html') &&
1759 file_exists($directory.'rsstemplate.html') &&
1760 file_exists($directory.'rsstitletemplate.html') &&
1761 file_exists($directory.'csstemplate.css') &&
1762 file_exists($directory.'jstemplate.js') &&
1763 file_exists($directory.'preset.xml')) return true;
1768 function clean_preset($folder) {
1769 if (@unlink
($folder.'/singletemplate.html') &&
1770 @unlink
($folder.'/listtemplate.html') &&
1771 @unlink
($folder.'/listtemplateheader.html') &&
1772 @unlink
($folder.'/listtemplatefooter.html') &&
1773 @unlink
($folder.'/addtemplate.html') &&
1774 @unlink
($folder.'/rsstemplate.html') &&
1775 @unlink
($folder.'/rsstitletemplate.html') &&
1776 @unlink
($folder.'/csstemplate.css') &&
1777 @unlink
($folder.'/jstemplate.js') &&
1778 @unlink
($folder.'/preset.xml')) {
1785 function data_presets_export($course, $cm, $data) {
1787 /* Info Collected. Now need to make files in moodledata/temp */
1788 $tempfolder = $CFG->dataroot
.'/temp';
1789 $singletemplate = fopen($tempfolder.'/singletemplate.html', 'w');
1790 $listtemplate = fopen($tempfolder.'/listtemplate.html', 'w');
1791 $listtemplateheader = fopen($tempfolder.'/listtemplateheader.html', 'w');
1792 $listtemplatefooter = fopen($tempfolder.'/listtemplatefooter.html', 'w');
1793 $addtemplate = fopen($tempfolder.'/addtemplate.html', 'w');
1794 $rsstemplate = fopen($tempfolder.'/rsstemplate.html', 'w');
1795 $rsstitletemplate = fopen($tempfolder.'/rsstitletemplate.html', 'w');
1796 $csstemplate = fopen($tempfolder.'/csstemplate.css', 'w');
1797 $jstemplate = fopen($tempfolder.'/jstemplate.js', 'w');
1799 fwrite($singletemplate, $data->singletemplate
);
1800 fwrite($listtemplate, $data->listtemplate
);
1801 fwrite($listtemplateheader, $data->listtemplateheader
);
1802 fwrite($listtemplatefooter, $data->listtemplatefooter
);
1803 fwrite($addtemplate, $data->addtemplate
);
1804 fwrite($rsstemplate, $data->rsstemplate
);
1805 fwrite($rsstitletemplate, $data->rsstitletemplate
);
1806 fwrite($csstemplate, $data->csstemplate
);
1807 fwrite($jstemplate, $data->jstemplate
);
1809 fclose($singletemplate);
1810 fclose($listtemplate);
1811 fclose($listtemplateheader);
1812 fclose($listtemplatefooter);
1813 fclose($addtemplate);
1814 fclose($rsstemplate);
1815 fclose($rsstitletemplate);
1816 fclose($csstemplate);
1817 fclose($jstemplate);
1819 /* All the display data is now done. Now assemble preset.xml */
1820 $fields = get_records('data_fields', 'dataid', $data->id
);
1821 $presetfile = fopen($tempfolder.'/preset.xml', 'w');
1822 $presetxml = "<preset>\n\n";
1824 /* Database settings first. Name not included? */
1825 $settingssaved = array('intro', 'comments',
1826 'requiredentries', 'requiredentriestoview', 'maxentries',
1827 'rssarticles', 'approval', 'scale', 'assessed',
1828 'defaultsort', 'defaultsortdir', 'editany');
1830 $presetxml .= "<settings>\n";
1831 foreach ($settingssaved as $setting) {
1832 $presetxml .= "<$setting>{$data->$setting}</$setting>\n";
1834 $presetxml .= "</settings>\n\n";
1836 /* Now for the fields. Grabs all settings that are non-empty */
1837 if (!empty($fields)) {
1838 foreach ($fields as $field) {
1839 $presetxml .= "<field>\n";
1840 foreach ($field as $key => $value) {
1841 if ($value != '' && $key != 'id' && $key != 'dataid') {
1842 $presetxml .= "<$key>$value</$key>\n";
1845 $presetxml .= "</field>\n\n";
1849 $presetxml .= "</preset>";
1850 fwrite($presetfile, $presetxml);
1851 fclose($presetfile);
1853 /* Check all is well */
1854 if (!is_directory_a_preset($tempfolder)) {
1855 error("Not all files generated!");
1859 'singletemplate.html',
1860 'listtemplate.html',
1861 'listtemplateheader.html',
1862 'listtemplatefooter.html',
1865 'rsstitletemplate.html',
1870 foreach ($filelist as $key => $file) {
1871 $filelist[$key] = $tempfolder.'/'.$filelist[$key];
1874 @unlink
($tempfolder.'/export.zip');
1875 $status = zip_files($filelist, $tempfolder.'/export.zip');
1877 /* made the zip... now return the filename for storage.*/
1878 return $tempfolder.'/export.zip';
1883 class PresetImporter
{
1884 function PresetImporter($course, $cm, $data, $userid, $shortname) {
1886 $this->course
= $course;
1888 $this->data
= $data;
1889 $this->userid
= $userid;
1890 $this->shortname
= $shortname;
1891 $this->folder
= data_preset_path($course, $userid, $shortname);
1894 function get_settings() {
1897 if (!is_directory_a_preset($this->folder
)) {
1898 error("$this->userid/$this->shortname Not a preset");
1902 $presetxml = file_get_contents($this->folder
.'/preset.xml');
1903 $parsedxml = xmlize($presetxml);
1905 /* First, do settings. Put in user friendly array. */
1906 $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
1907 $settings = new StdClass();
1909 foreach ($settingsarray as $setting => $value) {
1910 $settings->$setting = $value[0]['#'];
1913 /* Now work out fields to user friendly array */
1914 $fieldsarray = $parsedxml['preset']['#']['field'];
1916 foreach ($fieldsarray as $field) {
1917 $f = new StdClass();
1918 foreach ($field['#'] as $param => $value) {
1919 $f->$param = $value[0]['#'];
1921 $f->dataid
= $this->data
->id
;
1922 $f->type
= clean_param($f->type
, PARAM_ALPHA
);
1926 /* Now add the HTML templates to the settings array so we can update d */
1927 $settings->singletemplate
= file_get_contents($this->folder
."/singletemplate.html");
1928 $settings->listtemplate
= file_get_contents($this->folder
."/listtemplate.html");
1929 $settings->listtemplateheader
= file_get_contents($this->folder
."/listtemplateheader.html");
1930 $settings->listtemplatefooter
= file_get_contents($this->folder
."/listtemplatefooter.html");
1931 $settings->addtemplate
= file_get_contents($this->folder
."/addtemplate.html");
1932 $settings->rsstemplate
= file_get_contents($this->folder
."/rsstemplate.html");
1933 $settings->rsstitletemplate
= file_get_contents($this->folder
."/rsstitletemplate.html");
1934 $settings->csstemplate
= file_get_contents($this->folder
."/csstemplate.css");
1935 $settings->jstemplate
= file_get_contents($this->folder
."/jstemplate.js");
1937 $settings->instance
= $this->data
->id
;
1939 /* Now we look at the current structure (if any) to work out whether we need to clear db
1941 $currentfields = array();
1942 $currentfields = get_records('data_fields', 'dataid', $this->data
->id
);
1944 return array($settings, $fields, $currentfields);
1947 function import_options() {
1948 if (!confirm_sesskey()) {
1949 error("Sesskey Invalid");
1952 $strblank = get_string('blank', 'data');
1953 $strnofields = get_string('nofields', 'data');
1954 $strcontinue = get_string('continue');
1955 $strwarning = get_string('mappingwarning', 'data');
1956 $strfieldmappings = get_string('fieldmappings', 'data');
1957 $strnew = get_string('new');
1958 $strold = get_string('old');
1960 $sesskey = sesskey();
1962 list($settings, $newfields, $currentfields) = $this->get_settings();
1964 echo '<div style="text-align:center"><form action="preset.php" method="post">';
1965 echo '<fieldset class="invisiblefieldset">';
1966 echo '<input type="hidden" name="action" value="finishimport" />';
1967 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1968 echo '<input type="hidden" name="d" value="'.$this->data
->id
.'" />';
1969 echo '<input type="hidden" name="fullname" value="'.$this->userid
.'/'.$this->shortname
.'" />';
1971 if (!empty($currentfields) && !empty($newfields)) {
1972 echo "<h3>$strfieldmappings ";
1973 helpbutton('fieldmappings', '', 'data');
1974 echo '</h3><table>';
1976 foreach ($newfields as $nid => $newfield) {
1977 echo "<tr><td><label for=\"id_$newfield->name\">$newfield->name</label></td>";
1978 echo '<td><select name="field_'.$nid.'" id="id_'.$newfield->name
.'">';
1981 foreach ($currentfields as $cid => $currentfield) {
1982 if ($currentfield->type
== $newfield->type
) {
1983 if ($currentfield->name
== $newfield->name
) {
1984 echo '<option value="'.$cid.'" selected="selected">'.$currentfield->name
.'</option>';
1988 echo '<option value="$cid">'.$currentfield->name
.'</option>';
1994 echo '<option value="-1">-</option>';
1996 echo '<option value="-1" selected="selected">-</option>';
1997 echo '</select></td></tr>';
2000 echo "<p>$strwarning</p>";
2002 else if (empty($newfields)) {
2003 error("New preset has no defined fields!");
2005 echo '<input type="submit" value="'.$strcontinue.'" /></fieldset></form></div>';
2012 list($settings, $newfields, $currentfields) = $this->get_settings();
2013 $preservedfields = array();
2015 /* Maps fields and makes new ones */
2016 if (!empty($newfields)) {
2017 /* We require an injective mapping, and need to know what to protect */
2018 foreach ($newfields as $nid => $newfield) {
2019 $cid = optional_param("field_$nid", -1, PARAM_INT
);
2020 if ($cid == -1) continue;
2022 if (array_key_exists($cid, $preservedfields)) error("Not an injective map");
2023 else $preservedfields[$cid] = true;
2026 foreach ($newfields as $nid => $newfield) {
2027 $cid = optional_param("field_$nid", -1, PARAM_INT
);
2029 /* A mapping. Just need to change field params. Data kept. */
2030 if ($cid != -1 and isset($currentfields[$cid])) {
2031 $fieldobject = data_get_field_from_id($currentfields[$cid]->id
, $this->data
);
2032 foreach ($newfield as $param => $value) {
2033 if ($param != "id") {
2034 $fieldobject->field
->$param = $value;
2037 unset($fieldobject->field
->similarfield
);
2038 $fieldobject->update_field();
2039 unset($fieldobject);
2041 /* Make a new field */
2043 include_once("field/$newfield->type/field.class.php");
2045 if (!isset($newfield->description
)) {
2046 $newfield->description
= '';
2048 $classname = 'data_field_'.$newfield->type
;
2049 $fieldclass = new $classname($newfield, $this->data
);
2050 $fieldclass->insert_field();
2056 /* Get rid of all old unused data */
2057 if (!empty($preservedfields)) {
2058 foreach ($currentfields as $cid => $currentfield) {
2059 if (!array_key_exists($cid, $preservedfields)) {
2060 /* Data not used anymore so wipe! */
2061 print "Deleting field $currentfield->name<br />";
2063 $id = $currentfield->id
;
2064 //Why delete existing data records and related comments/ratings??
2066 if ($content = get_records('data_content', 'fieldid', $id)) {
2067 foreach ($content as $item) {
2068 delete_records('data_ratings', 'recordid', $item->recordid);
2069 delete_records('data_comments', 'recordid', $item->recordid);
2070 delete_records('data_records', 'id', $item->recordid);
2073 delete_records('data_content', 'fieldid', $id);
2074 delete_records('data_fields', 'id', $id);
2079 data_update_instance(addslashes_object($settings));
2081 if (strstr($this->folder
, '/temp/')) clean_preset($this->folder
); /* Removes the temporary files */
2086 function data_preset_path($course, $userid, $shortname) {
2089 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2091 $userid = (int)$userid;
2093 if ($userid > 0 && ($userid == $USER->id ||
has_capability('mod/data:viewalluserpresets', $context))) {
2094 return $CFG->dataroot
.'/data/preset/'.$userid.'/'.$shortname;
2095 } else if ($userid == 0) {
2096 return $CFG->dirroot
.'/mod/data/preset/'.$shortname;
2097 } else if ($userid < 0) {
2098 return $CFG->dataroot
.'/temp/data/'.-$userid.'/'.$shortname;
2101 return 'Does it disturb you that this code will never run?';