· 7 years ago · Mar 15, 2018, 02:20 AM
1<?php
2// Primeira página (index.php):
3
4 include('data/settings/twitter.php');
5
6 // Twitter Search API
7
8 define('CONSUMER_KEY', '');
9 define('CONSUMER_SECRET', '');
10 define('ACCESS_TOKEN', '');
11 define('ACCESS_TOKEN_SECRET', '');
12
13 function search(array $query){
14 $toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
15 return $toa->get('search/tweets', $query);
16 }
17 $query = array(
18 "q" => "#UniHabbo",
19 "count" => 3,
20 "result_type" => "recent"
21 );
22 $results = search($query);
23
24////////////////////////////////////////////////////////// twitter.php
25
26/*
27 * Abraham Williams (abraham@abrah.am) http://abrah.am
28 *
29 * The first PHP Library to support OAuth for Twitter's REST API.
30 */
31
32/* Load OAuth lib. You can find it at http://oauth.net */
33require_once('OAuth.php');
34
35/**
36 * Twitter OAuth class
37 */
38class TwitterOAuth {
39 /* Contains the last HTTP status code returned. */
40 public $http_code;
41 /* Contains the last API call. */
42 public $url;
43 /* Set up the API root URL. */
44 public $host = "https://api.twitter.com/1.1/";
45 /* Set timeout default. */
46 public $timeout = 30;
47 /* Set connect timeout. */
48 public $connecttimeout = 30;
49 /* Verify SSL Cert. */
50 public $ssl_verifypeer = FALSE;
51 /* Respons format. */
52 public $format = 'json';
53 /* Decode returned json data. */
54 public $decode_json = TRUE;
55 /* Contains the last HTTP headers returned. */
56 public $http_info;
57 /* Set the useragnet. */
58 public $useragent = 'TwitterOAuth v0.2.0-beta2';
59 /* Immediately retry the API call if the response was not successful. */
60 //public $retry = TRUE;
61
62
63
64
65 /**
66 * Set API URLS
67 */
68 function accessTokenURL() { return 'https://api.twitter.com/oauth/access_token'; }
69 function authenticateURL() { return 'https://api.twitter.com/oauth/authenticate'; }
70 function authorizeURL() { return 'https://api.twitter.com/oauth/authorize'; }
71 function requestTokenURL() { return 'https://api.twitter.com/oauth/request_token'; }
72
73 /**
74 * Debug helpers
75 */
76 function lastStatusCode() { return $this->http_status; }
77 function lastAPICall() { return $this->last_api_call; }
78
79 /**
80 * construct TwitterOAuth object
81 */
82 function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
83 $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
84 $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret);
85 if (!empty($oauth_token) && !empty($oauth_token_secret)) {
86 $this->token = new OAuthConsumer($oauth_token, $oauth_token_secret);
87 } else {
88 $this->token = NULL;
89 }
90 }
91
92
93 /**
94 * Get a request_token from Twitter
95 *
96 * @returns a key/value array containing oauth_token and oauth_token_secret
97 */
98 function getRequestToken($oauth_callback) {
99 $parameters = array();
100 $parameters['oauth_callback'] = $oauth_callback;
101 $request = $this->oAuthRequest($this->requestTokenURL(), 'GET', $parameters);
102 echo $request;
103 $token = OAuthUtil::parse_parameters($request);
104 $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
105 return $token;
106 }
107
108 /**
109 * Get the authorize URL
110 *
111 * @returns a string
112 */
113 function getAuthorizeURL($token, $sign_in_with_twitter = TRUE) {
114 if (is_array($token)) {
115 $token = $token['oauth_token'];
116 }
117 if (empty($sign_in_with_twitter)) {
118 return $this->authorizeURL() . "?oauth_token={$token}";
119 } else {
120 return $this->authenticateURL() . "?oauth_token={$token}";
121 }
122 }
123
124 /**
125 * Exchange request token and secret for an access token and
126 * secret, to sign API calls.
127 *
128 * @returns array("oauth_token" => "the-access-token",
129 * "oauth_token_secret" => "the-access-secret",
130 * "user_id" => "9436992",
131 * "screen_name" => "abraham")
132 */
133 function getAccessToken($oauth_verifier) {
134 $parameters = array();
135 $parameters['oauth_verifier'] = $oauth_verifier;
136 $request = $this->oAuthRequest($this->accessTokenURL(), 'GET', $parameters);
137 $token = OAuthUtil::parse_parameters($request);
138 $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
139 return $token;
140 }
141
142 /**
143 * One time exchange of username and password for access token and secret.
144 *
145 * @returns array("oauth_token" => "the-access-token",
146 * "oauth_token_secret" => "the-access-secret",
147 * "user_id" => "9436992",
148 * "screen_name" => "abraham",
149 * "x_auth_expires" => "0")
150 */
151 function getXAuthToken($username, $password) {
152 $parameters = array();
153 $parameters['x_auth_username'] = $username;
154 $parameters['x_auth_password'] = $password;
155 $parameters['x_auth_mode'] = 'client_auth';
156 $request = $this->oAuthRequest($this->accessTokenURL(), 'POST', $parameters);
157 $token = OAuthUtil::parse_parameters($request);
158 $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
159 return $token;
160 }
161
162 /**
163 * GET wrapper for oAuthRequest.
164 */
165 function get($url, $parameters = array()) {
166 $response = $this->oAuthRequest($url, 'GET', $parameters);
167 if ($this->format === 'json' && $this->decode_json) {
168 return json_decode($response);
169 }
170 return $response;
171 }
172
173 /**
174 * POST wrapper for oAuthRequest.
175 */
176 function post($url, $parameters = array()) {
177 $response = $this->oAuthRequest($url, 'POST', $parameters);
178 if ($this->format === 'json' && $this->decode_json) {
179 return json_decode($response);
180 }
181 return $response;
182 }
183
184 /**
185 * DELETE wrapper for oAuthReqeust.
186 */
187 function delete($url, $parameters = array()) {
188 $response = $this->oAuthRequest($url, 'DELETE', $parameters);
189 if ($this->format === 'json' && $this->decode_json) {
190 return json_decode($response);
191 }
192 return $response;
193 }
194
195 /**
196 * Format and sign an OAuth / API request
197 */
198 function oAuthRequest($url, $method, $parameters) {
199 if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) {
200 $url = "{$this->host}{$url}.{$this->format}";
201 }
202 $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters);
203 $request->sign_request($this->sha1_method, $this->consumer, $this->token);
204 switch ($method) {
205 case 'GET':
206 return $this->http($request->to_url(), 'GET');
207 default:
208 return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata());
209 }
210 }
211
212 /**
213 * Make an HTTP request
214 *
215 * @return API results
216 */
217 function http($url, $method, $postfields = NULL) {
218 $this->http_info = array();
219 $ci = curl_init();
220 /* Curl settings */
221 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
222 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
223 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
224 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
225 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
226 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
227 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
228 curl_setopt($ci, CURLOPT_HEADER, FALSE);
229
230 switch ($method) {
231 case 'POST':
232 curl_setopt($ci, CURLOPT_POST, TRUE);
233 if (!empty($postfields)) {
234 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
235 }
236 break;
237 case 'DELETE':
238 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
239 if (!empty($postfields)) {
240 $url = "{$url}?{$postfields}";
241 }
242 }
243
244 curl_setopt($ci, CURLOPT_URL, $url);
245 $response = curl_exec($ci);
246 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
247 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
248 $this->url = $url;
249 curl_close ($ci);
250 return $response;
251 }
252
253 /**
254 * Get the header info to store.
255 */
256 function getHeader($ch, $header) {
257 $i = strpos($header, ':');
258 if (!empty($i)) {
259 $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
260 $value = trim(substr($header, $i + 2));
261 $this->http_header[$key] = $value;
262 }
263 return strlen($header);
264 }
265}
266
267/////////////////////////////////////////////////////////////////// OAuth.php
268
269<?php
270// vim: foldmethod=marker
271
272/* Generic exception class
273 */
274if (!class_exists('OAuthException')) {
275 class OAuthException extends Exception {
276 // pass
277 }
278}
279
280class OAuthConsumer {
281 public $key;
282 public $secret;
283
284 function __construct($key, $secret, $callback_url=NULL) {
285 $this->key = $key;
286 $this->secret = $secret;
287 $this->callback_url = $callback_url;
288 }
289
290 function __toString() {
291 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
292 }
293}
294
295class OAuthToken {
296 // access tokens and request tokens
297 public $key;
298 public $secret;
299
300 /**
301 * key = the token
302 * secret = the token secret
303 */
304 function __construct($key, $secret) {
305 $this->key = $key;
306 $this->secret = $secret;
307 }
308
309 /**
310 * generates the basic string serialization of a token that a server
311 * would respond to request_token and access_token calls with
312 */
313 function to_string() {
314 return "oauth_token=" .
315 OAuthUtil::urlencode_rfc3986($this->key) .
316 "&oauth_token_secret=" .
317 OAuthUtil::urlencode_rfc3986($this->secret);
318 }
319
320 function __toString() {
321 return $this->to_string();
322 }
323}
324
325/**
326 * A class for implementing a Signature Method
327 * See section 9 ("Signing Requests") in the spec
328 */
329abstract class OAuthSignatureMethod {
330 /**
331 * Needs to return the name of the Signature Method (ie HMAC-SHA1)
332 * @return string
333 */
334 abstract public function get_name();
335
336 /**
337 * Build up the signature
338 * NOTE: The output of this function MUST NOT be urlencoded.
339 * the encoding is handled in OAuthRequest when the final
340 * request is serialized
341 * @param OAuthRequest $request
342 * @param OAuthConsumer $consumer
343 * @param OAuthToken $token
344 * @return string
345 */
346 abstract public function build_signature($request, $consumer, $token);
347
348 /**
349 * Verifies that a given signature is correct
350 * @param OAuthRequest $request
351 * @param OAuthConsumer $consumer
352 * @param OAuthToken $token
353 * @param string $signature
354 * @return bool
355 */
356 public function check_signature($request, $consumer, $token, $signature) {
357 $built = $this->build_signature($request, $consumer, $token);
358 return $built == $signature;
359 }
360}
361
362/**
363 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
364 * where the Signature Base String is the text and the key is the concatenated values (each first
365 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
366 * character (ASCII code 38) even if empty.
367 * - Chapter 9.2 ("HMAC-SHA1")
368 */
369class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
370 function get_name() {
371 return "HMAC-SHA1";
372 }
373
374 public function build_signature($request, $consumer, $token) {
375 $base_string = $request->get_signature_base_string();
376 $request->base_string = $base_string;
377
378 $key_parts = array(
379 $consumer->secret,
380 ($token) ? $token->secret : ""
381 );
382
383 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
384 $key = implode('&', $key_parts);
385
386 return base64_encode(hash_hmac('sha1', $base_string, $key, true));
387 }
388}
389
390/**
391 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
392 * over a secure channel such as HTTPS. It does not use the Signature Base String.
393 * - Chapter 9.4 ("PLAINTEXT")
394 */
395class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
396 public function get_name() {
397 return "PLAINTEXT";
398 }
399
400 /**
401 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
402 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
403 * empty. The result MUST be encoded again.
404 * - Chapter 9.4.1 ("Generating Signatures")
405 *
406 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
407 * OAuthRequest handles this!
408 */
409 public function build_signature($request, $consumer, $token) {
410 $key_parts = array(
411 $consumer->secret,
412 ($token) ? $token->secret : ""
413 );
414
415 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
416 $key = implode('&', $key_parts);
417 $request->base_string = $key;
418
419 return $key;
420 }
421}
422
423/**
424 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
425 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
426 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
427 * verified way to the Service Provider, in a manner which is beyond the scope of this
428 * specification.
429 * - Chapter 9.3 ("RSA-SHA1")
430 */
431abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
432 public function get_name() {
433 return "RSA-SHA1";
434 }
435
436 // Up to the SP to implement this lookup of keys. Possible ideas are:
437 // (1) do a lookup in a table of trusted certs keyed off of consumer
438 // (2) fetch via http using a url provided by the requester
439 // (3) some sort of specific discovery code based on request
440 //
441 // Either way should return a string representation of the certificate
442 protected abstract function fetch_public_cert(&$request);
443
444 // Up to the SP to implement this lookup of keys. Possible ideas are:
445 // (1) do a lookup in a table of trusted certs keyed off of consumer
446 //
447 // Either way should return a string representation of the certificate
448 protected abstract function fetch_private_cert(&$request);
449
450 public function build_signature($request, $consumer, $token) {
451 $base_string = $request->get_signature_base_string();
452 $request->base_string = $base_string;
453
454 // Fetch the private key cert based on the request
455 $cert = $this->fetch_private_cert($request);
456
457 // Pull the private key ID from the certificate
458 $privatekeyid = openssl_get_privatekey($cert);
459
460 // Sign using the key
461 $ok = openssl_sign($base_string, $signature, $privatekeyid);
462
463 // Release the key resource
464 openssl_free_key($privatekeyid);
465
466 return base64_encode($signature);
467 }
468
469 public function check_signature($request, $consumer, $token, $signature) {
470 $decoded_sig = base64_decode($signature);
471
472 $base_string = $request->get_signature_base_string();
473
474 // Fetch the public key cert based on the request
475 $cert = $this->fetch_public_cert($request);
476
477 // Pull the public key ID from the certificate
478 $publickeyid = openssl_get_publickey($cert);
479
480 // Check the computed signature against the one passed in the query
481 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
482
483 // Release the key resource
484 openssl_free_key($publickeyid);
485
486 return $ok == 1;
487 }
488}
489
490class OAuthRequest {
491 private $parameters;
492 private $http_method;
493 private $http_url;
494 // for debug purposes
495 public $base_string;
496 public static $version = '1.0';
497 public static $POST_INPUT = 'php://input';
498
499 function __construct($http_method, $http_url, $parameters=NULL) {
500 @$parameters or $parameters = array();
501 $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
502 $this->parameters = $parameters;
503 $this->http_method = $http_method;
504 $this->http_url = $http_url;
505 }
506
507
508 /**
509 * attempt to build up a request from what was passed to the server
510 */
511 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
512 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
513 ? 'http'
514 : 'https';
515 @$http_url or $http_url = $scheme .
516 '://' . $_SERVER['HTTP_HOST'] .
517 ':' .
518 $_SERVER['SERVER_PORT'] .
519 $_SERVER['REQUEST_URI'];
520 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
521
522 // We weren't handed any parameters, so let's find the ones relevant to
523 // this request.
524 // If you run XML-RPC or similar you should use this to provide your own
525 // parsed parameter-list
526 if (!$parameters) {
527 // Find request headers
528 $request_headers = OAuthUtil::get_headers();
529
530 // Parse the query-string to find GET parameters
531 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
532
533 // It's a POST request of the proper content-type, so parse POST
534 // parameters and add those overriding any duplicates from GET
535 if ($http_method == "POST"
536 && @strstr($request_headers["Content-Type"],
537 "application/x-www-form-urlencoded")
538 ) {
539 $post_data = OAuthUtil::parse_parameters(
540 file_get_contents(self::$POST_INPUT)
541 );
542 $parameters = array_merge($parameters, $post_data);
543 }
544
545 // We have a Authorization-header with OAuth data. Parse the header
546 // and add those overriding any duplicates from GET or POST
547 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
548 $header_parameters = OAuthUtil::split_header(
549 $request_headers['Authorization']
550 );
551 $parameters = array_merge($parameters, $header_parameters);
552 }
553
554 }
555
556 return new OAuthRequest($http_method, $http_url, $parameters);
557 }
558
559 /**
560 * pretty much a helper function to set up the request
561 */
562 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
563 @$parameters or $parameters = array();
564 $defaults = array("oauth_version" => OAuthRequest::$version,
565 "oauth_nonce" => OAuthRequest::generate_nonce(),
566 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
567 "oauth_consumer_key" => $consumer->key);
568 if ($token)
569 $defaults['oauth_token'] = $token->key;
570
571 $parameters = array_merge($defaults, $parameters);
572
573 return new OAuthRequest($http_method, $http_url, $parameters);
574 }
575
576 public function set_parameter($name, $value, $allow_duplicates = true) {
577 if ($allow_duplicates && isset($this->parameters[$name])) {
578 // We have already added parameter(s) with this name, so add to the list
579 if (is_scalar($this->parameters[$name])) {
580 // This is the first duplicate, so transform scalar (string)
581 // into an array so we can add the duplicates
582 $this->parameters[$name] = array($this->parameters[$name]);
583 }
584
585 $this->parameters[$name][] = $value;
586 } else {
587 $this->parameters[$name] = $value;
588 }
589 }
590
591 public function get_parameter($name) {
592 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
593 }
594
595 public function get_parameters() {
596 return $this->parameters;
597 }
598
599 public function unset_parameter($name) {
600 unset($this->parameters[$name]);
601 }
602
603 /**
604 * The request parameters, sorted and concatenated into a normalized string.
605 * @return string
606 */
607 public function get_signable_parameters() {
608 // Grab all parameters
609 $params = $this->parameters;
610
611 // Remove oauth_signature if present
612 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
613 if (isset($params['oauth_signature'])) {
614 unset($params['oauth_signature']);
615 }
616
617 return OAuthUtil::build_http_query($params);
618 }
619
620 /**
621 * Returns the base string of this request
622 *
623 * The base string defined as the method, the url
624 * and the parameters (normalized), each urlencoded
625 * and the concated with &.
626 */
627 public function get_signature_base_string() {
628 $parts = array(
629 $this->get_normalized_http_method(),
630 $this->get_normalized_http_url(),
631 $this->get_signable_parameters()
632 );
633
634 $parts = OAuthUtil::urlencode_rfc3986($parts);
635
636 return implode('&', $parts);
637 }
638
639 /**
640 * just uppercases the http method
641 */
642 public function get_normalized_http_method() {
643 return strtoupper($this->http_method);
644 }
645
646 /**
647 * parses the url and rebuilds it to be
648 * scheme://host/path
649 */
650 public function get_normalized_http_url() {
651 $parts = parse_url($this->http_url);
652
653 $port = @$parts['port'];
654 $scheme = $parts['scheme'];
655 $host = $parts['host'];
656 $path = @$parts['path'];
657
658 $port or $port = ($scheme == 'https') ? '443' : '80';
659
660 if (($scheme == 'https' && $port != '443')
661 || ($scheme == 'http' && $port != '80')) {
662 $host = "$host:$port";
663 }
664 return "$scheme://$host$path";
665 }
666
667 /**
668 * builds a url usable for a GET request
669 */
670 public function to_url() {
671 $post_data = $this->to_postdata();
672 $out = $this->get_normalized_http_url();
673 if ($post_data) {
674 $out .= '?'.$post_data;
675 }
676 return $out;
677 }
678
679 /**
680 * builds the data one would send in a POST request
681 */
682 public function to_postdata() {
683 return OAuthUtil::build_http_query($this->parameters);
684 }
685
686 /**
687 * builds the Authorization: header
688 */
689 public function to_header($realm=null) {
690 $first = true;
691 if($realm) {
692 $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
693 $first = false;
694 } else
695 $out = 'Authorization: OAuth';
696
697 $total = array();
698 foreach ($this->parameters as $k => $v) {
699 if (substr($k, 0, 5) != "oauth") continue;
700 if (is_array($v)) {
701 throw new OAuthException('Arrays not supported in headers');
702 }
703 $out .= ($first) ? ' ' : ',';
704 $out .= OAuthUtil::urlencode_rfc3986($k) .
705 '="' .
706 OAuthUtil::urlencode_rfc3986($v) .
707 '"';
708 $first = false;
709 }
710 return $out;
711 }
712
713 public function __toString() {
714 return $this->to_url();
715 }
716
717
718 public function sign_request($signature_method, $consumer, $token) {
719 $this->set_parameter(
720 "oauth_signature_method",
721 $signature_method->get_name(),
722 false
723 );
724 $signature = $this->build_signature($signature_method, $consumer, $token);
725 $this->set_parameter("oauth_signature", $signature, false);
726 }
727
728 public function build_signature($signature_method, $consumer, $token) {
729 $signature = $signature_method->build_signature($this, $consumer, $token);
730 return $signature;
731 }
732
733 /**
734 * util function: current timestamp
735 */
736 private static function generate_timestamp() {
737 return time();
738 }
739
740 /**
741 * util function: current nonce
742 */
743 private static function generate_nonce() {
744 $mt = microtime();
745 $rand = mt_rand();
746
747 return md5($mt . $rand); // md5s look nicer than numbers
748 }
749}
750
751class OAuthServer {
752 protected $timestamp_threshold = 300; // in seconds, five minutes
753 protected $version = '1.0'; // hi blaine
754 protected $signature_methods = array();
755
756 protected $data_store;
757
758 function __construct($data_store) {
759 $this->data_store = $data_store;
760 }
761
762 public function add_signature_method($signature_method) {
763 $this->signature_methods[$signature_method->get_name()] =
764 $signature_method;
765 }
766
767 // high level functions
768
769 /**
770 * process a request_token request
771 * returns the request token on success
772 */
773 public function fetch_request_token(&$request) {
774 $this->get_version($request);
775
776 $consumer = $this->get_consumer($request);
777
778 // no token required for the initial token request
779 $token = NULL;
780
781 $this->check_signature($request, $consumer, $token);
782
783 // Rev A change
784 $callback = $request->get_parameter('oauth_callback');
785 $new_token = $this->data_store->new_request_token($consumer, $callback);
786
787 return $new_token;
788 }
789
790 /**
791 * process an access_token request
792 * returns the access token on success
793 */
794 public function fetch_access_token(&$request) {
795 $this->get_version($request);
796
797 $consumer = $this->get_consumer($request);
798
799 // requires authorized request token
800 $token = $this->get_token($request, $consumer, "request");
801
802 $this->check_signature($request, $consumer, $token);
803
804 // Rev A change
805 $verifier = $request->get_parameter('oauth_verifier');
806 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
807
808 return $new_token;
809 }
810
811 /**
812 * verify an api call, checks all the parameters
813 */
814 public function verify_request(&$request) {
815 $this->get_version($request);
816 $consumer = $this->get_consumer($request);
817 $token = $this->get_token($request, $consumer, "access");
818 $this->check_signature($request, $consumer, $token);
819 return array($consumer, $token);
820 }
821
822 // Internals from here
823 /**
824 * version 1
825 */
826 private function get_version(&$request) {
827 $version = $request->get_parameter("oauth_version");
828 if (!$version) {
829 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
830 // Chapter 7.0 ("Accessing Protected Ressources")
831 $version = '1.0';
832 }
833 if ($version !== $this->version) {
834 throw new OAuthException("OAuth version '$version' not supported");
835 }
836 return $version;
837 }
838
839 /**
840 * figure out the signature with some defaults
841 */
842 private function get_signature_method(&$request) {
843 $signature_method =
844 @$request->get_parameter("oauth_signature_method");
845
846 if (!$signature_method) {
847 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
848 // parameter is required, and we can't just fallback to PLAINTEXT
849 throw new OAuthException('No signature method parameter. This parameter is required');
850 }
851
852 if (!in_array($signature_method,
853 array_keys($this->signature_methods))) {
854 throw new OAuthException(
855 "Signature method '$signature_method' not supported " .
856 "try one of the following: " .
857 implode(", ", array_keys($this->signature_methods))
858 );
859 }
860 return $this->signature_methods[$signature_method];
861 }
862
863 /**
864 * try to find the consumer for the provided request's consumer key
865 */
866 private function get_consumer(&$request) {
867 $consumer_key = @$request->get_parameter("oauth_consumer_key");
868 if (!$consumer_key) {
869 throw new OAuthException("Invalid consumer key");
870 }
871
872 $consumer = $this->data_store->lookup_consumer($consumer_key);
873 if (!$consumer) {
874 throw new OAuthException("Invalid consumer");
875 }
876
877 return $consumer;
878 }
879
880 /**
881 * try to find the token for the provided request's token key
882 */
883 private function get_token(&$request, $consumer, $token_type="access") {
884 $token_field = @$request->get_parameter('oauth_token');
885 $token = $this->data_store->lookup_token(
886 $consumer, $token_type, $token_field
887 );
888 if (!$token) {
889 throw new OAuthException("Invalid $token_type token: $token_field");
890 }
891 return $token;
892 }
893
894 /**
895 * all-in-one function to check the signature on a request
896 * should guess the signature method appropriately
897 */
898 private function check_signature(&$request, $consumer, $token) {
899 // this should probably be in a different method
900 $timestamp = @$request->get_parameter('oauth_timestamp');
901 $nonce = @$request->get_parameter('oauth_nonce');
902
903 $this->check_timestamp($timestamp);
904 $this->check_nonce($consumer, $token, $nonce, $timestamp);
905
906 $signature_method = $this->get_signature_method($request);
907
908 $signature = $request->get_parameter('oauth_signature');
909 $valid_sig = $signature_method->check_signature(
910 $request,
911 $consumer,
912 $token,
913 $signature
914 );
915
916 if (!$valid_sig) {
917 throw new OAuthException("Invalid signature");
918 }
919 }
920
921 /**
922 * check that the timestamp is new enough
923 */
924 private function check_timestamp($timestamp) {
925 if( ! $timestamp )
926 throw new OAuthException(
927 'Missing timestamp parameter. The parameter is required'
928 );
929
930 // verify that timestamp is recentish
931 $now = time();
932 if (abs($now - $timestamp) > $this->timestamp_threshold) {
933 throw new OAuthException(
934 "Expired timestamp, yours $timestamp, ours $now"
935 );
936 }
937 }
938
939 /**
940 * check that the nonce is not repeated
941 */
942 private function check_nonce($consumer, $token, $nonce, $timestamp) {
943 if( ! $nonce )
944 throw new OAuthException(
945 'Missing nonce parameter. The parameter is required'
946 );
947
948 // verify that the nonce is uniqueish
949 $found = $this->data_store->lookup_nonce(
950 $consumer,
951 $token,
952 $nonce,
953 $timestamp
954 );
955 if ($found) {
956 throw new OAuthException("Nonce already used: $nonce");
957 }
958 }
959
960}
961
962class OAuthDataStore {
963 function lookup_consumer($consumer_key) {
964 // implement me
965 }
966
967 function lookup_token($consumer, $token_type, $token) {
968 // implement me
969 }
970
971 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
972 // implement me
973 }
974
975 function new_request_token($consumer, $callback = null) {
976 // return a new token attached to this consumer
977 }
978
979 function new_access_token($token, $consumer, $verifier = null) {
980 // return a new access token attached to this consumer
981 // for the user associated with this token if the request token
982 // is authorized
983 // should also invalidate the request token
984 }
985
986}
987
988class OAuthUtil {
989 public static function urlencode_rfc3986($input) {
990 if (is_array($input)) {
991 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
992 } else if (is_scalar($input)) {
993 return str_replace(
994 '+',
995 ' ',
996 str_replace('%7E', '~', rawurlencode($input))
997 );
998 } else {
999 return '';
1000 }
1001}
1002
1003
1004 // This decode function isn't taking into consideration the above
1005 // modifications to the encoding process. However, this method doesn't
1006 // seem to be used anywhere so leaving it as is.
1007 public static function urldecode_rfc3986($string) {
1008 return urldecode($string);
1009 }
1010
1011 // Utility function for turning the Authorization: header into
1012 // parameters, has to do some unescaping
1013 // Can filter out any non-oauth parameters if needed (default behaviour)
1014 public static function split_header($header, $only_allow_oauth_parameters = true) {
1015 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
1016 $offset = 0;
1017 $params = array();
1018 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
1019 $match = $matches[0];
1020 $header_name = $matches[2][0];
1021 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
1022 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
1023 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
1024 }
1025 $offset = $match[1] + strlen($match[0]);
1026 }
1027
1028 if (isset($params['realm'])) {
1029 unset($params['realm']);
1030 }
1031
1032 return $params;
1033 }
1034
1035 // helper to try to sort out headers for people who aren't running apache
1036 public static function get_headers() {
1037 if (function_exists('apache_request_headers')) {
1038 // we need this to get the actual Authorization: header
1039 // because apache tends to tell us it doesn't exist
1040 $headers = apache_request_headers();
1041
1042 // sanitize the output of apache_request_headers because
1043 // we always want the keys to be Cased-Like-This and arh()
1044 // returns the headers in the same case as they are in the
1045 // request
1046 $out = array();
1047 foreach( $headers AS $key => $value ) {
1048 $key = str_replace(
1049 " ",
1050 "-",
1051 ucwords(strtolower(str_replace("-", " ", $key)))
1052 );
1053 $out[$key] = $value;
1054 }
1055 } else {
1056 // otherwise we don't have apache and are just going to have to hope
1057 // that $_SERVER actually contains what we need
1058 $out = array();
1059 if( isset($_SERVER['CONTENT_TYPE']) )
1060 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
1061 if( isset($_ENV['CONTENT_TYPE']) )
1062 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
1063
1064 foreach ($_SERVER as $key => $value) {
1065 if (substr($key, 0, 5) == "HTTP_") {
1066 // this is chaos, basically it is just there to capitalize the first
1067 // letter of every word that is not an initial HTTP and strip HTTP
1068 // code from przemek
1069 $key = str_replace(
1070 " ",
1071 "-",
1072 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
1073 );
1074 $out[$key] = $value;
1075 }
1076 }
1077 }
1078 return $out;
1079 }
1080
1081 // This function takes a input like a=b&a=c&d=e and returns the parsed
1082 // parameters like this
1083 // array('a' => array('b','c'), 'd' => 'e')
1084 public static function parse_parameters( $input ) {
1085 if (!isset($input) || !$input) return array();
1086
1087 $pairs = explode('&', $input);
1088
1089 $parsed_parameters = array();
1090 foreach ($pairs as $pair) {
1091 $split = explode('=', $pair, 2);
1092 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
1093 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
1094
1095 if (isset($parsed_parameters[$parameter])) {
1096 // We have already recieved parameter(s) with this name, so add to the list
1097 // of parameters with this name
1098
1099 if (is_scalar($parsed_parameters[$parameter])) {
1100 // This is the first duplicate, so transform scalar (string) into an array
1101 // so we can add the duplicates
1102 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
1103 }
1104
1105 $parsed_parameters[$parameter][] = $value;
1106 } else {
1107 $parsed_parameters[$parameter] = $value;
1108 }
1109 }
1110 return $parsed_parameters;
1111 }
1112
1113 public static function build_http_query($params) {
1114 if (!$params) return '';
1115
1116 // Urlencode both keys and values
1117 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
1118 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
1119 $params = array_combine($keys, $values);
1120
1121 // Parameters are sorted by name, using lexicographical byte value ordering.
1122 // Ref: Spec: 9.1.1 (1)
1123 uksort($params, 'strcmp');
1124
1125 $pairs = array();
1126 foreach ($params as $parameter => $value) {
1127 if (is_array($value)) {
1128 // If two or more parameters share the same name, they are sorted by their value
1129 // Ref: Spec: 9.1.1 (1)
1130 natsort($value);
1131 foreach ($value as $duplicate_value) {
1132 $pairs[] = $parameter . '=' . $duplicate_value;
1133 }
1134 } else {
1135 $pairs[] = $parameter . '=' . $value;
1136 }
1137 }
1138 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
1139 // Each name-value pair is separated by an '&' character (ASCII code 38)
1140 return implode('&', $pairs);
1141 }
1142}
1143
1144?>