Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

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