· 8 years ago · Dec 22, 2016, 03:26 PM
1<?php
2// vim: foldmethod=marker
3
4/* Generic exception class
5 */
6if (!class_exists('OAuthException')) {
7 class OAuthException extends Exception {
8 // pass
9 }
10}
11
12class OAuthConsumer {
13 public $key;<?php
14// vim: foldmethod=marker
15
16/* Generic exception class
17 */
18if (!class_exists('OAuthException')) {
19 class OAuthException extends Exception {
20 // pass
21 }
22}
23
24class OAuthConsumer {
25 public $key;
26 public $secret;
27
28 function __construct($key, $secret, $callback_url=NULL) {
29 $this->key = $key;
30 $this->secret = $secret;
31 $this->callback_url = $callback_url;
32 }
33
34 function __toString() {
35 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
36 }
37}
38
39class OAuthToken {
40 // access tokens and request tokens
41 public $key;
42 public $secret;
43
44 /**
45 * key = the token
46 * secret = the token secret
47 */
48 function __construct($key, $secret) {
49 $this->key = $key;
50 $this->secret = $secret;
51 }
52
53 /**
54 * generates the basic string serialization of a token that a server
55 * would respond to request_token and access_token calls with
56 */
57 function to_string() {
58 return "oauth_token=" .
59 OAuthUtil::urlencode_rfc3986($this->key) .
60 "&oauth_token_secret=" .
61 OAuthUtil::urlencode_rfc3986($this->secret);
62 }
63
64 function __toString() {
65 return $this->to_string();
66 }
67}
68
69/**
70 * A class for implementing a Signature Method
71 * See section 9 ("Signing Requests") in the spec
72 */
73abstract class OAuthSignatureMethod {
74 /**
75 * Needs to return the name of the Signature Method (ie HMAC-SHA1)
76 * @return string
77 */
78 abstract public function get_name();
79
80 /**
81 * Build up the signature
82 * NOTE: The output of this function MUST NOT be urlencoded.
83 * the encoding is handled in OAuthRequest when the final
84 * request is serialized
85 * @param OAuthRequest $request
86 * @param OAuthConsumer $consumer
87 * @param OAuthToken $token
88 * @return string
89 */
90 abstract public function build_signature($request, $consumer, $token);
91
92 /**
93 * Verifies that a given signature is correct
94 * @param OAuthRequest $request
95 * @param OAuthConsumer $consumer
96 * @param OAuthToken $token
97 * @param string $signature
98 * @return bool
99 */
100 public function check_signature($request, $consumer, $token, $signature) {
101 $built = $this->build_signature($request, $consumer, $token);
102 return $built == $signature;
103 }
104}
105
106/**
107 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
108 * where the Signature Base String is the text and the key is the concatenated values (each first
109 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
110 * character (ASCII code 38) even if empty.
111 * - Chapter 9.2 ("HMAC-SHA1")
112 */
113class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
114 function get_name() {
115 return "HMAC-SHA1";
116 }
117
118 public function build_signature($request, $consumer, $token) {
119 $base_string = $request->get_signature_base_string();
120 $request->base_string = $base_string;
121
122 $key_parts = array(
123 $consumer->secret,
124 ($token) ? $token->secret : ""
125 );
126
127 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
128 $key = implode('&', $key_parts);
129
130 return base64_encode(hash_hmac('sha1', $base_string, $key, true));
131 }
132}
133
134/**
135 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
136 * over a secure channel such as HTTPS. It does not use the Signature Base String.
137 * - Chapter 9.4 ("PLAINTEXT")
138 */
139class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
140 public function get_name() {
141 return "PLAINTEXT";
142 }
143
144 /**
145 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
146 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
147 * empty. The result MUST be encoded again.
148 * - Chapter 9.4.1 ("Generating Signatures")
149 *
150 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
151 * OAuthRequest handles this!
152 */
153 public function build_signature($request, $consumer, $token) {
154 $key_parts = array(
155 $consumer->secret,
156 ($token) ? $token->secret : ""
157 );
158
159 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
160 $key = implode('&', $key_parts);
161 $request->base_string = $key;
162
163 return $key;
164 }
165}
166
167/**
168 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
169 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
170 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
171 * verified way to the Service Provider, in a manner which is beyond the scope of this
172 * specification.
173 * - Chapter 9.3 ("RSA-SHA1")
174 */
175abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
176 public function get_name() {
177 return "RSA-SHA1";
178 }
179
180 // Up to the SP to implement this lookup of keys. Possible ideas are:
181 // (1) do a lookup in a table of trusted certs keyed off of consumer
182 // (2) fetch via http using a url provided by the requester
183 // (3) some sort of specific discovery code based on request
184 //
185 // Either way should return a string representation of the certificate
186 protected abstract function fetch_public_cert(&$request);
187
188 // Up to the SP to implement this lookup of keys. Possible ideas are:
189 // (1) do a lookup in a table of trusted certs keyed off of consumer
190 //
191 // Either way should return a string representation of the certificate
192 protected abstract function fetch_private_cert(&$request);
193
194 public function build_signature($request, $consumer, $token) {
195 $base_string = $request->get_signature_base_string();
196 $request->base_string = $base_string;
197
198 // Fetch the private key cert based on the request
199 $cert = $this->fetch_private_cert($request);
200
201 // Pull the private key ID from the certificate
202 $privatekeyid = openssl_get_privatekey($cert);
203
204 // Sign using the key
205 $ok = openssl_sign($base_string, $signature, $privatekeyid);
206
207 // Release the key resource
208 openssl_free_key($privatekeyid);
209
210 return base64_encode($signature);
211 }
212
213 public function check_signature($request, $consumer, $token, $signature) {
214 $decoded_sig = base64_decode($signature);
215
216 $base_string = $request->get_signature_base_string();
217
218 // Fetch the public key cert based on the request
219 $cert = $this->fetch_public_cert($request);
220
221 // Pull the public key ID from the certificate
222 $publickeyid = openssl_get_publickey($cert);
223
224 // Check the computed signature against the one passed in the query
225 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
226
227 // Release the key resource
228 openssl_free_key($publickeyid);
229
230 return $ok == 1;
231 }
232}
233
234class OAuthRequest {
235 private $parameters;
236 private $http_method;
237 private $http_url;
238 // for debug purposes
239 public $base_string;
240 public static $version = '1.0';
241 public static $POST_INPUT = 'php://input';
242
243 function __construct($http_method, $http_url, $parameters=NULL) {
244 @$parameters or $parameters = array();
245 $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
246 $this->parameters = $parameters;
247 $this->http_method = $http_method;
248 $this->http_url = $http_url;
249 }
250
251
252 /**
253 * attempt to build up a request from what was passed to the server
254 */
255 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
256 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
257 ? 'http'
258 : 'https';
259 @$http_url or $http_url = $scheme .
260 '://' . $_SERVER['HTTP_HOST'] .
261 ':' .
262 $_SERVER['SERVER_PORT'] .
263 $_SERVER['REQUEST_URI'];
264 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
265
266 // We weren't handed any parameters, so let's find the ones relevant to
267 // this request.
268 // If you run XML-RPC or similar you should use this to provide your own
269 // parsed parameter-list
270 if (!$parameters) {
271 // Find request headers
272 $request_headers = OAuthUtil::get_headers();
273
274 // Parse the query-string to find GET parameters
275 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
276
277 // It's a POST request of the proper content-type, so parse POST
278 // parameters and add those overriding any duplicates from GET
279 if ($http_method == "POST"
280 && @strstr($request_headers["Content-Type"],
281 "application/x-www-form-urlencoded")
282 ) {
283 $post_data = OAuthUtil::parse_parameters(
284 file_get_contents(self::$POST_INPUT)
285 );
286 $parameters = array_merge($parameters, $post_data);
287 }
288
289 // We have a Authorization-header with OAuth data. Parse the header
290 // and add those overriding any duplicates from GET or POST
291 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
292 $header_parameters = OAuthUtil::split_header(
293 $request_headers['Authorization']
294 );
295 $parameters = array_merge($parameters, $header_parameters);
296 }
297
298 }
299
300 return new OAuthRequest($http_method, $http_url, $parameters);
301 }
302
303 /**
304 * pretty much a helper function to set up the request
305 */
306 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
307 @$parameters or $parameters = array();
308 $defaults = array("oauth_version" => OAuthRequest::$version,
309 "oauth_nonce" => OAuthRequest::generate_nonce(),
310 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
311 "oauth_consumer_key" => $consumer->key);
312 if ($token)
313 $defaults['oauth_token'] = $token->key;
314
315 $parameters = array_merge($defaults, $parameters);
316
317 return new OAuthRequest($http_method, $http_url, $parameters);
318 }
319
320 public function set_parameter($name, $value, $allow_duplicates = true) {
321 if ($allow_duplicates && isset($this->parameters[$name])) {
322 // We have already added parameter(s) with this name, so add to the list
323 if (is_scalar($this->parameters[$name])) {
324 // This is the first duplicate, so transform scalar (string)
325 // into an array so we can add the duplicates
326 $this->parameters[$name] = array($this->parameters[$name]);
327 }
328
329 $this->parameters[$name][] = $value;
330 } else {
331 $this->parameters[$name] = $value;
332 }
333 }
334
335 public function get_parameter($name) {
336 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
337 }
338
339 public function get_parameters() {
340 return $this->parameters;
341 }
342
343 public function unset_parameter($name) {
344 unset($this->parameters[$name]);
345 }
346
347 /**
348 * The request parameters, sorted and concatenated into a normalized string.
349 * @return string
350 */
351 public function get_signable_parameters() {
352 // Grab all parameters
353 $params = $this->parameters;
354
355 // Remove oauth_signature if present
356 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
357 if (isset($params['oauth_signature'])) {
358 unset($params['oauth_signature']);
359 }
360
361 return OAuthUtil::build_http_query($params);
362 }
363
364 /**
365 * Returns the base string of this request
366 *
367 * The base string defined as the method, the url
368 * and the parameters (normalized), each urlencoded
369 * and the concated with &.
370 */
371 public function get_signature_base_string() {
372 $parts = array(
373 $this->get_normalized_http_method(),
374 $this->get_normalized_http_url(),
375 $this->get_signable_parameters()
376 );
377
378 $parts = OAuthUtil::urlencode_rfc3986($parts);
379
380 return implode('&', $parts);
381 }
382
383 /**
384 * just uppercases the http method
385 */
386 public function get_normalized_http_method() {
387 return strtoupper($this->http_method);
388 }
389
390 /**
391 * parses the url and rebuilds it to be
392 * scheme://host/path
393 */
394 public function get_normalized_http_url() {
395 $parts = parse_url($this->http_url);
396
397 $port = @$parts['port'];
398 $scheme = $parts['scheme'];
399 $host = $parts['host'];
400 $path = @$parts['path'];
401
402 $port or $port = ($scheme == 'https') ? '443' : '80';
403
404 if (($scheme == 'https' && $port != '443')
405 || ($scheme == 'http' && $port != '80')) {
406 $host = "$host:$port";
407 }
408 return "$scheme://$host$path";
409 }
410
411 /**
412 * builds a url usable for a GET request
413 */
414 public function to_url() {
415 $post_data = $this->to_postdata();
416 $out = $this->get_normalized_http_url();
417 if ($post_data) {
418 $out .= '?'.$post_data;
419 }
420 return $out;
421 }
422
423 /**
424 * builds the data one would send in a POST request
425 */
426 public function to_postdata() {
427 return OAuthUtil::build_http_query($this->parameters);
428 }
429
430 /**
431 * builds the Authorization: header
432 */
433 public function to_header($realm=null) {
434 $first = true;
435 if($realm) {
436 $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
437 $first = false;
438 } else
439 $out = 'Authorization: OAuth';
440
441 $total = array();
442 foreach ($this->parameters as $k => $v) {
443 if (substr($k, 0, 5) != "oauth") continue;
444 if (is_array($v)) {
445 throw new OAuthException('Arrays not supported in headers');
446 }
447 $out .= ($first) ? ' ' : ',';
448 $out .= OAuthUtil::urlencode_rfc3986($k) .
449 '="' .
450 OAuthUtil::urlencode_rfc3986($v) .
451 '"';
452 $first = false;
453 }
454 return $out;
455 }
456
457 public function __toString() {
458 return $this->to_url();
459 }
460
461
462 public function sign_request($signature_method, $consumer, $token) {
463 $this->set_parameter(
464 "oauth_signature_method",
465 $signature_method->get_name(),
466 false
467 );
468 $signature = $this->build_signature($signature_method, $consumer, $token);
469 $this->set_parameter("oauth_signature", $signature, false);
470 }
471
472 public function build_signature($signature_method, $consumer, $token) {
473 $signature = $signature_method->build_signature($this, $consumer, $token);
474 return $signature;
475 }
476
477 /**
478 * util function: current timestamp
479 */
480 private static function generate_timestamp() {
481 return time();
482 }
483
484 /**
485 * util function: current nonce
486 */
487 private static function generate_nonce() {
488 $mt = microtime();
489 $rand = mt_rand();
490
491 return md5($mt . $rand); // md5s look nicer than numbers
492 }
493}
494
495class OAuthServer {
496 protected $timestamp_threshold = 300; // in seconds, five minutes
497 protected $version = '1.0'; // hi blaine
498 protected $signature_methods = array();
499
500 protected $data_store;
501
502 function __construct($data_store) {
503 $this->data_store = $data_store;
504 }
505
506 public function add_signature_method($signature_method) {
507 $this->signature_methods[$signature_method->get_name()] =
508 $signature_method;
509 }
510
511 // high level functions
512
513 /**
514 * process a request_token request
515 * returns the request token on success
516 */
517 public function fetch_request_token(&$request) {
518 $this->get_version($request);
519
520 $consumer = $this->get_consumer($request);
521
522 // no token required for the initial token request
523 $token = NULL;
524
525 $this->check_signature($request, $consumer, $token);
526
527 // Rev A change
528 $callback = $request->get_parameter('oauth_callback');
529 $new_token = $this->data_store->new_request_token($consumer, $callback);
530
531 return $new_token;
532 }
533
534 /**
535 * process an access_token request
536 * returns the access token on success
537 */
538 public function fetch_access_token(&$request) {
539 $this->get_version($request);
540
541 $consumer = $this->get_consumer($request);
542
543 // requires authorized request token
544 $token = $this->get_token($request, $consumer, "request");
545
546 $this->check_signature($request, $consumer, $token);
547
548 // Rev A change
549 $verifier = $request->get_parameter('oauth_verifier');
550 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
551
552 return $new_token;
553 }
554
555 /**
556 * verify an api call, checks all the parameters
557 */
558 public function verify_request(&$request) {
559 $this->get_version($request);
560 $consumer = $this->get_consumer($request);
561 $token = $this->get_token($request, $consumer, "access");
562 $this->check_signature($request, $consumer, $token);
563 return array($consumer, $token);
564 }
565
566 // Internals from here
567 /**
568 * version 1
569 */
570 private function get_version(&$request) {
571 $version = $request->get_parameter("oauth_version");
572 if (!$version) {
573 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
574 // Chapter 7.0 ("Accessing Protected Ressources")
575 $version = '1.0';
576 }
577 if ($version !== $this->version) {
578 throw new OAuthException("OAuth version '$version' not supported");
579 }
580 return $version;
581 }
582
583 /**
584 * figure out the signature with some defaults
585 */
586 private function get_signature_method(&$request) {
587 $signature_method =
588 @$request->get_parameter("oauth_signature_method");
589
590 if (!$signature_method) {
591 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
592 // parameter is required, and we can't just fallback to PLAINTEXT
593 throw new OAuthException('No signature method parameter. This parameter is required');
594 }
595
596 if (!in_array($signature_method,
597 array_keys($this->signature_methods))) {
598 throw new OAuthException(
599 "Signature method '$signature_method' not supported " .
600 "try one of the following: " .
601 implode(", ", array_keys($this->signature_methods))
602 );
603 }
604 return $this->signature_methods[$signature_method];
605 }
606
607 /**
608 * try to find the consumer for the provided request's consumer key
609 */
610 private function get_consumer(&$request) {
611 $consumer_key = @$request->get_parameter("oauth_consumer_key");
612 if (!$consumer_key) {
613 throw new OAuthException("Invalid consumer key");
614 }
615
616 $consumer = $this->data_store->lookup_consumer($consumer_key);
617 if (!$consumer) {
618 throw new OAuthException("Invalid consumer");
619 }
620
621 return $consumer;
622 }
623
624 /**
625 * try to find the token for the provided request's token key
626 */
627 private function get_token(&$request, $consumer, $token_type="access") {
628 $token_field = @$request->get_parameter('oauth_token');
629 $token = $this->data_store->lookup_token(
630 $consumer, $token_type, $token_field
631 );
632 if (!$token) {
633 throw new OAuthException("Invalid $token_type token: $token_field");
634 }
635 return $token;
636 }
637
638 /**
639 * all-in-one function to check the signature on a request
640 * should guess the signature method appropriately
641 */
642 private function check_signature(&$request, $consumer, $token) {
643 // this should probably be in a different method
644 $timestamp = @$request->get_parameter('oauth_timestamp');
645 $nonce = @$request->get_parameter('oauth_nonce');
646
647 $this->check_timestamp($timestamp);
648 $this->check_nonce($consumer, $token, $nonce, $timestamp);
649
650 $signature_method = $this->get_signature_method($request);
651
652 $signature = $request->get_parameter('oauth_signature');
653 $valid_sig = $signature_method->check_signature(
654 $request,
655 $consumer,
656 $token,
657 $signature
658 );
659
660 if (!$valid_sig) {
661 throw new OAuthException("Invalid signature");
662 }
663 }
664
665 /**
666 * check that the timestamp is new enough
667 */
668 private function check_timestamp($timestamp) {
669 if( ! $timestamp )
670 throw new OAuthException(
671 'Missing timestamp parameter. The parameter is required'
672 );
673
674 // verify that timestamp is recentish
675 $now = time();
676 if (abs($now - $timestamp) > $this->timestamp_threshold) {
677 throw new OAuthException(
678 "Expired timestamp, yours $timestamp, ours $now"
679 );
680 }
681 }
682
683 /**
684 * check that the nonce is not repeated
685 */
686 private function check_nonce($consumer, $token, $nonce, $timestamp) {
687 if( ! $nonce )
688 throw new OAuthException(
689 'Missing nonce parameter. The parameter is required'
690 );
691
692 // verify that the nonce is uniqueish
693 $found = $this->data_store->lookup_nonce(
694 $consumer,
695 $token,
696 $nonce,
697 $timestamp
698 );
699 if ($found) {
700 throw new OAuthException("Nonce already used: $nonce");
701 }
702 }
703
704}
705
706class OAuthDataStore {
707 function lookup_consumer($consumer_key) {
708 // implement me
709 }
710
711 function lookup_token($consumer, $token_type, $token) {
712 // implement me
713 }
714
715 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
716 // implement me
717 }
718
719 function new_request_token($consumer, $callback = null) {
720 // return a new token attached to this consumer
721 }
722
723 function new_access_token($token, $consumer, $verifier = null) {
724 // return a new access token attached to this consumer
725 // for the user associated with this token if the request token
726 // is authorized
727 // should also invalidate the request token
728 }
729
730}
731
732class OAuthUtil {
733 public static function urlencode_rfc3986($input) {
734 if (is_array($input)) {
735 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
736 } else if (is_scalar($input)) {
737 return str_replace(
738 '+',
739 ' ',
740 str_replace('%7E', '~', rawurlencode($input))
741 );
742 } else {
743 return '';
744 }
745}
746
747
748 // This decode function isn't taking into consideration the above
749 // modifications to the encoding process. However, this method doesn't
750 // seem to be used anywhere so leaving it as is.
751 public static function urldecode_rfc3986($string) {
752 return urldecode($string);
753 }
754
755 // Utility function for turning the Authorization: header into
756 // parameters, has to do some unescaping
757 // Can filter out any non-oauth parameters if needed (default behaviour)
758 public static function split_header($header, $only_allow_oauth_parameters = true) {
759 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
760 $offset = 0;
761 $params = array();
762 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
763 $match = $matches[0];
764 $header_name = $matches[2][0];
765 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
766 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
767 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
768 }
769 $offset = $match[1] + strlen($match[0]);
770 }
771
772 if (isset($params['realm'])) {
773 unset($params['realm']);
774 }
775
776 return $params;
777 }
778
779 // helper to try to sort out headers for people who aren't running apache
780 public static function get_headers() {
781 if (function_exists('apache_request_headers')) {
782 // we need this to get the actual Authorization: header
783 // because apache tends to tell us it doesn't exist
784 $headers = apache_request_headers();
785
786 // sanitize the output of apache_request_headers because
787 // we always want the keys to be Cased-Like-This and arh()
788 // returns the headers in the same case as they are in the
789 // request
790 $out = array();
791 foreach( $headers AS $key => $value ) {
792 $key = str_replace(
793 " ",
794 "-",
795 ucwords(strtolower(str_replace("-", " ", $key)))
796 );
797 $out[$key] = $value;
798 }
799 } else {
800 // otherwise we don't have apache and are just going to have to hope
801 // that $_SERVER actually contains what we need
802 $out = array();
803 if( isset($_SERVER['CONTENT_TYPE']) )
804 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
805 if( isset($_ENV['CONTENT_TYPE']) )
806 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
807
808 foreach ($_SERVER as $key => $value) {
809 if (substr($key, 0, 5) == "HTTP_") {
810 // this is chaos, basically it is just there to capitalize the first
811 // letter of every word that is not an initial HTTP and strip HTTP
812 // code from przemek
813 $key = str_replace(
814 " ",
815 "-",
816 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
817 );
818 $out[$key] = $value;
819 }
820 }
821 }
822 return $out;
823 }
824
825 // This function takes a input like a=b&a=c&d=e and returns the parsed
826 // parameters like this
827 // array('a' => array('b','c'), 'd' => 'e')
828 public static function parse_parameters( $input ) {
829 if (!isset($input) || !$input) return array();
830
831 $pairs = explode('&', $input);
832
833 $parsed_parameters = array();
834 foreach ($pairs as $pair) {
835 $split = explode('=', $pair, 2);
836 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
837 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
838
839 if (isset($parsed_parameters[$parameter])) {
840 // We have already recieved parameter(s) with this name, so add to the list
841 // of parameters with this name
842
843 if (is_scalar($parsed_parameters[$parameter])) {
844 // This is the first duplicate, so transform scalar (string) into an array
845 // so we can add the duplicates
846 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
847 }
848
849 $parsed_parameters[$parameter][] = $value;
850 } else {
851 $parsed_parameters[$parameter] = $value;
852 }
853 }
854 return $parsed_parameters;
855 }
856
857 public static function build_http_query($params) {
858 if (!$params) return '';
859
860 // Urlencode both keys and values
861 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
862 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
863 $params = array_combine($keys, $values);
864
865 // Parameters are sorted by name, using lexicographical byte value ordering.
866 // Ref: Spec: 9.1.1 (1)
867 uksort($params, 'strcmp');
868
869 $pairs = array();
870 foreach ($params as $parameter => $value) {
871 if (is_array($value)) {
872 // If two or more parameters share the same name, they are sorted by their value
873 // Ref: Spec: 9.1.1 (1)
874 natsort($value);
875 foreach ($value as $duplicate_value) {
876 $pairs[] = $parameter . '=' . $duplicate_value;
877 }
878 } else {
879 $pairs[] = $parameter . '=' . $value;
880 }
881 }
882 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
883 // Each name-value pair is separated by an '&' character (ASCII code 38)
884 return implode('&', $pairs);
885 }
886}
887a
888 public $secret;
889
890 function __construct($key, $secret, $callback_url=NULL) {
891 $this->key = $key;
892 $this->secret = $secret;
893 $this->callback_url = $callback_url;
894 }
895
896 function __toString() {
897 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
898 }
899}
900
901class OAuthToken {
902 // access tokens and request tokens
903 public $key;
904 public $secret;
905
906 /**
907 * key = the token
908 * secret = the token secret
909 */
910 function __construct($key, $secret) {
911 $this->key = $key;
912 $this->secret = $secret;
913 }
914
915 /**
916 * generates the basic string serialization of a token that a server
917 * would respond to request_token and access_token calls with
918 */
919 function to_string() {
920 return "oauth_token=" .
921 OAuthUtil::urlencode_rfc3986($this->key) .
922 "&oauth_token_secret=" .
923 OAuthUtil::urlencode_rfc3986($this->secret);
924 }
925
926 function __toString() {
927 return $this->to_string();
928 }
929}
930
931/**
932 * A class for implementing a Signature Method
933 * See section 9 ("Signing Requests") in the spec
934 */
935abstract class OAuthSignatureMethod {
936 /**
937 * Needs to return the name of the Signature Method (ie HMAC-SHA1)
938 * @return string
939 */
940 abstract public function get_name();
941
942 /**
943 * Build up the signature
944 * NOTE: The output of this function MUST NOT be urlencoded.
945 * the encoding is handled in OAuthRequest when the final
946 * request is serialized
947 * @param OAuthRequest $request
948 * @param OAuthConsumer $consumer
949 * @param OAuthToken $token
950 * @return string
951 */
952 abstract public function build_signature($request, $consumer, $token);
953
954 /**
955 * Verifies that a given signature is correct
956 * @param OAuthRequest $request
957 * @param OAuthConsumer $consumer
958 * @param OAuthToken $token
959 * @param string $signature
960 * @return bool
961 */
962 public function check_signature($request, $consumer, $token, $signature) {
963 $built = $this->build_signature($request, $consumer, $token);
964 return $built == $signature;
965 }
966}
967
968/**
969 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
970 * where the Signature Base String is the text and the key is the concatenated values (each first
971 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
972 * character (ASCII code 38) even if empty.
973 * - Chapter 9.2 ("HMAC-SHA1")
974 */
975class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
976 function get_name() {
977 return "HMAC-SHA1";
978 }
979
980 public function build_signature($request, $consumer, $token) {
981 $base_string = $request->get_signature_base_string();
982 $request->base_string = $base_string;
983
984 $key_parts = array(
985 $consumer->secret,
986 ($token) ? $token->secret : ""
987 );
988
989 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
990 $key = implode('&', $key_parts);
991
992 return base64_encode(hash_hmac('sha1', $base_string, $key, true));
993 }
994}
995
996/**
997 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
998 * over a secure channel such as HTTPS. It does not use the Signature Base String.
999 * - Chapter 9.4 ("PLAINTEXT")
1000 */
1001class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
1002 public function get_name() {
1003 return "PLAINTEXT";
1004 }
1005
1006 /**
1007 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
1008 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
1009 * empty. The result MUST be encoded again.
1010 * - Chapter 9.4.1 ("Generating Signatures")
1011 *
1012 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
1013 * OAuthRequest handles this!
1014 */
1015 public function build_signature($request, $consumer, $token) {
1016 $key_parts = array(
1017 $consumer->secret,
1018 ($token) ? $token->secret : ""
1019 );
1020
1021 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
1022 $key = implode('&', $key_parts);
1023 $request->base_string = $key;
1024
1025 return $key;
1026 }
1027}
1028
1029/**
1030 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
1031 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
1032 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
1033 * verified way to the Service Provider, in a manner which is beyond the scope of this
1034 * specification.
1035 * - Chapter 9.3 ("RSA-SHA1")
1036 */
1037abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
1038 public function get_name() {
1039 return "RSA-SHA1";
1040 }
1041
1042 // Up to the SP to implement this lookup of keys. Possible ideas are:
1043 // (1) do a lookup in a table of trusted certs keyed off of consumer
1044 // (2) fetch via http using a url provided by the requester
1045 // (3) some sort of specific discovery code based on request
1046 //
1047 // Either way should return a string representation of the certificate
1048 protected abstract function fetch_public_cert(&$request);
1049
1050 // Up to the SP to implement this lookup of keys. Possible ideas are:
1051 // (1) do a lookup in a table of trusted certs keyed off of consumer
1052 //
1053 // Either way should return a string representation of the certificate
1054 protected abstract function fetch_private_cert(&$request);
1055
1056 public function build_signature($request, $consumer, $token) {
1057 $base_string = $request->get_signature_base_string();
1058 $request->base_string = $base_string;
1059
1060 // Fetch the private key cert based on the request
1061 $cert = $this->fetch_private_cert($request);
1062
1063 // Pull the private key ID from the certificate
1064 $privatekeyid = openssl_get_privatekey($cert);
1065
1066 // Sign using the key
1067 $ok = openssl_sign($base_string, $signature, $privatekeyid);
1068
1069 // Release the key resource
1070 openssl_free_key($privatekeyid);
1071
1072 return base64_encode($signature);
1073 }
1074
1075 public function check_signature($request, $consumer, $token, $signature) {
1076 $decoded_sig = base64_decode($signature);
1077
1078 $base_string = $request->get_signature_base_string();
1079
1080 // Fetch the public key cert based on the request
1081 $cert = $this->fetch_public_cert($request);
1082
1083 // Pull the public key ID from the certificate
1084 $publickeyid = openssl_get_publickey($cert);
1085
1086 // Check the computed signature against the one passed in the query
1087 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
1088
1089 // Release the key resource
1090 openssl_free_key($publickeyid);
1091
1092 return $ok == 1;
1093 }
1094}
1095
1096class OAuthRequest {
1097 private $parameters;
1098 private $http_method;
1099 private $http_url;
1100 // for debug purposes
1101 public $base_string;
1102 public static $version = '1.0';
1103 public static $POST_INPUT = 'php://input';
1104
1105 function __construct($http_method, $http_url, $parameters=NULL) {
1106 @$parameters or $parameters = array();
1107 $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
1108 $this->parameters = $parameters;
1109 $this->http_method = $http_method;
1110 $this->http_url = $http_url;
1111 }
1112
1113
1114 /**
1115 * attempt to build up a request from what was passed to the server
1116 */
1117 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
1118 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
1119 ? 'http'
1120 : 'https';
1121 @$http_url or $http_url = $scheme .
1122 '://' . $_SERVER['HTTP_HOST'] .
1123 ':' .
1124 $_SERVER['SERVER_PORT'] .
1125 $_SERVER['REQUEST_URI'];
1126 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
1127
1128 // We weren't handed any parameters, so let's find the ones relevant to
1129 // this request.
1130 // If you run XML-RPC or similar you should use this to provide your own
1131 // parsed parameter-list
1132 if (!$parameters) {
1133 // Find request headers
1134 $request_headers = OAuthUtil::get_headers();
1135
1136 // Parse the query-string to find GET parameters
1137 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
1138
1139 // It's a POST request of the proper content-type, so parse POST
1140 // parameters and add those overriding any duplicates from GET
1141 if ($http_method == "POST"
1142 && @strstr($request_headers["Content-Type"],
1143 "application/x-www-form-urlencoded")
1144 ) {
1145 $post_data = OAuthUtil::parse_parameters(
1146 file_get_contents(self::$POST_INPUT)
1147 );
1148 $parameters = array_merge($parameters, $post_data);
1149 }
1150
1151 // We have a Authorization-header with OAuth data. Parse the header
1152 // and add those overriding any duplicates from GET or POST
1153 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
1154 $header_parameters = OAuthUtil::split_header(
1155 $request_headers['Authorization']
1156 );
1157 $parameters = array_merge($parameters, $header_parameters);
1158 }
1159
1160 }
1161
1162 return new OAuthRequest($http_method, $http_url, $parameters);
1163 }
1164
1165 /**
1166 * pretty much a helper function to set up the request
1167 */
1168 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
1169 @$parameters or $parameters = array();
1170 $defaults = array("oauth_version" => OAuthRequest::$version,
1171 "oauth_nonce" => OAuthRequest::generate_nonce(),
1172 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
1173 "oauth_consumer_key" => $consumer->key);
1174 if ($token)
1175 $defaults['oauth_token'] = $token->key;
1176
1177 $parameters = array_merge($defaults, $parameters);
1178
1179 return new OAuthRequest($http_method, $http_url, $parameters);
1180 }
1181
1182 public function set_parameter($name, $value, $allow_duplicates = true) {
1183 if ($allow_duplicates && isset($this->parameters[$name])) {
1184 // We have already added parameter(s) with this name, so add to the list
1185 if (is_scalar($this->parameters[$name])) {
1186 // This is the first duplicate, so transform scalar (string)
1187 // into an array so we can add the duplicates
1188 $this->parameters[$name] = array($this->parameters[$name]);
1189 }
1190
1191 $this->parameters[$name][] = $value;
1192 } else {
1193 $this->parameters[$name] = $value;
1194 }
1195 }
1196
1197 public function get_parameter($name) {
1198 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
1199 }
1200
1201 public function get_parameters() {
1202 return $this->parameters;
1203 }
1204
1205 public function unset_parameter($name) {
1206 unset($this->parameters[$name]);
1207 }
1208
1209 /**
1210 * The request parameters, sorted and concatenated into a normalized string.
1211 * @return string
1212 */
1213 public function get_signable_parameters() {
1214 // Grab all parameters
1215 $params = $this->parameters;
1216
1217 // Remove oauth_signature if present
1218 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
1219 if (isset($params['oauth_signature'])) {
1220 unset($params['oauth_signature']);
1221 }
1222
1223 return OAuthUtil::build_http_query($params);
1224 }
1225
1226 /**
1227 * Returns the base string of this request
1228 *
1229 * The base string defined as the method, the url
1230 * and the parameters (normalized), each urlencoded
1231 * and the concated with &.
1232 */
1233 public function get_signature_base_string() {
1234 $parts = array(
1235 $this->get_normalized_http_method(),
1236 $this->get_normalized_http_url(),
1237 $this->get_signable_parameters()
1238 );
1239
1240 $parts = OAuthUtil::urlencode_rfc3986($parts);
1241
1242 return implode('&', $parts);
1243 }
1244
1245 /**
1246 * just uppercases the http method
1247 */
1248 public function get_normalized_http_method() {
1249 return strtoupper($this->http_method);
1250 }
1251
1252 /**
1253 * parses the url and rebuilds it to be
1254 * scheme://host/path
1255 */
1256 public function get_normalized_http_url() {
1257 $parts = parse_url($this->http_url);
1258
1259 $port = @$parts['port'];
1260 $scheme = $parts['scheme'];
1261 $host = $parts['host'];
1262 $path = @$parts['path'];
1263
1264 $port or $port = ($scheme == 'https') ? '443' : '80';
1265
1266 if (($scheme == 'https' && $port != '443')
1267 || ($scheme == 'http' && $port != '80')) {
1268 $host = "$host:$port";
1269 }
1270 return "$scheme://$host$path";
1271 }
1272
1273 /**
1274 * builds a url usable for a GET request
1275 */
1276 public function to_url() {
1277 $post_data = $this->to_postdata();
1278 $out = $this->get_normalized_http_url();
1279 if ($post_data) {
1280 $out .= '?'.$post_data;
1281 }
1282 return $out;
1283 }
1284
1285 /**
1286 * builds the data one would send in a POST request
1287 */
1288 public function to_postdata() {
1289 return OAuthUtil::build_http_query($this->parameters);
1290 }
1291
1292 /**
1293 * builds the Authorization: header
1294 */
1295 public function to_header($realm=null) {
1296 $first = true;
1297 if($realm) {
1298 $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
1299 $first = false;
1300 } else
1301 $out = 'Authorization: OAuth';
1302
1303 $total = array();
1304 foreach ($this->parameters as $k => $v) {
1305 if (substr($k, 0, 5) != "oauth") continue;
1306 if (is_array($v)) {
1307 throw new OAuthException('Arrays not supported in headers');
1308 }
1309 $out .= ($first) ? ' ' : ',';
1310 $out .= OAuthUtil::urlencode_rfc3986($k) .
1311 '="' .
1312 OAuthUtil::urlencode_rfc3986($v) .
1313 '"';
1314 $first = false;
1315 }
1316 return $out;
1317 }
1318
1319 public function __toString() {
1320 return $this->to_url();
1321 }
1322
1323
1324 public function sign_request($signature_method, $consumer, $token) {
1325 $this->set_parameter(
1326 "oauth_signature_method",
1327 $signature_method->get_name(),
1328 false
1329 );
1330 $signature = $this->build_signature($signature_method, $consumer, $token);
1331 $this->set_parameter("oauth_signature", $signature, false);
1332 }
1333
1334 public function build_signature($signature_method, $consumer, $token) {
1335 $signature = $signature_method->build_signature($this, $consumer, $token);
1336 return $signature;
1337 }
1338
1339 /**
1340 * util function: current timestamp
1341 */
1342 private static function generate_timestamp() {
1343 return time();
1344 }
1345
1346 /**
1347 * util function: current nonce
1348 */
1349 private static function generate_nonce() {
1350 $mt = microtime();
1351 $rand = mt_rand();
1352
1353 return md5($mt . $rand); // md5s look nicer than numbers
1354 }
1355}
1356
1357class OAuthServer {
1358 protected $timestamp_threshold = 300; // in seconds, five minutes
1359 protected $version = '1.0'; // hi blaine
1360 protected $signature_methods = array();
1361
1362 protected $data_store;
1363
1364 function __construct($data_store) {
1365 $this->data_store = $data_store;
1366 }
1367
1368 public function add_signature_method($signature_method) {
1369 $this->signature_methods[$signature_method->get_name()] =
1370 $signature_method;
1371 }
1372
1373 // high level functions
1374
1375 /**
1376 * process a request_token request
1377 * returns the request token on success
1378 */
1379 public function fetch_request_token(&$request) {
1380 $this->get_version($request);
1381
1382 $consumer = $this->get_consumer($request);
1383
1384 // no token required for the initial token request
1385 $token = NULL;
1386
1387 $this->check_signature($request, $consumer, $token);
1388
1389 // Rev A change
1390 $callback = $request->get_parameter('oauth_callback');
1391 $new_token = $this->data_store->new_request_token($consumer, $callback);
1392
1393 return $new_token;
1394 }
1395
1396 /**
1397 * process an access_token request
1398 * returns the access token on success
1399 */
1400 public function fetch_access_token(&$request) {
1401 $this->get_version($request);
1402
1403 $consumer = $this->get_consumer($request);
1404
1405 // requires authorized request token
1406 $token = $this->get_token($request, $consumer, "request");
1407
1408 $this->check_signature($request, $consumer, $token);
1409
1410 // Rev A change
1411 $verifier = $request->get_parameter('oauth_verifier');
1412 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
1413
1414 return $new_token;
1415 }
1416
1417 /**
1418 * verify an api call, checks all the parameters
1419 */
1420 public function verify_request(&$request) {
1421 $this->get_version($request);
1422 $consumer = $this->get_consumer($request);
1423 $token = $this->get_token($request, $consumer, "access");
1424 $this->check_signature($request, $consumer, $token);
1425 return array($consumer, $token);
1426 }
1427
1428 // Internals from here
1429 /**
1430 * version 1
1431 */
1432 private function get_version(&$request) {
1433 $version = $request->get_parameter("oauth_version");
1434 if (!$version) {
1435 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
1436 // Chapter 7.0 ("Accessing Protected Ressources")
1437 $version = '1.0';
1438 }
1439 if ($version !== $this->version) {
1440 throw new OAuthException("OAuth version '$version' not supported");
1441 }
1442 return $version;
1443 }
1444
1445 /**
1446 * figure out the signature with some defaults
1447 */
1448 private function get_signature_method(&$request) {
1449 $signature_method =
1450 @$request->get_parameter("oauth_signature_method");
1451
1452 if (!$signature_method) {
1453 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
1454 // parameter is required, and we can't just fallback to PLAINTEXT
1455 throw new OAuthException('No signature method parameter. This parameter is required');
1456 }
1457
1458 if (!in_array($signature_method,
1459 array_keys($this->signature_methods))) {
1460 throw new OAuthException(
1461 "Signature method '$signature_method' not supported " .
1462 "try one of the following: " .
1463 implode(", ", array_keys($this->signature_methods))
1464 );
1465 }
1466 return $this->signature_methods[$signature_method];
1467 }
1468
1469 /**
1470 * try to find the consumer for the provided request's consumer key
1471 */
1472 private function get_consumer(&$request) {
1473 $consumer_key = @$request->get_parameter("oauth_consumer_key");
1474 if (!$consumer_key) {
1475 throw new OAuthException("Invalid consumer key");
1476 }
1477
1478 $consumer = $this->data_store->lookup_consumer($consumer_key);
1479 if (!$consumer) {
1480 throw new OAuthException("Invalid consumer");
1481 }
1482
1483 return $consumer;
1484 }
1485
1486 /**
1487 * try to find the token for the provided request's token key
1488 */
1489 private function get_token(&$request, $consumer, $token_type="access") {
1490 $token_field = @$request->get_parameter('oauth_token');
1491 $token = $this->data_store->lookup_token(
1492 $consumer, $token_type, $token_field
1493 );
1494 if (!$token) {
1495 throw new OAuthException("Invalid $token_type token: $token_field");
1496 }
1497 return $token;
1498 }
1499
1500 /**
1501 * all-in-one function to check the signature on a request
1502 * should guess the signature method appropriately
1503 */
1504 private function check_signature(&$request, $consumer, $token) {
1505 // this should probably be in a different method
1506 $timestamp = @$request->get_parameter('oauth_timestamp');
1507 $nonce = @$request->get_parameter('oauth_nonce');
1508
1509 $this->check_timestamp($timestamp);
1510 $this->check_nonce($consumer, $token, $nonce, $timestamp);
1511
1512 $signature_method = $this->get_signature_method($request);
1513
1514 $signature = $request->get_parameter('oauth_signature');
1515 $valid_sig = $signature_method->check_signature(
1516 $request,
1517 $consumer,
1518 $token,
1519 $signature
1520 );
1521
1522 if (!$valid_sig) {
1523 throw new OAuthException("Invalid signature");
1524 }
1525 }
1526
1527 /**
1528 * check that the timestamp is new enough
1529 */
1530 private function check_timestamp($timestamp) {
1531 if( ! $timestamp )
1532 throw new OAuthException(
1533 'Missing timestamp parameter. The parameter is required'
1534 );
1535
1536 // verify that timestamp is recentish
1537 $now = time();
1538 if (abs($now - $timestamp) > $this->timestamp_threshold) {
1539 throw new OAuthException(
1540 "Expired timestamp, yours $timestamp, ours $now"
1541 );
1542 }
1543 }
1544
1545 /**
1546 * check that the nonce is not repeated
1547 */
1548 private function check_nonce($consumer, $token, $nonce, $timestamp) {
1549 if( ! $nonce )
1550 throw new OAuthException(
1551 'Missing nonce parameter. The parameter is required'
1552 );
1553
1554 // verify that the nonce is uniqueish
1555 $found = $this->data_store->lookup_nonce(
1556 $consumer,
1557 $token,
1558 $nonce,
1559 $timestamp
1560 );
1561 if ($found) {
1562 throw new OAuthException("Nonce already used: $nonce");
1563 }
1564 }
1565
1566}
1567
1568class OAuthDataStore {
1569 function lookup_consumer($consumer_key) {
1570 // implement me
1571 }
1572
1573 function lookup_token($consumer, $token_type, $token) {
1574 // implement me
1575 }
1576
1577 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
1578 // implement me
1579 }
1580
1581 function new_request_token($consumer, $callback = null) {
1582 // return a new token attached to this consumer
1583 }
1584
1585 function new_access_token($token, $consumer, $verifier = null) {
1586 // return a new access token attached to this consumer
1587 // for the user associated with this token if the request token
1588 // is authorized
1589 // should also invalidate the request token
1590 }
1591
1592}
1593
1594class OAuthUtil {
1595 public static function urlencode_rfc3986($input) {
1596 if (is_array($input)) {
1597 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
1598 } else if (is_scalar($input)) {
1599 return str_replace(
1600 '+',
1601 ' ',
1602 str_replace('%7E', '~', rawurlencode($input))
1603 );
1604 } else {
1605 return '';
1606 }
1607}
1608
1609
1610 // This decode function isn't taking into consideration the above
1611 // modifications to the encoding process. However, this method doesn't
1612 // seem to be used anywhere so leaving it as is.
1613 public static function urldecode_rfc3986($string) {
1614 return urldecode($string);
1615 }
1616
1617 // Utility function for turning the Authorization: header into
1618 // parameters, has to do some unescaping
1619 // Can filter out any non-oauth parameters if needed (default behaviour)
1620 public static function split_header($header, $only_allow_oauth_parameters = true) {
1621 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
1622 $offset = 0;
1623 $params = array();
1624 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
1625 $match = $matches[0];
1626 $header_name = $matches[2][0];
1627 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
1628 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
1629 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
1630 }
1631 $offset = $match[1] + strlen($match[0]);
1632 }
1633
1634 if (isset($params['realm'])) {
1635 unset($params['realm']);
1636 }
1637
1638 return $params;
1639 }
1640
1641 // helper to try to sort out headers for people who aren't running apache
1642 public static function get_headers() {
1643 if (function_exists('apache_request_headers')) {
1644 // we need this to get the actual Authorization: header
1645 // because apache tends to tell us it doesn't exist
1646 $headers = apache_request_headers();
1647
1648 // sanitize the output of apache_request_headers because
1649 // we always want the keys to be Cased-Like-This and arh()
1650 // returns the headers in the same case as they are in the
1651 // request
1652 $out = array();
1653 foreach( $headers AS $key => $value ) {
1654 $key = str_replace(
1655 " ",
1656 "-",
1657 ucwords(strtolower(str_replace("-", " ", $key)))
1658 );
1659 $out[$key] = $value;
1660 }
1661 } else {
1662 // otherwise we don't have apache and are just going to have to hope
1663 // that $_SERVER actually contains what we need
1664 $out = array();
1665 if( isset($_SERVER['CONTENT_TYPE']) )
1666 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
1667 if( isset($_ENV['CONTENT_TYPE']) )
1668 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
1669
1670 foreach ($_SERVER as $key => $value) {
1671 if (substr($key, 0, 5) == "HTTP_") {
1672 // this is chaos, basically it is just there to capitalize the first
1673 // letter of every word that is not an initial HTTP and strip HTTP
1674 // code from przemek
1675 $key = str_replace(
1676 " ",
1677 "-",
1678 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
1679 );
1680 $out[$key] = $value;
1681 }
1682 }
1683 }
1684 return $out;
1685 }
1686
1687 // This function takes a input like a=b&a=c&d=e and returns the parsed
1688 // parameters like this
1689 // array('a' => array('b','c'), 'd' => 'e')
1690 public static function parse_parameters( $input ) {
1691 if (!isset($input) || !$input) return array();
1692
1693 $pairs = explode('&', $input);
1694
1695 $parsed_parameters = array();
1696 foreach ($pairs as $pair) {
1697 $split = explode('=', $pair, 2);
1698 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
1699 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
1700
1701 if (isset($parsed_parameters[$parameter])) {
1702 // We have already recieved parameter(s) with this name, so add to the list
1703 // of parameters with this name
1704
1705 if (is_scalar($parsed_parameters[$parameter])) {
1706 // This is the first duplicate, so transform scalar (string) into an array
1707 // so we can add the duplicates
1708 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
1709 }
1710
1711 $parsed_parameters[$parameter][] = $value;
1712 } else {
1713 $parsed_parameters[$parameter] = $value;
1714 }
1715 }
1716 return $parsed_parameters;
1717 }
1718
1719 public static function build_http_query($params) {
1720 if (!$params) return '';
1721
1722 // Urlencode both keys and values
1723 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
1724 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
1725 $params = array_combine($keys, $values);
1726
1727 // Parameters are sorted by name, using lexicographical byte value ordering.
1728 // Ref: Spec: 9.1.1 (1)
1729 uksort($params, 'strcmp');
1730
1731 $pairs = array();
1732 foreach ($params as $parameter => $value) {
1733 if (is_array($value)) {
1734 // If two or more parameters share the same name, they are sorted by their value
1735 // Ref: Spec: 9.1.1 (1)
1736 natsort($value);
1737 foreach ($value as $duplicate_value) {
1738 $pairs[] = $parameter . '=' . $duplicate_value;
1739 }
1740 } else {
1741 $pairs[] = $parameter . '=' . $value;
1742 }
1743 }
1744 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
1745 // Each name-value pair is separated by an '&' character (ASCII code 38)
1746 return implode('&', $pairs);
1747 }
1748}