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_log
21
 * @copyright  2014 Rajesh Taneja <rajesh.taneja@gmail.com>
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
11 efrain 25
use core\dataformat;
1 efrain 26
use core\report_helper;
27
 
28
defined('MOODLE_INTERNAL') || die;
11 efrain 29
 
1 efrain 30
global $CFG;
31
require_once($CFG->libdir . '/tablelib.php');
32
 
33
/**
34
 * Table log class for displaying logs.
35
 *
36
 * @package    report_log
37
 * @copyright  2014 Rajesh Taneja <rajesh.taneja@gmail.com>
38
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39
 */
40
class report_log_table_log extends table_sql {
41
    /** @var array list of user fullnames shown in report */
42
    private $userfullnames = array();
43
 
44
    /** @var array list of context name shown in report */
45
    private $contextname = array();
46
 
47
    /** @var stdClass filters parameters */
48
    private $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', 'reportlog generaltable generalbox table-sm');
71
        $this->filterparams = $filterparams;
72
        // Add course column if logs are displayed for site.
73
        $cols = array();
74
        $headers = array();
75
        if (empty($filterparams->courseid)) {
76
            $cols = array('course');
77
            $headers = array(get_string('course'));
78
        }
79
 
80
        $this->define_columns(array_merge($cols, array('time', 'fullnameuser', 'relatedfullnameuser', 'context', 'component',
81
                'eventname', 'description', 'origin', 'ip')));
82
        $this->define_headers(array_merge($headers, array(
83
                get_string('time'),
84
                get_string('fullnameuser'),
85
                get_string('eventrelatedfullnameuser', 'report_log'),
86
                get_string('eventcontext', 'report_log'),
87
                get_string('eventcomponent', 'report_log'),
88
                get_string('eventname'),
89
                get_string('description'),
90
                get_string('eventorigin', 'report_log'),
91
                get_string('ip_address')
92
                )
93
            ));
94
        $this->collapsible(false);
95
        $this->sortable(false);
96
        $this->pageable(true);
97
    }
98
 
99
    /**
100
     * Generate the course column.
101
     *
102
     * @deprecated since Moodle 2.9 MDL-48595 - please do not use this function any more.
103
     */
104
    public function col_course($event) {
105
        throw new coding_exception('col_course() can not be used any more, there is no such column.');
106
    }
107
 
108
    /**
109
     * Gets the user full name.
110
     *
111
     * This function is useful because, in the unlikely case that the user is
112
     * not already loaded in $this->userfullnames it will fetch it from db.
113
     *
114
     * @since Moodle 2.9
115
     * @param int $userid
116
     * @return string|false
117
     */
118
    protected function get_user_fullname($userid) {
119
        if (empty($userid)) {
120
            return false;
121
        }
122
 
123
        // Check if we already have this users' fullname.
124
        $userfullname = $this->userfullnames[$userid] ?? null;
125
        if (!empty($userfullname)) {
126
            return $userfullname;
127
        }
128
 
129
        // We already looked for the user and it does not exist.
130
        if ($userfullname === false) {
131
            return false;
132
        }
133
 
134
        // If we reach that point new users logs have been generated since the last users db query.
135
        $userfieldsapi = \core_user\fields::for_name();
136
        $fields = $userfieldsapi->get_sql('', false, '', '', false)->selects;
137
        if ($user = \core_user::get_user($userid, $fields)) {
138
            $this->userfullnames[$userid] = fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context()));
139
        } else {
140
            $this->userfullnames[$userid] = false;
141
        }
142
 
143
        return $this->userfullnames[$userid];
144
    }
145
 
146
    /**
147
     * Generate the time column.
148
     *
149
     * @param stdClass $event event data.
150
     * @return string HTML for the time column
151
     */
152
    public function col_time($event) {
153
 
154
        if (empty($this->download)) {
155
            $dateformat = get_string('strftimedatetimeaccurate', 'core_langconfig');
156
        } else {
157
            $dateformat = get_string('strftimedatetimeshortaccurate', 'core_langconfig');
158
        }
159
        return userdate($event->timecreated, $dateformat);
160
    }
161
 
162
    /**
163
     * Generate the username column.
164
     *
165
     * @param \core\event\base $event event data.
166
     * @return string HTML for the username column
167
     */
