Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
/webservice/ -> lib.php (source)

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

   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  /**
  19   * Web services utility functions and classes
  20   *
  21   * @package    core_webservice
  22   * @copyright  2009 Jerome Mouneyrac <jerome@moodle.com>
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  require_once($CFG->libdir.'/externallib.php');
  27  
  28  /**
  29   * WEBSERVICE_AUTHMETHOD_USERNAME - username/password authentication (also called simple authentication)
  30   */
  31  define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
  32  
  33  /**
  34   * WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN - most common token authentication (external app, mobile app...)
  35   */
  36  define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
  37  
  38  /**
  39   * WEBSERVICE_AUTHMETHOD_SESSION_TOKEN - token for embedded application (requires Moodle session)
  40   */
  41  define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
  42  
  43  /**
  44   * General web service library
  45   *
  46   * @package    core_webservice
  47   * @copyright  2010 Jerome Mouneyrac <jerome@moodle.com>
  48   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  49   */
  50  class webservice {
  51      /**
  52       * Only update token last access once per this many seconds. (This constant controls update of
  53       * the external tokens last access field. There is a similar define LASTACCESS_UPDATE_SECS
  54       * which controls update of the web site last access fields.)
  55       *
  56       * @var int
  57       */
  58      const TOKEN_LASTACCESS_UPDATE_SECS = 60;
  59  
  60      /**
  61       * Authenticate user (used by download/upload file scripts)
  62       *
  63       * @param string $token
  64       * @return array - contains the authenticated user, token and service objects
  65       */
  66      public function authenticate_user($token) {
  67          global $DB, $CFG;
  68  
  69          // web service must be enabled to use this script
  70          if (!$CFG->enablewebservices) {
  71              throw new webservice_access_exception('Web services are not enabled in Advanced features.');
  72          }
  73  
  74          // Obtain token record
  75          if (!$token = $DB->get_record('external_tokens', array('token' => $token))) {
  76              //client may want to display login form => moodle_exception
  77              throw new moodle_exception('invalidtoken', 'webservice');
  78          }
  79  
  80          $loginfaileddefaultparams = array(
  81              'other' => array(
  82                  'method' => WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN,
  83                  'reason' => null,
  84                  'tokenid' => $token->id
  85              )
  86          );
  87  
  88          // Validate token date
  89          if ($token->validuntil and $token->validuntil < time()) {
  90              $params = $loginfaileddefaultparams;
  91              $params['other']['reason'] = 'token_expired';
  92              $event = \core\event\webservice_login_failed::create($params);
  93              $event->add_record_snapshot('external_tokens', $token);
  94              $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
  95                  get_string('invalidtimedtoken', 'webservice'), 0));
  96              $event->trigger();
  97              $DB->delete_records('external_tokens', array('token' => $token->token));
  98              throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
  99          }
 100  
 101          // Check ip
 102          if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
 103              $params = $loginfaileddefaultparams;
 104              $params['other']['reason'] = 'ip_restricted';
 105              $event = \core\event\webservice_login_failed::create($params);
 106              $event->add_record_snapshot('external_tokens', $token);
 107              $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
 108                  get_string('failedtolog', 'webservice') . ": " . getremoteaddr(), 0));
 109              $event->trigger();
 110              throw new webservice_access_exception('Invalid token - IP:' . getremoteaddr()
 111                      . ' is not supported');
 112          }
 113  
 114          //retrieve user link to the token
 115          $user = $DB->get_record('user', array('id' => $token->userid, 'deleted' => 0), '*', MUST_EXIST);
 116  
 117          // let enrol plugins deal with new enrolments if necessary
 118          enrol_check_plugins($user);
 119  
 120          // setup user session to check capability
 121          \core\session\manager::set_user($user);
 122          set_login_session_preferences();
 123  
 124          //assumes that if sid is set then there must be a valid associated session no matter the token type
 125          if ($token->sid) {
 126              if (!\core\session\manager::session_exists($token->sid)) {
 127                  $DB->delete_records('external_tokens', array('sid' => $token->sid));
 128                  throw new webservice_access_exception('Invalid session based token - session not found or expired');
 129              }
 130          }
 131  
 132          // Cannot authenticate unless maintenance access is granted.
 133          $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system::instance(), $user);
 134          if (!empty($CFG->maintenance_enabled) and !$hasmaintenanceaccess) {
 135              //this is usually temporary, client want to implement code logic  => moodle_exception
 136              throw new moodle_exception('sitemaintenance', 'admin');
 137          }
 138  
 139          //retrieve web service record
 140          $service = $DB->get_record('external_services', array('id' => $token->externalserviceid, 'enabled' => 1));
 141          if (empty($service)) {
 142              // will throw exception if no token found
 143              throw new webservice_access_exception('Web service is not available (it doesn\'t exist or might be disabled)');
 144          }
 145  
 146          //check if there is any required system capability
 147          if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
 148              throw new webservice_access_exception('The capability ' . $service->requiredcapability . ' is required.');
 149          }
 150  
 151          //specific checks related to user restricted service
 152          if ($service->restrictedusers) {
 153              $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));
 154  
 155              if (empty($authoriseduser)) {
 156                  throw new webservice_access_exception(
 157                          'The user is not allowed for this service. First you need to allow this user on the '
 158                          . $service->name . '\'s allowed users administration page.');
 159              }
 160  
 161              if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
 162                  throw new webservice_access_exception('Invalid service - service expired - check validuntil time for this allowed user');
 163              }
 164  
 165              if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
 166                  throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
 167                      . ' is not supported - check this allowed user');
 168              }
 169          }
 170  
 171          //only confirmed user should be able to call web service
 172          if (empty($user->confirmed)) {
 173              $params = $loginfaileddefaultparams;
 174              $params['other']['reason'] = 'user_unconfirmed';
 175              $event = \core\event\webservice_login_failed::create($params);
 176              $event->add_record_snapshot('external_tokens', $token);
 177              $event->set_legacy_logdata(array(SITEID, 'webservice', 'user unconfirmed', '', $user->username));
 178              $event->trigger();
 179              throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
 180          }
 181  
 182          //check the user is suspended
 183          if (!empty($user->suspended)) {
 184              $params = $loginfaileddefaultparams;
 185              $params['other']['reason'] = 'user_suspended';
 186              $event = \core\event\webservice_login_failed::create($params);
 187              $event->add_record_snapshot('external_tokens', $token);
 188              $event->set_legacy_logdata(array(SITEID, 'webservice', 'user suspended', '', $user->username));
 189              $event->trigger();
 190              throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
 191          }
 192  
 193          //check if the auth method is nologin (in this case refuse connection)
 194          if ($user->auth == 'nologin') {
 195              $params = $loginfaileddefaultparams;
 196              $params['other']['reason'] = 'nologin';
 197              $event = \core\event\webservice_login_failed::create($params);
 198              $event->add_record_snapshot('external_tokens', $token);
 199              $event->set_legacy_logdata(array(SITEID, 'webservice', 'nologin auth attempt with web service', '', $user->username));
 200              $event->trigger();
 201              throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
 202          }
 203  
 204          //Check if the user password is expired
 205          $auth = get_auth_plugin($user->auth);
 206          if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
 207              $days2expire = $auth->password_expire($user->username);
 208              if (intval($days2expire) < 0) {
 209                  $params = $loginfaileddefaultparams;
 210                  $params['other']['reason'] = 'password_expired';
 211                  $event = \core\event\webservice_login_failed::create($params);
 212                  $event->add_record_snapshot('external_tokens', $token);
 213                  $event->set_legacy_logdata(array(SITEID, 'webservice', 'expired password', '', $user->username));
 214                  $event->trigger();
 215                  throw new moodle_exception('passwordisexpired', 'webservice');
 216              }
 217          }
 218  
 219          // log token access
 220          self::update_token_lastaccess($token);
 221  
 222          return array('user' => $user, 'token' => $token, 'service' => $service);
 223      }
 224  
 225      /**
 226       * Updates the last access time for a token.
 227       *
 228       * @param \stdClass $token Token object (must include id, lastaccess fields)
 229       * @param int $time Time of access (0 = use current time)
 230       * @throws dml_exception If database error
 231       */
 232      public static function update_token_lastaccess($token, int $time = 0) {
 233          global $DB;
 234  
 235          if (!$time) {
 236              $time = time();
 237          }
 238  
 239          // Only update the field if it is a different time from previous request,
 240          // so as not to waste database effort.
 241          if ($time >= $token->lastaccess + self::TOKEN_LASTACCESS_UPDATE_SECS) {
 242              $DB->set_field('external_tokens', 'lastaccess', $time, array('id' => $token->id));
 243          }
 244      }
 245  
 246      /**
 247       * Allow user to call a service
 248       *
 249       * @param stdClass $user a user
 250       */
 251      public function add_ws_authorised_user($user) {
 252          global $DB;
 253          $user->timecreated = time();
 254          $DB->insert_record('external_services_users', $user);
 255      }
 256  
 257      /**
 258       * Disallow a user to call a service
 259       *
 260       * @param stdClass $user a user
 261       * @param int $serviceid
 262       */
 263      public function remove_ws_authorised_user($user, $serviceid) {
 264          global $DB;
 265          $DB->delete_records('external_services_users',
 266                  array('externalserviceid' => $serviceid, 'userid' => $user->id));
 267      }
 268  
 269      /**
 270       * Update allowed user settings (ip restriction, valid until...)
 271       *
 272       * @param stdClass $user
 273       */
 274      public function update_ws_authorised_user($user) {
 275          global $DB;
 276          $DB->update_record('external_services_users', $user);
 277      }
 278  
 279      /**
 280       * Return list of allowed users with their options (ip/timecreated / validuntil...)
 281       * for a given service
 282       *
 283       * @param int $serviceid the service id to search against
 284       * @return array $users
 285       */
 286      public function get_ws_authorised_users($serviceid) {
 287          global $DB, $CFG;
 288  
 289          $params = array($CFG->siteguest, $serviceid);
 290  
 291          $userfields = \core_user\fields::for_identity(context_system::instance())->with_name()->excluding('id');
 292          $fieldsql = $userfields->get_sql('u');
 293  
 294          $sql = " SELECT u.id as id, esu.id as serviceuserid {$fieldsql->selects},
 295                          esu.iprestriction as iprestriction, esu.validuntil as validuntil,
 296                          esu.timecreated as timecreated
 297                     FROM {user} u
 298                     JOIN {external_services_users} esu ON esu.userid = u.id
 299                          {$fieldsql->joins}
 300                    WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
 301                          AND esu.externalserviceid = ?";
 302  
 303          $users = $DB->get_records_sql($sql, array_merge($fieldsql->params, $params));
 304  
 305          return $users;
 306      }
 307  
 308      /**
 309       * Return an authorised user with their options (ip/timecreated / validuntil...)
 310       *
 311       * @param int $serviceid the service id to search against
 312       * @param int $userid the user to search against
 313       * @return stdClass
 314       */
 315      public function get_ws_authorised_user($serviceid, $userid) {
 316          global $DB, $CFG;
 317          $params = array($CFG->siteguest, $serviceid, $userid);
 318          $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
 319                          u.lastname as lastname,
 320                          esu.iprestriction as iprestriction, esu.validuntil as validuntil,
 321                          esu.timecreated as timecreated
 322                     FROM {user} u, {external_services_users} esu
 323                    WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
 324                          AND esu.userid = u.id
 325                          AND esu.externalserviceid = ?
 326                          AND u.id = ?";
 327          $user = $DB->get_record_sql($sql, $params);
 328          return $user;
 329      }
 330  
 331      /**
 332       * Generate all tokens of a specific user
 333       *
 334       * @param int $userid user id
 335       */
 336      public function generate_user_ws_tokens($userid) {
 337          global $CFG, $DB;
 338  
 339          // generate a token for non admin if web service are enable and the user has the capability to create a token
 340          if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) {
 341              // for every service than the user is authorised on, create a token (if it doesn't already exist)
 342  
 343              // get all services which are set to all user (no restricted to specific users)
 344              $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
 345              $serviceidlist = array();
 346              foreach ($norestrictedservices as $service) {
 347                  $serviceidlist[] = $service->id;
 348              }
 349  
 350              // get all services which are set to the current user (the current user is specified in the restricted user list)
 351              $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
 352              foreach ($servicesusers as $serviceuser) {
 353                  if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
 354                       $serviceidlist[] = $serviceuser->externalserviceid;
 355                  }
 356              }
 357  
 358              // get all services which already have a token set for the current user
 359              $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
 360              $tokenizedservice = array();
 361              foreach ($usertokens as $token) {
 362                      $tokenizedservice[]  = $token->externalserviceid;
 363              }
 364  
 365              // create a token for the service which have no token already
 366              foreach ($serviceidlist as $serviceid) {
 367                  if (!in_array($serviceid, $tokenizedservice)) {
 368                      // create the token for this service
 369                      $newtoken = new stdClass();
 370                      $newtoken->token = md5(uniqid(rand(),1));
 371                      // check that the user has capability on this service
 372                      $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
 373                      $newtoken->userid = $userid;
 374                      $newtoken->externalserviceid = $serviceid;
 375                      // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE
 376                      $newtoken->contextid = context_system::instance()->id;
 377                      $newtoken->creatorid = $userid;
 378                      $newtoken->timecreated = time();
 379                      // Generate the private token, it must be transmitted only via https.
 380                      $newtoken->privatetoken = random_string(64);
 381  
 382                      $DB->insert_record('external_tokens', $newtoken);
 383                  }
 384              }
 385  
 386  
 387          }
 388      }
 389  
 390      /**
 391       * Return all tokens of a specific user
 392       * + the service state (enabled/disabled)
 393       * + the authorised user mode (restricted/not restricted)
 394       *
 395       * @param int $userid user id
 396       * @return array
 397       */
 398      public function get_user_ws_tokens($userid) {
 399          global $DB;
 400          //here retrieve token list (including linked users firstname/lastname and linked services name)
 401          $sql = "SELECT
 402                      t.id, t.creatorid, t.token, u.firstname, u.lastname, s.id as wsid, s.name, s.enabled, s.restrictedusers, t.validuntil
 403                  FROM
 404                      {external_tokens} t, {user} u, {external_services} s
 405                  WHERE
 406                      t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
 407          $tokens = $DB->get_records_sql($sql, array( $userid));
 408          return $tokens;
 409      }
 410  
 411      /**
 412       * Return a token that has been created by the user (i.e. to created by an admin)
 413       * If no tokens exist an exception is thrown
 414       *
 415       * The returned value is a stdClass:
 416       * ->id token id
 417       * ->token
 418       * ->firstname user firstname
 419       * ->lastname
 420       * ->name service name
 421       *
 422       * @param int $userid user id
 423       * @param int $tokenid token id
 424       * @return stdClass
 425       */
 426      public function get_created_by_user_ws_token($userid, $tokenid) {
 427          global $DB;
 428          $sql = "SELECT
 429                          t.id, t.token, u.firstname, u.lastname, s.name
 430                      FROM
 431                          {external_tokens} t, {user} u, {external_services} s
 432                      WHERE
 433                          t.creatorid=? AND t.id=? AND t.tokentype = "
 434                  . EXTERNAL_TOKEN_PERMANENT
 435                  . " AND s.id = t.externalserviceid AND t.userid = u.id";
 436          //must be the token creator
 437          $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST);
 438          return $token;
 439      }
 440  
 441      /**
 442       * Return a token of an arbitrary user by tokenid, including details of the associated user and the service name.
 443       * If no tokens exist an exception is thrown
 444       *
 445       * The returned value is a stdClass:
 446       * ->id token id
 447       * ->token
 448       * ->firstname user firstname
 449       * ->lastname
 450       * ->name service name
 451       *
 452       * @param int $tokenid token id
 453       * @return stdClass
 454       */
 455      public function get_token_by_id_with_details($tokenid) {
 456          global $DB;
 457          $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.creatorid
 458                  FROM {external_tokens} t, {user} u, {external_services} s
 459                  WHERE t.id=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
 460          $token = $DB->get_record_sql($sql, array($tokenid, EXTERNAL_TOKEN_PERMANENT), MUST_EXIST);
 461          return $token;
 462      }
 463  
 464      /**
 465       * Return a database token record for a token id
 466       *
 467       * @param int $tokenid token id
 468       * @return object token
 469       */
 470      public function get_token_by_id($tokenid) {
 471          global $DB;
 472          return $DB->get_record('external_tokens', array('id' => $tokenid));
 473      }
 474  
 475      /**
 476       * Delete a token
 477       *
 478       * @param int $tokenid token id
 479       */
 480      public function delete_user_ws_token($tokenid) {
 481          global $DB;
 482          $DB->delete_records('external_tokens', array('id'=>$tokenid));
 483      }
 484  
 485      /**
 486       * Delete all the tokens belonging to a user.
 487       *
 488       * @param int $userid the user id whose tokens must be deleted
 489       */
 490      public static function delete_user_ws_tokens($userid) {
 491          global $DB;
 492          $DB->delete_records('external_tokens', array('userid' => $userid));
 493      }
 494  
 495      /**
 496       * Delete a service
 497       * Also delete function references and authorised user references.
 498       *
 499       * @param int $serviceid service id
 500       */
 501      public function delete_service($serviceid) {
 502          global $DB;
 503          $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
 504          $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
 505          $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
 506          $DB->delete_records('external_services', array('id' => $serviceid));
 507      }
 508  
 509      /**
 510       * Get a full database token record for a given token value
 511       *
 512       * @param string $token
 513       * @throws moodle_exception if there is multiple result
 514       */
 515      public function get_user_ws_token($token) {
 516          global $DB;
 517          return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
 518      }
 519  
 520      /**
 521       * Get the functions list of a service list (by id)
 522       *
 523       * @param array $serviceids service ids
 524       * @return array of functions
 525       */
 526      public function get_external_functions($serviceids) {
 527          global $DB;
 528          if (!empty($serviceids)) {
 529              list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
 530              $sql = "SELECT f.*
 531                        FROM {external_functions} f
 532                       WHERE f.name IN (SELECT sf.functionname
 533                                          FROM {external_services_functions} sf
 534                                         WHERE sf.externalserviceid $serviceids)
 535                       ORDER BY f.name ASC";
 536              $functions = $DB->get_records_sql($sql, $params);
 537          } else {
 538              $functions = array();
 539          }
 540          return $functions;
 541      }
 542  
 543      /**
 544       * Get the functions of a service list (by shortname). It can return only enabled functions if required.
 545       *
 546       * @param array $serviceshortnames service shortnames
 547       * @param bool $enabledonly if true then only return functions for services that have been enabled
 548       * @return array functions
 549       */
 550      public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
 551          global $DB;
 552          if (!empty($serviceshortnames)) {
 553              $enabledonlysql = $enabledonly?' AND s.enabled = 1 ':'';
 554              list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
 555              $sql = "SELECT f.*
 556                        FROM {external_functions} f
 557                       WHERE f.name IN (SELECT sf.functionname
 558                                          FROM {external_services_functions} sf, {external_services} s
 559                                         WHERE s.shortname $serviceshortnames
 560                                               AND sf.externalserviceid = s.id
 561                                               " . $enabledonlysql . ")";
 562              $functions = $DB->get_records_sql($sql, $params);
 563          } else {
 564              $functions = array();
 565          }
 566          return $functions;
 567      }
 568  
 569      /**
 570       * Get functions not included in a service
 571       *
 572       * @param int $serviceid service id
 573       * @return array functions
 574       */
 575      public function get_not_associated_external_functions($serviceid) {
 576          global $DB;
 577          $select = "name NOT IN (SELECT s.functionname
 578                                    FROM {external_services_functions} s
 579                                   WHERE s.externalserviceid = :sid
 580                                 )";
 581  
 582          $functions = $DB->get_records_select('external_functions',
 583                          $select, array('sid' => $serviceid), 'name');
 584  
 585          return $functions;
 586      }
 587  
 588      /**
 589       * Get list of required capabilities of a service, sorted by functions
 590       * Example of returned value:
 591       *  Array
 592       *  (
 593       *    [core_group_create_groups] => Array
 594       *    (
 595       *       [0] => moodle/course:managegroups
 596       *    )
 597       *
 598       *    [core_enrol_get_enrolled_users] => Array
 599       *    (
 600       *       [0] => moodle/user:viewdetails
 601       *       [1] => moodle/user:viewhiddendetails
 602       *       [2] => moodle/course:useremail
 603       *       [3] => moodle/user:update
 604       *       [4] => moodle/site:accessallgroups
 605       *    )
 606       *  )
 607       * @param int $serviceid service id
 608       * @return array
 609       */
 610      public function get_service_required_capabilities($serviceid) {
 611          $functions = $this->get_external_functions(array($serviceid));
 612          $requiredusercaps = array();
 613          foreach ($functions as $function) {
 614              $functioncaps = explode(',', $function->capabilities);
 615              if (!empty($functioncaps) and !empty($functioncaps[0])) {
 616                  foreach ($functioncaps as $functioncap) {
 617                      $requiredusercaps[$function->name][] = trim($functioncap);
 618                  }
 619              }
 620          }
 621          return $requiredusercaps;
 622      }
 623  
 624      /**
 625       * Get user capabilities (with context)
 626       * Only useful for documentation purpose
 627       * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
 628       * required by users. In theory we should not need to display this kind of information
 629       * as the front end does not display it itself. In pratice,
 630       * admins would like the info, for more info you can follow: MDL-29962
 631       *
 632       * @deprecated since Moodle 3.11 in MDL-67748 without a replacement.
 633       * @todo MDL-70187 Please delete this method completely in Moodle 4.3, thank you.
 634       * @param int $userid user id
 635       * @return array
 636       */
 637      public function get_user_capabilities($userid) {
 638          global $DB;
 639  
 640          debugging('webservice::get_user_capabilities() has been deprecated.', DEBUG_DEVELOPER);
 641  
 642          //retrieve the user capabilities
 643          $sql = "SELECT DISTINCT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
 644              WHERE rc.roleid=ra.roleid AND ra.userid= ? AND rc.permission = ?";
 645          $dbusercaps = $DB->get_records_sql($sql, array($userid, CAP_ALLOW));
 646          $usercaps = array();
 647          foreach ($dbusercaps as $usercap) {
 648              $usercaps[$usercap->capability] = true;
 649          }
 650          return $usercaps;
 651      }
 652  
 653      /**
 654       * Get missing user capabilities for the given service's functions.
 655       *
 656       * Every external function can declare some required capabilities to allow for easier setup of the web services.
 657       * However, that is supposed to be used for informational admin report only. There is no automatic evaluation of
 658       * the declared capabilities and the context of the capability evaluation is ignored. Also, actual capability
 659       * evaluation is much more complex as it allows for overrides etc.
 660       *
 661       * Returned are capabilities that the given users do not seem to have assigned anywhere at the site and that should
 662       * be checked by the admin.
 663       *
 664       * Do not use this method for anything else, particularly not for any security related checks. See MDL-29962 for the
 665       * background of why we have this - there are arguments for dropping this feature completely.
 666       *
 667       * @param array $users List of users to check, consisting of objects, arrays or integer ids.
 668       * @param int $serviceid The id of the external service to check.
 669       * @return array List of missing capabilities: (int)userid => array of (string)capabilitynames
 670       */
 671      public function get_missing_capabilities_by_users(array $users, int $serviceid): array {
 672          global $DB;
 673  
 674          // The following are default capabilities for all authenticated users and we will assume them granted.
 675          $commoncaps = get_default_capabilities('user');
 676  
 677          // Get the list of additional capabilities required by the service.
 678          $servicecaps = [];
 679          foreach ($this->get_service_required_capabilities($serviceid) as $service => $caps) {
 680              foreach ($caps as $cap) {
 681                  if (empty($commoncaps[$cap])) {
 682                      $servicecaps[$cap] = true;
 683                  }
 684              }
 685          }
 686  
 687          if (empty($servicecaps)) {
 688              return [];
 689          }
 690  
 691          // Prepare a list of user ids we want to check.
 692          $userids = [];
 693          foreach ($users as $user) {
 694              if (is_object($user) && isset($user->id)) {
 695                  $userids[$user->id] = true;
 696              } else if (is_array($user) && isset($user['id'])) {
 697                  $userids[$user['id']] = true;
 698              } else {
 699                  throw new coding_exception('Unexpected format of users list in webservice::get_missing_capabilities_by_users().');
 700              }
 701          }
 702  
 703          // Prepare a matrix of missing capabilities x users - consider them all missing by default.
 704          foreach (array_keys($userids) as $userid) {
 705              foreach (array_keys($servicecaps) as $capname) {
 706                  $matrix[$userid][$capname] = true;
 707              }
 708          }
 709  
 710          list($capsql, $capparams) = $DB->get_in_or_equal(array_keys($servicecaps), SQL_PARAMS_NAMED, 'paramcap');
 711          list($usersql, $userparams) = $DB->get_in_or_equal(array_keys($userids), SQL_PARAMS_NAMED, 'paramuser');
 712  
 713          $sql = "SELECT c.name AS capability, u.id AS userid
 714                    FROM {capabilities} c
 715                    JOIN {role_capabilities} rc ON c.name = rc.capability
 716                    JOIN {role_assignments} ra ON ra.roleid = rc.roleid
 717                    JOIN {user} u ON ra.userid = u.id
 718                   WHERE rc.permission = :capallow
 719                     AND c.name {$capsql}
 720                     AND u.id {$usersql}";
 721  
 722          $params = $capparams + $userparams + [
 723              'capallow' => CAP_ALLOW,
 724          ];
 725  
 726          $rs = $DB->get_recordset_sql($sql, $params);
 727  
 728          foreach ($rs as $record) {
 729              // If there was a potential role assignment found that might grant the user the given capability,
 730              // remove it from the matrix. Again, we ignore all the contexts, prohibits, prevents and other details
 731              // of the permissions evaluations. See the function docblock for details.
 732              unset($matrix[$record->userid][$record->capability]);
 733          }
 734  
 735          $rs->close();
 736  
 737          foreach ($matrix as $userid => $caps) {
 738              $matrix[$userid] = array_keys($caps);
 739              if (empty($matrix[$userid])) {
 740                  unset($matrix[$userid]);
 741              }
 742          }
 743  
 744          return $matrix;
 745      }
 746  
 747      /**
 748       * Get an external service for a given service id
 749       *
 750       * @param int $serviceid service id
 751       * @param int $strictness IGNORE_MISSING, MUST_EXIST...
 752       * @return stdClass external service
 753       */
 754      public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) {
 755          global $DB;
 756          $service = $DB->get_record('external_services',
 757                          array('id' => $serviceid), '*', $strictness);
 758          return $service;
 759      }
 760  
 761      /**
 762       * Get an external service for a given shortname
 763       *
 764       * @param string $shortname service shortname
 765       * @param int $strictness IGNORE_MISSING, MUST_EXIST...
 766       * @return stdClass external service
 767       */
 768      public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) {
 769          global $DB;
 770          $service = $DB->get_record('external_services',
 771                          array('shortname' => $shortname), '*', $strictness);
 772          return $service;
 773      }
 774  
 775      /**
 776       * Get an external function for a given function id
 777       *
 778       * @param int $functionid function id
 779       * @param int $strictness IGNORE_MISSING, MUST_EXIST...
 780       * @return stdClass external function
 781       */
 782      public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING) {
 783          global $DB;
 784          $function = $DB->get_record('external_functions',
 785                              array('id' => $functionid), '*', $strictness);
 786          return $function;
 787      }
 788  
 789      /**
 790       * Add a function to a service
 791       *
 792       * @param string $functionname function name
 793       * @param int $serviceid service id
 794       */
 795      public function add_external_function_to_service($functionname, $serviceid) {
 796          global $DB;
 797          $addedfunction = new stdClass();
 798          $addedfunction->externalserviceid = $serviceid;
 799          $addedfunction->functionname = $functionname;
 800          $DB->insert_record('external_services_functions', $addedfunction);
 801      }
 802  
 803      /**
 804       * Add a service
 805       * It generates the timecreated field automatically.
 806       *
 807       * @param stdClass $service
 808       * @return serviceid integer
 809       */
 810      public function add_external_service($service) {
 811          global $DB;
 812          $service->timecreated = time();
 813          $serviceid = $DB->insert_record('external_services', $service);
 814          return $serviceid;
 815      }
 816  
 817      /**
 818       * Update a service
 819       * It modifies the timemodified automatically.
 820       *
 821       * @param stdClass $service
 822       */
 823      public function update_external_service($service) {
 824          global $DB;
 825          $service->timemodified = time();
 826          $DB->update_record('external_services', $service);
 827      }
 828  
 829      /**
 830       * Test whether an external function is already linked to a service
 831       *
 832       * @param string $functionname function name
 833       * @param int $serviceid service id
 834       * @return bool true if a matching function exists for the service, else false.
 835       * @throws dml_exception if error
 836       */
 837      public function service_function_exists($functionname, $serviceid) {
 838          global $DB;
 839          return $DB->record_exists('external_services_functions',
 840                              array('externalserviceid' => $serviceid,
 841                                  'functionname' => $functionname));
 842      }
 843  
 844      /**
 845       * Remove a function from a service
 846       *
 847       * @param string $functionname function name
 848       * @param int $serviceid service id
 849       */
 850      public function remove_external_function_from_service($functionname, $serviceid) {
 851          global $DB;
 852          $DB->delete_records('external_services_functions',
 853                      array('externalserviceid' => $serviceid, 'functionname' => $functionname));
 854  
 855      }
 856  
 857      /**
 858       * Return a list with all the valid user tokens for the given user, it only excludes expired tokens.
 859       *
 860       * @param  string $userid user id to retrieve tokens from
 861       * @return array array of token entries
 862       * @since Moodle 3.2
 863       */
 864      public static function get_active_tokens($userid) {
 865          global $DB;
 866  
 867          $sql = 'SELECT t.*, s.name as servicename FROM {external_tokens} t JOIN
 868                  {external_services} s ON t.externalserviceid = s.id WHERE
 869                  t.userid = :userid AND (COALESCE(t.validuntil, 0) = 0 OR t.validuntil > :now)';
 870          $params = array('userid' => $userid, 'now' => time());
 871          return $DB->get_records_sql($sql, $params);
 872      }
 873  }
 874  
 875  /**
 876   * Exception indicating access control problem in web service call
 877   * This exception should return general errors about web service setup.
 878   * Errors related to the user like wrong username/password should not use it,
 879   * you should not use this exception if you want to let the client implement
 880   * some code logic against an access error.
 881   *
 882   * @package    core_webservice
 883   * @copyright  2009 Petr Skodak
 884   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 885   */
 886  class webservice_access_exception extends moodle_exception {
 887  
 888      /**
 889       * Constructor
 890       *
 891       * @param string $debuginfo the debug info
 892       */
 893      function __construct($debuginfo) {
 894          parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
 895      }
 896  }
 897  
 898  /**
 899   * Check if a protocol is enabled
 900   *
 901   * @param string $protocol name of WS protocol ('rest', 'soap', 'xmlrpc'...)
 902   * @return bool true if the protocol is enabled
 903   */
 904  function webservice_protocol_is_enabled($protocol) {
 905      global $CFG;
 906  
 907      if (empty($CFG->enablewebservices) || empty($CFG->webserviceprotocols)) {
 908          return false;
 909      }
 910  
 911      $active = explode(',', $CFG->webserviceprotocols);
 912  
 913      return(in_array($protocol, $active));
 914  }
 915  
 916  /**
 917   * Mandatory interface for all test client classes.
 918   *
 919   * @package    core_webservice
 920   * @copyright  2009 Petr Skodak
 921   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 922   */
 923  interface webservice_test_client_interface {
 924  
 925      /**
 926       * Execute test client WS request
 927       *
 928       * @param string $serverurl server url (including the token param)
 929       * @param string $function web service function name
 930       * @param array $params parameters of the web service function
 931       * @return mixed
 932       */
 933      public function simpletest($serverurl, $function, $params);
 934  }
 935  
 936  /**
 937   * Mandatory interface for all web service protocol classes
 938   *
 939   * @package    core_webservice
 940   * @copyright  2009 Petr Skodak
 941   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 942   */
 943  interface webservice_server_interface {
 944  
 945      /**
 946       * Process request from client.
 947       */
 948      public function run();
 949  }
 950  
 951  /**
 952   * Abstract web service base class.
 953   *
 954   * @package    core_webservice
 955   * @copyright  2009 Petr Skodak
 956   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 957   */
 958  abstract class webservice_server implements webservice_server_interface {
 959  
 960      /** @var string Name of the web server plugin */
 961      protected $wsname = null;
 962  
 963      /** @var string Name of local user */
 964      protected $username = null;
 965  
 966      /** @var string Password of the local user */
 967      protected $password = null;
 968  
 969      /** @var int The local user */
 970      protected $userid = null;
 971  
 972      /** @var integer Authentication method one of WEBSERVICE_AUTHMETHOD_* */
 973      protected $authmethod;
 974  
 975      /** @var string Authentication token*/
 976      protected $token = null;
 977  
 978      /** @var stdClass Restricted context */
 979      protected $restricted_context;
 980  
 981      /** @var int Restrict call to one service id*/
 982      protected $restricted_serviceid = null;
 983  
 984      /**
 985       * Constructor
 986       *
 987       * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
 988       */
 989      public function __construct($authmethod) {
 990          $this->authmethod = $authmethod;
 991      }
 992  
 993  
 994      /**
 995       * Authenticate user using username+password or token.
 996       * This function sets up $USER global.
 997       * It is safe to use has_capability() after this.
 998       * This method also verifies user is allowed to use this
 999       * server.
1000       */
1001      protected function authenticate_user() {
1002          global $CFG, $DB;
1003  
1004          if (!NO_MOODLE_COOKIES) {
1005              throw new coding_exception('Cookies must be disabled in WS servers!');
1006          }
1007  
1008          $loginfaileddefaultparams = array(
1009              'other' => array(
1010                  'method' => $this->authmethod,
1011                  'reason' => null
1012              )
1013          );
1014  
1015          if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1016  
1017              //we check that authentication plugin is enabled
1018              //it is only required by simple authentication
1019              if (!is_enabled_auth('webservice')) {
1020                  throw new webservice_access_exception('The web service authentication plugin is disabled.');
1021              }
1022  
1023              if (!$auth = get_auth_plugin('webservice')) {
1024                  throw new webservice_access_exception('The web service authentication plugin is missing.');
1025              }
1026  
1027              $this->restricted_context = context_system::instance();
1028  
1029              if (!$this->username) {
1030                  throw new moodle_exception('missingusername', 'webservice');
1031              }
1032  
1033              if (!$this->password) {
1034                  throw new moodle_exception('missingpassword', 'webservice');
1035              }
1036  
1037              if (!$auth->user_login_webservice($this->username, $this->password)) {
1038  
1039                  // Log failed login attempts.
1040                  $params = $loginfaileddefaultparams;
1041                  $params['other']['reason'] = 'password';
1042                  $params['other']['username'] = $this->username;
1043                  $event = \core\event\webservice_login_failed::create($params);
1044                  $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('simpleauthlog', 'webservice'), '' ,
1045                      get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0));
1046                  $event->trigger();
1047  
1048                  throw new moodle_exception('wrongusernamepassword', 'webservice');
1049              }
1050  
1051              $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
1052  
1053          } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
1054              $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
1055          } else {
1056              $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
1057          }
1058  
1059          // Cannot authenticate unless maintenance access is granted.
1060          $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system::instance(), $user);
1061          if (!empty($CFG->maintenance_enabled) and !$hasmaintenanceaccess) {
1062              throw new moodle_exception('sitemaintenance', 'admin');
1063          }
1064  
1065          //only confirmed user should be able to call web service
1066          if (!empty($user->deleted)) {
1067              $params = $loginfaileddefaultparams;
1068              $params['other']['reason'] = 'user_deleted';
1069              $params['other']['username'] = $user->username;
1070              $event = \core\event\webservice_login_failed::create($params);
1071              $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserdeleted', 'webservice',
1072                  $user->username) . " - ".getremoteaddr(), 0, $user->id));
1073              $event->trigger();
1074              throw new webservice_access_exception('Refused web service access for deleted username: ' . $user->username);
1075          }
1076  
1077          //only confirmed user should be able to call web service
1078          if (empty($user->confirmed)) {
1079              $params = $loginfaileddefaultparams;
1080              $params['other']['reason'] = 'user_unconfirmed';
1081              $params['other']['username'] = $user->username;
1082              $event = \core\event\webservice_login_failed::create($params);
1083              $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserunconfirmed', 'webservice',
1084                  $user->username) . " - ".getremoteaddr(), 0, $user->id));
1085              $event->trigger();
1086              throw new moodle_exception('wsaccessuserunconfirmed', 'webservice', '', $user->username);
1087          }
1088  
1089          //check the user is suspended
1090          if (!empty($user->suspended)) {
1091              $params = $loginfaileddefaultparams;
1092              $params['other']['reason'] = 'user_unconfirmed';
1093              $params['other']['username'] = $user->username;
1094              $event = \core\event\webservice_login_failed::create($params);
1095              $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusersuspended', 'webservice',
1096                  $user->username) . " - ".getremoteaddr(), 0, $user->id));
1097              $event->trigger();
1098              throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
1099          }
1100  
1101          //retrieve the authentication plugin if no previously done
1102          if (empty($auth)) {
1103            $auth  = get_auth_plugin($user->auth);
1104          }
1105  
1106          // check if credentials have expired
1107          if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
1108              $days2expire = $auth->password_expire($user->username);
1109              if (intval($days2expire) < 0 ) {
1110                  $params = $loginfaileddefaultparams;
1111                  $params['other']['reason'] = 'password_expired';
1112                  $params['other']['username'] = $user->username;
1113                  $event = \core\event\webservice_login_failed::create($params);
1114                  $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserexpired', 'webservice',
1115                      $user->username) . " - ".getremoteaddr(), 0, $user->id));
1116                  $event->trigger();
1117                  throw new webservice_access_exception('Refused web service access for password expired username: ' . $user->username);
1118              }
1119          }
1120  
1121          //check if the auth method is nologin (in this case refuse connection)
1122          if ($user->auth=='nologin') {
1123              $params = $loginfaileddefaultparams;
1124              $params['other']['reason'] = 'login';
1125              $params['other']['username'] = $user->username;
1126              $event = \core\event\webservice_login_failed::create($params);
1127              $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusernologin', 'webservice',
1128                  $user->username) . " - ".getremoteaddr(), 0, $user->id));
1129              $event->trigger();
1130              throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
1131          }
1132  
1133          // now fake user login, the session is completely empty too
1134          enrol_check_plugins($user);
1135          \core\session\manager::set_user($user);
1136          set_login_session_preferences();
1137          $this->userid = $user->id;
1138  
1139          if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
1140              throw new webservice_access_exception("You are not allowed to use the {$this->wsname} protocol " .
1141                  "(missing capability: webservice/{$this->wsname}:use)");
1142          }
1143  
1144          external_api::set_context_restriction($this->restricted_context);
1145      }
1146  
1147      /**
1148       * User authentication by token
1149       *
1150       * @param string $tokentype token type (EXTERNAL_TOKEN_EMBEDDED or EXTERNAL_TOKEN_PERMANENT)
1151       * @return stdClass the authenticated user
1152       * @throws webservice_access_exception
1153       */
1154      protected function authenticate_by_token($tokentype){
1155          global $DB;
1156  
1157          $loginfaileddefaultparams = array(
1158              'other' => array(
1159                  'method' => $this->authmethod,
1160                  'reason' => null
1161              )
1162          );
1163  
1164          if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
1165              // Log failed login attempts.
1166              $params = $loginfaileddefaultparams;
1167              $params['other']['reason'] = 'invalid_token';
1168              $event = \core\event\webservice_login_failed::create($params);
1169              $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
1170                  get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0));
1171              $event->trigger();
1172              throw new moodle_exception('invalidtoken', 'webservice');
1173          }
1174  
1175          if ($token->validuntil and $token->validuntil < time()) {
1176              $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
1177              throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
1178          }
1179  
1180          if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
1181              if (!\core\session\manager::session_exists($token->sid)){
1182                  $DB->delete_records('external_tokens', array('sid'=>$token->sid));
1183                  throw new webservice_access_exception('Invalid session based token - session not found or expired');
1184              }
1185          }
1186  
1187          if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1188              $params = $loginfaileddefaultparams;
1189              $params['other']['reason'] = 'ip_restricted';
1190              $params['other']['tokenid'] = $token->id;
1191              $event = \core\event\webservice_login_failed::create($params);
1192              $event->add_record_snapshot('external_tokens', $token);
1193              $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
1194                  get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0));
1195              $event->trigger();
1196              throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
1197                      . ' is not supported - check this allowed user');
1198          }
1199  
1200          $this->restricted_context = context::instance_by_id($token->contextid);
1201          $this->restricted_serviceid = $token->externalserviceid;
1202  
1203          $user = $DB->get_record('user', array('id'=>$token->userid), '*', MUST_EXIST);
1204  
1205          // log token access
1206          webservice::update_token_lastaccess($token);
1207  
1208          return $user;
1209  
1210      }
1211  
1212      /**
1213       * Intercept some moodlewssettingXXX $_GET and $_POST parameter
1214       * that are related to the web service call and are not the function parameters
1215       */
1216      protected function set_web_service_call_settings() {
1217          global $CFG;
1218  
1219          // Default web service settings.
1220          // Must be the same XXX key name as the external_settings::set_XXX function.
1221          // Must be the same XXX ws parameter name as 'moodlewssettingXXX'.
1222          $externalsettings = array(
1223              'raw' => array('default' => false, 'type' => PARAM_BOOL),
1224              'fileurl' => array('default' => true, 'type' => PARAM_BOOL),
1225              'filter' => array('default' => false, 'type' => PARAM_BOOL),
1226              'lang' => array('default' => '', 'type' => PARAM_LANG),
1227              'timezone' => array('default' => '', 'type' => PARAM_TIMEZONE),
1228          );
1229  
1230          // Load the external settings with the web service settings.
1231          $settings = external_settings::get_instance();
1232          foreach ($externalsettings as $name => $settingdata) {
1233  
1234              $wsparamname = 'moodlewssetting' . $name;
1235  
1236              // Retrieve and remove the setting parameter from the request.
1237              $value = optional_param($wsparamname, $settingdata['default'], $settingdata['type']);
1238              unset($_GET[$wsparamname]);
1239              unset($_POST[$wsparamname]);
1240  
1241              $functioname = 'set_' . $name;
1242              $settings->$functioname($value);
1243          }
1244  
1245      }
1246  }
1247  
1248  /**
1249   * Web Service server base class.
1250   *
1251   * This class handles both simple and token authentication.
1252   *
1253   * @package    core_webservice
1254   * @copyright  2009 Petr Skodak
1255   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1256   */
1257  abstract class webservice_base_server extends webservice_server {
1258  
1259      /** @var array The function parameters - the real values submitted in the request */
1260      protected $parameters = null;
1261  
1262      /** @var string The name of the function that is executed */
1263      protected $functionname = null;
1264  
1265      /** @var stdClass Full function description */
1266      protected $function = null;
1267  
1268      /** @var mixed Function return value */
1269      protected $returns = null;
1270  
1271      /** @var array List of methods and their information provided by the web service. */
1272      protected $servicemethods;
1273  
1274      /** @var  array List of struct classes generated for the web service methods. */
1275      protected $servicestructs;
1276  
1277      /**
1278       * This method parses the request input, it needs to get:
1279       *  1/ user authentication - username+password or token
1280       *  2/ function name
1281       *  3/ function parameters
1282       */
1283      abstract protected function parse_request();
1284  
1285      /**
1286       * Send the result of function call to the WS client.
1287       */
1288      abstract protected function send_response();
1289  
1290      /**
1291       * Send the error information to the WS client.
1292       *
1293       * @param exception $ex
1294       */
1295      abstract protected function send_error($ex=null);
1296  
1297      /**
1298       * Process request from client.
1299       *
1300       * @uses die
1301       */
1302      public function run() {
1303          global $CFG, $USER, $SESSION;
1304  
1305          // we will probably need a lot of memory in some functions
1306          raise_memory_limit(MEMORY_EXTRA);
1307  
1308          // set some longer timeout, this script is not sending any output,
1309          // this means we need to manually extend the timeout operations
1310          // that need longer time to finish
1311          external_api::set_timeout();
1312  
1313          // set up exception handler first, we want to sent them back in correct format that
1314          // the other system understands
1315          // we do not need to call the original default handler because this ws handler does everything
1316          set_exception_handler(array($this, 'exception_handler'));
1317  
1318          // init all properties from the request data
1319          $this->parse_request();
1320  
1321          // authenticate user, this has to be done after the request parsing
1322          // this also sets up $USER and $SESSION
1323          $this->authenticate_user();
1324  
1325          // find all needed function info and make sure user may actually execute the function
1326          $this->load_function_info();
1327  
1328          // Log the web service request.
1329          $params = array(
1330              'other' => array(
1331                  'function' => $this->functionname
1332              )
1333          );
1334          $event = \core\event\webservice_function_called::create($params);
1335          $event->set_legacy_logdata(array(SITEID, 'webservice', $this->functionname, '' , getremoteaddr() , 0, $this->userid));
1336          $event->trigger();
1337  
1338          // Do additional setup stuff.
1339          $settings = external_settings::get_instance();
1340          $sessionlang = $settings->get_lang();
1341          if (!empty($sessionlang)) {
1342              $SESSION->lang = $sessionlang;
1343          }
1344  
1345          setup_lang_from_browser();
1346  
1347          if (empty($CFG->lang)) {
1348              if (empty($SESSION->lang)) {
1349                  $CFG->lang = 'en';
1350              } else {
1351                  $CFG->lang = $SESSION->lang;
1352              }
1353          }
1354  
1355          // Change timezone only in sites where it isn't forced.
1356          $newtimezone = $settings->get_timezone();
1357          if (!empty($newtimezone) && (!isset($CFG->forcetimezone) || $CFG->forcetimezone == 99)) {
1358              $USER->timezone = $newtimezone;
1359          }
1360  
1361          // finally, execute the function - any errors are catched by the default exception handler
1362          $this->execute();
1363  
1364          // send the results back in correct format
1365          $this->send_response();
1366  
1367          // session cleanup
1368          $this->session_cleanup();
1369  
1370          die;
1371      }
1372  
1373      /**
1374       * Specialised exception handler, we can not use the standard one because
1375       * it can not just print html to output.
1376       *
1377       * @param exception $ex
1378       * $uses exit
1379       */
1380      public function exception_handler($ex) {
1381          // detect active db transactions, rollback and log as error
1382          abort_all_db_transactions();
1383  
1384          // some hacks might need a cleanup hook
1385          $this->session_cleanup($ex);
1386  
1387          // now let the plugin send the exception to client
1388          $this->send_error($ex);
1389  
1390          // not much else we can do now, add some logging later
1391          exit(1);
1392      }
1393  
1394      /**
1395       * Future hook needed for emulated sessions.
1396       *
1397       * @param exception $exception null means normal termination, $exception received when WS call failed
1398       */
1399      protected function session_cleanup($exception=null) {
1400          if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1401              // nothing needs to be done, there is no persistent session
1402          } else {
1403              // close emulated session if used
1404          }
1405      }
1406  
1407      /**
1408       * Fetches the function description from database,
1409       * verifies user is allowed to use this function and
1410       * loads all paremeters and return descriptions.
1411       */
1412      protected function load_function_info() {
1413          global $DB, $USER, $CFG;
1414  
1415          if (empty($this->functionname)) {
1416              throw new invalid_parameter_exception('Missing function name');
1417          }
1418  
1419          // function must exist
1420          $function = external_api::external_function_info($this->functionname);
1421  
1422          if ($this->restricted_serviceid) {
1423              $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
1424              $wscond1 = 'AND s.id = :sid1';
1425              $wscond2 = 'AND s.id = :sid2';
1426          } else {
1427              $params = array();
1428              $wscond1 = '';
1429              $wscond2 = '';
1430          }
1431  
1432          // now let's verify access control
1433  
1434          // now make sure the function is listed in at least one service user is allowed to use
1435          // allow access only if:
1436          //  1/ entry in the external_services_users table if required
1437          //  2/ validuntil not reached
1438          //  3/ has capability if specified in service desc
1439          //  4/ iprestriction
1440  
1441          $sql = "SELECT s.*, NULL AS iprestriction
1442                    FROM {external_services} s
1443                    JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
1444                   WHERE s.enabled = 1 $wscond1
1445  
1446                   UNION
1447  
1448                  SELECT s.*, su.iprestriction
1449                    FROM {external_services} s
1450                    JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
1451                    JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1452                   WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1453          $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
1454  
1455          $rs = $DB->get_recordset_sql($sql, $params);
1456          // now make sure user may access at least one service
1457          $remoteaddr = getremoteaddr();
1458          $allowed = false;
1459          foreach ($rs as $service) {
1460              if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1461                  continue; // cap required, sorry
1462              }
1463              if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1464                  continue; // wrong request source ip, sorry
1465              }
1466              $allowed = true;
1467              break; // one service is enough, no need to continue
1468          }
1469          $rs->close();
1470          if (!$allowed) {
1471              throw new webservice_access_exception(
1472                      'Access to the function '.$this->functionname.'() is not allowed.
1473                       There could be multiple reasons for this:
1474                       1. The service linked to the user token does not contain the function.
1475                       2. The service is user-restricted and the user is not listed.
1476                       3. The service is IP-restricted and the user IP is not listed.
1477                       4. The service is time-restricted and the time has expired.
1478                       5. The token is time-restricted and the time has expired.
1479                       6. The service requires a specific capability which the user does not have.
1480                       7. The function is called with username/password (no user token is sent)
1481                       and none of the services has the function to allow the user.
1482                       These settings can be found in Administration > Site administration
1483                       > Server > Web services > External services and Manage tokens.');
1484          }
1485  
1486          // we have all we need now
1487          $this->function = $function;
1488      }
1489  
1490      /**
1491       * Execute previously loaded function using parameters parsed from the request data.
1492       */
1493      protected function execute() {
1494          // validate params, this also sorts the params properly, we need the correct order in the next part
1495          $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
1496          $params = array_values($params);
1497  
1498          // Allow any Moodle plugin a chance to override this call. This is a convenient spot to
1499          // make arbitrary behaviour customisations, for example to affect the mobile app behaviour.
1500          // The overriding plugin could call the 'real' function first and then modify the results,
1501          // or it could do a completely separate thing.
1502          $callbacks = get_plugins_with_function('override_webservice_execution');
1503          foreach ($callbacks as $plugintype => $plugins) {
1504              foreach ($plugins as $plugin => $callback) {
1505                  $result = $callback($this->function, $params);
1506                  if ($result !== false) {
1507                      // If the callback returns anything other than false, we assume it replaces the
1508                      // real function.
1509                      $this->returns = $result;
1510                      return;
1511                  }
1512              }
1513          }
1514  
1515          // execute - yay!
1516          $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), $params);
1517      }
1518  
1519      /**
1520       * Load the virtual class needed for the web service.
1521       *
1522       * Initialises the virtual class that contains the web service functions that the user is allowed to use.
1523       * The web service function will be available if the user:
1524       * - is validly registered in the external_services_users table.
1525       * - has the required capability.
1526       * - meets the IP restriction requirement.
1527       * This virtual class can be used by web service protocols such as SOAP, especially when generating WSDL.
1528       */
1529      protected function init_service_class() {
1530          global $USER, $DB;
1531  
1532          // Initialise service methods and struct classes.
1533          $this->servicemethods = array();
1534          $this->servicestructs = array();
1535  
1536          $params = array();
1537          $wscond1 = '';
1538          $wscond2 = '';
1539          if ($this->restricted_serviceid) {
1540              $params = array('sid1' => $this->restricted_serviceid, 'sid2' => $this->restricted_serviceid);
1541              $wscond1 = 'AND s.id = :sid1';
1542              $wscond2 = 'AND s.id = :sid2';
1543          }
1544  
1545          $sql = "SELECT s.*, NULL AS iprestriction
1546                    FROM {external_services} s
1547                    JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
1548                   WHERE s.enabled = 1 $wscond1
1549  
1550                   UNION
1551  
1552                  SELECT s.*, su.iprestriction
1553                    FROM {external_services} s
1554                    JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
1555                    JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1556                   WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1557          $params = array_merge($params, array('userid' => $USER->id, 'now' => time()));
1558  
1559          $serviceids = array();
1560          $remoteaddr = getremoteaddr();
1561  
1562          // Query list of external services for the user.
1563          $rs = $DB->get_recordset_sql($sql, $params);
1564  
1565          // Check which service ID to include.
1566          foreach ($rs as $service) {
1567              if (isset($serviceids[$service->id])) {
1568                  continue; // Service already added.
1569              }
1570              if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1571                  continue; // Cap required, sorry.
1572              }
1573              if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1574                  continue; // Wrong request source ip, sorry.
1575              }
1576              $serviceids[$service->id] = $service->id;
1577          }
1578          $rs->close();
1579  
1580          // Generate the virtual class name.
1581          $classname = 'webservices_virtual_class_000000';
1582          while (class_exists($classname)) {
1583              $classname++;
1584          }
1585          $this->serviceclass = $classname;
1586  
1587          // Get the list of all available external functions.
1588          $wsmanager = new webservice();
1589          $functions = $wsmanager->get_external_functions($serviceids);
1590  
1591          // Generate code for the virtual methods for this web service.
1592          $methods = '';
1593          foreach ($functions as $function) {
1594              $methods .= $this->get_virtual_method_code($function);
1595          }
1596  
1597          $code = <<<EOD
1598  /**
1599   * Virtual class web services for user id $USER->id in context {$this->restricted_context->id}.
1600   */
1601  class $classname {
1602  $methods
1603  }
1604  EOD;
1605          // Load the virtual class definition into memory.
1606          eval($code);
1607      }
1608  
1609      /**
1610       * Generates a struct class.
1611       *
1612       * @param external_single_structure $structdesc The basis of the struct class to be generated.
1613       * @return string The class name of the generated struct class.
1614       */
1615      protected function generate_simple_struct_class(external_single_structure $structdesc) {
1616          global $USER;
1617  
1618          $propeties = array();
1619          $fields = array();
1620          foreach ($structdesc->keys as $name => $fieldsdesc) {
1621              $type = $this->get_phpdoc_type($fieldsdesc);
1622              $propertytype = array('type' => $type);
1623              if (empty($fieldsdesc->allownull) || $fieldsdesc->allownull == NULL_ALLOWED) {
1624                  $propertytype['nillable'] = true;
1625              }
1626              $propeties[$name] = $propertytype;
1627              $fields[] = '    /** @var ' . $type . ' $' . $name . '*/';
1628              $fields[] = '    public $' . $name .';';
1629          }
1630          $fieldsstr = implode("\n", $fields);
1631  
1632          // We do this after the call to get_phpdoc_type() to avoid duplicate class creation.
1633          $classname = 'webservices_struct_class_000000';
1634          while (class_exists($classname)) {
1635              $classname++;
1636          }
1637          $code = <<<EOD
1638  /**
1639   * Virtual struct class for web services for user id $USER->id in context {$this->restricted_context->id}.
1640   */
1641  class $classname {
1642  $fieldsstr
1643  }
1644  EOD;
1645          // Load into memory.
1646          eval($code);
1647  
1648          // Prepare struct info.
1649          $structinfo = new stdClass();
1650          $structinfo->classname = $classname;
1651          $structinfo->properties = $propeties;
1652          // Add the struct info the the list of service struct classes.
1653          $this->servicestructs[] = $structinfo;
1654  
1655          return $classname;
1656      }
1657  
1658      /**
1659       * Returns a virtual method code for a web service function.
1660       *
1661       * @param stdClass $function a record from external_function
1662       * @return string The PHP code of the virtual method.
1663       * @throws coding_exception
1664       * @throws moodle_exception
1665       */
1666      protected function get_virtual_method_code($function) {
1667          $function = external_api::external_function_info($function);
1668  
1669          // Parameters and their defaults for the method signature.
1670          $paramanddefaults = array();
1671          // Parameters for external lib call.
1672          $params = array();
1673          $paramdesc = array();
1674          // The method's input parameters and their respective types.
1675          $inputparams = array();
1676          // The method's output parameters and their respective types.
1677          $outputparams = array();
1678  
1679          foreach ($function->parameters_desc->keys as $name => $keydesc) {
1680              $param = '$' . $name;
1681              $paramanddefault = $param;
1682              if ($keydesc->required == VALUE_OPTIONAL) {
1683                  // It does not make sense to declare a parameter VALUE_OPTIONAL. VALUE_OPTIONAL is used only for array/object key.
1684                  throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
1685              } else if ($keydesc->required == VALUE_DEFAULT) {
1686                  // Need to generate the default, if there is any.
1687                  if ($keydesc instanceof external_value) {
1688                      if ($keydesc->default === null) {
1689                          $paramanddefault .= ' = null';
1690                      } else {
1691                          switch ($keydesc->type) {
1692                              case PARAM_BOOL:
1693                                  $default = (int)$keydesc->default;
1694                                  break;
1695                              case PARAM_INT:
1696                                  $default = $keydesc->default;
1697                                  break;
1698                              case PARAM_FLOAT;
1699                                  $default = $keydesc->default;
1700                                  break;
1701                              default:
1702                                  $default = "'$keydesc->default'";
1703                          }
1704                          $paramanddefault .= " = $default";
1705                      }
1706                  } else {
1707                      // Accept empty array as default.
1708                      if (isset($keydesc->default) && is_array($keydesc->default) && empty($keydesc->default)) {
1709                          $paramanddefault .= ' = array()';
1710                      } else {
1711                          // For the moment we do not support default for other structure types.
1712                          throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
1713                      }
1714                  }
1715              }
1716  
1717              $params[] = $param;
1718              $paramanddefaults[] = $paramanddefault;
1719              $type = $this->get_phpdoc_type($keydesc);
1720              $inputparams[$name]['type'] = $type;
1721  
1722              $paramdesc[] = '* @param ' . $type . ' $' . $name . ' ' . $keydesc->desc;
1723          }
1724          $paramanddefaults = implode(', ', $paramanddefaults);
1725          $paramdescstr = implode("\n ", $paramdesc);
1726  
1727          $serviceclassmethodbody = $this->service_class_method_body($function, $params);
1728  
1729          if (empty($function->returns_desc)) {
1730              $return = '* @return void';
1731          } else {
1732              $type = $this->get_phpdoc_type($function->returns_desc);
1733              $outputparams['return']['type'] = $type;
1734              $return = '* @return ' . $type . ' ' . $function->returns_desc->desc;
1735          }
1736  
1737          // Now create the virtual method that calls the ext implementation.
1738          $code = <<<EOD
1739  /**
1740   * $function->description.
1741   *
1742   $paramdescstr
1743   $return
1744   */
1745  public function $function->name($paramanddefaults) {
1746  $serviceclassmethodbody
1747  }
1748  EOD;
1749  
1750          // Prepare the method information.
1751          $methodinfo = new stdClass();
1752          $methodinfo->name = $function->name;
1753          $methodinfo->inputparams = $inputparams;
1754          $methodinfo->outputparams = $outputparams;
1755          $methodinfo->description = $function->description;
1756          // Add the method information into the list of service methods.
1757          $this->servicemethods[] = $methodinfo;
1758  
1759          return $code;
1760      }
1761  
1762      /**
1763       * Get the phpdoc type for an external_description object.
1764       * external_value => int, double or string
1765       * external_single_structure => object|struct, on-fly generated stdClass name.
1766       * external_multiple_structure => array
1767       *
1768       * @param mixed $keydesc The type description.
1769       * @return string The PHP doc type of the external_description object.
1770       */
1771      protected function get_phpdoc_type($keydesc) {
1772          $type = null;
1773          if ($keydesc instanceof external_value) {
1774              switch ($keydesc->type) {
1775                  case PARAM_BOOL: // 0 or 1 only for now.
1776                  case PARAM_INT:
1777                      $type = 'int';
1778                      break;
1779                  case PARAM_FLOAT;
1780                      $type = 'double';
1781                      break;
1782                  default:
1783                      $type = 'string';
1784              }
1785          } else if ($keydesc instanceof external_single_structure) {
1786              $type = $this->generate_simple_struct_class($keydesc);
1787          } else if ($keydesc instanceof external_multiple_structure) {
1788              $type = 'array';
1789          }
1790  
1791          return $type;
1792      }
1793  
1794      /**
1795       * Generates the method body of the virtual external function.
1796       *
1797       * @param stdClass $function a record from external_function.
1798       * @param array $params web service function parameters.
1799       * @return string body of the method for $function ie. everything within the {} of the method declaration.
1800       */
1801      protected function service_class_method_body($function, $params) {
1802          // Cast the param from object to array (validate_parameters except array only).
1803          $castingcode = '';
1804          $paramsstr = '';
1805          if (!empty($params)) {
1806              foreach ($params as $paramtocast) {
1807                  // Clean the parameter from any white space.
1808                  $paramtocast = trim($paramtocast);
1809                  $castingcode .= "    $paramtocast = json_decode(json_encode($paramtocast), true);\n";
1810              }
1811              $paramsstr = implode(', ', $params);
1812          }
1813  
1814          $descriptionmethod = $function->methodname . '_returns()';
1815          $callforreturnvaluedesc = $function->classname . '::' . $descriptionmethod;
1816  
1817          $methodbody = <<<EOD
1818  $castingcode
1819      if ($callforreturnvaluedesc == null) {
1820          $function->classname::$function->methodname($paramsstr);
1821          return null;
1822      }
1823      return external_api::clean_returnvalue($callforreturnvaluedesc, $function->classname::$function->methodname($paramsstr));
1824  EOD;
1825          return $methodbody;
1826      }
1827  }
1828  
1829  /**
1830   * Early WS exception handler.
1831   * It handles exceptions during setup and returns the Exception text in the WS format.
1832   * If a raise function is found nothing is returned. Throws Exception otherwise.
1833   *
1834   * @param  Exception $ex Raised exception.
1835   * @throws Exception
1836   */
1837  function early_ws_exception_handler(Exception $ex): void {
1838      if (function_exists('raise_early_ws_exception')) {
1839          raise_early_ws_exception($ex);
1840          die;
1841      }
1842  
1843      throw $ex;
1844  }