MDL-11517 reserved word MOD used in table alias in questions backup code
[moodle-pu.git] / mod / data / view.php
blobe17e53b9ce4dad480b174d71c896febc9965633c
1 <?php // $Id$
2 ///////////////////////////////////////////////////////////////////////////
3 // //
4 // NOTICE OF COPYRIGHT //
5 // //
6 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
7 // http://moodle.org //
8 // //
9 // Copyright (C) 2005 Martin Dougiamas http://dougiamas.com //
10 // //
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. //
15 // //
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: //
20 // //
21 // http://www.gnu.org/copyleft/gpl.html //
22 // //
23 ///////////////////////////////////////////////////////////////////////////
25 require_once('../../config.php');
26 require_once('lib.php');
27 require_once($CFG->libdir.'/blocklib.php');
28 require_once("$CFG->libdir/rsslib.php");
30 require_once('pagelib.php');
32 if (!empty($THEME->customcorners)) {
33 require_once($CFG->dirroot.'/lib/custom_corners_lib.php');
37 /// One of these is necessary!
38 $id = optional_param('id', 0, PARAM_INT); // course module id
39 $d = optional_param('d', 0, PARAM_INT); // database id
40 $rid = optional_param('rid', 0, PARAM_INT); //record id
42 $mode = optional_param('mode', '', PARAM_ALPHA); // Force the browse mode ('single')
44 $edit = optional_param('edit', -1, PARAM_BOOL);
45 $page = optional_param('page', 0, PARAM_INT);
46 /// These can be added to perform an action on a record
47 $approve = optional_param('approve', 0, PARAM_INT); //approval recordid
48 $delete = optional_param('delete', 0, PARAM_INT); //delete recordid
50 if ($id) {
51 if (! $cm = get_coursemodule_from_id('data', $id)) {
52 error('Course Module ID was incorrect');
54 if (! $course = get_record('course', 'id', $cm->course)) {
55 error('Course is misconfigured');
57 if (! $data = get_record('data', 'id', $cm->instance)) {
58 error('Course module is incorrect');
60 $record = NULL;
62 } else if ($rid) {
63 if (! $record = get_record('data_records', 'id', $rid)) {
64 error('Record ID is incorrect');
66 if (! $data = get_record('data', 'id', $record->dataid)) {
67 error('Data ID is incorrect');
69 if (! $course = get_record('course', 'id', $data->course)) {
70 error('Course is misconfigured');
72 if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
73 error('Course Module ID was incorrect');
75 } else { // We must have $d
76 if (! $data = get_record('data', 'id', $d)) {
77 error('Data ID is incorrect');
79 if (! $course = get_record('course', 'id', $data->course)) {
80 error('Course is misconfigured');
82 if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
83 error('Course Module ID was incorrect');
85 $record = NULL;
88 require_course_login($course, true, $cm);
90 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
91 require_capability('mod/data:viewentry', $context);
93 /// If it's hidden then it's don't show anything. :)
94 if (empty($cm->visible) and !has_capability('mod/data:managetemplates', $context)) {
95 $strdatabases = get_string("modulenameplural", "data");
97 $navlinks = array();
98 $navlinks[] = array('name' => $strdatabases, 'link' => "index.php?id=$course->id", 'type' => 'activity');
99 $navlinks[] = array('name' => format_string($data->name), 'link' => '', 'type' => 'activityinstance');
100 $navigation = build_navigation($navlinks);
102 print_header_simple(format_string($data->name), "",
103 $navigation, "", "", true, '', navmenu($course, $cm));
104 notice(get_string("activityiscurrentlyhidden"));
107 /// If we have an empty Database then redirect because this page is useless without data
108 if (has_capability('mod/data:managetemplates', $context)) {
109 if (!record_exists('data_fields','dataid',$data->id)) { // Brand new database!
110 redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id); // Redirect to field entry
115 /// Check further parameters that set browsing preferences
116 if (!isset($SESSION->dataprefs)) {
117 $SESSION->dataprefs = array();
119 if (!isset($SESSION->dataprefs[$data->id])) {
120 $SESSION->dataprefs[$data->id] = array();
121 $SESSION->dataprefs[$data->id]['search'] = '';
122 $SESSION->dataprefs[$data->id]['search_array'] = array();
123 $SESSION->dataprefs[$data->id]['sort'] = $data->defaultsort;
124 $SESSION->dataprefs[$data->id]['advanced'] = 0;
125 $SESSION->dataprefs[$data->id]['order'] = ($data->defaultsortdir == 0) ? 'ASC' : 'DESC';
127 $advanced = optional_param('advanced', $SESSION->dataprefs[$data->id]['advanced'], PARAM_INT);
128 $search_array = $SESSION->dataprefs[$data->id]['search_array'];
130 if (!empty($advanced)) {
131 $search = '';
132 $fields = get_records('data_fields', 'dataid', $data->id);
134 //Added to ammend paging error. This error would occur when attempting to go from one page of advanced
135 //search results to another. All fields were reset in the page transfer, and there was no way of determining
136 //whether or not the user reset them. This would cause a blank search to execute whenever the user attempted
137 //to see any page of results past the first.
138 //This fix works as follows:
139 //$paging flag is set to false when page 0 of the advanced search results is viewed for the first time.
140 //Viewing any page of results after page 0 passes the false $paging flag though the URL (see line 523) and the
141 //execution falls through to the second condition below, allowing paging to be set to true.
142 //Paging remains true and keeps getting passed though the URL until a new search is performed
143 //(even if page 0 is revisited).
144 //A false $paging flag generates advanced search results based on the fields input by the user.
145 //A true $paging flag generates davanced search results from the $SESSION global.
146 //(See lines 147-158)
148 $paging = optional_param('paging', NULL, PARAM_BOOL);
149 if($page == 0 && !isset($paging)) {
150 $paging = false;
152 else {
153 $paging = true;
155 if (!empty($fields)) {
156 foreach($fields as $field) {
157 $searchfield = data_get_field_from_id($field->id, $data);
158 //Get field data to build search sql with. If paging is false, get from user.
159 //If paging is true, get data from $search_array which is obtained from the $SESSION (see line 116).
160 if(!$paging) {
161 $val = $searchfield->parse_search_field();
163 else {
164 //Set value from session if there is a value @ the required index.
165 if(isset($search_array[$field->id])) {
166 $val = $search_array[$field->id]->data;
168 else { //If there is not an entry @ the required index, set value to blank.
169 $val = '';
172 if (!empty($val)) {
173 $search_array[$field->id] = new stdClass;
174 $search_array[$field->id]->sql = $searchfield->generate_sql('c'.$field->id, $val);
175 $search_array[$field->id]->data = $val;
176 $search .= ' '.$val;
178 else {
179 if (isset($search_array[$field->id])) {
180 // clear it out
181 unset($search_array[$field->id]);
186 $SESSION->dataprefs[$data->id]['search_array'] = $search_array; // Make it sticky
188 else {
189 $search = optional_param('search', $SESSION->dataprefs[$data->id]['search'], PARAM_NOTAGS);
190 //Paging variable not used for standard search. Set it to null.
191 $paging = NULL;
194 $textlib = textlib_get_instance();
195 if ($textlib->strlen($search) < 2) {
196 $search = '';
198 $SESSION->dataprefs[$data->id]['search'] = $search; // Make it sticky
200 $sort = optional_param('sort', $SESSION->dataprefs[$data->id]['sort'], PARAM_INT);
201 $SESSION->dataprefs[$data->id]['sort'] = $sort; // Make it sticky
203 $order = (optional_param('order', $SESSION->dataprefs[$data->id]['order'], PARAM_ALPHA) == 'ASC') ? 'ASC': 'DESC';
204 $SESSION->dataprefs[$data->id]['order'] = $order; // Make it sticky
207 $oldperpage = get_user_preferences('data_perpage_'.$data->id, 10);
208 $perpage = optional_param('perpage', $oldperpage, PARAM_INT);
210 if ($perpage < 2) {
211 $perpage = 2;
213 if ($perpage != $oldperpage) {
214 set_user_preference('data_perpage_'.$data->id, $perpage);
217 add_to_log($course->id, 'data', 'view', "view.php?id=$cm->id", $data->id, $cm->id);
220 // Initialize $PAGE, compute blocks
221 $PAGE = page_create_instance($data->id);
222 $pageblocks = blocks_setup($PAGE);
223 $blocks_preferred_width = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), 210);
225 if (($edit != -1) and $PAGE->user_allowed_editing()) {
226 $USER->editing = $edit;
229 /// RSS and CSS and JS meta
230 $meta = '';
231 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
232 $rsspath = rss_get_url($course->id, $USER->id, 'data', $data->id);
233 $meta .= '<link rel="alternate" type="application/rss+xml" ';
234 $meta .= 'title ="'. format_string($course->shortname) .': %fullname%" href="'.$rsspath.'" />';
236 if ($data->csstemplate) {
237 $meta .= '<link rel="stylesheet" type="text/css" href="'.$CFG->wwwroot.'/mod/data/css.php?d='.$data->id.'" /> ';
239 if ($data->jstemplate) {
240 $meta .= '<script type="text/javascript" src="'.$CFG->wwwroot.'/mod/data/js.php?d='.$data->id.'"></script>';
244 /// Print the page header
245 $PAGE->print_header($course->shortname.': %fullname%', '', $meta);
248 /// If we have blocks, then print the left side here
249 if (!empty($CFG->showblocksonmodpages)) {
250 echo '<table id="layout-table"><tr>';
251 if ((blocks_have_content($pageblocks, BLOCK_POS_LEFT) || $PAGE->user_is_editing())) {
252 echo '<td style="width: '.$blocks_preferred_width.'px;" id="left-column">';
253 if (!empty($THEME->customcorners)) print_custom_corners_start();
254 blocks_print_group($PAGE, $pageblocks, BLOCK_POS_LEFT);
255 if (!empty($THEME->customcorners)) print_custom_corners_end();
256 echo '</td>';
258 echo '<td id="middle-column">';
259 if (!empty($THEME->customcorners)) print_custom_corners_start();
262 /// Check to see if groups are being used here
263 $returnurl = 'view.php?d='.$data->id.'&amp;search='.s($search).'&amp;sort='.s($sort).'&amp;order='.s($order).'&amp;';
264 groups_print_activity_menu($cm, $returnurl);
265 $currentgroup = groups_get_activity_group($cm);
266 $groupmode = groups_get_activity_groupmode($cm);
268 print_heading(format_string($data->name));
270 // Do we need to show a link to the RSS feed for the records?
271 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
272 echo '<div style="float:right;">';
273 rss_print_link($course->id, $USER->id, 'data', $data->id, get_string('rsstype'));
274 echo '</div>';
275 echo '<div style="clear:both;"></div>';
278 if ($data->intro and empty($page) and empty($record) and $mode != 'single') {
279 print_box(format_text($data->intro), 'generalbox', 'intro');
282 /// Delete any requested records
284 if ($delete && confirm_sesskey() && (has_capability('mod/data:manageentries', $context) or data_isowner($delete))) {
285 if ($confirm = optional_param('confirm',0,PARAM_INT)) {
286 if ($deleterecord = get_record('data_records', 'id', $delete)) { // Need to check this is valid
287 if ($deleterecord->dataid == $data->id) { // Must be from this database
288 if ($contents = get_records('data_content','recordid', $deleterecord->id)) {
289 foreach ($contents as $content) { // Delete files or whatever else this field allows
290 if ($field = data_get_field_from_id($content->fieldid, $data)) { // Might not be there
291 $field->delete_content($content->recordid);
295 delete_records('data_content','recordid', $deleterecord->id);
296 delete_records('data_records','id', $deleterecord->id);
298 add_to_log($course->id, 'data', 'record delete', "view.php?id=$cm->id", $data->id, $cm->id);
300 notify(get_string('recorddeleted','data'), 'notifysuccess');
304 } else { // Print a confirmation page
305 if ($deleterecord = get_record('data_records', 'id', $delete)) { // Need to check this is valid
306 if ($deleterecord->dataid == $data->id) { // Must be from this database
307 notice_yesno(get_string('confirmdeleterecord','data'),
308 'view.php?d='.$data->id.'&amp;delete='.$delete.'&amp;confirm=1&amp;sesskey='.sesskey(),
309 'view.php?d='.$data->id);
311 $records[] = $deleterecord;
312 echo data_print_template('singletemplate', $records, $data, '', 0, true);
314 print_footer($course);
315 exit;
323 /// Print the tabs
325 if ($record or $mode == 'single') {
326 $currenttab = 'single';
327 } elseif($mode == 'asearch') {
328 $currenttab = 'asearch';
330 else {
331 $currenttab = 'list';
333 include('tabs.php');
335 if ($mode != 'asearch') {
336 /// Approve any requested records
338 if ($approve && confirm_sesskey() && has_capability('mod/data:approve', $context)) {
339 if ($approverecord = get_record('data_records', 'id', $approve)) { // Need to check this is valid
340 if ($approverecord->dataid == $data->id) { // Must be from this database
341 $newrecord->id = $approverecord->id;
342 $newrecord->approved = 1;
343 if (update_record('data_records', $newrecord)) {
344 notify(get_string('recordapproved','data'), 'notifysuccess');
350 // If not teacher, check whether user has sufficient records to view
351 if (!has_capability('mod/data:managetemplates', $context) and data_numentries($data) < $data->requiredentriestoview){
352 notify (($data->requiredentriestoview - data_numentries($data)).'&nbsp;'.get_string('insufficiententries','data'));
353 echo '</td></tr></table>';
354 print_footer($course);
355 exit;
359 /// We need to examine the whole dataset to produce the correct paging
361 if ((!has_capability('mod/data:managetemplates', $context)) && ($data->approval)) {
362 if (isloggedin()) {
363 $approveselect = ' AND (r.approved=1 OR r.userid='.$USER->id.') ';
364 } else {
365 $approveselect = ' AND r.approved=1 ';
367 } else {
368 $approveselect = ' ';
371 if ($currentgroup) {
372 $groupselect = " AND (r.groupid = '$currentgroup' OR r.groupid = 0)";
373 } else {
374 $groupselect = ' ';
377 /// Find the field we are sorting on
378 if ($sort and $sortfield = data_get_field_from_id($sort, $data)) {
380 $sortcontent = $sortfield->get_sort_field();
381 $sortcontentfull = $sortfield->get_sort_sql('c.'.$sortcontent);
383 $what = ' DISTINCT r.id, r.approved, r.userid, u.firstname, u.lastname, c.'.$sortcontent.', '.$sortcontentfull.' AS _order ';
384 $count = ' COUNT(DISTINCT c.recordid) ';
385 $tables = $CFG->prefix.'data_content c,'.$CFG->prefix.'data_records r,'.$CFG->prefix.'data_content c1, '.$CFG->prefix.'user u ';
386 $where = 'WHERE c.recordid = r.id
387 AND c.fieldid = '.$sort.'
388 AND r.dataid = '.$data->id.'
389 AND r.userid = u.id
390 AND c1.recordid = r.id ';
391 $sortorder = ' ORDER BY _order '.$order.' , r.id ASC ';
392 $searchselect = '';
394 if (!empty($advanced)) { //If advanced box is checked.
395 foreach($search_array as $key => $val) { //what does $search_array hold?
396 $tables .= ', '.$CFG->prefix.'data_content c'.$key.' ';
397 $where .= ' AND c'.$key.'.recordid = r.id';
398 $searchselect .= ' AND ('.$val->sql.') ';
401 elseif ($search) {
402 $searchselect = ' AND (c1.content ' . sql_ilike() . " '%$search%') "; //Be case-insensitive
403 } else {
404 $searchselect = ' ';
406 } else if ($search) {
407 $what = ' DISTINCT r.id, r.approved, r.userid, u.firstname, u.lastname ';
408 $count = ' COUNT(DISTINCT c.recordid) ';
409 $tables = $CFG->prefix.'data_content c,'.$CFG->prefix.'data_records r, '.$CFG->prefix.'user u ';
410 $where = 'WHERE c.recordid = r.id
411 AND r.userid = u.id
412 AND r.dataid = '.$data->id;
413 $sortorder = ' ORDER BY r.id ASC ';
414 $searchselect = '';
416 if (!empty($advanced)) { //Advanced search box again.
417 foreach($search_array as $key => $val) {
418 $tables .= ', '.$CFG->prefix.'data_content c'.$key.' ';
419 $where .= ' AND c'.$key.'.recordid = r.id ';
420 $searchselect .= ' AND ('.$val->sql.') ';
423 else {
424 $searchselect = ' AND (c.content ' . sql_ilike() . " '%$search%') "; //Be case-insensitive
428 } else {
429 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.userid, u.firstname, u.lastname ';
430 $count = ' COUNT(r.id) ';
431 $tables = $CFG->prefix.'data_records r, '.$CFG->prefix.'user u ';
432 $where = 'WHERE r.dataid = '.$data->id. ' AND r.userid = u.id ';
433 $sortorder = ' ORDER BY r.timecreated '.$order. ' ';
434 $searchselect = ' ';
438 /// To actually fetch the records
440 $fromsql = ' FROM '.$tables.$where.$groupselect.$approveselect.$searchselect;
442 $sqlselect = 'SELECT '.$what.$fromsql.$sortorder;
444 $sqlcount = 'SELECT '.$count.$fromsql; // Total number of records
446 /// Work out the paging numbers
448 $totalcount = count_records_sql($sqlcount);
450 if ($record) { // We need to just show one, so where is it in context?
451 $nowperpage = 1;
452 $mode = 'single';
454 # Following code needs testing to make it work
455 # if ($sort) { // We need to search by that field
456 # if ($content = get_field('data_content', 'content', 'recordid', $record->id, 'fieldid', $sort)) {
457 # $content = addslashes($content);
458 # if ($order == 'ASC') {
459 # $lessthan = " AND $sortcontentfull < '$content'
460 # OR ($sortcontentfull = '$content' AND r.id < '$record->id') ";
461 # } else {
462 # $lessthan = " AND $sortcontentfull > '$content'
463 # OR ($sortcontentfull = '$content' AND r.id < '$record->id') ";
465 # } else { // Failed to find data (shouldn't happen), so fall back to something easy
466 # $lessthan = " r.id < '$record->id' ";
468 # } else {
469 # $lessthan = " r.id < '$record->id' ";
471 # $sqlindex = 'SELECT COUNT(DISTINCT c.recordid) '.$fromsql.$lessthan.$sortorder;
472 # $page = count_records_sql($sqlindex);
475 $allrecords = get_records_sql($sqlselect); // Kludgey but accurate at least!
476 $page = 0;
477 foreach ($allrecords as $key => $allrecord) {
478 if ($key == $record->id) {
479 break;
481 $page++;
484 } else if ($mode == 'single') { // We rely on ambient $page settings
485 $nowperpage = 1;
487 } else {
488 $nowperpage = $perpage;
491 /// Get the actual records
493 $records = get_records_sql($sqlselect, $page * $nowperpage, $nowperpage);
495 if (empty($records)) { // Nothing to show!
496 if ($record) { // Something was requested so try to show that at least (bug 5132)
497 if (has_capability('mod/data:manageentries', $context) || empty($data->approval) ||
498 $record->approved || (isloggedin() && $record->userid == $USER->id)) {
499 if (!$currentgroup || $record->groupid == $currentgroup || $record->groupid == 0) {
500 $records[] = $record;
504 if ($records) { // OK, we can show this one
505 data_print_template('singletemplate', $records, $data, $search, $page);
506 } else if ($search){
507 notify(get_string('nomatch','data'));
508 } else {
509 notify(get_string('norecords','data'));
512 } else { // We have some records to print
514 if ($mode == 'single') { // Single template
515 $baseurl = 'view.php?d='.$data->id.'&amp;mode=single&amp;';
517 print_paging_bar($totalcount, $page, $nowperpage, $baseurl, $pagevar='page');
519 if (empty($data->singletemplate)){
520 notify(get_string('nosingletemplate','data'));
521 data_generate_default_template($data, 'singletemplate', 0, false, false);
524 data_print_template('singletemplate', $records, $data, $search, $page);
526 print_paging_bar($totalcount, $page, $nowperpage, $baseurl, $pagevar='page');
528 } else { // List template
529 $baseurl = 'view.php?d='.$data->id.'&amp;';
530 //send the advanced flag through the URL so it is remembered while paging.
531 $baseurl .= 'advanced='.$advanced.'&amp;';
532 //pass variable to allow determining whether or not we are paging through results.
533 $baseurl .= 'paging='.$paging.'&amp;';
535 print_paging_bar($totalcount, $page, $nowperpage, $baseurl, $pagevar='page');
537 if (empty($data->listtemplate)){
538 notify(get_string('nolisttemplate','data'));
539 data_generate_default_template($data, 'listtemplate', 0, false, false);
541 echo $data->listtemplateheader;
542 data_print_template('listtemplate', $records, $data, $search, $page);
543 echo $data->listtemplatefooter;
545 print_paging_bar($totalcount, $page, $nowperpage, $baseurl, $pagevar='page');
551 $search = trim($search);
552 if (empty($records)) {
553 $records = array();
556 //Advanced search form doesn't make sense for single (redirects list view)
557 if ($records || $search || $page || $mode = 'asearch' && $mode != 'single') {
558 data_print_preference_form($data, $perpage, $search, $sort, $order, $search_array, $advanced, $mode);
561 /// If we have blocks, then print the left side here
562 if (!empty($CFG->showblocksonmodpages)) {
563 if (!empty($THEME->customcorners)) print_custom_corners_end();
564 echo '</td>'; // Middle column
565 if ((blocks_have_content($pageblocks, BLOCK_POS_RIGHT) || $PAGE->user_is_editing())) {
566 echo '<td style="width: '.$blocks_preferred_width.'px;" id="right-column">';
567 if (!empty($THEME->customcorners)) print_custom_corners_start();
568 blocks_print_group($PAGE, $pageblocks, BLOCK_POS_RIGHT);
569 if (!empty($THEME->customcorners)) print_custom_corners_end();
570 echo '</td>';
572 echo '</tr></table>';
575 print_footer($course);