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