168
    public function col_fullnameuser($event) {
169
        // Get extra event data for origin and realuserid.
170
        $logextra = $event->get_logextra();
171
 
172
        $eventusername = $event->userid ? $this->get_user_fullname($event->userid) : false;
173
 
174
        // Add username who did the action.
175
        if (!empty($logextra['realuserid'])) {
176
            $a = new stdClass();
177
            if (!$a->realusername = $this->get_user_fullname($logextra['realuserid'])) {
178
                $a->realusername = '-';
179
            }
180
            if (!$a->asusername = $eventusername) {
181
                $a->asusername = '-';
182
            }
183
            if (empty($this->download)) {
184
                $params = array('id' => $logextra['realuserid']);
185
                if ($event->courseid) {
186
                    $params['course'] = $event->courseid;
187
                }
188
                $a->realusername = html_writer::link(new moodle_url('/user/view.php', $params), $a->realusername);
189
                $params['id'] = $event->userid;
190
                $a->asusername = html_writer::link(new moodle_url('/user/view.php', $params), $a->asusername);
191
            }
192
            $username = get_string('eventloggedas', 'report_log', $a);
193
 
194
        } else if ($eventusername) {
195
            if (empty($this->download)) {
196
                $params = ['id' => $event->userid];
197
                if ($event->courseid) {
198
                    $params['course'] = $event->courseid;
199
                }
200
                $username = html_writer::link(new moodle_url('/user/view.php', $params), $eventusername);
201
            } else {
202
                $username = $eventusername;
203
            }
204
        } else {
205
            $username = '-';
206
        }
207
        return $username;
208
    }
209
 
210
    /**
211
     * Generate the related username column.
212
     *
213
     * @param stdClass $event event data.
214
     * @return string HTML for the related username column
215
     */
216
    public function col_relatedfullnameuser($event) {
217
        // Add affected user.
218
        if (!empty($event->relateduserid) && $username = $this->get_user_fullname($event->relateduserid)) {
219
            if (empty($this->download)) {
220
                $params = array('id' => $event->relateduserid);
221
                if ($event->courseid) {
222
                    $params['course'] = $event->courseid;
223
                }
224
                $username = html_writer::link(new moodle_url('/user/view.php', $params), $username);
225
            }
226
        } else {
227
            $username = '-';
228
        }
229
        return $username;
230
    }
231
 
232
    /**
233
     * Generate the context column.
234
     *
235
     * @param stdClass $event event data.
236
     * @return string HTML for the context column
237
     */
238
    public function col_context($event) {
239
        // Add context name.
240
        if ($event->contextid) {
241
            // If context name was fetched before then return, else get one.
242
            if (isset($this->contextname[$event->contextid])) {
243
                return $this->contextname[$event->contextid];
244
            } else {
245
                $context = context::instance_by_id($event->contextid, IGNORE_MISSING);
246
                if ($context) {
247
                    $contextname = $context->get_context_name(true);
248
                    if (empty($this->download) && $url = $context->get_url()) {
249
                        $contextname = html_writer::link($url, $contextname);
250
                    }
251
                } else {
252
                    $contextname = get_string('other');
253
                }
254
            }
255
        } else {
256
            $contextname = get_string('other');
257
        }
258
 
259
        $this->contextname[$event->contextid] = $contextname;
260
        return $contextname;
261
    }
262
 
263
    /**
264
     * Generate the component column.
265
     *
266
     * @param stdClass $event event data.
267
     * @return string HTML for the component column
268
     */
269
    public function col_component($event) {
270
        // Component.
271
        $componentname = $event->component;
272
        if (($event->component === 'core') || ($event->component === 'legacy')) {
273
            return  get_string('coresystem');
274
        } else if (get_string_manager()->string_exists('pluginname', $event->component)) {
275
            return get_string('pluginname', $event->component);
276
        } else {
277
            return $componentname;
278
        }
279
    }
280
 
281
    /**
282
     * Generate the event name column.
283
     *
284
     * @param stdClass $event event data.
285
     * @return string HTML for the event name column
286
     */
287
    public function col_eventname($event) {
288
        // Event name.
289
        $eventname = $event->get_name();
290
        // Only encode as an action link if we're not downloading.
291
        if (($url = $event->get_url()) && empty($this->download)) {
292
            $eventname = $this->action_link($url, $eventname, 'action');
293
        }
294
        return $eventname;
295
    }
296
 
297
    /**
298
     * Generate the description column.
299
     *
300
     * @param stdClass $event event data.
301
     * @return string HTML for the description column
302
     */
303
    public function col_description($event) {
11 efrain 304
        if (empty($this->download) || dataformat::get_format_instance($this->download)->supports_html()) {
305
            return format_text($event->get_description(), FORMAT_PLAIN);
306
        } else {
307
            return $event->get_description();
308
        }
1 efrain 309
    }
310
 
311
    /**
312
     * Generate the origin column.
313
     *
314
     * @param stdClass $event event data.
315
     * @return string HTML for the origin column
316
     */
