OSDN Git Service

6f84b07b22d0d490def7c9436046a21097c89210
[embrj/master.git] / lib / oauth_lib.php
1 <?php\r
2 \r
3 /* Generic exception class\r
4  */\r
5 class OAuthException extends Exception {\r
6   // pass\r
7 }\r
8 \r
9 class OAuthConsumer {\r
10   public $key;\r
11   public $secret;\r
12 \r
13   function __construct($key, $secret) {\r
14     $this->key = $key;\r
15     $this->secret = $secret;\r
16   }\r
17 \r
18   function __toString() {\r
19     return "OAuthConsumer[key=$this->key,secret=$this->secret]";\r
20   }\r
21 }\r
22 \r
23 class OAuthToken {\r
24   // access tokens and request tokens\r
25   public $key;\r
26   public $secret;\r
27 \r
28   /**\r
29    * key = the token\r
30    * secret = the token secret\r
31    */\r
32   function __construct($key, $secret) {\r
33     $this->key = $key;\r
34     $this->secret = $secret;\r
35   }\r
36 \r
37   /**\r
38    * generates the basic string serialization of a token that a server\r
39    * would respond to request_token and access_token calls with\r
40    */\r
41   function to_string() {\r
42     return "oauth_token=" .\r
43            OAuthUtil::urlencode_rfc3986($this->key) .\r
44            "&oauth_token_secret=" .\r
45            OAuthUtil::urlencode_rfc3986($this->secret);\r
46   }\r
47 \r
48   function __toString() {\r
49     return $this->to_string();\r
50   }\r
51 }\r
52 \r
53 class OAuthSignatureMethod {\r
54   public function check_signature(&$request, $consumer, $token, $signature) {\r
55     $built = $this->build_signature($request, $consumer, $token);\r
56     return $built == $signature;\r
57   }\r
58 }\r
59 \r
60 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {\r
61   function get_name() {\r
62     return "HMAC-SHA1";\r
63   }\r
64 \r
65   public function build_signature($request, $consumer, $token) {\r
66     $base_string = $request->get_signature_base_string();\r
67     $request->base_string = $base_string;\r
68 \r
69     $key_parts = array(\r
70       $consumer->secret,\r
71       ($token) ? $token->secret : ""\r
72     );\r
73 \r
74     $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);\r
75     $key = implode('&', $key_parts);\r
76 \r
77     return base64_encode(hash_hmac('sha1', $base_string, $key, true));\r
78   }\r
79 }\r
80 \r
81 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {\r
82   public function get_name() {\r
83     return "PLAINTEXT";\r
84   }\r
85 \r
86   public function build_signature($request, $consumer, $token) {\r
87     $sig = array(\r
88       OAuthUtil::urlencode_rfc3986($consumer->secret)\r
89     );\r
90 \r
91     if ($token) {\r
92       array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));\r
93     } else {\r
94       array_push($sig, '');\r
95     }\r
96 \r
97     $raw = implode("&", $sig);\r
98     // for debug purposes\r
99     $request->base_string = $raw;\r
100 \r
101     return OAuthUtil::urlencode_rfc3986($raw);\r
102   }\r
103 }\r
104 \r
105 class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {\r
106   public function get_name() {\r
107     return "RSA-SHA1";\r
108   }\r
109 \r
110   protected function fetch_public_cert(&$request) {\r
111     // not implemented yet, ideas are:\r
112     // (1) do a lookup in a table of trusted certs keyed off of consumer\r
113     // (2) fetch via http using a url provided by the requester\r
114     // (3) some sort of specific discovery code based on request\r
115     //\r
116     // either way should return a string representation of the certificate\r
117     throw Exception("fetch_public_cert not implemented");\r
118   }\r
119 \r
120   protected function fetch_private_cert(&$request) {\r
121     // not implemented yet, ideas are:\r
122     // (1) do a lookup in a table of trusted certs keyed off of consumer\r
123     //\r
124     // either way should return a string representation of the certificate\r
125     throw Exception("fetch_private_cert not implemented");\r
126   }\r
127 \r
128   public function build_signature(&$request, $consumer, $token) {\r
129     $base_string = $request->get_signature_base_string();\r
130     $request->base_string = $base_string;\r
131 \r
132     // Fetch the private key cert based on the request\r
133     $cert = $this->fetch_private_cert($request);\r
134 \r
135     // Pull the private key ID from the certificate\r
136     $privatekeyid = openssl_get_privatekey($cert);\r
137 \r
138     // Sign using the key\r
139     $ok = openssl_sign($base_string, $signature, $privatekeyid);\r
140 \r
141     // Release the key resource\r
142     openssl_free_key($privatekeyid);\r
143 \r
144     return base64_encode($signature);\r
145   }\r
146 \r
147   public function check_signature(&$request, $consumer, $token, $signature) {\r
148     $decoded_sig = base64_decode($signature);\r
149 \r
150     $base_string = $request->get_signature_base_string();\r
151 \r
152     // Fetch the public key cert based on the request\r
153     $cert = $this->fetch_public_cert($request);\r
154 \r
155     // Pull the public key ID from the certificate\r
156     $publickeyid = openssl_get_publickey($cert);\r
157 \r
158     // Check the computed signature against the one passed in the query\r
159     $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);\r
160 \r
161     // Release the key resource\r
162     openssl_free_key($publickeyid);\r
163 \r
164     return $ok == 1;\r
165   }\r
166 }\r
167 \r
168 class OAuthRequest {\r
169   private $parameters;\r
170   private $http_method;\r
171   private $http_url;\r
172   public $http_header;\r
173   // for debug purposes\r
174   public $base_string;\r
175   public static $version = '1.0a';\r
176   public static $POST_INPUT = 'php://input';\r
177 \r
178   function __construct($http_method, $http_url, $parameters = array(), $http_header= array()) {\r
179     //@$parameters or $parameters = array();\r
180     $this->parameters = $parameters;\r
181         //@$http_header or $http_header = array();\r
182         $this->http_header = $http_header;\r
183     $this->http_method = $http_method;\r
184     $this->http_url = $http_url;\r
185   }\r
186 \r
187 \r
188   /**\r
189    * attempt to build up a request from what was passed to the server\r
190    */\r
191   public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {\r
192     $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")\r
193               ? 'http'\r
194               : 'https';\r
195     @$http_url or $http_url = $scheme .\r
196                               '://' . $_SERVER['HTTP_HOST'] .\r
197                               ':' .\r
198                               $_SERVER['SERVER_PORT'] .\r
199                               $_SERVER['REQUEST_URI'];\r
200     @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];\r
201 \r
202     // We weren't handed any parameters, so let's find the ones relevant to\r
203     // this request.\r
204     // If you run XML-RPC or similar you should use this to provide your own\r
205     // parsed parameter-list\r
206     if (!$parameters) {\r
207       // Find request headers\r
208       $request_headers = OAuthUtil::get_headers();\r
209 \r
210       // Parse the query-string to find GET parameters\r
211       $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);\r
212 \r
213       // It's a POST request of the proper content-type, so parse POST\r
214       // parameters and add those overriding any duplicates from GET\r
215       if ($http_method == "POST"\r
216           && @strstr($request_headers["Content-Type"],\r
217                      "application/x-www-form-urlencoded")\r
218           ) {\r
219         $post_data = OAuthUtil::parse_parameters(\r
220           file_get_contents(self::$POST_INPUT)\r
221         );\r
222         $parameters = array_merge($parameters, $post_data);\r
223       }\r
224 \r
225       // We have a Authorization-header with OAuth data. Parse the header\r
226       // and add those overriding any duplicates from GET or POST\r
227       if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {\r
228         $header_parameters = OAuthUtil::split_header(\r
229           $request_headers['Authorization']\r
230         );\r
231         $parameters = array_merge($parameters, $header_parameters);\r
232       }\r
233 \r
234     }\r
235 \r
236     return new OAuthRequest($http_method, $http_url, $parameters);\r
237   }\r
238 \r
239   /**\r
240    * pretty much a helper function to set up the request\r
241    */\r
242   public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {\r
243     @$parameters or $parameters = array();\r
244     $defaults = array("oauth_version" => OAuthRequest::$version,\r
245                       "oauth_nonce" => OAuthRequest::generate_nonce(),\r
246                       "oauth_timestamp" => OAuthRequest::generate_timestamp(),\r
247                       "oauth_consumer_key" => $consumer->key);\r
248     if ($token)\r
249       $defaults['oauth_token'] = $token->key;\r
250 \r
251     $parameters = array_merge($defaults, $parameters);\r
252 \r
253     return new OAuthRequest($http_method, $http_url, $parameters);\r
254   }\r
255 \r
256   public function set_parameter($name, $value, $allow_duplicates = true) {\r
257     if ($allow_duplicates && isset($this->parameters[$name])) {\r
258       // We have already added parameter(s) with this name, so add to the list\r
259       if (is_scalar($this->parameters[$name])) {\r
260         // This is the first duplicate, so transform scalar (string)\r
261         // into an array so we can add the duplicates\r
262         $this->parameters[$name] = array($this->parameters[$name]);\r
263       }\r
264 \r
265       $this->parameters[$name][] = $value;\r
266     } else {\r
267       $this->parameters[$name] = $value;\r
268     }\r
269   }\r
270   \r
271 \r
272   public function set_http_header(&$multipart = NULL) {\r
273         if (empty($this->parameters)) {\r
274                 $this->http_header[] = 'Content-Type:';\r
275       $this->http_header[] = 'Content-Length:';\r
276         } else {\r
277                 if($multipart) $this->http_header[] = $this->to_header(); //add OAuth header if we post multipart\r
278                 $this->http_header[] = 'Expect: ';\r
279         }\r
280   }\r
281 \r
282   public function get_parameter($name) {\r
283     return isset($this->parameters[$name]) ? $this->parameters[$name] : null;\r
284   }\r
285 \r
286   public function get_parameters() {\r
287     return $this->parameters;\r
288   }\r
289 \r
290   public function unset_parameter($name) {\r
291     unset($this->parameters[$name]);\r
292   }\r
293 \r
294   /**\r
295    * The request parameters, sorted and concatenated into a normalized string.\r
296    * @return string\r
297    */\r
298   public function get_signable_parameters() {\r
299     // Grab all parameters\r
300     $params = $this->parameters;\r
301 \r
302     // Remove oauth_signature if present\r
303     // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")\r
304     if (isset($params['oauth_signature'])) {\r
305       unset($params['oauth_signature']);\r
306     }\r
307 \r
308     return OAuthUtil::build_http_query($params);\r
309   }\r
310 \r
311   /**\r
312    * Returns the base string of this request\r
313    *\r
314    * The base string defined as the method, the url\r
315    * and the parameters (normalized), each urlencoded\r
316    * and the concated with &.\r
317    */\r
318   public function get_signature_base_string() {\r
319     $parts = array(\r
320       $this->get_normalized_http_method(),\r
321       $this->get_normalized_http_url(),\r
322       $this->get_signable_parameters()\r
323     );\r
324 \r
325     $parts = OAuthUtil::urlencode_rfc3986($parts);\r
326 \r
327     return implode('&', $parts);\r
328   }\r
329 \r
330   /**\r
331    * just uppercases the http method\r
332    */\r
333   public function get_normalized_http_method() {\r
334     return strtoupper($this->http_method);\r
335   }\r
336 \r
337   /**\r
338    * parses the url and rebuilds it to be\r
339    * scheme://host/path\r
340    */\r
341   public function get_normalized_http_url() {\r
342     $parts = parse_url($this->http_url);\r
343 \r
344     $port = @$parts['port'];\r
345     $scheme = $parts['scheme'];\r
346     $host = $parts['host'];\r
347     $path = @$parts['path'];\r
348 \r
349     $port or $port = ($scheme == 'https') ? '443' : '80';\r
350 \r
351     if (($scheme == 'https' && $port != '443')\r
352         || ($scheme == 'http' && $port != '80')) {\r
353       $host = "$host:$port";\r
354     }\r
355     return "$scheme://$host$path";\r
356   }\r
357 \r
358   /**\r
359    * builds a url usable for a GET request\r
360    */\r
361   public function to_url() {\r
362     $post_data = $this->to_postdata();\r
363     $out = $this->get_normalized_http_url();\r
364     if ($post_data) {\r
365       $out .= '?'.$post_data;\r
366     }\r
367     return $out;\r
368   }\r
369 \r
370   /**\r
371    * builds the data one would send in a POST request\r
372    */\r
373   public function to_postdata() {\r
374     return OAuthUtil::build_http_query($this->parameters);\r
375   }\r
376 \r
377   /**\r
378    * builds the Authorization: header\r
379    */\r
380   public function to_header($realm=NULL) {\r
381     $out = 'Authorization: OAuth ';\r
382         if ($realm) $out .= 'realm="'.$realm.'",';\r
383     $total = array();\r
384     foreach ($this->parameters as $k => $v) {\r
385       if (substr($k, 0, 5) != "oauth") continue;\r
386       if (is_array($v)) {\r
387         throw new OAuthException('Arrays not supported in headers');\r
388       }\r
389       $out .= OAuthUtil::urlencode_rfc3986($k) .\r
390               '="' .\r
391               OAuthUtil::urlencode_rfc3986($v) .\r
392               '",';\r
393     }\r
394     return substr($out,0,-1);\r
395   }\r
396 \r
397   public function __toString() {\r
398     return $this->to_url();\r
399   }\r
400 \r
401 \r
402   public function sign_request($signature_method, $consumer, $token) {\r
403     $this->set_parameter(\r
404       "oauth_signature_method",\r
405       $signature_method->get_name(),\r
406       false\r
407     );\r
408     $signature = $this->build_signature($signature_method, $consumer, $token);\r
409     $this->set_parameter("oauth_signature", $signature, false);\r
410   }\r
411 \r
412   public function build_signature($signature_method, $consumer, $token) {\r
413     $signature = $signature_method->build_signature($this, $consumer, $token);\r
414     return $signature;\r
415   }\r
416 \r
417   /**\r
418    * util function: current timestamp\r
419    */\r
420   private static function generate_timestamp() {\r
421     return $_SERVER['REQUEST_TIME'];\r
422   }\r
423 \r
424   /**\r
425    * util function: current nonce\r
426    */\r
427   private static function generate_nonce() {\r
428     $mt = microtime();\r
429     $rand = mt_rand();\r
430 \r
431     return md5($mt . $rand); // md5s look nicer than numbers\r
432   }\r
433 }\r
434 \r
435 class OAuthUtil {\r
436   public static function urlencode_rfc3986($input) {\r
437   if (is_array($input)) {\r
438     return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);\r
439   } else if (is_scalar($input)) {\r
440     return str_replace(\r
441       '+',\r
442       ' ',\r
443       str_replace('%7E', '~', rawurlencode($input))\r
444     );\r
445   } else {\r
446     return '';\r
447   }\r
448 }\r
449 \r
450 \r
451   // This decode function isn't taking into consideration the above\r
452   // modifications to the encoding process. However, this method doesn't\r
453   // seem to be used anywhere so leaving it as is.\r
454   public static function urldecode_rfc3986($string) {\r
455     return urldecode($string);\r
456   }\r
457 \r
458   // Utility function for turning the Authorization: header into\r
459   // parameters, has to do some unescaping\r
460   // Can filter out any non-oauth parameters if needed (default behaviour)\r
461   public static function split_header($header, $only_allow_oauth_parameters = true) {\r
462     $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';\r
463     $offset = 0;\r
464     $params = array();\r
465     while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {\r
466       $match = $matches[0];\r
467       $header_name = $matches[2][0];\r
468       $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];\r
469       if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {\r
470         $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);\r
471       }\r
472       $offset = $match[1] + strlen($match[0]);\r
473     }\r
474 \r
475     if (isset($params['realm'])) {\r
476       unset($params['realm']);\r
477     }\r
478 \r
479     return $params;\r
480   }\r
481 \r
482   // helper to try to sort out headers for people who aren't running apache\r
483   public static function get_headers() {\r
484     if (function_exists('apache_request_headers')) {\r
485       // we need this to get the actual Authorization: header\r
486       // because apache tends to tell us it doesn't exist\r
487       return apache_request_headers();\r
488     }\r
489     // otherwise we don't have apache and are just going to have to hope\r
490     // that $_SERVER actually contains what we need\r
491     $out = array();\r
492     foreach ($_SERVER as $key => $value) {\r
493       if (substr($key, 0, 5) == "HTTP_") {\r
494         // this is chaos, basically it is just there to capitalize the first\r
495         // letter of every word that is not an initial HTTP and strip HTTP\r
496         // code from przemek\r
497         $key = str_replace(\r
498           " ",\r
499           "-",\r
500           ucwords(strtolower(str_replace("_", " ", substr($key, 5))))\r
501         );\r
502         $out[$key] = $value;\r
503       }\r
504     }\r
505     return $out;\r
506   }\r
507 \r
508   // This function takes a input like a=b&a=c&d=e and returns the parsed\r
509   // parameters like this\r
510   // array('a' => array('b','c'), 'd' => 'e')\r
511   public static function parse_parameters( $input ) {\r
512     if (!isset($input) || !$input) return array();\r
513 \r
514     $pairs = explode('&', $input);\r
515 \r
516     $parsed_parameters = array();\r
517     foreach ($pairs as $pair) {\r
518       $split = explode('=', $pair, 2);\r
519       $parameter = OAuthUtil::urldecode_rfc3986($split[0]);\r
520       $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';\r
521 \r
522       if (isset($parsed_parameters[$parameter])) {\r
523         // We have already recieved parameter(s) with this name, so add to the list\r
524         // of parameters with this name\r
525 \r
526         if (is_scalar($parsed_parameters[$parameter])) {\r
527           // This is the first duplicate, so transform scalar (string) into an array\r
528           // so we can add the duplicates\r
529           $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);\r
530         }\r
531 \r
532         $parsed_parameters[$parameter][] = $value;\r
533       } else {\r
534         $parsed_parameters[$parameter] = $value;\r
535       }\r
536     }\r
537     return $parsed_parameters;\r
538   }\r
539 \r
540   public static function build_http_query($params,$multipart=NULL) {\r
541     if (!$params) return '';\r
542 \r
543     // Urlencode both keys and values\r
544     $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));\r
545     $values = OAuthUtil::urlencode_rfc3986(array_values($params));\r
546     $params = array_combine($keys, $values);\r
547 \r
548     // Parameters are sorted by name, using lexicographical byte value ordering.\r
549     // Ref: Spec: 9.1.1 (1)\r
550     uksort($params, 'strcmp');\r
551 \r
552     $pairs = array();\r
553     foreach ($params as $parameter => $value) {\r
554       if (is_array($value)) {\r
555         // If two or more parameters share the same name, they are sorted by their value\r
556         // Ref: Spec: 9.1.1 (1)\r
557         natsort($value);\r
558         foreach ($value as $duplicate_value) {\r
559           $pairs[] = $parameter . '=' . $duplicate_value;\r
560         }\r
561       } else {\r
562         $pairs[] = $parameter . '=' . $value;\r
563       }\r
564     }\r
565     // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)\r
566     // Each name-value pair is separated by an '&' character (ASCII code 38)\r
567     return implode('&', $pairs);\r
568   }\r
569 }\r
570 \r
571 ?>\r