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