3 /* Generic exception class
\r
5 class OAuthException extends Exception {
\r
9 class OAuthConsumer {
\r
13 function __construct($key, $secret) {
\r
15 $this->secret = $secret;
\r
18 function __toString() {
\r
19 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
\r
24 // access tokens and request tokens
\r
30 * secret = the token secret
\r
32 function __construct($key, $secret) {
\r
34 $this->secret = $secret;
\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
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
48 function __toString() {
\r
49 return $this->to_string();
\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
60 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
\r
61 function get_name() {
\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
71 ($token) ? $token->secret : ""
\r
74 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
\r
75 $key = implode('&', $key_parts);
\r
77 return base64_encode(hash_hmac('sha1', $base_string, $key, true));
\r
81 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
\r
82 public function get_name() {
\r
86 public function build_signature($request, $consumer, $token) {
\r
88 OAuthUtil::urlencode_rfc3986($consumer->secret)
\r
92 array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
\r
94 array_push($sig, '');
\r
97 $raw = implode("&", $sig);
\r
98 // for debug purposes
\r
99 $request->base_string = $raw;
\r
101 return OAuthUtil::urlencode_rfc3986($raw);
\r
105 class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
\r
106 public function get_name() {
\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
116 // either way should return a string representation of the certificate
\r
117 throw Exception("fetch_public_cert not implemented");
\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
124 // either way should return a string representation of the certificate
\r
125 throw Exception("fetch_private_cert not implemented");
\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
132 // Fetch the private key cert based on the request
\r
133 $cert = $this->fetch_private_cert($request);
\r
135 // Pull the private key ID from the certificate
\r
136 $privatekeyid = openssl_get_privatekey($cert);
\r
138 // Sign using the key
\r
139 $ok = openssl_sign($base_string, $signature, $privatekeyid);
\r
141 // Release the key resource
\r
142 openssl_free_key($privatekeyid);
\r
144 return base64_encode($signature);
\r
147 public function check_signature(&$request, $consumer, $token, $signature) {
\r
148 $decoded_sig = base64_decode($signature);
\r
150 $base_string = $request->get_signature_base_string();
\r
152 // Fetch the public key cert based on the request
\r
153 $cert = $this->fetch_public_cert($request);
\r
155 // Pull the public key ID from the certificate
\r
156 $publickeyid = openssl_get_publickey($cert);
\r
158 // Check the computed signature against the one passed in the query
\r
159 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
\r
161 // Release the key resource
\r
162 openssl_free_key($publickeyid);
\r
168 class OAuthRequest {
\r
169 private $parameters;
\r
170 private $http_method;
\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
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
189 * attempt to build up a request from what was passed to the server
\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
195 @$http_url or $http_url = $scheme .
\r
196 '://' . $_SERVER['HTTP_HOST'] .
\r
198 $_SERVER['SERVER_PORT'] .
\r
199 $_SERVER['REQUEST_URI'];
\r
200 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
\r
202 // We weren't handed any parameters, so let's find the ones relevant to
\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
210 // Parse the query-string to find GET parameters
\r
211 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
\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
219 $post_data = OAuthUtil::parse_parameters(
\r
220 file_get_contents(self::$POST_INPUT)
\r
222 $parameters = array_merge($parameters, $post_data);
\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
231 $parameters = array_merge($parameters, $header_parameters);
\r
236 return new OAuthRequest($http_method, $http_url, $parameters);
\r
240 * pretty much a helper function to set up the request
\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
249 $defaults['oauth_token'] = $token->key;
\r
251 $parameters = array_merge($defaults, $parameters);
\r
253 return new OAuthRequest($http_method, $http_url, $parameters);
\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
265 $this->parameters[$name][] = $value;
\r
267 $this->parameters[$name] = $value;
\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
277 if($multipart) $this->http_header[] = $this->to_header(); //add OAuth header if we post multipart
\r
278 $this->http_header[] = 'Expect: ';
\r
282 public function get_parameter($name) {
\r
283 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
\r
286 public function get_parameters() {
\r
287 return $this->parameters;
\r
290 public function unset_parameter($name) {
\r
291 unset($this->parameters[$name]);
\r
295 * The request parameters, sorted and concatenated into a normalized string.
\r
298 public function get_signable_parameters() {
\r
299 // Grab all parameters
\r
300 $params = $this->parameters;
\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
308 return OAuthUtil::build_http_query($params);
\r
312 * Returns the base string of this request
\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
318 public function get_signature_base_string() {
\r
320 $this->get_normalized_http_method(),
\r
321 $this->get_normalized_http_url(),
\r
322 $this->get_signable_parameters()
\r
325 $parts = OAuthUtil::urlencode_rfc3986($parts);
\r
327 return implode('&', $parts);
\r
331 * just uppercases the http method
\r
333 public function get_normalized_http_method() {
\r
334 return strtoupper($this->http_method);
\r
338 * parses the url and rebuilds it to be
\r
339 * scheme://host/path
\r
341 public function get_normalized_http_url() {
\r
342 $parts = parse_url($this->http_url);
\r
344 $port = @$parts['port'];
\r
345 $scheme = $parts['scheme'];
\r
346 $host = $parts['host'];
\r
347 $path = @$parts['path'];
\r
349 $port or $port = ($scheme == 'https') ? '443' : '80';
\r
351 if (($scheme == 'https' && $port != '443')
\r
352 || ($scheme == 'http' && $port != '80')) {
\r
353 $host = "$host:$port";
\r
355 return "$scheme://$host$path";
\r
359 * builds a url usable for a GET request
\r
361 public function to_url() {
\r
362 $post_data = $this->to_postdata();
\r
363 $out = $this->get_normalized_http_url();
\r
365 $out .= '?'.$post_data;
\r
371 * builds the data one would send in a POST request
\r
373 public function to_postdata() {
\r
374 return OAuthUtil::build_http_query($this->parameters);
\r
378 * builds the Authorization: header
\r
380 public function to_header($realm=NULL) {
\r
381 $out = 'Authorization: OAuth ';
\r
382 if ($realm) $out .= 'realm="'.$realm.'",';
\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
389 $out .= OAuthUtil::urlencode_rfc3986($k) .
\r
391 OAuthUtil::urlencode_rfc3986($v) .
\r
394 return substr($out,0,-1);
\r
397 public function __toString() {
\r
398 return $this->to_url();
\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
408 $signature = $this->build_signature($signature_method, $consumer, $token);
\r
409 $this->set_parameter("oauth_signature", $signature, false);
\r
412 public function build_signature($signature_method, $consumer, $token) {
\r
413 $signature = $signature_method->build_signature($this, $consumer, $token);
\r
418 * util function: current timestamp
\r
420 private static function generate_timestamp() {
\r
421 return $_SERVER['REQUEST_TIME'];
\r
425 * util function: current nonce
\r
427 private static function generate_nonce() {
\r
431 return md5($mt . $rand); // md5s look nicer than numbers
\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
443 str_replace('%7E', '~', rawurlencode($input))
\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
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
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
472 $offset = $match[1] + strlen($match[0]);
\r
475 if (isset($params['realm'])) {
\r
476 unset($params['realm']);
\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
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
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
500 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
\r
502 $out[$key] = $value;
\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
514 $pairs = explode('&', $input);
\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
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
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
532 $parsed_parameters[$parameter][] = $value;
\r
534 $parsed_parameters[$parameter] = $value;
\r
537 return $parsed_parameters;
\r
540 public static function build_http_query($params,$multipart=NULL) {
\r
541 if (!$params) return '';
\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
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
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
558 foreach ($value as $duplicate_value) {
\r
559 $pairs[] = $parameter . '=' . $duplicate_value;
\r
562 $pairs[] = $parameter . '=' . $value;
\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