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