OAuthSimple.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. <?php
  2. /**
  3. * OAuthSimple - A simpler version of OAuth
  4. *
  5. * https://github.com/jrconlin/oauthsimple
  6. *
  7. * @author jr conlin <src@jrconlin.com>
  8. * @copyright unitedHeroes.net 2011
  9. * @version 1.3
  10. * @license See license.txt
  11. *
  12. */
  13. class OAuthSimple {
  14. private $_secrets;
  15. private $_default_signature_method;
  16. private $_action;
  17. private $_nonce_chars;
  18. /**
  19. * Constructor
  20. *
  21. * @access public
  22. * @param api_key (String) The API Key (sometimes referred to as the consumer key) This value is usually supplied by the site you wish to use.
  23. * @param shared_secret (String) The shared secret. This value is also usually provided by the site you wish to use.
  24. * @return OAuthSimple (Object)
  25. */
  26. function __construct ($APIKey = "", $sharedSecret=""){
  27. if (!empty($APIKey))
  28. {
  29. $this->_secrets['consumer_key'] = $APIKey;
  30. }
  31. if (!empty($sharedSecret))
  32. {
  33. $this->_secrets['shared_secret'] = $sharedSecret;
  34. }
  35. $this->_default_signature_method = "HMAC-SHA1";
  36. $this->_action = "GET";
  37. $this->_nonce_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  38. return $this;
  39. }
  40. /**
  41. * Reset the parameters and URL
  42. *
  43. * @access public
  44. * @return OAuthSimple (Object)
  45. */
  46. public function reset() {
  47. $this->_parameters = Array();
  48. $this->path = NULL;
  49. $this->sbs = NULL;
  50. return $this;
  51. }
  52. /**
  53. * Set the parameters either from a hash or a string
  54. *
  55. * @access public
  56. * @param(string, object) List of parameters for the call, this can either be a URI string (e.g. "foo=bar&gorp=banana" or an object/hash)
  57. * @return OAuthSimple (Object)
  58. */
  59. public function setParameters ($parameters=Array()) {
  60. if (is_string($parameters))
  61. {
  62. $parameters = $this->_parseParameterString($parameters);
  63. }
  64. if (empty($this->_parameters))
  65. {
  66. $this->_parameters = $parameters;
  67. }
  68. else if (!empty($parameters))
  69. {
  70. $this->_parameters = array_merge($this->_parameters,$parameters);
  71. }
  72. if (empty($this->_parameters['oauth_nonce']))
  73. {
  74. $this->_getNonce();
  75. }
  76. if (empty($this->_parameters['oauth_timestamp']))
  77. {
  78. $this->_getTimeStamp();
  79. }
  80. if (empty($this->_parameters['oauth_consumer_key']))
  81. {
  82. $this->_getApiKey();
  83. }
  84. if (empty($this->_parameters['oauth_token']))
  85. {
  86. $this->_getAccessToken();
  87. }
  88. if (empty($this->_parameters['oauth_signature_method']))
  89. {
  90. $this->setSignatureMethod();
  91. }
  92. if (empty($this->_parameters['oauth_version']))
  93. {
  94. $this->_parameters['oauth_version']="1.0";
  95. }
  96. return $this;
  97. }
  98. /**
  99. * Convenience method for setParameters
  100. *
  101. * @access public
  102. * @see setParameters
  103. */
  104. public function setQueryString ($parameters)
  105. {
  106. return $this->setParameters($parameters);
  107. }
  108. /**
  109. * Set the target URL (does not include the parameters)
  110. *
  111. * @param path (String) the fully qualified URI (excluding query arguments) (e.g "http://example.org/foo")
  112. * @return OAuthSimple (Object)
  113. */
  114. public function setURL ($path)
  115. {
  116. if (empty($path))
  117. {
  118. throw new OAuthSimpleException('No path specified for OAuthSimple.setURL');
  119. }
  120. $this->_path=$path;
  121. return $this;
  122. }
  123. /**
  124. * Convenience method for setURL
  125. *
  126. * @param path (String)
  127. * @see setURL
  128. */
  129. public function setPath ($path)
  130. {
  131. return $this->_path=$path;
  132. }
  133. /**
  134. * Set the "action" for the url, (e.g. GET,POST, DELETE, etc.)
  135. *
  136. * @param action (String) HTTP Action word.
  137. * @return OAuthSimple (Object)
  138. */
  139. public function setAction ($action)
  140. {
  141. if (empty($action))
  142. {
  143. $action = 'GET';
  144. }
  145. $action = strtoupper($action);
  146. if (preg_match('/[^A-Z]/',$action))
  147. {
  148. throw new OAuthSimpleException('Invalid action specified for OAuthSimple.setAction');
  149. }
  150. $this->_action = $action;
  151. return $this;
  152. }
  153. /**
  154. * Set the signatures (as well as validate the ones you have)
  155. *
  156. * @param signatures (object) object/hash of the token/signature pairs {api_key:, shared_secret:, oauth_token: oauth_secret:}
  157. * @return OAuthSimple (Object)
  158. */
  159. public function signatures ($signatures)
  160. {
  161. if (!empty($signatures) && !is_array($signatures))
  162. {
  163. throw new OAuthSimpleException('Must pass dictionary array to OAuthSimple.signatures');
  164. }
  165. if (!empty($signatures))
  166. {
  167. if (empty($this->_secrets))
  168. {
  169. $this->_secrets=Array();
  170. }
  171. $this->_secrets=array_merge($this->_secrets,$signatures);
  172. }
  173. if (isset($this->_secrets['api_key']))
  174. {
  175. $this->_secrets['consumer_key'] = $this->_secrets['api_key'];
  176. }
  177. if (isset($this->_secrets['access_token']))
  178. {
  179. $this->_secrets['oauth_token'] = $this->_secrets['access_token'];
  180. }
  181. if (isset($this->_secrets['access_secret']))
  182. {
  183. $this->_secrets['shared_secret'] = $this->_secrets['access_secret'];
  184. }
  185. if (isset($this->_secrets['oauth_token_secret']))
  186. {
  187. $this->_secrets['oauth_secret'] = $this->_secrets['oauth_token_secret'];
  188. }
  189. if (empty($this->_secrets['consumer_key']))
  190. {
  191. throw new OAuthSimpleException('Missing required consumer_key in OAuthSimple.signatures');
  192. }
  193. if (empty($this->_secrets['shared_secret']))
  194. {
  195. throw new OAuthSimpleException('Missing requires shared_secret in OAuthSimple.signatures');
  196. }
  197. if (!empty($this->_secrets['oauth_token']) && empty($this->_secrets['oauth_secret']))
  198. {
  199. throw new OAuthSimpleException('Missing oauth_secret for supplied oauth_token in OAuthSimple.signatures');
  200. }
  201. return $this;
  202. }
  203. public function setTokensAndSecrets($signatures)
  204. {
  205. return $this->signatures($signatures);
  206. }
  207. /**
  208. * Set the signature method (currently only Plaintext or SHA-MAC1)
  209. *
  210. * @param method (String) Method of signing the transaction (only PLAINTEXT and SHA-MAC1 allowed for now)
  211. * @return OAuthSimple (Object)
  212. */
  213. public function setSignatureMethod ($method="")
  214. {
  215. if (empty($method))
  216. {
  217. $method = $this->_default_signature_method;
  218. }
  219. $method = strtoupper($method);
  220. switch($method)
  221. {
  222. case 'PLAINTEXT':
  223. case 'HMAC-SHA1':
  224. $this->_parameters['oauth_signature_method']=$method;
  225. break;
  226. default:
  227. throw new OAuthSimpleException ("Unknown signing method $method specified for OAuthSimple.setSignatureMethod");
  228. break;
  229. }
  230. return $this;
  231. }
  232. /** sign the request
  233. *
  234. * note: all arguments are optional, provided you've set them using the
  235. * other helper functions.
  236. *
  237. * @param args (Array) hash of arguments for the call {action, path, parameters (array), method, signatures (array)} all arguments are optional.
  238. * @return (Array) signed values
  239. */
  240. public function sign($args=array())
  241. {
  242. if (!empty($args['action']))
  243. {
  244. $this->setAction($args['action']);
  245. }
  246. if (!empty($args['path']))
  247. {
  248. $this->setPath($args['path']);
  249. }
  250. if (!empty($args['method']))
  251. {
  252. $this->setSignatureMethod($args['method']);
  253. }
  254. if (!empty($args['signatures']))
  255. {
  256. $this->signatures($args['signatures']);
  257. }
  258. if (empty($args['parameters']))
  259. {
  260. $args['parameters']=array();
  261. }
  262. $this->setParameters($args['parameters']);
  263. $normParams = $this->_normalizedParameters();
  264. return Array (
  265. 'parameters' => $this->_parameters,
  266. 'signature' => self::_oauthEscape($this->_parameters['oauth_signature']),
  267. 'signed_url' => $this->_path . '?' . $normParams,
  268. 'header' => $this->getHeaderString(),
  269. 'sbs'=> $this->sbs
  270. );
  271. }
  272. /**
  273. * Return a formatted "header" string
  274. *
  275. * NOTE: This doesn't set the "Authorization: " prefix, which is required.
  276. * It's not set because various set header functions prefer different
  277. * ways to do that.
  278. *
  279. * @param args (Array)
  280. * @return $result (String)
  281. */
  282. public function getHeaderString ($args=array())
  283. {
  284. if (empty($this->_parameters['oauth_signature']))
  285. {
  286. $this->sign($args);
  287. }
  288. $result = 'OAuth ';
  289. foreach ($this->_parameters as $pName => $pValue)
  290. {
  291. if (strpos($pName,'oauth_') !== 0)
  292. {
  293. continue;
  294. }
  295. if (is_array($pValue))
  296. {
  297. foreach ($pValue as $val)
  298. {
  299. $result .= $pName .'="' . self::_oauthEscape($val) . '", ';
  300. }
  301. }
  302. else
  303. {
  304. $result .= $pName . '="' . self::_oauthEscape($pValue) . '", ';
  305. }
  306. }
  307. return preg_replace('/, $/','',$result);
  308. }
  309. private function _parseParameterString ($paramString)
  310. {
  311. $elements = explode('&',$paramString);
  312. $result = array();
  313. foreach ($elements as $element)
  314. {
  315. list ($key,$token) = explode('=',$element);
  316. if ($token)
  317. {
  318. $token = urldecode($token);
  319. }
  320. if (!empty($result[$key]))
  321. {
  322. if (!is_array($result[$key]))
  323. {
  324. $result[$key] = array($result[$key],$token);
  325. }
  326. else
  327. {
  328. array_push($result[$key],$token);
  329. }
  330. }
  331. else
  332. $result[$key]=$token;
  333. }
  334. return $result;
  335. }
  336. private static function _oauthEscape($string)
  337. {
  338. if ($string === 0) { return 0; }
  339. if ($string == '0') { return '0'; }
  340. if (strlen($string) == 0) { return ''; }
  341. if (is_array($string)) {
  342. throw new OAuthSimpleException('Array passed to _oauthEscape');
  343. }
  344. $string = urlencode($string);
  345. //FIX: urlencode of ~ and '+'
  346. $string = str_replace(
  347. Array('%7E','+' ), // Replace these
  348. Array('~', '%20'), // with these
  349. $string);
  350. return $string;
  351. }
  352. private function _getNonce($length=5)
  353. {
  354. $result = '';
  355. $cLength = strlen($this->_nonce_chars);
  356. for ($i=0; $i < $length; $i++)
  357. {
  358. $rnum = rand(0,$cLength - 1);
  359. $result .= substr($this->_nonce_chars,$rnum,1);
  360. }
  361. $this->_parameters['oauth_nonce'] = $result;
  362. return $result;
  363. }
  364. private function _getApiKey()
  365. {
  366. if (empty($this->_secrets['consumer_key']))
  367. {
  368. throw new OAuthSimpleException('No consumer_key set for OAuthSimple');
  369. }
  370. $this->_parameters['oauth_consumer_key']=$this->_secrets['consumer_key'];
  371. return $this->_parameters['oauth_consumer_key'];
  372. }
  373. private function _getAccessToken()
  374. {
  375. if (!isset($this->_secrets['oauth_secret']))
  376. {
  377. return '';
  378. }
  379. if (!isset($this->_secrets['oauth_token']))
  380. {
  381. throw new OAuthSimpleException('No access token (oauth_token) set for OAuthSimple.');
  382. }
  383. $this->_parameters['oauth_token'] = $this->_secrets['oauth_token'];
  384. return $this->_parameters['oauth_token'];
  385. }
  386. private function _getTimeStamp()
  387. {
  388. return $this->_parameters['oauth_timestamp'] = time();
  389. }
  390. private function _normalizedParameters()
  391. {
  392. $normalized_keys = array();
  393. $return_array = array();
  394. foreach ( $this->_parameters as $paramName=>$paramValue) {
  395. if (preg_match('/w+_secret/', $paramName) OR
  396. $paramName == "oauth_signature") {
  397. continue;
  398. }
  399. // Read parameters from a file. Hope you're practicing safe PHP.
  400. //if (strpos($paramValue, '@') !== 0 && !file_exists(substr($paramValue, 1)))
  401. //{
  402. if (is_array($paramValue))
  403. {
  404. $normalized_keys[self::_oauthEscape($paramName)] = array();
  405. foreach($paramValue as $item)
  406. {
  407. array_push($normalized_keys[self::_oauthEscape($paramName)], self::_oauthEscape($item));
  408. }
  409. }
  410. else
  411. {
  412. $normalized_keys[self::_oauthEscape($paramName)] = self::_oauthEscape($paramValue);
  413. }
  414. //}
  415. }
  416. ksort($normalized_keys);
  417. foreach($normalized_keys as $key=>$val)
  418. {
  419. if (is_array($val))
  420. {
  421. sort($val);
  422. foreach($val as $element)
  423. {
  424. array_push($return_array, $key . "=" . $element);
  425. }
  426. }
  427. else
  428. {
  429. array_push($return_array, $key .'='. $val);
  430. }
  431. }
  432. $presig = join("&", $return_array);
  433. $sig = $this->_generateSignature($presig);
  434. $this->_parameters['oauth_signature']=$sig;
  435. array_push($return_array, "oauth_signature=$sig");
  436. return join("&", $return_array);
  437. }
  438. private function _generateSignature ($parameters="")
  439. {
  440. $secretKey = '';
  441. if(isset($this->_secrets['shared_secret']))
  442. {
  443. $secretKey = self::_oauthEscape($this->_secrets['shared_secret']);
  444. }
  445. $secretKey .= '&';
  446. if(isset($this->_secrets['oauth_secret']))
  447. {
  448. $secretKey .= self::_oauthEscape($this->_secrets['oauth_secret']);
  449. }
  450. if(!empty($parameters)){
  451. $parameters = urlencode($parameters);
  452. }
  453. switch($this->_parameters['oauth_signature_method'])
  454. {
  455. case 'PLAINTEXT':
  456. return urlencode($secretKey);;
  457. case 'HMAC-SHA1':
  458. $this->sbs = self::_oauthEscape($this->_action).'&'.self::_oauthEscape($this->_path).'&'.$parameters;
  459. return base64_encode(hash_hmac('sha1',$this->sbs,$secretKey,TRUE));
  460. default:
  461. throw new OAuthSimpleException('Unknown signature method for OAuthSimple');
  462. break;
  463. }
  464. }
  465. }
  466. class OAuthSimpleException extends Exception {
  467. public function __construct($err, $isDebug = FALSE)
  468. {
  469. self::log_error($err);
  470. if ($isDebug)
  471. {
  472. self::display_error($err, TRUE);
  473. }
  474. }
  475. public static function log_error($err)
  476. {
  477. error_log($err, 0);
  478. }
  479. public static function display_error($err, $kill = FALSE)
  480. {
  481. print_r($err);
  482. if ($kill === FALSE)
  483. {
  484. die();
  485. }
  486. }
  487. }