1
0
mirror of https://github.com/e107inc/e107.git synced 2025-07-31 20:00:37 +02:00

Upgraded HybridAuth to 2.6.0

This commit is contained in:
Cameron
2016-02-28 12:03:55 -08:00
parent c357a420cc
commit 7127339553
32 changed files with 4260 additions and 3931 deletions

View File

@@ -1,67 +1,84 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
/** /**
* Hybrid_Auth class * Hybrid_Auth class
* *
* Hybrid_Auth class provide a simple way to authenticate users via OpenID and OAuth. * Hybrid_Auth class provide a simple way to authenticate users via OpenID and OAuth.
* *
* Generally, Hybrid_Auth is the only class you should instanciate and use throughout your application. * Generally, Hybrid_Auth is the only class you should instanciate and use throughout your application.
*/ */
class Hybrid_Auth class Hybrid_Auth {
{
public static $version = "2.3.0";
public static $config = array(); public static $version = "2.6.0";
public static $store = NULL;
public static $error = NULL;
public static $logger = NULL;
// --------------------------------------------------------------------
/** /**
* Try to start a new session of none then initialize Hybrid_Auth * Configuration array
* * @var array
* Hybrid_Auth constructor will require either a valid config array or */
* a path for a configuration file as parameter. To know more please public static $config = array();
* refer to the Configuration section:
* http://hybridauth.sourceforge.net/userguide/Configuration.html /**
*/ * Auth cache
function __construct( $config ) * @var Hybrid_Storage
{ */
Hybrid_Auth::initialize( $config ); public static $store = null;
/**
* Error pool
* @var Hybrid_Error
*/
public static $error = null;
/**
* Logger
* @var Hybrid_Logger
*/
public static $logger = null;
/**
* Try to start a new session of none then initialize Hybrid_Auth
*
* Hybrid_Auth constructor will require either a valid config array or
* a path for a configuration file as parameter. To know more please
* refer to the Configuration section:
* http://hybridauth.sourceforge.net/userguide/Configuration.html
*
* @param array $config Configuration array or path to a configratuion file
*/
function __construct($config) {
Hybrid_Auth::initialize($config);
} }
// --------------------------------------------------------------------
/** /**
* Try to initialize Hybrid_Auth with given $config hash or file * Try to initialize Hybrid_Auth with given $config hash or file
*/ *
public static function initialize( $config ) * @param array $config Configuration array or path to a configratuion file
{ * @return void
if( ! is_array( $config ) && ! file_exists( $config ) ){ * @throws Exception
throw new Exception( "Hybriauth config does not exist on the given path.", 1 ); */
public static function initialize($config) {
if (!is_array($config) && !file_exists($config)) {
throw new Exception("Hybriauth config does not exist on the given path.", 1);
} }
if( ! is_array( $config ) ){ if (!is_array($config)) {
$config = include $config; $config = include $config;
} }
// build some need'd paths // build some need'd paths
$config["path_base"] = realpath( dirname( __FILE__ ) ) . "/"; $config["path_base"] = realpath(dirname(__FILE__)) . "/";
$config["path_libraries"] = $config["path_base"] . "thirdparty/"; $config["path_libraries"] = $config["path_base"] . "thirdparty/";
$config["path_resources"] = $config["path_base"] . "resources/"; $config["path_resources"] = $config["path_base"] . "resources/";
$config["path_providers"] = $config["path_base"] . "Providers/"; $config["path_providers"] = $config["path_base"] . "Providers/";
// reset debug mode // reset debug mode
if( ! isset( $config["debug_mode"] ) ){ if (!isset($config["debug_mode"])) {
$config["debug_mode"] = false; $config["debug_mode"] = false;
$config["debug_file"] = null; $config["debug_file"] = null;
} }
@@ -83,9 +100,9 @@ class Hybrid_Auth
require_once $config["path_base"] . "User_Contact.php"; require_once $config["path_base"] . "User_Contact.php";
require_once $config["path_base"] . "User_Activity.php"; require_once $config["path_base"] . "User_Activity.php";
if ( ! class_exists("Hybrid_Storage", false) ){ if (!class_exists("Hybrid_Storage", false)) {
require_once $config["path_base"] . "Storage.php"; require_once $config["path_base"] . "Storage.php";
} }
// hash given config // hash given config
Hybrid_Auth::$config = $config; Hybrid_Auth::$config = $config;
@@ -99,203 +116,187 @@ class Hybrid_Auth
// start session storage mng // start session storage mng
Hybrid_Auth::$store = new Hybrid_Storage(); Hybrid_Auth::$store = new Hybrid_Storage();
Hybrid_Logger::info( "Enter Hybrid_Auth::initialize()"); Hybrid_Logger::info("Enter Hybrid_Auth::initialize()");
Hybrid_Logger::info( "Hybrid_Auth::initialize(). PHP version: " . PHP_VERSION ); Hybrid_Logger::info("Hybrid_Auth::initialize(). PHP version: " . PHP_VERSION);
Hybrid_Logger::info( "Hybrid_Auth::initialize(). Hybrid_Auth version: " . Hybrid_Auth::$version ); Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth version: " . Hybrid_Auth::$version);
Hybrid_Logger::info( "Hybrid_Auth::initialize(). Hybrid_Auth called from: " . Hybrid_Auth::getCurrentUrl() ); Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth called from: " . Hybrid_Auth::getCurrentUrl());
// PHP Curl extension [http://www.php.net/manual/en/intro.curl.php] // PHP Curl extension [http://www.php.net/manual/en/intro.curl.php]
if ( ! function_exists('curl_init') ) { if (!function_exists('curl_init')) {
Hybrid_Logger::error('Hybridauth Library needs the CURL PHP extension.'); Hybrid_Logger::error('Hybridauth Library needs the CURL PHP extension.');
throw new Exception('Hybridauth Library needs the CURL PHP extension.'); throw new Exception('Hybridauth Library needs the CURL PHP extension.');
} }
// PHP JSON extension [http://php.net/manual/en/book.json.php] // PHP JSON extension [http://php.net/manual/en/book.json.php]
if ( ! function_exists('json_decode') ) { if (!function_exists('json_decode')) {
Hybrid_Logger::error('Hybridauth Library needs the JSON PHP extension.'); Hybrid_Logger::error('Hybridauth Library needs the JSON PHP extension.');
throw new Exception('Hybridauth Library needs the JSON PHP extension.'); throw new Exception('Hybridauth Library needs the JSON PHP extension.');
} }
// session.name // session.name
if( session_name() != "PHPSESSID" ){ if (session_name() != "PHPSESSID") {
Hybrid_Logger::info('PHP session.name diff from default PHPSESSID. http://php.net/manual/en/session.configuration.php#ini.session.name.'); Hybrid_Logger::info('PHP session.name diff from default PHPSESSID. http://php.net/manual/en/session.configuration.php#ini.session.name.');
} }
// safe_mode is on // safe_mode is on
if( ini_get('safe_mode') ){ if (ini_get('safe_mode')) {
Hybrid_Logger::info('PHP safe_mode is on. http://php.net/safe-mode.'); Hybrid_Logger::info('PHP safe_mode is on. http://php.net/safe-mode.');
} }
// open basedir is on // open basedir is on
if( ini_get('open_basedir') ){ if (ini_get('open_basedir')) {
Hybrid_Logger::info('PHP open_basedir is on. http://php.net/open-basedir.'); Hybrid_Logger::info('PHP open_basedir is on. http://php.net/open-basedir.');
} }
Hybrid_Logger::debug( "Hybrid_Auth initialize. dump used config: ", serialize( $config ) ); Hybrid_Logger::debug("Hybrid_Auth initialize. dump used config: ", serialize($config));
Hybrid_Logger::debug( "Hybrid_Auth initialize. dump current session: ", Hybrid_Auth::storage()->getSessionData() ); Hybrid_Logger::debug("Hybrid_Auth initialize. dump current session: ", Hybrid_Auth::storage()->getSessionData());
Hybrid_Logger::info( "Hybrid_Auth initialize: check if any error is stored on the endpoint..." ); Hybrid_Logger::info("Hybrid_Auth initialize: check if any error is stored on the endpoint...");
if( Hybrid_Error::hasError() ){ if (Hybrid_Error::hasError()) {
$m = Hybrid_Error::getErrorMessage(); $m = Hybrid_Error::getErrorMessage();
$c = Hybrid_Error::getErrorCode(); $c = Hybrid_Error::getErrorCode();
$p = Hybrid_Error::getErrorPrevious(); $p = Hybrid_Error::getErrorPrevious();
Hybrid_Logger::error( "Hybrid_Auth initialize: A stored Error found, Throw an new Exception and delete it from the store: Error#$c, '$m'" ); Hybrid_Logger::error("Hybrid_Auth initialize: A stored Error found, Throw an new Exception and delete it from the store: Error#$c, '$m'");
Hybrid_Error::clearError(); Hybrid_Error::clearError();
// try to provide the previous if any // try to provide the previous if any
// Exception::getPrevious (PHP 5 >= 5.3.0) http://php.net/manual/en/exception.getprevious.php // Exception::getPrevious (PHP 5 >= 5.3.0) http://php.net/manual/en/exception.getprevious.php
if ( version_compare( PHP_VERSION, '5.3.0', '>=' ) && ($p instanceof Exception) ) { if (version_compare(PHP_VERSION, '5.3.0', '>=') && ($p instanceof Exception)) {
throw new Exception( $m, $c, $p ); throw new Exception($m, $c, $p);
} } else {
else{ throw new Exception($m, $c);
throw new Exception( $m, $c );
} }
} }
Hybrid_Logger::info( "Hybrid_Auth initialize: no error found. initialization succeed." ); Hybrid_Logger::info("Hybrid_Auth initialize: no error found. initialization succeed.");
// Endof initialize
} }
// --------------------------------------------------------------------
/** /**
* Hybrid storage system accessor * Hybrid storage system accessor
* *
* Users sessions are stored using HybridAuth storage system ( HybridAuth 2.0 handle PHP Session only) and can be accessed directly by * Users sessions are stored using HybridAuth storage system ( HybridAuth 2.0 handle PHP Session only) and can be accessed directly by
* Hybrid_Auth::storage()->get($key) to retrieves the data for the given key, or calling * Hybrid_Auth::storage()->get($key) to retrieves the data for the given key, or calling
* Hybrid_Auth::storage()->set($key, $value) to store the key => $value set. * Hybrid_Auth::storage()->set($key, $value) to store the key => $value set.
*/ *
public static function storage() * @return Hybrid_Storage
{ */
public static function storage() {
return Hybrid_Auth::$store; return Hybrid_Auth::$store;
} }
// --------------------------------------------------------------------
/** /**
* Get hybridauth session data. * Get hybridauth session data
*/ * @return string|null
function getSessionData() */
{ function getSessionData() {
return Hybrid_Auth::storage()->getSessionData(); return Hybrid_Auth::storage()->getSessionData();
} }
// --------------------------------------------------------------------
/** /**
* restore hybridauth session data. * Restore hybridauth session data
*/ *
function restoreSessionData( $sessiondata = NULL ) * @param string $sessiondata Serialized session data
{ * @retun void
Hybrid_Auth::storage()->restoreSessionData( $sessiondata ); */
function restoreSessionData($sessiondata = null) {
Hybrid_Auth::storage()->restoreSessionData($sessiondata);
} }
// --------------------------------------------------------------------
/** /**
* Try to authenticate the user with a given provider. * Try to authenticate the user with a given provider.
* *
* If the user is already connected we just return and instance of provider adapter, * If the user is already connected we just return and instance of provider adapter,
* ELSE, try to authenticate and authorize the user with the provider. * ELSE, try to authenticate and authorize the user with the provider.
* *
* $params is generally an array with required info in order for this provider and HybridAuth to work, * $params is generally an array with required info in order for this provider and HybridAuth to work,
* like : * like :
* hauth_return_to: URL to call back after authentication is done * hauth_return_to: URL to call back after authentication is done
* openid_identifier: The OpenID identity provider identifier * openid_identifier: The OpenID identity provider identifier
* google_service: can be "Users" for Google user accounts service or "Apps" for Google hosted Apps * google_service: can be "Users" for Google user accounts service or "Apps" for Google hosted Apps
*/ *
public static function authenticate( $providerId, $params = NULL ) * @param string $providerId ID of the provider
{ * @param array $params Params
Hybrid_Logger::info( "Enter Hybrid_Auth::authenticate( $providerId )" ); * @return
*/
// if user not connected to $providerId then try setup a new adapter and start the login process for this provider public static function authenticate($providerId, $params = null) {
if( ! Hybrid_Auth::storage()->get( "hauth_session.$providerId.is_logged_in" ) ){ Hybrid_Logger::info("Enter Hybrid_Auth::authenticate( $providerId )");
Hybrid_Logger::info( "Hybrid_Auth::authenticate( $providerId ), User not connected to the provider. Try to authenticate.." );
$provider_adapter = Hybrid_Auth::setup( $providerId, $params );
if (!Hybrid_Auth::storage()->get("hauth_session.$providerId.is_logged_in")) {
// if user not connected to $providerId then try setup a new adapter and start the login process for this provider
Hybrid_Logger::info("Hybrid_Auth::authenticate( $providerId ), User not connected to the provider. Try to authenticate..");
$provider_adapter = Hybrid_Auth::setup($providerId, $params);
$provider_adapter->login(); $provider_adapter->login();
} } else {
// else, then return the adapter instance for the given provider
// else, then return the adapter instance for the given provider Hybrid_Logger::info("Hybrid_Auth::authenticate( $providerId ), User is already connected to this provider. Return the adapter instance.");
else{ return Hybrid_Auth::getAdapter($providerId);
Hybrid_Logger::info( "Hybrid_Auth::authenticate( $providerId ), User is already connected to this provider. Return the adapter instance." );
return Hybrid_Auth::getAdapter( $providerId );
} }
} }
// --------------------------------------------------------------------
/** /**
* Return the adapter instance for an authenticated provider * Return the adapter instance for an authenticated provider
*/ *
public static function getAdapter( $providerId = NULL ) * @param string $providerId ID of the provider
{ * @return Hybrid_Provider_Adapter
Hybrid_Logger::info( "Enter Hybrid_Auth::getAdapter( $providerId )" ); */
public static function getAdapter($providerId = null) {
return Hybrid_Auth::setup( $providerId ); Hybrid_Logger::info("Enter Hybrid_Auth::getAdapter( $providerId )");
return Hybrid_Auth::setup($providerId);
} }
// --------------------------------------------------------------------
/** /**
* Setup an adapter for a given provider * Setup an adapter for a given provider
*/ *
public static function setup( $providerId, $params = NULL ) * @param string $providerId ID of the provider
{ * @param array $params Adapter params
Hybrid_Logger::debug( "Enter Hybrid_Auth::setup( $providerId )", $params ); * @return Hybrid_Provider_Adapter
*/
public static function setup($providerId, $params = null) {
Hybrid_Logger::debug("Enter Hybrid_Auth::setup( $providerId )", $params);
if( ! $params ){ if (!$params) {
$params = Hybrid_Auth::storage()->get( "hauth_session.$providerId.id_provider_params" ); $params = Hybrid_Auth::storage()->get("hauth_session.$providerId.id_provider_params");
Hybrid_Logger::debug( "Hybrid_Auth::setup( $providerId ), no params given. Trying to get the stored for this provider.", $params ); Hybrid_Logger::debug("Hybrid_Auth::setup( $providerId ), no params given. Trying to get the stored for this provider.", $params);
} }
if( ! $params ){ if (!$params) {
$params = ARRAY(); $params = array();
Hybrid_Logger::info("Hybrid_Auth::setup( $providerId ), no stored params found for this provider. Initialize a new one for new session");
Hybrid_Logger::info( "Hybrid_Auth::setup( $providerId ), no stored params found for this provider. Initialize a new one for new session" );
} }
if( is_array($params) && ! isset( $params["hauth_return_to"] ) ){ if (is_array($params) && !isset($params["hauth_return_to"])) {
$params["hauth_return_to"] = Hybrid_Auth::getCurrentUrl(); $params["hauth_return_to"] = Hybrid_Auth::getCurrentUrl();
Hybrid_Logger::debug("Hybrid_Auth::setup( $providerId ). HybridAuth Callback URL set to: ", $params["hauth_return_to"]);
Hybrid_Logger::debug( "Hybrid_Auth::setup( $providerId ). HybridAuth Callback URL set to: ", $params["hauth_return_to"] );
} }
# instantiate a new IDProvider Adapter # instantiate a new IDProvider Adapter
$provider = new Hybrid_Provider_Adapter(); $provider = new Hybrid_Provider_Adapter();
$provider->factory($providerId, $params);
$provider->factory( $providerId, $params );
return $provider; return $provider;
}
// --------------------------------------------------------------------
/**
* Check if the current user is connected to a given provider
*/
public static function isConnectedWith( $providerId )
{
return (bool) Hybrid_Auth::storage()->get( "hauth_session.{$providerId}.is_logged_in" );
} }
// -------------------------------------------------------------------- /**
* Check if the current user is connected to a given provider
*
* @param string $providerId ID of the provider
* @return bool
*/
public static function isConnectedWith($providerId) {
return (bool) Hybrid_Auth::storage()->get("hauth_session.{$providerId}.is_logged_in");
}
/** /**
* Return array listing all authenticated providers * Return array listing all authenticated providers
*/ * @return array
public static function getConnectedProviders() */
{ public static function getConnectedProviders() {
$idps = array(); $idps = array();
foreach( Hybrid_Auth::$config["providers"] as $idpid => $params ){ foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
if( Hybrid_Auth::isConnectedWith( $idpid ) ){ if (Hybrid_Auth::isConnectedWith($idpid)) {
$idps[] = $idpid; $idps[] = $idpid;
} }
} }
@@ -303,20 +304,26 @@ class Hybrid_Auth
return $idps; return $idps;
} }
// --------------------------------------------------------------------
/** /**
* Return array listing all enabled providers as well as a flag if you are connected. * Return array listing all enabled providers as well as a flag if you are connected
*/ *
public static function getProviders() * <code>
{ * array(
* 'Facebook' => array(
* 'connected' => true
* )
* )
* </code>
* @return array
*/
public static function getProviders() {
$idps = array(); $idps = array();
foreach( Hybrid_Auth::$config["providers"] as $idpid => $params ){ foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
if($params['enabled']) { if ($params['enabled']) {
$idps[$idpid] = array( 'connected' => false ); $idps[$idpid] = array('connected' => false);
if( Hybrid_Auth::isConnectedWith( $idpid ) ){ if (Hybrid_Auth::isConnectedWith($idpid)) {
$idps[$idpid]['connected'] = true; $idps[$idpid]['connected'] = true;
} }
} }
@@ -325,35 +332,36 @@ class Hybrid_Auth
return $idps; return $idps;
} }
// --------------------------------------------------------------------
/** /**
* A generic function to logout all connected provider at once * A generic function to logout all connected provider at once
*/ * @return void
public static function logoutAllProviders() */
{ public static function logoutAllProviders() {
$idps = Hybrid_Auth::getConnectedProviders(); $idps = Hybrid_Auth::getConnectedProviders();
foreach( $idps as $idp ){ foreach ($idps as $idp) {
$adapter = Hybrid_Auth::getAdapter( $idp ); $adapter = Hybrid_Auth::getAdapter($idp);
$adapter->logout(); $adapter->logout();
} }
} }
// --------------------------------------------------------------------
/** /**
* Utility function, redirect to a given URL with php header or using javascript location.href * Utility function, redirect to a given URL with php header or using javascript location.href
*/ *
public static function redirect( $url, $mode = "PHP" ) * @param string $url URL to redirect to
{ * @param string $mode PHP|JS
Hybrid_Logger::info( "Enter Hybrid_Auth::redirect( $url, $mode )" ); */
public static function redirect($url, $mode = "PHP") {
Hybrid_Logger::info("Enter Hybrid_Auth::redirect( $url, $mode )");
if( $mode == "PHP" ){ // Ensure session is saved before sending response, see https://github.com/symfony/symfony/pull/12341
header( "Location: $url" ) ; if ((PHP_VERSION_ID >= 50400 && PHP_SESSION_ACTIVE === session_status()) || (PHP_VERSION_ID < 50400 && isset($_SESSION) && session_id())) {
session_write_close();
} }
elseif( $mode == "JS" ){
if ($mode == "PHP") {
header("Location: $url");
} elseif ($mode == "JS") {
echo '<html>'; echo '<html>';
echo '<head>'; echo '<head>';
echo '<script type="text/javascript">'; echo '<script type="text/javascript">';
@@ -363,39 +371,41 @@ class Hybrid_Auth
echo '<body onload="redirect()">'; echo '<body onload="redirect()">';
echo 'Redirecting, please wait...'; echo 'Redirecting, please wait...';
echo '</body>'; echo '</body>';
echo '</html>'; echo '</html>';
} }
die(); die();
} }
// --------------------------------------------------------------------
/** /**
* Utility function, return the current url. TRUE to get $_SERVER['REQUEST_URI'], FALSE for $_SERVER['PHP_SELF'] * Utility function, return the current url
*/ *
public static function getCurrentUrl( $request_uri = true ) * @param bool $request_uri true to get $_SERVER['REQUEST_URI'], false for $_SERVER['PHP_SELF']
{ * @return string
if( */
isset( $_SERVER['HTTPS'] ) && ( $_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 ) public static function getCurrentUrl($request_uri = true) {
|| isset( $_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' if (php_sapi_name() == 'cli') {
){ return '';
$protocol = 'https://';
} }
else {
$protocol = 'http://'; $protocol = 'http://';
if ((isset($_SERVER['HTTPS']) && ( $_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 ))
|| (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
$protocol = 'https://';
} }
$url = $protocol . $_SERVER['HTTP_HOST']; $url = $protocol . $_SERVER['HTTP_HOST'];
if( $request_uri ){ if ($request_uri) {
$url .= $_SERVER['REQUEST_URI']; $url .= $_SERVER['REQUEST_URI'];
} } else {
else{
$url .= $_SERVER['PHP_SELF']; $url .= $_SERVER['PHP_SELF'];
} }
// return current url // return current url
return $url; return $url;
} }
} }

View File

@@ -1,145 +1,146 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
/** /**
* Hybrid_Endpoint class * Hybrid_Endpoint class
* *
* Hybrid_Endpoint class provides a simple way to handle the OpenID and OAuth endpoint. * Provides a simple way to handle the OpenID and OAuth endpoint
*/ */
class Hybrid_Endpoint { class Hybrid_Endpoint {
public static $request = NULL;
public static $initDone = FALSE; protected $request = null;
protected $initDone = false;
/** /**
* Process the current request * Process the current request
* *
* $request - The current request parameters. Leave as NULL to default to use $_REQUEST. * @param array $request The current request parameters. Leave as null to default to use $_REQUEST.
*/ */
public static function process( $request = NULL ) public function __construct($request = null) {
{ if (is_null($request)) {
// Setup request variable
Hybrid_Endpoint::$request = $request;
if ( is_null(Hybrid_Endpoint::$request) ){
// Fix a strange behavior when some provider call back ha endpoint // Fix a strange behavior when some provider call back ha endpoint
// with /index.php?hauth.done={provider}?{args}... // with /index.php?hauth.done={provider}?{args}...
// >here we need to recreate the $_REQUEST // >here we need to parse $_SERVER[QUERY_STRING]
if ( strrpos( $_SERVER["QUERY_STRING"], '?' ) ) { $request = $_REQUEST;
$_SERVER["QUERY_STRING"] = str_replace( "?", "&", $_SERVER["QUERY_STRING"] ); if (strrpos($_SERVER["QUERY_STRING"], '?')) {
$_SERVER["QUERY_STRING"] = str_replace("?", "&", $_SERVER["QUERY_STRING"]);
parse_str( $_SERVER["QUERY_STRING"], $_REQUEST ); parse_str($_SERVER["QUERY_STRING"], $request);
} }
Hybrid_Endpoint::$request = $_REQUEST;
} }
// Setup request variable
$this->request = $request;
// If openid_policy requested, we return our policy document // If openid_policy requested, we return our policy document
if ( isset( Hybrid_Endpoint::$request["get"] ) && Hybrid_Endpoint::$request["get"] == "openid_policy" ) { if (isset($this->request["get"]) && $this->request["get"] == "openid_policy") {
Hybrid_Endpoint::processOpenidPolicy(); $this->processOpenidPolicy();
} }
// If openid_xrds requested, we return our XRDS document // If openid_xrds requested, we return our XRDS document
if ( isset( Hybrid_Endpoint::$request["get"] ) && Hybrid_Endpoint::$request["get"] == "openid_xrds" ) { if (isset($this->request["get"]) && $this->request["get"] == "openid_xrds") {
Hybrid_Endpoint::processOpenidXRDS(); $this->processOpenidXRDS();
} }
// If we get a hauth.start // If we get a hauth.start
if ( isset( Hybrid_Endpoint::$request["hauth_start"] ) && Hybrid_Endpoint::$request["hauth_start"] ) { if (isset($this->request["hauth_start"]) && $this->request["hauth_start"]) {
Hybrid_Endpoint::processAuthStart(); $this->processAuthStart();
} }
// Else if hauth.done // Else if hauth.done
elseif ( isset( Hybrid_Endpoint::$request["hauth_done"] ) && Hybrid_Endpoint::$request["hauth_done"] ) { elseif (isset($this->request["hauth_done"]) && $this->request["hauth_done"]) {
Hybrid_Endpoint::processAuthDone(); $this->processAuthDone();
} }
// Else we advertise our XRDS document, something supposed to be done from the Realm URL page // Else we advertise our XRDS document, something supposed to be done from the Realm URL page
else { else {
Hybrid_Endpoint::processOpenidRealm(); $this->processOpenidRealm();
} }
} }
/** /**
* Process OpenID policy request * Process the current request
*/ *
public static function processOpenidPolicy() * @param array $request The current request parameters. Leave as null to default to use $_REQUEST.
{ * @return Hybrid_Endpoint
$output = file_get_contents( dirname(__FILE__) . "/resources/openid_policy.html" ); */
public static function process($request = null) {
// Trick for PHP 5.2, because it doesn't support late static binding
$class = function_exists('get_called_class') ? get_called_class() : __CLASS__;
new $class($request);
}
/**
* Process OpenID policy request
* @return void
*/
protected function processOpenidPolicy() {
$output = file_get_contents(dirname(__FILE__) . "/resources/openid_policy.html");
print $output; print $output;
die(); die();
} }
/** /**
* Process OpenID XRDS request * Process OpenID XRDS request
*/ * @return void
public static function processOpenidXRDS() */
{ protected function processOpenidXRDS() {
header("Content-Type: application/xrds+xml"); header("Content-Type: application/xrds+xml");
$output = str_replace $output = str_replace("{RETURN_TO_URL}", str_replace(
( array("<", ">", "\"", "'", "&"), array("&lt;", "&gt;", "&quot;", "&apos;", "&amp;"), Hybrid_Auth::getCurrentUrl(false)
"{RETURN_TO_URL}", ), file_get_contents(dirname(__FILE__) . "/resources/openid_xrds.xml"));
str_replace(
array("<", ">", "\"", "'", "&"), array("&lt;", "&gt;", "&quot;", "&apos;", "&amp;"),
Hybrid_Auth::getCurrentUrl( false )
),
file_get_contents( dirname(__FILE__) . "/resources/openid_xrds.xml" )
);
print $output; print $output;
die(); die();
} }
/** /**
* Process OpenID realm request * Process OpenID realm request
*/ * @return void
public static function processOpenidRealm() */
{ protected function processOpenidRealm() {
$output = str_replace $output = str_replace("{X_XRDS_LOCATION}", htmlentities(Hybrid_Auth::getCurrentUrl(false), ENT_QUOTES, 'UTF-8')
( . "?get=openid_xrds&v="
"{X_XRDS_LOCATION}", . Hybrid_Auth::$version, file_get_contents(dirname(__FILE__) . "/resources/openid_realm.html"));
htmlentities( Hybrid_Auth::getCurrentUrl( false ), ENT_QUOTES, 'UTF-8' ) . "?get=openid_xrds&v=" . Hybrid_Auth::$version,
file_get_contents( dirname(__FILE__) . "/resources/openid_realm.html" )
);
print $output; print $output;
die(); die();
} }
/** /**
* define:endpoint step 3. * Define: endpoint step 3
*/ * @return void
public static function processAuthStart() * @throws Hybrid_Exception
{ */
Hybrid_Endpoint::authInit(); protected function processAuthStart() {
$this->authInit();
$provider_id = trim( strip_tags( Hybrid_Endpoint::$request["hauth_start"] ) ); $provider_id = trim(strip_tags($this->request["hauth_start"]));
# check if page accessed directly // check if page accessed directly
if( ! Hybrid_Auth::storage()->get( "hauth_session.$provider_id.hauth_endpoint" ) ) { if (!Hybrid_Auth::storage()->get("hauth_session.$provider_id.hauth_endpoint")) {
Hybrid_Logger::error( "Endpoint: hauth_endpoint parameter is not defined on hauth_start, halt login process!" ); Hybrid_Logger::error("Endpoint: hauth_endpoint parameter is not defined on hauth_start, halt login process!");
throw new Hybrid_Exception( "You cannot access this page directly." ); throw new Hybrid_Exception("You cannot access this page directly.");
} }
# define:hybrid.endpoint.php step 2. // define:hybrid.endpoint.php step 2.
$hauth = Hybrid_Auth::setup( $provider_id ); $hauth = Hybrid_Auth::setup($provider_id);
# if REQUESTed hauth_idprovider is wrong, session not created, etc. // if REQUESTed hauth_idprovider is wrong, session not created, etc.
if( ! $hauth ) { if (!$hauth) {
Hybrid_Logger::error( "Endpoint: Invalid parameter on hauth_start!" ); Hybrid_Logger::error("Endpoint: Invalid parameter on hauth_start!");
throw new Hybrid_Exception("Invalid parameter! Please return to the login page and try again.");
throw new Hybrid_Exception( "Invalid parameter! Please return to the login page and try again." );
} }
try { try {
Hybrid_Logger::info( "Endpoint: call adapter [{$provider_id}] loginBegin()" ); Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginBegin()");
$hauth->adapter->loginBegin(); $hauth->adapter->loginBegin();
} } catch (Exception $e) {
catch ( Exception $e ) { Hybrid_Logger::error("Exception:" . $e->getMessage(), $e);
Hybrid_Logger::error( "Exception:" . $e->getMessage(), $e ); Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e->getPrevious());
Hybrid_Error::setError( $e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e->getPrevious() );
$hauth->returnToCallbackUrl(); $hauth->returnToCallbackUrl();
} }
@@ -148,69 +149,74 @@ class Hybrid_Endpoint {
} }
/** /**
* define:endpoint step 3.1 and 3.2 * Define: endpoint step 3.1 and 3.2
*/ * @return void
public static function processAuthDone() * @throws Hybrid_Exception
{ */
Hybrid_Endpoint::authInit(); protected function processAuthDone() {
$this->authInit();
$provider_id = trim( strip_tags( Hybrid_Endpoint::$request["hauth_done"] ) ); $provider_id = trim(strip_tags($this->request["hauth_done"]));
$hauth = Hybrid_Auth::setup( $provider_id ); $hauth = Hybrid_Auth::setup($provider_id);
if( ! $hauth ) { if (!$hauth) {
Hybrid_Logger::error( "Endpoint: Invalid parameter on hauth_done!" ); Hybrid_Logger::error("Endpoint: Invalid parameter on hauth_done!");
$hauth->adapter->setUserUnconnected(); $hauth->adapter->setUserUnconnected();
throw new Hybrid_Exception( "Invalid parameter! Please return to the login page and try again." ); throw new Hybrid_Exception("Invalid parameter! Please return to the login page and try again.");
} }
try { try {
Hybrid_Logger::info( "Endpoint: call adapter [{$provider_id}] loginFinish() " ); Hybrid_Logger::info("Endpoint: call adapter [{$provider_id}] loginFinish() ");
$hauth->adapter->loginFinish();
} catch (Exception $e) {
Hybrid_Logger::error("Exception:" . $e->getMessage(), $e);
Hybrid_Error::setError($e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e->getPrevious());
$hauth->adapter->loginFinish(); $hauth->adapter->setUserUnconnected();
}
catch( Exception $e ){
Hybrid_Logger::error( "Exception:" . $e->getMessage(), $e );
Hybrid_Error::setError( $e->getMessage(), $e->getCode(), $e->getTraceAsString(), $e->getPrevious());
$hauth->adapter->setUserUnconnected();
} }
Hybrid_Logger::info( "Endpoint: job done. retrun to callback url." ); Hybrid_Logger::info("Endpoint: job done. return to callback url.");
$hauth->returnToCallbackUrl(); $hauth->returnToCallbackUrl();
die(); die();
} }
public static function authInit() /**
{ * Initializes authentication
if ( ! Hybrid_Endpoint::$initDone) { * @throws Hybrid_Exception
Hybrid_Endpoint::$initDone = TRUE; */
protected function authInit() {
if (!$this->initDone) {
$this->initDone = true;
# Init Hybrid_Auth // Init Hybrid_Auth
try { try {
if(!class_exists("Hybrid_Storage")){ if (!class_exists("Hybrid_Storage", false)) {
require_once realpath( dirname( __FILE__ ) ) . "/Storage.php"; require_once realpath(dirname(__FILE__)) . "/Storage.php";
} }
if (!class_exists("Hybrid_Exception", false)) {
$storage = new Hybrid_Storage(); require_once realpath(dirname(__FILE__)) . "/Exception.php";
}
// Check if Hybrid_Auth session already exist if (!class_exists("Hybrid_Logger", false)) {
if ( ! $storage->config( "CONFIG" ) ) { require_once realpath(dirname(__FILE__)) . "/Logger.php";
Hybrid_Logger::error( "Endpoint: Config storage not found when trying to init Hyrid_Auth. " );
throw new Hybrid_Exception( "You cannot access this page directly." );
} }
Hybrid_Auth::initialize( $storage->config( "CONFIG" ) ); $storage = new Hybrid_Storage();
}
catch ( Exception $e ){
Hybrid_Logger::error( "Endpoint: Error while trying to init Hybrid_Auth: " . $e->getMessage());
throw new Hybrid_Exception( "Oophs. Error!" ); // Check if Hybrid_Auth session already exist
if (!$storage->config("CONFIG")) {
throw new Hybrid_Exception("You cannot access this page directly.");
}
Hybrid_Auth::initialize($storage->config("CONFIG"));
} catch (Exception $e) {
Hybrid_Logger::error("Endpoint: Error while trying to init Hybrid_Auth: " . $e->getMessage());
throw new Hybrid_Exception( "Endpoint: Error while trying to init Hybrid_Auth: " . $e->getMessage(), $e->getCode(), $e );
} }
} }
} }
} }

View File

