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