PageRenderTime 41ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/wordpress/praized-community/includes/php/praized-php/PraizedOAuth.php

http://praized.googlecode.com/
PHP | 441 lines | 231 code | 61 blank | 149 comment | 43 complexity | 889461bfdcc84e0278c2cdebdedc78b6 MD5 | raw file
Possible License(s): Apache-2.0
  1. <?php
  2. /**
  3. * Praized OAuth handling library
  4. *
  5. * @version 2.0
  6. * @package Praized
  7. * @subpackage OAuth
  8. * @author Pier-Hugures Pellerin for Praized Media, Inc.
  9. * @author Stephane Daury for Praized Media, Inc.
  10. * @copyright Praized Media, Inc. <http://praizedmedia.com/>
  11. * @license Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0>
  12. */
  13. if ( ! class_exists('PraizedOAuth') ) {
  14. if ( ! class_exists('PraizedCipher') )
  15. include_once dirname(realpath(__FILE__)) . "/PraizedCipher.php";
  16. if ( ! class_exists('OAuthConsumer') )
  17. include_once dirname(realpath(__FILE__)) . "/vendor/OAuth.php";
  18. if ( ! class_exists('Snoopy') )
  19. include_once dirname(realpath(__FILE__)) . "/vendor/Snoopy.php";
  20. /**
  21. * Praized OAuth handling library: Class
  22. *
  23. * @package Praized
  24. * @subpackage OAuth
  25. * @since 0.1
  26. */
  27. class PraizedOAuth {
  28. var $_consumerKey = NULL;
  29. var $_consumerSecret = NULL;
  30. var $_requestTokenUrl = "/oauth/request_token";
  31. var $_requestAccessTokenURL = "/oauth/access_token";
  32. var $_authorizeURL = "/oauth/authorize";
  33. var $currentUser = array();
  34. var $_cookieHash = NULL;
  35. // OAuth System.
  36. var $_consumer = NULL;
  37. var $_encoder;
  38. var $_net;
  39. var $_version = '2.0';
  40. var $errors = array();
  41. var $_expirationTime = 1209600; // (14 * 24 * 3600);
  42. var $_oAuthToken;
  43. var $_test = 0;
  44. /**
  45. * Constructor.
  46. *
  47. * @param string $consumerKey Consumer Key
  48. * @param string $consumerSecret Consumer Secret
  49. * @since 0.1
  50. */
  51. function PraizedOAuth($consumerKey, $consumerSecret, $authHost = 'http://auth.praized.com') {
  52. $this->_consumerKey = $consumerKey;
  53. $this->_consumerSecret = $consumerSecret;
  54. $devInc = dirname(realpath(__FILE__)).'/Praized/Dev.php';
  55. if ( file_exists($devInc) ) {
  56. require_once($devInc);
  57. $pHosts = PraizedDev::praizedHosts();
  58. $this->_requestTokenUrl = $pHosts['auth'] . '/oauth/request_token';
  59. $this->_requestAccessTokenURL = $pHosts['auth'] . '/oauth/access_token';
  60. $this->_authorizeURL = $pHosts['auth'] . '/oauth/authorize';
  61. } else {
  62. $this->_requestTokenUrl = $authHost . $this->_requestTokenUrl;
  63. $this->_requestAccessTokenURL = $authHost . $this->_requestAccessTokenURL;
  64. $this->_authorizeURL = $authHost . $this->_authorizeURL;
  65. }
  66. $this->_consumer = new OAuthConsumer($this->_consumerKey, $this->_consumerSecret);
  67. $this->_encoder = new OAuthSignatureMethod_HMAC_SHA1();
  68. // initialize the Snoop Agent.
  69. $this->_net = new Snoopy();
  70. $this->_net->agent = "Praized PHP OAuth Request v." . $this->_version;
  71. $this->_oAuthToken = ( ! empty($_GET["oauth_token"]) ) ? $_GET["oauth_token"] : false;
  72. // Trying to get the user information.
  73. $this->_load();
  74. }
  75. /**
  76. * Returns the domain that the related cookie(s) should be valid for.
  77. *
  78. * @return string
  79. * @since 0.1
  80. */
  81. function _cookieDomain() {
  82. if ( ! isset($_SERVER["SERVER_NAME"]) || empty($_SERVER["SERVER_NAME"]) ) {
  83. if (strstr($_SERVER["HTTP_HOST"], ':'))
  84. list($host, $port) = explode(':', $_SERVER["HTTP_HOST"]);
  85. else
  86. $host = $_SERVER["HTTP_HOST"];
  87. } elseif ( $_SERVER["SERVER_NAME"] == $_SERVER["SERVER_ADDR"] ) {
  88. $host = $_SERVER["SERVER_ADDR"];
  89. } else {
  90. $host = $_SERVER["SERVER_NAME"];
  91. }
  92. if ( preg_match('/^.*?\.?([^\.]+\.[a-zA-Z]+)$/', $host, $matches) ) {
  93. if ( $matches[1] )
  94. $domain = '.' . $matches[1];
  95. }
  96. if ( ! isset($domain) )
  97. $domain = $host;
  98. return $domain;
  99. }
  100. /**
  101. * Start the authorization process.
  102. *
  103. * @param string $callback Fully qualifed URL, defaults to what is guessed to be the community's top level.
  104. * @since 0.1
  105. */
  106. function startAuthorization($callbackURL = NULL) {
  107. if ( $callbackURL == NULL ) {
  108. if ( ! isset($_SERVER['SCRIPT_URI']) ) {
  109. $scriptUri = sprintf(
  110. '%s://%s%s%s',
  111. ( isset($_SERVER['HTTPS']) ) ? 'https' : 'http',
  112. ( isset($_SERVER['PHP_AUTH_USER']) ) ? $_SERVER['PHP_AUTH_USER'].':'.$_SERVER['PHP_AUTH_PQ'].'@' : '',
  113. $_SERVER['HTTP_HOST'],
  114. ( isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : $_SERVER['REQUEST_URI'])
  115. );
  116. } else {
  117. $scriptUri = $_SERVER['SCRIPT_URI'];
  118. }
  119. $callbackURL = preg_replace('|/oauth[/]?.*$|', '/', $scriptUri);
  120. }
  121. $requestToken = $this->getRequestToken();
  122. $requestToken->callback = $callbackURL;
  123. $this->_saveReturnTo($callbackURL);
  124. $this->_addTokens("requestToken", $requestToken);
  125. $this->_authorize($requestToken, $callbackURL);
  126. }
  127. /**
  128. * Checks if the current user is already authorized.
  129. *
  130. * @return boolean TRUE if user is seen as currently authorized.
  131. * @since 0.1
  132. */
  133. function isAuthorized() {
  134. return ($this->_retrieveToken("accessToken")) ? TRUE: FALSE;
  135. }
  136. /**
  137. * Generates a request token before the authorization process is started.
  138. *
  139. * @return mixed FALSE if we are not able to get one or an OAuthConsumer object
  140. * @since 0.1
  141. */
  142. function getRequestToken() {
  143. $method = "GET";
  144. $req = OAuthRequest::from_consumer_and_token($this->_consumer,
  145. NULL,
  146. $method,
  147. $this->_requestTokenUrl,
  148. array());
  149. $req->sign_request($this->_encoder, $this->_consumer, NULL);
  150. $response = $this->_make_http_call($req, $method);
  151. if($response) {
  152. return $this->_parseOAuthToken($response);
  153. } else {
  154. return FALSE;
  155. }
  156. }
  157. /**
  158. * Checks the presence and state of a valid looking $this->_oAuthToken
  159. *
  160. * @return boolean
  161. * @since 0.1
  162. */
  163. function hasToken() {
  164. return ( $this->_oAuthToken !== false ) ? true : false;
  165. }
  166. /**
  167. * If we have an requestToken, try to get an accessToken
  168. *
  169. * @param string $OAuthToken The request token to get an access token for.
  170. * @return boolean TRUE is the authorization is complete.
  171. * @since 0.1
  172. */
  173. function completeAuthorization() {
  174. if ( $this->hasToken() && !$this->isAuthorized() ) {
  175. $oAuthToken = $this->_oAuthToken;
  176. $requestToken = $this->_retrieveToken("requestToken");
  177. if($requestToken != NULL && $requestToken->key === $oAuthToken) {
  178. $accessToken = $this->_getAccessToken($requestToken);
  179. if($accessToken) {
  180. $this->currentUser['login'] = trim(urldecode($_GET['login']));
  181. $this->currentUser['name'] = ( ! empty($_GET['name']) )
  182. ? trim(urldecode($_GET['name']))
  183. : $this->currentUser['login'];
  184. $this->_addTokens("accessToken", $accessToken);
  185. return TRUE;
  186. }
  187. }
  188. }
  189. return FALSE;
  190. }
  191. /**
  192. * Clears the cookie for the current user
  193. *
  194. * @since 0.1
  195. */
  196. function clear() {
  197. setcookie($this->_cookieHash, "", time() - 3600, '/', $this->_cookieDomain());
  198. }
  199. /**
  200. * Redirects to the initiating site/page.
  201. *
  202. * @since 0.1
  203. */
  204. function returnTo() {
  205. if(isset($this->currentUser["returnTo"]) && ! empty($this->currentUser["returnTo"]))
  206. header("Location: " . $this->currentUser["returnTo"]);
  207. }
  208. /**
  209. * Use a valid $requestToken to request an access token.
  210. *
  211. * @param OAuthConsumer A valid request token
  212. * @return mixed FALSE if the request is invalid or a OAuthConsumerObject.
  213. * @since 0.1
  214. */
  215. function _getAccessToken($requestToken) {
  216. $method = "GET";
  217. $req = OAuthRequest::from_consumer_and_token($this->_consumer,
  218. $requestToken,
  219. $method,
  220. $this->_requestAccessTokenURL,
  221. array());
  222. $req->sign_request($this->_encoder, $this->_consumer, $requestToken);
  223. $response = $this->_make_http_call($req, $method);
  224. if($response) {
  225. return $this->_parseOAuthToken($response);
  226. } else {
  227. return FALSE;
  228. }
  229. }
  230. /**
  231. * Return the header to make future compatible and authentified calls.
  232. *
  233. * @return mixed FALSE if not authorized or header string
  234. * @since 0.1
  235. */
  236. function getAccessHeader() {
  237. $accessToken = $this->_retrieveToken("accessToken");
  238. if($accessToken) {
  239. $method = "GET";
  240. $req = OAuthRequest::from_consumer_and_token($this->_consumer,
  241. $accessToken,
  242. $method,
  243. "http://api.praized.com/",
  244. array());
  245. $req->sign_request($this->_encoder, $this->_consumer, $accessToken);
  246. $accessHeaders = $req->to_header();
  247. // VENDOR OAUTH LIB OUTPUT CLEANUP
  248. $accessHeaders = preg_replace('/^"?Authorization:\s*(\S*)/', '\1', $accessHeaders);
  249. $accessHeaders = str_replace('OAuth realm="",', '', $accessHeaders);
  250. $accessHeaders = preg_replace('/^,(.*)/', '\1', $accessHeaders);
  251. return $accessHeaders;
  252. }
  253. return FALSE;
  254. }
  255. /**
  256. * Authorize the current tokens, then redirect the current user to
  257. * to the oauth provider (Praized) authorization page.
  258. *
  259. * @param OAuthConsumer Request token
  260. * @since 0.1
  261. */
  262. function _authorize($requestTokenConsumer, $callbackURL = NULL) {
  263. $queryString = "/?oauth_token=" . $requestTokenConsumer->key;
  264. if($callbackURL != NULL)
  265. $queryString .= "&oauth_callback=" . OAuthUtil::urlencode_RFC3986($callbackURL);
  266. $auth_url = $this->_authorizeURL . $queryString;
  267. if ( isset($_GET['i']) )
  268. $auth_url .= '&i=' . $_GET['i'];
  269. header("Location: $auth_url", false, 302);
  270. echo $auth_url;
  271. exit;
  272. }
  273. /**
  274. * Make HTTP requests to the oauth server
  275. *
  276. * @param OAuthRequest $request Request object
  277. * @param string $method Method to use for the call
  278. * @param array $parameters Any more parameters use for this call
  279. * @return mixed FALSE if not a 200 request or the response content
  280. * @since 0.1
  281. */
  282. function _make_http_call($request, $method, $parameters = array()) {
  283. @$this->_net->fetch($request->to_url());
  284. if(! strstr($this->_net->response_code, "200") ) {
  285. return FALSE;
  286. } else {
  287. return $this->_net->results;
  288. }
  289. }
  290. /**
  291. * Parse the string token and return an OAuthConsumer object.
  292. *
  293. * @param string $str query string to be parsed
  294. * @return OAuthConsumer
  295. * @since 0.1
  296. */
  297. function _parseOAuthToken($str) {
  298. parse_str($str, $parameters);
  299. return new OAuthConsumer($parameters["oauth_token"], $parameters["oauth_token_secret"]);
  300. }
  301. /**
  302. * Retrieve a specific token from the cookie.
  303. *
  304. * @param string $key the unique key
  305. * @return mixed OAuthConsumer for this specific key or FALSE if not found
  306. * @since 0.1
  307. */
  308. function _retrieveToken($key) {
  309. if( isset($this->currentUser[$key]) ) {
  310. $data = $this->currentUser[$key];
  311. return new OAuthConsumer($data["key"], $data["secret"], $data["callback"]);
  312. } else {
  313. return FALSE;
  314. }
  315. }
  316. /**
  317. * Save the a token to the cookie jar.
  318. *
  319. * @param string $key the unique key
  320. * @param OAuthConsumer $token Tokens to add
  321. * @since 0.1
  322. */
  323. function _addTokens($key, $token) {
  324. $this->currentUser[$key] = array(
  325. "key" => $token->key,
  326. "secret" => $token->secret,
  327. "callback" => $token->callback
  328. );
  329. $this->_saveTokens();
  330. }
  331. /**
  332. * Load the data for the current user
  333. *
  334. * @since 0.1
  335. */
  336. function _load() {
  337. $this->_cookieHash = "praized_user_" . $this->_generateCookieHash();
  338. if( ! isset($this->currentUser) ) {
  339. $this->currentUser = array();
  340. } else {
  341. $this->currentUser = unserialize(PraizedCipher::decrypt($_COOKIE[$this->_cookieHash], $this->_cookieHash));
  342. }
  343. }
  344. /**
  345. * Saves the fully qualified URL to return to
  346. *
  347. * @param string $url where to go after authorization?
  348. * @since 0.1
  349. */
  350. function _saveReturnTo($url = NULL) {
  351. if($url != NULL) {
  352. $this->currentUser["returnTo"] = $url;
  353. $this->_saveTokens();
  354. }
  355. }
  356. /**
  357. * Save the tokens to the cookie jar.
  358. *
  359. * @since 0.1
  360. */
  361. function _saveTokens() {
  362. setcookie($this->_cookieHash, PraizedCipher::encrypt(serialize($this->currentUser), $this->_cookieHash), time() + $this->_expirationTime, "/", $this->_cookieDomain());
  363. }
  364. /**
  365. * Generate the cookie hash for a specific user
  366. * this hash is use to get the correct cookie key.
  367. *
  368. * @return string the complete hash for the current session.
  369. * @since 0.1
  370. */
  371. function _generateCookieHash() {
  372. $secret = $this->_consumerKey . $this->_consumerSecret . $_SERVER['REMOTE_ADDR'];
  373. if ( function_exists('sha1') )
  374. return sha1($secret);
  375. else
  376. return md5($secret);
  377. }
  378. }
  379. }
  380. ?>