Fixes bug MDL-8234, "New groups code & AS keyword"
[moodle-pu.git] / mod / data / view.php
blob468818d0c4c824efe20b6b037d701714c76680e5
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');
33 /// One of these is necessary!
34 $id = optional_param('id', 0, PARAM_INT); // course module id
35 $d = optional_param('d', 0, PARAM_INT); // database id
36 $rid = optional_param('rid', 0, PARAM_INT); //record id
38 $mode = optional_param('mode', '', PARAM_ALPHA); // Force the browse mode ('single')
40 $edit = optional_param('edit', -1, PARAM_BOOL);
42 /// These can be added to perform an action on a record
43 $approve = optional_param('approve', 0, PARAM_INT); //approval recordid
44 $delete = optional_param('delete', 0, PARAM_INT); //delete recordid
46 if ($id) {
47 if (! $cm = get_coursemodule_from_id('data', $id)) {
48 error('Course Module ID was incorrect');
50 if (! $course = get_record('course', 'id', $cm->course)) {
51 error('Course is misconfigured');
53 if (! $data = get_record('data', 'id', $cm->instance)) {
54 error('Course module is incorrect');
56 $record = NULL;
58 } else if ($rid) {
59 if (! $record = get_record('data_records', 'id', $rid)) {
60 error('Record ID is incorrect');
62 if (! $data = get_record('data', 'id', $record->dataid)) {
63 error('Data ID is incorrect');
65 if (! $course = get_record('course', 'id', $data->course)) {
66 error('Course is misconfigured');
68 if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
69 error('Course Module ID was incorrect');
71 } else { // We must have $d
72 if (! $data = get_record('data', 'id', $d)) {
73 error('Data ID is incorrect');
75 if (! $course = get_record('course', 'id', $data->course)) {
76 error('Course is misconfigured');
78 if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
79 error('Course Module ID was incorrect');
81 $record = NULL;
84 require_course_login($course, true, $cm);
86 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
87 require_capability('mod/data:viewentry', $context);
89 /// If it's hidden then it's don't show anything. :)
90 if (empty($cm->visible) and !has_capability('mod/data:managetemplates', $context)) {
91 $strdatabases = get_string("modulenameplural", "data");
92 $navigation = "<a href=\"index.php?id=$course->id\">$strdatabases</a> ->";
93 print_header_simple(format_string($data->name), "",
94 "$navigation ".format_string($data->name), "", "", true, '', navmenu($course, $cm));
95 notice(get_string("activityiscurrentlyhidden"));
98 /// If we have an empty Database then redirect because this page is useless without data
99 if (has_capability('mod/data:managetemplates', $context)) {
100 if (!record_exists('data_fields','dataid',$data->id)) { // Brand new database!
101 redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id); // Redirect to field entry
106 /// Check further parameters that set browsing preferences
107 if (!isset($SESSION->dataprefs)) {
108 $SESSION->dataprefs = array();
110 if (!isset($SESSION->dataprefs[$data->id])) {
111 $SESSION->dataprefs[$data->id] = array();
112 $SESSION->dataprefs[$data->id]['search'] = '';
113 $SESSION->dataprefs[$data->id]['sort'] = $data->defaultsort;
114 $SESSION->dataprefs[$data->id]['order'] = ($data->defaultsortdir == 0) ? 'ASC' : 'DESC';
116 $search = optional_param('search', $SESSION->dataprefs[$data->id]['search'], PARAM_NOTAGS);
117 $textlib = new textlib();
118 if ($textlib->strlen($search) < 2) {
119 $search = '';
121 $SESSION->dataprefs[$data->id]['search'] = $search; // Make it sticky
123 $sort = optional_param('sort', $SESSION->dataprefs[$data->id]['sort'], PARAM_INT);
124 $SESSION->dataprefs[$data->id]['sort'] = $sort; // Make it sticky
126 $order = (optional_param('order', $SESSION->dataprefs[$data->id]['order'], PARAM_ALPHA) == 'ASC') ? 'ASC': 'DESC';
127 $SESSION->dataprefs[$data->id]['order'] = $order; // Make it sticky
130 $oldperpage = get_user_preferences('data_perpage_'.$data->id, 10);
131 $perpage = optional_param('perpage', $oldperpage, PARAM_INT);
133 if ($perpage < 2) {
134 $perpage = 2;
136 if ($perpage != $oldperpage) {
137 set_user_preference('data_perpage_'.$data->id, $perpage);
140 $page = optional_param('page', 0, PARAM_INT);
142 add_to_log($course->id, 'data', 'view', "view.php?id=$cm->id", $data->id, $cm->id);
145 // Initialize $PAGE, compute blocks
146 $PAGE = page_create_instance($data->id);
147 $pageblocks = blocks_setup($PAGE);
148 $blocks_preferred_width = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), 210);
150 if (($edit != -1) and $PAGE->user_allowed_editing()) {
151 $USER->editing = $edit;
154 /// RSS and CSS and JS meta
155 $meta = '';
156 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
157 $rsspath = rss_get_url($course->id, $USER->id, 'data', $data->id);
158 $meta .= '<link rel="alternate" type="application/rss+xml" ';
159 $meta .= 'title ="'.$course->shortname.': %fullname%" href="'.$rsspath.'" />';
161 if ($data->csstemplate) {
162 $meta .= '<link rel="stylesheet" type="text/css" href="'.$CFG->wwwroot.'/mod/data/css.php?d='.$data->id.'" /> ';
164 if ($data->jstemplate) {
165 $meta .= '<script type="text/javascript" src="'.$CFG->wwwroot.'/mod/data/js.php?d='.$data->id.'"></script>';
169 /// Print the page header
170 $PAGE->print_header($course->shortname.': %fullname%', '', $meta);
173 /// If we have blocks, then print the left side here
174 if (!empty($CFG->showblocksonmodpages)) {
175 echo '<table id="layout-table"><tr>';
176 if ((blocks_have_content($pageblocks, BLOCK_POS_LEFT) || $PAGE->user_is_editing())) {
177 echo '<td style="width: '.$blocks_preferred_width.'px;" id="left-column">';
178 blocks_print_group($PAGE, $pageblocks, BLOCK_POS_LEFT);
179 echo '</td>';
181 echo '<td id="middle-column">';
184 print_heading(format_string($data->name));
186 // Do we need to show a link to the RSS feed for the records?
187 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
188 echo '<div style="float:right;">';
189 rss_print_link($course->id, $USER->id, 'data', $data->id, get_string('rsstype'));
190 echo '</div>';
191 echo '<div style="clear:both;"></div>';
194 if ($data->intro and empty($page) and empty($record) and $mode != 'single') {
195 print_box(format_text($data->intro), 'generalbox', 'intro');
198 /// Check to see if groups are being used here
199 if ($groupmode = groupmode($course, $cm)) { // Groups are being used
200 $currentgroup = setup_and_print_groups($course, $groupmode,
201 'view.php?d='.$data->id.'&amp;search='.s($search).'&amp;sort='.s($sort).
202 '&amp;order='.s($order).'&amp;');
203 } else {
204 $currentgroup = 0;
207 /// Delete any requested records
209 if ($delete && confirm_sesskey() && (has_capability('mod/data:manageentries', $context) or data_isowner($delete))) {
210 if ($confirm = optional_param('confirm',0,PARAM_INT)) {
211 if ($deleterecord = get_record('data_records', 'id', $delete)) { // Need to check this is valid
212 if ($deleterecord->dataid == $data->id) { // Must be from this database
213 if ($contents = get_records('data_content','recordid', $deleterecord->id)) {
214 foreach ($contents as $content) { // Delete files or whatever else this field allows
215 if ($field = data_get_field_from_id($content->fieldid, $data)) { // Might not be there
216 $field->delete_content($content->recordid);
220 delete_records('data_content','recordid', $deleterecord->id);
221 delete_records('data_records','id', $deleterecord->id);
223 add_to_log($course->id, 'data', 'record delete', "view.php?id=$cm->id", $data->id, $cm->id);
225 notify(get_string('recorddeleted','data'), 'notifysuccess');
229 } else { // Print a confirmation page
230 if ($deleterecord = get_record('data_records', 'id', $delete)) { // Need to check this is valid
231 if ($deleterecord->dataid == $data->id) { // Must be from this database
232 notice_yesno(get_string('confirmdeleterecord','data'),
233 'view.php?d='.$data->id.'&amp;delete='.$delete.'&amp;confirm=1&amp;sesskey='.sesskey(),
234 'view.php?d='.$data->id);
236 $records[] = $deleterecord;
237 echo data_print_template('singletemplate', $records, $data, '', 0, true);
239 print_footer($course);
240 exit;
248 /// Print the tabs
250 if ($record or $mode == 'single') {
251 $currenttab = 'single';
252 } else {
253 $currenttab = 'list';
255 include('tabs.php');
258 /// Approve any requested records
260 if ($approve && confirm_sesskey() && has_capability('mod/data:approve', $context)) {
261 if ($approverecord = get_record('data_records', 'id', $approve)) { // Need to check this is valid
262 if ($approverecord->dataid == $data->id) { // Must be from this database
263 $newrecord->id = $approverecord->id;
264 $newrecord->approved = 1;
265 if (update_record('data_records', $newrecord)) {
266 notify(get_string('recordapproved','data'), 'notifysuccess');
272 // If not teacher, check whether user has sufficient records to view
273 if (!has_capability('mod/data:managetemplates', $context) and data_numentries($data) < $data->requiredentriestoview){
274 notify (($data->requiredentriestoview - data_numentries($data)).'&nbsp;'.get_string('insufficiententries','data'));
275 echo '</td></tr></table>';
276 print_footer($course);
277 exit;
281 /// We need to examine the whole dataset to produce the correct paging
283 if ((!has_capability('mod/data:managetemplates', $context)) && ($data->approval)) {
284 if (isloggedin()) {
285 $approveselect = ' AND (r.approved=1 OR r.userid='.$USER->id.') ';
286 } else {
287 $approveselect = ' AND r.approved=1 ';
289 } else {
290 $approveselect = ' ';
293 if ($currentgroup) {
294 $groupselect = " AND (r.groupid = '$currentgroup' OR r.groupid = 0)";
295 } else {
296 $groupselect = ' ';
299 /// Find the field we are sorting on
300 if ($sort and $sortfield = data_get_field_from_id($sort, $data)) {
302 $sortcontent = $sortfield->get_sort_field();
303 $sortcontentfull = $sortfield->get_sort_sql('c.'.$sortcontent);
305 $what = ' DISTINCT r.id, r.approved, r.userid, u.firstname, u.lastname, c.'.$sortcontent.' ';
306 $count = ' COUNT(DISTINCT c.recordid) ';
307 $tables = $CFG->prefix.'data_content c,'.$CFG->prefix.'data_records r,'.$CFG->prefix.'data_content c1, '.$CFG->prefix.'user u ';
308 $where = 'WHERE c.recordid = r.id
309 AND c.fieldid = '.$sort.'
310 AND r.dataid = '.$data->id.'
311 AND r.userid = u.id
312 AND c1.recordid = r.id ';
313 $sortorder = ' ORDER BY '.$sortcontentfull.' '.$order.' , r.id ASC ';
314 if ($search) {
315 $searchselect = " AND (c1.content LIKE '%$search%') ";
316 } else {
317 $searchselect = ' ';
320 } else if ($search) {
321 $what = ' DISTINCT r.id, r.approved, r.userid, u.firstname, u.lastname ';
322 $count = ' COUNT(DISTINCT c.recordid) ';
323 $tables = $CFG->prefix.'data_content c,'.$CFG->prefix.'data_records r, '.$CFG->prefix.'user u ';
324 $where = 'WHERE c.recordid = r.id
325 AND r.userid = u.id
326 AND r.dataid = '.$data->id;
327 $sortorder = ' ORDER BY r.id ASC ';
328 $searchselect = " AND (c.content LIKE '%$search%') ";
330 } else {
331 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.userid, u.firstname, u.lastname ';
332 $count = ' COUNT(r.id) ';
333 $tables = $CFG->prefix.'data_records r, '.$CFG->prefix.'user u ';
334 $where = 'WHERE r.dataid = '.$data->id. ' AND r.userid = u.id ';
335 $sortorder = ' ORDER BY r.timecreated '.$order. ' ';
336 $searchselect = ' ';
340 /// To actually fetch the records
342 $fromsql = ' FROM '.$tables.$where.$groupselect.$approveselect.$searchselect;
344 $sqlselect = 'SELECT '.$what.$fromsql.$sortorder;
346 $sqlcount = 'SELECT '.$count.$fromsql; // Total number of records
348 /// Work out the paging numbers
350 $totalcount = count_records_sql($sqlcount);
352 if ($record) { // We need to just show one, so where is it in context?
353 $nowperpage = 1;
354 $mode = 'single';
356 # Following code needs testing to make it work
357 # if ($sort) { // We need to search by that field
358 # if ($content = get_field('data_content', 'content', 'recordid', $record->id, 'fieldid', $sort)) {
359 # $content = addslashes($content);
360 # if ($order == 'ASC') {
361 # $lessthan = " AND $sortcontentfull < '$content'
362 # OR ($sortcontentfull = '$content' AND r.id < '$record->id') ";
363 # } else {
364 # $lessthan = " AND $sortcontentfull > '$content'
365 # OR ($sortcontentfull = '$content' AND r.id < '$record->id') ";
367 # } else { // Failed to find data (shouldn't happen), so fall back to something easy
368 # $lessthan = " r.id < '$record->id' ";
370 # } else {
371 # $lessthan = " r.id < '$record->id' ";
373 # $sqlindex = 'SELECT COUNT(DISTINCT c.recordid) '.$fromsql.$lessthan.$sortorder;
374 # $page = count_records_sql($sqlindex);
377 $allrecords = get_records_sql($sqlselect); // Kludgey but accurate at least!
378 $page = 0;
379 foreach ($allrecords as $key => $allrecord) {
380 if ($key == $record->id) {
381 break;
383 $page++;
386 } else if ($mode == 'single') { // We rely on ambient $page settings
387 $nowperpage = 1;
389 } else {
390 $nowperpage = $perpage;
393 /// Get the actual records
395 $records = get_records_sql($sqlselect, $page * $nowperpage, $nowperpage);
397 if (empty($records)) { // Nothing to show!
398 if ($record) { // Something was requested so try to show that at least (bug 5132)
399 if (has_capability('mod/data:manageentries', $context) || empty($data->approval) ||
400 $record->approved || (isloggedin() && $record->userid == $USER->id)) {
401 if (!$currentgroup || $record->groupid == $currentgroup || $record->groupid == 0) {
402 $records[] = $record;
406 if ($records) { // OK, we can show this one
407 data_print_template('singletemplate', $records, $data, $search, $page);
408 } else if ($search){
409 notify(get_string('nomatch','data'));
410 } else {
411 notify(get_string('norecords','data'));
414 } else { // We have some records to print
416 if ($mode == 'single') { // Single template
417 $baseurl = 'view.php?d='.$data->id.'&amp;mode=single&amp;';
419 print_paging_bar($totalcount, $page, $nowperpage, $baseurl, $pagevar='page');
421 if (empty($data->singletemplate)){
422 notify(get_string('nosingletemplate','data'));
423 data_generate_default_template($data, 'singletemplate', 0, false, false);
426 data_print_template('singletemplate', $records, $data, $search, $page);
428 print_paging_bar($totalcount, $page, $nowperpage, $baseurl, $pagevar='page');
430 } else { // List template
431 $baseurl = 'view.php?d='.$data->id.'&amp;';
433 print_paging_bar($totalcount, $page, $nowperpage, $baseurl, $pagevar='page');
435 if (empty($data->listtemplate)){
436 notify(get_string('nolisttemplate','data'));
437 data_generate_default_template($data, 'listtemplate', 0, false, false);
439 echo $data->listtemplateheader;
440 data_print_template('listtemplate', $records, $data, $search, $page);
441 echo $data->listtemplatefooter;
443 print_paging_bar($totalcount, $page, $nowperpage, $baseurl, $pagevar='page');
448 if ($records || $search || $page) {
449 data_print_preference_form($data, $perpage, $search, $sort, $order);
452 /// If we have blocks, then print the left side here
453 if (!empty($CFG->showblocksonmodpages)) {
454 echo '</td>'; // Middle column
455 if ((blocks_have_content($pageblocks, BLOCK_POS_RIGHT) || $PAGE->user_is_editing())) {
456 echo '<td style="width: '.$blocks_preferred_width.'px;" id="right-column">';
457 blocks_print_group($PAGE, $pageblocks, BLOCK_POS_RIGHT);
458 echo '</td>';
460 echo '</table>';
463 print_footer($course);