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.
/mod/lti/ -> OAuth.php (source)

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

   1  <?php
   2  // This file is part of BasicLTI4Moodle
   3  //
   4  // BasicLTI4Moodle is an IMS BasicLTI (Basic Learning Tools for Interoperability)
   5  // consumer for Moodle 1.9 and Moodle 2.0. BasicLTI is a IMS Standard that allows web
   6  // based learning tools to be easily integrated in LMS as native ones. The IMS BasicLTI
   7  // specification is part of the IMS standard Common Cartridge 1.1 Sakai and other main LMS
   8  // are already supporting or going to support BasicLTI. This project Implements the consumer
   9  // for Moodle. Moodle is a Free Open source Learning Management System by Martin Dougiamas.
  10  // BasicLTI4Moodle is a project iniciated and leaded by Ludo(Marc Alier) and Jordi Piguillem
  11  // at the GESSI research group at UPC.
  12  // SimpleLTI consumer for Moodle is an implementation of the early specification of LTI
  13  // by Charles Severance (Dr Chuck) htp://dr-chuck.com , developed by Jordi Piguillem in a
  14  // Google Summer of Code 2008 project co-mentored by Charles Severance and Marc Alier.
  15  //
  16  // BasicLTI4Moodle is copyright 2009 by Marc Alier Forment, Jordi Piguillem and Nikolas Galanis
  17  // of the Universitat Politecnica de Catalunya http://www.upc.edu
  18  // Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu
  19  //
  20  // OAuth.php is distributed under the MIT License
  21  //
  22  // The MIT License
  23  //
  24  // Copyright (c) 2007 Andy Smith
  25  //
  26  // Permission is hereby granted, free of charge, to any person obtaining a copy
  27  // of this software and associated documentation files (the "Software"), to deal
  28  // in the Software without restriction, including without limitation the rights
  29  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  30  // copies of the Software, and to permit persons to whom the Software is
  31  // furnished to do so, subject to the following conditions:
  32  //
  33  // The above copyright notice and this permission notice shall be included in
  34  // all copies or substantial portions of the Software.
  35  //
  36  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  39  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  42  // THE SOFTWARE.
  43  //
  44  // Moodle is free software: you can redistribute it and/or modify
  45  // it under the terms of the GNU General Public License as published by
  46  // the Free Software Foundation, either version 3 of the License, or
  47  // (at your option) any later version.
  48  //
  49  // Moodle is distributed in the hope that it will be useful,
  50  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  51  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  52  // GNU General Public License for more details.
  53  //
  54  // You should have received a copy of the GNU General Public License
  55  // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  56  
  57  /**
  58   * This file contains the OAuth 1.0a implementation used for support for LTI 1.1.
  59   *
  60   * @package    mod_lti
  61   * @copyright moodle
  62   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  63   */
  64  namespace moodle\mod\lti;//Using a namespace as the basicLTI module imports classes with the same names
  65  
  66  defined('MOODLE_INTERNAL') || die;
  67  
  68  $lastcomputedsignature = false;
  69  
  70  /**
  71   * Generic exception class
  72   */
  73  class OAuthException extends \Exception {
  74      // pass
  75  }
  76  
  77  /**
  78   * OAuth 1.0 Consumer class
  79   */
  80  class OAuthConsumer {
  81      public $key;
  82      public $secret;
  83  
  84      function __construct($key, $secret, $callback_url = null) {
  85          $this->key = $key;
  86          $this->secret = $secret;
  87          $this->callback_url = $callback_url;
  88      }
  89  
  90      function __toString() {
  91          return "OAuthConsumer[key=$this->key,secret=$this->secret]";
  92      }
  93  }
  94  
  95  class OAuthToken {
  96      // access tokens and request tokens
  97      public $key;
  98      public $secret;
  99  
 100      /**
 101       * key = the token
 102       * secret = the token secret
 103       */
 104      function __construct($key, $secret) {
 105          $this->key = $key;
 106          $this->secret = $secret;
 107      }
 108  
 109      /**
 110       * generates the basic string serialization of a token that a server
 111       * would respond to request_token and access_token calls with
 112       */
 113      function to_string() {
 114          return "oauth_token=" .
 115          OAuthUtil::urlencode_rfc3986($this->key) .
 116          "&oauth_token_secret=" .
 117          OAuthUtil::urlencode_rfc3986($this->secret);
 118      }
 119  
 120      function __toString() {
 121          return $this->to_string();
 122      }
 123  }
 124  
 125  class OAuthSignatureMethod {
 126      public function check_signature(&$request, $consumer, $token, $signature) {
 127          $built = $this->build_signature($request, $consumer, $token);
 128          return $built == $signature;
 129      }
 130  }
 131  
 132  
 133  /**
 134   * Base class for the HMac based signature methods.
 135   */
 136  abstract class OAuthSignatureMethod_HMAC extends OAuthSignatureMethod {
 137  
 138      /**
 139       * Name of the Algorithm used.
 140       *
 141       * @return string algorithm name.
 142       */
 143      abstract public function get_name(): string;
 144  
 145      public function build_signature($request, $consumer, $token) {
 146          global $lastcomputedsignature;
 147          $lastcomputedsignature = false;
 148  
 149          $basestring = $request->get_signature_base_string();
 150          $request->base_string = $basestring;
 151  
 152          $key_parts = array(
 153              $consumer->secret,
 154               ($token) ? $token->secret : ""
 155          );
 156  
 157          $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
 158          $key = implode('&', $key_parts);
 159  
 160          $computedsignature = base64_encode(hash_hmac(strtolower(substr($this->get_name(), 5)), $basestring, $key, true));
 161          $lastcomputedsignature = $computedsignature;
 162          return $computedsignature;
 163      }
 164  
 165  }
 166  
 167  /**
 168   * Implementation for SHA 1.
 169   */
 170  class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod_HMAC {
 171      /**
 172       * Name of the Algorithm used.
 173       *
 174       * @return string algorithm name.
 175       */
 176      public function get_name(): string {
 177          return "HMAC-SHA1";
 178      }
 179  }
 180  
 181  /**
 182   * Implementation for SHA 256.
 183   */
 184  class OAuthSignatureMethod_HMAC_SHA256 extends OAuthSignatureMethod_HMAC {
 185      /**
 186       * Name of the Algorithm used.
 187       *
 188       * @return string algorithm name.
 189       */
 190      public function get_name(): string {
 191          return "HMAC-SHA256";
 192      }
 193  }
 194  
 195  class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
 196      /**
 197       * Name of the Algorithm used.
 198       *
 199       * @return string algorithm name.
 200       */
 201      public function get_name(): string {
 202          return "PLAINTEXT";
 203      }
 204  
 205      public function build_signature($request, $consumer, $token) {
 206          $sig = array(
 207              OAuthUtil::urlencode_rfc3986($consumer->secret)
 208          );
 209  
 210          if ($token) {
 211              array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
 212          } else {
 213              array_push($sig, '');
 214          }
 215  
 216          $raw = implode("&", $sig);
 217          // for debug purposes
 218          $request->base_string = $raw;
 219  
 220          return OAuthUtil::urlencode_rfc3986($raw);
 221      }
 222  }
 223  
 224  class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
 225      /**
 226       * Name of the Algorithm used.
 227       *
 228       * @return string algorithm name.
 229       */
 230      public function get_name(): string {
 231          return "RSA-SHA1";
 232      }
 233  
 234      protected function fetch_public_cert(&$request) {
 235          // not implemented yet, ideas are:
 236          // (1) do a lookup in a table of trusted certs keyed off of consumer
 237          // (2) fetch via http using a url provided by the requester
 238          // (3) some sort of specific discovery code based on request
 239          //
 240          // either way should return a string representation of the certificate
 241          throw new OAuthException("fetch_public_cert not implemented");
 242      }
 243  
 244      protected function fetch_private_cert(&$request) {
 245          // not implemented yet, ideas are:
 246          // (1) do a lookup in a table of trusted certs keyed off of consumer
 247          //
 248          // either way should return a string representation of the certificate
 249          throw new OAuthException("fetch_private_cert not implemented");
 250      }
 251  
 252      public function build_signature(&$request, $consumer, $token) {
 253          $base_string = $request->get_signature_base_string();
 254          $request->base_string = $base_string;
 255  
 256          // Fetch the private key cert based on the request
 257          $cert = $this->fetch_private_cert($request);
 258  
 259          // Pull the private key ID from the certificate
 260          $privatekeyid = openssl_get_privatekey($cert);
 261  
 262          // Sign using the key
 263          $ok = openssl_sign($base_string, $signature, $privatekeyid);
 264  
 265          // TODO: Remove this block once PHP 8.0 becomes required.
 266          if (PHP_MAJOR_VERSION < 8) {
 267              // Release the key resource
 268              openssl_free_key($privatekeyid);
 269          }
 270  
 271          return base64_encode($signature);
 272      }
 273  
 274      public function check_signature(&$request, $consumer, $token, $signature) {
 275          $decoded_sig = base64_decode($signature);
 276  
 277          $base_string = $request->get_signature_base_string();
 278  
 279          // Fetch the public key cert based on the request
 280          $cert = $this->fetch_public_cert($request);
 281  
 282          // Pull the public key ID from the certificate
 283          $publickeyid = openssl_get_publickey($cert);
 284  
 285          // Check the computed signature against the one passed in the query
 286          $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
 287  
 288          // TODO: Remove this block once PHP 8.0 becomes required.
 289          if (PHP_MAJOR_VERSION < 8) {
 290              // Release the key resource
 291              openssl_free_key($publickeyid);
 292          }
 293  
 294          return $ok == 1;
 295      }
 296  }
 297  
 298  class OAuthRequest {
 299      private $parameters;
 300      private $http_method;
 301      private $http_url;
 302      // for debug purposes
 303      public $base_string;
 304      public static $version = '1.0';
 305      public static $POST_INPUT = 'php://input';
 306  
 307      function __construct($http_method, $http_url, $parameters = null) {
 308          @$parameters or $parameters = array();
 309          $this->parameters = $parameters;
 310          $this->http_method = $http_method;
 311          $this->http_url = $http_url;
 312      }
 313  
 314      /**
 315       * attempt to build up a request from what was passed to the server
 316       */
 317      public static function from_request($http_method = null, $http_url = null, $parameters = null) {
 318          $scheme = (!is_https()) ? 'http' : 'https';
 319          $port = "";
 320          if ($_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" && strpos(':', $_SERVER['HTTP_HOST']) < 0) {
 321              $port = ':' . $_SERVER['SERVER_PORT'];
 322          }
 323          @$http_url or $http_url = $scheme .
 324          '://' . $_SERVER['HTTP_HOST'] .
 325          $port .
 326          $_SERVER['REQUEST_URI'];
 327          @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
 328  
 329          // We weren't handed any parameters, so let's find the ones relevant to
 330          // this request.
 331          // If you run XML-RPC or similar you should use this to provide your own
 332          // parsed parameter-list
 333          if (!$parameters) {
 334              // Find request headers
 335              $request_headers = OAuthUtil::get_headers();
 336  
 337              // Parse the query-string to find GET parameters
 338              $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
 339  
 340              $ourpost = $_POST;
 341              // Add POST Parameters if they exist
 342              $parameters = array_merge($parameters, $ourpost);
 343  
 344              // We have a Authorization-header with OAuth data. Parse the header
 345              // and add those overriding any duplicates from GET or POST
 346              if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
 347                  $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);
 348                  $parameters = array_merge($parameters, $header_parameters);
 349              }
 350  
 351          }
 352  
 353          return new OAuthRequest($http_method, $http_url, $parameters);
 354      }
 355  
 356      /**
 357       * pretty much a helper function to set up the request
 358       */
 359      public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters = null) {
 360          @$parameters or $parameters = array();
 361          $defaults = array(
 362              "oauth_version" => self::$version,
 363              "oauth_nonce" => self::generate_nonce(),
 364              "oauth_timestamp" => self::generate_timestamp(),
 365              "oauth_consumer_key" => $consumer->key
 366          );
 367          if ($token) {
 368              $defaults['oauth_token'] = $token->key;
 369          }
 370  
 371          $parameters = array_merge($defaults, $parameters);
 372  
 373          // Parse the query-string to find and add GET parameters
 374          $parts = parse_url($http_url);
 375          if (isset($parts['query'])) {
 376              $qparms = OAuthUtil::parse_parameters($parts['query']);
 377              $parameters = array_merge($qparms, $parameters);
 378          }
 379  
 380          return new OAuthRequest($http_method, $http_url, $parameters);
 381      }
 382  
 383      public function set_parameter($name, $value, $allow_duplicates = true) {
 384          if ($allow_duplicates && isset($this->parameters[$name])) {
 385              // We have already added parameter(s) with this name, so add to the list
 386              if (is_scalar($this->parameters[$name])) {
 387                  // This is the first duplicate, so transform scalar (string)
 388                  // into an array so we can add the duplicates
 389                  $this->parameters[$name] = array($this->parameters[$name]);
 390              }
 391  
 392              $this->parameters[$name][] = $value;
 393          } else {
 394              $this->parameters[$name] = $value;
 395          }
 396      }
 397  
 398      public function get_parameter($name) {
 399          return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
 400      }
 401  
 402      public function get_parameters() {
 403          return $this->parameters;
 404      }
 405  
 406      public function unset_parameter($name) {
 407          unset($this->parameters[$name]);
 408      }
 409  
 410      /**
 411       * The request parameters, sorted and concatenated into a normalized string.
 412       * @return string
 413       */
 414      public function get_signable_parameters() {
 415          // Grab all parameters
 416          $params = $this->parameters;
 417  
 418          // Remove oauth_signature if present
 419          // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
 420          if (isset($params['oauth_signature'])) {
 421              unset($params['oauth_signature']);
 422          }
 423  
 424          return OAuthUtil::build_http_query($params);
 425      }
 426  
 427      /**
 428       * Returns the base string of this request
 429       *
 430       * The base string defined as the method, the url
 431       * and the parameters (normalized), each urlencoded
 432       * and the concated with &.
 433       */
 434      public function get_signature_base_string() {
 435          $parts = array(
 436              $this->get_normalized_http_method(),
 437              $this->get_normalized_http_url(),
 438              $this->get_signable_parameters()
 439          );
 440  
 441          $parts = OAuthUtil::urlencode_rfc3986($parts);
 442  
 443          return implode('&', $parts);
 444      }
 445  
 446      /**
 447       * just uppercases the http method
 448       */
 449      public function get_normalized_http_method() {
 450          return strtoupper($this->http_method);
 451      }
 452  
 453      /**
 454       * Parses {@see http_url} and returns normalized scheme://host/path if non-empty, otherwise return empty string
 455       *
 456       * @return string
 457       */
 458      public function get_normalized_http_url() {
 459          if ($this->http_url === '') {
 460              return '';
 461          }
 462  
 463          $parts = parse_url($this->http_url);
 464  
 465          $port = @$parts['port'];
 466          $scheme = $parts['scheme'];
 467          $host = $parts['host'];
 468          $path = @$parts['path'];
 469  
 470          $port or $port = ($scheme == 'https') ? '443' : '80';
 471  
 472          if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) {
 473              $host = "$host:$port";
 474          }
 475          return "$scheme://$host$path";
 476      }
 477  
 478      /**
 479       * builds a url usable for a GET request
 480       */
 481      public function to_url() {
 482          $post_data = $this->to_postdata();
 483          $out = $this->get_normalized_http_url();
 484          if ($post_data) {
 485              $out .= '?'.$post_data;
 486          }
 487          return $out;
 488      }
 489  
 490      /**
 491       * builds the data one would send in a POST request
 492       */
 493      public function to_postdata() {
 494          return OAuthUtil::build_http_query($this->parameters);
 495      }
 496  
 497      /**
 498       * builds the Authorization: header
 499       */
 500      public function to_header() {
 501          $out = 'Authorization: OAuth realm=""';
 502          $total = array();
 503          foreach ($this->parameters as $k => $v) {
 504              if (substr($k, 0, 5) != "oauth") {
 505                  continue;
 506              }
 507              if (is_array($v)) {
 508                  throw new OAuthException('Arrays not supported in headers');
 509              }
 510              $out .= ',' .
 511              OAuthUtil::urlencode_rfc3986($k) .
 512              '="' .
 513              OAuthUtil::urlencode_rfc3986($v) .
 514              '"';
 515          }
 516          return $out;
 517      }
 518  
 519      public function __toString() {
 520          return $this->to_url();
 521      }
 522  
 523      public function sign_request($signature_method, $consumer, $token) {
 524          $this->set_parameter("oauth_signature_method", $signature_method->get_name(), false);
 525          $signature = $this->build_signature($signature_method, $consumer, $token);
 526          $this->set_parameter("oauth_signature", $signature, false);
 527      }
 528  
 529      public function build_signature($signature_method, $consumer, $token) {
 530          $signature = $signature_method->build_signature($this, $consumer, $token);
 531          return $signature;
 532      }
 533  
 534      /**
 535       * util function: current timestamp
 536       */
 537      private static function generate_timestamp() {
 538          return time();
 539      }
 540  
 541      /**
 542       * util function: current nonce
 543       */
 544      private static function generate_nonce() {
 545          $mt = microtime();
 546          $rand = mt_rand();
 547  
 548          return md5($mt.$rand); // md5s look nicer than numbers
 549      }
 550  }
 551  
 552  class OAuthServer {
 553      protected $timestamp_threshold = 300; // in seconds, five minutes
 554      protected $version = 1.0; // hi blaine
 555      protected $signature_methods = array();
 556      protected $data_store;
 557  
 558      function __construct($data_store) {
 559          $this->data_store = $data_store;
 560      }
 561  
 562      public function add_signature_method($signature_method) {
 563          $this->signature_methods[$signature_method->get_name()] = $signature_method;
 564      }
 565  
 566      // high level functions
 567  
 568      /**
 569       * process a request_token request
 570       * returns the request token on success
 571       */
 572      public function fetch_request_token(&$request) {
 573          $this->get_version($request);
 574  
 575          $consumer = $this->get_consumer($request);
 576  
 577          // no token required for the initial token request
 578          $token = null;
 579  
 580          $this->check_signature($request, $consumer, $token);
 581  
 582          $new_token = $this->data_store->new_request_token($consumer);
 583  
 584          return $new_token;
 585      }
 586  
 587      /**
 588       * process an access_token request
 589       * returns the access token on success
 590       */
 591      public function fetch_access_token(&$request) {
 592          $this->get_version($request);
 593  
 594          $consumer = $this->get_consumer($request);
 595  
 596          // requires authorized request token
 597          $token = $this->get_token($request, $consumer, "request");
 598  
 599          $this->check_signature($request, $consumer, $token);
 600  
 601          $new_token = $this->data_store->new_access_token($token, $consumer);
 602  
 603          return $new_token;
 604      }
 605  
 606      /**
 607       * verify an api call, checks all the parameters
 608       */
 609      public function verify_request(&$request) {
 610          global $lastcomputedsignature;
 611          $lastcomputedsignature = false;
 612          $this->get_version($request);
 613          $consumer = $this->get_consumer($request);
 614          $token = $this->get_token($request, $consumer, "access");
 615          $this->check_signature($request, $consumer, $token);
 616          return array(
 617              $consumer,
 618              $token
 619          );
 620      }
 621  
 622      // Internals from here
 623      /**
 624       * version 1
 625       */
 626      private function get_version(&$request) {
 627          $version = $request->get_parameter("oauth_version");
 628          if (!$version) {
 629              $version = 1.0;
 630          }
 631          if ($version && $version != $this->version) {
 632              throw new OAuthException("OAuth version '$version' not supported");
 633          }
 634          return $version;
 635      }
 636  
 637      /**
 638       * figure out the signature with some defaults
 639       */
 640      private function get_signature_method(&$request) {
 641          $signature_method = @ $request->get_parameter("oauth_signature_method");
 642          if (!$signature_method) {
 643              $signature_method = "PLAINTEXT";
 644          }
 645          if (!in_array($signature_method, array_keys($this->signature_methods))) {
 646              throw new OAuthException("Signature method '$signature_method' not supported " .
 647              "try one of the following: " .
 648              implode(", ", array_keys($this->signature_methods)));
 649          }
 650          return $this->signature_methods[$signature_method];
 651      }
 652  
 653      /**
 654       * try to find the consumer for the provided request's consumer key
 655       */
 656      private function get_consumer(&$request) {
 657          $consumer_key = @ $request->get_parameter("oauth_consumer_key");
 658          if (!$consumer_key) {
 659              throw new OAuthException("Invalid consumer key");
 660          }
 661  
 662          $consumer = $this->data_store->lookup_consumer($consumer_key);
 663          if (!$consumer) {
 664              throw new OAuthException("Invalid consumer");
 665          }
 666  
 667          return $consumer;
 668      }
 669  
 670      /**
 671       * try to find the token for the provided request's token key
 672       */
 673      private function get_token(&$request, $consumer, $token_type = "access") {
 674          $token_field = @ $request->get_parameter('oauth_token');
 675          if (!$token_field) {
 676              return false;
 677          }
 678          $token = $this->data_store->lookup_token($consumer, $token_type, $token_field);
 679          if (!$token) {
 680              throw new OAuthException("Invalid $token_type token: $token_field");
 681          }
 682          return $token;
 683      }
 684  
 685      /**
 686       * all-in-one function to check the signature on a request
 687       * should guess the signature method appropriately
 688       */
 689      private function check_signature(&$request, $consumer, $token) {
 690          // this should probably be in a different method
 691          global $lastcomputedsignature;
 692          $lastcomputedsignature = false;
 693  
 694          $timestamp = @ $request->get_parameter('oauth_timestamp');
 695          $nonce = @ $request->get_parameter('oauth_nonce');
 696  
 697          $this->check_timestamp($timestamp);
 698          $this->check_nonce($consumer, $token, $nonce, $timestamp);
 699  
 700          $signature_method = $this->get_signature_method($request);
 701  
 702          $signature = $request->get_parameter('oauth_signature');
 703          $valid_sig = $signature_method->check_signature($request, $consumer, $token, $signature);
 704  
 705          if (!$valid_sig) {
 706              $ex_text = "Invalid signature";
 707              if ($lastcomputedsignature) {
 708                  $ex_text = $ex_text . " ours= $lastcomputedsignature yours=$signature";
 709              }
 710              throw new OAuthException($ex_text);
 711          }
 712      }
 713  
 714      /**
 715       * check that the timestamp is new enough
 716       */
 717      private function check_timestamp($timestamp) {
 718          // verify that timestamp is recentish
 719          $now = time();
 720          if ($now - $timestamp > $this->timestamp_threshold) {
 721              throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
 722          }
 723      }
 724  
 725      /**
 726       * check that the nonce is not repeated
 727       */
 728      private function check_nonce($consumer, $token, $nonce, $timestamp) {
 729          // verify that the nonce is uniqueish
 730          $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
 731          if ($found) {
 732              throw new OAuthException("Nonce already used: $nonce");
 733          }
 734      }
 735  
 736  }
 737  
 738  class OAuthDataStore {
 739      function lookup_consumer($consumer_key) {
 740          // implement me
 741      }
 742  
 743      function lookup_token($consumer, $token_type, $token) {
 744          // implement me
 745      }
 746  
 747      function lookup_nonce($consumer, $token, $nonce, $timestamp) {
 748          // implement me
 749      }
 750  
 751      function new_request_token($consumer) {
 752          // return a new token attached to this consumer
 753      }
 754  
 755      function new_access_token($token, $consumer) {
 756          // return a new access token attached to this consumer
 757          // for the user associated with this token if the request token
 758          // is authorized
 759          // should also invalidate the request token
 760      }
 761  
 762  }
 763  
 764  class OAuthUtil {
 765      public static function urlencode_rfc3986($input) {
 766          if (is_array($input)) {
 767              return array_map(array(
 768                  'moodle\mod\lti\OAuthUtil',
 769                  'urlencode_rfc3986'
 770              ), $input);
 771          } else {
 772              if (is_scalar($input)) {
 773                  return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($input)));
 774              } else {
 775                  return '';
 776              }
 777          }
 778      }
 779  
 780      // This decode function isn't taking into consideration the above
 781      // modifications to the encoding process. However, this method doesn't
 782      // seem to be used anywhere so leaving it as is.
 783      public static function urldecode_rfc3986($string) {
 784          return urldecode($string);
 785      }
 786  
 787      // Utility function for turning the Authorization: header into
 788      // parameters, has to do some unescaping
 789      // Can filter out any non-oauth parameters if needed (default behaviour)
 790      public static function split_header($header, $only_allow_oauth_parameters = true) {
 791          $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
 792          $offset = 0;
 793          $params = array();
 794          while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
 795              $match = $matches[0];
 796              $header_name = $matches[2][0];
 797              $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
 798              if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
 799                  $params[$header_name] = self::urldecode_rfc3986($header_content);
 800              }
 801              $offset = $match[1] + strlen($match[0]);
 802          }
 803  
 804          if (isset($params['realm'])) {
 805              unset($params['realm']);
 806          }
 807  
 808          return $params;
 809      }
 810  
 811      // helper to try to sort out headers for people who aren't running apache
 812      public static function get_headers() {
 813          if (function_exists('apache_request_headers')) {
 814              // we need this to get the actual Authorization: header
 815              // because apache tends to tell us it doesn't exist
 816              $in = apache_request_headers();
 817              $out = array();
 818              foreach ($in as $key => $value) {
 819                  $key = str_replace(" ", "-", ucwords(strtolower(str_replace("-", " ", $key))));
 820                  $out[$key] = $value;
 821              }
 822              return $out;
 823          }
 824          // otherwise we don't have apache and are just going to have to hope
 825          // that $_SERVER actually contains what we need
 826          $out = array();
 827          foreach ($_SERVER as $key => $value) {
 828              if (substr($key, 0, 5) == "HTTP_") {
 829                  // this is chaos, basically it is just there to capitalize the first
 830                  // letter of every word that is not an initial HTTP and strip HTTP
 831                  // code from przemek
 832                  $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
 833                  $out[$key] = $value;
 834              }
 835          }
 836          return $out;
 837      }
 838  
 839      // This function takes a input like a=b&a=c&d=e and returns the parsed
 840      // parameters like this
 841      // array('a' => array('b','c'), 'd' => 'e')
 842      public static function parse_parameters($input) {
 843          if (!isset($input) || !$input) {
 844              return array();
 845          }
 846  
 847          $pairs = explode('&', $input);
 848  
 849          $parsed_parameters = array();
 850          foreach ($pairs as $pair) {
 851              $split = explode('=', $pair, 2);
 852              $parameter = self::urldecode_rfc3986($split[0]);
 853              $value = isset($split[1]) ? self::urldecode_rfc3986($split[1]) : '';
 854  
 855              if (isset($parsed_parameters[$parameter])) {
 856                  // We have already recieved parameter(s) with this name, so add to the list
 857                  // of parameters with this name
 858  
 859                  if (is_scalar($parsed_parameters[$parameter])) {
 860                      // This is the first duplicate, so transform scalar (string) into an array
 861                      // so we can add the duplicates
 862                      $parsed_parameters[$parameter] = array(
 863                          $parsed_parameters[$parameter]
 864                      );
 865                  }
 866  
 867                  $parsed_parameters[$parameter][] = $value;
 868              } else {
 869                  $parsed_parameters[$parameter] = $value;
 870              }
 871          }
 872          return $parsed_parameters;
 873      }
 874  
 875      public static function build_http_query($params) {
 876          if (!$params) {
 877              return '';
 878          }
 879  
 880          // Urlencode both keys and values
 881          $keys = self::urlencode_rfc3986(array_keys($params));
 882          $values = self::urlencode_rfc3986(array_values($params));
 883          $params = array_combine($keys, $values);
 884  
 885          // Parameters are sorted by name, using lexicographical byte value ordering.
 886          // Ref: Spec: 9.1.1 (1)
 887          uksort($params, 'strcmp');
 888  
 889          $pairs = array();
 890          foreach ($params as $parameter => $value) {
 891              if (is_array($value)) {
 892                  // If two or more parameters share the same name, they are sorted by their value
 893                  // Ref: Spec: 9.1.1 (1)
 894                  natsort($value);
 895                  foreach ($value as $duplicate_value) {
 896                      $pairs[] = $parameter . '=' . $duplicate_value;
 897                  }
 898              } else {
 899                  $pairs[] = $parameter . '=' . $value;
 900              }
 901          }
 902          // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
 903          // Each name-value pair is separated by an '&' character (ASCII code 38)
 904          return implode('&', $pairs);
 905      }
 906  }