Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge branch 'master' of git://github.com/dwhittle/yos-social-php int…

…o dwhittle/master
  • Loading branch information...
commit 4904ff9ae59bdbd0eef3f00a0548b0013b581c9e 2 parents 8306ef3 + 8294eb2
@dustinwhittle dustinwhittle authored
Showing with 720 additions and 302 deletions.
  1. +82 −8 INSTALL.txt
  2. +311 −219 lib/Yahoo.inc
  3. +240 −0 sample/delicious.php
  4. +87 −75 sample/sampleapp.php
View
90 INSTALL.txt
@@ -1,7 +1,7 @@
Yahoo! OS PHP SDK
=============
-After downloading and unpackaging the release, copy the contents of yosdk/lib
-to a directory that is accessible via the PHP require/require_once methods. In
+After downloading and unpackaging the release, copy the contents of yosdk/lib
+to a directory that is accessible via the PHP require/require_once methods. In
your PHP scripts, require the Yahoo.inc file:
require("Yahoo.inc");
@@ -13,10 +13,84 @@ or
Now you should be ready to instantiate your YahooSession object and get
started.
-Sample Application
-==================
-In the yosdk/sample directory you'll find sampleapp.php, a sample application
-that will get you started. Put the file in your hosting directory and fill
-in the consumer key, consumer key secret and application ID. When you're done,
-point your browser at the URL. You will be directed to verify access to the
+===================
+Sample Applications
+===================
+
+In the yosdk/sample directory you'll find sampleapp.php, a sample application
+that will get you started. Put the file in your hosting directory and fill
+in the consumer key, consumer key secret and application ID. When you're done,
+point your browser at the URL. You will be directed to verify access to the
application and then you will be redirected back to your application.
+
+In the yosdk/sample directory you'll find delicious.php, a sample yahoo open
+application that shows how to use YQL to make web service request.
+
+==========================
+Debugging with the YOS SDK
+==========================
+
+The YOS SDK provides some methods that make debugging easier. Also, since the YOS
+SDK was designed for the greatest compatibility across PHP version, it is advised
+to suppress notices if using PHP 5.x:
+
+// debug settings
+error_reporting(E_ALL | E_NOTICE); # do not show notices as library is php4 compatable
+ini_set('display_errors', true);
+
+YahooLogger::setDebug(true);
+YahooLogger::setDebugDestination('LOG');
+
+
+==========================================================
+Storing OAuth credentials on filesystem, memcache, cookies
+==========================================================
+
+By default OAuth credential (request + access tokens) are stored in PHP sessions.
+PHP sessions can easily be configured to work from local filesystem, database, or
+a memcache instance. The sample apps provide working examples of filesystem storage
+and memcache storage.
+
+====================================
+Filesystem Session Storage (default)
+====================================
+
+// Include the YOS library.
+require dirname(__FILE__).'/../lib/Yahoo.inc';
+
+// use memcache to store oauth credentials via php native sessions
+ini_set('session.save_handler', 'memcache');
+session_save_path('tcp://localhost:11211?persistent=1&weight=1&timeout=1&retry_interval=15');
+session_start();
+
+========================
+Memcache Session Storage
+========================
+
+// Include the YOS library.
+require dirname(__FILE__).'/../lib/Yahoo.inc';
+
+// use memcache to store oauth credentials via php native sessions
+ini_set('session.save_handler', 'memcache');
+session_save_path('tcp://localhost:11211?persistent=1&weight=1&timeout=1&retry_interval=15');
+session_start();
+
+
+=======================================
+Cookie Based Session Storage (original)
+=======================================
+
+The original default storage backend was based on storing access tokens in a plain text cookie. This is bad for security, and the default has since been changed (breaks backwards compatibility). In order to use the original
+session store, you must instantiate 'CookieSessionStore' and pass into all methods of YahooSession:
+
+$sessionStore = new CookieSessionStore();
+
+YahooSession::hasSession($consumerKey, $consumerSecret, $applicationId, $sessionStore, $verifier)
+YahooSession::requireSession($consumerKey, $consumerSecret, $applicationId, $callback, $sessionStore, $verifier)
+YahooSession::initSession($consumerKey, $consumerSecret, $applicationId, $redirect, $callback, $sessionStore, $verifier)
+
+YahooSession::createAuthorizationUrl($consumerKey, $consumerSecret, $callback, $sessionStore)
+YahooSession::redirectForAuthorization($consumerKey, $consumerSecret, $callback, $sessionStore)
+YahooSession::clearSession($sessionStore)
+YahooSession::checkSession($sessionType, $sessionStore)
+
View
530 lib/Yahoo.inc
@@ -1,17 +1,17 @@
<?php
-//
+
// Yahoo.inc
// yos_sdk_php
//
// Created by Ryan Kennedy on 6/01/09.
// Copyright (c) 2009 Yahoo! Inc. All rights reserved.
-//
+//
// The copyrights embodied in the content of this file are licensed under the BSD (revised) open source license.
//
-//
+//
-// 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
+// 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.
if(!class_exists("OAuthConsumer")) {
require_once("OAuth.php");
@@ -44,30 +44,31 @@ class YahooUtil {
function current_url() {
return sprintf("http://%s%s",$_SERVER["HTTP_HOST"],$_SERVER["REQUEST_URI"]);
}
-
+
function verify_signature($consumer, $token=NULL, $oauth_signature) {
$oauth_signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$oauth_consumer = new OAuthConsumer($consumer->key, $consumer->secret);
$oauth_token = ($token) ? new OAuthToken($token->key, $token->secret) : NULL;
$oauth_request = OAuthRequest::from_request();
-
+
$ok = $oauth_signature_method->check_signature($oauth_request, $oauth_consumer, $oauth_token, $oauth_signature);
return $ok;
}
function is_yap_canvas() {
- return (isset($_POST['yap_appid'])
+ return (isset($_POST['yap_appid'])
&& isset($_POST['yap_view']));
}
-
+
function is_response_error($response) {
return (is_null($response) || $response["code"] != 200);
}
+
}
class YahooException extends Exception {
-
+
}
/**
@@ -82,6 +83,7 @@ class YahooLogger {
* @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) {
@@ -155,13 +157,13 @@ class YahooLogger {
/**
* Allows callers to configure where debugging output is sent.
*
- * @param $destination "LOG" to use error_log, "CONSOLE" to use printf,
+ * @param $destination "LOG" to use error_log, "CONSOLE" to use printf,
* "NULL" to disable all logging output.
* @return boolean True on success, false on failure.
*/
function setDebugDestination($destination) {
global $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION;
- if($destination == "LOG" || $destination == "CONSOLE" ||
+ if($destination == "LOG" || $destination == "CONSOLE" ||
$destination == "NULL") {
$GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION = $destination;
return true;
@@ -212,7 +214,7 @@ class YahooSession {
/**
* @private
*/
- function YahooSession($consumer, $accessToken, $applicationId)
+ function YahooSession($consumer, $accessToken, $applicationId)
{
$this->consumer = $consumer;
$this->accessToken = $accessToken;
@@ -220,9 +222,9 @@ class YahooSession {
$this->guid = $accessToken->guid;
$this->client = new OAuthClient($consumer, $accessToken);
-
+
$this->application = new YahooApplication($consumer->key, $consumer->secret);
- $this->application->token = $this->accessToken;
+ $this->application->token = $this->accessToken;
}
/**
@@ -280,7 +282,7 @@ class YahooSession {
function getUser($guid) {
return new YahooUser($this, $guid, isset($this->guid) && ($guid == $this->guid));
}
-
+
/**
* Executes the given YQL query.
*
@@ -291,7 +293,7 @@ class YahooSession {
function query($yql, $env=NULL) {
return $this->application->query($yql, $env);
}
-
+
/**
* @private
*/
@@ -312,18 +314,18 @@ class YahooSession {
* Destroys the current session, effectively logging out the current
* user.
*
- * @param $sessionStore The session store implementation to clear. See
- * YahooSessionStore for more information. If no
- * session store is provided, clearSession will
- * instantiate a CookieSessionStore and use that.
+ * @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.
*/
function clearSession($sessionStore = NULL) {
global $GLOBAL_YAHOO_SESSION;
if(is_null($sessionStore)) {
- $sessionStore = new CookieSessionStore();
+ $sessionStore = new NativeSessionStore();
}
-
+
$sessionStore->clearRequestToken();
$sessionStore->clearAccessToken();
@@ -331,101 +333,101 @@ class YahooSession {
}
/**
- * 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
+ * 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 CookieSessionStore and use that.
+ * @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)
+ function hasSession($consumerKey, $consumerSecret, $applicationId = NULL, $sessionStore = NULL, $verifier = NULL)
{
if(is_null($sessionStore)) {
- $sessionStore = new CookieSessionStore();
+ $sessionStore = new NativeSessionStore();
}
if(is_null($verifier) && array_key_exists("oauth_verifier", $_GET)) {
$verifier = $_GET["oauth_verifier"];
}
-
+
$session = YahooSession::initSession($consumerKey, $consumerSecret, $applicationId, FALSE, NULL, $sessionStore, $verifier);
return !is_null($session);
}
/**
- * 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
+ * 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
+ * @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 CookieSessionStore 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
+ * @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
* the $_GET superglobal.
- * @return YahooSession The current session or NULL if a session cannot
+ * @return YahooSession The current session or NULL if a session cannot
* be established.
*/
- function requireSession($consumerKey, $consumerSecret, $applicationId = NULL,
- $callback = NULL, $sessionStore = NULL, $verifier = NULL)
+ function requireSession($consumerKey, $consumerSecret, $applicationId = NULL,
+ $callback = NULL, $sessionStore = NULL, $verifier = NULL)
{
if(is_null($sessionStore)) {
- $sessionStore = new CookieSessionStore();
+ $sessionStore = new NativeSessionStore();
}
if(is_null($verifier) && array_key_exists("oauth_verifier", $_GET)) {
$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
+ * 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
+ * @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
+ * @param $sessionStore The session store implementation to use. See
+ * YahooSessionStore for more information. If no
* session store is provided, createAuthorizationUrl
- * will instantiate a CookieSessionStore 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>
+ * 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>
* tags.
*/
- function createAuthorizationUrl($consumerKey, $consumerSecret, $callback = NULL, $sessionStore = NULL)
+ function createAuthorizationUrl($consumerKey, $consumerSecret, $callback = NULL, $sessionStore = NULL)
{
global $GLOBAL_YAHOO_SESSION;
if(is_null($sessionStore)) {
- $sessionStore = new CookieSessionStore();
+ $sessionStore = new NativeSessionStore();
}
// No callback URL supplied. Build one from the current URL.
@@ -435,15 +437,15 @@ class YahooSession {
// Redirect the user to log in.
$requestToken = YahooAuthorization::getRequestToken($consumerKey, $consumerSecret, $callback);
-
- if(!is_null($requestToken))
+
+ if(!is_null($requestToken))
{
$sessionStore->storeRequestToken($requestToken);
$url = YahooAuthorization::createAuthorizationUrl($requestToken, $callback);
return $url;
}
- else
+ else
{
YahooLogger::error("Failed to create request token");
$GLOBAL_YAHOO_SESSION = NULL;
@@ -454,26 +456,26 @@ class YahooSession {
function initSessionFromYAP($consumerKey, $consumerSecret, $appid)
{
global $GLOBAL_YAHOO_SESSION;
-
+
if(!YahooUtil::is_yap_canvas()) {
// TODO: throw a YahooException
return NULL;
}
-
+
$consumer = new stdclass();
$consumer->key = $consumerKey;
$consumer->secret = $consumerSecret;
-
+
if ($consumer->key != $_POST["yap_consumer_key"]) {
error_log("Consumer key from YAP does not match provided key.");
// TODO: throw a YahooException
$GLOBAL_YAHOO_SESSION = NULL;
return;
}
-
+
$signature_ok = YahooUtil::verify_signature($consumer, null, $_REQUEST['oauth_signature']);
-
- if (!$signature_ok)
+
+ if (!$signature_ok)
{
error_log("Signature from YAP failed.");
// TODO: throw a YahooException
@@ -487,7 +489,7 @@ class YahooSession {
$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"];
@@ -499,7 +501,7 @@ class YahooSession {
/**
* @private
*/
- function initSession($consumerKey, $consumerSecret, $applicationId, $redirect, $callback, $sessionStore, $verifier)
+ function initSession($consumerKey, $consumerSecret, $applicationId, $redirect, $callback, $sessionStore, $verifier)
{
global $GLOBAL_YAHOO_SESSION;
@@ -512,7 +514,7 @@ class YahooSession {
$consumer->secret = $consumerSecret;
$checkSession = YahooSession::checkSession($type, $sessionStore);
-
+
if(!$checkSession) {
// There doesn't appear to be a session here.
if($redirect) {
@@ -520,7 +522,7 @@ class YahooSession {
YahooSession::redirectForAuthorization($consumerKey, $consumerSecret, $callback, $sessionStore);
}
else {
- // Don't redirect the user, just inform the caller that
+ // Don't redirect the user, just inform the caller that
// no session is present.
// TODO: throw a YahooException
$GLOBAL_YAHOO_SESSION = NULL;
@@ -529,26 +531,26 @@ class YahooSession {
else if($type == YAHOO_OAUTH_AT_SESSION_TYPE) {
// Found an OAuth Access Token session.
$accessToken = $sessionStore->fetchAccessToken();
- $now = time();
-
+ $now = time();
+
YahooLogger::debug("OAuth AT: " . $accessToken->key . " ATS: ". $accessToken->secret);
- if($accessToken->consumer != $consumerKey)
+ 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.");
YahooSession::clearSession($sessionStore);
-
+
if($redirect) {
YahooSession::redirectForAuthorization($consumerKey, $consumerSecret, $callback, $sessionStore);
}
}
-
+
if($accessToken->tokenExpires >= 0) {
YahooLogger::debug('AT Expires in: ' . ($accessToken->tokenExpires - $now));
}
if(($accessToken->tokenExpires >= 0) && ($accessToken->tokenExpires - $now) < 30) {
- // The access token will expire in less than 30 seconds or
+ // The access token will expire in less than 30 seconds or
// it may have expired already. Try to get a new one.
YahooSession::accessTokenExpired($accessToken, $consumer, $applicationId, $sessionStore);
}
@@ -557,10 +559,10 @@ class YahooSession {
$GLOBAL_YAHOO_SESSION = new YahooSession($consumer, $accessToken, $applicationId);
}
}
- else if($type == YAHOO_OAUTH_RT_SESSION_TYPE)
+ else if($type == YAHOO_OAUTH_RT_SESSION_TYPE)
{
if(is_null($verifier)) {
- // Can't proceed without the oauth_verifier, treat it as
+ // Can't proceed without the oauth_verifier, treat it as
// though there's no session present.
$sessionStore->clearRequestToken();
@@ -572,35 +574,35 @@ class YahooSession {
$requestToken = $sessionStore->fetchRequestToken();
$accessToken = YahooAuthorization::getAccessToken($consumerKey, $consumerSecret, $requestToken, $verifier);
-
+
if(!is_null($accessToken)) {
$sessionStore->storeAccessToken($accessToken);
$sessionStore->clearRequestToken();
$GLOBAL_YAHOO_SESSION = new YahooSession($consumer, $accessToken, $applicationId);
}
- else if($redirect)
+ else if($redirect)
{
// 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
+ // The fetch for the access token failed. Generate a new
// request token and try again.
$GLOBAL_YAHOO_SESSION = NULL;
YahooSession::redirectForAuthorization($consumerKey, $consumerSecret, $callback, $sessionStore);
}
- else
+ else
{
- // Don't redirect the user, just inform the caller that
+ // Don't redirect the user, just inform the caller that
// no session is present.
$sessionStore->clearRequestToken();
$GLOBAL_YAHOO_SESSION = NULL;
}
}
- else if($type == YAHOO_YAP_SESSION_TYPE)
+ else if($type == YAHOO_YAP_SESSION_TYPE)
{
// Found a YAP session.
$GLOBAL_YAHOO_SESSION = YahooSession::initSessionFromYAP($consumerKey, $consumerSecret, $applicationId);
}
- else
+ else
{
trigger_error("Unknown session type found", E_USER_ERROR);
// TODO: throw a YahooException
@@ -609,18 +611,18 @@ class YahooSession {
return $GLOBAL_YAHOO_SESSION;
}
-
+
/**
* @private
*/
- function accessTokenExpired($accessToken, $consumer, $applicationId, $sessionStore)
+ function accessTokenExpired($accessToken, $consumer, $applicationId, $sessionStore)
{
global $GLOBAL_YAHOO_SESSION;
$now = time();
if(($accessToken->handleExpires === -1) ||
($now < $accessToken->handleExpires)) {
- // Either the access session handle doesn't expire
+ // Either the access session handle doesn't expire
// or it hasn't expired yet. Get a new access token.
$newAccessToken = YahooAuthorization::getAccessToken(
$consumer->key, $consumer->secret, $accessToken, null);
@@ -637,14 +639,14 @@ class YahooSession {
$GLOBAL_YAHOO_SESSION = new YahooSession(
$consumer, $newAccessToken, $applicationId);
}
- else
+ else
{
- // 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
+ // 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();
-
+
if ($redirect) {
YahooSession::redirectForAuthorization($consumer->key, $consumer->secret, $callback, $sessionStore);
} else {
@@ -700,7 +702,7 @@ class YahooApplication {
/**
* @private
- */
+ */
var $token = NULL;
/**
@@ -722,9 +724,9 @@ class YahooApplication {
*/
function setSmallView($guid, $content) {
global $YahooConfig;
-
+
$client = new OAuthClient($this->consumer, NULL);
-
+
$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);
@@ -738,19 +740,19 @@ class YahooApplication {
* @param $env A URL to a YQL environment file.
* @return The response or NULL if the request fails..
*/
- function query($yql, $env=NULL)
+ function query($yql, $env=NULL)
{
global $YahooConfig;
-
+
$client = new OAuthClient($this->consumer, $this->token);
-
+
$request_url = sprintf("http://%s/v1/yql",$YahooConfig["QUERY_WS_HOSTNAME"]);
$params = array('q' => $yql, 'format' => 'json');
-
+
if(!is_null($env)) {
$params['env'] = $env;
}
-
+
$response = $client->get($request_url, $params, 30);
if(YahooUtil::is_response_error($response)) {
@@ -798,7 +800,7 @@ class YahooUser {
$this->guid = $guid;
$this->sessioned = $sessioned;
}
-
+
/**
* Gets the user's status message.
*
@@ -806,10 +808,10 @@ class YahooUser {
*/
function getStatus() {
global $YahooConfig;
-
- $request_url = sprintf("http://%s/v1/user/%s/profile/status",
+
+ $request_url = sprintf("http://%s/v1/user/%s/profile/status",
$YahooConfig["SOCIAL_WS_HOSTNAME"],urlencode($this->guid));
-
+
$response = $this->client->get($request_url);
if(is_null($response)) {
@@ -846,24 +848,24 @@ class YahooUser {
YahooLogger::error("Can't set the status of an unsessioned user");
return NULL;
}
-
+
$message = array("message" => $message);
$status = array("status" => $message);
$status_json = json_encode($status);
-
+
$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);
-
+
if(YahooUtil::is_response_error($response)) {
return NULL;
}
-
+
$status = json_decode($response["responseBody"]);
return $status;
}
-
+
/**
* Gets the updates for the current user.
*
@@ -874,10 +876,10 @@ class YahooUser {
function getUpdates($start = 0, $count = 10) {
$parameters = array("start" => $start, "count" => $count, "transform" => '(sort "pubDate" numeric descending (all))');
$updates = $this->get_resource("updates", $parameters);
-
+
return $updates->updates;
}
-
+
/**
* Gets the updates for the connections of the current user.
*
@@ -888,22 +890,22 @@ class YahooUser {
function getConnectionUpdates($start = 0, $count = 10) {
$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
+ * @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 $description Descriptive text associated with the update,
* optional.
* @param $date The date of the update event, optional, defaults to now.
*/
- function insertUpdate($suid, $title, $link, $description="", $date=NULL)
+ function insertUpdate($suid, $title, $link, $description="", $date=NULL)
{
global $YahooConfig;
@@ -925,7 +927,7 @@ class YahooUser {
}
$source = sprintf("APP.%s", $appid);
-
+
$update = array(
"collectionID" => $this->guid,
"collectionType" => "guid",
@@ -938,10 +940,10 @@ class YahooUser {
"link" => $link,
"pubDate" => (string)$date
);
-
+
$update_body = array("updates" => array($update));
$update_body_json = json_encode($update_body);
-
+
$request_url = sprintf("http://%s/v1/user/%s/updates/%s/%s",
$YahooConfig["UPDATES_WS_HOSTNAME"], $this->guid, $source, urlencode($suid));
@@ -956,7 +958,7 @@ class YahooUser {
/**
* Deletes the update of the given SUID. Only allows deleting updates
- * that were inserted by your own application. You won't be able to
+ * 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.
@@ -980,7 +982,7 @@ class YahooUser {
$source = sprintf("APP.%s", $appid);
- $request_url = sprintf("http://%s/v1/user/%s/updates/%s/%s",
+ $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);
@@ -991,7 +993,7 @@ class YahooUser {
return TRUE;
}
-
+
/**
* Loads the extended profile of the current user.
*
@@ -999,7 +1001,7 @@ class YahooUser {
*/
function getProfile() {
global $YahooConfig;
-
+
$profile = $this->get_resource("profile");
return $profile->profile;
@@ -1018,7 +1020,7 @@ class YahooUser {
$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;
@@ -1063,10 +1065,10 @@ class YahooUser {
function get_resource($resource, $parameters=array())
{
global $YahooConfig;
-
+
$request_url = sprintf("http://%s/v1/user/%s/%s",
$YahooConfig["SOCIAL_WS_HOSTNAME"], urlencode($this->guid), $resource);
-
+
$response = $this->client->get($request_url,$parameters);
if(YahooUtil::is_response_error($response)) {
@@ -1076,11 +1078,11 @@ class YahooUser {
$data = json_decode($response["responseBody"]);
return $data;
}
-
+
///////////////////////////////////////////////////////////////////////////
// Deprecated methods
///////////////////////////////////////////////////////////////////////////
-
+
/**
* Loads the extended profile of the current user.
* @deprecated As of 1.2, replaced by getProfile.
@@ -1091,11 +1093,11 @@ class YahooUser {
YahooLogger::info("loadProfile is deprecated since 1.2: Please use getProfile");
return $this->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)
@@ -1104,10 +1106,10 @@ class YahooUser {
function listUpdates($start = 0, $count = 10) {
// method renamed, keeping for compatibility.
YahooLogger::info("listUpdates is deprecated since 1.2: Please use getUpdates");
-
+
return $this->getUpdates($start, $count);
}
-
+
/**
* Gets the updates for the connections of the current user.
* @deprecated As of 1.2, replaced by getConnectionUpdates.
@@ -1118,24 +1120,24 @@ class YahooUser {
function listConnectionUpdates($start = 0, $count = 10) {
// method renamed, keeping for compatibility.
YahooLogger::info("listConnectionUpdates is deprecated since 1.2: Please use getConnectionUpdates");
-
+
return $this->getConnectionUpdates($start, $count);
}
-
+
/**
* 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
*/
function getPresence() {
global $YahooConfig;
-
+
YahooLogger::info("getPresence is deprecated since 1.2: Please use getStatus.");
-
- $request_url = sprintf("http://%s/v1/user/%s/presence/presence",
+
+ $request_url = sprintf("http://%s/v1/user/%s/presence/presence",
$YahooConfig["PRESENCE_WS_HOSTNAME"],urlencode($this->guid));
-
+
$response = $this->client->get($request_url);
if(is_null($response)) {
@@ -1156,27 +1158,27 @@ class YahooUser {
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
*/
function setPresence($status) {
global $YahooConfig;
-
+
YahooLogger::info("setPresence is deprecated since 1.2: Please use setStatus");
-
+
if(!$this->sessioned) {
YahooLogger::error("Can't set the presence of an unsessioned user");
return NULL;
}
-
+
$presence = array("status" => $status);
$presence_json = json_encode($presence);
-
+
$request_url = sprintf("http://%s/v1/user/%s/presence/presence",
$YahooConfig["PRESENCE_WS_HOSTNAME"], $this->guid);
@@ -1185,7 +1187,7 @@ class YahooUser {
if(YahooUtil::is_response_error($response)) {
return NULL;
}
-
+
$presence = json_decode($response["responseBody"]);
return $presence;
}
@@ -1211,7 +1213,7 @@ class YahooAuthorization {
$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);
if(is_null($response)) {
@@ -1222,13 +1224,13 @@ class YahooAuthorization {
parse_str($response["responseBody"], $token);
if($response["code"] != 200) {
- $problem = array_key_exists("oauth_problem", $token) ?
+ $problem = array_key_exists("oauth_problem", $token) ?
$token["oauth_problem"] : "unknown problem";
YahooLogger::error("Failed to create request token: $problem");
return NULL;
}
- if(!array_key_exists("oauth_callback_confirmed", $token) ||
+ if(!array_key_exists("oauth_callback_confirmed", $token) ||
!$token["oauth_callback_confirmed"]) {
// Callback wasn't confirmed.
YahooLogger::error("Failed to create request token: callback was not confirmed");
@@ -1252,12 +1254,12 @@ class YahooAuthorization {
return sprintf("https://%s/oauth/v2/request_auth?oauth_token=%s", $YahooConfig["OAUTH_HOSTNAME"], urlencode($requestToken->key));
}
- function getAccessToken($consumerKey, $consumerSecret, $requestToken, $verifier)
+ function getAccessToken($consumerKey, $consumerSecret, $requestToken, $verifier)
{
$at = YahooAuthorization::getAccessTokenProxy($consumerKey, $consumerSecret, $requestToken, $verifier);
if(is_null($at)) {
- // Failed to fetch the access token, sleep for 250ms and
+ // Failed to fetch the access token, sleep for 250ms and
// then try one more time.
YahooLogger::info("Failed to fetch access token, retrying");
usleep(250000);
@@ -1267,12 +1269,12 @@ class YahooAuthorization {
return $at;
}
- function getAccessTokenProxy($consumerKey, $consumerSecret, $requestToken, $verifier)
+ function getAccessTokenProxy($consumerKey, $consumerSecret, $requestToken, $verifier)
{
global $YahooConfig;
$request_url = sprintf("https://%s/oauth/v2/get_token", $YahooConfig["OAUTH_HOSTNAME"]);
-
+
$consumer = new OAuthConsumer($consumerKey, $consumerSecret);
$parameters = array();
@@ -1285,7 +1287,7 @@ class YahooAuthorization {
}
$client = new OAuthClient($consumer, $requestToken, OAUTH_PARAMS_IN_POST_BODY);
-
+
$response = $client->post($request_url, "application/x-www-form-urlencoded", $parameters);
if(is_null($response)) {
@@ -1320,7 +1322,7 @@ class YahooAuthorization {
// Check to see if the access session handle ever expires.
if(array_key_exists("oauth_authorization_expires_in", $token)) {
- $accessToken->handleExpires = $now +
+ $accessToken->handleExpires = $now +
$token["oauth_authorization_expires_in"];
}
else {
@@ -1331,13 +1333,13 @@ class YahooAuthorization {
}
/**
- * 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 CookieSessionStore is used.
+ * 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.
*/
@@ -1348,7 +1350,7 @@ class CookieSessionStore {
* @return True if a request token is present, false otherwise.
*/
function hasRequestToken() {
- return array_key_exists("yosdk_rt", $_COOKIE) &&
+ return array_key_exists("yosdk_rt", $_COOKIE) &&
(strlen($_COOKIE["yosdk_rt"]) > 0);
}
@@ -1358,20 +1360,20 @@ class CookieSessionStore {
* @return True if an access token is present, false otherwise.
*/
function hasAccessToken() {
- return array_key_exists("yosdk_at", $_COOKIE) &&
+ return array_key_exists("yosdk_at", $_COOKIE) &&
(strlen($_COOKIE["yosdk_at"]) > 0);
}
/**
* Stores the given request token in the session store.
*
- * @param $token A PHP stdclass object containing the components of
+ * @param $token A PHP stdclass object containing the components of
* the OAuth request token.
* @return True on success, false otherwise.
*/
function storeRequestToken($token) {
if(!headers_sent()) {
- return setcookie("yosdk_rt", base64_encode(json_encode($token)),
+ return setcookie("yosdk_rt", base64_encode(json_encode($token)),
time() + 600);
}
else {
@@ -1405,13 +1407,13 @@ class CookieSessionStore {
/**
* Stores the given access token in the session store.
*
- * @param $token A PHP stdclass object containing the components of
+ * @param $token A PHP stdclass object containing the components of
* the OAuth access token.
* @return True on success, false otherwise.
*/
function storeAccessToken($token) {
if(!headers_sent()) {
- return setcookie("yosdk_at", base64_encode(json_encode($token)),
+ return setcookie("yosdk_at", base64_encode(json_encode($token)),
time() + (30 * 24 * 60 * 60));
}
else {
@@ -1444,8 +1446,94 @@ class CookieSessionStore {
}
/**
+ * 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.
+ */
+class NativeSessionStore {
+ /**
+ * Indicates if the session store has a request token.
+ *
+ * @return True if a request token is present, false otherwise.
+ */
+ function hasRequestToken() {
+ return array_key_exists("yosdk_rt", $_SESSION) && (strlen($_SESSION["yosdk_rt"]) > 0);
+ }
+
+ /**
+ * Indicates if the session store has an access token.
+ *
+ * @return True if an access token is present, false otherwise.
+ */
+ function hasAccessToken() {
+ return array_key_exists("yosdk_at", $_SESSION) && (strlen($_SESSION["yosdk_at"]) > 0);
+ }
+
+ /**
+ * Stores the given request token in the session store.
+ *
+ * @param $token A PHP stdclass object containing the components of
+ * the OAuth request token.
+ */
+ function storeRequestToken($token) {
+ $_SESSION['yosdk_rt'] = json_encode($token);
+ }
+
+ /**
+ * Fetches and returns the request token from the session store.
+ *
+ * @return The request token.
+ */
+ function fetchRequestToken() {
+ return json_decode($_SESSION["yosdk_rt"]);
+ }
+
+ /**
+ * Clears the request token from the session store.
+ *
+ */
+ function clearRequestToken() {
+ 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.
+ */
+ function storeAccessToken($token) {
+ $_SESSION['yosdk_at'] = json_encode($token);
+ }
+
+ /**
+ * Fetches and returns the access token from the session store.
+ *
+ * @return The access token.
+ */
+ function fetchAccessToken() {
+ return json_decode($_SESSION["yosdk_at"]);
+ }
+
+ /**
+ * Clears the access token from the session store.
+ *
+ */
+ function clearAccessToken() {
+ 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.
*/
class OAuthClient {
@@ -1473,21 +1561,21 @@ class OAuthClient {
* @private
*/
var $signatureMethod = NULL;
-
+
/**
* @private
- */
+ */
var $accepts = "application/json";
/**
* 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,
+ function OAuthClient($consumer, $token = NULL,
$oauthParamsLocation = OAUTH_PARAMS_IN_HEADERS,
$signatureMethod = OAUTH_SIGNATURE_HMAC_SHA1) {
$this->consumer = $consumer;
@@ -1520,8 +1608,8 @@ class OAuthClient {
}
return $this->request(array(
- "method" => "GET",
- "url" => $url,
+ "method" => "GET",
+ "url" => $url,
"query" => $queryParameters,
"timeout" => $timeout));
}
@@ -1541,8 +1629,8 @@ class OAuthClient {
}
return $this->request(array(
- "method" => "DELETE",
- "url" => $url,
+ "method" => "DELETE",
+ "url" => $url,
"query" => $queryParameters,
"timeout" => $timeout));
}
@@ -1558,9 +1646,9 @@ class OAuthClient {
*/
function put($url, $contentType, $content, $timeout = NULL) {
return $this->request(array(
- "method" => "PUT",
- "url" => $url,
- "content" => $content,
+ "method" => "PUT",
+ "url" => $url,
+ "content" => $content,
"contentType" => $contentType,
"timeout" => $timeout));
}
@@ -1574,13 +1662,13 @@ class OAuthClient {
* @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",
+ function post($url, $contentType = "application/x-www-form-urlencoded",
$content = array(), $timeout = NULL) {
return $this->request(array(
- "method" => "POST",
- "url" => $url,
- "content" => $content,
- "contentType" => $contentType,
+ "method" => "POST",
+ "url" => $url,
+ "content" => $content,
+ "contentType" => $contentType,
"timeout" => $timeout));
}
@@ -1604,9 +1692,9 @@ class OAuthClient {
}
$oauthRequest = OAuthRequest::from_consumer_and_token(
- $this->consumer, $this->token, $request["method"],
+ $this->consumer, $this->token, $request["method"],
$request["url"], $combinedParams);
- $oauthRequest->sign_request($this->signatureMethod, $this->consumer,
+ $oauthRequest->sign_request($this->signatureMethod, $this->consumer,
$this->token);
$headers = array("Accept: " . $this->accepts);
@@ -1624,7 +1712,7 @@ class OAuthClient {
$requestUrl = $request["url"];
}
- $requestTimeout = array_key_exists("timeout", $request) ?
+ $requestTimeout = array_key_exists("timeout", $request) ?
$request["timeout"] : $this->defaultTimeout;
$ch = curl_init($requestUrl);
@@ -1632,7 +1720,7 @@ class OAuthClient {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request["method"]);
- if(($this->oauthParamsLocation == OAUTH_PARAMS_IN_POST_BODY) ||
+ if(($this->oauthParamsLocation == OAUTH_PARAMS_IN_POST_BODY) ||
(!empty($request["content"]) && is_array($request["content"]))) {
// Content is an array, URL encode it.
if($this->oauthParamsLocation == OAUTH_PARAMS_IN_POST_BODY) {
@@ -1651,8 +1739,8 @@ class OAuthClient {
// Enable compressed responses from the servers.
curl_setopt($ch, CURLOPT_ENCODING, "");
- // Set the user agent so the SDK properly identifies itself for
- // usage tracking purposes. Include the version of the SDK and
+ // 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.
$sdkVersion = "1.2";
$agent = sprintf("YosPhpSdk/%s php/%s", $sdkVersion, phpversion());
@@ -1775,8 +1863,8 @@ class YahooConfig {
}
/**
- * An OAuth compatible version of http_build_query. http_build_query
- * doesn't work because it turns spaces into "+", which isn't allowed
+ * An OAuth compatible version of http_build_query. http_build_query
+ * doesn't work because it turns spaces into "+", which isn't allowed
* by OAuth.
*/
function oauth_http_build_query($parameters) {
@@ -1788,12 +1876,27 @@ function oauth_http_build_query($parameters) {
return $query;
}
-// 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
+/**
+ * PHP Compatibility functions
+ */
+
+if(!function_exists("property_exists")) {
+ function property_exists( $class, $property ) {
+ if ( is_object( $class ) ) {
+ $vars = get_object_vars( $class );
+ } else {
+ $vars = get_class_vars( $class );
+ }
+ return array_key_exists( $property, $vars );
+ }
+}
+
+// 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.
if(!function_exists("json_decode")) {
- // Only include JSON.php if someone else hasn't already. Depending on
- // the operating environment, other code may have brought their own
+ // 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.
if(!class_exists("Services_JSON")) {
include_once("JSON.php");
@@ -1810,15 +1913,4 @@ if(!function_exists("json_decode")) {
}
}
-if(!function_exists("property_exists")) {
- function property_exists( $class, $property ) {
- if ( is_object( $class ) ) {
- $vars = get_object_vars( $class );
- } else {
- $vars = get_class_vars( $class );
- }
- return array_key_exists( $property, $vars );
- }
-}
-
?>
View
240 sample/delicious.php
@@ -0,0 +1,240 @@
+<?php
+
+/**
+ * Using YQL Open Tables to create Yahoo! Open Application - Delicious
+ *
+ * http://developer.yahoo.com/devtool
+ * http://developer.yahoo.com/yql/console
+ */
+
+// Include the YOS library.
+require dirname(__FILE__).'/../lib/Yahoo.inc';
+
+// debug settings
+error_reporting(E_ALL | E_NOTICE); # do not show notices as library is php4 compatable
+ini_set('display_errors', true);
+YahooLogger::setDebug(true);
+YahooLogger::setDebugDestination('LOG');
+
+// use memcache to store oauth credentials via php native sessions
+ini_set('session.save_handler', 'memcache');
+session_save_path('tcp://localhost:11211?persistent=1&weight=1&timeout=1&retry_interval=15');
+session_start();
+
+// Make sure you obtain application keys before continuing by visiting:
+// https://developer.yahoo.com/dashboard/createKey.html
+
+$consumerKey = '###';
+$consumerKeySecret = '###';
+$applicationId = '###';
+
+// oauth dance if not authenticated
+$session = YahooSession::requireSession($consumerKey, $consumerKeySecret, $applicationId);
+
+// get oauthed user guid + profile
+$user = $session->getSessionedUser();
+
+$header = '<h2><img src="http://delicious.com/favicon.ico" title="Delicious" width="16" height="16" />Delicious // social bookmarking</h2>';
+$content
+= '<div id="bookmarks">';
+
+// if user is logged in and oauth is valid
+if(is_object($user))
+{
+ // load y! profile data
+ $profile = $user->loadProfile();
+
+ // get yap app instance for yql / small view
+ $application = new YahooApplication($consumerKey, $consumerKeySecret);
+
+ // delicious yql
+ $yql = "use 'http://www.javarants.com/delicious/delicious.feeds.xml' as delicious.feeds;";
+ $yql .= "select * from delicious.feeds";
+
+ if(isset($_REQUEST['username']))
+ {
+ // validate delicious user and set username in datastore
+ $username = htmlspecialchars($_REQUEST['username']);
+ }
+ else
+ {
+ // fetch user data store
+ $username = apc_fetch('user_'.$user->guid);
+ }
+
+ if($username)
+ {
+ // if user has specified a delicious username
+ $yql .= " where username='".$username."';";
+ }
+
+ $data = $application->query($yql);
+ if(is_object($data) && isset($data->query->results->item))
+ {
+ // build small view content (my yahoo)
+ $content .= '<ul class="delicious">';
+ foreach($data->query->results->item as $bookmark):
+ $content .= '<li><a href="'.$bookmark->link.'">'.$bookmark->title.'</a></li>';
+ endforeach;
+ $content .= '</ul>';
+
+ if($username)
+ {
+ if(isset($_REQUEST['username']))
+ {
+ // username is valid (yql returned results), so save for future requests
+ apc_store('user_'.$user->guid, $username);
+ }
+
+ // update small view for user bookmarks
+ $application->setSmallView($user->guid, $header.$content);
+ }
+ }
+ else
+ {
+ $content .= '<ul><li><a href="http://delicious.com/popular">Invalid username...</a></li></ul>';
+ }
+}
+$content .= '</div>';
+
+/*
+ // available open tables
+
+ use 'http://www.javarants.com/delicious/delicious.feeds.popular.xml' as delicious.feeds.popular;
+ use 'http://www.javarants.com/delicious/delicious.feeds.xml' as delicious.feeds;
+
+ use 'http://www.javarants.com/friendfeed/friendfeed.feeds.xml' as friendfeed.feeds;
+ use 'http://www.javarants.com/friendfeed/friendfeed.home.xml' as friendfeed.home;
+ use 'http://www.javarants.com/friendfeed/friendfeed.profile.xml' as friendfeed.profile;
+ use 'http://www.javarants.com/friendfeed/friendfeed.rooms.xml' as friendfeed.rooms;
+ use 'http://www.javarants.com/friendfeed/friendfeed.services.xml' as friendfeed.services;
+ use 'http://www.javarants.com/friendfeed/friendfeed.updates.xml' as friendfeed.updates;
+
+ use 'http://www.javarants.com/nyt/nyt.article.search.xml' as nyt.article.search;
+ use 'http://www.javarants.com/nyt/nyt.bestsellers.history.xml' as nyt.bestsellers.history;
+ use 'http://www.javarants.com/nyt/nyt.bestsellers.search.xml' as nyt.bestsellers.search;
+ use 'http://www.javarants.com/nyt/nyt.bestsellers.xml' as nyt.bestsellers;
+ use 'http://www.javarants.com/nyt/nyt.movies.critics.xml' as nyt.movies.critics;
+ use 'http://www.javarants.com/nyt/nyt.movies.picks.xml' as nyt.movies.picks;
+ use 'http://www.javarants.com/nyt/nyt.movies.reviews.xml' as nyt.movies.reviews;
+
+ use 'http://www.javarants.com/shopping/shopping.product.search.xml' as shopping.product.search;
+
+ use 'http://www.javarants.com/weather/weather.local.xml' as weather.local;
+ use 'http://www.javarants.com/weather/weather.search.xml' as weather.search;
+
+ use 'http://www.javarants.com/dopplr/dopplr.auth.xml' as dopplr.auth;
+ use 'http://www.javarants.com/dopplr/dopplr.city.info.xml' as dopplr.city.info;
+ use 'http://www.javarants.com/dopplr/dopplr.futuretrips.info.xml' as dopplr.futuretrips.info;
+ use 'http://www.javarants.com/dopplr/dopplr.traveller.fellows.xml' as dopplr.traveller.fellows;
+ use 'http://www.javarants.com/dopplr/dopplr.traveller.info.xml' as dopplr.traveller.info;
+ use 'http://www.javarants.com/dopplr/dopplr.traveller.travelling.xml' as dopplr.traveller.travelling;
+ use 'http://www.javarants.com/dopplr/dopplr.trips.info.xml' as dopplr.trips.info;
+
+ use 'http://www.javarants.com/twitter/twitter.user.timeline.xml' as twitter.user.timeline;
+ use 'http://www.javarants.com/twitter/twitter.user.profile.xml' as twitter.user.profile;
+ use 'http://www.javarants.com/twitter/twitter.user.status.xml' as twitter.user.status;
+
+ use 'http://www.javarants.com/wesabe/wesabe.tags.xml' as wesabe.tags;
+
+ use 'http://www.javarants.com/whitepages/whitepages.search.xml' as whitepages.search;
+ use 'http://www.javarants.com/whitepages/whitepages.reverse.xml' as whitepages.reverse;
+
+ use 'http://www.javarants.com/github/github.repo.commits.xml' as github.repo.commits;
+ use 'http://www.javarants.com/github/github.user.repos.xml' as github.user.repos;
+ use 'http://www.javarants.com/github/github.user.info.xml' as github.user.info;
+
+ use 'http://www.javarants.com/zillow/zillow.search.xml' as zillow.search;
+*/
+
+// set content type + language
+// header("Content-Type: text/html; charset=utf-8");
+// header("Content-Language: en");
+/*
+echo '<?xml version="1.0" encoding="utf-8"?>';
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr">
+ <head profile="http://gmpg.org/xfn/11">
+ <title>Delicious // social bookmarking</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+ <meta http-equiv="Content-Language" content="en" />
+ <link rel="stylesheet" type="text/css" media="screen" href="http://yui.yahooapis.com/combo?3.0.0pr2/build/cssreset/reset-min.css&amp;3.0.0pr2/build/cssfonts/fonts-min.css&amp;3.0.0pr2/build/cssgrids/grids-min.css&amp;3.0.0pr2/build/cssbase/base-min.css&amp;3.0.0pr2/build/widget/assets/skins/sam/widget.css&amp;3.0.0pr2/build/widget/assets/skins/sam/widget-stack.css&amp;3.0.0pr2/build/overlay/assets/skins/sam/overlay.css" />
+ <link rel="stylesheet" type="text/css" media="screen" href="common.css" />
+ <link rel="shortcut icon" href="http://delicious.com/favicon.ico" />
+ <body>
+
+ <div id="itw" class="yui-d0 yui-skin-sam">
+ <?php echo $content; ?>
+ </div>
+
+ <script type="text/javascript" src="http://yui.yahooapis.com/combo?3.0.0pr2/build/yui/yui-min.js&amp;3.0.0pr2/build/oop/oop-min.js&amp;3.0.0pr2/build/event/event-min.js&amp;3.0.0pr2/build/dom/dom-min.js&amp;3.0.0pr2/build/node/node-min.js&amp;3.0.0pr2/build/attribute/attribute-min.js&amp;3.0.0pr2/build/base/base-min.js&amp;3.0.0pr2/build/anim/anim-min.js&amp;3.0.0pr2/build/cookie/cookie-min.js&amp;3.0.0pr2/build/io/io-min.js&amp;3.0.0pr2/build/json/json-min.js&amp;3.0.0pr2/build/dump/dump-min.js&amp;3.0.0pr2/build/substitute/substitute-min.js&amp;3.0.0pr2/build/classnamemanager/classnamemanager-min.js&amp;3.0.0pr2/build/widget/widget-min.js&amp;3.0.0pr2/build/widget/widget-position-min.js&amp;3.0.0pr2/build/widget/widget-position-ext-min.js&amp;3.0.0pr2/build/widget/widget-stack-min.js&amp;3.0.0pr2/build/widget/widget-stdmod-min.js&amp;3.0.0pr2/build/overlay/overlay-min.js"></script>
+ <script type="text/javascript" src="common.js"></script>
+ </body>
+</html>
+*/
+?>
+<style type="text/css">
+.yui-d0,.yui-d1,.yui-d1f,.yui-d2,.yui-d2f,.yui-d3,.yui-d3f{margin:auto;text-align:left;width:57.69em;}.yui-t1,.yui-t2,.yui-t3,.yui-t4,.yui-t5,.yui-t6{margin:auto;text-align:left;width:100%;}.yui-d0{margin:auto 10px;width:auto;}.yui-d0f{width:100%;}.yui-d2{width:73.076em;}.yui-d2f{width:950px;}.yui-d3{width:74.923em;}.yui-d3f{width:974px;}.yui-b{position:relative;}.yui-main .yui-b{position:static;}.yui-main{width:100%;}.yui-t1 .yui-main,.yui-t2 .yui-main,.yui-t3 .yui-main{float:right;margin-left:-25em;}.yui-t4 .yui-main,.yui-t5 .yui-main,.yui-t6 .yui-main{float:left;margin-right:-25em;}.yui-t1 .yui-b{float:left;width:12.30769em;}.yui-t1 .yui-main .yui-b{margin-left:13.30769em;}.yui-t2 .yui-b{float:left;width:13.84615em;}.yui-t2 .yui-main .yui-b{margin-left:14.84615em;}.yui-t3 .yui-b{float:left;width:23.0769em;}.yui-t3 .yui-main .yui-b{margin-left:24.0769em;}.yui-t4 .yui-b{float:right;width:13.8456em;}.yui-t4 .yui-main .yui-b{margin-right:14.8456em;}.yui-t5 .yui-b{float:right;width:18.4615em;}.yui-t5 .yui-main .yui-b{margin-right:19.4615em;}.yui-t6 .yui-b{float:right;width:23.0769em;}.yui-t6 .yui-main .yui-b{margin-right:24.0769em;}.yui-main .yui-b{float:none;width:auto;}.yui-gb .yui-u,.yui-g .yui-gb .yui-u,.yui-gb .yui-g,.yui-gb .yui-gb,.yui-gb .yui-gc,.yui-gb .yui-gd,.yui-gb .yui-ge,.yui-gb .yui-gf,.yui-gc .yui-u,.yui-gc .yui-g,.yui-gd .yui-u{float:left;}.yui-g .yui-u,.yui-g .yui-g,.yui-g .yui-gb,.yui-g .yui-gc,.yui-g .yui-gd,.yui-g .yui-ge,.yui-g .yui-gf,.yui-gc .yui-u,.yui-gd .yui-g,.yui-g .yui-gc .yui-u,.yui-ge .yui-u,.yui-ge .yui-g,.yui-gf .yui-g,.yui-gf .yui-u{float:right;}.yui-g div.first,.yui-gb div.first,.yui-gc div.first,.yui-gd div.first,.yui-ge div.first,.yui-gf div.first,.yui-g .yui-gc div.first,.yui-g .yui-ge div.first,.yui-gc div.first div.first{float:left;}.yui-g .yui-u,.yui-g .yui-g,.yui-g .yui-gb,.yui-g .yui-gc,.yui-g .yui-gd,.yui-g .yui-ge,.yui-g .yui-gf{width:49.1%;}.yui-gb .yui-u,.yui-g .yui-gb .yui-u,.yui-gb .yui-g,.yui-gb .yui-gb,.yui-gb .yui-gc,.yui-gb .yui-gd,.yui-gb .yui-ge,.yui-gb .yui-gf,.yui-gc .yui-u,.yui-gc .yui-g,.yui-gd .yui-u{width:32%;margin-left:2.0%;}.yui-gc div.first,.yui-gd .yui-u{width:66%;}.yui-gd div.first{width:32%;}.yui-ge div.first,.yui-gf .yui-u{width:74.2%;}.yui-ge .yui-u,.yui-gf div.first{width:24%;}.yui-g .yui-gb div.first,.yui-gb div.first,.yui-gc div.first,.yui-gd div.first{margin-left:0;}.yui-g .yui-g .yui-u,.yui-gb .yui-g .yui-u,.yui-gc .yui-g .yui-u,.yui-gd .yui-g .yui-u,.yui-ge .yui-g .yui-u,.yui-gf .yui-g .yui-u{width:49%;}.yui-g .yui-gc div.first,.yui-gd .yui-g{width:66%;}.yui-g .yui-gc .yui-u,.yui-gb .yui-gc .yui-u{width:32%;margin-right:0;}.yui-gb .yui-gc div.first{width:66%;}.yui-gb .yui-ge .yui-u,.yui-gb .yui-gf .yui-u{margin:0;}.yui-gb .yui-gd div.first{width:32%;}.yui-ge .yui-g{width:24%;}.yui-gf .yui-g{width:74.2%;}.yui-gb .yui-ge div.yui-u,.yui-gb .yui-gf div.yui-u{float:right;}.yui-gb .yui-ge div.first,.yui-gb .yui-gf div.first{float:left;}.yui-ge div.first .yui-gd .yui-u{width:65%;}.yui-ge div.first .yui-gd div.first{width:32%;}
+h1{font-size:138.5%;}h2{font-size:123.1%;}h3{font-size:108%;}h1,h2,h3{margin:1em 0;}h1,h2,h3,h4,h5,h6,strong{font-weight:bold;}abbr,acronym{border-bottom:1px dotted #000;cursor:help;}em{font-style:italic;}blockquote,ul,ol,dl{margin:1em;}ol,ul,dl{margin-left:2em;}ol li{list-style:decimal outside;}ul li{list-style:disc outside;}dl dd{margin-left:1em;}th,td{border:1px solid #000;padding:.5em;}th{font-weight:bold;text-align:center;}caption{margin-bottom:.5em;text-align:center;}p,fieldset,table,pre{margin-bottom:1em;}textarea{width:12.25em;}
+
+#itw {
+ text-align: left;
+ font-family: Tahoma, Georgia;
+ background-color: #fff;
+ color: #000;
+}
+
+
+img {
+ margin: 4px;
+}
+
+a {
+ text-decoration: none;
+ font-weight: bold;
+ color: #000;
+}
+
+a:hover {
+ color: #000;
+ text-decoration:underline;
+}
+
+div.delicious {
+ padding: 0 0 0 0;
+ margin: 0 0 0 0;
+}
+
+div.delicious ul {
+ padding: 0 0 0 0;
+ margin: 0 0 0 0;
+}
+
+div.delicious ul li {
+ list-style-type: none;
+ padding: 0 0 0 0;
+ margin: 0 0 0 0;
+}
+
+div.delicious ul li a {
+ font-weight: normal;
+}
+
+div.delicious h2 a {
+ color: #000;
+}
+</style>
+<div id="itw" class="yui-d0 yui-skin-sam">
+
+ <?php echo $header; ?>
+
+ <yml:form method="POST" view="YahooFullView">
+ <fieldset>
+ <legend>Delicious Username</legend>
+ <input type="text" name="username" />
+ <input type="submit" value="Refresh" />
+ </fieldset>
+ </yml:form>
+
+ <?php echo $content; ?>
+</div>
View
162 sample/sampleapp.php
@@ -1,126 +1,138 @@
<?php
- // Include the YOS library.
- require("Yahoo.inc");
-
- // Make sure you obtain application keys before continuing by visiting:
- // https://developer.yahoo.com/dashboard/createKey.html
-
- // Your consumer key goes here.
- define("CONSUMER_KEY","");
-
- // Your consumer key secret goes here.
- define("CONSUMER_SECRET","");
-
- // Your application ID goes here.
- define("APP_ID","");
-
- if(array_key_exists("logout", $_GET)) {
- // if a session exists and the logout flag is detected
- // clear the session tokens and reload the page.
- YahooSession::clearSession();
- header("Location: sampleapp.php");
- }
-
- // check for the existance of a session.
- // this will determine if we need to show a pop-up and fetch the auth url,
- // or fetch the user's social data.
- $hasSession = YahooSession::hasSession(CONSUMER_KEY, CONSUMER_SECRET, APP_ID);
-
- if($hasSession == FALSE) {
- // create the callback url,
- $callback = YahooUtil::current_url()."?in_popup";
-
- // pass the credentials to get an auth url.
- // this URL will be used for the pop-up.
- $auth_url = YahooSession::createAuthorizationUrl(CONSUMER_KEY, CONSUMER_SECRET, $callback);
+
+// Include the YOS library.
+require dirname(__FILE__).'/../lib/Yahoo.inc';
+
+// debug settings
+error_reporting(E_ALL | E_NOTICE); # do not show notices as library is php4 compatable
+ini_set('display_errors', true);
+YahooLogger::setDebug(true);
+YahooLogger::setDebugDestination('LOG');
+
+// use memcache to store oauth credentials via php native sessions
+ini_set('session.save_handler', 'files');
+session_save_path('/tmp/');
+session_start();
+
+// Make sure you obtain application keys before continuing by visiting:
+// https://developer.yahoo.com/dashboard/createKey.html
+
+// Your consumer key goes here.
+define("CONSUMER_KEY","###");
+
+// Your consumer key secret goes here.
+define("CONSUMER_SECRET","###");
+
+// Your application ID goes here.
+define("APP_ID","###");
+
+if(array_key_exists("logout", $_GET)) {
+ // if a session exists and the logout flag is detected
+ // clear the session tokens and reload the page.
+ YahooSession::clearSession();
+ header("Location: sampleapp.php");
+}
+
+// check for the existance of a session.
+// this will determine if we need to show a pop-up and fetch the auth url,
+// or fetch the user's social data.
+$hasSession = YahooSession::hasSession(CONSUMER_KEY, CONSUMER_SECRET, APP_ID);
+
+if($hasSession == FALSE) {
+ // create the callback url,
+ $callback = YahooUtil::current_url()."?in_popup";
+
+ // pass the credentials to get an auth url.
+ // this URL will be used for the pop-up.
+ $auth_url = YahooSession::createAuthorizationUrl(CONSUMER_KEY, CONSUMER_SECRET, $callback);
+}
+else {
+ // pass the credentials to initiate a session
+ $session = YahooSession::requireSession(CONSUMER_KEY, CONSUMER_SECRET, APP_ID);
+
+ // if the in_popup flag is detected,
+ // the pop-up has loaded the callback_url and we can close this window.
+ if(array_key_exists("in_popup", $_GET)) {
+ close_popup();
+ exit;
}
- else {
- // pass the credentials to initiate a session
- $session = YahooSession::requireSession(CONSUMER_KEY, CONSUMER_SECRET, APP_ID);
-
- // if the in_popup flag is detected,
- // the pop-up has loaded the callback_url and we can close this window.
- if(array_key_exists("in_popup", $_GET)) {
- close_popup();
- exit;
- }
-
- // if a session is initialized, fetch the user's profile information
- if($session) {
- // Get the currently sessioned user.
- $user = $session->getSessionedUser();
-
- // Load the profile for the current user.
- $profile = $user->getProfile();
- }
+
+ // if a session is initialized, fetch the user's profile information
+ if($session) {
+ // Get the currently sessioned user.
+ $user = $session->getSessionedUser();
+
+ // Load the profile for the current user.
+ $profile = $user->getProfile();
}
-
- /**
- * Helper method to close the pop-up window via javascript.
- */
- function close_popup() {
+}
+
+/**
+ * Helper method to close the pop-up window via javascript.
+ */
+function close_popup() {
?>
<script type="text/javascript">
window.close();
</script>
<?php
- }
+}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>YOS Social Platform Sample Application</title>
-
- <!-- Combo-handled YUI JS files: -->
+
+ <!-- Combo-handled YUI JS files: -->
<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.7.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="popupmanager.js"></script>
-
- <!-- Combo-handled YUI CSS files: -->
+
+ <!-- Combo-handled YUI CSS files: -->
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.7.0/build/reset-fonts-grids/reset-fonts-grids.css&2.7.0/build/base/base-min.css">
</head>
<body>
<?php
if($hasSession == FALSE) {
- // if a session does not exist, output the
+ // if a session does not exist, output the
// login / share button linked to the auth_url.
echo sprintf("<a href=\"%s\" id=\"yloginLink\"><img src=\"http://l.yimg.com/a/i/ydn/social/updt-spurp.png\"></a>\n",
$auth_url);
}
else if($hasSession && $profile) {
- // if a session does exist and the profile data was
+ // if a session does exist and the profile data was
// fetched without error, print out a simple usercard.
- echo sprintf("<img src=\"%s\"/><p><h2>Hi <a href=\"%s\" target=\"_blank\">%s!</a></h2></p>\n",
+ echo sprintf("<img src=\"%s\"/><p><h2>Hi <a href=\"%s\" target=\"_blank\">%s!</a></h2></p>\n",
$profile->image->imageUrl, $profile->profileUrl, $profile->nickname);
if($profile->status->message != "") {
$statusDate = date('F j, y, g:i a', strtotime($profile->status->lastStatusModified));
- echo sprintf("<p><strong>&#8220;</strong>%s<strong>&#8221;</strong> on %s</p>",
- $profile->status->message, $statusDate);
+ echo sprintf("<p><strong>&#8220;</strong>%s<strong>&#8221;</strong> on %s</p>",
+ $profile->status->message, $statusDate);
}
-
+
echo "<p><a href=\"?logout\">Logout</a></p>";
}
?>
<script type="text/javascript">
var Event = YAHOO.util.Event;
var _gel = function(el) {return document.getElementById(el)};
-
+
function handleDOMReady() {
if(_gel("yloginLink")) {
- Event.addListener("yloginLink", "click", handleLoginClick);
+ Event.addListener("yloginLink", "click", handleLoginClick);
}
}
-
+
function handleLoginClick(event) {
// block the url from opening like normal
Event.preventDefault(event);
-
+
// open pop-up using the auth_url
var auth_url = _gel("yloginLink").href;
PopupManager.open(auth_url,600,435);
}
-
- Event.onDOMReady(handleDOMReady);
+
+ Event.onDOMReady(handleDOMReady);
</script>
</body>
</html>
Please sign in to comment.
Something went wrong with that request. Please try again.