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