@@ -1,89 +1,88 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
/** /**
* Errors manager * Errors manager
* *
* HybridAuth errors are stored in Hybrid::storage() and not displayed directly to the end user * HybridAuth errors are stored in Hybrid::storage() and not displayed directly to the end user
*/ */
class Hybrid_Error class Hybrid_Error {
{
/**
* Store error in session
*
* @param String $message
* @param Number $code
* @param String $trace
* @param String $previous
*/
public static function setError( $message, $code = NULL, $trace = NULL, $previous = NULL )
{
Hybrid_Logger::info( "Enter Hybrid_Error::setError( $message )" );
Hybrid_Auth::storage()->set( "hauth_session.error.status" , 1 ); /**
Hybrid_Auth::storage()->set( "hauth_session.error.message" , $message ); * Store error in session
Hybrid_Auth::storage()->set( "hauth_session.error.code" , $code ); *
Hybrid_Auth::storage()->set( "hauth_session.error.trace" , $trace ); * @param string $message Error message
Hybrid_Auth::storage()->set( "hauth_session.error.previous", $previous ); * @param int $code Error code
* @param string $trace Back trace
* @param string $previous Previous exception
*/
public static function setError($message, $code = null, $trace = null, $previous = null) {
Hybrid_Logger::info("Enter Hybrid_Error::setError( $message )");
Hybrid_Auth::storage()->set("hauth_session.error.status", 1);
Hybrid_Auth::storage()->set("hauth_session.error.message", $message);
Hybrid_Auth::storage()->set("hauth_session.error.code", $code);
Hybrid_Auth::storage()->set("hauth_session.error.trace", $trace);
Hybrid_Auth::storage()->set("hauth_session.error.previous", $previous);
} }
/** /**
* Clear the last error * Clear the last error
*/ * @return void
public static function clearError() */
{ public static function clearError() {
Hybrid_Logger::info( "Enter Hybrid_Error::clearError()" ); Hybrid_Logger::info("Enter Hybrid_Error::clearError()");
Hybrid_Auth::storage()->delete( "hauth_session.error.status" ); Hybrid_Auth::storage()->delete("hauth_session.error.status");
Hybrid_Auth::storage()->delete( "hauth_session.error.message" ); Hybrid_Auth::storage()->delete("hauth_session.error.message");
Hybrid_Auth::storage()->delete( "hauth_session.error.code" ); Hybrid_Auth::storage()->delete("hauth_session.error.code");
Hybrid_Auth::storage()->delete( "hauth_session.error.trace" ); Hybrid_Auth::storage()->delete("hauth_session.error.trace");
Hybrid_Auth::storage()->delete( "hauth_session.error.previous" ); Hybrid_Auth::storage()->delete("hauth_session.error.previous");
} }
/** /**
* Checks to see if there is a an error. * Checks to see if there is a an error.
* * @return boolean true if there is an error.
* @return boolean True if there is an error. */
*/ public static function hasError() {
public static function hasError() return (bool) Hybrid_Auth::storage()->get("hauth_session.error.status");
{
return (bool) Hybrid_Auth::storage()->get( "hauth_session.error.status" );
} }
/** /**
* return error message * Return error message
*/ * @return string
public static function getErrorMessage() */
{ public static function getErrorMessage() {
return Hybrid_Auth::storage()->get( "hauth_session.error.message" ); return Hybrid_Auth::storage()->get("hauth_session.error.message");
} }
/** /**
* return error code * Return error code
*/ * @return int
public static function getErrorCode() */
{ public static function getErrorCode() {
return Hybrid_Auth::storage()->get( "hauth_session.error.code" ); return Hybrid_Auth::storage()->get("hauth_session.error.code");
} }
/** /**
* return string detailed error backtrace as string. * Return string detailed error backtrace as string
*/ * @return string
public static function getErrorTrace() */
{ public static function getErrorTrace() {
return Hybrid_Auth::storage()->get( "hauth_session.error.trace" ); return Hybrid_Auth::storage()->get("hauth_session.error.trace");
} }
/** /**
* @return string detailed error backtrace as string. * Detailed error backtrace as string
*/ * @return string
public static function getErrorPrevious() */
{ public static function getErrorPrevious() {
return Hybrid_Auth::storage()->get( "hauth_session.error.previous" ); return Hybrid_Auth::storage()->get("hauth_session.error.previous");
} }
} }

View File

@@ -1,16 +1,17 @@
<?php <?php
/*!
* HybridAuth /* !
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * HybridAuth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
*/ * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* Exception implementation * Exception implementation
* *
* The base Exception is extended to allow applications to handle exceptions from hybrid auth * The base Exception is extended to allow applications to handle exceptions from hybrid auth
* separately from general exceptions. * separately from general exceptions.
*/ */
class Hybrid_Exception extends Exception class Hybrid_Exception extends Exception {
{
} }

View File

@@ -1,89 +1,102 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
/** /**
* Debugging and Logging manager * Debugging and Logging manager
*/ */
class Hybrid_Logger class Hybrid_Logger {
{
/** /**
* Constructor * Constructor
*/ */
function __construct() function __construct() {
{ // if debug mode is set to true, then check for the writable log file
// if debug mode is set to true, then check for the writable log file if (Hybrid_Auth::$config["debug_mode"]) {
if ( Hybrid_Auth::$config["debug_mode"] ){ if (!isset(Hybrid_Auth::$config["debug_file"])) {
if ( ! isset(Hybrid_Auth::$config["debug_file"]) ) { throw new Exception("'debug_mode' is set to 'true' but no log file path 'debug_file' is set.", 1);
throw new Exception( "'debug_mode' is set to 'true' but no log file path 'debug_file' is set.", 1 ); } elseif (!file_exists(Hybrid_Auth::$config["debug_file"]) && !is_writable(Hybrid_Auth::$config["debug_file"])) {
} if (!touch(Hybrid_Auth::$config["debug_file"])) {
elseif ( ! file_exists( Hybrid_Auth::$config["debug_file"] ) && ! is_writable( Hybrid_Auth::$config["debug_file"]) ){ throw new Exception("'debug_mode' is set to 'true', but the file " . Hybrid_Auth::$config['debug_file'] . " in 'debug_file' can not be created.", 1);
if ( ! touch( Hybrid_Auth::$config["debug_file"] ) ){ }
throw new Exception( "'debug_mode' is set to 'true', but the file " . Hybrid_Auth::$config['debug_file'] . " in 'debug_file' can not be created.", 1 ); } elseif (!is_writable(Hybrid_Auth::$config["debug_file"])) {
} throw new Exception("'debug_mode' is set to 'true', but the given log file path 'debug_file' is not a writable file.", 1);
} }
elseif ( ! is_writable( Hybrid_Auth::$config["debug_file"] ) ){ }
throw new Exception( "'debug_mode' is set to 'true', but the given log file path 'debug_file' is not a writable file.", 1 );
}
}
} }
/**
* Debug
* @param String $message
* @param Object $object
*/
public static function debug( $message, $object = NULL )
{
if( Hybrid_Auth::$config["debug_mode"] ){
$datetime = new DateTime();
$datetime = $datetime->format(DATE_ATOM);
file_put_contents( /**
Hybrid_Auth::$config["debug_file"], * Logs a debug message with an object dump
"DEBUG -- " . $_SERVER['REMOTE_ADDR'] . " -- " . $datetime . " -- " . $message . " -- " . print_r($object, true) . "\n", *
FILE_APPEND * @param string $message Debug message
* @param stdClass $object Object being debugged
* @return void
*/
public static function debug($message, $object = null) {
if (Hybrid_Auth::$config["debug_mode"] === true) {
$dt = new DateTime('now', new DateTimeZone( 'UTC' ));
file_put_contents(Hybrid_Auth::$config["debug_file"], implode(' -- ', array(
"DEBUG",
$_SERVER['REMOTE_ADDR'],
$dt->format(DATE_ATOM),
$message,
print_r($object, true) . PHP_EOL,
)), FILE_APPEND
); );
} }
} }
/**
* Info
* @param String $message
*/
public static function info( $message )
{
if( in_array(Hybrid_Auth::$config["debug_mode"], array(true, 'info'), true) ){
$datetime = new DateTime();
$datetime = $datetime->format(DATE_ATOM);
file_put_contents( /**
Hybrid_Auth::$config["debug_file"], * Logs an info message
"INFO -- " . $_SERVER['REMOTE_ADDR'] . " -- " . $datetime . " -- " . $message . "\n", *
FILE_APPEND * @param string $message Info message
); * @return void
*/
public static function info($message) {
if (in_array(Hybrid_Auth::$config["debug_mode"], array(true, 'info'), true)) {
$dt = new DateTime('now', new DateTimeZone( 'UTC' ));
file_put_contents(Hybrid_Auth::$config["debug_file"], implode(' -- ', array(
"INFO",
$_SERVER['REMOTE_ADDR'],
$dt->format(DATE_ATOM),
$message . PHP_EOL,
)), FILE_APPEND);
} }
} }
/**
* Error
* @param String $message Error message
* @param Object $object
*/
public static function error($message, $object = NULL)
{
if(isset(Hybrid_Auth::$config["debug_mode"]) && in_array(Hybrid_Auth::$config["debug_mode"], array(true, 'info', 'error'), true) ){
$datetime = new DateTime();
$datetime = $datetime->format(DATE_ATOM);
file_put_contents( /**
Hybrid_Auth::$config["debug_file"], * Logs an error message with an object dump
"ERROR -- " . $_SERVER['REMOTE_ADDR'] . " -- " . $datetime . " -- " . $message . " -- " . print_r($object, true) . "\n", *
FILE_APPEND * @param string $message Error message
); * @param stdClass $object Object being debugged
* @return void
*/
public static function error($message, $object = null) {
if (isset(Hybrid_Auth::$config["debug_mode"]) && in_array(Hybrid_Auth::$config["debug_mode"], array(true, 'info', 'error'), true)) {
$dt = new DateTime('now', new DateTimeZone( 'UTC' ));
file_put_contents(Hybrid_Auth::$config["debug_file"], implode(' -- ', array(
'ERROR',
$_SERVER['REMOTE_ADDR'],
$dt->format(DATE_ATOM),
$message,
print_r($object, true) . PHP_EOL
)), FILE_APPEND);
} }
} }
/**
* Dumps the data in the way suitable to be output in log files for debug purposes
*
* @param mixed $data
*
* @return string
*/
public static function dumpData($data) {
return var_export($data, true);
}
} }

View File

@@ -1,128 +1,126 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
/** /**
* Hybrid_Provider_Adapter is the basic class which Hybrid_Auth will use * Hybrid_Provider_Adapter is the basic class which Hybrid_Auth will use
* to connect users to a given provider. * to connect users to a given provider.
* *
* Basically Hybrid_Provider_Adapter will create a bridge from your php * Basically Hybrid_Provider_Adapter will create a bridge from your php
* application to the provider api. * application to the provider api.
* *
* Hybrid_Auth will automatically load Hybrid_Provider_Adapter and create * Hybrid_Auth will automatically load Hybrid_Provider_Adapter and create
* an instance of it for each authenticated provider. * an instance of it for each authenticated provider.
*/ */
class Hybrid_Provider_Adapter class Hybrid_Provider_Adapter {
{
/** /**
* Provider ID (or unique name) * Provider ID (or unique name)
* @var Numeric/String * @var mixed
*/ */
public $id = NULL ; public $id = null;
/** /**
* Provider adapter specific config * Provider adapter specific config
* @var Array * @var array
*/ */
public $config = NULL ; public $config = null;
/** /**
* Provider adapter extra parameters * Provider adapter extra parameters
* @var array * @var array
*/ */
public $params = array() ; public $params = array();
/** /**
* Provider adapter wrapper path * Provider adapter wrapper path
* @var String * @var string
*/ */
public $wrapper = NULL ; public $wrapper = null;
/** /**
* Provider adapter instance * Provider adapter instance
* @var object * @var Hybrid_Provider_Model
*/ */
public $adapter = NULL ; public $adapter = null;
// --------------------------------------------------------------------
/** /**
* create a new adapter switch IDp name or ID * Create a new adapter switch IDp name or ID
* *
* @param string $id The id or name of the IDp * @param string $id The id or name of the IDp
* @param array $params (optional) required parameters by the adapter * @param array $params (optional) required parameters by the adapter
*/ * @return Hybrid_Provider_Adapter
function factory( $id, $params = array() ) * @throws Exception
{ */
Hybrid_Logger::info( "Enter Hybrid_Provider_Adapter::factory( $id )" ); function factory($id, $params = array()) {
Hybrid_Logger::info("Enter Hybrid_Provider_Adapter::factory( $id )");
# init the adapter config and params # init the adapter config and params
$this->id = $id; $this->id = $id;
$this->params = $params; $this->params = $params;
$this->id = $this->getProviderCiId( $this->id ); $this->id = $this->getProviderCiId($this->id);
$this->config = $this->getConfigById( $this->id ); $this->config = $this->getConfigById($this->id);
# check the IDp id # check the IDp id
if( ! $this->id ){ if (!$this->id) {
throw new Exception( "No provider ID specified.", 2 ); throw new Exception("No provider ID specified.", 2);
} }
# check the IDp config # check the IDp config
if( ! $this->config ){ if (!$this->config) {
throw new Exception( "Unknown Provider ID, check your configuration file.", 3 ); throw new Exception("Unknown Provider ID, check your configuration file.", 3);
} }
# check the IDp adapter is enabled # check the IDp adapter is enabled
if( ! $this->config["enabled"] ){ if (!$this->config["enabled"]) {
throw new Exception( "The provider '{$this->id}' is not enabled.", 3 ); throw new Exception("The provider '{$this->id}' is not enabled.", 3);
} }
# include the adapter wrapper # include the adapter wrapper
if( isset( $this->config["wrapper"] ) && is_array( $this->config["wrapper"] ) ){ if (isset($this->config["wrapper"]) && is_array($this->config["wrapper"])) {
if (isset( $this->config["wrapper"]["path"] )) { if (isset($this->config["wrapper"]["path"])) {
require_once $this->config["wrapper"]["path"]; require_once $this->config["wrapper"]["path"];
} }
if( ! class_exists( $this->config["wrapper"]["class"] ) ){ if (!class_exists($this->config["wrapper"]["class"])) {
throw new Exception( "Unable to load the adapter class.", 3 ); throw new Exception("Unable to load the adapter class.", 3);
} }
$this->wrapper = $this->config["wrapper"]["class"]; $this->wrapper = $this->config["wrapper"]["class"];
} } else {
else{ require_once Hybrid_Auth::$config["path_providers"] . $this->id . ".php";
require_once Hybrid_Auth::$config["path_providers"] . $this->id . ".php" ;
$this->wrapper = "Hybrid_Providers_" . $this->id; $this->wrapper = "Hybrid_Providers_" . $this->id;
} }
# create the adapter instance, and pass the current params and config # create the adapter instance, and pass the current params and config
$this->adapter = new $this->wrapper( $this->id, $this->config, $this->params ); $this->adapter = new $this->wrapper($this->id, $this->config, $this->params);
return $this; return $this;
} }
// --------------------------------------------------------------------
/** /**
* Hybrid_Provider_Adapter::login(), prepare the user session and the authentication request * Hybrid_Provider_Adapter::login(), prepare the user session and the authentication request
* for index.php * for index.php
*/ * @return void
function login() * @throw Exception
{ */
Hybrid_Logger::info( "Enter Hybrid_Provider_Adapter::login( {$this->id} ) " ); function login() {
Hybrid_Logger::info("Enter Hybrid_Provider_Adapter::login( {$this->id} ) ");
if( ! $this->adapter ){ if (!$this->adapter) {
throw new Exception( "Hybrid_Provider_Adapter::login() should not directly used." ); throw new Exception("Hybrid_Provider_Adapter::login() should not directly used.");
} }
// clear all unneeded params // clear all unneeded params
foreach( Hybrid_Auth::$config["providers"] as $idpid => $params ){ foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
Hybrid_Auth::storage()->delete( "hauth_session.{$idpid}.hauth_return_to" ); Hybrid_Auth::storage()->delete("hauth_session.{$idpid}.hauth_return_to");
Hybrid_Auth::storage()->delete( "hauth_session.{$idpid}.hauth_endpoint" ); Hybrid_Auth::storage()->delete("hauth_session.{$idpid}.hauth_endpoint");
Hybrid_Auth::storage()->delete( "hauth_session.{$idpid}.id_provider_params" ); Hybrid_Auth::storage()->delete("hauth_session.{$idpid}.id_provider_params");
} }
// make a fresh start // make a fresh start
@@ -130,9 +128,9 @@ class Hybrid_Provider_Adapter
# get hybridauth base url # get hybridauth base url
if (empty(Hybrid_Auth::$config["base_url"])) { if (empty(Hybrid_Auth::$config["base_url"])) {
// the base url wasn't provide, so we must use the current // the base url wasn't provide, so we must use the current
// url (which makes sense actually) // url (which makes sense actually)
$url = empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off' ? 'http' : 'https'; $url = empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off' ? 'http' : 'https';
$url .= '://' . $_SERVER['HTTP_HOST']; $url .= '://' . $_SERVER['HTTP_HOST'];
$url .= $_SERVER['REQUEST_URI']; $url .= $_SERVER['REQUEST_URI'];
$HYBRID_AUTH_URL_BASE = $url; $HYBRID_AUTH_URL_BASE = $url;
@@ -140,183 +138,184 @@ class Hybrid_Provider_Adapter
$HYBRID_AUTH_URL_BASE = Hybrid_Auth::$config["base_url"]; $HYBRID_AUTH_URL_BASE = Hybrid_Auth::$config["base_url"];
} }
// make sure params is array // make sure params is array
if( !is_array( $this->params ) ){ if (!is_array($this->params)) {
$this->params = array(); $this->params = array();
} }
# we make use of session_id() as storage hash to identify the current user # we make use of session_id() as storage hash to identify the current user
# using session_regenerate_id() will be a problem, but .. # using session_regenerate_id() will be a problem, but ..
$this->params["hauth_token"] = session_id(); $this->params["hauth_token"] = session_id();
# set request timestamp # set request timestamp
$this->params["hauth_time"] = time(); $this->params["hauth_time"] = time();
# for default HybridAuth endpoint url hauth_login_start_url # for default HybridAuth endpoint url hauth_login_start_url
# auth.start required the IDp ID # auth.start required the IDp ID
# auth.time optional login request timestamp # auth.time optional login request timestamp
$this->params["login_start"] = $HYBRID_AUTH_URL_BASE . ( strpos( $HYBRID_AUTH_URL_BASE, '?' ) ? '&' : '?' ) . "hauth.start={$this->id}&hauth.time={$this->params["hauth_time"]}"; $this->params["login_start"] = $HYBRID_AUTH_URL_BASE . ( strpos($HYBRID_AUTH_URL_BASE, '?') ? '&' : '?' ) . "hauth.start={$this->id}&hauth.time={$this->params["hauth_time"]}";
# for default HybridAuth endpoint url hauth_login_done_url # for default HybridAuth endpoint url hauth_login_done_url
# auth.done required the IDp ID # auth.done required the IDp ID
$this->params["login_done"] = $HYBRID_AUTH_URL_BASE . ( strpos( $HYBRID_AUTH_URL_BASE, '?' ) ? '&' : '?' ) . "hauth.done={$this->id}"; $this->params["login_done"] = $HYBRID_AUTH_URL_BASE . ( strpos($HYBRID_AUTH_URL_BASE, '?') ? '&' : '?' ) . "hauth.done={$this->id}";
if( isset( $this->params["hauth_return_to"] ) ){ if (isset($this->params["hauth_return_to"])) {
Hybrid_Auth::storage()->set( "hauth_session.{$this->id}.hauth_return_to", $this->params["hauth_return_to"] ); Hybrid_Auth::storage()->set("hauth_session.{$this->id}.hauth_return_to", $this->params["hauth_return_to"]);
} }
if( isset( $this->params["login_done"] ) ){ if (isset($this->params["login_done"])) {
Hybrid_Auth::storage()->set( "hauth_session.{$this->id}.hauth_endpoint" , $this->params["login_done"] ); Hybrid_Auth::storage()->set("hauth_session.{$this->id}.hauth_endpoint", $this->params["login_done"]);
} }
Hybrid_Auth::storage()->set( "hauth_session.{$this->id}.id_provider_params" , $this->params ); Hybrid_Auth::storage()->set("hauth_session.{$this->id}.id_provider_params", $this->params);
// store config to be used by the end point // store config to be used by the end point
Hybrid_Auth::storage()->config( "CONFIG", Hybrid_Auth::$config ); Hybrid_Auth::storage()->config("CONFIG", Hybrid_Auth::$config);
// move on // move on
Hybrid_Logger::debug( "Hybrid_Provider_Adapter::login( {$this->id} ), redirect the user to login_start URL." ); Hybrid_Logger::debug("Hybrid_Provider_Adapter::login( {$this->id} ), redirect the user to login_start URL.");
Hybrid_Auth::redirect( $this->params["login_start"] ); Hybrid_Auth::redirect($this->params["login_start"]);
} }
// --------------------------------------------------------------------
/** /**
* let hybridauth forget all about the user for the current provider * Let hybridauth forget all about the user for the current provider
*/ * @return bool
function logout() */
{ function logout() {
$this->adapter->logout(); $this->adapter->logout();
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
/** /**
* return true if the user is connected to the current provider * Return true if the user is connected to the current provider
*/ * @return bool
public function isUserConnected() */
{ public function isUserConnected() {
return $this->adapter->isUserConnected(); return $this->adapter->isUserConnected();
} }
// -------------------------------------------------------------------- // --------------------------------------------------------------------
/** /**
* handle : * Call adapter methods defined in the adapter model:
* getUserProfile() * getUserProfile()
* getUserContacts() * getUserContacts()
* getUserActivity() * getUserActivity()
* setUserStatus() * setUserStatus()
*/ *
public function __call( $name, $arguments ) * @param string $name Method name
{ * @param array $arguments Call arguments
Hybrid_Logger::info( "Enter Hybrid_Provider_Adapter::$name(), Provider: {$this->id}" ); * @return mixed
* @throws Exception
*/
public function __call($name, $arguments) {
Hybrid_Logger::info("Enter Hybrid_Provider_Adapter::$name(), Provider: {$this->id}");
if ( ! $this->isUserConnected() ){ if (!$this->isUserConnected()) {
throw new Exception( "User not connected to the provider {$this->id}.", 7 ); throw new Exception("User not connected to the provider {$this->id}.", 7);
}
if ( ! method_exists( $this->adapter, $name ) ){
throw new Exception( "Call to undefined function Hybrid_Providers_{$this->id}::$name()." );
} }
$counter = count( $arguments ); if (!method_exists($this->adapter, $name)) {
if( $counter == 1 ){ throw new Exception("Call to undefined function Hybrid_Providers_{$this->id}::$name().");
return $this->adapter->$name( $arguments[0] ); }
}
elseif( $counter == 2 ){ $counter = count($arguments);
return $this->adapter->$name( $arguments[0], $arguments[1] ); if ($counter == 1) {
} return $this->adapter->$name($arguments[0]);
else{ } elseif ($counter == 2) {
return $this->adapter->$name(); return $this->adapter->$name($arguments[0], $arguments[1]);
} } else {
return $this->adapter->$name();
}
} }
// --------------------------------------------------------------------
/** /**
* If the user is connected, then return the access_token and access_token_secret * If the user is connected, then return the access_token and access_token_secret
* if the provider api use oauth * if the provider api use oauth
*/ *
public function getAccessToken() * <code>
{ * array(
if( ! $this->adapter->isUserConnected() ){ * 'access_token' => '',
Hybrid_Logger::error( "User not connected to the provider." ); * 'access_token_secret' => '',
* 'refresh_token' => '',
throw new Exception( "User not connected to the provider.", 7 ); * 'expires_in' => '',
* 'expires_at' => '',
* )
* </code>
* @return array
*/
public function getAccessToken() {
if (!$this->adapter->isUserConnected()) {
Hybrid_Logger::error("User not connected to the provider.");
throw new Exception("User not connected to the provider.", 7);
} }
return return array(
ARRAY( "access_token" => $this->adapter->token("access_token"), // OAuth access token
"access_token" => $this->adapter->token( "access_token" ) , // OAuth access token "access_token_secret" => $this->adapter->token("access_token_secret"), // OAuth access token secret
"access_token_secret" => $this->adapter->token( "access_token_secret" ), // OAuth access token secret "refresh_token" => $this->adapter->token("refresh_token"), // OAuth refresh token
"refresh_token" => $this->adapter->token( "refresh_token" ) , // OAuth refresh token "expires_in" => $this->adapter->token("expires_in"), // OPTIONAL. The duration in seconds of the access token lifetime
"expires_in" => $this->adapter->token( "expires_in" ) , // OPTIONAL. The duration in seconds of the access token lifetime "expires_at" => $this->adapter->token("expires_at"), // OPTIONAL. Timestamp when the access_token expire. if not provided by the social api, then it should be calculated: expires_at = now + expires_in
"expires_at" => $this->adapter->token( "expires_at" ) , // OPTIONAL. Timestamp when the access_token expire. if not provided by the social api, then it should be calculated: expires_at = now + expires_in );
);
} }
// --------------------------------------------------------------------
/** /**
* Naive getter of the current connected IDp API client * Naive getter of the current connected IDp API client
*/ * @return stdClass
function api() * @throws Exception
{ */
if( ! $this->adapter->isUserConnected() ){ function api() {
Hybrid_Logger::error( "User not connected to the provider." ); if (!$this->adapter->isUserConnected()) {
Hybrid_Logger::error("User not connected to the provider.");
throw new Exception( "User not connected to the provider.", 7 ); throw new Exception("User not connected to the provider.", 7);
} }
return $this->adapter->api; return $this->adapter->api;
} }
// --------------------------------------------------------------------
/** /**
* redirect the user to hauth_return_to (the callback url) * Redirect the user to hauth_return_to (the callback url)
*/ * @return void
function returnToCallbackUrl() */
{ function returnToCallbackUrl() {
// get the stored callback url // get the stored callback url
$callback_url = Hybrid_Auth::storage()->get( "hauth_session.{$this->id}.hauth_return_to" ); $callback_url = Hybrid_Auth::storage()->get("hauth_session.{$this->id}.hauth_return_to");
// remove some unneeded stored data // remove some unneeded stored data
Hybrid_Auth::storage()->delete( "hauth_session.{$this->id}.hauth_return_to" ); Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.hauth_return_to");
Hybrid_Auth::storage()->delete( "hauth_session.{$this->id}.hauth_endpoint" ); Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.hauth_endpoint");
Hybrid_Auth::storage()->delete( "hauth_session.{$this->id}.id_provider_params" ); Hybrid_Auth::storage()->delete("hauth_session.{$this->id}.id_provider_params");
// back to home // back to home
Hybrid_Auth::redirect( $callback_url ); Hybrid_Auth::redirect($callback_url);
} }
// --------------------------------------------------------------------
/** /**
* return the provider config by id * Return the provider config by id
*/ *
function getConfigById( $id ) * @param string $id Config key
{ * @return mixed
if( isset( Hybrid_Auth::$config["providers"][$id] ) ){ */
function getConfigById($id) {
if (isset(Hybrid_Auth::$config["providers"][$id])) {
return Hybrid_Auth::$config["providers"][$id]; return Hybrid_Auth::$config["providers"][$id];
} }
return null;
return NULL;
} }
// --------------------------------------------------------------------
/** /**
* return the provider config by id; insensitive * Return the provider config by id; case insensitive
*/ *
function getProviderCiId( $id ) * @param string $id Provider id
{ * @return mixed
foreach( Hybrid_Auth::$config["providers"] as $idpid => $params ){ */
if( strtolower( $idpid ) == strtolower( $id ) ){ function getProviderCiId($id) {
foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
if (strtolower($idpid) == strtolower($id)) {
return $idpid; return $idpid;
} }
} }
return null;
return NULL;
} }
} }

View File

@@ -1,9 +1,10 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
/** /**
* Hybrid_Provider_Model provide a common interface for supported IDps on HybridAuth. * Hybrid_Provider_Model provide a common interface for supported IDps on HybridAuth.
@@ -19,245 +20,225 @@
* Class Hybrid_Provider_Model_OAuth1 for providers that uses the OAuth 1 protocol. * Class Hybrid_Provider_Model_OAuth1 for providers that uses the OAuth 1 protocol.
* Class Hybrid_Provider_Model_OAuth2 for providers that uses the OAuth 2 protocol. * Class Hybrid_Provider_Model_OAuth2 for providers that uses the OAuth 2 protocol.
*/ */
abstract class Hybrid_Provider_Model abstract class Hybrid_Provider_Model {
{
/**
* IDp ID (or unique name)
* @var Numeric/String
*/
public $providerId = NULL;
/** /**
* specific provider adapter config * IDp ID (or unique name)
* @var array * @var mixed
*/ */
public $config = NULL; public $providerId = null;
/** /**
* provider extra parameters * Specific provider adapter config
* @var array * @var array
*/ */
public $params = NULL; public $config = null;
/** /**
* Endpoint URL for that provider * Provider extra parameters
* @var String * @var array
*/ */
public $endpoint = NULL; public $params = null;
/** /**
* Hybrid_User obj, represents the current loggedin user * Endpoint URL for that provider
* @var object * @var string
*/ */
public $user = NULL; public $endpoint = null;
/** /**
* the provider api client (optional) * Hybrid_User obj, represents the current loggedin user
* @var String * @var Hybrid_User
*/ */
public $api = NULL; public $user = null;
/** /**
* Common providers adapter constructor * The provider api client (optional)
* @param Numeric/String $providerId * @var stdClass
* @param Array $config */
* @param Array $params public $api = null;
*/
function __construct( $providerId, $config, $params = NULL )
{
# init the IDp adapter parameters, get them from the cache if possible
if( ! $params ){
$this->params = Hybrid_Auth::storage()->get( "hauth_session.$providerId.id_provider_params" );
}
else{
$this->params = $params;
}
// idp id /**
$this->providerId = $providerId; * Model should use "gzip,deflate" for CURLOPT_ENCODING
* @var stdClass
*/
public $compressed = false;
// set HybridAuth endpoint for this provider /**
$this->endpoint = Hybrid_Auth::storage()->get( "hauth_session.$providerId.hauth_endpoint" ); * Common providers adapter constructor
*
* @param mixed $providerId Provider ID
* @param array $config Provider adapter config
* @param array $params Provider extra params
*/
function __construct($providerId, $config, $params = null) {
# init the IDp adapter parameters, get them from the cache if possible
if (!$params) {
$this->params = Hybrid_Auth::storage()->get("hauth_session.$providerId.id_provider_params");
} else {
$this->params = $params;
}
// idp config // idp id
$this->config = $config; $this->providerId = $providerId;
// new user instance // set HybridAuth endpoint for this provider
$this->user = new Hybrid_User(); $this->endpoint = Hybrid_Auth::storage()->get("hauth_session.$providerId.hauth_endpoint");
$this->user->providerId = $providerId;
// initialize the current provider adapter // idp config
$this->initialize(); $this->config = $config;
Hybrid_Logger::debug( "Hybrid_Provider_Model::__construct( $providerId ) initialized. dump current adapter instance: ", serialize( $this ) ); // new user instance
} $this->user = new Hybrid_User();
$this->user->providerId = $providerId;
// -------------------------------------------------------------------- // initialize the current provider adapter
$this->initialize();
/** Hybrid_Logger::debug("Hybrid_Provider_Model::__construct( $providerId ) initialized. dump current adapter instance: ", serialize($this));
* IDp wrappers initializer }
*
* The main job of wrappers initializer is to performs (depend on the IDp api client it self):
* - include some libs needed by this provider,
* - check IDp key and secret,
* - set some needed parameters (stored in $this->params) by this IDp api client
* - create and setup an instance of the IDp api client on $this->api
*/
abstract protected function initialize();
// -------------------------------------------------------------------- /**
* IDp wrappers initializer
*
* The main job of wrappers initializer is to performs (depend on the IDp api client it self):
* - include some libs needed by this provider,
* - check IDp key and secret,
* - set some needed parameters (stored in $this->params) by this IDp api client
* - create and setup an instance of the IDp api client on $this->api
*
* @return void
* @throws Exception
*/
abstract protected function initialize();
/** /**
* begin login * Begin login
*/ *
abstract protected function loginBegin(); * @return void
* @throws Exception
*/
abstract protected function loginBegin();
// -------------------------------------------------------------------- /**
* Finish login
* @return void
* @throws Exception
*/
abstract protected function loginFinish();
/** /**
* finish login * Generic logout, just erase current provider adapter stored data to let Hybrid_Auth all forget about it
*/ * @return bool
abstract protected function loginFinish(); */
function logout() {
Hybrid_Logger::info("Enter [{$this->providerId}]::logout()");
$this->clearTokens();
return true;
}
// -------------------------------------------------------------------- /**
* Grab the user profile from the IDp api client
* @return Hybrid_User_Profile
* @throw Exception
*/
function getUserProfile() {
Hybrid_Logger::error("HybridAuth do not provide users contacts list for {$this->providerId} yet.");
throw new Exception("Provider does not support this feature.", 8);
}
/** /**
* generic logout, just erase current provider adapter stored data to let Hybrid_Auth all forget about it * Load the current logged in user contacts list from the IDp api client
*/ * @return Hybrid_User_Contact[]
function logout() * @throws Exception
{ */
Hybrid_Logger::info( "Enter [{$this->providerId}]::logout()" ); function getUserContacts() {
Hybrid_Logger::error("HybridAuth do not provide users contacts list for {$this->providerId} yet.");
throw new Exception("Provider does not support this feature.", 8);
}
$this->clearTokens(); /**
* Return the user activity stream
* @return Hybrid_User_Activity[]
* @throws Exception
*/
function getUserActivity($stream) {
Hybrid_Logger::error("HybridAuth do not provide user's activity stream for {$this->providerId} yet.");
throw new Exception("Provider does not support this feature.", 8);
}
return TRUE; /**
} * Set user status
* @return mixed Provider response
* @throws Exception
*/
function setUserStatus($status) {
Hybrid_Logger::error("HybridAuth do not provide user's activity stream for {$this->providerId} yet.");
throw new Exception("Provider does not support this feature.", 8);
}
// -------------------------------------------------------------------- /**
* Return the user status
* @return mixed Provider response
* @throws Exception
*/
function getUserStatus($statusid) {
Hybrid_Logger::error("HybridAuth do not provide user's status for {$this->providerId} yet.");
throw new Exception("Provider does not support this feature.", 8);
}
/** /**
* grab the user profile from the IDp api client * Return true if the user is connected to the current provider
*/ * @return bool
function getUserProfile() */
{ public function isUserConnected() {
Hybrid_Logger::error( "HybridAuth do not provide users contacts list for {$this->providerId} yet." ); return (bool) Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.is_logged_in");
}
throw new Exception( "Provider does not support this feature.", 8 );
}
// -------------------------------------------------------------------- /**
* Set user to connected
* @return void
*/
public function setUserConnected() {
Hybrid_Logger::info("Enter [{$this->providerId}]::setUserConnected()");
Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.is_logged_in", 1);
}
/** /**
* load the current logged in user contacts list from the IDp api client * Set user to unconnected
*/ * @return void
function getUserContacts() */
{ public function setUserUnconnected() {
Hybrid_Logger::error( "HybridAuth do not provide users contacts list for {$this->providerId} yet." ); Hybrid_Logger::info("Enter [{$this->providerId}]::setUserUnconnected()");
Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.is_logged_in", 0);
throw new Exception( "Provider does not support this feature.", 8 ); }
}
// -------------------------------------------------------------------- /**
* Get or set a token
* @return string
*/
public function token($token, $value = null) {
if ($value === null) {
return Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.token.$token");
} else {
Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.token.$token", $value);
}
}
/** /**
* return the user activity stream * Delete a stored token
*/ * @return void
function getUserActivity( $stream ) */
{ public function deleteToken($token) {
Hybrid_Logger::error( "HybridAuth do not provide user's activity stream for {$this->providerId} yet." ); Hybrid_Auth::storage()->delete("hauth_session.{$this->providerId}.token.$token");
}
throw new Exception( "Provider does not support this feature.", 8 );
}
// -------------------------------------------------------------------- /**
* Clear all existent tokens for this provider
* @return void
*/
public function clearTokens() {
Hybrid_Auth::storage()->deleteMatch("hauth_session.{$this->providerId}.");
}
/**
* set user status
*/
function setUserStatus( $status )
{
Hybrid_Logger::error( "HybridAuth do not provide user's activity stream for {$this->providerId} yet." );
throw new Exception( "Provider does not support this feature.", 8 );
}
/**
* return the user status
*/
function getUserStatus( $statusid )
{
Hybrid_Logger::error( "HybridAuth do not provide user's status for {$this->providerId} yet." );
throw new Exception( "Provider does not support this feature.", 8 );
}
// --------------------------------------------------------------------
/**
* return true if the user is connected to the current provider
*/
public function isUserConnected()
{
return (bool) Hybrid_Auth::storage()->get( "hauth_session.{$this->providerId}.is_logged_in" );
}
// --------------------------------------------------------------------
/**
* set user to connected
*/
public function setUserConnected()
{
Hybrid_Logger::info( "Enter [{$this->providerId}]::setUserConnected()" );
Hybrid_Auth::storage()->set( "hauth_session.{$this->providerId}.is_logged_in", 1 );
}
// --------------------------------------------------------------------
/**
* set user to unconnected
*/
public function setUserUnconnected()
{
Hybrid_Logger::info( "Enter [{$this->providerId}]::setUserUnconnected()" );
Hybrid_Auth::storage()->set( "hauth_session.{$this->providerId}.is_logged_in", 0 );
}
// --------------------------------------------------------------------
/**
* get or set a token
*/
public function token( $token, $value = NULL )
{
if( $value === NULL ){
return Hybrid_Auth::storage()->get( "hauth_session.{$this->providerId}.token.$token" );
}
else{
Hybrid_Auth::storage()->set( "hauth_session.{$this->providerId}.token.$token", $value );
}
}
// --------------------------------------------------------------------
/**
* delete a stored token
*/
public function deleteToken( $token )
{
Hybrid_Auth::storage()->delete( "hauth_session.{$this->providerId}.token.$token" );
}
// --------------------------------------------------------------------
/**
* clear all existent tokens for this provider
*/
public function clearTokens()
{
Hybrid_Auth::storage()->deleteMatch( "hauth_session.{$this->providerId}." );
}
} }

View File

@@ -1,14 +1,15 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
/** /**
* To implement an OAuth 1 based service provider, Hybrid_Provider_Model_OAuth1 * To implement an OAuth 1 based service provider, Hybrid_Provider_Model_OAuth1
* can be used to save the hassle of the authentication flow. * can be used to save the hassle of the authentication flow.
* *
* Each class that inherit from Hybrid_Provider_Model_OAuth1 have to implement * Each class that inherit from Hybrid_Provider_Model_OAuth1 have to implement
* at least 2 methods: * at least 2 methods:
* Hybrid_Providers_{provider_name}::initialize() to setup the provider api end-points urls * Hybrid_Providers_{provider_name}::initialize() to setup the provider api end-points urls
@@ -17,155 +18,157 @@
* Hybrid_Provider_Model_OAuth1 use OAuth1Client v0.1 which can be found on * Hybrid_Provider_Model_OAuth1 use OAuth1Client v0.1 which can be found on
* Hybrid/thirdparty/OAuth/OAuth1Client.php * Hybrid/thirdparty/OAuth/OAuth1Client.php
*/ */
class Hybrid_Provider_Model_OAuth1 extends Hybrid_Provider_Model class Hybrid_Provider_Model_OAuth1 extends Hybrid_Provider_Model {
{
/** /**
* request_tokens as received from provider * Provider API client
* @var object * @var OAuth1Client
*/
public $api = null;
/**
* Request_tokens as received from provider
* @var stdClas
*/ */
public $request_tokens_raw = null; public $request_tokens_raw = null;
/** /**
* access_tokens as received from provider * Access_tokens as received from provider
* @var object * @var stdClass
*/ */
public $access_tokens_raw = null; public $access_tokens_raw = null;
/** /**
* Try to get the error message from provider api * Try to get the error message from provider api
* @param Numeric $code *
*/ * @param int $code Error code
function errorMessageByStatus( $code = null ) { * @return string
$http_status_codes = ARRAY( */
function errorMessageByStatus($code = null) {
$http_status_codes = array(
200 => "OK: Success!", 200 => "OK: Success!",
304 => "Not Modified: There was no new data to return.", 304 => "Not Modified: There was no new data to return.",
400 => "Bad Request: The request was invalid.", 400 => "Bad Request: The request was invalid.",
401 => "Unauthorized.", 401 => "Unauthorized.",
403 => "Forbidden: The request is understood, but it has been refused.", 403 => "Forbidden: The request is understood, but it has been refused.",
404 => "Not Found: The URI requested is invalid or the resource requested does not exists.", 404 => "Not Found: The URI requested is invalid or the resource requested does not exists.",
406 => "Not Acceptable.", 406 => "Not Acceptable.",
500 => "Internal Server Error: Something is broken.", 500 => "Internal Server Error: Something is broken.",
502 => "Bad Gateway.", 502 => "Bad Gateway.",
503 => "Service Unavailable." 503 => "Service Unavailable."
); );
if( ! $code && $this->api ) if (!$code && $this->api) {
$code = $this->api->http_code; $code = $this->api->http_code;
}
if( isset( $http_status_codes[ $code ] ) ) if (isset($http_status_codes[$code])) {
return $code . " " . $http_status_codes[ $code ]; return $code . " " . $http_status_codes[$code];
}
} }
// --------------------------------------------------------------------
/** /**
* adapter initializer * {@inheritdoc}
*/ */
function initialize() function initialize() {
{
// 1 - check application credentials // 1 - check application credentials
if ( ! $this->config["keys"]["key"] || ! $this->config["keys"]["secret"] ){ if (!$this->config["keys"]["key"] || !$this->config["keys"]["secret"]) {
throw new Exception( "Your application key and secret are required in order to connect to {$this->providerId}.", 4 ); throw new Exception("Your application key and secret are required in order to connect to {$this->providerId}.", 4);
} }
// 2 - include OAuth lib and client // 2 - include OAuth lib and client
require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth.php"; if (! class_exists('OAuthConsumer') ) {
require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth1Client.php"; require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth.php";
}
require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth1Client.php";
// 3.1 - setup access_token if any stored // 3.1 - setup access_token if any stored
if( $this->token( "access_token" ) ){ if ($this->token("access_token")) {
$this->api = new OAuth1Client( $this->api = new OAuth1Client(
$this->config["keys"]["key"], $this->config["keys"]["secret"], $this->config["keys"]["key"], $this->config["keys"]["secret"], $this->token("access_token"), $this->token("access_token_secret")
$this->token( "access_token" ), $this->token( "access_token_secret" )
); );
} }
// 3.2 - setup request_token if any stored, in order to exchange with an access token // 3.2 - setup request_token if any stored, in order to exchange with an access token
elseif( $this->token( "request_token" ) ){ elseif ($this->token("request_token")) {
$this->api = new OAuth1Client( $this->api = new OAuth1Client(
$this->config["keys"]["key"], $this->config["keys"]["secret"], $this->config["keys"]["key"], $this->config["keys"]["secret"], $this->token("request_token"), $this->token("request_token_secret")
$this->token( "request_token" ), $this->token( "request_token_secret" )
); );
} }
// 3.3 - instanciate OAuth client with client credentials // 3.3 - instanciate OAuth client with client credentials
else{ else {
$this->api = new OAuth1Client( $this->config["keys"]["key"], $this->config["keys"]["secret"] ); $this->api = new OAuth1Client($this->config["keys"]["key"], $this->config["keys"]["secret"]);
} }
// Set curl proxy if exist // Set curl proxy if exist
if( isset( Hybrid_Auth::$config["proxy"] ) ){ if (isset(Hybrid_Auth::$config["proxy"])) {
$this->api->curl_proxy = Hybrid_Auth::$config["proxy"]; $this->api->curl_proxy = Hybrid_Auth::$config["proxy"];
} }
} }
// --------------------------------------------------------------------
/** /**
* begin login step * {@inheritdoc}
*/ */
function loginBegin() function loginBegin() {
{ $tokens = $this->api->requestToken($this->endpoint);
$tokens = $this->api->requestToken( $this->endpoint );
// request tokens as received from provider // request tokens as received from provider
$this->request_tokens_raw = $tokens; $this->request_tokens_raw = $tokens;
// check the last HTTP status code returned // check the last HTTP status code returned
if ( $this->api->http_code != 200 ){ if ($this->api->http_code != 200) {
throw new Exception( "Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ), 5 ); throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
} }
if ( ! isset( $tokens["oauth_token"] ) ){ if (!isset($tokens["oauth_token"])) {
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid oauth token.", 5 ); throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth token.", 5);
} }
$this->token( "request_token" , $tokens["oauth_token"] ); $this->token("request_token", $tokens["oauth_token"]);
$this->token( "request_token_secret", $tokens["oauth_token_secret"] ); $this->token("request_token_secret", $tokens["oauth_token_secret"]);
# redirect the user to the provider authentication url # redirect the user to the provider authentication url
Hybrid_Auth::redirect( $this->api->authorizeUrl( $tokens ) ); Hybrid_Auth::redirect($this->api->authorizeUrl($tokens));
} }
// --------------------------------------------------------------------
/** /**
* finish login step * {@inheritdoc}
*/ */
function loginFinish() function loginFinish() {
{ $oauth_token = (array_key_exists('oauth_token', $_REQUEST)) ? $_REQUEST['oauth_token'] : "";
$oauth_token = (array_key_exists('oauth_token',$_REQUEST))?$_REQUEST['oauth_token']:""; $oauth_verifier = (array_key_exists('oauth_verifier', $_REQUEST)) ? $_REQUEST['oauth_verifier'] : "";
$oauth_verifier = (array_key_exists('oauth_verifier',$_REQUEST))?$_REQUEST['oauth_verifier']:"";
if ( ! $oauth_token || ! $oauth_verifier ){ if (!$oauth_token || !$oauth_verifier) {
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid oauth verifier.", 5 ); throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth verifier.", 5);
} }
// request an access token // request an access token
$tokens = $this->api->accessToken( $oauth_verifier ); $tokens = $this->api->accessToken($oauth_verifier);
// access tokens as received from provider // access tokens as received from provider
$this->access_tokens_raw = $tokens; $this->access_tokens_raw = $tokens;
// check the last HTTP status code returned // check the last HTTP status code returned
if ( $this->api->http_code != 200 ){ if ($this->api->http_code != 200) {
throw new Exception( "Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ), 5 ); throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
} }
// we should have an access_token, or else, something has gone wrong // we should have an access_token, or else, something has gone wrong
if ( ! isset( $tokens["oauth_token"] ) ){ if (!isset($tokens["oauth_token"])) {
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid access token.", 5 ); throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5);
} }
// we no more need to store request tokens // we no more need to store request tokens
$this->deleteToken( "request_token" ); $this->deleteToken("request_token");
$this->deleteToken( "request_token_secret" ); $this->deleteToken("request_token_secret");
// store access_token for later user // store access_token for later user
$this->token( "access_token" , $tokens['oauth_token'] ); $this->token("access_token", $tokens['oauth_token']);
$this->token( "access_token_secret" , $tokens['oauth_token_secret'] ); $this->token("access_token_secret", $tokens['oauth_token_secret']);
// set user as logged in to the current provider // set user as logged in to the current provider
$this->setUserConnected(); $this->setUserConnected();
} }
} }

View File

@@ -1,14 +1,15 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
/** /**
* To implement an OAuth 2 based service provider, Hybrid_Provider_Model_OAuth2 * To implement an OAuth 2 based service provider, Hybrid_Provider_Model_OAuth2
* can be used to save the hassle of the authentication flow. * can be used to save the hassle of the authentication flow.
* *
* Each class that inherit from Hybrid_Provider_Model_OAuth2 have to implement * Each class that inherit from Hybrid_Provider_Model_OAuth2 have to implement
* at least 2 methods: * at least 2 methods:
* Hybrid_Providers_{provider_name}::initialize() to setup the provider api end-points urls * Hybrid_Providers_{provider_name}::initialize() to setup the provider api end-points urls
@@ -17,164 +18,167 @@
* Hybrid_Provider_Model_OAuth2 use OAuth2Client v0.1 which can be found on * Hybrid_Provider_Model_OAuth2 use OAuth2Client v0.1 which can be found on
* Hybrid/thirdparty/OAuth/OAuth2Client.php * Hybrid/thirdparty/OAuth/OAuth2Client.php
*/ */
class Hybrid_Provider_Model_OAuth2 extends Hybrid_Provider_Model class Hybrid_Provider_Model_OAuth2 extends Hybrid_Provider_Model {
{
/**
* default permissions
* @var string
*/
public $scope = "";
/** /**
* Try to get the error message from provider api * Default permissions
* @param Numeric $code * @var string
*/ */
function errorMessageByStatus( $code = null ) { public $scope = "";
$http_status_codes = ARRAY(
200 => "OK: Success!",
304 => "Not Modified: There was no new data to return.",
400 => "Bad Request: The request was invalid.",
401 => "Unauthorized.",
403 => "Forbidden: The request is understood, but it has been refused.",
404 => "Not Found: The URI requested is invalid or the resource requested does not exists.",
406 => "Not Acceptable.",
500 => "Internal Server Error: Something is broken.",
502 => "Bad Gateway.",
503 => "Service Unavailable."
);
if( ! $code && $this->api ) /**
$code = $this->api->http_code; * Provider API wrapper
* @var OAuth2Client
*/
public $api = null;
if( isset( $http_status_codes[ $code ] ) ) /**
return $code . " " . $http_status_codes[ $code ]; * Try to get the error message from provider api
} *
* @param int $code Error code
* @return string
*/
function errorMessageByStatus($code = null) {
$http_status_codes = array(
200 => "OK: Success!",
304 => "Not Modified: There was no new data to return.",
400 => "Bad Request: The request was invalid.",
401 => "Unauthorized.",
403 => "Forbidden: The request is understood, but it has been refused.",
404 => "Not Found: The URI requested is invalid or the resource requested does not exists.",
406 => "Not Acceptable.",
500 => "Internal Server Error: Something is broken.",
502 => "Bad Gateway.",
503 => "Service Unavailable."
);
// -------------------------------------------------------------------- if (!$code && $this->api) {
$code = $this->api->http_code;
}
/** if (isset($http_status_codes[$code])) {
* adapter initializer return $code . " " . $http_status_codes[$code];
*/ }
function initialize() }
{
if ( ! $this->config["keys"]["id"] || ! $this->config["keys"]["secret"] ){
throw new Exception( "Your application id and secret are required in order to connect to {$this->providerId}.", 4 );
}
// override requested scope /**
if( isset( $this->config["scope"] ) && ! empty( $this->config["scope"] ) ){ * Adapter initializer
$this->scope = $this->config["scope"]; */
} function initialize() {
if (!$this->config["keys"]["id"] || !$this->config["keys"]["secret"]) {
throw new Exception("Your application id and secret are required in order to connect to {$this->providerId}.", 4);
}
// include OAuth2 client // override requested scope
require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth2Client.php"; if (isset($this->config["scope"]) && !empty($this->config["scope"])) {
$this->scope = $this->config["scope"];
}
// create a new OAuth2 client instance // include OAuth2 client
$this->api = new OAuth2Client( $this->config["keys"]["id"], $this->config["keys"]["secret"], $this->endpoint ); require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth2Client.php";
// If we have an access token, set it // create a new OAuth2 client instance
if( $this->token( "access_token" ) ){ $this->api = new OAuth2Client($this->config["keys"]["id"], $this->config["keys"]["secret"], $this->endpoint, $this->compressed);
$this->api->access_token = $this->token( "access_token" );
$this->api->refresh_token = $this->token( "refresh_token" );
$this->api->access_token_expires_in = $this->token( "expires_in" );
$this->api->access_token_expires_at = $this->token( "expires_at" );
}
// Set curl proxy if exist // If we have an access token, set it
if( isset( Hybrid_Auth::$config["proxy"] ) ){ if ($this->token("access_token")) {
$this->api->curl_proxy = Hybrid_Auth::$config["proxy"]; $this->api->access_token = $this->token("access_token");
} $this->api->refresh_token = $this->token("refresh_token");
} $this->api->access_token_expires_in = $this->token("expires_in");
$this->api->access_token_expires_at = $this->token("expires_at");
}
// -------------------------------------------------------------------- // Set curl proxy if exist
if (isset(Hybrid_Auth::$config["proxy"])) {
$this->api->curl_proxy = Hybrid_Auth::$config["proxy"];
}
}
/** /**
* begin login step * {@inheritdoc}
*/ */
function loginBegin() function loginBegin() {
{ // redirect the user to the provider authentication url
// redirect the user to the provider authentication url Hybrid_Auth::redirect($this->api->authorizeUrl(array("scope" => $this->scope)));
Hybrid_Auth::redirect( $this->api->authorizeUrl( array( "scope" => $this->scope ) ) ); }
}
// -------------------------------------------------------------------- /**
* {@inheritdoc}
*/
function loginFinish() {
$error = (array_key_exists('error', $_REQUEST)) ? $_REQUEST['error'] : "";
/** // check for errors
* finish login step if ($error) {
*/ throw new Exception("Authentication failed! {$this->providerId} returned an error: $error", 5);
function loginFinish() }
{
$error = (array_key_exists('error',$_REQUEST))?$_REQUEST['error']:"";
// check for errors // try to authenticate user
if ( $error ){ $code = (array_key_exists('code', $_REQUEST)) ? $_REQUEST['code'] : "";
throw new Exception( "Authentication failed! {$this->providerId} returned an error: $error", 5 );
}
// try to authenticate user try {
$code = (array_key_exists('code',$_REQUEST))?$_REQUEST['code']:""; $this->api->authenticate($code);
} catch (Exception $e) {
throw new Exception("User profile request failed! {$this->providerId} returned an error: $e", 6);
}
try{ // check if authenticated
$this->api->authenticate( $code ); if (!$this->api->access_token) {
} throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5);
catch( Exception $e ){ }
throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
}
// check if authenticated // store tokens
if ( ! $this->api->access_token ){ $this->token("access_token", $this->api->access_token);
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid access token.", 5 ); $this->token("refresh_token", $this->api->refresh_token);
} $this->token("expires_in", $this->api->access_token_expires_in);
$this->token("expires_at", $this->api->access_token_expires_at);
// store tokens // set user connected locally
$this->token( "access_token" , $this->api->access_token ); $this->setUserConnected();
$this->token( "refresh_token", $this->api->refresh_token ); }
$this->token( "expires_in" , $this->api->access_token_expires_in );
$this->token( "expires_at" , $this->api->access_token_expires_at );
// set user connected locally /**
$this->setUserConnected(); * {@inheritdoc}
} */
function refreshToken() {
function refreshToken() // have an access token?
{ if ($this->api->access_token) {
// have an access token?
if( $this->api->access_token ){
// have to refresh? // have to refresh?
if( $this->api->refresh_token && $this->api->access_token_expires_at ){ if ($this->api->refresh_token && $this->api->access_token_expires_at) {
// expired? // expired?
if( $this->api->access_token_expires_at <= time() ){ if ($this->api->access_token_expires_at <= time()) {
$response = $this->api->refreshToken( array( "refresh_token" => $this->api->refresh_token ) ); $response = $this->api->refreshToken(array("refresh_token" => $this->api->refresh_token));
if( ! isset( $response->access_token ) || ! $response->access_token ){ if (!isset($response->access_token) || !$response->access_token) {
// set the user as disconnected at this point and throw an exception // set the user as disconnected at this point and throw an exception
$this->setUserUnconnected(); $this->setUserUnconnected();
throw new Exception( "The Authorization Service has return an invalid response while requesting a new access token. " . (string) $response->error ); throw new Exception("The Authorization Service has return an invalid response while requesting a new access token. " . (string) $response->error);
} }
// set new access_token // set new access_token
$this->api->access_token = $response->access_token; $this->api->access_token = $response->access_token;
if( isset( $response->refresh_token ) ) if (isset($response->refresh_token))
$this->api->refresh_token = $response->refresh_token; $this->api->refresh_token = $response->refresh_token;
if( isset( $response->expires_in ) ){ if (isset($response->expires_in)) {
$this->api->access_token_expires_in = $response->expires_in; $this->api->access_token_expires_in = $response->expires_in;
// even given by some idp, we should calculate this // even given by some idp, we should calculate this
$this->api->access_token_expires_at = time() + $response->expires_in; $this->api->access_token_expires_at = time() + $response->expires_in;
} }
} }
} }
// re store tokens
$this->token("access_token", $this->api->access_token);
$this->token("refresh_token", $this->api->refresh_token);
$this->token("expires_in", $this->api->access_token_expires_in);
$this->token("expires_at", $this->api->access_token_expires_at);
}
}
// re store tokens
$this->token( "access_token" , $this->api->access_token );
$this->token( "refresh_token", $this->api->refresh_token );
$this->token( "expires_in" , $this->api->access_token_expires_in );
$this->token( "expires_at" , $this->api->access_token_expires_at );
}
}
} }

