PageRenderTime 51ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Yahoo.inc

https://github.com/mdawaffe/yos-social-php
Pascal | 1942 lines | 943 code | 188 blank | 811 comment | 153 complexity | 8ac2f39785a13b37fb82b19a8aca130d MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * YOS PHP SDK for accessing social and data apis at Yahoo!
  4. *
  5. * @package yos-php-sdk
  6. * @author Yahoo! Developer Network
  7. * @example http://developer.yahoo.com/social/sdk/php/
  8. *
  9. * @copyright Copyright (c) 2009 Yahoo! Inc. All rights reserved.
  10. * @license
  11. *
  12. * The copyrights embodied in the content of this file are licensed under the
  13. * BSD (revised) open source license.
  14. *
  15. * Redistribution and use of this software in source and binary forms, with
  16. * or without modification, are permitted provided that the following
  17. * conditions are met:
  18. *
  19. * * Redistributions of source code must retain the above
  20. * copyright notice, this list of conditions and the
  21. * following disclaimer.
  22. *
  23. * * Redistributions in binary form must reproduce the above
  24. * copyright notice, this list of conditions and the
  25. * following disclaimer in the documentation and/or other
  26. * materials provided with the distribution.
  27. *
  28. * * Neither the name of Yahoo! Inc. nor the names of its
  29. * contributors may be used to endorse or promote products
  30. * derived from this software without specific prior
  31. * written permission of Yahoo! Inc.
  32. *
  33. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  34. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  35. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  36. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  37. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  38. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  39. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  40. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  41. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  42. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. *
  44. * Please see the Yahoo! Developer Network forums for support: http://developer.yahoo.net/forum/
  45. *
  46. * Documentation: http://developer.yahoo.com/social/sdk/php/
  47. */
  48. // Use OAuthConsumer as a test to see if any other instances of OAuth.php may
  49. // have been included. require_once() won't catch situations where multiple
  50. // copies of OAuth.php are included by different parts of an application.
  51. if(!class_exists("OAuthConsumer")) {
  52. require_once("OAuth.php");
  53. }
  54. define("OAUTH_PARAMS_IN_HEADERS", "HEADERS");
  55. define("OAUTH_PARAMS_IN_POST_BODY", "POSTBODY");
  56. define("OAUTH_SIGNATURE_PLAINTEXT", "PLAINTEXT");
  57. define("OAUTH_SIGNATURE_HMAC_SHA1", "HMAC_SHA1");
  58. define("YAHOO_YAP_SESSION_TYPE", "YAHOO_YAP_SESSION_TYPE");
  59. define("YAHOO_OAUTH_RT_SESSION_TYPE", "YAHOO_OAUTH_RT_SESSION_TYPE");
  60. define("YAHOO_OAUTH_AT_SESSION_TYPE", "YAHOO_OAUTH_AT_SESSION_TYPE");
  61. global $YahooConfig, $GLOBAL_YAHOO_SESSION, $GLOBAL_YAHOO_LOGGER_DEBUG, $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
  62. $YahooConfig = array(
  63. "SOCIAL_WS_HOSTNAME" => "social.yahooapis.com",
  64. "PRESENCE_WS_HOSTNAME" => "social.yahooapis.com",
  65. "UPDATES_WS_HOSTNAME" => "social.yahooapis.com",
  66. "QUERY_WS_HOSTNAME" => "query.yahooapis.com",
  67. "OAUTH_HOSTNAME" => "api.login.yahoo.com",
  68. "YAP_WS_HOSTNAME" => "appstore.apps.yahooapis.com"
  69. );
  70. $GLOBAL_YAHOO_SESSION = NULL;
  71. $GLOBAL_YAHOO_LOGGER_DEBUG = false;
  72. $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION = "LOG";
  73. class YahooUtil {
  74. function current_url() {
  75. return sprintf("http://%s%s",$_SERVER["HTTP_HOST"],$_SERVER["REQUEST_URI"]);
  76. }
  77. function verify_signature($consumer, $token=NULL, $oauth_signature) {
  78. $oauth_signature_method = new OAuthSignatureMethod_HMAC_SHA1();
  79. $oauth_consumer = new OAuthConsumer($consumer->key, $consumer->secret);
  80. $oauth_token = ($token) ? new OAuthToken($token->key, $token->secret) : NULL;
  81. $oauth_request = OAuthRequest::from_request();
  82. $ok = $oauth_signature_method->check_signature($oauth_request, $oauth_consumer, $oauth_token, $oauth_signature);
  83. return $ok;
  84. }
  85. function is_yap_canvas() {
  86. return (isset($_POST['yap_appid'])
  87. && isset($_POST['yap_view']));
  88. }
  89. function is_response_error($response) {
  90. return (is_null($response) || $response["code"] != 200);
  91. }
  92. }
  93. class YahooException extends Exception {
  94. }
  95. /**
  96. * Logging wrapper for the Yahoo objects.
  97. *
  98. * @brief Logging wrapper for the Yahoo objects.
  99. */
  100. class YahooLogger {
  101. /**
  102. * Log a message at the debug level.
  103. *
  104. * @param $message The message to log.
  105. */
  106. function debug($message, $object = NULL) {
  107. global $GLOBAL_YAHOO_LOGGER_DEBUG;
  108. global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
  109. if($GLOBAL_YAHOO_LOGGER_DEBUG) {
  110. if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "CONSOLE") {
  111. print("DEBUG - $message\n");
  112. if(!is_null($object)) {
  113. print("DEBUG OBJECT - " . print_r($object, true) . "\n");
  114. }
  115. }
  116. else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "LOG") {
  117. error_log("DEBUG - $message");
  118. if(!is_null($object)) {
  119. error_log("DEBUG OBJECT - " . print_r($object, true));
  120. }
  121. }
  122. }
  123. }
  124. /**
  125. * Log a message at the info level.
  126. *
  127. * @param $message The message to log.
  128. */
  129. function info($message, $object = NULL) {
  130. global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
  131. if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "CONSOLE") {
  132. print("INFO - $message\n");
  133. if(!is_null($object)) {
  134. print("INFO OBJECT - " . print_r($object, true) . "\n");
  135. }
  136. }
  137. else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "LOG") {
  138. error_log("INFO - $message");
  139. if(!is_null($object)) {
  140. error_log("INFO OBJECT - " . print_r($object, true));
  141. }
  142. }
  143. }
  144. /**
  145. * Log a message at the error level.
  146. *
  147. * @param $message The message to log.
  148. */
  149. function error($message, $object = NULL) {
  150. global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
  151. if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "CONSOLE") {
  152. print("ERROR - $message\n");
  153. if(!is_null($object)) {
  154. print("ERROR OBJECT - " . print_r($object, true) . "\n");
  155. }
  156. }
  157. else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "LOG") {
  158. error_log("ERROR - $message");
  159. if(!is_null($object)) {
  160. error_log("ERROR OBJECT - " . print_r($object, true));
  161. }
  162. }
  163. }
  164. /**
  165. * Enables/disables session debugging.
  166. *
  167. * @param $debug Boolean to enable/disable debugging.
  168. */
  169. function setDebug($debug) {
  170. global $GLOBAL_YAHOO_LOGGER_DEBUG;
  171. $GLOBAL_YAHOO_LOGGER_DEBUG = (bool) $debug;
  172. }
  173. /**
  174. * Allows callers to configure where debugging output is sent.
  175. *
  176. * @param $destination "LOG" to use error_log, "CONSOLE" to use printf,
  177. * "NULL" to disable all logging output.
  178. * @return boolean True on success, false on failure.
  179. */
  180. function setDebugDestination($destination) {
  181. global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
  182. if($destination == "LOG" || $destination == "CONSOLE" ||
  183. $destination == "NULL") {
  184. $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION = $destination;
  185. return true;
  186. }
  187. else {
  188. return false;
  189. }
  190. }
  191. }
  192. /**
  193. * Defines a session between an application and the Yahoo! platform.
  194. *
  195. * @brief Defines a session between an application and the Yahoo! platform.
  196. */
  197. class YahooSession {
  198. /**
  199. * @private
  200. */
  201. var $guid = NULL;
  202. /**
  203. * @private
  204. */
  205. var $consumer = NULL;
  206. /**
  207. * @private
  208. */
  209. var $accessToken = NULL;
  210. /**
  211. * @private
  212. */
  213. var $applicationId = NULL;
  214. /**
  215. * @private
  216. */
  217. var $client = NULL;
  218. /**
  219. * @private
  220. */
  221. var $application = NULL;
  222. /**
  223. * @private
  224. */
  225. function YahooSession($consumer, $accessToken, $applicationId)
  226. {
  227. $this->consumer = $consumer;
  228. $this->accessToken = $accessToken;
  229. $this->applicationId = $applicationId;
  230. $this->guid = $accessToken->guid;
  231. $this->client = new OAuthClient($consumer, $accessToken);
  232. $this->application = new YahooApplication($consumer->key, $consumer->secret);
  233. $this->application->token = $this->accessToken;
  234. }
  235. /**
  236. * @private
  237. */
  238. function getConsumer() {
  239. return $this->consumer;
  240. }
  241. /**
  242. * @private
  243. */
  244. function getAccessToken() {
  245. return $this->accessToken;
  246. }
  247. /**
  248. * @private
  249. */
  250. function getApplicationId() {
  251. return $this->applicationId;
  252. }
  253. /**
  254. * Gets the currently sessioned user.
  255. *
  256. * @return YahooUser The currently sessioned YahooUser.
  257. */
  258. function getSessionedUser() {
  259. return new YahooUser($this, $this->guid, true);
  260. }
  261. /**
  262. * Gets the user who owns the application install.
  263. * Only valid when viewed in YAP, otherwise will default
  264. * to the logged-in user.
  265. *
  266. * @return YahooUser The currently sessioned YahooUser.
  267. */
  268. function getOwner() {
  269. if(isset($this->accessToken->owner)) {
  270. return $this->getUser($this->accessToken->owner);
  271. }
  272. else {
  273. return $this->getSessionedUser();
  274. }
  275. }
  276. /**
  277. * Gets the user indicated by the GUID given.
  278. *
  279. * @param $guid The GUID of the user to get.
  280. * @return YahooUser The user indicated by the GUID given.
  281. */
  282. function getUser($guid) {
  283. return new YahooUser($this, $guid, isset($this->guid) && ($guid == $this->guid));
  284. }
  285. /**
  286. * Executes the given YQL query.
  287. *
  288. * @param $yql The query to execute.
  289. * @param $env A URL to a YQL environment file.
  290. * @return The response or NULL if the request fails..
  291. */
  292. function query($yql, $env=NULL) {
  293. return $this->application->query($yql, $env);
  294. }
  295. /**
  296. * @private
  297. */
  298. function redirectForAuthorization($consumerKey, $consumerSecret, $callback = NULL, $sessionStore = NULL) {
  299. $url = YahooSession::createAuthorizationUrl($consumerKey, $consumerSecret, $callback, $sessionStore);
  300. if(!is_null($url)) {
  301. header(sprintf("Location: %s", $url));
  302. exit();
  303. }
  304. else {
  305. // TODO: throw a YahooException
  306. YahooLogger::error("Failed to create authorization URLs");
  307. }
  308. }
  309. /**
  310. * Destroys the current session, effectively logging out the current
  311. * user.
  312. *
  313. * @param $sessionStore The session store implementation to clear. See
  314. * YahooSessionStore for more information. If no
  315. * session store is provided, clearSession will
  316. * instantiate a NativeSessionStore and use that.
  317. */
  318. function clearSession($sessionStore = NULL) {
  319. global $GLOBAL_YAHOO_SESSION;
  320. if(is_null($sessionStore)) {
  321. $sessionStore = new NativeSessionStore();
  322. }
  323. $sessionStore->clearRequestToken();
  324. $sessionStore->clearAccessToken();
  325. $GLOBAL_YAHOO_SESSION = NULL;
  326. }
  327. /**
  328. * Checks to see if there is a session in this PHP page request.
  329. * Doesn't cause any redirects for the user to log in, for that
  330. * you should call requireSession().
  331. *
  332. * @param $consumerKey The OAuth consumer key.
  333. * @param $consumerSecret The OAuth consumer key secret.
  334. * @param $applicationId The application ID, optional.
  335. * @param $sessionStore The session store implementation to use. See
  336. * YahooSessionStore for more information. If no
  337. * session store is provided, clearSession will
  338. * instantiate a NativeSessionStore and use that.
  339. * @return boolean True if a session is present, false otherwise.
  340. */
  341. function hasSession($consumerKey, $consumerSecret, $applicationId = NULL, $sessionStore = NULL, $verifier = NULL)
  342. {
  343. if(is_null($sessionStore)) {
  344. $sessionStore = new NativeSessionStore();
  345. }
  346. if(is_null($verifier) && array_key_exists("oauth_verifier", $_GET)) {
  347. $verifier = $_GET["oauth_verifier"];
  348. }
  349. $session = YahooSession::initSession($consumerKey, $consumerSecret, $applicationId, FALSE, NULL, $sessionStore, $verifier);
  350. return !is_null($session);
  351. }
  352. /**
  353. * Requires that there be a session in this PHP page request. Generates
  354. * a redirect for the user to log in, if necessary. You must call
  355. * requireSession() before any data is sent back to the user in order
  356. * for the redirect to work.
  357. *
  358. * @param $consumerKey The OAuth consumer key.
  359. * @param $consumerSecret The OAuth consumer key secret.
  360. * @param $applicationId The application ID, optional.
  361. * @param $callback The callback URL to redirect the user to after
  362. * they verify the application access. If no callback
  363. * is provided, the current page URL will be used.
  364. * @param $sessionStore The session store implementation to use. See
  365. * YahooSessionStore for more information. If no
  366. * session store is provided, clearSession will
  367. * instantiate a NativeSessionStore and use that.
  368. * @param $verifier The oauth_verifier returned by the OAuth servers
  369. * after authorization. Passing NULL indicates that
  370. * authorization was completed previously or that
  371. * requireSession() should look for oauth_verifier in
  372. * the $_GET superglobal.
  373. * @return YahooSession The current session or NULL if a session cannot
  374. * be established.
  375. */
  376. function requireSession($consumerKey, $consumerSecret, $applicationId = NULL,
  377. $callback = NULL, $sessionStore = NULL, $verifier = NULL)
  378. {
  379. if(is_null($sessionStore)) {
  380. $sessionStore = new NativeSessionStore();
  381. }
  382. if(is_null($verifier) && array_key_exists("oauth_verifier", $_GET)) {
  383. $verifier = $_GET["oauth_verifier"];
  384. }
  385. return YahooSession::initSession($consumerKey, $consumerSecret, $applicationId, TRUE, $callback, $sessionStore, $verifier);
  386. }
  387. /**
  388. * Creates authorization URLs, allowing applications to manage their
  389. * user experience when the user needs to be sent to Yahoo! to authorize
  390. * the application to access their account.
  391. *
  392. * @param $consumerKey The OAuth consumer key.
  393. * @param $consumerSecret The OAuth consumer key secret.
  394. * @param $callback The callback URL to redirect the user to after
  395. * they verify the application access. If no callback
  396. * is provided, the current page URL will be used.
  397. * Use the "oob" callback for desktop clients or for
  398. * web clients where no callback should be used.
  399. * @param $sessionStore The session store implementation to use. See
  400. * YahooSessionStore for more information. If no
  401. * session store is provided, createAuthorizationUrl
  402. * will instantiate a NativeSessionStore and use that.
  403. * @return stdclass A PHP object with two properties: "urlWithCallback"
  404. * and "urlWithoutCallback". This allows the application
  405. * to mix and match authorizations that do and don't
  406. * have callbacks in the URLs. urlWithoutCallback is
  407. * useful for JavaScript popup windows while
  408. * urlWithCallback is useful for normal <a href>
  409. * tags.
  410. */
  411. function createAuthorizationUrl($consumerKey, $consumerSecret, $callback = NULL, $sessionStore = NULL)
  412. {
  413. global $GLOBAL_YAHOO_SESSION;
  414. if(is_null($sessionStore)) {
  415. $sessionStore = new NativeSessionStore();
  416. }
  417. // No callback URL supplied. Build one from the current URL.
  418. if(is_null($callback)) {
  419. $callback = YahooUtil::current_url();
  420. }
  421. // Redirect the user to log in.
  422. $requestToken = YahooAuthorization::getRequestToken($consumerKey, $consumerSecret, $callback);
  423. if(!is_null($requestToken))
  424. {
  425. $sessionStore->storeRequestToken($requestToken);
  426. $url = YahooAuthorization::createAuthorizationUrl($requestToken, $callback);
  427. return $url;
  428. }
  429. else
  430. {
  431. YahooLogger::error("Failed to create request token");
  432. $GLOBAL_YAHOO_SESSION = NULL;
  433. return null;
  434. }
  435. }
  436. function initSessionFromYAP($consumerKey, $consumerSecret, $appid)
  437. {
  438. global $GLOBAL_YAHOO_SESSION;
  439. if(!YahooUtil::is_yap_canvas()) {
  440. // TODO: throw a YahooException
  441. return NULL;
  442. }
  443. $consumer = new stdclass();
  444. $consumer->key = $consumerKey;
  445. $consumer->secret = $consumerSecret;
  446. if ($consumer->key != $_POST["yap_consumer_key"]) {
  447. error_log("Consumer key from YAP does not match provided key.");
  448. // TODO: throw a YahooException
  449. $GLOBAL_YAHOO_SESSION = NULL;
  450. return;
  451. }
  452. $signature_ok = YahooUtil::verify_signature($consumer, null, $_REQUEST['oauth_signature']);
  453. if (!$signature_ok)
  454. {
  455. error_log("Signature from YAP failed.");
  456. // TODO: throw a YahooException
  457. $GLOBAL_YAHOO_SESSION = NULL;
  458. return;
  459. }
  460. $accessToken = new stdclass();
  461. $accessToken->key = $_POST["yap_viewer_access_token"];
  462. $accessToken->secret = $_POST["yap_viewer_access_token_secret"];
  463. $accessToken->guid = $_POST["yap_viewer_guid"];
  464. $accessToken->owner = $_POST["yap_owner_guid"];
  465. $accessToken->tokenExpires = -1;
  466. //YahooLogger::debug("YAP AT: " . $accessToken->key . " ATS: " . $accessToken->secret);
  467. $applicationId = $_POST["yap_appid"];
  468. $GLOBAL_YAHOO_SESSION = new YahooSession($consumer, $accessToken, $applicationId);
  469. return $GLOBAL_YAHOO_SESSION;
  470. }
  471. /**
  472. * @private
  473. */
  474. function initSession($consumerKey, $consumerSecret, $applicationId, $redirect, $callback, $sessionStore, $verifier)
  475. {
  476. global $GLOBAL_YAHOO_SESSION;
  477. if(!is_null($GLOBAL_YAHOO_SESSION)) {
  478. return $GLOBAL_YAHOO_SESSION;
  479. }
  480. $consumer = new stdclass();
  481. $consumer->key = $consumerKey;
  482. $consumer->secret = $consumerSecret;
  483. $checkSession = YahooSession::checkSession($type, $sessionStore);
  484. if(!$checkSession) {
  485. // There doesn't appear to be a session here.
  486. if($redirect) {
  487. $GLOBAL_YAHOO_SESSION = NULL;
  488. YahooSession::redirectForAuthorization($consumerKey, $consumerSecret, $callback, $sessionStore);
  489. }
  490. else {
  491. // Don't redirect the user, just inform the caller that
  492. // no session is present.
  493. // TODO: throw a YahooException
  494. $GLOBAL_YAHOO_SESSION = NULL;
  495. }
  496. }
  497. else if($type == YAHOO_OAUTH_AT_SESSION_TYPE) {
  498. // Found an OAuth Access Token session.
  499. $accessToken = $sessionStore->fetchAccessToken();
  500. $now = time();
  501. YahooLogger::debug("OAuth AT: " . $accessToken->key . " ATS: ". $accessToken->secret);
  502. if($accessToken->consumer != $consumerKey)
  503. {
  504. YahooLogger::error("Consumer key for token does not match the defined Consumer Key. The Consumer Key has probably changed since the user last authorized the application.");
  505. YahooSession::clearSession($sessionStore);
  506. if($redirect) {
  507. YahooSession::redirectForAuthorization($consumerKey, $consumerSecret, $callback, $sessionStore);
  508. }
  509. }
  510. if($accessToken->tokenExpires >= 0) {
  511. YahooLogger::debug('AT Expires in: ' . ($accessToken->tokenExpires - $now));
  512. }
  513. if(($accessToken->tokenExpires >= 0) && ($accessToken->tokenExpires - $now) < 30) {
  514. // The access token will expire in less than 30 seconds or
  515. // it may have expired already. Try to get a new one.
  516. YahooSession::accessTokenExpired($accessToken, $consumer, $applicationId, $sessionStore);
  517. }
  518. else {
  519. // The access token is still good for a little while, continue using it.
  520. $GLOBAL_YAHOO_SESSION = new YahooSession($consumer, $accessToken, $applicationId);
  521. }
  522. }
  523. else if($type == YAHOO_OAUTH_RT_SESSION_TYPE)
  524. {
  525. if(is_null($verifier)) {
  526. // Can't proceed without the oauth_verifier, treat it as
  527. // though there's no session present.
  528. $sessionStore->clearRequestToken();
  529. // TODO: throw a YahooException
  530. $GLOBAL_YAHOO_SESSION = NULL;
  531. }
  532. // Found an OAuth Request Token session.
  533. $requestToken = $sessionStore->fetchRequestToken();
  534. $accessToken = YahooAuthorization::getAccessToken($consumerKey, $consumerSecret, $requestToken, $verifier);
  535. if(!is_null($accessToken)) {
  536. $sessionStore->storeAccessToken($accessToken);
  537. $sessionStore->clearRequestToken();
  538. $GLOBAL_YAHOO_SESSION = new YahooSession($consumer, $accessToken, $applicationId);
  539. }
  540. else if($redirect)
  541. {
  542. // TODO: Add redirect counter so this doesn't happen over and over and over when Yahoo! is completely busted.
  543. // The fetch for the access token failed. Generate a new
  544. // request token and try again.
  545. $GLOBAL_YAHOO_SESSION = NULL;
  546. YahooSession::redirectForAuthorization($consumerKey, $consumerSecret, $callback, $sessionStore);
  547. }
  548. else
  549. {
  550. // Don't redirect the user, just inform the caller that
  551. // no session is present.
  552. $sessionStore->clearRequestToken();
  553. $GLOBAL_YAHOO_SESSION = NULL;
  554. }
  555. }
  556. else if($type == YAHOO_YAP_SESSION_TYPE)
  557. {
  558. // Found a YAP session.
  559. $GLOBAL_YAHOO_SESSION = YahooSession::initSessionFromYAP($consumerKey, $consumerSecret, $applicationId);
  560. }
  561. else
  562. {
  563. trigger_error("Unknown session type found", E_USER_ERROR);
  564. // TODO: throw a YahooException
  565. $GLOBAL_YAHOO_SESSION = NULL;
  566. }
  567. return $GLOBAL_YAHOO_SESSION;
  568. }
  569. /**
  570. * @private
  571. */
  572. function accessTokenExpired($accessToken, $consumer, $applicationId, $sessionStore)
  573. {
  574. global $GLOBAL_YAHOO_SESSION;
  575. $now = time();
  576. if(($accessToken->handleExpires === -1) ||
  577. ($now < $accessToken->handleExpires)) {
  578. // Either the access session handle doesn't expire
  579. // or it hasn't expired yet. Get a new access token.
  580. $newAccessToken = YahooAuthorization::getAccessToken(
  581. $consumer->key, $consumer->secret, $accessToken, null);
  582. if(is_null($newAccessToken)) {
  583. YahooLogger::error("Failed to fetch access token");
  584. $GLOBAL_YAHOO_SESSION = NULL;
  585. }
  586. $sessionStore->storeAccessToken($newAccessToken);
  587. YahooLogger::debug("Got new AT/ATS from ASH!");
  588. YahooLogger::debug("OAuth AT: " . $newAccessToken->key . " ATS: ". $newAccessToken->secret);
  589. $GLOBAL_YAHOO_SESSION = new YahooSession(
  590. $consumer, $newAccessToken, $applicationId);
  591. }
  592. else
  593. {
  594. // The access token is expired and we don't have
  595. // a sufficient access session handle to renew
  596. // the access token. Clear the cookie and redirect
  597. // to authorization point or return a NULL session.
  598. $sessionStore->clearAccessToken();
  599. if ($redirect) {
  600. YahooSession::redirectForAuthorization($consumer->key, $consumer->secret, $callback, $sessionStore);
  601. } else {
  602. $GLOBAL_YAHOO_SESSION = NULL;
  603. }
  604. }
  605. }
  606. /**
  607. * @private
  608. *
  609. * Checks to see if the current PHP page request has a session and, if so,
  610. * indicates what type of session is present.
  611. *
  612. * @param[out] $sessionType The session type present, if any.
  613. * @return boolean True if a session is present, false otherwise.
  614. */
  615. function checkSession(&$sessionType, $sessionStore) {
  616. if(array_key_exists("yap_appid", $_POST)) {
  617. $sessionType = YAHOO_YAP_SESSION_TYPE;
  618. return true;
  619. }
  620. else if($sessionStore->hasAccessToken()) {
  621. $sessionType = YAHOO_OAUTH_AT_SESSION_TYPE;
  622. return true;
  623. }
  624. else if($sessionStore->hasRequestToken()) {
  625. $sessionType = YAHOO_OAUTH_RT_SESSION_TYPE;
  626. return true;
  627. }
  628. else {
  629. return false;
  630. }
  631. }
  632. }
  633. /**
  634. * Represents a Yahoo! application.
  635. *
  636. * @brief Represents a Yahoo! application.
  637. */
  638. class YahooApplication {
  639. /**
  640. * @private
  641. */
  642. var $consumer = NULL;
  643. /**
  644. * @private
  645. * @deprecated
  646. */
  647. var $client = NULL;
  648. /**
  649. * @private
  650. */
  651. var $token = NULL;
  652. /**
  653. * Constructs a new YahooApplication object.
  654. *
  655. * @param $consumerKey The consumer key of the application.
  656. * @param $consumerKeySecret The consumer key secret of the application.
  657. */
  658. function YahooApplication($consumerKey, $consumerKeySecret) {
  659. $this->consumer = new OAuthConsumer($consumerKey, $consumerKeySecret);
  660. }
  661. /**
  662. * Sets the small view for the user given by the GUID.
  663. *
  664. * @param $guid The GUID of the user to set the small view for.
  665. * @param $content The content to set the small view to.
  666. * @return True on success, false otherwise.
  667. */
  668. function setSmallView($guid, $content) {
  669. global $YahooConfig;
  670. $client = new OAuthClient($this->consumer, NULL);
  671. $request_url = sprintf("http://%s/v1/cache/view/small/%s", $YahooConfig["YAP_WS_HOSTNAME"], urlencode($guid));
  672. $response = $client->put($request_url, "text/html;charset=utf-8", $content);
  673. return !(YahooUtil::is_response_error($response));
  674. }
  675. /**
  676. * Executes the given YQL query.
  677. *
  678. * @param $yql The query to execute.
  679. * @param $env A URL to a YQL environment file.
  680. * @return The response or NULL if the request fails..
  681. */
  682. function query($yql, $env=NULL)
  683. {
  684. global $YahooConfig;
  685. $client = new OAuthClient($this->consumer, $this->token);
  686. $request_url = sprintf("http://%s/v1/yql",$YahooConfig["QUERY_WS_HOSTNAME"]);
  687. $params = array('q' => $yql, 'format' => 'json', 'env' => 'http://datatables.org/alltables.env');
  688. if(!is_null($env)) {
  689. $params['env'] = $env;
  690. }
  691. $response = $client->get($request_url, $params, 30);
  692. if(YahooUtil::is_response_error($response)) {
  693. return NULL;
  694. }
  695. $resultSet = json_decode($response["responseBody"]);
  696. return $resultSet;
  697. }
  698. }
  699. /**
  700. * Represents a Yahoo! user.
  701. *
  702. * @brief Represents a Yahoo! user.
  703. */
  704. class YahooUser {
  705. /**
  706. * @private
  707. */
  708. var $session = NULL;
  709. /**
  710. * @private
  711. */
  712. var $guid = NULL;
  713. /**
  714. * @private
  715. */
  716. var $sessioned = false;
  717. /**
  718. * @private
  719. */
  720. var $client = NULL;
  721. /**
  722. * @private
  723. */
  724. function YahooUser($session, $guid, $sessioned) {
  725. $this->session = $session;
  726. $this->client = $session->client;
  727. $this->guid = $guid;
  728. $this->sessioned = $sessioned;
  729. }
  730. /**
  731. * Gets the user's status message.
  732. *
  733. * @return The status of the user or NULL if the fetch fails.
  734. */
  735. function getStatus() {
  736. global $YahooConfig;
  737. $request_url = sprintf("http://%s/v1/user/%s/profile/status",
  738. $YahooConfig["SOCIAL_WS_HOSTNAME"],urlencode($this->guid));
  739. $response = $this->client->get($request_url);
  740. if(is_null($response)) {
  741. return NULL;
  742. }
  743. else if($response["code"] == 404) {
  744. // No presence is set, return an empty presence.
  745. $status = new stdclass();
  746. $status->message = "";
  747. $status->lastStatusModified = NULL;
  748. $status->uri = NULL;
  749. return $status;
  750. }
  751. else if($response["code"] != 200) {
  752. return NULL;
  753. }
  754. else {
  755. $rsp = json_decode($response["responseBody"]);
  756. return $rsp->status;
  757. }
  758. }
  759. /**
  760. * Sets the user's status message.
  761. *
  762. * @param $message The new status message for the user.
  763. * @return The status message on success, NULL on failure.
  764. */
  765. function setStatus($message) {
  766. global $YahooConfig;
  767. if(!$this->sessioned) {
  768. YahooLogger::error("Can't set the status of an unsessioned user");
  769. return NULL;
  770. }
  771. $message = array("message" => $message);
  772. $status = array("status" => $message);
  773. $status_json = json_encode($status);
  774. $request_url = sprintf("http://%s/v1/user/%s/profile/status", $YahooConfig["SOCIAL_WS_HOSTNAME"], $this->guid);
  775. $response = $this->client->put($request_url, "application/json", $status_json);
  776. if(YahooUtil::is_response_error($response)) {
  777. return NULL;
  778. }
  779. $status = json_decode($response["responseBody"]);
  780. return $status;
  781. }
  782. /**
  783. * Gets the updates for the current user.
  784. *
  785. * @param $start The starting offset to list updates from. (default = 0)
  786. * @param $count The number of updates to request. (default = 10)
  787. * @return An array of updates for the current user.
  788. */
  789. function getUpdates($start = 0, $count = 10) {
  790. $parameters = array("start" => $start, "count" => $count, "transform" => '(sort "pubDate" numeric descending (all))');
  791. $updates = $this->get_resource("updates", $parameters);
  792. return $updates->updates;
  793. }
  794. /**
  795. * Gets the updates for the connections of the current user.
  796. *
  797. * @param $start The starting offset to list updates from.
  798. * @param $count The number of updates to request.
  799. * @return A list of updates for the connections of the current user.
  800. */
  801. function getConnectionUpdates($start = 0, $count = 10) {
  802. $parameters = array("start" => $start, "count" => $count, "transform" => '(sort "pubDate" numeric descending (all))');
  803. $updates = $this->get_resource("updates/connections", $parameters);
  804. return $updates->updates;
  805. }
  806. /**
  807. * Inserts an update for the current user.
  808. *
  809. * @param $suid Identifier that globally unique for a given
  810. * collectionId within producing source.
  811. * @param $title Title for the update.
  812. * @param $link Link back to the cause of the event.
  813. * @param $description Descriptive text associated with the update,
  814. * optional.
  815. * @param $date The date of the update event, optional, defaults to now.
  816. */
  817. function insertUpdate($suid, $title, $link, $description="", $date=NULL) {
  818. global $YahooConfig;
  819. // Make sure this YahooUser is sessioned.
  820. if(!$this->sessioned) {
  821. YahooLogger::error("Can't insert updates for an unsessioned user");
  822. return NULL;
  823. }
  824. if (is_null($date)) {
  825. $date = time();
  826. }
  827. // Make sure an application ID was given.
  828. $appid = $this->session->getApplicationId();
  829. if(empty($appid)) {
  830. YahooLogger::error("No application ID given, can't insert update");
  831. return NULL;
  832. }
  833. $source = sprintf("APP.%s", $appid);
  834. $update = array(
  835. "collectionID" => $this->guid,
  836. "collectionType" => "guid",
  837. "class" => "app",
  838. "source" => $source,
  839. "type" => 'appActivity',
  840. "suid" => $suid,
  841. "title" => $title,
  842. "description" => $description,
  843. "link" => $link,
  844. "pubDate" => (string)$date
  845. );
  846. $update_body = array("updates" => array($update));
  847. $update_body_json = json_encode($update_body);
  848. $request_url = sprintf("http://%s/v1/user/%s/updates/%s/%s", $YahooConfig["UPDATES_WS_HOSTNAME"], $this->guid, $source, urlencode($suid));
  849. $response = $this->client->put($request_url, "application/json", $update_body_json);
  850. if(YahooUtil::is_response_error($response)) {
  851. return NULL;
  852. }
  853. return TRUE;
  854. }
  855. /**
  856. * Deletes the update of the given SUID. Only allows deleting updates
  857. * that were inserted by your own application. You won't be able to
  858. * delete updates from other applications.
  859. *
  860. * @param $suid The SUID of the update to be deleted.
  861. * @return boolean True on success, false on failure.
  862. */
  863. function deleteUpdate($suid) {
  864. global $YahooConfig;
  865. // Make sure this YahooUser is sessioned.
  866. if(!$this->sessioned) {
  867. YahooLogger::error("Can't delete updates for an unsessioned user");
  868. return FALSE;
  869. }
  870. // Make sure an application ID was given.
  871. $appid = $this->session->getApplicationId();
  872. if( empty($appid) ) {
  873. YahooLogger::error("No application ID given, can't delete update");
  874. return FALSE;
  875. }
  876. $source = sprintf("APP.%s", $appid);
  877. $request_url = sprintf("http://%s/v1/user/%s/updates/%s/%s", $YahooConfig["UPDATES_WS_HOSTNAME"], $this->guid, $source, urlencode($suid));
  878. $response = $this->client->delete($request_url);
  879. if(YahooUtil::is_response_error($response)) {
  880. return NULL;
  881. }
  882. return TRUE;
  883. }
  884. /**
  885. * Loads the extended profile of the current user.
  886. *
  887. * @return The extended profile of the current user.
  888. */
  889. function getProfile() {
  890. global $YahooConfig;
  891. $profile = $this->get_resource("profile");
  892. return $profile->profile;
  893. }
  894. /**
  895. * Gets a list of connections for the current user.
  896. *
  897. * @param[in,out] $start The starting offset.
  898. * @param[in,out] $count The number of connections to fetch.
  899. * @param[out] $total The total number of contacts available.
  900. * @return List of connections for the current user.
  901. */
  902. function getConnections(&$start, &$count, &$total) {
  903. global $YahooConfig;
  904. $parameters = array("view" => "usercard", "start" => $start, "count" => $count);
  905. $connections = $this->get_resource("connections",$parameters);
  906. $start = $connections->connections->start;
  907. $count = $connections->connections->count;
  908. $total = $connections->connections->total;
  909. return $connections->connections->connection;
  910. }
  911. /**
  912. * Gets a list of contacts for the current user.
  913. *
  914. * @param $start The starting offset.
  915. * @param $count The number of contacts to fetch.
  916. * @return List of contacts for the current user.
  917. */
  918. function getContacts($start = 0, $count = 10) {
  919. global $YahooConfig;
  920. if(!$this->sessioned) {
  921. YahooLogger::error("Can't get contacts for an unsessioned user");
  922. return NULL;
  923. }
  924. $parameters = array("view" => "tinyusercard", "start" => $start, "count" => $count);
  925. $contacts = $this->get_resource("contacts",$parameters);
  926. return $contacts;
  927. }
  928. /**
  929. * Sets the small view for the current user.
  930. *
  931. * @param $content The content to set the small view to.
  932. * @return True on success, false otherwise.
  933. */
  934. function setSmallView($content) {
  935. return $this->session->application->setSmallView($this->guid, $content);
  936. }
  937. /**
  938. * @private
  939. */
  940. function get_resource($resource, $parameters=array())
  941. {
  942. global $YahooConfig;
  943. $request_url = sprintf("http://%s/v1/user/%s/%s",
  944. $YahooConfig["SOCIAL_WS_HOSTNAME"], urlencode($this->guid), $resource);
  945. $response = $this->client->get($request_url,$parameters);
  946. if(YahooUtil::is_response_error($response)) {
  947. return NULL;
  948. }
  949. $data = json_decode($response["responseBody"]);
  950. return $data;
  951. }
  952. ///////////////////////////////////////////////////////////////////////////
  953. // Deprecated methods
  954. ///////////////////////////////////////////////////////////////////////////
  955. /**
  956. * Loads the extended profile of the current user.
  957. * @deprecated As of 1.2, replaced by getProfile.
  958. * @return The extended profile of the current user.
  959. */
  960. function loadProfile() {
  961. // method renamed, keeping for compatibility.
  962. YahooLogger::info("loadProfile is deprecated since 1.2: Please use getProfile");
  963. return $this->getProfile();
  964. }
  965. /**
  966. * Lists the updates for the current user.
  967. * @deprecated As of 1.2, replaced by getUpdates.
  968. *
  969. *
  970. * @param $start The starting offset to list updates from. (default = 0)
  971. * @param $count The number of updates to request. (default = 10)
  972. * @return A list of updates for the current user.
  973. */
  974. function listUpdates($start = 0, $count = 10) {
  975. // method renamed, keeping for compatibility.
  976. YahooLogger::info("listUpdates is deprecated since 1.2: Please use getUpdates");
  977. return $this->getUpdates($start, $count);
  978. }
  979. /**
  980. * Gets the updates for the connections of the current user.
  981. * @deprecated As of 1.2, replaced by getConnectionUpdates.
  982. * @param $start The starting offset to list updates from.
  983. * @param $count The number of updates to request.
  984. * @return An array of updates for the connections of the current user.
  985. */
  986. function listConnectionUpdates($start = 0, $count = 10) {
  987. // method renamed, keeping for compatibility.
  988. YahooLogger::info("listConnectionUpdates is deprecated since 1.2: Please use getConnectionUpdates");
  989. return $this->getConnectionUpdates($start, $count);
  990. }
  991. /**
  992. * Gets the presence of the user, including the status.
  993. *
  994. * @return The presence of the user or NULL if the fetch fails.
  995. * @deprecated As of 1.2, replaced by getStatus
  996. */
  997. function getPresence() {
  998. global $YahooConfig;
  999. YahooLogger::info("getPresence is deprecated since 1.2: Please use getStatus.");
  1000. $request_url = sprintf("http://%s/v1/user/%s/presence/presence",
  1001. $YahooConfig["PRESENCE_WS_HOSTNAME"],urlencode($this->guid));
  1002. $response = $this->client->get($request_url);
  1003. if(is_null($response)) {
  1004. return NULL;
  1005. }
  1006. else if($response["code"] == 404) {
  1007. // No presence is set, return an empty presence.
  1008. $presence = new stdclass();
  1009. $presence->value = new stdclass();
  1010. $presence->value->status = "";
  1011. return $presence;
  1012. }
  1013. else if($response["code"] != 200) {
  1014. return NULL;
  1015. }
  1016. else {
  1017. $presence = json_decode($response["responseBody"]);
  1018. return $presence->presence;
  1019. }
  1020. }
  1021. /**
  1022. * Sets the presence of the user.
  1023. *
  1024. * @param $status The new status message for the user.
  1025. * @return The status message on success, NULL on failure.
  1026. * @deprecated As of 1.2, replaced by setStatus
  1027. */
  1028. function setPresence($status) {
  1029. global $YahooConfig;
  1030. YahooLogger::info("setPresence is deprecated since 1.2: Please use setStatus");
  1031. if(!$this->sessioned) {
  1032. YahooLogger::error("Can't set the presence of an unsessioned user");
  1033. return NULL;
  1034. }
  1035. $presence = array("status" => $status);
  1036. $presence_json = json_encode($presence);
  1037. $request_url = sprintf("http://%s/v1/user/%s/presence/presence", $YahooConfig["PRESENCE_WS_HOSTNAME"], $this->guid);
  1038. $response = $this->client->put($request_url, "application/json", $presence_json);
  1039. if(YahooUtil::is_response_error($response)) {
  1040. return NULL;
  1041. }
  1042. $presence = json_decode($response["responseBody"]);
  1043. return $presence;
  1044. }
  1045. ///////////////////////////////////////////////////////////////////////////
  1046. // End Deprecated methods
  1047. ///////////////////////////////////////////////////////////////////////////
  1048. }
  1049. /**
  1050. * @private
  1051. */
  1052. class YahooAuthorization {
  1053. function getRequestToken($consumerKey, $consumerSecret, $callback) {
  1054. global $YahooConfig;
  1055. if(is_null($callback)) {
  1056. $callback = "oob";
  1057. }
  1058. $consumer = new OAuthConsumer($consumerKey, $consumerSecret);
  1059. $client = new OAuthClient($consumer, NULL, OAUTH_PARAMS_IN_POST_BODY, OAUTH_SIGNATURE_HMAC_SHA1);
  1060. $request_url = sprintf("https://%s/oauth/v2/get_request_token", $YahooConfig["OAUTH_HOSTNAME"]);
  1061. $parameters = array("oauth_callback" => $callback);
  1062. $response = $client->post($request_url, "application/x-www-form-urlencoded", $parameters);
  1063. if(is_null($response)) {
  1064. YahooLogger::error("OAuth call to get request token failed");
  1065. return NULL;
  1066. }
  1067. parse_str($response["responseBody"], $token);
  1068. if($response["code"] != 200) {
  1069. $problem = array_key_exists("oauth_problem", $token) ?
  1070. $token["oauth_problem"] : "unknown problem";
  1071. YahooLogger::error("Failed to create request token: $problem");
  1072. return NULL;
  1073. }
  1074. if(!array_key_exists("oauth_callback_confirmed", $token) ||
  1075. !$token["oauth_callback_confirmed"]) {
  1076. // Callback wasn't confirmed.
  1077. YahooLogger::error("Failed to create request token: callback was not confirmed");
  1078. return NULL;
  1079. }
  1080. $requestToken = new stdclass();
  1081. $requestToken->key = $token["oauth_token"];
  1082. $requestToken->secret = $token["oauth_token_secret"];
  1083. return $requestToken;
  1084. }
  1085. function createAuthorizationUrl($requestToken) {
  1086. global $YahooConfig;
  1087. if(!is_object($requestToken) || !property_exists($requestToken, "key")) {
  1088. YahooLogger::error("Request token doesn't have a 'key' property");
  1089. return NULL;
  1090. }
  1091. return sprintf("https://%s/oauth/v2/request_auth?oauth_token=%s", $YahooConfig["OAUTH_HOSTNAME"], urlencode($requestToken->key));
  1092. }
  1093. function getAccessToken($consumerKey, $consumerSecret, $requestToken, $verifier) {
  1094. $at = YahooAuthorization::getAccessTokenProxy($consumerKey, $consumerSecret, $requestToken, $verifier);
  1095. if(is_null($at)) {
  1096. // Failed to fetch the access token, sleep for 250ms and
  1097. // then try one more time.
  1098. YahooLogger::info("Failed to fetch access token, retrying");
  1099. usleep(250000);
  1100. $at = YahooAuthorization::getAccessTokenProxy($consumerKey, $consumerSecret, $requestToken, $verifier);
  1101. }
  1102. return $at;
  1103. }
  1104. function getAccessTokenProxy($consumerKey, $consumerSecret, $requestToken, $verifier) {
  1105. global $YahooConfig;
  1106. $request_url = sprintf("https://%s/oauth/v2/get_token", $YahooConfig["OAUTH_HOSTNAME"]);
  1107. $consumer = new OAuthConsumer($consumerKey, $consumerSecret);
  1108. $parameters = array();
  1109. if(property_exists($requestToken, "sessionHandle")) {
  1110. $parameters["oauth_session_handle"] = $requestToken->sessionHandle;
  1111. }
  1112. if(!is_null($verifier)) {
  1113. $parameters["oauth_verifier"] = $verifier;
  1114. }
  1115. $client = new OAuthClient($consumer, $requestToken, OAUTH_PARAMS_IN_POST_BODY);
  1116. $response = $client->post($request_url, "application/x-www-form-urlencoded", $parameters);
  1117. if(is_null($response)) {
  1118. YahooLogger::error("OAuth call to get access token failed");
  1119. return NULL;
  1120. }
  1121. parse_str($response["responseBody"], $token);
  1122. if($response["code"] != 200) {
  1123. YahooLogger::error("Failed to fetch access token: " . $token["oauth_problem"]);
  1124. return NULL;
  1125. }
  1126. $now = time();
  1127. $accessToken = new stdclass();
  1128. $accessToken->key = $token["oauth_token"];
  1129. $accessToken->secret = $token["oauth_token_secret"];
  1130. $accessToken->guid = $token["xoauth_yahoo_guid"];
  1131. $accessToken->consumer = $consumerKey;
  1132. $accessToken->sessionHandle = $token["oauth_session_handle"];
  1133. // Check to see if the access token ever expires.
  1134. YahooLogger::debug('AT expires in '.$token['oauth_expires_in'].'; ASH expires in '.$token["oauth_authorization_expires_in"]);
  1135. if(array_key_exists("oauth_expires_in", $token)) {
  1136. $accessToken->tokenExpires = $now + $token["oauth_expires_in"];
  1137. }
  1138. else {
  1139. $accessToken->tokenExpires = -1;
  1140. }
  1141. // Check to see if the access session handle ever expires.
  1142. if(array_key_exists("oauth_authorization_expires_in", $token)) {
  1143. $accessToken->handleExpires = $now +
  1144. $token["oauth_authorization_expires_in"];
  1145. }
  1146. else {
  1147. $accessToken->handleExpires = -1;
  1148. }
  1149. return $accessToken;
  1150. }
  1151. }
  1152. /**
  1153. * Cookie-based implementation of the session store. This is the default
  1154. * session storage used by the Y!OS PHP SDK. Developers are free to
  1155. * implement their own session store implementations and pass them to
  1156. * YahooSession::hasSession, YahooSession::requireSession and
  1157. * YahooSession::clearSession. By default, if no session store is passed
  1158. * to YahooSession::hasSession or YahooSession::requireSession, an instance
  1159. * of a NativeSessionStore is used.
  1160. *
  1161. * @brief Cookie-based implementation of the session store.
  1162. */
  1163. class CookieSessionStore {
  1164. /**
  1165. * Indicates if the session store has a request token.
  1166. *
  1167. * @return True if a request token is present, false otherwise.
  1168. */
  1169. function hasRequestToken() {
  1170. return array_key_exists("yosdk_rt", $_COOKIE) && (strlen($_COOKIE["yosdk_rt"]) > 0);
  1171. }
  1172. /**
  1173. * Indicates if the session store has an access token.
  1174. *
  1175. * @return True if an access token is present, false otherwise.
  1176. */
  1177. function hasAccessToken() {
  1178. return array_key_exists("yosdk_at", $_COOKIE) && (strlen($_COOKIE["yosdk_at"]) > 0);
  1179. }
  1180. /**
  1181. * Stores the given request token in the session store.
  1182. *
  1183. * @param $token A PHP stdclass object containing the components of
  1184. * the OAuth request token.
  1185. * @return True on success, false otherwise.
  1186. */
  1187. function storeRequestToken($token) {
  1188. if(!headers_sent()) {
  1189. return setcookie("yosdk_rt", base64_encode(json_encode($token)), time() + 600);
  1190. }
  1191. else {
  1192. return false;
  1193. }
  1194. }
  1195. /**
  1196. * Fetches and returns the request token from the session store.
  1197. *
  1198. * @return The request token.
  1199. */
  1200. function fetchRequestToken() {
  1201. return json_decode(base64_decode($_COOKIE["yosdk_rt"]));
  1202. }
  1203. /**
  1204. * Clears the request token from the session store.
  1205. *
  1206. * @return True on success, false otherwise.
  1207. */
  1208. function clearRequestToken() {
  1209. if(!headers_sent()) {
  1210. return setcookie("yosdk_rt", "", time() - 600);
  1211. }
  1212. else {
  1213. return false;
  1214. }
  1215. }
  1216. /**
  1217. * Stores the given access token in the session store.
  1218. *
  1219. * @param $token A PHP stdclass object containing the components of
  1220. * the OAuth access token.
  1221. * @return True on success, false otherwise.
  1222. */
  1223. function storeAccessToken($token) {
  1224. if(!headers_sent()) {
  1225. return setcookie("yosdk_at", base64_encode(json_encode($token)),
  1226. time() + (30 * 24 * 60 * 60));
  1227. }
  1228. else {
  1229. return false;
  1230. }
  1231. }
  1232. /**
  1233. * Fetches and returns the access token from the session store.
  1234. *
  1235. * @return The access token.
  1236. */
  1237. function fetchAccessToken() {
  1238. return json_decode(base64_decode($_COOKIE["yosdk_at"]));
  1239. }
  1240. /**
  1241. * Clears the access token from the session store.
  1242. *
  1243. * @return True on success, false otherwise.
  1244. */
  1245. function clearAccessToken() {
  1246. if(!headers_sent()) {
  1247. return setcookie("yosdk_at", "", time() - 600);
  1248. }
  1249. else {
  1250. return false;
  1251. }
  1252. }
  1253. }
  1254. /**
  1255. * PHP session based implementation of the session store. This is the default
  1256. * session storage used by the Y!OS PHP SDK. Developers are free to
  1257. * implement their own session store implementations and pass them to
  1258. * YahooSession::hasSession, YahooSession::requireSession and
  1259. * YahooSession::clearSession. By default, if no session store is passed
  1260. * to YahooSession::hasSession or YahooSession::requireSession, an instance
  1261. * of a NativeSessionStore is used.
  1262. *
  1263. * @brief Native php session based implementation of the session store, by default
  1264. * stored on file system, but can be database or memcache backend.
  1265. */
  1266. class NativeSessionStore {
  1267. /**
  1268. * Indicates if the session store has a request token.
  1269. *
  1270. * @return True if a request token is present, false otherwise.
  1271. */
  1272. function hasRequestToken() {
  1273. return array_key_exists("yosdk_rt", $_SESSION) && (strlen($_SESSION["…

Large files files are truncated, but you can click here to view the full file