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