View File

@@ -1,9 +1,10 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
/** /**
* To implement an OpenID based service provider, Hybrid_Provider_Model_OpenID * To implement an OpenID based service provider, Hybrid_Provider_Model_OpenID
@@ -15,22 +16,25 @@
* Hybrid_Provider_Model_OpenID use LightOpenID lib which can be found on * Hybrid_Provider_Model_OpenID use LightOpenID lib which can be found on
* Hybrid/thirdparty/OpenID/LightOpenID.php * Hybrid/thirdparty/OpenID/LightOpenID.php
*/ */
class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model {
{
/**
* Provider API client
* @var LightOpenID
*/
public $api = null;
/** /**
* Openid provider identifier * Openid provider identifier
* @var string * @var string
*/ */
public $openidIdentifier = ""; public $openidIdentifier = "";
// --------------------------------------------------------------------
/** /**
* adapter initializer * {@inheritdoc}
*/ */
function initialize() function initialize() {
{ if (isset($this->params["openid_identifier"])) {
if( isset( $this->params["openid_identifier"] ) ){
$this->openidIdentifier = $this->params["openid_identifier"]; $this->openidIdentifier = $this->params["openid_identifier"];
} }
@@ -38,117 +42,106 @@ class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model
require_once Hybrid_Auth::$config["path_libraries"] . "OpenID/LightOpenID.php"; require_once Hybrid_Auth::$config["path_libraries"] . "OpenID/LightOpenID.php";
// An error was occurring when proxy wasn't set. Not sure where proxy was meant to be set/initialized. // An error was occurring when proxy wasn't set. Not sure where proxy was meant to be set/initialized.
Hybrid_Auth::$config['proxy'] = isset(Hybrid_Auth::$config['proxy'])?Hybrid_Auth::$config['proxy']:''; Hybrid_Auth::$config['proxy'] = isset(Hybrid_Auth::$config['proxy']) ? Hybrid_Auth::$config['proxy'] : '';
$hostPort = parse_url( Hybrid_Auth::$config["base_url"], PHP_URL_PORT); $hostPort = parse_url(Hybrid_Auth::$config["base_url"], PHP_URL_PORT);
$hostUrl = parse_url( Hybrid_Auth::$config["base_url"], PHP_URL_HOST); $hostUrl = parse_url(Hybrid_Auth::$config["base_url"], PHP_URL_HOST);
// Check for port on url // Check for port on url
if($hostPort) { if ($hostPort) {
$hostUrl .= ':'.$hostPort; $hostUrl .= ':' . $hostPort;
} }
$this->api = new LightOpenID( $hostUrl, Hybrid_Auth::$config["proxy"] ); $this->api = new LightOpenID($hostUrl, Hybrid_Auth::$config["proxy"]);
} }
// --------------------------------------------------------------------
/** /**
* begin login step * {@inheritdoc}
*/ */
function loginBegin() function loginBegin() {
{ if (empty($this->openidIdentifier)) {
if( empty( $this->openidIdentifier ) ){ throw new Exception("OpenID adapter require the identity provider identifier 'openid_identifier' as an extra parameter.", 4);
throw new Exception( "OpenID adapter require the identity provider identifier 'openid_identifier' as an extra parameter.", 4 );
} }
$this->api->identity = $this->openidIdentifier; $this->api->identity = $this->openidIdentifier;
$this->api->returnUrl = $this->endpoint; $this->api->returnUrl = $this->endpoint;
$this->api->required = ARRAY( $this->api->required = array(
'namePerson/first' , 'namePerson/first',
'namePerson/last' , 'namePerson/last',
'namePerson/friendly' , 'namePerson/friendly',
'namePerson' , 'namePerson',
'contact/email',
'contact/email' , 'birthDate',
'birthDate/birthDay',
'birthDate' , 'birthDate/birthMonth',
'birthDate/birthDay' , 'birthDate/birthYear',
'birthDate/birthMonth' , 'person/gender',
'birthDate/birthYear' , 'pref/language',
'person/gender' ,
'pref/language' ,
'contact/postalCode/home', 'contact/postalCode/home',
'contact/city/home' , 'contact/city/home',
'contact/country/home' , 'contact/country/home',
'media/image/default',
'media/image/default' ,
); );
# redirect the user to the provider authentication url # redirect the user to the provider authentication url
Hybrid_Auth::redirect( $this->api->authUrl() ); Hybrid_Auth::redirect($this->api->authUrl());
} }
// --------------------------------------------------------------------
/** /**
* finish login step * {@inheritdoc}
*/ */
function loginFinish() function loginFinish() {
{
# if user don't grant access of their data to your site, halt with an Exception # if user don't grant access of their data to your site, halt with an Exception
if( $this->api->mode == 'cancel'){ if ($this->api->mode == 'cancel') {
throw new Exception( "Authentication failed! User has canceled authentication!", 5 ); throw new Exception("Authentication failed! User has canceled authentication!", 5);
} }
# if something goes wrong # if something goes wrong
if( ! $this->api->validate() ){ if (!$this->api->validate()) {
throw new Exception( "Authentication failed. Invalid request received!", 5 ); throw new Exception("Authentication failed. Invalid request received!", 5);
} }
# fetch received user data # fetch received user data
$response = $this->api->getAttributes(); $response = $this->api->getAttributes();
# store the user profile # store the user profile
$this->user->profile->identifier = $this->api->identity; $this->user->profile->identifier = $this->api->identity;
$this->user->profile->firstName = (array_key_exists("namePerson/first",$response))?$response["namePerson/first"]:""; $this->user->profile->firstName = (array_key_exists("namePerson/first", $response)) ? $response["namePerson/first"] : "";
$this->user->profile->lastName = (array_key_exists("namePerson/last",$response))?$response["namePerson/last"]:""; $this->user->profile->lastName = (array_key_exists("namePerson/last", $response)) ? $response["namePerson/last"] : "";
$this->user->profile->displayName = (array_key_exists("namePerson",$response))?$response["namePerson"]:""; $this->user->profile->displayName = (array_key_exists("namePerson", $response)) ? $response["namePerson"] : "";
$this->user->profile->email = (array_key_exists("contact/email",$response))?$response["contact/email"]:""; $this->user->profile->email = (array_key_exists("contact/email", $response)) ? $response["contact/email"] : "";
$this->user->profile->language = (array_key_exists("pref/language",$response))?$response["pref/language"]:""; $this->user->profile->language = (array_key_exists("pref/language", $response)) ? $response["pref/language"] : "";
$this->user->profile->country = (array_key_exists("contact/country/home",$response))?$response["contact/country/home"]:""; $this->user->profile->country = (array_key_exists("contact/country/home", $response)) ? $response["contact/country/home"] : "";
$this->user->profile->zip = (array_key_exists("contact/postalCode/home",$response))?$response["contact/postalCode/home"]:""; $this->user->profile->zip = (array_key_exists("contact/postalCode/home", $response)) ? $response["contact/postalCode/home"] : "";
$this->user->profile->gender = (array_key_exists("person/gender",$response))?$response["person/gender"]:""; $this->user->profile->gender = (array_key_exists("person/gender", $response)) ? $response["person/gender"] : "";
$this->user->profile->photoURL = (array_key_exists("media/image/default",$response))?$response["media/image/default"]:""; $this->user->profile->photoURL = (array_key_exists("media/image/default", $response)) ? $response["media/image/default"] : "";
$this->user->profile->birthDay = (array_key_exists("birthDate/birthDay",$response))?$response["birthDate/birthDay"]:""; $this->user->profile->birthDay = (array_key_exists("birthDate/birthDay", $response)) ? $response["birthDate/birthDay"] : "";
$this->user->profile->birthMonth = (array_key_exists("birthDate/birthMonth",$response))?$response["birthDate/birthMonth"]:""; $this->user->profile->birthMonth = (array_key_exists("birthDate/birthMonth", $response)) ? $response["birthDate/birthMonth"] : "";
$this->user->profile->birthYear = (array_key_exists("birthDate/birthDate",$response))?$response["birthDate/birthDate"]:""; $this->user->profile->birthYear = (array_key_exists("birthDate/birthDate", $response)) ? $response["birthDate/birthDate"] : "";
if( isset( $response['namePerson/friendly'] ) && ! empty( $response['namePerson/friendly'] ) && ! $this->user->profile->displayName ) { if (isset($response['namePerson/friendly']) && !empty($response['namePerson/friendly']) && !$this->user->profile->displayName) {
$this->user->profile->displayName = $response["namePerson/friendly"]; $this->user->profile->displayName = $response["namePerson/friendly"];
} }
if( isset( $response['birthDate'] ) && ! empty( $response['birthDate'] ) && ! $this->user->profile->birthDay ) { if (isset($response['birthDate']) && !empty($response['birthDate']) && !$this->user->profile->birthDay) {
list( $birthday_year, $birthday_month, $birthday_day ) = $response['birthDate']; list( $birthday_year, $birthday_month, $birthday_day ) = $response['birthDate'];
$this->user->profile->birthDay = (int) $birthday_day; $this->user->profile->birthDay = (int) $birthday_day;
$this->user->profile->birthMonth = (int) $birthday_month; $this->user->profile->birthMonth = (int) $birthday_month;
$this->user->profile->birthYear = (int) $birthday_year; $this->user->profile->birthYear = (int) $birthday_year;
} }
if( ! $this->user->profile->displayName ){ if (!$this->user->profile->displayName) {
$this->user->profile->displayName = trim( $this->user->profile->firstName . " " . $this->user->profile->lastName ); $this->user->profile->displayName = trim($this->user->profile->firstName . " " . $this->user->profile->lastName);
} }
if( $this->user->profile->gender == "f" ){ if ($this->user->profile->gender == "f") {
$this->user->profile->gender = "female"; $this->user->profile->gender = "female";
} }
if( $this->user->profile->gender == "m" ){ if ($this->user->profile->gender == "m") {
$this->user->profile->gender = "male"; $this->user->profile->gender = "male";
} }
@@ -156,24 +149,22 @@ class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model
$this->setUserConnected(); $this->setUserConnected();
// with openid providers we get the user profile only once, so store it // with openid providers we get the user profile only once, so store it
Hybrid_Auth::storage()->set( "hauth_session.{$this->providerId}.user", $this->user ); Hybrid_Auth::storage()->set("hauth_session.{$this->providerId}.user", $this->user);
} }
// --------------------------------------------------------------------
/** /**
* load the user profile from the IDp api client * {@inheritdoc}
*/ */
function getUserProfile() function getUserProfile() {
{
// try to get the user profile from stored data // try to get the user profile from stored data
$this->user = Hybrid_Auth::storage()->get( "hauth_session.{$this->providerId}.user" ) ; $this->user = Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.user");
// if not found // if not found
if ( ! is_object( $this->user ) ){ if (!is_object($this->user)) {
throw new Exception( "User profile request failed! User is not connected to {$this->providerId} or his session has expired.", 6 ); throw new Exception("User profile request failed! User is not connected to {$this->providerId} or his session has expired.", 6);
} }
return $this->user->profile; return $this->user->profile;
} }
} }

View File

