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