Source for file Yahoo.inc
Documentation is available at Yahoo.inc
* YOS PHP SDK for accessing social and data apis at Yahoo!
* @package yos-social-php
* @author Yahoo! Developer Network
* @example http://developer.yahoo.com/social/sdk/php/
* @copyright Copyright (c) 2009 Yahoo! Inc. All rights reserved.
* @license BSD License (http://www.opensource.org/licenses/bsd-license.php)
* The copyrights embodied in the content of this file are licensed under the
* BSD (revised) open source license.
* Redistribution and use of this software in source and binary forms, with
* or without modification, are permitted provided that the following
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
* * Neither the name of Yahoo! Inc. nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior
* written permission of Yahoo! Inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* Please see the Yahoo! Developer Network forums for support: http://developer.yahoo.net/forum/
* Documentation: http://developer.yahoo.com/social/sdk/php/
// Use OAuthConsumer as a test to see if any other instances of OAuth.php may
// have been included. require_once() won't catch situations where multiple
// copies of OAuth.php are included by different parts of an application.
require_once("OAuth.php");
define("OAUTH_PARAMS_IN_HEADERS", "HEADERS");
define("OAUTH_PARAMS_IN_POST_BODY", "POSTBODY");
define("OAUTH_SIGNATURE_PLAINTEXT", "PLAINTEXT");
define("OAUTH_SIGNATURE_HMAC_SHA1", "HMAC_SHA1");
define("YAHOO_YAP_SESSION_TYPE", "YAHOO_YAP_SESSION_TYPE");
define("YAHOO_OAUTH_RT_SESSION_TYPE", "YAHOO_OAUTH_RT_SESSION_TYPE");
define("YAHOO_OAUTH_AT_SESSION_TYPE", "YAHOO_OAUTH_AT_SESSION_TYPE");
"SOCIAL_WS_HOSTNAME" =>
"social.yahooapis.com",
"PRESENCE_WS_HOSTNAME" =>
"social.yahooapis.com",
"UPDATES_WS_HOSTNAME" =>
"social.yahooapis.com",
"QUERY_WS_HOSTNAME" =>
"query.yahooapis.com",
"OAUTH_HOSTNAME" =>
"api.login.yahoo.com",
"YAP_WS_HOSTNAME" =>
"appstore.apps.yahooapis.com"
$GLOBAL_YAHOO_SESSION =
NULL;
$GLOBAL_YAHOO_LOGGER_DEBUG =
false;
$GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION =
"LOG";
global $YahooConfig, $GLOBAL_YAHOO_SESSION, $GLOBAL_YAHOO_LOGGER_DEBUG, $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
return sprintf("http://%s%s",$_SERVER["HTTP_HOST"],$_SERVER["REQUEST_URI"]);
$oauth_consumer =
new OAuthConsumer($consumer->key, $consumer->secret);
$oauth_token =
($token) ?
new OAuthToken($token->key, $token->secret) :
NULL;
$ok =
$oauth_signature_method->check_signature($oauth_request, $oauth_consumer, $oauth_token, $oauth_signature);
return (isset
($_POST['yap_appid'])
&& isset
($_POST['yap_view']));
return (is_null($response) ||
$response["code"] !=
200);
* Logging wrapper for the Yahoo objects.
* @brief Logging wrapper for the Yahoo objects.
* Log a message at the debug level.
* @param $message The message to log.
function debug($message, $object =
NULL) {
global $GLOBAL_YAHOO_LOGGER_DEBUG;
global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
if($GLOBAL_YAHOO_LOGGER_DEBUG) {
if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION ==
"CONSOLE") {
print
("DEBUG - $message\n");
print
("DEBUG OBJECT - " .
print_r($object, true) .
"\n");
else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION ==
"LOG") {
* Log a message at the info level.
* @param $message The message to log.
function info($message, $object =
NULL) {
global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION ==
"CONSOLE") {
print
("INFO - $message\n");
print
("INFO OBJECT - " .
print_r($object, true) .
"\n");
else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION ==
"LOG") {
* Log a message at the error level.
* @param $message The message to log.
function error($message, $object =
NULL) {
global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION ==
"CONSOLE") {
print
("ERROR - $message\n");
print
("ERROR OBJECT - " .
print_r($object, true) .
"\n");
else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION ==
"LOG") {
* Enables/disables session debugging.
* @param $debug Boolean to enable/disable debugging.
global $GLOBAL_YAHOO_LOGGER_DEBUG;
$GLOBAL_YAHOO_LOGGER_DEBUG = (bool)
$debug;
* Allows callers to configure where debugging output is sent.
* @param $destination "LOG" to use YahooLogger::error, "CONSOLE" to use printf,
* "NULL" to disable all logging output.
* @return boolean True on success, false on failure.
global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
if($destination ==
"LOG" ||
$destination ==
"CONSOLE" ||
$destination ==
"NULL") {
$GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION =
$destination;
* Defines a session between an application and the Yahoo! platform.
* @brief Defines a session between an application and the Yahoo! platform.
function YahooSession($consumer, $accessToken, $applicationId)
$this->guid =
$accessToken->guid;
* Gets the currently sessioned user.
* @return YahooUser The currently sessioned YahooUser.
* Gets the user who owns the application install.
* Only valid when viewed in YAP, otherwise will default
* @return YahooUser The currently sessioned YahooUser.
* Gets the user indicated by the GUID given.
* @param $guid The GUID of the user to get.
* @return YahooUser The user indicated by the GUID given.
* Executes the given YQL query.
* @param $yql The query to execute.
* @param $env A URL to a YQL environment file.
* @return The response or NULL if the request fails..
function query($yql, $env=
NULL) {
// TODO: throw a YahooException
* Destroys the current session, effectively logging out the current
* @param $sessionStore The session store implementation to clear. See
* YahooSessionStore for more information. If no
* session store is provided, clearSession will
* instantiate a NativeSessionStore and use that.
global $GLOBAL_YAHOO_SESSION;
$sessionStore->clearRequestToken();
$sessionStore->clearAccessToken();
$GLOBAL_YAHOO_SESSION =
NULL;
* Checks to see if there is a session in this PHP page request.
* Doesn't cause any redirects for the user to log in, for that
* you should call requireSession().
* @param $consumerKey The OAuth consumer key.
* @param $consumerSecret The OAuth consumer key secret.
* @param $applicationId The application ID, optional.
* @param $sessionStore The session store implementation to use. See
* YahooSessionStore for more information. If no
* session store is provided, clearSession will
* instantiate a NativeSessionStore and use that.
* @return boolean True if a session is present, false otherwise.
function hasSession($consumerKey, $consumerSecret, $applicationId =
NULL, $sessionStore =
NULL, $verifier =
NULL)
$verifier =
$_GET["oauth_verifier"];
$session =
YahooSession::initSession($consumerKey, $consumerSecret, $applicationId, FALSE, NULL, $sessionStore, $verifier);
* Requires that there be a session in this PHP page request. Generates
* a redirect for the user to log in, if necessary. You must call
* requireSession() before any data is sent back to the user in order
* for the redirect to work.
* @param $consumerKey The OAuth consumer key.
* @param $consumerSecret The OAuth consumer key secret.
* @param $applicationId The application ID, optional.
* @param $callback The callback URL to redirect the user to after
* they verify the application access. If no callback
* is provided, the current page URL will be used.
* @param $sessionStore The session store implementation to use. See
* YahooSessionStore for more information. If no
* session store is provided, clearSession will
* instantiate a NativeSessionStore and use that.
* @param $verifier The oauth_verifier returned by the OAuth servers
* after authorization. Passing NULL indicates that
* authorization was completed previously or that
* requireSession() should look for oauth_verifier in
* @return YahooSession The current session or NULL if a session cannot
function requireSession($consumerKey, $consumerSecret, $applicationId =
NULL,
$callback =
NULL, $sessionStore =
NULL, $verifier =
NULL)
$verifier =
$_GET["oauth_verifier"];
return YahooSession::initSession($consumerKey, $consumerSecret, $applicationId, TRUE, $callback, $sessionStore, $verifier);
* Creates authorization URLs, allowing applications to manage their
* user experience when the user needs to be sent to Yahoo! to authorize
* the application to access their account.
* @param $consumerKey The OAuth consumer key.
* @param $consumerSecret The OAuth consumer key secret.
* @param $callback The callback URL to redirect the user to after
* they verify the application access. If no callback
* is provided, the current page URL will be used.
* Use the "oob" callback for desktop clients or for
* web clients where no callback should be used.
* @param $sessionStore The session store implementation to use. See
* YahooSessionStore for more information. If no
* session store is provided, createAuthorizationUrl
* will instantiate a NativeSessionStore and use that.
* @return stdclass A PHP object with two properties: "urlWithCallback"
* and "urlWithoutCallback". This allows the application
* to mix and match authorizations that do and don't
* have callbacks in the URLs. urlWithoutCallback is
* useful for JavaScript popup windows while
* urlWithCallback is useful for normal <a href>
global $GLOBAL_YAHOO_SESSION;
// No callback URL supplied. Build one from the current URL.
// Redirect the user to log in.
$sessionStore->storeRequestToken($requestToken);
$GLOBAL_YAHOO_SESSION =
NULL;
global $GLOBAL_YAHOO_SESSION;
// TODO: throw a YahooException
$consumer =
new stdclass();
$consumer->key =
$consumerKey;
$consumer->secret =
$consumerSecret;
if ($consumer->key !=
$_POST["yap_consumer_key"]) {
// TODO: throw a YahooException
$GLOBAL_YAHOO_SESSION =
NULL;
// TODO: throw a YahooException
$GLOBAL_YAHOO_SESSION =
NULL;
$accessToken =
new stdclass();
$accessToken->key =
$_POST["yap_viewer_access_token"];
$accessToken->secret =
$_POST["yap_viewer_access_token_secret"];
$accessToken->guid =
$_POST["yap_viewer_guid"];
$accessToken->owner =
$_POST["yap_owner_guid"];
$accessToken->tokenExpires = -
1;
YahooLogger::debug("YAP AT: " .
$accessToken->key .
" ATS: " .
$accessToken->secret);
$applicationId =
$_POST["yap_appid"];
$GLOBAL_YAHOO_SESSION =
new YahooSession($consumer, $accessToken, $applicationId);
return $GLOBAL_YAHOO_SESSION;
function initSession($consumerKey, $consumerSecret, $applicationId, $redirect, $callback, $sessionStore, $verifier)
global $GLOBAL_YAHOO_SESSION;
if(!is_null($GLOBAL_YAHOO_SESSION)) {
return $GLOBAL_YAHOO_SESSION;
$consumer =
new stdclass();
$consumer->key =
$consumerKey;
$consumer->secret =
$consumerSecret;
// There doesn't appear to be a session here.
$GLOBAL_YAHOO_SESSION =
NULL;
// Don't redirect the user, just inform the caller that
// no session is present.
// TODO: throw a YahooException
$GLOBAL_YAHOO_SESSION =
NULL;
// Found an OAuth Access Token session.
$accessToken =
$sessionStore->fetchAccessToken();
YahooLogger::debug("OAuth AT: " .
$accessToken->key .
" ATS: ".
$accessToken->secret);
if($accessToken->consumer !=
$consumerKey)
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.");
if($accessToken->tokenExpires >=
0) {
if(($accessToken->tokenExpires >=
0) &&
($accessToken->tokenExpires -
$now) <
30) {
// The access token will expire in less than 30 seconds or
// it may have expired already. Try to get a new one.
// The access token is still good for a little while, continue using it.
$GLOBAL_YAHOO_SESSION =
new YahooSession($consumer, $accessToken, $applicationId);
// Can't proceed without the oauth_verifier, treat it as
// though there's no session present.
$sessionStore->clearRequestToken();
// TODO: throw a YahooException
$GLOBAL_YAHOO_SESSION =
NULL;
// Found an OAuth Request Token session.
$requestToken =
$sessionStore->fetchRequestToken();
$sessionStore->storeAccessToken($accessToken);
$sessionStore->clearRequestToken();
$GLOBAL_YAHOO_SESSION =
new YahooSession($consumer, $accessToken, $applicationId);
// TODO: Add redirect counter so this doesn't happen over and over and over when Yahoo! is completely busted.
// The fetch for the access token failed. Generate a new
// request token and try again.
$GLOBAL_YAHOO_SESSION =
NULL;
// Don't redirect the user, just inform the caller that
// no session is present.
$sessionStore->clearRequestToken();
$GLOBAL_YAHOO_SESSION =
NULL;
// TODO: throw a YahooException
$GLOBAL_YAHOO_SESSION =
NULL;
return $GLOBAL_YAHOO_SESSION;
global $GLOBAL_YAHOO_SESSION;
if(($accessToken->handleExpires === -
1) ||
($now <
$accessToken->handleExpires)) {
// Either the access session handle doesn't expire
// or it hasn't expired yet. Get a new access token.
$consumer->key, $consumer->secret, $accessToken, null);
$GLOBAL_YAHOO_SESSION =
NULL;
$sessionStore->storeAccessToken($newAccessToken);
YahooLogger::debug("OAuth AT: " .
$newAccessToken->key .
" ATS: ".
$newAccessToken->secret);
$consumer, $newAccessToken, $applicationId);
// The access token is expired and we don't have
// a sufficient access session handle to renew
// the access token. Clear the cookie and redirect
// to authorization point or return a NULL session.
$sessionStore->clearAccessToken();
$GLOBAL_YAHOO_SESSION =
NULL;
* Checks to see if the current PHP page request has a session and, if so,
* indicates what type of session is present.
* @param[out] $sessionType The session type present, if any.
* @return boolean True if a session is present, false otherwise.
else if($sessionStore->hasAccessToken()) {
else if($sessionStore->hasRequestToken()) {
* Represents a Yahoo! application.
* @brief Represents a Yahoo! application.
* Constructs a new YahooApplication object.
* @param $consumerKey The consumer key of the application.
* @param $consumerKeySecret The consumer key secret of the application.
* Sets the small view for the user given by the GUID.
* @param $guid The GUID of the user to set the small view for.
* @param $content The content to set the small view to.
* @return True on success, false otherwise.
$request_url =
sprintf("http://%s/v1/cache/view/small/%s", $YahooConfig["YAP_WS_HOSTNAME"], urlencode($guid));
$response =
$client->put($request_url, "text/html;charset=utf-8", $content);
* Executes the given YQL query.
* @param $yql The query to execute.
* @param $env A URL to a YQL environment file.
* @return The response or NULL if the request fails..
function query($yql, $env=
NULL)
$request_url =
sprintf("http://%s/v1/yql",$YahooConfig["QUERY_WS_HOSTNAME"]);
$params =
array('q' =>
$yql, 'format' =>
'json', 'env' =>
'http://datatables.org/alltables.env');
$response =
$client->get($request_url, $params, 30);
* Represents a Yahoo! user.
* @brief Represents a Yahoo! user.
function YahooUser($session, $guid, $sessioned) {
$this->client =
$session->client;
* Gets the user's status message.
* @return The status of the user or NULL if the fetch fails.
$request_url =
sprintf("http://%s/v1/user/%s/profile/status",
$response =
$this->client->get($request_url);
else if($response["code"] ==
404) {
// No presence is set, return an empty presence.
$status =
new stdclass();
$status->lastStatusModified =
NULL;
else if($response["code"] !=
200) {
* Sets the user's status message.
* @param $message The new status message for the user.
* @return The status message on success, NULL on failure.
$message =
array("message" =>
$message);
$status =
array("status" =>
$message);
$request_url =
sprintf("http://%s/v1/user/%s/profile/status", $YahooConfig["SOCIAL_WS_HOSTNAME"], $this->guid);
$response =
$this->client->put($request_url, "application/json", $status_json);
* Gets the updates for the current user.
* @param $start The starting offset to list updates from. (default = 0)
* @param $count The number of updates to request. (default = 10)
* @return An array of updates for the current user.
$parameters =
array("start" =>
$start, "count" =>
$count, "transform" =>
'(sort "pubDate" numeric descending (all))');
return $updates->updates;
* Gets the updates for the connections of the current user.
* @param $start The starting offset to list updates from.
* @param $count The number of updates to request.
* @return A list of updates for the connections of the current user.
$parameters =
array("start" =>
$start, "count" =>
$count, "transform" =>
'(sort "pubDate" numeric descending (all))');
$updates =
$this->get_resource("updates/connections", $parameters);
return $updates->updates;
* Inserts an update for the current user.
* @param $suid Identifier that globally unique for a given
* collectionId within producing source.
* @param $title Title for the update.
* @param $link Link back to the cause of the event.
* @param $description Descriptive text associated with the update,
* @param $date The date of the update event, optional, defaults to now.
function insertUpdate($suid, $title, $link, $description=
"", $date=
NULL) {
// Make sure this YahooUser is sessioned.
// Make sure an application ID was given.
$appid =
$this->session->getApplicationId();
$source =
sprintf("APP.%s", $appid);
"collectionID" =>
$this->guid,
"collectionType" =>
"guid",
"description" =>
$description,
"pubDate" => (string)
$date
$update_body =
array("updates" =>
array($update));
$request_url =
sprintf("http://%s/v1/user/%s/updates/%s/%s", $YahooConfig["UPDATES_WS_HOSTNAME"], $this->guid, $source, urlencode($suid));
$response =
$this->client->put($request_url, "application/json", $update_body_json);
* Deletes the update of the given SUID. Only allows deleting updates
* that were inserted by your own application. You won't be able to
* delete updates from other applications.
* @param $suid The SUID of the update to be deleted.
* @return boolean True on success, false on failure.
// Make sure this YahooUser is sessioned.
// Make sure an application ID was given.
$appid =
$this->session->getApplicationId();
$source =
sprintf("APP.%s", $appid);
$request_url =
sprintf("http://%s/v1/user/%s/updates/%s/%s", $YahooConfig["UPDATES_WS_HOSTNAME"], $this->guid, $source, urlencode($suid));
$response =
$this->client->delete($request_url);
* Loads the extended profile of the current user.
* @return The extended profile of the current user.
return $profile->profile;
* Gets a list of connections for the current user.
* @param[in,out] $start The starting offset.
* @param[in,out] $count The number of connections to fetch.
* @param[out] $total The total number of contacts available.
* @return List of connections for the current user.
$parameters =
array("view" =>
"usercard", "start" =>
$start, "count" =>
$count);
$connections =
$this->get_resource("connections",$parameters);
$start =
$connections->connections->start;
$count =
$connections->connections->count;
$total =
$connections->connections->total;
return $connections->connections->connection;
* Gets a list of contacts for the current user.
* @param $start The starting offset.
* @param $count The number of contacts to fetch.
* @return List of contacts for the current user.
$parameters =
array("view" =>
"tinyusercard", "start" =>
$start, "count" =>
$count);
$parameters =
array('view' =>
'sync', 'rev' =>
$rev);
$parameters =
array('format' =>
'json');
$data =
array('contactsync' =>
$contactsync);
$request_url =
sprintf("http://%s/v1/user/%s/contacts", $YahooConfig["SOCIAL_WS_HOSTNAME"], $this->guid);
$response =
$this->client->put($request_url, "application/json", $body);
$data =
array('contact' =>
$contact);
$request_url =
sprintf("http://%s/v1/user/%s/contacts", $YahooConfig["SOCIAL_WS_HOSTNAME"], $this->guid);
$response =
$this->client->post($request_url, "application/json", $body);
* Sets the small view for the current user.
* @param $content The content to set the small view to.
* @return True on success, false otherwise.
return $this->session->application->setSmallView($this->guid, $content);
$request_url =
sprintf("http://%s/v1/user/%s/%s",
$YahooConfig["SOCIAL_WS_HOSTNAME"], urlencode($this->guid), $resource);
$response =
$this->client->get($request_url,$parameters);
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
* Loads the extended profile of the current user.
* @deprecated As of 1.2, replaced by getProfile.
* @return The extended profile of the current user.
// method renamed, keeping for compatibility.
YahooLogger::info("loadProfile is deprecated since 1.2: Please use getProfile");
* Lists the updates for the current user.
* @deprecated As of 1.2, replaced by getUpdates.
* @param $start The starting offset to list updates from. (default = 0)
* @param $count The number of updates to request. (default = 10)
* @return A list of updates for the current user.
// method renamed, keeping for compatibility.
YahooLogger::info("listUpdates is deprecated since 1.2: Please use getUpdates");
* Gets the updates for the connections of the current user.
* @deprecated As of 1.2, replaced by getConnectionUpdates.
* @param $start The starting offset to list updates from.
* @param $count The number of updates to request.
* @return An array of updates for the connections of the current user.
// method renamed, keeping for compatibility.
YahooLogger::info("listConnectionUpdates is deprecated since 1.2: Please use getConnectionUpdates");
* Gets the presence of the user, including the status.
* @return The presence of the user or NULL if the fetch fails.
* @deprecated As of 1.2, replaced by getStatus
YahooLogger::info("getPresence is deprecated since 1.2: Please use getStatus.");
$request_url =
sprintf("http://%s/v1/user/%s/presence/presence",
$response =
$this->client->get($request_url);
else if($response["code"] ==
404) {
// No presence is set, return an empty presence.
$presence =
new stdclass();
$presence->value =
new stdclass();
$presence->value->status =
"";
else if($response["code"] !=
200) {
return $presence->presence;
* Sets the presence of the user.
* @param $status The new status message for the user.
* @return The status message on success, NULL on failure.
* @deprecated As of 1.2, replaced by setStatus
YahooLogger::info("setPresence is deprecated since 1.2: Please use setStatus");
$presence =
array("status" =>
$status);
$request_url =
sprintf("http://%s/v1/user/%s/presence/presence", $YahooConfig["PRESENCE_WS_HOSTNAME"], $this->guid);
$response =
$this->client->put($request_url, "application/json", $presence_json);
///////////////////////////////////////////////////////////////////////////
// End Deprecated methods
///////////////////////////////////////////////////////////////////////////
$request_url =
sprintf("https://%s/oauth/v2/get_request_token", $YahooConfig["OAUTH_HOSTNAME"]);
$parameters =
array("oauth_callback" =>
$callback);
$response =
$client->post($request_url, "application/x-www-form-urlencoded", $parameters);
parse_str($response["responseBody"], $token);
if($response["code"] !=
200) {
$token["oauth_problem"] :
"unknown problem";
!$token["oauth_callback_confirmed"]) {
// Callback wasn't confirmed.
YahooLogger::error("Failed to create request token: callback was not confirmed");
$requestToken =
new stdclass();
$requestToken->key =
$token["oauth_token"];
$requestToken->secret =
$token["oauth_token_secret"];
return sprintf("https://%s/oauth/v2/request_auth?oauth_token=%s", $YahooConfig["OAUTH_HOSTNAME"], urlencode($requestToken->key));
function getAccessToken($consumerKey, $consumerSecret, $requestToken, $verifier) {
// Failed to fetch the access token, sleep for 250ms and
// then try one more time.
$request_url =
sprintf("https://%s/oauth/v2/get_token", $YahooConfig["OAUTH_HOSTNAME"]);
$parameters["oauth_session_handle"] =
$requestToken->sessionHandle;
$parameters["oauth_verifier"] =
$verifier;
$response =
$client->post($request_url, "application/x-www-form-urlencoded", $parameters);
parse_str($response["responseBody"], $token);
if($response["code"] !=
200) {
$accessToken =
new stdclass();
$accessToken->key =
$token["oauth_token"];
$accessToken->secret =
$token["oauth_token_secret"];
$accessToken->guid =
$token["xoauth_yahoo_guid"];
$accessToken->consumer =
$consumerKey;
$accessToken->sessionHandle =
$token["oauth_session_handle"];
// Check to see if the access token ever expires.
YahooLogger::debug('AT expires in '.
$token['oauth_expires_in'].
'; ASH expires in '.
$token["oauth_authorization_expires_in"]);
$accessToken->tokenExpires =
$now +
$token["oauth_expires_in"];
$accessToken->tokenExpires = -
1;
// Check to see if the access session handle ever expires.
$accessToken->handleExpires =
$now +
$token["oauth_authorization_expires_in"];
$accessToken->handleExpires = -
1;
* Cookie-based implementation of the session store. This is the default
* session storage used by the Y!OS PHP SDK. Developers are free to
* implement their own session store implementations and pass them to
* YahooSession::hasSession, YahooSession::requireSession and
* YahooSession::clearSession. By default, if no session store is passed
* to YahooSession::hasSession or YahooSession::requireSession, an instance
* of a NativeSessionStore is used.
* @brief Cookie-based implementation of the session store.
* Indicates if the session store has a request token.
* @return True if a request token is present, false otherwise.
* Indicates if the session store has an access token.
* @return True if an access token is present, false otherwise.
* Stores the given request token in the session store.
* @param $token A PHP stdclass object containing the components of
* the OAuth request token.
* @return True on success, false otherwise.
* Fetches and returns the request token from the session store.
* @return The request token.
* Clears the request token from the session store.
* @return True on success, false otherwise.
* Stores the given access token in the session store.
* @param $token A PHP stdclass object containing the components of
* the OAuth access token.
* @return True on success, false otherwise.
time() +
(30 *
24 *
60 *
60));
* Fetches and returns the access token from the session store.
* @return The access token.
* Clears the access token from the session store.
* @return True on success, false otherwise.
* PHP session based implementation of the session store. This is the default
* session storage used by the Y!OS PHP SDK. Developers are free to
* implement their own session store implementations and pass them to
* YahooSession::hasSession, YahooSession::requireSession and
* YahooSession::clearSession. By default, if no session store is passed
* to YahooSession::hasSession or YahooSession::requireSession, an instance
* of a NativeSessionStore is used.
* @brief Native php session based implementation of the session store, by default
* stored on file system, but can be database or memcache backend.
* Indicates if the session store has a request token.
* @return True if a request token is present, false otherwise.
* Indicates if the session store has an access token.
* @return True if an access token is present, false otherwise.
* Stores the given request token in the session store.
* @param $token A PHP stdclass object containing the components of the OAuth request token.
* Fetches and returns the request token from the session store.
* @return The request token.
return isset
($_SESSION["yosdk_rt"]) ?
json_decode($_SESSION["yosdk_rt"]) :
false;
* Clears the request token from the session store.
unset
($_SESSION['yosdk_rt']);
* Stores the given access token in the session store.
* @param $token A PHP stdclass object containing the components of the OAuth access token.
* Fetches and returns the access token from the session store.
* @return The access token.
return isset
($_SESSION["yosdk_at"]) ?
json_decode($_SESSION["yosdk_at"]) :
false;
* Clears the access token from the session store.
unset
($_SESSION['yosdk_at']);
* A simple OAuth client class for making 2 and 3 legged OAuth HTTP requests.
* @brief A simple OAuth client class for making 2 and 3 legged OAuth HTTP requests.
* Constructs a new OAuth client.
* @param $consumer The OAuthConsumer object to use for the requests.
* @param $token The OAuthToken to use for the requests. Optional.
* @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.
* @param $signatureMethod OAUTH_SIGNATURE_PLAINTEXT or OAUTH_SIGNATURE_HMAC_SHA1, depending on what request signing mechanism to use. Optional, defaults to HMAC SHA1 signatures.
function OAuthClient($consumer, $token =
NULL, $oauthParamsLocation =
OAUTH_PARAMS_IN_HEADERS, $signatureMethod =
OAUTH_SIGNATURE_HMAC_SHA1) {
* Executes a properly signed OAuth HTTP GET request.
* @param $url The URL to request.
* @param $queryParameters Any query string parameters to be sent in the request.
* @param $timeout Optional, the number of seconds to wait for the request to return.
* @return The response object.
function get($url, $queryParameters =
array(), $timeout =
NULL) {
if(strpos($url, "?") !==
FALSE) {
YahooLogger::error("Put the query parameters in the second argument to OAuthClient::get(), not in the URL itself: URL = $url");
"query" =>
$queryParameters,
* Executes a properly signed OAuth HTTP DELETE request.
* @param $url The URL to request.
* @param $queryParameters Any query string parameters to be sent in the request.
* @param $timeout Optional, the number of seconds to wait for the request to return.
* @return The response object.
function delete($url, $queryParameters =
array(), $timeout =
NULL) {
if(strpos($url, "?") !==
FALSE) {
YahooLogger::error("Put the query parameters in the second argument to OAuthClient::delete(), not in the URL itself: URL = $url");
"query" =>
$queryParameters,
* Executes a properly signed OAuth HTTP PUT request.
* @param $url The URL to request.
* @param $contentType The Content-Type of the PUT data.
* @param $content The raw content to be PUT.
* @param $timeout Optional, the number of seconds to wait for the request to return.
* @return The response object.
function put($url, $contentType, $content, $timeout =
NULL) {
"contentType" =>
$contentType,
* Executes a properly signed OAuth HTTP POST request.
* @param $url The URL to request.
* @param $contentType The Content-Type of the POST data.
* @param $content The content to be POST.
* @param $timeout Optional, the number of seconds to wait for the request to return.
* @return The response object.
function post($url, $contentType =
"application/x-www-form-urlencoded",
$content =
array(), $timeout =
NULL) {
"contentType" =>
$contentType,
$request["content"] =
array();
$request["query"] =
array();
$request["query"], $request["content"]);
$combinedParams =
$request["query"];
$request["url"], $combinedParams);
$headers =
array("Accept: " .
$this->accepts);
$headers[] =
$oauthRequest->to_header();
$headers[] =
"Content-Type: " .
$request["contentType"];
if(!empty($request["query"])) {
$requestUrl =
$request["url"];
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request["method"]);
(!empty($request["content"]) &&
is_array($request["content"]))) {
// Content is an array, URL encode it.
$request["content"] =
$oauthRequest->to_postdata();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request["content"]);
else if(!empty($request["content"])) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $request["content"]);
// Enable compressed responses from the servers.
// Set the user agent so the SDK properly identifies itself for
// usage tracking purposes. Include the version of the SDK and
// the version of PHP being used.
curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$headerParser, "read"));
if(is_bool($response) &&
!$response) {
'method' =>
$request["method"],
'requestHeaders' =>
$headers,
'requestBody' =>
!empty($request["content"]) ?
$request["content"] :
NULL,
'responseHeaders' =>
$headerParser->headers,
'responseBody' =>
$response
if(($response["code"] >
200) &&
($response["code"] <
300)) {
* Checks to see if the code and headers indicate an expired OAuth token.
* If so, requests a new one.
if ($code !=
401) return; // HTTP Unauthorized
$authenticateHeader =
$headerParser->get('WWW-Authenticate');
if (!$authenticateHeader) return;
if (!preg_match('/oauth_problem="([^"]+)"/', $authenticateHeader, $match)) return;
$oauth_problem =
$match[1];
if ($oauth_problem ==
'token_expired') {
if ($oauth_problem ==
'consumer_key_unknown') {
YahooLogger::error('Consumer Key unkown. Please check that the Consumer Key is valid.');
if ($oauth_problem ==
'additional_authorization_required') {
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.');
function read($ch, $header) {
$name =
substr($header, 0, $pos);
* Interface to modify the underlying configuration of the library.
$YahooConfig["SOCIAL_WS_HOSTNAME"] =
$hostname;
$YahooConfig["PRESENCE_WS_HOSTNAME"] =
$hostname;
$YahooConfig["UPDATES_WS_HOSTNAME"] =
$hostname;
$YahooConfig["QUERY_WS_HOSTNAME"] =
$hostname;
$YahooConfig["OAUTH_HOSTNAME"] =
$hostname;
$YahooConfig["YAP_WS_HOSTNAME"] =
$hostname;
* An OAuth compatible version of http_build_query. http_build_query
* doesn't work because it turns spaces into "+", which isn't allowed
foreach($parameters as $name =>
$value) {
* PHP4/5 compatibility functions
// If json_decode doesn't exist, then php-json must not be included in this
// version of PHP. Include fake versions of json_encode/json_decode that
// are backed by the native PHP php-json library, which is available in PEAR.
// Only include JSON.php if someone else hasn't already. Depending on
// the operating environment, other code may have brought their own
// version of that source code.
include_once("JSON.php");
return $js->decode($json);
return $js->encode($value);
Documentation generated on Thu, 22 Oct 2009 12:54:51 -0700 by phpDocumentor 1.4.3