@@ -1,16 +1,18 @@
<?php <?php
/*!
* HybridAuth /* !
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * HybridAuth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
*/ * (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* Hybrid_Providers_AOL provider adapter based on OpenID protocol * Hybrid_Providers_AOL provider adapter based on OpenID protocol
* *
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_AOL.html * http://hybridauth.sourceforge.net/userguide/IDProvider_info_AOL.html
*/ */
class Hybrid_Providers_AOL extends Hybrid_Provider_Model_OpenID class Hybrid_Providers_AOL extends Hybrid_Provider_Model_OpenID {
{
var $openidIdentifier = "http://openid.aol.com/"; var $openidIdentifier = "http://openid.aol.com/";
} }

View File

@@ -1,433 +1,431 @@
<?php <?php
/*!
* HybridAuth /* !
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * HybridAuth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
*/ * (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* Hybrid_Providers_Facebook provider adapter based on OAuth2 protocol * Hybrid_Providers_Facebook provider adapter based on OAuth2 protocol
* *
* Hybrid_Providers_Facebook use the Facebook PHP SDK created by Facebook * Hybrid_Providers_Facebook use the Facebook PHP SDK created by Facebook
* *
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Facebook.html * http://hybridauth.sourceforge.net/userguide/IDProvider_info_Facebook.html
*/ */
class Hybrid_Providers_Facebook extends Hybrid_Provider_Model class Hybrid_Providers_Facebook extends Hybrid_Provider_Model {
{
// default permissions, and a lot of them. You can change them from the configuration by setting the scope to what you want/need
public $scope = "email, user_about_me, user_birthday, user_hometown, user_website, read_stream, publish_actions, read_friendlists";
/** /**
* IDp wrappers initializer * default permissions, and a lot of them. You can change them from the configuration by setting the scope to what you want/need
*/ * {@inheritdoc}
function initialize() */
{ public $scope = "email, user_about_me, user_birthday, user_hometown, user_location, user_website, publish_actions, read_custom_friendlists";
if ( ! $this->config["keys"]["id"] || ! $this->config["keys"]["secret"] ){
throw new Exception( "Your application id and secret are required in order to connect to {$this->providerId}.", 4 ); /**
* Provider API client
* @var Facebook
*/
public $api;
/**
* {@inheritdoc}
*/
function initialize() {
if (!$this->config["keys"]["id"] || !$this->config["keys"]["secret"]) {
throw new Exception("Your application id and secret are required in order to connect to {$this->providerId}.", 4);
} }
if ( ! class_exists('FacebookApiException', false) ) { if (!class_exists('FacebookApiException', false)) {
require_once Hybrid_Auth::$config["path_libraries"] . "Facebook/base_facebook.php"; require_once Hybrid_Auth::$config["path_libraries"] . "Facebook/base_facebook.php";
require_once Hybrid_Auth::$config["path_libraries"] . "Facebook/facebook.php"; require_once Hybrid_Auth::$config["path_libraries"] . "Facebook/facebook.php";
} }
if ( isset ( Hybrid_Auth::$config["proxy"] ) ) { if (isset(Hybrid_Auth::$config["proxy"])) {
BaseFacebook::$CURL_OPTS[CURLOPT_PROXY] = Hybrid_Auth::$config["proxy"]; BaseFacebook::$CURL_OPTS[CURLOPT_PROXY] = Hybrid_Auth::$config["proxy"];
} }
$trustForwarded = isset( $this->config['trustForwarded'] ) ? (bool) $this->config['trustForwarded'] : false; $trustForwarded = isset($this->config['trustForwarded']) ? (bool) $this->config['trustForwarded'] : false;
$this->api = new Facebook( ARRAY( 'appId' => $this->config["keys"]["id"], 'secret' => $this->config["keys"]["secret"], 'trustForwarded' => $trustForwarded ) ); $this->api = new Facebook(array('appId' => $this->config["keys"]["id"], 'secret' => $this->config["keys"]["secret"], 'trustForwarded' => $trustForwarded));
if ( $this->token("access_token") ) { if ($this->token("access_token")) {
$this->api->setAccessToken( $this->token("access_token") ); $this->api->setAccessToken($this->token("access_token"));
$this->api->setExtendedAccessToken(); $this->api->setExtendedAccessToken();
$access_token = $this->api->getAccessToken(); $access_token = $this->api->getAccessToken();
if( $access_token ){ if ($access_token) {
$this->token("access_token", $access_token ); $this->token("access_token", $access_token);
$this->api->setAccessToken( $access_token ); $this->api->setAccessToken($access_token);
} }
$this->api->setAccessToken( $this->token("access_token") ); $this->api->setAccessToken($this->token("access_token"));
} }
$this->api->getUser(); $this->api->getUser();
} }
/** /**
* begin login step * {@inheritdoc}
* */
* simply call Facebook::require_login(). function loginBegin() {
*/
function loginBegin()
{
$parameters = array("scope" => $this->scope, "redirect_uri" => $this->endpoint, "display" => "page"); $parameters = array("scope" => $this->scope, "redirect_uri" => $this->endpoint, "display" => "page");
$optionals = array("scope", "redirect_uri", "display", "auth_type"); $optionals = array("scope", "redirect_uri", "display", "auth_type");
foreach ($optionals as $parameter){ foreach ($optionals as $parameter) {
if( isset( $this->config[$parameter] ) && ! empty( $this->config[$parameter] ) ){ if (isset($this->config[$parameter]) && !empty($this->config[$parameter])) {
$parameters[$parameter] = $this->config[$parameter]; $parameters[$parameter] = $this->config[$parameter];
//If the auth_type parameter is used, we need to generate a nonce and include it as a parameter //If the auth_type parameter is used, we need to generate a nonce and include it as a parameter
if($parameter == "auth_type"){ if ($parameter == "auth_type") {
$nonce = md5(uniqid(mt_rand(), true)); $nonce = md5(uniqid(mt_rand(), true));
$parameters['auth_nonce'] = $nonce; $parameters['auth_nonce'] = $nonce;
Hybrid_Auth::storage()->set('fb_auth_nonce', $nonce); Hybrid_Auth::storage()->set('fb_auth_nonce', $nonce);
} }
} }
} }
if( isset( $this->config[ 'force' ] ) && $this->config[ 'force' ] === true ){ if (isset($this->config['force']) && $this->config['force'] === true) {
$parameters[ 'auth_type' ] = 'reauthenticate'; $parameters['auth_type'] = 'reauthenticate';
$parameters[ 'auth_nonce' ] = md5( uniqid( mt_rand(), true ) ); $parameters['auth_nonce'] = md5(uniqid(mt_rand(), true));
Hybrid_Auth::storage()->set( 'fb_auth_nonce', $parameters[ 'auth_nonce' ] ); Hybrid_Auth::storage()->set('fb_auth_nonce', $parameters['auth_nonce']);
} }
// get the login url // get the login url
$url = $this->api->getLoginUrl( $parameters ); $url = $this->api->getLoginUrl($parameters);
// redirect to facebook // redirect to facebook
Hybrid_Auth::redirect( $url ); Hybrid_Auth::redirect($url);
} }
/** /**
* finish login step * {@inheritdoc}
*/ */
function loginFinish() function loginFinish() {
{
// in case we get error_reason=user_denied&error=access_denied // in case we get error_reason=user_denied&error=access_denied
if ( isset( $_REQUEST['error'] ) && $_REQUEST['error'] == "access_denied" ){ if (isset($_REQUEST['error']) && $_REQUEST['error'] == "access_denied") {
throw new Exception( "Authentication failed! The user denied your request.", 5 ); throw new Exception("Authentication failed! The user denied your request.", 5);
} }
// in case we are using iOS/Facebook reverse authentication // in case we are using iOS/Facebook reverse authentication
if(isset($_REQUEST['access_token'])){ if (isset($_REQUEST['access_token'])) {
$this->token("access_token", $_REQUEST['access_token'] ); $this->token("access_token", $_REQUEST['access_token']);
$this->api->setAccessToken( $this->token("access_token") ); $this->api->setAccessToken($this->token("access_token"));
$this->api->setExtendedAccessToken(); $this->api->setExtendedAccessToken();
$access_token = $this->api->getAccessToken(); $access_token = $this->api->getAccessToken();
if( $access_token ){ if ($access_token) {
$this->token("access_token", $access_token ); $this->token("access_token", $access_token);
$this->api->setAccessToken( $access_token ); $this->api->setAccessToken($access_token);
} }
$this->api->setAccessToken( $this->token("access_token") ); $this->api->setAccessToken($this->token("access_token"));
} }
// if auth_type is used, then an auth_nonce is passed back, and we need to check it. // if auth_type is used, then an auth_nonce is passed back, and we need to check it.
if(isset($_REQUEST['auth_nonce'])){ if (isset($_REQUEST['auth_nonce'])) {
$nonce = Hybrid_Auth::storage()->get('fb_auth_nonce'); $nonce = Hybrid_Auth::storage()->get('fb_auth_nonce');
//Delete the nonce //Delete the nonce
Hybrid_Auth::storage()->delete('fb_auth_nonce'); Hybrid_Auth::storage()->delete('fb_auth_nonce');
if($_REQUEST['auth_nonce'] != $nonce){ if ($_REQUEST['auth_nonce'] != $nonce) {
throw new Exception( "Authentication failed! Invalid nonce used for reauthentication.", 5 ); throw new Exception("Authentication failed! Invalid nonce used for reauthentication.", 5);
} }
} }
// try to get the UID of the connected user from fb, should be > 0 // try to get the UID of the connected user from fb, should be > 0
if ( ! $this->api->getUser() ){ if (!$this->api->getUser()) {
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid user id.", 5 ); throw new Exception("Authentication failed! {$this->providerId} returned an invalid user id.", 5);
} }
// set user as logged in // set user as logged in
$this->setUserConnected(); $this->setUserConnected();
// store facebook access token // store facebook access token
$this->token( "access_token", $this->api->getAccessToken() ); $this->token("access_token", $this->api->getAccessToken());
} }
/** /**
* logout * {@inheritdoc}
*/ */
function logout() function logout() {
{
$this->api->destroySession(); $this->api->destroySession();
parent::logout(); parent::logout();
} }
/** /**
* load the user profile from the IDp api client * {@inheritdoc}
*/ */
function getUserProfile() function getUserProfile() {
{
// request user profile from fb api // request user profile from fb api
try{ try {
$data = $this->api->api('/me'); $fields = array(
'id', 'name', 'first_name', 'last_name', 'link', 'website',
'gender', 'locale', 'about', 'email', 'hometown', 'location',
'birthday'
);
$data = $this->api->api('/me?fields=' . implode(',', $fields));
} catch (FacebookApiException $e) {
throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e->getMessage()}", 6, $e);
} }
catch( FacebookApiException $e ){
throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
}
// if the provider identifier is not received, we assume the auth has failed // if the provider identifier is not received, we assume the auth has failed
if ( ! isset( $data["id"] ) ){ if (!isset($data["id"])) {
throw new Exception( "User profile request failed! {$this->providerId} api returned an invalid response.", 6 ); throw new Exception("User profile request failed! {$this->providerId} api returned an invalid response: " . Hybrid_Logger::dumpData( $data ), 6);
} }
# store the user profile. # store the user profile.
$this->user->profile->identifier = (array_key_exists('id',$data))?$data['id']:""; $this->user->profile->identifier = (array_key_exists('id', $data)) ? $data['id'] : "";
$this->user->profile->username = (array_key_exists('username',$data))?$data['username']:""; $this->user->profile->username = (array_key_exists('username', $data)) ? $data['username'] : "";
$this->user->profile->displayName = (array_key_exists('name',$data))?$data['name']:""; $this->user->profile->displayName = (array_key_exists('name', $data)) ? $data['name'] : "";
$this->user->profile->firstName = (array_key_exists('first_name',$data))?$data['first_name']:""; $this->user->profile->firstName = (array_key_exists('first_name', $data)) ? $data['first_name'] : "";
$this->user->profile->lastName = (array_key_exists('last_name',$data))?$data['last_name']:""; $this->user->profile->lastName = (array_key_exists('last_name', $data)) ? $data['last_name'] : "";
$this->user->profile->photoURL = "https://graph.facebook.com/" . $this->user->profile->identifier . "/picture?width=150&height=150"; $this->user->profile->photoURL = "https://graph.facebook.com/" . $this->user->profile->identifier . "/picture?width=150&height=150";
$this->user->profile->coverInfoURL = "https://graph.facebook.com/" . $this->user->profile->identifier . "?fields=cover"; $this->user->profile->coverInfoURL = "https://graph.facebook.com/" . $this->user->profile->identifier . "?fields=cover&access_token=" . $this->api->getAccessToken();
$this->user->profile->profileURL = (array_key_exists('link',$data))?$data['link']:""; $this->user->profile->profileURL = (array_key_exists('link', $data)) ? $data['link'] : "";
$this->user->profile->webSiteURL = (array_key_exists('website',$data))?$data['website']:""; $this->user->profile->webSiteURL = (array_key_exists('website', $data)) ? $data['website'] : "";
$this->user->profile->gender = (array_key_exists('gender',$data))?$data['gender']:""; $this->user->profile->gender = (array_key_exists('gender', $data)) ? $data['gender'] : "";
$this->user->profile->language = (array_key_exists('locale',$data))?$data['locale']:""; $this->user->profile->language = (array_key_exists('locale', $data)) ? $data['locale'] : "";
$this->user->profile->description = (array_key_exists('about',$data))?$data['about']:""; $this->user->profile->description = (array_key_exists('about', $data)) ? $data['about'] : "";
$this->user->profile->email = (array_key_exists('email',$data))?$data['email']:""; $this->user->profile->email = (array_key_exists('email', $data)) ? $data['email'] : "";
$this->user->profile->emailVerified = (array_key_exists('email',$data))?$data['email']:""; $this->user->profile->emailVerified = (array_key_exists('email', $data)) ? $data['email'] : "";
$this->user->profile->region = (array_key_exists("hometown",$data)&&array_key_exists("name",$data['hometown']))?$data['hometown']["name"]:""; $this->user->profile->region = (array_key_exists("location", $data) && array_key_exists("name", $data['location'])) ? $data['location']["name"] : "";
if(!empty($this->user->profile->region )){ if (!empty($this->user->profile->region)) {
$regionArr = explode(',',$this->user->profile->region ); $regionArr = explode(',', $this->user->profile->region);
if(count($regionArr) > 1){ if (count($regionArr) > 1) {
$this->user->profile->city = trim($regionArr[0]); $this->user->profile->city = trim($regionArr[0]);
$this->user->profile->country = trim($regionArr[1]); $this->user->profile->country = trim($regionArr[1]);
} }
} }
if( array_key_exists('birthday',$data) ) {
list($birthday_month, $birthday_day, $birthday_year) = explode( "/", $data['birthday'] );
$this->user->profile->birthDay = (int) $birthday_day; if (array_key_exists('birthday', $data)) {
list($birthday_month, $birthday_day, $birthday_year) = explode("/", $data['birthday']);
$this->user->profile->birthDay = (int) $birthday_day;
$this->user->profile->birthMonth = (int) $birthday_month; $this->user->profile->birthMonth = (int) $birthday_month;
$this->user->profile->birthYear = (int) $birthday_year; $this->user->profile->birthYear = (int) $birthday_year;
} }
return $this->user->profile; return $this->user->profile;
} }
/** /**
* Attempt to retrieve the url to the cover image given the coverInfoURL * Attempt to retrieve the url to the cover image given the coverInfoURL
* *
* @param string $coverInfoURL coverInfoURL variable * @param string $coverInfoURL coverInfoURL variable
* @retval string url to the cover image OR blank string * @return string url to the cover image OR blank string
*/ */
function getCoverURL($coverInfoURL) function getCoverURL($coverInfoURL) {
{
try { try {
$headers = get_headers($coverInfoURL); $headers = get_headers($coverInfoURL);
if(substr($headers[0], 9, 3) != "404") { if (substr($headers[0], 9, 3) != "404") {
$coverOBJ = json_decode(file_get_contents($coverInfoURL)); $coverOBJ = json_decode(file_get_contents($coverInfoURL));
if(array_key_exists('cover', $coverOBJ)) { if (array_key_exists('cover', $coverOBJ)) {
return $coverOBJ->cover->source; return $coverOBJ->cover->source;
} }
} }
} catch (Exception $e) { } } catch (Exception $e) {
}
return ""; return "";
} }
/** /**
* load the user contacts * {@inheritdoc}
*/ */
function getUserContacts() function getUserContacts() {
{
$apiCall = '?fields=link,name'; $apiCall = '?fields=link,name';
$returnedContacts = array(); $returnedContacts = array();
$pagedList = false; $pagedList = false;
do { do {
try{ try {
$response = $this->api->api('/me/friends' . $apiCall); $response = $this->api->api('/me/friends' . $apiCall);
} catch (FacebookApiException $e) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e);
} }
catch( FacebookApiException $e ){
throw new Exception( 'User contacts request failed! {$this->providerId} returned an error: $e' );
}
// Prepare the next call if paging links have been returned // Prepare the next call if paging links have been returned
if (array_key_exists('paging', $response) && array_key_exists('next', $response['paging'])) { if (array_key_exists('paging', $response) && array_key_exists('next', $response['paging'])) {
$pagedList = true; $pagedList = true;
$next_page = explode('friends', $response['paging']['next']); $next_page = explode('friends', $response['paging']['next']);
$apiCall = $next_page[1]; $apiCall = $next_page[1];
} } else {
else{
$pagedList = false; $pagedList = false;
} }
// Add the new page contacts // Add the new page contacts
$returnedContacts = array_merge($returnedContacts, $response['data']); $returnedContacts = array_merge($returnedContacts, $response['data']);
} } while ($pagedList == true);
while ($pagedList == true);
$contacts = array();
foreach ($returnedContacts as $item) {
$contacts = ARRAY();
foreach( $returnedContacts as $item ){
$uc = new Hybrid_User_Contact(); $uc = new Hybrid_User_Contact();
$uc->identifier = (array_key_exists("id", $item)) ? $item["id"] : "";
$uc->identifier = (array_key_exists("id",$item))?$item["id"]:""; $uc->displayName = (array_key_exists("name", $item)) ? $item["name"] : "";
$uc->displayName = (array_key_exists("name",$item))?$item["name"]:""; $uc->profileURL = (array_key_exists("link", $item)) ? $item["link"] : "https://www.facebook.com/profile.php?id=" . $uc->identifier;
$uc->profileURL = (array_key_exists("link",$item))?$item["link"]:"https://www.facebook.com/profile.php?id=" . $uc->identifier; $uc->photoURL = "https://graph.facebook.com/" . $uc->identifier . "/picture?width=150&height=150";
$uc->photoURL = "https://graph.facebook.com/" . $uc->identifier . "/picture?width=150&height=150";
$contacts[] = $uc; $contacts[] = $uc;
} }
return $contacts; return $contacts;
} }
/**
* update user status
*
* @param string $pageid (optional) User page id
*/
function setUserStatus( $status, $pageid = null )
{
if( !is_array( $status ) ){
$status = array( 'message' => $status );
}
if( is_null( $pageid ) ){
$pageid = 'me';
// if post on page, get access_token page
}else{
$access_token = null;
foreach( $this->getUserPages( true ) as $p ){
if( isset( $p[ 'id' ] ) && intval( $p['id'] ) == intval( $pageid ) ){
$access_token = $p[ 'access_token' ];
break;
}
}
if( is_null( $access_token ) ){
throw new Exception( "Update user page failed, page not found or not writable!" );
}
$status[ 'access_token' ] = $access_token;
}
try{
$response = $this->api->api( '/' . $pageid . '/feed', 'post', $status );
}
catch( FacebookApiException $e ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error: $e" );
}
return $response;
}
/** /**
* get user status * Update user status
*/ *
function getUserStatus( $postid ) * @param mixed $status An array describing the status, or string
{ * @param string $pageid (optional) User page id
try{ * @return array
$postinfo = $this->api->api( "/" . $postid ); * @throw Exception
} */
catch( FacebookApiException $e ){ function setUserStatus($status, $pageid = null) {
throw new Exception( "Cannot retrieve user status! {$this->providerId} returned an error: $e" ); if (!is_array($status)) {
$status = array('message' => $status);
} }
return $postinfo; if (is_null($pageid)) {
} $pageid = 'me';
// if post on page, get access_token page
/** } else {
* get user pages $access_token = null;
*/ foreach ($this->getUserPages(true) as $p) {
function getUserPages( $writableonly = false ) if (isset($p['id']) && intval($p['id']) == intval($pageid)) {
{ $access_token = $p['access_token'];
if( ( isset( $this->config[ 'scope' ] ) && strpos( $this->config[ 'scope' ], 'manage_pages' ) === false ) || ( !isset( $this->config[ 'scope' ] ) && strpos( $this->scope, 'manage_pages' ) === false ) ) break;
throw new Exception( "User status requires manage_page permission!" ); }
try{
$pages = $this->api->api( "/me/accounts", 'get' );
}
catch( FacebookApiException $e ){
throw new Exception( "Cannot retrieve user pages! {$this->providerId} returned an error: $e" );
}
if( !isset( $pages[ 'data' ] ) ){
return array();
}
if( !$writableonly ){
return $pages[ 'data' ];
}
$wrpages = array();
foreach( $pages[ 'data' ] as $p ){
if( isset( $p[ 'perms' ] ) && in_array( 'CREATE_CONTENT', $p[ 'perms' ] ) ){
$wrpages[] = $p;
}
}
return $wrpages;
}
/**
* load the user latest activity
* - timeline : all the stream
* - me : the user activity only
*/
function getUserActivity( $stream )
{
try{
if( $stream == "me" ){
$response = $this->api->api( '/me/feed' );
} }
else{
$response = $this->api->api('/me/home'); if (is_null($access_token)) {
throw new Exception("Update user page failed, page not found or not writable!");
}
$status['access_token'] = $access_token;
}
try {
$response = $this->api->api('/' . $pageid . '/feed', 'post', $status);
} catch (FacebookApiException $e) {
throw new Exception("Update user status failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e);
}
return $response;
}
/**
* {@inheridoc}
*/
function getUserStatus($postid) {
try {
$postinfo = $this->api->api("/" . $postid);
} catch (FacebookApiException $e) {
throw new Exception("Cannot retrieve user status! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
return $postinfo;
}
/**
* {@inheridoc}
*/
function getUserPages($writableonly = false) {
if (( isset($this->config['scope']) && strpos($this->config['scope'], 'manage_pages') === false ) || (!isset($this->config['scope']) && strpos($this->scope, 'manage_pages') === false ))
throw new Exception("User status requires manage_page permission!");
try {
$pages = $this->api->api("/me/accounts", 'get');
} catch (FacebookApiException $e) {
throw new Exception("Cannot retrieve user pages! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if (!isset($pages['data'])) {
return array();
}
if (!$writableonly) {
return $pages['data'];
}
$wrpages = array();
foreach ($pages['data'] as $p) {
if (isset($p['perms']) && in_array('CREATE_CONTENT', $p['perms'])) {
$wrpages[] = $p;
} }
} }
catch( FacebookApiException $e ){
throw new Exception( "User activity stream request failed! {$this->providerId} returned an error: $e" );
}
if( ! $response || ! count( $response['data'] ) ){ return $wrpages;
return ARRAY(); }
/**
* load the user latest activity
* - timeline : all the stream
* - me : the user activity only
* {@inheritdoc}
*/
function getUserActivity($stream) {
try {
if ($stream == "me") {
$response = $this->api->api('/me/feed');
} else {
$response = $this->api->api('/me/home');
}
} catch (FacebookApiException $e) {
throw new Exception("User activity stream request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
} }
$activities = ARRAY(); if (!$response || !count($response['data'])) {
return array();
}
foreach( $response['data'] as $item ){ $activities = array();
if( $stream == "me" && $item["from"]["id"] != $this->api->getUser() ){
foreach ($response['data'] as $item) {
if ($stream == "me" && $item["from"]["id"] != $this->api->getUser()) {
continue; continue;
} }
$ua = new Hybrid_User_Activity(); $ua = new Hybrid_User_Activity();
$ua->id = (array_key_exists("id",$item))?$item["id"]:""; $ua->id = (array_key_exists("id", $item)) ? $item["id"] : "";
$ua->date = (array_key_exists("created_time",$item))?strtotime($item["created_time"]):""; $ua->date = (array_key_exists("created_time", $item)) ? strtotime($item["created_time"]) : "";
if( $item["type"] == "video" ){ if ($item["type"] == "video") {
$ua->text = (array_key_exists("link",$item))?$item["link"]:""; $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
} }
if( $item["type"] == "link" ){ if ($item["type"] == "link") {
$ua->text = (array_key_exists("link",$item))?$item["link"]:""; $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
} }
if( empty( $ua->text ) && isset( $item["story"] ) ){ if (empty($ua->text) && isset($item["story"])) {
$ua->text = (array_key_exists("link",$item))?$item["link"]:""; $ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
} }
if( empty( $ua->text ) && isset( $item["message"] ) ){ if (empty($ua->text) && isset($item["message"])) {
$ua->text = (array_key_exists("message",$item))?$item["message"]:""; $ua->text = (array_key_exists("message", $item)) ? $item["message"] : "";
} }
if( ! empty( $ua->text ) ){ if (!empty($ua->text)) {
$ua->user->identifier = (array_key_exists("id",$item["from"]))?$item["from"]["id"]:""; $ua->user->identifier = (array_key_exists("id", $item["from"])) ? $item["from"]["id"] : "";
$ua->user->displayName = (array_key_exists("name",$item["from"]))?$item["from"]["name"]:""; $ua->user->displayName = (array_key_exists("name", $item["from"])) ? $item["from"]["name"] : "";
$ua->user->profileURL = "https://www.facebook.com/profile.php?id=" . $ua->user->identifier; $ua->user->profileURL = "https://www.facebook.com/profile.php?id=" . $ua->user->identifier;
$ua->user->photoURL = "https://graph.facebook.com/" . $ua->user->identifier . "/picture?type=square"; $ua->user->photoURL = "https://graph.facebook.com/" . $ua->user->identifier . "/picture?type=square";
$activities[] = $ua; $activities[] = $ua;
} }
} }
return $activities; return $activities;
} }
} }

View File

@@ -1,74 +1,121 @@
<?php <?php
/*!
* HybridAuth /* !
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * HybridAuth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
*/ * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* Hybrid_Providers_Foursquare provider adapter based on OAuth2 protocol * Hybrid_Providers_Foursquare provider adapter based on OAuth2 protocol
* *
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Foursquare.html * http://hybridauth.sourceforge.net/userguide/IDProvider_info_Foursquare.html
*/ */
/** /**
* Howto define profile photo size: * Howto define profile photo size:
* - add params key into hybridauth config * - add params key into hybridauth config
* ... * ...
* "Foursquare" => array ( * "Foursquare" => array (
* "enabled" => true, * "enabled" => true,
* "keys" => ..., * "keys" => ...,
* "params" => array( "photo_size" => "16x16" ) * "params" => array( "photo_size" => "16x16" )
* ), * ),
* ... * ...
* - list of valid photo_size values is described here https://developer.foursquare.com/docs/responses/photo.html * - list of valid photo_size values is described here https://developer.foursquare.com/docs/responses/photo.html
* - default photo_size is 100x100 * - default photo_size is 100x100
*/ */
class Hybrid_Providers_Foursquare extends Hybrid_Provider_Model_OAuth2 {
private static $apiVersion = array("v" => "20120610");
private static $defPhotoSize = "100x100";
class Hybrid_Providers_Foursquare extends Hybrid_Provider_Model_OAuth2
{
/** /**
* IDp wrappers initializer * {@inheritdoc}
*/ */
function initialize() function initialize() {
{
parent::initialize(); parent::initialize();
// Provider apis end-points // Provider apis end-points
$this->api->api_base_url = "https://api.foursquare.com/v2/"; $this->api->api_base_url = "https://api.foursquare.com/v2/";
$this->api->authorize_url = "https://foursquare.com/oauth2/authenticate"; $this->api->authorize_url = "https://foursquare.com/oauth2/authenticate";
$this->api->token_url = "https://foursquare.com/oauth2/access_token"; $this->api->token_url = "https://foursquare.com/oauth2/access_token";
$this->api->sign_token_name = "oauth_token"; $this->api->sign_token_name = "oauth_token";
} }
/** /**
* load the user profile from the IDp api client * {@inheritdoc}
*/ */
function getUserProfile() function getUserProfile() {
{ $data = $this->api->api("users/self", "GET", Hybrid_Providers_Foursquare::$apiVersion);
$data = $this->api->api( "users/self", "GET", array( "v" => "20120610" ) );
if ( ! isset( $data->response->user->id ) ){ if (!isset($data->response->user->id)) {
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 ); throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData( $data ), 6);
} }
$data = $data->response->user; $data = $data->response->user;
// get profile photo size from config $this->user->profile->identifier = $data->id;
$photoSize = ((isset($this->config["params"]["photo_size"]))?($this->config["params"]["photo_size"]):("100x100")); $this->user->profile->firstName = $data->firstName;
$this->user->profile->lastName = $data->lastName;
$this->user->profile->identifier = $data->id; $this->user->profile->displayName = $this->buildDisplayName($this->user->profile->firstName, $this->user->profile->lastName);
$this->user->profile->firstName = $data->firstName; $this->user->profile->photoURL = $this->buildPhotoURL($data->photo->prefix, $data->photo->suffix);
$this->user->profile->lastName = $data->lastName; $this->user->profile->profileURL = "https://www.foursquare.com/user/" . $data->id;
$this->user->profile->displayName = trim( $this->user->profile->firstName . " " . $this->user->profile->lastName ); $this->user->profile->gender = $data->gender;
$this->user->profile->photoURL = $data->photo->prefix.$photoSize.$data->photo->suffix; $this->user->profile->city = $data->homeCity;
$this->user->profile->profileURL = "https://www.foursquare.com/user/" . $data->id; $this->user->profile->email = $data->contact->email;
$this->user->profile->gender = $data->gender;
$this->user->profile->city = $data->homeCity;
$this->user->profile->email = $data->contact->email;
$this->user->profile->emailVerified = $data->contact->email; $this->user->profile->emailVerified = $data->contact->email;
return $this->user->profile; return $this->user->profile;
} }
/**
* {@inheritdoc}
*/
function getUserContacts() {
// refresh tokens if needed
$this->refreshToken();
//
$response = array();
$contacts = array();
try {
$response = $this->api->api("users/self/friends", "GET", Hybrid_Providers_Foursquare::$apiVersion);
} catch (LinkedInException $e) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if (isset($response) && $response->meta->code == 200) {
foreach ($response->response->friends->items as $contact) {
$uc = new Hybrid_User_Contact();
//
$uc->identifier = $contact->id;
//$uc->profileURL = ;
//$uc->webSiteURL = ;
$uc->photoURL = $this->buildPhotoURL($contact->photo->prefix, $contact->photo->suffix);
$uc->displayName = $this->buildDisplayName((isset($contact->firstName) ? ($contact->firstName) : ("")), (isset($contact->lastName) ? ($contact->lastName) : ("")));
//$uc->description = ;
$uc->email = (isset($contact->contact->email) ? ($contact->contact->email) : (""));
//
$contacts[] = $uc;
}
}
return $contacts;
}
/**
* {@inheritdoc}
*/
private function buildDisplayName($firstName, $lastName) {
return trim($firstName . " " . $lastName);
}
private function buildPhotoURL($prefix, $suffix) {
if (isset($prefix) && isset($suffix)) {
return $prefix . ((isset($this->config["params"]["photo_size"])) ? ($this->config["params"]["photo_size"]) : (Hybrid_Providers_Foursquare::$defPhotoSize)) . $suffix;
}
return ("");
}
} }

View File

@@ -6,18 +6,18 @@
*/ */
/** /**
* Hybrid_Providers_GitHub * Hybrid_Providers_GitHub
*/ */
class Hybrid_Providers_GitHub extends Hybrid_Provider_Model_OAuth2 class Hybrid_Providers_GitHub extends Hybrid_Provider_Model_OAuth2
{ {
// default permissions // default permissions
// (no scope) => public read-only access (includes public user profile info, public repo info, and gists). // (no scope) => public read-only access (includes public user profile info, public repo info, and gists).
public $scope = ""; public $scope = "";
/** /**
* IDp wrappers initializer * IDp wrappers initializer
*/ */
function initialize() function initialize()
{ {
parent::initialize(); parent::initialize();
@@ -32,17 +32,17 @@ class Hybrid_Providers_GitHub extends Hybrid_Provider_Model_OAuth2
*/ */
function getUserProfile() function getUserProfile()
{ {
$data = $this->api->api( "user" ); $data = $this->api->api( "user" );
if ( ! isset( $data->id ) ){ if ( ! isset( $data->id ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 ); throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 );
} }
$this->user->profile->identifier = @ $data->id; $this->user->profile->identifier = @ $data->id;
$this->user->profile->displayName = @ $data->name; $this->user->profile->displayName = @ $data->name;
$this->user->profile->description = @ $data->bio; $this->user->profile->description = @ $data->bio;
$this->user->profile->photoURL = @ $data->avatar_url; $this->user->profile->photoURL = @ $data->avatar_url;
$this->user->profile->profileURL = @ $data->html_url; $this->user->profile->profileURL = @ $data->html_url;
$this->user->profile->email = @ $data->email; $this->user->profile->email = @ $data->email;
$this->user->profile->webSiteURL = @ $data->blog; $this->user->profile->webSiteURL = @ $data->blog;
$this->user->profile->region = @ $data->location; $this->user->profile->region = @ $data->location;
@@ -60,9 +60,9 @@ class Hybrid_Providers_GitHub extends Hybrid_Provider_Model_OAuth2
if (is_array($emails)) { if (is_array($emails)) {
foreach ($emails as $email) { foreach ($emails as $email) {
if ($email instanceof stdClass if ($email instanceof stdClass
&& property_exists('primary', $email) && property_exists($email, 'primary')
&& true === $email->primary && true === $email->primary
&& property_exists('email', $email) && property_exists($email, 'email')
) { ) {
$this->user->profile->email = $email->email; $this->user->profile->email = $email->email;
break; break;
@@ -77,4 +77,43 @@ class Hybrid_Providers_GitHub extends Hybrid_Provider_Model_OAuth2
return $this->user->profile; return $this->user->profile;
} }
/**
*
*/
function getUserContacts() {
// refresh tokens if needed
$this->refreshToken();
//
$response = array();
$contacts = array();
try {
$response = $this->api->api( "user/followers" );
} catch (LinkedInException $e) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error: $e");
}
//
if ( isset( $response ) ) {
foreach ($response as $contact) {
try {
$contactInfo = $this->api->api( "users/".$contact->login );
} catch (LinkedInException $e) {
throw new Exception("Contact info request failed for user {$contact->login}! {$this->providerId} returned an error: $e");
}
//
$uc = new Hybrid_User_Contact();
//
$uc->identifier = $contact->id;
$uc->profileURL = @$contact->html_url;
$uc->webSiteURL = @$contact->blog;
$uc->photoURL = @$contact->avatar_url;
$uc->displayName = ( isset( $contactInfo->name )?( $contactInfo->name ):( $contact->login ) );
//$uc->description = ;
$uc->email = @$contactInfo->email;
//
$contacts[] = $uc;
}
}
return $contacts;
}
} }

View File

@@ -1,103 +1,106 @@
<?php <?php
/*!
* HybridAuth /* !
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * HybridAuth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
*/ * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* Hybrid_Providers_Google provider adapter based on OAuth2 protocol * Hybrid_Providers_Google provider adapter based on OAuth2 protocol
* *
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Google.html * http://hybridauth.sourceforge.net/userguide/IDProvider_info_Google.html
*/ */
class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 {
{
// > more infos on google APIs: http://developer.google.com (official site)
// or here: http://discovery-check.appspot.com/ (unofficial but up to date)
// default permissions /**
* > more infos on google APIs: http://developer.google.com (official site)
* or here: http://discovery-check.appspot.com/ (unofficial but up to date)
* default permissions
* {@inheritdoc}
*/
public $scope = "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read https://www.google.com/m8/feeds/"; public $scope = "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read https://www.google.com/m8/feeds/";
/** /**
* IDp wrappers initializer * {@inheritdoc}
*/ */
function initialize() function initialize() {
{
parent::initialize(); parent::initialize();
// Provider api end-points // Provider api end-points
$this->api->authorize_url = "https://accounts.google.com/o/oauth2/auth"; $this->api->authorize_url = "https://accounts.google.com/o/oauth2/auth";
$this->api->token_url = "https://accounts.google.com/o/oauth2/token"; $this->api->token_url = "https://accounts.google.com/o/oauth2/token";
$this->api->token_info_url = "https://www.googleapis.com/oauth2/v2/tokeninfo"; $this->api->token_info_url = "https://www.googleapis.com/oauth2/v2/tokeninfo";
// Google POST methods require an access_token in the header
$this->api->curl_header = array("Authorization: OAuth " . $this->api->access_token);
// Override the redirect uri when it's set in the config parameters. This way we prevent // Override the redirect uri when it's set in the config parameters. This way we prevent
// redirect uri mismatches when authenticating with Google. // redirect uri mismatches when authenticating with Google.
if( isset( $this->config['redirect_uri'] ) && ! empty( $this->config['redirect_uri'] ) ){ if (isset($this->config['redirect_uri']) && !empty($this->config['redirect_uri'])) {
$this->api->redirect_uri = $this->config['redirect_uri']; $this->api->redirect_uri = $this->config['redirect_uri'];
} }
} }
/** /**
* begin login step * {@inheritdoc}
*/ */
function loginBegin() function loginBegin() {
{
$parameters = array("scope" => $this->scope, "access_type" => "offline"); $parameters = array("scope" => $this->scope, "access_type" => "offline");
$optionals = array("scope", "access_type", "redirect_uri", "approval_prompt", "hd", "state"); $optionals = array("scope", "access_type", "redirect_uri", "approval_prompt", "hd", "state");
foreach ($optionals as $parameter){ foreach ($optionals as $parameter) {
if( isset( $this->config[$parameter] ) && ! empty( $this->config[$parameter] ) ){ if (isset($this->config[$parameter]) && !empty($this->config[$parameter])) {
$parameters[$parameter] = $this->config[$parameter]; $parameters[$parameter] = $this->config[$parameter];
} }
if( isset( $this->config["scope"] ) && ! empty( $this->config["scope"] ) ){ if (isset($this->config["scope"]) && !empty($this->config["scope"])) {
$this->scope = $this->config["scope"]; $this->scope = $this->config["scope"];
} }
} }
if( isset( $this->config[ 'force' ] ) && $this->config[ 'force' ] === true ){ if (isset($this->config['force']) && $this->config['force'] === true) {
$parameters[ 'approval_prompt' ] = 'force'; $parameters['approval_prompt'] = 'force';
} }
Hybrid_Auth::redirect( $this->api->authorizeUrl( $parameters ) ); Hybrid_Auth::redirect($this->api->authorizeUrl($parameters));
} }
/** /**
* load the user profile from the IDp api client * {@inheritdoc}
*/ */
function getUserProfile() function getUserProfile() {
{ // refresh tokens if needed
// refresh tokens if needed
$this->refreshToken(); $this->refreshToken();
// ask google api for user infos // ask google api for user infos
if (strpos($this->scope, '/auth/plus.profile.emails.read') !== false) { if (strpos($this->scope, '/auth/plus.profile.emails.read') !== false) {
$verified = $this->api->api( "https://www.googleapis.com/plus/v1/people/me" ); $verified = $this->api->api("https://www.googleapis.com/plus/v1/people/me");
if ( ! isset( $verified->id ) || isset( $verified->error ) ) if (!isset($verified->id) || isset($verified->error))
$verified = new stdClass(); $verified = new stdClass();
} else { } else {
$verified = $this->api->api( "https://www.googleapis.com/plus/v1/people/me/openIdConnect" ); $verified = $this->api->api("https://www.googleapis.com/plus/v1/people/me/openIdConnect");
if ( ! isset( $verified->sub ) || isset( $verified->error ) ) if (!isset($verified->sub) || isset($verified->error))
$verified = new stdClass(); $verified = new stdClass();
} }
$response = $this->api->api( "https://www.googleapis.com/plus/v1/people/me" ); $response = $this->api->api("https://www.googleapis.com/plus/v1/people/me");
if ( ! isset( $response->id ) || isset( $response->error ) ){ if (!isset($response->id) || isset($response->error)) {
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 ); throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData( $response ), 6);
} }
$this->user->profile->identifier = (property_exists($verified,'id'))?$verified->id:((property_exists($response,'id'))?$response->id:""); $this->user->profile->identifier = (property_exists($verified, 'id')) ? $verified->id : ((property_exists($response, 'id')) ? $response->id : "");
$this->user->profile->firstName = (property_exists($response,'name'))?$response->name->givenName:""; $this->user->profile->firstName = (property_exists($response, 'name')) ? $response->name->givenName : "";
$this->user->profile->lastName = (property_exists($response,'name'))?$response->name->familyName:""; $this->user->profile->lastName = (property_exists($response, 'name')) ? $response->name->familyName : "";
$this->user->profile->displayName = (property_exists($response,'displayName'))?$response->displayName:""; $this->user->profile->displayName = (property_exists($response, 'displayName')) ? $response->displayName : "";
$this->user->profile->photoURL = (property_exists($response,'image'))?((property_exists($response->image,'url'))?substr($response->image->url, 0, -2)."200":''):''; $this->user->profile->photoURL = (property_exists($response, 'image')) ? ((property_exists($response->image, 'url')) ? substr($response->image->url, 0, -2) . "200" : '') : '';
$this->user->profile->profileURL = (property_exists($response,'url'))?$response->url:""; $this->user->profile->profileURL = (property_exists($response, 'url')) ? $response->url : "";
$this->user->profile->description = (property_exists($response,'aboutMe'))?$response->aboutMe:""; $this->user->profile->description = (property_exists($response, 'aboutMe')) ? $response->aboutMe : "";
$this->user->profile->gender = (property_exists($response,'gender'))?$response->gender:""; $this->user->profile->gender = (property_exists($response, 'gender')) ? $response->gender : "";
$this->user->profile->language = (property_exists($response,'locale'))?$response->locale:((property_exists($verified,'locale'))?$verified->locale:""); $this->user->profile->language = (property_exists($response, 'locale')) ? $response->locale : ((property_exists($verified, 'locale')) ? $verified->locale : "");
$this->user->profile->email = (property_exists($response,'email'))?$response->email:((property_exists($verified,'email'))?$verified->email:""); $this->user->profile->email = (property_exists($response, 'email')) ? $response->email : ((property_exists($verified, 'email')) ? $verified->email : "");
$this->user->profile->emailVerified = (property_exists($verified,'email'))?$verified->email:""; $this->user->profile->emailVerified = (property_exists($verified, 'email')) ? $verified->email : "";
if (property_exists($response, 'emails')) { if (property_exists($response, 'emails')) {
if (count($response->emails) == 1) { if (count($response->emails) == 1) {
$this->user->profile->email = $response->emails[0]->value; $this->user->profile->email = $response->emails[0]->value;
@@ -109,103 +112,116 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2
} }
} }
} }
} if (property_exists($verified, 'emails')) {
$this->user->profile->phone = (property_exists($response,'phone'))?$response->phone:""; if (count($verified->emails) == 1) {
$this->user->profile->country = (property_exists($response,'country'))?$response->country:""; $this->user->profile->emailVerified = $verified->emails[0]->value;
$this->user->profile->region = (property_exists($response,'region'))?$response->region:""; } else {
$this->user->profile->zip = (property_exists($response,'zip'))?$response->zip:""; foreach ($verified->emails as $email) {
if( property_exists($response,'placesLived') ){ if ($email->type == 'account') {
$this->user->profile->city = ""; $this->user->profile->emailVerified = $email->value;
$this->user->profile->address = ""; break;
foreach($response->placesLived as $c){ }
if(property_exists($c,'primary')){
if($c->primary == true){
$this->user->profile->address = $c->value;
$this->user->profile->city = $c->value;
break;
} }
}else{
if(property_exists($c,'value')){
$this->user->profile->address = $c->value;
$this->user->profile->city = $c->value;
}
} }
} }
} }
$this->user->profile->phone = (property_exists($response, 'phone')) ? $response->phone : "";
// google API returns multiple urls, but a "website" only if it is verified $this->user->profile->country = (property_exists($response, 'country')) ? $response->country : "";
$this->user->profile->region = (property_exists($response, 'region')) ? $response->region : "";
$this->user->profile->zip = (property_exists($response, 'zip')) ? $response->zip : "";
if (property_exists($response, 'placesLived')) {
$this->user->profile->city = "";
$this->user->profile->address = "";
foreach ($response->placesLived as $c) {
if (property_exists($c, 'primary')) {
if ($c->primary == true) {
$this->user->profile->address = $c->value;
$this->user->profile->city = $c->value;
break;
}
} else {
if (property_exists($c, 'value')) {
$this->user->profile->address = $c->value;
$this->user->profile->city = $c->value;
}
}
}
}
// google API returns multiple urls, but a "website" only if it is verified
// see http://support.google.com/plus/answer/1713826?hl=en // see http://support.google.com/plus/answer/1713826?hl=en
if( property_exists($response,'urls') ){ if (property_exists($response, 'urls')) {
foreach($response->urls as $u){ foreach ($response->urls as $u) {
if(property_exists($u, 'primary') && $u->primary == true) $this->user->profile->webSiteURL = $u->value; if (property_exists($u, 'primary') && $u->primary == true)
$this->user->profile->webSiteURL = $u->value;
} }
} else { } else {
$this->user->profile->webSiteURL = ''; $this->user->profile->webSiteURL = '';
} }
// google API returns age ranges or min. age only (with plus.login scope) // google API returns age ranges or min. age only (with plus.login scope)
if( property_exists($response,'ageRange') ){ if (property_exists($response, 'ageRange')) {
if( property_exists($response->ageRange,'min') && property_exists($response->ageRange,'max') ){ if (property_exists($response->ageRange, 'min') && property_exists($response->ageRange, 'max')) {
$this->user->profile->age = $response->ageRange->min.' - '.$response->ageRange->max; $this->user->profile->age = $response->ageRange->min . ' - ' . $response->ageRange->max;
} else { } else {
$this->user->profile->age = '> '.$response->ageRange->min; $this->user->profile->age = '> ' . $response->ageRange->min;
} }
} else { } else {
$this->user->profile->age = ''; $this->user->profile->age = '';
} }
// google API returns birthdays only if a user set 'show in my account' // google API returns birthdays only if a user set 'show in my account'
if( property_exists($response,'birthday') ){ if (property_exists($response, 'birthday')) {
list($birthday_year, $birthday_month, $birthday_day) = explode( '-', $response->birthday ); list($birthday_year, $birthday_month, $birthday_day) = explode('-', $response->birthday);
$this->user->profile->birthDay = (int) $birthday_day; $this->user->profile->birthDay = (int) $birthday_day;
$this->user->profile->birthMonth = (int) $birthday_month; $this->user->profile->birthMonth = (int) $birthday_month;
$this->user->profile->birthYear = (int) $birthday_year; $this->user->profile->birthYear = (int) $birthday_year;
} else { } else {
$this->user->profile->birthDay=0;$this->user->profile->birthMonth=0;$this->user->profile->birthYear=0; $this->user->profile->birthDay = 0;
$this->user->profile->birthMonth = 0;
$this->user->profile->birthYear = 0;
} }
return $this->user->profile; return $this->user->profile;
} }
/** /**
* load the user (Gmail and google plus) contacts * {@inheritdoc}
* ..toComplete */
*/ function getUserContacts() {
function getUserContacts() // refresh tokens if needed
{ $this->refreshToken();
// refresh tokens if needed
$this->refreshToken();
$contacts = array(); $contacts = array();
if( ! isset( $this->config['contacts_param'] ) ){ if (!isset($this->config['contacts_param'])) {
$this->config['contacts_param'] = array( "max-results" => 500 ); $this->config['contacts_param'] = array("max-results" => 500);
} }
// Google Gmail and Android contacts // Google Gmail and Android contacts
if (strpos($this->scope, '/m8/feeds/') !== false) { if (strpos($this->scope, '/m8/feeds/') !== false) {
$response = $this->api->api( "https://www.google.com/m8/feeds/contacts/default/full?" $response = $this->api->api("https://www.google.com/m8/feeds/contacts/default/full?"
. http_build_query( array_merge( array('alt' => 'json', 'v' => '3.0'), $this->config['contacts_param'] ) ) ); . http_build_query(array_merge(array('alt' => 'json', 'v' => '3.0'), $this->config['contacts_param'])));
if( ! $response ){ if (!$response) {
return ARRAY(); return array();
} }
if (isset($response->feed->entry)) { if (isset($response->feed->entry)) {
foreach( $response->feed->entry as $idx => $entry ){ foreach ($response->feed->entry as $idx => $entry) {
$uc = new Hybrid_User_Contact(); $uc = new Hybrid_User_Contact();
$uc->email = isset($entry->{'gd$email'}[0]->address) ? (string) $entry->{'gd$email'}[0]->address : ''; $uc->email = isset($entry->{'gd$email'}[0]->address) ? (string) $entry->{'gd$email'}[0]->address : '';
$uc->displayName = isset($entry->title->{'$t'}) ? (string) $entry->title->{'$t'} : ''; $uc->displayName = isset($entry->title->{'$t'}) ? (string) $entry->title->{'$t'} : '';
$uc->identifier = ($uc->email!='')?$uc->email:''; $uc->identifier = ($uc->email != '') ? $uc->email : '';
$uc->description = ''; $uc->description = '';
if( property_exists($entry,'link') ){ if (property_exists($entry, 'link')) {
/** /**
* sign links with access_token * sign links with access_token
*/ */
if(is_array($entry->link)){ if (is_array($entry->link)) {
foreach($entry->link as $l){ foreach ($entry->link as $l) {
if( property_exists($l,'gd$etag') && $l->type=="image/*"){ if (property_exists($l, 'gd$etag') && $l->type == "image/*") {
$uc->photoURL = $this->addUrlParam($l->href, array('access_token' => $this->api->access_token)); $uc->photoURL = $this->addUrlParam($l->href, array('access_token' => $this->api->access_token));
} else if($l->type=="self"){ } else if ($l->type == "self") {
$uc->profileURL = $this->addUrlParam($l->href, array('access_token' => $this->api->access_token)); $uc->profileURL = $this->addUrlParam($l->href, array('access_token' => $this->api->access_token));
} }
} }
@@ -213,10 +229,11 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2
} else { } else {
$uc->profileURL = ''; $uc->profileURL = '';
} }
if( property_exists($response,'website') ){ if (property_exists($response, 'website')) {
if(is_array($response->website)){ if (is_array($response->website)) {
foreach($response->website as $w){ foreach ($response->website as $w) {
if($w->primary == true) $uc->webSiteURL = $w->value; if ($w->primary == true)
$uc->webSiteURL = $w->value;
} }
} else { } else {
$uc->webSiteURL = $response->website->value; $uc->webSiteURL = $response->website->value;
@@ -229,52 +246,52 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2
} }
} }
} }
// Google social contacts // Google social contacts
if (strpos($this->scope, '/auth/plus.login') !== false) { if (strpos($this->scope, '/auth/plus.login') !== false) {
$response = $this->api->api( "https://www.googleapis.com/plus/v1/people/me/people/visible?" $response = $this->api->api("https://www.googleapis.com/plus/v1/people/me/people/visible?"
. http_build_query( $this->config['contacts_param'] ) ); . http_build_query($this->config['contacts_param']));
if( ! $response ){ if (!$response) {
return ARRAY(); return array();
} }
foreach( $response->items as $idx => $item ){ foreach ($response->items as $idx => $item) {
$uc = new Hybrid_User_Contact(); $uc = new Hybrid_User_Contact();
$uc->email = (property_exists($item,'email'))?$item->email:''; $uc->email = (property_exists($item, 'email')) ? $item->email : '';
$uc->displayName = (property_exists($item,'displayName'))?$item->displayName:''; $uc->displayName = (property_exists($item, 'displayName')) ? $item->displayName : '';
$uc->identifier = (property_exists($item,'id'))?$item->id:''; $uc->identifier = (property_exists($item, 'id')) ? $item->id : '';
$uc->description = (property_exists($item,'objectType'))?$item->objectType:''; $uc->description = (property_exists($item, 'objectType')) ? $item->objectType : '';
$uc->photoURL = (property_exists($item,'image'))?((property_exists($item->image,'url'))?$item->image->url:''):''; $uc->photoURL = (property_exists($item, 'image')) ? ((property_exists($item->image, 'url')) ? $item->image->url : '') : '';
$uc->profileURL = (property_exists($item,'url'))?$item->url:''; $uc->profileURL = (property_exists($item, 'url')) ? $item->url : '';
$uc->webSiteURL = ''; $uc->webSiteURL = '';
$contacts[] = $uc; $contacts[] = $uc;
} }
} }
return $contacts; return $contacts;
} }
/** /**
* Add to the $url new parameters * Add query parameters to the $url
* @param string $url *
* @param array $params * @param string $url URL
* @param array $params Parameters to add
* @return string * @return string
*/ */
function addUrlParam($url, array $params) function addUrlParam($url, array $params) {
{
$query = parse_url($url, PHP_URL_QUERY); $query = parse_url($url, PHP_URL_QUERY);
// Returns the URL string with new parameters // Returns the URL string with new parameters
if( $query ) { if ($query) {
$url .= '&' . http_build_query( $params ); $url .= '&' . http_build_query($params);
} else { } else {
$url .= '?' . http_build_query( $params ); $url .= '?' . http_build_query($params);
} }
return $url; return $url;
} }
} }

View File

@@ -1,168 +1,169 @@
<?php <?php
/*!
* HybridAuth /* !
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * HybridAuth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
*/ * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* Hybrid_Providers_LinkedIn provider adapter based on OAuth1 protocol * Hybrid_Providers_LinkedIn provider adapter based on OAuth1 protocol
* *
* Hybrid_Providers_LinkedIn use linkedinPHP library created by fiftyMission Inc. * Hybrid_Providers_LinkedIn use linkedinPHP library created by fiftyMission Inc.
* *
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_LinkedIn.html * http://hybridauth.sourceforge.net/userguide/IDProvider_info_LinkedIn.html
*/ */
class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model {
{
/** /**
* IDp wrappers initializer * Provider API Wrapper
*/ * @var LinkedIn
function initialize() */
{ public $api;
if ( ! $this->config["keys"]["key"] || ! $this->config["keys"]["secret"] ){
throw new Exception( "Your application key and secret are required in order to connect to {$this->providerId}.", 4 ); /**
* {@inheritdoc}
*/
function initialize() {
if (!$this->config["keys"]["key"] || !$this->config["keys"]["secret"]) {
throw new Exception("Your application key and secret are required in order to connect to {$this->providerId}.", 4);
} }
if ( ! class_exists('OAuthConsumer') ) { if (!class_exists('OAuthConsumer', false)) {
require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth.php"; require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth.php";
} }
require_once Hybrid_Auth::$config["path_libraries"] . "LinkedIn/LinkedIn.php"; require_once Hybrid_Auth::$config["path_libraries"] . "LinkedIn/LinkedIn.php";
$this->api = new LinkedIn( array( 'appKey' => $this->config["keys"]["key"], 'appSecret' => $this->config["keys"]["secret"], 'callbackUrl' => $this->endpoint ) ); $this->api = new LinkedIn(array('appKey' => $this->config["keys"]["key"], 'appSecret' => $this->config["keys"]["secret"], 'callbackUrl' => $this->endpoint));
if( $this->token( "access_token_linkedin" ) ){ if ($this->token("access_token_linkedin")) {
$this->api->setTokenAccess( $this->token( "access_token_linkedin" ) ); $this->api->setTokenAccess($this->token("access_token_linkedin"));
} }
} }
/** /**
* begin login step * {@inheritdoc}
*/ */
function loginBegin() function loginBegin() {
{
// send a request for a LinkedIn access token // send a request for a LinkedIn access token
$response = $this->api->retrieveTokenRequest(); $response = $this->api->retrieveTokenRequest();
if( isset( $response['success'] ) && $response['success'] === TRUE ){ if (isset($response['success']) && $response['success'] === true) {
$this->token( "oauth_token", $response['linkedin']['oauth_token'] ); $this->token("oauth_token", $response['linkedin']['oauth_token']);
$this->token( "oauth_token_secret", $response['linkedin']['oauth_token_secret'] ); $this->token("oauth_token_secret", $response['linkedin']['oauth_token_secret']);
# redirect user to LinkedIn authorisation web page # redirect user to LinkedIn authorisation web page
Hybrid_Auth::redirect( LINKEDIN::_URL_AUTH . $response['linkedin']['oauth_token'] ); Hybrid_Auth::redirect(LINKEDIN::_URL_AUTH . $response['linkedin']['oauth_token']);
} } else {
else{ throw new Exception("Authentication failed! {$this->providerId} returned an invalid Token in response: " . Hybrid_Logger::dumpData( $response ), 5);
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid Token.", 5 );
} }
} }
/** /**
* finish login step * {@inheritdoc}
*/ */
function loginFinish() function loginFinish() {
{ // in case we get oauth_problem=user_refused
$oauth_token = $_REQUEST['oauth_token']; if (isset($_REQUEST['oauth_problem']) && $_REQUEST['oauth_problem'] == "user_refused") {
$oauth_verifier = $_REQUEST['oauth_verifier']; throw new Exception("Authentication failed! The user denied your request.", 5);
}
if ( ! $oauth_verifier ){ $oauth_token = isset($_REQUEST['oauth_token']) ? $_REQUEST['oauth_token'] : null;
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid Token.", 5 ); $oauth_verifier = isset($_REQUEST['oauth_verifier']) ? $_REQUEST['oauth_verifier'] : null;
if (!$oauth_token || !$oauth_verifier) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid Token.", 5);
} }
$response = $this->api->retrieveTokenAccess( $oauth_token, $this->token( "oauth_token_secret" ), $oauth_verifier ); $response = $this->api->retrieveTokenAccess($oauth_token, $this->token("oauth_token_secret"), $oauth_verifier);
if( isset( $response['success'] ) && $response['success'] === TRUE ){ if (isset($response['success']) && $response['success'] === true) {
$this->deleteToken( "oauth_token" ); $this->deleteToken("oauth_token");
$this->deleteToken( "oauth_token_secret" ); $this->deleteToken("oauth_token_secret");
$this->token( "access_token_linkedin", $response['linkedin'] ); $this->token("access_token_linkedin", $response['linkedin']);
$this->token( "access_token" , $response['linkedin']['oauth_token'] ); $this->token("access_token", $response['linkedin']['oauth_token']);
$this->token( "access_token_secret" , $response['linkedin']['oauth_token_secret'] ); $this->token("access_token_secret", $response['linkedin']['oauth_token_secret']);
// set user as logged in // set user as logged in
$this->setUserConnected(); $this->setUserConnected();
} } else {
else{ throw new Exception("Authentication failed! {$this->providerId} returned an invalid Token in response: " . Hybrid_Logger::dumpData( $response ), 5);
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid Token.", 5 );
} }
} }
/** /**
* load the user profile from the IDp api client * {@inheritdoc}
*/ */
function getUserProfile() function getUserProfile() {
{ try {
try{
// http://developer.linkedin.com/docs/DOC-1061 // http://developer.linkedin.com/docs/DOC-1061
$response = $this->api->profile('~:(id,first-name,last-name,public-profile-url,picture-url,email-address,date-of-birth,phone-numbers,summary)'); $response = $this->api->profile('~:(id,first-name,last-name,public-profile-url,picture-url,email-address,date-of-birth,phone-numbers,summary)');
} } catch (LinkedInException $e) {
catch( LinkedInException $e ){ throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e->getMessage()}", 6, $e);
throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
} }
if( isset( $response['success'] ) && $response['success'] === TRUE ){ if (isset($response['success']) && $response['success'] === true) {
$data = @ new SimpleXMLElement( $response['linkedin'] ); $data = @ new SimpleXMLElement($response['linkedin']);
if ( ! is_object( $data ) ){ if (!is_object($data)) {
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid xml data.", 6 ); throw new Exception("User profile request failed! {$this->providerId} returned an invalid xml data: " . Hybrid_Logger::dumpData( $data ), 6);
} }
$this->user->profile->identifier = (string) $data->{'id'}; $this->user->profile->identifier = (string) $data->{'id'};
$this->user->profile->firstName = (string) $data->{'first-name'}; $this->user->profile->firstName = (string) $data->{'first-name'};
$this->user->profile->lastName = (string) $data->{'last-name'}; $this->user->profile->lastName = (string) $data->{'last-name'};
$this->user->profile->displayName = trim( $this->user->profile->firstName . " " . $this->user->profile->lastName ); $this->user->profile->displayName = trim($this->user->profile->firstName . " " . $this->user->profile->lastName);
$this->user->profile->email = (string) $data->{'email-address'}; $this->user->profile->email = (string) $data->{'email-address'};
$this->user->profile->emailVerified = (string) $data->{'email-address'}; $this->user->profile->emailVerified = (string) $data->{'email-address'};
$this->user->profile->photoURL = (string) $data->{'picture-url'}; $this->user->profile->photoURL = (string) $data->{'picture-url'};
$this->user->profile->profileURL = (string) $data->{'public-profile-url'}; $this->user->profile->profileURL = (string) $data->{'public-profile-url'};
$this->user->profile->description = (string) $data->{'summary'}; $this->user->profile->description = (string) $data->{'summary'};
if( $data->{'phone-numbers'} && $data->{'phone-numbers'}->{'phone-number'} ){ if ($data->{'phone-numbers'} && $data->{'phone-numbers'}->{'phone-number'}) {
$this->user->profile->phone = (string) $data->{'phone-numbers'}->{'phone-number'}->{'phone-number'}; $this->user->profile->phone = (string) $data->{'phone-numbers'}->{'phone-number'}->{'phone-number'};
} } else {
else{
$this->user->profile->phone = null; $this->user->profile->phone = null;
} }
if( $data->{'date-of-birth'} ){ if ($data->{'date-of-birth'}) {
$this->user->profile->birthDay = (string) $data->{'date-of-birth'}->day; $this->user->profile->birthDay = (string) $data->{'date-of-birth'}->day;
$this->user->profile->birthMonth = (string) $data->{'date-of-birth'}->month; $this->user->profile->birthMonth = (string) $data->{'date-of-birth'}->month;
$this->user->profile->birthYear = (string) $data->{'date-of-birth'}->year; $this->user->profile->birthYear = (string) $data->{'date-of-birth'}->year;
} }
return $this->user->profile; return $this->user->profile;
} } else {
else{ throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData( $response ), 6);
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 );
} }
} }
/** /**
* load the user contacts * {@inheritdoc}
*/ */
function getUserContacts() function getUserContacts() {
{ try {
try{
$response = $this->api->profile('~/connections:(id,first-name,last-name,picture-url,public-profile-url,summary)'); $response = $this->api->profile('~/connections:(id,first-name,last-name,picture-url,public-profile-url,summary)');
} } catch (LinkedInException $e) {
catch( LinkedInException $e ){ throw new Exception("User contacts request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
throw new Exception( "User contacts request failed! {$this->providerId} returned an error: $e" );
} }
if( ! $response || ! $response['success'] ){ if (!$response || !$response['success']) {
return ARRAY(); return array();
} }
$connections = new SimpleXMLElement( $response['linkedin'] ); $connections = new SimpleXMLElement($response['linkedin']);
$contacts = ARRAY();
foreach( $connections->person as $connection ) { $contacts = array();
foreach ($connections->person as $connection) {
$uc = new Hybrid_User_Contact(); $uc = new Hybrid_User_Contact();
$uc->identifier = (string) $connection->id; $uc->identifier = (string) $connection->id;
$uc->displayName = (string) $connection->{'last-name'} . " " . $connection->{'first-name'}; $uc->displayName = (string) $connection->{'last-name'} . " " . $connection->{'first-name'};
$uc->profileURL = (string) $connection->{'public-profile-url'}; $uc->profileURL = (string) $connection->{'public-profile-url'};
$uc->photoURL = (string) $connection->{'picture-url'}; $uc->photoURL = (string) $connection->{'picture-url'};
$uc->description = (string) $connection->{'summary'}; $uc->description = (string) $connection->{'summary'};
$contacts[] = $uc; $contacts[] = $uc;
@@ -172,84 +173,85 @@ class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model
} }
/** /**
* update user status * {@inheritdoc}
*/ */
function setUserStatus( $status ) function setUserStatus($status) {
{
$parameters = array(); $parameters = array();
$private = true; // share with your connections only $private = true; // share with your connections only
if( is_array( $status ) ){ if (is_array($status)) {
if( isset( $status[0] ) && ! empty( $status[0] ) ) $parameters["title"] = $status[0]; // post title if (isset($status[0]) && !empty($status[0]))
if( isset( $status[1] ) && ! empty( $status[1] ) ) $parameters["comment"] = $status[1]; // post comment $parameters["title"] = $status[0]; // post title
if( isset( $status[2] ) && ! empty( $status[2] ) ) $parameters["submitted-url"] = $status[2]; // post url if (isset($status[1]) && !empty($status[1]))
if( isset( $status[3] ) && ! empty( $status[3] ) ) $parameters["submitted-image-url"] = $status[3]; // post picture url $parameters["comment"] = $status[1]; // post comment
if( isset( $status[4] ) && ! empty( $status[4] ) ) $private = $status[4]; // true or false if (isset($status[2]) && !empty($status[2]))
$parameters["submitted-url"] = $status[2]; // post url
if (isset($status[3]) && !empty($status[3]))
$parameters["submitted-image-url"] = $status[3]; // post picture url
if (isset($status[4]) && !empty($status[4]))
$private = $status[4]; // true or false
} }
else{ else {
$parameters["comment"] = $status; $parameters["comment"] = $status;
} }
try{ try {
$response = $this->api->share( 'new', $parameters, $private ); $response = $this->api->share('new', $parameters, $private);
} } catch (LinkedInException $e) {
catch( LinkedInException $e ){ throw new Exception("Update user status update failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
throw new Exception( "Update user status update failed! {$this->providerId} returned an error: $e" );
} }
if ( ! $response || ! $response['success'] ) if (!$response || !$response['success']) {
{ throw new Exception("Update user status update failed! {$this->providerId} returned an error in response: " . Hybrid_Logger::dumpData( $response ));
throw new Exception( "Update user status update failed! {$this->providerId} returned an error." );
} }
return $response; return $response;
} }
/** /**
* load the user latest activity * load the user latest activity
* - timeline : all the stream * - timeline : all the stream
* - me : the user activity only * - me : the user activity only
*/ * {@inheritdoc}
function getUserActivity( $stream ) */
{ function getUserActivity($stream) {
try{ try {
if( $stream == "me" ){ if ($stream == "me") {
$response = $this->api->updates( '?type=SHAR&scope=self&count=25' ); $response = $this->api->updates('?type=SHAR&scope=self&count=25');
} else {
$response = $this->api->updates('?type=SHAR&count=25');
} }
else{ } catch (LinkedInException $e) {
$response = $this->api->updates( '?type=SHAR&count=25' ); throw new Exception("User activity stream request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
}
catch( LinkedInException $e ){
throw new Exception( "User activity stream request failed! {$this->providerId} returned an error: $e" );
} }
if( ! $response || ! $response['success'] ){ if (!$response || !$response['success']) {
return ARRAY(); return array();
} }
$updates = new SimpleXMLElement( $response['linkedin'] ); $updates = new SimpleXMLElement($response['linkedin']);
$activities = ARRAY(); $activities = array();
foreach( $updates->update as $update ) { foreach ($updates->update as $update) {
$person = $update->{'update-content'}->person; $person = $update->{'update-content'}->person;
$share = $update->{'update-content'}->person->{'current-share'}; $share = $update->{'update-content'}->person->{'current-share'};
$ua = new Hybrid_User_Activity(); $ua = new Hybrid_User_Activity();
$ua->id = (string) $update->id; $ua->id = (string) $update->id;
$ua->date = (string) $update->timestamp; $ua->date = (string) $update->timestamp;
$ua->text = (string) $share->{'comment'}; $ua->text = (string) $share->{'comment'};
$ua->user->identifier = (string) $person->id;
$ua->user->displayName = (string) $person->{'first-name'} . ' ' . $person->{'last-name'};
$ua->user->profileURL = (string) $person->{'site-standard-profile-request'}->url;
$ua->user->photoURL = null;
$ua->user->identifier = (string) $person->id;
$ua->user->displayName = (string) $person->{'first-name'} . ' ' . $person->{'last-name'};
$ua->user->profileURL = (string) $person->{'site-standard-profile-request'}->url;
$ua->user->photoURL = NULL;
$activities[] = $ua; $activities[] = $ua;
} }
return $activities; return $activities;
} }
} }

View File

@@ -1,106 +1,102 @@
<?php <?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Windows Live OAuth2 Class * Windows Live OAuth2 Class
* *
* @package HybridAuth providers package * @package HybridAuth providers package
* @author Lukasz Koprowski <azram19@gmail.com> * @author Lukasz Koprowski <azram19@gmail.com>
* @version 0.2 * @version 0.2
* @license BSD License * @license BSD License
*/ */
/** /**
* Hybrid_Providers_Live - Windows Live provider adapter based on OAuth2 protocol * Hybrid_Providers_Live - Windows Live provider adapter based on OAuth2 protocol
*/ */
class Hybrid_Providers_Live extends Hybrid_Provider_Model_OAuth2 class Hybrid_Providers_Live extends Hybrid_Provider_Model_OAuth2 {
{
// default permissions /**
* {@inheritdoc}
*/
public $scope = "wl.basic wl.contacts_emails wl.emails wl.signin wl.share wl.birthday"; public $scope = "wl.basic wl.contacts_emails wl.emails wl.signin wl.share wl.birthday";
/** /**
* IDp wrappers initializer * {@inheritdoc}
*/ */
function initialize() function initialize() {
{
parent::initialize(); parent::initialize();
// Provider api end-points // Provider api end-points
$this->api->api_base_url = 'https://apis.live.net/v5.0/'; $this->api->api_base_url = 'https://apis.live.net/v5.0/';
$this->api->authorize_url = 'https://login.live.com/oauth20_authorize.srf'; $this->api->authorize_url = 'https://login.live.com/oauth20_authorize.srf';
$this->api->token_url = 'https://login.live.com/oauth20_token.srf'; $this->api->token_url = 'https://login.live.com/oauth20_token.srf';
$this->api->curl_authenticate_method = "GET"; $this->api->curl_authenticate_method = "GET";
} }
/** /**
* grab the user profile from the api client * {@inheritdoc}
*/ */
function getUserProfile() function getUserProfile() {
{ $data = $this->api->get("me");
$data = $this->api->get( "me" );
if ( ! isset( $data->id ) ){ if (!isset($data->id)) {
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 ); throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData( $data ), 6);
} }
$this->user->profile->identifier = (property_exists($data,'id'))?$data->id:""; $this->user->profile->identifier = (property_exists($data, 'id')) ? $data->id : "";
$this->user->profile->firstName = (property_exists($data,'first_name'))?$data->first_name:""; $this->user->profile->firstName = (property_exists($data, 'first_name')) ? $data->first_name : "";
$this->user->profile->lastName = (property_exists($data,'last_name'))?$data->last_name:""; $this->user->profile->lastName = (property_exists($data, 'last_name')) ? $data->last_name : "";
$this->user->profile->displayName = (property_exists($data,'name'))?trim( $data->name ):""; $this->user->profile->displayName = (property_exists($data, 'name')) ? trim($data->name) : "";
$this->user->profile->gender = (property_exists($data,'gender'))?$data->gender:""; $this->user->profile->gender = (property_exists($data, 'gender')) ? $data->gender : "";
//wl.basic //wl.basic
$this->user->profile->profileURL = (property_exists($data,'link'))?$data->link:""; $this->user->profile->profileURL = (property_exists($data, 'link')) ? $data->link : "";
//wl.emails //wl.emails
$this->user->profile->email = (property_exists($data,'emails'))?$data->emails->account:""; $this->user->profile->email = (property_exists($data, 'emails')) ? $data->emails->account : "";
$this->user->profile->emailVerified = (property_exists($data,'emails'))?$data->emails->account:""; $this->user->profile->emailVerified = (property_exists($data, 'emails')) ? $data->emails->account : "";
//wl.birthday //wl.birthday
$this->user->profile->birthDay = (property_exists($data,'birth_day'))?$data->birth_day:""; $this->user->profile->birthDay = (property_exists($data, 'birth_day')) ? $data->birth_day : "";
$this->user->profile->birthMonth = (property_exists($data,'birth_month'))?$data->birth_month:""; $this->user->profile->birthMonth = (property_exists($data, 'birth_month')) ? $data->birth_month : "";
$this->user->profile->birthYear = (property_exists($data,'birth_year'))?$data->birth_year:""; $this->user->profile->birthYear = (property_exists($data, 'birth_year')) ? $data->birth_year : "";
return $this->user->profile; return $this->user->profile;
} }
/** /**
* load the current logged in user contacts list from the IDp api client * Windows Live api does not support retrieval of email addresses (only hashes :/)
*/ * {@inheritdoc}
*/
function getUserContacts() {
$response = $this->api->get('me/contacts');
/* Windows Live api does not support retrieval of email addresses (only hashes :/) */ if ($this->api->http_code != 200) {
function getUserContacts() throw new Exception('User contacts request failed! ' . $this->providerId . ' returned an error: ' . $this->errorMessageByStatus($this->api->http_code));
{
$response = $this->api->get( 'me/contacts' );
if ( $this->api->http_code != 200 )
{
throw new Exception( 'User contacts request failed! ' . $this->providerId . ' returned an error: ' . $this->errorMessageByStatus( $this->api->http_code ) );
} }
if ( !isset($response->data) || ( isset($response->errcode) && $response->errcode != 0 ) ) if (!isset($response->data) || ( isset($response->errcode) && $response->errcode != 0 )) {
{
return array(); return array();
} }
$contacts = array(); $contacts = array();
foreach( $response->data as $item ) { foreach ($response->data as $item) {
$uc = new Hybrid_User_Contact(); $uc = new Hybrid_User_Contact();
$uc->identifier = (property_exists($item,'id'))?$item->id:""; $uc->identifier = (property_exists($item, 'id')) ? $item->id : "";
$uc->displayName = (property_exists($item,'name'))?$item->name:""; $uc->displayName = (property_exists($item, 'name')) ? $item->name : "";
$uc->email = (property_exists($item,'emails'))?$item->emails->preferred:""; $uc->email = (property_exists($item, 'emails')) ? $item->emails->preferred : "";
$contacts[] = $uc; $contacts[] = $uc;
} }
return $contacts; return $contacts;
} }
} }

View File

@@ -1,15 +1,16 @@
<?php <?php
/*!
* HybridAuth /* !
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * HybridAuth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
*/ * (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* Hybrid_Providers_OpenID provider adapter for any idp openid based * Hybrid_Providers_OpenID provider adapter for any idp openid based
* *
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_OpenID.html * http://hybridauth.sourceforge.net/userguide/IDProvider_info_OpenID.html
*/ */
class Hybrid_Providers_OpenID extends Hybrid_Provider_Model_OpenID class Hybrid_Providers_OpenID extends Hybrid_Provider_Model_OpenID {
{
} }

View File

@@ -1,270 +1,263 @@
<?php <?php
/*!
* HybridAuth /* !
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * HybridAuth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
*/ * (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* Hybrid_Providers_Twitter provider adapter based on OAuth1 protocol * Hybrid_Providers_Twitter provider adapter based on OAuth1 protocol
*/ */
class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1 class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1 {
{
/** /**
* IDp wrappers initializer * {@inheritdoc}
*/ */
function initialize() function initialize() {
{
parent::initialize(); parent::initialize();
// Provider api end-points // Provider api end-points
$this->api->api_base_url = "https://api.twitter.com/1.1/"; $this->api->api_base_url = "https://api.twitter.com/1.1/";
$this->api->authorize_url = "https://api.twitter.com/oauth/authenticate"; $this->api->authorize_url = "https://api.twitter.com/oauth/authenticate";
$this->api->request_token_url = "https://api.twitter.com/oauth/request_token"; $this->api->request_token_url = "https://api.twitter.com/oauth/request_token";
$this->api->access_token_url = "https://api.twitter.com/oauth/access_token"; $this->api->access_token_url = "https://api.twitter.com/oauth/access_token";
if ( isset( $this->config['api_version'] ) && $this->config['api_version'] ){ if (isset($this->config['api_version']) && $this->config['api_version']) {
$this->api->api_base_url = "https://api.twitter.com/{$this->config['api_version']}/"; $this->api->api_base_url = "https://api.twitter.com/{$this->config['api_version']}/";
} }
if ( isset( $this->config['authorize'] ) && $this->config['authorize'] ){ if (isset($this->config['authorize']) && $this->config['authorize']) {
$this->api->authorize_url = "https://api.twitter.com/oauth/authorize"; $this->api->authorize_url = "https://api.twitter.com/oauth/authorize";
} }
$this->api->curl_auth_header = false; $this->api->curl_auth_header = false;
} }
/** /**
* begin login step * {@inheritdoc}
*/ */
function loginBegin() function loginBegin() {
{
// Initiate the Reverse Auth flow; cf. https://dev.twitter.com/docs/ios/using-reverse-auth // Initiate the Reverse Auth flow; cf. https://dev.twitter.com/docs/ios/using-reverse-auth
if (isset($_REQUEST['reverse_auth']) && ($_REQUEST['reverse_auth'] == 'yes')){ if (isset($_REQUEST['reverse_auth']) && ($_REQUEST['reverse_auth'] == 'yes')) {
$stage1 = $this->api->signedRequest( $this->api->request_token_url, 'POST', array( 'x_auth_mode' => 'reverse_auth' ) ); $stage1 = $this->api->signedRequest($this->api->request_token_url, 'POST', array('x_auth_mode' => 'reverse_auth'));
if ( $this->api->http_code != 200 ){ if ($this->api->http_code != 200) {
throw new Exception( "Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ), 5 ); throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
} }
$responseObj = array( 'x_reverse_auth_parameters' => $stage1, 'x_reverse_auth_target' => $this->config["keys"]["key"] ); $responseObj = array('x_reverse_auth_parameters' => $stage1, 'x_reverse_auth_target' => $this->config["keys"]["key"]);
$response = json_encode($responseObj); $response = json_encode($responseObj);
header( "Content-Type: application/json", true, 200 ) ; header("Content-Type: application/json", true, 200);
echo $response; echo $response;
die(); die();
} }
$tokens = $this->api->requestToken( $this->endpoint ); $tokens = $this->api->requestToken($this->endpoint);
// request tokens as received from provider // request tokens as received from provider
$this->request_tokens_raw = $tokens; $this->request_tokens_raw = $tokens;
// check the last HTTP status code returned // check the last HTTP status code returned
if ( $this->api->http_code != 200 ){ if ($this->api->http_code != 200) {
throw new Exception( "Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ), 5 ); throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
} }
if ( ! isset( $tokens["oauth_token"] ) ){ if (!isset($tokens["oauth_token"])) {
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid oauth token.", 5 ); throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth token.", 5);
} }
$this->token( "request_token" , $tokens["oauth_token"] ); $this->token("request_token", $tokens["oauth_token"]);
$this->token( "request_token_secret", $tokens["oauth_token_secret"] ); $this->token("request_token_secret", $tokens["oauth_token_secret"]);
// redirect the user to the provider authentication url with force_login // redirect the user to the provider authentication url with force_login
if ( ( isset( $this->config['force_login'] ) && $this->config['force_login'] ) || ( isset( $this->config[ 'force' ] ) && $this->config[ 'force' ] === true ) ){ if (( isset($this->config['force_login']) && $this->config['force_login'] ) || ( isset($this->config['force']) && $this->config['force'] === true )) {
Hybrid_Auth::redirect( $this->api->authorizeUrl( $tokens, array( 'force_login' => true ) ) ); Hybrid_Auth::redirect($this->api->authorizeUrl($tokens, array('force_login' => true)));
} }
// else, redirect the user to the provider authentication url // else, redirect the user to the provider authentication url
Hybrid_Auth::redirect( $this->api->authorizeUrl( $tokens ) ); Hybrid_Auth::redirect($this->api->authorizeUrl($tokens));
} }
/** /**
* finish login step * {@inheritdoc}
*/ */
function loginFinish() function loginFinish() {
{
// in case we are completing a Reverse Auth flow; cf. https://dev.twitter.com/docs/ios/using-reverse-auth // in case we are completing a Reverse Auth flow; cf. https://dev.twitter.com/docs/ios/using-reverse-auth
if(isset($_REQUEST['oauth_token_secret'])){ if (isset($_REQUEST['oauth_token_secret'])) {
$tokens = $_REQUEST; $tokens = $_REQUEST;
$this->access_tokens_raw = $tokens; $this->access_tokens_raw = $tokens;
// we should have an access_token unless something has gone wrong // we should have an access_token unless something has gone wrong
if ( ! isset( $tokens["oauth_token"] ) ){ if (!isset($tokens["oauth_token"])) {
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid access token.", 5 ); throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5);
} }
// Get rid of tokens we don't need // Get rid of tokens we don't need
$this->deleteToken( "request_token" ); $this->deleteToken("request_token");
$this->deleteToken( "request_token_secret" ); $this->deleteToken("request_token_secret");
// Store access_token and secret for later use // Store access_token and secret for later use
$this->token( "access_token" , $tokens['oauth_token'] ); $this->token("access_token", $tokens['oauth_token']);
$this->token( "access_token_secret" , $tokens['oauth_token_secret'] ); $this->token("access_token_secret", $tokens['oauth_token_secret']);
// set user as logged in to the current provider // set user as logged in to the current provider
$this->setUserConnected(); $this->setUserConnected();
return; return;
} }
parent::loginFinish(); parent::loginFinish();
} }
/** /**
* load the user profile from the IDp api client * {@inheritdoc}
*/ */
function getUserProfile() function getUserProfile() {
{ $includeEmail = isset($this->config['includeEmail']) ? (bool) $this->config['includeEmail'] : false;
$response = $this->api->get( 'account/verify_credentials.json' ); $response = $this->api->get('account/verify_credentials.json'. ($includeEmail ? '?include_email=true' : ''));
// check the last HTTP status code returned // check the last HTTP status code returned
if ( $this->api->http_code != 200 ){ if ($this->api->http_code != 200) {
throw new Exception( "User profile request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ), 6 ); throw new Exception("User profile request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 6);
} }
if ( ! is_object( $response ) || ! isset( $response->id ) ){ if (!is_object($response) || !isset($response->id)) {
throw new Exception( "User profile request failed! {$this->providerId} api returned an invalid response.", 6 ); throw new Exception("User profile request failed! {$this->providerId} api returned an invalid response: " . Hybrid_Logger::dumpData( $response ), 6);
} }
# store the user profile. # store the user profile.
$this->user->profile->identifier = (property_exists($response,'id'))?$response->id:""; $this->user->profile->identifier = (property_exists($response, 'id')) ? $response->id : "";
$this->user->profile->displayName = (property_exists($response,'screen_name'))?$response->screen_name:""; $this->user->profile->displayName = (property_exists($response, 'screen_name')) ? $response->screen_name : "";
$this->user->profile->description = (property_exists($response,'description'))?$response->description:""; $this->user->profile->description = (property_exists($response, 'description')) ? $response->description : "";
$this->user->profile->firstName = (property_exists($response,'name'))?$response->name:""; $this->user->profile->firstName = (property_exists($response, 'name')) ? $response->name : "";
$this->user->profile->photoURL = (property_exists($response,'profile_image_url'))?(str_replace('_normal', '', $response->profile_image_url)):""; $this->user->profile->photoURL = (property_exists($response, 'profile_image_url')) ? (str_replace('_normal', '', $response->profile_image_url)) : "";
$this->user->profile->profileURL = (property_exists($response,'screen_name'))?("http://twitter.com/".$response->screen_name):""; $this->user->profile->profileURL = (property_exists($response, 'screen_name')) ? ("http://twitter.com/" . $response->screen_name) : "";
$this->user->profile->webSiteURL = (property_exists($response,'url'))?$response->url:""; $this->user->profile->webSiteURL = (property_exists($response, 'url')) ? $response->url : "";
$this->user->profile->region = (property_exists($response,'location'))?$response->location:""; $this->user->profile->region = (property_exists($response, 'location')) ? $response->location : "";
if($includeEmail) $this->user->profile->email = (property_exists($response, 'email')) ? $response->email : "";
return $this->user->profile; return $this->user->profile;
} }
/** /**
* load the user contacts * {@inheritdoc}
*/ */
function getUserContacts() function getUserContacts() {
{ $parameters = array('cursor' => '-1');
$parameters = array( 'cursor' => '-1' ); $response = $this->api->get('friends/ids.json', $parameters);
$response = $this->api->get( 'friends/ids.json', $parameters );
// check the last HTTP status code returned // check the last HTTP status code returned
if ( $this->api->http_code != 200 ){ if ($this->api->http_code != 200) {
throw new Exception( "User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) ); throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
} }
if( ! $response || ! count( $response->ids ) ){ if (!$response || !count($response->ids)) {
return ARRAY(); return array();
} }
// 75 id per time should be okey // 75 id per time should be okey
$contactsids = array_chunk ( $response->ids, 75 ); $contactsids = array_chunk($response->ids, 75);
$contacts = ARRAY(); $contacts = array();
foreach( $contactsids as $chunk ){ foreach ($contactsids as $chunk) {
$parameters = array( 'user_id' => implode( ",", $chunk ) ); $parameters = array('user_id' => implode(",", $chunk));
$response = $this->api->get( 'users/lookup.json', $parameters ); $response = $this->api->get('users/lookup.json', $parameters);
// check the last HTTP status code returned // check the last HTTP status code returned
if ( $this->api->http_code != 200 ){ if ($this->api->http_code != 200) {
throw new Exception( "User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) ); throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
} }
if( $response && count( $response ) ){ if ($response && count($response)) {
foreach( $response as $item ){ foreach ($response as $item) {
$uc = new Hybrid_User_Contact(); $uc = new Hybrid_User_Contact();
$uc->identifier = (property_exists($item,'id'))?$item->id:""; $uc->identifier = (property_exists($item, 'id')) ? $item->id : "";
$uc->displayName = (property_exists($item,'name'))?$item->name:""; $uc->displayName = (property_exists($item, 'name')) ? $item->name : "";
$uc->profileURL = (property_exists($item,'screen_name'))?("http://twitter.com/".$item->screen_name):""; $uc->profileURL = (property_exists($item, 'screen_name')) ? ("http://twitter.com/" . $item->screen_name) : "";
$uc->photoURL = (property_exists($item,'profile_image_url'))?$item->profile_image_url:""; $uc->photoURL = (property_exists($item, 'profile_image_url')) ? $item->profile_image_url : "";
$uc->description = (property_exists($item,'description'))?$item->description:""; $uc->description = (property_exists($item, 'description')) ? $item->description : "";
$contacts[] = $uc; $contacts[] = $uc;
} }
} }
} }
return $contacts; return $contacts;
} }
/**
* update user status
*/
function setUserStatus( $status )
{
if( is_array( $status ) && isset( $status[ 'message' ] ) && isset( $status[ 'picture' ] ) ){
$response = $this->api->post( 'statuses/update_with_media.json', array( 'status' => $status[ 'message' ], 'media[]' => file_get_contents( $status[ 'picture' ] ) ), null, null, true );
}else{
$response = $this->api->post( 'statuses/update.json', array( 'status' => $status ) );
}
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
return $response;
}
/** /**
* get user status * {@inheritdoc}
*/ */
function getUserStatus( $tweetid ) function setUserStatus($status) {
{
$info = $this->api->get( 'statuses/show.json?id=' . $tweetid . '&include_entities=true' );
// check the last HTTP status code returned if (is_array($status) && isset($status['message']) && isset($status['picture'])) {
if ( $this->api->http_code != 200 || !isset( $info->id ) ){ $response = $this->api->post('statuses/update_with_media.json', array('status' => $status['message'], 'media[]' => file_get_contents($status['picture'])), null, null, true);
throw new Exception( "Cannot retrieve user status! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) ); } else {
} $response = $this->api->post('statuses/update.json', array('status' => $status));
return $info;
}
/**
* load the user latest activity
* - timeline : all the stream
* - me : the user activity only
*
* by default return the timeline
*/
function getUserActivity( $stream )
{
if( $stream == "me" ){
$response = $this->api->get( 'statuses/user_timeline.json' );
}
else{
$response = $this->api->get( 'statuses/home_timeline.json' );
} }
// check the last HTTP status code returned // check the last HTTP status code returned
if ( $this->api->http_code != 200 ){ if ($this->api->http_code != 200) {
throw new Exception( "User activity stream request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) ); throw new Exception("Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
} }
if( ! $response ){ return $response;
return ARRAY(); }
/**
* {@inheritdoc}
*/
function getUserStatus($tweetid) {
$info = $this->api->get('statuses/show.json?id=' . $tweetid . '&include_entities=true');
// check the last HTTP status code returned
if ($this->api->http_code != 200 || !isset($info->id)) {
throw new Exception("Cannot retrieve user status! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
} }
$activities = ARRAY(); return $info;
}
foreach( $response as $item ){ /**
* load the user latest activity
* - timeline : all the stream
* - me : the user activity only
*
* by default return the timeline
* {@inheritdoc}
*/
function getUserActivity($stream) {
if ($stream == "me") {
$response = $this->api->get('statuses/user_timeline.json');
} else {
$response = $this->api->get('statuses/home_timeline.json');
}
// check the last HTTP status code returned
if ($this->api->http_code != 200) {
throw new Exception("User activity stream request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
}
if (!$response) {
return array();
}
$activities = array();
foreach ($response as $item) {
$ua = new Hybrid_User_Activity(); $ua = new Hybrid_User_Activity();
$ua->id = (property_exists($item,'id'))?$item->id:""; $ua->id = (property_exists($item, 'id')) ? $item->id : "";
$ua->date = (property_exists($item,'created_at'))?strtotime($item->created_at):""; $ua->date = (property_exists($item, 'created_at')) ? strtotime($item->created_at) : "";
$ua->text = (property_exists($item,'text'))?$item->text:""; $ua->text = (property_exists($item, 'text')) ? $item->text : "";
$ua->user->identifier = (property_exists($item->user, 'id')) ? $item->user->id : "";
$ua->user->displayName = (property_exists($item->user, 'name')) ? $item->user->name : "";
$ua->user->profileURL = (property_exists($item->user, 'screen_name')) ? ("http://twitter.com/" . $item->user->screen_name) : "";
$ua->user->photoURL = (property_exists($item->user, 'profile_image_url')) ? $item->user->profile_image_url : "";
$ua->user->identifier = (property_exists($item->user,'id'))?$item->user->id:"";
$ua->user->displayName = (property_exists($item->user,'name'))?$item->user->name:"";
$ua->user->profileURL = (property_exists($item->user,'screen_name'))?("http://twitter.com/".$item->user->screen_name):"";
$ua->user->photoURL = (property_exists($item->user,'profile_image_url'))?$item->user->profile_image_url:"";
$activities[] = $ua; $activities[] = $ua;
} }
return $activities; return $activities;
} }
} }

View File

@@ -1,168 +1,168 @@
<?php <?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /* !
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Yahoo OAuth Class * Yahoo OAuth Class
* *
* @package HybridAuth providers package * @package HybridAuth providers package
* @author Lukasz Koprowski <azram19@gmail.com> * @author Lukasz Koprowski <azram19@gmail.com>
* @version 0.2 * @version 0.2
* @license BSD License * @license BSD License
*/ */
/** /**
* Hybrid_Providers_Yahoo - Yahoo provider adapter based on OAuth1 protocol * Hybrid_Providers_Yahoo - Yahoo provider adapter based on OAuth1 protocol
*/ */
class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth1 class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth1 {
{
function initialize() /**
{ * {@inheritdoc}
*/
function initialize() {
parent::initialize(); parent::initialize();
// Provider api end-points // Provider api end-points
$this->api->api_base_url = 'https://social.yahooapis.com/v1/'; $this->api->api_base_url = 'https://social.yahooapis.com/v1/';
$this->api->authorize_url = 'https://api.login.yahoo.com/oauth/v2/request_auth'; $this->api->authorize_url = 'https://api.login.yahoo.com/oauth/v2/request_auth';
$this->api->request_token_url = 'https://api.login.yahoo.com/oauth/v2/get_request_token'; $this->api->request_token_url = 'https://api.login.yahoo.com/oauth/v2/get_request_token';
$this->api->access_token_url = 'https://api.login.yahoo.com/oauth/v2/get_token'; $this->api->access_token_url = 'https://api.login.yahoo.com/oauth/v2/get_token';
} }
function getUserProfile() /**
{ * {@inheritdoc}
*/
function getUserProfile() {
$userId = $this->getCurrentUserId(); $userId = $this->getCurrentUserId();
$parameters = array(); $parameters = array();
$parameters['format'] = 'json'; $parameters['format'] = 'json';
$response = $this->api->get( 'user/' . $userId . '/profile', $parameters ); $response = $this->api->get('user/' . $userId . '/profile', $parameters);
if ( ! isset( $response->profile ) ){ if (!isset($response->profile)) {
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 ); throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData( $response ), 6);
} }
$data = $response->profile; $data = $response->profile;
$this->user->profile->identifier = (property_exists($data,'guid'))?$data->guid:""; $this->user->profile->identifier = (property_exists($data, 'guid')) ? $data->guid : "";
$this->user->profile->firstName = (property_exists($data,'givenName'))?$data->givenName:""; $this->user->profile->firstName = (property_exists($data, 'givenName')) ? $data->givenName : "";
$this->user->profile->lastName = (property_exists($data,'familyName'))?$data->familyName:""; $this->user->profile->lastName = (property_exists($data, 'familyName')) ? $data->familyName : "";
$this->user->profile->displayName = (property_exists($data,'nickname'))?trim( $data->nickname ):""; $this->user->profile->displayName = (property_exists($data, 'nickname')) ? trim($data->nickname) : "";
$this->user->profile->profileURL = (property_exists($data,'profileUrl'))?$data->profileUrl:""; $this->user->profile->profileURL = (property_exists($data, 'profileUrl')) ? $data->profileUrl : "";
$this->user->profile->gender = (property_exists($data,'gender'))?$data->gender:""; $this->user->profile->gender = (property_exists($data, 'gender')) ? $data->gender : "";
if( $this->user->profile->gender == "F" ){ if ($this->user->profile->gender == "F") {
$this->user->profile->gender = "female"; $this->user->profile->gender = "female";
} }
if( $this->user->profile->gender == "M" ){ if ($this->user->profile->gender == "M") {
$this->user->profile->gender = "male"; $this->user->profile->gender = "male";
} }
if( isset($data->emails) ){ if (isset($data->emails)) {
$email = ""; $email = "";
foreach( $data->emails as $v ){ foreach ($data->emails as $v) {
if( isset($v->primary) && $v->primary ) { if (isset($v->primary) && $v->primary) {
$email = (property_exists($v,'handle'))?$v->handle:""; $email = (property_exists($v, 'handle')) ? $v->handle : "";
break; break;
} }
} }
$this->user->profile->email = $email; $this->user->profile->email = $email;
$this->user->profile->emailVerified = $email; $this->user->profile->emailVerified = $email;
} }
$this->user->profile->age = (property_exists($data,'displayAge'))?$data->displayAge:"";
$this->user->profile->photoURL = (property_exists($data,'image'))?$data->image->imageUrl:"";
$this->user->profile->address = (property_exists($data,'location'))?$data->location:""; $this->user->profile->age = (property_exists($data, 'displayAge')) ? $data->displayAge : "";
$this->user->profile->language = (property_exists($data,'lang'))?$data->lang:""; $this->user->profile->photoURL = (property_exists($data, 'image')) ? $data->image->imageUrl : "";
$this->user->profile->address = (property_exists($data, 'location')) ? $data->location : "";
$this->user->profile->language = (property_exists($data, 'lang')) ? $data->lang : "";
return $this->user->profile; return $this->user->profile;
} }
/** /**
* load the user contacts * {@inheritdoc}
*/ */
function getUserContacts() function getUserContacts() {
{
$userId = $this->getCurrentUserId(); $userId = $this->getCurrentUserId();
$parameters = array(); $parameters = array();
$parameters['format'] = 'json'; $parameters['format'] = 'json';
$parameters['count'] = 'max'; $parameters['count'] = 'max';
$response = $this->api->get('user/' . $userId . '/contacts', $parameters); $response = $this->api->get('user/' . $userId . '/contacts', $parameters);
if ( $this->api->http_code != 200 ) if ($this->api->http_code != 200) {
{ throw new Exception('User contacts request failed! ' . $this->providerId . ' returned an error: ' . $this->errorMessageByStatus($this->api->http_code));
throw new Exception( 'User contacts request failed! ' . $this->providerId . ' returned an error: ' . $this->errorMessageByStatus( $this->api->http_code ) );
} }
if ( !isset($response->contacts) || !isset($response->contacts->contact) || ( isset($response->errcode) && $response->errcode != 0 ) ) if (!isset($response->contacts) || !isset($response->contacts->contact) || ( isset($response->errcode) && $response->errcode != 0 )) {
{
return array(); return array();
} }
$contacts = array(); $contacts = array();
foreach( $response->contacts->contact as $item ) { foreach ($response->contacts->contact as $item) {
$uc = new Hybrid_User_Contact(); $uc = new Hybrid_User_Contact();
$uc->identifier = $this->selectGUID( $item ); $uc->identifier = $this->selectGUID($item);
$uc->email = $this->selectEmail( $item->fields ); $uc->email = $this->selectEmail($item->fields);
$uc->displayName = $this->selectName( $item->fields ); $uc->displayName = $this->selectName($item->fields);
$uc->photoURL = $this->selectPhoto( $item->fields ); $uc->photoURL = $this->selectPhoto($item->fields);
$contacts[] = $uc; $contacts[] = $uc;
} }
return $contacts; return $contacts;
} }
/** /**
* return the user activity stream * {@inheritdoc}
*/ */
function getUserActivity( $stream ) function getUserActivity($stream) {
{
$userId = $this->getCurrentUserId(); $userId = $this->getCurrentUserId();
$parameters = array(); $parameters = array();
$parameters['format'] = 'json'; $parameters['format'] = 'json';
$parameters['count'] = 'max'; $parameters['count'] = 'max';
$response = $this->api->get('user/' . $userId . '/updates', $parameters); $response = $this->api->get('user/' . $userId . '/updates', $parameters);
if( ! $response->updates || $this->api->http_code != 200 ) if (!$response->updates || $this->api->http_code != 200) {
{ throw new Exception('User activity request failed! ' . $this->providerId . ' returned an error: ' . $this->errorMessageByStatus($this->api->http_code));
throw new Exception( 'User activity request failed! ' . $this->providerId . ' returned an error: ' . $this->errorMessageByStatus( $this->api->http_code ) );
} }
$activities = array(); $activities = array();
foreach( $response->updates as $item ){ foreach ($response->updates as $item) {
$ua = new Hybrid_User_Activity(); $ua = new Hybrid_User_Activity();
$ua->id = (property_exists($item,'collectionID'))?$item->collectionID:""; $ua->id = (property_exists($item, 'collectionID')) ? $item->collectionID : "";
$ua->date = (property_exists($item,'lastUpdated'))?$item->lastUpdated:""; $ua->date = (property_exists($item, 'lastUpdated')) ? $item->lastUpdated : "";
$ua->text = (property_exists($item,'loc_longForm'))?$item->loc_longForm:""; $ua->text = (property_exists($item, 'loc_longForm')) ? $item->loc_longForm : "";
$ua->user->identifier = (property_exists($item,'profile_guid'))?$item->profile_guid:""; $ua->user->identifier = (property_exists($item, 'profile_guid')) ? $item->profile_guid : "";
$ua->user->displayName = (property_exists($item,'profile_nickname'))?$item->profile_nickname:""; $ua->user->displayName = (property_exists($item, 'profile_nickname')) ? $item->profile_nickname : "";
$ua->user->profileURL = (property_exists($item,'profile_profileUrl'))?$item->profile_profileUrl:""; $ua->user->profileURL = (property_exists($item, 'profile_profileUrl')) ? $item->profile_profileUrl : "";
$ua->user->photoURL = (property_exists($item,'profile_displayImage'))?$item->profile_displayImage:""; $ua->user->photoURL = (property_exists($item, 'profile_displayImage')) ? $item->profile_displayImage : "";
$activities[] = $ua; $activities[] = $ua;
} }
if( $stream == "me" ){ if ($stream == "me") {
$userId = $this->getCurrentUserId(); $userId = $this->getCurrentUserId();
$my_activities = array(); $my_activities = array();
foreach( $activities as $a ){ foreach ($activities as $a) {
if( $a->user->identifier == $userId ){ if ($a->user->identifier == $userId) {
$my_activities[] = $a; $my_activities[] = $a;
} }
} }
@@ -173,70 +173,104 @@ class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth1
return $activities; return $activities;
} }
//-- /**
* Utility function for returning values from XML-like objects
function select($vs, $t) *
{ * @param stdClass $vs Object
foreach( $vs as $v ){ * @param string $t Property name
if( $v->type == $t ) { * @return mixed
*/
function select($vs, $t) {
foreach ($vs as $v) {
if ($v->type == $t) {
return $v; return $v;
} }
} }
return null;
return NULL;
} }
function selectGUID( $v ) /**
{ * Parses guid
return (property_exists($v,'id'))?$v->id:""; *
* @param stdClass $v Object
* @return string
*/
function selectGUID($v) {
return (property_exists($v, 'id')) ? $v->id : "";
} }
function selectName( $v ) /**
{ * Parses user name
*
* @param stdClass $v Object
* @return string
*/
function selectName($v) {
$s = $this->select($v, 'name'); $s = $this->select($v, 'name');
if( ! $s ){ if (!$s) {
$s = $this->select($v, 'nickname'); $s = $this->select($v, 'nickname');
return ($s)?$s->value:""; return ($s) ? $s->value : "";
} else { } else {
return ($s)?$s->value->givenName . " " . $s->value->familyName:""; return ($s) ? $s->value->givenName . " " . $s->value->familyName : "";
} }
} }
function selectNickame( $v ) /**
{ * Parses nickname
*
* @param stdClass $v Object
* @return string
*/
function selectNickame($v) {
$s = $this->select($v, 'nickname'); $s = $this->select($v, 'nickname');
return ($s)?$s:""; return ($s) ? $s : "";
} }
function selectPhoto( $v ) /**
{ * Parses photo URL
*
* @param stdClass $v Object
* @return string
*/
function selectPhoto($v) {
$s = $this->select($v, 'guid'); $s = $this->select($v, 'guid');
return ($s)?(property_exists($s,'image')):""; return ($s) ? (property_exists($s, 'image')) : "";
} }
function selectEmail( $v ) /**
{ * Parses email
*
* @param stdClass $v Object
* @return string
*/
function selectEmail($v) {
$s = $this->select($v, 'email'); $s = $this->select($v, 'email');
if(empty($s)){ if (empty($s)) {
$s = $this->select($v, 'yahooid'); $s = $this->select($v, 'yahooid');
if(!empty($s) && isset($s->value) && strpos($s->value,"@")===FALSE) if (!empty($s) && isset($s->value) && strpos($s->value, "@") === false)
$s->value .= "@yahoo.com"; $s->value .= "@yahoo.com";
} }
return ($s)?$s->value:""; return ($s) ? $s->value : "";
} }
public function getCurrentUserId() /**
{ * Returns current user id
*
* @return int
* @throws Exception
*/
public function getCurrentUserId() {
$parameters = array(); $parameters = array();
$parameters['format'] = 'json'; $parameters['format'] = 'json';
$response = $this->api->get( 'me/guid', $parameters ); $response = $this->api->get('me/guid', $parameters);
if ( ! isset( $response->guid->value ) ){ if (!isset($response->guid->value)) {
throw new Exception( "User id request failed! {$this->providerId} returned an invalid response." ); throw new Exception("User id request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData( $response ));
} }
return $response->guid->value; return $response->guid->value;
} }
} }

View File

@@ -1,140 +1,141 @@
<?php <?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
require_once realpath( dirname( __FILE__ ) ) . "/StorageInterface.php"; /**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
require_once realpath(dirname(__FILE__)) . "/StorageInterface.php";
/** /**
* HybridAuth storage manager * HybridAuth storage manager
*/ */
class Hybrid_Storage implements Hybrid_Storage_Interface class Hybrid_Storage implements Hybrid_Storage_Interface {
{
/** /**
* Constructor * Constructor
*/ */
function __construct() function __construct() {
{ if (!session_id()) {
if ( ! session_id() ){ if (!session_start()) {
if( ! session_start() ){ throw new Exception("Hybridauth requires the use of 'session_start()' at the start of your script, which appears to be disabled.", 1);
throw new Exception( "Hybridauth requires the use of 'session_start()' at the start of your script, which appears to be disabled.", 1 );
} }
} }
$this->config( "php_session_id", session_id() ); $this->config("php_session_id", session_id());
$this->config( "version", Hybrid_Auth::$version ); $this->config("version", Hybrid_Auth::$version);
} }
/**
* Config
* @param String $key
* @param String $value
*/
public function config($key, $value = null)
{
$key = strtolower( $key );
if( $value ){ /**
$_SESSION["HA::CONFIG"][$key] = serialize( $value ); * Saves a value in the config storage, or returns config if value is null
*
* @param string $key Config name
* @param string $value Config value
* @return array|null
*/
public function config($key, $value = null) {
$key = strtolower($key);
if ($value) {
$_SESSION["HA::CONFIG"][$key] = serialize($value);
} elseif (isset($_SESSION["HA::CONFIG"][$key])) {
return unserialize($_SESSION["HA::CONFIG"][$key]);
} }
elseif( isset( $_SESSION["HA::CONFIG"][$key] ) ){
return unserialize( $_SESSION["HA::CONFIG"][$key] ); return null;
}
/**
* Returns value from session storage
*
* @param string $key Key
* @return string|null
*/
public function get($key) {
$key = strtolower($key);
if (isset($_SESSION["HA::STORE"], $_SESSION["HA::STORE"][$key])) {
return unserialize($_SESSION["HA::STORE"][$key]);
} }
return NULL; return null;
} }
/** /**
* Get a key * Saves a key value pair to the session storage
* @param String $key *
* @param string $key Key
* @param string $value Value
* @return void
*/ */
public function get($key) public function set($key, $value) {
{ $key = strtolower($key);
$key = strtolower( $key ); $_SESSION["HA::STORE"][$key] = serialize($value);
if( isset( $_SESSION["HA::STORE"], $_SESSION["HA::STORE"][$key] ) ){
return unserialize( $_SESSION["HA::STORE"][$key] );
}
return NULL;
} }
/**
* GEt a set of key and value
* @param String $key
* @param String $value
*/
public function set( $key, $value )
{
$key = strtolower( $key );
$_SESSION["HA::STORE"][$key] = serialize( $value );
}
/** /**
* Clear session storage * Clear session storage
* @return void
*/ */
function clear() function clear() {
{ $_SESSION["HA::STORE"] = array();
$_SESSION["HA::STORE"] = ARRAY();
} }
/**
* Delete a specific key
* @param String $key
*/
function delete($key)
{
$key = strtolower( $key );
if( isset( $_SESSION["HA::STORE"], $_SESSION["HA::STORE"][$key] ) ){ /**
$f = $_SESSION['HA::STORE']; * Delete a specific key from session storage
unset($f[$key]); *
$_SESSION["HA::STORE"] = $f; * @param string $key Key
} * @return void
*/
function delete($key) {
$key = strtolower($key);
if (isset($_SESSION["HA::STORE"], $_SESSION["HA::STORE"][$key])) {
$f = $_SESSION['HA::STORE'];
unset($f[$key]);
$_SESSION["HA::STORE"] = $f;
}
} }
/**
* Delete a set
* @param String $key
*/
function deleteMatch($key)
{
$key = strtolower( $key );
if( isset( $_SESSION["HA::STORE"] ) && count( $_SESSION["HA::STORE"] ) ) { /**
$f = $_SESSION['HA::STORE']; * Delete all keys recursively from session storage
foreach( $f as $k => $v ){ *
if( strstr( $k, $key ) ){ * @param string $key Key
unset( $f[ $k ] ); * @retun void
*/
function deleteMatch($key) {
$key = strtolower($key);
if (isset($_SESSION["HA::STORE"]) && count($_SESSION["HA::STORE"])) {
$f = $_SESSION['HA::STORE'];
foreach ($f as $k => $v) {
if (strstr($k, $key)) {
unset($f[$k]);
} }
} }
$_SESSION["HA::STORE"] = $f; $_SESSION["HA::STORE"] = $f;
} }
} }
/**
* Get the storage session data into an array
* @return Array
*/
function getSessionData()
{
if( isset( $_SESSION["HA::STORE"] ) ){
return serialize( $_SESSION["HA::STORE"] );
}
return NULL;
}
/** /**
* Restore the storage back into session from an array * Returns session storage as a serialized string
* @param Array $sessiondata * @return string|null
*/ */
function restoreSessionData( $sessiondata = NULL ) function getSessionData() {
{ if (isset($_SESSION["HA::STORE"])) {
$_SESSION["HA::STORE"] = unserialize( $sessiondata ); return serialize($_SESSION["HA::STORE"]);
} }
return null;
}
/**
* Restores the session from serialized session data
*
* @param string $sessiondata Serialized session data
* @return void
*/
function restoreSessionData($sessiondata = null) {
$_SESSION["HA::STORE"] = unserialize($sessiondata);
}
} }

View File

@@ -1,28 +1,29 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
/** /**
* HybridAuth storage manager interface * HybridAuth storage manager interface
*/ */
interface Hybrid_Storage_Interface interface Hybrid_Storage_Interface {
{
public function config($key, $value);
public function get($key); public function config($key, $value = null);
public function set( $key, $value ); public function get($key);
function clear(); public function set($key, $value);
function delete($key); function clear();
function deleteMatch($key); function delete($key);
function getSessionData(); function deleteMatch($key);
function restoreSessionData( $sessiondata); function getSessionData();
function restoreSessionData($sessiondata = null);
} }

View File

@@ -1,40 +1,40 @@
<?php <?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* The Hybrid_User class represents the current logged in user * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
class Hybrid_User
{ /**
* The Hybrid_User class represents the current logged in user
*/
class Hybrid_User {
/** /**
* The ID (name) of the connected provider * The ID (name) of the connected provider
* @var Numeric/String * @var mixed
*/ */
public $providerId = NULL; public $providerId = null;
/** /**
* timestamp connection to the provider * Timestamp connection to the provider
* @var timestamp * @var int
*/ */
public $timestamp = NULL; public $timestamp = null;
/** /**
* User profile, contains the list of fields available in the normalized user profile structure used by HybridAuth. * User profile, contains the list of fields available in the normalized user profile structure used by HybridAuth
* @var object * @var Hybrid_User_Profile
*/ */
public $profile = NULL; public $profile = null;
/** /**
* Initialize the user object. * Initialize the user object
*/ */
function __construct() function __construct() {
{ $this->timestamp = time();
$this->timestamp = time(); $this->profile = new Hybrid_User_Profile();
$this->profile = new Hybrid_User_Profile();
} }
} }

View File

@@ -1,54 +1,55 @@
<?php <?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* Hybrid_User_Activity * HybridAuth
* * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_User_Activity
*
* used to provider the connected user activity stream on a standardized structure across supported social apis. * used to provider the connected user activity stream on a standardized structure across supported social apis.
* *
* http://hybridauth.sourceforge.net/userguide/Profile_Data_User_Activity.html * http://hybridauth.sourceforge.net/userguide/Profile_Data_User_Activity.html
*/ */
class Hybrid_User_Activity class Hybrid_User_Activity {
{
/**
* activity id on the provider side, usually given as integer
* @var Numeric/String
*/
public $id = NULL;
/** /**
* activity date of creation * Activity id on the provider side, usually given as integer
* @var timestamp * @var mixed
*/ */
public $date = NULL; public $id = null;
/** /**
* activity content as a string * Activity date of creation
* @var String * @var int
*/ */
public $text = NULL; public $date = null;
/** /**
* user who created the activity * Activity content as a string
* @var object * @var string
*/ */
public $user = NULL; public $text = null;
/**
* User who created the activity
* @var stdClass
*/
public $user = null;
/** /**
* Constructor * Constructor
*/ */
public function __construct() public function __construct() {
{
$this->user = new stdClass(); $this->user = new stdClass();
// typically, we should have a few information about the user who created the event from social apis // typically, we should have a few information about the user who created the event from social apis
$this->user->identifier = NULL; $this->user->identifier = null;
$this->user->displayName = NULL; $this->user->displayName = null;
$this->user->profileURL = NULL; $this->user->profileURL = null;
$this->user->photoURL = NULL; $this->user->photoURL = null;
} }
} }

View File

@@ -1,58 +1,60 @@
<?php <?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* Hybrid_User_Contact * HybridAuth
* * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_User_Contact
*
* used to provider the connected user contacts list on a standardized structure across supported social apis. * used to provider the connected user contacts list on a standardized structure across supported social apis.
* *
* http://hybridauth.sourceforge.net/userguide/Profile_Data_User_Contacts.html * http://hybridauth.sourceforge.net/userguide/Profile_Data_User_Contacts.html
*/ */
class Hybrid_User_Contact class Hybrid_User_Contact {
{
/**
* The Unique contact user ID
* @var Numeric
*/
public $identifier = NULL;
/** /**
* User website, blog, web page * The Unique contact user ID
* @var String * @var mixed
*/ */
public $webSiteURL = NULL; public $identifier = null;
/** /**
* URL link to profile page on the IDp web site * User website, blog, web page
* @var String * @var string
*/ */
public $profileURL = NULL; public $webSiteURL = null;
/** /**
* URL link to user photo or avatar * URL link to profile page on the IDp web site
* @var String * @var string
*/ */
public $photoURL = NULL; public $profileURL = null;
/** /**
* User displayName provided by the IDp or a concatenation of first and last name * URL link to user photo or avatar
* @var String * @var string
*/ */
public $displayName = NULL; public $photoURL = null;
/**
* A short about_me
* @var String
*/
public $description = NULL;
/** /**
* User email. Not all of IDp grant access to the user email * User displayName provided by the IDp or a concatenation of first and last name
* @var String * @var string
*/ */
public $email = NULL; public $displayName = null;
/**
* A short about_me
* @var string
*/
public $description = null;
/**
* User email. Not all of IDp grant access to the user email
* @var string
*/
public $email = null;
} }

View File

@@ -1,150 +1,152 @@
<?php <?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/** /**
* Hybrid_User_Profile object represents the current logged in user profile. * HybridAuth
* The list of fields available in the normalized user profile structure used by HybridAuth. * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_User_Profile object represents the current logged in user profile.
* The list of fields available in the normalized user profile structure used by HybridAuth.
* *
* The Hybrid_User_Profile object is populated with as much information about the user as * The Hybrid_User_Profile object is populated with as much information about the user as
* HybridAuth was able to pull from the given API or authentication provider. * HybridAuth was able to pull from the given API or authentication provider.
* *
* http://hybridauth.sourceforge.net/userguide/Profile_Data_User_Profile.html * http://hybridauth.sourceforge.net/userguide/Profile_Data_User_Profile.html
*/ */
class Hybrid_User_Profile class Hybrid_User_Profile {
{
/**
* The Unique user's ID on the connected provider
* @var Numeric
*/
public $identifier = NULL;
/** /**
* User website, blog, web page * The Unique user's ID on the connected provider
* @var String * @var mixed
*/ */
public $webSiteURL = NULL; public $identifier = null;
/** /**
* URL link to profile page on the IDp web site * User website, blog, web page
* @var String * @var string
*/ */
public $profileURL = NULL; public $webSiteURL = null;
/** /**
* URL link to user photo or avatar * URL link to profile page on the IDp web site
* @var String * @var string
*/ */
public $photoURL = NULL; public $profileURL = null;
/** /**
* User displayName provided by the IDp or a concatenation of first and last name. * URL link to user photo or avatar
* @var String * @var string
*/ */
public $displayName = NULL; public $photoURL = null;
/** /**
* A short about_me * User displayName provided by the IDp or a concatenation of first and last name.
* @var String * @var string
*/ */
public $description = NULL; public $displayName = null;
/** /**
* User's first name * A short about_me
* @var String * @var string
*/ */
public $firstName = NULL; public $description = null;
/** /**
* User's last name * User's first name
* @var String * @var string
*/ */
public $lastName = NULL; public $firstName = null;
/** /**
* male or female * User's last name
* @var String * @var string
*/ */
public $gender = NULL; public $lastName = null;
/** /**
* Language * Male or female
* @var String * @var string
*/ */
public $language = NULL; public $gender = null;
/** /**
* User age, we don't calculate it. we return it as is if the IDp provide it. * Language
* @var Numeric * @var string
*/ */
public $age = NULL; public $language = null;
/**
* User birth Day
* @var Numeric
*/
public $birthDay = NULL;
/**
* User birth Month
* @var Numeric/String
*/
public $birthMonth = NULL;
/**
* User birth Year
* @var Numeric
*/
public $birthYear = NULL;
/**
* User email. Note: not all of IDp grant access to the user email
* @var String
*/
public $email = NULL;
/**
* Verified user email. Note: not all of IDp grant access to verified user email
* @var String
*/
public $emailVerified = NULL;
/** /**
* Phone number * User age, we don't calculate it. we return it as is if the IDp provide it.
* @var String * @var int
*/ */
public $phone = NULL; public $age = null;
/** /**
* Complete user address * User birth Day
* @var String * @var int
*/ */
public $address = NULL; public $birthDay = null;
/** /**
* User country * User birth Month
* @var String * @var int
*/ */
public $country = NULL; public $birthMonth = null;
/** /**
* Region * User birth Year
* @var String * @var int
*/ */
public $region = NULL; public $birthYear = null;
/** /**
* City * User email. Note: not all of IDp grant access to the user email
* @var String * @var string
*/ */
public $city = NULL; public $email = null;
/** /**
* Postal code * Verified user email. Note: not all of IDp grant access to verified user email
* @var String * @var string
*/ */
public $zip = NULL; public $emailVerified = null;
/**
* Phone number
* @var string
*/
public $phone = null;
/**
* Complete user address
* @var string
*/
public $address = null;
/**
* User country
* @var string
*/
public $country = null;
/**
* Region
* @var string
*/
public $region = null;
/**
* City
* @var string
*/
public $city = null;
/**
* Postal code
* @var string
*/
public $zip = null;
} }

View File

@@ -170,6 +170,13 @@ abstract class BaseFacebook
'www' => 'https://www.facebook.com/', 'www' => 'https://www.facebook.com/',
); );
/**
* The decoded response object.
*
* @var mixed
*/
protected $response;
/** /**
* The Application ID. * The Application ID.
* *
@@ -451,6 +458,16 @@ abstract class BaseFacebook
return $this->accessToken; return $this->accessToken;
} }
/**
* Return the response object afer the fact
*
* @return mixed
*/
public function getResponse()
{
return $this->response;
}
/** /**
* Determines and returns the user access token, first using * Determines and returns the user access token, first using
* the signed request if present, and then falling back on * the signed request if present, and then falling back on
@@ -721,7 +738,7 @@ abstract class BaseFacebook
* code could not be determined. * code could not be determined.
*/ */
protected function getCode() { protected function getCode() {
if (!isset($_REQUEST['code']) || !isset($_REQUEST['state'])) { if (!isset($_REQUEST['code']) || !isset($_REQUEST['state']) || $this->state === null) {
return false; return false;
} }
if ($this->state === $_REQUEST['state']) { if ($this->state === $_REQUEST['state']) {
@@ -913,7 +930,7 @@ abstract class BaseFacebook
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
return $result; return $this->response = $result;
} }
/** /**
@@ -1471,7 +1488,7 @@ abstract class BaseFacebook
* @param string $big The value to be checked against $small * @param string $big The value to be checked against $small
* @param string $small The input string * @param string $small The input string
* *
* @return boolean Returns TRUE if $big matches $small * @return boolean Returns true if $big matches $small
*/ */
protected static function isAllowedDomain($big, $small) { protected static function isAllowedDomain($big, $small) {
if ($big === $small) { if ($big === $small) {
@@ -1486,7 +1503,7 @@ abstract class BaseFacebook
* @param string $big The value to be checked against $small * @param string $big The value to be checked against $small
* @param string $small The input string * @param string $small The input string
* *
* @return boolean TRUE if $big ends with $small * @return boolean true if $big ends with $small
*/ */
protected static function endsWith($big, $small) { protected static function endsWith($big, $small) {
$len = strlen($small); $len = strlen($small);

File diff suppressed because it is too large Load Diff

View File

@@ -6,7 +6,7 @@
/* Generic exception class /* Generic exception class
*/ */
if (!class_exists('OAuthException')) { if (!class_exists('OAuthException', false)) {
class OAuthException extends Exception { class OAuthException extends Exception {
// pass // pass
} }
@@ -16,7 +16,7 @@ class OAuthConsumer {
public $key; public $key;
public $secret; public $secret;
function __construct($key, $secret, $callback_url=NULL) { function __construct($key, $secret, $callback_url=null) {
$this->key = $key; $this->key = $key;
$this->secret = $secret; $this->secret = $secret;
$this->callback_url = $callback_url; $this->callback_url = $callback_url;
@@ -247,7 +247,7 @@ class OAuthRequest {
public static $version = '1.0'; public static $version = '1.0';
public static $POST_INPUT = 'php://input'; public static $POST_INPUT = 'php://input';
function __construct($http_method, $http_url, $parameters=NULL) { function __construct($http_method, $http_url, $parameters=null) {
$parameters = ($parameters) ? $parameters : array(); $parameters = ($parameters) ? $parameters : array();
$parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters); $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
$this->parameters = $parameters; $this->parameters = $parameters;
@@ -259,7 +259,7 @@ class OAuthRequest {
/** /**
* attempt to build up a request from what was passed to the server * attempt to build up a request from what was passed to the server
*/ */
public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) { public static function from_request($http_method=null, $http_url=null, $parameters=null) {
$scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
? 'http' ? 'http'
: 'https'; : 'https';
@@ -314,7 +314,7 @@ class OAuthRequest {
/** /**
* pretty much a helper function to set up the request * pretty much a helper function to set up the request
*/ */
public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) { public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=null) {
$parameters = ($parameters) ? $parameters : array(); $parameters = ($parameters) ? $parameters : array();
$defaults = array("oauth_version" => OAuthRequest::$version, $defaults = array("oauth_version" => OAuthRequest::$version,
"oauth_nonce" => OAuthRequest::generate_nonce(), "oauth_nonce" => OAuthRequest::generate_nonce(),
@@ -451,7 +451,7 @@ class OAuthRequest {
foreach ($this->parameters as $k => $v) { foreach ($this->parameters as $k => $v) {
if (substr($k, 0, 5) != "oauth") continue; if (substr($k, 0, 5) != "oauth") continue;
if (is_array($v)) { if (is_array($v)) {
throw new OAuthException('Arrays not supported in headers'); throw new OAuthException('arrays not supported in headers');
} }
$out .= ($first) ? ' ' : ','; $out .= ($first) ? ' ' : ',';
$out .= OAuthUtil::urlencode_rfc3986($k) . $out .= OAuthUtil::urlencode_rfc3986($k) .
@@ -529,7 +529,7 @@ class OAuthServer {
$consumer = $this->get_consumer($request); $consumer = $this->get_consumer($request);
// no token required for the initial token request // no token required for the initial token request
$token = NULL; $token = null;
$this->check_signature($request, $consumer, $token); $this->check_signature($request, $consumer, $token);
@@ -595,7 +595,7 @@ class OAuthServer {
private function get_signature_method($request) { private function get_signature_method($request) {
$signature_method = $request instanceof OAuthRequest $signature_method = $request instanceof OAuthRequest
? $request->get_parameter("oauth_signature_method") ? $request->get_parameter("oauth_signature_method")
: NULL; : null;
if (!$signature_method) { if (!$signature_method) {
// According to chapter 7 ("Accessing Protected Ressources") the signature-method // According to chapter 7 ("Accessing Protected Ressources") the signature-method
@@ -620,7 +620,7 @@ class OAuthServer {
private function get_consumer($request) { private function get_consumer($request) {
$consumer_key = $request instanceof OAuthRequest $consumer_key = $request instanceof OAuthRequest
? $request->get_parameter("oauth_consumer_key") ? $request->get_parameter("oauth_consumer_key")
: NULL; : null;
if (!$consumer_key) { if (!$consumer_key) {
throw new OAuthException("Invalid consumer key"); throw new OAuthException("Invalid consumer key");
@@ -640,7 +640,7 @@ class OAuthServer {
private function get_token($request, $consumer, $token_type="access") { private function get_token($request, $consumer, $token_type="access") {
$token_field = $request instanceof OAuthRequest $token_field = $request instanceof OAuthRequest
? $request->get_parameter('oauth_token') ? $request->get_parameter('oauth_token')
: NULL; : null;
$token = $this->data_store->lookup_token( $token = $this->data_store->lookup_token(
$consumer, $token_type, $token_field $consumer, $token_type, $token_field
@@ -659,10 +659,10 @@ class OAuthServer {
// this should probably be in a different method // this should probably be in a different method
$timestamp = $request instanceof OAuthRequest $timestamp = $request instanceof OAuthRequest
? $request->get_parameter('oauth_timestamp') ? $request->get_parameter('oauth_timestamp')
: NULL; : null;
$nonce = $request instanceof OAuthRequest $nonce = $request instanceof OAuthRequest
? $request->get_parameter('oauth_nonce') ? $request->get_parameter('oauth_nonce')
: NULL; : null;
$this->check_timestamp($timestamp); $this->check_timestamp($timestamp);
$this->check_nonce($consumer, $token, $nonce, $timestamp); $this->check_nonce($consumer, $token, $nonce, $timestamp);

View File

@@ -1,253 +1,264 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
// A service client for the OAuth 1/1.0a flow. // A service client for the OAuth 1/1.0a flow.
// v0.1 // v0.1
class OAuth1Client{ class OAuth1Client{
public $api_base_url = ""; public $api_base_url = "";
public $authorize_url = ""; public $authorize_url = "";
public $authenticate_url = ""; public $authenticate_url = "";
public $request_token_url = ""; public $request_token_url = "";
public $access_token_url = ""; public $access_token_url = "";
public $request_token_method = "GET"; public $request_token_method = "GET";
public $access_token_method = "GET"; public $access_token_method = "GET";
public $redirect_uri = ""; public $redirect_uri = "";
public $decode_json = true; public $decode_json = true;
public $curl_time_out = 30; public $curl_time_out = 30;
public $curl_connect_time_out = 30; public $curl_connect_time_out = 30;
public $curl_ssl_verifypeer = false; public $curl_ssl_verifypeer = false;
public $curl_auth_header = true; public $curl_auth_header = true;
public $curl_useragent = "OAuth/1 Simple PHP Client v0.1; HybridAuth http://hybridauth.sourceforge.net/"; public $curl_useragent = "OAuth/1 Simple PHP Client v0.1; HybridAuth http://hybridauth.sourceforge.net/";
public $curl_proxy = null; public $curl_proxy = null;
//-- //--
public $http_code = ""; public $http_code = "";
public $http_info = ""; public $http_info = "";
protected $response = null;
/**
* OAuth client constructor /**
*/ * OAuth client constructor
function __construct( $consumer_key, $consumer_secret, $oauth_token = null, $oauth_token_secret = null ) */
{ function __construct( $consumer_key, $consumer_secret, $oauth_token = null, $oauth_token_secret = null )
$this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); {
$this->consumer = new OAuthConsumer( $consumer_key, $consumer_secret ); $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
$this->token = null; $this->consumer = new OAuthConsumer( $consumer_key, $consumer_secret );
$this->token = null;
if ( $oauth_token && $oauth_token_secret ){
$this->token = new OAuthConsumer( $oauth_token, $oauth_token_secret ); if ( $oauth_token && $oauth_token_secret ){
} $this->token = new OAuthConsumer( $oauth_token, $oauth_token_secret );
} }
}
/**
* Build authorize url /**
* * Build authorize url
* @return string *
*/ * @return string
function authorizeUrl( $token, $extras =array() ) */
{ function authorizeUrl( $token, $extras =array() )
if ( is_array( $token ) ){ {
$token = $token['oauth_token']; if ( is_array( $token ) ){
} $token = $token['oauth_token'];
}
$parameters = array( "oauth_token" => $token );
$parameters = array( "oauth_token" => $token );
if( count($extras) )
foreach( $extras as $k=>$v ) if( count($extras) )
$parameters[$k] = $v; foreach( $extras as $k=>$v )
$parameters[$k] = $v;
return $this->authorize_url . "?" . http_build_query( $parameters );
} return $this->authorize_url . "?" . http_build_query( $parameters );
}
/**
* Get a request_token from provider /**
* * Get a request_token from provider
* @return array a key/value array containing oauth_token and oauth_token_secret *
*/ * @return array a key/value array containing oauth_token and oauth_token_secret
function requestToken( $callback = null ) */
{ function requestToken( $callback = null )
$parameters = array(); {
$parameters = array();
if ( $callback ) {
$this->redirect_uri = $parameters['oauth_callback'] = $callback; if ( $callback ) {
} $this->redirect_uri = $parameters['oauth_callback'] = $callback;
}
$request = $this->signedRequest( $this->request_token_url, $this->request_token_method, $parameters );
$token = OAuthUtil::parse_parameters( $request ); $request = $this->signedRequest( $this->request_token_url, $this->request_token_method, $parameters );
$this->token = new OAuthConsumer( $token['oauth_token'], $token['oauth_token_secret'] ); $token = OAuthUtil::parse_parameters( $request );
$this->token = new OAuthConsumer( $token['oauth_token'], $token['oauth_token_secret'] );
return $token;
} return $token;
}
/**
* Exchange the request token and secret for an access token and secret, to sign API calls. /**
* * Exchange the request token and secret for an access token and secret, to sign API calls.
* @return array array('oauth_token' => the access token, 'oauth_token_secret' => the access secret) *
*/ * @return array array('oauth_token' => the access token, 'oauth_token_secret' => the access secret)
function accessToken( $oauth_verifier = false, $oauth_token = false ) */
{ function accessToken( $oauth_verifier = false, $oauth_token = false )
$parameters = array(); {
$parameters = array();
// 1.0a
if ( $oauth_verifier ) { // 1.0a
$parameters['oauth_verifier'] = $oauth_verifier; if ( $oauth_verifier ) {
} $parameters['oauth_verifier'] = $oauth_verifier;
}
$request = $this->signedRequest( $this->access_token_url, $this->access_token_method, $parameters );
$token = OAuthUtil::parse_parameters( $request ); $request = $this->signedRequest( $this->access_token_url, $this->access_token_method, $parameters );
$this->token = new OAuthConsumer( $token['oauth_token'], $token['oauth_token_secret'] ); $token = OAuthUtil::parse_parameters( $request );
$this->token = new OAuthConsumer( $token['oauth_token'], $token['oauth_token_secret'] );
return $token;
} return $token;
}
/**
* GET wrapper for provider apis request /**
*/ * GET wrapper for provider apis request
function get($url, $parameters = array(), $content_type = NULL) */
{ function get($url, $parameters = array(), $content_type = null)
return $this->api($url, 'GET', $parameters, NULL, $content_type); {
} return $this->api($url, 'GET', $parameters, null, $content_type);
}
/**
* POST wrapper for provider apis request /**
*/ * POST wrapper for provider apis request
function post($url, $parameters = array(), $body = NULL, $content_type = NULL, $multipart = false) */
{ function post($url, $parameters = array(), $body = null, $content_type = null, $multipart = false)
return $this->api($url, 'POST', $parameters, $body, $content_type, $multipart ); {
} return $this->api($url, 'POST', $parameters, $body, $content_type, $multipart );
}
/**
* Format and sign an oauth for provider api /**
*/ * Format and sign an oauth for provider api
function api( $url, $method = 'GET', $parameters = array(), $body = NULL, $content_type = NULL, $multipart = false ) */
{ function api( $url, $method = 'GET', $parameters = array(), $body = null, $content_type = null, $multipart = false )
if ( strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0 ) { {
$url = $this->api_base_url . $url; if ( strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0 ) {
} $url = $this->api_base_url . $url;
}
$response = $this->signedRequest( $url, $method, $parameters, $body, $content_type, $multipart );
$response = $this->signedRequest( $url, $method, $parameters, $body, $content_type, $multipart );
if( $this->decode_json ){
$response = json_decode( $response ); if( $this->decode_json ){
} $response = json_decode( $response );
}
return $response;
} return $this->response = $response;
}
/**
* Make signed request /**
*/ * Return the response object afer the fact
function signedRequest( $url, $method, $parameters, $body = NULL, $content_type = NULL, $multipart = false ) *
{ * @return mixed
*/
$signature_parameters = array(); public function getResponse()
{
// when making a multipart request, use only oauth_* keys for signature return $this->response;
foreach( $parameters AS $key => $value ){ }
if( !$multipart || strpos( $key, 'oauth_' ) === 0 ){
$signature_parameters[$key] = $value; /**
} * Make signed request
} */
function signedRequest( $url, $method, $parameters, $body = null, $content_type = null, $multipart = false )
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $signature_parameters); {
$request->sign_request($this->sha1_method, $this->consumer, $this->token);
switch ($method) { $signature_parameters = array();
case 'GET': return $this->request( $request->to_url(), 'GET', NULL, NULL, $content_type );
default : // when making a multipart request, use only oauth_* keys for signature
if ($body) foreach( $parameters AS $key => $value ){
return $this->request( $request->to_url(), $method, $body, $request->to_header(), $content_type ); if( !$multipart || strpos( $key, 'oauth_' ) === 0 ){
else $signature_parameters[$key] = $value;
return $this->request( $request->get_normalized_http_url(), $method, ($multipart ? $parameters : $request->to_postdata()), $request->to_header(), $content_type, $multipart ) ; }
} }
}
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $signature_parameters);
/** $request->sign_request($this->sha1_method, $this->consumer, $this->token);
* Make http request switch ($method) {
*/ case 'GET': return $this->request( $request->to_url(), 'GET', null, null, $content_type );
function request( $url, $method, $postfields = NULL, $auth_header = NULL, $content_type = NULL, $multipart = false ) default :
{ if ($body)
Hybrid_Logger::info( "Enter OAuth1Client::request( $method, $url )" ); return $this->request( $request->to_url(), $method, $body, $request->to_header(), $content_type );
Hybrid_Logger::debug( "OAuth1Client::request(). dump post fields: ", serialize( $postfields ) ); else
return $this->request( $request->get_normalized_http_url(), $method, ($multipart ? $parameters : $request->to_postdata()), $request->to_header(), $content_type, $multipart ) ;
$this->http_info = array(); }
$ci = curl_init(); }
/* Curl settings */ /**
curl_setopt( $ci, CURLOPT_USERAGENT , $this->curl_useragent ); * Make http request
curl_setopt( $ci, CURLOPT_CONNECTTIMEOUT, $this->curl_connect_time_out ); */
curl_setopt( $ci, CURLOPT_TIMEOUT , $this->curl_time_out ); function request( $url, $method, $postfields = null, $auth_header = null, $content_type = null, $multipart = false )
curl_setopt( $ci, CURLOPT_RETURNTRANSFER, TRUE ); {
curl_setopt( $ci, CURLOPT_HTTPHEADER , array('Expect:') ); Hybrid_Logger::info( "Enter OAuth1Client::request( $method, $url )" );
curl_setopt( $ci, CURLOPT_SSL_VERIFYPEER, $this->curl_ssl_verifypeer ); Hybrid_Logger::debug( "OAuth1Client::request(). dump post fields: ", serialize( $postfields ) );
curl_setopt( $ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader') );
curl_setopt( $ci, CURLOPT_HEADER , FALSE ); $this->http_info = array();
$ci = curl_init();
if( $multipart ){
curl_setopt( $ci, CURLOPT_HTTPHEADER, array( 'Expect:', $auth_header ) ); /* Curl settings */
curl_setopt( $ci, CURLOPT_USERAGENT , $this->curl_useragent );
}elseif ($content_type) curl_setopt( $ci, CURLOPT_CONNECTTIMEOUT, $this->curl_connect_time_out );
curl_setopt( $ci, CURLOPT_HTTPHEADER, array('Expect:', "Content-Type: $content_type") ); curl_setopt( $ci, CURLOPT_TIMEOUT , $this->curl_time_out );
curl_setopt( $ci, CURLOPT_RETURNTRANSFER, true );
if($this->curl_proxy){ curl_setopt( $ci, CURLOPT_HTTPHEADER , array('Expect:') );
curl_setopt( $ci, CURLOPT_PROXY , $this->curl_proxy); curl_setopt( $ci, CURLOPT_SSL_VERIFYPEER, $this->curl_ssl_verifypeer );
} curl_setopt( $ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader') );
curl_setopt( $ci, CURLOPT_HEADER , false );
switch ($method){
case 'POST': if( $multipart ){
curl_setopt( $ci, CURLOPT_POST, TRUE ); curl_setopt( $ci, CURLOPT_HTTPHEADER, array( 'Expect:', $auth_header ) );
if ( !empty($postfields) ){ }elseif ($content_type)
curl_setopt( $ci, CURLOPT_POSTFIELDS, $postfields ); curl_setopt( $ci, CURLOPT_HTTPHEADER, array('Expect:', "Content-Type: $content_type") );
}
if($this->curl_proxy){
if ( !empty($auth_header) && $this->curl_auth_header && !$multipart ){ curl_setopt( $ci, CURLOPT_PROXY , $this->curl_proxy);
curl_setopt( $ci, CURLOPT_HTTPHEADER, array( 'Content-Type: application/atom+xml', $auth_header ) ); }
}
break; switch ($method){
case 'DELETE': case 'POST':
curl_setopt( $ci, CURLOPT_CUSTOMREQUEST, 'DELETE' ); curl_setopt( $ci, CURLOPT_POST, true );
if ( !empty($postfields) ){
$url = "{$url}?{$postfields}"; if ( !empty($postfields) ){
} curl_setopt( $ci, CURLOPT_POSTFIELDS, $postfields );
} }
curl_setopt($ci, CURLOPT_URL, $url); if ( !empty($auth_header) && $this->curl_auth_header && !$multipart ){
$response = curl_exec($ci); curl_setopt( $ci, CURLOPT_HTTPHEADER, array( 'Content-Type: application/atom+xml', $auth_header ) );
if( $response === FALSE ) { }
Hybrid_Logger::error( "OAuth1Client::request(). curl_exec error: ", curl_error($ci) ); break;
} case 'DELETE':
curl_setopt( $ci, CURLOPT_CUSTOMREQUEST, 'DELETE' );
if ( !empty($postfields) ){
Hybrid_Logger::debug( "OAuth1Client::request(). dump request info: ", serialize( curl_getinfo($ci) ) ); $url = "{$url}?{$postfields}";
Hybrid_Logger::debug( "OAuth1Client::request(). dump request result: ", serialize( $response ) ); }
}
$this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
$this->http_info = array_merge($this->http_info, curl_getinfo($ci)); curl_setopt($ci, CURLOPT_URL, $url);
$response = curl_exec($ci);
curl_close ($ci); if( $response === false ) {
Hybrid_Logger::error( "OAuth1Client::request(). curl_exec error: ", curl_error($ci) );
return $response; }
}
/** Hybrid_Logger::debug( "OAuth1Client::request(). dump request info: ", serialize( curl_getinfo($ci) ) );
* Get the header info to store. Hybrid_Logger::debug( "OAuth1Client::request(). dump request result: ", serialize( $response ) );
*/
function getHeader($ch, $header) { $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
$i = strpos($header, ':'); $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
if ( !empty($i) ){ curl_close ($ci);
$key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
$value = trim(substr($header, $i + 2)); return $response;
$this->http_header[$key] = $value; }
}
/**
return strlen($header); * Get the header info to store.
} */
} function getHeader($ch, $header) {
$i = strpos($header, ':');
if ( !empty($i) ){
$key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
$value = trim(substr($header, $i + 2));
$this->http_header[$key] = $value;
}
return strlen($header);
}
}

View File

@@ -1,250 +1,266 @@
<?php <?php
/** /**
* HybridAuth * HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth * http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html * (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/ */
// A service client for the OAuth 2 flow. // A service client for the OAuth 2 flow.
// v0.1 // v0.1.1
class OAuth2Client class OAuth2Client
{ {
public $api_base_url = ""; public $api_base_url = "";
public $authorize_url = ""; public $authorize_url = "";
public $token_url = ""; public $token_url = "";
public $token_info_url = ""; public $token_info_url = "";
public $client_id = "" ; public $client_id = "" ;
public $client_secret = "" ; public $client_secret = "" ;
public $redirect_uri = "" ; public $redirect_uri = "" ;
public $access_token = "" ; public $access_token = "" ;
public $refresh_token = "" ; public $refresh_token = "" ;
public $access_token_expires_in = "" ; public $access_token_expires_in = "" ;
public $access_token_expires_at = "" ; public $access_token_expires_at = "" ;
//-- //--
public $sign_token_name = "access_token"; public $sign_token_name = "access_token";
public $decode_json = true; public $decode_json = true;
public $curl_time_out = 30; public $curl_time_out = 30;
public $curl_connect_time_out = 30; public $curl_connect_time_out = 30;
public $curl_ssl_verifypeer = false; public $curl_ssl_verifypeer = false;
public $curl_ssl_verifyhost = false; public $curl_ssl_verifyhost = false;
public $curl_header = array(); public $curl_header = array();
public $curl_useragent = "OAuth/2 Simple PHP Client v0.1; HybridAuth http://hybridauth.sourceforge.net/"; public $curl_useragent = "OAuth/2 Simple PHP Client v0.1.1; HybridAuth http://hybridauth.sourceforge.net/";
public $curl_authenticate_method = "POST"; public $curl_authenticate_method = "POST";
public $curl_proxy = null; public $curl_proxy = null;
public $curl_compressed = false;
//-- //--
public $http_code = ""; public $http_code = "";
public $http_info = ""; public $http_info = "";
protected $response = null;
//--
//--
public function __construct( $client_id = false, $client_secret = false, $redirect_uri='' )
{ public function __construct( $client_id = false, $client_secret = false, $redirect_uri='', $compressed = false )
$this->client_id = $client_id; {
$this->client_secret = $client_secret; $this->client_id = $client_id;
$this->redirect_uri = $redirect_uri; $this->client_secret = $client_secret;
} $this->redirect_uri = $redirect_uri;
$this->curl_compressed = $compressed;
public function authorizeUrl( $extras = array() ) }
{
$params = array( public function authorizeUrl( $extras = array() )
"client_id" => $this->client_id, {
"redirect_uri" => $this->redirect_uri, $params = array(
"response_type" => "code" "client_id" => $this->client_id,
); "redirect_uri" => $this->redirect_uri,
"response_type" => "code"
if( count($extras) ) );
foreach( $extras as $k=>$v )
$params[$k] = $v; if( count($extras) )
foreach( $extras as $k=>$v )
return $this->authorize_url . "?" . http_build_query($params, '', '&'); $params[$k] = $v;
}
return $this->authorize_url . "?" . http_build_query($params, '', '&');
public function authenticate( $code ) }
{
$params = array( public function authenticate( $code )
"client_id" => $this->client_id, {
"client_secret" => $this->client_secret, $params = array(
"grant_type" => "authorization_code", "client_id" => $this->client_id,
"redirect_uri" => $this->redirect_uri, "client_secret" => $this->client_secret,
"code" => $code "grant_type" => "authorization_code",
); "redirect_uri" => $this->redirect_uri,
"code" => $code
$response = $this->request( $this->token_url, $params, $this->curl_authenticate_method ); );
$response = $this->parseRequestResult( $response ); $response = $this->request( $this->token_url, $params, $this->curl_authenticate_method );
if( ! $response || ! isset( $response->access_token ) ){ $response = $this->parseRequestResult( $response );
throw new Exception( "The Authorization Service has return: " . $response->error );
} if( ! $response || ! isset( $response->access_token ) ){
throw new Exception( "The Authorization Service has return: " . $response->error );
if( isset( $response->access_token ) ) $this->access_token = $response->access_token; }
if( isset( $response->refresh_token ) ) $this->refresh_token = $response->refresh_token;
if( isset( $response->expires_in ) ) $this->access_token_expires_in = $response->expires_in; if( isset( $response->access_token ) ) $this->access_token = $response->access_token;
if( isset( $response->refresh_token ) ) $this->refresh_token = $response->refresh_token;
// calculate when the access token expire if( isset( $response->expires_in ) ) $this->access_token_expires_in = $response->expires_in;
if( isset($response->expires_in)) {
$this->access_token_expires_at = time() + $response->expires_in; // calculate when the access token expire
} if( isset($response->expires_in)) {
$this->access_token_expires_at = time() + $response->expires_in;
return $response; }
}
return $response;
public function authenticated() }
{
if ( $this->access_token ){ public function authenticated()
if ( $this->token_info_url && $this->refresh_token ){ {
// check if this access token has expired, if ( $this->access_token ){
$tokeninfo = $this->tokenInfo( $this->access_token ); if ( $this->token_info_url && $this->refresh_token ){
// check if this access token has expired,
// if yes, access_token has expired, then ask for a new one $tokeninfo = $this->tokenInfo( $this->access_token );
if( $tokeninfo && isset( $tokeninfo->error ) ){
$response = $this->refreshToken( $this->refresh_token ); // if yes, access_token has expired, then ask for a new one
if( $tokeninfo && isset( $tokeninfo->error ) ){
// if wrong response $response = $this->refreshToken( $this->refresh_token );
if( ! isset( $response->access_token ) || ! $response->access_token ){
throw new Exception( "The Authorization Service has return an invalid response while requesting a new access token. given up!" ); // if wrong response
} if( ! isset( $response->access_token ) || ! $response->access_token ){
throw new Exception( "The Authorization Service has return an invalid response while requesting a new access token. given up!" );
// set new access_token }
$this->access_token = $response->access_token;
} // set new access_token
} $this->access_token = $response->access_token;
}
return true; }
}
return true;
return false; }
}
return false;
/** }
* Format and sign an oauth for provider api
*/ /**
public function api( $url, $method = "GET", $parameters = array() ) * Format and sign an oauth for provider api
{ */
if ( strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0 ) { public function api( $url, $method = "GET", $parameters = array() )
$url = $this->api_base_url . $url; {
} if ( strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0 ) {
$url = $this->api_base_url . $url;
$parameters[$this->sign_token_name] = $this->access_token; }
$response = null;
$parameters[$this->sign_token_name] = $this->access_token;
switch( $method ){ $response = null;
case 'GET' : $response = $this->request( $url, $parameters, "GET" ); break;
case 'POST' : $response = $this->request( $url, $parameters, "POST" ); break; switch( $method ){
} case 'GET' : $response = $this->request( $url, $parameters, "GET" ); break;
case 'POST' : $response = $this->request( $url, $parameters, "POST" ); break;
if( $response && $this->decode_json ){ }
$response = json_decode( $response );
} if( $response && $this->decode_json ){
return $this->response = json_decode( $response );
return $response; }
}
return $this->response = $response;
/** }
* GET wrapper for provider apis request
*/ /**
function get( $url, $parameters = array() ) * Return the response object afer the fact
{ *
return $this->api( $url, 'GET', $parameters ); * @return mixed
} */
public function getResponse()
/** {
* POST wrapper for provider apis request return $this->response;
*/ }
function post( $url, $parameters = array() )
{ /**
return $this->api( $url, 'POST', $parameters ); * GET wrapper for provider apis request
} */
function get( $url, $parameters = array() )
// -- tokens {
return $this->api( $url, 'GET', $parameters );
public function tokenInfo($accesstoken) }
{
$params['access_token'] = $this->access_token; /**
$response = $this->request( $this->token_info_url, $params ); * POST wrapper for provider apis request
return $this->parseRequestResult( $response ); */
} function post( $url, $parameters = array() )
{
public function refreshToken( $parameters = array() ) return $this->api( $url, 'POST', $parameters );
{ }
$params = array(
"client_id" => $this->client_id, // -- tokens
"client_secret" => $this->client_secret,
"grant_type" => "refresh_token" public function tokenInfo($accesstoken)
); {
$params['access_token'] = $this->access_token;
foreach($parameters as $k=>$v ){ $response = $this->request( $this->token_info_url, $params );
$params[$k] = $v; return $this->parseRequestResult( $response );
} }
$response = $this->request( $this->token_url, $params, "POST" ); public function refreshToken( $parameters = array() )
return $this->parseRequestResult( $response ); {
} $params = array(
"client_id" => $this->client_id,
// -- utilities "client_secret" => $this->client_secret,
"grant_type" => "refresh_token"
private function request( $url, $params=false, $type="GET" ) );
{
Hybrid_Logger::info( "Enter OAuth2Client::request( $url )" ); foreach($parameters as $k=>$v ){
Hybrid_Logger::debug( "OAuth2Client::request(). dump request params: ", serialize( $params ) ); $params[$k] = $v;
}
if( $type == "GET" ){
$url = $url . ( strpos( $url, '?' ) ? '&' : '?' ) . http_build_query($params, '', '&'); $response = $this->request( $this->token_url, $params, "POST" );
} return $this->parseRequestResult( $response );
}
$this->http_info = array();
$ch = curl_init(); // -- utilities
curl_setopt($ch, CURLOPT_URL , $url ); private function request( $url, $params=false, $type="GET" )
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1 ); {
curl_setopt($ch, CURLOPT_TIMEOUT , $this->curl_time_out ); Hybrid_Logger::info( "Enter OAuth2Client::request( $url )" );
curl_setopt($ch, CURLOPT_USERAGENT , $this->curl_useragent ); Hybrid_Logger::debug( "OAuth2Client::request(). dump request params: ", serialize( $params ) );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , $this->curl_connect_time_out );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , $this->curl_ssl_verifypeer ); if( $type == "GET" ){
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , $this->curl_ssl_verifyhost ); $url = $url . ( strpos( $url, '?' ) ? '&' : '?' ) . http_build_query($params, '', '&');
curl_setopt($ch, CURLOPT_HTTPHEADER , $this->curl_header ); }
if($this->curl_proxy){ $this->http_info = array();
curl_setopt( $ch, CURLOPT_PROXY , $this->curl_proxy); $ch = curl_init();
}
curl_setopt($ch, CURLOPT_URL , $url );
if( $type == "POST" ){ curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1 );
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_TIMEOUT , $this->curl_time_out );
if($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($params, '', '&') ); curl_setopt($ch, CURLOPT_USERAGENT , $this->curl_useragent );
} curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , $this->curl_connect_time_out );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , $this->curl_ssl_verifypeer );
$response = curl_exec($ch); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , $this->curl_ssl_verifyhost );
if( $response === FALSE ) { curl_setopt($ch, CURLOPT_HTTPHEADER , $this->curl_header );
Hybrid_Logger::error( "OAuth2Client::request(). curl_exec error: ", curl_error($ch) );
} if ($this->curl_compressed){
Hybrid_Logger::debug( "OAuth2Client::request(). dump request info: ", serialize( curl_getinfo($ch) ) ); curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
Hybrid_Logger::debug( "OAuth2Client::request(). dump request result: ", serialize( $response ) ); }
$this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if($this->curl_proxy){
$this->http_info = array_merge($this->http_info, curl_getinfo($ch)); curl_setopt( $ch, CURLOPT_PROXY , $this->curl_proxy);
}
curl_close ($ch);
if( $type == "POST" ){
return $response; curl_setopt($ch, CURLOPT_POST, 1);
} if($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, $params );
}
private function parseRequestResult( $result )
{ $response = curl_exec($ch);
if( json_decode( $result ) ) return json_decode( $result ); if( $response === false ) {
Hybrid_Logger::error( "OAuth2Client::request(). curl_exec error: ", curl_error($ch) );
parse_str( $result, $output ); }
Hybrid_Logger::debug( "OAuth2Client::request(). dump request info: ", serialize( curl_getinfo($ch) ) );
$result = new StdClass(); Hybrid_Logger::debug( "OAuth2Client::request(). dump request result: ", serialize( $response ) );
foreach( $output as $k => $v ) $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result->$k = $v; $this->http_info = array_merge($this->http_info, curl_getinfo($ch));
return $result; curl_close ($ch);
}
} return $response;
}
private function parseRequestResult( $result )
{
if( json_decode( $result ) ) return json_decode( $result );
parse_str( $result, $output );
$result = new StdClass();
foreach( $output as $k => $v )
$result->$k = $v;
return $result;
}
}

View File

@@ -1,17 +1,15 @@
<?php <?php
// https://github.com/iignatov/LightOpenID
/** /**
* This class provides a simple interface for OpenID 1.1/2.0 authentication. * This class provides a simple interface for OpenID 1.1/2.0 authentication.
* *
* It requires PHP >= 5.1.2 with cURL or HTTP/HTTPS stream wrappers enabled. * It requires PHP >= 5.1.2 with cURL or HTTP/HTTPS stream wrappers enabled.
* *
* @version v1.1.2 2013-01-15 * @version v1.2.0 (2014-01-14)
* @link http://gitorious.org/lightopenid Official Repo * @link https://code.google.com/p/lightopenid/ Project URL
* @link http://github.com/iignatov/LightOpenID GitHub Clone * @link https://github.com/iignatov/LightOpenID GitHub Repo
* @author Mewp * @author Mewp <mewp151 at gmail dot com>
* @copyright Copyright (c) 2010, Mewp * @copyright Copyright (c) 2013 Mewp
* @license http://www.opensource.org/licenses/mit-license.php MIT License * @license http://opensource.org/licenses/mit-license.php MIT License
*/ */
class LightOpenID class LightOpenID
{ {
@@ -21,11 +19,15 @@ class LightOpenID
, $verify_peer = null , $verify_peer = null
, $capath = null , $capath = null
, $cainfo = null , $cainfo = null
, $cnmatch = null
, $data , $data
, $oauth = array(); , $oauth = array()
, $curl_time_out = 30
, $curl_connect_time_out = 30;
private $identity, $claimed_id; private $identity, $claimed_id;
protected $server, $version, $trustRoot, $aliases, $identifier_select = false protected $server, $version, $trustRoot, $aliases, $identifier_select = false
, $ax = false, $sreg = false, $setup_url = null, $headers = array(), $proxy = null , $ax = false, $sreg = false, $setup_url = null, $headers = array()
, $proxy = null, $user_agent = 'LightOpenID'
, $xrds_override_pattern = null, $xrds_override_replacement = null; , $xrds_override_pattern = null, $xrds_override_replacement = null;
static protected $ax_to_sreg = array( static protected $ax_to_sreg = array(
'namePerson/friendly' => 'nickname', 'namePerson/friendly' => 'nickname',
@@ -41,18 +43,7 @@ class LightOpenID
function __construct($host, $proxy = null) function __construct($host, $proxy = null)
{ {
$this->trustRoot = (strpos($host, '://') ? $host : 'http://' . $host); $this->set_realm($host);
if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off')
|| (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
&& $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
) {
$this->trustRoot = (strpos($host, '://') ? $host : 'https://' . $host);
}
if(strlen($this->trustRoot >= 8) && ($host_end = strpos($this->trustRoot, '/', 8)) !== false) {
$this->trustRoot = substr($this->trustRoot, 0, $host_end);
}
$this->set_proxy($proxy); $this->set_proxy($proxy);
$uri = rtrim(preg_replace('#((?<=\?)|&)openid\.[^&]+#', '', $_SERVER['REQUEST_URI']), '?'); $uri = rtrim(preg_replace('#((?<=\?)|&)openid\.[^&]+#', '', $_SERVER['REQUEST_URI']), '?');
@@ -65,6 +56,11 @@ class LightOpenID
} }
} }
function __isset($name)
{
return in_array($name, array('identity', 'trustRoot', 'realm', 'xrdsOverride', 'mode'));
}
function __set($name, $value) function __set($name, $value)
{ {
switch ($name) { switch ($name) {
@@ -112,7 +108,7 @@ class LightOpenID
return empty($this->data['openid_mode']) ? null : $this->data['openid_mode']; return empty($this->data['openid_mode']) ? null : $this->data['openid_mode'];
} }
} }
function set_proxy($proxy) function set_proxy($proxy)
{ {
if (!empty($proxy)) { if (!empty($proxy)) {
@@ -120,7 +116,7 @@ class LightOpenID
if (!is_array($proxy)) { if (!is_array($proxy)) {
$proxy = parse_url($proxy); $proxy = parse_url($proxy);
} }
// Check if $proxy is valid after the parsing. // Check if $proxy is valid after the parsing.
if ($proxy && !empty($proxy['host'])) { if ($proxy && !empty($proxy['host'])) {
// Make sure that a valid port number is specified. // Make sure that a valid port number is specified.
@@ -128,12 +124,12 @@ class LightOpenID
if (!is_int($proxy['port'])) { if (!is_int($proxy['port'])) {
$proxy['port'] = is_numeric($proxy['port']) ? intval($proxy['port']) : 0; $proxy['port'] = is_numeric($proxy['port']) ? intval($proxy['port']) : 0;
} }
if ($proxy['port'] <= 0) { if ($proxy['port'] <= 0) {
throw new ErrorException('The specified proxy port number is invalid.'); throw new ErrorException('The specified proxy port number is invalid.');
} }
} }
$this->proxy = $proxy; $this->proxy = $proxy;
} }
} }
@@ -160,25 +156,63 @@ class LightOpenID
return !!gethostbynamel($server); return !!gethostbynamel($server);
} }
protected function set_realm($uri)
{
$realm = '';
# Set a protocol, if not specified.
$realm .= (($offset = strpos($uri, '://')) === false) ? $this->get_realm_protocol() : '';
# Set the offset properly.
$offset = (($offset !== false) ? $offset + 3 : 0);
# Get only the root, without the path.
$realm .= (($end = strpos($uri, '/', $offset)) === false) ? $uri : substr($uri, 0, $end);
$this->trustRoot = $realm;
}
protected function get_realm_protocol()
{
if (!empty($_SERVER['HTTPS'])) {
$use_secure_protocol = ($_SERVER['HTTPS'] != 'off');
} else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$use_secure_protocol = ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
} else {
$use_secure_protocol = false;
}
return $use_secure_protocol ? 'https://' : 'http://';
}
protected function request_curl($url, $method='GET', $params=array(), $update_claimed_id) protected function request_curl($url, $method='GET', $params=array(), $update_claimed_id)
{ {
$params = http_build_query($params, '', '&'); $params = http_build_query($params, '', '&');
$curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : '')); $curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : ''));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*')); curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_time_out);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT , $this->curl_connect_time_out);
if ($method == 'POST') {
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
} else {
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*'));
}
if (!empty($this->proxy)) { if (!empty($this->proxy)) {
curl_setopt($curl, CURLOPT_PROXY, $this->proxy['host']); curl_setopt($curl, CURLOPT_PROXY, $this->proxy['host']);
if (!empty($this->proxy['port'])) { if (!empty($this->proxy['port'])) {
curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxy['port']); curl_setopt($curl, CURLOPT_PROXYPORT, $this->proxy['port']);
} }
if (!empty($this->proxy['user'])) { if (!empty($this->proxy['user'])) {
curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxy['user'] . ':' . $this->proxy['pass']); curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxy['user'] . ':' . $this->proxy['pass']);
} }
} }
@@ -204,9 +238,6 @@ class LightOpenID
curl_setopt($curl, CURLOPT_HTTPGET, true); curl_setopt($curl, CURLOPT_HTTPGET, true);
} }
$response = curl_exec($curl); $response = curl_exec($curl);
if( $response === FALSE ) {
Hybrid_Logger::error( "LightOpenID::request_curl(). curl_exec error: ", curl_error($curl) );
}
if($method == 'HEAD' && curl_getinfo($curl, CURLINFO_HTTP_CODE) == 405) { if($method == 'HEAD' && curl_getinfo($curl, CURLINFO_HTTP_CODE) == 405) {
curl_setopt($curl, CURLOPT_HTTPGET, true); curl_setopt($curl, CURLOPT_HTTPGET, true);
@@ -232,9 +263,10 @@ class LightOpenID
} }
if($update_claimed_id) { if($update_claimed_id) {
# Updating claimed_id in case of redirections. # Update the claimed_id value in case of redirections.
$effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL); $effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
if($effective_url != $url) { # Ignore the fragment (some cURL versions don't handle it well).
if (strtok($effective_url, '#') != strtok($url, '#')) {
$this->identity = $this->claimed_id = $effective_url; $this->identity = $this->claimed_id = $effective_url;
} }
} }
@@ -289,6 +321,10 @@ class LightOpenID
throw new ErrorException("Could not connect to $url.", 404); throw new ErrorException("Could not connect to $url.", 404);
} }
if (empty($this->cnmatch)) {
$this->cnmatch = parse_url($url, PHP_URL_HOST);
}
$params = http_build_query($params, '', '&'); $params = http_build_query($params, '', '&');
switch($method) { switch($method) {
case 'GET': case 'GET':
@@ -296,10 +332,12 @@ class LightOpenID
'http' => array( 'http' => array(
'method' => 'GET', 'method' => 'GET',
'header' => 'Accept: application/xrds+xml, */*', 'header' => 'Accept: application/xrds+xml, */*',
'user_agent' => $this->user_agent,
'ignore_errors' => true, 'ignore_errors' => true,
), 'ssl' => array(
'CN_match' => parse_url($url, PHP_URL_HOST),
), ),
'ssl' => array(
'CN_match' => $this->cnmatch
)
); );
$url = $url . ($params ? '?' . $params : ''); $url = $url . ($params ? '?' . $params : '');
if (!empty($this->proxy)) { if (!empty($this->proxy)) {
@@ -311,21 +349,23 @@ class LightOpenID
'http' => array( 'http' => array(
'method' => 'POST', 'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded', 'header' => 'Content-type: application/x-www-form-urlencoded',
'user_agent' => $this->user_agent,
'content' => $params, 'content' => $params,
'ignore_errors' => true, 'ignore_errors' => true,
), 'ssl' => array(
'CN_match' => parse_url($url, PHP_URL_HOST),
), ),
'ssl' => array(
'CN_match' => $this->cnmatch
)
); );
if (!empty($this->proxy)) { if (!empty($this->proxy)) {
$opts['http']['proxy'] = $this->proxy_url(); $opts['http']['proxy'] = $this->proxy_url();
} }
break; break;
case 'HEAD': case 'HEAD':
// We want to send a HEAD request, but since get_headers() doesn't // We want to send a HEAD request, but since get_headers() doesn't
// accept $context parameter, we have to change the defaults. // accept $context parameter, we have to change the defaults.
$default = stream_context_get_options(stream_context_get_default()); $default = stream_context_get_options(stream_context_get_default());
// PHP does not reset all options. Instead, it just sets the options // PHP does not reset all options. Instead, it just sets the options
// available in the passed array, therefore set the defaults manually. // available in the passed array, therefore set the defaults manually.
$default += array( $default += array(
@@ -335,23 +375,25 @@ class LightOpenID
$default['http'] += array( $default['http'] += array(
'method' => 'GET', 'method' => 'GET',
'header' => '', 'header' => '',
'user_agent' => '',
'ignore_errors' => false 'ignore_errors' => false
); );
$default['ssl'] += array( $default['ssl'] += array(
'CN_match' => '' 'CN_match' => ''
); );
$opts = array( $opts = array(
'http' => array( 'http' => array(
'method' => 'HEAD', 'method' => 'HEAD',
'header' => 'Accept: application/xrds+xml, */*', 'header' => 'Accept: application/xrds+xml, */*',
'user_agent' => $this->user_agent,
'ignore_errors' => true, 'ignore_errors' => true,
), ),
'ssl' => array( 'ssl' => array(
'CN_match' => parse_url($url, PHP_URL_HOST) 'CN_match' => $this->cnmatch
) )
); );
// Enable validation of the SSL certificates. // Enable validation of the SSL certificates.
if ($this->verify_peer) { if ($this->verify_peer) {
$default['ssl'] += array( $default['ssl'] += array(
@@ -365,15 +407,15 @@ class LightOpenID
'cafile' => $this->cainfo 'cafile' => $this->cainfo
); );
} }
// Change the stream context options. // Change the stream context options.
stream_context_get_default($opts); stream_context_get_default($opts);
$headers = get_headers($url . ($params ? '?' . $params : '')); $headers = get_headers($url . ($params ? '?' . $params : ''));
// Restore the stream context options. // Restore the stream context options.
stream_context_get_default($default); stream_context_get_default($default);
if (!empty($headers)) { if (!empty($headers)) {
if (intval(substr($headers[0], strlen('HTTP/1.1 '))) == 405) { if (intval(substr($headers[0], strlen('HTTP/1.1 '))) == 405) {
// The server doesn't support HEAD - emulate it with a GET. // The server doesn't support HEAD - emulate it with a GET.
@@ -387,7 +429,7 @@ class LightOpenID
} else { } else {
$headers = array(); $headers = array();
} }
return $headers; return $headers;
} }
@@ -412,32 +454,49 @@ class LightOpenID
protected function request($url, $method='GET', $params=array(), $update_claimed_id=false) protected function request($url, $method='GET', $params=array(), $update_claimed_id=false)
{ {
if (function_exists('curl_init') $use_curl = false;
&& (!in_array('https', stream_get_wrappers()) || !ini_get('safe_mode') && !ini_get('open_basedir'))
) { if (function_exists('curl_init')) {
return $this->request_curl($url, $method, $params, $update_claimed_id); if (!$use_curl) {
# When allow_url_fopen is disabled, PHP streams will not work.
$use_curl = !ini_get('allow_url_fopen');
}
if (!$use_curl) {
# When there is no HTTPS wrapper, PHP streams cannott be used.
$use_curl = !in_array('https', stream_get_wrappers());
}
if (!$use_curl) {
# With open_basedir or safe_mode set, cURL can't follow redirects.
$use_curl = !(ini_get('safe_mode') || ini_get('open_basedir'));
}
} }
return $this->request_streams($url, $method, $params, $update_claimed_id);
return
$use_curl
? $this->request_curl($url, $method, $params, $update_claimed_id)
: $this->request_streams($url, $method, $params, $update_claimed_id);
} }
protected function proxy_url() protected function proxy_url()
{ {
$result = ''; $result = '';
if (!empty($this->proxy)) { if (!empty($this->proxy)) {
$result = $this->proxy['host']; $result = $this->proxy['host'];
if (!empty($this->proxy['port'])) { if (!empty($this->proxy['port'])) {
$result = $result . ':' . $this->proxy['port']; $result = $result . ':' . $this->proxy['port'];
} }
if (!empty($this->proxy['user'])) { if (!empty($this->proxy['user'])) {
$result = $this->proxy['user'] . ':' . $this->proxy['pass'] . '@' . $result; $result = $this->proxy['user'] . ':' . $this->proxy['pass'] . '@' . $result;
} }
$result = 'http://' . $result; $result = 'http://' . $result;
} }
return $result; return $result;
} }
@@ -494,7 +553,7 @@ class LightOpenID
# A flag to disable yadis discovery in case of failure in headers. # A flag to disable yadis discovery in case of failure in headers.
$yadis = true; $yadis = true;
# Allows optional regex replacement of the URL, e.g. to use Google Apps # Allows optional regex replacement of the URL, e.g. to use Google Apps
# as an OpenID provider without setting up XRDS on the domain hosting. # as an OpenID provider without setting up XRDS on the domain hosting.
if (!is_null($this->xrds_override_pattern) && !is_null($this->xrds_override_replacement)) { if (!is_null($this->xrds_override_pattern) && !is_null($this->xrds_override_replacement)) {
@@ -512,14 +571,7 @@ class LightOpenID
$next = true; $next = true;
} }
if (isset($headers['content-type']) if (isset($headers['content-type']) && $this->is_allowed_type($headers['content-type'])) {
&& (strpos($headers['content-type'], 'application/xrds+xml') !== false
|| strpos($headers['content-type'], 'text/xml') !== false)
) {
# Apparently, some providers return XRDS documents as text/html.
# While it is against the spec, allowing this here shouldn't break
# compatibility with anything.
# ---
# Found an XRDS document, now let's find the server, and optionally delegate. # Found an XRDS document, now let's find the server, and optionally delegate.
$content = $this->request($url, 'GET'); $content = $this->request($url, 'GET');
@@ -625,11 +677,26 @@ class LightOpenID
throw new ErrorException('Endless redirection!', 500); throw new ErrorException('Endless redirection!', 500);
} }
protected function is_allowed_type($content_type) {
# Apparently, some providers return XRDS documents as text/html.
# While it is against the spec, allowing this here shouldn't break
# compatibility with anything.
$allowed_types = array('application/xrds+xml', 'text/html', 'text/xml');
foreach ($allowed_types as $type) {
if (strpos($content_type, $type) !== false) {
return true;
}
}
return false;
}
protected function sregParams() protected function sregParams()
{ {
$params = array(); $params = array();
# We always use SREG 1.1, even if the server is advertising only support for 1.0. # We always use SREG 1.1, even if the server is advertising only support for 1.0.
# That's because it's fully backwards compatible with 1.0, and some providers # That's because it's fully backwards compatibile with 1.0, and some providers
# advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com # advertise 1.0 even if they accept only 1.1. One such provider is myopenid.com
$params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1'; $params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1';
if ($this->required) { if ($this->required) {
@@ -679,7 +746,7 @@ class LightOpenID
$params['openid.ax.count.' . $alias] = $count; $params['openid.ax.count.' . $alias] = $count;
} }
# Don't send empty ax.required and ax.if_available. # Don't send empty ax.requied and ax.if_available.
# Google and possibly other providers refuse to support ax when one of these is empty. # Google and possibly other providers refuse to support ax when one of these is empty.
if($required) { if($required) {
$params['openid.ax.required'] = implode(',', $required); $params['openid.ax.required'] = implode(',', $required);
@@ -720,15 +787,15 @@ class LightOpenID
'openid.return_to' => $this->returnUrl, 'openid.return_to' => $this->returnUrl,
'openid.realm' => $this->trustRoot, 'openid.realm' => $this->trustRoot,
); );
if ($this->ax) { if ($this->ax) {
$params += $this->axParams(); $params += $this->axParams();
} }
if ($this->sreg) { if ($this->sreg) {
$params += $this->sregParams(); $params += $this->sregParams();
} }
if (!$this->ax && !$this->sreg) { if (!$this->ax && !$this->sreg) {
# If OP doesn't advertise either SREG, nor AX, let's send them both # If OP doesn't advertise either SREG, nor AX, let's send them both
# in worst case we don't get anything in return. # in worst case we don't get anything in return.
@@ -812,7 +879,7 @@ class LightOpenID
if ($this->data['openid_return_to'] != $this->returnUrl) { if ($this->data['openid_return_to'] != $this->returnUrl) {
# The return_to url must match the url of current request. # The return_to url must match the url of current request.
# I'm assuming that no one will set the returnUrl to something that doesn't make sense. # I'm assuing that noone will set the returnUrl to something that doesn't make sense.
return false; return false;
} }
@@ -821,7 +888,7 @@ class LightOpenID
foreach (explode(',', $this->data['openid_signed']) as $item) { foreach (explode(',', $this->data['openid_signed']) as $item) {
# Checking whether magic_quotes_gpc is turned on, because # Checking whether magic_quotes_gpc is turned on, because
# the function may fail if it is. For example, when fetching # the function may fail if it is. For example, when fetching
# AX namePerson, it might contain an apostrophe, which will be escaped. # AX namePerson, it might containg an apostrophe, which will be escaped.
# In such case, validation would fail, since we'd send different data than OP # In such case, validation would fail, since we'd send different data than OP
# wants to verify. stripslashes() should solve that problem, but we can't # wants to verify. stripslashes() should solve that problem, but we can't
# use it when magic_quotes is off. # use it when magic_quotes is off.
@@ -840,36 +907,36 @@ class LightOpenID
protected function getAxAttributes() protected function getAxAttributes()
{ {
$result = array(); $result = array();
if ($alias = $this->getNamespaceAlias('http://openid.net/srv/ax/1.0', 'ax')) { if ($alias = $this->getNamespaceAlias('http://openid.net/srv/ax/1.0', 'ax')) {
$prefix = 'openid_' . $alias; $prefix = 'openid_' . $alias;
$length = strlen('http://axschema.org/'); $length = strlen('http://axschema.org/');
foreach (explode(',', $this->data['openid_signed']) as $key) { foreach (explode(',', $this->data['openid_signed']) as $key) {
$keyMatch = $alias . '.type.'; $keyMatch = $alias . '.type.';
if (strncmp($key, $keyMatch, strlen($keyMatch)) !== 0) { if (strncmp($key, $keyMatch, strlen($keyMatch)) !== 0) {
continue; continue;
} }
$key = substr($key, strlen($keyMatch)); $key = substr($key, strlen($keyMatch));
$idv = $prefix . '_value_' . $key; $idv = $prefix . '_value_' . $key;
$idc = $prefix . '_count_' . $key; $idc = $prefix . '_count_' . $key;
$key = substr($this->getItem($prefix . '_type_' . $key), $length); $key = substr($this->getItem($prefix . '_type_' . $key), $length);
if (!empty($key)) { if (!empty($key)) {
if (($count = intval($this->getItem($idc))) > 0) { if (($count = intval($this->getItem($idc))) > 0) {
$value = array(); $value = array();
for ($i = 1; $i <= $count; $i++) { for ($i = 1; $i <= $count; $i++) {
$value[] = $this->getItem($idv . '_' . $i); $value[] = $this->getItem($idv . '_' . $i);
} }
$value = ($count == 1) ? reset($value) : $value; $value = ($count == 1) ? reset($value) : $value;
} else { } else {
$value = $this->getItem($idv); $value = $this->getItem($idv);
} }
if (!is_null($value)) { if (!is_null($value)) {
$result[$key] = $value; $result[$key] = $value;
} }
@@ -879,7 +946,7 @@ class LightOpenID
// No alias for the AX schema has been found, // No alias for the AX schema has been found,
// so there is no AX data in the OP's response. // so there is no AX data in the OP's response.
} }
return $result; return $result;
} }
@@ -903,7 +970,7 @@ class LightOpenID
} }
/** /**
* Gets AX/SREG attributes provided by OP. should be used only after successful validation. * Gets AX/SREG attributes provided by OP. should be used only after successful validaton.
* Note that it does not guarantee that any of the required/optional parameters will be present, * Note that it does not guarantee that any of the required/optional parameters will be present,
* or that there will be no other attributes besides those specified. * or that there will be no other attributes besides those specified.
* In other words. OP may provide whatever information it wants to. * In other words. OP may provide whatever information it wants to.
@@ -928,19 +995,19 @@ class LightOpenID
* In order to use the OpenID+OAuth hybrid protocol, you need to add at least one * In order to use the OpenID+OAuth hybrid protocol, you need to add at least one
* scope to the $openid->oauth array before you get the call to getAuthUrl(), e.g.: * scope to the $openid->oauth array before you get the call to getAuthUrl(), e.g.:
* $openid->oauth[] = 'https://www.googleapis.com/auth/plus.me'; * $openid->oauth[] = 'https://www.googleapis.com/auth/plus.me';
* *
* Furthermore the registered consumer name must fit the OpenID realm. * Furthermore the registered consumer name must fit the OpenID realm.
* To register an OpenID consumer at Google use: https://www.google.com/accounts/ManageDomains * To register an OpenID consumer at Google use: https://www.google.com/accounts/ManageDomains
* *
* @return string|bool OAuth request token on success, FALSE if no token was provided. * @return string|bool OAuth request token on success, FALSE if no token was provided.
*/ */
function getOAuthRequestToken() function getOAuthRequestToken()
{ {
$alias = $this->getNamespaceAlias('http://specs.openid.net/extensions/oauth/1.0'); $alias = $this->getNamespaceAlias('http://specs.openid.net/extensions/oauth/1.0');
return !empty($alias) ? $this->data['openid_' . $alias . '_request_token'] : false; return !empty($alias) ? $this->data['openid_' . $alias . '_request_token'] : false;
} }
/** /**
* Gets the alias for the specified namespace, if it's present. * Gets the alias for the specified namespace, if it's present.
* *
@@ -951,13 +1018,13 @@ class LightOpenID
private function getNamespaceAlias($namespace, $hint = null) private function getNamespaceAlias($namespace, $hint = null)
{ {
$result = null; $result = null;
if (empty($hint) || $this->getItem('openid_ns_' . $hint) != $namespace) { if (empty($hint) || $this->getItem('openid_ns_' . $hint) != $namespace) {
// The common alias is either undefined or points to // The common alias is either undefined or points to
// some other extension - search for another alias.. // some other extension - search for another alias..
$prefix = 'openid_ns_'; $prefix = 'openid_ns_';
$length = strlen($prefix); $length = strlen($prefix);
foreach ($this->data as $key => $val) { foreach ($this->data as $key => $val) {
if (strncmp($key, $prefix, $length) === 0 && $val === $namespace) { if (strncmp($key, $prefix, $length) === 0 && $val === $namespace) {
$result = trim(substr($key, $length)); $result = trim(substr($key, $length));
@@ -967,10 +1034,10 @@ class LightOpenID
} else { } else {
$result = $hint; $result = $hint;
} }
return $result; return $result;
} }
/** /**
* Gets an item from the $data array by the specified id. * Gets an item from the $data array by the specified id.
* *
@@ -979,6 +1046,6 @@ class LightOpenID
*/ */
private function getItem($id) private function getItem($id)
{ {
return isset($this->data[$id]) ? $this->data[$id] : null; return isset($this->data[$id]) ? $this->data[$id] : null;
} }
} }