Merge branch 'MDL-73996-master-fix' of https://github.com/junpataleta/moodle
[moodle.git] / mod / data / view.php
blob3947545bac6b18a134195d9079537d96c6cf0953
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/locallib.php');
27 require_once($CFG->libdir . '/rsslib.php');
29 /// One of these is necessary!
30 $id = optional_param('id', 0, PARAM_INT); // course module id
31 $d = optional_param('d', 0, PARAM_INT); // database id
32 $rid = optional_param('rid', 0, PARAM_INT); //record id
33 $mode = optional_param('mode', '', PARAM_ALPHA); // Force the browse mode ('single')
34 $filter = optional_param('filter', 0, PARAM_BOOL);
35 // search filter will only be applied when $filter is true
37 $edit = optional_param('edit', -1, PARAM_BOOL);
38 $page = optional_param('page', 0, PARAM_INT);
39 /// These can be added to perform an action on a record
40 $approve = optional_param('approve', 0, PARAM_INT); //approval recordid
41 $disapprove = optional_param('disapprove', 0, PARAM_INT); // disapproval recordid
42 $delete = optional_param('delete', 0, PARAM_INT); //delete recordid
43 $multidelete = optional_param_array('delcheck', null, PARAM_INT);
44 $serialdelete = optional_param('serialdelete', null, PARAM_RAW);
46 if ($id) {
47 if (! $cm = get_coursemodule_from_id('data', $id)) {
48 print_error('invalidcoursemodule');
50 if (! $course = $DB->get_record('course', array('id'=>$cm->course))) {
51 print_error('coursemisconf');
53 if (! $data = $DB->get_record('data', array('id'=>$cm->instance))) {
54 print_error('invalidcoursemodule');
56 $record = NULL;
58 } else if ($rid) {
59 if (! $record = $DB->get_record('data_records', array('id'=>$rid))) {
60 print_error('invalidrecord', 'data');
62 if (! $data = $DB->get_record('data', array('id'=>$record->dataid))) {
63 print_error('invalidid', 'data');
65 if (! $course = $DB->get_record('course', array('id'=>$data->course))) {
66 print_error('coursemisconf');
68 if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
69 print_error('invalidcoursemodule');
71 } else { // We must have $d
72 if (! $data = $DB->get_record('data', array('id'=>$d))) {
73 print_error('invalidid', 'data');
75 if (! $course = $DB->get_record('course', array('id'=>$data->course))) {
76 print_error('coursemisconf');
78 if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
79 print_error('invalidcoursemodule');
81 $record = NULL;
83 $cm = cm_info::create($cm);
84 require_course_login($course, true, $cm);
86 require_once($CFG->dirroot . '/comment/lib.php');
87 comment::init();
89 $context = context_module::instance($cm->id);
90 require_capability('mod/data:viewentry', $context);
92 /// If we have an empty Database then redirect because this page is useless without data
93 if (has_capability('mod/data:managetemplates', $context)) {
94 if (!$DB->record_exists('data_fields', array('dataid'=>$data->id))) { // Brand new database!
95 redirect($CFG->wwwroot.'/mod/data/field.php?d='.$data->id); // Redirect to field entry
100 /// Check further parameters that set browsing preferences
101 if (!isset($SESSION->dataprefs)) {
102 $SESSION->dataprefs = array();
104 if (!isset($SESSION->dataprefs[$data->id])) {
105 $SESSION->dataprefs[$data->id] = array();
106 $SESSION->dataprefs[$data->id]['search'] = '';
107 $SESSION->dataprefs[$data->id]['search_array'] = array();
108 $SESSION->dataprefs[$data->id]['sort'] = $data->defaultsort;
109 $SESSION->dataprefs[$data->id]['advanced'] = 0;
110 $SESSION->dataprefs[$data->id]['order'] = ($data->defaultsortdir == 0) ? 'ASC' : 'DESC';
113 // reset advanced form
114 if (!is_null(optional_param('resetadv', null, PARAM_RAW))) {
115 $SESSION->dataprefs[$data->id]['search_array'] = array();
116 // we need the redirect to cleanup the form state properly
117 redirect("view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=1");
120 $advanced = optional_param('advanced', -1, PARAM_INT);
121 if ($advanced == -1) {
122 $advanced = $SESSION->dataprefs[$data->id]['advanced'];
123 } else {
124 if (!$advanced) {
125 // explicitly switched to normal mode - discard all advanced search settings
126 $SESSION->dataprefs[$data->id]['search_array'] = array();
128 $SESSION->dataprefs[$data->id]['advanced'] = $advanced;
131 $search_array = $SESSION->dataprefs[$data->id]['search_array'];
133 if (!empty($advanced)) {
134 $search = '';
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).
146 //A false $paging flag generates advanced search results based on the fields input by the user.
147 //A true $paging flag generates davanced search results from the $SESSION global.
149 $paging = optional_param('paging', NULL, PARAM_BOOL);
150 if($page == 0 && !isset($paging)) {
151 $paging = false;
153 else {
154 $paging = true;
157 // Now build the advanced search array.
158 list($search_array, $search) = data_build_search_array($data, $paging, $search_array);
159 $SESSION->dataprefs[$data->id]['search_array'] = $search_array; // Make it sticky.
161 } else {
162 $search = optional_param('search', $SESSION->dataprefs[$data->id]['search'], PARAM_NOTAGS);
163 //Paging variable not used for standard search. Set it to null.
164 $paging = NULL;
167 // Disable search filters if $filter is not true:
168 if (! $filter) {
169 $search = '';
172 $SESSION->dataprefs[$data->id]['search'] = $search; // Make it sticky
174 $sort = optional_param('sort', $SESSION->dataprefs[$data->id]['sort'], PARAM_INT);
175 $SESSION->dataprefs[$data->id]['sort'] = $sort; // Make it sticky
177 $order = (optional_param('order', $SESSION->dataprefs[$data->id]['order'], PARAM_ALPHA) == 'ASC') ? 'ASC': 'DESC';
178 $SESSION->dataprefs[$data->id]['order'] = $order; // Make it sticky
181 $oldperpage = get_user_preferences('data_perpage_'.$data->id, 10);
182 $perpage = optional_param('perpage', $oldperpage, PARAM_INT);
184 if ($perpage < 2) {
185 $perpage = 2;
187 if ($perpage != $oldperpage) {
188 set_user_preference('data_perpage_'.$data->id, $perpage);
191 // Completion and trigger events.
192 data_view($data, $course, $cm, $context);
194 $urlparams = array('d' => $data->id);
195 if ($record) {
196 $urlparams['rid'] = $record->id;
198 if ($mode) {
199 $urlparams['mode'] = $mode;
201 if ($page) {
202 $urlparams['page'] = $page;
204 if ($filter) {
205 $urlparams['filter'] = $filter;
207 $pageurl = new moodle_url('/mod/data/view.php', $urlparams);
209 // Initialize $PAGE, compute blocks.
210 $PAGE->set_url($pageurl);
212 if (($edit != -1) and $PAGE->user_allowed_editing()) {
213 $USER->editing = $edit;
216 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
218 /// RSS and CSS and JS meta
219 $meta = '';
220 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
221 $rsstitle = $courseshortname . ': ' . format_string($data->name);
222 rss_add_http_header($context, 'mod_data', $data, $rsstitle);
224 if ($data->csstemplate) {
225 $PAGE->requires->css('/mod/data/css.php?d='.$data->id);
227 if ($data->jstemplate) {
228 $PAGE->requires->js('/mod/data/js.php?d='.$data->id, true);
231 /// Print the page header
232 // Note: MDL-19010 there will be further changes to printing header and blocks.
233 // The code will be much nicer than this eventually.
234 $title = $courseshortname.': ' . format_string($data->name);
236 if ($PAGE->user_allowed_editing() && !$PAGE->theme->haseditswitch) {
237 // Change URL parameter and block display string value depending on whether editing is enabled or not
238 if ($PAGE->user_is_editing()) {
239 $urlediting = 'off';
240 $strediting = get_string('blockseditoff');
241 } else {
242 $urlediting = 'on';
243 $strediting = get_string('blocksediton');
245 $url = new moodle_url($CFG->wwwroot.'/mod/data/view.php', array('id' => $cm->id, 'edit' => $urlediting));
246 $PAGE->set_button($OUTPUT->single_button($url, $strediting));
249 if ($mode == 'asearch') {
250 $PAGE->navbar->add(get_string('search'));
253 $PAGE->set_title($title);
254 $PAGE->set_heading($course->fullname);
255 $PAGE->force_settings_menu(true);
256 if ($delete && confirm_sesskey() && (data_user_can_manage_entry($delete, $data, $context))) {
257 $PAGE->activityheader->disable();
260 // Check to see if groups are being used here.
261 // We need the most up to date current group value. Make sure it is updated at this point.
262 $currentgroup = groups_get_activity_group($cm, true);
263 $groupmode = groups_get_activity_groupmode($cm);
264 $canmanageentries = has_capability('mod/data:manageentries', $context);
265 echo $OUTPUT->header();
267 // Detect entries not approved yet and show hint instead of not found error.
268 if ($record and !data_can_view_record($data, $record, $currentgroup, $canmanageentries)) {
269 print_error('notapproved', 'data');
272 // Do we need to show a link to the RSS feed for the records?
273 //this links has been Settings (database activity administration) block
274 /*if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
275 echo '<div style="float:right;">';
276 rss_print_link($context->id, $USER->id, 'mod_data', $data->id, get_string('rsstype'));
277 echo '</div>';
278 echo '<div style="clear:both;"></div>';
281 if ($data->intro and empty($page) and empty($record) and $mode != 'single') {
282 $options = new stdClass();
283 $options->noclean = true;
286 /// Delete any requested records
288 if ($delete && confirm_sesskey() && (data_user_can_manage_entry($delete, $data, $context))) {
289 if ($confirm = optional_param('confirm',0,PARAM_INT)) {
290 if (data_delete_record($delete, $data, $course->id, $cm->id)) {
291 echo $OUTPUT->notification(get_string('recorddeleted','data'), 'notifysuccess');
293 } else { // Print a confirmation page
294 $userfieldsapi = \core_user\fields::for_userpic()->excluding('id');
295 $allnamefields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
296 $dbparams = array($delete);
297 if ($deleterecord = $DB->get_record_sql("SELECT dr.*, $allnamefields
298 FROM {data_records} dr
299 JOIN {user} u ON dr.userid = u.id
300 WHERE dr.id = ?", $dbparams, MUST_EXIST)) { // Need to check this is valid.
301 if ($deleterecord->dataid == $data->id) { // Must be from this database
302 echo $OUTPUT->heading(get_string('deleteentry', 'mod_data'), 2, 'mb-4');
303 $deletebutton = new single_button(new moodle_url('/mod/data/view.php?d='.$data->id.'&delete='.$delete.'&confirm=1'), get_string('delete'), 'post');
304 echo $OUTPUT->confirm(get_string('confirmdeleterecord','data'),
305 $deletebutton, 'view.php?d='.$data->id);
307 $records[] = $deleterecord;
308 echo data_print_template('singletemplate', $records, $data, '', 0, true);
310 echo $OUTPUT->footer();
311 exit;
318 // Multi-delete.
319 if ($serialdelete) {
320 $multidelete = json_decode($serialdelete);
323 if ($multidelete && confirm_sesskey() && $canmanageentries) {
324 if ($confirm = optional_param('confirm', 0, PARAM_INT)) {
325 foreach ($multidelete as $value) {
326 data_delete_record($value, $data, $course->id, $cm->id);
328 } else {
329 $validrecords = array();
330 $recordids = array();
331 foreach ($multidelete as $value) {
332 $userfieldsapi = \core_user\fields::for_userpic()->excluding('id');
333 $allnamefields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
334 $dbparams = array('id' => $value);
335 if ($deleterecord = $DB->get_record_sql("SELECT dr.*, $allnamefields
336 FROM {data_records} dr
337 JOIN {user} u ON dr.userid = u.id
338 WHERE dr.id = ?", $dbparams)) { // Need to check this is valid.
339 if ($deleterecord->dataid == $data->id) { // Must be from this database.
340 $validrecords[] = $deleterecord;
341 $recordids[] = $deleterecord->id;
345 $serialiseddata = json_encode($recordids);
346 $submitactions = array('d' => $data->id, 'sesskey' => sesskey(), 'confirm' => '1', 'serialdelete' => $serialiseddata);
347 $action = new moodle_url('/mod/data/view.php', $submitactions);
348 $cancelurl = new moodle_url('/mod/data/view.php', array('d' => $data->id));
349 $deletebutton = new single_button($action, get_string('delete'));
350 echo $OUTPUT->confirm(get_string('confirmdeleterecords', 'data'), $deletebutton, $cancelurl);
351 echo data_print_template('listtemplate', $validrecords, $data, '', 0, false);
352 echo $OUTPUT->footer();
353 exit;
357 // If data activity closed dont let students in.
358 // No need to display warnings because activity dates are displayed at the top of the page.
359 list($showactivity, $warnings) = data_get_time_availability_status($data, $canmanageentries);
361 if ($showactivity) {
363 if ($mode == 'asearch') {
364 $maxcount = 0;
365 data_print_preference_form($data, $perpage, $search, $sort, $order, $search_array, $advanced, $mode);
367 } else {
368 // Approve or disapprove any requested records
369 $approvecap = has_capability('mod/data:approve', $context);
371 if (($approve || $disapprove) && confirm_sesskey() && $approvecap) {
372 $newapproved = $approve ? true : false;
373 $recordid = $newapproved ? $approve : $disapprove;
374 if ($approverecord = $DB->get_record('data_records', array('id' => $recordid))) { // Need to check this is valid
375 if ($approverecord->dataid == $data->id) { // Must be from this database
376 data_approve_entry($approverecord->id, $newapproved);
377 $msgkey = $newapproved ? 'recordapproved' : 'recorddisapproved';
378 echo $OUTPUT->notification(get_string($msgkey, 'data'), 'notifysuccess');
383 $numentries = data_numentries($data);
384 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
385 if ($data->entriesleft = data_get_entries_left_to_add($data, $numentries, $canmanageentries)) {
386 $strentrieslefttoadd = get_string('entrieslefttoadd', 'data', $data);
387 echo $OUTPUT->notification($strentrieslefttoadd);
390 /// 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)
391 $requiredentries_allowed = true;
392 if ($data->entrieslefttoview = data_get_entries_left_to_view($data, $numentries, $canmanageentries)) {
393 $strentrieslefttoaddtoview = get_string('entrieslefttoaddtoview', 'data', $data);
394 echo $OUTPUT->notification($strentrieslefttoaddtoview);
395 $requiredentries_allowed = false;
398 // Search for entries.
399 list($records, $maxcount, $totalcount, $page, $nowperpage, $sort, $mode) =
400 data_search_entries($data, $cm, $context, $mode, $currentgroup, $search, $sort, $order, $page, $perpage, $advanced, $search_array, $record);
401 $hasrecords = !empty($records);
403 $actionbar = new \mod_data\output\action_bar($data->id, $pageurl);
404 echo $actionbar->get_view_action_bar($hasrecords);
406 if ($mode === 'single') {
407 echo $OUTPUT->heading(get_string('singleview', 'mod_data'), 2, 'mb-4');
408 } else {
409 echo $OUTPUT->heading(get_string('listview', 'mod_data'), 2, 'mb-4');
412 if ($groupmode) {
413 $returnurl = new moodle_url('/mod/data/view.php', ['d' => $data->id, 'mode' => $mode, 'search' => s($search),
414 'sort' => s($sort), 'order' => s($order)]);
415 echo html_writer::div(groups_print_activity_menu($cm, $returnurl, true), 'mb-3');
418 // Advanced search form doesn't make sense for single (redirects list view).
419 if ($maxcount && $mode != 'single') {
420 data_print_preference_form($data, $perpage, $search, $sort, $order, $search_array, $advanced, $mode);
423 if (empty($records)) {
424 if ($maxcount){
425 $a = new stdClass();
426 $a->max = $maxcount;
427 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
428 echo $OUTPUT->notification(get_string('foundnorecords','data', $a));
429 } else {
430 echo $OUTPUT->notification(get_string('norecords','data'));
433 } else {
434 // We have some records to print.
435 $url = new moodle_url('/mod/data/view.php', array('d' => $data->id, 'sesskey' => sesskey()));
436 echo html_writer::start_tag('form', array('action' => $url, 'method' => 'post'));
438 if ($maxcount != $totalcount) {
439 $a = new stdClass();
440 $a->num = $totalcount;
441 $a->max = $maxcount;
442 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
443 echo $OUTPUT->notification(get_string('foundrecords', 'data', $a), 'notifysuccess');
446 if ($mode == 'single') { // Single template
447 $baseurl = 'view.php?d=' . $data->id . '&mode=single&';
448 if (!empty($search)) {
449 $baseurl .= 'filter=1&';
451 if (!empty($page)) {
452 $baseurl .= 'page=' . $page;
454 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
456 if (empty($data->singletemplate)){
457 echo $OUTPUT->notification(get_string('nosingletemplate','data'));
458 data_generate_default_template($data, 'singletemplate', 0, false, false);
461 //data_print_template() only adds ratings for singletemplate which is why we're attaching them here
462 //attach ratings to data records
463 require_once($CFG->dirroot.'/rating/lib.php');
464 if ($data->assessed != RATING_AGGREGATE_NONE) {
465 $ratingoptions = new stdClass;
466 $ratingoptions->context = $context;
467 $ratingoptions->component = 'mod_data';
468 $ratingoptions->ratingarea = 'entry';
469 $ratingoptions->items = $records;
470 $ratingoptions->aggregate = $data->assessed;//the aggregation method
471 $ratingoptions->scaleid = $data->scale;
472 $ratingoptions->userid = $USER->id;
473 $ratingoptions->returnurl = $CFG->wwwroot.'/mod/data/'.$baseurl;
474 $ratingoptions->assesstimestart = $data->assesstimestart;
475 $ratingoptions->assesstimefinish = $data->assesstimefinish;
477 $rm = new rating_manager();
478 $records = $rm->get_ratings($ratingoptions);
481 data_print_template('singletemplate', $records, $data, $search, $page, false, new moodle_url($baseurl));
483 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
485 } else { // List template
486 $baseurl = 'view.php?d='.$data->id.'&amp;';
487 //send the advanced flag through the URL so it is remembered while paging.
488 $baseurl .= 'advanced='.$advanced.'&amp;';
489 if (!empty($search)) {
490 $baseurl .= 'filter=1&amp;';
492 //pass variable to allow determining whether or not we are paging through results.
493 $baseurl .= 'paging='.$paging.'&amp;';
495 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
497 if (empty($data->listtemplate)){
498 echo $OUTPUT->notification(get_string('nolisttemplate','data'));
499 data_generate_default_template($data, 'listtemplate', 0, false, false);
501 echo $data->listtemplateheader;
502 data_print_template('listtemplate', $records, $data, $search, $page, false, new moodle_url($baseurl));
503 echo $data->listtemplatefooter;
505 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
508 if ($mode != 'single' && $canmanageentries) {
509 // Build the select/deselect all control.
510 $selectallid = 'selectall-listview-entries';
511 $togglegroup = 'listview-entries';
512 $mastercheckbox = new \core\output\checkbox_toggleall($togglegroup, true, [
513 'id' => $selectallid,
514 'name' => $selectallid,
515 'value' => 1,
516 'label' => get_string('selectall'),
517 'classes' => 'btn-secondary mr-1',
518 ], true);
519 echo $OUTPUT->render($mastercheckbox);
521 $deleteselected = html_writer::empty_tag('input', array(
522 'class' => 'btn btn-secondary',
523 'type' => 'submit',
524 'value' => get_string('deleteselected'),
525 'disabled' => true,
526 'data-action' => 'toggle',
527 'data-togglegroup' => $togglegroup,
528 'data-toggle' => 'action',
530 echo $deleteselected;
533 echo html_writer::end_tag('form');
537 $search = trim($search);
538 if (empty($records)) {
539 $records = array();
542 // Check to see if we can export records to a portfolio. This is for exporting all records, not just the ones in the search.
543 if ($mode == '' && !empty($CFG->enableportfolios) && !empty($records)) {
544 $canexport = false;
545 // Exportallentries and exportentry are basically the same capability.
546 if (has_capability('mod/data:exportallentries', $context) || has_capability('mod/data:exportentry', $context)) {
547 $canexport = true;
548 } else if (has_capability('mod/data:exportownentry', $context) &&
549 $DB->record_exists('data_records', array('userid' => $USER->id))) {
550 $canexport = true;
552 if ($canexport) {
553 require_once($CFG->libdir . '/portfoliolib.php');
554 $button = new portfolio_add_button();
555 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id), 'mod_data');
556 if (data_portfolio_caller::has_files($data)) {
557 $button->set_formats(array(PORTFOLIO_FORMAT_RICHHTML, PORTFOLIO_FORMAT_LEAP2A)); // No plain html for us.
559 echo $button->to_html(PORTFOLIO_ADD_FULL_FORM);
564 echo $OUTPUT->footer();