Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

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

   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   * Reports implementation
  19   *
  20   * @package    report
  21   * @subpackage stats
  22   * @copyright  1999 onwards Martin Dougiamas (http://dougiamas.com)
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  defined('MOODLE_INTERNAL') || die;
  27  
  28  require_once (__DIR__.'/lib.php');
  29  require_once($CFG->dirroot.'/lib/statslib.php');
  30  
  31  function report_stats_mode_menu($course, $mode, $time, $url) {
  32      global $CFG, $OUTPUT;
  33      /*
  34      $reportoptions = stats_get_report_options($course->id, $mode);
  35      $timeoptions = report_stats_timeoptions($mode);
  36      if (empty($timeoptions)) {
  37          throw new \moodle_exception('nostatstodisplay', '', $CFG->wwwroot.'/course/view.php?id='.$course->id);
  38      }
  39      */
  40  
  41      $options = array();
  42      $options[STATS_MODE_GENERAL] = get_string('statsmodegeneral');
  43      $options[STATS_MODE_DETAILED] = get_string('statsmodedetailed');
  44      if (has_capability('report/stats:view', context_system::instance())) {
  45          $options[STATS_MODE_RANKED] = get_string('reports');
  46      }
  47      $popupurl = $url."?course=$course->id&time=$time";
  48      $select = new single_select(new moodle_url($popupurl), 'mode', $options, $mode, null);
  49      $select->set_label(get_string('reports'), array('class' => 'accesshide'));
  50      $select->formid = 'switchmode';
  51      return $OUTPUT->render($select);
  52  }
  53  
  54  function report_stats_timeoptions($mode) {
  55      global $CFG, $DB;
  56  
  57      if ($mode == STATS_MODE_DETAILED) {
  58          $earliestday = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_user_daily}');
  59          $earliestweek = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_user_weekly}');
  60          $earliestmonth = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_user_monthly}');
  61      } else {
  62          $earliestday = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_daily}');
  63          $earliestweek = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_weekly}');
  64          $earliestmonth = $DB->get_field_sql('SELECT MIN(timeend) FROM {stats_monthly}');
  65      }
  66  
  67  
  68      if (empty($earliestday)) $earliestday = time();
  69      if (empty($earliestweek)) $earliestweek = time();
  70      if (empty($earliestmonth)) $earliestmonth = time();
  71  
  72      $now = stats_get_base_daily();
  73      $lastweekend = stats_get_base_weekly();
  74      $lastmonthend = stats_get_base_monthly();
  75  
  76      return stats_get_time_options($now,$lastweekend,$lastmonthend,$earliestday,$earliestweek,$earliestmonth);
  77  }
  78  
  79  function report_stats_report($course, $report, $mode, $user, $roleid, $time) {
  80      global $CFG, $DB, $OUTPUT;
  81  
  82      if ($user) {
  83          $userid = $user->id;
  84      } else {
  85          $userid = 0;
  86      }
  87  
  88      $fields = 'c.id,c.shortname,c.visible';
  89      $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
  90      $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
  91      $sortstatement = 'ORDER BY c.shortname';
  92  
  93      $sql = "SELECT $fields $ccselect FROM {course} c $ccjoin $sortstatement";
  94  
  95      $params = array();
  96      $params['contextlevel'] = CONTEXT_COURSE;
  97  
  98      $courses = $DB->get_recordset_sql($sql, $params);
  99  
 100      $courseoptions = array();
 101  
 102      foreach ($courses as $c) {
 103          context_helper::preload_from_record($c);
 104          $context = context_course::instance($c->id);
 105  
 106          if (has_capability('report/stats:view', $context)) {
 107              if (isset($c->visible) && $c->visible <= 0) {
 108                  // For hidden courses, require visibility check.
 109                  if (!has_capability('moodle/course:viewhiddencourses', $context)) {
 110                      continue;
 111                  }
 112              }
 113              $courseoptions[$c->id] = format_string($c->shortname, true, array('context' => $context));
 114          }
 115      }
 116  
 117      $courses->close();
 118  
 119      $reportoptions = stats_get_report_options($course->id, $mode);
 120      $timeoptions = report_stats_timeoptions($mode);
 121      if (empty($timeoptions)) {
 122          throw new \moodle_exception('nostatstodisplay', '', $CFG->wwwroot.'/course/view.php?id='.$course->id);
 123      }
 124  
 125      $users = array();
 126      $table = new html_table();
 127      $table->width = 'auto';
 128  
 129      if ($mode == STATS_MODE_DETAILED) {
 130          $param = stats_get_parameters($time, null, $course->id, $mode, $roleid); // We only care about the table and the time string (if we have time).
 131  
 132          list($sort, $moreparams) = users_order_by_sql('u');
 133          $moreparams['courseid'] = $course->id;
 134          $userfieldsapi = \core_user\fields::for_userpic()->including('idnumber');
 135          $fields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
 136          $sql = "SELECT DISTINCT $fields
 137                    FROM {stats_user_{$param->table}} s
 138                    JOIN {user} u ON u.id = s.userid
 139                   WHERE courseid = :courseid";
 140          if (!empty($param->stattype)) {
 141              $sql .= " AND stattype = :stattype";
 142              $moreparams['stattype'] = $param->stattype;
 143          }
 144          if (!empty($time)) {
 145              $sql .= " AND timeend >= :timeafter";
 146              $moreparams['timeafter'] = $param->timeafter;
 147          }
 148          $sql .= " ORDER BY {$sort}";
 149  
 150          if (!$us = $DB->get_records_sql($sql, array_merge($param->params, $moreparams))) {
 151              throw new \moodle_exception('nousers');
 152          }
 153          foreach ($us as $u) {
 154              $users[$u->id] = fullname($u, true);
 155          }
 156  
 157          $table->align = array('left','left','left','left','left','left','left','left');
 158          $table->data[] = array(html_writer::label(get_string('course'), 'menucourse'), html_writer::select($courseoptions, 'course', $course->id, false),
 159                                 html_writer::label(get_string('users'), 'menuuserid'), html_writer::select($users, 'userid', $userid, false),
 160                                 html_writer::label(get_string('statsreporttype'), 'menureport'), html_writer::select($reportoptions, 'report', ($report == 5) ? $report.$roleid : $report, false),
 161                                 html_writer::label(get_string('statstimeperiod'), 'menutime'), html_writer::select($timeoptions, 'time', $time, false),
 162                                 '<input type="submit" class="btn btn-secondary" value="'.get_string('view').'" />');
 163      } else if ($mode == STATS_MODE_RANKED) {
 164          $table->align = array('left','left','left','left','left','left');
 165          $table->data[] = array(html_writer::label(get_string('statsreporttype'), 'menureport'), html_writer::select($reportoptions, 'report', ($report == 5) ? $report.$roleid : $report, false),
 166                                 html_writer::label(get_string('statstimeperiod'), 'menutime'), html_writer::select($timeoptions, 'time', $time, false),
 167                                 '<input type="submit" class="btn btn-secondary" value="'.get_string('view').'" />');
 168      } else if ($mode == STATS_MODE_GENERAL) {
 169          $table->align = array('left','left','left','left','left','left','left');
 170          $table->data[] = array(html_writer::label(get_string('course'), 'menucourse'), html_writer::select($courseoptions, 'course', $course->id, false),
 171                                 html_writer::label(get_string('statsreporttype'), 'menureport'), html_writer::select($reportoptions, 'report', ($report == 5) ? $report.$roleid : $report, false),
 172                                 html_writer::label(get_string('statstimeperiod'), 'menutime'), html_writer::select($timeoptions, 'time', $time, false),
 173                                 '<input type="submit" class="btn btn-secondary" value="'.get_string('view').'" />');
 174      }
 175  
 176      echo '<form action="index.php" method="post">'."\n"
 177          .'<div>'."\n"
 178          .'<input type="hidden" name="mode" value="'.$mode.'" />'."\n";
 179  
 180      echo html_writer::table($table);
 181  
 182      echo '</div>';
 183      echo '</form>';
 184  
 185      // Display the report if:
 186      //  - A report has been selected.
 187      //  - A time frame has been provided
 188      //  - If the mode is not detailed OR a valid user has been selected.
 189      if (!empty($report) && !empty($time) && ($mode !== STATS_MODE_DETAILED || !empty($userid))) {
 190          if ($report == STATS_REPORT_LOGINS && $course->id != SITEID) {
 191              throw new \moodle_exception('reportnotavailable');
 192          }
 193  
 194          $param = stats_get_parameters($time, $report, $course->id, $mode, $roleid);
 195  
 196          if ($mode == STATS_MODE_DETAILED) {
 197              $param->table = 'user_'.$param->table;
 198          }
 199  
 200          if (!empty($param->sql)) {
 201              $sql = $param->sql;
 202          } else {
 203              //TODO: lceanup this ugly mess
 204              $sql = 'SELECT '.((empty($param->fieldscomplete)) ? 'id,roleid,timeend,' : '').$param->fields
 205                  .' FROM {stats_'.$param->table.'} WHERE '
 206                  .(($course->id == SITEID) ? '' : ' courseid = '.$course->id.' AND ')
 207                  .((!empty($userid)) ? ' userid = '.$userid.' AND ' : '')
 208                  .((!empty($roleid)) ? ' roleid = '.$roleid.' AND ' : '')
 209                  . ((!empty($param->stattype)) ? ' stattype = \''.$param->stattype.'\' AND ' : '')
 210                  .' timeend >= '.$param->timeafter
 211                  .' '.$param->extras
 212                  .' ORDER BY timeend DESC';
 213          }
 214  
 215          $stats = $DB->get_records_sql($sql);
 216  
 217          if (empty($stats)) {
 218              echo $OUTPUT->notification(get_string('statsnodata'));
 219  
 220          } else {
 221  
 222              $stats = stats_fix_zeros($stats,$param->timeafter,$param->table,(!empty($param->line2)));
 223  
 224              $rolename = '';
 225              $userdisplayname = '';
 226              $coursecontext = context_course::instance($course->id);
 227  
 228              if (!empty($roleid) && $role = $DB->get_record('role', ['id' => $roleid])) {
 229                  $rolename = ' ' . role_get_name($role, $coursecontext);
 230              }
 231              if (!empty($user)) {
 232                  $userdisplayname = ' ' . fullname($user, true);
 233              }
 234              echo $OUTPUT->heading(
 235                  format_string($course->shortname) .
 236                  ' - ' .
 237                  get_string('statsreport' . $report) .
 238                  $rolename .
 239                  $userdisplayname, 3
 240              );
 241  
 242              if ($mode == STATS_MODE_DETAILED) {
 243                  report_stats_print_chart($course->id, $report, $time, $mode, $userid);
 244              } else {
 245                  report_stats_print_chart($course->id, $report, $time, $mode, null, $roleid);
 246              }
 247  
 248              $table = new html_table();
 249              $table->align = array('left','center','center','center');
 250              $param->table = str_replace('user_','',$param->table);
 251              switch ($param->table) {
 252                  case 'daily'  : $period = get_string('day'); break;
 253                  case 'weekly' : $period = get_string('week'); break;
 254                  case 'monthly': $period = get_string('month', 'form'); break;
 255                  default : $period = '';
 256              }
 257              $table->head = array(get_string('periodending','moodle',$period));
 258              if (empty($param->crosstab)) {
 259                  $table->head[] = $param->line1;
 260                  if (!empty($param->line2)) {
 261                      $table->head[] = $param->line2;
 262                  }
 263              }
 264              if (!file_exists($CFG->dirroot.'/report/log/index.php')) {
 265                  // bad luck, we can not link other report
 266              } else if (empty($param->crosstab)) {
 267                  foreach  ($stats as $stat) {
 268                      $a = array(userdate($stat->timeend - DAYSECS, get_string('strftimedate'), $CFG->timezone),
 269                              $stat->line1);
 270                      if (isset($stat->line2)) {
 271                          $a[] = $stat->line2;
 272                      }
 273                      if (empty($CFG->loglifetime) || ($stat->timeend-(60*60*24)) >= (time()-60*60*24*$CFG->loglifetime)) {
 274                          if (has_capability('report/log:view', context_course::instance($course->id))) {
 275                              $a[] = '<a href="'.$CFG->wwwroot.'/report/log/index.php?id='.
 276                                  $course->id.'&amp;chooselog=1&amp;showusers=1&amp;showcourses=1&amp;user='
 277                                  .$userid.'&amp;date='.usergetmidnight($stat->timeend-(60*60*24)).'">'
 278                                  .get_string('course').' ' .get_string('logs').'</a>&nbsp;';
 279                          } else {
 280                              $a[] = '';
 281                          }
 282                      }
 283                      $table->data[] = $a;
 284                  }
 285              } else {
 286                  $data = array();
 287                  $roles = array();
 288                  $times = array();
 289                  $missedlines = array();
 290                  $coursecontext = context_course::instance($course->id);
 291                  $rolenames = get_viewable_roles($coursecontext);
 292                  foreach ($stats as $stat) {
 293                      if (!empty($stat->zerofixed)) {
 294                          $missedlines[] = $stat->timeend;
 295                      }
 296                      $data[$stat->timeend][$stat->roleid] = $stat->line1;
 297                      if ($stat->roleid != 0) {
 298                          if (!array_key_exists($stat->roleid, $roles) && array_key_exists($stat->roleid, $rolenames)) {
 299                              $roles[$stat->roleid] = $rolenames[$stat->roleid];
 300                          }
 301                      } else {
 302                          if (!array_key_exists($stat->roleid,$roles)) {
 303                              $roles[$stat->roleid] = get_string('all');
 304                          }
 305                      }
 306                      if (!array_key_exists($stat->timeend,$times)) {
 307                          $times[$stat->timeend] = userdate($stat->timeend - DAYSECS, get_string('strftimedate'),
 308                                  $CFG->timezone);
 309                      }
 310                  }
 311  
 312                  foreach ($data as $time => $rolesdata) {
 313                      if (in_array($time,$missedlines)) {
 314                          $rolesdata = array();
 315                          foreach ($roles as $roleid => $guff) {
 316                              $rolesdata[$roleid] = 0;
 317                          }
 318                      }
 319                      else {
 320                          foreach (array_keys($roles) as $r) {
 321                              if (!array_key_exists($r, $rolesdata)) {
 322                                  $rolesdata[$r] = 0;
 323                              }
 324                          }
 325                      }
 326                      krsort($rolesdata);
 327                      $row = array_merge(array($times[$time]),$rolesdata);
 328                      if (empty($CFG->loglifetime) || ($stat->timeend-(60*60*24)) >= (time()-60*60*24*$CFG->loglifetime)) {
 329                          if (has_capability('report/log:view', context_course::instance($course->id))) {
 330                              $row[] = '<a href="'.$CFG->wwwroot.'/report/log/index.php?id='
 331                                  .$course->id.'&amp;chooselog=1&amp;showusers=1&amp;showcourses=1&amp;user='.$userid
 332                                  .'&amp;date='.usergetmidnight($time-(60*60*24)).'">'
 333                                  .get_string('course').' ' .get_string('logs').'</a>&nbsp;';
 334                          } else {
 335                              $row[] = '';
 336                          }
 337                      }
 338                      $table->data[] = $row;
 339                  }
 340                  krsort($roles);
 341                  $table->head = array_merge($table->head,$roles);
 342              }
 343              $table->head[] = get_string('logs');
 344              //if (!empty($lastrecord)) {
 345                  //$lastrecord[] = $lastlink;
 346                  //$table->data[] = $lastrecord;
 347              //}
 348              echo html_writer::table($table);
 349          }
 350      }
 351  }
 352  
 353  /**
 354   * Fetch statistics data and generate a line chart.
 355   *
 356   * The statistic chart can be view, posts separated by roles and dates.
 357   *
 358   * @param int $courseid course id.
 359   * @param int $report the report type constant eg. STATS_REPORT_LOGINS as defined on statslib.
 360   * @param int $time timestamp of the selected time period.
 361   * @param int $mode the report mode, eg. STATS_MODE_DETAILED as defined on statslib.
 362   * @param int $userid selected user id.
 363   * @param int $roleid selected role id.
 364   */
 365  function report_stats_print_chart($courseid, $report, $time, $mode, $userid = 0, $roleid = 0) {
 366      global $DB, $CFG, $OUTPUT;
 367  
 368      $course = $DB->get_record("course", array("id" => $courseid), '*', MUST_EXIST);
 369      $coursecontext = context_course::instance($course->id);
 370  
 371      stats_check_uptodate($course->id);
 372  
 373      $param = stats_get_parameters($time, $report, $course->id, $mode, $roleid);
 374  
 375      if (!empty($userid)) {
 376          $param->table = 'user_' . $param->table;
 377      }
 378  
 379      // TODO: cleanup this ugly mess.
 380      $sql = 'SELECT '.((empty($param->fieldscomplete)) ? 'id,roleid,timeend,' : '').$param->fields
 381          .' FROM {stats_'.$param->table.'} WHERE '
 382          .(($course->id == SITEID) ? '' : ' courseid = '.$course->id.' AND ')
 383          .((!empty($userid)) ? ' userid = '.$userid.' AND ' : '')
 384          .((!empty($roleid)) ? ' roleid = '.$roleid.' AND ' : '')
 385          . ((!empty($param->stattype)) ? ' stattype = \''.$param->stattype.'\' AND ' : '')
 386          .' timeend >= '.$param->timeafter
 387          .' '.$param->extras
 388          .' ORDER BY timeend DESC';
 389      $stats = $DB->get_records_sql($sql, $param->params);
 390      $stats = stats_fix_zeros($stats, $param->timeafter, $param->table, (!empty($param->line2)),
 391              (!empty($param->line3)));
 392      $stats = array_reverse($stats);
 393  
 394      $chart = new \core\chart_line();
 395      if (empty($param->crosstab)) {
 396          $data = [];
 397          $times = [];
 398          foreach ($stats as $stat) {
 399              // Build the array of formatted times indexed by timestamp used as labels.
 400              if (!array_key_exists($stat->timeend, $times)) {
 401                  $times[$stat->timeend] = userdate($stat->timeend - DAYSECS, get_string('strftimedate'), $CFG->timezone);
 402  
 403                  // Just add the data if the time hasn't been added yet.
 404                  // The number of lines of data must match the number of labels.
 405                  $data['line1'][] = $stat->line1;
 406                  if (isset($stat->line2)) {
 407                      $data['line2'][] = $stat->line2;
 408                  }
 409                  if (isset($stat->line3)) {
 410                      $data['line3'][] = $stat->line3;
 411                  }
 412              }
 413          }
 414          foreach ($data as $line => $serie) {
 415              $series = new \core\chart_series($param->{$line}, array_values($serie));
 416              $chart->add_series($series);
 417          }
 418      } else {
 419          $data = array();
 420          $times = array();
 421          $roles = array();
 422          $missedlines = array();
 423          $rolenames = get_viewable_roles($coursecontext);
 424  
 425          foreach ($stats as $stat) {
 426              $data[$stat->roleid][$stat->timeend] = $stat->line1;
 427              if (!empty($stat->zerofixed)) {
 428                  $missedlines[] = $stat->timeend;
 429              }
 430              if ($stat->roleid != 0) {
 431                  if (!array_key_exists($stat->roleid, $roles) && array_key_exists($stat->roleid, $rolenames)) {
 432                      $roles[$stat->roleid] = $rolenames[$stat->roleid];
 433                  }
 434              } else {
 435                  if (!array_key_exists($stat->roleid, $roles)) {
 436                      $roles[$stat->roleid] = get_string('all');
 437                  }
 438              }
 439  
 440              // Build the array of formatted times indexed by timestamp used as labels.
 441              if (!array_key_exists($stat->timeend, $times)) {
 442                  $times[$stat->timeend] = userdate($stat->timeend - DAYSECS, get_string('strftimedate'), $CFG->timezone);
 443              }
 444          }
 445          // Fill empty days with zero to avoid chart errors.
 446          foreach (array_keys($times) as $t) {
 447              foreach ($data as $roleid => $stuff) {
 448                  if (!array_key_exists($t, $stuff)) {
 449                      $data[$roleid][$t] = 0;
 450                  }
 451              }
 452          }
 453          krsort($roles);
 454          foreach ($roles as $roleid => $rolename) {
 455              ksort($data[$roleid]);
 456              $series = new \core\chart_series($rolename, array_values($data[$roleid]));
 457              $chart->add_series($series);
 458          }
 459      }
 460      $chart->set_labels(array_values($times));
 461      echo $OUTPUT->render_chart($chart, false);
 462  }