first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
@@ -0,0 +1,74 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* The report_loglive report viewed event.
*
* @package report_loglive
* @copyright 2013 Ankit Agarwal
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace report_loglive\event;
defined('MOODLE_INTERNAL') || die();
/**
* The report_loglive report viewed event class.
*
* @package report_loglive
* @since Moodle 2.7
* @copyright 2013 Ankit Agarwal
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class report_viewed extends \core\event\base {
/**
* Init method.
*
* @return void
*/
protected function init() {
$this->data['crud'] = 'r';
$this->data['edulevel'] = self::LEVEL_OTHER;
}
/**
* Return localised event name.
*
* @return string
*/
public static function get_name() {
return get_string('eventreportviewed', 'report_loglive');
}
/**
* Returns description of what happened.
*
* @return string
*/
public function get_description() {
return "The user with id '$this->userid' viewed the live log report for the course with id '$this->courseid'.";
}
/**
* Returns relevant URL.
*
* @return \moodle_url
*/
public function get_url() {
return new \moodle_url('/report/loglive/index.php', array('id' => $this->courseid));
}
}
@@ -0,0 +1,46 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for report_loglive.
*
* @package report_loglive
* @copyright 2018 Zig Tan <zig@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace report_loglive\privacy;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for report_loglive implementing null_provider.
*
* @copyright 2018 Zig Tan <zig@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason(): string {
return 'privacy:metadata';
}
}
+233
View File
@@ -0,0 +1,233 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Loglive report renderable class.
*
* @package report_loglive
* @copyright 2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* Report loglive renderable class.
*
* @since Moodle 2.7
* @package report_loglive
* @copyright 2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class report_loglive_renderable implements renderable {
/** @var int number of seconds to show logs from, by default. */
const CUTOFF = 3600;
/** @var \core\log\manager log manager */
protected $logmanager;
/** @var string selected log reader pluginname */
public $selectedlogreader = null;
/** @var int page number */
public $page;
/** @var int perpage records to show */
public $perpage;
/** @var stdClass course record */
public $course;
/** @var moodle_url url of report page */
public $url;
/** @var int selected date from which records should be displayed */
public $date;
/** @var string order to sort */
public $order;
/** @var int group id */
public $groupid;
/** @var report_loglive_table_log table log which will be used for rendering logs */
public $tablelog;
/** @var int refresh rate in seconds */
protected $refresh = 60;
/**
* Constructor.
*
* @param string $logreader (optional)reader pluginname from which logs will be fetched.
* @param stdClass|int $course (optional) course record or id
* @param moodle_url|string $url (optional) page url.
* @param int $date date (optional) from which records will be fetched.
* @param int $page (optional) page number.
* @param int $perpage (optional) number of records to show per page.
* @param string $order (optional) sortorder of fetched records
*/
public function __construct($logreader = "", $course = 0, $url = "", $date = 0, $page = 0, $perpage = 100,
$order = "timecreated DESC") {
global $PAGE;
// Use first reader as selected reader, if not passed.
if (empty($logreader)) {
$readers = $this->get_readers();
if (!empty($readers)) {
reset($readers);
$logreader = key($readers);
} else {
$logreader = null;
}
}
$this->selectedlogreader = $logreader;
// Use page url if empty.
if (empty($url)) {
$url = new moodle_url($PAGE->url);
} else {
$url = new moodle_url($url);
}
$this->url = $url;
// Use site course id, if course is empty.
if (!empty($course) && is_int($course)) {
$course = get_course($course);
}
$this->course = $course;
if ($date == 0 ) {
$date = time() - self::CUTOFF;
}
$this->date = $date;
$this->page = $page;
$this->perpage = $perpage;
$this->order = $order;
$this->set_refresh_rate();
}
/**
* Get a list of enabled sql_reader objects/name
*
* @param bool $nameonly if true only reader names will be returned.
*
* @return array core\log\sql_reader object or name.
*/
public function get_readers($nameonly = false) {
if (!isset($this->logmanager)) {
$this->logmanager = get_log_manager();
}
$readers = $this->logmanager->get_readers('core\log\sql_reader');
if ($nameonly) {
foreach ($readers as $pluginname => $reader) {
$readers[$pluginname] = $reader->get_name();
}
}
return $readers;
}
/**
* Setup table log.
*/
protected function setup_table() {
$filter = $this->setup_filters();
$this->tablelog = new report_loglive_table_log('report_loglive', $filter);
$this->tablelog->define_baseurl($this->url);
}
/**
* Setup table log for ajax output.
*/
protected function setup_table_ajax() {
$filter = $this->setup_filters();
$this->tablelog = new report_loglive_table_log_ajax('report_loglive', $filter);
$this->tablelog->define_baseurl($this->url);
}
/**
* Setup filters
*
* @return stdClass filters
*/
protected function setup_filters() {
$readers = $this->get_readers();
// Set up filters.
$filter = new \stdClass();
if (!empty($this->course)) {
$filter->courseid = $this->course->id;
$context = context_course::instance($filter->courseid);
if (!has_capability('moodle/site:viewanonymousevents', $context)) {
$filter->anonymous = 0;
}
} else {
$filter->courseid = 0;
}
$filter->logreader = $readers[$this->selectedlogreader];
$filter->date = $this->date;
$filter->orderby = $this->order;
return $filter;
}
/**
* Set refresh rate of the live updates.
*/
protected function set_refresh_rate() {
if (defined('BEHAT_SITE_RUNNING')) {
// Hack for behat tests.
$this->refresh = 5;
} else {
if (defined('REPORT_LOGLIVE_REFRESH')) {
// Backward compatibility.
$this->refresh = REPORT_LOGLIVE_REFRESH;
} else {
// Default.
$this->refresh = 60;
}
}
}
/**
* Get refresh rate of the live updates.
*/
public function get_refresh_rate() {
return $this->refresh;
}
/**
* Setup table and return it.
*
* @param bool $ajax If set to true report_loglive_table_log_ajax is set instead of report_loglive_table_log.
*
* @return report_loglive_table_log|report_loglive_table_log_ajax table object
*/
public function get_table($ajax = false) {
if (empty($this->tablelog)) {
if ($ajax) {
$this->setup_table_ajax();
} else {
$this->setup_table();
}
}
return $this->tablelog;
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Loglive report renderer.
*
* @package report_loglive
* @copyright 2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* Report log renderer's for printing reports.
*
* @since Moodle 2.7
* @package report_loglive
* @copyright 2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class report_loglive_renderer extends plugin_renderer_base {
/**
* This method should never be manually called, it should only be called by process.
* Please call the render method instead.
*
* @deprecated since 2.8, to be removed in 2.9
* @param report_loglive_renderable $reportloglive
* @return string
*/
public function render_report_loglive_renderable(report_loglive_renderable $reportloglive) {
debugging('Do not call this method. Please call $renderer->render($reportloglive) instead.', DEBUG_DEVELOPER);
return $this->render($reportloglive);
}
/**
* Return html to render the loglive page..
*
* @param report_loglive_renderable $reportloglive object of report_log.
*
* @return string html used to render the page;
*/
protected function render_report_loglive(report_loglive_renderable $reportloglive) {
if (empty($reportloglive->selectedlogreader)) {
return $this->output->notification(get_string('nologreaderenabled', 'report_loglive'), 'notifyproblem');
}
$table = $reportloglive->get_table();
return $this->render_table($table, $reportloglive->perpage);
}
/**
* Prints/return reader selector
*
* @param report_loglive_renderable $reportloglive log report.
*
* @return string Returns rendered widget
*/
public function reader_selector(report_loglive_renderable $reportloglive) {
$readers = $reportloglive->get_readers(true);
if (count($readers) <= 1) {
// One or no readers found, no need of this drop down.
return '';
}
$select = new single_select($reportloglive->url, 'logreader', $readers, $reportloglive->selectedlogreader, null);
$select->set_label(get_string('selectlogreader', 'report_loglive'));
return $this->output->render($select);
}
/**
* Prints a button to update/resume live updates.
*
* @param report_loglive_renderable $reportloglive log report.
*
* @return string Returns rendered widget
*/
public function toggle_liveupdate_button(report_loglive_renderable $reportloglive) {
// Add live log controls.
if ($reportloglive->page == 0 && $reportloglive->selectedlogreader) {
echo html_writer::tag('button' , get_string('pause', 'report_loglive'),
array('id' => 'livelogs-pause-button', 'class' => 'btn btn-secondary'));
$icon = new pix_icon('i/loading_small', 'loading', 'moodle', array('class' => 'spinner'));
return html_writer::tag('span', $this->output->render($icon), array('class' => 'spinner'));
}
return '';
}
/**
* Get the html for the table.
*
* @param report_loglive_table_log $table table object.
* @param int $perpage entries to display perpage.
*
* @return string table html
*/
protected function render_table(report_loglive_table_log $table, $perpage) {
$o = '';
ob_start();
$table->out($perpage, true);
$o = ob_get_contents();
ob_end_clean();
return $o;
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Log live report ajax renderer.
*
* @package report_loglive
* @copyright 2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Log live report ajax renderer.
*
* @since Moodle 2.7
* @package report_loglive
* @copyright 2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class report_loglive_renderer_ajax extends plugin_renderer_base {
/**
* This method should never be manually called, it should only be called by process.
* Please call the render method instead.
*
* @deprecated since 2.8, to be removed in 2.9
* @param report_loglive_renderable $reportloglive
* @return string
*/
public function render_report_loglive_renderable(report_loglive_renderable $reportloglive) {
debugging('Do not call this method. Please call $renderer->render($reportloglive) instead.', DEBUG_DEVELOPER);
return $this->render($reportloglive);
}
/**
* Render logs for ajax.
*
* @param report_loglive_renderable $reportloglive object of report_loglive_renderable.
*
* @return string html to be displayed to user.
*/
protected function render_report_loglive(report_loglive_renderable $reportloglive) {
if (empty($reportloglive->selectedlogreader)) {
return null;
}
$table = $reportloglive->get_table(true);
return $table->out($reportloglive->perpage, false);
}
}
+441
View File
@@ -0,0 +1,441 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Table log for displaying logs.
*
* @package report_loglive
* @copyright 2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
require_once($CFG->libdir . '/tablelib.php');
/**
* Table log class for displaying logs.
*
* @since Moodle 2.7
* @package report_loglive
* @copyright 2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class report_loglive_table_log extends table_sql {
/** @var array list of user fullnames shown in report */
protected $userfullnames = array();
/** @var array list of course short names shown in report */
protected $courseshortnames = array();
/** @var array list of context name shown in report */
protected $contextname = array();
/** @var stdClass filters parameters */
protected $filterparams;
/** @var int[] A list of users to filter by */
private ?array $lateuseridfilter = null;
/**
* Sets up the table_log parameters.
*
* @param string $uniqueid unique id of form.
* @param stdClass $filterparams (optional) filter params.
* - int courseid: id of course
* - int userid: user id
* - int|string modid: Module id or "site_errors" to view site errors
* - int groupid: Group id
* - \core\log\sql_reader logreader: reader from which data will be fetched.
* - int edulevel: educational level.
* - string action: view action
* - int date: Date from which logs to be viewed.
*/
public function __construct($uniqueid, $filterparams = null) {
parent::__construct($uniqueid);
$this->set_attribute('class', 'reportloglive generaltable table-sm');
$this->set_attribute('aria-live', 'polite');
$this->filterparams = $filterparams;
// Add course column if logs are displayed for site.
$cols = array();
$headers = array();
if (empty($filterparams->courseid)) {
$cols = array('course');
$headers = array(get_string('course'));
}
$this->define_columns(array_merge($cols, array('time', 'fullnameuser', 'relatedfullnameuser', 'context', 'component',
'eventname', 'description', 'origin', 'ip')));
$this->define_headers(array_merge($headers, array(
get_string('time'),
get_string('fullnameuser'),
get_string('eventrelatedfullnameuser', 'report_loglive'),
get_string('eventcontext', 'report_loglive'),
get_string('eventcomponent', 'report_loglive'),
get_string('eventname'),
get_string('description'),
get_string('eventorigin', 'report_loglive'),
get_string('ip_address')
)
));
$this->collapsible(false);
$this->sortable(false);
$this->pageable(true);
$this->is_downloadable(false);
}
/**
* Generate the course column.
*
* @param stdClass $event event data.
* @return string HTML for the course column.
*/
public function col_course($event) {
if (empty($event->courseid) || empty($this->courseshortnames[$event->courseid])) {
return '-';
} else {
return $this->courseshortnames[$event->courseid];
}
}
/**
* Generate the time column.
*
* @param stdClass $event event data.
* @return string HTML for the time column
*/
public function col_time($event) {
$recenttimestr = get_string('strftimedatetimeaccurate', 'core_langconfig');
return userdate($event->timecreated, $recenttimestr);
}
/**
* Generate the username column.
*
* @param stdClass $event event data.
* @return string HTML for the username column
*/
public function col_fullnameuser($event) {
// Get extra event data for origin and realuserid.
$logextra = $event->get_logextra();
// Add username who did the action.
if (!empty($logextra['realuserid'])) {
$a = new stdClass();
$params = array('id' => $logextra['realuserid']);
if ($event->courseid) {
$params['course'] = $event->courseid;
}
$a->realusername = html_writer::link(new moodle_url("/user/view.php", $params),
$this->userfullnames[$logextra['realuserid']]);
$params['id'] = $event->userid;
$a->asusername = html_writer::link(new moodle_url("/user/view.php", $params),
$this->userfullnames[$event->userid]);
$username = get_string('eventloggedas', 'report_loglive', $a);
} else if (!empty($event->userid) && !empty($this->userfullnames[$event->userid])) {
$params = array('id' => $event->userid);
if ($event->courseid) {
$params['course'] = $event->courseid;
}
$username = html_writer::link(new moodle_url("/user/view.php", $params), $this->userfullnames[$event->userid]);
} else {
$username = '-';
}
return $username;
}
/**
* Generate the related username column.
*
* @param stdClass $event event data.
* @return string HTML for the related username column
*/
public function col_relatedfullnameuser($event) {
// Add affected user.
if (!empty($event->relateduserid) && isset($this->userfullnames[$event->relateduserid])) {
$params = array('id' => $event->relateduserid);
if ($event->courseid) {
$params['course'] = $event->courseid;
}
return html_writer::link(new moodle_url("/user/view.php", $params), $this->userfullnames[$event->relateduserid]);
} else {
return '-';
}
}
/**
* Generate the context column.
*
* @param stdClass $event event data.
* @return string HTML for the context column
*/
public function col_context($event) {
// Add context name.
if ($event->contextid) {
// If context name was fetched before then return, else get one.
if (isset($this->contextname[$event->contextid])) {
return $this->contextname[$event->contextid];
} else {
$context = context::instance_by_id($event->contextid, IGNORE_MISSING);
if ($context) {
$contextname = $context->get_context_name(true);
if ($url = $context->get_url()) {
$contextname = html_writer::link($url, $contextname);
}
} else {
$contextname = get_string('other');
}
}
} else {
$contextname = get_string('other');
}
$this->contextname[$event->contextid] = $contextname;
return $contextname;
}
/**
* Generate the component column.
*
* @param stdClass $event event data.
* @return string HTML for the component column
*/
public function col_component($event) {
// Component.
$componentname = $event->component;
if (($event->component === 'core') || ($event->component === 'legacy')) {
return get_string('coresystem');
} else if (get_string_manager()->string_exists('pluginname', $event->component)) {
return get_string('pluginname', $event->component);
} else {
return $componentname;
}
}
/**
* Generate the event name column.
*
* @param stdClass $event event data.
* @return string HTML for the event name column
*/
public function col_eventname($event) {
$eventname = $event->get_name();
if ($url = $event->get_url()) {
$eventname = $this->action_link($url, $eventname, 'action');
}
return $eventname;
}
/**
* Generate the description column.
*
* @param stdClass $event event data.
* @return string HTML for the description column
*/
public function col_description($event) {
// Description.
return $event->get_description();
}
/**
* Generate the origin column.
*
* @param stdClass $event event data.
* @return string HTML for the origin column
*/
public function col_origin($event) {
// Get extra event data for origin and realuserid.
$logextra = $event->get_logextra();
// Add event origin, normally IP/cron.
return $logextra['origin'];
}
/**
* Generate the ip column.
*
* @param stdClass $event event data.
* @return string HTML for the ip column
*/
public function col_ip($event) {
// Get extra event data for origin and realuserid.
$logextra = $event->get_logextra();
$url = new moodle_url("/iplookup/index.php?popup=1&ip={$logextra['ip']}&user=$event->userid");
return $this->action_link($url, $logextra['ip'], 'ip');
}
/**
* Method to create a link with popup action.
*
* @param moodle_url $url The url to open.
* @param string $text Anchor text for the link.
* @param string $name Name of the popup window.
*
* @return string html to use.
*/
protected function action_link(moodle_url $url, $text, $name = 'popup') {
global $OUTPUT;
$link = new action_link($url, $text, new popup_action('click', $url, $name, array('height' => 550, 'width' => 700)));
return $OUTPUT->render($link);
}
/**
* Query the reader. Store results in the object for use by build_table.
*
* @param int $pagesize size of page for paginated displayed table.
* @param bool $useinitialsbar do you want to use the initials bar.
*/
public function query_db($pagesize, $useinitialsbar = true) {
$joins = [];
$params = [];
if (!empty($this->filterparams->courseid)) {
$joins[] = "courseid = :courseid";
$params['courseid'] = $this->filterparams->courseid;
}
// Getting all members of a group.
[
'joins' => $groupjoins,
'params' => $groupparams,
'useridfilter' => $this->lateuseridfilter,
] = \core\report_helper::get_group_filter($this->filterparams);
$joins = array_merge($joins, $groupjoins);
$params = array_merge($params, $groupparams);
if (!empty($this->filterparams->date)) {
$joins[] = "timecreated > :date";
$params['date'] = $this->filterparams->date;
}
if (isset($this->filterparams->anonymous)) {
$joins[] = "anonymous = :anon";
$params['anon'] = $this->filterparams->anonymous;
}
$selector = implode(' AND ', $joins);
$total = $this->filterparams->logreader->get_events_select_count($selector, $params);
$this->pagesize($pagesize, $total);
$this->rawdata =
array_filter(
$this->filterparams->logreader->get_events_select(
$selector,
$params,
$this->filterparams->orderby,
$this->get_page_start(),
$this->get_page_size(),
),
function($event) {
if ($this->lateuseridfilter === null) {
return true;
}
return isset($this->lateuseridfilter[$event->userid]);
},
);
// Set initial bars.
if ($useinitialsbar) {
$this->initialbars($total > $pagesize);
}
// Update list of users and courses list which will be displayed on log page.
$this->update_users_and_courses_used();
}
/**
* Helper function to create list of course shortname and user fullname shown in log report.
* This will update $this->userfullnames and $this->courseshortnames array with userfullname and courseshortname (with link),
* which will be used to render logs in table.
*/
public function update_users_and_courses_used() {
global $SITE, $DB;
$this->userfullnames = array();
$this->courseshortnames = array($SITE->id => $SITE->shortname);
$userids = array();
$courseids = array();
// For each event cache full username and course.
// Get list of userids and courseids which will be shown in log report.
foreach ($this->rawdata as $event) {
$logextra = $event->get_logextra();
if (!empty($event->userid) && !in_array($event->userid, $userids)) {
$userids[] = $event->userid;
}
if (!empty($logextra['realuserid']) && !in_array($logextra['realuserid'], $userids)) {
$userids[] = $logextra['realuserid'];
}
if (!empty($event->relateduserid) && !in_array($event->relateduserid, $userids)) {
$userids[] = $event->relateduserid;
}
if (!empty($event->courseid) && ($event->courseid != $SITE->id) && !in_array($event->courseid, $courseids)) {
$courseids[] = $event->courseid;
}
}
// Get user fullname and put that in return list.
if (!empty($userids)) {
list($usql, $uparams) = $DB->get_in_or_equal($userids);
$userfieldsapi = \core_user\fields::for_name();
$users = $DB->get_records_sql("SELECT id," .
$userfieldsapi->get_sql('', false, '', '', false)->selects . " FROM {user} WHERE id " . $usql,
$uparams);
foreach ($users as $userid => $user) {
$this->userfullnames[$userid] = fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context()));
}
}
// Get course shortname and put that in return list.
if (!empty($courseids)) { // If all logs don't belog to site level then get course info.
list($coursesql, $courseparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
$ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
$ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
$courseparams['contextlevel'] = CONTEXT_COURSE;
$sql = "SELECT c.id,c.shortname $ccselect FROM {course} c
$ccjoin
WHERE c.id " . $coursesql;
$courses = $DB->get_records_sql($sql, $courseparams);
foreach ($courses as $courseid => $course) {
$url = new moodle_url("/course/view.php", array('id' => $courseid));
context_helper::preload_from_record($course);
$context = context_course::instance($courseid, IGNORE_MISSING);
// Method format_string() takes care of missing contexts.
$this->courseshortnames[$courseid] = html_writer::link($url, format_string($course->shortname, true,
array('context' => $context)));
}
}
}
/**
* Returns the latest timestamp of the records in the table.
*
* @return int
*/
public function get_until(): int {
$until = $this->filterparams->date;
if (!empty($this->rawdata)) {
foreach ($this->rawdata as $row) {
$until = max($row->timecreated, $until);
}
}
return $until;
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Table log for generating data in ajax mode.
*
* @package report_loglive
* @copyright 2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* Table log class for generating data in ajax mode.
*
* @since Moodle 2.7
* @package report_loglive
* @copyright 2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class report_loglive_table_log_ajax extends report_loglive_table_log {
/**
* Convenience method to call a number of methods for you to display the
* table.
*
* @param int $pagesize pagesize
* @param bool $useinitialsbar Not used, present only for compatibility with parent.
* @param string $downloadhelpbutton Not used, present only for compatibility with parent.
*
* @return string json encoded data containing html of new rows.
*/
public function out($pagesize, $useinitialsbar, $downloadhelpbutton = '') {
$this->query_db($pagesize, false);
$html = '';
if ($this->rawdata && $this->columns) {
foreach ($this->rawdata as $row) {
$formatedrow = $this->format_row($row);
$formatedrow = $this->get_row_from_keyed($formatedrow);
$html .= $this->get_row_html($formatedrow, 'newrow');
}
}
$result = array('logs' => $html, 'until' => $this->get_until());
return json_encode($result);
}
/**
* Popup actions do not function when they are rendered in response to an AJAX request, encode within the link itself
*
* @param moodle_url $url
* @param string $text
* @param string $name
* @return string
*/
protected function action_link(moodle_url $url, $text, $name = 'popup') {
global $OUTPUT;
$link = new action_link($url, $text, null, [
'data-action' => 'action-popup',
'data-popup-action' => json_encode(
new popup_action('click', $url, $name, ['height' => 440, 'width' => 700])
),
]);
return $OUTPUT->render($link);
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Capabilities
*
* This files lists capabilites related to report_logline
*
* @package report_loglive
* @copyright 2011 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$capabilities = array(
'report/loglive:view' => array(
'riskbitmask' => RISK_PERSONAL,
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'archetypes' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'manager' => CAP_ALLOW
),
),
);
+102
View File
@@ -0,0 +1,102 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Displays live view of recent logs
*
* This file generates live view of recent logs.
*
* @package report_loglive
* @copyright 2011 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use core\report_helper;
require('../../config.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->dirroot.'/course/lib.php');
$id = optional_param('id', 0, PARAM_INT);
$page = optional_param('page', 0, PARAM_INT);
$logreader = optional_param('logreader', '', PARAM_COMPONENT); // Reader which will be used for displaying logs.
if (empty($id)) {
admin_externalpage_setup('reportloglive', '', null, '', array('pagelayout' => 'report'));
$context = context_system::instance();
$coursename = format_string($SITE->fullname, true, array('context' => $context));
} else {
$course = get_course($id);
require_login($course);
$context = context_course::instance($course->id);
$coursename = format_string($course->fullname, true, array('context' => $context));
}
require_capability('report/loglive:view', $context);
$params = array();
if ($id != 0) {
$params['id'] = $id;
}
if ($page != 0) {
$params['page'] = $page;
}
if ($logreader !== '') {
$params['logreader'] = $logreader;
}
$url = new moodle_url("/report/loglive/index.php", $params);
$PAGE->set_url($url);
$PAGE->set_pagelayout('report');
$renderable = new report_loglive_renderable($logreader, $id, $url, 0, $page);
$refresh = $renderable->get_refresh_rate();
$logreader = $renderable->selectedlogreader;
$strlivelogs = get_string('livelogs', 'report_loglive');
$strupdatesevery = get_string('updatesevery', 'moodle', $refresh);
$PAGE->set_url($url);
$PAGE->set_context($context);
$PAGE->set_title("$coursename: $strlivelogs");
$PAGE->set_heading($coursename);
$output = $PAGE->get_renderer('report_loglive');
echo $output->header();
// Print selector dropdown.
$pluginname = get_string('pluginname', 'report_loglive');
report_helper::print_report_selector($pluginname);
echo html_writer::div(get_string('livelogswithupdate', 'report_loglive', $strupdatesevery), 'mb-3');
echo $output->reader_selector($renderable);
echo $output->toggle_liveupdate_button($renderable);
echo $output->render($renderable);
// Include and trigger ajax requests.
if ($page == 0 && !empty($logreader)) {
// Tell Js to fetch new logs only, by passing the latest timestamp of records in the table.
$until = $renderable->get_table()->get_until();
$jsparams = array('since' => $until , 'courseid' => $id, 'page' => $page, 'logreader' => $logreader,
'interval' => $refresh, 'perpage' => $renderable->perpage);
$PAGE->requires->strings_for_js(array('pause', 'resume'), 'report_loglive');
$PAGE->requires->yui_module('moodle-report_loglive-fetchlogs', 'Y.M.report_loglive.FetchLogs.init', array($jsparams));
}
// Trigger a logs viewed event.
$event = \report_loglive\event\report_viewed::create(array('context' => $context));
$event->trigger();
echo $output->footer();
+41
View File
@@ -0,0 +1,41 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Lang strings.
*
* Language strings used by report_loglive
*
* @package report_loglive
* @copyright 2011 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['eventreportviewed'] = 'Live log report viewed';
$string['eventcomponent'] = 'Component';
$string['eventcontext'] = 'Event context';
$string['eventloggedas'] = '{$a->realusername} as {$a->asusername}';
$string['eventorigin'] = 'Origin';
$string['eventrelatedfullnameuser'] = 'Affected user';
$string['livelogs'] = 'Live logs from the past hour';
$string['livelogswithupdate'] = 'Live logs from the past hour ({$a})';
$string['loglive:view'] = 'View live logs';
$string['nologreaderenabled'] = 'No log reader enabled';
$string['pause'] = 'Pause live updates';
$string['pluginname'] = 'Live logs';
$string['resume'] = 'Resume live updates';
$string['selectlogreader'] = 'Select log reader';
$string['privacy:metadata'] = 'The Live logs plugin does not store any personal data.';
+58
View File
@@ -0,0 +1,58 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Libs, public API.
*
* NOTE: page type not included because there can not be any blocks in popups
*
* @package report_loglive
* @copyright 2011 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* This function extends the navigation with the report items
*
* @global stdClass $CFG
* @global core_renderer $OUTPUT
* @param navigation_node $navigation The navigation node to extend
* @param stdClass $course The course to object for the report
* @param context $context The context of the course
*/
function report_loglive_extend_navigation_course($navigation, $course, $context) {
if (has_capability('report/loglive:view', $context)) {
$url = new moodle_url('/report/loglive/index.php', array('id' => $course->id));
$navigation->add(get_string('pluginname', 'report_loglive'), $url, navigation_node::TYPE_SETTING, null, null,
new pix_icon('i/report', ''));
}
}
/**
* Callback to verify if the given instance of store is supported by this report or not.
*
* @param string $instance store instance.
*
* @return bool returns true if the store is supported by the report, false otherwise.
*/
function report_loglive_supports_logstore($instance) {
if ($instance instanceof \core\log\sql_reader) {
return true;
}
return false;
}
+53
View File
@@ -0,0 +1,53 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Ajax responder page.
*
* @package report_loglive
* @copyright 2014 onwards Ankit Agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define('AJAX_SCRIPT', true);
require_once('../../config.php');
$id = optional_param('id', 0, PARAM_INT);
$page = optional_param('page', 0, PARAM_INT);
$since = optional_param('since', 0, PARAM_INT);
$logreader = optional_param('logreader', '', PARAM_COMPONENT); // Reader which will be used for displaying logs.
$PAGE->set_url('/report/loglive/loglive_ajax.php');
// Capability checks.
if (empty($id)) {
require_login();
$context = context_system::instance();
$PAGE->set_context($context);
} else {
$course = get_course($id);
require_login($course);
$context = context_course::instance($course->id);
}
require_capability('report/loglive:view', $context);
if (!$since) {
echo $since = $since - report_loglive_renderable::CUTOFF;
}
$renderable = new report_loglive_renderable($logreader, $id, '', $since, $page);
$output = $PAGE->get_renderer('report_loglive');
echo $output->render($renderable);
+34
View File
@@ -0,0 +1,34 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Links and settings
*
* This file contains links and settings used by report_loglive
*
* @package report_loglive
* @copyright 2011 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
// Just a link to course report.
$ADMIN->add('reports', new admin_externalpage('reportloglive', get_string('pluginname', 'report_loglive'),
"$CFG->wwwroot/report/loglive/index.php", 'report/loglive:view'));
// No report settings.
$settings = null;
+7
View File
@@ -0,0 +1,7 @@
#page-report-loglive-index .info {
margin: 10px;
}
table.flexible > tbody > tr:nth-child(n).newrow > td {
background: #d4d4d4;
}
@@ -0,0 +1,26 @@
@report @report_loglive
Feature: In a course administration page, navigate through report page, test for report live log page
In order to navigate through report page
As an admin
Go to the course administration -> reports -> live logs
Background:
Given the following "courses" exist:
| fullname | shortname | category | groupmode |
| Course 1 | C1 | 0 | 1 |
And the following "users" exist:
| username | firstname | lastname | email |
| student1 | Student | 1 | student1@example.com |
And the following "course enrolments" exist:
| user | course | role |
| admin | C1 | editingteacher |
| student1 | C1 | student |
@javascript
Scenario: Selector should be available in live logs page
Given I log in as "admin"
And I am on "Course 1" course homepage
When I navigate to "Reports" in current page administration
And I click on "Live logs" "link"
Then "Report" "field" should exist in the "tertiary-navigation" "region"
And I should see "Live logs" in the "tertiary-navigation" "region"
@@ -0,0 +1,61 @@
@report @report_loglive
Feature: In a report, admin can see loglive data
In order see loglive data
As an admin
I need to view loglive report and see if the live update feature works
Background:
Given the following "courses" exist:
| fullname | shortname | category | groupmode |
| Course 1 | C1 | 0 | 1 |
And the following "users" exist:
| username | firstname | lastname | email | idnumber | middlename | alternatename | firstnamephonetic | lastnamephonetic |
| student1 | Grainne | Beauchamp | student1@example.com | s1 | Ann | Jill | Gronya | Beecham |
And the following "course enrolments" exist:
| user | course | role |
| student1 | C1 | student |
And the following config values are set as admin:
| fullnamedisplay | firstname |
| alternativefullnameformat | middlename, alternatename, firstname, lastname |
And I log in as "admin"
And I add a data activity to course "Course 1" section "3" and I fill the form with:
| Name | Test name |
| Description | Test database description |
@javascript
Scenario: Check loglive report entries and make sure the report works for standard reader
Given I navigate to "Reports > Live logs" in site administration
When I should see "Course module created"
Then I should see "Test name"
@javascript @_switch_window
Scenario: Check loglive report entries and make sure the pause/resume button works for standard reader along with ajax calls
Given I am on site homepage
When I navigate to "Reports > Live logs" in site administration
And I should not see "Test name2"
And I press "Pause live updates"
And I follow "Course module created"
And I switch to "action" window
And I am on "Course 1" course homepage
And I change window size to "large"
And I reload the page
And I add a data activity to course "Course 1" section "3" and I fill the form with:
| Name | Test name2 |
| Description | Test database description |
And I switch to the main window
And I wait "8" seconds
Then I should not see "Test name2"
And I press "Resume live updates"
And I wait "8" seconds
And I should see "Test name2"
@javascript
Scenario: Check course loglive report entries for a user
Given I log out
And I am on the "Test name" "data activity" page logged in as student1
And I log out
And I am on the "Course 1" Course page logged in as admin
When I navigate to "Reports > Live logs" in site administration
Then I should see "Course module viewed"
And I should see "Test name"
And I should see "Ann, Jill, Grainne, Beauchamp"
@@ -0,0 +1,70 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Tests for report log live events.
*
* @package report_loglive
* @copyright 2014 Rajesh Taneja <rajesh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later.
*/
namespace report_loglive\event;
/**
* Class report_loglive_events_testcase
*
* Class for tests related to log live events.
*
* @package report_loglive
* @copyright 2014 Rajesh Taneja <rajesh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later.
*/
class events_test extends \advanced_testcase {
/**
* Setup testcase.
*/
public function setUp(): void {
$this->setAdminUser();
$this->resetAfterTest();
}
/**
* Test the report viewed event.
*
* It's not possible to use the moodle API to simulate the viewing of log report, so here we
* simply create the event and trigger it.
*/
public function test_report_viewed(): void {
$course = $this->getDataGenerator()->create_course();
$context = \context_course::instance($course->id);
// Trigger event for loglive report viewed.
$event = \report_loglive\event\report_viewed::create(array('context' => $context));
// Trigger and capture the event.
$sink = $this->redirectEvents();
$event->trigger();
$events = $sink->get_events();
$event = reset($events);
$this->assertInstanceOf('\report_loglive\event\report_viewed', $event);
$this->assertEquals($context, $event->get_context());
$this->assertEventContextNotUsed($event);
$url = new \moodle_url('/report/loglive/index.php', array('id' => $course->id));
$this->assertEquals($url, $event->get_url());
}
}
+94
View File
@@ -0,0 +1,94 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Tests for report library functions.
*
* @package report_loglive
* @copyright 2014 onwards Ankit agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later.
*/
namespace report_loglive;
defined('MOODLE_INTERNAL') || die();
/**
* Class report_loglive_lib_testcase
*
* @package report_loglive
* @copyright 2014 onwards Ankit agarwal <ankit.agrr@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later.
*/
class lib_test extends \advanced_testcase {
/**
* Test report_log_supports_logstore.
*/
public function test_report_participation_supports_logstore(): void {
$logmanager = get_log_manager();
$allstores = \core_component::get_plugin_list_with_class('logstore', 'log\store');
$supportedstores = array(
'logstore_standard' => '\logstore_standard\log\store'
);
// Make sure all supported stores are installed.
$expectedstores = array_keys(array_intersect($allstores, $supportedstores));
$stores = $logmanager->get_supported_logstores('report_loglive');
$stores = array_keys($stores);
foreach ($expectedstores as $expectedstore) {
$this->assertContains($expectedstore, $stores);
}
}
/**
* Test the latest record timestamp of the report data set.
*
* @covers ::get_until()
*/
public function test_report_get_until(): void {
global $DB;
$this->resetAfterTest();
$this->preventResetByRollback();
$now = time();
// Configure log store.
set_config('enabled_stores', 'logstore_standard', 'tool_log');
$manager = get_log_manager();
$stores = $manager->get_readers();
$store = $stores['logstore_standard'];
$DB->delete_records('logstore_standard_log');
// Build the report.
$url = new \moodle_url("/report/loglive/index.php");
$renderable = new \report_loglive_renderable('logstore_standard', 0, $url);
$table = $renderable->get_table();
$table->query_db(100);
$until = $table->get_until();
// There is no record in the log table at this stage so until date is supposed to be equal to CUTOFF date.
$this->assertLessThanOrEqual(time() - \report_loglive_renderable::CUTOFF, $until);
// Create a user, store the event and re-build the report.
$this->getDataGenerator()->create_user();
$store->flush();
$table->query_db(100);
$until = $table->get_until();
// Assert that until date reflects user creation event date (now).
$this->assertGreaterThanOrEqual($now, $until);
}
}
+320
View File
@@ -0,0 +1,320 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace report_loglive;
use advanced_testcase;
use context_course;
use core_user;
/**
* Tests for table log and groups.
*
* @package report_loglive
* @copyright 2024 onwards Laurent David <laurent.david@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later.
*/
class table_log_test extends advanced_testcase {
/**
* @var int The course with separate groups.
*/
const COURSE_SEPARATE_GROUP = 0;
/**
* @var int The course with separate groups.
*/
const COURSE_VISIBLE_GROUP = 1;
/**
* @var int The course with separate groups.
*/
const COURSE_NO_GROUP = 2;
/**
* @var array The setup of users.
*/
const SETUP_USER_DEFS = [
// Make student2 also member of group1.
'student' => [
'student0' => ['group0'],
'student1' => ['group1'],
'student2' => ['group0', 'group1'],
'student3' => [],
],
// Make teacher2 also member of group1.
'teacher' => [
'teacher0' => ['group0'],
'teacher1' => ['group1'],
'teacher2' => ['group0', 'group1'],
'teacher3' => [],
],
// Make editingteacher also member of group1.
'editingteacher' => [
'editingteacher0' => ['group0'],
'editingteacher1' => ['group1'],
'editingteacher2' => ['group0', 'group1'],
],
];
/**
* @var array|\stdClass all users indexed by username.
*/
private $users = [];
/**
* @var array The groups by courses (array of array).
*/
private $groupsbycourse = [];
/**
* @var array The courses.
*/
private $courses;
/**
* Data provider for test_get_table_logs.
*
* @return array
*/
public static function get_report_logs_provider(): array {
return [
'separategroups: student 0' => [
self::COURSE_SEPARATE_GROUP,
'student0',
// All users in group 0.
[
'student0', 'student2',
'teacher0', 'teacher2',
'editingteacher0', 'editingteacher2',
],
],
'separategroups: student 1' => [
self::COURSE_SEPARATE_GROUP,
'student1',
// All users in group1.
[
'student1', 'student2',
'teacher1', 'teacher2',
'editingteacher1', 'editingteacher2',
],
],
'separategroups: student 2' => [
self::COURSE_SEPARATE_GROUP,
'student2',
// All users in group0 and group1.
[
'student0', 'student1', 'student2',
'teacher0', 'teacher1', 'teacher2',
'editingteacher0', 'editingteacher1', 'editingteacher2',
],
],
'separategroups: student3' => [
self::COURSE_SEPARATE_GROUP,
'student3',
// Student 3 is not in any group so should only see user without a group.
[
'student3',
'teacher3',
],
],
'separategroups: editing teacher 0' => [
self::COURSE_SEPARATE_GROUP,
'editingteacher0',
// All users including student 3 as we can see all users (event the one not in a group).
[
'student0', 'student1', 'student2', 'student3',
'teacher0', 'teacher1', 'teacher2', 'teacher3',
'editingteacher0', 'editingteacher1', 'editingteacher2',
],
],
'separategroups: teacher 0' => [
self::COURSE_SEPARATE_GROUP,
'teacher0',
// All users in group 0.
[
'student0', 'student2',
'teacher0', 'teacher2',
'editingteacher0', 'editingteacher2',
],
],
'separategroups: teacher 2' => [
self::COURSE_SEPARATE_GROUP,
'teacher2',
// All users in group0 and group1.
[
'student0', 'student1', 'student2',
'teacher0', 'teacher1', 'teacher2',
'editingteacher0', 'editingteacher1', 'editingteacher2',
],
],
'separategroups: teacher 3' => [
self::COURSE_SEPARATE_GROUP,
'teacher3',
// Teacher 3 is not in any group so should only see user without a group.
[
'student3',
'teacher3',
],
],
'visiblegroup: editing teacher' => [
self::COURSE_VISIBLE_GROUP,
'editingteacher0',
// All users.
[
'student0', 'student1', 'student2', 'student3',
'teacher0', 'teacher1', 'teacher2', 'teacher3',
'editingteacher0', 'editingteacher1', 'editingteacher2',
],
],
'visiblegroup: student' => [
self::COURSE_VISIBLE_GROUP,
'student0',
// All users.
[
'student0', 'student1', 'student2', 'student3',
'teacher0', 'teacher1', 'teacher2', 'teacher3',
'editingteacher0', 'editingteacher1', 'editingteacher2',
],
],
'nogroup: teacher 0' => [
self::COURSE_VISIBLE_GROUP,
'teacher2',
// All users.
[
'student0', 'student1', 'student2', 'student3',
'teacher0', 'teacher1', 'teacher2', 'teacher3',
'editingteacher0', 'editingteacher1', 'editingteacher2',
],
],
'nogroup: editing teacher 0' => [
self::COURSE_VISIBLE_GROUP,
'editingteacher0',
// All users.
[
'student0', 'student1', 'student2', 'student3',
'teacher0', 'teacher1', 'teacher2', 'teacher3',
'editingteacher0', 'editingteacher1', 'editingteacher2',
],
],
'nogroup: student' => [
self::COURSE_VISIBLE_GROUP,
'student0',
// All users.
[
'student0', 'student1', 'student2', 'student3',
'teacher0', 'teacher1', 'teacher2', 'teacher3',
'editingteacher0', 'editingteacher1', 'editingteacher2',
],
],
];
}
/**
* Set up a course with two groups, three students being each in one of the groups,
* two teachers each in either group while the second teacher is also member of the other group.
*
* @return void
* @throws \coding_exception
*/
public function setUp(): void {
global $DB;
$this->resetAfterTest();
$this->preventResetByRollback(); // This is to ensure that we can actually trigger event and record them in the log store.
$this->courses[self::COURSE_SEPARATE_GROUP] = $this->getDataGenerator()->create_course(['groupmode' => SEPARATEGROUPS]);
$this->courses[self::COURSE_VISIBLE_GROUP] = $this->getDataGenerator()->create_course(['groupmode' => VISIBLEGROUPS]);
$this->courses[self::COURSE_NO_GROUP] = $this->getDataGenerator()->create_course();
foreach ($this->courses as $coursetype => $course) {
if ($coursetype == self::COURSE_NO_GROUP) {
continue;
}
$this->groupsbycourse[$coursetype] = [];
$this->groupsbycourse[$coursetype]['group0'] =
$this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'group0']);
$this->groupsbycourse[$coursetype]['group1'] =
$this->getDataGenerator()->create_group(['courseid' => $course->id, 'name' => 'group1']);
}
foreach (self::SETUP_USER_DEFS as $role => $userdefs) {
foreach ($userdefs as $username => $groups) {
$user = $this->getDataGenerator()->create_user(
[
'username' => $username,
'firstname' => "FN{$role}{$username}",
'lastname' => "LN{$role}{$username}",
]);
foreach ($this->courses as $coursetype => $course) {
$this->getDataGenerator()->enrol_user($user->id, $course->id, $role);
foreach ($groups as $groupname) {
if ($coursetype == self::COURSE_NO_GROUP) {
continue;
}
$this->getDataGenerator()->create_group_member([
'groupid' => $this->groupsbycourse[$coursetype][$groupname]->id,
'userid' => $user->id,
]);
}
}
$this->users[$username] = $user;
}
}
// Configure log store.
set_config('enabled_stores', 'logstore_standard', 'tool_log');
get_log_manager(true);
$DB->delete_records('logstore_standard_log');
foreach ($this->courses as $course) {
foreach ($this->users as $user) {
$eventdata = [
'context' => context_course::instance($course->id),
'userid' => $user->id,
];
$event = \core\event\course_viewed::create($eventdata);
$event->trigger();
}
}
}
/**
* Test table_log
*
* @param int $courseindex
* @param string $username
* @param array $expectedusers
* @covers \report_log_renderable::get_user_list
* @dataProvider get_report_logs_provider
* @return void
*/
public function test_get_table_logs(int $courseindex, string $username, array $expectedusers): void {
$manager = get_log_manager();
$stores = $manager->get_readers();
$store = $stores['logstore_standard'];
// Build the report.
$url = new \moodle_url("/report/loglive/index.php");
$renderable = new \report_loglive_renderable('logstore_standard', $this->courses[$courseindex], $url);
$table = $renderable->get_table();
$currentuser = $this->users[$username];
$this->setUser($currentuser->id);
$store->flush();
$table->query_db(100);
$filteredevents =
array_filter(
$table->rawdata, fn($event) => get_class($event) === \core\event\course_viewed::class
);
$usernames = array_map(
function($event) {
$user = core_user::get_user($event->userid, '*', MUST_EXIST);
return $user->username;
},
$filteredevents);
sort($expectedusers);
sort($usernames);
$this->assertEquals($expectedusers, $usernames);
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Version info
*
* This file contains version information about report_loglive
*
* @package report_loglive
* @copyright 2011 Petr Skoda
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
$plugin->version = 2024042200; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2024041600; // Requires this Moodle version.
$plugin->component = 'report_loglive'; // Full name of the plugin (used for diagnostics).
@@ -0,0 +1,260 @@
YUI.add('moodle-report_loglive-fetchlogs', function (Y, NAME) {
/**
* A module to manage ajax requests.
*
* @module moodle-report_loglive-fetchlogs
*/
/**
* A module to manage ajax requests.
*
* @class moodle-report_loglive.fetchlogs
* @extends Base
* @constructor
*/
function FetchLogs() {
FetchLogs.superclass.constructor.apply(this, arguments);
}
var CSS = {
NEWROW: 'newrow',
SPINNER: 'spinner',
ICONSMALL: 'iconsmall'
},
SELECTORS = {
NEWROW: '.' + CSS.NEWROW,
TBODY: '.flexible tbody',
ACTIONLINK: '[data-action="action-popup"]',
PAUSEBUTTON: '#livelogs-pause-button',
SPINNER: '.' + CSS.SPINNER
};
Y.extend(FetchLogs, Y.Base, {
/**
* Reference to the callBack object generated by Y.later
*
* @property callBack
* @type Object
* @default {}
* @protected
*/
callBack: {},
/**
* Reference to the spinner node.
*
* @property callBack
* @type Object
* @default {}
* @protected
*/
spinner: {},
/**
* Reference to the toggleButton node.
*
* @property pauseButton
* @type Object
* @default {}
* @protected
*/
pauseButton: {},
/**
* Initializer.
* Basic setup and event listeners.
*
* @method initializer
*/
initializer: function() {
// We don't want the pages to be updated when viewing a specific page in the chain.
if (this.get('page') === 0) {
this.callBack = Y.later(this.get('interval') * 1000, this, this.fetchRecentLogs, null, true);
}
this.spinner = Y.one(SELECTORS.SPINNER);
this.pauseButton = Y.one(SELECTORS.PAUSEBUTTON);
this.spinner.hide();
Y.one(SELECTORS.TBODY).delegate('click', this.openActionLink, SELECTORS.ACTIONLINK, this);
Y.one(SELECTORS.PAUSEBUTTON).on('click', this.toggleUpdate, this);
},
/**
* Method to fetch recent logs.
*
* @method fetchRecentLogs
*/
fetchRecentLogs: function() {
this.spinner.show(); // Show a loading icon.
var data = {
logreader: this.get('logreader'),
since: this.get('since'),
page: this.get('page'),
id: this.get('courseid')
};
var cfg = {
method: 'get',
context: this,
on: {
complete: this.updateLogTable
},
data: data
};
var url = M.cfg.wwwroot + '/report/loglive/loglive_ajax.php';
Y.io(url, cfg);
},
/**
* Method to update the log table, populate the table with new entries and remove old entries if needed.
*
* @method updateLogTable
*/
updateLogTable: function(tid, response) {
// Hide loading icon, give sometime to people to actually see it. We should do it, event in case of an error.
Y.later(600, this, 'hideLoadingIcon');
var responseobject;
// Attempt to parse the response into an object.
try {
responseobject = Y.JSON.parse(response.responseText);
if (responseobject.error) {
Y.use('moodle-core-notification-ajaxexception', function() {
return new M.core.ajaxException(responseobject);
});
return this;
}
} catch (error) {
Y.use('moodle-core-notification-exception', function() {
return new M.core.exception(error);
});
return this;
}
this.set('since', responseobject.until);
var logs = responseobject.logs;
var tbody = Y.one(SELECTORS.TBODY);
var firstTr = null;
if (tbody && logs) {
firstTr = tbody.get('firstChild');
if (firstTr) {
tbody.insertBefore(logs, firstTr);
}
// @Todo, when no data is present our library should generate an empty table. so data can be added
// dynamically (MDL-44525).
// Let us chop off some data from end of table to prevent really long pages.
var oldChildren = tbody.get('children').slice(this.get('perpage'));
oldChildren.remove();
Y.later(5000, this, 'removeHighlight'); // Remove highlighting from new rows.
}
},
/**
* Remove background highlight from the newly added rows.
*
* @method removeHighlight
*/
removeHighlight: function() {
Y.all(SELECTORS.NEWROW).removeClass(CSS.NEWROW);
},
/**
* Hide the spinning icon.
*
* @method hideLoadingIcon
*/
hideLoadingIcon: function() {
this.spinner.hide();
},
/**
* Open a report action link
*
* @param {Event} event
* @method openActionLink
*/
openActionLink: function(event) {
var popupAction = JSON.parse(event.target.get('dataset').popupAction);
window.openpopup(event, popupAction.jsfunctionargs);
},
/**
* Toggle live update.
*
* @method toggleUpdate
*/
toggleUpdate: function() {
if (this.callBack) {
this.callBack.cancel();
this.callBack = '';
this.pauseButton.setContent(M.util.get_string('resume', 'report_loglive'));
} else {
this.callBack = Y.later(this.get('interval') * 1000, this, this.fetchRecentLogs, null, true);
this.pauseButton.setContent(M.util.get_string('pause', 'report_loglive'));
}
}
}, {
NAME: 'fetchLogs',
ATTRS: {
/**
* time stamp from where the new logs needs to be fetched.
*
* @attribute since
* @default null
* @type String
*/
since: null,
/**
* courseid for which the logs are shown.
*
* @attribute courseid
* @default 0
* @type int
*/
courseid: 0,
/**
* Page number shown to user.
*
* @attribute page
* @default 0
* @type int
*/
page: 0,
/**
* Items to show per page.
*
* @attribute perpage
* @default 100
* @type int
*/
perpage: 100,
/**
* Refresh interval.
*
* @attribute interval
* @default 60
* @type int
*/
interval: 60,
/**
* Which logstore is being used.
*
* @attribute logreader
* @default logstore_standard
* @type String
*/
logreader: 'logstore_standard'
}
});
Y.namespace('M.report_loglive.FetchLogs').init = function(config) {
return new FetchLogs(config);
};
}, '@VERSION@', {"requires": ["base", "event", "node", "io", "node-event-delegate"]});
@@ -0,0 +1 @@
YUI.add("moodle-report_loglive-fetchlogs",function(a,e){function t(){t.superclass.constructor.apply(this,arguments)}var i="newrow",r={NEWROW:"."+i,TBODY:".flexible tbody",ACTIONLINK:'[data-action="action-popup"]',PAUSEBUTTON:"#livelogs-pause-button",SPINNER:"."+"spinner"};a.extend(t,a.Base,{callBack:{},spinner:{},pauseButton:{},initializer:function(){0===this.get("page")&&(this.callBack=a.later(1e3*this.get("interval"),this,this.fetchRecentLogs,null,!0)),this.spinner=a.one(r.SPINNER),this.pauseButton=a.one(r.PAUSEBUTTON),this.spinner.hide(),a.one(r.TBODY).delegate("click",this.openActionLink,r.ACTIONLINK,this),a.one(r.PAUSEBUTTON).on("click",this.toggleUpdate,this)},fetchRecentLogs:function(){var e,t;this.spinner.show(),e={logreader:this.get("logreader"),since:this.get("since"),page:this.get("page"),id:this.get("courseid")},e={method:"get",context:this,on:{complete:this.updateLogTable},data:e},t=M.cfg.wwwroot+"/report/loglive/loglive_ajax.php",a.io(t,e)},updateLogTable:function(e,t){var i,n,o;a.later(600,this,"hideLoadingIcon");try{if((i=a.JSON.parse(t.responseText)).error)return a.use("moodle-core-notification-ajaxexception",function(){return new M.core.ajaxException(i)}),this}catch(s){return a.use("moodle-core-notification-exception",function(){return new M.core.exception(s)}),this}this.set("since",i.until),t=i.logs,(n=a.one(r.TBODY))&&t&&((o=n.get("firstChild"))&&n.insertBefore(t,o),n.get("children").slice(this.get("perpage")).remove(),a.later(5e3,this,"removeHighlight"))},removeHighlight:function(){a.all(r.NEWROW).removeClass(i)},hideLoadingIcon:function(){this.spinner.hide()},openActionLink:function(e){var t=JSON.parse(e.target.get("dataset").popupAction);window.openpopup(e,t.jsfunctionargs)},toggleUpdate:function(){this.callBack?(this.callBack.cancel(),this.callBack="",this.pauseButton.setContent(M.util.get_string("resume","report_loglive"))):(this.callBack=a.later(1e3*this.get("interval"),this,this.fetchRecentLogs,null,!0),this.pauseButton.setContent(M.util.get_string("pause","report_loglive")))}},{NAME:"fetchLogs",ATTRS:{since:null,courseid:0,page:0,perpage:100,interval:60,logreader:"logstore_standard"}}),a.namespace("M.report_loglive.FetchLogs").init=function(e){return new t(e)}},"@VERSION@",{requires:["base","event","node","io","node-event-delegate"]});
@@ -0,0 +1,260 @@
YUI.add('moodle-report_loglive-fetchlogs', function (Y, NAME) {
/**
* A module to manage ajax requests.
*
* @module moodle-report_loglive-fetchlogs
*/
/**
* A module to manage ajax requests.
*
* @class moodle-report_loglive.fetchlogs
* @extends Base
* @constructor
*/
function FetchLogs() {
FetchLogs.superclass.constructor.apply(this, arguments);
}
var CSS = {
NEWROW: 'newrow',
SPINNER: 'spinner',
ICONSMALL: 'iconsmall'
},
SELECTORS = {
NEWROW: '.' + CSS.NEWROW,
TBODY: '.flexible tbody',
ACTIONLINK: '[data-action="action-popup"]',
PAUSEBUTTON: '#livelogs-pause-button',
SPINNER: '.' + CSS.SPINNER
};
Y.extend(FetchLogs, Y.Base, {
/**
* Reference to the callBack object generated by Y.later
*
* @property callBack
* @type Object
* @default {}
* @protected
*/
callBack: {},
/**
* Reference to the spinner node.
*
* @property callBack
* @type Object
* @default {}
* @protected
*/
spinner: {},
/**
* Reference to the toggleButton node.
*
* @property pauseButton
* @type Object
* @default {}
* @protected
*/
pauseButton: {},
/**
* Initializer.
* Basic setup and event listeners.
*
* @method initializer
*/
initializer: function() {
// We don't want the pages to be updated when viewing a specific page in the chain.
if (this.get('page') === 0) {
this.callBack = Y.later(this.get('interval') * 1000, this, this.fetchRecentLogs, null, true);
}
this.spinner = Y.one(SELECTORS.SPINNER);
this.pauseButton = Y.one(SELECTORS.PAUSEBUTTON);
this.spinner.hide();
Y.one(SELECTORS.TBODY).delegate('click', this.openActionLink, SELECTORS.ACTIONLINK, this);
Y.one(SELECTORS.PAUSEBUTTON).on('click', this.toggleUpdate, this);
},
/**
* Method to fetch recent logs.
*
* @method fetchRecentLogs
*/
fetchRecentLogs: function() {
this.spinner.show(); // Show a loading icon.
var data = {
logreader: this.get('logreader'),
since: this.get('since'),
page: this.get('page'),
id: this.get('courseid')
};
var cfg = {
method: 'get',
context: this,
on: {
complete: this.updateLogTable
},
data: data
};
var url = M.cfg.wwwroot + '/report/loglive/loglive_ajax.php';
Y.io(url, cfg);
},
/**
* Method to update the log table, populate the table with new entries and remove old entries if needed.
*
* @method updateLogTable
*/
updateLogTable: function(tid, response) {
// Hide loading icon, give sometime to people to actually see it. We should do it, event in case of an error.
Y.later(600, this, 'hideLoadingIcon');
var responseobject;
// Attempt to parse the response into an object.
try {
responseobject = Y.JSON.parse(response.responseText);
if (responseobject.error) {
Y.use('moodle-core-notification-ajaxexception', function() {
return new M.core.ajaxException(responseobject);
});
return this;
}
} catch (error) {
Y.use('moodle-core-notification-exception', function() {
return new M.core.exception(error);
});
return this;
}
this.set('since', responseobject.until);
var logs = responseobject.logs;
var tbody = Y.one(SELECTORS.TBODY);
var firstTr = null;
if (tbody && logs) {
firstTr = tbody.get('firstChild');
if (firstTr) {
tbody.insertBefore(logs, firstTr);
}
// @Todo, when no data is present our library should generate an empty table. so data can be added
// dynamically (MDL-44525).
// Let us chop off some data from end of table to prevent really long pages.
var oldChildren = tbody.get('children').slice(this.get('perpage'));
oldChildren.remove();
Y.later(5000, this, 'removeHighlight'); // Remove highlighting from new rows.
}
},
/**
* Remove background highlight from the newly added rows.
*
* @method removeHighlight
*/
removeHighlight: function() {
Y.all(SELECTORS.NEWROW).removeClass(CSS.NEWROW);
},
/**
* Hide the spinning icon.
*
* @method hideLoadingIcon
*/
hideLoadingIcon: function() {
this.spinner.hide();
},
/**
* Open a report action link
*
* @param {Event} event
* @method openActionLink
*/
openActionLink: function(event) {
var popupAction = JSON.parse(event.target.get('dataset').popupAction);
window.openpopup(event, popupAction.jsfunctionargs);
},
/**
* Toggle live update.
*
* @method toggleUpdate
*/
toggleUpdate: function() {
if (this.callBack) {
this.callBack.cancel();
this.callBack = '';
this.pauseButton.setContent(M.util.get_string('resume', 'report_loglive'));
} else {
this.callBack = Y.later(this.get('interval') * 1000, this, this.fetchRecentLogs, null, true);
this.pauseButton.setContent(M.util.get_string('pause', 'report_loglive'));
}
}
}, {
NAME: 'fetchLogs',
ATTRS: {
/**
* time stamp from where the new logs needs to be fetched.
*
* @attribute since
* @default null
* @type String
*/
since: null,
/**
* courseid for which the logs are shown.
*
* @attribute courseid
* @default 0
* @type int
*/
courseid: 0,
/**
* Page number shown to user.
*
* @attribute page
* @default 0
* @type int
*/
page: 0,
/**
* Items to show per page.
*
* @attribute perpage
* @default 100
* @type int
*/
perpage: 100,
/**
* Refresh interval.
*
* @attribute interval
* @default 60
* @type int
*/
interval: 60,
/**
* Which logstore is being used.
*
* @attribute logreader
* @default logstore_standard
* @type String
*/
logreader: 'logstore_standard'
}
});
Y.namespace('M.report_loglive.FetchLogs').init = function(config) {
return new FetchLogs(config);
};
}, '@VERSION@', {"requires": ["base", "event", "node", "io", "node-event-delegate"]});
@@ -0,0 +1,10 @@
{
"name": "moodle-report_loglive-fetchlogs",
"builds": {
"moodle-report_loglive-fetchlogs": {
"jsfiles": [
"fetchlogs.js"
]
}
}
}
+255
View File
@@ -0,0 +1,255 @@
/**
* A module to manage ajax requests.
*
* @module moodle-report_loglive-fetchlogs
*/
/**
* A module to manage ajax requests.
*
* @class moodle-report_loglive.fetchlogs
* @extends Base
* @constructor
*/
function FetchLogs() {
FetchLogs.superclass.constructor.apply(this, arguments);
}
var CSS = {
NEWROW: 'newrow',
SPINNER: 'spinner',
ICONSMALL: 'iconsmall'
},
SELECTORS = {
NEWROW: '.' + CSS.NEWROW,
TBODY: '.flexible tbody',
ACTIONLINK: '[data-action="action-popup"]',
PAUSEBUTTON: '#livelogs-pause-button',
SPINNER: '.' + CSS.SPINNER
};
Y.extend(FetchLogs, Y.Base, {
/**
* Reference to the callBack object generated by Y.later
*
* @property callBack
* @type Object
* @default {}
* @protected
*/
callBack: {},
/**
* Reference to the spinner node.
*
* @property callBack
* @type Object
* @default {}
* @protected
*/
spinner: {},
/**
* Reference to the toggleButton node.
*
* @property pauseButton
* @type Object
* @default {}
* @protected
*/
pauseButton: {},
/**
* Initializer.
* Basic setup and event listeners.
*
* @method initializer
*/
initializer: function() {
// We don't want the pages to be updated when viewing a specific page in the chain.
if (this.get('page') === 0) {
this.callBack = Y.later(this.get('interval') * 1000, this, this.fetchRecentLogs, null, true);
}
this.spinner = Y.one(SELECTORS.SPINNER);
this.pauseButton = Y.one(SELECTORS.PAUSEBUTTON);
this.spinner.hide();
Y.one(SELECTORS.TBODY).delegate('click', this.openActionLink, SELECTORS.ACTIONLINK, this);
Y.one(SELECTORS.PAUSEBUTTON).on('click', this.toggleUpdate, this);
},
/**
* Method to fetch recent logs.
*
* @method fetchRecentLogs
*/
fetchRecentLogs: function() {
this.spinner.show(); // Show a loading icon.
var data = {
logreader: this.get('logreader'),
since: this.get('since'),
page: this.get('page'),
id: this.get('courseid')
};
var cfg = {
method: 'get',
context: this,
on: {
complete: this.updateLogTable
},
data: data
};
var url = M.cfg.wwwroot + '/report/loglive/loglive_ajax.php';
Y.io(url, cfg);
},
/**
* Method to update the log table, populate the table with new entries and remove old entries if needed.
*
* @method updateLogTable
*/
updateLogTable: function(tid, response) {
// Hide loading icon, give sometime to people to actually see it. We should do it, event in case of an error.
Y.later(600, this, 'hideLoadingIcon');
var responseobject;
// Attempt to parse the response into an object.
try {
responseobject = Y.JSON.parse(response.responseText);
if (responseobject.error) {
Y.use('moodle-core-notification-ajaxexception', function() {
return new M.core.ajaxException(responseobject);
});
return this;
}
} catch (error) {
Y.use('moodle-core-notification-exception', function() {
return new M.core.exception(error);
});
return this;
}
this.set('since', responseobject.until);
var logs = responseobject.logs;
var tbody = Y.one(SELECTORS.TBODY);
var firstTr = null;
if (tbody && logs) {
firstTr = tbody.get('firstChild');
if (firstTr) {
tbody.insertBefore(logs, firstTr);
}
// @Todo, when no data is present our library should generate an empty table. so data can be added
// dynamically (MDL-44525).
// Let us chop off some data from end of table to prevent really long pages.
var oldChildren = tbody.get('children').slice(this.get('perpage'));
oldChildren.remove();
Y.later(5000, this, 'removeHighlight'); // Remove highlighting from new rows.
}
},
/**
* Remove background highlight from the newly added rows.
*
* @method removeHighlight
*/
removeHighlight: function() {
Y.all(SELECTORS.NEWROW).removeClass(CSS.NEWROW);
},
/**
* Hide the spinning icon.
*
* @method hideLoadingIcon
*/
hideLoadingIcon: function() {
this.spinner.hide();
},
/**
* Open a report action link
*
* @param {Event} event
* @method openActionLink
*/
openActionLink: function(event) {
var popupAction = JSON.parse(event.target.get('dataset').popupAction);
window.openpopup(event, popupAction.jsfunctionargs);
},
/**
* Toggle live update.
*
* @method toggleUpdate
*/
toggleUpdate: function() {
if (this.callBack) {
this.callBack.cancel();
this.callBack = '';
this.pauseButton.setContent(M.util.get_string('resume', 'report_loglive'));
} else {
this.callBack = Y.later(this.get('interval') * 1000, this, this.fetchRecentLogs, null, true);
this.pauseButton.setContent(M.util.get_string('pause', 'report_loglive'));
}
}
}, {
NAME: 'fetchLogs',
ATTRS: {
/**
* time stamp from where the new logs needs to be fetched.
*
* @attribute since
* @default null
* @type String
*/
since: null,
/**
* courseid for which the logs are shown.
*
* @attribute courseid
* @default 0
* @type int
*/
courseid: 0,
/**
* Page number shown to user.
*
* @attribute page
* @default 0
* @type int
*/
page: 0,
/**
* Items to show per page.
*
* @attribute perpage
* @default 100
* @type int
*/
perpage: 100,
/**
* Refresh interval.
*
* @attribute interval
* @default 60
* @type int
*/
interval: 60,
/**
* Which logstore is being used.
*
* @attribute logreader
* @default logstore_standard
* @type String
*/
logreader: 'logstore_standard'
}
});
Y.namespace('M.report_loglive.FetchLogs').init = function(config) {
return new FetchLogs(config);
};
@@ -0,0 +1,11 @@
{
"moodle-report_loglive-fetchlogs": {
"requires": [
"base",
"event",
"node",
"io",
"node-event-delegate"
]
}
}