Search moodle.org's
Developer Documentation


/mod/data/ -> view.php (source)
   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  ///////////////////////////////////////////////////////////////////////////
  24  
  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');
  29  
  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
  37  
  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);
  46  
  47      if ($id) {
  48          if (! $cm = get_coursemodule_from_id('data', $id)) {
  49              print_error('invalidcoursemodule');
  50          }
  51          if (! $course = $DB->get_record('course', array('id'=>$cm->course))) {
  52              print_error('coursemisconf');
  53          }
  54          if (! $data = $DB->get_record('data', array('id'=>$cm->instance))) {
  55              print_error('invalidcoursemodule');
  56          }
  57          $record = NULL;
  58  
  59      } else if ($rid) {
  60          if (! $record = $DB->get_record('data_records', array('id'=>$rid))) {
  61              print_error('invalidrecord', 'data');
  62          }
  63          if (! $data = $DB->get_record('data', array('id'=>$record->dataid))) {
  64              print_error('invalidid', 'data');
  65          }
  66          if (! $course = $DB->get_record('course', array('id'=>$data->course))) {
  67              print_error('coursemisconf');
  68          }
  69          if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
  70              print_error('invalidcoursemodule');
  71          }
  72      } else {   // We must have $d
  73          if (! $data = $DB->get_record('data', array('id'=>$d))) {
  74              print_error('invalidid', 'data');
  75          }
  76          if (! $course = $DB->get_record('course', array('id'=>$data->course))) {
  77              print_error('coursemisconf');
  78          }
  79          if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
  80              print_error('invalidcoursemodule');
  81          }
  82          $record = NULL;
  83      }
  84  
  85      require_course_login($course, true, $cm);
  86  
  87      require_once($CFG->dirroot . '/comment/lib.php');
  88      comment::init();
  89  
  90      $context = context_module::instance($cm->id);
  91      require_capability('mod/data:viewentry', $context);
  92  
  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
  97          }
  98      }
  99  
 100  
 101  /// Check further parameters that set browsing preferences
 102      if (!isset($SESSION->dataprefs)) {
 103          $SESSION->dataprefs = array();
 104      }
 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';
 112      }
 113  
 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");
 119      }
 120  
 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();
 128          }
 129          $SESSION->dataprefs[$data->id]['advanced'] = $advanced;
 130      }
 131  
 132      $search_array = $SESSION->dataprefs[$data->id]['search_array'];
 133  
 134      if (!empty($advanced)) {
 135          $search = '';
 136          $vals = array();
 137          $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
 138  
 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.
 151  
 152          $paging = optional_param('paging', NULL, PARAM_BOOL);
 153          if($page == 0 && !isset($paging)) {
 154              $paging = false;
 155          }
 156          else {
 157              $paging = true;
 158          }
 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 = '';
 172                      }
 173                  }
 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]);
 182                  }
 183              }
 184          }
 185  
 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 : '';
 193          }
 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]);
 203          }
 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]);
 213          }
 214  
 215          $SESSION->dataprefs[$data->id]['search_array'] = $search_array;     // Make it sticky
 216  
 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;
 222              }
 223          }
 224  
 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;
 229      }
 230  
 231      // Disable search filters if $filter is not true:
 232      if (! $filter) {
 233          $search = '';
 234      }
 235  
 236      if (core_text::strlen($search) < 2) {
 237          $search = '';
 238      }
 239      $SESSION->dataprefs[$data->id]['search'] = $search;   // Make it sticky
 240  
 241      $sort = optional_param('sort', $SESSION->dataprefs[$data->id]['sort'], PARAM_INT);
 242      $SESSION->dataprefs[$data->id]['sort'] = $sort;       // Make it sticky
 243  
 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
 246  
 247  
 248      $oldperpage = get_user_preferences('data_perpage_'.$data->id, 10);
 249      $perpage = optional_param('perpage', $oldperpage, PARAM_INT);
 250  
 251      if ($perpage < 2) {
 252          $perpage = 2;
 253      }
 254      if ($perpage != $oldperpage) {
 255          set_user_preference('data_perpage_'.$data->id, $perpage);
 256      }
 257  
 258      $params = array(
 259          'context' => $context,
 260          'objectid' => $data->id
 261      );
 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();
 267  
 268      $urlparams = array('d' => $data->id);
 269      if ($record) {
 270          $urlparams['rid'] = $record->id;
 271      }
 272      if ($page) {
 273          $urlparams['page'] = $page;
 274      }
 275      if ($mode) {
 276          $urlparams['mode'] = $mode;
 277      }
 278      if ($filter) {
 279          $urlparams['filter'] = $filter;
 280      }
 281  // Initialize $PAGE, compute blocks
 282      $PAGE->set_url('/mod/data/view.php', $urlparams);
 283  
 284      if (($edit != -1) and $PAGE->user_allowed_editing()) {
 285          $USER->editing = $edit;
 286      }
 287  
 288      $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
 289  
 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);
 295      }
 296      if ($data->csstemplate) {
 297          $PAGE->requires->css('/mod/data/css.php?d='.$data->id);
 298      }
 299      if ($data->jstemplate) {
 300          $PAGE->requires->js('/mod/data/js.php?d='.$data->id, true);
 301      }
 302  
 303      // Mark as viewed
 304      $completion = new completion_info($course);
 305      $completion->set_module_viewed($cm);
 306  
 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);
 311  
 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');
 320          }
 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));
 323      }
 324  
 325      if ($mode == 'asearch') {
 326          $PAGE->navbar->add(get_string('search'));
 327      }
 328  
 329      $PAGE->set_title($title);
 330      $PAGE->set_heading($course->fullname);
 331  
 332      echo $OUTPUT->header();
 333  
 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;
 345      }
 346  
 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');
 351          }
 352      }
 353  
 354      echo $OUTPUT->heading(format_string($data->name), 2);
 355  
 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>';
 363      }*/
 364  
 365      if ($data->intro and empty($page) and empty($record) and $mode != 'single') {
 366          $options = new stdClass();
 367          $options->noclean = true;
 368      }
 369      echo $OUTPUT->box(format_module_intro('data', $data, $cm->id), 'generalbox', 'intro');
 370  
 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);
 373  
 374  /// Delete any requested records
 375  
 376      if ($delete && confirm_sesskey() && ($canmanageentries or data_isowner($delete))) {
 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');
 380              }
 381          } else {   // Print a confirmation page
 382              $allnamefields = get_all_user_name_fields(true, 'u');
 383              $dbparams = array($delete);
 384              if ($deleterecord = $DB->get_record_sql("SELECT dr.*, $allnamefields
 385                                                         FROM {data_records} dr
 386                                                              JOIN {user} u ON dr.userid = u.id
 387                                                        WHERE dr.id = ?", $dbparams, MUST_EXIST)) { // Need to check this is valid.
 388                  if ($deleterecord->dataid == $data->id) {                       // Must be from this database
 389                      $deletebutton = new single_button(new moodle_url('/mod/data/view.php?d='.$data->id.'&delete='.$delete.'&confirm=1'), get_string('delete'), 'post');
 390                      echo $OUTPUT->confirm(get_string('confirmdeleterecord','data'),
 391                              $deletebutton, 'view.php?d='.$data->id);
 392  
 393                      $records[] = $deleterecord;
 394                      echo data_print_template('singletemplate', $records, $data, '', 0, true);
 395  
 396                      echo $OUTPUT->footer();
 397                      exit;
 398                  }
 399              }
 400          }
 401      }
 402  
 403  
 404      // Multi-delete.
 405      if ($serialdelete) {
 406          $multidelete = json_decode($serialdelete);
 407      }
 408  
 409      if ($multidelete && confirm_sesskey() && $canmanageentries) {
 410          if ($confirm = optional_param('confirm', 0, PARAM_INT)) {
 411              foreach ($multidelete as $value) {
 412                  data_delete_record($value, $data, $course->id, $cm->id);
 413              }
 414          } else {
 415              $validrecords = array();
 416              $recordids = array();
 417              foreach ($multidelete as $value) {
 418                  if ($deleterecord = $DB->get_record('data_records', array('id'=>$value))) {   // Need to check this is valid
 419                      if ($deleterecord->dataid == $data->id) {                       // Must be from this database
 420                          $validrecords[] = $deleterecord;
 421                          $recordids[] = $deleterecord->id;
 422                      }
 423                  }
 424              }
 425  
 426              $serialiseddata = json_encode($recordids);
 427              $submitactions = array('d' => $data->id, 'sesskey' => sesskey(), 'confirm' => '1', 'serialdelete' => $serialiseddata);
 428              $action = new moodle_url('/mod/data/view.php', $submitactions);
 429              $cancelurl = new moodle_url('/mod/data/view.php', array('d' => $data->id));
 430              $deletebutton = new single_button($action, get_string('delete'));
 431              echo $OUTPUT->confirm(get_string('confirmdeleterecords', 'data'), $deletebutton, $cancelurl);
 432              echo data_print_template('listtemplate', $validrecords, $data, '', 0, false);
 433              echo $OUTPUT->footer();
 434              exit;
 435          }
 436      }
 437  
 438  
 439  //if data activity closed dont let students in
 440  $showactivity = true;
 441  if (!$canmanageentries) {
 442      $timenow = time();
 443      if (!empty($data->timeavailablefrom) && $data->timeavailablefrom > $timenow) {
 444          echo $OUTPUT->notification(get_string('notopenyet', 'data', userdate($data->timeavailablefrom)));
 445          $showactivity = false;
 446      } else if (!empty($data->timeavailableto) && $timenow > $data->timeavailableto) {
 447          echo $OUTPUT->notification(get_string('expired', 'data', userdate($data->timeavailableto)));
 448          $showactivity = false;
 449      }
 450  }
 451  
 452  if ($showactivity) {
 453      // Print the tabs
 454      if ($record or $mode == 'single') {
 455          $currenttab = 'single';
 456      } elseif($mode == 'asearch') {
 457          $currenttab = 'asearch';
 458      }
 459      else {
 460          $currenttab = 'list';
 461      }
 462      include ('tabs.php');
 463  
 464      $url = new moodle_url('/mod/data/view.php', array('d' => $data->id, 'sesskey' => sesskey()));
 465      echo html_writer::start_tag('form', array('action' => $url, 'method' => 'post'));
 466  
 467      if ($mode == 'asearch') {
 468          $maxcount = 0;
 469  
 470      } else {
 471          // Approve or disapprove any requested records
 472          $params = array(); // named params array
 473  
 474          $approvecap = has_capability('mod/data:approve', $context);
 475  
 476          if (($approve || $disapprove) && confirm_sesskey() && $approvecap) {
 477              $newapproved = $approve ? 1 : 0;
 478              $recordid = $newapproved ? $approve : $disapprove;
 479              if ($approverecord = $DB->get_record('data_records', array('id' => $recordid))) {   // Need to check this is valid
 480                  if ($approverecord->dataid == $data->id) {                       // Must be from this database
 481                      $newrecord = new stdClass();
 482                      $newrecord->id = $approverecord->id;
 483                      $newrecord->approved = $newapproved;
 484                      $DB->update_record('data_records', $newrecord);
 485                      $msgkey = $newapproved ? 'recordapproved' : 'recorddisapproved';
 486                      echo $OUTPUT->notification(get_string($msgkey, 'data'), 'notifysuccess');
 487                  }
 488              }
 489          }
 490  
 491           $numentries = data_numentries($data);
 492      /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
 493          if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !$canmanageentries) {
 494              $data->entriesleft = $data->requiredentries - $numentries;
 495              $strentrieslefttoadd = get_string('entrieslefttoadd', 'data', $data);
 496              echo $OUTPUT->notification($strentrieslefttoadd);
 497          }
 498  
 499      /// 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)
 500          $requiredentries_allowed = true;
 501          if ($data->requiredentriestoview > 0 && $numentries < $data->requiredentriestoview && !$canmanageentries) {
 502              $data->entrieslefttoview = $data->requiredentriestoview - $numentries;
 503              $strentrieslefttoaddtoview = get_string('entrieslefttoaddtoview', 'data', $data);
 504              echo $OUTPUT->notification($strentrieslefttoaddtoview);
 505              $requiredentries_allowed = false;
 506          }
 507  
 508          // Initialise the first group of params for advanced searches.
 509          $initialparams   = array();
 510  
 511      /// setup group and approve restrictions
 512          if (!$approvecap && $data->approval) {
 513              if (isloggedin()) {
 514                  $approveselect = ' AND (r.approved=1 OR r.userid=:myid1) ';
 515                  $params['myid1'] = $USER->id;
 516                  $initialparams['myid1'] = $params['myid1'];
 517              } else {
 518                  $approveselect = ' AND r.approved=1 ';
 519              }
 520          } else {
 521              $approveselect = ' ';
 522          }
 523  
 524          if ($currentgroup) {
 525              $groupselect = " AND (r.groupid = :currentgroup OR r.groupid = 0)";
 526              $params['currentgroup'] = $currentgroup;
 527              $initialparams['currentgroup'] = $params['currentgroup'];
 528          } else {
 529              if ($canviewallrecords) {
 530                  $groupselect = ' ';
 531              } else {
 532                  // If separate groups are enabled and the user isn't in a group or
 533                  // a teacher, manager, admin etc, then just show them entries for 'All participants'.
 534                  $groupselect = " AND r.groupid = 0";
 535              }
 536          }
 537  
 538          // Init some variables to be used by advanced search
 539          $advsearchselect = '';
 540          $advwhere        = '';
 541          $advtables       = '';
 542          $advparams       = array();
 543          // This is used for the initial reduction of advanced search results with required entries.
 544          $entrysql        = '';
 545          $namefields = get_all_user_name_fields(true, 'u');
 546  
 547      /// Find the field we are sorting on
 548          if ($sort <= 0 or !$sortfield = data_get_field_from_id($sort, $data)) {
 549  
 550              switch ($sort) {
 551                  case DATA_LASTNAME:
 552                      $ordering = "u.lastname $order, u.firstname $order";
 553                      break;
 554                  case DATA_FIRSTNAME:
 555                      $ordering = "u.firstname $order, u.lastname $order";
 556                      break;
 557                  case DATA_APPROVED:
 558                      $ordering = "r.approved $order, r.timecreated $order";
 559                      break;
 560                  case DATA_TIMEMODIFIED:
 561                      $ordering = "r.timemodified $order";
 562                      break;
 563                  case DATA_TIMEADDED:
 564                  default:
 565                      $sort     = 0;
 566                      $ordering = "r.timecreated $order";
 567              }
 568  
 569              $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields;
 570              $count = ' COUNT(DISTINCT c.recordid) ';
 571              $tables = '{data_content} c,{data_records} r, {user} u ';
 572              $where =  'WHERE c.recordid = r.id
 573                           AND r.dataid = :dataid
 574                           AND r.userid = u.id ';
 575              $params['dataid'] = $data->id;
 576              $sortorder = " ORDER BY $ordering, r.id $order";
 577              $searchselect = '';
 578  
 579              // If requiredentries is not reached, only show current user's entries
 580              if (!$requiredentries_allowed) {
 581                  $where .= ' AND u.id = :myid2 ';
 582                  $entrysql = ' AND r.userid = :myid3 ';
 583                  $params['myid2'] = $USER->id;
 584                  $initialparams['myid3'] = $params['myid2'];
 585              }
 586  
 587              if (!empty($advanced)) {                                                  //If advanced box is checked.
 588                  $i = 0;
 589                  foreach($search_array as $key => $val) {                              //what does $search_array hold?
 590                      if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
 591                          $i++;
 592                          $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
 593                          $params['search_flname_'.$i] = "%$val->data%";
 594                          continue;
 595                      }
 596                      $advtables .= ', {data_content} c'.$key.' ';
 597                      $advwhere .= ' AND c'.$key.'.recordid = r.id';
 598                      $advsearchselect .= ' AND ('.$val->sql.') ';
 599                      $advparams = array_merge($advparams, $val->params);
 600                  }
 601              } else if ($search) {
 602                  $searchselect = " AND (".$DB->sql_like('c.content', ':search1', false)."
 603                                    OR ".$DB->sql_like('u.firstname', ':search2', false)."
 604                                    OR ".$DB->sql_like('u.lastname', ':search3', false)." ) ";
 605                  $params['search1'] = "%$search%";
 606                  $params['search2'] = "%$search%";
 607                  $params['search3'] = "%$search%";
 608              } else {
 609                  $searchselect = ' ';
 610              }
 611  
 612          } else {
 613  
 614              $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
 615              $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
 616  
 617              $what = ' DISTINCT r.id, r.approved, r.timecreated, r.timemodified, r.userid, ' . $namefields . ',
 618                      ' . $sortcontentfull . ' AS sortorder ';
 619              $count = ' COUNT(DISTINCT c.recordid) ';
 620              $tables = '{data_content} c, {data_records} r, {user} u ';
 621              $where =  'WHERE c.recordid = r.id
 622                           AND r.dataid = :dataid
 623                           AND r.userid = u.id ';
 624              if (!$advanced) {
 625                  $where .=  'AND c.fieldid = :sort';
 626              }
 627              $params['dataid'] = $data->id;
 628              $params['sort'] = $sort;
 629              $sortorder = ' ORDER BY sortorder '.$order.' , r.id ASC ';
 630              $searchselect = '';
 631  
 632              // If requiredentries is not reached, only show current user's entries
 633              if (!$requiredentries_allowed) {
 634                  $where .= ' AND u.id = :myid2';
 635                  $entrysql = ' AND r.userid = :myid3';
 636                  $params['myid2'] = $USER->id;
 637                  $initialparams['myid3'] = $params['myid2'];
 638              }
 639              $i = 0;
 640              if (!empty($advanced)) {                                                  //If advanced box is checked.
 641                  foreach($search_array as $key => $val) {                              //what does $search_array hold?
 642                      if ($key == DATA_FIRSTNAME or $key == DATA_LASTNAME) {
 643                          $i++;
 644                          $searchselect .= " AND ".$DB->sql_like($val->field, ":search_flname_$i", false);
 645                          $params['search_flname_'.$i] = "%$val->data%";
 646                          continue;
 647                      }
 648                      $advtables .= ', {data_content} c'.$key.' ';
 649                      $advwhere .= ' AND c'.$key.'.recordid = r.id AND c'.$key.'.fieldid = '.$key;
 650                      $advsearchselect .= ' AND ('.$val->sql.') ';
 651                      $advparams = array_merge($advparams, $val->params);
 652                  }
 653              } else if ($search) {
 654                  $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)." ) ";
 655                  $params['search1'] = "%$search%";
 656                  $params['search2'] = "%$search%";
 657                  $params['search3'] = "%$search%";
 658              } else {
 659                  $searchselect = ' ';
 660              }
 661          }
 662  
 663      /// To actually fetch the records
 664  
 665          $fromsql    = "FROM $tables $advtables $where $advwhere $groupselect $approveselect $searchselect $advsearchselect";
 666          $allparams  = array_merge($params, $advparams);
 667  
 668          // Provide initial sql statements and parameters to reduce the number of total records.
 669          $initialselect = $groupselect . $approveselect . $entrysql;
 670  
 671          $recordids = data_get_all_recordids($data->id, $initialselect, $initialparams);
 672          $newrecordids = data_get_advance_search_ids($recordids, $search_array, $data->id);
 673          $totalcount = count($newrecordids);
 674          $selectdata = $where . $groupselect . $approveselect;
 675  
 676          if (!empty($advanced)) {
 677              $advancedsearchsql = data_get_advanced_search_sql($sort, $data, $newrecordids, $selectdata, $sortorder);
 678              $sqlselect = $advancedsearchsql['sql'];
 679              $allparams = array_merge($allparams, $advancedsearchsql['params']);
 680          } else {
 681              $sqlselect  = "SELECT $what $fromsql $sortorder";
 682          }
 683  
 684          /// Work out the paging numbers and counts
 685          if (empty($searchselect) && empty($advsearchselect)) {
 686              $maxcount = $totalcount;
 687          } else {
 688              $maxcount = count($recordids);
 689          }
 690  
 691          if ($record) {     // We need to just show one, so where is it in context?
 692              $nowperpage = 1;
 693              $mode = 'single';
 694              $page = 0;
 695              // TODO MDL-33797 - Reduce this or consider redesigning the paging system.
 696              if ($allrecordids = $DB->get_fieldset_sql($sqlselect, $allparams)) {
 697                  $page = (int)array_search($record->id, $allrecordids);
 698                  unset($allrecordids);
 699              }
 700          } else if ($mode == 'single') {  // We rely on ambient $page settings
 701              $nowperpage = 1;
 702  
 703          } else {
 704              $nowperpage = $perpage;
 705          }
 706  
 707      /// Get the actual records
 708  
 709          if (!$records = $DB->get_records_sql($sqlselect, $allparams, $page * $nowperpage, $nowperpage)) {
 710              // Nothing to show!
 711              if ($record) {         // Something was requested so try to show that at least (bug 5132)
 712                  if ($canmanageentries || empty($data->approval) ||
 713                           $record->approved || (isloggedin() && $record->userid == $USER->id)) {
 714                      if (!$currentgroup || $record->groupid == $currentgroup || $record->groupid == 0) {
 715                          // OK, we can show this one
 716                          $records = array($record->id => $record);
 717                          $totalcount = 1;
 718                      }
 719                  }
 720              }
 721          }
 722  
 723          if (empty($records)) {
 724              if ($maxcount){
 725                  $a = new stdClass();
 726                  $a->max = $maxcount;
 727                  $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
 728                  echo $OUTPUT->notification(get_string('foundnorecords','data', $a));
 729              } else {
 730                  echo $OUTPUT->notification(get_string('norecords','data'));
 731              }
 732  
 733          } else { //  We have some records to print
 734  
 735              if ($maxcount != $totalcount) {
 736                  $a = new stdClass();
 737                  $a->num = $totalcount;
 738                  $a->max = $maxcount;
 739                  $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
 740                  echo $OUTPUT->notification(get_string('foundrecords', 'data', $a), 'notifysuccess');
 741              }
 742  
 743              if ($mode == 'single') { // Single template
 744                  $baseurl = 'view.php?d=' . $data->id . '&mode=single&';
 745                  if (!empty($search)) {
 746                      $baseurl .= 'filter=1&';
 747                  }
 748                  if (!empty($page)) {
 749                      $baseurl .= 'page=' . $page;
 750                  }
 751                  echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
 752  
 753                  if (empty($data->singletemplate)){
 754                      echo $OUTPUT->notification(get_string('nosingletemplate','data'));
 755                      data_generate_default_template($data, 'singletemplate', 0, false, false);
 756                  }
 757  
 758                  //data_print_template() only adds ratings for singletemplate which is why we're attaching them here
 759                  //attach ratings to data records
 760                  require_once($CFG->dirroot.'/rating/lib.php');
 761                  if ($data->assessed != RATING_AGGREGATE_NONE) {
 762                      $ratingoptions = new stdClass;
 763                      $ratingoptions->context = $context;
 764                      $ratingoptions->component = 'mod_data';
 765                      $ratingoptions->ratingarea = 'entry';
 766                      $ratingoptions->items = $records;
 767                      $ratingoptions->aggregate = $data->assessed;//the aggregation method
 768                      $ratingoptions->scaleid = $data->scale;
 769                      $ratingoptions->userid = $USER->id;
 770                      $ratingoptions->returnurl = $CFG->wwwroot.'/mod/data/'.$baseurl;
 771                      $ratingoptions->assesstimestart = $data->assesstimestart;
 772                      $ratingoptions->assesstimefinish = $data->assesstimefinish;
 773  
 774                      $rm = new rating_manager();
 775                      $records = $rm->get_ratings($ratingoptions);
 776                  }
 777  
 778                  data_print_template('singletemplate', $records, $data, $search, $page, false, new moodle_url($baseurl));
 779  
 780                  echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
 781  
 782              } else {                                  // List template
 783                  $baseurl = 'view.php?d='.$data->id.'&amp;';
 784                  //send the advanced flag through the URL so it is remembered while paging.
 785                  $baseurl .= 'advanced='.$advanced.'&amp;';
 786                  if (!empty($search)) {
 787                      $baseurl .= 'filter=1&amp;';
 788                  }
 789                  //pass variable to allow determining whether or not we are paging through results.
 790                  $baseurl .= 'paging='.$paging.'&amp;';
 791  
 792                  echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
 793  
 794                  if (empty($data->listtemplate)){
 795                      echo $OUTPUT->notification(get_string('nolisttemplate','data'));
 796                      data_generate_default_template($data, 'listtemplate', 0, false, false);
 797                  }
 798                  echo $data->listtemplateheader;
 799                  data_print_template('listtemplate', $records, $data, $search, $page, false, new moodle_url($baseurl));
 800                  echo $data->listtemplatefooter;
 801  
 802                  echo $OUTPUT->paging_bar($totalcount, $page, $nowperpage, $baseurl);
 803              }
 804  
 805          }
 806      }
 807  
 808      $search = trim($search);
 809      if (empty($records)) {
 810          $records = array();
 811      }
 812  
 813      if ($mode != 'single' && $canmanageentries) {
 814          echo html_writer::empty_tag('input', array('type' => 'button', 'id' => 'checkall', 'value' => get_string('selectall')));
 815          echo html_writer::empty_tag('input', array('type' => 'button', 'id' => 'checknone', 'value' => get_string('deselectall')));
 816          echo html_writer::empty_tag('input', array('class' => 'form-submit', 'type' => 'submit', 'value' => get_string('deleteselected')));
 817  
 818          $module = array('name'=>'mod_data', 'fullpath'=>'/mod/data/module.js');
 819          $PAGE->requires->js_init_call('M.mod_data.init_view', null, false, $module);
 820      }
 821      echo html_writer::end_tag('form');
 822  
 823      // Check to see if we can export records to a portfolio. This is for exporting all records, not just the ones in the search.
 824      if ($mode == '' && !empty($CFG->enableportfolios) && !empty($records)) {
 825          $canexport = false;
 826          // Exportallentries and exportentry are basically the same capability.
 827          if (has_capability('mod/data:exportallentries', $context) || has_capability('mod/data:exportentry', $context)) {
 828              $canexport = true;
 829          } else if (has_capability('mod/data:exportownentry', $context) &&
 830                  $DB->record_exists('data_records', array('userid' => $USER->id))) {
 831              $canexport = true;
 832          }
 833          if ($canexport) {
 834              require_once($CFG->libdir . '/portfoliolib.php');
 835              $button = new portfolio_add_button();
 836              $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id), 'mod_data');
 837              if (data_portfolio_caller::has_files($data)) {
 838                  $button->set_formats(array(PORTFOLIO_FORMAT_RICHHTML, PORTFOLIO_FORMAT_LEAP2A)); // No plain html for us.
 839              }
 840              echo $button->to_html(PORTFOLIO_ADD_FULL_FORM);
 841          }
 842      }
 843  
 844      //Advanced search form doesn't make sense for single (redirects list view)
 845      if (($maxcount || $mode == 'asearch') && $mode != 'single') {
 846          data_print_preference_form($data, $perpage, $search, $sort, $order, $search_array, $advanced, $mode);
 847      }
 848  }
 849  
 850  echo $OUTPUT->footer();

Search This Site: