on-demand release 3.8dev+
[moodle.git] / mod / data / view.php
blob5f7800e1cefb1b38f298bbc13b523d2362a803ac
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;
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 ($page) {
199 $urlparams['page'] = $page;
201 if ($mode) {
202 $urlparams['mode'] = $mode;
204 if ($filter) {
205 $urlparams['filter'] = $filter;
207 // Initialize $PAGE, compute blocks
208 $PAGE->set_url('/mod/data/view.php', $urlparams);
210 if (($edit != -1) and $PAGE->user_allowed_editing()) {
211 $USER->editing = $edit;
214 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
216 /// RSS and CSS and JS meta
217 $meta = '';
218 if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
219 $rsstitle = $courseshortname . ': ' . format_string($data->name);
220 rss_add_http_header($context, 'mod_data', $data, $rsstitle);
222 if ($data->csstemplate) {
223 $PAGE->requires->css('/mod/data/css.php?d='.$data->id);
225 if ($data->jstemplate) {
226 $PAGE->requires->js('/mod/data/js.php?d='.$data->id, true);
229 /// Print the page header
230 // Note: MDL-19010 there will be further changes to printing header and blocks.
231 // The code will be much nicer than this eventually.
232 $title = $courseshortname.': ' . format_string($data->name);
234 if ($PAGE->user_allowed_editing()) {
235 // Change URL parameter and block display string value depending on whether editing is enabled or not
236 if ($PAGE->user_is_editing()) {
237 $urlediting = 'off';
238 $strediting = get_string('blockseditoff');
239 } else {
240 $urlediting = 'on';
241 $strediting = get_string('blocksediton');
243 $url = new moodle_url($CFG->wwwroot.'/mod/data/view.php', array('id' => $cm->id, 'edit' => $urlediting));
244 $PAGE->set_button($OUTPUT->single_button($url, $strediting));
247 if ($mode == 'asearch') {
248 $PAGE->navbar->add(get_string('search'));
251 $PAGE->force_settings_menu();
252 $PAGE->set_title($title);
253 $PAGE->set_heading($course->fullname);
255 echo $OUTPUT->header();
257 // Check to see if groups are being used here.
258 // We need the most up to date current group value. Make sure it is updated at this point.
259 $currentgroup = groups_get_activity_group($cm, true);
260 $groupmode = groups_get_activity_groupmode($cm);
261 $canmanageentries = has_capability('mod/data:manageentries', $context);
264 // Detect entries not approved yet and show hint instead of not found error.
265 if ($record and !data_can_view_record($data, $record, $currentgroup, $canmanageentries)) {
266 print_error('notapproved', 'data');
269 echo $OUTPUT->heading(format_string($data->name), 2);
271 // Do we need to show a link to the RSS feed for the records?
272 //this links has been Settings (database activity administration) block
273 /*if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
274 echo '<div style="float:right;">';
275 rss_print_link($context->id, $USER->id, 'mod_data', $data->id, get_string('rsstype'));
276 echo '</div>';
277 echo '<div style="clear:both;"></div>';
280 if ($data->intro and empty($page) and empty($record) and $mode != 'single') {
281 $options = new stdClass();
282 $options->noclean = true;
284 echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
286 $returnurl = $CFG->wwwroot . '/mod/data/view.php?d='.$data->id.'&amp;search='.s($search).'&amp;sort='.s($sort).'&amp;order='.s($order).'&amp;';
287 groups_print_activity_menu($cm, $returnurl);
289 /// Delete any requested records
291 if ($delete && confirm_sesskey() && (data_user_can_manage_entry($delete, $data, $context))) {
292 if ($confirm = optional_param('confirm',0,PARAM_INT)) {
293 if (data_delete_record($delete, $data, $course->id, $cm->id)) {
294 echo $OUTPUT->notification(get_string('recorddeleted','data'), 'notifysuccess');
296 } else { // Print a confirmation page
297 $allnamefields = user_picture::fields('u');
298 // Remove the id from the string. This already exists in the sql statement.
299 $allnamefields = str_replace('u.id,', '', $allnamefields);
300 $dbparams = array($delete);
301 if ($deleterecord = $DB->get_record_sql("SELECT dr.*, $allnamefields
302 FROM {data_records} dr
303 JOIN {user} u ON dr.userid = u.id
304 WHERE dr.id = ?", $dbparams, MUST_EXIST)) { // Need to check this is valid.
305 if ($deleterecord->dataid == $data->id) { // Must be from this database
306 $deletebutton = new single_button(new moodle_url('/mod/data/view.php?d='.$data->id.'&delete='.$delete.'&confirm=1'), get_string('delete'), 'post');
307 echo $OUTPUT->confirm(get_string('confirmdeleterecord','data'),
308 $deletebutton, 'view.php?d='.$data->id);
310 $records[] = $deleterecord;
311 echo data_print_template('singletemplate', $records, $data, '', 0, true);
313 echo $OUTPUT->footer();
314 exit;
321 // Multi-delete.
322 if ($serialdelete) {
323 $multidelete = json_decode($serialdelete);
326 if ($multidelete && confirm_sesskey() && $canmanageentries) {
327 if ($confirm = optional_param('confirm', 0, PARAM_INT)) {
328 foreach ($multidelete as $value) {
329 data_delete_record($value, $data, $course->id, $cm->id);
331 } else {
332 $validrecords = array();
333 $recordids = array();
334 foreach ($multidelete as $value) {
335 $allnamefields = user_picture::fields('u');
336 // Remove the id from the string. This already exists in the sql statement.
337 $allnamefields = str_replace('u.id,', '', $allnamefields);
338 $dbparams = array('id' => $value);
339 if ($deleterecord = $DB->get_record_sql("SELECT dr.*, $allnamefields
340 FROM {data_records} dr
341 JOIN {user} u ON dr.userid = u.id
342 WHERE dr.id = ?", $dbparams)) { // Need to check this is valid.
343 if ($deleterecord->dataid == $data->id) { // Must be from this database.
344 $validrecords[] = $deleterecord;
345 $recordids[] = $deleterecord->id;
349 $serialiseddata = json_encode($recordids);
350 $submitactions = array('d' => $data->id, 'sesskey' => sesskey(), 'confirm' => '1', 'serialdelete' => $serialiseddata);
351 $action = new moodle_url('/mod/data/view.php', $submitactions);
352 $cancelurl = new moodle_url('/mod/data/view.php', array('d' => $data->id));
353 $deletebutton = new single_button($action, get_string('delete'));
354 echo $OUTPUT->confirm(get_string('confirmdeleterecords', 'data'), $deletebutton, $cancelurl);
355 echo data_print_template('listtemplate', $validrecords, $data, '', 0, false);
356 echo $OUTPUT->footer();
357 exit;
361 // If data activity closed dont let students in.
362 list($showactivity, $warnings) = data_get_time_availability_status($data, $canmanageentries);
364 if (!$showactivity) {
365 $reason = current(array_keys($warnings));
366 echo $OUTPUT->notification(get_string($reason, 'data', $warnings[$reason]));
369 if ($showactivity) {
370 // Print the tabs
371 if ($record or $mode == 'single') {
372 $currenttab = 'single';
373 } elseif($mode == 'asearch') {
374 $currenttab = 'asearch';
376 else {
377 $currenttab = 'list';
379 include('tabs.php');
381 if ($mode == 'asearch') {
382 $maxcount = 0;
383 data_print_preference_form($data, $perpage, $search, $sort, $order, $search_array, $advanced, $mode);
385 } else {
386 // Approve or disapprove any requested records
387 $approvecap = has_capability('mod/data:approve', $context);
389 if (($approve || $disapprove) && confirm_sesskey() && $approvecap) {
390 $newapproved = $approve ? true : false;
391 $recordid = $newapproved ? $approve : $disapprove;
392 if ($approverecord = $DB->get_record('data_records', array('id' => $recordid))) { // Need to check this is valid
393 if ($approverecord->dataid == $data->id) { // Must be from this database
394 data_approve_entry($approverecord->id, $newapproved);
395 $msgkey = $newapproved ? 'recordapproved' : 'recorddisapproved';
396 echo $OUTPUT->notification(get_string($msgkey, 'data'), 'notifysuccess');
401 $numentries = data_numentries($data);
402 /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
403 if ($data->entriesleft = data_get_entries_left_to_add($data, $numentries, $canmanageentries)) {
404 $strentrieslefttoadd = get_string('entrieslefttoadd', 'data', $data);
405 echo $OUTPUT->notification($strentrieslefttoadd);
408 /// 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)
409 $requiredentries_allowed = true;
410 if ($data->entrieslefttoview = data_get_entries_left_to_view($data, $numentries, $canmanageentries)) {
411 $strentrieslefttoaddtoview = get_string('entrieslefttoaddtoview', 'data', $data);
412 echo $OUTPUT->notification($strentrieslefttoaddtoview);
413 $requiredentries_allowed = false;
416 // Search for entries.
417 list($records, $maxcount, $totalcount, $page, $nowperpage, $sort, $mode) =
418 data_search_entries($data, $cm, $context, $mode, $currentgroup, $search, $sort, $order, $page, $perpage, $advanced, $search_array, $record);
420 // Advanced search form doesn't make sense for single (redirects list view).
421 if ($maxcount && $mode != 'single') {
422 data_print_preference_form($data, $perpage, $search, $sort, $order, $search_array, $advanced, $mode);
425 if (empty($records)) {
426 if ($maxcount){
427 $a = new stdClass();
428 $a->max = $maxcount;
429 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
430 echo $OUTPUT->notification(get_string('foundnorecords','data', $a));
431 } else {
432 echo $OUTPUT->notification(get_string('norecords','data'));
435 } else {
436 // We have some records to print.
437 $url = new moodle_url('/mod/data/view.php', array('d' => $data->id, 'sesskey' => sesskey()));
438 echo html_writer::start_tag('form', array('action' => $url, 'method' => 'post'));
440 if ($maxcount != $totalcount) {
441 $a = new stdClass();
442 $a->num = $totalcount;
443 $a->max = $maxcount;
444 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
445 echo $OUTPUT->notification(get_string('foundrecords', 'data', $a), 'notifysuccess');
448 if ($mode == 'single') { // Single template
449 $baseurl = 'view.php?d=' . $data->id . '&mode=single&';
450 if (!empty($search)) {
451 $baseurl .= 'filter=1&';
453 if (!empty($page)) {
454 $baseurl .= 'page=' . $page;
456 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
458 if (empty($data->singletemplate)){
459 echo $OUTPUT->notification(get_string('nosingletemplate','data'));
460 data_generate_default_template($data, 'singletemplate', 0, false, false);
463 //data_print_template() only adds ratings for singletemplate which is why we're attaching them here
464 //attach ratings to data records
465 require_once($CFG->dirroot.'/rating/lib.php');
466 if ($data->assessed != RATING_AGGREGATE_NONE) {
467 $ratingoptions = new stdClass;
468 $ratingoptions->context = $context;
469 $ratingoptions->component = 'mod_data';
470 $ratingoptions->ratingarea = 'entry';
471 $ratingoptions->items = $records;
472 $ratingoptions->aggregate = $data->assessed;//the aggregation method
473 $ratingoptions->scaleid = $data->scale;
474 $ratingoptions->userid = $USER->id;
475 $ratingoptions->returnurl = $CFG->wwwroot.'/mod/data/'.$baseurl;
476 $ratingoptions->assesstimestart = $data->assesstimestart;
477 $ratingoptions->assesstimefinish = $data->assesstimefinish;
479 $rm = new rating_manager();
480 $records = $rm->get_ratings($ratingoptions);
483 data_print_template('singletemplate', $records, $data, $search, $page, false, new moodle_url($baseurl));
485 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
487 } else { // List template
488 $baseurl = 'view.php?d='.$data->id.'&amp;';
489 //send the advanced flag through the URL so it is remembered while paging.
490 $baseurl .= 'advanced='.$advanced.'&amp;';
491 if (!empty($search)) {
492 $baseurl .= 'filter=1&amp;';
494 //pass variable to allow determining whether or not we are paging through results.
495 $baseurl .= 'paging='.$paging.'&amp;';
497 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
499 if (empty($data->listtemplate)){
500 echo $OUTPUT->notification(get_string('nolisttemplate','data'));
501 data_generate_default_template($data, 'listtemplate', 0, false, false);
503 echo $data->listtemplateheader;
504 data_print_template('listtemplate', $records, $data, $search, $page, false, new moodle_url($baseurl));
505 echo $data->listtemplatefooter;
507 echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
510 if ($mode != 'single' && $canmanageentries) {
511 // Build the select/deselect all control.
512 $selectallid = 'selectall-listview-entries';
513 $togglegroup = 'listview-entries';
514 $mastercheckbox = new \core\output\checkbox_toggleall($togglegroup, true, [
515 'id' => $selectallid,
516 'name' => $selectallid,
517 'value' => 1,
518 'label' => get_string('selectall'),
519 'classes' => 'btn-secondary mr-1',
520 ], true);
521 echo $OUTPUT->render($mastercheckbox);
523 $deleteselected = html_writer::empty_tag('input', array(
524 'class' => 'btn btn-secondary',
525 'type' => 'submit',
526 'value' => get_string('deleteselected'),
527 'disabled' => true,
528 'data-action' => 'toggle',
529 'data-togglegroup' => $togglegroup,
530 'data-toggle' => 'action',
532 echo $deleteselected;
535 echo html_writer::end_tag('form');
539 $search = trim($search);
540 if (empty($records)) {
541 $records = array();
544 // Check to see if we can export records to a portfolio. This is for exporting all records, not just the ones in the search.
545 if ($mode == '' && !empty($CFG->enableportfolios) && !empty($records)) {
546 $canexport = false;
547 // Exportallentries and exportentry are basically the same capability.
548 if (has_capability('mod/data:exportallentries', $context) || has_capability('mod/data:exportentry', $context)) {
549 $canexport = true;
550 } else if (has_capability('mod/data:exportownentry', $context) &&
551 $DB->record_exists('data_records', array('userid' => $USER->id))) {
552 $canexport = true;
554 if ($canexport) {
555 require_once($CFG->libdir . '/portfoliolib.php');
556 $button = new portfolio_add_button();
557 $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id), 'mod_data');
558 if (data_portfolio_caller::has_files($data)) {
559 $button->set_formats(array(PORTFOLIO_FORMAT_RICHHTML, PORTFOLIO_FORMAT_LEAP2A)); // No plain html for us.
561 echo $button->to_html(PORTFOLIO_ADD_FULL_FORM);
566 echo $OUTPUT->footer();