"DATA MODULE MDL-25564 fixed $PAGE->url, credits to Davo Smith"
[moodle.git] / mod / data / view.php
CommitLineData
1adbd2c3 1<?php
3d4b223a 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///////////////////////////////////////////////////////////////////////////
24
3681f9a9 25 require_once(dirname(__FILE__) . '/../../config.php');
26 require_once($CFG->dirroot . '/mod/data/lib.php');
27 require_once($CFG->libdir . '/rsslib.php');
4e1132a8 28 require_once($CFG->libdir . '/completionlib.php');
9f7f1a74 29
3d45b8e5 30/// One of these is necessary!
d53e5129 31 $id = optional_param('id', 0, PARAM_INT); // course module id
32 $d = optional_param('d', 0, PARAM_INT); // database id
33 $rid = optional_param('rid', 0, PARAM_INT); //record id
34 $mode = optional_param('mode', '', PARAM_ALPHA); // Force the browse mode ('single')
35 $filter = optional_param('filter', 0, PARAM_BOOL);
36 // search filter will only be applied when $filter is true
3d45b8e5 37
d2b23346 38 $edit = optional_param('edit', -1, PARAM_BOOL);
7900ecb0 39 $page = optional_param('page', 0, PARAM_INT);
3d45b8e5 40/// These can be added to perform an action on a record
473dd288 41 $approve = optional_param('approve', 0, PARAM_INT); //approval recordid
42 $delete = optional_param('delete', 0, PARAM_INT); //delete recordid
aab98aaf 43
3d4b223a 44 if ($id) {
f9d5371b 45 if (! $cm = get_coursemodule_from_id('data', $id)) {
29c1bb15 46 print_error('invalidcoursemodule');
3d4b223a 47 }
3223bc9e 48 if (! $course = $DB->get_record('course', array('id'=>$cm->course))) {
29c1bb15 49 print_error('coursemisconf');
3d4b223a 50 }
3223bc9e 51 if (! $data = $DB->get_record('data', array('id'=>$cm->instance))) {
29c1bb15 52 print_error('invalidcoursemodule');
3d4b223a 53 }
3d45b8e5 54 $record = NULL;
3d4b223a 55
3d45b8e5 56 } else if ($rid) {
3223bc9e 57 if (! $record = $DB->get_record('data_records', array('id'=>$rid))) {
29c1bb15 58 print_error('invalidrecord', 'data');
3d45b8e5 59 }
3223bc9e 60 if (! $data = $DB->get_record('data', array('id'=>$record->dataid))) {
29c1bb15 61 print_error('invalidid', 'data');
3d45b8e5 62 }
3223bc9e 63 if (! $course = $DB->get_record('course', array('id'=>$data->course))) {
29c1bb15 64 print_error('coursemisconf');
3d45b8e5 65 }
66 if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
29c1bb15 67 print_error('invalidcoursemodule');
3d45b8e5 68 }
69 } else { // We must have $d
3223bc9e 70 if (! $data = $DB->get_record('data', array('id'=>$d))) {
29c1bb15 71 print_error('invalidid', 'data');
3d4b223a 72 }
3223bc9e 73 if (! $course = $DB->get_record('course', array('id'=>$data->course))) {
29c1bb15 74 print_error('coursemisconf');
3d4b223a 75 }
76 if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
29c1bb15 77 print_error('invalidcoursemodule');
3d4b223a 78 }
3d45b8e5 79 $record = NULL;
3d4b223a 80 }
81
7ddda9db 82 require_course_login($course, true, $cm);
aab98aaf 83
36051c9e
DC
84 require_once($CFG->dirroot . '/comment/lib.php');
85 comment::init();
e998effa 86
dabfd0ed 87 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
20821a12 88 require_capability('mod/data:viewentry', $context);
3d1c33ef 89
3d45b8e5 90/// If we have an empty Database then redirect because this page is useless without data
0468976c 91 if (has_capability('mod/data:managetemplates', $context)) {
3223bc9e 92 if (!$DB->record_exists('data_fields', array('dataid'=>$data->id))) { // Brand new database!
5bac6d10 93 redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id); // Redirect to field entry
3d4b223a 94 }
95 }
e0279f63 96
3d45b8e5 97
98/// Check further parameters that set browsing preferences
99 if (!isset($SESSION->dataprefs)) {
100 $SESSION->dataprefs = array();
e0279f63 101 }
3d45b8e5 102 if (!isset($SESSION->dataprefs[$data->id])) {
103 $SESSION->dataprefs[$data->id] = array();
104 $SESSION->dataprefs[$data->id]['search'] = '';
7900ecb0 105 $SESSION->dataprefs[$data->id]['search_array'] = array();
3d45b8e5 106 $SESSION->dataprefs[$data->id]['sort'] = $data->defaultsort;
7900ecb0 107 $SESSION->dataprefs[$data->id]['advanced'] = 0;
3d45b8e5 108 $SESSION->dataprefs[$data->id]['order'] = ($data->defaultsortdir == 0) ? 'ASC' : 'DESC';
3d4b223a 109 }
de8ff581 110
eeeb4f2a 111 // reset advanced form
112 if (!is_null(optional_param('resetadv', null, PARAM_RAW))) {
113 $SESSION->dataprefs[$data->id]['search_array'] = array();
114 // we need the redirect to cleanup the form state properly
115 redirect("view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=1");
116 }
117
de8ff581 118 $advanced = optional_param('advanced', -1, PARAM_INT);
119 if ($advanced == -1) {
120 $advanced = $SESSION->dataprefs[$data->id]['advanced'];
121 } else {
122 if (!$advanced) {
123 // explicitly switched to normal mode - discard all advanced search settings
124 $SESSION->dataprefs[$data->id]['search_array'] = array();
125 }
832123e1 126 $SESSION->dataprefs[$data->id]['advanced'] = $advanced;
de8ff581 127 }
128
7900ecb0 129 $search_array = $SESSION->dataprefs[$data->id]['search_array'];
eeeb4f2a 130
7900ecb0 131 if (!empty($advanced)) {
132 $search = '';
69c0a609 133 $vals = array();
3223bc9e 134 $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
8429163d 135
7900ecb0 136 //Added to ammend paging error. This error would occur when attempting to go from one page of advanced
137 //search results to another. All fields were reset in the page transfer, and there was no way of determining
138 //whether or not the user reset them. This would cause a blank search to execute whenever the user attempted
139 //to see any page of results past the first.
140 //This fix works as follows:
141 //$paging flag is set to false when page 0 of the advanced search results is viewed for the first time.
142 //Viewing any page of results after page 0 passes the false $paging flag though the URL (see line 523) and the
143 //execution falls through to the second condition below, allowing paging to be set to true.
144 //Paging remains true and keeps getting passed though the URL until a new search is performed
145 //(even if page 0 is revisited).
8429163d 146 //A false $paging flag generates advanced search results based on the fields input by the user.
7900ecb0 147 //A true $paging flag generates davanced search results from the $SESSION global.
8429163d 148
7900ecb0 149 $paging = optional_param('paging', NULL, PARAM_BOOL);
150 if($page == 0 && !isset($paging)) {
151 $paging = false;
152 }
153 else {
154 $paging = true;
155 }
714bec74 156 if (!empty($fields)) {
7900ecb0 157 foreach($fields as $field) {
2d9b3ef2 158 $searchfield = data_get_field_from_id($field->id, $data);
7900ecb0 159 //Get field data to build search sql with. If paging is false, get from user.
160 //If paging is true, get data from $search_array which is obtained from the $SESSION (see line 116).
161 if(!$paging) {
162 $val = $searchfield->parse_search_field();
714bec74 163 } else {
7900ecb0 164 //Set value from session if there is a value @ the required index.
714bec74 165 if (isset($search_array[$field->id])) {
7900ecb0 166 $val = $search_array[$field->id]->data;
714bec74 167 } else { //If there is not an entry @ the required index, set value to blank.
7900ecb0 168 $val = '';
169 }
7900ecb0 170 }
714bec74 171 if (!empty($val)) {
39790bd8 172 $search_array[$field->id] = new stdClass();
e3487936 173 list($search_array[$field->id]->sql, $search_array[$field->id]->params) = $searchfield->generate_sql('c'.$field->id, $val);
714bec74 174 $search_array[$field->id]->data = $val;
69c0a609 175 $vals[] = $val;
714bec74 176 } else {
177 // clear it out
178 unset($search_array[$field->id]);
7900ecb0 179 }
180 }
181 }
714bec74 182
183 if (!$paging) {
184 // name searching
185 $fn = optional_param('u_fn', '', PARAM_NOTAGS);
186 $ln = optional_param('u_ln', '', PARAM_NOTAGS);
187 } else {
de8ff581 188 $fn = isset($search_array[DATA_FIRSTNAME]) ? $search_array[DATA_FIRSTNAME]->data : '';
189 $ln = isset($search_array[DATA_LASTNAME]) ? $search_array[DATA_LASTNAME]->data : '';
714bec74 190 }
191 if (!empty($fn)) {
39790bd8 192 $search_array[DATA_FIRSTNAME] = new stdClass();
e3487936 193 $search_array[DATA_FIRSTNAME]->sql = '';
194 $search_array[DATA_FIRSTNAME]->params = array();
195 $search_array[DATA_FIRSTNAME]->field = 'u.firstname';
196 $search_array[DATA_FIRSTNAME]->data = $fn;
69c0a609 197 $vals[] = $fn;
714bec74 198 } else {
199 unset($search_array[DATA_FIRSTNAME]);
200 }
201 if (!empty($ln)) {
39790bd8 202 $search_array[DATA_LASTNAME] = new stdClass();
e3487936 203 $search_array[DATA_LASTNAME]->sql = '';
1e72829d 204 $search_array[DATA_LASTNAME]->params = array();
e3487936 205 $search_array[DATA_LASTNAME]->field = 'u.lastname';
206 $search_array[DATA_LASTNAME]->data = $ln;
69c0a609 207 $vals[] = $ln;
714bec74 208 } else {
209 unset($search_array[DATA_LASTNAME]);
210 }
211
7900ecb0 212 $SESSION->dataprefs[$data->id]['search_array'] = $search_array; // Make it sticky
714bec74 213
69c0a609 214 // in case we want to switch to simple search later - there might be multiple values there ;-)
215 if ($vals) {
216 $val = reset($vals);
217 if (is_string($val)) {
218 $search = $val;
219 }
220 }
221
714bec74 222 } else {
7900ecb0 223 $search = optional_param('search', $SESSION->dataprefs[$data->id]['search'], PARAM_NOTAGS);
224 //Paging variable not used for standard search. Set it to null.
225 $paging = NULL;
226 }
227
d53e5129 228 // Disable search filters if $filter is not true:
32d799c6 229 if (! $filter) {
230 $search = '';
231 }
d53e5129 232
8e1ec6be 233 $textlib = textlib_get_instance();
76a2fd82 234 if ($textlib->strlen($search) < 2) {
235 $search = '';
236 }
3d45b8e5 237 $SESSION->dataprefs[$data->id]['search'] = $search; // Make it sticky
238
239 $sort = optional_param('sort', $SESSION->dataprefs[$data->id]['sort'], PARAM_INT);
240 $SESSION->dataprefs[$data->id]['sort'] = $sort; // Make it sticky
241
242 $order = (optional_param('order', $SESSION->dataprefs[$data->id]['order'], PARAM_ALPHA) == 'ASC') ? 'ASC': 'DESC';
243 $SESSION->dataprefs[$data->id]['order'] = $order; // Make it sticky
244
245
246 $oldperpage = get_user_preferences('data_perpage_'.$data->id, 10);
247 $perpage = optional_param('perpage', $oldperpage, PARAM_INT);
248
249 if ($perpage < 2) {
250 $perpage = 2;
251 }
252 if ($perpage != $oldperpage) {
253 set_user_preference('data_perpage_'.$data->id, $perpage);
254 }
255
3d4b223a 256 add_to_log($course->id, 'data', 'view', "view.php?id=$cm->id", $data->id, $cm->id);
257
258
a9f19d81
DC
259 $urlparams = array('d' => $data->id);
260 if ($record) {
261 $urlparams['rid'] = $record->id;
262 }
263 if ($page) {
264 $urlparams['page'] = $page;
265 }
266 if ($mode) {
267 $urlparams['mode'] = $mode;
268 }
269 if ($filter) {
270 $urlparams['filter'] = $filter;
271 }
3d4b223a 272// Initialize $PAGE, compute blocks
a9f19d81 273 $PAGE->set_url('/mod/data/view.php', $urlparams);
3d4b223a 274
d2b23346 275 if (($edit != -1) and $PAGE->user_allowed_editing()) {
276 $USER->editing = $edit;
3d4b223a 277 }
3d4b223a 278
b0100852 279/// RSS and CSS and JS meta
68635e6f 280 $meta = '';
64452eb4 281 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
9e86f2e7 282 $rsstitle = format_string($course->shortname) . ': %fullname%';
43b92251 283 rss_add_http_header($context, 'mod_data', $data, $rsstitle);
68635e6f 284 }
285 if ($data->csstemplate) {
c0467479 286 $PAGE->requires->css('/mod/data/css.php?d='.$data->id);
c853304e 287 }
b0100852 288 if ($data->jstemplate) {
60409fe1 289 $PAGE->requires->js('/mod/data/js.php?d='.$data->id, true);
b0100852 290 }
291
c853304e 292/// Print the page header
b7b2d0f3 293 // Note: MDL-19010 there will be further changes to printing header and blocks.
294 // The code will be much nicer than this eventually.
3681f9a9 295 $title = $course->shortname.': ' . format_string($data->name);
296
59e2121e 297 if ($PAGE->user_allowed_editing()) {
4aea3cc7 298 $buttons = '<table><tr><td><form method="get" action="view.php"><div>'.
3681f9a9 299 '<input type="hidden" name="id" value="'.$cm->id.'" />'.
300 '<input type="hidden" name="edit" value="'.($PAGE->user_is_editing()?'off':'on').'" />'.
92059c7e
SH
301 '<input type="submit" value="'.get_string($PAGE->user_is_editing()?'blockseditoff':'blocksediton').'" /></div></form></td></tr></table>';
302 $PAGE->set_button($buttons);
3681f9a9 303 }
aab98aaf 304
29b64a22 305 if ($mode == 'asearch') {
306 $PAGE->navbar->add(get_string('search'));
307 }
308
b0ff558c 309 $PAGE->set_title($title);
310 $PAGE->set_heading($course->fullname);
dd88de0e 311
b0ff558c 312 echo $OUTPUT->header();
1adbd2c3 313
3b27b0fe 314/// Check to see if groups are being used here
f1035deb 315 $returnurl = $CFG->wwwroot . '/mod/data/view.php?d='.$data->id.'&amp;search='.s($search).'&amp;sort='.s($sort).'&amp;order='.s($order).'&amp;';
13534ef7
ML
316 groups_print_activity_menu($cm, $returnurl);
317 $currentgroup = groups_get_activity_group($cm);
318 $groupmode = groups_get_activity_groupmode($cm);
3b27b0fe 319
e822f07b 320 // detect entries not approved yet and show hint instead of not found error
ebb621f6 321 if ($record and $data->approval and !$record->approved and $record->userid != $USER->id and !has_capability('mod/data:manageentries', $context)) {
322 if (!$currentgroup or $record->groupid == $currentgroup or $record->groupid == 0) {
323 print_error('notapproved', 'data');
324 }
325 }
326
b2dc6880 327 echo $OUTPUT->heading(format_string($data->name));
aab98aaf 328
a593aeee 329 // Do we need to show a link to the RSS feed for the records?
9e86f2e7
AD
330 //this links has been Settings (database activity administration) block
331 /*if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
a593aeee 332 echo '<div style="float:right;">';
aa60291e 333 rss_print_link($context->id, $USER->id, 'mod_data', $data->id, get_string('rsstype'));
a593aeee 334 echo '</div>';
335 echo '<div style="clear:both;"></div>';
9e86f2e7 336 }*/
aab98aaf 337
9e08cf6e 338 if ($data->intro and empty($page) and empty($record) and $mode != 'single') {
39790bd8 339 $options = new stdClass();
ea6073bb 340 $options->noclean = true;
883fa987 341 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
56135f6b 342 }
343
473dd288 344/// Delete any requested records
345
046dd7dc 346 if ($delete && confirm_sesskey() && (has_capability('mod/data:manageentries', $context) or data_isowner($delete))) {
3d45b8e5 347 if ($confirm = optional_param('confirm',0,PARAM_INT)) {
3223bc9e 348 if ($deleterecord = $DB->get_record('data_records', array('id'=>$delete))) { // Need to check this is valid
3d45b8e5 349 if ($deleterecord->dataid == $data->id) { // Must be from this database
3223bc9e 350 if ($contents = $DB->get_records('data_content', array('recordid'=>$deleterecord->id))) {
3d45b8e5 351 foreach ($contents as $content) { // Delete files or whatever else this field allows
352 if ($field = data_get_field_from_id($content->fieldid, $data)) { // Might not be there
353 $field->delete_content($content->recordid);
354 }
3d4b223a 355 }
356 }
3223bc9e 357 $DB->delete_records('data_content', array('recordid'=>$deleterecord->id));
358 $DB->delete_records('data_records', array('id'=>$deleterecord->id));
f0497d6f 359
3d45b8e5 360 add_to_log($course->id, 'data', 'record delete', "view.php?id=$cm->id", $data->id, $cm->id);
f0497d6f 361
4102b449 362 echo $OUTPUT->notification(get_string('recorddeleted','data'), 'notifysuccess');
3d45b8e5 363 }
3d4b223a 364 }
3d45b8e5 365
366 } else { // Print a confirmation page
3223bc9e 367 if ($deleterecord = $DB->get_record('data_records', array('id'=>$delete))) { // Need to check this is valid
64452eb4 368 if ($deleterecord->dataid == $data->id) { // Must be from this database
e822f07b 369 $deletebutton = new single_button(new moodle_url('/mod/data/view.php?d='.$data->id.'&delete='.$delete.'&confirm=1'), get_string('delete'), 'post');
cd6137d7 370 echo $OUTPUT->confirm(get_string('confirmdeleterecord','data'),
e822f07b 371 $deletebutton, 'view.php?d='.$data->id);
3d45b8e5 372
64452eb4 373 $records[] = $deleterecord;
3f9672d3 374 echo data_print_template('singletemplate', $records, $data, '', 0, true);
64452eb4 375
7b30ba8b 376 echo $OUTPUT->footer();
64452eb4 377 exit;
378 }
379 }
380 }
381 }
382
383
2742ffe7 384//if data activity closed dont let students in
4a9eecc4 385$showactivity = true;
2742ffe7
AD
386if (!has_capability('mod/data:manageentries', $context)) {
387 $timenow = time();
388 if (!empty($data->timeavailablefrom) && $data->timeavailablefrom > $timenow) {
4a9eecc4
AD
389 echo $OUTPUT->notification(get_string('notopenyet', 'data', userdate($data->timeavailablefrom)));
390 $showactivity = false;
2742ffe7 391 } else if (!empty($data->timeavailableto) && $timenow > $data->timeavailableto) {
4a9eecc4
AD
392 echo $OUTPUT->notification(get_string('expired', 'data', userdate($data->timeavailableto)));
393 $showactivity = false;
2742ffe7
AD
394 }
395}
64452eb4 396
4a9eecc4
AD
397if ($showactivity) {
398 // Print the tabs
64452eb4 399 if ($record or $mode == 'single') {
400 $currenttab = 'single';
7900ecb0 401 } elseif($mode == 'asearch') {
402 $currenttab = 'asearch';
403 }
404 else {
64452eb4 405 $currenttab = 'list';
406 }
aab98aaf 407 include('tabs.php');
64452eb4 408
eeeb4f2a 409 if ($mode == 'asearch') {
410 $maxcount = 0;
8429163d 411
eeeb4f2a 412 } else {
7900ecb0 413 /// Approve any requested records
e3487936 414 $params = array(); // named params array
64452eb4 415
8429163d 416 $approvecap = has_capability('mod/data:approve', $context);
bb5740f4 417
418 if ($approve && confirm_sesskey() && $approvecap) {
3223bc9e 419 if ($approverecord = $DB->get_record('data_records', array('id'=>$approve))) { // Need to check this is valid
7900ecb0 420 if ($approverecord->dataid == $data->id) { // Must be from this database
39790bd8 421 $newrecord = new stdClass();
7900ecb0 422 $newrecord->id = $approverecord->id;
423 $newrecord->approved = 1;
dd88de0e
PS
424 $DB->update_record('data_records', $newrecord);
425 echo $OUTPUT->notification(get_string('recordapproved','data'), 'notifysuccess');
64452eb4 426 }
427 }
3d4b223a 428 }
8429163d 429
c861f079 430 $numentries = data_numentries($data);
431 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
eeeb4f2a 432 if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !has_capability('mod/data:manageentries', $context)) {
433 $data->entriesleft = $data->requiredentries - $numentries;
434 $strentrieslefttoadd = get_string('entrieslefttoadd', 'data', $data);
4102b449 435 echo $OUTPUT->notification($strentrieslefttoadd);
c861f079 436 }
437
438 /// Check the number of entries required before to view other participant's entries against the number of entries already made (doesn't apply to teachers)
439 $requiredentries_allowed = true;
440 if ($data->requiredentriestoview > 0 && $numentries < $data->requiredentriestoview && !has_capability('mod/data:manageentries', $context)) {
441 $data->entrieslefttoview = $data->requiredentriestoview - $numentries;
442 $strentrieslefttoaddtoview = get_string('entrieslefttoaddtoview', 'data', $data);
4102b449 443 echo $OUTPUT->notification($strentrieslefttoaddtoview);
eeeb4f2a 444 $requiredentries_allowed = false;
445 }
3d4b223a 446
bb5740f4 447 /// setup group and approve restrictions
448 if (!$approvecap && $data->approval) {
7900ecb0 449 if (isloggedin()) {
e3487936 450 $approveselect = ' AND (r.approved=1 OR r.userid=:myid1) ';
451 $params['myid1'] = $USER->id;
7900ecb0 452 } else {
453 $approveselect = ' AND r.approved=1 ';
454 }
4431d2e0 455 } else {
7900ecb0 456 $approveselect = ' ';
4431d2e0 457 }
3d4b223a 458
7900ecb0 459 if ($currentgroup) {
e3487936 460 $groupselect = " AND (r.groupid = :currentgroup OR r.groupid = 0)";
461 $params['currentgroup'] = $currentgroup;
64452eb4 462 } else {
7900ecb0 463 $groupselect = ' ';
64452eb4 464 }
3d45b8e5 465
5e1f1a6e 466 // Init some variables to be used by advanced search
467 $advsearchselect = '';
468 $advwhere = '';
469 $advtables = '';
470 $advparams = array();
471
7900ecb0 472 /// Find the field we are sorting on
3239b010 473 if ($sort <= 0 or !$sortfield = data_get_field_from_id($sort, $data)) {
bb5740f4 474
475 switch ($sort) {
476 case DATA_LASTNAME:
477 $ordering = "u.lastname $order, u.firstname $order";
478 break;
479 case DATA_FIRSTNAME:
480 $ordering = "u.firstname $order, u.lastname $order";
481 break;
482 case DATA_APPROVED:
483 $ordering = "r.approved $order, r.timecreated $order";
484 break;
3239b010 485 case DATA_TIMEMODIFIED:
486 $ordering = "r.timemodified $order";
487 break;
488 case DATA_TIMEADDED:
bb5740f4 489 default:
3239b010 490 $sort = 0;
bb5740f4 491 $ordering = "r.timecreated $order";
714bec74 492 }
493
494 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname';
495 $count = ' COUNT(DISTINCT c.recordid) ';
e3487936 496 $tables = '{data_content} c,{data_records} r, {data_content} cs, {user} u ';
714bec74 497 $where = 'WHERE c.recordid = r.id
e3487936 498 AND r.dataid = :dataid
714bec74 499 AND r.userid = u.id
500 AND cs.recordid = r.id ';
e3487936 501 $params['dataid'] = $data->id;
714bec74 502 $sortorder = ' ORDER BY '.$ordering.', r.id ASC ';
503 $searchselect = '';
504
505 // If requiredentries is not reached, only show current user's entries
506 if (!$requiredentries_allowed) {
e3487936 507 $where .= ' AND u.id = :myid2 ';
508 $params['myid2'] = $USER->id;
714bec74 509 }
510
511 if (!empty($advanced)) { //If advanced box is checked.
e3487936 512 $i = 0;
714bec74 513 foreach($search_array as $key => $val) { //what does $search_array hold?
514 if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
e3487936 515 $i++;
800bb0f7 516 $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
e3487936 517 $params['search_flname_'.$i] = "%$val->data%";
714bec74 518 continue;
519 }
5e1f1a6e 520 $advtables .= ', {data_content} c'.$key.' ';
521 $advwhere .= ' AND c'.$key.'.recordid = r.id';
522 $advsearchselect .= ' AND ('.$val->sql.') ';
523 $advparams = array_merge($advparams, $val->params);
714bec74 524 }
525 } else if ($search) {
800bb0f7 526 $searchselect = " AND (".$DB->sql_like('cs.content', ':search1', false)." OR ".$DB->sql_like('u.firstname', ':search2', false)." OR ".$DB->sql_like('u.lastname', ':search3', false)." ) ";
e3487936 527 $params['search1'] = "%$search%";
528 $params['search2'] = "%$search%";
529 $params['search3'] = "%$search%";
714bec74 530 } else {
531 $searchselect = ' ';
532 }
533
3239b010 534 } else {
7900ecb0 535
6e6878b5
EL
536 $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
537 $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
714bec74 538
6e6878b5 539 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' . $sortcontentfull . ' AS _order ';
7900ecb0 540 $count = ' COUNT(DISTINCT c.recordid) ';
e3487936 541 $tables = '{data_content} c, {data_records} r, {data_content} cs, {user} u ';
7900ecb0 542 $where = 'WHERE c.recordid = r.id
e3487936 543 AND c.fieldid = :sort
544 AND r.dataid = :dataid
7900ecb0 545 AND r.userid = u.id
714bec74 546 AND cs.recordid = r.id ';
e3487936 547 $params['dataid'] = $data->id;
548 $params['sort'] = $sort;
b99b25ea 549 $sortorder = ' ORDER BY _order '.$order.' , r.id ASC ';
7900ecb0 550 $searchselect = '';
714bec74 551
87518137 552 // If requiredentries is not reached, only show current user's entries
553 if (!$requiredentries_allowed) {
554 $where .= ' AND u.id = ' . $USER->id;
e3487936 555 $params['myid2'] = $USER->id;
87518137 556 }
714bec74 557
558 if (!empty($advanced)) { //If advanced box is checked.
559 foreach($search_array as $key => $val) { //what does $search_array hold?
560 if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
e3487936 561 $i++;
800bb0f7 562 $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
e3487936 563 $params['search_flname_'.$i] = "%$val->data%";
714bec74 564 continue;
565 }
5e1f1a6e 566 $advtables .= ', {data_content} c'.$key.' ';
567 $advwhere .= ' AND c'.$key.'.recordid = r.id AND c'.$key.'.fieldid = '.$key;
568 $advsearchselect .= ' AND ('.$val->sql.') ';
569 $advparams = array_merge($advparams, $val->params);
7900ecb0 570 }
714bec74 571 } else if ($search) {
800bb0f7 572 $searchselect = " AND (".$DB->sql_like('cs.content', ':search1', false)." OR ".$DB->sql_like('u.firstname', ':search2', false)." OR ".$DB->sql_like('u.lastname', ':search3', false)." ) ";
e3487936 573 $params['search1'] = "%$search%";
574 $params['search2'] = "%$search%";
575 $params['search3'] = "%$search%";
7900ecb0 576 } else {
577 $searchselect = ' ';
714bec74 578 }
7900ecb0 579 }
3d4b223a 580
7900ecb0 581 /// To actually fetch the records
3d45b8e5 582
5e1f1a6e 583 $fromsql = "FROM $tables $advtables $where $advwhere $groupselect $approveselect $searchselect $advsearchselect";
eeeb4f2a 584 $sqlselect = "SELECT $what $fromsql $sortorder";
585 $sqlcount = "SELECT $count $fromsql"; // Total number of records when searching
eeeb4f2a 586 $sqlmax = "SELECT $count FROM $tables $where $groupselect $approveselect"; // number of all recoirds user may see
5e1f1a6e 587 $allparams = array_merge($params, $advparams);
3d45b8e5 588
eeeb4f2a 589 /// Work out the paging numbers and counts
3d45b8e5 590
5e1f1a6e 591 $totalcount = $DB->count_records_sql($sqlcount, $allparams);
592 if (empty($searchselect) && empty($advsearchselect)) {
eeeb4f2a 593 $maxcount = $totalcount;
594 } else {
e3487936 595 $maxcount = $DB->count_records_sql($sqlmax, $params);
eeeb4f2a 596 }
3d4b223a 597
7900ecb0 598 if ($record) { // We need to just show one, so where is it in context?
599 $nowperpage = 1;
600 $mode = 'single';
de89899b 601
7900ecb0 602 $page = 0;
80c2a742
EL
603 // TODO: Improve this because we are executing $sqlselect twice (here and some lines below)!
604 if ($allrecordids = $DB->get_fieldset_sql($sqlselect, $allparams)) {
029cf846 605 $page = (int)array_search($record->id, $allrecordids);
606 unset($allrecordids);
3d45b8e5 607 }
3d45b8e5 608
7900ecb0 609 } else if ($mode == 'single') { // We rely on ambient $page settings
610 $nowperpage = 1;
3d45b8e5 611
7900ecb0 612 } else {
613 $nowperpage = $perpage;
614 }
3d45b8e5 615
7900ecb0 616 /// Get the actual records
8429163d 617
5e1f1a6e 618 if (!$records = $DB->get_records_sql($sqlselect, $allparams, $page * $nowperpage, $nowperpage)) {
eeeb4f2a 619 // Nothing to show!
7900ecb0 620 if ($record) { // Something was requested so try to show that at least (bug 5132)
621 if (has_capability('mod/data:manageentries', $context) || empty($data->approval) ||
622 $record->approved || (isloggedin() && $record->userid == $USER->id)) {
623 if (!$currentgroup || $record->groupid == $currentgroup || $record->groupid == 0) {
eeeb4f2a 624 // OK, we can show this one
625 $records = array($record->id => $record);
626 $totalcount = 1;
7900ecb0 627 }
3dec563c 628 }
629 }
eeeb4f2a 630 }
631
632 if (empty($records)) {
633 if ($maxcount){
39790bd8 634 $a = new stdClass();
eeeb4f2a 635 $a->max = $maxcount;
636 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
4102b449 637 echo $OUTPUT->notification(get_string('foundnorecords','data', $a));
7900ecb0 638 } else {
4102b449 639 echo $OUTPUT->notification(get_string('norecords','data'));
7900ecb0 640 }
cf3e199b 641
eeeb4f2a 642 } else { // We have some records to print
643
644 if ($maxcount != $totalcount) {
39790bd8 645 $a = new stdClass();
eeeb4f2a 646 $a->num = $totalcount;
647 $a->max = $maxcount;
648 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
4102b449 649 echo $OUTPUT->notification(get_string('foundrecords', 'data', $a), 'notifysuccess');
eeeb4f2a 650 }
68c88622 651
7900ecb0 652 if ($mode == 'single') { // Single template
d53e5129 653 $baseurl = 'view.php?d=' . $data->id . '&amp;mode=single&amp;';
2d9b3ef2 654 if (!empty($search)) {
655 $baseurl .= 'filter=1&amp;';
656 }
929d7a83 657 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
3d45b8e5 658
7900ecb0 659 if (empty($data->singletemplate)){
4102b449 660 echo $OUTPUT->notification(get_string('nosingletemplate','data'));
7900ecb0 661 data_generate_default_template($data, 'singletemplate', 0, false, false);
662 }
3d4b223a 663
d251b259
AD
664 //data_print_template() only adds ratings for singletemplate which is why we're attaching them here
665 //attach ratings to data records
666 require_once($CFG->dirroot.'/rating/lib.php');
198ff498
AD
667 if ($data->assessed!=RATING_AGGREGATE_NONE) {
668 $ratingoptions = new stdclass();
669 $ratingoptions->context = $cm->context;
670 $ratingoptions->items = $records;
671 $ratingoptions->aggregate = $data->assessed;//the aggregation method
672 $ratingoptions->scaleid = $data->scale;
673 $ratingoptions->userid = $USER->id;
674 $ratingoptions->returnurl = $CFG->wwwroot.'/mod/data/'.$baseurl;
675 $ratingoptions->assesstimestart = $data->assesstimestart;
676 $ratingoptions->assesstimefinish = $data->assesstimefinish;
677 $ratingoptions->plugintype = 'mod';
678 $ratingoptions->pluginname = 'data';
679
680 $rm = new rating_manager();
681 $records = $rm->get_ratings($ratingoptions);
682 }
d251b259 683
7900ecb0 684 data_print_template('singletemplate', $records, $data, $search, $page);
3d45b8e5 685
929d7a83 686 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
3d45b8e5 687
7900ecb0 688 } else { // List template
689 $baseurl = 'view.php?d='.$data->id.'&amp;';
690 //send the advanced flag through the URL so it is remembered while paging.
691 $baseurl .= 'advanced='.$advanced.'&amp;';
2d9b3ef2 692 if (!empty($search)) {
693 $baseurl .= 'filter=1&amp;';
694 }
7900ecb0 695 //pass variable to allow determining whether or not we are paging through results.
696 $baseurl .= 'paging='.$paging.'&amp;';
3d45b8e5 697
929d7a83 698 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
3d45b8e5 699
7900ecb0 700 if (empty($data->listtemplate)){
4102b449 701 echo $OUTPUT->notification(get_string('nolisttemplate','data'));
7900ecb0 702 data_generate_default_template($data, 'listtemplate', 0, false, false);
703 }
704 echo $data->listtemplateheader;
705 data_print_template('listtemplate', $records, $data, $search, $page);
706 echo $data->listtemplatefooter;
707
929d7a83 708 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
3d45b8e5 709 }
3d45b8e5 710
3d45b8e5 711 }
7900ecb0 712 }
8429163d 713
7900ecb0 714 $search = trim($search);
715 if (empty($records)) {
716 $records = array();
f852d652 717 }
718
c3e1b5bd
PL
719 if ($mode == '' && $CFG->enableportfolios) {
720 require_once($CFG->libdir . '/portfoliolib.php');
721 $button = new portfolio_add_button();
722 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id), '/mod/data/locallib.php');
723 if (data_portfolio_caller::has_files($data)) {
724 $button->set_formats(array(PORTFOLIO_FORMAT_RICHHTML, PORTFOLIO_FORMAT_LEAP2A)); // no plain html for us
725 }
726 echo $button->to_html(PORTFOLIO_ADD_FULL_FORM);
727 }
728
7900ecb0 729 //Advanced search form doesn't make sense for single (redirects list view)
eeeb4f2a 730 if (($maxcount || $mode == 'asearch') && $mode != 'single') {
7900ecb0 731 data_print_preference_form($data, $perpage, $search, $sort, $order, $search_array, $advanced, $mode);
64452eb4 732 }
3d4b223a 733
18a2a0cb 734/// Mark as viewed
735 $completion=new completion_info($course);
736 $completion->set_module_viewed($cm);
4a9eecc4 737}
d4a03c00 738
4a9eecc4 739echo $OUTPUT->footer();
1adbd2c3 740