Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 310 and 311] [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403] [Versions 39 and 311]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Table log for displaying logs.
  19   *
  20   * @package    report_loglive
  21   * @copyright  2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die;
  26  require_once($CFG->libdir . '/tablelib.php');
  27  
  28  /**
  29   * Table log class for displaying logs.
  30   *
  31   * @since      Moodle 2.7
  32   * @package    report_loglive
  33   * @copyright  2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
  34   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35   */
  36  class report_loglive_table_log extends table_sql {
  37  
  38      /** @var array list of user fullnames shown in report */
  39      protected $userfullnames = array();
  40  
  41      /** @var array list of course short names shown in report */
  42      protected $courseshortnames = array();
  43  
  44      /** @var array list of context name shown in report */
  45      protected $contextname = array();
  46  
  47      /** @var stdClass filters parameters */
  48      protected $filterparams;
  49  
  50      /**
  51       * Sets up the table_log parameters.
  52       *
  53       * @param string $uniqueid unique id of form.
  54       * @param stdClass $filterparams (optional) filter params.
  55       *     - int courseid: id of course
  56       *     - int userid: user id
  57       *     - int|string modid: Module id or "site_errors" to view site errors
  58       *     - int groupid: Group id
  59       *     - array groups: List of group ids
  60       *     - \core\log\sql_reader logreader: reader from which data will be fetched.
  61       *     - int edulevel: educational level.
  62       *     - string action: view action
  63       *     - int date: Date from which logs to be viewed.
  64       */
  65      public function __construct($uniqueid, $filterparams = null) {
  66          parent::__construct($uniqueid);
  67  
  68          $this->set_attribute('class', 'reportloglive generaltable table-sm');
  69          $this->set_attribute('aria-live', 'polite');
  70          $this->filterparams = $filterparams;
  71          // Add course column if logs are displayed for site.
  72          $cols = array();
  73          $headers = array();
  74          if (empty($filterparams->courseid)) {
  75              $cols = array('course');
  76              $headers = array(get_string('course'));
  77          }
  78  
  79          $this->define_columns(array_merge($cols, array('time', 'fullnameuser', 'relatedfullnameuser', 'context', 'component',
  80                  'eventname', 'description', 'origin', 'ip')));
  81          $this->define_headers(array_merge($headers, array(
  82                  get_string('time'),
  83                  get_string('fullnameuser'),
  84                  get_string('eventrelatedfullnameuser', 'report_loglive'),
  85                  get_string('eventcontext', 'report_loglive'),
  86                  get_string('eventcomponent', 'report_loglive'),
  87                  get_string('eventname'),
  88                  get_string('description'),
  89                  get_string('eventorigin', 'report_loglive'),
  90                  get_string('ip_address')
  91                  )
  92              ));
  93          $this->collapsible(false);
  94          $this->sortable(false);
  95          $this->pageable(true);
  96          $this->is_downloadable(false);
  97      }
  98  
  99      /**
 100       * Generate the course column.
 101       *
 102       * @param stdClass $event event data.
 103       * @return string HTML for the course column.
 104       */
 105      public function col_course($event) {
 106          if (empty($event->courseid) || empty($this->courseshortnames[$event->courseid])) {
 107              return '-';
 108          } else {
 109              return $this->courseshortnames[$event->courseid];
 110          }
 111      }
 112  
 113      /**
 114       * Generate the time column.
 115       *
 116       * @param stdClass $event event data.
 117       * @return string HTML for the time column
 118       */
 119      public function col_time($event) {
 120          $recenttimestr = get_string('strftimedatetime', 'core_langconfig');
 121          return userdate($event->timecreated, $recenttimestr);
 122      }
 123  
 124      /**
 125       * Generate the username column.
 126       *
 127       * @param stdClass $event event data.
 128       * @return string HTML for the username column
 129       */
 130      public function col_fullnameuser($event) {
 131          // Get extra event data for origin and realuserid.
 132          $logextra = $event->get_logextra();
 133  
 134          // Add username who did the action.
 135          if (!empty($logextra['realuserid'])) {
 136              $a = new stdClass();
 137              $params = array('id' => $logextra['realuserid']);
 138              if ($event->courseid) {
 139                  $params['course'] = $event->courseid;
 140              }
 141              $a->realusername = html_writer::link(new moodle_url("/user/view.php", $params),
 142                  $this->userfullnames[$logextra['realuserid']]);
 143              $params['id'] = $event->userid;
 144              $a->asusername = html_writer::link(new moodle_url("/user/view.php", $params),
 145                  $this->userfullnames[$event->userid]);
 146              $username = get_string('eventloggedas', 'report_loglive', $a);
 147          } else if (!empty($event->userid) && !empty($this->userfullnames[$event->userid])) {
 148              $params = array('id' => $event->userid);
 149              if ($event->courseid) {
 150                  $params['course'] = $event->courseid;
 151              }
 152              $username = html_writer::link(new moodle_url("/user/view.php", $params), $this->userfullnames[$event->userid]);
 153          } else {
 154              $username = '-';
 155          }
 156          return $username;
 157      }
 158  
 159      /**
 160       * Generate the related username column.
 161       *
 162       * @param stdClass $event event data.
 163       * @return string HTML for the related username column
 164       */
 165      public function col_relatedfullnameuser($event) {
 166          // Add affected user.
 167          if (!empty($event->relateduserid) && isset($this->userfullnames[$event->relateduserid])) {
 168              $params = array('id' => $event->relateduserid);
 169              if ($event->courseid) {
 170                  $params['course'] = $event->courseid;
 171              }
 172              return html_writer::link(new moodle_url("/user/view.php", $params), $this->userfullnames[$event->relateduserid]);
 173          } else {
 174              return '-';
 175          }
 176      }
 177  
 178      /**
 179       * Generate the context column.
 180       *
 181       * @param stdClass $event event data.
 182       * @return string HTML for the context column
 183       */
 184      public function col_context($event) {
 185          // Add context name.
 186          if ($event->contextid) {
 187              // If context name was fetched before then return, else get one.
 188              if (isset($this->contextname[$event->contextid])) {
 189                  return $this->contextname[$event->contextid];
 190              } else {
 191                  $context = context::instance_by_id($event->contextid, IGNORE_MISSING);
 192                  if ($context) {
 193                      $contextname = $context->get_context_name(true);
 194                      if ($url = $context->get_url()) {
 195                          $contextname = html_writer::link($url, $contextname);
 196                      }
 197                  } else {
 198                      $contextname = get_string('other');
 199                  }
 200              }
 201          } else {
 202              $contextname = get_string('other');
 203          }
 204  
 205          $this->contextname[$event->contextid] = $contextname;
 206          return $contextname;
 207      }
 208  
 209      /**
 210       * Generate the component column.
 211       *
 212       * @param stdClass $event event data.
 213       * @return string HTML for the component column
 214       */
 215      public function col_component($event) {
 216          // Component.
 217          $componentname = $event->component;
 218          if (($event->component === 'core') || ($event->component === 'legacy')) {
 219              return  get_string('coresystem');
 220          } else if (get_string_manager()->string_exists('pluginname', $event->component)) {
 221              return get_string('pluginname', $event->component);
 222          } else {
 223              return $componentname;
 224          }
 225      }
 226  
 227      /**
 228       * Generate the event name column.
 229       *
 230       * @param stdClass $event event data.
 231       * @return string HTML for the event name column
 232       */
 233      public function col_eventname($event) {
 234          // Event name.
 235          if ($this->filterparams->logreader instanceof logstore_legacy\log\store) {
 236              // Hack for support of logstore_legacy.
 237              $eventname = $event->eventname;
 238          } else {
 239              $eventname = $event->get_name();
 240          }
 241          if ($url = $event->get_url()) {
 242              $eventname = $this->action_link($url, $eventname, 'action');
 243          }
 244          return $eventname;
 245      }
 246  
 247      /**
 248       * Generate the description column.
 249       *
 250       * @param stdClass $event event data.
 251       * @return string HTML for the description column
 252       */
 253      public function col_description($event) {
 254          // Description.
 255          return $event->get_description();
 256      }
 257  
 258      /**
 259       * Generate the origin column.
 260       *
 261       * @param stdClass $event event data.
 262       * @return string HTML for the origin column
 263       */
 264      public function col_origin($event) {
 265          // Get extra event data for origin and realuserid.
 266          $logextra = $event->get_logextra();
 267  
 268          // Add event origin, normally IP/cron.
 269          return $logextra['origin'];
 270      }
 271  
 272      /**
 273       * Generate the ip column.
 274       *
 275       * @param stdClass $event event data.
 276       * @return string HTML for the ip column
 277       */
 278      public function col_ip($event) {
 279          // Get extra event data for origin and realuserid.
 280          $logextra = $event->get_logextra();
 281  
 282          $url = new moodle_url("/iplookup/index.php?ip={$logextra['ip']}&user=$event->userid");
 283          return $this->action_link($url, $logextra['ip'], 'ip');
 284      }
 285  
 286      /**
 287       * Method to create a link with popup action.
 288       *
 289       * @param moodle_url $url The url to open.
 290       * @param string $text Anchor text for the link.
 291       * @param string $name Name of the popup window.
 292       *
 293       * @return string html to use.
 294       */
 295      protected function action_link(moodle_url $url, $text, $name = 'popup') {
 296          global $OUTPUT;
 297          $link = new action_link($url, $text, new popup_action('click', $url, $name, array('height' => 440, 'width' => 700)));
 298          return $OUTPUT->render($link);
 299      }
 300  
 301      /**
 302       * Query the reader. Store results in the object for use by build_table.
 303       *
 304       * @param int $pagesize size of page for paginated displayed table.
 305       * @param bool $useinitialsbar do you want to use the initials bar.
 306       */
 307      public function query_db($pagesize, $useinitialsbar = true) {
 308          global $DB;
 309  
 310          $joins = array();
 311          $params = array();
 312  
 313          // Set up filtering.
 314          if (!empty($this->filterparams->courseid)) {
 315              // For a normal course, set the course filter.
 316              $joins[] = "courseid = :courseid";
 317              $params['courseid'] = $this->filterparams->courseid;
 318              // If we have a course, then check if the groups filter is set.
 319              if ($this->filterparams->courseid != SITEID && !empty($this->filterparams->groups)) {
 320                  // If that's the case, limit the users to be in the groups only, defined by the filter.
 321                  $useringroups = [];
 322                  foreach ($this->filterparams->groups as $groupid) {
 323                      $gusers = groups_get_members($groupid, 'u.id');
 324                      $useringroups = array_merge($useringroups, array_keys($gusers));
 325                  }
 326                  $useringroups = array_unique($useringroups);
 327                  list($ugsql, $ugparams) = $DB->get_in_or_equal($useringroups, SQL_PARAMS_NAMED);
 328                  $joins[] = 'userid ' . $ugsql;
 329                  $params = array_merge($params, $ugparams);
 330              }
 331          }
 332  
 333          if (!empty($this->filterparams->date)) {
 334              $joins[] = "timecreated > :date";
 335              $params['date'] = $this->filterparams->date;
 336          }
 337  
 338          if (isset($this->filterparams->anonymous)) {
 339              $joins[] = "anonymous = :anon";
 340              $params['anon'] = $this->filterparams->anonymous;
 341          }
 342          $selector = implode(' AND ', $joins);
 343  
 344          $total = $this->filterparams->logreader->get_events_select_count($selector, $params);
 345          $this->pagesize($pagesize, $total);
 346          $this->rawdata = $this->filterparams->logreader->get_events_select($selector, $params, $this->filterparams->orderby,
 347                  $this->get_page_start(), $this->get_page_size());
 348  
 349          // Set initial bars.
 350          if ($useinitialsbar) {
 351              $this->initialbars($total > $pagesize);
 352          }
 353  
 354          // Update list of users and courses list which will be displayed on log page.
 355          $this->update_users_and_courses_used();
 356      }
 357  
 358      /**
 359       * Helper function to create list of course shortname and user fullname shown in log report.
 360       * This will update $this->userfullnames and $this->courseshortnames array with userfullname and courseshortname (with link),
 361       * which will be used to render logs in table.
 362       */
 363      public function update_users_and_courses_used() {
 364          global $SITE, $DB;
 365  
 366          $this->userfullnames = array();
 367          $this->courseshortnames = array($SITE->id => $SITE->shortname);
 368          $userids = array();
 369          $courseids = array();
 370          // For each event cache full username and course.
 371          // Get list of userids and courseids which will be shown in log report.
 372          foreach ($this->rawdata as $event) {
 373              $logextra = $event->get_logextra();
 374              if (!empty($event->userid) && !in_array($event->userid, $userids)) {
 375                  $userids[] = $event->userid;
 376              }
 377              if (!empty($logextra['realuserid']) && !in_array($logextra['realuserid'], $userids)) {
 378                  $userids[] = $logextra['realuserid'];
 379              }
 380              if (!empty($event->relateduserid) && !in_array($event->relateduserid, $userids)) {
 381                  $userids[] = $event->relateduserid;
 382              }
 383  
 384              if (!empty($event->courseid) && ($event->courseid != $SITE->id) && !in_array($event->courseid, $courseids)) {
 385                  $courseids[] = $event->courseid;
 386              }
 387          }
 388  
 389          // Get user fullname and put that in return list.
 390          if (!empty($userids)) {
 391              list($usql, $uparams) = $DB->get_in_or_equal($userids);
 392              $userfieldsapi = \core_user\fields::for_name();
 393              $users = $DB->get_records_sql("SELECT id," .
 394                      $userfieldsapi->get_sql('', false, '', '', false)->selects . " FROM {user} WHERE id " . $usql,
 395                      $uparams);
 396              foreach ($users as $userid => $user) {
 397                  $this->userfullnames[$userid] = fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context()));
 398              }
 399          }
 400  
 401          // Get course shortname and put that in return list.
 402          if (!empty($courseids)) { // If all logs don't belog to site level then get course info.
 403              list($coursesql, $courseparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
 404              $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
 405              $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
 406              $courseparams['contextlevel'] = CONTEXT_COURSE;
 407              $sql = "SELECT c.id,c.shortname $ccselect FROM {course} c
 408                     $ccjoin
 409                       WHERE c.id " . $coursesql;
 410  
 411              $courses = $DB->get_records_sql($sql, $courseparams);
 412              foreach ($courses as $courseid => $course) {
 413                  $url = new moodle_url("/course/view.php", array('id' => $courseid));
 414                  context_helper::preload_from_record($course);
 415                  $context = context_course::instance($courseid, IGNORE_MISSING);
 416                  // Method format_string() takes care of missing contexts.
 417                  $this->courseshortnames[$courseid] = html_writer::link($url, format_string($course->shortname, true,
 418                          array('context' => $context)));
 419              }
 420          }
 421      }
 422  
 423      /**
 424       * Returns the latest timestamp of the records in the table.
 425       *
 426       * @return int
 427       */
 428      public function get_until(): int {
 429          $until = $this->filterparams->date;
 430          if (!empty($this->rawdata)) {
 431              foreach ($this->rawdata as $row) {
 432                  $until = max($row->timecreated, $until);
 433              }
 434          }
 435          return $until;
 436      }
 437  }