[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/webservice/ -> lib.php (source)

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


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1