2 // Modified from http://oauth.googlecode.com/svn/code/php/
4 // vim: foldmethod=marker
5 if (!defined('TR_INCLUDE_PATH')) exit;
7 require_once(TR_INCLUDE_PATH. 'classes/DAO/OAuthServerConsumersDAO.class.php');
9 /* Generic exception class
11 class OAuthException extends Exception {
12 function __construct($exception)
14 echo 'error='.urlencode($exception);
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);
28 if (!is_array($consumer)) throw new OAuthException('Consumer is not registered.');
31 $this->secret = $secret;
32 $this->callback_url = $callback_url;
36 function __toString() {
37 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
42 // access tokens and request tokens
48 * secret = the token secret
50 function __construct($key, $secret) {
52 $this->secret = $secret;
56 * generates the basic string serialization of a token that a server
57 * would respond to request_token and access_token calls with
59 function to_string() {
60 return "oauth_token=" .
61 OAuthUtil::urlencode_rfc3986($this->key) .
62 "&oauth_token_secret=" .
63 OAuthUtil::urlencode_rfc3986($this->secret);
66 function __toString() {
67 return $this->to_string();
71 class OAuthSignatureMethod {
72 public function check_signature(&$request, $consumer, $token, $signature) {
73 $built = $this->build_signature($request, $consumer, $token);
74 return $built == $signature;
78 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
83 public function build_signature($request, $consumer, $token) {
84 $base_string = $request->get_signature_base_string();
85 $request->base_string = $base_string;
89 ($token) ? $token->secret : ""
92 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
93 $key = implode('&', $key_parts);
95 return base64_encode(hash_hmac('sha1', $base_string, $key, true));
99 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
100 public function get_name() {
104 public function build_signature($request, $consumer, $token) {
106 OAuthUtil::urlencode_rfc3986($consumer->secret)
110 array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
112 array_push($sig, '');
115 $raw = implode("&", $sig);
116 // for debug purposes
117 $request->base_string = $raw;
119 return OAuthUtil::urlencode_rfc3986($raw);
123 class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
124 public function get_name() {
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
134 // either way should return a string representation of the certificate
135 throw Exception("fetch_public_cert not implemented");
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
142 // either way should return a string representation of the certificate
143 throw Exception("fetch_private_cert not implemented");
146 public function build_signature(&$request, $consumer, $token) {
147 $base_string = $request->get_signature_base_string();
148 $request->base_string = $base_string;
150 // Fetch the private key cert based on the request
151 $cert = $this->fetch_private_cert($request);
153 // Pull the private key ID from the certificate
154 $privatekeyid = openssl_get_privatekey($cert);
156 // Sign using the key
157 $ok = openssl_sign($base_string, $signature, $privatekeyid);
159 // Release the key resource
160 openssl_free_key($privatekeyid);
162 return base64_encode($signature);
165 public function check_signature(&$request, $consumer, $token, $signature) {
166 $decoded_sig = base64_decode($signature);
168 $base_string = $request->get_signature_base_string();
170 // Fetch the public key cert based on the request
171 $cert = $this->fetch_public_cert($request);
173 // Pull the public key ID from the certificate
174 $publickeyid = openssl_get_publickey($cert);
176 // Check the computed signature against the one passed in the query
177 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
179 // Release the key resource
180 openssl_free_key($publickeyid);
188 private $http_method;
190 // for debug purposes
192 public static $version = '1.0';
193 public static $POST_INPUT = 'php://input';
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;
204 * attempt to build up a request from what was passed to the server
206 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
207 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
210 @$http_url or $http_url = $scheme .
211 '://' . $_SERVER['HTTP_HOST'] .
213 $_SERVER['SERVER_PORT'] .
214 $_SERVER['REQUEST_URI'];
215 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
217 // We weren't handed any parameters, so let's find the ones relevant to
219 // If you run XML-RPC or similar you should use this to provide your own
220 // parsed parameter-list
222 // Find request headers
223 $request_headers = OAuthUtil::get_headers();
225 // Parse the query-string to find GET parameters
226 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
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")
234 $post_data = OAuthUtil::parse_parameters(
235 file_get_contents(self::$POST_INPUT)
237 $parameters = array_merge($parameters, $post_data);
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']
246 $parameters = array_merge($parameters, $header_parameters);
251 return new OAuthRequest($http_method, $http_url, $parameters);
255 * pretty much a helper function to set up the request
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);
264 $defaults['oauth_token'] = $token->key;
266 $parameters = array_merge($defaults, $parameters);
268 return new OAuthRequest($http_method, $http_url, $parameters);
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]);
280 $this->parameters[$name][] = $value;
282 $this->parameters[$name] = $value;
286 public function get_parameter($name) {
287 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
290 public function get_parameters() {
291 return $this->parameters;
294 public function unset_parameter($name) {
295 unset($this->parameters[$name]);
299 * The request parameters, sorted and concatenated into a normalized string.
302 public function get_signable_parameters() {
303 // Grab all parameters
304 $params = $this->parameters;
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']);
312 return OAuthUtil::build_http_query($params);
316 * Returns the base string of this request
318 * The base string defined as the method, the url
319 * and the parameters (normalized), each urlencoded
320 * and the concated with &.
322 public function get_signature_base_string() {
324 $this->get_normalized_http_method(),
325 $this->get_normalized_http_url(),
326 $this->get_signable_parameters()
329 $parts = OAuthUtil::urlencode_rfc3986($parts);
331 return implode('&', $parts);
335 * just uppercases the http method
337 public function get_normalized_http_method() {
338 return strtoupper($this->http_method);
342 * parses the url and rebuilds it to be
345 public function get_normalized_http_url() {
346 $parts = parse_url($this->http_url);
348 $port = @$parts['port'];
349 $scheme = $parts['scheme'];
350 $host = $parts['host'];
351 $path = @$parts['path'];
353 $port or $port = ($scheme == 'https') ? '443' : '80';
355 if (($scheme == 'https' && $port != '443')
356 || ($scheme == 'http' && $port != '80')) {
357 $host = "$host:$port";
359 return "$scheme://$host$path";
363 * builds a url usable for a GET request
365 public function to_url() {
366 $post_data = $this->to_postdata();
367 $out = $this->get_normalized_http_url();
369 $out .= '?'.$post_data;
375 * builds the data one would send in a POST request
377 public function to_postdata() {
378 return OAuthUtil::build_http_query($this->parameters);
382 * builds the Authorization: header
384 public function to_header() {
385 $out ='Authorization: OAuth realm=""';
387 foreach ($this->parameters as $k => $v) {
388 if (substr($k, 0, 5) != "oauth") continue;
390 throw new OAuthException('Arrays not supported in headers');
393 OAuthUtil::urlencode_rfc3986($k) .
395 OAuthUtil::urlencode_rfc3986($v) .
401 public function __toString() {
402 return $this->to_url();
406 public function sign_request($signature_method, $consumer, $token) {
407 $this->set_parameter(
408 "oauth_signature_method",
409 $signature_method->get_name(),
412 $signature = $this->build_signature($signature_method, $consumer, $token);
413 $this->set_parameter("oauth_signature", $signature, false);
416 public function build_signature($signature_method, $consumer, $token) {
417 $signature = $signature_method->build_signature($this, $consumer, $token);
422 * util function: current timestamp
424 private static function generate_timestamp() {
429 * util function: current nonce
431 private static function generate_nonce() {
435 return md5($mt . $rand); // md5s look nicer than numbers
440 protected $timestamp_threshold; // in seconds, five minutes
441 protected $version = 1.0; // hi blaine
442 protected $signature_methods = array();
444 protected $data_store;
446 function __construct($data_store) {
447 $this->data_store = $data_store;
450 public function add_signature_method($signature_method) {
451 $this->signature_methods[$signature_method->get_name()] =
455 // high level functions
458 * process a request_token request
459 * returns the request token on success
461 public function fetch_request_token(&$request) {
462 $this->get_version($request);
464 $consumer = $this->get_consumer($request);
466 // no token required for the initial token request
469 $this->check_signature($request, $consumer, $token);
471 $new_token = $this->data_store->new_request_token($consumer);
477 * process an access_token request
478 * returns the access token on success
480 public function fetch_access_token(&$request) {
481 $this->get_version($request);
483 $consumer = $this->get_consumer($request);
485 // requires authorized request token
486 $token = $this->get_token($request, $consumer, "request");
488 $this->check_signature($request, $consumer, $token);
490 if ($this->data_store->lookup_authenticate_request_token($token))
492 $new_token = $this->data_store->new_access_token($token, $consumer);
496 throw new OAuthException("User authenticate is not performed.");
500 * verify an api call, checks all the parameters
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);
510 // Internals from here
514 private function get_version(&$request) {
515 $version = $request->get_parameter("oauth_version");
519 if ($version && $version != $this->version) {
520 throw new OAuthException("OAuth version '$version' not supported");
526 * figure out the signature with some defaults
528 private function get_signature_method(&$request) {
530 @$request->get_parameter("oauth_signature_method");
531 if (!$signature_method) {
532 $signature_method = "PLAINTEXT";
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))
542 return $this->signature_methods[$signature_method];
546 * try to find the consumer for the provided request's consumer key
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");
554 $consumer = $this->data_store->lookup_consumer($consumer_key);
556 throw new OAuthException("Invalid consumer");
563 * try to find the token for the provided request's token key
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
571 throw new OAuthException("Invalid $token_type token: $token_field");
577 * all-in-one function to check the signature on a request
578 * should guess the signature method appropriately
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');
585 $this->timestamp_threshold = $this->data_store->lookup_expire_threshold($consumer);
587 $this->check_timestamp($timestamp);
588 $this->check_nonce($consumer, $token, $nonce, $timestamp);
590 $signature_method = $this->get_signature_method($request);
592 $signature = $request->get_parameter('oauth_signature');
593 $valid_sig = $signature_method->check_signature(
601 throw new OAuthException("Invalid signature");
606 * check that the timestamp is new enough
608 private function check_timestamp($timestamp) {
609 // verify that timestamp is recentish
610 // when threshold is 0, never expire
612 if ($this->timestamp_threshold <> 0 && $now - $timestamp > $this->timestamp_threshold) {
613 throw new OAuthException(
614 "Expired timestamp, yours $timestamp, ours $now"
620 * check that the nonce is not repeated
622 private function check_nonce($consumer, $token, $nonce, $timestamp) {
623 // verify that the nonce is uniqueish
624 $found = $this->data_store->lookup_nonce(
631 throw new OAuthException("Nonce already used: $nonce");
637 class OAuthDataStore {
638 function lookup_consumer($consumer_key) {
642 function lookup_token($consumer, $token_type, $token) {
646 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
650 function new_request_token($consumer) {
651 // return a new token attached to this consumer
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
658 // should also invalidate the request token
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)) {
671 str_replace('%7E', '~', rawurlencode($input))
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);
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]*)=("([^"]*)"|([^,]*)),?)/';
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);
700 $offset = $match[1] + strlen($match[0]);
703 if (isset($params['realm'])) {
704 unset($params['realm']);
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();
717 // otherwise we don't have apache and are just going to have to hope
718 // that $_SERVER actually contains what we need
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
728 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
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();
742 $pairs = explode('&', $input);
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]) : '';
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
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]);
760 $parsed_parameters[$parameter][] = $value;
762 $parsed_parameters[$parameter] = $value;
765 return $parsed_parameters;
768 public static function build_http_query($params) {
769 if (!$params) return '';
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);
776 // Parameters are sorted by name, using lexicographical byte value ordering.
777 // Ref: Spec: 9.1.1 (1)
778 uksort($params, 'strcmp');
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)
786 foreach ($value as $duplicate_value) {
787 $pairs[] = $parameter . '=' . $duplicate_value;
790 $pairs[] = $parameter . '=' . $value;
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);