OAuth.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. <?php
  2. // vim: foldmethod=marker
  3. /* Generic exception class
  4. */
  5. class OAuthException extends Exception {
  6. // pass
  7. }
  8. class OAuthConsumer {
  9. public $key;
  10. public $secret;
  11. function __construct($key, $secret, $callback_url=NULL) {
  12. $this->key = $key;
  13. $this->secret = $secret;
  14. $this->callback_url = $callback_url;
  15. }
  16. function __toString() {
  17. return "OAuthConsumer[key=$this->key,secret=$this->secret]";
  18. }
  19. }
  20. class OAuthToken {
  21. // access tokens and request tokens
  22. public $key;
  23. public $secret;
  24. /**
  25. * key = the token
  26. * secret = the token secret
  27. */
  28. function __construct($key, $secret) {
  29. $this->key = $key;
  30. $this->secret = $secret;
  31. }
  32. /**
  33. * generates the basic string serialization of a token that a server
  34. * would respond to request_token and access_token calls with
  35. */
  36. function to_string() {
  37. return "oauth_token=" .
  38. OAuthUtil::urlencode_rfc3986($this->key) .
  39. "&oauth_token_secret=" .
  40. OAuthUtil::urlencode_rfc3986($this->secret);
  41. }
  42. function __toString() {
  43. return $this->to_string();
  44. }
  45. }
  46. /**
  47. * A class for implementing a Signature Method
  48. * See section 9 ("Signing Requests") in the spec
  49. */
  50. abstract class OAuthSignatureMethod {
  51. /**
  52. * Needs to return the name of the Signature Method (ie HMAC-SHA1)
  53. * @return string
  54. */
  55. abstract public function get_name();
  56. /**
  57. * Build up the signature
  58. * NOTE: The output of this function MUST NOT be urlencoded.
  59. * the encoding is handled in OAuthRequest when the final
  60. * request is serialized
  61. * @param OAuthRequest $request
  62. * @param OAuthConsumer $consumer
  63. * @param OAuthToken $token
  64. * @return string
  65. */
  66. abstract public function build_signature($request, $consumer, $token);
  67. /**
  68. * Verifies that a given signature is correct
  69. * @param OAuthRequest $request
  70. * @param OAuthConsumer $consumer
  71. * @param OAuthToken $token
  72. * @param string $signature
  73. * @return bool
  74. */
  75. public function check_signature($request, $consumer, $token, $signature) {
  76. $built = $this->build_signature($request, $consumer, $token);
  77. // Check for zero length, although unlikely here
  78. if (strlen($built) == 0 || strlen($signature) == 0) {
  79. return false;
  80. }
  81. if (strlen($built) != strlen($signature)) {
  82. return false;
  83. }
  84. // Avoid a timing leak with a (hopefully) time insensitive compare
  85. $result = 0;
  86. for ($i = 0; $i < strlen($signature); $i++) {
  87. $result |= ord($built{$i}) ^ ord($signature{$i});
  88. }
  89. return $result == 0;
  90. }
  91. }
  92. /**
  93. * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
  94. * where the Signature Base String is the text and the key is the concatenated values (each first
  95. * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
  96. * character (ASCII code 38) even if empty.
  97. * - Chapter 9.2 ("HMAC-SHA1")
  98. */
  99. class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
  100. function get_name() {
  101. return "HMAC-SHA1";
  102. }
  103. public function build_signature($request, $consumer, $token) {
  104. $base_string = $request->get_signature_base_string();
  105. $request->base_string = $base_string;
  106. $key_parts = array(
  107. $consumer->secret,
  108. ($token) ? $token->secret : ""
  109. );
  110. $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
  111. $key = implode('&', $key_parts);
  112. return base64_encode(hash_hmac('sha1', $base_string, $key, true));
  113. }
  114. }
  115. /**
  116. * The PLAINTEXT method does not provide any security protection and SHOULD only be used
  117. * over a secure channel such as HTTPS. It does not use the Signature Base String.
  118. * - Chapter 9.4 ("PLAINTEXT")
  119. */
  120. class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
  121. public function get_name() {
  122. return "PLAINTEXT";
  123. }
  124. /**
  125. * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
  126. * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
  127. * empty. The result MUST be encoded again.
  128. * - Chapter 9.4.1 ("Generating Signatures")
  129. *
  130. * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
  131. * OAuthRequest handles this!
  132. */
  133. public function build_signature($request, $consumer, $token) {
  134. $key_parts = array(
  135. $consumer->secret,
  136. ($token) ? $token->secret : ""
  137. );
  138. $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
  139. $key = implode('&', $key_parts);
  140. $request->base_string = $key;
  141. return $key;
  142. }
  143. }
  144. /**
  145. * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
  146. * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
  147. * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
  148. * verified way to the Service Provider, in a manner which is beyond the scope of this
  149. * specification.
  150. * - Chapter 9.3 ("RSA-SHA1")
  151. */
  152. abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
  153. public function get_name() {
  154. return "RSA-SHA1";
  155. }
  156. // Up to the SP to implement this lookup of keys. Possible ideas are:
  157. // (1) do a lookup in a table of trusted certs keyed off of consumer
  158. // (2) fetch via http using a url provided by the requester
  159. // (3) some sort of specific discovery code based on request
  160. //
  161. // Either way should return a string representation of the certificate
  162. protected abstract function fetch_public_cert(&$request);
  163. // Up to the SP to implement this lookup of keys. Possible ideas are:
  164. // (1) do a lookup in a table of trusted certs keyed off of consumer
  165. //
  166. // Either way should return a string representation of the certificate
  167. protected abstract function fetch_private_cert(&$request);
  168. public function build_signature($request, $consumer, $token) {
  169. $base_string = $request->get_signature_base_string();
  170. $request->base_string = $base_string;
  171. // Fetch the private key cert based on the request
  172. $cert = $this->fetch_private_cert($request);
  173. // Pull the private key ID from the certificate
  174. $privatekeyid = openssl_get_privatekey($cert);
  175. // Sign using the key
  176. $ok = openssl_sign($base_string, $signature, $privatekeyid);
  177. // Release the key resource
  178. openssl_free_key($privatekeyid);
  179. return base64_encode($signature);
  180. }
  181. public function check_signature($request, $consumer, $token, $signature) {
  182. $decoded_sig = base64_decode($signature);
  183. $base_string = $request->get_signature_base_string();
  184. // Fetch the public key cert based on the request
  185. $cert = $this->fetch_public_cert($request);
  186. // Pull the public key ID from the certificate
  187. $publickeyid = openssl_get_publickey($cert);
  188. // Check the computed signature against the one passed in the query
  189. $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
  190. // Release the key resource
  191. openssl_free_key($publickeyid);
  192. return $ok == 1;
  193. }
  194. }
  195. class OAuthRequest {
  196. protected $parameters;
  197. protected $http_method;
  198. protected $http_url;
  199. // for debug purposes
  200. public $base_string;
  201. public static $version = '1.0';
  202. public static $POST_INPUT = 'php://input';
  203. function __construct($http_method, $http_url, $parameters=NULL) {
  204. $parameters = ($parameters) ? $parameters : array();
  205. $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
  206. $this->parameters = $parameters;
  207. $this->http_method = $http_method;
  208. $this->http_url = $http_url;
  209. }
  210. /**
  211. * attempt to build up a request from what was passed to the server
  212. */
  213. public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
  214. $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
  215. ? 'http'
  216. : 'https';
  217. $http_url = ($http_url) ? $http_url : $scheme .
  218. '://' . $_SERVER['SERVER_NAME'] .
  219. ':' .
  220. $_SERVER['SERVER_PORT'] .
  221. $_SERVER['REQUEST_URI'];
  222. $http_method = ($http_method) ? $http_method : $_SERVER['REQUEST_METHOD'];
  223. // We weren't handed any parameters, so let's find the ones relevant to
  224. // this request.
  225. // If you run XML-RPC or similar you should use this to provide your own
  226. // parsed parameter-list
  227. if (!$parameters) {
  228. // Find request headers
  229. $request_headers = OAuthUtil::get_headers();
  230. // Parse the query-string to find GET parameters
  231. $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
  232. // It's a POST request of the proper content-type, so parse POST
  233. // parameters and add those overriding any duplicates from GET
  234. if ($http_method == "POST"
  235. && isset($request_headers['Content-Type'])
  236. && strstr($request_headers['Content-Type'],
  237. 'application/x-www-form-urlencoded')
  238. ) {
  239. $post_data = OAuthUtil::parse_parameters(
  240. file_get_contents(self::$POST_INPUT)
  241. );
  242. $parameters = array_merge($parameters, $post_data);
  243. }
  244. // We have a Authorization-header with OAuth data. Parse the header
  245. // and add those overriding any duplicates from GET or POST
  246. if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == 'OAuth ') {
  247. $header_parameters = OAuthUtil::split_header(
  248. $request_headers['Authorization']
  249. );
  250. $parameters = array_merge($parameters, $header_parameters);
  251. }
  252. }
  253. return new OAuthRequest($http_method, $http_url, $parameters);
  254. }
  255. /**
  256. * pretty much a helper function to set up the request
  257. */
  258. public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
  259. $parameters = ($parameters) ? $parameters : array();
  260. $defaults = array("oauth_version" => OAuthRequest::$version,
  261. "oauth_nonce" => OAuthRequest::generate_nonce(),
  262. "oauth_timestamp" => OAuthRequest::generate_timestamp(),
  263. "oauth_consumer_key" => $consumer->key);
  264. if ($token)
  265. $defaults['oauth_token'] = $token->key;
  266. $parameters = array_merge($defaults, $parameters);
  267. return new OAuthRequest($http_method, $http_url, $parameters);
  268. }
  269. public function set_parameter($name, $value, $allow_duplicates = true) {
  270. if ($allow_duplicates && isset($this->parameters[$name])) {
  271. // We have already added parameter(s) with this name, so add to the list
  272. if (is_scalar($this->parameters[$name])) {
  273. // This is the first duplicate, so transform scalar (string)
  274. // into an array so we can add the duplicates
  275. $this->parameters[$name] = array($this->parameters[$name]);
  276. }
  277. $this->parameters[$name][] = $value;
  278. } else {
  279. $this->parameters[$name] = $value;
  280. }
  281. }
  282. public function get_parameter($name) {
  283. return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
  284. }
  285. public function get_parameters() {
  286. return $this->parameters;
  287. }
  288. public function unset_parameter($name) {
  289. unset($this->parameters[$name]);
  290. }
  291. /**
  292. * The request parameters, sorted and concatenated into a normalized string.
  293. * @return string
  294. */
  295. public function get_signable_parameters() {
  296. // Grab all parameters
  297. $params = $this->parameters;
  298. // Remove oauth_signature if present
  299. // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
  300. if (isset($params['oauth_signature'])) {
  301. unset($params['oauth_signature']);
  302. }
  303. return OAuthUtil::build_http_query($params);
  304. }
  305. /**
  306. * Returns the base string of this request
  307. *
  308. * The base string defined as the method, the url
  309. * and the parameters (normalized), each urlencoded
  310. * and the concated with &.
  311. */
  312. public function get_signature_base_string() {
  313. $parts = array(
  314. $this->get_normalized_http_method(),
  315. $this->get_normalized_http_url(),
  316. $this->get_signable_parameters()
  317. );
  318. $parts = OAuthUtil::urlencode_rfc3986($parts);
  319. return implode('&', $parts);
  320. }
  321. /**
  322. * just uppercases the http method
  323. */
  324. public function get_normalized_http_method() {
  325. return strtoupper($this->http_method);
  326. }
  327. /**
  328. * parses the url and rebuilds it to be
  329. * scheme://host/path
  330. */
  331. public function get_normalized_http_url() {
  332. $parts = parse_url($this->http_url);
  333. $scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http';
  334. $port = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80');
  335. $host = (isset($parts['host'])) ? strtolower($parts['host']) : '';
  336. $path = (isset($parts['path'])) ? $parts['path'] : '';
  337. if (($scheme == 'https' && $port != '443')
  338. || ($scheme == 'http' && $port != '80')) {
  339. $host = "$host:$port";
  340. }
  341. return "$scheme://$host$path";
  342. }
  343. /**
  344. * builds a url usable for a GET request
  345. */
  346. public function to_url() {
  347. $post_data = $this->to_postdata();
  348. $out = $this->get_normalized_http_url();
  349. if ($post_data) {
  350. $out .= '?'.$post_data;
  351. }
  352. return $out;
  353. }
  354. /**
  355. * builds the data one would send in a POST request
  356. */
  357. public function to_postdata() {
  358. return OAuthUtil::build_http_query($this->parameters);
  359. }
  360. /**
  361. * builds the Authorization: header
  362. */
  363. public function to_header($realm=null) {
  364. $first = true;
  365. if($realm) {
  366. $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
  367. $first = false;
  368. } else
  369. $out = 'Authorization: OAuth';
  370. $total = array();
  371. foreach ($this->parameters as $k => $v) {
  372. if (substr($k, 0, 5) != "oauth") continue;
  373. if (is_array($v)) {
  374. throw new OAuthException('Arrays not supported in headers');
  375. }
  376. $out .= ($first) ? ' ' : ',';
  377. $out .= OAuthUtil::urlencode_rfc3986($k) .
  378. '="' .
  379. OAuthUtil::urlencode_rfc3986($v) .
  380. '"';
  381. $first = false;
  382. }
  383. return $out;
  384. }
  385. public function __toString() {
  386. return $this->to_url();
  387. }
  388. public function sign_request($signature_method, $consumer, $token) {
  389. $this->set_parameter(
  390. "oauth_signature_method",
  391. $signature_method->get_name(),
  392. false
  393. );
  394. $signature = $this->build_signature($signature_method, $consumer, $token);
  395. $this->set_parameter("oauth_signature", $signature, false);
  396. }
  397. public function build_signature($signature_method, $consumer, $token) {
  398. $signature = $signature_method->build_signature($this, $consumer, $token);
  399. return $signature;
  400. }
  401. /**
  402. * util function: current timestamp
  403. */
  404. private static function generate_timestamp() {
  405. return time();
  406. }
  407. /**
  408. * util function: current nonce
  409. */
  410. private static function generate_nonce() {
  411. $mt = microtime();
  412. $rand = mt_rand();
  413. return md5($mt . $rand); // md5s look nicer than numbers
  414. }
  415. }
  416. class OAuthServer {
  417. protected $timestamp_threshold = 300; // in seconds, five minutes
  418. protected $version = '1.0'; // hi blaine
  419. protected $signature_methods = array();
  420. protected $data_store;
  421. function __construct($data_store) {
  422. $this->data_store = $data_store;
  423. }
  424. public function add_signature_method($signature_method) {
  425. $this->signature_methods[$signature_method->get_name()] =
  426. $signature_method;
  427. }
  428. // high level functions
  429. /**
  430. * process a request_token request
  431. * returns the request token on success
  432. */
  433. public function fetch_request_token(&$request) {
  434. $this->get_version($request);
  435. $consumer = $this->get_consumer($request);
  436. // no token required for the initial token request
  437. $token = NULL;
  438. $this->check_signature($request, $consumer, $token);
  439. // Rev A change
  440. $callback = $request->get_parameter('oauth_callback');
  441. $new_token = $this->data_store->new_request_token($consumer, $callback);
  442. return $new_token;
  443. }
  444. /**
  445. * process an access_token request
  446. * returns the access token on success
  447. */
  448. public function fetch_access_token(&$request) {
  449. $this->get_version($request);
  450. $consumer = $this->get_consumer($request);
  451. // requires authorized request token
  452. $token = $this->get_token($request, $consumer, "request");
  453. $this->check_signature($request, $consumer, $token);
  454. // Rev A change
  455. $verifier = $request->get_parameter('oauth_verifier');
  456. $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
  457. return $new_token;
  458. }
  459. /**
  460. * verify an api call, checks all the parameters
  461. */
  462. public function verify_request(&$request) {
  463. $this->get_version($request);
  464. $consumer = $this->get_consumer($request);
  465. $token = $this->get_token($request, $consumer, "access");
  466. $this->check_signature($request, $consumer, $token);
  467. return array($consumer, $token);
  468. }
  469. // Internals from here
  470. /**
  471. * version 1
  472. */
  473. private function get_version(&$request) {
  474. $version = $request->get_parameter("oauth_version");
  475. if (!$version) {
  476. // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
  477. // Chapter 7.0 ("Accessing Protected Ressources")
  478. $version = '1.0';
  479. }
  480. if ($version !== $this->version) {
  481. throw new OAuthException("OAuth version '$version' not supported");
  482. }
  483. return $version;
  484. }
  485. /**
  486. * figure out the signature with some defaults
  487. */
  488. private function get_signature_method($request) {
  489. $signature_method = $request instanceof OAuthRequest
  490. ? $request->get_parameter("oauth_signature_method")
  491. : NULL;
  492. if (!$signature_method) {
  493. // According to chapter 7 ("Accessing Protected Ressources") the signature-method
  494. // parameter is required, and we can't just fallback to PLAINTEXT
  495. throw new OAuthException('No signature method parameter. This parameter is required');
  496. }
  497. if (!in_array($signature_method,
  498. array_keys($this->signature_methods))) {
  499. throw new OAuthException(
  500. "Signature method '$signature_method' not supported " .
  501. "try one of the following: " .
  502. implode(", ", array_keys($this->signature_methods))
  503. );
  504. }
  505. return $this->signature_methods[$signature_method];
  506. }
  507. /**
  508. * try to find the consumer for the provided request's consumer key
  509. */
  510. private function get_consumer($request) {
  511. $consumer_key = $request instanceof OAuthRequest
  512. ? $request->get_parameter("oauth_consumer_key")
  513. : NULL;
  514. if (!$consumer_key) {
  515. throw new OAuthException("Invalid consumer key");
  516. }
  517. $consumer = $this->data_store->lookup_consumer($consumer_key);
  518. if (!$consumer) {
  519. throw new OAuthException("Invalid consumer");
  520. }
  521. return $consumer;
  522. }
  523. /**
  524. * try to find the token for the provided request's token key
  525. */
  526. private function get_token($request, $consumer, $token_type="access") {
  527. $token_field = $request instanceof OAuthRequest
  528. ? $request->get_parameter('oauth_token')
  529. : NULL;
  530. $token = $this->data_store->lookup_token(
  531. $consumer, $token_type, $token_field
  532. );
  533. if (!$token) {
  534. throw new OAuthException("Invalid $token_type token: $token_field");
  535. }
  536. return $token;
  537. }
  538. /**
  539. * all-in-one function to check the signature on a request
  540. * should guess the signature method appropriately
  541. */
  542. private function check_signature($request, $consumer, $token) {
  543. // this should probably be in a different method
  544. $timestamp = $request instanceof OAuthRequest
  545. ? $request->get_parameter('oauth_timestamp')
  546. : NULL;
  547. $nonce = $request instanceof OAuthRequest
  548. ? $request->get_parameter('oauth_nonce')
  549. : NULL;
  550. $this->check_timestamp($timestamp);
  551. $this->check_nonce($consumer, $token, $nonce, $timestamp);
  552. $signature_method = $this->get_signature_method($request);
  553. $signature = $request->get_parameter('oauth_signature');
  554. $valid_sig = $signature_method->check_signature(
  555. $request,
  556. $consumer,
  557. $token,
  558. $signature
  559. );
  560. if (!$valid_sig) {
  561. throw new OAuthException("Invalid signature");
  562. }
  563. }
  564. /**
  565. * check that the timestamp is new enough
  566. */
  567. private function check_timestamp($timestamp) {
  568. if( ! $timestamp )
  569. throw new OAuthException(
  570. 'Missing timestamp parameter. The parameter is required'
  571. );
  572. // verify that timestamp is recentish
  573. $now = time();
  574. if (abs($now - $timestamp) > $this->timestamp_threshold) {
  575. throw new OAuthException(
  576. "Expired timestamp, yours $timestamp, ours $now"
  577. );
  578. }
  579. }
  580. /**
  581. * check that the nonce is not repeated
  582. */
  583. private function check_nonce($consumer, $token, $nonce, $timestamp) {
  584. if( ! $nonce )
  585. throw new OAuthException(
  586. 'Missing nonce parameter. The parameter is required'
  587. );
  588. // verify that the nonce is uniqueish
  589. $found = $this->data_store->lookup_nonce(
  590. $consumer,
  591. $token,
  592. $nonce,
  593. $timestamp
  594. );
  595. if ($found) {
  596. throw new OAuthException("Nonce already used: $nonce");
  597. }
  598. }
  599. }
  600. class OAuthDataStore {
  601. function lookup_consumer($consumer_key) {
  602. // implement me
  603. }
  604. function lookup_token($consumer, $token_type, $token) {
  605. // implement me
  606. }
  607. function lookup_nonce($consumer, $token, $nonce, $timestamp) {
  608. // implement me
  609. }
  610. function new_request_token($consumer, $callback = null) {
  611. // return a new token attached to this consumer
  612. }
  613. function new_access_token($token, $consumer, $verifier = null) {
  614. // return a new access token attached to this consumer
  615. // for the user associated with this token if the request token
  616. // is authorized
  617. // should also invalidate the request token
  618. }
  619. }
  620. class OAuthUtil {
  621. public static function urlencode_rfc3986($input) {
  622. if (is_array($input)) {
  623. return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
  624. } else if (is_scalar($input)) {
  625. return str_replace(
  626. '+',
  627. ' ',
  628. str_replace('%7E', '~', rawurlencode($input))
  629. );
  630. } else {
  631. return '';
  632. }
  633. }
  634. // This decode function isn't taking into consideration the above
  635. // modifications to the encoding process. However, this method doesn't
  636. // seem to be used anywhere so leaving it as is.
  637. public static function urldecode_rfc3986($string) {
  638. return urldecode($string);
  639. }
  640. // Utility function for turning the Authorization: header into
  641. // parameters, has to do some unescaping
  642. // Can filter out any non-oauth parameters if needed (default behaviour)
  643. // May 28th, 2010 - method updated to tjerk.meesters for a speed improvement.
  644. // see http://code.google.com/p/oauth/issues/detail?id=163
  645. public static function split_header($header, $only_allow_oauth_parameters = true) {
  646. $params = array();
  647. if (preg_match_all('/('.($only_allow_oauth_parameters ? 'oauth_' : '').'[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $header, $matches)) {
  648. foreach ($matches[1] as $i => $h) {
  649. $params[$h] = OAuthUtil::urldecode_rfc3986(empty($matches[3][$i]) ? $matches[4][$i] : $matches[3][$i]);
  650. }
  651. if (isset($params['realm'])) {
  652. unset($params['realm']);
  653. }
  654. }
  655. return $params;
  656. }
  657. // helper to try to sort out headers for people who aren't running apache
  658. public static function get_headers() {
  659. if (function_exists('apache_request_headers')) {
  660. // we need this to get the actual Authorization: header
  661. // because apache tends to tell us it doesn't exist
  662. $headers = apache_request_headers();
  663. // sanitize the output of apache_request_headers because
  664. // we always want the keys to be Cased-Like-This and arh()
  665. // returns the headers in the same case as they are in the
  666. // request
  667. $out = array();
  668. foreach ($headers AS $key => $value) {
  669. $key = str_replace(
  670. " ",
  671. "-",
  672. ucwords(strtolower(str_replace("-", " ", $key)))
  673. );
  674. $out[$key] = $value;
  675. }
  676. } else {
  677. // otherwise we don't have apache and are just going to have to hope
  678. // that $_SERVER actually contains what we need
  679. $out = array();
  680. if( isset($_SERVER['CONTENT_TYPE']) )
  681. $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
  682. if( isset($_ENV['CONTENT_TYPE']) )
  683. $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
  684. foreach ($_SERVER as $key => $value) {
  685. if (substr($key, 0, 5) == "HTTP_") {
  686. // this is chaos, basically it is just there to capitalize the first
  687. // letter of every word that is not an initial HTTP and strip HTTP
  688. // code from przemek
  689. $key = str_replace(
  690. " ",
  691. "-",
  692. ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
  693. );
  694. $out[$key] = $value;
  695. }
  696. }
  697. }
  698. return $out;
  699. }
  700. // This function takes a input like a=b&a=c&d=e and returns the parsed
  701. // parameters like this
  702. // array('a' => array('b','c'), 'd' => 'e')
  703. public static function parse_parameters( $input ) {
  704. if (!isset($input) || !$input) return array();
  705. $pairs = explode('&', $input);
  706. $parsed_parameters = array();
  707. foreach ($pairs as $pair) {
  708. $split = explode('=', $pair, 2);
  709. $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
  710. $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
  711. if (isset($parsed_parameters[$parameter])) {
  712. // We have already recieved parameter(s) with this name, so add to the list
  713. // of parameters with this name
  714. if (is_scalar($parsed_parameters[$parameter])) {
  715. // This is the first duplicate, so transform scalar (string) into an array
  716. // so we can add the duplicates
  717. $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
  718. }
  719. $parsed_parameters[$parameter][] = $value;
  720. } else {
  721. $parsed_parameters[$parameter] = $value;
  722. }
  723. }
  724. return $parsed_parameters;
  725. }
  726. public static function build_http_query($params) {
  727. if (!$params) return '';
  728. // Urlencode both keys and values
  729. $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
  730. $values = OAuthUtil::urlencode_rfc3986(array_values($params));
  731. $params = array_combine($keys, $values);
  732. // Parameters are sorted by name, using lexicographical byte value ordering.
  733. // Ref: Spec: 9.1.1 (1)
  734. uksort($params, 'strcmp');
  735. $pairs = array();
  736. foreach ($params as $parameter => $value) {
  737. if (is_array($value)) {
  738. // If two or more parameters share the same name, they are sorted by their value
  739. // Ref: Spec: 9.1.1 (1)
  740. // June 12th, 2010 - changed to sort because of issue 164 by hidetaka
  741. sort($value, SORT_STRING);
  742. foreach ($value as $duplicate_value) {
  743. $pairs[] = $parameter . '=' . $duplicate_value;
  744. }
  745. } else {
  746. $pairs[] = $parameter . '=' . $value;
  747. }
  748. }
  749. // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
  750. // Each name-value pair is separated by an '&' character (ASCII code 38)
  751. return implode('&', $pairs);
  752. }
  753. }
  754. ?>