MDL-56338 message_popup: add behat tests for message popover
[moodle.git] / mod / data / view.php
blob964945170853f62b8d22577c1e47098990a99837
1 <?php
2 ///////////////////////////////////////////////////////////////////////////
3 // //
4 // NOTICE OF COPYRIGHT //
5 // //
6 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
7 // http://moodle.org //
8 // //
9 // Copyright (C) 2005 Martin Dougiamas http://dougiamas.com //
10 // //
11 // This program is free software; you can redistribute it and/or modify //
12 // it under the terms of the GNU General Public License as published by //
13 // the Free Software Foundation; either version 2 of the License, or //
14 // (at your option) any later version. //
15 // //
16 // This program is distributed in the hope that it will be useful, //
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
19 // GNU General Public License for more details: //
20 // //
21 // http://www.gnu.org/copyleft/gpl.html //
22 // //
23 ///////////////////////////////////////////////////////////////////////////
25 require_once(__DIR__ . '/../../config.php');
26 require_once($CFG->dirroot . '/mod/data/lib.php');
27 require_once($CFG->libdir . '/rsslib.php');
28 require_once($CFG->libdir . '/completionlib.php');
30 /// One of these is necessary!
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
38 $edit = optional_param('edit', -1, PARAM_BOOL);
39 $page = optional_param('page', 0, PARAM_INT);
40 /// These can be added to perform an action on a record
41 $approve = optional_param('approve', 0, PARAM_INT); //approval recordid
42 $disapprove = optional_param('disapprove', 0, PARAM_INT); // disapproval recordid
43 $delete = optional_param('delete', 0, PARAM_INT); //delete recordid
44 $multidelete = optional_param_array('delcheck', null, PARAM_INT);
45 $serialdelete = optional_param('serialdelete', null, PARAM_RAW);
47 if ($id) {
48 if (! $cm = get_coursemodule_from_id('data', $id)) {
49 print_error('invalidcoursemodule');
51 if (! $course = $DB->get_record('course', array('id'=>$cm->course))) {
52 print_error('coursemisconf');
54 if (! $data = $DB->get_record('data', array('id'=>$cm->instance))) {
55 print_error('invalidcoursemodule');
57 $record = NULL;
59 } else if ($rid) {
60 if (! $record = $DB->get_record('data_records', array('id'=>$rid))) {
61 print_error('invalidrecord', 'data');
63 if (! $data = $DB->get_record('data', array('id'=>$record->dataid))) {
64 print_error('invalidid', 'data');
66 if (! $course = $DB->get_record('course', array('id'=>$data->course))) {
67 print_error('coursemisconf');
69 if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
70 print_error('invalidcoursemodule');
72 } else { // We must have $d
73 if (! $data = $DB->get_record('data', array('id'=>$d))) {
74 print_error('invalidid', 'data');
76 if (! $course = $DB->get_record('course', array('id'=>$data->course))) {
77 print_error('coursemisconf');
79 if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
80 print_error('invalidcoursemodule');
82 $record = NULL;
85 require_course_login($course, true, $cm);
87 require_once($CFG->dirroot . '/comment/lib.php');
88 comment::init();
90 $context = context_module::instance($cm->id);
91 require_capability('mod/data:viewentry', $context);
93 /// If we have an empty Database then redirect because this page is useless without data
94 if (has_capability('mod/data:managetemplates', $context)) {
95 if (!$DB->record_exists('data_fields', array('dataid'=>$data->id))) { // Brand new database!
96 redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id); // Redirect to field entry
101 /// Check further parameters that set browsing preferences
102 if (!isset($SESSION->dataprefs)) {
103 $SESSION->dataprefs = array();
105 if (!isset($SESSION->dataprefs[$data->id])) {
106 $SESSION->dataprefs[$data->id] = array();
107 $SESSION->dataprefs[$data->id]['search'] = '';
108 $SESSION->dataprefs[$data->id]['search_array'] = array();
109 $SESSION->dataprefs[$data->id]['sort'] = $data->defaultsort;
110 $SESSION->dataprefs[$data->id]['advanced'] = 0;
111 $SESSION->dataprefs[$data->id]['order'] = ($data->defaultsortdir == 0) ? 'ASC' : 'DESC';
114 // reset advanced form
115 if (!is_null(optional_param('resetadv', null, PARAM_RAW))) {
116 $SESSION->dataprefs[$data->id]['search_array'] = array();
117 // we need the redirect to cleanup the form state properly
118 redirect("view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=1");
121 $advanced = optional_param('advanced', -1, PARAM_INT);
122 if ($advanced == -1) {
123 $advanced = $SESSION->dataprefs[$data->id]['advanced'];
124 } else {
125 if (!$advanced) {
126 // explicitly switched to normal mode - discard all advanced search settings
127 $SESSION->dataprefs[$data->id]['search_array'] = array();
129 $SESSION->dataprefs[$data->id]['advanced'] = $advanced;
132 $search_array = $SESSION->dataprefs[$data->id]['search_array'];
134 if (!empty($advanced)) {
135 $search = '';
136 $vals = array();
137 $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
139 //Added to ammend paging error. This error would occur when attempting to go from one page of advanced
140 //search results to another. All fields were reset in the page transfer, and there was no way of determining
141 //whether or not the user reset them. This would cause a blank search to execute whenever the user attempted
142 //to see any page of results past the first.
143 //This fix works as follows:
144 //$paging flag is set to false when page 0 of the advanced search results is viewed for the first time.
145 //Viewing any page of results after page 0 passes the false $paging flag though the URL (see line 523) and the
146 //execution falls through to the second condition below, allowing paging to be set to true.
147 //Paging remains true and keeps getting passed though the URL until a new search is performed
148 //(even if page 0 is revisited).
149 //A false $paging flag generates advanced search results based on the fields input by the user.
150 //A true $paging flag generates davanced search results from the $SESSION global.
152 $paging = optional_param('paging', NULL, PARAM_BOOL);
153 if($page == 0 && !isset($paging)) {
154 $paging = false;
156 else {
157 $paging = true;
159 if (!empty($fields)) {
160 foreach($fields as $field) {
161 $searchfield = data_get_field_from_id($field->id, $data);
162 //Get field data to build search sql with. If paging is false, get from user.
163 //If paging is true, get data from $search_array which is obtained from the $SESSION (see line 116).
164 if(!$paging) {
165 $val = $searchfield->parse_search_field();
166 } else {
167 //Set value from session if there is a value @ the required index.
168 if (isset($search_array[$field->id])) {
169 $val = $search_array[$field->id]->data;
170 } else { //If there is not an entry @ the required index, set value to blank.
171 $val = '';
174 if (!empty($val)) {
175 $search_array[$field->id] = new stdClass();
176 list($search_array[$field->id]->sql, $search_array[$field->id]->params) = $searchfield->generate_sql('c'.$field->id, $val);
177 $search_array[$field->id]->data = $val;
178 $vals[] = $val;
179 } else {
180 // clear it out
181 unset($search_array[$field->id]);
186 if (!$paging) {
187 // name searching
188 $fn = optional_param('u_fn', '', PARAM_NOTAGS);
189 $ln = optional_param('u_ln', '', PARAM_NOTAGS);
190 } else {
191 $fn = isset($search_array[DATA_FIRSTNAME]) ? $search_array[DATA_FIRSTNAME]->data : '';
192 $ln = isset($search_array[DATA_LASTNAME]) ? $search_array[DATA_LASTNAME]->data : '';
194 if (!empty($fn)) {
195 $search_array[DATA_FIRSTNAME] = new stdClass();
196 $search_array[DATA_FIRSTNAME]->sql = '';
197 $search_array[DATA_FIRSTNAME]->params = array();
198 $search_array[DATA_FIRSTNAME]->field = 'u.firstname';
199 $search_array[DATA_FIRSTNAME]->data = $fn;
200 $vals[] = $fn;
201 } else {
202 unset($search_array[DATA_FIRSTNAME]);
204 if (!empty($ln)) {
205 $search_array[DATA_LASTNAME] = new stdClass();
206 $search_array[DATA_LASTNAME]->sql = '';
207 $search_array[DATA_LASTNAME]->params = array();
208 $search_array[DATA_LASTNAME]->field = 'u.lastname';
209 $search_array[DATA_LASTNAME]->data = $ln;
210 $vals[] = $ln;
211 } else {
212 unset($search_array[DATA_LASTNAME]);
215 $SESSION->dataprefs[$data->id]['search_array'] = $search_array; // Make it sticky
217 // in case we want to switch to simple search later - there might be multiple values there ;-)
218 if ($vals) {
219 $val = reset($vals);
220 if (is_string($val)) {
221 $search = $val;
225 } else {
226 $search = optional_param('search', $SESSION->dataprefs[$data->id]['search'], PARAM_NOTAGS);
227 //Paging variable not used for standard search. Set it to null.
228 $paging = NULL;
231 // Disable search filters if $filter is not true:
232 if (! $filter) {
233 $search = '';
236 if (core_text::strlen($search) < 2) {
237 $search = '';
239 $SESSION->dataprefs[$data->id]['search'] = $search; // Make it sticky
241 $sort = optional_param('sort', $SESSION->dataprefs[$data->id]['sort'], PARAM_INT);
242 $SESSION->dataprefs[$data->id]['sort'] = $sort; // Make it sticky
244 $order = (optional_param('order', $SESSION->dataprefs[$data->id]['order'], PARAM_ALPHA) == 'ASC') ? 'ASC': 'DESC';
245 $SESSION->dataprefs[$data->id]['order'] = $order; // Make it sticky
248 $oldperpage = get_user_preferences('data_perpage_'.$data->id, 10);
249 $perpage = optional_param('perpage', $oldperpage, PARAM_INT);
251 if ($perpage < 2) {
252 $perpage = 2;
254 if ($perpage != $oldperpage) {
255 set_user_preference('data_perpage_'.$data->id, $perpage);
258 $params = array(
259 'context' => $context,
260 'objectid' => $data->id
262 $event = \mod_data\event\course_module_viewed::create($params);
263 $event->add_record_snapshot('course_modules', $cm);
264 $event->add_record_snapshot('course', $course);
265 $event->add_record_snapshot('data', $data);
266 $event->trigger();
268 $urlparams = array('d' => $data->id);
269 if ($record) {
270 $urlparams['rid'] = $record->id;
272 if ($page) {
273 $urlparams['page'] = $page;
275 if ($mode) {
276 $urlparams['mode'] = $mode;
278 if ($filter) {
279 $urlparams['filter'] = $filter;
281 // Initialize $PAGE, compute blocks
282 $PAGE->set_url('/mod/data/view.php', $urlparams);
284 if (($edit != -1) and $PAGE->user_allowed_editing()) {
285 $USER->editing = $edit;
288 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
290 /// RSS and CSS and JS meta
291 $meta = '';
292 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
293 $rsstitle = $courseshortname . ': ' . format_string($data->name);
294 rss_add_http_header($context, 'mod_data', $data, $rsstitle);
296 if ($data->csstemplate) {
297 $PAGE->requires->css('/mod/data/css.php?d='.$data->id);
299 if ($data->jstemplate) {
300 $PAGE->requires->js('/mod/data/js.php?d='.$data->id, true);
303 // Mark as viewed
304 $completion = new completion_info($course);
305 $completion->set_module_viewed($cm);
307 /// Print the page header
308 // Note: MDL-19010 there will be further changes to printing header and blocks.
309 // The code will be much nicer than this eventually.
310 $title = $courseshortname.': ' . format_string($data->name);
312 if ($PAGE->user_allowed_editing()) {
313 // Change URL parameter and block display string value depending on whether editing is enabled or not
314 if ($PAGE->user_is_editing()) {
315 $urlediting = 'off';
316 $strediting = get_string('blockseditoff');
317 } else {
318 $urlediting = 'on';
319 $strediting = get_string('blocksediton');
321 $url = new moodle_url($CFG->wwwroot.'/mod/data/view.php', array('id' => $cm->id, 'edit' => $urlediting));
322 $PAGE->set_button($OUTPUT->single_button($url, $strediting));
325 if ($mode == 'asearch') {
326 $PAGE->navbar->add(get_string('search'));
329 $PAGE->set_title($title);
330 $PAGE->set_heading($course->fullname);
332 echo $OUTPUT->header();
334 // Check to see if groups are being used here.
335 // We need the most up to date current group value. Make sure it is updated at this point.
336 $currentgroup = groups_get_activity_group($cm, true);
337 $groupmode = groups_get_activity_groupmode($cm);
338 $canmanageentries = has_capability('mod/data:manageentries', $context);
339 // If a student is not part of a group and seperate groups is enabled, we don't
340 // want them seeing all records.
341 if ($currentgroup == 0 && $groupmode == 1 && !$canmanageentries) {
342 $canviewallrecords = false;
343 } else {
344 $canviewallrecords = true;
347 // detect entries not approved yet and show hint instead of not found error
348 if ($record and $data->approval and !$record->approved and $record->userid != $USER->id and !$canmanageentries) {
349 if (!$currentgroup or $record->groupid == $currentgroup or $record->groupid == 0) {
350 print_error('notapproved', 'data');
354 echo $OUTPUT->heading(format_string($data->name), 2);
356 // Do we need to show a link to the RSS feed for the records?
357 //this links has been Settings (database activity administration) block
358 /*if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
359 echo '<div style="float:right;">';
360 rss_print_link($context->id, $USER->id, 'mod_data', $data->id, get_string('rsstype'));
361 echo '</div>';
362 echo '<div style="clear:both;"></div>';
365 if ($data->intro and empty($page) and empty($record) and $mode != 'single') {
366 $options = new stdClass();
367 $options->noclean = true;
369 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
371 $returnurl = $CFG->wwwroot . '/mod/data/view.php?d='.$data->id.'&amp;search='.s($search).'&amp;sort='.s($sort).'&amp;order='.s($order).'&amp;';
372 groups_print_activity_menu($cm, $returnurl);
374 /// Delete any requested records
376 if ($delete && confirm_sesskey() && (data_user_can_manage_entry($delete, $data, $context))) {
377 if ($confirm = optional_param('confirm',0,PARAM_INT)) {
378 if (data_delete_record($delete, $data, $course->id, $cm->id)) {
379 echo $OUTPUT->notification(get_string('recorddeleted','data'), 'notifysuccess');
381 } else { // Print a confirmation page
382 $allnamefields = user_picture::fields('u');
383 // Remove the id from the string. This already exists in the sql statement.
384 $allnamefields = str_replace('u.id,', '', $allnamefields);
385 $dbparams = array($delete);
386 if ($deleterecord = $DB->get_record_sql("SELECT dr.*, $allnamefields
387 FROM {data_records} dr
388 JOIN {user} u ON dr.userid = u.id
389 WHERE dr.id = ?", $dbparams, MUST_EXIST)) { // Need to check this is valid.
390 if ($deleterecord->dataid == $data->id) { // Must be from this database
391 $deletebutton = new single_button(new moodle_url('/mod/data/view.php?d='.$data->id.'&delete='.$delete.'&confirm=1'), get_string('delete'), 'post');
392 echo $OUTPUT->confirm(get_string('confirmdeleterecord','data'),
393 $deletebutton, 'view.php?d='.$data->id);
395 $records[] = $deleterecord;
396 echo data_print_template('singletemplate', $records, $data, '', 0, true);
398 echo $OUTPUT->footer();
399 exit;
406 // Multi-delete.
407 if ($serialdelete) {
408 $multidelete = json_decode($serialdelete);
411 if ($multidelete && confirm_sesskey() && $canmanageentries) {
412 if ($confirm = optional_param('confirm', 0, PARAM_INT)) {
413 foreach ($multidelete as $value) {
414 data_delete_record($value, $data, $course->id, $cm->id);
416 } else {
417 $validrecords = array();
418 $recordids = array();
419 foreach ($multidelete as $value) {
420 $allnamefields = user_picture::fields('u');
421 // Remove the id from the string. This already exists in the sql statement.
422 $allnamefields = str_replace('u.id,', '', $allnamefields);
423 $dbparams = array('id' => $value);
424 if ($deleterecord = $DB->get_record_sql("SELECT dr.*, $allnamefields
425 FROM {data_records} dr
426 JOIN {user} u ON dr.userid = u.id
427 WHERE dr.id = ?", $dbparams)) { // Need to check this is valid.
428 if ($deleterecord->dataid == $data->id) { // Must be from this database.
429 $validrecords[] = $deleterecord;
430 $recordids[] = $deleterecord->id;
434 $serialiseddata = json_encode($recordids);
435 $submitactions = array('d' => $data->id, 'sesskey' => sesskey(), 'confirm' => '1', 'serialdelete' => $serialiseddata);
436 $action = new moodle_url('/mod/data/view.php', $submitactions);
437 $cancelurl = new moodle_url('/mod/data/view.php', array('d' => $data->id));
438 $deletebutton = new single_button($action, get_string('delete'));
439 echo $OUTPUT->confirm(get_string('confirmdeleterecords', 'data'), $deletebutton, $cancelurl);
440 echo data_print_template('listtemplate', $validrecords, $data, '', 0, false);
441 echo $OUTPUT->footer();
442 exit;
447 //if data activity closed dont let students in
448 $showactivity = true;
449 if (!$canmanageentries) {
450 $timenow = time();
451 if (!empty($data->timeavailablefrom) && $data->timeavailablefrom > $timenow) {
452 echo $OUTPUT->notification(get_string('notopenyet', 'data', userdate($data->timeavailablefrom)));
453 $showactivity = false;
454 } else if (!empty($data->timeavailableto) && $timenow > $data->timeavailableto) {
455 echo $OUTPUT->notification(get_string('expired', 'data', userdate($data->timeavailableto)));
456 $showactivity = false;
460 if ($showactivity) {
461 // Print the tabs
462 if ($record or $mode == 'single') {
463 $currenttab = 'single';
464 } elseif($mode == 'asearch') {
465 $currenttab = 'asearch';
467 else {
468 $currenttab = 'list';
470 include('tabs.php');
472 if ($mode == 'asearch') {
473 $maxcount = 0;
474 data_print_preference_form($data, $perpage, $search, $sort, $order, $search_array, $advanced, $mode);
476 } else {
477 // Approve or disapprove any requested records
478 $params = array(); // named params array
480 $approvecap = has_capability('mod/data:approve', $context);
482 if (($approve || $disapprove) && confirm_sesskey() && $approvecap) {
483 $newapproved = $approve ? 1 : 0;
484 $recordid = $newapproved ? $approve : $disapprove;
485 if ($approverecord = $DB->get_record('data_records', array('id' => $recordid))) { // Need to check this is valid
486 if ($approverecord->dataid == $data->id) { // Must be from this database
487 $newrecord = new stdClass();
488 $newrecord->id = $approverecord->id;
489 $newrecord->approved = $newapproved;
490 $DB->update_record('data_records', $newrecord);
491 $msgkey = $newapproved ? 'recordapproved' : 'recorddisapproved';
492 echo $OUTPUT->notification(get_string($msgkey, 'data'), 'notifysuccess');
497 $numentries = data_numentries($data);
498 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
499 if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !$canmanageentries) {
500 $data->entriesleft = $data->requiredentries - $numentries;
501 $strentrieslefttoadd = get_string('entrieslefttoadd', 'data', $data);
502 echo $OUTPUT->notification($strentrieslefttoadd);
505 /// 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)
506 $requiredentries_allowed = true;
507 if ($data->requiredentriestoview > 0 && $numentries < $data->requiredentriestoview && !$canmanageentries) {
508 $data->entrieslefttoview = $data->requiredentriestoview - $numentries;
509 $strentrieslefttoaddtoview = get_string('entrieslefttoaddtoview', 'data', $data);
510 echo $OUTPUT->notification($strentrieslefttoaddtoview);
511 $requiredentries_allowed = false;
514 // Initialise the first group of params for advanced searches.
515 $initialparams = array();
517 /// setup group and approve restrictions
518 if (!$approvecap && $data->approval) {
519 if (isloggedin()) {
520 $approveselect = ' AND (r.approved=1 OR r.userid=:myid1) ';
521 $params['myid1'] = $USER->id;
522 $initialparams['myid1'] = $params['myid1'];
523 } else {
524 $approveselect = ' AND r.approved=1 ';
526 } else {
527 $approveselect = ' ';
530 if ($currentgroup) {
531 $groupselect = " AND (r.groupid = :currentgroup OR r.groupid = 0)";
532 $params['currentgroup'] = $currentgroup;
533 $initialparams['currentgroup'] = $params['currentgroup'];
534 } else {
535 if ($canviewallrecords) {
536 $groupselect = ' ';
537 } else {
538 // If separate groups are enabled and the user isn't in a group or
539 // a teacher, manager, admin etc, then just show them entries for 'All participants'.
540 $groupselect = " AND r.groupid = 0";
544 // Init some variables to be used by advanced search
545 $advsearchselect = '';
546 $advwhere = '';
547 $advtables = '';
548 $advparams = array();
549 // This is used for the initial reduction of advanced search results with required entries.
550 $entrysql = '';
551 $namefields = user_picture::fields('u');
552 // Remove the id from the string. This already exists in the sql statement.
553 $namefields = str_replace('u.id,', '', $namefields);
555 /// Find the field we are sorting on
556 if ($sort <= 0 or !$sortfield = data_get_field_from_id($sort, $data)) {
558 switch ($sort) {
559 case DATA_LASTNAME:
560 $ordering = "u.lastname $order, u.firstname $order";
561 break;
562 case DATA_FIRSTNAME:
563 $ordering = "u.firstname $order, u.lastname $order";
564 break;
565 case DATA_APPROVED:
566 $ordering = "r.approved $order, r.timecreated $order";
567 break;
568 case DATA_TIMEMODIFIED:
569 $ordering = "r.timemodified $order";
570 break;
571 case DATA_TIMEADDED:
572 default:
573 $sort = 0;
574 $ordering = "r.timecreated $order";
577 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields;
578 $count = ' COUNT(DISTINCT c.recordid) ';
579 $tables = '{data_content} c,{data_records} r, {user} u ';
580 $where = 'WHERE c.recordid = r.id
581 AND r.dataid = :dataid
582 AND r.userid = u.id ';
583 $params['dataid'] = $data->id;
584 $sortorder = " ORDER BY $ordering, r.id $order";
585 $searchselect = '';
587 // If requiredentries is not reached, only show current user's entries
588 if (!$requiredentries_allowed) {
589 $where .= ' AND u.id = :myid2 ';
590 $entrysql = ' AND r.userid = :myid3 ';
591 $params['myid2'] = $USER->id;
592 $initialparams['myid3'] = $params['myid2'];
595 if (!empty($advanced)) { //If advanced box is checked.
596 $i = 0;
597 foreach($search_array as $key => $val) { //what does $search_array hold?
598 if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
599 $i++;
600 $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
601 $params['search_flname_'.$i] = "%$val->data%";
602 continue;
604 $advtables .= ', {data_content} c'.$key.' ';
605 $advwhere .= ' AND c'.$key.'.recordid = r.id';
606 $advsearchselect .= ' AND ('.$val->sql.') ';
607 $advparams = array_merge($advparams, $val->params);
609 } else if ($search) {
610 $searchselect = " AND (".$DB->sql_like('c.content', ':search1', false)."
611 OR ".$DB->sql_like('u.firstname', ':search2', false)."
612 OR ".$DB->sql_like('u.lastname', ':search3', false)." ) ";
613 $params['search1'] = "%$search%";
614 $params['search2'] = "%$search%";
615 $params['search3'] = "%$search%";
616 } else {
617 $searchselect = ' ';
620 } else {
622 $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
623 $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
625 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ',
626 ' . $sortcontentfull . ' AS sortorder ';
627 $count = ' COUNT(DISTINCT c.recordid) ';
628 $tables = '{data_content} c, {data_records} r, {user} u ';
629 $where = 'WHERE c.recordid = r.id
630 AND r.dataid = :dataid
631 AND r.userid = u.id ';
632 if (!$advanced) {
633 $where .= 'AND c.fieldid = :sort';
635 $params['dataid'] = $data->id;
636 $params['sort'] = $sort;
637 $sortorder = ' ORDER BY sortorder '.$order.' , r.id ASC ';
638 $searchselect = '';
640 // If requiredentries is not reached, only show current user's entries
641 if (!$requiredentries_allowed) {
642 $where .= ' AND u.id = :myid2';
643 $entrysql = ' AND r.userid = :myid3';
644 $params['myid2'] = $USER->id;
645 $initialparams['myid3'] = $params['myid2'];
647 $i = 0;
648 if (!empty($advanced)) { //If advanced box is checked.
649 foreach($search_array as $key => $val) { //what does $search_array hold?
650 if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
651 $i++;
652 $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
653 $params['search_flname_'.$i] = "%$val->data%";
654 continue;
656 $advtables .= ', {data_content} c'.$key.' ';
657 $advwhere .= ' AND c'.$key.'.recordid = r.id AND c'.$key.'.fieldid = '.$key;
658 $advsearchselect .= ' AND ('.$val->sql.') ';
659 $advparams = array_merge($advparams, $val->params);
661 } else if ($search) {
662 $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)." ) ";
663 $params['search1'] = "%$search%";
664 $params['search2'] = "%$search%";
665 $params['search3'] = "%$search%";
666 } else {
667 $searchselect = ' ';
671 /// To actually fetch the records
673 $fromsql = "FROM $tables $advtables $where $advwhere $groupselect $approveselect $searchselect $advsearchselect";
674 $allparams = array_merge($params, $advparams);
676 // Provide initial sql statements and parameters to reduce the number of total records.
677 $initialselect = $groupselect . $approveselect . $entrysql;
679 $recordids = data_get_all_recordids($data->id, $initialselect, $initialparams);
680 $newrecordids = data_get_advance_search_ids($recordids, $search_array, $data->id);
681 $totalcount = count($newrecordids);
682 $selectdata = $where . $groupselect . $approveselect;
684 if (!empty($advanced)) {
685 $advancedsearchsql = data_get_advanced_search_sql($sort, $data, $newrecordids, $selectdata, $sortorder);
686 $sqlselect = $advancedsearchsql['sql'];
687 $allparams = array_merge($allparams, $advancedsearchsql['params']);
688 } else {
689 $sqlselect = "SELECT $what $fromsql $sortorder";
692 /// Work out the paging numbers and counts
693 if (empty($searchselect) && empty($advsearchselect)) {
694 $maxcount = $totalcount;
695 } else {
696 $maxcount = count($recordids);
699 if ($record) { // We need to just show one, so where is it in context?
700 $nowperpage = 1;
701 $mode = 'single';
702 $page = 0;
703 // TODO MDL-33797 - Reduce this or consider redesigning the paging system.
704 if ($allrecordids = $DB->get_fieldset_sql($sqlselect, $allparams)) {
705 $page = (int)array_search($record->id, $allrecordids);
706 unset($allrecordids);
708 } else if ($mode == 'single') { // We rely on ambient $page settings
709 $nowperpage = 1;
711 } else {
712 $nowperpage = $perpage;
715 // Advanced search form doesn't make sense for single (redirects list view).
716 if ($maxcount && $mode != 'single') {
717 data_print_preference_form($data, $perpage, $search, $sort, $order, $search_array, $advanced, $mode);
720 /// Get the actual records
722 if (!$records = $DB->get_records_sql($sqlselect, $allparams, $page * $nowperpage, $nowperpage)) {
723 // Nothing to show!
724 if ($record) { // Something was requested so try to show that at least (bug 5132)
725 if ($canmanageentries || empty($data->approval) ||
726 $record->approved || (isloggedin() && $record->userid == $USER->id)) {
727 if (!$currentgroup || $record->groupid == $currentgroup || $record->groupid == 0) {
728 // OK, we can show this one
729 $records = array($record->id => $record);
730 $totalcount = 1;
736 if (empty($records)) {
737 if ($maxcount){
738 $a = new stdClass();
739 $a->max = $maxcount;
740 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
741 echo $OUTPUT->notification(get_string('foundnorecords','data', $a));
742 } else {
743 echo $OUTPUT->notification(get_string('norecords','data'));
746 } else {
747 // We have some records to print.
748 $url = new moodle_url('/mod/data/view.php', array('d' => $data->id, 'sesskey' => sesskey()));
749 echo html_writer::start_tag('form', array('action' => $url, 'method' => 'post'));
751 if ($maxcount != $totalcount) {
752 $a = new stdClass();
753 $a->num = $totalcount;
754 $a->max = $maxcount;
755 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
756 echo $OUTPUT->notification(get_string('foundrecords', 'data', $a), 'notifysuccess');
759 if ($mode == 'single') { // Single template
760 $baseurl = 'view.php?d=' . $data->id . '&mode=single&';
761 if (!empty($search)) {
762 $baseurl .= 'filter=1&';
764 if (!empty($page)) {
765 $baseurl .= 'page=' . $page;
767 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
769 if (empty($data->singletemplate)){
770 echo $OUTPUT->notification(get_string('nosingletemplate','data'));
771 data_generate_default_template($data, 'singletemplate', 0, false, false);
774 //data_print_template() only adds ratings for singletemplate which is why we're attaching them here
775 //attach ratings to data records
776 require_once($CFG->dirroot.'/rating/lib.php');
777 if ($data->assessed != RATING_AGGREGATE_NONE) {
778 $ratingoptions = new stdClass;
779 $ratingoptions->context = $context;
780 $ratingoptions->component = 'mod_data';
781 $ratingoptions->ratingarea = 'entry';
782 $ratingoptions->items = $records;
783 $ratingoptions->aggregate = $data->assessed;//the aggregation method
784 $ratingoptions->scaleid = $data->scale;
785 $ratingoptions->userid = $USER->id;
786 $ratingoptions->returnurl = $CFG->wwwroot.'/mod/data/'.$baseurl;
787 $ratingoptions->assesstimestart = $data->assesstimestart;
788 $ratingoptions->assesstimefinish = $data->assesstimefinish;
790 $rm = new rating_manager();
791 $records = $rm->get_ratings($ratingoptions);
794 data_print_template('singletemplate', $records, $data, $search, $page, false, new moodle_url($baseurl));
796 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
798 } else { // List template
799 $baseurl = 'view.php?d='.$data->id.'&amp;';
800 //send the advanced flag through the URL so it is remembered while paging.
801 $baseurl .= 'advanced='.$advanced.'&amp;';
802 if (!empty($search)) {
803 $baseurl .= 'filter=1&amp;';
805 //pass variable to allow determining whether or not we are paging through results.
806 $baseurl .= 'paging='.$paging.'&amp;';
808 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
810 if (empty($data->listtemplate)){
811 echo $OUTPUT->notification(get_string('nolisttemplate','data'));
812 data_generate_default_template($data, 'listtemplate', 0, false, false);
814 echo $data->listtemplateheader;
815 data_print_template('listtemplate', $records, $data, $search, $page, false, new moodle_url($baseurl));
816 echo $data->listtemplatefooter;
818 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
821 if ($mode != 'single' && $canmanageentries) {
822 echo html_writer::empty_tag('input', array(
823 'type' => 'button',
824 'id' => 'checkall',
825 'value' => get_string('selectall'),
827 echo html_writer::empty_tag('input', array(
828 'type' => 'button',
829 'id' => 'checknone',
830 'value' => get_string('deselectall'),
832 echo html_writer::empty_tag('input', array(
833 'class' => 'form-submit',
834 'type' => 'submit',
835 'value' => get_string('deleteselected'),
838 $module = array('name' => 'mod_data', 'fullpath' => '/mod/data/module.js');
839 $PAGE->requires->js_init_call('M.mod_data.init_view', null, false, $module);
842 echo html_writer::end_tag('form');
846 $search = trim($search);
847 if (empty($records)) {
848 $records = array();
851 // Check to see if we can export records to a portfolio. This is for exporting all records, not just the ones in the search.
852 if ($mode == '' && !empty($CFG->enableportfolios) && !empty($records)) {
853 $canexport = false;
854 // Exportallentries and exportentry are basically the same capability.
855 if (has_capability('mod/data:exportallentries', $context) || has_capability('mod/data:exportentry', $context)) {
856 $canexport = true;
857 } else if (has_capability('mod/data:exportownentry', $context) &&
858 $DB->record_exists('data_records', array('userid' => $USER->id))) {
859 $canexport = true;
861 if ($canexport) {
862 require_once($CFG->libdir . '/portfoliolib.php');
863 $button = new portfolio_add_button();
864 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id), 'mod_data');
865 if (data_portfolio_caller::has_files($data)) {
866 $button->set_formats(array(PORTFOLIO_FORMAT_RICHHTML, PORTFOLIO_FORMAT_LEAP2A)); // No plain html for us.
868 echo $button->to_html(PORTFOLIO_ADD_FULL_FORM);
873 echo $OUTPUT->footer();