Search moodle.org's
Developer Documentation

See Release Notes

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

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

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