typo
[friendica.git/.git] / library / OAuth1.php
1 <?php
2 // vim: foldmethod=marker
3
4 /* Generic exception class
5  */
6 if (!class_exists('OAuthException', false)) {
7   class OAuthException extends Exception {
8     // 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     return ($built == $signature);
95   }
96 }
97
98 /**
99  * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104] 
100  * where the Signature Base String is the text and the key is the concatenated values (each first 
101  * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&' 
102  * character (ASCII code 38) even if empty.
103  *   - Chapter 9.2 ("HMAC-SHA1")
104  */
105 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
106   function get_name() {
107     return "HMAC-SHA1";
108   }
109
110   public function build_signature($request, $consumer, $token) {
111     $base_string = $request->get_signature_base_string();
112     $request->base_string = $base_string;
113
114     $key_parts = array(
115       $consumer->secret,
116       ($token) ? $token->secret : ""
117     );
118
119     $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
120     $key = implode('&', $key_parts);
121
122
123     $r = base64_encode(hash_hmac('sha1', $base_string, $key, true));
124     return $r;
125   }
126 }
127
128 /**
129  * The PLAINTEXT method does not provide any security protection and SHOULD only be used 
130  * over a secure channel such as HTTPS. It does not use the Signature Base String.
131  *   - Chapter 9.4 ("PLAINTEXT")
132  */
133 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
134   public function get_name() {
135     return "PLAINTEXT";
136   }
137
138   /**
139    * oauth_signature is set to the concatenated encoded values of the Consumer Secret and 
140    * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is 
141    * empty. The result MUST be encoded again.
142    *   - Chapter 9.4.1 ("Generating Signatures")
143    *
144    * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
145    * OAuthRequest handles this!
146    */
147   public function build_signature($request, $consumer, $token) {
148     $key_parts = array(
149       $consumer->secret,
150       ($token) ? $token->secret : ""
151     );
152
153     $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
154     $key = implode('&', $key_parts);
155     $request->base_string = $key;
156
157     return $key;
158   }
159 }
160
161 /**
162  * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in 
163  * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for 
164  * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a 
165  * verified way to the Service Provider, in a manner which is beyond the scope of this 
166  * specification.
167  *   - Chapter 9.3 ("RSA-SHA1")
168  */
169 abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
170   public function get_name() {
171     return "RSA-SHA1";
172   }
173
174   // Up to the SP to implement this lookup of keys. Possible ideas are:
175   // (1) do a lookup in a table of trusted certs keyed off of consumer
176   // (2) fetch via http using a url provided by the requester
177   // (3) some sort of specific discovery code based on request
178   //
179   // Either way should return a string representation of the certificate
180   protected abstract function fetch_public_cert(&$request);
181
182   // Up to the SP to implement this lookup of keys. Possible ideas are:
183   // (1) do a lookup in a table of trusted certs keyed off of consumer
184   //
185   // Either way should return a string representation of the certificate
186   protected abstract function fetch_private_cert(&$request);
187
188   public function build_signature($request, $consumer, $token) {
189     $base_string = $request->get_signature_base_string();
190     $request->base_string = $base_string;
191
192     // Fetch the private key cert based on the request
193     $cert = $this->fetch_private_cert($request);
194
195     // Pull the private key ID from the certificate
196     $privatekeyid = openssl_get_privatekey($cert);
197
198     // Sign using the key
199     $ok = openssl_sign($base_string, $signature, $privatekeyid);
200
201     // Release the key resource
202     openssl_free_key($privatekeyid);
203
204     return base64_encode($signature);
205   }
206
207   public function check_signature($request, $consumer, $token, $signature) {
208     $decoded_sig = base64_decode($signature);
209
210     $base_string = $request->get_signature_base_string();
211
212     // Fetch the public key cert based on the request
213     $cert = $this->fetch_public_cert($request);
214
215     // Pull the public key ID from the certificate
216     $publickeyid = openssl_get_publickey($cert);
217
218     // Check the computed signature against the one passed in the query
219     $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
220
221     // Release the key resource
222     openssl_free_key($publickeyid);
223
224     return $ok == 1;
225   }
226 }
227
228 class OAuthRequest {
229   private $parameters;
230   private $http_method;
231   private $http_url;
232   // for debug purposes
233   public $base_string;
234   public static $version = '1.0';
235   public static $POST_INPUT = 'php://input';
236
237   function __construct($http_method, $http_url, $parameters=NULL) {
238     @$parameters or $parameters = array();
239     $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
240     $this->parameters = $parameters;
241     $this->http_method = $http_method;
242     $this->http_url = $http_url;
243   }
244
245
246   /**
247    * attempt to build up a request from what was passed to the server
248    */
249   public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
250     $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
251               ? 'http'
252               : 'https';
253     @$http_url or $http_url = $scheme .
254                               '://' . $_SERVER['HTTP_HOST'] .
255                               ':' .
256                               $_SERVER['SERVER_PORT'] .
257                               $_SERVER['REQUEST_URI'];
258     @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
259
260     // We weren't handed any parameters, so let's find the ones relevant to
261     // this request.
262     // If you run XML-RPC or similar you should use this to provide your own
263     // parsed parameter-list
264     if (!$parameters) {
265       // Find request headers
266       $request_headers = OAuthUtil::get_headers();
267
268       // Parse the query-string to find GET parameters
269       $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
270
271       // It's a POST request of the proper content-type, so parse POST
272       // parameters and add those overriding any duplicates from GET
273       if ($http_method == "POST"
274           && @strstr($request_headers["Content-Type"],
275                      "application/x-www-form-urlencoded")
276           ) {
277         $post_data = OAuthUtil::parse_parameters(
278           file_get_contents(self::$POST_INPUT)
279         );
280         $parameters = array_merge($parameters, $post_data);
281       }
282
283       // We have a Authorization-header with OAuth data. Parse the header
284       // and add those overriding any duplicates from GET or POST
285       if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
286         $header_parameters = OAuthUtil::split_header(
287           $request_headers['Authorization']
288         );
289         $parameters = array_merge($parameters, $header_parameters);
290       }
291
292     }
293     // fix for friendica redirect system
294     
295     $http_url =  substr($http_url, 0, strpos($http_url,$parameters['pagename'])+strlen($parameters['pagename']));
296     unset( $parameters['pagename'] );
297     
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     $token = $this->get_token($request, $consumer, "access");
563     $this->check_signature($request, $consumer, $token);
564     return array($consumer, $token);
565   }
566
567   // Internals from here
568   /**
569    * version 1
570    */
571   private function get_version(&$request) {
572     $version = $request->get_parameter("oauth_version");
573     if (!$version) {
574       // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present. 
575       // Chapter 7.0 ("Accessing Protected Ressources")
576       $version = '1.0';
577     }
578     if ($version !== $this->version) {
579       throw new OAuthException("OAuth version '$version' not supported");
580     }
581     return $version;
582   }
583
584   /**
585    * figure out the signature with some defaults
586    */
587   private function get_signature_method(&$request) {
588     $signature_method =
589         @$request->get_parameter("oauth_signature_method");
590
591     if (!$signature_method) {
592       // According to chapter 7 ("Accessing Protected Ressources") the signature-method
593       // parameter is required, and we can't just fallback to PLAINTEXT
594       throw new OAuthException('No signature method parameter. This parameter is required');
595     }
596
597     if (!in_array($signature_method,
598                   array_keys($this->signature_methods))) {
599       throw new OAuthException(
600         "Signature method '$signature_method' not supported " .
601         "try one of the following: " .
602         implode(", ", array_keys($this->signature_methods))
603       );
604     }
605     return $this->signature_methods[$signature_method];
606   }
607
608   /**
609    * try to find the consumer for the provided request's consumer key
610    */
611   private function get_consumer(&$request) {
612     $consumer_key = @$request->get_parameter("oauth_consumer_key");
613     if (!$consumer_key) {
614       throw new OAuthException("Invalid consumer key");
615     }
616
617     $consumer = $this->data_store->lookup_consumer($consumer_key);
618     if (!$consumer) {
619       throw new OAuthException("Invalid consumer");
620     }
621
622     return $consumer;
623   }
624
625   /**
626    * try to find the token for the provided request's token key
627    */
628   private function get_token(&$request, $consumer, $token_type="access") {
629     $token_field = @$request->get_parameter('oauth_token');
630     $token = $this->data_store->lookup_token(
631       $consumer, $token_type, $token_field
632     );
633     if (!$token) {
634       throw new OAuthException("Invalid $token_type token: $token_field");
635     }
636     return $token;
637   }
638
639   /**
640    * all-in-one function to check the signature on a request
641    * should guess the signature method appropriately
642    */
643   private function check_signature(&$request, $consumer, $token) {
644     // this should probably be in a different method
645     $timestamp = @$request->get_parameter('oauth_timestamp');
646     $nonce = @$request->get_parameter('oauth_nonce');
647
648     $this->check_timestamp($timestamp);
649     $this->check_nonce($consumer, $token, $nonce, $timestamp);
650
651     $signature_method = $this->get_signature_method($request);
652
653     $signature = $request->get_parameter('oauth_signature');
654     $valid_sig = $signature_method->check_signature(
655       $request,
656       $consumer,
657       $token,
658       $signature
659     );
660         
661
662     if (!$valid_sig) {
663       throw new OAuthException("Invalid signature");
664     }
665   }
666
667   /**
668    * check that the timestamp is new enough
669    */
670   private function check_timestamp($timestamp) {
671     if( ! $timestamp )
672       throw new OAuthException(
673         'Missing timestamp parameter. The parameter is required'
674       );
675     
676     // verify that timestamp is recentish
677     $now = time();
678     if (abs($now - $timestamp) > $this->timestamp_threshold) {
679       throw new OAuthException(
680         "Expired timestamp, yours $timestamp, ours $now"
681       );
682     }
683   }
684
685   /**
686    * check that the nonce is not repeated
687    */
688   private function check_nonce($consumer, $token, $nonce, $timestamp) {
689     if( ! $nonce )
690       throw new OAuthException(
691         'Missing nonce parameter. The parameter is required'
692       );
693
694     // verify that the nonce is uniqueish
695     $found = $this->data_store->lookup_nonce(
696       $consumer,
697       $token,
698       $nonce,
699       $timestamp
700     );
701     if ($found) {
702       throw new OAuthException("Nonce already used: $nonce");
703     }
704   }
705
706 }
707
708 class OAuthDataStore {
709   function lookup_consumer($consumer_key) {
710     // implement me
711   }
712
713   function lookup_token($consumer, $token_type, $token) {
714     // implement me
715   }
716
717   function lookup_nonce($consumer, $token, $nonce, $timestamp) {
718     // implement me
719   }
720
721   function new_request_token($consumer, $callback = null) {
722     // return a new token attached to this consumer
723   }
724
725   function new_access_token($token, $consumer, $verifier = null) {
726     // return a new access token attached to this consumer
727     // for the user associated with this token if the request token
728     // is authorized
729     // should also invalidate the request token
730   }
731
732 }
733
734 class OAuthUtil {
735   public static function urlencode_rfc3986($input) {
736   if (is_array($input)) {
737     return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
738   } else if (is_scalar($input)) {
739     return str_replace(
740       '+',
741       ' ',
742       str_replace('%7E', '~', rawurlencode($input))
743     );
744   } else {
745     return '';
746   }
747 }
748
749
750   // This decode function isn't taking into consideration the above
751   // modifications to the encoding process. However, this method doesn't
752   // seem to be used anywhere so leaving it as is.
753   public static function urldecode_rfc3986($string) {
754     return urldecode($string);
755   }
756
757   // Utility function for turning the Authorization: header into
758   // parameters, has to do some unescaping
759   // Can filter out any non-oauth parameters if needed (default behaviour)
760   public static function split_header($header, $only_allow_oauth_parameters = true) {
761     $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
762     $offset = 0;
763     $params = array();
764     while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
765       $match = $matches[0];
766       $header_name = $matches[2][0];
767       $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
768       if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
769         $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
770       }
771       $offset = $match[1] + strlen($match[0]);
772     }
773
774     if (isset($params['realm'])) {
775       unset($params['realm']);
776     }
777
778     return $params;
779   }
780
781   // helper to try to sort out headers for people who aren't running apache
782   public static function get_headers() {
783     if (function_exists('apache_request_headers')) {
784       // we need this to get the actual Authorization: header
785       // because apache tends to tell us it doesn't exist
786       $headers = apache_request_headers();
787
788       // sanitize the output of apache_request_headers because
789       // we always want the keys to be Cased-Like-This and arh()
790       // returns the headers in the same case as they are in the
791       // request
792       $out = array();
793       foreach( $headers AS $key => $value ) {
794         $key = str_replace(
795             " ",
796             "-",
797             ucwords(strtolower(str_replace("-", " ", $key)))
798           );
799         $out[$key] = $value;
800       }
801     } else {
802       // otherwise we don't have apache and are just going to have to hope
803       // that $_SERVER actually contains what we need
804       $out = array();
805       if( isset($_SERVER['CONTENT_TYPE']) )
806         $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
807       if( isset($_ENV['CONTENT_TYPE']) )
808         $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
809
810       foreach ($_SERVER as $key => $value) {
811         if (substr($key, 0, 5) == "HTTP_") {
812           // this is chaos, basically it is just there to capitalize the first
813           // letter of every word that is not an initial HTTP and strip HTTP
814           // code from przemek
815           $key = str_replace(
816             " ",
817             "-",
818             ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
819           );
820           $out[$key] = $value;
821         }
822       }
823     }
824     return $out;
825   }
826
827   // This function takes a input like a=b&a=c&d=e and returns the parsed
828   // parameters like this
829   // array('a' => array('b','c'), 'd' => 'e')
830   public static function parse_parameters( $input ) {
831     if (!isset($input) || !$input) return array();
832
833     $pairs = explode('&', $input);
834
835     $parsed_parameters = array();
836     foreach ($pairs as $pair) {
837       $split = explode('=', $pair, 2);
838       $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
839       $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
840
841       if (isset($parsed_parameters[$parameter])) {
842         // We have already recieved parameter(s) with this name, so add to the list
843         // of parameters with this name
844
845         if (is_scalar($parsed_parameters[$parameter])) {
846           // This is the first duplicate, so transform scalar (string) into an array
847           // so we can add the duplicates
848           $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
849         }
850
851         $parsed_parameters[$parameter][] = $value;
852       } else {
853         $parsed_parameters[$parameter] = $value;
854       }
855     }
856     return $parsed_parameters;
857   }
858
859   public static function build_http_query($params) {
860     if (!$params) return '';
861
862     // Urlencode both keys and values
863     $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
864     $values = OAuthUtil::urlencode_rfc3986(array_values($params));
865     $params = array_combine($keys, $values);
866
867     // Parameters are sorted by name, using lexicographical byte value ordering.
868     // Ref: Spec: 9.1.1 (1)
869     uksort($params, 'strcmp');
870
871     $pairs = array();
872     foreach ($params as $parameter => $value) {
873       if (is_array($value)) {
874         // If two or more parameters share the same name, they are sorted by their value
875         // Ref: Spec: 9.1.1 (1)
876         natsort($value);
877         foreach ($value as $duplicate_value) {
878           $pairs[] = $parameter . '=' . $duplicate_value;
879         }
880       } else {
881         $pairs[] = $parameter . '=' . $value;
882       }
883     }
884     // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
885     // Each name-value pair is separated by an '&' character (ASCII code 38)
886     return implode('&', $pairs);
887   }
888 }
889
890 ?>