[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/mod/lti/ -> OAuth.php (source)

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


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