]> git.mxchange.org Git - friendica.git/blob - library/OAuth1.php
Merge pull request #1460 from FlxAlbroscheit/develop
[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['pagename'])+strlen($parameters['pagename']));
297     unset( $parameters['pagename'] );
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($raw = false) {
427     if ($raw)
428       return($this->parameters);
429     else
430       return OAuthUtil::build_http_query($this->parameters);
431   }
432
433   /**
434    * builds the Authorization: header
435    */
436   public function to_header($realm=null) {
437     $first = true;
438         if($realm) {
439       $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
440       $first = false;
441     } else
442       $out = 'Authorization: OAuth';
443
444     $total = array();
445     foreach ($this->parameters as $k => $v) {
446       if (substr($k, 0, 5) != "oauth") continue;
447       if (is_array($v)) {
448         throw new OAuthException('Arrays not supported in headers');
449       }
450       $out .= ($first) ? ' ' : ',';
451       $out .= OAuthUtil::urlencode_rfc3986($k) .
452               '="' .
453               OAuthUtil::urlencode_rfc3986($v) .
454               '"';
455       $first = false;
456     }
457     return $out;
458   }
459
460   public function __toString() {
461     return $this->to_url();
462   }
463
464
465   public function sign_request($signature_method, $consumer, $token) {
466     $this->set_parameter(
467       "oauth_signature_method",
468       $signature_method->get_name(),
469       false
470     );
471     $signature = $this->build_signature($signature_method, $consumer, $token);
472     $this->set_parameter("oauth_signature", $signature, false);
473   }
474
475   public function build_signature($signature_method, $consumer, $token) {
476     $signature = $signature_method->build_signature($this, $consumer, $token);
477     return $signature;
478   }
479
480   /**
481    * util function: current timestamp
482    */
483   private static function generate_timestamp() {
484     return time();
485   }
486
487   /**
488    * util function: current nonce
489    */
490   private static function generate_nonce() {
491     $mt = microtime();
492     $rand = mt_rand();
493
494     return md5($mt . $rand); // md5s look nicer than numbers
495   }
496 }
497
498 class OAuthServer {
499   protected $timestamp_threshold = 300; // in seconds, five minutes
500   protected $version = '1.0';             // hi blaine
501   protected $signature_methods = array();
502
503   protected $data_store;
504
505   function __construct($data_store) {
506     $this->data_store = $data_store;
507   }
508
509   public function add_signature_method($signature_method) {
510     $this->signature_methods[$signature_method->get_name()] =
511       $signature_method;
512   }
513
514   // high level functions
515
516   /**
517    * process a request_token request
518    * returns the request token on success
519    */
520   public function fetch_request_token(&$request) {
521     $this->get_version($request);
522
523     $consumer = $this->get_consumer($request);
524
525     // no token required for the initial token request
526     $token = NULL;
527
528     $this->check_signature($request, $consumer, $token);
529
530     // Rev A change
531     $callback = $request->get_parameter('oauth_callback');
532     $new_token = $this->data_store->new_request_token($consumer, $callback);
533
534     return $new_token;
535   }
536
537   /**
538    * process an access_token request
539    * returns the access token on success
540    */
541   public function fetch_access_token(&$request) {
542     $this->get_version($request);
543
544     $consumer = $this->get_consumer($request);
545
546     // requires authorized request token
547     $token = $this->get_token($request, $consumer, "request");
548
549     $this->check_signature($request, $consumer, $token);
550
551     // Rev A change
552     $verifier = $request->get_parameter('oauth_verifier');
553     $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
554
555     return $new_token;
556   }
557
558   /**
559    * verify an api call, checks all the parameters
560    */
561   public function verify_request(&$request) {
562     $this->get_version($request);
563     $consumer = $this->get_consumer($request);
564     //echo __file__.__line__.__function__."<pre>"; var_dump($consumer); die();
565     $token = $this->get_token($request, $consumer, "access");
566     $this->check_signature($request, $consumer, $token);
567     return array($consumer, $token);
568   }
569
570   // Internals from here
571   /**
572    * version 1
573    */
574   private function get_version(&$request) {
575     $version = $request->get_parameter("oauth_version");
576     if (!$version) {
577       // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present. 
578       // Chapter 7.0 ("Accessing Protected Ressources")
579       $version = '1.0';
580     }
581     if ($version !== $this->version) {
582       throw new OAuthException("OAuth version '$version' not supported");
583     }
584     return $version;
585   }
586
587   /**
588    * figure out the signature with some defaults
589    */
590   private function get_signature_method(&$request) {
591     $signature_method =
592         @$request->get_parameter("oauth_signature_method");
593
594     if (!$signature_method) {
595       // According to chapter 7 ("Accessing Protected Ressources") the signature-method
596       // parameter is required, and we can't just fallback to PLAINTEXT
597       throw new OAuthException('No signature method parameter. This parameter is required');
598     }
599
600     if (!in_array($signature_method,
601                   array_keys($this->signature_methods))) {
602       throw new OAuthException(
603         "Signature method '$signature_method' not supported " .
604         "try one of the following: " .
605         implode(", ", array_keys($this->signature_methods))
606       );
607     }
608     return $this->signature_methods[$signature_method];
609   }
610
611   /**
612    * try to find the consumer for the provided request's consumer key
613    */
614   private function get_consumer(&$request) {
615     $consumer_key = @$request->get_parameter("oauth_consumer_key");
616     if (!$consumer_key) {
617       throw new OAuthException("Invalid consumer key");
618     }
619
620     $consumer = $this->data_store->lookup_consumer($consumer_key);
621     if (!$consumer) {
622       throw new OAuthException("Invalid consumer");
623     }
624
625     return $consumer;
626   }
627
628   /**
629    * try to find the token for the provided request's token key
630    */
631   private function get_token(&$request, $consumer, $token_type="access") {
632     $token_field = @$request->get_parameter('oauth_token');
633     $token = $this->data_store->lookup_token(
634       $consumer, $token_type, $token_field
635     );
636     if (!$token) {
637       throw new OAuthException("Invalid $token_type token: $token_field");
638     }
639     return $token;
640   }
641
642   /**
643    * all-in-one function to check the signature on a request
644    * should guess the signature method appropriately
645    */
646   private function check_signature(&$request, $consumer, $token) {
647     // this should probably be in a different method
648     $timestamp = @$request->get_parameter('oauth_timestamp');
649     $nonce = @$request->get_parameter('oauth_nonce');
650
651     $this->check_timestamp($timestamp);
652     $this->check_nonce($consumer, $token, $nonce, $timestamp);
653
654     $signature_method = $this->get_signature_method($request);
655
656     $signature = $request->get_parameter('oauth_signature');
657     $valid_sig = $signature_method->check_signature(
658       $request,
659       $consumer,
660       $token,
661       $signature
662     );
663         
664
665     if (!$valid_sig) {
666       throw new OAuthException("Invalid signature");
667     }
668   }
669
670   /**
671    * check that the timestamp is new enough
672    */
673   private function check_timestamp($timestamp) {
674     if( ! $timestamp )
675       throw new OAuthException(
676         'Missing timestamp parameter. The parameter is required'
677       );
678     
679     // verify that timestamp is recentish
680     $now = time();
681     if (abs($now - $timestamp) > $this->timestamp_threshold) {
682       throw new OAuthException(
683         "Expired timestamp, yours $timestamp, ours $now"
684       );
685     }
686   }
687
688   /**
689    * check that the nonce is not repeated
690    */
691   private function check_nonce($consumer, $token, $nonce, $timestamp) {
692     if( ! $nonce )
693       throw new OAuthException(
694         'Missing nonce parameter. The parameter is required'
695       );
696
697     // verify that the nonce is uniqueish
698     $found = $this->data_store->lookup_nonce(
699       $consumer,
700       $token,
701       $nonce,
702       $timestamp
703     );
704     if ($found) {
705       throw new OAuthException("Nonce already used: $nonce");
706     }
707   }
708
709 }
710
711 class OAuthDataStore {
712   function lookup_consumer($consumer_key) {
713     // implement me
714   }
715
716   function lookup_token($consumer, $token_type, $token) {
717     // implement me
718   }
719
720   function lookup_nonce($consumer, $token, $nonce, $timestamp) {
721     // implement me
722   }
723
724   function new_request_token($consumer, $callback = null) {
725     // return a new token attached to this consumer
726   }
727
728   function new_access_token($token, $consumer, $verifier = null) {
729     // return a new access token attached to this consumer
730     // for the user associated with this token if the request token
731     // is authorized
732     // should also invalidate the request token
733   }
734
735 }
736
737 class OAuthUtil {
738   public static function urlencode_rfc3986($input) {
739   if (is_array($input)) {
740     return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
741   } else if (is_scalar($input)) {
742     return str_replace(
743       '+',
744       ' ',
745       str_replace('%7E', '~', rawurlencode($input))
746     );
747   } else {
748     return '';
749   }
750 }
751
752
753   // This decode function isn't taking into consideration the above
754   // modifications to the encoding process. However, this method doesn't
755   // seem to be used anywhere so leaving it as is.
756   public static function urldecode_rfc3986($string) {
757     return urldecode($string);
758   }
759
760   // Utility function for turning the Authorization: header into
761   // parameters, has to do some unescaping
762   // Can filter out any non-oauth parameters if needed (default behaviour)
763   public static function split_header($header, $only_allow_oauth_parameters = true) {
764     $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
765     $offset = 0;
766     $params = array();
767     while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
768       $match = $matches[0];
769       $header_name = $matches[2][0];
770       $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
771       if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
772         $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
773       }
774       $offset = $match[1] + strlen($match[0]);
775     }
776
777     if (isset($params['realm'])) {
778       unset($params['realm']);
779     }
780
781     return $params;
782   }
783
784   // helper to try to sort out headers for people who aren't running apache
785   public static function get_headers() {
786     if (function_exists('apache_request_headers')) {
787       // we need this to get the actual Authorization: header
788       // because apache tends to tell us it doesn't exist
789       $headers = apache_request_headers();
790
791       // sanitize the output of apache_request_headers because
792       // we always want the keys to be Cased-Like-This and arh()
793       // returns the headers in the same case as they are in the
794       // request
795       $out = array();
796       foreach( $headers AS $key => $value ) {
797         $key = str_replace(
798             " ",
799             "-",
800             ucwords(strtolower(str_replace("-", " ", $key)))
801           );
802         $out[$key] = $value;
803       }
804     } else {
805       // otherwise we don't have apache and are just going to have to hope
806       // that $_SERVER actually contains what we need
807       $out = array();
808       if( isset($_SERVER['CONTENT_TYPE']) )
809         $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
810       if( isset($_ENV['CONTENT_TYPE']) )
811         $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
812
813       foreach ($_SERVER as $key => $value) {
814         if (substr($key, 0, 5) == "HTTP_") {
815           // this is chaos, basically it is just there to capitalize the first
816           // letter of every word that is not an initial HTTP and strip HTTP
817           // code from przemek
818           $key = str_replace(
819             " ",
820             "-",
821             ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
822           );
823           $out[$key] = $value;
824         }
825       }
826     }
827     return $out;
828   }
829
830   // This function takes a input like a=b&a=c&d=e and returns the parsed
831   // parameters like this
832   // array('a' => array('b','c'), 'd' => 'e')
833   public static function parse_parameters( $input ) {
834     if (!isset($input) || !$input) return array();
835
836     $pairs = explode('&', $input);
837
838     $parsed_parameters = array();
839     foreach ($pairs as $pair) {
840       $split = explode('=', $pair, 2);
841       $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
842       $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
843
844       if (isset($parsed_parameters[$parameter])) {
845         // We have already recieved parameter(s) with this name, so add to the list
846         // of parameters with this name
847
848         if (is_scalar($parsed_parameters[$parameter])) {
849           // This is the first duplicate, so transform scalar (string) into an array
850           // so we can add the duplicates
851           $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
852         }
853
854         $parsed_parameters[$parameter][] = $value;
855       } else {
856         $parsed_parameters[$parameter] = $value;
857       }
858     }
859     return $parsed_parameters;
860   }
861
862   public static function build_http_query($params) {
863     if (!$params) return '';
864
865     // Urlencode both keys and values
866     $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
867     $values = OAuthUtil::urlencode_rfc3986(array_values($params));
868     $params = array_combine($keys, $values);
869
870     // Parameters are sorted by name, using lexicographical byte value ordering.
871     // Ref: Spec: 9.1.1 (1)
872     uksort($params, 'strcmp');
873
874     $pairs = array();
875     foreach ($params as $parameter => $value) {
876       if (is_array($value)) {
877         // If two or more parameters share the same name, they are sorted by their value
878         // Ref: Spec: 9.1.1 (1)
879         natsort($value);
880         foreach ($value as $duplicate_value) {
881           $pairs[] = $parameter . '=' . $duplicate_value;
882         }
883       } else {
884         $pairs[] = $parameter . '=' . $value;
885       }
886     }
887     // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
888     // Each name-value pair is separated by an '&' character (ASCII code 38)
889     return implode('&', $pairs);
890   }
891 }
892
893 ?>