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