317
    public function col_origin($event) {
318
        // Get extra event data for origin and realuserid.
319
        $logextra = $event->get_logextra();
320
 
321
        // Add event origin, normally IP/cron.
322
        return $logextra['origin'];
323
    }
324
 
325
    /**
326
     * Generate the ip column.
327
     *
328
     * @param stdClass $event event data.
329
     * @return string HTML for the ip column
330
     */
331
    public function col_ip($event) {
332
        // Get extra event data for origin and realuserid.
333
        $logextra = $event->get_logextra();
334
        $ip = $logextra['ip'];
335
 
336
        if (empty($this->download)) {
337
            $url = new moodle_url("/iplookup/index.php?popup=1&ip={$ip}&user={$event->userid}");
338
            $ip = $this->action_link($url, $ip, 'ip');
339
        }
340
        return $ip;
341
    }
342
 
343
    /**
344
     * Method to create a link with popup action.
345
     *
346
     * @param moodle_url $url The url to open.
347
     * @param string $text Anchor text for the link.
348
     * @param string $name Name of the popup window.
349
     *
350
     * @return string html to use.
351
     */
352
    protected function action_link(moodle_url $url, $text, $name = 'popup') {
353
        global $OUTPUT;
354
        $link = new action_link($url, $text, new popup_action('click', $url, $name, array('height' => 440, 'width' => 700)));
355
        return $OUTPUT->render($link);
356
    }
357
 
358
    /**
359
     * Helper function to get legacy crud action.
360
     *
361
     * @param string $crud crud action
362
     * @return string legacy action.
363
     */
364
    public function get_legacy_crud_action($crud) {
365
        $legacyactionmap = array('c' => 'add', 'r' => 'view', 'u' => 'update', 'd' => 'delete');
366
        if (array_key_exists($crud, $legacyactionmap)) {
367
            return $legacyactionmap[$crud];
368
        } else {
369
            // From old legacy log.
370
            return '-view';
371
        }
372
    }
373
 
374
    /**
375
     * Helper function which is used by build logs to get action sql and param.
376
     *
377
     * @return array sql and param for action.
378
     */
379
    public function get_action_sql() {
380
        global $DB;
381
 
382
        // In new logs we have a field to pick, and in legacy try get this from action.
383
        if (!empty($this->filterparams->action)) {
384
             list($sql, $params) = $DB->get_in_or_equal(str_split($this->filterparams->action),
385
                    SQL_PARAMS_NAMED, 'crud');
386
            $sql = "crud " . $sql;
387
        } else {
388
            // Add condition for all possible values of crud (to use db index).
389
            list($sql, $params) = $DB->get_in_or_equal(array('c', 'r', 'u', 'd'),
390
                    SQL_PARAMS_NAMED, 'crud');
391
            $sql = "crud ".$sql;
392
        }
393
        return array($sql, $params);
394
    }
395
 
396
    /**
397
     * Helper function which is used by build logs to get course module sql and param.
398
     *
399
     * @return array sql and param for action.
400
     */
401
    public function get_cm_sql() {
402
        $joins = array();
403
        $params = array();
404
 
405
        $joins[] = "contextinstanceid = :contextinstanceid";
406
        $joins[] = "contextlevel = :contextmodule";
407
        $params['contextinstanceid'] = $this->filterparams->modid;
408
        $params['contextmodule'] = CONTEXT_MODULE;
409
 
410
        $sql = implode(' AND ', $joins);
411
        return array($sql, $params);
412
    }
413
 
414
    /**
415
     * Query the reader. Store results in the object for use by build_table.
416
     *
417
     * @param int $pagesize size of page for paginated displayed table.
418
     * @param bool $useinitialsbar do you want to use the initials bar.
419
     */
