Skip to content
Browse files

removed php sdk

  • Loading branch information...
1 parent 5b5087c commit ed495e43cd57fedcba98f49726a143f3963ffe45 @jcleblanc jcleblanc committed Jul 20, 2009
View
17 php_sdk/.svn/all-wcprops
@@ -1,17 +0,0 @@
-K 25
-svn:wc:ra_dav:version-url
-V 30
-/yoshackday/!svn/ver/8/php_sdk
-END
-OAuth.php
-K 25
-svn:wc:ra_dav:version-url
-V 40
-/yoshackday/!svn/ver/8/php_sdk/OAuth.php
-END
-Yahoo.inc
-K 25
-svn:wc:ra_dav:version-url
-V 40
-/yoshackday/!svn/ver/8/php_sdk/Yahoo.inc
-END
View
103 php_sdk/.svn/entries
@@ -1,103 +0,0 @@
-9
-
-dir
-8
-http://subversion.theurer.cc/yoshackday/php_sdk
-http://subversion.theurer.cc/yoshackday
-
-
-
-2009-07-10T17:20:42.059818Z
-8
-dan
-
-
-svn:special svn:externals svn:needs-lock
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-0
-
-OAuth.php
-file
-
-
-
-
-2009-02-18T18:44:10.000000Z
-255da61230daf678522bba9341749cff
-2009-07-10T17:20:42.059818Z
-8
-dan
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-24487
-
-Yahoo.inc
-file
-
-
-
-
-2009-02-18T18:44:10.000000Z
-a9daa60fdc1fbc6ae0edcf9aff89d1d8
-2009-07-10T17:20:42.059818Z
-8
-dan
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-51854
-
View
1 php_sdk/.svn/format
@@ -1 +0,0 @@
-9
View
819 php_sdk/.svn/text-base/OAuth.php.svn-base
@@ -1,819 +0,0 @@
-<?php
-/**
- * The MIT License
- *
- * Copyright (c) 2008 OAuth.net
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- */
-
-/**
- * Branched from version 587 of OAuth.php from the OAuth.net project. Major
- * changes are limited to adding PHP 4 compatibility.
- *
- * Ryan Kennedy (rckenned@yahoo-inc.com)
- */
-
-class OAuthConsumer {/*{{{*/
- var $key;
- var $secret;
-
- function OAuthConsumer($key, $secret, $callback_url=NULL) {/*{{{*/
- $this->key = $key;
- $this->secret = $secret;
- $this->callback_url = $callback_url;
- }/*}}}*/
-}/*}}}*/
-
-class OAuthToken {/*{{{*/
- // access tokens and request tokens
- var $key;
- var $secret;
-
- /**
- * key = the token
- * secret = the token secret
- */
- function OAuthToken($key, $secret) {/*{{{*/
- $this->key = $key;
- $this->secret = $secret;
- }/*}}}*/
-
- /**
- * generates the basic string serialization of a token that a server
- * would respond to request_token and access_token calls with
- */
- function to_string() {/*{{{*/
- return "oauth_token=" . OAuthUtil::urlencodeRFC3986($this->key) .
- "&oauth_token_secret=" . OAuthUtil::urlencodeRFC3986($this->secret);
- }/*}}}*/
-
- function __toString() {/*{{{*/
- return $this->to_string();
- }/*}}}*/
-}/*}}}*/
-
-class OAuthSignatureMethod {/*{{{*/
- function check_signature(&$request, $consumer, $token, $signature) {
- $built = $this->build_signature($request, $consumer, $token);
- return $built == $signature;
- }
-}/*}}}*/
-
-class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {/*{{{*/
- function get_name() {/*{{{*/
- return "HMAC-SHA1";
- }/*}}}*/
-
- function build_signature($request, $consumer, $token) {/*{{{*/
- $base_string = $request->get_signature_base_string();
- $request->base_string = $base_string;
-
- $key_parts = array(
- $consumer->secret,
- ($token) ? $token->secret : ""
- );
-
- $key_parts = array_map(array('OAuthUtil','urlencodeRFC3986'), $key_parts);
- $key = implode('&', $key_parts);
-
- return base64_encode(hash_hmac('sha1', $base_string, $key, true));
- }/*}}}*/
-}/*}}}*/
-
-class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {/*{{{*/
- function get_name() {/*{{{*/
- return "PLAINTEXT";
- }/*}}}*/
-
- function build_signature($request, $consumer, $token) {/*{{{*/
- $sig = array(
- OAuthUtil::urlencodeRFC3986($consumer->secret)
- );
-
- if ($token) {
- array_push($sig, OAuthUtil::urlencodeRFC3986($token->secret));
- } else {
- array_push($sig, '');
- }
-
- $raw = implode("&", $sig);
- // for debug purposes
- $request->base_string = $raw;
-
- return $raw;
- }/*}}}*/
-}/*}}}*/
-
-class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {/*{{{*/
- function get_name() {/*{{{*/
- return "RSA-SHA1";
- }/*}}}*/
-
- function fetch_public_cert(&$request) {/*{{{*/
- // not implemented yet, ideas are:
- // (1) do a lookup in a table of trusted certs keyed off of consumer
- // (2) fetch via http using a url provided by the requester
- // (3) some sort of specific discovery code based on request
- //
- // either way should return a string representation of the certificate
- trigger_error("fetch_public_cert not implemented", E_USER_ERROR);
- return NULL;
- }/*}}}*/
-
- function fetch_private_cert(&$request) {/*{{{*/
- // not implemented yet, ideas are:
- // (1) do a lookup in a table of trusted certs keyed off of consumer
- //
- // either way should return a string representation of the certificate
- trigger_error("fetch_private_cert not implemented", E_USER_ERROR);
- return NULL;
- }/*}}}*/
-
- function build_signature(&$request, $consumer, $token) {/*{{{*/
- $base_string = $request->get_signature_base_string();
-
- // Fetch the private key cert based on the request
- $cert = $this->fetch_private_cert($request);
-
- // Pull the private key ID from the certificate
- $privatekeyid = openssl_get_privatekey($cert);
-
- // Sign using the key
- $ok = openssl_sign($base_string, $signature, $privatekeyid);
-
- // Release the key resource
- openssl_free_key($privatekeyid);
-
- return base64_encode($signature);
- } /*}}}*/
-
- function check_signature(&$request, $consumer, $token, $signature) {/*{{{*/
- $decoded_sig = base64_decode($signature);
-
- $base_string = $request->get_signature_base_string();
-
- // Fetch the public key cert based on the request
- $cert = $this->fetch_public_cert($request);
-
- // Pull the public key ID from the certificate
- $publickeyid = openssl_get_publickey($cert);
-
- // Check the computed signature against the one passed in the query
- $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
-
- // Release the key resource
- openssl_free_key($publickeyid);
-
- return $ok == 1;
- } /*}}}*/
-}/*}}}*/
-
-class OAuthRequest {/*{{{*/
- var $parameters;
- var $http_method;
- var $http_url;
- // for debug purposes
- var $base_string;
-
- function OAuthRequest($http_method, $http_url, $parameters=array()) {/*{{{*/
- $this->parameters = $parameters;
- $this->http_method = $http_method;
- $this->http_url = $http_url;
- }/*}}}*/
-
-
- /**
- * attempt to build up a request from what was passed to the server
- */
- function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {/*{{{*/
- $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
- @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
- @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
-
- $request_headers = OAuthRequest::get_headers();
-
- // let the library user override things however they'd like, if they know
- // which parameters to use then go for it, for example XMLRPC might want to
- // do this
- if ($parameters) {
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- }
- // next check for the auth header, we need to do some extra stuff
- // if that is the case, namely suck in the parameters from GET or POST
- // so that we can include them in the signature
- else if (@substr($request_headers['Authorization'], 0, 5) == "OAuth") {
- $header_parameters = OAuthRequest::split_header($request_headers['Authorization']);
- if ($http_method == "GET") {
- $req_parameters = $_GET;
- }
- else if ($http_method = "POST") {
- $req_parameters = $_POST;
- }
- $parameters = array_merge($header_parameters, $req_parameters);
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- }
- else if ($http_method == "GET") {
- $req = new OAuthRequest($http_method, $http_url, $_GET);
- }
- else if ($http_method == "POST") {
- $req = new OAuthRequest($http_method, $http_url, $_POST);
- }
- return $req;
- }/*}}}*/
-
- /**
- * pretty much a helper function to set up the request
- */
- function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=array()) {/*{{{*/
- static $version = '1.0';
- $defaults = array("oauth_version" => $version,
- "oauth_nonce" => OAuthRequest::generate_nonce(),
- "oauth_timestamp" => OAuthRequest::generate_timestamp(),
- "oauth_consumer_key" => $consumer->key);
- $parameters = array_merge($defaults, $parameters);
-
- if ($token) {
- $parameters['oauth_token'] = $token->key;
- }
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- return $req;
- }/*}}}*/
-
- function set_parameter($name, $value) {/*{{{*/
- $this->parameters[$name] = $value;
- }/*}}}*/
-
- function get_parameter($name) {/*{{{*/
- return $this->parameters[$name];
- }/*}}}*/
-
- function get_parameters() {/*{{{*/
- return $this->parameters;
- }/*}}}*/
-
- /**
- * Returns the normalized parameters of the request
- *
- * This will be all (except oauth_signature) parameters,
- * sorted first by key, and if duplicate keys, then by
- * value.
- *
- * The returned string will be all the key=value pairs
- * concated by &.
- *
- * @return string
- */
- function get_signable_parameters() {/*{{{*/
- // Include query parameters
- $url = parse_url($this->http_url);
- if(array_key_exists("query", $url)) {
- parse_str($url["query"], $query);
-
- foreach($query as $key => $value) {
- $this->set_parameter($key, $value);
- }
- }
-
- // Grab all parameters
- $params = $this->parameters;
-
- // Remove oauth_signature if present
- if (isset($params['oauth_signature'])) {
- unset($params['oauth_signature']);
- }
-
- // Urlencode both keys and values
- $keys = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_keys($params));
- $values = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_values($params));
- $params = array();
- for($i = 0; $i < count($keys); $i++) {
- $params[$keys[$i]] = $values[$i];
- }
-
- // Sort by keys (natsort)
- uksort($params, 'strnatcmp');
-
- // Generate key=value pairs
- $pairs = array();
- foreach ($params as $key=>$value ) {
- if (is_array($value)) {
- // If the value is an array, it's because there are multiple
- // with the same key, sort them, then add all the pairs
- natsort($value);
- foreach ($value as $v2) {
- $pairs[] = $key . '=' . $v2;
- }
- } else {
- $pairs[] = $key . '=' . $value;
- }
- }
-
- // Return the pairs, concated with &
- return implode('&', $pairs);
- }/*}}}*/
-
- /**
- * Returns the base string of this request
- *
- * The base string defined as the method, the url
- * and the parameters (normalized), each urlencoded
- * and the concated with &.
- */
- function get_signature_base_string() {/*{{{*/
- $parts = array(
- $this->get_normalized_http_method(),
- $this->get_normalized_http_url(),
- $this->get_signable_parameters()
- );
-
- $parts = array_map(array('OAuthUtil', 'urlencodeRFC3986'), $parts);
-
- return implode('&', $parts);
- }/*}}}*/
-
- /**
- * just uppercases the http method
- */
- function get_normalized_http_method() {/*{{{*/
- return strtoupper($this->http_method);
- }/*}}}*/
-
- /**
- * parses the url and rebuilds it to be
- * scheme://host/path
- */
- function get_normalized_http_url() {/*{{{*/
- $parts = parse_url($this->http_url);
-
- // FIXME: port should handle according to http://groups.google.com/group/oauth/browse_thread/thread/1b203a51d9590226
- $port = (isset($parts['port']) && $parts['port'] != '80') ? ':' . $parts['port'] : '';
- $path = (isset($parts['path'])) ? $parts['path'] : '';
-
- return $parts['scheme'] . '://' . $parts['host'] . $port . $path;
- }/*}}}*/
-
- /**
- * builds a url usable for a GET request
- */
- function to_url() {/*{{{*/
- $out = $this->get_normalized_http_url() . "?";
- $out .= $this->to_postdata();
- return $out;
- }/*}}}*/
-
- /**
- * builds the data one would send in a POST request
- */
- function to_postdata() {/*{{{*/
- $total = array();
- foreach ($this->parameters as $k => $v) {
- $total[] = OAuthUtil::urlencodeRFC3986($k) . "=" . OAuthUtil::urlencodeRFC3986($v);
- }
- $out = implode("&", $total);
- return $out;
- }/*}}}*/
-
- /**
- * builds the Authorization: header
- */
- function to_header() {/*{{{*/
- $headerParams = array();
- foreach ($this->parameters as $k => $v) {
- if (substr($k, 0, 5) != "oauth") continue;
- $headerParams[] = OAuthUtil::urlencodeRFC3986($k) . '="' . OAuthUtil::urlencodeRFC3986($v) . '"';
- }
- return sprintf("Authorization: OAuth %s", implode(",", $headerParams));
- }/*}}}*/
-
- function __toString() {/*{{{*/
- return $this->to_url();
- }/*}}}*/
-
-
- function sign_request($signature_method, $consumer, $token) {/*{{{*/
- $this->set_parameter("oauth_signature_method", $signature_method->get_name());
- $signature = $this->build_signature($signature_method, $consumer, $token);
- $this->set_parameter("oauth_signature", $signature);
- }/*}}}*/
-
- function build_signature($signature_method, $consumer, $token) {/*{{{*/
- $signature = $signature_method->build_signature($this, $consumer, $token);
- return $signature;
- }/*}}}*/
-
- /**
- * util function: current timestamp
- */
- function generate_timestamp() {/*{{{*/
- return time();
- }/*}}}*/
-
- /**
- * util function: current nonce
- */
- function generate_nonce() {/*{{{*/
- $mt = microtime();
- $rand = mt_rand();
-
- return md5($mt . $rand); // md5s look nicer than numbers
- }/*}}}*/
-
- /**
- * util function for turning the Authorization: header into
- * parameters, has to do some unescaping
- */
- function split_header($header) {/*{{{*/
- // this should be a regex
- // error cases: commas in parameter values
- $parts = explode(",", $header);
- $out = array();
- foreach ($parts as $param) {
- $param = ltrim($param);
- // skip the "realm" param, nobody ever uses it anyway
- if (substr($param, 0, 5) != "oauth") continue;
-
- $param_parts = explode("=", $param);
-
- // rawurldecode() used because urldecode() will turn a "+" in the
- // value into a space
- $out[$param_parts[0]] = rawurldecode(substr($param_parts[1], 1, -1));
- }
- return $out;
- }/*}}}*/
-
- /**
- * helper to try to sort out headers for people who aren't running apache
- */
- function get_headers() {/*{{{*/
- if (function_exists('apache_request_headers')) {
- // we need this to get the actual Authorization: header
- // because apache tends to tell us it doesn't exist
- return apache_request_headers();
- }
- // otherwise we don't have apache and are just going to have to hope
- // that $_SERVER actually contains what we need
- $out = array();
- foreach ($_SERVER as $key => $value) {
- if (substr($key, 0, 5) == "HTTP_") {
- // this is chaos, basically it is just there to capitalize the first
- // letter of every word that is not an initial HTTP and strip HTTP
- // code from przemek
- $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
- $out[$key] = $value;
- }
- }
- return $out;
- }/*}}}*/
-}/*}}}*/
-
-class OAuthServer {/*{{{*/
- var $timestamp_threshold = 300; // in seconds, five minutes
- var $version = 1.0; // hi blaine
- var $signature_methods = array();
-
- var $data_store;
-
- function OAuthServer($data_store) {/*{{{*/
- $this->data_store = $data_store;
- }/*}}}*/
-
- function add_signature_method($signature_method) {/*{{{*/
- $this->signature_methods[$signature_method->get_name()] =
- $signature_method;
- }/*}}}*/
-
- // high level functions
-
- /**
- * process a request_token request
- * returns the request token on success
- */
- function fetch_request_token(&$request) {/*{{{*/
- $this->get_version($request);
-
- $consumer = $this->get_consumer($request);
-
- // no token required for the initial token request
- $token = NULL;
-
- $this->check_signature($request, $consumer, $token);
-
- $new_token = $this->data_store->new_request_token($consumer);
-
- return $new_token;
- }/*}}}*/
-
- /**
- * process an access_token request
- * returns the access token on success
- */
- function fetch_access_token(&$request) {/*{{{*/
- $this->get_version($request);
-
- $consumer = $this->get_consumer($request);
-
- // requires authorized request token
- $token = $this->get_token($request, $consumer, "request");
-
- $this->check_signature($request, $consumer, $token);
-
- $new_token = $this->data_store->new_access_token($token, $consumer);
-
- return $new_token;
- }/*}}}*/
-
- /**
- * verify an api call, checks all the parameters
- */
- function verify_request(&$request) {/*{{{*/
- $this->get_version($request);
- $consumer = $this->get_consumer($request);
- $token = $this->get_token($request, $consumer, "access");
- $this->check_signature($request, $consumer, $token);
- return array($consumer, $token);
- }/*}}}*/
-
- // Internals from here
- /**
- * version 1
- */
- function get_version(&$request) {/*{{{*/
- $version = $request->get_parameter("oauth_version");
- if (!$version) {
- $version = 1.0;
- }
- if ($version && $version != $this->version) {
- trigger_error("OAuth version '$version' not supported", E_USER_WARNING);
- return NULL;
- }
- return $version;
- }/*}}}*/
-
- /**
- * figure out the signature with some defaults
- */
- function get_signature_method(&$request) {/*{{{*/
- $signature_method =
- @$request->get_parameter("oauth_signature_method");
- if (!$signature_method) {
- $signature_method = "PLAINTEXT";
- }
- if (!in_array($signature_method,
- array_keys($this->signature_methods))) {
- trigger_error("Signature method '$signature_method' not supported try one of the following: " . implode(", ", array_keys($this->signature_methods)), E_USER_WARNING);
- return NULL;
- }
- return $this->signature_methods[$signature_method];
- }/*}}}*/
-
- /**
- * try to find the consumer for the provided request's consumer key
- */
- function get_consumer(&$request) {/*{{{*/
- $consumer_key = @$request->get_parameter("oauth_consumer_key");
- if (!$consumer_key) {
- trigger_error("Invalid consumer key", E_USER_WARNING);
- return NULL;
- }
-
- $consumer = $this->data_store->lookup_consumer($consumer_key);
- if (!$consumer) {
- trigger_error("Invalid consumer", E_USER_WARNING);
- return NULL;
- }
-
- return $consumer;
- }/*}}}*/
-
- /**
- * try to find the token for the provided request's token key
- */
- function get_token(&$request, $consumer, $token_type="access") {/*{{{*/
- $token_field = @$request->get_parameter('oauth_token');
- $token = $this->data_store->lookup_token(
- $consumer, $token_type, $token_field
- );
- if (!$token) {
- trigger_error("Invalid $token_type token: $token_field", E_USER_WARNING);
- return NULL;
- }
- return $token;
- }/*}}}*/
-
- /**
- * all-in-one function to check the signature on a request
- * should guess the signature method appropriately
- */
- function check_signature(&$request, $consumer, $token) {/*{{{*/
- // this should probably be in a different method
- $timestamp = @$request->get_parameter('oauth_timestamp');
- $nonce = @$request->get_parameter('oauth_nonce');
-
- $this->check_timestamp($timestamp);
- $this->check_nonce($consumer, $token, $nonce, $timestamp);
-
- $signature_method = $this->get_signature_method($request);
-
- $signature = $request->get_parameter('oauth_signature');
- $valid_sig = $signature_method->check_signature(
- $request,
- $consumer,
- $token,
- $signature
- );
-
- if (!$valid_sig) {
- trigger_error("Invalid signature", E_USER_WARNING);
- return NULL;
- }
- }/*}}}*/
-
- /**
- * check that the timestamp is new enough
- */
- function check_timestamp($timestamp) {/*{{{*/
- // verify that timestamp is recentish
- $now = time();
- if ($now - $timestamp > $this->timestamp_threshold) {
- trigger_error("Expired timestamp, yours $timestamp, ours $now", E_USER_WARNING);
- return NULL;
- }
- }/*}}}*/
-
- /**
- * check that the nonce is not repeated
- */
- function check_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
- // verify that the nonce is uniqueish
- $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
- if ($found) {
- trigger_error("Nonce already used: $nonce", E_USER_WARNING);
- return NULL;
- }
- }/*}}}*/
-
-
-
-}/*}}}*/
-
-class OAuthDataStore {/*{{{*/
- function lookup_consumer($consumer_key) {/*{{{*/
- // implement me
- }/*}}}*/
-
- function lookup_token($consumer, $token_type, $token) {/*{{{*/
- // implement me
- }/*}}}*/
-
- function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
- // implement me
- }/*}}}*/
-
- function fetch_request_token($consumer) {/*{{{*/
- // return a new token attached to this consumer
- }/*}}}*/
-
- function fetch_access_token($token, $consumer) {/*{{{*/
- // return a new access token attached to this consumer
- // for the user associated with this token if the request token
- // is authorized
- // should also invalidate the request token
- }/*}}}*/
-
-}/*}}}*/
-
-
-/* A very naive dbm-based oauth storage
- */
-class SimpleOAuthDataStore extends OAuthDataStore {/*{{{*/
- var $dbh;
-
- function SimpleOAuthDataStore($path = "oauth.gdbm") {/*{{{*/
- $this->dbh = dba_popen($path, 'c', 'gdbm');
- }/*}}}*/
-
- function __destruct() {/*{{{*/
- dba_close($this->dbh);
- }/*}}}*/
-
- function lookup_consumer($consumer_key) {/*{{{*/
- $rv = dba_fetch("consumer_$consumer_key", $this->dbh);
- if ($rv === FALSE) {
- return NULL;
- }
- $obj = unserialize($rv);
- if (!is_a($obj, "OAuthConsumer")) {
- return NULL;
- }
- return $obj;
- }/*}}}*/
-
- function lookup_token($consumer, $token_type, $token) {/*{{{*/
- $rv = dba_fetch("${token_type}_${token}", $this->dbh);
- if ($rv === FALSE) {
- return NULL;
- }
- $obj = unserialize($rv);
- if (!is_a($obj, "OAuthToken")) {
- return NULL;
- }
- return $obj;
- }/*}}}*/
-
- function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
- if (dba_exists("nonce_$nonce", $this->dbh)) {
- return TRUE;
- } else {
- dba_insert("nonce_$nonce", "1", $this->dbh);
- return FALSE;
- }
- }/*}}}*/
-
- function new_token($consumer, $type="request") {/*{{{*/
- $key = md5(time());
- $secret = time() + time();
- $token = new OAuthToken($key, md5(md5($secret)));
- if (!dba_insert("${type}_$key", serialize($token), $this->dbh)) {
- trigger_error("doooom!", E_USER_WARNING);
- return NULL;
- }
- return $token;
- }/*}}}*/
-
- function new_request_token($consumer) {/*{{{*/
- return $this->new_token($consumer, "request");
- }/*}}}*/
-
- function new_access_token($token, $consumer) {/*{{{*/
-
- $token = $this->new_token($consumer, 'access');
- dba_delete("request_" . $token->key, $this->dbh);
- return $token;
- }/*}}}*/
-}/*}}}*/
-
-class OAuthUtil {/*{{{*/
- function urlencodeRFC3986($string) {/*{{{*/
- return str_replace('%7E', '~', rawurlencode($string));
- }/*}}}*/
-
- function urldecodeRFC3986($string) {/*{{{*/
- return rawurldecode($string);
- }/*}}}*/
-}/*}}}*/
-
-/**
- * Crib'd native implementation of hash_hmac() for SHA1 from the
- * Fire Eagle PHP code:
- *
- * http://fireeagle.yahoo.net/developer/code/php
- */
-if (!function_exists("hash_hmac")) {
- // Earlier versions of PHP5 are missing hash_hmac(). Here's a
- // pure-PHP version in case you're using one of them.
- function hash_hmac($algo, $data, $key) {
- // Thanks, Kellan: http://laughingmeme.org/code/hmacsha1.php.txt
- if ($algo != 'sha1') {
- error_log("Internal hash_hmac() can only do sha1, sorry");
- return NULL;
- }
-
- $blocksize = 64;
- $hashfunc = 'sha1';
- if (strlen($key)>$blocksize)
- $key = pack('H*', $hashfunc($key));
- $key = str_pad($key,$blocksize,chr(0x00));
- $ipad = str_repeat(chr(0x36),$blocksize);
- $opad = str_repeat(chr(0x5c),$blocksize);
- $hmac = pack(
- 'H*',$hashfunc(
- ($key^$opad).pack(
- 'H*',$hashfunc(
- ($key^$ipad).$data
- )
- )
- )
- );
- return $hmac;
- }
-}
-
-?>
View
1,517 php_sdk/.svn/text-base/Yahoo.inc.svn-base
@@ -1,1517 +0,0 @@
-<?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.
-if(!class_exists("OAuthConsumer")) {
- 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");
-
-define("SOCIAL_WS_HOSTNAME", "social.yahooapis.com");
-define("PRESENCE_WS_HOSTNAME", "social.yahooapis.com");
-define("UPDATES_WS_HOSTNAME", "social.yahooapis.com");
-define("QUERY_WS_HOSTNAME", "query.yahooapis.com");
-define("OAUTH_HOSTNAME", "api.login.yahoo.com");
-define("YAP_WS_HOSTNAME", "appstore.apps.yahooapis.com");
-
-$GLOBAL_YAHOO_SESSION = NULL;
-
-$GLOBAL_YAHOO_LOGGER_DEBUG = false;
-$GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION = "LOG";
-
-/**
- * Logging wrapper for the Yahoo objects.
- *
- * @brief Logging wrapper for the Yahoo objects.
- */
-class YahooLogger {
- /**
- * 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");
- if(!is_null($object)) {
- print("DEBUG OBJECT - " . print_r($object, true) . "\n");
- }
- }
- else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "LOG") {
- error_log("DEBUG - $message");
- if(!is_null($object)) {
- error_log("DEBUG OBJECT - " . print_r($object, true));
- }
- }
- }
- }
-
- /**
- * 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");
- if(!is_null($object)) {
- print("INFO OBJECT - " . print_r($object, true) . "\n");
- }
- }
- else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "LOG") {
- error_log("INFO - $message");
- if(!is_null($object)) {
- error_log("INFO OBJECT - " . print_r($object, true));
- }
- }
- }
-
- /**
- * 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");
- if(!is_null($object)) {
- print("ERROR OBJECT - " . print_r($object, true) . "\n");
- }
- }
- else if($GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION == "LOG") {
- error_log("ERROR - $message");
- if(!is_null($object)) {
- error_log("ERROR OBJECT - " . print_r($object, true));
- }
- }
- }
-
- /**
- * Enables/disables session debugging.
- *
- * @param $debug Boolean to enable/disable debugging.
- */
- function setDebug($debug) {
- 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 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" ||
- $destination == "NULL") {
- $GLOBAL_YAHOO_LOGGER_DEBUG_DESTINATION = $destination;
- return true;
- }
- else {
- return false;
- }
- }
-}
-
-/**
- * Represents a Yahoo! application.
- *
- * @brief Represents a Yahoo! application.
- */
-class YahooApplication {
- /**
- * @private
- */
- var $consumer = NULL;
-
- /**
- * @private
- */
- var $client = NULL;
-
- /**
- * Constructs a new YahooApplication object.
- *
- * @param $consumerKey The consumer key of the application.
- * @param $consumerKeySecret The consumer key secret of the application.
- */
- function YahooApplication($consumerKey, $consumerKeySecret) {
- $this->consumer = new OAuthConsumer($consumerKey, $consumerKeySecret);
- $this->client = new OAuthClient($this->consumer);
- }
-
- /**
- * 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.
- */
- function setSmallView($guid, $content) {
- $url = sprintf("http://%s/v1/cache/view/small/%s", YAP_WS_HOSTNAME,
- urlencode($guid));
- $response = $this->client->put($url, "text/html;charset=utf-8",
- $content);
-
- return !is_null($response) && ($response["code"] == 200);
- }
-
- /**
- * Executes the given YQL query.
- *
- * @param $yql The query to execute.
- * @return The response or NULL if the request fails..
- */
- function query($yql) {
- $response = $this->client->get(
- sprintf("http://%s/v1/yql",
- QUERY_WS_HOSTNAME),
- array('q' => $yql, 'format' => 'json'), 30);
-
- if(is_null($response) || $response["code"] != 200) {
- return NULL;
- }
-
- $resultSet = json_decode($response["responseBody"]);
-
- return $resultSet;
- }
-}
-
-/**
- * Defines a session between an application and the Yahoo! platform.
- *
- * @brief Defines a session between an application and the Yahoo! platform.
- */
-class YahooSession {
- /**
- * @private
- */
- var $guid = NULL;
-
- /**
- * @private
- */
- var $consumer = NULL;
-
- /**
- * @private
- */
- var $accessToken = NULL;
-
- /**
- * @private
- */
- var $applicationId = NULL;
-
- /**
- * @private
- */
- var $client = NULL;
-
- /**
- * @private
- */
- var $application = NULL;
-
- /**
- * @private
- */
- function YahooSession($consumer, $accessToken, $applicationId) {
- $this->consumer = $consumer;
- $this->accessToken = $accessToken;
- $this->applicationId = $applicationId;
- $this->guid = $accessToken->guid;
-
- $this->client = new OAuthClient($consumer, $accessToken);
- $this->application = new YahooApplication($consumer->key,
- $consumer->secret);
- }
-
- /**
- * @private
- */
- function getConsumer() {
- return $this->consumer;
- }
-
- /**
- * @private
- */
- function getAccessToken() {
- return $this->accessToken;
- }
-
- /**
- * @private
- */
- function getApplicationId() {
- return $this->applicationId;
- }
-
- /**
- * Gets the currently sessioned user.
- *
- * @return YahooUser The currently sessioned YahooUser.
- */
- function getSessionedUser() {
- return new YahooUser($this, $this->guid, true);
- }
-
- /**
- * Gets the user who owns the application install.
- * Only valid when viewed in YAP, otherwise will default
- * to the logged-in user.
- *
- * @return YahooUser The currently sessioned YahooUser.
- */
- function getOwner() {
- if(isset($this->accessToken->owner)) {
- return $this->getUser($this->accessToken->owner);
- }
- else {
- return $this->getSessionedUser();
- }
- }
-
- /**
- * 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.
- */
- function getUser($guid) {
- return new YahooUser($this, $guid, isset($this->guid) && ($guid == $this->guid));
- }
-
- /**
- * @private
- */
- function redirectForAuthorization($consumerKey, $consumerSecret,
- $callback = NULL, $sessionStore = NULL) {
- global $GLOBAL_YAHOO_SESSION;
-
- // Redirect the user to log in.
- $requestToken = YahooAuthentication::createRequestToken(
- $consumerKey, $consumerSecret);
- if(!is_null($requestToken)) {
- $sessionStore->storeRequestToken($requestToken);
-
- if(is_null($callback)) {
- // No callback URL supplied. Build one from the current
- // URL.
- $callback = sprintf("http://%s%s",
- $_SERVER["HTTP_HOST"],
- $_SERVER["REQUEST_URI"]);
- }
-
- $authorizationUrl = YahooAuthentication::createAuthorizationUrl(
- $requestToken, $callback);
-
- header("Location: $authorizationUrl");
- exit();
- }
- else {
- YahooLogger::error("Failed to create request token");
- $GLOBAL_YAHOO_SESSION = NULL;
- }
- }
-
- /**
- * 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.
- */
- function clearSession($sessionStore = NULL) {
- global $GLOBAL_YAHOO_SESSION;
-
- if(is_null($sessionStore)) {
- $sessionStore = new CookieSessionStore();
- }
- $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 CookieSessionStore and use that.
- * @return boolean True if a session is present, false otherwise.
- */
- function hasSession($consumerKey, $consumerSecret, $applicationId = NULL,
- $sessionStore = NULL) {
- if(is_null($sessionStore)) {
- $sessionStore = new CookieSessionStore();
- }
- $session = YahooSession::initSession($consumerKey, $consumerSecret,
- $applicationId, FALSE, NULL, $sessionStore);
- 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
- * 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 CookieSessionStore and use that.
- * @return YahooSession The current session or NULL if a session cannot
- * be established.
- */
- function requireSession($consumerKey, $consumerSecret,
- $applicationId = NULL, $callback = NULL, $sessionStore = NULL) {
- if(is_null($sessionStore)) {
- $sessionStore = new CookieSessionStore();
- }
- return YahooSession::initSession($consumerKey, $consumerSecret,
- $applicationId, TRUE, $callback, $sessionStore);
- }
-
- /**
- * @private
- */
- function initSession($consumerKey, $consumerSecret, $applicationId,
- $redirect, $callback, $sessionStore) {
- global $GLOBAL_YAHOO_SESSION;
- if(!is_null($GLOBAL_YAHOO_SESSION)) {
- return $GLOBAL_YAHOO_SESSION;
- }
-
- $consumer = new stdclass();
- $consumer->key = $consumerKey;
- $consumer->secret = $consumerSecret;
-
- $checkSession = YahooSession::checkSession($type, $sessionStore);
- if(!$checkSession) {
- // There doesn't appear to be a session here.
- if($redirect) {
- $GLOBAL_YAHOO_SESSION = NULL;
- YahooSession::redirectForAuthorization($consumerKey, $consumerSecret, $callback, $sessionStore);
- }
- else {
- // Don't redirect the user, just inform the caller that
- // no session is present.
- $GLOBAL_YAHOO_SESSION = NULL;
- }
- }
- else if($type == YAHOO_YAP_SESSION_TYPE) {
- // Found a YAP session.
- if ($consumer->key != $_POST["yap_consumer_key"]) {
- error_log("Consumer key from YAP does not match config.");
- $GLOBAL_YAHOO_SESSION = NULL;
- return;
- }
-
- if (!YahooSession::checkSignature($consumer, $_REQUEST['oauth_signature'])) {
- error_log("Signature from YAP failed.");
- $GLOBAL_YAHOO_SESSION = NULL;
- return;
- }
-
- $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);
- }
- else if($type == YAHOO_OAUTH_AT_SESSION_TYPE) {
- // Found an OAuth Access Token session.
- $accessToken = $sessionStore->fetchAccessToken();
- $now = time();
- 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.");
- 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
- // it may have expired already. Try to get a new one.
- YahooSession::accessTokenExpired(
- $accessToken, $consumer, $applicationId, $sessionStore);
- }
- else {
- // The access token is still good for a little while,
- // continue using it.
- $GLOBAL_YAHOO_SESSION = new YahooSession(
- $consumer, $accessToken, $applicationId);
- }
- }
- else if($type == YAHOO_OAUTH_RT_SESSION_TYPE) {
- // Found an OAuth Request Token session.
- $requestToken = $sessionStore->fetchRequestToken();
-
- $accessToken = YahooAuthentication::fetchAccessToken(
- $consumerKey, $consumerSecret, $requestToken);
- if(!is_null($accessToken)) {
- $sessionStore->storeAccessToken($accessToken);
- $sessionStore->clearRequestToken();
-
- $GLOBAL_YAHOO_SESSION = new YahooSession(
- $consumer, $accessToken, $applicationId);
- }
- 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
- // request token and try again.
- $GLOBAL_YAHOO_SESSION = NULL;
- YahooSession::redirectForAuthorization($consumerKey,
- $consumerSecret, $callback, $sessionStore);
- }
- else {
- // Don't redirect the user, just inform the caller that
- // no session is present.
- $sessionStore->clearRequestToken();
- $GLOBAL_YAHOO_SESSION = NULL;
- }
- }
- else {
- trigger_error("Unknown session type found", E_USER_ERROR);
- $GLOBAL_YAHOO_SESSION = NULL;
- }
-
- return $GLOBAL_YAHOO_SESSION;
- }
-
- /**
- * Executes the given YQL query.
- *
- * @param $yql The query to execute.
- * @return The response or NULL if the request fails..
- */
- function query($yql) {
- $response = $this->client->get(
- sprintf("http://%s/v1/yql",
- QUERY_WS_HOSTNAME),
- array('q' => $yql, 'format' => 'json'), 30);
-
- if(is_null($response) || $response["code"] != 200) {
- return NULL;
- }
-
- $resultSet = json_decode($response["responseBody"]);
-
- return $resultSet;
- }
-
- /**
- * @private
- */
- function checkSignature($consumer, $oauth_signature) {
- $oauth_sign_method = new OAuthSignatureMethod_HMAC_SHA1();
- $oauth_consumer = new OAuthConsumer($consumer->key, $consumer->secret);
- $oauth_token = null; // since this is a 2-legged signing only, no token is needed
- $oauth_request = OAuthRequest::from_request();
- $ok = $oauth_sign_method->check_signature($oauth_request, $oauth_consumer, $oauth_token, $oauth_signature);
-
- return $ok;
- }
-
- /**
- * @private
- */
- 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
- // or it hasn't expired yet. Get a new access token.
- $newAccessToken = YahooAuthentication::fetchAccessToken(
- $consumer->key, $consumer->secret, $accessToken);
- if(is_null($newAccessToken)) {
- YahooLogger::error("Failed to fetch access token");
- $GLOBAL_YAHOO_SESSION = NULL;
- }
-
- $sessionStore->storeAccessToken($newAccessToken);
-
- YahooLogger::debug("Got new AT/ATS from ASH!");
- YahooLogger::debug("OAuth AT: " . $newAccessToken->key . " ATS: ". $newAccessToken->secret);
-
- $GLOBAL_YAHOO_SESSION = new YahooSession(
- $consumer, $newAccessToken, $applicationId);
- }
- 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
- // to authorization point or return a NULL session.
- $sessionStore->clearAccessToken();
- if ($redirect) {
- YahooSession::redirectForAuthorization($consumer->key, $consumer->secret, $callback, $sessionStore);
- }
- else {
- $GLOBAL_YAHOO_SESSION = NULL;
- }
- }
- }
-
- /**
- * @private
- *
- * 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.
- */
- function checkSession(&$sessionType, $sessionStore) {
- if(array_key_exists("yap_appid", $_POST)) {
- $sessionType = YAHOO_YAP_SESSION_TYPE;
- return true;
- }
- else if($sessionStore->hasAccessToken()) {
- $sessionType = YAHOO_OAUTH_AT_SESSION_TYPE;
- return true;
- }
- else if($sessionStore->hasRequestToken()) {
- $sessionType = YAHOO_OAUTH_RT_SESSION_TYPE;
- return true;
- }
- else {
- return false;
- }
- }
-}
-
-/**
- * Represents a Yahoo! user.
- *
- * @brief Represents a Yahoo! user.
- */
-class YahooUser {
- /**
- * @private
- */
- var $session = NULL;
-
- /**
- * @private
- */
- var $guid = NULL;
-
- /**
- * @private
- */
- var $sessioned = false;
-
- /**
- * @private
- */
- var $client = NULL;
-
- /**
- * @private
- */
- function YahooUser($session, $guid, $sessioned) {
- $this->session = $session;
- $this->client = $session->client;
- $this->guid = $guid;
- $this->sessioned = $sessioned;
- }
-
- /**
- * Gets the presence of the user, including the status.
- *
- * @return The presence of the user or NULL if the fetch fails.
- */
- function getPresence() {
- $response = $this->client->get(
- sprintf("http://%s/v1/user/%s/presence/presence",
- PRESENCE_WS_HOSTNAME,
- urlencode($this->guid)));
-
- if(is_null($response)) {
- return NULL;
- }
- else if($response["code"] == 404) {
- // No presence is set, return an empty presence.
- $presence = new stdclass();
- $presence->value = new stdclass();
- $presence->value->status = "";
- return $presence;
- }
- else if($response["code"] != 200) {
- return NULL;
- }
- else {
- $presence = json_decode($response["responseBody"]);
- 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.
- */
- function setPresence($status) {
- if(!$this->sessioned) {
- YahooLogger::error("Can't set the presence of an unsessioned user");
- return NULL;
- }
-
- $presence = array("status" => $status);
- $response = $this->client->put(
- sprintf("http://%s/v1/user/%s/presence/presence",
- PRESENCE_WS_HOSTNAME, $this->guid), "application/json",
- json_encode($presence));
- if(is_null($response) || $response["code"] != 200) {
- return NULL;
- }
- $presence = json_decode($response["responseBody"]);
- return $presence;
- }
-
- /**
- * Lists the updates for 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 current user.
- */
- function listUpdates($start = 0, $count = 10) {
- $response = $this->client->get(
- sprintf("http://%s/v1/user/%s/updates",
- UPDATES_WS_HOSTNAME, urlencode($this->guid)),
- array("start" => $start, "count" => $count,
- "transform" => '(sort "pubDate" numeric descending (all))'));
- if(is_null($response) || $response["code"] != 200) {
- return NULL;
- }
-
- $updates = json_decode($response["responseBody"]);
- return $updates->updates;
- }
-
- /**
- * Lists 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.
- */
- function listConnectionUpdates($start = 0, $count = 10) {
- $response = $this->client->get(
- sprintf("http://%s/v1/user/%s/updates/connections",
- UPDATES_WS_HOSTNAME, urlencode($this->guid)),
- array("start" => $start, "count" => $count,
- "transform" => '(sort "pubDate" numeric descending (all))'));
- if(is_null($response) || $response["code"] != 200) {
- return NULL;
- }
-
- $updates = json_decode($response["responseBody"]);
- 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,
- * optional.
- * @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.
- if(!$this->sessioned) {
- YahooLogger::error("Can't insert updates for an unsessioned user");
- return NULL;
- }
-
- if (is_null($date)) {
- $date = time();
- }
-
- // Make sure an application ID was given.
- $applicationId = $this->session->getApplicationId();
- if(empty($applicationId)) {
- YahooLogger::error("No application ID given, can't insert update");
- return NULL;
- }
-
- $source = sprintf("APP.%s", $applicationId);
- $body = array("updates" => array(array(
- "collectionID" => $this->guid,
- "collectionType" => "guid",
- "class" => "app",
- "source" => $source,
- "type" => 'appActivity',
- "suid" => $suid,
- "title" => $title,
- "description" => $description,
- "link" => $link,
- "pubDate" => (string)$date)));
-
- $response = $this->client->put(
- sprintf("http://%s/v1/user/%s/updates/%s/%s",
- UPDATES_WS_HOSTNAME, $this->guid, $source, urlencode($suid)),
- "application/json",
- json_encode($body));
-
- if(is_null($response) || $response["code"] != 200) {
- return NULL;
- }
-
- return TRUE;
- }
-
- /**
- * 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.
- */
- function deleteUpdate($suid) {
- // Make sure this YahooUser is sessioned.
- if(!$this->sessioned) {
- YahooLogger::error("Can't delete updates for an unsessioned user");
- return FALSE;
- }
-
- // Make sure an application ID was given.
- $applicationId = $this->session->getApplicationId();
- if(empty($applicationId)) {
- YahooLogger::error("No application ID given, can't delete update");
- return FALSE;
- }
-
- $source = sprintf("APP.%s", $applicationId);
-
- $response = $this->client->delete(
- sprintf("http://%s/v1/user/%s/updates/%s/%s",
- UPDATES_WS_HOSTNAME, $this->guid, $source, urlencode($suid)));
-
- if(is_null($response) || $response["code"] != 200) {
- YahooLogger::error("Failed to delete update $suid, HTTP response code $responseCode");
- return FALSE;
- }
-
- return TRUE;
- }
-
- /**
- * Loads the extended profile of the current user.
- *
- * @return The extended profile of the current user.
- */
- function loadProfile() {
- $response = $this->client->get(
- sprintf("http://%s/v1/user/%s/profile",
- SOCIAL_WS_HOSTNAME,
- urlencode($this->guid)));
- if(is_null($response) || $response["code"] != 200) {
- return NULL;
- }
-
- $profile = json_decode($response["responseBody"]);
- 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.
- */
- function getConnections(&$start, &$count, &$total) {
- $response = $this->client->get(
- sprintf("http://%s/v1/user/%s/connections",
- SOCIAL_WS_HOSTNAME,
- urlencode($this->guid)),
- array("view" => "usercard", "start" => $start,
- "count" => $count));
- if(is_null($response) || $response["code"] != 200) {
- return NULL;
- }
-
- $connections = json_decode($response["responseBody"]);
-
- $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.
- */
- function getContacts($start = 0, $count = 10) {
- if(!$this->sessioned) {
- YahooLogger::error("Can't get contacts for an unsessioned user");
- return NULL;
- }
-
- $response = $this->client->get(
- sprintf("http://%s/v1/user/%s/contacts",
- SOCIAL_WS_HOSTNAME,
- urlencode($this->guid)), array("view" => "tinyusercard", "start" => $start, "count" => $count));
- if(is_null($response) || $response["code"] != 200) {
- return NULL;
- }
-
- $contacts = json_decode($response["responseBody"]);
-
- return $contacts;
- }
-
- /**
- * Sets the small view for the current user.
- *
- * @param $content The content to set the small view to.
- * @return True on success, false otherwise.
- */
- function setSmallView($content) {
- return $this->session->application->setSmallView($this->guid, $content);
- }
-}
-
-/**
- * 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.
- *
- * @brief Cookie-based implementation of the session store.
- */
-class CookieSessionStore {
- /**
- * 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", $_COOKIE) &&
- (strlen($_COOKIE["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", $_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
- * 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)),
- time() + 600);
- }
- else {
- return false;
- }
- }
-
- /**
- * Fetches and returns the request token from the session store.
- *
- * @return The request token.
- */
- function fetchRequestToken() {
- return json_decode(base64_decode($_COOKIE["yosdk_rt"]));
- }
-
- /**
- * Clears the request token from the session store.
- *
- * @return True on success, false otherwise.
- */
- function clearRequestToken() {
- if(!headers_sent()) {
- return setcookie("yosdk_rt", "", time() - 600);
- }
- else {
- return false;
- }
- }
-
- /**
- * 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.
- */
- function storeAccessToken($token) {
- if(!headers_sent()) {
- return setcookie("yosdk_at", base64_encode(json_encode($token)),
- time() + (30 * 24 * 60 * 60));
- }
- else {
- return false;
- }
- }
-
- /**
- * Fetches and returns the access token from the session store.
- *
- * @return The access token.
- */
- function fetchAccessToken() {
- return json_decode(base64_decode($_COOKIE["yosdk_at"]));
- }
-
- /**
- * Clears the access token from the session store.
- *
- * @return True on success, false otherwise.
- */
- function clearAccessToken() {
- if(!headers_sent()) {
- return setcookie("yosdk_at", "", time() - 600);
- }
- else {
- return false;
- }
- }
-}
-
-/**
- * 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 {
- /**
- * @private
- */
- var $consumer = NULL;
-
- /**
- * @private
- */
- var $token = NULL;
-
- /**
- * @private
- */
- var $defaultTimeout = 3;
-
- /**
- * @private
- */
- var $oauthParamsLocation = NULL;
-
- /**
- * @private
- */
- var $signatureMethod = NULL;
-
- 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,
- $oauthParamsLocation = OAUTH_PARAMS_IN_HEADERS,
- $signatureMethod = OAUTH_SIGNATURE_HMAC_SHA1) {
- $this->consumer = $consumer;
- $this->token = $token;
- $this->oauthParamsLocation = $oauthParamsLocation;
-
- if($signatureMethod == OAUTH_SIGNATURE_HMAC_SHA1) {
- $this->signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
- }
- else if($signatureMethod == OAUTH_SIGNATURE_PLAINTEXT) {
- $this->signatureMethod = new OAuthSignatureMethod_PLAINTEXT();
- }
- else {
- YahooLogger::error("Invalid signature method: $signatureMethod");
- }
- }
-
- /**
- * 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");
- return NULL;
- }
-
- return $this->request(array(
- "method" => "GET",
- "url" => $url,
- "query" => $queryParameters,
- "timeout" => $timeout));
- }
-
- /**
- * 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");
- return NULL;
- }
-
- return $this->request(array(
- "method" => "DELETE",
- "url" => $url,
- "query" => $queryParameters,
- "timeout" => $timeout));
- }
-
- /**
- * 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) {
- return $this->request(array(
- "method" => "PUT",
- "url" => $url,
- "content" => $content,
- "contentType" => $contentType,
- "timeout" => $timeout));
- }
-
- /**
- * 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) {
- return $this->request(array(
- "method" => "POST",
- "url" => $url,
- "content" => $content,
- "contentType" => $contentType,
- "timeout" => $timeout));
- }
-
- /**
- * @private
- */
- function request($request) {
- if(!array_key_exists("content", $request)) {
- $request["content"] = array();
- }
- if(!array_key_exists("query", $request)) {
- $request["query"] = array();
- }
-
- if(is_array($request["content"])) {
- $combinedParams = array_merge(
- $request["query"], $request["content"]);
- }
- else {
- $combinedParams = $request["query"];
- }
-
- $oauthRequest = OAuthRequest::from_consumer_and_token(
- $this->consumer, $this->token, $request["method"],
- $request["url"], $combinedParams);
- $oauthRequest->sign_request($this->signatureMethod, $this->consumer,
- $this->token);
-
- $headers = array("Accept: " . $this->accepts);
- if($this->oauthParamsLocation == OAUTH_PARAMS_IN_HEADERS) {
- $headers[] = $oauthRequest->to_header();
- }
- if(!empty($request["content"]) || $this->oauthParamsLocation == OAUTH_PARAMS_IN_POST_BODY) {
- $headers[] = "Content-Type: " . $request["contentType"];
- }
-
- if(!empty($request["query"])) {
- $requestUrl = sprintf("%s?%s", $request["url"],
- oauth_http_build_query($request["query"]));
- }
- else {
- $requestUrl = $request["url"];
- }
-
- $requestTimeout = array_key_exists("timeout", $request) ?
- $request["timeout"] : $this->defaultTimeout;
-
- $ch = curl_init($requestUrl);
- curl_setopt($ch, CURLOPT_TIMEOUT, $requestTimeout);
- 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) ||
- (!empty($request["content"]) && is_array($request["content"]))) {
- // Content is an array, URL encode it.
- if($this->oauthParamsLocation == OAUTH_PARAMS_IN_POST_BODY) {
- $request["content"] = $oauthRequest->to_postdata();
- curl_setopt($ch, CURLOPT_POSTFIELDS, $request["content"]);
- }
- else {
- curl_setopt($ch, CURLOPT_POSTFIELDS,
- oauth_http_build_query($request["content"]));
- }
- }
- else if(!empty($request["content"])) {
- // Content is raw.
- curl_setopt($ch, CURLOPT_POSTFIELDS, $request["content"]);
- }
-
- // 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
- // the version of PHP being used.
- $sdkVersion = "1.1";
- $agent = sprintf("YosPhpSdk/%s php/%s", $sdkVersion, phpversion());
- curl_setopt($ch, CURLOPT_USERAGENT, $agent);
-
- $headerParser = new YahooHeaderParser();
- curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$headerParser, "read"));
- $response = curl_exec($ch);
- if(is_bool($response) && !$response) {
- YahooLogger::error("Error making libcurl request(" .
- $requestUrl . "): " . curl_error($ch));
- return NULL;
- }
-
- $response = array(
- 'method' => $request["method"],
- 'url' => $requestUrl,
- 'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
- 'requestHeaders' => $headers,
- 'requestBody' => !empty($request["content"]) ? $request["content"] : NULL,
- 'responseHeaders' => $headerParser->headers,
- 'responseBody' => $response
- );
- if($response["code"] != 200) {
- YahooLogger::error("HTTP request failed", $response);
-
- $this->checkExpired($response["code"], $headerParser);
- return NULL;
- }
- YahooLogger::debug("HTTP request details", $response);
-
- return $response;
- }
-
- /**
- * Checks to see if the code and headers indicate an expired OAuth token.
- * If so, requests a new one.
- *
- * @private
- */
- function checkExpired($code, $headerParser) {
- 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') {
- YahooLogger::error('Access token expired. Please fetch a new one');
- }
- 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.');
- }
- }
-}
-
-/**
- * @private
- */
-class YahooHeaderParser {
- var $headers = array();
-
- function YahooHeaderParser() {
- }
-
- function read($ch, $header) {
- $pos = strpos($header, ":");
- if($pos !== FALSE) {
- $name = substr($header, 0, $pos);
- $value = trim(substr($header, $pos + 1));
- $this->headers[$name] = $value;
- }
- return strlen($header);
- }
-
- function get($name) {
- if(array_key_exists($name, $this->headers)) {
- return $this->headers[$name];
- }
- else {
- return NULL;
- }
- }
-}
-
-/**
- * @private
- */
-class YahooAuthentication {
- function createRequestToken($consumerKey, $consumerSecret) {
- $consumer = new OAuthConsumer($consumerKey, $consumerSecret);
- $client = new OAuthClient($consumer, NULL, OAUTH_PARAMS_IN_POST_BODY,
- OAUTH_SIGNATURE_PLAINTEXT);
-
- $baseUrl = sprintf("https://%s/oauth/v2/get_request_token",
- OAUTH_HOSTNAME);
- $response = $client->post($baseUrl);
-
- if(is_null($response)) {
- YahooLogger::error("OAuth call to get request token failed");
- return NULL;
- }
-
- parse_str($response["responseBody"], $token);
-
- if($response["code"] != 200) {
- $problem = array_key_exists("oauth_problem", $token) ?
- $token["oauth_problem"] : "unknown problem";
- YahooLogger::error("Failed to create request token: $problem");
- return NULL;
- }
-
- $requestToken = new stdclass();
- $requestToken->key = $token["oauth_token"];
- $requestToken->secret = $token["oauth_token_secret"];
- return $requestToken;
- }
-
- function createAuthorizationUrl($requestToken, $callbackUrl = NULL) {
- if(!is_object($requestToken) || !property_exists($requestToken, "key")) {
- YahooLogger::error("Request token doesn't have a 'key' property");
- return NULL;
- }
-
- if(!empty($callbackUrl)) {
- return sprintf("https://%s/oauth/v2/request_auth?oauth_token=%s&oauth_callback=%s",
- OAUTH_HOSTNAME, urlencode($requestToken->key), urlencode($callbackUrl));
- }
- else {
- return sprintf("https://%s/oauth/v2/request_auth?oauth_token=%s",
- OAUTH_HOSTNAME, urlencode($requestToken->key));
- }
- }
-
- function fetchAccessToken($consumerKey, $consumerSecret, $requestToken) {
- $at = YahooAuthentication::_fetchAccessToken($consumerKey,
- $consumerSecret, $requestToken);
-
- if(is_null($at)) {
- // 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);
- $at = YahooAuthentication::_fetchAccessToken($consumerKey,
- $consumerSecret, $requestToken);
- }
-
- return $at;
- }
-
- function _fetchAccessToken($consumerKey, $consumerSecret, $requestToken) {
- $baseUrl = sprintf("https://%s/oauth/v2/get_token", OAUTH_HOSTNAME);
- $consumer = new OAuthConsumer($consumerKey, $consumerSecret);
-
- $parameters = array();
- if(property_exists($requestToken, "sessionHandle")) {
- $parameters["oauth_session_handle"] = $requestToken->sessionHandle;
- }
-
- $client = new OAuthClient($consumer, $requestToken,
- OAUTH_PARAMS_IN_POST_BODY);
- $response = $client->post($baseUrl, "application/x-www-form-urlencoded",
- $parameters);
-
- if(is_null($response)) {
- YahooLogger::error("OAuth call to get access token failed");
- return NULL;
- }
-
- parse_str($response["responseBody"], $token);
-
- if($response["code"] != 200) {
- YahooLogger::error("Failed to fetch access token: " . $token["oauth_problem"]);
- return NULL;
- }
-
- $now = time();
-
- $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"]);
- if(array_key_exists("oauth_expires_in", $token)) {
- $accessToken->tokenExpires = $now + $token["oauth_expires_in"];
- }
- else {
- $accessToken->tokenExpires = -1;
- }
-
- // Check to see if the access session handle ever expires.
- if(array_key_exists("oauth_authorization_expires_in", $token)) {
- $accessToken->handleExpires = $now +
- $token["oauth_authorization_expires_in"];
- }
- else {
- $accessToken->handleExpires = -1;
- }
- return $accessToken;
- }
-}
-
-// 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
- // version of that source code.
- if(!class_exists("Services_JSON")) {
- include_once("JSON.php");
- }
-
- function json_decode($json) {
- $js = new Services_JSON();
- return $js->decode($json);
- }
-
- function json_encode($value) {
- $js = new Services_JSON();
- return $js->encode($value);
- }
-}
-
-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 );
- }
-}
-
-/**
- * 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) {
- $strings = array();
- foreach($parameters as $name => $value) {
- $strings[] = sprintf("%s=%s", rawurlencode($name), rawurlencode($value));
- }
- $query = implode("&", $strings);
- return $query;
-}
-
-?>
View
819 php_sdk/OAuth.php
@@ -1,819 +0,0 @@
-<?php
-/**
- * The MIT License
- *
- * Copyright (c) 2008 OAuth.net
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- */
-
-/**
- * Branched from version 587 of OAuth.php from the OAuth.net project. Major
- * changes are limited to adding PHP 4 compatibility.
- *
- * Ryan Kennedy (rckenned@yahoo-inc.com)
- */
-
-class OAuthConsumer {/*{{{*/
- var $key;
- var $secret;
-
- function OAuthConsumer($key, $secret, $callback_url=NULL) {/*{{{*/
- $this->key = $key;
- $this->secret = $secret;
- $this->callback_url = $callback_url;
- }/*}}}*/
-}/*}}}*/
-
-class OAuthToken {/*{{{*/
- // access tokens and request tokens
- var $key;
- var $secret;
-
- /**
- * key = the token
- * secret = the token secret
- */
- function OAuthToken($key, $secret) {/*{{{*/
- $this->key = $key;
- $this->secret = $secret;
- }/*}}}*/
-
- /**
- * generates the basic string serialization of a token that a server
- * would respond to request_token and access_token calls with
- */
- function to_string() {/*{{{*/
- return "oauth_token=" . OAuthUtil::urlencodeRFC3986($this->key) .
- "&oauth_token_secret=" . OAuthUtil::urlencodeRFC3986($this->secret);
- }/*}}}*/
-
- function __toString() {/*{{{*/
- return $this->to_string();
- }/*}}}*/
-}/*}}}*/
-
-class OAuthSignatureMethod {/*{{{*/
- function check_signature(&$request, $consumer, $token, $signature) {
- $built = $this->build_signature($request, $consumer, $token);
- return $built == $signature;
- }
-}/*}}}*/
-
-class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {/*{{{*/
- function get_name() {/*{{{*/
- return "HMAC-SHA1";
- }/*}}}*/
-
- function build_signature($request, $consumer, $token) {/*{{{*/
- $base_string = $request->get_signature_base_string();
- $request->base_string = $base_string;
-
- $key_parts = array(
- $consumer->secret,
- ($token) ? $token->secret : ""
- );
-
- $key_parts = array_map(array('OAuthUtil','urlencodeRFC3986'), $key_parts);
- $key = implode('&', $key_parts);
-
- return base64_encode(hash_hmac('sha1', $base_string, $key, true));
- }/*}}}*/
-}/*}}}*/
-
-class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {/*{{{*/
- function get_name() {/*{{{*/
- return "PLAINTEXT";
- }/*}}}*/
-
- function build_signature($request, $consumer, $token) {/*{{{*/
- $sig = array(
- OAuthUtil::urlencodeRFC3986($consumer->secret)
- );
-
- if ($token) {
- array_push($sig, OAuthUtil::urlencodeRFC3986($token->secret));
- } else {
- array_push($sig, '');
- }
-
- $raw = implode("&", $sig);
- // for debug purposes
- $request->base_string = $raw;
-
- return $raw;
- }/*}}}*/
-}/*}}}*/
-
-class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {/*{{{*/
- function get_name() {/*{{{*/
- return "RSA-SHA1";
- }/*}}}*/
-
- function fetch_public_cert(&$request) {/*{{{*/
- // not implemented yet, ideas are:
- // (1) do a lookup in a table of trusted certs keyed off of consumer
- // (2) fetch via http using a url provided by the requester
- // (3) some sort of specific discovery code based on request
- //
- // either way should return a string representation of the certificate
- trigger_error("fetch_public_cert not implemented", E_USER_ERROR);
- return NULL;
- }/*}}}*/
-
- function fetch_private_cert(&$request) {/*{{{*/
- // not implemented yet, ideas are:
- // (1) do a lookup in a table of trusted certs keyed off of consumer
- //
- // either way should return a string representation of the certificate
- trigger_error("fetch_private_cert not implemented", E_USER_ERROR);
- return NULL;
- }/*}}}*/
-
- function build_signature(&$request, $consumer, $token) {/*{{{*/
- $base_string = $request->get_signature_base_string();
-
- // Fetch the private key cert based on the request
- $cert = $this->fetch_private_cert($request);
-
- // Pull the private key ID from the certificate
- $privatekeyid = openssl_get_privatekey($cert);
-
- // Sign using the key
- $ok = openssl_sign($base_string, $signature, $privatekeyid);
-
- // Release the key resource
- openssl_free_key($privatekeyid);
-
- return base64_encode($signature);
- } /*}}}*/
-
- function check_signature(&$request, $consumer, $token, $signature) {/*{{{*/
- $decoded_sig = base64_decode($signature);
-
- $base_string = $request->get_signature_base_string();
-
- // Fetch the public key cert based on the request
- $cert = $this->fetch_public_cert($request);
-
- // Pull the public key ID from the certificate
- $publickeyid = openssl_get_publickey($cert);
-
- // Check the computed signature against the one passed in the query
- $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
-
- // Release the key resource
- openssl_free_key($publickeyid);
-
- return $ok == 1;
- } /*}}}*/
-}/*}}}*/
-
-class OAuthRequest {/*{{{*/
- var $parameters;
- var $http_method;
- var $http_url;
- // for debug purposes
- var $base_string;
-
- function OAuthRequest($http_method, $http_url, $parameters=array()) {/*{{{*/
- $this->parameters = $parameters;
- $this->http_method = $http_method;
- $this->http_url = $http_url;
- }/*}}}*/
-
-
- /**
- * attempt to build up a request from what was passed to the server
- */
- function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {/*{{{*/
- $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
- @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
- @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
-
- $request_headers = OAuthRequest::get_headers();
-
- // let the library user override things however they'd like, if they know
- // which parameters to use then go for it, for example XMLRPC might want to
- // do this
- if ($parameters) {
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- }
- // next check for the auth header, we need to do some extra stuff
- // if that is the case, namely suck in the parameters from GET or POST
- // so that we can include them in the signature
- else if (@substr($request_headers['Authorization'], 0, 5) == "OAuth") {
- $header_parameters = OAuthRequest::split_header($request_headers['Authorization']);
- if ($http_method == "GET") {
- $req_parameters = $_GET;
- }
- else if ($http_method = "POST") {
- $req_parameters = $_POST;
- }
- $parameters = array_merge($header_parameters, $req_parameters);
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- }
- else if ($http_method == "GET") {
- $req = new OAuthRequest($http_method, $http_url, $_GET);
- }
- else if ($http_method == "POST") {
- $req = new OAuthRequest($http_method, $http_url, $_POST);
- }
- return $req;
- }/*}}}*/
-
- /**
- * pretty much a helper function to set up the request
- */
- function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=array()) {/*{{{*/
- static $version = '1.0';
- $defaults = array("oauth_version" => $version,
- "oauth_nonce" => OAuthRequest::generate_nonce(),
- "oauth_timestamp" => OAuthRequest::generate_timestamp(),
- "oauth_consumer_key" => $consumer->key);
- $parameters = array_merge($defaults, $parameters);
-
- if ($token) {
- $parameters['oauth_token'] = $token->key;
- }
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- return $req;
- }/*}}}*/
-
- function set_parameter($name, $value) {/*{{{*/
- $this->parameters[$name] = $value;
- }/*}}}*/
-
- function get_parameter($name) {/*{{{*/
- return $this->parameters[$name];
- }/*}}}*/
-
- function get_parameters() {/*{{{*/
- return $this->parameters;
- }/*}}}*/
-