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