2 // Modified from http://oauth.googlecode.com/svn/code/php/
4 // vim: foldmethod=marker
5 if (!defined('AT_INCLUDE_PATH')) exit;
7 /* Generic exception class
9 class OAuthException extends Exception {
10 function __construct($exception)
12 echo 'error='.urlencode($exception);
21 function __construct($key, $secret, $callback_url=NULL) {
22 // check if the consumer is registered
24 // $oAuthServerConsumersDAO = new OAuthServerConsumersDAO();
25 // $consumer = $oAuthServerConsumersDAO->getByConsumerKeyAndSecret($key, $secret);
27 // if (!is_array($consumer)) throw new OAuthException('Consumer is not registered.');
30 $this->secret = $secret;
31 $this->callback_url = $callback_url;
35 function __toString() {
36 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
41 // access tokens and request tokens
47 * secret = the token secret
49 function __construct($key, $secret) {
51 $this->secret = $secret;
55 * generates the basic string serialization of a token that a server
56 * would respond to request_token and access_token calls with
58 function to_string() {
59 return "oauth_token=" .
60 OAuthUtil::urlencode_rfc3986($this->key) .
61 "&oauth_token_secret=" .
62 OAuthUtil::urlencode_rfc3986($this->secret);
65 function __toString() {
66 return $this->to_string();
70 class OAuthSignatureMethod {
71 public function check_signature(&$request, $consumer, $token, $signature) {
72 $built = $this->build_signature($request, $consumer, $token);
73 return $built == $signature;
77 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
82 public function build_signature($request, $consumer, $token) {
83 $base_string = $request->get_signature_base_string();
84 $request->base_string = $base_string;
88 ($token) ? $token->secret : ""
91 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
92 $key = implode('&', $key_parts);
94 return base64_encode(hash_hmac('sha1', $base_string, $key, true));
98 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
99 public function get_name() {
103 public function build_signature($request, $consumer, $token) {
105 OAuthUtil::urlencode_rfc3986($consumer->secret)
109 array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
111 array_push($sig, '');
114 $raw = implode("&", $sig);
115 // for debug purposes
116 $request->base_string = $raw;
118 return OAuthUtil::urlencode_rfc3986($raw);
122 class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
123 public function get_name() {
127 protected function fetch_public_cert(&$request) {
128 // not implemented yet, ideas are:
129 // (1) do a lookup in a table of trusted certs keyed off of consumer
130 // (2) fetch via http using a url provided by the requester
131 // (3) some sort of specific discovery code based on request
133 // either way should return a string representation of the certificate
134 throw Exception("fetch_public_cert not implemented");
137 protected function fetch_private_cert(&$request) {
138 // not implemented yet, ideas are:
139 // (1) do a lookup in a table of trusted certs keyed off of consumer
141 // either way should return a string representation of the certificate
142 throw Exception("fetch_private_cert not implemented");
145 public function build_signature(&$request, $consumer, $token) {
146 $base_string = $request->get_signature_base_string();
147 $request->base_string = $base_string;
149 // Fetch the private key cert based on the request
150 $cert = $this->fetch_private_cert($request);
152 // Pull the private key ID from the certificate
153 $privatekeyid = openssl_get_privatekey($cert);
155 // Sign using the key
156 $ok = openssl_sign($base_string, $signature, $privatekeyid);
158 // Release the key resource
159 openssl_free_key($privatekeyid);
161 return base64_encode($signature);
164 public function check_signature(&$request, $consumer, $token, $signature) {
165 $decoded_sig = base64_decode($signature);
167 $base_string = $request->get_signature_base_string();
169 // Fetch the public key cert based on the request
170 $cert = $this->fetch_public_cert($request);
172 // Pull the public key ID from the certificate
173 $publickeyid = openssl_get_publickey($cert);
175 // Check the computed signature against the one passed in the query
176 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
178 // Release the key resource
179 openssl_free_key($publickeyid);
187 private $http_method;
189 // for debug purposes
191 public static $version = '1.0';
192 public static $POST_INPUT = 'php://input';
194 function __construct($http_method, $http_url, $parameters=NULL) {
195 @$parameters or $parameters = array();
196 $this->parameters = $parameters;
197 $this->http_method = $http_method;
198 $this->http_url = $http_url;
203 * attempt to build up a request from what was passed to the server
205 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
206 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
209 @$http_url or $http_url = $scheme .
210 '://' . $_SERVER['HTTP_HOST'] .
212 $_SERVER['SERVER_PORT'] .
213 $_SERVER['REQUEST_URI'];
214 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
216 // We weren't handed any parameters, so let's find the ones relevant to
218 // If you run XML-RPC or similar you should use this to provide your own
219 // parsed parameter-list
221 // Find request headers
222 $request_headers = OAuthUtil::get_headers();
224 // Parse the query-string to find GET parameters
225 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
227 // It's a POST request of the proper content-type, so parse POST
228 // parameters and add those overriding any duplicates from GET
229 if ($http_method == "POST"
230 && @strstr($request_headers["Content-Type"],
231 "application/x-www-form-urlencoded")
233 $post_data = OAuthUtil::parse_parameters(
234 file_get_contents(self::$POST_INPUT)
236 $parameters = array_merge($parameters, $post_data);
239 // We have a Authorization-header with OAuth data. Parse the header
240 // and add those overriding any duplicates from GET or POST
241 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
242 $header_parameters = OAuthUtil::split_header(
243 $request_headers['Authorization']
245 $parameters = array_merge($parameters, $header_parameters);
250 return new OAuthRequest($http_method, $http_url, $parameters);
254 * pretty much a helper function to set up the request
256 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
257 @$parameters or $parameters = array();
258 $defaults = array("oauth_version" => OAuthRequest::$version,
259 "oauth_nonce" => OAuthRequest::generate_nonce(),
260 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
261 "oauth_consumer_key" => $consumer->key);
263 $defaults['oauth_token'] = $token->key;
265 $parameters = array_merge($defaults, $parameters);
267 return new OAuthRequest($http_method, $http_url, $parameters);
270 public function set_parameter($name, $value, $allow_duplicates = true) {
271 if ($allow_duplicates && isset($this->parameters[$name])) {
272 // We have already added parameter(s) with this name, so add to the list
273 if (is_scalar($this->parameters[$name])) {
274 // This is the first duplicate, so transform scalar (string)
275 // into an array so we can add the duplicates
276 $this->parameters[$name] = array($this->parameters[$name]);
279 $this->parameters[$name][] = $value;
281 $this->parameters[$name] = $value;
285 public function get_parameter($name) {
286 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
289 public function get_parameters() {
290 return $this->parameters;
293 public function unset_parameter($name) {
294 unset($this->parameters[$name]);
298 * The request parameters, sorted and concatenated into a normalized string.
301 public function get_signable_parameters() {
302 // Grab all parameters
303 $params = $this->parameters;
305 // Remove oauth_signature if present
306 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
307 if (isset($params['oauth_signature'])) {
308 unset($params['oauth_signature']);
311 return OAuthUtil::build_http_query($params);
315 * Returns the base string of this request
317 * The base string defined as the method, the url
318 * and the parameters (normalized), each urlencoded
319 * and the concated with &.
321 public function get_signature_base_string() {
323 $this->get_normalized_http_method(),
324 $this->get_normalized_http_url(),
325 $this->get_signable_parameters()
328 $parts = OAuthUtil::urlencode_rfc3986($parts);
330 return implode('&', $parts);
334 * just uppercases the http method
336 public function get_normalized_http_method() {
337 return strtoupper($this->http_method);
341 * parses the url and rebuilds it to be
344 public function get_normalized_http_url() {
345 $parts = parse_url($this->http_url);
347 $port = @$parts['port'];
348 $scheme = $parts['scheme'];
349 $host = $parts['host'];
350 $path = @$parts['path'];
352 $port or $port = ($scheme == 'https') ? '443' : '80';
354 if (($scheme == 'https' && $port != '443')
355 || ($scheme == 'http' && $port != '80')) {
356 $host = "$host:$port";
358 return "$scheme://$host$path";
362 * builds a url usable for a GET request
364 public function to_url() {
365 $post_data = $this->to_postdata();
366 $out = $this->get_normalized_http_url();
368 $out .= '?'.$post_data;
374 * builds the data one would send in a POST request
376 public function to_postdata() {
377 return OAuthUtil::build_http_query($this->parameters);
381 * builds the Authorization: header
383 public function to_header() {
384 $out ='Authorization: OAuth realm=""';
386 foreach ($this->parameters as $k => $v) {
387 if (substr($k, 0, 5) != "oauth") continue;
389 throw new OAuthException('Arrays not supported in headers');
392 OAuthUtil::urlencode_rfc3986($k) .
394 OAuthUtil::urlencode_rfc3986($v) .
400 public function __toString() {
401 return $this->to_url();
405 public function sign_request($signature_method, $consumer, $token) {
406 $this->set_parameter(
407 "oauth_signature_method",
408 $signature_method->get_name(),
411 $signature = $this->build_signature($signature_method, $consumer, $token);
412 $this->set_parameter("oauth_signature", $signature, false);
415 public function build_signature($signature_method, $consumer, $token) {
416 $signature = $signature_method->build_signature($this, $consumer, $token);
421 * util function: current timestamp
423 private static function generate_timestamp() {
428 * util function: current nonce
430 private static function generate_nonce() {
434 return md5($mt . $rand); // md5s look nicer than numbers
439 protected $timestamp_threshold; // in seconds, five minutes
440 protected $version = 1.0; // hi blaine
441 protected $signature_methods = array();
443 protected $data_store;
445 function __construct($data_store) {
446 $this->data_store = $data_store;
449 public function add_signature_method($signature_method) {
450 $this->signature_methods[$signature_method->get_name()] =
454 // high level functions
457 * process a request_token request
458 * returns the request token on success
460 public function fetch_request_token(&$request) {
461 $this->get_version($request);
463 $consumer = $this->get_consumer($request);
465 // no token required for the initial token request
468 $this->check_signature($request, $consumer, $token);
470 $new_token = $this->data_store->new_request_token($consumer);
476 * process an access_token request
477 * returns the access token on success
479 public function fetch_access_token(&$request) {
480 $this->get_version($request);
482 $consumer = $this->get_consumer($request);
484 // requires authorized request token
485 $token = $this->get_token($request, $consumer, "request");
487 $this->check_signature($request, $consumer, $token);
489 if ($this->data_store->lookup_authenticate_request_token($token))
491 $new_token = $this->data_store->new_access_token($token, $consumer);
495 throw new OAuthException("User authenticate is not performed.");
499 * verify an api call, checks all the parameters
501 public function verify_request(&$request) {
502 $this->get_version($request);
503 $consumer = $this->get_consumer($request);
504 $token = $this->get_token($request, $consumer, "access");
505 $this->check_signature($request, $consumer, $token);
506 return array($consumer, $token);
509 // Internals from here
513 private function get_version(&$request) {
514 $version = $request->get_parameter("oauth_version");
518 if ($version && $version != $this->version) {
519 throw new OAuthException("OAuth version '$version' not supported");
525 * figure out the signature with some defaults
527 private function get_signature_method(&$request) {
529 @$request->get_parameter("oauth_signature_method");
530 if (!$signature_method) {
531 $signature_method = "PLAINTEXT";
533 if (!in_array($signature_method,
534 array_keys($this->signature_methods))) {
535 throw new OAuthException(
536 "Signature method '$signature_method' not supported " .
537 "try one of the following: " .
538 implode(", ", array_keys($this->signature_methods))
541 return $this->signature_methods[$signature_method];
545 * try to find the consumer for the provided request's consumer key
547 private function get_consumer(&$request) {
548 $consumer_key = @$request->get_parameter("oauth_consumer_key");
549 if (!$consumer_key) {
550 throw new OAuthException("Invalid consumer key");
553 $consumer = $this->data_store->lookup_consumer($consumer_key);
555 throw new OAuthException("Invalid consumer");
562 * try to find the token for the provided request's token key
564 private function get_token(&$request, $consumer, $token_type="access") {
565 $token_field = @$request->get_parameter('oauth_token');
566 $token = $this->data_store->lookup_token(
567 $consumer, $token_type, $token_field
570 throw new OAuthException("Invalid $token_type token: $token_field");
576 * all-in-one function to check the signature on a request
577 * should guess the signature method appropriately
579 private function check_signature(&$request, $consumer, $token) {
580 // this should probably be in a different method
581 $timestamp = @$request->get_parameter('oauth_timestamp');
582 $nonce = @$request->get_parameter('oauth_nonce');
584 $this->timestamp_threshold = $this->data_store->lookup_expire_threshold($consumer);
586 $this->check_timestamp($timestamp);
587 $this->check_nonce($consumer, $token, $nonce, $timestamp);
589 $signature_method = $this->get_signature_method($request);
591 $signature = $request->get_parameter('oauth_signature');
592 $valid_sig = $signature_method->check_signature(
600 throw new OAuthException("Invalid signature");
605 * check that the timestamp is new enough
607 private function check_timestamp($timestamp) {
608 // verify that timestamp is recentish
609 // when threshold is 0, never expire
611 if ($this->timestamp_threshold <> 0 && $now - $timestamp > $this->timestamp_threshold) {
612 throw new OAuthException(
613 "Expired timestamp, yours $timestamp, ours $now"
619 * check that the nonce is not repeated
621 private function check_nonce($consumer, $token, $nonce, $timestamp) {
622 // verify that the nonce is uniqueish
623 $found = $this->data_store->lookup_nonce(
630 throw new OAuthException("Nonce already used: $nonce");
636 class OAuthDataStore {
637 function lookup_consumer($consumer_key) {
641 function lookup_token($consumer, $token_type, $token) {
645 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
649 function new_request_token($consumer) {
650 // return a new token attached to this consumer
653 function new_access_token($token, $consumer) {
654 // return a new access token attached to this consumer
655 // for the user associated with this token if the request token
657 // should also invalidate the request token
663 public static function urlencode_rfc3986($input) {
664 if (is_array($input)) {
665 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
666 } else if (is_scalar($input)) {
670 str_replace('%7E', '~', rawurlencode($input))
678 // This decode function isn't taking into consideration the above
679 // modifications to the encoding process. However, this method doesn't
680 // seem to be used anywhere so leaving it as is.
681 public static function urldecode_rfc3986($string) {
682 return urldecode($string);
685 // Utility function for turning the Authorization: header into
686 // parameters, has to do some unescaping
687 // Can filter out any non-oauth parameters if needed (default behaviour)
688 public static function split_header($header, $only_allow_oauth_parameters = true) {
689 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
692 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
693 $match = $matches[0];
694 $header_name = $matches[2][0];
695 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
696 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
697 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
699 $offset = $match[1] + strlen($match[0]);
702 if (isset($params['realm'])) {
703 unset($params['realm']);
709 // helper to try to sort out headers for people who aren't running apache
710 public static function get_headers() {
711 if (function_exists('apache_request_headers')) {
712 // we need this to get the actual Authorization: header
713 // because apache tends to tell us it doesn't exist
714 return apache_request_headers();
716 // otherwise we don't have apache and are just going to have to hope
717 // that $_SERVER actually contains what we need
719 foreach ($_SERVER as $key => $value) {
720 if (substr($key, 0, 5) == "HTTP_") {
721 // this is chaos, basically it is just there to capitalize the first
722 // letter of every word that is not an initial HTTP and strip HTTP
727 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
735 // This function takes a input like a=b&a=c&d=e and returns the parsed
736 // parameters like this
737 // array('a' => array('b','c'), 'd' => 'e')
738 public static function parse_parameters( $input ) {
739 if (!isset($input) || !$input) return array();
741 $pairs = explode('&', $input);
743 $parsed_parameters = array();
744 foreach ($pairs as $pair) {
745 $split = explode('=', $pair, 2);
746 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
747 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
749 if (isset($parsed_parameters[$parameter])) {
750 // We have already recieved parameter(s) with this name, so add to the list
751 // of parameters with this name
753 if (is_scalar($parsed_parameters[$parameter])) {
754 // This is the first duplicate, so transform scalar (string) into an array
755 // so we can add the duplicates
756 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
759 $parsed_parameters[$parameter][] = $value;
761 $parsed_parameters[$parameter] = $value;
764 return $parsed_parameters;
767 public static function build_http_query($params) {
768 if (!$params) return '';
770 // Urlencode both keys and values
771 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
772 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
773 $params = array_combine($keys, $values);
775 // Parameters are sorted by name, using lexicographical byte value ordering.
776 // Ref: Spec: 9.1.1 (1)
777 uksort($params, 'strcmp');
780 foreach ($params as $parameter => $value) {
781 if (is_array($value)) {
782 // If two or more parameters share the same name, they are sorted by their value
783 // Ref: Spec: 9.1.1 (1)
785 foreach ($value as $duplicate_value) {
786 $pairs[] = $parameter . '=' . $duplicate_value;
789 $pairs[] = $parameter . '=' . $value;
792 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
793 // Each name-value pair is separated by an '&' character (ASCII code 38)
794 return implode('&', $pairs);