Source for file Yahoo.inc

Documentation is available at Yahoo.inc

  1. <?php
  2.  
  3. /**
  4.  *  YOS PHP SDK for accessing social and data apis at Yahoo!
  5.  *
  6.  *  @package     yos-social-php
  7.  *  @author      Yahoo! Developer Network
  8.  *  @example     http://developer.yahoo.com/social/sdk/php/
  9.  *
  10.  *  @copyright   Copyright (c) 2009 Yahoo! Inc. All rights reserved.
  11.  *  @license     BSD License (http://www.opensource.org/licenses/bsd-license.php)
  12.  *
  13.  *   The copyrights embodied in the content of this file are licensed under the
  14.  *   BSD (revised) open source license.
  15.  *
  16.  *   Redistribution and use of this software in source and binary forms, with
  17.  *   or without modification, are permitted provided that the following
  18.  *   conditions are met:
  19.  *
  20.  *   * Redistributions of source code must retain the above
  21.  *     copyright notice, this list of conditions and the
  22.  *     following disclaimer.
  23.  *
  24.  *   * Redistributions in binary form must reproduce the above
  25.  *     copyright notice, this list of conditions and the
  26.  *     following disclaimer in the documentation and/or other
  27.  *     materials provided with the distribution.
  28.  *
  29.  *   * Neither the name of Yahoo! Inc. nor the names of its
  30.  *     contributors may be used to endorse or promote products
  31.  *     derived from this software without specific prior
  32.  *     written permission of Yahoo! Inc.
  33.  *
  34.  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  35.  *   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  36.  *   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  37.  *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  38.  *   FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  39.  *   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  40.  *   SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41.  *   CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  42.  *   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  43.  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  44.  *
  45.  *   Please see the Yahoo! Developer Network forums for support: http://developer.yahoo.net/forum/
  46.  *
  47.  *   Documentation: http://developer.yahoo.com/social/sdk/php/
  48.  */
  49.  
  50. // Use OAuthConsumer as a test to see if any other instances of OAuth.php may
  51. // have been included. require_once() won't catch situations where multiple
  52. // copies of OAuth.php are included by different parts of an application.
  53. if(!class_exists("OAuthConsumer")) {
  54.     require_once("OAuth.php");
  55. }
  56.  
  57. define("OAUTH_PARAMS_IN_HEADERS""HEADERS");
  58. define("OAUTH_PARAMS_IN_POST_BODY""POSTBODY");
  59. define("OAUTH_SIGNATURE_PLAINTEXT""PLAINTEXT");
  60. define("OAUTH_SIGNATURE_HMAC_SHA1""HMAC_SHA1");
  61.  
  62. define("YAHOO_YAP_SESSION_TYPE""YAHOO_YAP_SESSION_TYPE");
  63. define("YAHOO_OAUTH_RT_SESSION_TYPE""YAHOO_OAUTH_RT_SESSION_TYPE");
  64. define("YAHOO_OAUTH_AT_SESSION_TYPE""YAHOO_OAUTH_AT_SESSION_TYPE");
  65.  
  66. $YahooConfig array(
  67.     "SOCIAL_WS_HOSTNAME" => "social.yahooapis.com",
  68.     "PRESENCE_WS_HOSTNAME" => "social.yahooapis.com",
  69.     "UPDATES_WS_HOSTNAME" => "social.yahooapis.com",
  70.     "QUERY_WS_HOSTNAME" => "query.yahooapis.com",
  71.     "OAUTH_HOSTNAME" => "api.login.yahoo.com",
  72.     "YAP_WS_HOSTNAME" => "appstore.apps.yahooapis.com"
  73. );
  74.  
  75. $GLOBAL_YAHOO_SESSION NULL;
  76.  
  77. $GLOBAL_YAHOO_LOGGER_DEBUG false;
  78. $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION "LOG";
  79.  
  80. global $YahooConfig$GLOBAL_YAHOO_SESSION$GLOBAL_YAHOO_LOGGER_DEBUG$GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
  81.  
  82. class YahooUtil {
  83.   function current_url({
  84.     return sprintf("http://%s%s",$_SERVER["HTTP_HOST"],$_SERVER["REQUEST_URI"]);
  85.   }
  86.  
  87.     function verify_signature($consumer$token=NULL$oauth_signature{
  88.         $oauth_signature_method new OAuthSignatureMethod_HMAC_SHA1();
  89.         $oauth_consumer new OAuthConsumer($consumer->key$consumer->secret);
  90.         $oauth_token ($tokennew OAuthToken($token->key$token->secretNULL;
  91.         $oauth_request OAuthRequest::from_request();
  92.  
  93.         $ok $oauth_signature_method->check_signature($oauth_request$oauth_consumer$oauth_token$oauth_signature);
  94.  
  95.         return $ok;
  96.     }
  97.  
  98.   function is_yap_canvas({
  99.     return (isset($_POST['yap_appid'])
  100.       && isset($_POST['yap_view']));
  101.   }
  102.  
  103.   function is_response_error($response{
  104.     return (is_null($response|| $response["code"!= 200);
  105.   }
  106.  
  107. }
  108.  
  109. class YahooException extends Exception {
  110.  
  111. }
  112.  
  113. /**
  114.  * Logging wrapper for the Yahoo objects.
  115.  *
  116.  * @brief Logging wrapper for the Yahoo objects.
  117.  */
  118. class YahooLogger {
  119.     /**
  120.      * Log a message at the debug level.
  121.      *
  122.      * @param $message The message to log.
  123.      */
  124.     function debug($message$object NULL{
  125.  
  126.         global $GLOBAL_YAHOO_LOGGER_DEBUG;
  127.         global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
  128.         if($GLOBAL_YAHOO_LOGGER_DEBUG{
  129.             if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "CONSOLE"{
  130.                 print("DEBUG - $message\n");
  131.                 if(!is_null($object)) {
  132.                     print("DEBUG OBJECT - " print_r($objecttrue"\n");
  133.                 }
  134.             }
  135.             else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "LOG"{
  136.                 YahooLogger::error("DEBUG - $message");
  137.                 if(!is_null($object)) {
  138.                     YahooLogger::error("DEBUG OBJECT - " print_r($objecttrue));
  139.                 }
  140.             }
  141.         }
  142.     }
  143.  
  144.     /**
  145.      * Log a message at the info level.
  146.      *
  147.      * @param $message The message to log.
  148.      */
  149.     function info($message$object NULL{
  150.         global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
  151.         if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "CONSOLE"{
  152.             print("INFO - $message\n");
  153.             if(!is_null($object)) {
  154.                 print("INFO OBJECT - " print_r($objecttrue"\n");
  155.             }
  156.         }
  157.         else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "LOG"{
  158.             YahooLogger::error("INFO - $message");
  159.             if(!is_null($object)) {
  160.                 YahooLogger::error("INFO OBJECT - " print_r($objecttrue));
  161.             }
  162.         }
  163.     }
  164.  
  165.     /**
  166.      * Log a message at the error level.
  167.      *
  168.      * @param $message The message to log.
  169.      */
  170.     function error($message$object NULL{
  171.         global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
  172.         if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "CONSOLE"{
  173.             print("ERROR - $message\n");
  174.             if(!is_null($object)) {
  175.                 print("ERROR OBJECT - " print_r($objecttrue"\n");
  176.             }
  177.         }
  178.         else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "LOG"{
  179.             YahooLogger::error("ERROR - $message");
  180.             if(!is_null($object)) {
  181.                 YahooLogger::error("ERROR OBJECT - " print_r($objecttrue));
  182.             }
  183.         }
  184.     }
  185.  
  186.     /**
  187.      * Enables/disables session debugging.
  188.      *
  189.      * @param $debug Boolean to enable/disable debugging.
  190.      */
  191.     function setDebug($debug{
  192.         global $GLOBAL_YAHOO_LOGGER_DEBUG;
  193.         $GLOBAL_YAHOO_LOGGER_DEBUG = (bool) $debug;
  194.     }
  195.  
  196.     /**
  197.      * Allows callers to configure where debugging output is sent.
  198.      *
  199.      * @param $destination "LOG" to use YahooLogger::error, "CONSOLE" to use printf,
  200.      *                      "NULL" to disable all logging output.
  201.      * @return boolean True on success, false on failure.
  202.      */
  203.     function setDebugDestination($destination{
  204.         global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
  205.         if($destination == "LOG" || $destination == "CONSOLE" ||
  206.                 $destination == "NULL"{
  207.             $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION $destination;
  208.             return true;
  209.         }
  210.         else {
  211.             return false;
  212.         }
  213.     }
  214. }
  215.  
  216.  
  217. /**
  218.  * Defines a session between an application and the Yahoo! platform.
  219.  *
  220.  * @brief Defines a session between an application and the Yahoo! platform.
  221.  */
  222. class YahooSession {
  223.     /**
  224.      * @private
  225.      */
  226.     var $guid = NULL;
  227.  
  228.     /**
  229.      * @private
  230.      */
  231.     var $consumer = NULL;
  232.  
  233.     /**
  234.      * @private
  235.      */
  236.     var $accessToken = NULL;
  237.  
  238.     /**
  239.      * @private
  240.      */
  241.     var $applicationId = NULL;
  242.  
  243.     /**
  244.      * @private
  245.      */
  246.     var $client = NULL;
  247.  
  248.     /**
  249.      * @private
  250.      */
  251.     var $application = NULL;
  252.  
  253.     /**
  254.      * @private
  255.      */
  256.     function YahooSession($consumer$accessToken$applicationId)
  257.     {
  258.         $this->consumer = $consumer;
  259.         $this->accessToken = $accessToken;
  260.         $this->applicationId = $applicationId;
  261.         $this->guid = $accessToken->guid;
  262.  
  263.         $this->client = new OAuthClient($consumer$accessToken);
  264.  
  265.         $this->application = new YahooApplication($consumer->key$consumer->secret);
  266.         $this->application->token $this->accessToken;
  267.     }
  268.  
  269.     /**
  270.      * @private
  271.      */
  272.     function getConsumer({
  273.         return $this->consumer;
  274.     }
  275.  
  276.     /**
  277.      * @private
  278.      */
  279.     function getAccessToken({
  280.         return $this->accessToken;
  281.     }
  282.  
  283.     /**
  284.      * @private
  285.      */
  286.     function getApplicationId({
  287.         return $this->applicationId;
  288.     }
  289.  
  290.     /**
  291.      * Gets the currently sessioned user.
  292.      *
  293.      * @return YahooUser The currently sessioned YahooUser.
  294.      */
  295.     function getSessionedUser({
  296.         return new YahooUser($this$this->guidtrue);
  297.     }
  298.  
  299.     /**
  300.      * Gets the user who owns the application install.
  301.      * Only valid when viewed in YAP, otherwise will default
  302.      * to the logged-in user.
  303.      *
  304.      * @return YahooUser The currently sessioned YahooUser.
  305.      */
  306.     function getOwner({
  307.         if(isset($this->accessToken->owner)) {
  308.             return $this->getUser($this->accessToken->owner);
  309.         }
  310.         else {
  311.             return $this->getSessionedUser();
  312.         }
  313.     }
  314.  
  315.     /**
  316.      * Gets the user indicated by the GUID given.
  317.      *
  318.      * @param $guid The GUID of the user to get.
  319.      * @return YahooUser The user indicated by the GUID given.
  320.      */
  321.     function getUser($guid{
  322.         return new YahooUser($this$guidisset($this->guid&& ($guid == $this->guid));
  323.     }
  324.  
  325.   /**
  326.      * Executes the given YQL query.
  327.      *
  328.      * @param $yql The query to execute.
  329.    * @param $env A URL to a YQL environment file.
  330.      * @return The response or NULL if the request fails..
  331.      */
  332.     function query($yql$env=NULL{
  333.         return $this->application->query($yql$env);
  334.     }
  335.  
  336.     /**
  337.      * @private
  338.      */
  339.     function redirectForAuthorization($consumerKey$consumerSecret$callback NULL$sessionStore NULL{
  340.         $url YahooSession::createAuthorizationUrl($consumerKey$consumerSecret$callback$sessionStore);
  341.  
  342.         if(!is_null($url)) {
  343.             header(sprintf("Location: %s"$url));
  344.             exit();
  345.         }
  346.         else {
  347.       // TODO: throw a YahooException
  348.             YahooLogger::error("Failed to create authorization URLs");
  349.         }
  350.     }
  351.  
  352.     /**
  353.      * Destroys the current session, effectively logging out the current
  354.      * user.
  355.      *
  356.      * @param $sessionStore The session store implementation to clear. See
  357.      *                       YahooSessionStore for more information. If no
  358.      *                       session store is provided, clearSession will
  359.      *                       instantiate a NativeSessionStore and use that.
  360.      */
  361.     function clearSession($sessionStore NULL{
  362.         global $GLOBAL_YAHOO_SESSION;
  363.  
  364.         if(is_null($sessionStore)) {
  365.             $sessionStore new NativeSessionStore();
  366.         }
  367.  
  368.         $sessionStore->clearRequestToken();
  369.         $sessionStore->clearAccessToken();
  370.  
  371.         $GLOBAL_YAHOO_SESSION NULL;
  372.     }
  373.  
  374.     /**
  375.      * Checks to see if there is a session in this PHP page request.
  376.      * Doesn't cause any redirects for the user to log in, for that
  377.      * you should call requireSession().
  378.      *
  379.      * @param $consumerKey The OAuth consumer key.
  380.      * @param $consumerSecret The OAuth consumer key secret.
  381.      * @param $applicationId The application ID, optional.
  382.      * @param $sessionStore The session store implementation to use. See
  383.      *                       YahooSessionStore for more information. If no
  384.      *                       session store is provided, clearSession will
  385.      *                       instantiate a NativeSessionStore and use that.
  386.      * @return boolean True if a session is present, false otherwise.
  387.      */
  388.     function hasSession($consumerKey$consumerSecret$applicationId NULL$sessionStore NULL$verifier NULL)
  389.     {
  390.         if(is_null($sessionStore)) {
  391.             $sessionStore new NativeSessionStore();
  392.         }
  393.  
  394.     if(is_null($verifier&& array_key_exists("oauth_verifier"$_GET)) {
  395.             $verifier $_GET["oauth_verifier"];
  396.         }
  397.  
  398.         $session YahooSession::initSession($consumerKey$consumerSecret$applicationIdFALSENULL$sessionStore$verifier);
  399.         return !is_null($session);
  400.     }
  401.  
  402.     /**
  403.      * Requires that there be a session in this PHP page request. Generates
  404.      * a redirect for the user to log in, if necessary. You must call
  405.      * requireSession() before any data is sent back to the user in order
  406.      * for the redirect to work.
  407.      *
  408.      * @param $consumerKey The OAuth consumer key.
  409.      * @param $consumerSecret The OAuth consumer key secret.
  410.      * @param $applicationId The application ID, optional.
  411.      * @param $callback The callback URL to redirect the user to after
  412.      *                   they verify the application access. If no callback
  413.      *                   is provided, the current page URL will be used.
  414.      * @param $sessionStore The session store implementation to use. See
  415.      *                       YahooSessionStore for more information. If no
  416.      *                       session store is provided, clearSession will
  417.      *                       instantiate a NativeSessionStore and use that.
  418.      * @param $verifier The oauth_verifier returned by the OAuth servers
  419.      *                   after authorization. Passing NULL indicates that
  420.      *                   authorization was completed previously or that
  421.      *                   requireSession() should look for oauth_verifier in
  422.      *                   the $_GET superglobal.
  423.      * @return YahooSession The current session or NULL if a session cannot
  424.      *                       be established.
  425.      */
  426.     function requireSession($consumerKey$consumerSecret$applicationId NULL,
  427.                           $callback NULL$sessionStore NULL$verifier NULL)
  428.     {
  429.         if(is_null($sessionStore)) {
  430.             $sessionStore new NativeSessionStore();
  431.         }
  432.  
  433.         if(is_null($verifier&& array_key_exists("oauth_verifier"$_GET)) {
  434.             $verifier $_GET["oauth_verifier"];
  435.         }
  436.  
  437.         return YahooSession::initSession($consumerKey$consumerSecret$applicationIdTRUE$callback$sessionStore$verifier);
  438.     }
  439.  
  440.     /**
  441.      * Creates authorization URLs, allowing applications to manage their
  442.      * user experience when the user needs to be sent to Yahoo! to authorize
  443.      * the application to access their account.
  444.      *
  445.      * @param $consumerKey The OAuth consumer key.
  446.      * @param $consumerSecret The OAuth consumer key secret.
  447.      * @param $callback The callback URL to redirect the user to after
  448.      *                   they verify the application access. If no callback
  449.      *                   is provided, the current page URL will be used.
  450.      *                   Use the "oob" callback for desktop clients or for
  451.      *                   web clients where no callback should be used.
  452.      * @param $sessionStore The session store implementation to use. See
  453.      *                       YahooSessionStore for more information. If no
  454.      *                       session store is provided, createAuthorizationUrl
  455.      *                       will instantiate a NativeSessionStore and use that.
  456.      * @return stdclass A PHP object with two properties: "urlWithCallback"
  457.      *                   and "urlWithoutCallback". This allows the application
  458.      *                   to mix and match authorizations that do and don't
  459.      *                   have callbacks in the URLs. urlWithoutCallback is
  460.      *                   useful for JavaScript popup windows while
  461.      *                   urlWithCallback is useful for normal <a href>
  462.      *                   tags.
  463.      */
  464.     function createAuthorizationUrl($consumerKey$consumerSecret$callback NULL$sessionStore NULL)
  465.     {
  466.         global $GLOBAL_YAHOO_SESSION;
  467.  
  468.         if(is_null($sessionStore)) {
  469.             $sessionStore new NativeSessionStore();
  470.         }
  471.  
  472.         // No callback URL supplied. Build one from the current URL.
  473.         if(is_null($callback)) {
  474.             $callback YahooUtil::current_url();
  475.         }
  476.  
  477.         // Redirect the user to log in.
  478.         $requestToken YahooAuthorization::getRequestToken($consumerKey$consumerSecret$callback);
  479.  
  480.         if(!is_null($requestToken))
  481.         {
  482.             $sessionStore->storeRequestToken($requestToken);
  483.  
  484.             $url YahooAuthorization::createAuthorizationUrl($requestToken$callback);
  485.             return $url;
  486.         }
  487.         else
  488.         {
  489.             YahooLogger::error("Failed to create request token");
  490.             $GLOBAL_YAHOO_SESSION NULL;
  491.             return null;
  492.         }
  493.     }
  494.  
  495.   function initSessionFromYAP($consumerKey$consumerSecret$appid)
  496.   {
  497.     global $GLOBAL_YAHOO_SESSION;
  498.  
  499.     if(!YahooUtil::is_yap_canvas()) {
  500.       // TODO: throw a YahooException
  501.       return NULL;
  502.     }
  503.  
  504.     $consumer new stdclass();
  505.         $consumer->key $consumerKey;
  506.         $consumer->secret $consumerSecret;
  507.  
  508.     if ($consumer->key != $_POST["yap_consumer_key"]{
  509.             YahooLogger::error("Consumer key from YAP does not match provided key.");
  510.             // TODO: throw a YahooException
  511.             $GLOBAL_YAHOO_SESSION NULL;
  512.             return;
  513.         }
  514.  
  515.     $signature_ok YahooUtil::verify_signature($consumernull$_REQUEST['oauth_signature']);
  516.  
  517.         if (!$signature_ok)
  518.         {
  519.             YahooLogger::error("Signature from YAP failed.");
  520.             // TODO: throw a YahooException
  521.             $GLOBAL_YAHOO_SESSION NULL;
  522.             return;
  523.         }
  524.  
  525.         $accessToken new stdclass();
  526.         $accessToken->key $_POST["yap_viewer_access_token"];
  527.         $accessToken->secret $_POST["yap_viewer_access_token_secret"];
  528.         $accessToken->guid $_POST["yap_viewer_guid"];
  529.         $accessToken->owner $_POST["yap_owner_guid"];
  530.         $accessToken->tokenExpires = -1;
  531.  
  532.         YahooLogger::debug("YAP AT: " $accessToken->key " ATS: " $accessToken->secret);
  533.  
  534.         $applicationId $_POST["yap_appid"];
  535.         $GLOBAL_YAHOO_SESSION new YahooSession($consumer$accessToken$applicationId);
  536.  
  537.         return $GLOBAL_YAHOO_SESSION;
  538.   }
  539.  
  540.     /**
  541.      * @private
  542.      */
  543.     function initSession($consumerKey$consumerSecret$applicationId$redirect$callback$sessionStore$verifier)
  544.     {
  545.         global $GLOBAL_YAHOO_SESSION;
  546.  
  547.         if(!is_null($GLOBAL_YAHOO_SESSION)) {
  548.             return $GLOBAL_YAHOO_SESSION;
  549.         }
  550.  
  551.         $consumer new stdclass();
  552.         $consumer->key $consumerKey;
  553.         $consumer->secret $consumerSecret;
  554.  
  555.         $checkSession YahooSession::checkSession($type$sessionStore);
  556.  
  557.         if(!$checkSession{
  558.             // There doesn't appear to be a session here.
  559.             if($redirect)  {
  560.                 $GLOBAL_YAHOO_SESSION NULL;
  561.                 YahooSession::redirectForAuthorization($consumerKey$consumerSecret$callback$sessionStore);
  562.             }
  563.             else {
  564.                 // Don't redirect the user, just inform the caller that
  565.                 // no session is present.
  566.                 // TODO: throw a YahooException
  567.                 $GLOBAL_YAHOO_SESSION NULL;
  568.             }
  569.         }
  570.         else if($type == YAHOO_OAUTH_AT_SESSION_TYPE{
  571.             // Found an OAuth Access Token session.
  572.             $accessToken $sessionStore->fetchAccessToken();
  573.             $now time();
  574.  
  575.             YahooLogger::debug("OAuth AT: " $accessToken->key "   ATS: "$accessToken->secret);
  576.  
  577.             if($accessToken->consumer != $consumerKey)
  578.             {
  579.                 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.");
  580.                 YahooSession::clearSession($sessionStore);
  581.  
  582.                 if($redirect{
  583.                     YahooSession::redirectForAuthorization($consumerKey$consumerSecret$callback$sessionStore);
  584.                 }
  585.             }
  586.  
  587.             if($accessToken->tokenExpires >= 0{
  588.                 YahooLogger::debug('AT Expires in: ' ($accessToken->tokenExpires $now));
  589.             }
  590.  
  591.             if(($accessToken->tokenExpires >= 0&& ($accessToken->tokenExpires $now30{
  592.                 // The access token will expire in less than 30 seconds or
  593.                 // it may have expired already. Try to get a new one.
  594.                 YahooSession::accessTokenExpired($accessToken$consumer$applicationId$sessionStore);
  595.             }
  596.             else {
  597.                 // The access token is still good for a little while, continue using it.
  598.                 $GLOBAL_YAHOO_SESSION new YahooSession($consumer$accessToken$applicationId);
  599.             }
  600.         }
  601.         else if($type == YAHOO_OAUTH_RT_SESSION_TYPE)
  602.         {
  603.             if(is_null($verifier)) {
  604.                 // Can't proceed without the oauth_verifier, treat it as
  605.                 // though there's no session present.
  606.                 $sessionStore->clearRequestToken();
  607.  
  608.                 // TODO: throw a YahooException
  609.                 $GLOBAL_YAHOO_SESSION NULL;
  610.             }
  611.  
  612.             // Found an OAuth Request Token session.
  613.             $requestToken $sessionStore->fetchRequestToken();
  614.  
  615.             $accessToken YahooAuthorization::getAccessToken($consumerKey$consumerSecret$requestToken$verifier);
  616.  
  617.             if(!is_null($accessToken)) {
  618.                 $sessionStore->storeAccessToken($accessToken);
  619.                 $sessionStore->clearRequestToken();
  620.  
  621.                 $GLOBAL_YAHOO_SESSION new YahooSession($consumer$accessToken$applicationId);
  622.             }
  623.             else if($redirect)
  624.             {
  625.                 // TODO: Add redirect counter so this doesn't happen over and over and over when Yahoo! is completely busted.
  626.                 // The fetch for the access token failed. Generate a new
  627.                 // request token and try again.
  628.                 $GLOBAL_YAHOO_SESSION NULL;
  629.                 YahooSession::redirectForAuthorization($consumerKey$consumerSecret$callback$sessionStore);
  630.             }
  631.             else
  632.             {
  633.                 // Don't redirect the user, just inform the caller that
  634.                 // no session is present.
  635.                 $sessionStore->clearRequestToken();
  636.                 $GLOBAL_YAHOO_SESSION NULL;
  637.             }
  638.         }
  639.         else if($type == YAHOO_YAP_SESSION_TYPE)
  640.         {
  641.             // Found a YAP session.
  642.             $GLOBAL_YAHOO_SESSION YahooSession::initSessionFromYAP($consumerKey$consumerSecret$applicationId);
  643.         }
  644.         else
  645.         {
  646.             YahooLogger::error("Unknown session type found");
  647.             // TODO: throw a YahooException
  648.             $GLOBAL_YAHOO_SESSION NULL;
  649.         }
  650.  
  651.         return $GLOBAL_YAHOO_SESSION;
  652.     }
  653.  
  654.     /**
  655.      * @private
  656.      */
  657.     function accessTokenExpired($accessToken$consumer$applicationId$sessionStore)
  658.     {
  659.         global $GLOBAL_YAHOO_SESSION;
  660.  
  661.         $now time();
  662.         if(($accessToken->handleExpires === -1||
  663.                 ($now $accessToken->handleExpires)) {
  664.             // Either the access session handle doesn't expire
  665.             // or it hasn't expired yet. Get a new access token.
  666.             $newAccessToken YahooAuthorization::getAccessToken(
  667.                     $consumer->key$consumer->secret$accessTokennull);
  668.             if(is_null($newAccessToken)) {
  669.                 YahooLogger::error("Failed to fetch access token");
  670.                 $GLOBAL_YAHOO_SESSION NULL;
  671.             }
  672.  
  673.             $sessionStore->storeAccessToken($newAccessToken);
  674.  
  675.             YahooLogger::debug("Got new AT/ATS from ASH!");
  676.             YahooLogger::debug("OAuth AT: " $newAccessToken->key "   ATS: "$newAccessToken->secret);
  677.  
  678.             $GLOBAL_YAHOO_SESSION new YahooSession(
  679.                     $consumer$newAccessToken$applicationId);
  680.         }
  681.         else
  682.         {
  683.             // The access token is expired and we don't have
  684.             // a sufficient access session handle to renew
  685.             // the access token. Clear the cookie and redirect
  686.             // to authorization point or return a NULL session.
  687.             $sessionStore->clearAccessToken();
  688.  
  689.             if ($redirect{
  690.                 YahooSession::redirectForAuthorization($consumer->key$consumer->secret$callback$sessionStore);
  691.             else {
  692.                 $GLOBAL_YAHOO_SESSION NULL;
  693.             }
  694.         }
  695.     }
  696.  
  697.     /**
  698.      * @private
  699.      *
  700.      *  Checks to see if the current PHP page request has a session and, if so,
  701.      *  indicates what type of session is present.
  702.      *
  703.      * @param[out] $sessionType The session type present, if any.
  704.      * @return boolean True if a session is present, false otherwise.
  705.      */
  706.     function checkSession(&$sessionType$sessionStore{
  707.         if(array_key_exists("yap_appid"$_POST)) {
  708.             $sessionType YAHOO_YAP_SESSION_TYPE;
  709.             return true;
  710.         }
  711.         else if($sessionStore->hasAccessToken()) {
  712.             $sessionType YAHOO_OAUTH_AT_SESSION_TYPE;
  713.             return true;
  714.         }
  715.         else if($sessionStore->hasRequestToken()) {
  716.             $sessionType YAHOO_OAUTH_RT_SESSION_TYPE;
  717.             return true;
  718.         }
  719.         else {
  720.             return false;
  721.         }
  722.     }
  723. }
  724.  
  725. /**
  726.  * Represents a Yahoo! application.
  727.  *
  728.  * @brief Represents a Yahoo! application.
  729.  */
  730.     /**
  731.      * @private
  732.      */
  733.     var $consumer = NULL;
  734.  
  735.     /**
  736.      * @private
  737.      * @deprecated
  738.      */
  739.     var $client = NULL;
  740.  
  741.   /**
  742.    * @private
  743.    */
  744.   var $token = NULL;
  745.  
  746.     /**
  747.      * Constructs a new YahooApplication object.
  748.      *
  749.      * @param $consumerKey The consumer key of the application.
  750.      * @param $consumerKeySecret The consumer key secret of the application.
  751.      */
  752.     function YahooApplication($consumerKey$consumerKeySecret{
  753.         $this->consumer = new OAuthConsumer($consumerKey$consumerKeySecret);
  754.     }
  755.  
  756.     /**
  757.      * Sets the small view for the user given by the GUID.
  758.      *
  759.      * @param $guid The GUID of the user to set the small view for.
  760.      * @param $content The content to set the small view to.
  761.      * @return True on success, false otherwise.
  762.      */
  763.     function setSmallView($guid$content{
  764.         global $YahooConfig;
  765.  
  766.         $client new OAuthClient($this->consumerNULL);
  767.  
  768.         $request_url sprintf("http://%s/v1/cache/view/small/%s"$YahooConfig["YAP_WS_HOSTNAME"]urlencode($guid));
  769.         $response $client->put($request_url"text/html;charset=utf-8"$content);
  770.  
  771.         return !(YahooUtil::is_response_error($response));
  772.     }
  773.  
  774.     /**
  775.      * Executes the given YQL query.
  776.      *
  777.      * @param $yql The query to execute.
  778.      * @param $env A URL to a YQL environment file.
  779.      * @return The response or NULL if the request fails..
  780.      */
  781.     function query($yql$env=NULL)
  782.     {
  783.         global $YahooConfig;
  784.  
  785.         $client new OAuthClient($this->consumer$this->token);
  786.  
  787.         $request_url sprintf("http://%s/v1/yql",$YahooConfig["QUERY_WS_HOSTNAME"]);
  788.         $params array('q' => $yql'format' => 'json''env' => 'http://datatables.org/alltables.env');
  789.  
  790.         if(!is_null($env)) {
  791.           $params['env'$env;
  792.         }
  793.  
  794.         $response $client->get($request_url$params30);
  795.  
  796.         if(YahooUtil::is_response_error($response)) {
  797.             return NULL;
  798.         }
  799.  
  800.         $resultSet json_decode($response["responseBody"]);
  801.  
  802.         return $resultSet;
  803.     }
  804. }
  805.  
  806. /**
  807.  * Represents a Yahoo! user.
  808.  *
  809.  * @brief Represents a Yahoo! user.
  810.  */
  811. class YahooUser {
  812.     /**
  813.      * @private
  814.      */
  815.     var $session = NULL;
  816.  
  817.     /**
  818.      * @private
  819.      */
  820.     var $guid = NULL;
  821.  
  822.     /**
  823.      * @private
  824.      */
  825.     var $sessioned = false;
  826.  
  827.     /**
  828.      * @private
  829.      */
  830.     var $client = NULL;
  831.  
  832.     /**
  833.      * @private
  834.      */
  835.     function YahooUser($session$guid$sessioned{
  836.         $this->session = $session;
  837.         $this->client = $session->client;
  838.         $this->guid = $guid;
  839.         $this->sessioned = $sessioned;
  840.     }
  841.  
  842.     /**
  843.      * Gets the user's status message.
  844.      *
  845.      * @return The status of the user or NULL if the fetch fails.
  846.      */
  847.     function getStatus({
  848.         global $YahooConfig;
  849.  
  850.         $request_url sprintf("http://%s/v1/user/%s/profile/status",
  851.         $YahooConfig["SOCIAL_WS_HOSTNAME"],urlencode($this->guid));
  852.  
  853.         $response $this->client->get($request_url);
  854.  
  855.         if(is_null($response)) {
  856.             return NULL;
  857.         }
  858.         else if($response["code"== 404{
  859.             // No presence is set, return an empty presence.
  860.  
  861.             $status new stdclass();
  862.             $status->message "";
  863.             $status->lastStatusModified NULL;
  864.             $status->uri NULL;
  865.             return $status;
  866.         }
  867.         else if($response["code"!= 200{
  868.             return NULL;
  869.         }
  870.         else {
  871.             $rsp json_decode($response["responseBody"]);
  872.             return $rsp->status;
  873.         }
  874.     }
  875.  
  876.     /**
  877.      * Sets the user's status message.
  878.      *
  879.      * @param $message The new status message for the user.
  880.      * @return The status message on success, NULL on failure.
  881.      */
  882.     function setStatus($message{
  883.         global $YahooConfig;
  884.  
  885.         if(!$this->sessioned{
  886.             YahooLogger::error("Can't set the status of an unsessioned user");
  887.             return NULL;
  888.         }
  889.  
  890.         $message array("message" => $message);
  891.         $status array("status" => $message);
  892.         $status_json json_encode($status);
  893.  
  894.         $request_url sprintf("http://%s/v1/user/%s/profile/status"$YahooConfig["SOCIAL_WS_HOSTNAME"]$this->guid);
  895.  
  896.         $response $this->client->put($request_url"application/json"$status_json);
  897.  
  898.         if(YahooUtil::is_response_error($response)) {
  899.             return NULL;
  900.         }
  901.  
  902.         $status json_decode($response["responseBody"]);
  903.         return $status;
  904.     }
  905.  
  906.     /**
  907.      * Gets the updates for the current user.
  908.      *
  909.      * @param $start The starting offset to list updates from. (default = 0)
  910.      * @param $count The number of updates to request. (default = 10)
  911.      * @return An array of updates for the current user.
  912.      */
  913.     function getUpdates($start 0$count 10{
  914.         $parameters array("start" => $start"count" => $count"transform" => '(sort "pubDate" numeric descending (all))');
  915.         $updates $this->get_resource("updates"$parameters);
  916.  
  917.         return $updates->updates;
  918.     }
  919.  
  920.     /**
  921.      * Gets the updates for the connections of the current user.
  922.      *
  923.      * @param $start The starting offset to list updates from.
  924.      * @param $count The number of updates to request.
  925.      * @return list of updates for the connections of the current user.
  926.      */
  927.     function getConnectionUpdates($start 0$count 10{
  928.         $parameters array("start" => $start"count" => $count"transform" => '(sort "pubDate" numeric descending (all))');
  929.         $updates $this->get_resource("updates/connections"$parameters);
  930.  
  931.         return $updates->updates;
  932.     }
  933.  
  934.     /**
  935.      * Inserts an update for the current user.
  936.      *
  937.      * @param $suid Identifier that globally unique for a given
  938.      *               collectionId within producing source.
  939.      * @param $title Title for the update.
  940.      * @param $link Link back to the cause of the event.
  941.      * @param $description Descriptive text associated with the update,
  942.      *                      optional.
  943.      * @param $date The date of the update event, optional, defaults to now.
  944.      */
  945.     function insertUpdate($suid$title$link$description=""$date=NULL{
  946.         global $YahooConfig;
  947.  
  948.         // Make sure this YahooUser is sessioned.
  949.         if(!$this->sessioned{
  950.             YahooLogger::error("Can't insert updates for an unsessioned user");
  951.             return NULL;
  952.         }
  953.  
  954.         if (is_null($date)) {
  955.             $date time();
  956.         }
  957.  
  958.         // Make sure an application ID was given.
  959.         $appid $this->session->getApplicationId();
  960.         if(empty($appid)) {
  961.             YahooLogger::error("No application ID given, can't insert update");
  962.             return NULL;
  963.         }
  964.  
  965.         $source sprintf("APP.%s"$appid);
  966.  
  967.         $update array(
  968.           "collectionID" => $this->guid,
  969.           "collectionType" => "guid",
  970.           "class" => "app",
  971.           "source" => $source,
  972.           "type" => 'appActivity',
  973.           "suid" => $suid,
  974.           "title" => $title,
  975.           "description" => $description,
  976.           "link" => $link,
  977.           "pubDate" => (string)$date
  978.         );
  979.  
  980.         $update_body array("updates" => array($update));
  981.         $update_body_json json_encode($update_body);
  982.  
  983.         $request_url sprintf("http://%s/v1/user/%s/updates/%s/%s"$YahooConfig["UPDATES_WS_HOSTNAME"]$this->guid$sourceurlencode($suid));
  984.  
  985.         $response $this->client->put($request_url"application/json"$update_body_json);
  986.  
  987.         return !(YahooUtil::is_response_error($response));
  988.     }
  989.  
  990.     /**
  991.      * Deletes the update of the given SUID. Only allows deleting updates
  992.      * that were inserted by your own application. You won't be able to
  993.      * delete updates from other applications.
  994.      *
  995.      * @param $suid The SUID of the update to be deleted.
  996.      * @return boolean True on success, false on failure.
  997.      */
  998.     function deleteUpdate($suid{
  999.         global $YahooConfig;
  1000.  
  1001.         // Make sure this YahooUser is sessioned.
  1002.         if(!$this->sessioned{
  1003.             YahooLogger::error("Can't delete updates for an unsessioned user");
  1004.             return FALSE;
  1005.         }
  1006.  
  1007.         // Make sure an application ID was given.
  1008.         $appid $this->session->getApplicationId();
  1009.         ifempty($appid) ) {
  1010.             YahooLogger::error("No application ID given, can't delete update");
  1011.             return FALSE;
  1012.         }
  1013.  
  1014.         $source sprintf("APP.%s"$appid);
  1015.  
  1016.         $request_url sprintf("http://%s/v1/user/%s/updates/%s/%s"$YahooConfig["UPDATES_WS_HOSTNAME"]$this->guid$sourceurlencode($suid));
  1017.  
  1018.         $response $this->client->delete($request_url);
  1019.  
  1020.         return !(YahooUtil::is_response_error($response));
  1021.     }
  1022.  
  1023.     /**
  1024.      * Loads the extended profile of the current user.
  1025.      *
  1026.      * @return The extended profile of the current user.
  1027.      */
  1028.     function getProfile({
  1029.         global $YahooConfig;
  1030.  
  1031.         $profile $this->get_resource("profile");
  1032.  
  1033.         return $profile->profile;
  1034.     }
  1035.  
  1036.     /**
  1037.      * Gets a list of connections for the current user.
  1038.      *
  1039.      * @param[in,out] $start The starting offset.
  1040.      * @param[in,out] $count The number of connections to fetch.
  1041.      * @param[out] $total The total number of contacts available.
  1042.      * @return List of connections for the current user.
  1043.      */
  1044.     function getConnections(&$start&$count&$total{
  1045.         global $YahooConfig;
  1046.  
  1047.         $parameters array("view" => "usercard""start" => $start"count" => $count);
  1048.         $connections $this->get_resource("connections",$parameters);
  1049.  
  1050.         $start $connections->connections->start;
  1051.         $count $connections->connections->count;
  1052.         $total $connections->connections->total;
  1053.  
  1054.         return $connections->connections->connection;
  1055.     }
  1056.  
  1057.     /**
  1058.      * Gets a list of contacts for the current user.
  1059.      *
  1060.      * @param $start The starting offset.
  1061.      * @param $count The number of contacts to fetch.
  1062.      * @return List of contacts for the current user.
  1063.      */
  1064.     function getContacts($start 0$count 10{
  1065.         global $YahooConfig;
  1066.  
  1067.         if(!$this->sessioned{
  1068.             YahooLogger::error("Can't get contacts for an unsessioned user");
  1069.             return NULL;
  1070.         }
  1071.  
  1072.         $parameters array("view" => "tinyusercard""start" => $start"count" => $count);
  1073.         $contacts $this->get_resource("contacts",$parameters);
  1074.  
  1075.         return $contacts;
  1076.     }
  1077.  
  1078.     function getContact($contact_id)
  1079.     {
  1080.       global $YahooConfig;
  1081.  
  1082.         if(!$this->sessioned{
  1083.             YahooLogger::error("Can't get contacts for an unsessioned user");
  1084.             return NULL;
  1085.         }
  1086.  
  1087.         $parameters array();
  1088.         $contacts $this->get_resource(sprintf("contact/%s"$contact_id)$parameters);
  1089.  
  1090.         return $contacts;
  1091.     }
  1092.  
  1093.   function getContactSync($rev 0)
  1094.     {
  1095.         global $YahooConfig;
  1096.  
  1097.         if(!$this->sessioned{
  1098.             YahooLogger::error("Can't get contacts for an unsessioned user");
  1099.             return NULL;
  1100.         }
  1101.  
  1102.         $parameters array('view' => 'sync''rev' => $rev);
  1103.         $contactsync $this->get_resource("contacts",$parameters);
  1104.  
  1105.         return $contactsync;
  1106.     }
  1107.  
  1108.     function syncContacts($contactsync)
  1109.     {
  1110.         global $YahooConfig;
  1111.  
  1112.         if(!$this->sessioned{
  1113.             YahooLogger::error("Can't get contacts for an unsessioned user");
  1114.             return NULL;
  1115.         }
  1116.  
  1117.       $parameters array('format' => 'json');
  1118.  
  1119.       $data array('contactsync' => $contactsync);
  1120.       $body json_encode($data);
  1121.  
  1122.         $request_url sprintf("http://%s/v1/user/%s/contacts"$YahooConfig["SOCIAL_WS_HOSTNAME"]$this->guid);
  1123.  
  1124.         $response $this->client->put($request_url"application/json"$body);
  1125.  
  1126.         return !(YahooUtil::is_response_error($response));
  1127.     }
  1128.  
  1129.   function addContact($contact)
  1130.     {
  1131.         global $YahooConfig;
  1132.  
  1133.         if(!$this->sessioned{
  1134.             YahooLogger::error("Can't get contacts for an unsessioned user");
  1135.             return NULL;
  1136.         }
  1137.  
  1138.     $data array('contact' => $contact);
  1139.       $body json_encode($data);
  1140.  
  1141.         $request_url sprintf("http://%s/v1/user/%s/contacts"$YahooConfig["SOCIAL_WS_HOSTNAME"]$this->guid);
  1142.  
  1143.     $response $this->client->post($request_url"application/json"$body);
  1144.  
  1145.         return !(YahooUtil::is_response_error($response));
  1146.     }
  1147.  
  1148.     /**
  1149.      * Sets the small view for the current user.
  1150.      *
  1151.      * @param $content The content to set the small view to.
  1152.      * @return True on success, false otherwise.
  1153.      */
  1154.     function setSmallView($content{
  1155.         return $this->session->application->setSmallView($this->guid$content);
  1156.     }
  1157.  
  1158.     /**
  1159.      * @private
  1160.      */
  1161.     function get_resource($resource$parameters=array())
  1162.     {
  1163.         global $YahooConfig;
  1164.  
  1165.         $request_url sprintf("http://%s/v1/user/%s/%s",
  1166.         $YahooConfig["SOCIAL_WS_HOSTNAME"]urlencode($this->guid)$resource);
  1167.  
  1168.         $response $this->client->get($request_url,$parameters);
  1169.         $data json_decode($response["responseBody"]);
  1170.  
  1171.         return (YahooUtil::is_response_error($response)) null $data;
  1172.     }
  1173.  
  1174.   ///////////////////////////////////////////////////////////////////////////
  1175.   // Deprecated methods
  1176.   ///////////////////////////////////////////////////////////////////////////
  1177.  
  1178.     /**
  1179.      * Loads the extended profile of the current user.
  1180.      * @deprecated As of 1.2, replaced by getProfile.
  1181.      * @return The extended profile of the current user.
  1182.      */
  1183.     function loadProfile({
  1184.         // method renamed, keeping for compatibility.
  1185.         YahooLogger::info("loadProfile is deprecated since 1.2: Please use getProfile");
  1186.  
  1187.         return $this->getProfile();
  1188.     }
  1189.  
  1190.     /**
  1191.      * Lists the updates for the current user.
  1192.      * @deprecated As of 1.2, replaced by getUpdates.
  1193.      *
  1194.      *
  1195.      * @param $start The starting offset to list updates from. (default = 0)
  1196.      * @param $count The number of updates to request. (default = 10)
  1197.      * @return list of updates for the current user.
  1198.      */
  1199.     function listUpdates($start 0$count 10{
  1200.        // method renamed, keeping for compatibility.
  1201.        YahooLogger::info("listUpdates is deprecated since 1.2: Please use getUpdates");
  1202.  
  1203.        return $this->getUpdates($start$count);
  1204.     }
  1205.  
  1206.     /**
  1207.      * Gets the updates for the connections of the current user.
  1208.      * @deprecated As of 1.2, replaced by getConnectionUpdates.
  1209.      * @param $start The starting offset to list updates from.
  1210.      * @param $count The number of updates to request.
  1211.      * @return An array of updates for the connections of the current user.
  1212.      */
  1213.     function listConnectionUpdates($start 0$count 10{
  1214.         // method renamed, keeping for compatibility.
  1215.         YahooLogger::info("listConnectionUpdates is deprecated since 1.2: Please use getConnectionUpdates");
  1216.  
  1217.         return $this->getConnectionUpdates($start$count);
  1218.     }
  1219.  
  1220.     /**
  1221.      * Gets the presence of the user, including the status.
  1222.      *
  1223.      * @return The presence of the user or NULL if the fetch fails.
  1224.      * @deprecated As of 1.2, replaced by getStatus
  1225.      */
  1226.     function getPresence({
  1227.         global $YahooConfig;
  1228.  
  1229.         YahooLogger::info("getPresence is deprecated since 1.2: Please use getStatus.");
  1230.  
  1231.         $request_url sprintf("http://%s/v1/user/%s/presence/presence",
  1232.         $YahooConfig["PRESENCE_WS_HOSTNAME"],urlencode($this->guid));
  1233.  
  1234.         $response $this->client->get($request_url);
  1235.  
  1236.         if(is_null($response)) {
  1237.             return NULL;
  1238.         }
  1239.         else if($response["code"== 404{
  1240.             // No presence is set, return an empty presence.
  1241.             $presence new stdclass();
  1242.             $presence->value new stdclass();
  1243.             $presence->value->status "";
  1244.             return $presence;
  1245.         }
  1246.         else if($response["code"!= 200{
  1247.             return NULL;
  1248.         }
  1249.         else {
  1250.             $presence json_decode($response["responseBody"]);
  1251.             return $presence->presence;
  1252.         }
  1253.     }
  1254.  
  1255.     /**
  1256.      * Sets the presence of the user.
  1257.      *
  1258.      * @param $status The new status message for the user.
  1259.      * @return The status message on success, NULL on failure.
  1260.      * @deprecated As of 1.2, replaced by setStatus
  1261.      */
  1262.     function setPresence($status{
  1263.         global $YahooConfig;
  1264.  
  1265.         YahooLogger::info("setPresence is deprecated since 1.2: Please use setStatus");
  1266.  
  1267.         if(!$this->sessioned{
  1268.             YahooLogger::error("Can't set the presence of an unsessioned user");
  1269.             return NULL;
  1270.         }
  1271.  
  1272.         $presence array("status" => $status);
  1273.         $presence_json json_encode($presence);
  1274.  
  1275.         $request_url sprintf("http://%s/v1/user/%s/presence/presence"$YahooConfig["PRESENCE_WS_HOSTNAME"]$this->guid);
  1276.  
  1277.         $response $this->client->put($request_url"application/json"$presence_json);
  1278.  
  1279.         if(YahooUtil::is_response_error($response)) {
  1280.             return NULL;
  1281.         }
  1282.  
  1283.         $presence json_decode($response["responseBody"]);
  1284.         return $presence;
  1285.     }
  1286.  
  1287.   ///////////////////////////////////////////////////////////////////////////
  1288.   // End Deprecated methods
  1289.   ///////////////////////////////////////////////////////////////////////////
  1290. }
  1291.  
  1292. /**
  1293.  * @private
  1294.  */
  1295.     function getRequestToken($consumerKey$consumerSecret$callback{
  1296.         global $YahooConfig;
  1297.  
  1298.         if(is_null($callback)) {
  1299.             $callback "oob";
  1300.         }
  1301.  
  1302.         $consumer new OAuthConsumer($consumerKey$consumerSecret);
  1303.         $client new OAuthClient($consumerNULLOAUTH_PARAMS_IN_POST_BODYOAUTH_SIGNATURE_HMAC_SHA1);
  1304.  
  1305.         $request_url sprintf("https://%s/oauth/v2/get_request_token"$YahooConfig["OAUTH_HOSTNAME"]);
  1306.         $parameters array("oauth_callback" => $callback);
  1307.  
  1308.         $response $client->post($request_url"application/x-www-form-urlencoded"$parameters);
  1309.  
  1310.         if(is_null($response)) {
  1311.             YahooLogger::error("OAuth call to get request token failed");
  1312.             return NULL;
  1313.         }
  1314.  
  1315.         parse_str($response["responseBody"]$token);
  1316.  
  1317.         if($response["code"!= 200{
  1318.             $problem array_key_exists("oauth_problem"$token?
  1319.                     $token["oauth_problem""unknown problem";
  1320.             YahooLogger::error("Failed to create request token: $problem");
  1321.             return NULL;
  1322.         }
  1323.  
  1324.         if(!array_key_exists("oauth_callback_confirmed"$token||
  1325.                 !$token["oauth_callback_confirmed"]{
  1326.             // Callback wasn't confirmed.
  1327.             YahooLogger::error("Failed to create request token: callback was not confirmed");
  1328.             return NULL;
  1329.         }
  1330.  
  1331.         $requestToken new stdclass();
  1332.         $requestToken->key $token["oauth_token"];
  1333.         $requestToken->secret $token["oauth_token_secret"];
  1334.         return $requestToken;
  1335.     }
  1336.  
  1337.     function createAuthorizationUrl($requestToken{
  1338.         global $YahooConfig;
  1339.  
  1340.         if(!is_object($requestToken|| !property_exists($requestToken"key")) {
  1341.             YahooLogger::error("Request token doesn't have a 'key' property");
  1342.             return NULL;
  1343.         }
  1344.  
  1345.         return sprintf("https://%s/oauth/v2/request_auth?oauth_token=%s"$YahooConfig["OAUTH_HOSTNAME"]urlencode($requestToken->key));
  1346.     }
  1347.  
  1348.     function getAccessToken($consumerKey$consumerSecret$requestToken$verifier{
  1349.         $at YahooAuthorization::getAccessTokenProxy($consumerKey$consumerSecret$requestToken$verifier);
  1350.  
  1351.         if(is_null($at)) {
  1352.             // Failed to fetch the access token, sleep for 250ms and
  1353.             // then try one more time.
  1354.             YahooLogger::info("Failed to fetch access token, retrying");
  1355.             usleep(250000);
  1356.             $at YahooAuthorization::getAccessTokenProxy($consumerKey$consumerSecret$requestToken$verifier);
  1357.         }
  1358.  
  1359.         return $at;
  1360.     }
  1361.  
  1362.     function getAccessTokenProxy($consumerKey$consumerSecret$requestToken$verifier{
  1363.         global $YahooConfig;
  1364.  
  1365.         $request_url sprintf("https://%s/oauth/v2/get_token"$YahooConfig["OAUTH_HOSTNAME"]);
  1366.  
  1367.         $consumer new OAuthConsumer($consumerKey$consumerSecret);
  1368.  
  1369.         $parameters array();
  1370.         if(property_exists($requestToken"sessionHandle")) {
  1371.             $parameters["oauth_session_handle"$requestToken->sessionHandle;
  1372.         }
  1373.  
  1374.         if(!is_null($verifier)) {
  1375.             $parameters["oauth_verifier"$verifier;
  1376.         }
  1377.  
  1378.         $client new OAuthClient($consumer$requestTokenOAUTH_PARAMS_IN_POST_BODY);
  1379.  
  1380.         $response $client->post($request_url"application/x-www-form-urlencoded"$parameters);
  1381.  
  1382.         if(is_null($response)) {
  1383.             YahooLogger::error("OAuth call to get access token failed");
  1384.             return NULL;
  1385.         }
  1386.  
  1387.         parse_str($response["responseBody"]$token);
  1388.  
  1389.         if($response["code"!= 200{
  1390.             YahooLogger::error("Failed to fetch access token: " $token["oauth_problem"]);
  1391.             return NULL;
  1392.         }
  1393.  
  1394.         $now time();
  1395.  
  1396.         $accessToken new stdclass();
  1397.         $accessToken->key $token["oauth_token"];
  1398.         $accessToken->secret $token["oauth_token_secret"];
  1399.         $accessToken->guid $token["xoauth_yahoo_guid"];
  1400.         $accessToken->consumer $consumerKey;
  1401.         $accessToken->sessionHandle $token["oauth_session_handle"];
  1402.  
  1403.         // Check to see if the access token ever expires.
  1404.         YahooLogger::debug('AT expires in '.$token['oauth_expires_in'].'; ASH expires in '.$token["oauth_authorization_expires_in"]);
  1405.         if(array_key_exists("oauth_expires_in"$token)) {
  1406.             $accessToken->tokenExpires $now $token["oauth_expires_in"];
  1407.         }
  1408.         else {
  1409.             $accessToken->tokenExpires = -1;
  1410.         }
  1411.  
  1412.         // Check to see if the access session handle ever expires.
  1413.         if(array_key_exists("oauth_authorization_expires_in"$token)) {
  1414.             $accessToken->handleExpires $now +
  1415.                     $token["oauth_authorization_expires_in"];
  1416.         }
  1417.         else {
  1418.             $accessToken->handleExpires = -1;
  1419.         }
  1420.         return $accessToken;
  1421.     }
  1422. }
  1423.  
  1424. /**
  1425.  * Cookie-based implementation of the session store. This is the default
  1426.  * session storage used by the Y!OS PHP SDK. Developers are free to
  1427.  * implement their own session store implementations and pass them to
  1428.  * YahooSession::hasSession, YahooSession::requireSession and
  1429.  * YahooSession::clearSession. By default, if no session store is passed
  1430.  * to YahooSession::hasSession or YahooSession::requireSession, an instance
  1431.  * of a NativeSessionStore is used.
  1432.  *
  1433.  * @brief Cookie-based implementation of the session store.
  1434.  */
  1435.     /**
  1436.      * Indicates if the session store has a request token.
  1437.      *
  1438.      * @return True if a request token is present, false otherwise.
  1439.      */
  1440.     function hasRequestToken({
  1441.         return array_key_exists("yosdk_rt"$_COOKIE&& (strlen($_COOKIE["yosdk_rt"]0);
  1442.     }
  1443.  
  1444.     /**
  1445.      * Indicates if the session store has an access token.
  1446.      *
  1447.      * @return True if an access token is present, false otherwise.
  1448.      */
  1449.     function hasAccessToken({
  1450.         return array_key_exists("yosdk_at"$_COOKIE&& (strlen($_COOKIE["yosdk_at"]0);
  1451.     }
  1452.  
  1453.     /**
  1454.      * Stores the given request token in the session store.
  1455.      *
  1456.      * @param $token A PHP stdclass object containing the components of
  1457.      *                the OAuth request token.
  1458.      * @return True on success, false otherwise.
  1459.      */
  1460.     function storeRequestToken($token{
  1461.         if(!headers_sent()) {
  1462.             return setcookie("yosdk_rt"base64_encode(json_encode($token))time(600);
  1463.         }
  1464.         else {
  1465.             return false;
  1466.         }
  1467.     }
  1468.  
  1469.     /**
  1470.      * Fetches and returns the request token from the session store.
  1471.      *
  1472.      * @return The request token.
  1473.      */
  1474.     function fetchRequestToken({
  1475.         return json_decode(base64_decode($_COOKIE["yosdk_rt"]));
  1476.     }
  1477.  
  1478.     /**
  1479.      * Clears the request token from the session store.
  1480.      *
  1481.      * @return True on success, false otherwise.
  1482.      */
  1483.     function clearRequestToken({
  1484.         if(!headers_sent()) {
  1485.             return setcookie("yosdk_rt"""time(600);
  1486.         }
  1487.         else {
  1488.             return false;
  1489.         }
  1490.     }
  1491.  
  1492.     /**
  1493.      * Stores the given access token in the session store.
  1494.      *
  1495.      * @param $token A PHP stdclass object containing the components of
  1496.      *                the OAuth access token.
  1497.      * @return True on success, false otherwise.
  1498.      */
  1499.     function storeAccessToken($token{
  1500.         if(!headers_sent()) {
  1501.             return setcookie("yosdk_at"base64_encode(json_encode($token)),
  1502.                     time((30 24 60 60));
  1503.         }
  1504.         else {
  1505.             return false;
  1506.         }
  1507.     }
  1508.  
  1509.     /**
  1510.      * Fetches and returns the access token from the session store.
  1511.      *
  1512.      * @return The access token.
  1513.      */
  1514.     function fetchAccessToken({
  1515.         return json_decode(base64_decode($_COOKIE["yosdk_at"]));
  1516.     }
  1517.  
  1518.     /**
  1519.      * Clears the access token from the session store.
  1520.      *
  1521.      * @return True on success, false otherwise.
  1522.      */
  1523.     function clearAccessToken({
  1524.         if(!headers_sent()) {
  1525.             return setcookie("yosdk_at"""time(600);
  1526.         }
  1527.         else {
  1528.             return false;
  1529.         }
  1530.     }
  1531. }
  1532.  
  1533. /**
  1534.  * PHP session based implementation of the session store. This is the default
  1535.  * session storage used by the Y!OS PHP SDK. Developers are free to
  1536.  * implement their own session store implementations and pass them to
  1537.  * YahooSession::hasSession, YahooSession::requireSession and
  1538.  * YahooSession::clearSession. By default, if no session store is passed
  1539.  * to YahooSession::hasSession or YahooSession::requireSession, an instance
  1540.  * of a NativeSessionStore is used.
  1541.  *
  1542.  * @brief Native php session based implementation of the session store, by default
  1543.  *  stored on file system, but can be database or memcache backend.
  1544.  */
  1545.  
  1546.     function NativeSessionStore({
  1547.       $id session_id();
  1548.       if(empty($id)) {
  1549.         session_start();
  1550.       }
  1551.     }
  1552.  
  1553.     /**
  1554.      * Indicates if the session store has a request token.
  1555.      *
  1556.      * @return True if a request token is present, false otherwise.
  1557.      */
  1558.     function hasRequestToken({
  1559.         return array_key_exists("yosdk_rt"$_SESSION&& (strlen($_SESSION["yosdk_rt"]0);
  1560.     }
  1561.  
  1562.     /**
  1563.      * Indicates if the session store has an access token.
  1564.      *
  1565.      * @return True if an access token is present, false otherwise.
  1566.      */
  1567.     function hasAccessToken({
  1568.         return array_key_exists("yosdk_at"$_SESSION&& (strlen($_SESSION["yosdk_at"]0);
  1569.     }
  1570.  
  1571.     /**
  1572.      * Stores the given request token in the session store.
  1573.      *
  1574.      * @param $token A PHP stdclass object containing the components of the OAuth request token.
  1575.      */
  1576.     function storeRequestToken($token{
  1577.         $_SESSION['yosdk_rt'json_encode($token);
  1578.     }
  1579.  
  1580.     /**
  1581.      * Fetches and returns the request token from the session store.
  1582.      *
  1583.      * @return The request token.
  1584.      */
  1585.     function fetchRequestToken({
  1586.         return isset($_SESSION["yosdk_rt"]json_decode($_SESSION["yosdk_rt"]false;
  1587.     }
  1588.  
  1589.     /**
  1590.      * Clears the request token from the session store.
  1591.      *
  1592.      */
  1593.     function clearRequestToken({
  1594.         unset($_SESSION['yosdk_rt']);
  1595.     }
  1596.  
  1597.     /**
  1598.      * Stores the given access token in the session store.
  1599.      *
  1600.      * @param $token A PHP stdclass object containing the components of the OAuth access token.
  1601.      */
  1602.     function storeAccessToken($token{
  1603.         $_SESSION['yosdk_at'json_encode($token);
  1604.     }
  1605.  
  1606.     /**
  1607.      * Fetches and returns the access token from the session store.
  1608.      *
  1609.      * @return The access token.
  1610.      */
  1611.     function fetchAccessToken({
  1612.         return isset($_SESSION["yosdk_at"]json_decode($_SESSION["yosdk_at"]false;
  1613.     }
  1614.  
  1615.     /**
  1616.      * Clears the access token from the session store.
  1617.      *
  1618.      */
  1619.     function clearAccessToken({
  1620.         unset($_SESSION['yosdk_at']);
  1621.     }
  1622. }
  1623.  
  1624. /**
  1625.  * A simple OAuth client class for making 2 and 3 legged OAuth HTTP requests.
  1626.  *
  1627.  * @brief A simple OAuth client class for making 2 and 3 legged OAuth HTTP requests.
  1628.  */
  1629. class OAuthClient {
  1630.     /**
  1631.      * @private
  1632.      */
  1633.     var $consumer = NULL;
  1634.  
  1635.     /**
  1636.      * @private
  1637.      */
  1638.     var $token = NULL;
  1639.  
  1640.     /**
  1641.      * @private
  1642.      */
  1643.     var $defaultTimeout = 3;
  1644.  
  1645.     /**
  1646.      * @private
  1647.      */
  1648.     var $oauthParamsLocation = NULL;
  1649.  
  1650.     /**
  1651.      * @private
  1652.      */
  1653.     var $signatureMethod = NULL;
  1654.  
  1655.     /**
  1656.      * @private
  1657.      */
  1658.     var $accepts = "application/json";
  1659.  
  1660.     /**
  1661.      * Constructs a new OAuth client.
  1662.      *
  1663.      * @param $consumer The OAuthConsumer object to use for the requests.
  1664.      * @param $token The OAuthToken to use for the requests. Optional.
  1665.      * @param $oauthParamsLocation OAUTH_PARAMS_IN_HEADERS or OAUTH_PARAMS_IN_POST_BODY, depending on where you want the OAuth parameters to show up. Optional, defaults to using the headers.
  1666.      * @param $signatureMethod OAUTH_SIGNATURE_PLAINTEXT or OAUTH_SIGNATURE_HMAC_SHA1, depending on what request signing mechanism to use. Optional, defaults to HMAC SHA1 signatures.
  1667.      */
  1668.     function OAuthClient($consumer$token NULL$oauthParamsLocation OAUTH_PARAMS_IN_HEADERS$signatureMethod OAUTH_SIGNATURE_HMAC_SHA1{
  1669.         $this->consumer = $consumer;
  1670.         $this->token = $token;
  1671.         $this->oauthParamsLocation = $oauthParamsLocation;
  1672.  
  1673.         if($signatureMethod == OAUTH_SIGNATURE_HMAC_SHA1{
  1674.             $this->signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
  1675.         }
  1676.         else if($signatureMethod == OAUTH_SIGNATURE_PLAINTEXT{
  1677.             $this->signatureMethod = new OAuthSignatureMethod_PLAINTEXT();
  1678.         }
  1679.         else {
  1680.             YahooLogger::error("Invalid signature method: $signatureMethod");
  1681.         }
  1682.     }
  1683.  
  1684.     /**
  1685.      * Executes a properly signed OAuth HTTP GET request.
  1686.      *
  1687.      * @param $url The URL to request.
  1688.      * @param $queryParameters Any query string parameters to be sent in the request.
  1689.      * @param $timeout Optional, the number of seconds to wait for the request to return.
  1690.      * @return The response object.
  1691.      */
  1692.     function get($url$queryParameters array()$timeout NULL{
  1693.         if(strpos($url"?"!== FALSE{
  1694.             YahooLogger::error("Put the query parameters in the second argument to OAuthClient::get(), not in the URL itself: URL = $url");
  1695.             return NULL;
  1696.         }
  1697.  
  1698.         return $this->request(array(
  1699.                 "method" => "GET",
  1700.                 "url" => $url,
  1701.                 "query" => $queryParameters,
  1702.                 "timeout" => $timeout));
  1703.     }
  1704.  
  1705.     /**
  1706.      * Executes a properly signed OAuth HTTP DELETE request.
  1707.      *
  1708.      * @param $url The URL to request.
  1709.      * @param $queryParameters Any query string parameters to be sent in the request.
  1710.      * @param $timeout Optional, the number of seconds to wait for the request to return.
  1711.      * @return The response object.
  1712.      */
  1713.     function delete($url$queryParameters array()$timeout NULL{
  1714.         if(strpos($url"?"!== FALSE{
  1715.             YahooLogger::error("Put the query parameters in the second argument to OAuthClient::delete(), not in the URL itself: URL = $url");
  1716.             return NULL;
  1717.         }
  1718.  
  1719.         return $this->request(array(
  1720.                 "method" => "DELETE",
  1721.                 "url" => $url,
  1722.                 "query" => $queryParameters,
  1723.                 "timeout" => $timeout));
  1724.     }
  1725.  
  1726.     /**
  1727.      * Executes a properly signed OAuth HTTP PUT request.
  1728.      *
  1729.      * @param $url The URL to request.
  1730.      * @param $contentType The Content-Type of the PUT data.
  1731.      * @param $content The raw content to be PUT.
  1732.      * @param $timeout Optional, the number of seconds to wait for the request to return.
  1733.      * @return The response object.
  1734.      */
  1735.     function put($url$contentType$content$timeout NULL{
  1736.         return $this->request(array(
  1737.                 "method" => "PUT",
  1738.                 "url" => $url,
  1739.                 "content" => $content,
  1740.                 "contentType" => $contentType,
  1741.                 "timeout" => $timeout));
  1742.     }
  1743.  
  1744.     /**
  1745.      * Executes a properly signed OAuth HTTP POST request.
  1746.      *
  1747.      * @param $url The URL to request.
  1748.      * @param $contentType The Content-Type of the POST data.
  1749.      * @param $content The content to be POST.
  1750.      * @param $timeout Optional, the number of seconds to wait for the request to return.
  1751.      * @return The response object.
  1752.      */
  1753.     function post($url$contentType "application/x-www-form-urlencoded",
  1754.                 $content array()$timeout NULL{
  1755.         return $this->request(array(
  1756.                 "method" => "POST",
  1757.                 "url" => $url,
  1758.                 "content" => $content,
  1759.                 "contentType" => $contentType,
  1760.                 "timeout" => $timeout));
  1761.     }
  1762.  
  1763.     /**
  1764.      * @private
  1765.      */
  1766.     function request($request{
  1767.         if(!array_key_exists("content"$request)) {
  1768.             $request["content"array();
  1769.         }
  1770.         if(!array_key_exists("query"$request)) {
  1771.             $request["query"array();
  1772.         }
  1773.  
  1774.         if(is_array($request["content"])) {
  1775.             $combinedParams array_merge(
  1776.                     $request["query"]$request["content"]);
  1777.         }
  1778.         else {
  1779.             $combinedParams $request["query"];
  1780.         }
  1781.  
  1782.         $oauthRequest OAuthRequest::from_consumer_and_token(
  1783.                 $this->consumer$this->token$request["method"],
  1784.                 $request["url"]$combinedParams);
  1785.         $oauthRequest->sign_request($this->signatureMethod$this->consumer,
  1786.                 $this->token);
  1787.  
  1788.         $headers array("Accept: " $this->accepts);
  1789.         if($this->oauthParamsLocation == OAUTH_PARAMS_IN_HEADERS{
  1790.             $headers[$oauthRequest->to_header();
  1791.         }
  1792.         if(!empty($request["content"]|| $this->oauthParamsLocation == OAUTH_PARAMS_IN_POST_BODY{
  1793.             $headers["Content-Type: " $request["contentType"];
  1794.         }
  1795.  
  1796.         if(!empty($request["query"])) {
  1797.             $requestUrl sprintf("%s?%s"$request["url"]oauth_http_build_query($request["query"]));
  1798.         }
  1799.         else {
  1800.             $requestUrl $request["url"];
  1801.         }
  1802.  
  1803.         $requestTimeout array_key_exists("timeout"$request?
  1804.         $request["timeout"$this->defaultTimeout;
  1805.  
  1806.         $ch curl_init($requestUrl);
  1807.         curl_setopt($chCURLOPT_TIMEOUT$requestTimeout);
  1808.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  1809.         curl_setopt($chCURLOPT_HTTPHEADER$headers);
  1810.         curl_setopt($chCURLOPT_CUSTOMREQUEST$request["method"]);
  1811.         if(($this->oauthParamsLocation == OAUTH_PARAMS_IN_POST_BODY||
  1812.                 (!empty($request["content"]&& is_array($request["content"]))) {
  1813.             // Content is an array, URL encode it.
  1814.             if($this->oauthParamsLocation == OAUTH_PARAMS_IN_POST_BODY{
  1815.                 $request["content"$oauthRequest->to_postdata();
  1816.                 curl_setopt($chCURLOPT_POSTFIELDS$request["content"]);
  1817.             }
  1818.             else {
  1819.                 curl_setopt($chCURLOPT_POSTFIELDSoauth_http_build_query($request["content"]));
  1820.             }
  1821.         }
  1822.         else if(!empty($request["content"])) {
  1823.             // Content is raw.
  1824.             curl_setopt($chCURLOPT_POSTFIELDS$request["content"]);
  1825.         }
  1826.  
  1827.         // Enable compressed responses from the servers.
  1828.         curl_setopt($chCURLOPT_ENCODING"");
  1829.  
  1830.         // Set the user agent so the SDK properly identifies itself for
  1831.         // usage tracking purposes. Include the version of the SDK and
  1832.         // the version of PHP being used.
  1833.         $sdkVersion "1.2";
  1834.         $agent sprintf("YosPhpSdk/%s php/%s"$sdkVersionphpversion());
  1835.         curl_setopt($chCURLOPT_USERAGENT$agent);
  1836.  
  1837.         $headerParser new YahooHeaderParser();
  1838.         curl_setopt($chCURLOPT_HEADERFUNCTIONarray(&$headerParser"read"));
  1839.         $response curl_exec($ch);
  1840.         if(is_bool($response&& !$response{
  1841.             YahooLogger::error("Error making libcurl request(" $requestUrl "): " curl_error($ch));
  1842.             return NULL;
  1843.         }
  1844.  
  1845.         $response array(
  1846.             'method' => $request["method"],
  1847.             'url' => $requestUrl,
  1848.             'code' => curl_getinfo($chCURLINFO_HTTP_CODE),
  1849.             'requestHeaders' => $headers,
  1850.             'requestBody' => !empty($request["content"]$request["content"NULL,
  1851.             'responseHeaders' => $headerParser->headers,
  1852.             'responseBody' => $response
  1853.             );
  1854.  
  1855.  
  1856.         if(($response["code"200&& ($response["code"300)) {
  1857.             YahooLogger::error("HTTP request failed"$response);
  1858.  
  1859.             $this->checkExpired($response["code"]$headerParser);
  1860.             return NULL;
  1861.         }
  1862.         YahooLogger::debug("HTTP request details"$response);
  1863.  
  1864.         return $response;
  1865.     }
  1866.  
  1867.     /**
  1868.      * Checks to see if the code and headers indicate an expired OAuth token.
  1869.      * If so, requests a new one.
  1870.      *
  1871.      * @private
  1872.      */
  1873.     function checkExpired($code$headerParser{
  1874.         if ($code != 401return// HTTP Unauthorized
  1875.         $authenticateHeader $headerParser->get('WWW-Authenticate');
  1876.         if (!$authenticateHeaderreturn;
  1877.         if (!preg_match('/oauth_problem="([^"]+)"/'$authenticateHeader$match)) return;
  1878.         $oauth_problem $match[1];
  1879.         if ($oauth_problem == 'token_expired'{
  1880.             YahooLogger::error('Access token expired. Please fetch a new one');
  1881.         }
  1882.         if ($oauth_problem == 'consumer_key_unknown'{
  1883.             YahooLogger::error('Consumer Key unkown.  Please check that the Consumer Key is valid.');
  1884.         }
  1885.         if ($oauth_problem == 'additional_authorization_required'{
  1886.             YahooLogger::error('The app identified by this Consumer Key is not authorized to access this resource.  Authorization is defined under Access Scopes on the application\'s settings page.');
  1887.         }
  1888.     }
  1889. }
  1890.  
  1891. /**
  1892.  * @private
  1893.  */
  1894.     var $headers = array();
  1895.  
  1896.     function YahooHeaderParser({
  1897.     }
  1898.  
  1899.     function read($ch$header{
  1900.         $pos strpos($header":");
  1901.         if($pos !== FALSE{
  1902.             $name substr($header0$pos);
  1903.             $value trim(substr($header$pos 1));
  1904.             $this->headers[$name$value;
  1905.         }
  1906.         return strlen($header);
  1907.     }
  1908.  
  1909.     function get($name{
  1910.         if(array_key_exists($name$this->headers)) {
  1911.             return $this->headers[$name];
  1912.         }
  1913.         else {
  1914.             return NULL;
  1915.         }
  1916.     }
  1917. }
  1918.  
  1919. /**
  1920.  * Interface to modify the underlying configuration of the library.
  1921.  */
  1922. class YahooConfig {
  1923.     function setSocialWsHostname($hostname{
  1924.         global $YahooConfig;
  1925.         $YahooConfig["SOCIAL_WS_HOSTNAME"$hostname;
  1926.     }
  1927.  
  1928.     function setPresenceWsHostname($hostname{
  1929.         global $YahooConfig;
  1930.         $YahooConfig["PRESENCE_WS_HOSTNAME"$hostname;
  1931.     }
  1932.  
  1933.     function setUpdatesWsHostname($hostname{
  1934.         global $YahooConfig;
  1935.         $YahooConfig["UPDATES_WS_HOSTNAME"$hostname;
  1936.     }
  1937.  
  1938.     function setQueryWsHostname($hostname{
  1939.         global $YahooConfig;
  1940.         $YahooConfig["QUERY_WS_HOSTNAME"$hostname;
  1941.     }
  1942.  
  1943.     function setOauthHostname($hostname{
  1944.         global $YahooConfig;
  1945.         $YahooConfig["OAUTH_HOSTNAME"$hostname;
  1946.     }
  1947.  
  1948.     function setYapWsHostname($hostname{
  1949.         global $YahooConfig;
  1950.         $YahooConfig["YAP_WS_HOSTNAME"$hostname;
  1951.     }
  1952. }
  1953.  
  1954. /**
  1955.  * An OAuth compatible version of http_build_query. http_build_query
  1956.  * doesn't work because it turns spaces into "+", which isn't allowed
  1957.  * by OAuth.
  1958.  */
  1959. function oauth_http_build_query($parameters{
  1960.     $strings array();
  1961.     foreach($parameters as $name => $value{
  1962.         $strings[sprintf("%s=%s"rawurlencode($name)rawurlencode($value));
  1963.     }
  1964.     $query implode("&"$strings);
  1965.     return $query;
  1966. }
  1967.  
  1968. /**
  1969.  * PHP4/5 compatibility functions
  1970.  */
  1971. if(!function_exists("property_exists")) {
  1972.     function property_exists$class$property {
  1973.         if is_object$class ) ) {
  1974.             $vars get_object_vars$class );
  1975.         else {
  1976.             $vars get_class_vars$class );
  1977.         }
  1978.         return array_key_exists$property$vars );
  1979.     }
  1980. }
  1981.  
  1982. // If json_decode doesn't exist, then php-json must not be included in this
  1983. // version of PHP. Include fake versions of json_encode/json_decode that
  1984. // are backed by the native PHP php-json library, which is available in PEAR.
  1985. if(!function_exists("json_decode")) {
  1986.     // Only include JSON.php if someone else hasn't already. Depending on
  1987.     // the operating environment, other code may have brought their own
  1988.     // version of that source code.
  1989.     if(!class_exists("Services_JSON")) {
  1990.         include_once("JSON.php");
  1991.     }
  1992.  
  1993.     function json_decode($json{
  1994.         $js new Services_JSON();
  1995.         return $js->decode($json);
  1996.     }
  1997.  
  1998.     function json_encode($value{
  1999.         $js new Services_JSON();
  2000.         return $js->encode($value);
  2001.     }
  2002. }

Documentation generated on Thu, 22 Oct 2009 12:54:51 -0700 by phpDocumentor 1.4.3