MDL-78251 tiny: Reduce use of UI for setting test expectations
[moodle.git] / mod / lti / OAuth.php
blob3147692dd06f56643541d9220300624ba1ff84a9
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.
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
20 // OAuth.php is distributed under the MIT License
22 // The MIT License
24 // Copyright (c) 2007 Andy Smith
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:
33 // The above copyright notice and this permission notice shall be included in
34 // all copies or substantial portions of the Software.
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.
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.
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.
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/>.
57 /**
58 * This file contains the OAuth 1.0a implementation used for support for LTI 1.1.
60 * @package mod_lti
61 * @copyright moodle
62 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
64 namespace moodle\mod\lti;//Using a namespace as the basicLTI module imports classes with the same names
66 defined('MOODLE_INTERNAL') || die;
68 $lastcomputedsignature = false;
70 /**
71 * Generic exception class
73 class OAuthException extends \Exception {
74 // pass
77 /**
78 * OAuth 1.0 Consumer class
80 class OAuthConsumer {
81 public $key;
82 public $secret;
84 /** @var string|null callback URL. */
85 public ?string $callback_url;
87 function __construct($key, $secret, $callback_url = null) {
88 $this->key = $key;
89 $this->secret = $secret;
90 $this->callback_url = $callback_url;
93 function __toString() {
94 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
98 class OAuthToken {
99 // access tokens and request tokens
100 public $key;
101 public $secret;
104 * key = the token
105 * secret = the token secret
107 function __construct($key, $secret) {
108 $this->key = $key;
109 $this->secret = $secret;
113 * generates the basic string serialization of a token that a server
114 * would respond to request_token and access_token calls with
116 function to_string() {
117 return "oauth_token=" .
118 OAuthUtil::urlencode_rfc3986($this->key) .
119 "&oauth_token_secret=" .
120 OAuthUtil::urlencode_rfc3986($this->secret);
123 function __toString() {
124 return $this->to_string();
128 class OAuthSignatureMethod {
129 public function check_signature(&$request, $consumer, $token, $signature) {
130 $built = $this->build_signature($request, $consumer, $token);
131 return $built == $signature;
137 * Base class for the HMac based signature methods.
139 abstract class OAuthSignatureMethod_HMAC extends OAuthSignatureMethod {
142 * Name of the Algorithm used.
144 * @return string algorithm name.
146 abstract public function get_name(): string;
148 public function build_signature($request, $consumer, $token) {
149 global $lastcomputedsignature;
150 $lastcomputedsignature = false;
152 $basestring = $request->get_signature_base_string();
153 $request->base_string = $basestring;
155 $key_parts = array(
156 $consumer->secret,
157 ($token) ? $token->secret : ""
160 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
161 $key = implode('&', $key_parts);
163 $computedsignature = base64_encode(hash_hmac(strtolower(substr($this->get_name(), 5)), $basestring, $key, true));
164 $lastcomputedsignature = $computedsignature;
165 return $computedsignature;
171 * Implementation for SHA 1.
173 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod_HMAC {
175 * Name of the Algorithm used.
177 * @return string algorithm name.
179 public function get_name(): string {
180 return "HMAC-SHA1";
185 * Implementation for SHA 256.
187 class OAuthSignatureMethod_HMAC_SHA256 extends OAuthSignatureMethod_HMAC {
189 * Name of the Algorithm used.
191 * @return string algorithm name.
193 public function get_name(): string {
194 return "HMAC-SHA256";
198 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
200 * Name of the Algorithm used.
202 * @return string algorithm name.
204 public function get_name(): string {
205 return "PLAINTEXT";
208 public function build_signature($request, $consumer, $token) {
209 $sig = array(
210 OAuthUtil::urlencode_rfc3986($consumer->secret)
213 if ($token) {
214 array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
215 } else {
216 array_push($sig, '');
219 $raw = implode("&", $sig);
220 // for debug purposes
221 $request->base_string = $raw;
223 return OAuthUtil::urlencode_rfc3986($raw);
227 class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
229 * Name of the Algorithm used.
231 * @return string algorithm name.
233 public function get_name(): string {
234 return "RSA-SHA1";
237 protected function fetch_public_cert(&$request) {
238 // not implemented yet, ideas are:
239 // (1) do a lookup in a table of trusted certs keyed off of consumer
240 // (2) fetch via http using a url provided by the requester
241 // (3) some sort of specific discovery code based on request
243 // either way should return a string representation of the certificate
244 throw new OAuthException("fetch_public_cert not implemented");
247 protected function fetch_private_cert(&$request) {
248 // not implemented yet, ideas are:
249 // (1) do a lookup in a table of trusted certs keyed off of consumer
251 // either way should return a string representation of the certificate
252 throw new OAuthException("fetch_private_cert not implemented");
255 public function build_signature(&$request, $consumer, $token) {
256 $base_string = $request->get_signature_base_string();
257 $request->base_string = $base_string;
259 // Fetch the private key cert based on the request
260 $cert = $this->fetch_private_cert($request);
262 // Pull the private key ID from the certificate
263 $privatekeyid = openssl_get_privatekey($cert);
265 // Sign using the key
266 $ok = openssl_sign($base_string, $signature, $privatekeyid);
268 // Avoid passing null values to base64_encode.
269 if (!$ok) {
270 throw new OAuthException("OpenSSL unable to sign data");
273 // TODO: Remove this block once PHP 8.0 becomes required.
274 if (PHP_MAJOR_VERSION < 8) {
275 // Release the key resource
276 openssl_free_key($privatekeyid);
279 return base64_encode($signature);
282 public function check_signature(&$request, $consumer, $token, $signature) {
283 $decoded_sig = base64_decode($signature);
285 $base_string = $request->get_signature_base_string();
287 // Fetch the public key cert based on the request
288 $cert = $this->fetch_public_cert($request);
290 // Pull the public key ID from the certificate
291 $publickeyid = openssl_get_publickey($cert);
293 // Check the computed signature against the one passed in the query
294 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
296 // TODO: Remove this block once PHP 8.0 becomes required.
297 if (PHP_MAJOR_VERSION < 8) {
298 // Release the key resource
299 openssl_free_key($publickeyid);
302 return $ok == 1;
306 class OAuthRequest {
307 private $parameters;
308 private $http_method;
309 private $http_url;
310 // for debug purposes
311 public $base_string;
312 public static $version = '1.0';
313 public static $POST_INPUT = 'php://input';
315 function __construct($http_method, $http_url, $parameters = null) {
316 @$parameters or $parameters = array();
317 $this->parameters = $parameters;
318 $this->http_method = $http_method;
319 $this->http_url = $http_url;
323 * attempt to build up a request from what was passed to the server
325 public static function from_request($http_method = null, $http_url = null, $parameters = null) {
326 $scheme = (!is_https()) ? 'http' : 'https';
327 $port = "";
328 if ($_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" && strpos(':', $_SERVER['HTTP_HOST']) < 0) {
329 $port = ':' . $_SERVER['SERVER_PORT'];
331 @$http_url or $http_url = $scheme .
332 '://' . $_SERVER['HTTP_HOST'] .
333 $port .
334 $_SERVER['REQUEST_URI'];
335 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
337 // We weren't handed any parameters, so let's find the ones relevant to
338 // this request.
339 // If you run XML-RPC or similar you should use this to provide your own
340 // parsed parameter-list
341 if (!$parameters) {
342 // Find request headers
343 $request_headers = OAuthUtil::get_headers();
345 // Parse the query-string to find GET parameters
346 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
348 $ourpost = $_POST;
349 // Add POST Parameters if they exist
350 $parameters = array_merge($parameters, $ourpost);
352 // We have a Authorization-header with OAuth data. Parse the header
353 // and add those overriding any duplicates from GET or POST
354 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
355 $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);
356 $parameters = array_merge($parameters, $header_parameters);
361 return new OAuthRequest($http_method, $http_url, $parameters);
365 * pretty much a helper function to set up the request
367 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters = null) {
368 @$parameters or $parameters = array();
369 $defaults = array(
370 "oauth_version" => self::$version,
371 "oauth_nonce" => self::generate_nonce(),
372 "oauth_timestamp" => self::generate_timestamp(),
373 "oauth_consumer_key" => $consumer->key
375 if ($token) {
376 $defaults['oauth_token'] = $token->key;
379 $parameters = array_merge($defaults, $parameters);
381 // Parse the query-string to find and add GET parameters
382 $parts = parse_url($http_url);
383 if (isset($parts['query'])) {
384 $qparms = OAuthUtil::parse_parameters($parts['query']);
385 $parameters = array_merge($qparms, $parameters);
388 return new OAuthRequest($http_method, $http_url, $parameters);
391 public function set_parameter($name, $value, $allow_duplicates = true) {
392 if ($allow_duplicates && isset($this->parameters[$name])) {
393 // We have already added parameter(s) with this name, so add to the list
394 if (is_scalar($this->parameters[$name])) {
395 // This is the first duplicate, so transform scalar (string)
396 // into an array so we can add the duplicates
397 $this->parameters[$name] = array($this->parameters[$name]);
400 $this->parameters[$name][] = $value;
401 } else {
402 $this->parameters[$name] = $value;
406 public function get_parameter($name) {
407 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
410 public function get_parameters() {
411 return $this->parameters;
414 public function unset_parameter($name) {
415 unset($this->parameters[$name]);
419 * The request parameters, sorted and concatenated into a normalized string.
420 * @return string
422 public function get_signable_parameters() {
423 // Grab all parameters
424 $params = $this->parameters;
426 // Remove oauth_signature if present
427 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
428 if (isset($params['oauth_signature'])) {
429 unset($params['oauth_signature']);
432 return OAuthUtil::build_http_query($params);
436 * Returns the base string of this request
438 * The base string defined as the method, the url
439 * and the parameters (normalized), each urlencoded
440 * and the concated with &.
442 public function get_signature_base_string() {
443 $parts = array(
444 $this->get_normalized_http_method(),
445 $this->get_normalized_http_url(),
446 $this->get_signable_parameters()
449 $parts = OAuthUtil::urlencode_rfc3986($parts);
451 return implode('&', $parts);
455 * just uppercases the http method
457 public function get_normalized_http_method() {
458 return strtoupper($this->http_method);
462 * Parses {@see http_url} and returns normalized scheme://host/path if non-empty, otherwise return empty string
464 * @return string
466 public function get_normalized_http_url() {
467 if ($this->http_url === '') {
468 return '';
471 $parts = parse_url($this->http_url);
473 $port = @$parts['port'];
474 $scheme = $parts['scheme'];
475 $host = $parts['host'];
476 $path = @$parts['path'];
478 $port or $port = ($scheme == 'https') ? '443' : '80';
480 if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) {
481 $host = "$host:$port";
483 return "$scheme://$host$path";
487 * builds a url usable for a GET request
489 public function to_url() {
490 $post_data = $this->to_postdata();
491 $out = $this->get_normalized_http_url();
492 if ($post_data) {
493 $out .= '?'.$post_data;
495 return $out;
499 * builds the data one would send in a POST request
501 public function to_postdata() {
502 return OAuthUtil::build_http_query($this->parameters);
506 * builds the Authorization: header
508 public function to_header() {
509 $out = 'Authorization: OAuth realm=""';
510 $total = array();
511 foreach ($this->parameters as $k => $v) {
512 if (substr($k, 0, 5) != "oauth") {
513 continue;
515 if (is_array($v)) {
516 throw new OAuthException('Arrays not supported in headers');
518 $out .= ',' .
519 OAuthUtil::urlencode_rfc3986($k) .
520 '="' .
521 OAuthUtil::urlencode_rfc3986($v) .
522 '"';
524 return $out;
527 public function __toString() {
528 return $this->to_url();
531 public function sign_request($signature_method, $consumer, $token) {
532 $this->set_parameter("oauth_signature_method", $signature_method->get_name(), false);
533 $signature = $this->build_signature($signature_method, $consumer, $token);
534 $this->set_parameter("oauth_signature", $signature, false);
537 public function build_signature($signature_method, $consumer, $token) {
538 $signature = $signature_method->build_signature($this, $consumer, $token);
539 return $signature;
543 * util function: current timestamp
545 private static function generate_timestamp() {
546 return time();
550 * util function: current nonce
552 private static function generate_nonce() {
553 $mt = microtime();
554 $rand = mt_rand();
556 return md5($mt.$rand); // md5s look nicer than numbers
560 class OAuthServer {
561 protected $timestamp_threshold = 300; // in seconds, five minutes
562 protected $version = 1.0; // hi blaine
563 protected $signature_methods = array();
564 protected $data_store;
566 function __construct($data_store) {
567 $this->data_store = $data_store;
570 public function add_signature_method($signature_method) {
571 $this->signature_methods[$signature_method->get_name()] = $signature_method;
574 // high level functions
577 * process a request_token request
578 * returns the request token on success
580 public function fetch_request_token(&$request) {
581 $this->get_version($request);
583 $consumer = $this->get_consumer($request);
585 // no token required for the initial token request
586 $token = null;
588 $this->check_signature($request, $consumer, $token);
590 $new_token = $this->data_store->new_request_token($consumer);
592 return $new_token;
596 * process an access_token request
597 * returns the access token on success
599 public function fetch_access_token(&$request) {
600 $this->get_version($request);
602 $consumer = $this->get_consumer($request);
604 // requires authorized request token
605 $token = $this->get_token($request, $consumer, "request");
607 $this->check_signature($request, $consumer, $token);
609 $new_token = $this->data_store->new_access_token($token, $consumer);
611 return $new_token;
615 * verify an api call, checks all the parameters
617 public function verify_request(&$request) {
618 global $lastcomputedsignature;
619 $lastcomputedsignature = false;
620 $this->get_version($request);
621 $consumer = $this->get_consumer($request);
622 $token = $this->get_token($request, $consumer, "access");
623 $this->check_signature($request, $consumer, $token);
624 return array(
625 $consumer,
626 $token
630 // Internals from here
632 * version 1
634 private function get_version(&$request) {
635 $version = $request->get_parameter("oauth_version");
636 if (!$version) {
637 $version = 1.0;
639 if ($version && $version != $this->version) {
640 throw new OAuthException("OAuth version '$version' not supported");
642 return $version;
646 * figure out the signature with some defaults
648 private function get_signature_method(&$request) {
649 $signature_method = @ $request->get_parameter("oauth_signature_method");
650 if (!$signature_method) {
651 $signature_method = "PLAINTEXT";
653 if (!in_array($signature_method, array_keys($this->signature_methods))) {
654 throw new OAuthException("Signature method '$signature_method' not supported " .
655 "try one of the following: " .
656 implode(", ", array_keys($this->signature_methods)));
658 return $this->signature_methods[$signature_method];
662 * try to find the consumer for the provided request's consumer key
664 private function get_consumer(&$request) {
665 $consumer_key = @ $request->get_parameter("oauth_consumer_key");
666 if (!$consumer_key) {
667 throw new OAuthException("Invalid consumer key");
670 $consumer = $this->data_store->lookup_consumer($consumer_key);
671 if (!$consumer) {
672 throw new OAuthException("Invalid consumer");
675 return $consumer;
679 * try to find the token for the provided request's token key
681 private function get_token(&$request, $consumer, $token_type = "access") {
682 $token_field = @ $request->get_parameter('oauth_token');
683 if (!$token_field) {
684 return false;
686 $token = $this->data_store->lookup_token($consumer, $token_type, $token_field);
687 if (!$token) {
688 throw new OAuthException("Invalid $token_type token: $token_field");
690 return $token;
694 * all-in-one function to check the signature on a request
695 * should guess the signature method appropriately
697 private function check_signature(&$request, $consumer, $token) {
698 // this should probably be in a different method
699 global $lastcomputedsignature;
700 $lastcomputedsignature = false;
702 $timestamp = @ $request->get_parameter('oauth_timestamp');
703 $nonce = @ $request->get_parameter('oauth_nonce');
705 $this->check_timestamp($timestamp);
706 $this->check_nonce($consumer, $token, $nonce, $timestamp);
708 $signature_method = $this->get_signature_method($request);
710 $signature = $request->get_parameter('oauth_signature');
711 $valid_sig = $signature_method->check_signature($request, $consumer, $token, $signature);
713 if (!$valid_sig) {
714 $ex_text = "Invalid signature";
715 if ($lastcomputedsignature) {
716 $ex_text = $ex_text . " ours= $lastcomputedsignature yours=$signature";
718 throw new OAuthException($ex_text);
723 * check that the timestamp is new enough
725 private function check_timestamp($timestamp) {
726 // verify that timestamp is recentish
727 $now = time();
728 if ($now - $timestamp > $this->timestamp_threshold) {
729 throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
734 * check that the nonce is not repeated
736 private function check_nonce($consumer, $token, $nonce, $timestamp) {
737 // verify that the nonce is uniqueish
738 $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
739 if ($found) {
740 throw new OAuthException("Nonce already used: $nonce");
746 class OAuthDataStore {
747 function lookup_consumer($consumer_key) {
748 // implement me
751 function lookup_token($consumer, $token_type, $token) {
752 // implement me
755 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
756 // implement me
759 function new_request_token($consumer) {
760 // return a new token attached to this consumer
763 function new_access_token($token, $consumer) {
764 // return a new access token attached to this consumer
765 // for the user associated with this token if the request token
766 // is authorized
767 // should also invalidate the request token
772 class OAuthUtil {
773 public static function urlencode_rfc3986($input) {
774 if (is_array($input)) {
775 return array_map(array(
776 'moodle\mod\lti\OAuthUtil',
777 'urlencode_rfc3986'
778 ), $input);
779 } else {
780 if (is_scalar($input)) {
781 return str_replace('+', ' ', str_replace('%7E', '~', rawurlencode($input)));
782 } else {
783 return '';
788 // This decode function isn't taking into consideration the above
789 // modifications to the encoding process. However, this method doesn't
790 // seem to be used anywhere so leaving it as is.
791 public static function urldecode_rfc3986($string) {
792 return urldecode($string);
795 // Utility function for turning the Authorization: header into
796 // parameters, has to do some unescaping
797 // Can filter out any non-oauth parameters if needed (default behaviour)
798 public static function split_header($header, $only_allow_oauth_parameters = true) {
799 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
800 $offset = 0;
801 $params = array();
802 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
803 $match = $matches[0];
804 $header_name = $matches[2][0];
805 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
806 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
807 $params[$header_name] = self::urldecode_rfc3986($header_content);
809 $offset = $match[1] + strlen($match[0]);
812 if (isset($params['realm'])) {
813 unset($params['realm']);
816 return $params;
819 // helper to try to sort out headers for people who aren't running apache
820 public static function get_headers() {
821 if (function_exists('apache_request_headers')) {
822 // we need this to get the actual Authorization: header
823 // because apache tends to tell us it doesn't exist
824 $in = apache_request_headers();
825 $out = array();
826 foreach ($in as $key => $value) {
827 $key = str_replace(" ", "-", ucwords(strtolower(str_replace("-", " ", $key))));
828 $out[$key] = $value;
830 return $out;
832 // otherwise we don't have apache and are just going to have to hope
833 // that $_SERVER actually contains what we need
834 $out = array();
835 foreach ($_SERVER as $key => $value) {
836 if (substr($key, 0, 5) == "HTTP_") {
837 // this is chaos, basically it is just there to capitalize the first
838 // letter of every word that is not an initial HTTP and strip HTTP
839 // code from przemek
840 $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
841 $out[$key] = $value;
844 return $out;
847 // This function takes a input like a=b&a=c&d=e and returns the parsed
848 // parameters like this
849 // array('a' => array('b','c'), 'd' => 'e')
850 public static function parse_parameters($input) {
851 if (!isset($input) || !$input) {
852 return array();
855 $pairs = explode('&', $input);
857 $parsed_parameters = array();
858 foreach ($pairs as $pair) {
859 $split = explode('=', $pair, 2);
860 $parameter = self::urldecode_rfc3986($split[0]);
861 $value = isset($split[1]) ? self::urldecode_rfc3986($split[1]) : '';
863 if (isset($parsed_parameters[$parameter])) {
864 // We have already recieved parameter(s) with this name, so add to the list
865 // of parameters with this name
867 if (is_scalar($parsed_parameters[$parameter])) {
868 // This is the first duplicate, so transform scalar (string) into an array
869 // so we can add the duplicates
870 $parsed_parameters[$parameter] = array(
871 $parsed_parameters[$parameter]
875 $parsed_parameters[$parameter][] = $value;
876 } else {
877 $parsed_parameters[$parameter] = $value;
880 return $parsed_parameters;
883 public static function build_http_query($params) {
884 if (!$params) {
885 return '';
888 // Urlencode both keys and values
889 $keys = self::urlencode_rfc3986(array_keys($params));
890 $values = self::urlencode_rfc3986(array_values($params));
891 $params = array_combine($keys, $values);
893 // Parameters are sorted by name, using lexicographical byte value ordering.
894 // Ref: Spec: 9.1.1 (1)
895 uksort($params, 'strcmp');
897 $pairs = array();
898 foreach ($params as $parameter => $value) {
899 if (is_array($value)) {
900 // If two or more parameters share the same name, they are sorted by their value
901 // Ref: Spec: 9.1.1 (1)
902 natsort($value);
903 foreach ($value as $duplicate_value) {
904 $pairs[] = $parameter . '=' . $duplicate_value;
906 } else {
907 $pairs[] = $parameter . '=' . $value;
910 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
911 // Each name-value pair is separated by an '&' character (ASCII code 38)
912 return implode('&', $pairs);