Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

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

   1  <?php
   2  // vim: foldmethod=marker
   3  
   4  $OAuth_last_computed_siguature = false;
   5  
   6  /* Generic exception class
   7   */
   8  class OAuthException extends \Exception {
   9    // pass
  10  }
  11  
  12  class OAuthConsumer {
  13    public $key;
  14    public $secret;
  15  
  16    function __construct($key, $secret, $callback_url=NULL) {
  17      $this->key = $key;
  18      $this->secret = $secret;
  19      $this->callback_url = $callback_url;
  20    }
  21  
  22    function __toString() {
  23      return "OAuthConsumer[key=$this->key,secret=$this->secret]";
  24    }
  25  }
  26  
  27  class OAuthToken {
  28    // access tokens and request tokens
  29    public $key;
  30    public $secret;
  31  
  32    /**
  33     * key = the token
  34     * secret = the token secret
  35     */
  36    function __construct($key, $secret) {
  37      $this->key = $key;
  38      $this->secret = $secret;
  39    }
  40  
  41    /**
  42     * generates the basic string serialization of a token that a server
  43     * would respond to request_token and access_token calls with
  44     */
  45    function to_string() {
  46      return "oauth_token=" .
  47             OAuthUtil::urlencode_rfc3986($this->key) .
  48             "&oauth_token_secret=" .
  49             OAuthUtil::urlencode_rfc3986($this->secret);
  50    }
  51  
  52    function __toString() {
  53      return $this->to_string();
  54    }
  55  }
  56  
  57  class OAuthSignatureMethod {
  58    public function check_signature(&$request, $consumer, $token, $signature) {
  59      $built = $this->build_signature($request, $consumer, $token);
  60      return $built == $signature;
  61    }
  62  }
  63  
  64  class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
  65    function get_name() {
  66      return "HMAC-SHA1";
  67    }
  68  
  69    public function build_signature($request, $consumer, $token) {
  70      global $OAuth_last_computed_signature;
  71      $OAuth_last_computed_signature = false;
  72  
  73      $base_string = $request->get_signature_base_string();
  74      $request->base_string = $base_string;
  75  
  76      $key_parts = array(
  77        $consumer->secret,
  78        ($token) ? $token->secret : ""
  79      );
  80  
  81      $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
  82      $key = implode('&', $key_parts);
  83  
  84      $computed_signature = base64_encode(hash_hmac('sha1', $base_string, $key, true));
  85      $OAuth_last_computed_signature = $computed_signature;
  86      return $computed_signature;
  87    }
  88  
  89  }
  90  
  91  class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
  92    public function get_name() {
  93      return "PLAINTEXT";
  94    }
  95  
  96    public function build_signature($request, $consumer, $token) {
  97      $sig = array(
  98        OAuthUtil::urlencode_rfc3986($consumer->secret)
  99      );
 100  
 101      if ($token) {
 102        array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
 103      } else {
 104        array_push($sig, '');
 105      }
 106  
 107      $raw = implode("&", $sig);
 108      // for debug purposes
 109      $request->base_string = $raw;
 110  
 111      return OAuthUtil::urlencode_rfc3986($raw);
 112    }
 113  }
 114  
 115  class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
 116    public function get_name() {
 117      return "RSA-SHA1";
 118    }
 119  
 120    protected function fetch_public_cert(&$request) {
 121      // not implemented yet, ideas are:
 122      // (1) do a lookup in a table of trusted certs keyed off of consumer
 123      // (2) fetch via http using a url provided by the requester
 124      // (3) some sort of specific discovery code based on request
 125      //
 126      // either way should return a string representation of the certificate
 127      throw Exception("fetch_public_cert not implemented");
 128    }
 129  
 130    protected function fetch_private_cert(&$request) {
 131      // not implemented yet, ideas are:
 132      // (1) do a lookup in a table of trusted certs keyed off of consumer
 133      //
 134      // either way should return a string representation of the certificate
 135      throw Exception("fetch_private_cert not implemented");
 136    }
 137  
 138    public function build_signature(&$request, $consumer, $token) {
 139      $base_string = $request->get_signature_base_string();
 140      $request->base_string = $base_string;
 141  
 142      // Fetch the private key cert based on the request
 143      $cert = $this->fetch_private_cert($request);
 144  
 145      // Pull the private key ID from the certificate
 146      $privatekeyid = openssl_get_privatekey($cert);
 147  
 148      // Sign using the key
 149      $ok = openssl_sign($base_string, $signature, $privatekeyid);
 150  
 151      // Avoid passing null values to base64_encode.
 152      if (!$ok) {
 153        throw new OAuthException("OpenSSL unable to sign data");
 154      }
 155  
 156      // TODO: Remove this block once PHP 8.0 becomes required.
 157      if (PHP_MAJOR_VERSION < 8) {
 158        // Release the key resource
 159        openssl_free_key($privatekeyid);
 160      }
 161  
 162      return base64_encode($signature);
 163    }
 164  
 165    public function check_signature(&$request, $consumer, $token, $signature) {
 166      $decoded_sig = base64_decode($signature);
 167  
 168      $base_string = $request->get_signature_base_string();
 169  
 170      // Fetch the public key cert based on the request
 171      $cert = $this->fetch_public_cert($request);
 172  
 173      // Pull the public key ID from the certificate
 174      $publickeyid = openssl_get_publickey($cert);
 175  
 176      // Check the computed signature against the one passed in the query
 177      $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
 178  
 179      // TODO: Remove this block once PHP 8.0 becomes required.
 180      if (PHP_MAJOR_VERSION < 8) {
 181        // Release the key resource
 182        openssl_free_key($publickeyid);
 183      }
 184  
 185      return $ok == 1;
 186    }
 187  }
 188  
 189  class OAuthRequest {
 190    private $parameters;
 191    private $http_method;
 192    private $http_url;
 193    // for debug purposes
 194    public $base_string;
 195    public static $version = '1.0';
 196    public static $POST_INPUT = 'php://input';
 197  
 198    function __construct($http_method, $http_url, $parameters=NULL) {
 199      @$parameters or $parameters = array();
 200      $this->parameters = $parameters;
 201      $this->http_method = $http_method;
 202      $this->http_url = $http_url;
 203    }
 204  
 205  
 206    /**
 207     * attempt to build up a request from what was passed to the server
 208     */
 209    public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
 210      $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
 211                ? 'http'
 212                : 'https';
 213      $port = "";
 214      if ( $_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" &&
 215          strpos(':', $_SERVER['HTTP_HOST']) < 0 ) {
 216        $port =  ':' . $_SERVER['SERVER_PORT'] ;
 217      }
 218      @$http_url or $http_url = $scheme .
 219                                '://' . $_SERVER['HTTP_HOST'] .
 220                                $port .
 221                                $_SERVER['REQUEST_URI'];
 222      @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
 223  
 224      // We weren't handed any parameters, so let's find the ones relevant to
 225      // this request.
 226      // If you run XML-RPC or similar you should use this to provide your own
 227      // parsed parameter-list
 228      if (!$parameters) {
 229        // Find request headers
 230        $request_headers = OAuthUtil::get_headers();
 231  
 232        // Parse the query-string to find GET parameters
 233        $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
 234  
 235        $ourpost = $_POST;
 236       // Add POST Parameters if they exist
 237        $parameters = array_merge($parameters, $ourpost);
 238  
 239        // We have a Authorization-header with OAuth data. Parse the header
 240        // and add those overriding any duplicates from GET or POST
 241        if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
 242          $header_parameters = OAuthUtil::split_header(
 243            $request_headers['Authorization']
 244          );
 245          $parameters = array_merge($parameters, $header_parameters);
 246        }
 247  
 248      }
 249  
 250      return new OAuthRequest($http_method, $http_url, $parameters);
 251    }
 252  
 253    /**
 254     * pretty much a helper function to set up the request
 255     */
 256    public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
 257      @$parameters or $parameters = array();
 258      $defaults = array("oauth_version" => OAuthRequest::$version,
 259                        "oauth_nonce" => OAuthRequest::generate_nonce(),
 260                        "oauth_timestamp" => OAuthRequest::generate_timestamp(),
 261                        "oauth_consumer_key" => $consumer->key);
 262      if ($token)
 263        $defaults['oauth_token'] = $token->key;
 264  
 265      $parameters = array_merge($defaults, $parameters);
 266  
 267      // Parse the query-string to find and add GET parameters
 268      $parts = parse_url($http_url);
 269      if ( !empty($parts['query']) ) {
 270        $qparms = OAuthUtil::parse_parameters($parts['query']);
 271        $parameters = array_merge($qparms, $parameters);
 272      }
 273  
 274  
 275      return new OAuthRequest($http_method, $http_url, $parameters);
 276    }
 277  
 278    public function set_parameter($name, $value, $allow_duplicates = true) {
 279      if ($allow_duplicates && isset($this->parameters[$name])) {
 280        // We have already added parameter(s) with this name, so add to the list
 281        if (is_scalar($this->parameters[$name])) {
 282          // This is the first duplicate, so transform scalar (string)
 283          // into an array so we can add the duplicates
 284          $this->parameters[$name] = array($this->parameters[$name]);
 285        }
 286  
 287        $this->parameters[$name][] = $value;
 288      } else {
 289        $this->parameters[$name] = $value;
 290      }
 291    }
 292  
 293    public function get_parameter($name) {
 294      return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
 295    }
 296  
 297    public function get_parameters() {
 298      return $this->parameters;
 299    }
 300  
 301    public function unset_parameter($name) {
 302      unset($this->parameters[$name]);
 303    }
 304  
 305    /**
 306     * The request parameters, sorted and concatenated into a normalized string.
 307     * @return string
 308     */
 309    public function get_signable_parameters() {
 310      // Grab all parameters
 311      $params = $this->parameters;
 312  
 313      // Remove oauth_signature if present
 314      // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
 315      if (isset($params['oauth_signature'])) {
 316        unset($params['oauth_signature']);
 317      }
 318  
 319      return OAuthUtil::build_http_query($params);
 320    }
 321  
 322    /**
 323     * Returns the base string of this request
 324     *
 325     * The base string defined as the method, the url
 326     * and the parameters (normalized), each urlencoded
 327     * and the concated with &.
 328     */
 329    public function get_signature_base_string() {
 330      $parts = array(
 331        $this->get_normalized_http_method(),
 332        $this->get_normalized_http_url(),
 333        $this->get_signable_parameters()
 334      );
 335  
 336      $parts = OAuthUtil::urlencode_rfc3986($parts);
 337  
 338      return implode('&', $parts);
 339    }
 340  
 341    /**
 342     * just uppercases the http method
 343     */
 344    public function get_normalized_http_method() {
 345      return strtoupper($this->http_method);
 346    }
 347  
 348    /**
 349     * parses the url and rebuilds it to be
 350     * scheme://host/path
 351     */
 352    public function get_normalized_http_url() {
 353      $parts = parse_url($this->http_url);
 354  
 355      $port = @$parts['port'];
 356      $scheme = $parts['scheme'];
 357      $host = $parts['host'];
 358      $path = @$parts['path'];
 359  
 360      $port or $port = ($scheme == 'https') ? '443' : '80';
 361  
 362      if (($scheme == 'https' && $port != '443')
 363          || ($scheme == 'http' && $port != '80')) {
 364        $host = "$host:$port";
 365      }
 366      return "$scheme://$host$path";
 367    }
 368  
 369    /**
 370     * builds a url usable for a GET request
 371     */
 372    public function to_url() {
 373      $post_data = $this->to_postdata();
 374      $out = $this->get_normalized_http_url();
 375      if ($post_data) {
 376        $out .= '?'.$post_data;
 377      }
 378      return $out;
 379    }
 380  
 381    /**
 382     * builds the data one would send in a POST request
 383     */
 384    public function to_postdata() {
 385      return OAuthUtil::build_http_query($this->parameters);
 386    }
 387  
 388    /**
 389     * builds the Authorization: header
 390     */
 391    public function to_header() {
 392      $out ='Authorization: OAuth realm=""';
 393      $total = array();
 394      foreach ($this->parameters as $k => $v) {
 395        if (substr($k, 0, 5) != "oauth") continue;
 396        if (is_array($v)) {
 397          throw new OAuthException('Arrays not supported in headers');
 398        }
 399        $out .= ',' .
 400                OAuthUtil::urlencode_rfc3986($k) .
 401                '="' .
 402                OAuthUtil::urlencode_rfc3986($v) .
 403                '"';
 404      }
 405      return $out;
 406    }
 407  
 408    public function __toString() {
 409      return $this->to_url();
 410    }
 411  
 412  
 413    public function sign_request($signature_method, $consumer, $token) {
 414      $this->set_parameter(
 415        "oauth_signature_method",
 416        $signature_method->get_name(),
 417        false
 418      );
 419      $signature = $this->build_signature($signature_method, $consumer, $token);
 420      $this->set_parameter("oauth_signature", $signature, false);
 421    }
 422  
 423    public function build_signature($signature_method, $consumer, $token) {
 424      $signature = $signature_method->build_signature($this, $consumer, $token);
 425      return $signature;
 426    }
 427  
 428    /**
 429     * util function: current timestamp
 430     */
 431    private static function generate_timestamp() {
 432      return time();
 433    }
 434  
 435    /**
 436     * util function: current nonce
 437     */
 438    private static function generate_nonce() {
 439      $mt = microtime();
 440      $rand = mt_rand();
 441  
 442      return md5($mt . $rand); // md5s look nicer than numbers
 443    }
 444  }
 445  
 446  class OAuthServer {
 447    protected $timestamp_threshold = 300; // in seconds, five minutes
 448    protected $version = 1.0;             // hi blaine
 449    protected $signature_methods = array();
 450  
 451    protected $data_store;
 452  
 453    function __construct($data_store) {
 454      $this->data_store = $data_store;
 455    }
 456  
 457    public function add_signature_method($signature_method) {
 458      $this->signature_methods[$signature_method->get_name()] =
 459        $signature_method;
 460    }
 461  
 462    // high level functions
 463  
 464    /**
 465     * process a request_token request
 466     * returns the request token on success
 467     */
 468    public function fetch_request_token(&$request) {
 469      $this->get_version($request);
 470  
 471      $consumer = $this->get_consumer($request);
 472  
 473      // no token required for the initial token request
 474      $token = NULL;
 475  
 476      $this->check_signature($request, $consumer, $token);
 477  
 478      $new_token = $this->data_store->new_request_token($consumer);
 479  
 480      return $new_token;
 481    }
 482  
 483    /**
 484     * process an access_token request
 485     * returns the access token on success
 486     */
 487    public function fetch_access_token(&$request) {
 488      $this->get_version($request);
 489  
 490      $consumer = $this->get_consumer($request);
 491  
 492      // requires authorized request token
 493      $token = $this->get_token($request, $consumer, "request");
 494  
 495  
 496      $this->check_signature($request, $consumer, $token);
 497  
 498      $new_token = $this->data_store->new_access_token($token, $consumer);
 499  
 500      return $new_token;
 501    }
 502  
 503    /**
 504     * verify an api call, checks all the parameters
 505     */
 506    public function verify_request(&$request) {
 507      global $OAuth_last_computed_signature;
 508      $OAuth_last_computed_signature = false;
 509      $this->get_version($request);
 510      $consumer = $this->get_consumer($request);
 511      $token = $this->get_token($request, $consumer, "access");
 512      $this->check_signature($request, $consumer, $token);
 513      return array($consumer, $token);
 514    }
 515  
 516    // Internals from here
 517    /**
 518     * version 1
 519     */
 520    private function get_version(&$request) {
 521      $version = $request->get_parameter("oauth_version");
 522      if (!$version) {
 523        $version = 1.0;
 524      }
 525      if ($version && $version != $this->version) {
 526        throw new OAuthException("OAuth version '$version' not supported");
 527      }
 528      return $version;
 529    }
 530  
 531    /**
 532     * figure out the signature with some defaults
 533     */
 534    private function get_signature_method(&$request) {
 535      $signature_method =
 536          @$request->get_parameter("oauth_signature_method");
 537      if (!$signature_method) {
 538        $signature_method = "PLAINTEXT";
 539      }
 540      if (!in_array($signature_method,
 541                    array_keys($this->signature_methods))) {
 542        throw new OAuthException(
 543          "Signature method '$signature_method' not supported " .
 544          "try one of the following: " .
 545          implode(", ", array_keys($this->signature_methods))
 546        );
 547      }
 548      return $this->signature_methods[$signature_method];
 549    }
 550  
 551    /**
 552     * try to find the consumer for the provided request's consumer key
 553     */
 554    private function get_consumer(&$request) {
 555      $consumer_key = @$request->get_parameter("oauth_consumer_key");
 556      if (!$consumer_key) {
 557        throw new OAuthException("Invalid consumer key");
 558      }
 559  
 560      $consumer = $this->data_store->lookup_consumer($consumer_key);
 561      if (!$consumer) {
 562        throw new OAuthException("Invalid consumer");
 563      }
 564  
 565      return $consumer;
 566    }
 567  
 568    /**
 569     * try to find the token for the provided request's token key
 570     */
 571    private function get_token(&$request, $consumer, $token_type="access") {
 572      $token_field = @$request->get_parameter('oauth_token');
 573      if ( !$token_field) return false;
 574      $token = $this->data_store->lookup_token(
 575        $consumer, $token_type, $token_field
 576      );
 577      if (!$token) {
 578        throw new OAuthException("Invalid $token_type token: $token_field");
 579      }
 580      return $token;
 581    }
 582  
 583    /**
 584     * all-in-one function to check the signature on a request
 585     * should guess the signature method appropriately
 586     */
 587    private function check_signature(&$request, $consumer, $token) {
 588      // this should probably be in a different method
 589      global $OAuth_last_computed_signature;
 590      $OAuth_last_computed_signature = false;
 591  
 592      $timestamp = @$request->get_parameter('oauth_timestamp');
 593      $nonce = @$request->get_parameter('oauth_nonce');
 594  
 595      $this->check_timestamp($timestamp);
 596      $this->check_nonce($consumer, $token, $nonce, $timestamp);
 597  
 598      $signature_method = $this->get_signature_method($request);
 599  
 600      $signature = $request->get_parameter('oauth_signature');
 601      $valid_sig = $signature_method->check_signature(
 602        $request,
 603        $consumer,
 604        $token,
 605        $signature
 606      );
 607  
 608      if (!$valid_sig) {
 609        $ex_text = "Invalid signature";
 610        if ( $OAuth_last_computed_signature ) {
 611            $ex_text = $ex_text . " ours= $OAuth_last_computed_signature yours=$signature";
 612        }
 613        throw new OAuthException($ex_text);
 614      }
 615    }
 616  
 617    /**
 618     * check that the timestamp is new enough
 619     */
 620    private function check_timestamp($timestamp) {
 621      // verify that timestamp is recentish
 622      $now = time();
 623      if ($now - $timestamp > $this->timestamp_threshold) {
 624        throw new OAuthException(
 625          "Expired timestamp, yours $timestamp, ours $now"
 626        );
 627      }
 628    }
 629  
 630    /**
 631     * check that the nonce is not repeated
 632     */
 633    private function check_nonce($consumer, $token, $nonce, $timestamp) {
 634      // verify that the nonce is uniqueish
 635      $found = $this->data_store->lookup_nonce(
 636        $consumer,
 637        $token,
 638        $nonce,
 639        $timestamp
 640      );
 641      if ($found) {
 642        throw new OAuthException("Nonce already used: $nonce");
 643      }
 644    }
 645  
 646  }
 647  
 648  class OAuthDataStore {
 649    function lookup_consumer($consumer_key) {
 650      // implement me
 651    }
 652  
 653    function lookup_token($consumer, $token_type, $token) {
 654      // implement me
 655    }
 656  
 657    function lookup_nonce($consumer, $token, $nonce, $timestamp) {
 658      // implement me
 659    }
 660  
 661    function new_request_token($consumer) {
 662      // return a new token attached to this consumer
 663    }
 664  
 665    function new_access_token($token, $consumer) {
 666      // return a new access token attached to this consumer
 667      // for the user associated with this token if the request token
 668      // is authorized
 669      // should also invalidate the request token
 670    }
 671  
 672  }
 673  
 674  class OAuthUtil {
 675    public static function urlencode_rfc3986($input) {
 676    if (is_array($input)) {
 677      return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
 678    } else if (is_scalar($input)) {
 679      return str_replace(
 680        '+',
 681        ' ',
 682        str_replace('%7E', '~', rawurlencode($input))
 683      );
 684    } else {
 685      return '';
 686    }
 687  }
 688  
 689  
 690    // This decode function isn't taking into consideration the above
 691    // modifications to the encoding process. However, this method doesn't
 692    // seem to be used anywhere so leaving it as is.
 693    public static function urldecode_rfc3986($string) {
 694      return urldecode($string);
 695    }
 696  
 697    // Utility function for turning the Authorization: header into
 698    // parameters, has to do some unescaping
 699    // Can filter out any non-oauth parameters if needed (default behaviour)
 700    public static function split_header($header, $only_allow_oauth_parameters = true) {
 701      $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
 702      $offset = 0;
 703      $params = array();
 704      while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
 705        $match = $matches[0];
 706        $header_name = $matches[2][0];
 707        $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
 708        if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
 709          $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
 710        }
 711        $offset = $match[1] + strlen($match[0]);
 712      }
 713  
 714      if (isset($params['realm'])) {
 715        unset($params['realm']);
 716      }
 717  
 718      return $params;
 719    }
 720  
 721    // helper to try to sort out headers for people who aren't running apache
 722    public static function get_headers() {
 723      if (function_exists('apache_request_headers')) {
 724        // we need this to get the actual Authorization: header
 725        // because apache tends to tell us it doesn't exist
 726        return apache_request_headers();
 727      }
 728      // otherwise we don't have apache and are just going to have to hope
 729      // that $_SERVER actually contains what we need
 730      $out = array();
 731      foreach ($_SERVER as $key => $value) {
 732        if (substr($key, 0, 5) == "HTTP_") {
 733          // this is chaos, basically it is just there to capitalize the first
 734          // letter of every word that is not an initial HTTP and strip HTTP
 735          // code from przemek
 736          $key = str_replace(
 737            " ",
 738            "-",
 739            ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
 740          );
 741          $out[$key] = $value;
 742        }
 743      }
 744      return $out;
 745    }
 746  
 747    // This function takes a input like a=b&a=c&d=e and returns the parsed
 748    // parameters like this
 749    // array('a' => array('b','c'), 'd' => 'e')
 750    public static function parse_parameters( $input ) {
 751      if (!isset($input) || !$input) return array();
 752  
 753      $pairs = explode('&', $input);
 754  
 755      $parsed_parameters = array();
 756      foreach ($pairs as $pair) {
 757        $split = explode('=', $pair, 2);
 758        $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
 759        $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
 760  
 761        if (isset($parsed_parameters[$parameter])) {
 762          // We have already recieved parameter(s) with this name, so add to the list
 763          // of parameters with this name
 764  
 765          if (is_scalar($parsed_parameters[$parameter])) {
 766            // This is the first duplicate, so transform scalar (string) into an array
 767            // so we can add the duplicates
 768            $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
 769          }
 770  
 771          $parsed_parameters[$parameter][] = $value;
 772        } else {
 773          $parsed_parameters[$parameter] = $value;
 774        }
 775      }
 776      return $parsed_parameters;
 777    }
 778  
 779    public static function build_http_query($params) {
 780      if (!$params) return '';
 781  
 782      // Urlencode both keys and values
 783      $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
 784      $values = OAuthUtil::urlencode_rfc3986(array_values($params));
 785      $params = array_combine($keys, $values);
 786  
 787      // Parameters are sorted by name, using lexicographical byte value ordering.
 788      // Ref: Spec: 9.1.1 (1)
 789      uksort($params, 'strcmp');
 790  
 791      $pairs = array();
 792      foreach ($params as $parameter => $value) {
 793        if (is_array($value)) {
 794          // If two or more parameters share the same name, they are sorted by their value
 795          // Ref: Spec: 9.1.1 (1)
 796          natsort($value);
 797          foreach ($value as $duplicate_value) {
 798            $pairs[] = $parameter . '=' . $duplicate_value;
 799          }
 800        } else {
 801          $pairs[] = $parameter . '=' . $value;
 802        }
 803      }
 804      // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
 805      // Each name-value pair is separated by an '&' character (ASCII code 38)
 806      return implode('&', $pairs);
 807    }
 808  }
 809  
 810  ?>