Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.

Differences Between: [Versions 310 and 403] [Versions 311 and 403] [Versions 39 and 403] [Versions 400 and 403] [Versions 401 and 403] [Versions 402 and 403]

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