MDL-33791 Portfolio: Fixed security issue with passing file paths.
[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
0b3b8c30 87 $context = context_module::instance($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
f8311def 233 if (textlib::strlen($search) < 2) {
76a2fd82 234 $search = '';
235 }
3d45b8e5 236 $SESSION->dataprefs[$data->id]['search'] = $search; // Make it sticky
237
238 $sort = optional_param('sort', $SESSION->dataprefs[$data->id]['sort'], PARAM_INT);
239 $SESSION->dataprefs[$data->id]['sort'] = $sort; // Make it sticky
240
241 $order = (optional_param('order', $SESSION->dataprefs[$data->id]['order'], PARAM_ALPHA) == 'ASC') ? 'ASC': 'DESC';
242 $SESSION->dataprefs[$data->id]['order'] = $order; // Make it sticky
243
244
245 $oldperpage = get_user_preferences('data_perpage_'.$data->id, 10);
246 $perpage = optional_param('perpage', $oldperpage, PARAM_INT);
247
248 if ($perpage < 2) {
249 $perpage = 2;
250 }
251 if ($perpage != $oldperpage) {
252 set_user_preference('data_perpage_'.$data->id, $perpage);
253 }
254
3d4b223a 255 add_to_log($course->id, 'data', 'view', "view.php?id=$cm->id", $data->id, $cm->id);
256
257
a9f19d81
DC
258 $urlparams = array('d' => $data->id);
259 if ($record) {
260 $urlparams['rid'] = $record->id;
261 }
262 if ($page) {
263 $urlparams['page'] = $page;
264 }
265 if ($mode) {
266 $urlparams['mode'] = $mode;
267 }
268 if ($filter) {
269 $urlparams['filter'] = $filter;
270 }
3d4b223a 271// Initialize $PAGE, compute blocks
a9f19d81 272 $PAGE->set_url('/mod/data/view.php', $urlparams);
3d4b223a 273
d2b23346 274 if (($edit != -1) and $PAGE->user_allowed_editing()) {
275 $USER->editing = $edit;
3d4b223a 276 }
3d4b223a 277
0b3b8c30 278 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
8ebbb06a 279
b0100852 280/// RSS and CSS and JS meta
68635e6f 281 $meta = '';
64452eb4 282 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
8ebbb06a 283 $rsstitle = $courseshortname . ': %fullname%';
43b92251 284 rss_add_http_header($context, 'mod_data', $data, $rsstitle);
68635e6f 285 }
286 if ($data->csstemplate) {
c0467479 287 $PAGE->requires->css('/mod/data/css.php?d='.$data->id);
c853304e 288 }
b0100852 289 if ($data->jstemplate) {
60409fe1 290 $PAGE->requires->js('/mod/data/js.php?d='.$data->id, true);
b0100852 291 }
292
6553cda7 293 // Mark as viewed
294 $completion = new completion_info($course);
295 $completion->set_module_viewed($cm);
296
c853304e 297/// Print the page header
b7b2d0f3 298 // Note: MDL-19010 there will be further changes to printing header and blocks.
299 // The code will be much nicer than this eventually.
8ebbb06a 300 $title = $courseshortname.': ' . format_string($data->name);
3681f9a9 301
59e2121e 302 if ($PAGE->user_allowed_editing()) {
4aea3cc7 303 $buttons = '<table><tr><td><form method="get" action="view.php"><div>'.
3681f9a9 304 '<input type="hidden" name="id" value="'.$cm->id.'" />'.
305 '<input type="hidden" name="edit" value="'.($PAGE->user_is_editing()?'off':'on').'" />'.
92059c7e
SH
306 '<input type="submit" value="'.get_string($PAGE->user_is_editing()?'blockseditoff':'blocksediton').'" /></div></form></td></tr></table>';
307 $PAGE->set_button($buttons);
3681f9a9 308 }
aab98aaf 309
29b64a22 310 if ($mode == 'asearch') {
311 $PAGE->navbar->add(get_string('search'));
312 }
313
b0ff558c 314 $PAGE->set_title($title);
315 $PAGE->set_heading($course->fullname);
dd88de0e 316
b0ff558c 317 echo $OUTPUT->header();
1adbd2c3 318
3b27b0fe 319/// Check to see if groups are being used here
f1035deb 320 $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
321 groups_print_activity_menu($cm, $returnurl);
322 $currentgroup = groups_get_activity_group($cm);
323 $groupmode = groups_get_activity_groupmode($cm);
76fb0443
AG
324 // If a student is not part of a group and seperate groups is enabled, we don't
325 // want them seeing all records.
326 if ($currentgroup == 0 && $groupmode == 1 && !has_capability('mod/data:manageentries', $context)) {
327 $canviewallrecords = false;
328 } else {
329 $canviewallrecords = true;
330 }
3b27b0fe 331
e822f07b 332 // detect entries not approved yet and show hint instead of not found error
ebb621f6 333 if ($record and $data->approval and !$record->approved and $record->userid != $USER->id and !has_capability('mod/data:manageentries', $context)) {
334 if (!$currentgroup or $record->groupid == $currentgroup or $record->groupid == 0) {
335 print_error('notapproved', 'data');
336 }
337 }
338
b2dc6880 339 echo $OUTPUT->heading(format_string($data->name));
aab98aaf 340
a593aeee 341 // Do we need to show a link to the RSS feed for the records?
9e86f2e7
AD
342 //this links has been Settings (database activity administration) block
343 /*if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
a593aeee 344 echo '<div style="float:right;">';
aa60291e 345 rss_print_link($context->id, $USER->id, 'mod_data', $data->id, get_string('rsstype'));
a593aeee 346 echo '</div>';
347 echo '<div style="clear:both;"></div>';
9e86f2e7 348 }*/
aab98aaf 349
9e08cf6e 350 if ($data->intro and empty($page) and empty($record) and $mode != 'single') {
39790bd8 351 $options = new stdClass();
ea6073bb 352 $options->noclean = true;
883fa987 353 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
56135f6b 354 }
355
473dd288 356/// Delete any requested records
357
046dd7dc 358 if ($delete && confirm_sesskey() && (has_capability('mod/data:manageentries', $context) or data_isowner($delete))) {
3d45b8e5 359 if ($confirm = optional_param('confirm',0,PARAM_INT)) {
3223bc9e 360 if ($deleterecord = $DB->get_record('data_records', array('id'=>$delete))) { // Need to check this is valid
3d45b8e5 361 if ($deleterecord->dataid == $data->id) { // Must be from this database
3223bc9e 362 if ($contents = $DB->get_records('data_content', array('recordid'=>$deleterecord->id))) {
3d45b8e5 363 foreach ($contents as $content) { // Delete files or whatever else this field allows
364 if ($field = data_get_field_from_id($content->fieldid, $data)) { // Might not be there
365 $field->delete_content($content->recordid);
366 }
3d4b223a 367 }
368 }
3223bc9e 369 $DB->delete_records('data_content', array('recordid'=>$deleterecord->id));
370 $DB->delete_records('data_records', array('id'=>$deleterecord->id));
f0497d6f 371
3d45b8e5 372 add_to_log($course->id, 'data', 'record delete', "view.php?id=$cm->id", $data->id, $cm->id);
f0497d6f 373
4102b449 374 echo $OUTPUT->notification(get_string('recorddeleted','data'), 'notifysuccess');
3d45b8e5 375 }
3d4b223a 376 }
3d45b8e5 377
378 } else { // Print a confirmation page
3223bc9e 379 if ($deleterecord = $DB->get_record('data_records', array('id'=>$delete))) { // Need to check this is valid
64452eb4 380 if ($deleterecord->dataid == $data->id) { // Must be from this database
e822f07b 381 $deletebutton = new single_button(new moodle_url('/mod/data/view.php?d='.$data->id.'&delete='.$delete.'&confirm=1'), get_string('delete'), 'post');
cd6137d7 382 echo $OUTPUT->confirm(get_string('confirmdeleterecord','data'),
e822f07b 383 $deletebutton, 'view.php?d='.$data->id);
3d45b8e5 384
64452eb4 385 $records[] = $deleterecord;
3f9672d3 386 echo data_print_template('singletemplate', $records, $data, '', 0, true);
64452eb4 387
7b30ba8b 388 echo $OUTPUT->footer();
64452eb4 389 exit;
390 }
391 }
392 }
393 }
394
395
2742ffe7 396//if data activity closed dont let students in
4a9eecc4 397$showactivity = true;
2742ffe7
AD
398if (!has_capability('mod/data:manageentries', $context)) {
399 $timenow = time();
400 if (!empty($data->timeavailablefrom) && $data->timeavailablefrom > $timenow) {
4a9eecc4
AD
401 echo $OUTPUT->notification(get_string('notopenyet', 'data', userdate($data->timeavailablefrom)));
402 $showactivity = false;
2742ffe7 403 } else if (!empty($data->timeavailableto) && $timenow > $data->timeavailableto) {
4a9eecc4
AD
404 echo $OUTPUT->notification(get_string('expired', 'data', userdate($data->timeavailableto)));
405 $showactivity = false;
2742ffe7
AD
406 }
407}
64452eb4 408
4a9eecc4
AD
409if ($showactivity) {
410 // Print the tabs
64452eb4 411 if ($record or $mode == 'single') {
412 $currenttab = 'single';
7900ecb0 413 } elseif($mode == 'asearch') {
414 $currenttab = 'asearch';
415 }
416 else {
64452eb4 417 $currenttab = 'list';
418 }
aab98aaf 419 include('tabs.php');
64452eb4 420
eeeb4f2a 421 if ($mode == 'asearch') {
422 $maxcount = 0;
8429163d 423
eeeb4f2a 424 } else {
7900ecb0 425 /// Approve any requested records
e3487936 426 $params = array(); // named params array
64452eb4 427
8429163d 428 $approvecap = has_capability('mod/data:approve', $context);
bb5740f4 429
430 if ($approve && confirm_sesskey() && $approvecap) {
3223bc9e 431 if ($approverecord = $DB->get_record('data_records', array('id'=>$approve))) { // Need to check this is valid
7900ecb0 432 if ($approverecord->dataid == $data->id) { // Must be from this database
39790bd8 433 $newrecord = new stdClass();
7900ecb0 434 $newrecord->id = $approverecord->id;
435 $newrecord->approved = 1;
dd88de0e
PS
436 $DB->update_record('data_records', $newrecord);
437 echo $OUTPUT->notification(get_string('recordapproved','data'), 'notifysuccess');
64452eb4 438 }
439 }
3d4b223a 440 }
8429163d 441
c861f079 442 $numentries = data_numentries($data);
443 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
eeeb4f2a 444 if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !has_capability('mod/data:manageentries', $context)) {
445 $data->entriesleft = $data->requiredentries - $numentries;
446 $strentrieslefttoadd = get_string('entrieslefttoadd', 'data', $data);
4102b449 447 echo $OUTPUT->notification($strentrieslefttoadd);
c861f079 448 }
449
450 /// 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)
451 $requiredentries_allowed = true;
452 if ($data->requiredentriestoview > 0 && $numentries < $data->requiredentriestoview && !has_capability('mod/data:manageentries', $context)) {
453 $data->entrieslefttoview = $data->requiredentriestoview - $numentries;
454 $strentrieslefttoaddtoview = get_string('entrieslefttoaddtoview', 'data', $data);
4102b449 455 echo $OUTPUT->notification($strentrieslefttoaddtoview);
eeeb4f2a 456 $requiredentries_allowed = false;
457 }
3d4b223a 458
e2c5f386
AG
459 // Initialise the first group of params for advanced searches.
460 $initialparams = array();
461
bb5740f4 462 /// setup group and approve restrictions
463 if (!$approvecap && $data->approval) {
7900ecb0 464 if (isloggedin()) {
e3487936 465 $approveselect = ' AND (r.approved=1 OR r.userid=:myid1) ';
466 $params['myid1'] = $USER->id;
e2c5f386 467 $initialparams['myid1'] = $params['myid1'];
7900ecb0 468 } else {
469 $approveselect = ' AND r.approved=1 ';
470 }
4431d2e0 471 } else {
7900ecb0 472 $approveselect = ' ';
4431d2e0 473 }
3d4b223a 474
7900ecb0 475 if ($currentgroup) {
e3487936 476 $groupselect = " AND (r.groupid = :currentgroup OR r.groupid = 0)";
477 $params['currentgroup'] = $currentgroup;
e2c5f386 478 $initialparams['currentgroup'] = $params['currentgroup'];
64452eb4 479 } else {
76fb0443
AG
480 if ($canviewallrecords) {
481 $groupselect = ' ';
482 } else {
483 // If separate groups are enabled and the user isn't in a group or
484 // a teacher, manager, admin etc, then just show them entries for 'All participants'.
485 $groupselect = " AND r.groupid = 0";
486 }
64452eb4 487 }
3d45b8e5 488
5e1f1a6e 489 // Init some variables to be used by advanced search
490 $advsearchselect = '';
491 $advwhere = '';
492 $advtables = '';
493 $advparams = array();
e2c5f386
AG
494 // This is used for the initial reduction of advanced search results with required entries.
495 $entrysql = '';
5e1f1a6e 496
7900ecb0 497 /// Find the field we are sorting on
3239b010 498 if ($sort <= 0 or !$sortfield = data_get_field_from_id($sort, $data)) {
bb5740f4 499
500 switch ($sort) {
501 case DATA_LASTNAME:
502 $ordering = "u.lastname $order, u.firstname $order";
503 break;
504 case DATA_FIRSTNAME:
505 $ordering = "u.firstname $order, u.lastname $order";
506 break;
507 case DATA_APPROVED:
508 $ordering = "r.approved $order, r.timecreated $order";
509 break;
3239b010 510 case DATA_TIMEMODIFIED:
511 $ordering = "r.timemodified $order";
512 break;
513 case DATA_TIMEADDED:
bb5740f4 514 default:
3239b010 515 $sort = 0;
bb5740f4 516 $ordering = "r.timecreated $order";
714bec74 517 }
518
519 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname';
520 $count = ' COUNT(DISTINCT c.recordid) ';
eb6e0c61 521 $tables = '{data_content} c,{data_records} r, {user} u ';
714bec74 522 $where = 'WHERE c.recordid = r.id
e3487936 523 AND r.dataid = :dataid
eb6e0c61 524 AND r.userid = u.id ';
e3487936 525 $params['dataid'] = $data->id;
714bec74 526 $sortorder = ' ORDER BY '.$ordering.', r.id ASC ';
527 $searchselect = '';
528
529 // If requiredentries is not reached, only show current user's entries
530 if (!$requiredentries_allowed) {
e3487936 531 $where .= ' AND u.id = :myid2 ';
e2c5f386 532 $entrysql = ' AND r.userid = :myid3 ';
e3487936 533 $params['myid2'] = $USER->id;
e2c5f386 534 $initialparams['myid3'] = $params['myid2'];
714bec74 535 }
536
537 if (!empty($advanced)) { //If advanced box is checked.
e3487936 538 $i = 0;
714bec74 539 foreach($search_array as $key => $val) { //what does $search_array hold?
540 if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
e3487936 541 $i++;
800bb0f7 542 $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
e3487936 543 $params['search_flname_'.$i] = "%$val->data%";
714bec74 544 continue;
545 }
5e1f1a6e 546 $advtables .= ', {data_content} c'.$key.' ';
547 $advwhere .= ' AND c'.$key.'.recordid = r.id';
548 $advsearchselect .= ' AND ('.$val->sql.') ';
549 $advparams = array_merge($advparams, $val->params);
714bec74 550 }
551 } else if ($search) {
eb6e0c61 552 $searchselect = " AND (".$DB->sql_like('c.content', ':search1', false)." OR ".$DB->sql_like('u.firstname', ':search2', false)." OR ".$DB->sql_like('u.lastname', ':search3', false)." ) ";
e3487936 553 $params['search1'] = "%$search%";
554 $params['search2'] = "%$search%";
555 $params['search3'] = "%$search%";
714bec74 556 } else {
557 $searchselect = ' ';
558 }
559
3239b010 560 } else {
7900ecb0 561
6e6878b5
EL
562 $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
563 $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
714bec74 564
0a498686 565 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' . $sortcontentfull . ' AS sortorder ';
7900ecb0 566 $count = ' COUNT(DISTINCT c.recordid) ';
eb6e0c61 567 $tables = '{data_content} c, {data_records} r, {user} u ';
7900ecb0 568 $where = 'WHERE c.recordid = r.id
e3487936 569 AND r.dataid = :dataid
eb6e0c61 570 AND r.userid = u.id ';
e2c5f386
AG
571 if (!$advanced) {
572 $where .= 'AND c.fieldid = :sort';
573 }
e3487936 574 $params['dataid'] = $data->id;
575 $params['sort'] = $sort;
0a498686 576 $sortorder = ' ORDER BY sortorder '.$order.' , r.id ASC ';
7900ecb0 577 $searchselect = '';
714bec74 578
87518137 579 // If requiredentries is not reached, only show current user's entries
580 if (!$requiredentries_allowed) {
e2c5f386
AG
581 $where .= ' AND u.id = :myid2';
582 $entrysql = ' AND r.userid = :myid3';
e3487936 583 $params['myid2'] = $USER->id;
e2c5f386 584 $initialparams['myid3'] = $params['myid2'];
87518137 585 }
db546510 586 $i = 0;
714bec74 587 if (!empty($advanced)) { //If advanced box is checked.
588 foreach($search_array as $key => $val) { //what does $search_array hold?
589 if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
e3487936 590 $i++;
800bb0f7 591 $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
e3487936 592 $params['search_flname_'.$i] = "%$val->data%";
714bec74 593 continue;
594 }
5e1f1a6e 595 $advtables .= ', {data_content} c'.$key.' ';
596 $advwhere .= ' AND c'.$key.'.recordid = r.id AND c'.$key.'.fieldid = '.$key;
597 $advsearchselect .= ' AND ('.$val->sql.') ';
598 $advparams = array_merge($advparams, $val->params);
7900ecb0 599 }
714bec74 600 } else if ($search) {
eb6e0c61 601 $searchselect = " AND (".$DB->sql_like('c.content', ':search1', false)." OR ".$DB->sql_like('u.firstname', ':search2', false)." OR ".$DB->sql_like('u.lastname', ':search3', false)." ) ";
e3487936 602 $params['search1'] = "%$search%";
603 $params['search2'] = "%$search%";
604 $params['search3'] = "%$search%";
7900ecb0 605 } else {
606 $searchselect = ' ';
714bec74 607 }
7900ecb0 608 }
3d4b223a 609
7900ecb0 610 /// To actually fetch the records
3d45b8e5 611
5e1f1a6e 612 $fromsql = "FROM $tables $advtables $where $advwhere $groupselect $approveselect $searchselect $advsearchselect";
5e1f1a6e 613 $allparams = array_merge($params, $advparams);
3d45b8e5 614
76fb0443 615 // Provide initial sql statements and parameters to reduce the number of total records.
e2c5f386 616 $initialselect = $groupselect . $approveselect . $entrysql;
76fb0443 617
e2c5f386 618 $recordids = data_get_all_recordids($data->id, $initialselect, $initialparams);
db546510 619 $newrecordids = data_get_advance_search_ids($recordids, $search_array, $data->id);
0ba303e8 620 $totalcount = count($newrecordids);
e2c5f386 621 $selectdata = $where . $groupselect . $approveselect;
db546510 622
623 if (!empty($advanced)) {
624 $advancedsearchsql = data_get_advanced_search_sql($sort, $data, $newrecordids, $selectdata, $sortorder);
625 $sqlselect = $advancedsearchsql['sql'];
626 $allparams = array_merge($allparams, $advancedsearchsql['params']);
627 } else {
628 $sqlselect = "SELECT $what $fromsql $sortorder";
629 }
3d45b8e5 630
db546510 631 /// Work out the paging numbers and counts
5e1f1a6e 632 if (empty($searchselect) && empty($advsearchselect)) {
eeeb4f2a 633 $maxcount = $totalcount;
634 } else {
db546510 635 $maxcount = count($recordids);
eeeb4f2a 636 }
3d4b223a 637
7900ecb0 638 if ($record) { // We need to just show one, so where is it in context?
639 $nowperpage = 1;
640 $mode = 'single';
db79db63
AG
641 $page = 0;
642 // TODO MDL-33797 - Reduce this or consider redesigning the paging system.
643 if ($allrecordids = $DB->get_fieldset_sql($sqlselect, $allparams)) {
644 $page = (int)array_search($record->id, $allrecordids);
645 unset($allrecordids);
646 }
7900ecb0 647 } else if ($mode == 'single') { // We rely on ambient $page settings
648 $nowperpage = 1;
3d45b8e5 649
7900ecb0 650 } else {
651 $nowperpage = $perpage;
652 }
3d45b8e5 653
7900ecb0 654 /// Get the actual records
8429163d 655
5e1f1a6e 656 if (!$records = $DB->get_records_sql($sqlselect, $allparams, $page * $nowperpage, $nowperpage)) {
eeeb4f2a 657 // Nothing to show!
7900ecb0 658 if ($record) { // Something was requested so try to show that at least (bug 5132)
659 if (has_capability('mod/data:manageentries', $context) || empty($data->approval) ||
660 $record->approved || (isloggedin() && $record->userid == $USER->id)) {
661 if (!$currentgroup || $record->groupid == $currentgroup || $record->groupid == 0) {
eeeb4f2a 662 // OK, we can show this one
663 $records = array($record->id => $record);
664 $totalcount = 1;
7900ecb0 665 }
3dec563c 666 }
667 }
eeeb4f2a 668 }
669
670 if (empty($records)) {
671 if ($maxcount){
39790bd8 672 $a = new stdClass();
eeeb4f2a 673 $a->max = $maxcount;
674 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
4102b449 675 echo $OUTPUT->notification(get_string('foundnorecords','data', $a));
7900ecb0 676 } else {
4102b449 677 echo $OUTPUT->notification(get_string('norecords','data'));
7900ecb0 678 }
cf3e199b 679
eeeb4f2a 680 } else { // We have some records to print
681
682 if ($maxcount != $totalcount) {
39790bd8 683 $a = new stdClass();
eeeb4f2a 684 $a->num = $totalcount;
685 $a->max = $maxcount;
686 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
4102b449 687 echo $OUTPUT->notification(get_string('foundrecords', 'data', $a), 'notifysuccess');
eeeb4f2a 688 }
68c88622 689
c04b01f4
AD
690 if ($mode == 'single') { // Single template
691 $baseurl = 'view.php?d=' . $data->id . '&mode=single&';
2d9b3ef2 692 if (!empty($search)) {
c04b01f4
AD
693 $baseurl .= 'filter=1&';
694 }
695 if (!empty($page)) {
696 $baseurl .= 'page=' . $page;
2d9b3ef2 697 }
929d7a83 698 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
3d45b8e5 699
7900ecb0 700 if (empty($data->singletemplate)){
4102b449 701 echo $OUTPUT->notification(get_string('nosingletemplate','data'));
7900ecb0 702 data_generate_default_template($data, 'singletemplate', 0, false, false);
703 }
3d4b223a 704
d251b259
AD
705 //data_print_template() only adds ratings for singletemplate which is why we're attaching them here
706 //attach ratings to data records
707 require_once($CFG->dirroot.'/rating/lib.php');
2b04c41c
SH
708 if ($data->assessed != RATING_AGGREGATE_NONE) {
709 $ratingoptions = new stdClass;
195a0848 710 $ratingoptions->context = $context;
2c2ff8d5 711 $ratingoptions->component = 'mod_data';
2b04c41c 712 $ratingoptions->ratingarea = 'entry';
198ff498
AD
713 $ratingoptions->items = $records;
714 $ratingoptions->aggregate = $data->assessed;//the aggregation method
715 $ratingoptions->scaleid = $data->scale;
716 $ratingoptions->userid = $USER->id;
717 $ratingoptions->returnurl = $CFG->wwwroot.'/mod/data/'.$baseurl;
718 $ratingoptions->assesstimestart = $data->assesstimestart;
719 $ratingoptions->assesstimefinish = $data->assesstimefinish;
198ff498
AD
720
721 $rm = new rating_manager();
722 $records = $rm->get_ratings($ratingoptions);
723 }
d251b259 724
7900ecb0 725 data_print_template('singletemplate', $records, $data, $search, $page);
3d45b8e5 726
929d7a83 727 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
3d45b8e5 728
7900ecb0 729 } else { // List template
730 $baseurl = 'view.php?d='.$data->id.'&amp;';
731 //send the advanced flag through the URL so it is remembered while paging.
732 $baseurl .= 'advanced='.$advanced.'&amp;';
2d9b3ef2 733 if (!empty($search)) {
734 $baseurl .= 'filter=1&amp;';
735 }
7900ecb0 736 //pass variable to allow determining whether or not we are paging through results.
737 $baseurl .= 'paging='.$paging.'&amp;';
3d45b8e5 738
929d7a83 739 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
3d45b8e5 740
7900ecb0 741 if (empty($data->listtemplate)){
4102b449 742 echo $OUTPUT->notification(get_string('nolisttemplate','data'));
7900ecb0 743 data_generate_default_template($data, 'listtemplate', 0, false, false);
744 }
745 echo $data->listtemplateheader;
746 data_print_template('listtemplate', $records, $data, $search, $page);
747 echo $data->listtemplatefooter;
748
929d7a83 749 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
3d45b8e5 750 }
3d45b8e5 751
3d45b8e5 752 }
7900ecb0 753 }
8429163d 754
7900ecb0 755 $search = trim($search);
756 if (empty($records)) {
757 $records = array();
f852d652 758 }
759
6708a1f5 760 if ($mode == '' && !empty($CFG->enableportfolios)) {
c3e1b5bd
PL
761 require_once($CFG->libdir . '/portfoliolib.php');
762 $button = new portfolio_add_button();
37743241 763 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id), 'mod_data');
c3e1b5bd
PL
764 if (data_portfolio_caller::has_files($data)) {
765 $button->set_formats(array(PORTFOLIO_FORMAT_RICHHTML, PORTFOLIO_FORMAT_LEAP2A)); // no plain html for us
766 }
767 echo $button->to_html(PORTFOLIO_ADD_FULL_FORM);
768 }
769
7900ecb0 770 //Advanced search form doesn't make sense for single (redirects list view)
eeeb4f2a 771 if (($maxcount || $mode == 'asearch') && $mode != 'single') {
7900ecb0 772 data_print_preference_form($data, $perpage, $search, $sort, $order, $search_array, $advanced, $mode);
64452eb4 773 }
4a9eecc4 774}
d4a03c00 775
4a9eecc4 776echo $OUTPUT->footer();