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
 * Contains the class used for the displaying the tokens table.
19
 *
20
 * @package    core_webservice
21
 * @copyright  2017 John Okely <john@moodle.com>
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
namespace core_webservice;
26
 
27
defined('MOODLE_INTERNAL') || die;
28
 
29
require_once($CFG->libdir . '/tablelib.php');
30
require_once($CFG->dirroot . '/webservice/lib.php');
31
require_once($CFG->dirroot . '/user/lib.php');
32
 
33
/**
34
 * Class for the displaying the participants table.
35
 *
36
 * @package    core_webservice
37
 * @copyright  2017 John Okely <john@moodle.com>
38
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1441 ariadna 39
 *
40
 * @deprecated since 4.5 MDL-79496. Table replaced with a report builder system report.
41
 * @todo MDL-79909 This will be deleted in Moodle 6.0.
1 efrain 42
 */
1441 ariadna 43
#[\core\attribute\deprecated(
44
    replacement: null,
45
    since: '4.5',
46
    reason: 'Table replaced with a report builder system report',
47
    mdl: 'MDL-79496',
48
)]
1 efrain 49
class token_table extends \table_sql {
50
 
51
    /**
52
     * @var bool $showalltokens Whether or not the user is able to see all tokens.
53
     */
54
    protected $showalltokens;
55
 
56
    /** @var bool $hasviewfullnames Does the user have the viewfullnames capability. */
57
    protected $hasviewfullnames;
58
 
59
    /** @var array */
60
    protected $userextrafields;
61
 
62
    /** @var object */
63
    protected $filterdata;
64
 
65
    /**
66
     * Sets up the table.
67
     *
68
     * @param int $id The id of the table
69
     * @param object $filterdata The data submitted by the {@see token_filter}.
70
     */
71
    public function __construct($id, $filterdata = null) {
72
        parent::__construct($id);
73
 
74
        // Get the context.
75
        $context = \context_system::instance();
76
 
77
        // Can we see tokens created by all users?
78
        $this->showalltokens = has_capability('moodle/webservice:managealltokens', $context);
79
        $this->hasviewfullnames = has_capability('moodle/site:viewfullnames', $context);
80
 
81
        // List of user identity fields.
82
        $this->userextrafields = \core_user\fields::get_identity_fields(\context_system::instance(), false);
83
 
84
        // Filter form values.
85
        $this->filterdata = $filterdata;
86
 
87
        // Define the headers and columns.
88
        $headers = [];
89
        $columns = [];
90
 
91
        $headers[] = get_string('tokenname', 'webservice');
92
        $columns[] = 'name';
93
        $headers[] = get_string('user');
94
        $columns[] = 'fullname';
95
        $headers[] = get_string('service', 'webservice');
96
        $columns[] = 'servicename';
97
        $headers[] = get_string('iprestriction', 'webservice');
98
        $columns[] = 'iprestriction';
99
        $headers[] = get_string('validuntil', 'webservice');
100
        $columns[] = 'validuntil';
101
        $headers[] = get_string('lastaccess');
102
        $columns[] = 'lastaccess';
103
        if ($this->showalltokens) {
104
            // Only need to show creator if you can see tokens created by other people.
105
            $headers[] = get_string('tokencreator', 'webservice');
106
            $columns[] = 'creatorlastname'; // So we can have semi-useful sorting. Table SQL doesn't two fullname collumns.
107
        }
108
        $headers[] = get_string('operation', 'webservice');
109
        $columns[] = 'operation';
110
 
111
        $this->define_columns($columns);
112
        $this->define_headers($headers);
113
 
114
        $this->no_sorting('operation');
115
        $this->no_sorting('token');
116
        $this->no_sorting('iprestriction');
117
 
118
        $this->set_attribute('id', $id);
119
    }
120
 
121
    /**
122
     * Generate the operation column.
123
     *
124
     * @param \stdClass $data Data for the current row
125
     * @return string Content for the column
126
     */
127
    public function col_operation($data) {
128
        $tokenpageurl = new \moodle_url(
129
            "/admin/webservice/tokens.php",
130
            [
131
                "action" => "delete",
132
                "tokenid" => $data->id
133
            ]
134
        );
135
        return \html_writer::link($tokenpageurl, get_string("delete"));
136
    }
137
 
138
    /**
139
     * Generate the validuntil column.
140
     *
141
     * @param \stdClass $data Data for the current row
142
     * @return string Content for the column
143
     */
144
    public function col_validuntil($data) {
145
        if (empty($data->validuntil)) {
146
            return get_string('validuntil_empty', 'webservice');
147
        } else {
148
            return userdate($data->validuntil, get_string('strftimedatetime', 'langconfig'));
149
        }
150
    }
151
 
152
    /**
153
     * Generate the last access column
154
     *
155
     * @param \stdClass $data
156
     * @return string
157
     */
158
    public function col_lastaccess(\stdClass $data): string {
159
        if (empty($data->lastaccess)) {
160
            return get_string('never');
161
        } else {
162
            return userdate($data->lastaccess, get_string('strftimedatetime', 'langconfig'));
163
        }
164
    }
165
 
166
    /**
167
     * Generate the fullname column. Also includes capabilities the user is missing for the webservice (if any)
168
     *
169
     * @param \stdClass $data Data for the current row
170
     * @return string Content for the column
171
     */
172
    public function col_fullname($data) {
173
        global $OUTPUT;
174
 
175
        $identity = [];
176
 
177
        foreach ($this->userextrafields as $userextrafield) {
178
            $identity[] = s($data->$userextrafield);
179
        }
180
 
181
        $userprofilurl = new \moodle_url('/user/profile.php', ['id' => $data->userid]);
182
        $content = \html_writer::link($userprofilurl, fullname($data, $this->hasviewfullnames));
183
 
184
        if ($identity) {
185
            $content .= \html_writer::div('<small>' . implode(', ', $identity) . '</small>', 'useridentity text-muted');
186
        }
187
 
188
        // Make up list of capabilities that the user is missing for the given webservice.
189
        $webservicemanager = new \webservice();
190
        $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users([['id' => $data->userid]], $data->serviceid);
191
 
192
        if ($data->serviceshortname <> MOODLE_OFFICIAL_MOBILE_SERVICE && !is_siteadmin($data->userid)
193
                && array_key_exists($data->userid, $usermissingcaps)) {
194
            $count = \html_writer::span(count($usermissingcaps[$data->userid]), 'badge bg-danger text-white');
195
            $links = array_map(function($capname) {
196
                return get_capability_docs_link((object)['name' => $capname]) . \html_writer::div($capname, 'text-muted');
197
            }, $usermissingcaps[$data->userid]);
198
            $list = \html_writer::alist($links);
199
            $help = $OUTPUT->help_icon('missingcaps', 'webservice');
200
            $content .= print_collapsible_region(\html_writer::div($list . $help, 'missingcaps'), 'small mt-2',
201
                \html_writer::random_id('usermissingcaps'), get_string('usermissingcaps', 'webservice', $count), '', true, true);
202
        }
203
 
204
        return $content;
205
    }
206
 
207
    /**
208
     * Generate the name column.
209
     *
210
     * @param \stdClass $data Data for the current row
211
     * @return string Content for the column
212
     */
213
    public function col_name($data) {
214
        return $data->name;
215
    }
216
 
217
    /**
218
     * Generate the creator column.
219
     *
220
     * @param \stdClass $data
221
     * @return string
222
     */
223
    public function col_creatorlastname($data) {
224
        // We have loaded all the name fields for the creator, with the 'creator' prefix.
225
        // So just remove the prefix and make up a user object.
226
        $user = [];
227
        foreach ($data as $key => $value) {
228
            if (strpos($key, 'creator') !== false) {
229
                $newkey = str_replace('creator', '', $key);
230
                $user[$newkey] = $value;
231
            }
232
        }
233
 
234
        $creatorprofileurl = new \moodle_url('/user/profile.php', ['id' => $data->creatorid]);
235
        return \html_writer::link($creatorprofileurl, fullname((object)$user, $this->hasviewfullnames));
236
    }
237
 
238
    /**
239
     * Format the service name column.
240
     *
241
     * @param \stdClass $data
242
     * @return string
243
     */
244
    public function col_servicename($data) {
245
        return \html_writer::div(s($data->servicename)) . \html_writer::div(s($data->serviceshortname), 'small text-muted');
246
    }
247
 
248
    /**
249
     * This function is used for the extra user fields.
250
     *
251
     * These are being dynamically added to the table so there are no functions 'col_<userfieldname>' as
252
     * the list has the potential to increase in the future and we don't want to have to remember to add
253
     * a new method to this class. We also don't want to pollute this class with unnecessary methods.
254
     *
255
     * @param string $colname The column name
256
     * @param \stdClass $data
257
     * @return string
258
     */
259
    public function other_cols($colname, $data) {
260
        return s($data->{$colname});
261
    }
262
 
263
    /**
264
     * Query the database for results to display in the table.
265
     *
266
     * Note: Initial bars are not implemented for this table because it includes user details twice and the initial bars do not work
267
     * when the user table is included more than once.
268
     *
269
     * @param int $pagesize size of page for paginated displayed table.
270
     * @param bool $useinitialsbar Not implemented. Please pass false.
271
     */
272
    public function query_db($pagesize, $useinitialsbar = false) {
273
        global $DB, $USER;
274
 
275
        if ($useinitialsbar) {
276
            debugging('Initial bar not implemented yet. Call out($pagesize, false)');
277
        }
278
 
279
        $userfieldsapi = \core_user\fields::for_name();
280
        $usernamefields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
281
        $creatorfields = $userfieldsapi->get_sql('c', false, 'creator', '', false)->selects;
282
 
283
        if (!empty($this->userextrafields)) {
284
            $usernamefields .= ',u.' . implode(',u.', $this->userextrafields);
285
        }
286
 
287
        $params = ['tokenmode' => EXTERNAL_TOKEN_PERMANENT];
288
 
289
        $selectfields = "SELECT t.id, t.name, t.iprestriction, t.validuntil, t.creatorid, t.lastaccess,
290
                                u.id AS userid, $usernamefields,
291
                                s.id AS serviceid, s.name AS servicename, s.shortname AS serviceshortname,
292
                                $creatorfields ";
293
 
294
        $selectcount = "SELECT COUNT(t.id) ";
295
 
296
        $sql = "  FROM {external_tokens} t
297
                  JOIN {user} u ON u.id = t.userid
298
                  JOIN {external_services} s ON s.id = t.externalserviceid
299
                  JOIN {user} c ON c.id = t.creatorid
300
                 WHERE t.tokentype = :tokenmode";
301
 
302
        if (!$this->showalltokens) {
303
            // Only show tokens created by the current user.
304
            $sql .= " AND t.creatorid = :userid";
305
            $params['userid'] = $USER->id;
306
        }
307
 
308
        if ($this->filterdata->name !== '') {
309
            $sql .= " AND " . $DB->sql_like("t.name", ":name", false, false);
310
            $params['name'] = "%" . $DB->sql_like_escape($this->filterdata->name) . "%";
311
        }
312
 
313
        if (!empty($this->filterdata->users)) {
314
            list($sqlusers, $paramsusers) = $DB->get_in_or_equal($this->filterdata->users, SQL_PARAMS_NAMED, 'user');
315
            $sql .= " AND t.userid {$sqlusers}";
316
            $params += $paramsusers;
317
        }
318
 
319
        if (!empty($this->filterdata->services)) {
320
            list($sqlservices, $paramsservices) = $DB->get_in_or_equal($this->filterdata->services, SQL_PARAMS_NAMED, 'service');
321
            $sql .= " AND s.id {$sqlservices}";
322
            $params += $paramsservices;
323
        }
324
 
325
        $sort = $this->get_sql_sort();
326
        $sortsql = '';
327
 
328
        if ($sort) {
329
            $sortsql = " ORDER BY {$sort}";
330
        }
331
 
332
        $total = $DB->count_records_sql($selectcount . $sql, $params);
333
        $this->pagesize($pagesize, $total);
334
 
335
        $this->rawdata = $DB->get_recordset_sql($selectfields . $sql . $sortsql, $params, $this->get_page_start(),
336
            $this->get_page_size());
337
    }
338
}