420
    public function query_db($pagesize, $useinitialsbar = true) {
421
        global $DB, $USER;
422
 
423
        $joins = array();
424
        $params = array();
425
 
426
        // If we filter by userid and module id we also need to filter by crud and edulevel to ensure DB index is engaged.
427
        $useextendeddbindex = !empty($this->filterparams->userid) && !empty($this->filterparams->modid);
428
 
429
        if (!empty($this->filterparams->courseid) && $this->filterparams->courseid != SITEID) {
430
            $joins[] = "courseid = :courseid";
431
            $params['courseid'] = $this->filterparams->courseid;
432
        }
433
 
434
        if (!empty($this->filterparams->siteerrors)) {
435
            $joins[] = "( action='error' OR action='infected' OR action='failed' )";
436
        }
437
 
438
        if (!empty($this->filterparams->modid)) {
439
            list($actionsql, $actionparams) = $this->get_cm_sql();
440
            $joins[] = $actionsql;
441
            $params = array_merge($params, $actionparams);
442
        }
443
 
444
        if (!empty($this->filterparams->action) || $useextendeddbindex) {
445
            list($actionsql, $actionparams) = $this->get_action_sql();
446
            $joins[] = $actionsql;
447
            $params = array_merge($params, $actionparams);
448
        }
449
 
450
        // Getting all members of a group.
451
        [
452
            'joins' => $groupjoins,
453
            'params' => $groupparams,
454
            'useridfilter' => $this->lateuseridfilter,
455
        ] = report_helper::get_group_filter($this->filterparams);
456
 
457
        $joins = array_merge($joins, $groupjoins);
458
        $params = array_merge($params, $groupparams);
459
 
460
        if (!empty($this->filterparams->date)) {
461
            $joins[] = "timecreated > :date AND timecreated < :enddate";
462
            $params['date'] = $this->filterparams->date;
463
            $params['enddate'] = $this->filterparams->date + DAYSECS; // Show logs only for the selected date.
464
        }
465
 
466
        if (isset($this->filterparams->edulevel) && ($this->filterparams->edulevel >= 0)) {
467
            $joins[] = "edulevel = :edulevel";
468
            $params['edulevel'] = $this->filterparams->edulevel;
469
        } else if ($useextendeddbindex) {
470
            list($edulevelsql, $edulevelparams) = $DB->get_in_or_equal(array(\core\event\base::LEVEL_OTHER,
471
                \core\event\base::LEVEL_PARTICIPATING, \core\event\base::LEVEL_TEACHING), SQL_PARAMS_NAMED, 'edulevel');
472
            $joins[] = "edulevel ".$edulevelsql;
473
            $params = array_merge($params, $edulevelparams);
474
        }
475
 
476
        // Origin.
477
        if (isset($this->filterparams->origin) && ($this->filterparams->origin != '')) {
478
            if ($this->filterparams->origin !== '---') {
479
                // Filter by a single origin.
480
                $joins[] = "origin = :origin";
481
                $params['origin'] = $this->filterparams->origin;
482
            } else {
483
                // Filter by everything else.
484
                list($originsql, $originparams) = $DB->get_in_or_equal(array('cli', 'restore', 'ws', 'web'),
485
                    SQL_PARAMS_NAMED, 'origin', false);
486
                $joins[] = "origin " . $originsql;
487
                $params = array_merge($params, $originparams);
488
            }
489
        }
490
 
491
        // Filter out anonymous actions, this is N/A for legacy log because it never stores them.
492
        if ($this->filterparams->modid) {
493
            $context = context_module::instance($this->filterparams->modid);
494
        } else {
495
            $context = context_course::instance($this->filterparams->courseid);
496
        }
497
        if (!has_capability('moodle/site:viewanonymousevents', $context)) {
498
            $joins[] = "anonymous = 0";
499
        }
500
 
501
        $selector = implode(' AND ', $joins);
502
 
503
        if (!$this->is_downloading()) {
504
            $total = $this->filterparams->logreader->get_events_select_count($selector, $params);
505
            $this->pagesize($pagesize, $total);
506
        } else {
507
            $this->pageable(false);
508
        }
509
 
510
        // Get the events. Same query than before; even if it is not likely, logs from new users
511
        // may be added since last query so we will need to work around later to prevent problems.
512
        // In almost most of the cases this will be better than having two opened recordsets.
513
        $this->rawdata = new \CallbackFilterIterator(
514
            $this->filterparams->logreader->get_events_select_iterator(
515
                $selector,
516
                $params,
517
                $this->filterparams->orderby,
518
                $this->get_page_start(),
519
                $this->get_page_size(),
520
            ),
521
            function ($event) {
522
                if ($this->lateuseridfilter === null) {
523
                    return true;
524
                }
525
                return isset($this->lateuseridfilter[$event->userid]);
526
            },
527
        );
528
 
529
        // Set initial bars.
530
        if ($useinitialsbar && !$this->is_downloading()) {
531
            $this->initialbars($total > $pagesize);
532
        }
533
    }
534
 
535
    /**
536
     * Helper function to create list of course shortname and user fullname shown in log report.
537
     *
538
     * This will update $this->userfullnames and $this->courseshortnames array with userfullname and courseshortname (with link),
539
     * which will be used to render logs in table.
540
     *
541
     * @deprecated since Moodle 2.9 MDL-48595 - please do not use this function any more.
542
     */
543
    public function update_users_and_courses_used() {
544
        throw new coding_exception('update_users_and_courses_used() can not be used any more.');
545
    }
546
}