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,9 +1,10 @@
<?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Auth class
@@ -12,19 +13,33 @@
*
* Generally, Hybrid_Auth is the only class you should instanciate and use throughout your application.
*/
class Hybrid_Auth
{
public static $version = "2.3.0";
class Hybrid_Auth {
public static $version = "2.6.0";
/**
* Configuration array
* @var array
*/
public static $config = array();
public static $store = NULL;
/**
* Auth cache
* @var Hybrid_Storage
*/
public static $store = null;
public static $error = NULL;
/**
* Error pool
* @var Hybrid_Error
*/
public static $error = null;
public static $logger = NULL;
// --------------------------------------------------------------------
/**
* Logger
* @var Hybrid_Logger
*/
public static $logger = null;
/**
* Try to start a new session of none then initialize Hybrid_Auth
@@ -33,35 +48,37 @@ class Hybrid_Auth
* 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 );
function __construct($config) {
Hybrid_Auth::initialize($config);
}
// --------------------------------------------------------------------
/**
* Try to initialize Hybrid_Auth with given $config hash or file
*
* @param array $config Configuration array or path to a configratuion file
* @return void
* @throws Exception
*/
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 );
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;
}
// 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_resources"] = $config["path_base"] . "resources/";
$config["path_providers"] = $config["path_base"] . "Providers/";
// reset debug mode
if( ! isset( $config["debug_mode"] ) ){
if (!isset($config["debug_mode"])) {
$config["debug_mode"] = false;
$config["debug_file"] = null;
}
@@ -83,7 +100,7 @@ class Hybrid_Auth
require_once $config["path_base"] . "User_Contact.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";
}
@@ -99,102 +116,94 @@ class Hybrid_Auth
// start session storage mng
Hybrid_Auth::$store = new Hybrid_Storage();
Hybrid_Logger::info( "Enter Hybrid_Auth::initialize()");
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 called from: " . Hybrid_Auth::getCurrentUrl() );
Hybrid_Logger::info("Enter Hybrid_Auth::initialize()");
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 called from: " . Hybrid_Auth::getCurrentUrl());
// 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.');
throw new Exception('Hybridauth Library needs the CURL PHP extension.');
}
// 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.');
throw new Exception('Hybridauth Library needs the JSON PHP extension.');
}
// 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.');
}
// 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.');
}
// 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::debug( "Hybrid_Auth initialize. dump used config: ", serialize( $config ) );
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::debug("Hybrid_Auth initialize. dump used config: ", serialize($config));
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...");
if( Hybrid_Error::hasError() ){
if (Hybrid_Error::hasError()) {
$m = Hybrid_Error::getErrorMessage();
$c = Hybrid_Error::getErrorCode();
$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();
// try to provide the previous if any
// 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) ) {
throw new Exception( $m, $c, $p );
}
else{
throw new Exception( $m, $c );
if (version_compare(PHP_VERSION, '5.3.0', '>=') && ($p instanceof Exception)) {
throw new Exception($m, $c, $p);
} else {
throw new Exception($m, $c);
}
}
Hybrid_Logger::info( "Hybrid_Auth initialize: no error found. initialization succeed." );
// Endof initialize
Hybrid_Logger::info("Hybrid_Auth initialize: no error found. initialization succeed.");
}
// --------------------------------------------------------------------
/**
* 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
* 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.
*
* @return Hybrid_Storage
*/
public static function storage()
{
public static function storage() {
return Hybrid_Auth::$store;
}
// --------------------------------------------------------------------
/**
* Get hybridauth session data.
* Get hybridauth session data
* @return string|null
*/
function getSessionData()
{
function getSessionData() {
return Hybrid_Auth::storage()->getSessionData();
}
// --------------------------------------------------------------------
/**
* restore hybridauth session data.
* Restore hybridauth session data
*
* @param string $sessiondata Serialized session data
* @retun void
*/
function restoreSessionData( $sessiondata = NULL )
{
Hybrid_Auth::storage()->restoreSessionData( $sessiondata );
function restoreSessionData($sessiondata = null) {
Hybrid_Auth::storage()->restoreSessionData($sessiondata);
}
// --------------------------------------------------------------------
/**
* Try to authenticate the user with a given provider.
*
@@ -206,96 +215,88 @@ class Hybrid_Auth
* hauth_return_to: URL to call back after authentication is done
* openid_identifier: The OpenID identity provider identifier
* google_service: can be "Users" for Google user accounts service or "Apps" for Google hosted Apps
*
* @param string $providerId ID of the provider
* @param array $params Params
* @return
*/
public static function authenticate( $providerId, $params = NULL )
{
Hybrid_Logger::info( "Enter Hybrid_Auth::authenticate( $providerId )" );
public static function authenticate($providerId, $params = null) {
Hybrid_Logger::info("Enter Hybrid_Auth::authenticate( $providerId )");
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
if( ! Hybrid_Auth::storage()->get( "hauth_session.$providerId.is_logged_in" ) ){
Hybrid_Logger::info( "Hybrid_Auth::authenticate( $providerId ), User not connected to the provider. Try to authenticate.." );
$provider_adapter = Hybrid_Auth::setup( $providerId, $params );
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();
}
} else {
// else, then return the adapter instance for the given provider
else{
Hybrid_Logger::info( "Hybrid_Auth::authenticate( $providerId ), User is already connected to this provider. Return the adapter instance." );
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
*
* @param string $providerId ID of the provider
* @return Hybrid_Provider_Adapter
*/
public static function getAdapter( $providerId = NULL )
{
Hybrid_Logger::info( "Enter Hybrid_Auth::getAdapter( $providerId )" );
return Hybrid_Auth::setup( $providerId );
public static function getAdapter($providerId = null) {
Hybrid_Logger::info("Enter Hybrid_Auth::getAdapter( $providerId )");
return Hybrid_Auth::setup($providerId);
}
// --------------------------------------------------------------------
/**
* Setup an adapter for a given provider
*
* @param string $providerId ID of the provider
* @param array $params Adapter params
* @return Hybrid_Provider_Adapter
*/
public static function setup( $providerId, $params = NULL )
{
Hybrid_Logger::debug( "Enter Hybrid_Auth::setup( $providerId )", $params );
public static function setup($providerId, $params = null) {
Hybrid_Logger::debug("Enter Hybrid_Auth::setup( $providerId )", $params);
if( ! $params ){
$params = Hybrid_Auth::storage()->get( "hauth_session.$providerId.id_provider_params" );
if (!$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 ){
$params = ARRAY();
Hybrid_Logger::info( "Hybrid_Auth::setup( $providerId ), no stored params found for this provider. Initialize a new one for new session" );
if (!$params) {
$params = array();
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();
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
$provider = new Hybrid_Provider_Adapter();
$provider->factory( $providerId, $params );
$provider->factory($providerId, $params);
return $provider;
}
// --------------------------------------------------------------------
/**
* 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" );
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
*/
public static function getConnectedProviders()
{
public static function getConnectedProviders() {
$idps = array();
foreach( Hybrid_Auth::$config["providers"] as $idpid => $params ){
if( Hybrid_Auth::isConnectedWith( $idpid ) ){
foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
if (Hybrid_Auth::isConnectedWith($idpid)) {
$idps[] = $idpid;
}
}
@@ -303,20 +304,26 @@ class Hybrid_Auth
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
*
* <code>
* array(
* 'Facebook' => array(
* 'connected' => true
* )
* )
* </code>
* @return array
*/
public static function getProviders()
{
public static function getProviders() {
$idps = array();
foreach( Hybrid_Auth::$config["providers"] as $idpid => $params ){
if($params['enabled']) {
$idps[$idpid] = array( 'connected' => false );
foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
if ($params['enabled']) {
$idps[$idpid] = array('connected' => false);
if( Hybrid_Auth::isConnectedWith( $idpid ) ){
if (Hybrid_Auth::isConnectedWith($idpid)) {
$idps[$idpid]['connected'] = true;
}
}
@@ -325,35 +332,36 @@ class Hybrid_Auth
return $idps;
}
// --------------------------------------------------------------------
/**
* A generic function to logout all connected provider at once
* @return void
*/
public static function logoutAllProviders()
{
public static function logoutAllProviders() {
$idps = Hybrid_Auth::getConnectedProviders();
foreach( $idps as $idp ){
$adapter = Hybrid_Auth::getAdapter( $idp );
foreach ($idps as $idp) {
$adapter = Hybrid_Auth::getAdapter($idp);
$adapter->logout();
}
}
// --------------------------------------------------------------------
/**
* Utility function, redirect to a given URL with php header or using javascript location.href
*
* @param string $url URL to redirect to
* @param string $mode PHP|JS
*/
public static function redirect( $url, $mode = "PHP" )
{
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" ){
header( "Location: $url" ) ;
// Ensure session is saved before sending response, see https://github.com/symfony/symfony/pull/12341
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 '<head>';
echo '<script type="text/javascript">';
@@ -369,33 +377,35 @@ class Hybrid_Auth
die();
}
// --------------------------------------------------------------------
/**
* Utility function, return the current url. TRUE to get $_SERVER['REQUEST_URI'], FALSE for $_SERVER['PHP_SELF']
* Utility function, return the current url
*
* @param bool $request_uri true to get $_SERVER['REQUEST_URI'], false for $_SERVER['PHP_SELF']
* @return string
*/
public static function getCurrentUrl( $request_uri = true )
{
if(
isset( $_SERVER['HTTPS'] ) && ( $_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 )
|| isset( $_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
){
$protocol = 'https://';
public static function getCurrentUrl($request_uri = true) {
if (php_sapi_name() == 'cli') {
return '';
}
else {
$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'];
if( $request_uri ){
if ($request_uri) {
$url .= $_SERVER['REQUEST_URI'];
}
else{
} else {
$url .= $_SERVER['PHP_SELF'];
}
// return current url
return $url;
}
}

View File

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

View File

@@ -1,89 +1,88 @@
<?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Errors manager
*
* 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
* @param string $message Error message
* @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 )" );
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 );
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
* @return void
*/
public static function clearError()
{
Hybrid_Logger::info( "Enter Hybrid_Error::clearError()" );
public static function clearError() {
Hybrid_Logger::info("Enter Hybrid_Error::clearError()");
Hybrid_Auth::storage()->delete( "hauth_session.error.status" );
Hybrid_Auth::storage()->delete( "hauth_session.error.message" );
Hybrid_Auth::storage()->delete( "hauth_session.error.code" );
Hybrid_Auth::storage()->delete( "hauth_session.error.trace" );
Hybrid_Auth::storage()->delete( "hauth_session.error.previous" );
Hybrid_Auth::storage()->delete("hauth_session.error.status");
Hybrid_Auth::storage()->delete("hauth_session.error.message");
Hybrid_Auth::storage()->delete("hauth_session.error.code");
Hybrid_Auth::storage()->delete("hauth_session.error.trace");
Hybrid_Auth::storage()->delete("hauth_session.error.previous");
}
/**
* 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()
{
return (bool) Hybrid_Auth::storage()->get( "hauth_session.error.status" );
public static function hasError() {
return (bool) Hybrid_Auth::storage()->get("hauth_session.error.status");
}
/**
* return error message
* Return error message
* @return string
*/
public static function getErrorMessage()
{
return Hybrid_Auth::storage()->get( "hauth_session.error.message" );
public static function getErrorMessage() {
return Hybrid_Auth::storage()->get("hauth_session.error.message");
}
/**
* return error code
* Return error code
* @return int
*/
public static function getErrorCode()
{
return Hybrid_Auth::storage()->get( "hauth_session.error.code" );
public static function getErrorCode() {
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()
{
return Hybrid_Auth::storage()->get( "hauth_session.error.trace" );
public static function getErrorTrace() {
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()
{
return Hybrid_Auth::storage()->get( "hauth_session.error.previous" );
public static function getErrorPrevious() {
return Hybrid_Auth::storage()->get("hauth_session.error.previous");
}
}

View File

@@ -1,9 +1,10 @@
<?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-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Exception implementation
@@ -11,6 +12,6 @@
* The base Exception is extended to allow applications to handle exceptions from hybrid auth
* separately from general exceptions.
*/
class Hybrid_Exception extends Exception
{
class Hybrid_Exception extends Exception {
}

View File

@@ -1,89 +1,102 @@
<?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Debugging and Logging manager
*/
class Hybrid_Logger
{
class Hybrid_Logger {
/**
* Constructor
*/
function __construct()
{
function __construct() {
// if debug mode is set to true, then check for the writable log file
if ( Hybrid_Auth::$config["debug_mode"] ){
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 );
if (Hybrid_Auth::$config["debug_mode"]) {
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);
} elseif (!file_exists(Hybrid_Auth::$config["debug_file"]) && !is_writable(Hybrid_Auth::$config["debug_file"])) {
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 ( ! file_exists( Hybrid_Auth::$config["debug_file"] ) && ! is_writable( Hybrid_Auth::$config["debug_file"]) ){
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
* Logs a debug message with an object dump
*
* @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"] ){
$datetime = new DateTime();
$datetime = $datetime->format(DATE_ATOM);
file_put_contents(
Hybrid_Auth::$config["debug_file"],
"DEBUG -- " . $_SERVER['REMOTE_ADDR'] . " -- " . $datetime . " -- " . $message . " -- " . print_r($object, true) . "\n",
FILE_APPEND
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
* Logs an info message
*
* @param string $message Info message
* @return void
*/
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"],
"INFO -- " . $_SERVER['REMOTE_ADDR'] . " -- " . $datetime . " -- " . $message . "\n",
FILE_APPEND
);
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
* Logs an error message with an object dump
*
* @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) ){
$datetime = new DateTime();
$datetime = $datetime->format(DATE_ATOM);
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);
}
}
file_put_contents(
Hybrid_Auth::$config["debug_file"],
"ERROR -- " . $_SERVER['REMOTE_ADDR'] . " -- " . $datetime . " -- " . $message . " -- " . print_r($object, true) . "\n",
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,9 +1,10 @@
<?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Provider_Adapter is the basic class which Hybrid_Auth will use
@@ -15,114 +16,111 @@
* Hybrid_Auth will automatically load Hybrid_Provider_Adapter and create
* an instance of it for each authenticated provider.
*/
class Hybrid_Provider_Adapter
{
class Hybrid_Provider_Adapter {
/**
* Provider ID (or unique name)
* @var Numeric/String
* @var mixed
*/
public $id = NULL ;
public $id = null;
/**
* Provider adapter specific config
* @var Array
* @var array
*/
public $config = NULL ;
public $config = null;
/**
* Provider adapter extra parameters
* @var array
*/
public $params = array() ;
public $params = array();
/**
* Provider adapter wrapper path
* @var String
* @var string
*/
public $wrapper = NULL ;
public $wrapper = null;
/**
* 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 array $params (optional) required parameters by the adapter
* @return Hybrid_Provider_Adapter
* @throws Exception
*/
function factory( $id, $params = array() )
{
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
$this->id = $id;
$this->params = $params;
$this->id = $this->getProviderCiId( $this->id );
$this->config = $this->getConfigById( $this->id );
$this->id = $this->getProviderCiId($this->id);
$this->config = $this->getConfigById($this->id);
# check the IDp id
if( ! $this->id ){
throw new Exception( "No provider ID specified.", 2 );
if (!$this->id) {
throw new Exception("No provider ID specified.", 2);
}
# check the IDp config
if( ! $this->config ){
throw new Exception( "Unknown Provider ID, check your configuration file.", 3 );
if (!$this->config) {
throw new Exception("Unknown Provider ID, check your configuration file.", 3);
}
# check the IDp adapter is enabled
if( ! $this->config["enabled"] ){
throw new Exception( "The provider '{$this->id}' is not enabled.", 3 );
if (!$this->config["enabled"]) {
throw new Exception("The provider '{$this->id}' is not enabled.", 3);
}
# include the adapter wrapper
if( isset( $this->config["wrapper"] ) && is_array( $this->config["wrapper"] ) ){
if (isset( $this->config["wrapper"]["path"] )) {
if (isset($this->config["wrapper"]) && is_array($this->config["wrapper"])) {
if (isset($this->config["wrapper"]["path"])) {
require_once $this->config["wrapper"]["path"];
}
if( ! class_exists( $this->config["wrapper"]["class"] ) ){
throw new Exception( "Unable to load the adapter class.", 3 );
if (!class_exists($this->config["wrapper"]["class"])) {
throw new Exception("Unable to load the adapter class.", 3);
}
$this->wrapper = $this->config["wrapper"]["class"];
}
else{
require_once Hybrid_Auth::$config["path_providers"] . $this->id . ".php" ;
} else {
require_once Hybrid_Auth::$config["path_providers"] . $this->id . ".php";
$this->wrapper = "Hybrid_Providers_" . $this->id;
}
# 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;
}
// --------------------------------------------------------------------
/**
* Hybrid_Provider_Adapter::login(), prepare the user session and the authentication request
* for index.php
* @return void
* @throw Exception
*/
function login()
{
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 ){
throw new Exception( "Hybrid_Provider_Adapter::login() should not directly used." );
if (!$this->adapter) {
throw new Exception("Hybrid_Provider_Adapter::login() should not directly used.");
}
// clear all unneeded 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_endpoint" );
Hybrid_Auth::storage()->delete( "hauth_session.{$idpid}.id_provider_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_endpoint");
Hybrid_Auth::storage()->delete("hauth_session.{$idpid}.id_provider_params");
}
// make a fresh start
@@ -141,7 +139,7 @@ class Hybrid_Provider_Adapter
}
// make sure params is array
if( !is_array( $this->params ) ){
if (!is_array($this->params)) {
$this->params = array();
}
@@ -155,168 +153,169 @@ class Hybrid_Provider_Adapter
# for default HybridAuth endpoint url hauth_login_start_url
# auth.start required the IDp ID
# 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
# 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"] ) ){
Hybrid_Auth::storage()->set( "hauth_session.{$this->id}.hauth_return_to", $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"]);
}
if( isset( $this->params["login_done"] ) ){
Hybrid_Auth::storage()->set( "hauth_session.{$this->id}.hauth_endpoint" , $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}.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
Hybrid_Auth::storage()->config( "CONFIG", Hybrid_Auth::$config );
Hybrid_Auth::storage()->config("CONFIG", Hybrid_Auth::$config);
// 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();
}
// --------------------------------------------------------------------
/**
* 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();
}
// --------------------------------------------------------------------
/**
* handle :
* Call adapter methods defined in the adapter model:
* getUserProfile()
* getUserContacts()
* getUserActivity()
* setUserStatus()
*
* @param string $name Method name
* @param array $arguments Call arguments
* @return mixed
* @throws Exception
*/
public function __call( $name, $arguments )
{
Hybrid_Logger::info( "Enter Hybrid_Provider_Adapter::$name(), Provider: {$this->id}" );
public function __call($name, $arguments) {
Hybrid_Logger::info("Enter Hybrid_Provider_Adapter::$name(), Provider: {$this->id}");
if ( ! $this->isUserConnected() ){
throw new Exception( "User not connected to the provider {$this->id}.", 7 );
if (!$this->isUserConnected()) {
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()." );
if (!method_exists($this->adapter, $name)) {
throw new Exception("Call to undefined function Hybrid_Providers_{$this->id}::$name().");
}
$counter = count( $arguments );
if( $counter == 1 ){
return $this->adapter->$name( $arguments[0] );
}
elseif( $counter == 2 ){
return $this->adapter->$name( $arguments[0], $arguments[1] );
}
else{
$counter = count($arguments);
if ($counter == 1) {
return $this->adapter->$name($arguments[0]);
} elseif ($counter == 2) {
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 provider api use oauth
*
* <code>
* array(
* 'access_token' => '',
* 'access_token_secret' => '',
* 'refresh_token' => '',
* '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 );
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
ARRAY(
"access_token" => $this->adapter->token( "access_token" ) , // OAuth access token
"access_token_secret" => $this->adapter->token( "access_token_secret" ), // OAuth access token secret
"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_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
return array(
"access_token" => $this->adapter->token("access_token"), // OAuth access token
"access_token_secret" => $this->adapter->token("access_token_secret"), // OAuth access token secret
"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_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
* @return stdClass
* @throws Exception
*/
function api()
{
if( ! $this->adapter->isUserConnected() ){
Hybrid_Logger::error( "User not connected to the provider." );
function api() {
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;
}
// --------------------------------------------------------------------
/**
* 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
$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
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}.id_provider_params" );
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}.id_provider_params");
// 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
*
* @param string $id Config key
* @return mixed
*/
function getConfigById( $id )
{
if( isset( Hybrid_Auth::$config["providers"][$id] ) ){
function getConfigById($id) {
if (isset(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
*
* @param string $id Provider id
* @return mixed
*/
function getProviderCiId( $id )
{
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 NULL;
return null;
}
}

View File

@@ -1,9 +1,10 @@
<?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Provider_Model provide a common interface for supported IDps on HybridAuth.
@@ -19,57 +20,62 @@
* 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.
*/
abstract class Hybrid_Provider_Model
{
abstract class Hybrid_Provider_Model {
/**
* IDp ID (or unique name)
* @var Numeric/String
* @var mixed
*/
public $providerId = NULL;
public $providerId = null;
/**
* specific provider adapter config
* Specific provider adapter config
* @var array
*/
public $config = NULL;
public $config = null;
/**
* provider extra parameters
* Provider extra parameters
* @var array
*/
public $params = NULL;
public $params = null;
/**
* Endpoint URL for that provider
* @var String
* @var string
*/
public $endpoint = NULL;
public $endpoint = null;
/**
* Hybrid_User obj, represents the current loggedin user
* @var object
* @var Hybrid_User
*/
public $user = NULL;
public $user = null;
/**
* the provider api client (optional)
* @var String
* The provider api client (optional)
* @var stdClass
*/
public $api = NULL;
public $api = null;
/**
* Model should use "gzip,deflate" for CURLOPT_ENCODING
* @var stdClass
*/
public $compressed = false;
/**
* Common providers adapter constructor
* @param Numeric/String $providerId
* @param Array $config
* @param Array $params
*
* @param mixed $providerId Provider ID
* @param array $config Provider adapter config
* @param array $params Provider extra params
*/
function __construct( $providerId, $config, $params = 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{
if (!$params) {
$this->params = Hybrid_Auth::storage()->get("hauth_session.$providerId.id_provider_params");
} else {
$this->params = $params;
}
@@ -77,7 +83,7 @@ abstract class Hybrid_Provider_Model
$this->providerId = $providerId;
// set HybridAuth endpoint for this provider
$this->endpoint = Hybrid_Auth::storage()->get( "hauth_session.$providerId.hauth_endpoint" );
$this->endpoint = Hybrid_Auth::storage()->get("hauth_session.$providerId.hauth_endpoint");
// idp config
$this->config = $config;
@@ -89,11 +95,9 @@ abstract class Hybrid_Provider_Model
// initialize the current provider adapter
$this->initialize();
Hybrid_Logger::debug( "Hybrid_Provider_Model::__construct( $providerId ) initialized. dump current adapter instance: ", serialize( $this ) );
Hybrid_Logger::debug("Hybrid_Provider_Model::__construct( $providerId ) initialized. dump current adapter instance: ", serialize($this));
}
// --------------------------------------------------------------------
/**
* IDp wrappers initializer
*
@@ -102,162 +106,139 @@ abstract class Hybrid_Provider_Model
* - 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
*
* @return void
* @throws Exception
*/
abstract protected function loginBegin();
// --------------------------------------------------------------------
/**
* finish login
* Finish login
* @return void
* @throws Exception
*/
abstract protected function loginFinish();
// --------------------------------------------------------------------
/**
* generic logout, just erase current provider adapter stored data to let Hybrid_Auth all forget about it
* Generic logout, just erase current provider adapter stored data to let Hybrid_Auth all forget about it
* @return bool
*/
function logout()
{
Hybrid_Logger::info( "Enter [{$this->providerId}]::logout()" );
function logout() {
Hybrid_Logger::info("Enter [{$this->providerId}]::logout()");
$this->clearTokens();
return TRUE;
return true;
}
// --------------------------------------------------------------------
/**
* grab the user profile from the IDp api client
* 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 );
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);
}
// --------------------------------------------------------------------
/**
* load the current logged in user contacts list from the IDp api client
* Load the current logged in user contacts list from the IDp api client
* @return Hybrid_User_Contact[]
* @throws Exception
*/
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 );
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);
}
// --------------------------------------------------------------------
/**
* return the user activity stream
* 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 );
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);
}
// --------------------------------------------------------------------
/**
* set user status
* 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 );
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 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 );
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
* Return true if the user is connected to the current provider
* @return bool
*/
public function isUserConnected()
{
return (bool) Hybrid_Auth::storage()->get( "hauth_session.{$this->providerId}.is_logged_in" );
public function isUserConnected() {
return (bool) Hybrid_Auth::storage()->get("hauth_session.{$this->providerId}.is_logged_in");
}
// --------------------------------------------------------------------
/**
* set user to connected
* 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 );
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
* Set user to unconnected
* @return void
*/
public function setUserUnconnected()
{
Hybrid_Logger::info( "Enter [{$this->providerId}]::setUserUnconnected()" );
Hybrid_Auth::storage()->set( "hauth_session.{$this->providerId}.is_logged_in", 0 );
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
* 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 );
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
* Delete a stored token
* @return void
*/
public function deleteToken( $token )
{
Hybrid_Auth::storage()->delete( "hauth_session.{$this->providerId}.token.$token" );
public function deleteToken($token) {
Hybrid_Auth::storage()->delete("hauth_session.{$this->providerId}.token.$token");
}
// --------------------------------------------------------------------
/**
* clear all existent tokens for this provider
* Clear all existent tokens for this provider
* @return void
*/
public function clearTokens()
{
Hybrid_Auth::storage()->deleteMatch( "hauth_session.{$this->providerId}." );
public function clearTokens() {
Hybrid_Auth::storage()->deleteMatch("hauth_session.{$this->providerId}.");
}
}

View File

@@ -1,9 +1,10 @@
<?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* To implement an OAuth 1 based service provider, Hybrid_Provider_Model_OAuth1
@@ -17,26 +18,34 @@
* Hybrid_Provider_Model_OAuth1 use OAuth1Client v0.1 which can be found on
* 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
* @var object
* Provider API client
* @var OAuth1Client
*/
public $api = null;
/**
* Request_tokens as received from provider
* @var stdClas
*/
public $request_tokens_raw = null;
/**
* access_tokens as received from provider
* @var object
* Access_tokens as received from provider
* @var stdClass
*/
public $access_tokens_raw = null;
/**
* Try to get the error message from provider api
* @param Numeric $code
*
* @param int $code Error code
* @return string
*/
function errorMessageByStatus( $code = null ) {
$http_status_codes = ARRAY(
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.",
@@ -49,123 +58,117 @@ class Hybrid_Provider_Model_OAuth1 extends Hybrid_Provider_Model
503 => "Service Unavailable."
);
if( ! $code && $this->api )
if (!$code && $this->api) {
$code = $this->api->http_code;
if( isset( $http_status_codes[ $code ] ) )
return $code . " " . $http_status_codes[ $code ];
}
// --------------------------------------------------------------------
if (isset($http_status_codes[$code])) {
return $code . " " . $http_status_codes[$code];
}
}
/**
* adapter initializer
* {@inheritdoc}
*/
function initialize()
{
function initialize() {
// 1 - check application credentials
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 (!$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);
}
// 2 - include OAuth lib and client
if (! class_exists('OAuthConsumer') ) {
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
if( $this->token( "access_token" ) ){
if ($this->token("access_token")) {
$this->api = new OAuth1Client(
$this->config["keys"]["key"], $this->config["keys"]["secret"],
$this->token( "access_token" ), $this->token( "access_token_secret" )
$this->config["keys"]["key"], $this->config["keys"]["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
elseif( $this->token( "request_token" ) ){
elseif ($this->token("request_token")) {
$this->api = new OAuth1Client(
$this->config["keys"]["key"], $this->config["keys"]["secret"],
$this->token( "request_token" ), $this->token( "request_token_secret" )
$this->config["keys"]["key"], $this->config["keys"]["secret"], $this->token("request_token"), $this->token("request_token_secret")
);
}
// 3.3 - instanciate OAuth client with client credentials
else{
$this->api = new OAuth1Client( $this->config["keys"]["key"], $this->config["keys"]["secret"] );
else {
$this->api = new OAuth1Client($this->config["keys"]["key"], $this->config["keys"]["secret"]);
}
// 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"];
}
}
// --------------------------------------------------------------------
/**
* begin login step
* {@inheritdoc}
*/
function loginBegin()
{
$tokens = $this->api->requestToken( $this->endpoint );
function loginBegin() {
$tokens = $this->api->requestToken($this->endpoint);
// request tokens as received from provider
$this->request_tokens_raw = $tokens;
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ), 5 );
if ($this->api->http_code != 200) {
throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
}
if ( ! isset( $tokens["oauth_token"] ) ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid oauth token.", 5 );
if (!isset($tokens["oauth_token"])) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth token.", 5);
}
$this->token( "request_token" , $tokens["oauth_token"] );
$this->token( "request_token_secret", $tokens["oauth_token_secret"] );
$this->token("request_token", $tokens["oauth_token"]);
$this->token("request_token_secret", $tokens["oauth_token_secret"]);
# 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()
{
$oauth_token = (array_key_exists('oauth_token',$_REQUEST))?$_REQUEST['oauth_token']:"";
$oauth_verifier = (array_key_exists('oauth_verifier',$_REQUEST))?$_REQUEST['oauth_verifier']:"";
function loginFinish() {
$oauth_token = (array_key_exists('oauth_token', $_REQUEST)) ? $_REQUEST['oauth_token'] : "";
$oauth_verifier = (array_key_exists('oauth_verifier', $_REQUEST)) ? $_REQUEST['oauth_verifier'] : "";
if ( ! $oauth_token || ! $oauth_verifier ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid oauth verifier.", 5 );
if (!$oauth_token || !$oauth_verifier) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth verifier.", 5);
}
// request an access token
$tokens = $this->api->accessToken( $oauth_verifier );
$tokens = $this->api->accessToken($oauth_verifier);
// access tokens as received from provider
$this->access_tokens_raw = $tokens;
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ), 5 );
if ($this->api->http_code != 200) {
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
if ( ! isset( $tokens["oauth_token"] ) ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid access token.", 5 );
if (!isset($tokens["oauth_token"])) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5);
}
// we no more need to store request tokens
$this->deleteToken( "request_token" );
$this->deleteToken( "request_token_secret" );
$this->deleteToken("request_token");
$this->deleteToken("request_token_secret");
// store access_token for later user
$this->token( "access_token" , $tokens['oauth_token'] );
$this->token( "access_token_secret" , $tokens['oauth_token_secret'] );
$this->token("access_token", $tokens['oauth_token']);
$this->token("access_token_secret", $tokens['oauth_token_secret']);
// set user as logged in to the current provider
$this->setUserConnected();
}
}

View File

@@ -1,9 +1,10 @@
<?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* To implement an OAuth 2 based service provider, Hybrid_Provider_Model_OAuth2
@@ -17,20 +18,28 @@
* Hybrid_Provider_Model_OAuth2 use OAuth2Client v0.1 which can be found on
* 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
* Default permissions
* @var string
*/
public $scope = "";
/**
* Try to get the error message from provider api
* @param Numeric $code
* Provider API wrapper
* @var OAuth2Client
*/
function errorMessageByStatus( $code = null ) {
$http_status_codes = ARRAY(
public $api = null;
/**
* 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.",
@@ -43,26 +52,25 @@ class Hybrid_Provider_Model_OAuth2 extends Hybrid_Provider_Model
503 => "Service Unavailable."
);
if( ! $code && $this->api )
if (!$code && $this->api) {
$code = $this->api->http_code;
if( isset( $http_status_codes[ $code ] ) )
return $code . " " . $http_status_codes[ $code ];
}
// --------------------------------------------------------------------
if (isset($http_status_codes[$code])) {
return $code . " " . $http_status_codes[$code];
}
}
/**
* adapter initializer
* Adapter initializer
*/
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 );
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"] ) ){
if (isset($this->config["scope"]) && !empty($this->config["scope"])) {
$this->scope = $this->config["scope"];
}
@@ -70,98 +78,93 @@ class Hybrid_Provider_Model_OAuth2 extends Hybrid_Provider_Model
require_once Hybrid_Auth::$config["path_libraries"] . "OAuth/OAuth2Client.php";
// create a new OAuth2 client instance
$this->api = new OAuth2Client( $this->config["keys"]["id"], $this->config["keys"]["secret"], $this->endpoint );
$this->api = new OAuth2Client($this->config["keys"]["id"], $this->config["keys"]["secret"], $this->endpoint, $this->compressed);
// If we have an access token, set it
if( $this->token( "access_token" ) ){
$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" );
if ($this->token("access_token")) {
$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"] ) ){
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
Hybrid_Auth::redirect( $this->api->authorizeUrl( array( "scope" => $this->scope ) ) );
Hybrid_Auth::redirect($this->api->authorizeUrl(array("scope" => $this->scope)));
}
// --------------------------------------------------------------------
/**
* finish login step
* {@inheritdoc}
*/
function loginFinish()
{
$error = (array_key_exists('error',$_REQUEST))?$_REQUEST['error']:"";
function loginFinish() {
$error = (array_key_exists('error', $_REQUEST)) ? $_REQUEST['error'] : "";
// check for errors
if ( $error ){
throw new Exception( "Authentication failed! {$this->providerId} returned an error: $error", 5 );
if ($error) {
throw new Exception("Authentication failed! {$this->providerId} returned an error: $error", 5);
}
// try to authenticate user
$code = (array_key_exists('code',$_REQUEST))?$_REQUEST['code']:"";
$code = (array_key_exists('code', $_REQUEST)) ? $_REQUEST['code'] : "";
try{
$this->api->authenticate( $code );
}
catch( Exception $e ){
throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
try {
$this->api->authenticate($code);
} catch (Exception $e) {
throw new Exception("User profile request failed! {$this->providerId} returned an error: $e", 6);
}
// check if authenticated
if ( ! $this->api->access_token ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid access token.", 5 );
if (!$this->api->access_token) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5);
}
// 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 );
$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);
// set user connected locally
$this->setUserConnected();
}
function refreshToken()
{
/**
* {@inheritdoc}
*/
function refreshToken() {
// have an access token?
if( $this->api->access_token ){
if ($this->api->access_token) {
// 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?
if( $this->api->access_token_expires_at <= time() ){
$response = $this->api->refreshToken( array( "refresh_token" => $this->api->refresh_token ) );
if ($this->api->access_token_expires_at <= time()) {
$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
$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
$this->api->access_token = $response->access_token;
if( isset( $response->refresh_token ) )
if (isset($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;
// even given by some idp, we should calculate this
@@ -171,10 +174,11 @@ class Hybrid_Provider_Model_OAuth2 extends Hybrid_Provider_Model
}
// 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 );
$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
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* 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/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
* @var string
*/
public $openidIdentifier = "";
// --------------------------------------------------------------------
/**
* adapter initializer
* {@inheritdoc}
*/
function initialize()
{
if( isset( $this->params["openid_identifier"] ) ){
function initialize() {
if (isset($this->params["openid_identifier"])) {
$this->openidIdentifier = $this->params["openid_identifier"];
}
@@ -38,74 +42,63 @@ class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model
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.
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);
$hostUrl = parse_url( Hybrid_Auth::$config["base_url"], PHP_URL_HOST);
$hostPort = parse_url(Hybrid_Auth::$config["base_url"], PHP_URL_PORT);
$hostUrl = parse_url(Hybrid_Auth::$config["base_url"], PHP_URL_HOST);
// Check for port on url
if($hostPort) {
$hostUrl .= ':'.$hostPort;
if ($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()
{
if( empty( $this->openidIdentifier ) ){
throw new Exception( "OpenID adapter require the identity provider identifier 'openid_identifier' as an extra parameter.", 4 );
function loginBegin() {
if (empty($this->openidIdentifier)) {
throw new Exception("OpenID adapter require the identity provider identifier 'openid_identifier' as an extra parameter.", 4);
}
$this->api->identity = $this->openidIdentifier;
$this->api->returnUrl = $this->endpoint;
$this->api->required = ARRAY(
'namePerson/first' ,
'namePerson/last' ,
'namePerson/friendly' ,
'namePerson' ,
'contact/email' ,
'birthDate' ,
'birthDate/birthDay' ,
'birthDate/birthMonth' ,
'birthDate/birthYear' ,
'person/gender' ,
'pref/language' ,
$this->api->required = array(
'namePerson/first',
'namePerson/last',
'namePerson/friendly',
'namePerson',
'contact/email',
'birthDate',
'birthDate/birthDay',
'birthDate/birthMonth',
'birthDate/birthYear',
'person/gender',
'pref/language',
'contact/postalCode/home',
'contact/city/home' ,
'contact/country/home' ,
'media/image/default' ,
'contact/city/home',
'contact/country/home',
'media/image/default',
);
# 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( $this->api->mode == 'cancel'){
throw new Exception( "Authentication failed! User has canceled authentication!", 5 );
if ($this->api->mode == 'cancel') {
throw new Exception("Authentication failed! User has canceled authentication!", 5);
}
# if something goes wrong
if( ! $this->api->validate() ){
throw new Exception( "Authentication failed. Invalid request received!", 5 );
if (!$this->api->validate()) {
throw new Exception("Authentication failed. Invalid request received!", 5);
}
# fetch received user data
@@ -114,25 +107,25 @@ class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model
# store the user profile
$this->user->profile->identifier = $this->api->identity;
$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->displayName = (array_key_exists("namePerson",$response))?$response["namePerson"]:"";
$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->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->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->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->displayName = (array_key_exists("namePerson", $response)) ? $response["namePerson"] : "";
$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->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->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->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->birthYear = (array_key_exists("birthDate/birthDate",$response))?$response["birthDate/birthDate"]:"";
$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->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"];
}
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'];
$this->user->profile->birthDay = (int) $birthday_day;
@@ -140,15 +133,15 @@ class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model
$this->user->profile->birthYear = (int) $birthday_year;
}
if( ! $this->user->profile->displayName ){
$this->user->profile->displayName = trim( $this->user->profile->firstName . " " . $this->user->profile->lastName );
if (!$this->user->profile->displayName) {
$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";
}
if( $this->user->profile->gender == "m" ){
if ($this->user->profile->gender == "m") {
$this->user->profile->gender = "male";
}
@@ -156,24 +149,22 @@ class Hybrid_Provider_Model_OpenID extends Hybrid_Provider_Model
$this->setUserConnected();
// 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
$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 ( ! is_object( $this->user ) ){
throw new Exception( "User profile request failed! User is not connected to {$this->providerId} or his session has expired.", 6 );
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);
}
return $this->user->profile;
}
}

View File

@@ -1,16 +1,18 @@
<?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
*/
/**
* Hybrid_Providers_AOL provider adapter based on OpenID protocol
*
* 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/";
}

View File

@@ -1,9 +1,10 @@
<?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
*/
/**
* Hybrid_Providers_Facebook provider adapter based on OAuth2 protocol
@@ -12,64 +13,69 @@
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Facebook.html
*/
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";
class Hybrid_Providers_Facebook extends Hybrid_Provider_Model {
/**
* 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()
{
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 );
public $scope = "email, user_about_me, user_birthday, user_hometown, user_location, user_website, publish_actions, read_custom_friendlists";
/**
* 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/facebook.php";
}
if ( isset ( Hybrid_Auth::$config["proxy"] ) ) {
if (isset(Hybrid_Auth::$config["proxy"])) {
BaseFacebook::$CURL_OPTS[CURLOPT_PROXY] = Hybrid_Auth::$config["proxy"];
}
$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 ) );
$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));
if ( $this->token("access_token") ) {
$this->api->setAccessToken( $this->token("access_token") );
if ($this->token("access_token")) {
$this->api->setAccessToken($this->token("access_token"));
$this->api->setExtendedAccessToken();
$access_token = $this->api->getAccessToken();
if( $access_token ){
$this->token("access_token", $access_token );
$this->api->setAccessToken( $access_token );
if ($access_token) {
$this->token("access_token", $access_token);
$this->api->setAccessToken($access_token);
}
$this->api->setAccessToken( $this->token("access_token") );
$this->api->setAccessToken($this->token("access_token"));
}
$this->api->getUser();
}
/**
* begin login step
*
* simply call Facebook::require_login().
* {@inheritdoc}
*/
function loginBegin()
{
function loginBegin() {
$parameters = array("scope" => $this->scope, "redirect_uri" => $this->endpoint, "display" => "page");
$optionals = array("scope", "redirect_uri", "display", "auth_type");
foreach ($optionals as $parameter){
if( isset( $this->config[$parameter] ) && ! empty( $this->config[$parameter] ) ){
foreach ($optionals as $parameter) {
if (isset($this->config[$parameter]) && !empty($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($parameter == "auth_type"){
if ($parameter == "auth_type") {
$nonce = md5(uniqid(mt_rand(), true));
$parameters['auth_nonce'] = $nonce;
@@ -78,126 +84,127 @@ class Hybrid_Providers_Facebook extends Hybrid_Provider_Model
}
}
if( isset( $this->config[ 'force' ] ) && $this->config[ 'force' ] === true ){
$parameters[ 'auth_type' ] = 'reauthenticate';
$parameters[ 'auth_nonce' ] = md5( uniqid( mt_rand(), true ) );
if (isset($this->config['force']) && $this->config['force'] === true) {
$parameters['auth_type'] = 'reauthenticate';
$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
$url = $this->api->getLoginUrl( $parameters );
$url = $this->api->getLoginUrl($parameters);
// 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
if ( isset( $_REQUEST['error'] ) && $_REQUEST['error'] == "access_denied" ){
throw new Exception( "Authentication failed! The user denied your request.", 5 );
if (isset($_REQUEST['error']) && $_REQUEST['error'] == "access_denied") {
throw new Exception("Authentication failed! The user denied your request.", 5);
}
// in case we are using iOS/Facebook reverse authentication
if(isset($_REQUEST['access_token'])){
$this->token("access_token", $_REQUEST['access_token'] );
$this->api->setAccessToken( $this->token("access_token") );
if (isset($_REQUEST['access_token'])) {
$this->token("access_token", $_REQUEST['access_token']);
$this->api->setAccessToken($this->token("access_token"));
$this->api->setExtendedAccessToken();
$access_token = $this->api->getAccessToken();
if( $access_token ){
$this->token("access_token", $access_token );
$this->api->setAccessToken( $access_token );
if ($access_token) {
$this->token("access_token", $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(isset($_REQUEST['auth_nonce'])){
if (isset($_REQUEST['auth_nonce'])) {
$nonce = Hybrid_Auth::storage()->get('fb_auth_nonce');
//Delete the nonce
Hybrid_Auth::storage()->delete('fb_auth_nonce');
if($_REQUEST['auth_nonce'] != $nonce){
throw new Exception( "Authentication failed! Invalid nonce used for reauthentication.", 5 );
if ($_REQUEST['auth_nonce'] != $nonce) {
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
if ( ! $this->api->getUser() ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid user id.", 5 );
if (!$this->api->getUser()) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid user id.", 5);
}
// set user as logged in
$this->setUserConnected();
// 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();
parent::logout();
}
/**
* load the user profile from the IDp api client
* {@inheritdoc}
*/
function getUserProfile()
{
function getUserProfile() {
// request user profile from fb api
try{
$data = $this->api->api('/me');
}
catch( FacebookApiException $e ){
throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
try {
$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);
}
// if the provider identifier is not received, we assume the auth has failed
if ( ! isset( $data["id"] ) ){
throw new Exception( "User profile request failed! {$this->providerId} api returned an invalid response.", 6 );
if (!isset($data["id"])) {
throw new Exception("User profile request failed! {$this->providerId} api returned an invalid response: " . Hybrid_Logger::dumpData( $data ), 6);
}
# store the user profile.
$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->displayName = (array_key_exists('name',$data))?$data['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->identifier = (array_key_exists('id', $data)) ? $data['id'] : "";
$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->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->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->profileURL = (array_key_exists('link',$data))?$data['link']:"";
$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->language = (array_key_exists('locale',$data))?$data['locale']:"";
$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->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->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->webSiteURL = (array_key_exists('website', $data)) ? $data['website'] : "";
$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->description = (array_key_exists('about', $data)) ? $data['about'] : "";
$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->region = (array_key_exists("location", $data) && array_key_exists("name", $data['location'])) ? $data['location']["name"] : "";
if(!empty($this->user->profile->region )){
$regionArr = explode(',',$this->user->profile->region );
if(count($regionArr) > 1){
if (!empty($this->user->profile->region)) {
$regionArr = explode(',', $this->user->profile->region);
if (count($regionArr) > 1) {
$this->user->profile->city = trim($regionArr[0]);
$this->user->profile->country = trim($regionArr[1]);
}
}
if( array_key_exists('birthday',$data) ) {
list($birthday_month, $birthday_day, $birthday_year) = explode( "/", $data['birthday'] );
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;
@@ -211,38 +218,37 @@ class Hybrid_Providers_Facebook extends Hybrid_Provider_Model
* Attempt to retrieve the url to the cover image given the coverInfoURL
*
* @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 {
$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));
if(array_key_exists('cover', $coverOBJ)) {
if (array_key_exists('cover', $coverOBJ)) {
return $coverOBJ->cover->source;
}
}
} catch (Exception $e) { }
} catch (Exception $e) {
}
return "";
}
/**
* load the user contacts
* {@inheritdoc}
*/
function getUserContacts()
{
function getUserContacts() {
$apiCall = '?fields=link,name';
$returnedContacts = array();
$pagedList = false;
do {
try{
try {
$response = $this->api->api('/me/friends' . $apiCall);
}
catch( FacebookApiException $e ){
throw new Exception( 'User contacts request failed! {$this->providerId} returned an error: $e' );
} catch (FacebookApiException $e) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error {$e->getMessage()}", 0, $e);
}
// Prepare the next call if paging links have been returned
@@ -250,24 +256,22 @@ class Hybrid_Providers_Facebook extends Hybrid_Provider_Model
$pagedList = true;
$next_page = explode('friends', $response['paging']['next']);
$apiCall = $next_page[1];
}
else{
} else {
$pagedList = false;
}
// Add the new page contacts
$returnedContacts = array_merge($returnedContacts, $response['data']);
}
while ($pagedList == true);
} while ($pagedList == true);
$contacts = ARRAY();
$contacts = array();
foreach ($returnedContacts as $item) {
foreach( $returnedContacts as $item ){
$uc = new Hybrid_User_Contact();
$uc->identifier = (array_key_exists("id",$item))?$item["id"]:"";
$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->identifier = (array_key_exists("id", $item)) ? $item["id"] : "";
$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->photoURL = "https://graph.facebook.com/" . $uc->identifier . "/picture?width=150&height=150";
$contacts[] = $uc;
@@ -277,89 +281,84 @@ class Hybrid_Providers_Facebook extends Hybrid_Provider_Model
}
/**
* update user status
* Update user status
*
* @param mixed $status An array describing the status, or string
* @param string $pageid (optional) User page id
* @return array
* @throw Exception
*/
function setUserStatus( $status, $pageid = null )
{
if( !is_array( $status ) ){
$status = array( 'message' => $status );
function setUserStatus($status, $pageid = null) {
if (!is_array($status)) {
$status = array('message' => $status);
}
if( is_null( $pageid ) ){
if (is_null($pageid)) {
$pageid = 'me';
// if post on page, get access_token page
}else{
} else {
$access_token = null;
foreach( $this->getUserPages( true ) as $p ){
if( isset( $p[ 'id' ] ) && intval( $p['id'] ) == intval( $pageid ) ){
$access_token = $p[ 'access_token' ];
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!" );
if (is_null($access_token)) {
throw new Exception("Update user page failed, page not found or not writable!");
}
$status[ 'access_token' ] = $access_token;
$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" );
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;
}
/**
* get user status
* {@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" );
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;
}
/**
* get user pages
* {@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!" );
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" );
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' ] ) ){
if (!isset($pages['data'])) {
return array();
}
if( !$writableonly ){
return $pages[ 'data' ];
if (!$writableonly) {
return $pages['data'];
}
$wrpages = array();
foreach( $pages[ 'data' ] as $p ){
if( isset( $p[ 'perms' ] ) && in_array( 'CREATE_CONTENT', $p[ 'perms' ] ) ){
foreach ($pages['data'] as $p) {
if (isset($p['perms']) && in_array('CREATE_CONTENT', $p['perms'])) {
$wrpages[] = $p;
}
}
@@ -371,56 +370,54 @@ class Hybrid_Providers_Facebook extends Hybrid_Provider_Model
* 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{
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" );
} catch (FacebookApiException $e) {
throw new Exception("User activity stream request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if( ! $response || ! count( $response['data'] ) ){
return ARRAY();
if (!$response || !count($response['data'])) {
return array();
}
$activities = ARRAY();
$activities = array();
foreach( $response['data'] as $item ){
if( $stream == "me" && $item["from"]["id"] != $this->api->getUser() ){
foreach ($response['data'] as $item) {
if ($stream == "me" && $item["from"]["id"] != $this->api->getUser()) {
continue;
}
$ua = new Hybrid_User_Activity();
$ua->id = (array_key_exists("id",$item))?$item["id"]:"";
$ua->date = (array_key_exists("created_time",$item))?strtotime($item["created_time"]):"";
$ua->id = (array_key_exists("id", $item)) ? $item["id"] : "";
$ua->date = (array_key_exists("created_time", $item)) ? strtotime($item["created_time"]) : "";
if( $item["type"] == "video" ){
$ua->text = (array_key_exists("link",$item))?$item["link"]:"";
if ($item["type"] == "video") {
$ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
}
if( $item["type"] == "link" ){
$ua->text = (array_key_exists("link",$item))?$item["link"]:"";
if ($item["type"] == "link") {
$ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
}
if( empty( $ua->text ) && isset( $item["story"] ) ){
$ua->text = (array_key_exists("link",$item))?$item["link"]:"";
if (empty($ua->text) && isset($item["story"])) {
$ua->text = (array_key_exists("link", $item)) ? $item["link"] : "";
}
if( empty( $ua->text ) && isset( $item["message"] ) ){
$ua->text = (array_key_exists("message",$item))?$item["message"]:"";
if (empty($ua->text) && isset($item["message"])) {
$ua->text = (array_key_exists("message", $item)) ? $item["message"] : "";
}
if( ! empty( $ua->text ) ){
$ua->user->identifier = (array_key_exists("id",$item["from"]))?$item["from"]["id"]:"";
$ua->user->displayName = (array_key_exists("name",$item["from"]))?$item["from"]["name"]:"";
if (!empty($ua->text)) {
$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->profileURL = "https://www.facebook.com/profile.php?id=" . $ua->user->identifier;
$ua->user->photoURL = "https://graph.facebook.com/" . $ua->user->identifier . "/picture?type=square";
@@ -430,4 +427,5 @@ class Hybrid_Providers_Facebook extends Hybrid_Provider_Model
return $activities;
}
}

View File

@@ -1,9 +1,10 @@
<?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-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_Foursquare provider adapter based on OAuth2 protocol
@@ -24,14 +25,15 @@
* - list of valid photo_size values is described here https://developer.foursquare.com/docs/responses/photo.html
* - 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();
// Provider apis end-points
@@ -43,26 +45,22 @@ class Hybrid_Providers_Foursquare extends Hybrid_Provider_Model_OAuth2
}
/**
* load the user profile from the IDp api client
* {@inheritdoc}
*/
function getUserProfile()
{
$data = $this->api->api( "users/self", "GET", array( "v" => "20120610" ) );
function getUserProfile() {
$data = $this->api->api("users/self", "GET", Hybrid_Providers_Foursquare::$apiVersion);
if ( ! isset( $data->response->user->id ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 );
if (!isset($data->response->user->id)) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response:" . Hybrid_Logger::dumpData( $data ), 6);
}
$data = $data->response->user;
// get profile photo size from config
$photoSize = ((isset($this->config["params"]["photo_size"]))?($this->config["params"]["photo_size"]):("100x100"));
$this->user->profile->identifier = $data->id;
$this->user->profile->firstName = $data->firstName;
$this->user->profile->lastName = $data->lastName;
$this->user->profile->displayName = trim( $this->user->profile->firstName . " " . $this->user->profile->lastName );
$this->user->profile->photoURL = $data->photo->prefix.$photoSize.$data->photo->suffix;
$this->user->profile->displayName = $this->buildDisplayName($this->user->profile->firstName, $this->user->profile->lastName);
$this->user->profile->photoURL = $this->buildPhotoURL($data->photo->prefix, $data->photo->suffix);
$this->user->profile->profileURL = "https://www.foursquare.com/user/" . $data->id;
$this->user->profile->gender = $data->gender;
$this->user->profile->city = $data->homeCity;
@@ -71,4 +69,53 @@ class Hybrid_Providers_Foursquare extends Hybrid_Provider_Model_OAuth2
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

@@ -60,9 +60,9 @@ class Hybrid_Providers_GitHub extends Hybrid_Provider_Model_OAuth2
if (is_array($emails)) {
foreach ($emails as $email) {
if ($email instanceof stdClass
&& property_exists('primary', $email)
&& property_exists($email, 'primary')
&& true === $email->primary
&& property_exists('email', $email)
&& property_exists($email, 'email')
) {
$this->user->profile->email = $email->email;
break;
@@ -77,4 +77,43 @@ class Hybrid_Providers_GitHub extends Hybrid_Provider_Model_OAuth2
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,28 +1,30 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/* !
* HybridAuth
* 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
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Google.html
*/
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)
class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2 {
// 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/";
/**
* IDp wrappers initializer
* {@inheritdoc}
*/
function initialize()
{
function initialize() {
parent::initialize();
// Provider api end-points
@@ -30,74 +32,75 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2
$this->api->token_url = "https://accounts.google.com/o/oauth2/token";
$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
// 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'];
}
}
/**
* begin login step
* {@inheritdoc}
*/
function loginBegin()
{
function loginBegin() {
$parameters = array("scope" => $this->scope, "access_type" => "offline");
$optionals = array("scope", "access_type", "redirect_uri", "approval_prompt", "hd", "state");
foreach ($optionals as $parameter){
if( isset( $this->config[$parameter] ) && ! empty( $this->config[$parameter] ) ){
foreach ($optionals as $parameter) {
if (isset($this->config[$parameter]) && !empty($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"];
}
}
if( isset( $this->config[ 'force' ] ) && $this->config[ 'force' ] === true ){
$parameters[ 'approval_prompt' ] = 'force';
if (isset($this->config['force']) && $this->config['force'] === true) {
$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
$this->refreshToken();
// ask google api for user infos
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();
} 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();
}
$response = $this->api->api( "https://www.googleapis.com/plus/v1/people/me" );
if ( ! isset( $response->id ) || isset( $response->error ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 );
$response = $this->api->api("https://www.googleapis.com/plus/v1/people/me");
if (!isset($response->id) || isset($response->error)) {
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->firstName = (property_exists($response,'name'))?$response->name->givenName:"";
$this->user->profile->lastName = (property_exists($response,'name'))?$response->name->familyName:"";
$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->profileURL = (property_exists($response,'url'))?$response->url:"";
$this->user->profile->description = (property_exists($response,'aboutMe'))?$response->aboutMe:"";
$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->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->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->lastName = (property_exists($response, 'name')) ? $response->name->familyName : "";
$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->profileURL = (property_exists($response, 'url')) ? $response->url : "";
$this->user->profile->description = (property_exists($response, 'aboutMe')) ? $response->aboutMe : "";
$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->email = (property_exists($response, 'email')) ? $response->email : ((property_exists($verified, 'email')) ? $verified->email : "");
$this->user->profile->emailVerified = (property_exists($verified, 'email')) ? $verified->email : "";
if (property_exists($response, 'emails')) {
if (count($response->emails) == 1) {
$this->user->profile->email = $response->emails[0]->value;
@@ -109,23 +112,35 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2
}
}
}
if (property_exists($verified, 'emails')) {
if (count($verified->emails) == 1) {
$this->user->profile->emailVerified = $verified->emails[0]->value;
} else {
foreach ($verified->emails as $email) {
if ($email->type == 'account') {
$this->user->profile->emailVerified = $email->value;
break;
}
$this->user->profile->phone = (property_exists($response,'phone'))?$response->phone:"";
$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->phone = (property_exists($response, 'phone')) ? $response->phone : "";
$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){
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')){
} else {
if (property_exists($c, 'value')) {
$this->user->profile->address = $c->value;
$this->user->profile->city = $c->value;
}
@@ -135,77 +150,78 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2
// google API returns multiple urls, but a "website" only if it is verified
// see http://support.google.com/plus/answer/1713826?hl=en
if( property_exists($response,'urls') ){
foreach($response->urls as $u){
if(property_exists($u, 'primary') && $u->primary == true) $this->user->profile->webSiteURL = $u->value;
if (property_exists($response, 'urls')) {
foreach ($response->urls as $u) {
if (property_exists($u, 'primary') && $u->primary == true)
$this->user->profile->webSiteURL = $u->value;
}
} else {
$this->user->profile->webSiteURL = '';
}
// google API returns age ranges or min. age only (with plus.login scope)
if( property_exists($response,'ageRange') ){
if( property_exists($response->ageRange,'min') && property_exists($response->ageRange,'max') ){
$this->user->profile->age = $response->ageRange->min.' - '.$response->ageRange->max;
if (property_exists($response, 'ageRange')) {
if (property_exists($response->ageRange, 'min') && property_exists($response->ageRange, 'max')) {
$this->user->profile->age = $response->ageRange->min . ' - ' . $response->ageRange->max;
} else {
$this->user->profile->age = '> '.$response->ageRange->min;
$this->user->profile->age = '> ' . $response->ageRange->min;
}
} else {
$this->user->profile->age = '';
}
// google API returns birthdays only if a user set 'show in my account'
if( property_exists($response,'birthday') ){
list($birthday_year, $birthday_month, $birthday_day) = explode( '-', $response->birthday );
if (property_exists($response, 'birthday')) {
list($birthday_year, $birthday_month, $birthday_day) = explode('-', $response->birthday);
$this->user->profile->birthDay = (int) $birthday_day;
$this->user->profile->birthMonth = (int) $birthday_month;
$this->user->profile->birthYear = (int) $birthday_year;
} 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;
}
/**
* load the user (Gmail and google plus) contacts
* ..toComplete
* {@inheritdoc}
*/
function getUserContacts()
{
function getUserContacts() {
// refresh tokens if needed
$this->refreshToken();
$contacts = array();
if( ! isset( $this->config['contacts_param'] ) ){
$this->config['contacts_param'] = array( "max-results" => 500 );
if (!isset($this->config['contacts_param'])) {
$this->config['contacts_param'] = array("max-results" => 500);
}
// Google Gmail and Android contacts
if (strpos($this->scope, '/m8/feeds/') !== false) {
$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'] ) ) );
$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'])));
if( ! $response ){
return ARRAY();
if (!$response) {
return array();
}
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->email = isset($entry->{'gd$email'}[0]->address) ? (string) $entry->{'gd$email'}[0]->address : '';
$uc->displayName = isset($entry->title->{'$t'}) ? (string) $entry->title->{'$t'} : '';
$uc->identifier = ($uc->email!='')?$uc->email:'';
$uc->identifier = ($uc->email != '') ? $uc->email : '';
$uc->description = '';
if( property_exists($entry,'link') ){
if (property_exists($entry, 'link')) {
/**
* sign links with access_token
*/
if(is_array($entry->link)){
foreach($entry->link as $l){
if( property_exists($l,'gd$etag') && $l->type=="image/*"){
if (is_array($entry->link)) {
foreach ($entry->link as $l) {
if (property_exists($l, 'gd$etag') && $l->type == "image/*") {
$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));
}
}
@@ -213,10 +229,11 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2
} else {
$uc->profileURL = '';
}
if( property_exists($response,'website') ){
if(is_array($response->website)){
foreach($response->website as $w){
if($w->primary == true) $uc->webSiteURL = $w->value;
if (property_exists($response, 'website')) {
if (is_array($response->website)) {
foreach ($response->website as $w) {
if ($w->primary == true)
$uc->webSiteURL = $w->value;
}
} else {
$uc->webSiteURL = $response->website->value;
@@ -233,48 +250,48 @@ class Hybrid_Providers_Google extends Hybrid_Provider_Model_OAuth2
// Google social contacts
if (strpos($this->scope, '/auth/plus.login') !== false) {
$response = $this->api->api( "https://www.googleapis.com/plus/v1/people/me/people/visible?"
. http_build_query( $this->config['contacts_param'] ) );
$response = $this->api->api("https://www.googleapis.com/plus/v1/people/me/people/visible?"
. http_build_query($this->config['contacts_param']));
if( ! $response ){
return ARRAY();
if (!$response) {
return array();
}
foreach( $response->items as $idx => $item ){
foreach ($response->items as $idx => $item) {
$uc = new Hybrid_User_Contact();
$uc->email = (property_exists($item,'email'))?$item->email:'';
$uc->displayName = (property_exists($item,'displayName'))?$item->displayName:'';
$uc->identifier = (property_exists($item,'id'))?$item->id:'';
$uc->email = (property_exists($item, 'email')) ? $item->email : '';
$uc->displayName = (property_exists($item, 'displayName')) ? $item->displayName : '';
$uc->identifier = (property_exists($item, 'id')) ? $item->id : '';
$uc->description = (property_exists($item,'objectType'))?$item->objectType:'';
$uc->photoURL = (property_exists($item,'image'))?((property_exists($item->image,'url'))?$item->image->url:''):'';
$uc->profileURL = (property_exists($item,'url'))?$item->url:'';
$uc->description = (property_exists($item, 'objectType')) ? $item->objectType : '';
$uc->photoURL = (property_exists($item, 'image')) ? ((property_exists($item->image, 'url')) ? $item->image->url : '') : '';
$uc->profileURL = (property_exists($item, 'url')) ? $item->url : '';
$uc->webSiteURL = '';
$contacts[] = $uc;
}
}
return $contacts;
}
/**
* Add to the $url new parameters
* @param string $url
* @param array $params
* Add query parameters to the $url
*
* @param string $url URL
* @param array $params Parameters to add
* @return string
*/
function addUrlParam($url, array $params)
{
function addUrlParam($url, array $params) {
$query = parse_url($url, PHP_URL_QUERY);
// Returns the URL string with new parameters
if( $query ) {
$url .= '&' . http_build_query( $params );
if ($query) {
$url .= '&' . http_build_query($params);
} else {
$url .= '?' . http_build_query( $params );
$url .= '?' . http_build_query($params);
}
return $url;
}
}

View File

@@ -1,9 +1,10 @@
<?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-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_LinkedIn provider adapter based on OAuth1 protocol
@@ -12,102 +13,106 @@
*
* 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()
{
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 );
public $api;
/**
* {@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"] . "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" ) ){
$this->api->setTokenAccess( $this->token( "access_token_linkedin" ) );
if ($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
$response = $this->api->retrieveTokenRequest();
if( isset( $response['success'] ) && $response['success'] === TRUE ){
$this->token( "oauth_token", $response['linkedin']['oauth_token'] );
$this->token( "oauth_token_secret", $response['linkedin']['oauth_token_secret'] );
if (isset($response['success']) && $response['success'] === true) {
$this->token("oauth_token", $response['linkedin']['oauth_token']);
$this->token("oauth_token_secret", $response['linkedin']['oauth_token_secret']);
# redirect user to LinkedIn authorisation web page
Hybrid_Auth::redirect( LINKEDIN::_URL_AUTH . $response['linkedin']['oauth_token'] );
}
else{
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid Token.", 5 );
Hybrid_Auth::redirect(LINKEDIN::_URL_AUTH . $response['linkedin']['oauth_token']);
} else {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid Token in response: " . Hybrid_Logger::dumpData( $response ), 5);
}
}
/**
* finish login step
* {@inheritdoc}
*/
function loginFinish()
{
$oauth_token = $_REQUEST['oauth_token'];
$oauth_verifier = $_REQUEST['oauth_verifier'];
if ( ! $oauth_verifier ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid Token.", 5 );
function loginFinish() {
// in case we get oauth_problem=user_refused
if (isset($_REQUEST['oauth_problem']) && $_REQUEST['oauth_problem'] == "user_refused") {
throw new Exception("Authentication failed! The user denied your request.", 5);
}
$response = $this->api->retrieveTokenAccess( $oauth_token, $this->token( "oauth_token_secret" ), $oauth_verifier );
$oauth_token = isset($_REQUEST['oauth_token']) ? $_REQUEST['oauth_token'] : null;
$oauth_verifier = isset($_REQUEST['oauth_verifier']) ? $_REQUEST['oauth_verifier'] : null;
if( isset( $response['success'] ) && $response['success'] === TRUE ){
$this->deleteToken( "oauth_token" );
$this->deleteToken( "oauth_token_secret" );
if (!$oauth_token || !$oauth_verifier) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid Token.", 5);
}
$this->token( "access_token_linkedin", $response['linkedin'] );
$this->token( "access_token" , $response['linkedin']['oauth_token'] );
$this->token( "access_token_secret" , $response['linkedin']['oauth_token_secret'] );
$response = $this->api->retrieveTokenAccess($oauth_token, $this->token("oauth_token_secret"), $oauth_verifier);
if (isset($response['success']) && $response['success'] === true) {
$this->deleteToken("oauth_token");
$this->deleteToken("oauth_token_secret");
$this->token("access_token_linkedin", $response['linkedin']);
$this->token("access_token", $response['linkedin']['oauth_token']);
$this->token("access_token_secret", $response['linkedin']['oauth_token_secret']);
// set user as logged in
$this->setUserConnected();
}
else{
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid Token.", 5 );
} else {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid Token in response: " . Hybrid_Logger::dumpData( $response ), 5);
}
}
/**
* load the user profile from the IDp api client
* {@inheritdoc}
*/
function getUserProfile()
{
try{
function getUserProfile() {
try {
// 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)');
}
catch( LinkedInException $e ){
throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
} catch (LinkedInException $e) {
throw new Exception("User profile request failed! {$this->providerId} returned an error: {$e->getMessage()}", 6, $e);
}
if( isset( $response['success'] ) && $response['success'] === TRUE ){
$data = @ new SimpleXMLElement( $response['linkedin'] );
if (isset($response['success']) && $response['success'] === true) {
$data = @ new SimpleXMLElement($response['linkedin']);
if ( ! is_object( $data ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid xml data.", 6 );
if (!is_object($data)) {
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->firstName = (string) $data->{'first-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->emailVerified = (string) $data->{'email-address'};
@@ -116,47 +121,43 @@ class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model
$this->user->profile->profileURL = (string) $data->{'public-profile-url'};
$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'};
}
else{
} else {
$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->birthMonth = (string) $data->{'date-of-birth'}->month;
$this->user->profile->birthYear = (string) $data->{'date-of-birth'}->year;
}
return $this->user->profile;
}
else{
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 );
} else {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData( $response ), 6);
}
}
/**
* load the user contacts
* {@inheritdoc}
*/
function getUserContacts()
{
try{
function getUserContacts() {
try {
$response = $this->api->profile('~/connections:(id,first-name,last-name,picture-url,public-profile-url,summary)');
}
catch( LinkedInException $e ){
throw new Exception( "User contacts request failed! {$this->providerId} returned an error: $e" );
} catch (LinkedInException $e) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if( ! $response || ! $response['success'] ){
return ARRAY();
if (!$response || !$response['success']) {
return array();
}
$connections = new SimpleXMLElement( $response['linkedin'] );
$connections = new SimpleXMLElement($response['linkedin']);
$contacts = ARRAY();
$contacts = array();
foreach( $connections->person as $connection ) {
foreach ($connections->person as $connection) {
$uc = new Hybrid_User_Contact();
$uc->identifier = (string) $connection->id;
@@ -172,34 +173,36 @@ class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model
}
/**
* update user status
* {@inheritdoc}
*/
function setUserStatus( $status )
{
function setUserStatus($status) {
$parameters = array();
$private = true; // share with your connections only
if( is_array( $status ) ){
if( isset( $status[0] ) && ! empty( $status[0] ) ) $parameters["title"] = $status[0]; // post title
if( isset( $status[1] ) && ! empty( $status[1] ) ) $parameters["comment"] = $status[1]; // post comment
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
if (is_array($status)) {
if (isset($status[0]) && !empty($status[0]))
$parameters["title"] = $status[0]; // post title
if (isset($status[1]) && !empty($status[1]))
$parameters["comment"] = $status[1]; // post comment
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;
}
try{
$response = $this->api->share( 'new', $parameters, $private );
}
catch( LinkedInException $e ){
throw new Exception( "Update user status update failed! {$this->providerId} returned an error: $e" );
try {
$response = $this->api->share('new', $parameters, $private);
} catch (LinkedInException $e) {
throw new Exception("Update user status update failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if ( ! $response || ! $response['success'] )
{
throw new Exception( "Update user status update failed! {$this->providerId} returned an error." );
if (!$response || !$response['success']) {
throw new Exception("Update user status update failed! {$this->providerId} returned an error in response: " . Hybrid_Logger::dumpData( $response ));
}
return $response;
@@ -209,30 +212,28 @@ class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model
* 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->updates( '?type=SHAR&scope=self&count=25' );
function getUserActivity($stream) {
try {
if ($stream == "me") {
$response = $this->api->updates('?type=SHAR&scope=self&count=25');
} else {
$response = $this->api->updates('?type=SHAR&count=25');
}
else{
$response = $this->api->updates( '?type=SHAR&count=25' );
}
}
catch( LinkedInException $e ){
throw new Exception( "User activity stream request failed! {$this->providerId} returned an error: $e" );
} catch (LinkedInException $e) {
throw new Exception("User activity stream request failed! {$this->providerId} returned an error: {$e->getMessage()}", 0, $e);
}
if( ! $response || ! $response['success'] ){
return ARRAY();
if (!$response || !$response['success']) {
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;
$share = $update->{'update-content'}->person->{'current-share'};
@@ -245,11 +246,12 @@ class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model
$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->photoURL = null;
$activities[] = $ua;
}
return $activities;
}
}

View File

@@ -1,9 +1,10 @@
<?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
@@ -17,17 +18,17 @@
/**
* Hybrid_Providers_Live - Windows Live provider adapter based on OAuth2 protocol
*/
class Hybrid_Providers_Live extends Hybrid_Provider_Model_OAuth2
{
// default permissions
public $scope = "wl.basic wl.contacts_emails wl.emails wl.signin wl.share wl.birthday";
class Hybrid_Providers_Live extends Hybrid_Provider_Model_OAuth2 {
/**
* IDp wrappers initializer
* {@inheritdoc}
*/
function initialize()
{
public $scope = "wl.basic wl.contacts_emails wl.emails wl.signin wl.share wl.birthday";
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
// Provider api end-points
@@ -39,68 +40,63 @@ class Hybrid_Providers_Live extends Hybrid_Provider_Model_OAuth2
}
/**
* grab the user profile from the api client
* {@inheritdoc}
*/
function getUserProfile()
{
$data = $this->api->get( "me" );
function getUserProfile() {
$data = $this->api->get("me");
if ( ! isset( $data->id ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 );
if (!isset($data->id)) {
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->firstName = (property_exists($data,'first_name'))?$data->first_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->gender = (property_exists($data,'gender'))?$data->gender:"";
$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->lastName = (property_exists($data, 'last_name')) ? $data->last_name : "";
$this->user->profile->displayName = (property_exists($data, 'name')) ? trim($data->name) : "";
$this->user->profile->gender = (property_exists($data, 'gender')) ? $data->gender : "";
//wl.basic
$this->user->profile->profileURL = (property_exists($data,'link'))?$data->link:"";
$this->user->profile->profileURL = (property_exists($data, 'link')) ? $data->link : "";
//wl.emails
$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->email = (property_exists($data, 'emails')) ? $data->emails->account : "";
$this->user->profile->emailVerified = (property_exists($data, 'emails')) ? $data->emails->account : "";
//wl.birthday
$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->birthYear = (property_exists($data,'birth_year'))?$data->birth_year:"";
$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->birthYear = (property_exists($data, 'birth_year')) ? $data->birth_year : "";
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 :/) */
function getUserContacts()
{
$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 ($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();
}
$contacts = array();
foreach( $response->data as $item ) {
foreach ($response->data as $item) {
$uc = new Hybrid_User_Contact();
$uc->identifier = (property_exists($item,'id'))?$item->id:"";
$uc->displayName = (property_exists($item,'name'))?$item->name:"";
$uc->email = (property_exists($item,'emails'))?$item->emails->preferred:"";
$uc->identifier = (property_exists($item, 'id')) ? $item->id : "";
$uc->displayName = (property_exists($item, 'name')) ? $item->name : "";
$uc->email = (property_exists($item, 'emails')) ? $item->emails->preferred : "";
$contacts[] = $uc;
}
return $contacts;
}
}

View File

@@ -1,15 +1,16 @@
<?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
*/
/**
* Hybrid_Providers_OpenID provider adapter for any idp openid based
*
* 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,20 +1,20 @@
<?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
*/
/**
* Hybrid_Providers_Twitter provider adapter based on OAuth1 protocol
*/
class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1
{
/**
* IDp wrappers initializer
* Hybrid_Providers_Twitter provider adapter based on OAuth1 protocol
*/
function initialize()
{
class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1 {
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
// Provider api end-points
@@ -23,11 +23,11 @@ class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1
$this->api->request_token_url = "https://api.twitter.com/oauth/request_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']}/";
}
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";
}
@@ -35,70 +35,68 @@ class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1
}
/**
* begin login step
* {@inheritdoc}
*/
function loginBegin()
{
function loginBegin() {
// Initiate the Reverse Auth flow; cf. https://dev.twitter.com/docs/ios/using-reverse-auth
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' ) );
if ( $this->api->http_code != 200 ){
throw new Exception( "Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ), 5 );
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'));
if ($this->api->http_code != 200) {
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);
header( "Content-Type: application/json", true, 200 ) ;
header("Content-Type: application/json", true, 200);
echo $response;
die();
}
$tokens = $this->api->requestToken( $this->endpoint );
$tokens = $this->api->requestToken($this->endpoint);
// request tokens as received from provider
$this->request_tokens_raw = $tokens;
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ), 5 );
if ($this->api->http_code != 200) {
throw new Exception("Authentication failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code), 5);
}
if ( ! isset( $tokens["oauth_token"] ) ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid oauth token.", 5 );
if (!isset($tokens["oauth_token"])) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid oauth token.", 5);
}
$this->token( "request_token" , $tokens["oauth_token"] );
$this->token( "request_token_secret", $tokens["oauth_token_secret"] );
$this->token("request_token", $tokens["oauth_token"]);
$this->token("request_token_secret", $tokens["oauth_token_secret"]);
// 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 ) ){
Hybrid_Auth::redirect( $this->api->authorizeUrl( $tokens, array( 'force_login' => 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)));
}
// 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
if(isset($_REQUEST['oauth_token_secret'])){
if (isset($_REQUEST['oauth_token_secret'])) {
$tokens = $_REQUEST;
$this->access_tokens_raw = $tokens;
// we should have an access_token unless something has gone wrong
if ( ! isset( $tokens["oauth_token"] ) ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid access token.", 5 );
if (!isset($tokens["oauth_token"])) {
throw new Exception("Authentication failed! {$this->providerId} returned an invalid access token.", 5);
}
// Get rid of tokens we don't need
$this->deleteToken( "request_token" );
$this->deleteToken( "request_token_secret" );
$this->deleteToken("request_token");
$this->deleteToken("request_token_secret");
// Store access_token and secret for later use
$this->token( "access_token" , $tokens['oauth_token'] );
$this->token( "access_token_secret" , $tokens['oauth_token_secret'] );
$this->token("access_token", $tokens['oauth_token']);
$this->token("access_token_secret", $tokens['oauth_token_secret']);
// set user as logged in to the current provider
$this->setUserConnected();
@@ -107,76 +105,75 @@ class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1
parent::loginFinish();
}
/**
* load the user profile from the IDp api client
* {@inheritdoc}
*/
function getUserProfile()
{
$response = $this->api->get( 'account/verify_credentials.json' );
function getUserProfile() {
$includeEmail = isset($this->config['includeEmail']) ? (bool) $this->config['includeEmail'] : false;
$response = $this->api->get('account/verify_credentials.json'. ($includeEmail ? '?include_email=true' : ''));
// check the last HTTP status code returned
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 );
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);
}
if ( ! is_object( $response ) || ! isset( $response->id ) ){
throw new Exception( "User profile request failed! {$this->providerId} api returned an invalid response.", 6 );
if (!is_object($response) || !isset($response->id)) {
throw new Exception("User profile request failed! {$this->providerId} api returned an invalid response: " . Hybrid_Logger::dumpData( $response ), 6);
}
# store the user profile.
$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->description = (property_exists($response,'description'))?$response->description:"";
$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->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->region = (property_exists($response,'location'))?$response->location:"";
$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->description = (property_exists($response, 'description')) ? $response->description : "";
$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->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->region = (property_exists($response, 'location')) ? $response->location : "";
if($includeEmail) $this->user->profile->email = (property_exists($response, 'email')) ? $response->email : "";
return $this->user->profile;
}
/**
* load the user contacts
* {@inheritdoc}
*/
function getUserContacts()
{
$parameters = array( 'cursor' => '-1' );
$response = $this->api->get( 'friends/ids.json', $parameters );
function getUserContacts() {
$parameters = array('cursor' => '-1');
$response = $this->api->get('friends/ids.json', $parameters);
// check the last HTTP status code returned
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 ($this->api->http_code != 200) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
}
if( ! $response || ! count( $response->ids ) ){
return ARRAY();
if (!$response || !count($response->ids)) {
return array();
}
// 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 ){
$parameters = array( 'user_id' => implode( ",", $chunk ) );
$response = $this->api->get( 'users/lookup.json', $parameters );
foreach ($contactsids as $chunk) {
$parameters = array('user_id' => implode(",", $chunk));
$response = $this->api->get('users/lookup.json', $parameters);
// check the last HTTP status code returned
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 ($this->api->http_code != 200) {
throw new Exception("User contacts request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus($this->api->http_code));
}
if( $response && count( $response ) ){
foreach( $response as $item ){
if ($response && count($response)) {
foreach ($response as $item) {
$uc = new Hybrid_User_Contact();
$uc->identifier = (property_exists($item,'id'))?$item->id:"";
$uc->displayName = (property_exists($item,'name'))?$item->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->description = (property_exists($item,'description'))?$item->description:"";
$uc->identifier = (property_exists($item, 'id')) ? $item->id : "";
$uc->displayName = (property_exists($item, 'name')) ? $item->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->description = (property_exists($item, 'description')) ? $item->description : "";
$contacts[] = $uc;
}
@@ -187,84 +184,80 @@ class Hybrid_Providers_Twitter extends Hybrid_Provider_Model_OAuth1
}
/**
* update user status
* {@inheritdoc}
*/
function setUserStatus( $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 ) );
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 ) );
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 )
{
$info = $this->api->get( 'statuses/show.json?id=' . $tweetid . '&include_entities=true' );
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 ) );
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));
}
return $info;
}
/**
* 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' );
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 ($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();
if (!$response) {
return array();
}
$activities = ARRAY();
$activities = array();
foreach( $response as $item ){
foreach ($response as $item) {
$ua = new Hybrid_User_Activity();
$ua->id = (property_exists($item,'id'))?$item->id:"";
$ua->date = (property_exists($item,'created_at'))?strtotime($item->created_at):"";
$ua->text = (property_exists($item,'text'))?$item->text:"";
$ua->id = (property_exists($item, 'id')) ? $item->id : "";
$ua->date = (property_exists($item, 'created_at')) ? strtotime($item->created_at) : "";
$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;
}
return $activities;
}
}

View File

@@ -1,9 +1,10 @@
<?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
@@ -17,10 +18,12 @@
/**
* Hybrid_Providers_Yahoo - Yahoo provider adapter based on OAuth1 protocol
*/
class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth1
{
function initialize()
{
class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth1 {
/**
* {@inheritdoc}
*/
function initialize() {
parent::initialize();
// Provider api end-points
@@ -30,41 +33,43 @@ class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth1
$this->api->access_token_url = 'https://api.login.yahoo.com/oauth/v2/get_token';
}
function getUserProfile()
{
/**
* {@inheritdoc}
*/
function getUserProfile() {
$userId = $this->getCurrentUserId();
$parameters = array();
$parameters['format'] = 'json';
$response = $this->api->get( 'user/' . $userId . '/profile', $parameters );
$response = $this->api->get('user/' . $userId . '/profile', $parameters);
if ( ! isset( $response->profile ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 );
if (!isset($response->profile)) {
throw new Exception("User profile request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData( $response ), 6);
}
$data = $response->profile;
$this->user->profile->identifier = (property_exists($data,'guid'))?$data->guid:"";
$this->user->profile->firstName = (property_exists($data,'givenName'))?$data->givenName:"";
$this->user->profile->lastName = (property_exists($data,'familyName'))?$data->familyName:"";
$this->user->profile->displayName = (property_exists($data,'nickname'))?trim( $data->nickname ):"";
$this->user->profile->profileURL = (property_exists($data,'profileUrl'))?$data->profileUrl:"";
$this->user->profile->gender = (property_exists($data,'gender'))?$data->gender:"";
$this->user->profile->identifier = (property_exists($data, 'guid')) ? $data->guid : "";
$this->user->profile->firstName = (property_exists($data, 'givenName')) ? $data->givenName : "";
$this->user->profile->lastName = (property_exists($data, 'familyName')) ? $data->familyName : "";
$this->user->profile->displayName = (property_exists($data, 'nickname')) ? trim($data->nickname) : "";
$this->user->profile->profileURL = (property_exists($data, 'profileUrl')) ? $data->profileUrl : "";
$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";
}
if( $this->user->profile->gender == "M" ){
if ($this->user->profile->gender == "M") {
$this->user->profile->gender = "male";
}
if( isset($data->emails) ){
if (isset($data->emails)) {
$email = "";
foreach( $data->emails as $v ){
if( isset($v->primary) && $v->primary ) {
$email = (property_exists($v,'handle'))?$v->handle:"";
foreach ($data->emails as $v) {
if (isset($v->primary) && $v->primary) {
$email = (property_exists($v, 'handle')) ? $v->handle : "";
break;
}
@@ -74,20 +79,19 @@ class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth1
$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->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->language = (property_exists($data,'lang'))?$data->lang:"";
$this->user->profile->address = (property_exists($data, 'location')) ? $data->location : "";
$this->user->profile->language = (property_exists($data, 'lang')) ? $data->lang : "";
return $this->user->profile;
}
/**
* load the user contacts
* {@inheritdoc}
*/
function getUserContacts()
{
function getUserContacts() {
$userId = $this->getCurrentUserId();
$parameters = array();
@@ -96,25 +100,23 @@ class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth1
$response = $this->api->get('user/' . $userId . '/contacts', $parameters);
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 ($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->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();
}
$contacts = array();
foreach( $response->contacts->contact as $item ) {
foreach ($response->contacts->contact as $item) {
$uc = new Hybrid_User_Contact();
$uc->identifier = $this->selectGUID( $item );
$uc->email = $this->selectEmail( $item->fields );
$uc->displayName = $this->selectName( $item->fields );
$uc->photoURL = $this->selectPhoto( $item->fields );
$uc->identifier = $this->selectGUID($item);
$uc->email = $this->selectEmail($item->fields);
$uc->displayName = $this->selectName($item->fields);
$uc->photoURL = $this->selectPhoto($item->fields);
$contacts[] = $uc;
}
@@ -123,10 +125,9 @@ class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth1
}
/**
* return the user activity stream
* {@inheritdoc}
*/
function getUserActivity( $stream )
{
function getUserActivity($stream) {
$userId = $this->getCurrentUserId();
$parameters = array();
@@ -135,34 +136,33 @@ class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth1
$response = $this->api->get('user/' . $userId . '/updates', $parameters);
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 ) );
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));
}
$activities = array();
foreach( $response->updates as $item ){
foreach ($response->updates as $item) {
$ua = new Hybrid_User_Activity();
$ua->id = (property_exists($item,'collectionID'))?$item->collectionID:"";
$ua->date = (property_exists($item,'lastUpdated'))?$item->lastUpdated:"";
$ua->text = (property_exists($item,'loc_longForm'))?$item->loc_longForm:"";
$ua->id = (property_exists($item, 'collectionID')) ? $item->collectionID : "";
$ua->date = (property_exists($item, 'lastUpdated')) ? $item->lastUpdated : "";
$ua->text = (property_exists($item, 'loc_longForm')) ? $item->loc_longForm : "";
$ua->user->identifier = (property_exists($item,'profile_guid'))?$item->profile_guid:"";
$ua->user->displayName = (property_exists($item,'profile_nickname'))?$item->profile_nickname:"";
$ua->user->profileURL = (property_exists($item,'profile_profileUrl'))?$item->profile_profileUrl:"";
$ua->user->photoURL = (property_exists($item,'profile_displayImage'))?$item->profile_displayImage:"";
$ua->user->identifier = (property_exists($item, 'profile_guid')) ? $item->profile_guid : "";
$ua->user->displayName = (property_exists($item, 'profile_nickname')) ? $item->profile_nickname : "";
$ua->user->profileURL = (property_exists($item, 'profile_profileUrl')) ? $item->profile_profileUrl : "";
$ua->user->photoURL = (property_exists($item, 'profile_displayImage')) ? $item->profile_displayImage : "";
$activities[] = $ua;
}
if( $stream == "me" ){
if ($stream == "me") {
$userId = $this->getCurrentUserId();
$my_activities = array();
foreach( $activities as $a ){
if( $a->user->identifier == $userId ){
foreach ($activities as $a) {
if ($a->user->identifier == $userId) {
$my_activities[] = $a;
}
}
@@ -173,70 +173,104 @@ class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OAuth1
return $activities;
}
//--
function select($vs, $t)
{
foreach( $vs as $v ){
if( $v->type == $t ) {
/**
* Utility function for returning values from XML-like objects
*
* @param stdClass $vs Object
* @param string $t Property name
* @return mixed
*/
function select($vs, $t) {
foreach ($vs as $v) {
if ($v->type == $t) {
return $v;
}
}
return NULL;
return null;
}
function selectGUID( $v )
{
return (property_exists($v,'id'))?$v->id:"";
/**
* Parses guid
*
* @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');
if( ! $s ){
if (!$s) {
$s = $this->select($v, 'nickname');
return ($s)?$s->value:"";
return ($s) ? $s->value : "";
} 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');
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');
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');
if(empty($s)){
if (empty($s)) {
$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";
}
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['format'] = 'json';
$response = $this->api->get( 'me/guid', $parameters );
$response = $this->api->get('me/guid', $parameters);
if ( ! isset( $response->guid->value ) ){
throw new Exception( "User id request failed! {$this->providerId} returned an invalid response." );
if (!isset($response->guid->value)) {
throw new Exception("User id request failed! {$this->providerId} returned an invalid response: " . Hybrid_Logger::dumpData( $response ));
}
return $response->guid->value;
}
}

View File

@@ -1,95 +1,96 @@
<?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
*/
class Hybrid_Storage implements Hybrid_Storage_Interface
{
class Hybrid_Storage implements Hybrid_Storage_Interface {
/**
* Constructor
*/
function __construct()
{
if ( ! session_id() ){
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 );
function __construct() {
if (!session_id()) {
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);
}
}
$this->config( "php_session_id", session_id() );
$this->config( "version", Hybrid_Auth::$version );
$this->config("php_session_id", session_id());
$this->config("version", Hybrid_Auth::$version);
}
/**
* Config
* @param String $key
* @param String $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 );
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] );
if ($value) {
$_SESSION["HA::CONFIG"][$key] = serialize($value);
} elseif (isset($_SESSION["HA::CONFIG"][$key])) {
return unserialize($_SESSION["HA::CONFIG"][$key]);
}
return NULL;
return null;
}
/**
* Get a key
* @param String $key
* Returns value from session storage
*
* @param string $key Key
* @return string|null
*/
public function get($key)
{
$key = strtolower( $key );
public function get($key) {
$key = strtolower($key);
if( isset( $_SESSION["HA::STORE"], $_SESSION["HA::STORE"][$key] ) ){
return unserialize( $_SESSION["HA::STORE"][$key] );
if (isset($_SESSION["HA::STORE"], $_SESSION["HA::STORE"][$key])) {
return unserialize($_SESSION["HA::STORE"][$key]);
}
return NULL;
return null;
}
/**
* GEt a set of key and value
* @param String $key
* @param String $value
* Saves a key value pair to the session storage
*
* @param string $key Key
* @param string $value Value
* @return void
*/
public function set( $key, $value )
{
$key = strtolower( $key );
$_SESSION["HA::STORE"][$key] = serialize( $value );
public function set($key, $value) {
$key = strtolower($key);
$_SESSION["HA::STORE"][$key] = serialize($value);
}
/**
* Clear session storage
* @return void
*/
function clear()
{
$_SESSION["HA::STORE"] = ARRAY();
function clear() {
$_SESSION["HA::STORE"] = array();
}
/**
* Delete a specific key
* @param String $key
* Delete a specific key from session storage
*
* @param string $key Key
* @return void
*/
function delete($key)
{
$key = strtolower( $key );
function delete($key) {
$key = strtolower($key);
if( isset( $_SESSION["HA::STORE"], $_SESSION["HA::STORE"][$key] ) ){
if (isset($_SESSION["HA::STORE"], $_SESSION["HA::STORE"][$key])) {
$f = $_SESSION['HA::STORE'];
unset($f[$key]);
$_SESSION["HA::STORE"] = $f;
@@ -97,44 +98,44 @@ class Hybrid_Storage implements Hybrid_Storage_Interface
}
/**
* Delete a set
* @param String $key
* Delete all keys recursively from session storage
*
* @param string $key Key
* @retun void
*/
function deleteMatch($key)
{
$key = strtolower( $key );
function deleteMatch($key) {
$key = strtolower($key);
if( isset( $_SESSION["HA::STORE"] ) && count( $_SESSION["HA::STORE"] ) ) {
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 ] );
foreach ($f as $k => $v) {
if (strstr($k, $key)) {
unset($f[$k]);
}
}
$_SESSION["HA::STORE"] = $f;
}
}
/**
* Get the storage session data into an array
* @return Array
* Returns session storage as a serialized string
* @return string|null
*/
function getSessionData()
{
if( isset( $_SESSION["HA::STORE"] ) ){
return serialize( $_SESSION["HA::STORE"] );
function getSessionData() {
if (isset($_SESSION["HA::STORE"])) {
return serialize($_SESSION["HA::STORE"]);
}
return NULL;
return null;
}
/**
* Restore the storage back into session from an array
* @param Array $sessiondata
* Restores the session from serialized session data
*
* @param string $sessiondata Serialized session data
* @return void
*/
function restoreSessionData( $sessiondata = NULL )
{
$_SESSION["HA::STORE"] = unserialize( $sessiondata );
function restoreSessionData($sessiondata = null) {
$_SESSION["HA::STORE"] = unserialize($sessiondata);
}
}

View File

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

View File

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

View File

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

View File

@@ -1,9 +1,10 @@
<?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_User_Contact
@@ -12,47 +13,48 @@
*
* 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
* @var mixed
*/
public $identifier = NULL;
public $identifier = null;
/**
* User website, blog, web page
* @var String
* @var string
*/
public $webSiteURL = NULL;
public $webSiteURL = null;
/**
* URL link to profile page on the IDp web site
* @var String
* @var string
*/
public $profileURL = NULL;
public $profileURL = null;
/**
* URL link to user photo or avatar
* @var String
* @var string
*/
public $photoURL = NULL;
public $photoURL = null;
/**
* User displayName provided by the IDp or a concatenation of first and last name
* @var String
* @var string
*/
public $displayName = NULL;
public $displayName = null;
/**
* A short about_me
* @var String
* @var string
*/
public $description = NULL;
public $description = null;
/**
* User email. Not all of IDp grant access to the user email
* @var String
* @var string
*/
public $email = NULL;
public $email = null;
}

View File

@@ -1,9 +1,10 @@
<?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2014, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
* 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.
@@ -14,137 +15,138 @@
*
* 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
* @var mixed
*/
public $identifier = NULL;
public $identifier = null;
/**
* User website, blog, web page
* @var String
* @var string
*/
public $webSiteURL = NULL;
public $webSiteURL = null;
/**
* URL link to profile page on the IDp web site
* @var String
* @var string
*/
public $profileURL = NULL;
public $profileURL = null;
/**
* URL link to user photo or avatar
* @var String
* @var string
*/
public $photoURL = NULL;
public $photoURL = null;
/**
* User displayName provided by the IDp or a concatenation of first and last name.
* @var String
* @var string
*/
public $displayName = NULL;
public $displayName = null;
/**
* A short about_me
* @var String
* @var string
*/
public $description = NULL;
public $description = null;
/**
* User's first name
* @var String
* @var string
*/
public $firstName = NULL;
public $firstName = null;
/**
* User's last name
* @var String
* @var string
*/
public $lastName = NULL;
public $lastName = null;
/**
* male or female
* @var String
* Male or female
* @var string
*/
public $gender = NULL;
public $gender = null;
/**
* Language
* @var String
* @var string
*/
public $language = NULL;
public $language = null;
/**
* User age, we don't calculate it. we return it as is if the IDp provide it.
* @var Numeric
* @var int
*/
public $age = NULL;
public $age = null;
/**
* User birth Day
* @var Numeric
* @var int
*/
public $birthDay = NULL;
public $birthDay = null;
/**
* User birth Month
* @var Numeric/String
* @var int
*/
public $birthMonth = NULL;
public $birthMonth = null;
/**
* User birth Year
* @var Numeric
* @var int
*/
public $birthYear = NULL;
public $birthYear = null;
/**
* User email. Note: not all of IDp grant access to the user email
* @var String
* @var string
*/
public $email = NULL;
public $email = null;
/**
* Verified user email. Note: not all of IDp grant access to verified user email
* @var String
* @var string
*/
public $emailVerified = NULL;
public $emailVerified = null;
/**
* Phone number
* @var String
* @var string
*/
public $phone = NULL;
public $phone = null;
/**
* Complete user address
* @var String
* @var string
*/
public $address = NULL;
public $address = null;
/**
* User country
* @var String
* @var string
*/
public $country = NULL;
public $country = null;
/**
* Region
* @var String
* @var string
*/
public $region = NULL;
public $region = null;
/**
* City
* @var String
* @var string
*/
public $city = NULL;
public $city = null;
/**
* Postal code
* @var String
* @var string
*/
public $zip = NULL;
public $zip = null;
}

View File

@@ -170,6 +170,13 @@ abstract class BaseFacebook
'www' => 'https://www.facebook.com/',
);
/**
* The decoded response object.
*
* @var mixed
*/
protected $response;
/**
* The Application ID.
*
@@ -451,6 +458,16 @@ abstract class BaseFacebook
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
* the signed request if present, and then falling back on
@@ -721,7 +738,7 @@ abstract class BaseFacebook
* code could not be determined.
*/
protected function getCode() {
if (!isset($_REQUEST['code']) || !isset($_REQUEST['state'])) {
if (!isset($_REQUEST['code']) || !isset($_REQUEST['state']) || $this->state === null) {
return false;
}
if ($this->state === $_REQUEST['state']) {
@@ -913,7 +930,7 @@ abstract class BaseFacebook
}
// @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 $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) {
if ($big === $small) {
@@ -1486,7 +1503,7 @@ abstract class BaseFacebook
* @param string $big The value to be checked against $small
* @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) {
$len = strlen($small);

View File

@@ -133,7 +133,7 @@ class LinkedIn {
// oauth properties
protected $callback;
protected $token = NULL;
protected $token = null;
// application properties
protected $application_key,
@@ -190,7 +190,7 @@ class LinkedIn {
* Job ID you want to bookmark.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function bookmarkJob($jid) {
// check passed data
@@ -218,7 +218,7 @@ class LinkedIn {
* http://developer.linkedin.com/docs/DOC-1323
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function bookmarkedJobs() {
// construct and send the request
@@ -252,7 +252,7 @@ class LinkedIn {
* An array containing a LinkedIn response.
*
* @return boolean
* TRUE or FALSE depending on if the passed LinkedIn response matches the expected response.
* true or false depending on if the passed LinkedIn response matches the expected response.
*/
private function checkResponse($http_code_required, $response) {
// check passed data
@@ -272,10 +272,10 @@ class LinkedIn {
// check for a match
if(in_array($response['info']['http_code'], $http_code_required)) {
// response found
$response['success'] = TRUE;
$response['success'] = true;
} else {
// response not found
$response['success'] = FALSE;
$response['success'] = false;
$response['error'] = 'HTTP response from LinkedIn end-point was not code ' . implode(', ', $http_code_required);
}
return $response;
@@ -292,7 +292,7 @@ class LinkedIn {
* Job ID you want to close.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function closeJob($jid) {
// check passed data
@@ -326,7 +326,7 @@ class LinkedIn {
* The share comment to be posted.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function comment($uid, $comment) {
// check passed data
@@ -373,7 +373,7 @@ class LinkedIn {
* The LinkedIn update ID.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function comments($uid) {
// check passed data
@@ -409,9 +409,9 @@ class LinkedIn {
* [OPTIONAL] Search by email domain?
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function company($options, $by_email = FALSE) {
public function company($options, $by_email = false) {
// check passed data
if(!is_string($options)) {
// bad data passed
@@ -448,7 +448,7 @@ class LinkedIn {
* [OPTIONAL] Data retrieval options.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function companyProducts($cid, $options = '') {
// check passed data
@@ -485,7 +485,7 @@ class LinkedIn {
* [OPTIONAL] Data retrieval options.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function connections($options = '~/connections') {
// check passed data
@@ -518,7 +518,7 @@ class LinkedIn {
* [OPTIONAL] The content or summary of the post. This can be empty.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function createPost($gid, $title, $summary = '') {
if(!is_string($gid)) {
@@ -559,7 +559,7 @@ class LinkedIn {
* The post id.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function deletePost($pid) {
if(!is_string($pid)) {
@@ -592,7 +592,7 @@ class LinkedIn {
* The XML containing the job fields to edit.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function editJob($jid, $xml) {
// check passed data
@@ -631,7 +631,7 @@ class LinkedIn {
* [OPTIONAL] Addition OAuth parameters to send to LinkedIn.
*
* @return arr
* Array containing:
* array containing:
*
* array(
* 'info' => Connection information,
@@ -639,7 +639,7 @@ class LinkedIn {
* 'oauth' => The OAuth request string that was sent to LinkedIn
* )
*/
protected function fetch($method, $url, $data = NULL, $parameters = array()) {
protected function fetch($method, $url, $data = null, $parameters = array()) {
// check for cURL
if(!extension_loaded('curl')) {
// cURL not present
@@ -650,7 +650,7 @@ class LinkedIn {
// generate OAuth values
$oauth_consumer = new OAuthConsumer($this->getApplicationKey(), $this->getApplicationSecret(), $this->getCallbackUrl());
$oauth_token = $this->getToken();
$oauth_token = (!is_null($oauth_token)) ? new OAuthToken($oauth_token['oauth_token'], $oauth_token['oauth_token_secret']) : NULL;
$oauth_token = (!is_null($oauth_token)) ? new OAuthToken($oauth_token['oauth_token'], $oauth_token['oauth_token_secret']) : null;
$defaults = array(
'oauth_version' => self::_API_OAUTH_VERSION
);
@@ -668,10 +668,14 @@ class LinkedIn {
// set cURL options, based on parameters passed
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_VERBOSE, FALSE);
curl_setopt($handle, CURLOPT_VERBOSE, false);
// Restrict the request timeout to 5 seconds. Linkedin is sometimes very
// slow and we don't want to trigger a PHP timeout on our end.
curl_setopt($handle, CURLOPT_TIMEOUT, 5);
if ( isset ( Hybrid_Auth::$config["proxy"] ) ) {
curl_setopt($handle, CURLOPT_PROXY, Hybrid_Auth::$config["proxy"]);
@@ -702,8 +706,8 @@ class LinkedIn {
// gather the response
$return_data['linkedin'] = curl_exec($handle);
if( $return_data['linkedin'] === FALSE ) {
Hybrid_Logger::error( "LinkedIn::fetch(). curl_exec error: ", curl_error($ch) );
if( $return_data['linkedin'] === false ) {
Hybrid_Logger::error( "LinkedIn::fetch(). curl_exec error: ", curl_error($handle) );
}
$return_data['info'] = curl_getinfo($handle);
$return_data['oauth']['header'] = $oauth_req->to_header(self::_API_OAUTH_REALM);
@@ -738,7 +742,7 @@ class LinkedIn {
* The type to flag the post as.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function flagPost($pid, $type) {
if(!is_string($pid)) {
@@ -784,7 +788,7 @@ class LinkedIn {
* Company ID you want to follow.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function followCompany($cid) {
// check passed data
@@ -812,17 +816,17 @@ class LinkedIn {
* @param str $pid
* The post id.
* @param bool $follow
* Determines whether to follow or unfollow the post. TRUE = follow, FALSE = unfollow
* Determines whether to follow or unfollow the post. true = follow, false = unfollow
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function followPost($pid, $follow) {
if(!is_string($pid)) {
throw new LinkedInException('LinkedIn->followPost(): bad data passed, $pid must be of type string');
}
if(!($follow === TRUE || $follow === FALSE)) {
if(!($follow === true || $follow === false)) {
throw new LinkedInException('LinkedIn->followPost(): bad data passed, $follow must be of type boolean');
}
@@ -849,7 +853,7 @@ class LinkedIn {
* http://developer.linkedin.com/docs/DOC-1324
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function followedCompanies() {
// construct and send the request
@@ -936,7 +940,7 @@ class LinkedIn {
* [OPTIONAL] Field selectors for the group.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function group($gid, $options = '') {
@@ -967,7 +971,7 @@ class LinkedIn {
* [OPTIONAL] Field selectors for the groups.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function groupMemberships($options = '') {
if(!is_string($options)) {
@@ -996,7 +1000,7 @@ class LinkedIn {
* [OPTIONAL] Field selectors for the post.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function groupPost($pid, $options = '') {
if(!is_string($pid)) {
@@ -1028,7 +1032,7 @@ class LinkedIn {
* [OPTIONAL] Field selectors for the post comments.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function groupPostComments($pid, $options = ''){
if(!is_string($pid)){
@@ -1058,7 +1062,7 @@ class LinkedIn {
* The group id.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function groupPosts($gid, $options = '') {
if(!is_string($gid)){
@@ -1090,7 +1094,7 @@ class LinkedIn {
* [OPTIONAL] Field selectors for the group.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function groupSettings($gid, $options = '') {
if(!is_string($gid)) {
@@ -1131,7 +1135,7 @@ class LinkedIn {
* [OPTIONAL] The invitation request type (only friend is supported at this time by the Invite API).
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function invite($method, $recipient, $subject, $body, $type = 'friend') {
/**
@@ -1224,8 +1228,8 @@ class LinkedIn {
$query = 'id=' . $recipient . ':(api-standard-profile-request)';
$response = self::profile($query);
if($response['info']['http_code'] == 200) {
$response['linkedin'] = self::xmlToArray($response['linkedin']);
if($response['linkedin'] === FALSE) {
$response['linkedin'] = self::xmlToarray($response['linkedin']);
if($response['linkedin'] === false) {
// bad XML data
throw new LinkedInException('LinkedIn->invite(): LinkedIn returned bad XML data.');
}
@@ -1238,7 +1242,7 @@ class LinkedIn {
</authorization>';
} else {
// bad response from the profile request, not a valid ID?
throw new LinkedInException('LinkedIn->invite(): could not send invitation, LinkedIn says: ' . print_r($response['linkedin'], TRUE));
throw new LinkedInException('LinkedIn->invite(): could not send invitation, LinkedIn says: ' . print_r($response['linkedin'], true));
}
break;
}
@@ -1269,7 +1273,7 @@ class LinkedIn {
* A possible LinkedIn ID.
*
* @return bool
* TRUE/FALSE depending on valid ID format determination.
* true/false depending on valid ID format determination.
*/
public static function isId($id) {
// check passed data
@@ -1281,10 +1285,10 @@ class LinkedIn {
$pattern = '/^[a-z0-9_\-]{10}$/i';
if($match = preg_match($pattern, $id)) {
// we have a match
$return_data = TRUE;
$return_data = true;
} else {
// no match
$return_data = FALSE;
$return_data = false;
}
return $return_data;
}
@@ -1301,22 +1305,22 @@ class LinkedIn {
* The LinkedIn response.
*
* @return bool
* TRUE/FALSE depending on content of response.
* true/false depending on content of response.
*/
public static function isThrottled($response) {
$return_data = FALSE;
$return_data = false;
// check the variable
if(!empty($response) && is_string($response)) {
// we have an array and have a properly formatted LinkedIn response
// store the response in a temp variable
$temp_response = self::xmlToArray($response);
if($temp_response !== FALSE) {
$temp_response = self::xmlToarray($response);
if($temp_response !== false) {
// check to see if we have an error
if(array_key_exists('error', $temp_response) && ($temp_response['error']['children']['status']['content'] == 403) && preg_match('/throttle/i', $temp_response['error']['children']['message']['content'])) {
// we have an error, it is 403 and we have hit a throttle limit
$return_data = TRUE;
$return_data = true;
}
}
}
@@ -1339,7 +1343,7 @@ class LinkedIn {
* [OPTIONAL] Data retrieval options.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function job($jid, $options = '') {
// check passed data
@@ -1372,7 +1376,7 @@ class LinkedIn {
* The group id.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function joinGroup($gid) {
if(!is_string($gid)) {
@@ -1429,7 +1433,7 @@ class LinkedIn {
* The group id.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function leaveGroup($gid){
if(!is_string($gid)) {
@@ -1456,7 +1460,7 @@ class LinkedIn {
* The LinkedIn update ID.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function like($uid) {
// check passed data
@@ -1488,16 +1492,16 @@ class LinkedIn {
* @param str $pid
* The post id.
* @param bool $like
* Determines whether to like or unlike. TRUE = like, FALSE = unlike.
* Determines whether to like or unlike. true = like, false = unlike.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function likePost($pid, $like) {
if(!is_string($pid)) {
throw new LinkedInException ('LinkedIn->likePost(): bad data passed, $pid must be of type string');
}
if(!($like === TRUE || $like === FALSE)) {
if(!($like === true || $like === false)) {
throw new LinkedInException('LinkedIn->likePost(): bad data passed, $like must be of type boolean');
}
@@ -1527,7 +1531,7 @@ class LinkedIn {
* The LinkedIn update ID.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function likes($uid) {
// check passed data
@@ -1565,9 +1569,9 @@ class LinkedIn {
* [OPTIONAL] Also update the teathered Twitter account.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function message($recipients, $subject, $body, $copy_self = FALSE) {
public function message($recipients, $subject, $body, $copy_self = false) {
/**
* Clean up the passed data per these rules:
*
@@ -1629,7 +1633,7 @@ class LinkedIn {
* The XML defining a job to post.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function postJob($xml) {
// check passed data
@@ -1664,7 +1668,7 @@ class LinkedIn {
* [OPTIONAL] Data retrieval options.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function profile($options = '~') {
// check passed data
@@ -1684,6 +1688,77 @@ class LinkedIn {
return $this->checkResponse(200, $response);
}
/**
* Send a message
*
* Send a message to another member or members
*
* @author @timersys
*
* @param array $recipients
* The id or ids to send the message to.
* @param str $subject
* The subject of the invitation to send.
* @param str $body
* The body of the invitation to send.
*
* @return arr array
* Containing retrieval success, LinkedIn response.
*/
public function send_msg($recipients, $subject, $body) {
/**
* Clean up the passed data per these rules:
*
* 1) No HTML permitted
* 2) 200 characters max in the invitation subject
* 3) Only able to connect as a friend at this point
*/
// check passed data
if(empty($recipients)) {
throw new LinkedInException('LinkedIn->send_msg(): you must provide an invitation recipient.');
}
if(!empty($subject)) {
$subject = trim(htmlspecialchars(strip_tags(stripslashes($subject))));
} else {
throw new LinkedInException('LinkedIn->send_msg(): message subject is empty.');
}
if(!empty($body)) {
$body = trim(htmlspecialchars(strip_tags(stripslashes($body))));
if(strlen($body) > self::_INV_BODY_LENGTH) {
throw new LinkedInException('LinkedIn->send_msg(): message body length is too long - max length is ' . self::_INV_BODY_LENGTH . ' characters.');
}
} else {
throw new LinkedInException('LinkedIn->send_msg(): message body is empty.');
}
// construct the xml data
$data = '<?xml version="1.0" encoding="UTF-8"?>
<mailbox-item>
<recipients>';
foreach( $recipients as $recipient )
{
$data .= '<recipient>';
$data .= '<person path="/people/'. $recipient . '"/>';
$data .= '</recipient>';
}
$data .= ' </recipients>
<subject>' . $subject . '</subject>
<body>' . $body . '</body>
</mailbox-item>';
// send request
$query = self::_URL_API . '/v1/people/~/mailbox';
$response = $this->fetch('POST', $query, $data);
/**
* Check for successful request (a 201 response from LinkedIn server)
* per the documentation linked in method comments above.
*/
return $this->checkResponse(201, $response);
}
/**
* Manual API call method, allowing for support for un-implemented API
* functionality to be supported.
@@ -1697,11 +1772,11 @@ class LinkedIn {
* [OPTIONAL] The URL-encoded body data to send to LinkedIn with the request.
*
* @return arr
* Array containing retrieval information, LinkedIn response. Note that you
* array containing retrieval information, LinkedIn response. Note that you
* must manually check the return code and compare this to the expected
* API response to determine if the raw call was successful.
*/
public function raw($method, $url, $body = NULL) {
public function raw($method, $url, $body = null) {
if(!is_string($method)) {
// bad data passed
throw new LinkedInException('LinkedIn->raw(): bad data passed, $method must be of string value.');
@@ -1729,7 +1804,7 @@ class LinkedIn {
* The group id.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function removeSuggestedGroup($gid) {
if(!is_string($gid)) {
@@ -1760,7 +1835,7 @@ class LinkedIn {
* Contract ID that covers the passed Job ID.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function renewJob($jid, $cid) {
// check passed data
@@ -1818,7 +1893,7 @@ class LinkedIn {
$parameters = array(
'oauth_verifier' => $verifier
);
$response = $this->fetch(self::_METHOD_TOKENS, self::_URL_ACCESS, NULL, $parameters);
$response = $this->fetch(self::_METHOD_TOKENS, self::_URL_ACCESS, null, $parameters);
parse_str($response['linkedin'], $response['linkedin']);
/**
@@ -1831,15 +1906,15 @@ class LinkedIn {
// set the response
$return_data = $response;
$return_data['success'] = TRUE;
$return_data['success'] = true;
} else {
// error getting the request tokens
$this->setToken(NULL);
$this->setToken(null);
// set the response
$return_data = $response;
$return_data['error'] = 'HTTP response from LinkedIn end-point was not code 200';
$return_data['success'] = FALSE;
$return_data['success'] = false;
}
return $return_data;
}
@@ -1856,7 +1931,7 @@ class LinkedIn {
$parameters = array(
'oauth_callback' => $this->getCallbackUrl()
);
$response = $this->fetch(self::_METHOD_TOKENS, self::_URL_REQUEST, NULL, $parameters);
$response = $this->fetch(self::_METHOD_TOKENS, self::_URL_REQUEST, null, $parameters);
parse_str($response['linkedin'], $response['linkedin']);
/**
@@ -1869,10 +1944,10 @@ class LinkedIn {
// set the response
$return_data = $response;
$return_data['success'] = TRUE;
$return_data['success'] = true;
} else {
// error getting the request tokens
$this->setToken(NULL);
$this->setToken(null);
// set the response
$return_data = $response;
@@ -1881,7 +1956,7 @@ class LinkedIn {
} else {
$return_data['error'] = 'OAuth callback URL was not confirmed by the LinkedIn end-point';
}
$return_data['success'] = FALSE;
$return_data['success'] = false;
}
return $return_data;
}
@@ -1896,7 +1971,7 @@ class LinkedIn {
* http://developer.linkedin.com/community/apis/blog/2010/04/29/oauth--now-for-authentication
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function revoke() {
// construct and send the request
@@ -1922,9 +1997,9 @@ class LinkedIn {
* [OPTIONAL] Data retrieval options.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function search($options = NULL) {
public function search($options = null) {
return searchPeople($options);
}
@@ -1940,7 +2015,7 @@ class LinkedIn {
* @param str $options
* [OPTIONAL] Search options.
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function searchCompanies($options = '') {
// check passed data
@@ -1973,7 +2048,7 @@ class LinkedIn {
* [OPTIONAL] Data retrieval options.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function searchJobs($options = '') {
// check passed data
@@ -2006,9 +2081,9 @@ class LinkedIn {
* [OPTIONAL] Data retrieval options.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function searchPeople($options = NULL) {
public function searchPeople($options = null) {
// check passed data
if(!is_null($options) && !is_string($options)) {
// bad data passed
@@ -2073,7 +2148,7 @@ class LinkedIn {
* -<email-for-every-new-post>
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function setGroupSettings($gid, $xml) {
if(!is_string ($gid)) {
@@ -2154,9 +2229,9 @@ class LinkedIn {
* [OPTIONAL] Also update the teathered Twitter account.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function share($action, $content, $private = TRUE, $twitter = FALSE) {
public function share($action, $content, $private = true, $twitter = false) {
// check the status itself
if(!empty($action) && !empty($content)) {
/**
@@ -2173,8 +2248,8 @@ class LinkedIn {
*/
// prepare the share data per the rules above
$share_flag = FALSE;
$content_xml = NULL;
$share_flag = false;
$content_xml = null;
switch($action) {
case 'new':
// share can be an article
@@ -2199,7 +2274,7 @@ class LinkedIn {
}
$content_xml .= '</content>';
$share_flag = TRUE;
$share_flag = true;
}
// share can be just a comment
@@ -2211,7 +2286,7 @@ class LinkedIn {
}
$content_xml .= '<comment>' . $comment . '</comment>';
$share_flag = TRUE;
$share_flag = true;
}
break;
case 'reshare':
@@ -2233,7 +2308,7 @@ class LinkedIn {
$content_xml .= '<comment>' . $comment . '</comment>';
}
$share_flag = TRUE;
$share_flag = true;
}
break;
default:
@@ -2288,7 +2363,7 @@ class LinkedIn {
* http://developer.linkedin.com/docs/DOC-1006
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function statistics() {
// construct and send the request
@@ -2310,7 +2385,7 @@ class LinkedIn {
* http://developer.linkedin.com/docs/DOC-1324
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function suggestedCompanies() {
// construct and send the request
@@ -2330,7 +2405,7 @@ class LinkedIn {
* http://developer.linkedin.com/documents/groups-api
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function suggestedGroups() {
// construct and send the request
@@ -2355,7 +2430,7 @@ class LinkedIn {
* [OPTIONAL] Data retrieval options.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function suggestedJobs($options = ':(jobs)') {
// check passed data
@@ -2387,7 +2462,7 @@ class LinkedIn {
* Job ID you want to unbookmark.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function unbookmarkJob($jid) {
// check passed data
@@ -2419,7 +2494,7 @@ class LinkedIn {
* Company ID you want to unfollow.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function unfollowCompany($cid) {
// check passed data
@@ -2450,7 +2525,7 @@ class LinkedIn {
* The LinkedIn update ID.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function unlike($uid) {
// check passed data
@@ -2487,7 +2562,7 @@ class LinkedIn {
* The network update.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function updateNetwork($update) {
// check passed data
@@ -2505,14 +2580,14 @@ class LinkedIn {
*/
// get the user data
$response = self::profile('~:(first-name,last-name,site-standard-profile-request)');
if($response['success'] === TRUE) {
if($response['success'] === true) {
/**
* We are converting response to usable data. I'd use SimpleXML here, but
* to keep the class self-contained, we will use a portable XML parsing
* routine, self::xmlToArray.
* routine, self::xmlToarray.
*/
$person = self::xmlToArray($response['linkedin']);
if($person === FALSE) {
$person = self::xmlToarray($response['linkedin']);
if($person === false) {
// bad xml data
throw new LinkedInException('LinkedIn->updateNetwork(): LinkedIn returned bad XML data.');
}
@@ -2568,9 +2643,9 @@ class LinkedIn {
* [OPTIONAL] The LinkedIn ID to restrict the updates for.
*
* @return arr
* Array containing retrieval success, LinkedIn response.
* array containing retrieval success, LinkedIn response.
*/
public function updates($options = NULL, $id = NULL) {
public function updates($options = null, $id = null) {
// check passed data
if(!is_null($options) && !is_string($options)) {
// bad data passed
@@ -2603,15 +2678,15 @@ class LinkedIn {
* The XML to convert to an array.
*
* @return arr
* Array containing the XML data.
* array containing the XML data.
* @return bool
* FALSE if passed data cannot be parsed to an array.
* false if passed data cannot be parsed to an array.
*/
public static function xmlToArray($xml) {
public static function xmlToarray($xml) {
// check passed data
if(!is_string($xml)) {
// bad data passed
throw new LinkedInException('LinkedIn->xmlToArray(): bad data passed, $xml must be a non-zero length string.');
throw new LinkedInException('LinkedIn->xmlToarray(): bad data passed, $xml must be a non-zero length string.');
}
$parser = xml_parser_create();
@@ -2624,8 +2699,8 @@ class LinkedIn {
$index = count($elements);
if($tag['type'] == 'complete' || $tag['type'] == 'open') {
$elements[$tag['tag']] = array();
$elements[$tag['tag']]['attributes'] = (array_key_exists('attributes', $tag)) ? $tag['attributes'] : NULL;
$elements[$tag['tag']]['content'] = (array_key_exists('value', $tag)) ? $tag['value'] : NULL;
$elements[$tag['tag']]['attributes'] = (array_key_exists('attributes', $tag)) ? $tag['attributes'] : null;
$elements[$tag['tag']]['content'] = (array_key_exists('value', $tag)) ? $tag['value'] : null;
if($tag['type'] == 'open') {
$elements[$tag['tag']]['children'] = array();
$stack[count($stack)] = &$elements;
@@ -2640,7 +2715,7 @@ class LinkedIn {
$return_data = $elements;
} else {
// not valid xml data
$return_data = FALSE;
$return_data = false;
}
xml_parser_free($parser);
return $return_data;

View File

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

View File

@@ -31,6 +31,7 @@ class OAuth1Client{
public $http_code = "";
public $http_info = "";
protected $response = null;
/**
* OAuth client constructor
@@ -110,15 +111,15 @@ class OAuth1Client{
/**
* 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
*/
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 );
}
@@ -126,7 +127,7 @@ class OAuth1Client{
/**
* 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;
@@ -138,13 +139,23 @@ class OAuth1Client{
$response = json_decode( $response );
}
return $response;
return $this->response = $response;
}
/**
* Return the response object afer the fact
*
* @return mixed
*/
public function getResponse()
{
return $this->response;
}
/**
* Make signed request
*/
function signedRequest( $url, $method, $parameters, $body = NULL, $content_type = NULL, $multipart = false )
function signedRequest( $url, $method, $parameters, $body = null, $content_type = null, $multipart = false )
{
$signature_parameters = array();
@@ -159,7 +170,7 @@ class OAuth1Client{
$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) {
case 'GET': return $this->request( $request->to_url(), 'GET', NULL, NULL, $content_type );
case 'GET': return $this->request( $request->to_url(), 'GET', null, null, $content_type );
default :
if ($body)
return $this->request( $request->to_url(), $method, $body, $request->to_header(), $content_type );
@@ -171,7 +182,7 @@ class OAuth1Client{
/**
* Make http request
*/
function request( $url, $method, $postfields = NULL, $auth_header = NULL, $content_type = NULL, $multipart = false )
function request( $url, $method, $postfields = null, $auth_header = null, $content_type = null, $multipart = false )
{
Hybrid_Logger::info( "Enter OAuth1Client::request( $method, $url )" );
Hybrid_Logger::debug( "OAuth1Client::request(). dump post fields: ", serialize( $postfields ) );
@@ -183,11 +194,11 @@ class OAuth1Client{
curl_setopt( $ci, CURLOPT_USERAGENT , $this->curl_useragent );
curl_setopt( $ci, CURLOPT_CONNECTTIMEOUT, $this->curl_connect_time_out );
curl_setopt( $ci, CURLOPT_TIMEOUT , $this->curl_time_out );
curl_setopt( $ci, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt( $ci, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ci, CURLOPT_HTTPHEADER , array('Expect:') );
curl_setopt( $ci, CURLOPT_SSL_VERIFYPEER, $this->curl_ssl_verifypeer );
curl_setopt( $ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader') );
curl_setopt( $ci, CURLOPT_HEADER , FALSE );
curl_setopt( $ci, CURLOPT_HEADER , false );
if( $multipart ){
curl_setopt( $ci, CURLOPT_HTTPHEADER, array( 'Expect:', $auth_header ) );
@@ -201,7 +212,7 @@ class OAuth1Client{
switch ($method){
case 'POST':
curl_setopt( $ci, CURLOPT_POST, TRUE );
curl_setopt( $ci, CURLOPT_POST, true );
if ( !empty($postfields) ){
curl_setopt( $ci, CURLOPT_POSTFIELDS, $postfields );
@@ -220,7 +231,7 @@ class OAuth1Client{
curl_setopt($ci, CURLOPT_URL, $url);
$response = curl_exec($ci);
if( $response === FALSE ) {
if( $response === false ) {
Hybrid_Logger::error( "OAuth1Client::request(). curl_exec error: ", curl_error($ci) );
}

View File

@@ -6,7 +6,7 @@
*/
// A service client for the OAuth 2 flow.
// v0.1
// v0.1.1
class OAuth2Client
{
public $api_base_url = "";
@@ -32,22 +32,24 @@ class OAuth2Client
public $curl_ssl_verifypeer = false;
public $curl_ssl_verifyhost = false;
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_proxy = null;
public $curl_compressed = false;
//--
public $http_code = "";
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->redirect_uri = $redirect_uri;
$this->curl_compressed = $compressed;
}
public function authorizeUrl( $extras = array() )
@@ -140,10 +142,20 @@ class OAuth2Client
}
if( $response && $this->decode_json ){
$response = json_decode( $response );
return $this->response = json_decode( $response );
}
return $response;
return $this->response = $response;
}
/**
* Return the response object afer the fact
*
* @return mixed
*/
public function getResponse()
{
return $this->response;
}
/**
@@ -210,17 +222,21 @@ class OAuth2Client
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , $this->curl_ssl_verifyhost );
curl_setopt($ch, CURLOPT_HTTPHEADER , $this->curl_header );
if ($this->curl_compressed){
curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
}
if($this->curl_proxy){
curl_setopt( $ch, CURLOPT_PROXY , $this->curl_proxy);
}
if( $type == "POST" ){
curl_setopt($ch, CURLOPT_POST, 1);
if($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($params, '', '&') );
if($params) curl_setopt( $ch, CURLOPT_POSTFIELDS, $params );
}
$response = curl_exec($ch);
if( $response === FALSE ) {
if( $response === false ) {
Hybrid_Logger::error( "OAuth2Client::request(). curl_exec error: ", curl_error($ch) );
}
Hybrid_Logger::debug( "OAuth2Client::request(). dump request info: ", serialize( curl_getinfo($ch) ) );

View File

@@ -1,17 +1,15 @@
<?php
// https://github.com/iignatov/LightOpenID
/**
* 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.
*
* @version v1.1.2 2013-01-15
* @link http://gitorious.org/lightopenid Official Repo
* @link http://github.com/iignatov/LightOpenID GitHub Clone
* @author Mewp
* @copyright Copyright (c) 2010, Mewp
* @license http://www.opensource.org/licenses/mit-license.php MIT License
* @version v1.2.0 (2014-01-14)
* @link https://code.google.com/p/lightopenid/ Project URL
* @link https://github.com/iignatov/LightOpenID GitHub Repo
* @author Mewp <mewp151 at gmail dot com>
* @copyright Copyright (c) 2013 Mewp
* @license http://opensource.org/licenses/mit-license.php MIT License
*/
class LightOpenID
{
@@ -21,11 +19,15 @@ class LightOpenID
, $verify_peer = null
, $capath = null
, $cainfo = null
, $cnmatch = null
, $data
, $oauth = array();
, $oauth = array()
, $curl_time_out = 30
, $curl_connect_time_out = 30;
private $identity, $claimed_id;
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;
static protected $ax_to_sreg = array(
'namePerson/friendly' => 'nickname',
@@ -41,18 +43,7 @@ class LightOpenID
function __construct($host, $proxy = null)
{
$this->trustRoot = (strpos($host, '://') ? $host : 'http://' . $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_realm($host);
$this->set_proxy($proxy);
$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)
{
switch ($name) {
@@ -160,15 +156,53 @@ class LightOpenID
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)
{
$params = http_build_query($params, '', '&');
$curl = curl_init($url . ($method == 'GET' && $params ? '?' . $params : ''));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
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_RETURNTRANSFER, true);
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)) {
curl_setopt($curl, CURLOPT_PROXY, $this->proxy['host']);
@@ -204,9 +238,6 @@ class LightOpenID
curl_setopt($curl, CURLOPT_HTTPGET, true);
}
$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) {
curl_setopt($curl, CURLOPT_HTTPGET, true);
@@ -232,9 +263,10 @@ class LightOpenID
}
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);
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;
}
}
@@ -289,6 +321,10 @@ class LightOpenID
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, '', '&');
switch($method) {
case 'GET':
@@ -296,10 +332,12 @@ class LightOpenID
'http' => array(
'method' => 'GET',
'header' => 'Accept: application/xrds+xml, */*',
'user_agent' => $this->user_agent,
'ignore_errors' => true,
), 'ssl' => array(
'CN_match' => parse_url($url, PHP_URL_HOST),
),
'ssl' => array(
'CN_match' => $this->cnmatch
)
);
$url = $url . ($params ? '?' . $params : '');
if (!empty($this->proxy)) {
@@ -311,11 +349,13 @@ class LightOpenID
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'user_agent' => $this->user_agent,
'content' => $params,
'ignore_errors' => true,
), 'ssl' => array(
'CN_match' => parse_url($url, PHP_URL_HOST),
),
'ssl' => array(
'CN_match' => $this->cnmatch
)
);
if (!empty($this->proxy)) {
$opts['http']['proxy'] = $this->proxy_url();
@@ -335,6 +375,7 @@ class LightOpenID
$default['http'] += array(
'method' => 'GET',
'header' => '',
'user_agent' => '',
'ignore_errors' => false
);
$default['ssl'] += array(
@@ -345,10 +386,11 @@ class LightOpenID
'http' => array(
'method' => 'HEAD',
'header' => 'Accept: application/xrds+xml, */*',
'user_agent' => $this->user_agent,
'ignore_errors' => true,
),
'ssl' => array(
'CN_match' => parse_url($url, PHP_URL_HOST)
'CN_match' => $this->cnmatch
)
);
@@ -412,12 +454,29 @@ class LightOpenID
protected function request($url, $method='GET', $params=array(), $update_claimed_id=false)
{
if (function_exists('curl_init')
&& (!in_array('https', stream_get_wrappers()) || !ini_get('safe_mode') && !ini_get('open_basedir'))
) {
return $this->request_curl($url, $method, $params, $update_claimed_id);
$use_curl = false;
if (function_exists('curl_init')) {
if (!$use_curl) {
# When allow_url_fopen is disabled, PHP streams will not work.
$use_curl = !ini_get('allow_url_fopen');
}
return $this->request_streams($url, $method, $params, $update_claimed_id);
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
$use_curl
? $this->request_curl($url, $method, $params, $update_claimed_id)
: $this->request_streams($url, $method, $params, $update_claimed_id);
}
protected function proxy_url()
@@ -512,14 +571,7 @@ class LightOpenID
$next = true;
}
if (isset($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.
# ---
if (isset($headers['content-type']) && $this->is_allowed_type($headers['content-type'])) {
# Found an XRDS document, now let's find the server, and optionally delegate.
$content = $this->request($url, 'GET');
@@ -625,11 +677,26 @@ class LightOpenID
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()
{
$params = array();
# 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
$params['openid.ns.sreg'] = 'http://openid.net/extensions/sreg/1.1';
if ($this->required) {
@@ -679,7 +746,7 @@ class LightOpenID
$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.
if($required) {
$params['openid.ax.required'] = implode(',', $required);
@@ -812,7 +879,7 @@ class LightOpenID
if ($this->data['openid_return_to'] != $this->returnUrl) {
# 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;
}
@@ -821,7 +888,7 @@ class LightOpenID
foreach (explode(',', $this->data['openid_signed']) as $item) {
# Checking whether magic_quotes_gpc is turned on, because
# 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
# wants to verify. stripslashes() should solve that problem, but we can't
# use it when magic_quotes is off.
@@ -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,
* or that there will be no other attributes besides those specified.
* In other words. OP may provide whatever information it wants to.