Merge branch 'MDL-44822' of git://github.com/aolley/moodle
[moodle.git] / mod / data / view.php
blob1d53a5b2ec23d7439633f4d6da13047daea56a2b
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(dirname(__FILE__) . '/../../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 $currentgroup = groups_get_activity_group($cm);
336 $groupmode = groups_get_activity_groupmode($cm);
337 $canmanageentries = has_capability('mod/data:manageentries', $context);
338 // If a student is not part of a group and seperate groups is enabled, we don't
339 // want them seeing all records.
340 if ($currentgroup == 0 && $groupmode == 1 && !$canmanageentries) {
341 $canviewallrecords = false;
342 } else {
343 $canviewallrecords = true;
346 // detect entries not approved yet and show hint instead of not found error
347 if ($record and $data->approval and !$record->approved and $record->userid != $USER->id and !$canmanageentries) {
348 if (!$currentgroup or $record->groupid == $currentgroup or $record->groupid == 0) {
349 print_error('notapproved', 'data');
353 echo $OUTPUT->heading(format_string($data->name), 2);
355 // Do we need to show a link to the RSS feed for the records?
356 //this links has been Settings (database activity administration) block
357 /*if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
358 echo '<div style="float:right;">';
359 rss_print_link($context->id, $USER->id, 'mod_data', $data->id, get_string('rsstype'));
360 echo '</div>';
361 echo '<div style="clear:both;"></div>';
364 if ($data->intro and empty($page) and empty($record) and $mode != 'single') {
365 $options = new stdClass();
366 $options->noclean = true;
368 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
370 $returnurl = $CFG->wwwroot . '/mod/data/view.php?d='.$data->id.'&amp;search='.s($search).'&amp;sort='.s($sort).'&amp;order='.s($order).'&amp;';
371 groups_print_activity_menu($cm, $returnurl);
373 /// Delete any requested records
375 if ($delete && confirm_sesskey() && ($canmanageentries or data_isowner($delete))) {
376 if ($confirm = optional_param('confirm',0,PARAM_INT)) {
377 if (data_delete_record($delete, $data, $course->id, $cm->id)) {
378 echo $OUTPUT->notification(get_string('recorddeleted','data'), 'notifysuccess');
380 } else { // Print a confirmation page
381 $allnamefields = get_all_user_name_fields(true, 'u');
382 $dbparams = array($delete);
383 if ($deleterecord = $DB->get_record_sql("SELECT dr.*, $allnamefields
384 FROM {data_records} dr
385 JOIN {user} u ON dr.userid = u.id
386 WHERE dr.id = ?", $dbparams, MUST_EXIST)) { // Need to check this is valid.
387 if ($deleterecord->dataid == $data->id) { // Must be from this database
388 $deletebutton = new single_button(new moodle_url('/mod/data/view.php?d='.$data->id.'&delete='.$delete.'&confirm=1'), get_string('delete'), 'post');
389 echo $OUTPUT->confirm(get_string('confirmdeleterecord','data'),
390 $deletebutton, 'view.php?d='.$data->id);
392 $records[] = $deleterecord;
393 echo data_print_template('singletemplate', $records, $data, '', 0, true);
395 echo $OUTPUT->footer();
396 exit;
403 // Multi-delete.
404 if ($serialdelete) {
405 $multidelete = json_decode($serialdelete);
408 if ($multidelete && confirm_sesskey() && $canmanageentries) {
409 if ($confirm = optional_param('confirm', 0, PARAM_INT)) {
410 foreach ($multidelete as $value) {
411 data_delete_record($value, $data, $course->id, $cm->id);
413 } else {
414 $validrecords = array();
415 $recordids = array();
416 foreach ($multidelete as $value) {
417 if ($deleterecord = $DB->get_record('data_records', array('id'=>$value))) { // Need to check this is valid
418 if ($deleterecord->dataid == $data->id) { // Must be from this database
419 $validrecords[] = $deleterecord;
420 $recordids[] = $deleterecord->id;
425 $serialiseddata = json_encode($recordids);
426 $submitactions = array('d' => $data->id, 'sesskey' => sesskey(), 'confirm' => '1', 'serialdelete' => $serialiseddata);
427 $action = new moodle_url('/mod/data/view.php', $submitactions);
428 $cancelurl = new moodle_url('/mod/data/view.php', array('d' => $data->id));
429 $deletebutton = new single_button($action, get_string('delete'));
430 echo $OUTPUT->confirm(get_string('confirmdeleterecords', 'data'), $deletebutton, $cancelurl);
431 echo data_print_template('listtemplate', $validrecords, $data, '', 0, false);
432 echo $OUTPUT->footer();
433 exit;
438 //if data activity closed dont let students in
439 $showactivity = true;
440 if (!$canmanageentries) {
441 $timenow = time();
442 if (!empty($data->timeavailablefrom) && $data->timeavailablefrom > $timenow) {
443 echo $OUTPUT->notification(get_string('notopenyet', 'data', userdate($data->timeavailablefrom)));
444 $showactivity = false;
445 } else if (!empty($data->timeavailableto) && $timenow > $data->timeavailableto) {
446 echo $OUTPUT->notification(get_string('expired', 'data', userdate($data->timeavailableto)));
447 $showactivity = false;
451 if ($showactivity) {
452 // Print the tabs
453 if ($record or $mode == 'single') {
454 $currenttab = 'single';
455 } elseif($mode == 'asearch') {
456 $currenttab = 'asearch';
458 else {
459 $currenttab = 'list';
461 include('tabs.php');
463 $url = new moodle_url('/mod/data/view.php', array('d' => $data->id, 'sesskey' => sesskey()));
464 echo html_writer::start_tag('form', array('action' => $url, 'method' => 'post'));
466 if ($mode == 'asearch') {
467 $maxcount = 0;
469 } else {
470 // Approve or disapprove any requested records
471 $params = array(); // named params array
473 $approvecap = has_capability('mod/data:approve', $context);
475 if (($approve || $disapprove) && confirm_sesskey() && $approvecap) {
476 $newapproved = $approve ? 1 : 0;
477 $recordid = $newapproved ? $approve : $disapprove;
478 if ($approverecord = $DB->get_record('data_records', array('id' => $recordid))) { // Need to check this is valid
479 if ($approverecord->dataid == $data->id) { // Must be from this database
480 $newrecord = new stdClass();
481 $newrecord->id = $approverecord->id;
482 $newrecord->approved = $newapproved;
483 $DB->update_record('data_records', $newrecord);
484 $msgkey = $newapproved ? 'recordapproved' : 'recorddisapproved';
485 echo $OUTPUT->notification(get_string($msgkey, 'data'), 'notifysuccess');
490 $numentries = data_numentries($data);
491 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
492 if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !$canmanageentries) {
493 $data->entriesleft = $data->requiredentries - $numentries;
494 $strentrieslefttoadd = get_string('entrieslefttoadd', 'data', $data);
495 echo $OUTPUT->notification($strentrieslefttoadd);
498 /// 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)
499 $requiredentries_allowed = true;
500 if ($data->requiredentriestoview > 0 && $numentries < $data->requiredentriestoview && !$canmanageentries) {
501 $data->entrieslefttoview = $data->requiredentriestoview - $numentries;
502 $strentrieslefttoaddtoview = get_string('entrieslefttoaddtoview', 'data', $data);
503 echo $OUTPUT->notification($strentrieslefttoaddtoview);
504 $requiredentries_allowed = false;
507 // Initialise the first group of params for advanced searches.
508 $initialparams = array();
510 /// setup group and approve restrictions
511 if (!$approvecap && $data->approval) {
512 if (isloggedin()) {
513 $approveselect = ' AND (r.approved=1 OR r.userid=:myid1) ';
514 $params['myid1'] = $USER->id;
515 $initialparams['myid1'] = $params['myid1'];
516 } else {
517 $approveselect = ' AND r.approved=1 ';
519 } else {
520 $approveselect = ' ';
523 if ($currentgroup) {
524 $groupselect = " AND (r.groupid = :currentgroup OR r.groupid = 0)";
525 $params['currentgroup'] = $currentgroup;
526 $initialparams['currentgroup'] = $params['currentgroup'];
527 } else {
528 if ($canviewallrecords) {
529 $groupselect = ' ';
530 } else {
531 // If separate groups are enabled and the user isn't in a group or
532 // a teacher, manager, admin etc, then just show them entries for 'All participants'.
533 $groupselect = " AND r.groupid = 0";
537 // Init some variables to be used by advanced search
538 $advsearchselect = '';
539 $advwhere = '';
540 $advtables = '';
541 $advparams = array();
542 // This is used for the initial reduction of advanced search results with required entries.
543 $entrysql = '';
544 $namefields = get_all_user_name_fields(true, 'u');
546 /// Find the field we are sorting on
547 if ($sort <= 0 or !$sortfield = data_get_field_from_id($sort, $data)) {
549 switch ($sort) {
550 case DATA_LASTNAME:
551 $ordering = "u.lastname $order, u.firstname $order";
552 break;
553 case DATA_FIRSTNAME:
554 $ordering = "u.firstname $order, u.lastname $order";
555 break;
556 case DATA_APPROVED:
557 $ordering = "r.approved $order, r.timecreated $order";
558 break;
559 case DATA_TIMEMODIFIED:
560 $ordering = "r.timemodified $order";
561 break;
562 case DATA_TIMEADDED:
563 default:
564 $sort = 0;
565 $ordering = "r.timecreated $order";
568 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields;
569 $count = ' COUNT(DISTINCT c.recordid) ';
570 $tables = '{data_content} c,{data_records} r, {user} u ';
571 $where = 'WHERE c.recordid = r.id
572 AND r.dataid = :dataid
573 AND r.userid = u.id ';
574 $params['dataid'] = $data->id;
575 $sortorder = ' ORDER BY '.$ordering.', r.id ASC ';
576 $searchselect = '';
578 // If requiredentries is not reached, only show current user's entries
579 if (!$requiredentries_allowed) {
580 $where .= ' AND u.id = :myid2 ';
581 $entrysql = ' AND r.userid = :myid3 ';
582 $params['myid2'] = $USER->id;
583 $initialparams['myid3'] = $params['myid2'];
586 if (!empty($advanced)) { //If advanced box is checked.
587 $i = 0;
588 foreach($search_array as $key => $val) { //what does $search_array hold?
589 if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
590 $i++;
591 $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
592 $params['search_flname_'.$i] = "%$val->data%";
593 continue;
595 $advtables .= ', {data_content} c'.$key.' ';
596 $advwhere .= ' AND c'.$key.'.recordid = r.id';
597 $advsearchselect .= ' AND ('.$val->sql.') ';
598 $advparams = array_merge($advparams, $val->params);
600 } else if ($search) {
601 $searchselect = " AND (".$DB->sql_like('c.content', ':search1', false)."
602 OR ".$DB->sql_like('u.firstname', ':search2', false)."
603 OR ".$DB->sql_like('u.lastname', ':search3', false)." ) ";
604 $params['search1'] = "%$search%";
605 $params['search2'] = "%$search%";
606 $params['search3'] = "%$search%";
607 } else {
608 $searchselect = ' ';
611 } else {
613 $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
614 $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
616 $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ',
617 ' . $sortcontentfull . ' AS sortorder ';
618 $count = ' COUNT(DISTINCT c.recordid) ';
619 $tables = '{data_content} c, {data_records} r, {user} u ';
620 $where = 'WHERE c.recordid = r.id
621 AND r.dataid = :dataid
622 AND r.userid = u.id ';
623 if (!$advanced) {
624 $where .= 'AND c.fieldid = :sort';
626 $params['dataid'] = $data->id;
627 $params['sort'] = $sort;
628 $sortorder = ' ORDER BY sortorder '.$order.' , r.id ASC ';
629 $searchselect = '';
631 // If requiredentries is not reached, only show current user's entries
632 if (!$requiredentries_allowed) {
633 $where .= ' AND u.id = :myid2';
634 $entrysql = ' AND r.userid = :myid3';
635 $params['myid2'] = $USER->id;
636 $initialparams['myid3'] = $params['myid2'];
638 $i = 0;
639 if (!empty($advanced)) { //If advanced box is checked.
640 foreach($search_array as $key => $val) { //what does $search_array hold?
641 if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
642 $i++;
643 $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
644 $params['search_flname_'.$i] = "%$val->data%";
645 continue;
647 $advtables .= ', {data_content} c'.$key.' ';
648 $advwhere .= ' AND c'.$key.'.recordid = r.id AND c'.$key.'.fieldid = '.$key;
649 $advsearchselect .= ' AND ('.$val->sql.') ';
650 $advparams = array_merge($advparams, $val->params);
652 } else if ($search) {
653 $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)." ) ";
654 $params['search1'] = "%$search%";
655 $params['search2'] = "%$search%";
656 $params['search3'] = "%$search%";
657 } else {
658 $searchselect = ' ';
662 /// To actually fetch the records
664 $fromsql = "FROM $tables $advtables $where $advwhere $groupselect $approveselect $searchselect $advsearchselect";
665 $allparams = array_merge($params, $advparams);
667 // Provide initial sql statements and parameters to reduce the number of total records.
668 $initialselect = $groupselect . $approveselect . $entrysql;
670 $recordids = data_get_all_recordids($data->id, $initialselect, $initialparams);
671 $newrecordids = data_get_advance_search_ids($recordids, $search_array, $data->id);
672 $totalcount = count($newrecordids);
673 $selectdata = $where . $groupselect . $approveselect;
675 if (!empty($advanced)) {
676 $advancedsearchsql = data_get_advanced_search_sql($sort, $data, $newrecordids, $selectdata, $sortorder);
677 $sqlselect = $advancedsearchsql['sql'];
678 $allparams = array_merge($allparams, $advancedsearchsql['params']);
679 } else {
680 $sqlselect = "SELECT $what $fromsql $sortorder";
683 /// Work out the paging numbers and counts
684 if (empty($searchselect) && empty($advsearchselect)) {
685 $maxcount = $totalcount;
686 } else {
687 $maxcount = count($recordids);
690 if ($record) { // We need to just show one, so where is it in context?
691 $nowperpage = 1;
692 $mode = 'single';
693 $page = 0;
694 // TODO MDL-33797 - Reduce this or consider redesigning the paging system.
695 if ($allrecordids = $DB->get_fieldset_sql($sqlselect, $allparams)) {
696 $page = (int)array_search($record->id, $allrecordids);
697 unset($allrecordids);
699 } else if ($mode == 'single') { // We rely on ambient $page settings
700 $nowperpage = 1;
702 } else {
703 $nowperpage = $perpage;
706 /// Get the actual records
708 if (!$records = $DB->get_records_sql($sqlselect, $allparams, $page * $nowperpage, $nowperpage)) {
709 // Nothing to show!
710 if ($record) { // Something was requested so try to show that at least (bug 5132)
711 if ($canmanageentries || empty($data->approval) ||
712 $record->approved || (isloggedin() && $record->userid == $USER->id)) {
713 if (!$currentgroup || $record->groupid == $currentgroup || $record->groupid == 0) {
714 // OK, we can show this one
715 $records = array($record->id => $record);
716 $totalcount = 1;
722 if (empty($records)) {
723 if ($maxcount){
724 $a = new stdClass();
725 $a->max = $maxcount;
726 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
727 echo $OUTPUT->notification(get_string('foundnorecords','data', $a));
728 } else {
729 echo $OUTPUT->notification(get_string('norecords','data'));
732 } else { // We have some records to print
734 if ($maxcount != $totalcount) {
735 $a = new stdClass();
736 $a->num = $totalcount;
737 $a->max = $maxcount;
738 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
739 echo $OUTPUT->notification(get_string('foundrecords', 'data', $a), 'notifysuccess');
742 if ($mode == 'single') { // Single template
743 $baseurl = 'view.php?d=' . $data->id . '&mode=single&';
744 if (!empty($search)) {
745 $baseurl .= 'filter=1&';
747 if (!empty($page)) {
748 $baseurl .= 'page=' . $page;
750 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
752 if (empty($data->singletemplate)){
753 echo $OUTPUT->notification(get_string('nosingletemplate','data'));
754 data_generate_default_template($data, 'singletemplate', 0, false, false);
757 //data_print_template() only adds ratings for singletemplate which is why we're attaching them here
758 //attach ratings to data records
759 require_once($CFG->dirroot.'/rating/lib.php');
760 if ($data->assessed != RATING_AGGREGATE_NONE) {
761 $ratingoptions = new stdClass;
762 $ratingoptions->context = $context;
763 $ratingoptions->component = 'mod_data';
764 $ratingoptions->ratingarea = 'entry';
765 $ratingoptions->items = $records;
766 $ratingoptions->aggregate = $data->assessed;//the aggregation method
767 $ratingoptions->scaleid = $data->scale;
768 $ratingoptions->userid = $USER->id;
769 $ratingoptions->returnurl = $CFG->wwwroot.'/mod/data/'.$baseurl;
770 $ratingoptions->assesstimestart = $data->assesstimestart;
771 $ratingoptions->assesstimefinish = $data->assesstimefinish;
773 $rm = new rating_manager();
774 $records = $rm->get_ratings($ratingoptions);
777 data_print_template('singletemplate', $records, $data, $search, $page);
779 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
781 } else { // List template
782 $baseurl = 'view.php?d='.$data->id.'&amp;';
783 //send the advanced flag through the URL so it is remembered while paging.
784 $baseurl .= 'advanced='.$advanced.'&amp;';
785 if (!empty($search)) {
786 $baseurl .= 'filter=1&amp;';
788 //pass variable to allow determining whether or not we are paging through results.
789 $baseurl .= 'paging='.$paging.'&amp;';
791 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
793 if (empty($data->listtemplate)){
794 echo $OUTPUT->notification(get_string('nolisttemplate','data'));
795 data_generate_default_template($data, 'listtemplate', 0, false, false);
797 echo $data->listtemplateheader;
798 data_print_template('listtemplate', $records, $data, $search, $page);
799 echo $data->listtemplatefooter;
801 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
807 $search = trim($search);
808 if (empty($records)) {
809 $records = array();
812 if ($mode != 'single' && $canmanageentries) {
813 echo html_writer::empty_tag('input', array('type' => 'button', 'id' => 'checkall', 'value' => get_string('selectall')));
814 echo html_writer::empty_tag('input', array('type' => 'button', 'id' => 'checknone', 'value' => get_string('deselectall')));
815 echo html_writer::empty_tag('input', array('class' => 'form-submit', 'type' => 'submit', 'value' => get_string('deleteselected')));
817 $module = array('name'=>'mod_data', 'fullpath'=>'/mod/data/module.js');
818 $PAGE->requires->js_init_call('M.mod_data.init_view', null, false, $module);
820 echo html_writer::end_tag('form');
822 if ($mode == '' && !empty($CFG->enableportfolios) && !empty($records)) {
823 require_once($CFG->libdir . '/portfoliolib.php');
824 $button = new portfolio_add_button();
825 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id), 'mod_data');
826 if (data_portfolio_caller::has_files($data)) {
827 $button->set_formats(array(PORTFOLIO_FORMAT_RICHHTML, PORTFOLIO_FORMAT_LEAP2A)); // no plain html for us
829 echo $button->to_html(PORTFOLIO_ADD_FULL_FORM);
832 //Advanced search form doesn't make sense for single (redirects list view)
833 if (($maxcount || $mode == 'asearch') && $mode != 'single') {
834 data_print_preference_form($data, $perpage, $search, $sort, $order, $search_array, $advanced, $mode);
838 echo $OUTPUT->footer();