OAuth.php 27 KB

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