PageRenderTime 54ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/lib/twitter/oauth.php

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