PageRenderTime 68ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/chapter_9/oauth1-php-3legged/OAuth.php

https://github.com/AramZS/programming-social-applications
PHP | 819 lines | 489 code | 130 blank | 200 comment | 58 complexity | 255da61230daf678522bba9341749cff MD5 | raw file
  1. <?php
  2. /**
  3. * The MIT License
  4. *
  5. * Copyright (c) 2008 OAuth.net
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. * THE SOFTWARE.
  24. *
  25. */
  26. /**
  27. * Branched from version 587 of OAuth.php from the OAuth.net project. Major
  28. * changes are limited to adding PHP 4 compatibility.
  29. *
  30. * Ryan Kennedy (rckenned@yahoo-inc.com)
  31. */
  32. class OAuthConsumer {/*{{{*/
  33. var $key;
  34. var $secret;
  35. function OAuthConsumer($key, $secret, $callback_url=NULL) {/*{{{*/
  36. $this->key = $key;
  37. $this->secret = $secret;
  38. $this->callback_url = $callback_url;
  39. }/*}}}*/
  40. }/*}}}*/
  41. class OAuthToken {/*{{{*/
  42. // access tokens and request tokens
  43. var $key;
  44. var $secret;
  45. /**
  46. * key = the token
  47. * secret = the token secret
  48. */
  49. function OAuthToken($key, $secret) {/*{{{*/
  50. $this->key = $key;
  51. $this->secret = $secret;
  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=" . OAuthUtil::urlencodeRFC3986($this->key) .
  59. "&oauth_token_secret=" . OAuthUtil::urlencodeRFC3986($this->secret);
  60. }/*}}}*/
  61. function __toString() {/*{{{*/
  62. return $this->to_string();
  63. }/*}}}*/
  64. }/*}}}*/
  65. class OAuthSignatureMethod {/*{{{*/
  66. function check_signature(&$request, $consumer, $token, $signature) {
  67. $built = $this->build_signature($request, $consumer, $token);
  68. return $built == $signature;
  69. }
  70. }/*}}}*/
  71. class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {/*{{{*/
  72. function get_name() {/*{{{*/
  73. return "HMAC-SHA1";
  74. }/*}}}*/
  75. function build_signature($request, $consumer, $token) {/*{{{*/
  76. $base_string = $request->get_signature_base_string();
  77. $request->base_string = $base_string;
  78. $key_parts = array(
  79. $consumer->secret,
  80. ($token) ? $token->secret : ""
  81. );
  82. $key_parts = array_map(array('OAuthUtil','urlencodeRFC3986'), $key_parts);
  83. $key = implode('&', $key_parts);
  84. return base64_encode(hash_hmac('sha1', $base_string, $key, true));
  85. }/*}}}*/
  86. }/*}}}*/
  87. class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {/*{{{*/
  88. function get_name() {/*{{{*/
  89. return "PLAINTEXT";
  90. }/*}}}*/
  91. function build_signature($request, $consumer, $token) {/*{{{*/
  92. $sig = array(
  93. OAuthUtil::urlencodeRFC3986($consumer->secret)
  94. );
  95. if ($token) {
  96. array_push($sig, OAuthUtil::urlencodeRFC3986($token->secret));
  97. } else {
  98. array_push($sig, '');
  99. }
  100. $raw = implode("&", $sig);
  101. // for debug purposes
  102. $request->base_string = $raw;
  103. return $raw;
  104. }/*}}}*/
  105. }/*}}}*/
  106. class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {/*{{{*/
  107. function get_name() {/*{{{*/
  108. return "RSA-SHA1";
  109. }/*}}}*/
  110. function fetch_public_cert(&$request) {/*{{{*/
  111. // not implemented yet, ideas are:
  112. // (1) do a lookup in a table of trusted certs keyed off of consumer
  113. // (2) fetch via http using a url provided by the requester
  114. // (3) some sort of specific discovery code based on request
  115. //
  116. // either way should return a string representation of the certificate
  117. trigger_error("fetch_public_cert not implemented", E_USER_ERROR);
  118. return NULL;
  119. }/*}}}*/
  120. function fetch_private_cert(&$request) {/*{{{*/
  121. // not implemented yet, ideas are:
  122. // (1) do a lookup in a table of trusted certs keyed off of consumer
  123. //
  124. // either way should return a string representation of the certificate
  125. trigger_error("fetch_private_cert not implemented", E_USER_ERROR);
  126. return NULL;
  127. }/*}}}*/
  128. function build_signature(&$request, $consumer, $token) {/*{{{*/
  129. $base_string = $request->get_signature_base_string();
  130. // Fetch the private key cert based on the request
  131. $cert = $this->fetch_private_cert($request);
  132. // Pull the private key ID from the certificate
  133. $privatekeyid = openssl_get_privatekey($cert);
  134. // Sign using the key
  135. $ok = openssl_sign($base_string, $signature, $privatekeyid);
  136. // Release the key resource
  137. openssl_free_key($privatekeyid);
  138. return base64_encode($signature);
  139. } /*}}}*/
  140. function check_signature(&$request, $consumer, $token, $signature) {/*{{{*/
  141. $decoded_sig = base64_decode($signature);
  142. $base_string = $request->get_signature_base_string();
  143. // Fetch the public key cert based on the request
  144. $cert = $this->fetch_public_cert($request);
  145. // Pull the public key ID from the certificate
  146. $publickeyid = openssl_get_publickey($cert);
  147. // Check the computed signature against the one passed in the query
  148. $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
  149. // Release the key resource
  150. openssl_free_key($publickeyid);
  151. return $ok == 1;
  152. } /*}}}*/
  153. }/*}}}*/
  154. class OAuthRequest {/*{{{*/
  155. var $parameters;
  156. var $http_method;
  157. var $http_url;
  158. // for debug purposes
  159. var $base_string;
  160. function OAuthRequest($http_method, $http_url, $parameters=array()) {/*{{{*/
  161. $this->parameters = $parameters;
  162. $this->http_method = $http_method;
  163. $this->http_url = $http_url;
  164. }/*}}}*/
  165. /**
  166. * attempt to build up a request from what was passed to the server
  167. */
  168. function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {/*{{{*/
  169. $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
  170. @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  171. @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
  172. $request_headers = OAuthRequest::get_headers();
  173. // let the library user override things however they'd like, if they know
  174. // which parameters to use then go for it, for example XMLRPC might want to
  175. // do this
  176. if ($parameters) {
  177. $req = new OAuthRequest($http_method, $http_url, $parameters);
  178. }
  179. // next check for the auth header, we need to do some extra stuff
  180. // if that is the case, namely suck in the parameters from GET or POST
  181. // so that we can include them in the signature
  182. else if (@substr($request_headers['Authorization'], 0, 5) == "OAuth") {
  183. $header_parameters = OAuthRequest::split_header($request_headers['Authorization']);
  184. if ($http_method == "GET") {
  185. $req_parameters = $_GET;
  186. }
  187. else if ($http_method = "POST") {
  188. $req_parameters = $_POST;
  189. }
  190. $parameters = array_merge($header_parameters, $req_parameters);
  191. $req = new OAuthRequest($http_method, $http_url, $parameters);
  192. }
  193. else if ($http_method == "GET") {
  194. $req = new OAuthRequest($http_method, $http_url, $_GET);
  195. }
  196. else if ($http_method == "POST") {
  197. $req = new OAuthRequest($http_method, $http_url, $_POST);
  198. }
  199. return $req;
  200. }/*}}}*/
  201. /**
  202. * pretty much a helper function to set up the request
  203. */
  204. function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=array()) {/*{{{*/
  205. static $version = '1.0';
  206. $defaults = array("oauth_version" => $version,
  207. "oauth_nonce" => OAuthRequest::generate_nonce(),
  208. "oauth_timestamp" => OAuthRequest::generate_timestamp(),
  209. "oauth_consumer_key" => $consumer->key);
  210. $parameters = array_merge($defaults, $parameters);
  211. if ($token) {
  212. $parameters['oauth_token'] = $token->key;
  213. }
  214. $req = new OAuthRequest($http_method, $http_url, $parameters);
  215. return $req;
  216. }/*}}}*/
  217. function set_parameter($name, $value) {/*{{{*/
  218. $this->parameters[$name] = $value;
  219. }/*}}}*/
  220. function get_parameter($name) {/*{{{*/
  221. return $this->parameters[$name];
  222. }/*}}}*/
  223. function get_parameters() {/*{{{*/
  224. return $this->parameters;
  225. }/*}}}*/
  226. /**
  227. * Returns the normalized parameters of the request
  228. *
  229. * This will be all (except oauth_signature) parameters,
  230. * sorted first by key, and if duplicate keys, then by
  231. * value.
  232. *
  233. * The returned string will be all the key=value pairs
  234. * concated by &.
  235. *
  236. * @return string
  237. */
  238. function get_signable_parameters() {/*{{{*/
  239. // Include query parameters
  240. $url = parse_url($this->http_url);
  241. if(array_key_exists("query", $url)) {
  242. parse_str($url["query"], $query);
  243. foreach($query as $key => $value) {
  244. $this->set_parameter($key, $value);
  245. }
  246. }
  247. // Grab all parameters
  248. $params = $this->parameters;
  249. // Remove oauth_signature if present
  250. if (isset($params['oauth_signature'])) {
  251. unset($params['oauth_signature']);
  252. }
  253. // Urlencode both keys and values
  254. $keys = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_keys($params));
  255. $values = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_values($params));
  256. $params = array();
  257. for($i = 0; $i < count($keys); $i++) {
  258. $params[$keys[$i]] = $values[$i];
  259. }
  260. // Sort by keys (natsort)
  261. uksort($params, 'strnatcmp');
  262. // Generate key=value pairs
  263. $pairs = array();
  264. foreach ($params as $key=>$value ) {
  265. if (is_array($value)) {
  266. // If the value is an array, it's because there are multiple
  267. // with the same key, sort them, then add all the pairs
  268. natsort($value);
  269. foreach ($value as $v2) {
  270. $pairs[] = $key . '=' . $v2;
  271. }
  272. } else {
  273. $pairs[] = $key . '=' . $value;
  274. }
  275. }
  276. // Return the pairs, concated with &
  277. return implode('&', $pairs);
  278. }/*}}}*/
  279. /**
  280. * Returns the base string of this request
  281. *
  282. * The base string defined as the method, the url
  283. * and the parameters (normalized), each urlencoded
  284. * and the concated with &.
  285. */
  286. function get_signature_base_string() {/*{{{*/
  287. $parts = array(
  288. $this->get_normalized_http_method(),
  289. $this->get_normalized_http_url(),
  290. $this->get_signable_parameters()
  291. );
  292. $parts = array_map(array('OAuthUtil', 'urlencodeRFC3986'), $parts);
  293. return implode('&', $parts);
  294. }/*}}}*/
  295. /**
  296. * just uppercases the http method
  297. */
  298. function get_normalized_http_method() {/*{{{*/
  299. return strtoupper($this->http_method);
  300. }/*}}}*/
  301. /**
  302. * parses the url and rebuilds it to be
  303. * scheme://host/path
  304. */
  305. function get_normalized_http_url() {/*{{{*/
  306. $parts = parse_url($this->http_url);
  307. // FIXME: port should handle according to http://groups.google.com/group/oauth/browse_thread/thread/1b203a51d9590226
  308. $port = (isset($parts['port']) && $parts['port'] != '80') ? ':' . $parts['port'] : '';
  309. $path = (isset($parts['path'])) ? $parts['path'] : '';
  310. return $parts['scheme'] . '://' . $parts['host'] . $port . $path;
  311. }/*}}}*/
  312. /**
  313. * builds a url usable for a GET request
  314. */
  315. function to_url() {/*{{{*/
  316. $out = $this->get_normalized_http_url() . "?";
  317. $out .= $this->to_postdata();
  318. return $out;
  319. }/*}}}*/
  320. /**
  321. * builds the data one would send in a POST request
  322. */
  323. function to_postdata() {/*{{{*/
  324. $total = array();
  325. foreach ($this->parameters as $k => $v) {
  326. $total[] = OAuthUtil::urlencodeRFC3986($k) . "=" . OAuthUtil::urlencodeRFC3986($v);
  327. }
  328. $out = implode("&", $total);
  329. return $out;
  330. }/*}}}*/
  331. /**
  332. * builds the Authorization: header
  333. */
  334. function to_header() {/*{{{*/
  335. $headerParams = array();
  336. foreach ($this->parameters as $k => $v) {
  337. if (substr($k, 0, 5) != "oauth") continue;
  338. $headerParams[] = OAuthUtil::urlencodeRFC3986($k) . '="' . OAuthUtil::urlencodeRFC3986($v) . '"';
  339. }
  340. return sprintf("Authorization: OAuth %s", implode(",", $headerParams));
  341. }/*}}}*/
  342. function __toString() {/*{{{*/
  343. return $this->to_url();
  344. }/*}}}*/
  345. function sign_request($signature_method, $consumer, $token) {/*{{{*/
  346. $this->set_parameter("oauth_signature_method", $signature_method->get_name());
  347. $signature = $this->build_signature($signature_method, $consumer, $token);
  348. $this->set_parameter("oauth_signature", $signature);
  349. }/*}}}*/
  350. function build_signature($signature_method, $consumer, $token) {/*{{{*/
  351. $signature = $signature_method->build_signature($this, $consumer, $token);
  352. return $signature;
  353. }/*}}}*/
  354. /**
  355. * util function: current timestamp
  356. */
  357. function generate_timestamp() {/*{{{*/
  358. return time();
  359. }/*}}}*/
  360. /**
  361. * util function: current nonce
  362. */
  363. function generate_nonce() {/*{{{*/
  364. $mt = microtime();
  365. $rand = mt_rand();
  366. return md5($mt . $rand); // md5s look nicer than numbers
  367. }/*}}}*/
  368. /**
  369. * util function for turning the Authorization: header into
  370. * parameters, has to do some unescaping
  371. */
  372. function split_header($header) {/*{{{*/
  373. // this should be a regex
  374. // error cases: commas in parameter values
  375. $parts = explode(",", $header);
  376. $out = array();
  377. foreach ($parts as $param) {
  378. $param = ltrim($param);
  379. // skip the "realm" param, nobody ever uses it anyway
  380. if (substr($param, 0, 5) != "oauth") continue;
  381. $param_parts = explode("=", $param);
  382. // rawurldecode() used because urldecode() will turn a "+" in the
  383. // value into a space
  384. $out[$param_parts[0]] = rawurldecode(substr($param_parts[1], 1, -1));
  385. }
  386. return $out;
  387. }/*}}}*/
  388. /**
  389. * helper to try to sort out headers for people who aren't running apache
  390. */
  391. function get_headers() {/*{{{*/
  392. if (function_exists('apache_request_headers')) {
  393. // we need this to get the actual Authorization: header
  394. // because apache tends to tell us it doesn't exist
  395. return apache_request_headers();
  396. }
  397. // otherwise we don't have apache and are just going to have to hope
  398. // that $_SERVER actually contains what we need
  399. $out = array();
  400. foreach ($_SERVER as $key => $value) {
  401. if (substr($key, 0, 5) == "HTTP_") {
  402. // this is chaos, basically it is just there to capitalize the first
  403. // letter of every word that is not an initial HTTP and strip HTTP
  404. // code from przemek
  405. $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
  406. $out[$key] = $value;
  407. }
  408. }
  409. return $out;
  410. }/*}}}*/
  411. }/*}}}*/
  412. class OAuthServer {/*{{{*/
  413. var $timestamp_threshold = 300; // in seconds, five minutes
  414. var $version = 1.0; // hi blaine
  415. var $signature_methods = array();
  416. var $data_store;
  417. function OAuthServer($data_store) {/*{{{*/
  418. $this->data_store = $data_store;
  419. }/*}}}*/
  420. function add_signature_method($signature_method) {/*{{{*/
  421. $this->signature_methods[$signature_method->get_name()] =
  422. $signature_method;
  423. }/*}}}*/
  424. // high level functions
  425. /**
  426. * process a request_token request
  427. * returns the request token on success
  428. */
  429. function fetch_request_token(&$request) {/*{{{*/
  430. $this->get_version($request);
  431. $consumer = $this->get_consumer($request);
  432. // no token required for the initial token request
  433. $token = NULL;
  434. $this->check_signature($request, $consumer, $token);
  435. $new_token = $this->data_store->new_request_token($consumer);
  436. return $new_token;
  437. }/*}}}*/
  438. /**
  439. * process an access_token request
  440. * returns the access token on success
  441. */
  442. function fetch_access_token(&$request) {/*{{{*/
  443. $this->get_version($request);
  444. $consumer = $this->get_consumer($request);
  445. // requires authorized request token
  446. $token = $this->get_token($request, $consumer, "request");
  447. $this->check_signature($request, $consumer, $token);
  448. $new_token = $this->data_store->new_access_token($token, $consumer);
  449. return $new_token;
  450. }/*}}}*/
  451. /**
  452. * verify an api call, checks all the parameters
  453. */
  454. function verify_request(&$request) {/*{{{*/
  455. $this->get_version($request);
  456. $consumer = $this->get_consumer($request);
  457. $token = $this->get_token($request, $consumer, "access");
  458. $this->check_signature($request, $consumer, $token);
  459. return array($consumer, $token);
  460. }/*}}}*/
  461. // Internals from here
  462. /**
  463. * version 1
  464. */
  465. function get_version(&$request) {/*{{{*/
  466. $version = $request->get_parameter("oauth_version");
  467. if (!$version) {
  468. $version = 1.0;
  469. }
  470. if ($version && $version != $this->version) {
  471. trigger_error("OAuth version '$version' not supported", E_USER_WARNING);
  472. return NULL;
  473. }
  474. return $version;
  475. }/*}}}*/
  476. /**
  477. * figure out the signature with some defaults
  478. */
  479. function get_signature_method(&$request) {/*{{{*/
  480. $signature_method =
  481. @$request->get_parameter("oauth_signature_method");
  482. if (!$signature_method) {
  483. $signature_method = "PLAINTEXT";
  484. }
  485. if (!in_array($signature_method,
  486. array_keys($this->signature_methods))) {
  487. trigger_error("Signature method '$signature_method' not supported try one of the following: " . implode(", ", array_keys($this->signature_methods)), E_USER_WARNING);
  488. return NULL;
  489. }
  490. return $this->signature_methods[$signature_method];
  491. }/*}}}*/
  492. /**
  493. * try to find the consumer for the provided request's consumer key
  494. */
  495. function get_consumer(&$request) {/*{{{*/
  496. $consumer_key = @$request->get_parameter("oauth_consumer_key");
  497. if (!$consumer_key) {
  498. trigger_error("Invalid consumer key", E_USER_WARNING);
  499. return NULL;
  500. }
  501. $consumer = $this->data_store->lookup_consumer($consumer_key);
  502. if (!$consumer) {
  503. trigger_error("Invalid consumer", E_USER_WARNING);
  504. return NULL;
  505. }
  506. return $consumer;
  507. }/*}}}*/
  508. /**
  509. * try to find the token for the provided request's token key
  510. */
  511. function get_token(&$request, $consumer, $token_type="access") {/*{{{*/
  512. $token_field = @$request->get_parameter('oauth_token');
  513. $token = $this->data_store->lookup_token(
  514. $consumer, $token_type, $token_field
  515. );
  516. if (!$token) {
  517. trigger_error("Invalid $token_type token: $token_field", E_USER_WARNING);
  518. return NULL;
  519. }
  520. return $token;
  521. }/*}}}*/
  522. /**
  523. * all-in-one function to check the signature on a request
  524. * should guess the signature method appropriately
  525. */
  526. function check_signature(&$request, $consumer, $token) {/*{{{*/
  527. // this should probably be in a different method
  528. $timestamp = @$request->get_parameter('oauth_timestamp');
  529. $nonce = @$request->get_parameter('oauth_nonce');
  530. $this->check_timestamp($timestamp);
  531. $this->check_nonce($consumer, $token, $nonce, $timestamp);
  532. $signature_method = $this->get_signature_method($request);
  533. $signature = $request->get_parameter('oauth_signature');
  534. $valid_sig = $signature_method->check_signature(
  535. $request,
  536. $consumer,
  537. $token,
  538. $signature
  539. );
  540. if (!$valid_sig) {
  541. trigger_error("Invalid signature", E_USER_WARNING);
  542. return NULL;
  543. }
  544. }/*}}}*/
  545. /**
  546. * check that the timestamp is new enough
  547. */
  548. function check_timestamp($timestamp) {/*{{{*/
  549. // verify that timestamp is recentish
  550. $now = time();
  551. if ($now - $timestamp > $this->timestamp_threshold) {
  552. trigger_error("Expired timestamp, yours $timestamp, ours $now", E_USER_WARNING);
  553. return NULL;
  554. }
  555. }/*}}}*/
  556. /**
  557. * check that the nonce is not repeated
  558. */
  559. function check_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
  560. // verify that the nonce is uniqueish
  561. $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
  562. if ($found) {
  563. trigger_error("Nonce already used: $nonce", E_USER_WARNING);
  564. return NULL;
  565. }
  566. }/*}}}*/
  567. }/*}}}*/
  568. class OAuthDataStore {/*{{{*/
  569. function lookup_consumer($consumer_key) {/*{{{*/
  570. // implement me
  571. }/*}}}*/
  572. function lookup_token($consumer, $token_type, $token) {/*{{{*/
  573. // implement me
  574. }/*}}}*/
  575. function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
  576. // implement me
  577. }/*}}}*/
  578. function fetch_request_token($consumer) {/*{{{*/
  579. // return a new token attached to this consumer
  580. }/*}}}*/
  581. function fetch_access_token($token, $consumer) {/*{{{*/
  582. // return a new access token attached to this consumer
  583. // for the user associated with this token if the request token
  584. // is authorized
  585. // should also invalidate the request token
  586. }/*}}}*/
  587. }/*}}}*/
  588. /* A very naive dbm-based oauth storage
  589. */
  590. class SimpleOAuthDataStore extends OAuthDataStore {/*{{{*/
  591. var $dbh;
  592. function SimpleOAuthDataStore($path = "oauth.gdbm") {/*{{{*/
  593. $this->dbh = dba_popen($path, 'c', 'gdbm');
  594. }/*}}}*/
  595. function __destruct() {/*{{{*/
  596. dba_close($this->dbh);
  597. }/*}}}*/
  598. function lookup_consumer($consumer_key) {/*{{{*/
  599. $rv = dba_fetch("consumer_$consumer_key", $this->dbh);
  600. if ($rv === FALSE) {
  601. return NULL;
  602. }
  603. $obj = unserialize($rv);
  604. if (!is_a($obj, "OAuthConsumer")) {
  605. return NULL;
  606. }
  607. return $obj;
  608. }/*}}}*/
  609. function lookup_token($consumer, $token_type, $token) {/*{{{*/
  610. $rv = dba_fetch("${token_type}_${token}", $this->dbh);
  611. if ($rv === FALSE) {
  612. return NULL;
  613. }
  614. $obj = unserialize($rv);
  615. if (!is_a($obj, "OAuthToken")) {
  616. return NULL;
  617. }
  618. return $obj;
  619. }/*}}}*/
  620. function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
  621. if (dba_exists("nonce_$nonce", $this->dbh)) {
  622. return TRUE;
  623. } else {
  624. dba_insert("nonce_$nonce", "1", $this->dbh);
  625. return FALSE;
  626. }
  627. }/*}}}*/
  628. function new_token($consumer, $type="request") {/*{{{*/
  629. $key = md5(time());
  630. $secret = time() + time();
  631. $token = new OAuthToken($key, md5(md5($secret)));
  632. if (!dba_insert("${type}_$key", serialize($token), $this->dbh)) {
  633. trigger_error("doooom!", E_USER_WARNING);
  634. return NULL;
  635. }
  636. return $token;
  637. }/*}}}*/
  638. function new_request_token($consumer) {/*{{{*/
  639. return $this->new_token($consumer, "request");
  640. }/*}}}*/
  641. function new_access_token($token, $consumer) {/*{{{*/
  642. $token = $this->new_token($consumer, 'access');
  643. dba_delete("request_" . $token->key, $this->dbh);
  644. return $token;
  645. }/*}}}*/
  646. }/*}}}*/
  647. class OAuthUtil {/*{{{*/
  648. function urlencodeRFC3986($string) {/*{{{*/
  649. return str_replace('%7E', '~', rawurlencode($string));
  650. }/*}}}*/
  651. function urldecodeRFC3986($string) {/*{{{*/
  652. return rawurldecode($string);
  653. }/*}}}*/
  654. }/*}}}*/
  655. /**
  656. * Crib'd native implementation of hash_hmac() for SHA1 from the
  657. * Fire Eagle PHP code:
  658. *
  659. * http://fireeagle.yahoo.net/developer/code/php
  660. */
  661. if (!function_exists("hash_hmac")) {
  662. // Earlier versions of PHP5 are missing hash_hmac(). Here's a
  663. // pure-PHP version in case you're using one of them.
  664. function hash_hmac($algo, $data, $key) {
  665. // Thanks, Kellan: http://laughingmeme.org/code/hmacsha1.php.txt
  666. if ($algo != 'sha1') {
  667. error_log("Internal hash_hmac() can only do sha1, sorry");
  668. return NULL;
  669. }
  670. $blocksize = 64;
  671. $hashfunc = 'sha1';
  672. if (strlen($key)>$blocksize)
  673. $key = pack('H*', $hashfunc($key));
  674. $key = str_pad($key,$blocksize,chr(0x00));
  675. $ipad = str_repeat(chr(0x36),$blocksize);
  676. $opad = str_repeat(chr(0x5c),$blocksize);
  677. $hmac = pack(
  678. 'H*',$hashfunc(
  679. ($key^$opad).pack(
  680. 'H*',$hashfunc(
  681. ($key^$ipad).$data
  682. )
  683. )
  684. )
  685. );
  686. return $hmac;
  687. }
  688. }
  689. ?>