task_log_table.php 8.91 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?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/>.

/**
 * Task log table.
 *
 * @package    core_admin
 * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace core_admin;

defined('MOODLE_INTERNAL') || die();

require_once($CFG->libdir . '/tablelib.php');

/**
 * Table to display list of task logs.
 *
 * @copyright  2018 Andrew Nicols <andrew@nicols.co.uk>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class task_log_table extends \table_sql {

    /**
     * Constructor for the task_log table.
     *
     * @param   string      $filter
     * @param   int         $resultfilter
     */
    public function __construct(string $filter = '', int $resultfilter = null) {
        global $DB;

        if (-1 === $resultfilter) {
            $resultfilter = null;
        }

        parent::__construct('tasklogs');

        $columnheaders = [
            'classname'  => get_string('name'),
            'type'       => get_string('tasktype', 'admin'),
            'userid'     => get_string('user', 'admin'),
            'timestart'  => get_string('task_starttime', 'admin'),
            'duration'   => get_string('task_duration', 'admin'),
60
61
            'hostname'   => get_string('hostname', 'tool_task'),
            'pid'        => get_string('pid', 'tool_task'),
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
            'db'         => get_string('task_dbstats', 'admin'),
            'result'     => get_string('task_result', 'admin'),
            'actions'    => '',
        ];
        $this->define_columns(array_keys($columnheaders));
        $this->define_headers(array_values($columnheaders));

        // The name column is a header.
        $this->define_header_column('classname');

        // This table is not collapsible.
        $this->collapsible(false);

        // The actions class should not wrap. Use the BS text utility class.
        $this->column_class('actions', 'text-nowrap');

        // Allow pagination.
        $this->pageable(true);

        // Allow sorting. Default to sort by timestarted DESC.
        $this->sortable(true, 'timestart', SORT_DESC);

        // Add filtering.
        $where = [];
        $params = [];
        if (!empty($filter)) {
88
            $orwhere = [];
89
            $filter = str_replace('\\', '\\\\', $filter);
90
91
92
93
94
95
96
97
98

            // Check the class name.
            $orwhere[] = $DB->sql_like('classname', ':classfilter', false, false);
            $params['classfilter'] = '%' . $DB->sql_like_escape($filter) . '%';

            $orwhere[] = $DB->sql_like('output', ':outputfilter', false, false);
            $params['outputfilter'] = '%' . $DB->sql_like_escape($filter) . '%';

            $where[] = "(" . implode(' OR ', $orwhere) . ")";
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
        }

        if (null !== $resultfilter) {
            $where[] = 'tl.result = :result';
            $params['result'] = $resultfilter;
        }

        $where = implode(' AND ', $where);

        $this->set_sql('', '', $where, $params);
    }

    /**
     * Query the db. Store results in the table 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. Bar
     * will only be used if there is a fullname column defined for the table.
     */
    public function query_db($pagesize, $useinitialsbar = true) {
        global $DB;

        // Fetch the attempts.
        $sort = $this->get_sql_sort();
        if ($sort) {
            $sort = "ORDER BY $sort";
        }

127
        // TODO Does not support custom user profile fields (MDL-70456).
128
        $userfieldsapi = \core_user\fields::for_identity(\context_system::instance(), false)->with_userpic();
129
        $userfields = $userfieldsapi->get_sql('u', false, 'user', 'userid2', false)->selects;
130
131
132
133
134
135
136

        $where = '';
        if (!empty($this->sql->where)) {
            $where = "WHERE {$this->sql->where}";
        }

        $sql = "SELECT
137
                    tl.id, tl.type, tl.component, tl.classname, tl.userid, tl.timestart, tl.timeend,
138
                    tl.hostname, tl.pid,
139
                    tl.dbreads, tl.dbwrites, tl.result,
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
                    tl.dbreads + tl.dbwrites AS db,
                    tl.timeend - tl.timestart AS duration,
                    {$userfields}
                FROM {task_log} tl
           LEFT JOIN {user} u ON u.id = tl.userid
                {$where}
                {$sort}";

        $this->pagesize($pagesize, $DB->count_records_sql("SELECT COUNT('x') FROM {task_log} tl {$where}", $this->sql->params));
        if (!$this->is_downloading()) {
            $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size());
        } else {
            $this->rawdata = $DB->get_records_sql($sql, $this->sql->params);
        }
    }

    /**
     * Format the name cell.
     *
     * @param   \stdClass $row
     * @return  string
     */
    public function col_classname($row) : string {
        $output = '';
        if (class_exists($row->classname)) {
            $task = new $row->classname;
            if ($task instanceof \core\task\scheduled_task) {
                $output = $task->get_name();
            }
        }

        $output .= \html_writer::tag('div', "\\{$row->classname}", [
                'class' => 'task-class',
            ]);
        return $output;
    }

    /**
     * Format the type cell.
     *
     * @param   \stdClass $row
     * @return  string
     */
    public function col_type($row) : string {
        if (\core\task\database_logger::TYPE_SCHEDULED == $row->type) {
            return get_string('task_type:scheduled', 'admin');
        } else {
            return get_string('task_type:adhoc', 'admin');
        }
    }

    /**
     * Format the timestart cell.
     *
     * @param   \stdClass $row
     * @return  string
     */
    public function col_result($row) : string {
        if ($row->result) {
            return get_string('task_result:failed', 'admin');
        } else {
            return get_string('success');
        }
    }

    /**
     * Format the timestart cell.
     *
     * @param   \stdClass $row
     * @return  string
     */
    public function col_timestart($row) : string {
        return userdate($row->timestart, get_string('strftimedatetimeshort', 'langconfig'));
    }

    /**
     * Format the duration cell.
     *
     * @param   \stdClass $row
     * @return  string
     */
    public function col_duration($row) : string {
        $duration = round($row->timeend - $row->timestart, 2);

        if (empty($duration)) {
            // The format_time function returns 'now' when the difference is exactly 0.
            // Note: format_time performs concatenation in exactly this fashion so we should do this for consistency.
            return '0 ' . get_string('secs', 'moodle');
        }

        return format_time($duration);
    }

    /**
     * Format the DB details cell.
     *
     * @param   \stdClass $row
     * @return  string
     */
    public function col_db($row) : string {
        $output = '';

        $output .= \html_writer::div(get_string('task_stats:dbreads', 'admin', $row->dbreads));
        $output .= \html_writer::div(get_string('task_stats:dbwrites', 'admin', $row->dbwrites));

        return $output;
    }

    /**
     * Format the actions cell.
     *
     * @param   \stdClass $row
     * @return  string
     */
    public function col_actions($row) : string {
        global $OUTPUT;

        $actions = [];

        $url = new \moodle_url('/admin/tasklogs.php', ['logid' => $row->id]);

        // Quick view.
        $actions[] = $OUTPUT->action_icon(
            $url,
            new \pix_icon('e/search', get_string('view')),
            new \popup_action('click', $url)
        );

        // Download.
        $actions[] = $OUTPUT->action_icon(
            new \moodle_url($url, ['download' => true]),
            new \pix_icon('t/download', get_string('download'))
        );

        return implode('&nbsp;', $actions);
    }

    /**
     * Format the user cell.
     *
     * @param   \stdClass $row
     * @return  string
     */
    public function col_userid($row) : string {
        if (empty($row->userid)) {
            return '';
        }

        $user = (object) [];
        username_load_fields_from_object($user, $row, 'user');

        return fullname($user);
    }
}