1
0
mirror of https://github.com/e107inc/e107.git synced 2025-08-05 22:27:34 +02:00

Start of HybridAuth integration

This commit is contained in:
CaMer0n
2012-06-13 12:34:09 +00:00
parent 2cd1d38efb
commit 3b9d9a31c3
60 changed files with 10198 additions and 32 deletions

View File

@@ -58,7 +58,12 @@ if(isset($_POST['submit_resetdisplaynames']))
/* UPDATE PREFERENCES */
if(isset($_POST['updateprefs']))
{
unset($_POST['updateprefs'], $_POST['sitelanguage']);
print_a($_POST);
$_POST['cookie_name'] = str_replace(array(" ", "."), "_", $_POST['cookie_name']);
$_POST['cookie_name'] = preg_replace("#[^a-zA-Z0-9_]#", "", $_POST['cookie_name']);
@@ -660,6 +665,139 @@ $text .= "
</fieldset>
";
// Single Login / / copied from hybridAuth config.php so it's easy to add more.
// Used Below.
$single_logins = array (
// openid providers
"OpenID" => array (
"enabled" => true
),
"Yahoo" => array (
"enabled" => true
),
"AOL" => array (
"enabled" => true
),
"Google" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" ),
"scope" => ""
),
"Facebook" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" ),
// A comma-separated list of permissions you want to request from the user. See the Facebook docs for a full list of available permissions: http://developers.facebook.com/docs/reference/api/permissions.
"scope" => "",
// The display context to show the authentication page. Options are: page, popup, iframe, touch and wap. Read the Facebook docs for more details: http://developers.facebook.com/docs/reference/dialogs#display. Default: page
"display" => ""
),
"Twitter" => array (
"enabled" => true,
"keys" => array ( "key" => "", "secret" => "" )
),
// windows live
"Live" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" )
),
"MySpace" => array (
"enabled" => true,
"keys" => array ( "key" => "", "secret" => "" )
),
"LinkedIn" => array (
"enabled" => true,
"keys" => array ( "key" => "", "secret" => "" )
),
"Foursquare" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" )
)
);
$text .= "
<fieldset class='e-hideme' id='core-prefs-single-login'>
<legend>Single Login Options</legend>
<div>Note: This section is not functional at the moment</div>
<table class='adminform'>
<colgroup>
<col class='col-label' />
<col class='col-control' />
</colgroup>
<tbody>
<tr>
<td class='label'>Enable Single Logins</td>
<td class='control'>
".$frm->radio_switch('single_login_active', $pref['single_login_active'])."
</td>
</tr>";
foreach($single_logins as $prov=>$val)
{
$text .= "
<tr>
<td class='label'>".$prov."</td>
<td class='control'>
";
foreach($val as $k=>$v)
{
switch ($k) {
case 'enabled':
$eopt = array('class'=>'e-expandit');
$text .= $frm->radio_switch('single_login['.$prov.'][enabled]', $pref['single_login'][$prov]['enabled'],'','',$eopt);
break;
case 'keys':
// $cls = vartrue($pref['single_login'][$prov]['keys'][$tk]) ? "class='e-hideme'" : '';
$sty = vartrue($pref['single_login'][$prov]['keys'][$tk]) ? "" : "display:none";
$text .= "<div id='option-{$prov}' style='padding:10px;{$sty}'>";
foreach($v as $tk=>$idk)
{
$opt['placeholder'] = $tk;
$text .= "<br />".$frm->text('single_login['.$prov.'][keys]['.$tk.']', $pref['single_login'][$prov]['keys'][$tk],20,$opt);
}
$text .= "</div>";
break;
default:
break;
}
}
$text .= "</td>
</tr>
";
}
$text .= "
</tbody>
</table>
".pref_submit('single-login')."
</fieldset>
";
// Signup options ===========================.
@@ -1256,39 +1394,17 @@ $text .= "
);
//TODO FIXME - remove JS framework dependency from front-end and backend.
// ie. no JS errors when prototype.js is completely disabled.
// no JS error with only 'e107 Core Minimum' is enabled.
// e107 Core Minimum should function independently of framework.
//TODO FIXME
// ie. e107 Core Minimum: JS similar to e107 v1.0 should be loaded "e_js.php" (no framwork dependency)
// with basic functions like SyncWithServerTime() and expandit(), externalLinks() etc.
//TODO Move paths into js_manager and store only keys like 'prototype-local', 'core-minimum' in prefs.
/*
$js_types = array(
array('name'=> 'Prototype (local)', 'path'=> 'prototype/prototype.js') ,
array('name'=> 'Scriptaculous (local)', 'path'=> 'scriptaculous/scriptaculous.js'),
array('name'=> 'Scriptaculous-effects (local)', 'path'=> 'scriptaculous/effects.js'),
array('name'=> 'Prototype (CDN)', 'path'=> 'https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js'),
array('name'=> 'Scriptaculous + Effects (CDN)', 'path'=> 'https://ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js?load=effects'),
array('name'=> 'jQuery (CDN)', 'path'=> 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'),
array('name'=> 'jQuery UI (CDN)', 'path'=> 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js'),
array('name'=> 'e107 Core Minimum', 'path'=> 'e107.js'),
array('name'=> 'e107 Plugin Scripts (TO-DO)', 'path'=> ''), // all js that has been added by Plugins.
array('name'=> 'e107 Theme Scripts (TO-DO)', 'path'=> ''), // all js that has been added by Themes.
);
*/
// e107 minimum loaded by default once dependency is removed.
$js_types = array(
array('id' => 'prototype', 'name'=> 'Prototype (local)'),
// array('id' => 'prototype-cdn', 'name'=> 'Prototype (CDN)'),
array('id' => 'jquery', 'name'=> 'jQuery (local)'),
// array('id' => 'jquery-cdn', 'name'=> 'jQuery (CDN)')
array('id' => 'jquery', 'name'=> 'jQuery (local)'),
);
//TODO // separate switch for CDN.. or automatic fall-back.
@@ -1484,6 +1600,7 @@ function prefs_adminmenu()
$var['core-prefs-date']['text'] = PRFLAN_21;
$var['core-prefs-registration']['text'] = PRFLAN_28;
$var['core-prefs-signup']['text'] = PRFLAN_19;
$var['core-prefs-single-login']['text'] = "Single-Login";
$var['core-prefs-textpost']['text'] = PRFLAN_101;
$var['core-prefs-security']['text'] = PRFLAN_47;
$var['core-prefs-comments']['text'] = PRFLAN_210;

View File

@@ -40,6 +40,31 @@ class signup_shortcodes extends e_shortcode
}
}
function sc_signup_xup() // show it to those who were using xup
{
return $this->sc_single_login();
}
function sc_single_login()
{
$pref['single_login_active'] = 1;
if(vartrue($pref['single_login_active']))
{
$text = "";
$providers = array('facebook','twitter','google','yahoo');
foreach($providers as $p)
{
$text .= "<a href='".e_SELF."?provider={$p}'><img src='".e_HANDLER."hybridauth/icons/{$p}.png' alt='' /></a>";
}
$text .= "<hr />";
return $text;
// return $tp->parseTemplate($SIGNUP_XUP_FORM, TRUE, $signup_shortcodes);
}
}
function sc_signup_form_open()
{

View File

@@ -3,14 +3,77 @@ $(document).ready(function()
$(".e-hideme").hide();
$(".e-expandit").show();
// default 'toggle'.
$(".e-expandit").click(function () {
var href = ($(this).is("a")) ? $(this).attr("href") : '';
if(href === "#" || href == "")
{
idt = $(this).nextAll("div");
$(idt).toggle("slow");
return true;
}
var id = $(this).attr("href");
$(id).toggle("slow");
return false;
});
// On
$(".e-expandit-on").click(function () {
var href = ($(this).is("a")) ? $(this).attr("href") : '';
if(href === "#" || href == "")
{
idt = $(this).nextAll("div");
$(idt).show("slow");
return true; // must be true or radio buttons etc. won't work
}
if($(this).attr("data-expandit"))
{
var id = $(this).attr("data-expandit");
}
else
{
var id = $(this).attr("href");
}
$(id).show("slow");
return false;
});
// Off.
$(".e-expandit-off").click(function () {
var href = ($(this).is("a")) ? $(this).attr("href") : '';
if(href === "#" || href == "")
{
idt = $(this).nextAll("div");
$(idt).hide("slow");
return true; // must be true or radio buttons etc. won't work
}
if($(this).attr("data-expandit"))
{
var id = $(this).attr("data-expandit");
}
else
{
var id = $(this).attr("href");
}
$(id).hide("slow");
return false;
});
// Dates --------------------------------------------------
$("input.e-date").each(function() {

View File

@@ -735,10 +735,19 @@ class e_form
}
function radio_switch($name, $checked_enabled = false, $label_enabled = '', $label_disabled = '')
function radio_switch($name, $checked_enabled = false, $label_enabled = '', $label_disabled = '',$options=array())
{
return $this->radio($name, 1, $checked_enabled)."".$this->label($label_enabled ? $label_enabled : LAN_ENABLED, $name, 1)."&nbsp;&nbsp;
".$this->radio($name, 0, !$checked_enabled)."".$this->label($label_disabled ? $label_disabled : LAN_DISABLED, $name, 0);
$options_on = array();
$options_off = array();
if($options['class'] == 'e-expandit') // See admin->prefs 'Single Login' for an example.
{
$options_on = array('class' => 'e-expandit-on');
$options_off = array('class' => 'e-expandit-off');
}
return $this->radio($name, 1, $checked_enabled, $options_on)."".$this->label($label_enabled ? $label_enabled : LAN_ENABLED, $name, 1)."&nbsp;&nbsp;
".$this->radio($name, 0, !$checked_enabled, $options_off)."".$this->label($label_disabled ? $label_disabled : LAN_DISABLED, $name, 0);
}

View File

@@ -0,0 +1,408 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Auth class
*
* Hybrid_Auth class provide a simple way to authenticate users via OpenID and OAuth.
*
* Generally, Hybrid_Auth is the only class you should instanciate and use throughout your application.
*/
class Hybrid_Auth
{
public static $version = "2.0.11-dev";
public static $config = array();
public static $store = NULL;
public static $error = NULL;
public static $logger = NULL;
// --------------------------------------------------------------------
/**
* Try to start a new session of none then initialize Hybrid_Auth
*
* Hybrid_Auth constructor will require either a valid config array or
* a path for a configuration file as parameter. To know more please
* refer to the Configuration section:
* http://hybridauth.sourceforge.net/userguide/Configuration.html
*/
function __construct( $config )
{
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 );
}
}
#{{{ well, should we check this each time? ..
// PHP Curl extension [http://www.php.net/manual/en/intro.curl.php]
if ( ! function_exists('curl_init') ) {
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') ) {
throw new Exception('Hybridauth Library needs the JSON PHP extension.');
}
// OAuth PECL extension is not compatible with this library
if( extension_loaded('oauth') ) {
throw new Exception('Hybridauth Library not compatible with installed PECL OAuth extension. Please disable it.');
}
#}}}
Hybrid_Auth::initialize( $config );
}
// --------------------------------------------------------------------
/**
* Try to initialize Hybrid_Auth with given $config hash or file
*/
public static function initialize( $config )
{
if ( ! session_id() ){
throw new Exception( "Hybriauth require the use of 'session_start()' at the start of your script.", 1 );
}
if( ! is_array( $config ) && ! file_exists( $config ) ){
throw new Exception( "Hybriauth config does not exist on the given path.", 1 );
}
if( ! is_array( $config ) ){
$config = include $config;
}
// build some need'd paths
$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"] ) ){
$config["debug_mode"] = false;
$config["debug_file"] = null;
}
# load hybridauth required files, a autoload is on the way...
require_once $config["path_base"] . "Error.php";
require_once $config["path_base"] . "Logger.php";
require_once $config["path_base"] . "Storage.php";
require_once $config["path_base"] . "Provider_Adapter.php";
require_once $config["path_base"] . "Provider_Model.php";
require_once $config["path_base"] . "Provider_Model_OpenID.php";
require_once $config["path_base"] . "Provider_Model_OAuth1.php";
require_once $config["path_base"] . "Provider_Model_OAuth2.php";
require_once $config["path_base"] . "User.php";
require_once $config["path_base"] . "User_Profile.php";
require_once $config["path_base"] . "User_Contact.php";
require_once $config["path_base"] . "User_Activity.php";
// hash given config
Hybrid_Auth::$config = $config;
// start session storage mng
Hybrid_Auth::$store = new Hybrid_Storage();
// instace of errors mng
Hybrid_Auth::$error = new Hybrid_Error();
// instace of log mng
Hybrid_Auth::$logger = new Hybrid_Logger();
// store php session and version..
$_SESSION["HA::PHP_SESSION_ID"] = session_id();
$_SESSION["HA::VERSION"] = Hybrid_Auth::$version;
// almost done, check for errors then move on
Hybrid_Logger::info( "Enter Hybrid_Auth::initialize()");
Hybrid_Logger::info( "Hybrid_Auth::initialize(). Hybrid_Auth used version: " . Hybrid_Auth::$version );
Hybrid_Logger::info( "Hybrid_Auth::initialize(). Hybrid_Auth called from: " . Hybrid_Auth::getCurrentUrl() );
Hybrid_Logger::debug( "Hybrid_Auth initialize. dump used config: ", serialize( $config ) );
Hybrid_Logger::debug( "Hybrid_Auth initialize. dump current session: ", serialize( $_SESSION ) );
Hybrid_Logger::info( "Hybrid_Auth initialize: check if any error is stored on the endpoint..." );
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_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 );
}
}
Hybrid_Logger::info( "Hybrid_Auth initialize: no error found. initialization succeed." );
// Endof initialize
}
// --------------------------------------------------------------------
/**
* Hybrid storage system accessor
*
* Users sessions are stored using HybridAuth storage system ( HybridAuth 2.0 handle PHP Session only) and can be acessed 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.
*/
public static function storage()
{
return Hybrid_Auth::$store;
}
// --------------------------------------------------------------------
/**
* Get hybridauth session data.
*/
function getSessionData()
{
return Hybrid_Auth::storage()->getSessionData();
}
// --------------------------------------------------------------------
/**
* restore hybridauth session data.
*/
function restoreSessionData( $sessiondata = NULL )
{
Hybrid_Auth::storage()->restoreSessionData( $sessiondata );
}
// --------------------------------------------------------------------
/**
* Try to authenticate the user with a given provider.
*
* If the user is already connected we just return and instance of provider adapter,
* ELSE, try to authenticate and authorize the user with the provider.
*
* $params is generally an array with required info in order for this provider and HybridAuth to work,
* like :
* 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
*/
public static function authenticate( $providerId, $params = NULL )
{
Hybrid_Logger::info( "Enter Hybrid_Auth::authenticate( $providerId )" );
// 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 );
$provider_adapter->login();
}
// 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 );
}
}
// --------------------------------------------------------------------
/**
* Return the adapter instance for an authenticated provider
*/
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
*/
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" );
Hybrid_Logger::debug( "Hybrid_Auth::setup( $providerId ), no params given. Trying to get the sotred 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( ! 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"] );
# instantiate a new IDProvider Adapter
$provider = new Hybrid_Provider_Adapter();
$provider->factory( $providerId, $params );
return $provider;
}
// --------------------------------------------------------------------
/**
* Check if the current user is connected to a given provider
*/
public static function isConnectedWith( $providerId )
{
return (bool) Hybrid_Auth::storage()->get( "hauth_session.{$providerId}.is_logged_in" );
}
// --------------------------------------------------------------------
/**
* Return array listing all authenticated providers
*/
public static function getConnectedProviders()
{
$idps = array();
foreach( Hybrid_Auth::$config["providers"] as $idpid => $params ){
if( Hybrid_Auth::isConnectedWith( $idpid ) ){
$idps[] = $idpid;
}
}
return $idps;
}
// --------------------------------------------------------------------
/**
* Return array listing all enabled providers as well as a flag if you are connected.
*/
public static function getProviders()
{
$idps = array();
foreach( Hybrid_Auth::$config["providers"] as $idpid => $params ){
if($params['enabled']) {
$idps[$idpid] = array( 'connected' => false );
if( Hybrid_Auth::isConnectedWith( $idpid ) ){
$idps[$idpid]['connected'] = true;
}
}
}
return $idps;
}
// --------------------------------------------------------------------
/**
* A generic function to logout all connected provider at once
*/
public static function logoutAllProviders()
{
$idps = Hybrid_Auth::getConnectedProviders();
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
*/
public static function redirect( $url, $mode = "PHP" )
{
Hybrid_Logger::info( "Enter Hybrid_Auth::redirect( $url, $mode )" );
if( $mode == "PHP" ){
header( "Location: $url" ) ;
}
elseif( $mode == "JS" ){
echo '<html>';
echo '<head>';
echo '<script type="text/javascript">';
echo 'function redirect(){ window.top.location.href="' . $url . '"; }';
echo '</script>';
echo '</head>';
echo '<body onload="redirect()">';
echo 'Redirecting, please wait...';
echo '</body>';
echo '</html>';
}
die();
}
// --------------------------------------------------------------------
/**
* Utility function, return the current url. TRUE to get $_SERVER['REQUEST_URI'], FALSE for $_SERVER['PHP_SELF']
*/
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://';
}
else {
$protocol = 'http://';
}
$url = $protocol . $_SERVER['SERVER_NAME'];
// use port if non default
$url .=
isset( $_SERVER['SERVER_PORT'] )
&&( ($protocol === 'http://' && $_SERVER['SERVER_PORT'] != 80) || ($protocol === 'https://' && $_SERVER['SERVER_PORT'] != 443) )
? ':' . $_SERVER['SERVER_PORT']
: '';
if( $request_uri ){
$url .= $_SERVER['REQUEST_URI'];
}
else{
$url .= $_SERVER['PHP_SELF'];
}
// return current url
return $url;
}
}

View File

@@ -0,0 +1,242 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Endpoint class
*
* Hybrid_Endpoint class provides a simple way to handle the OpenID and OAuth endpoint.
*/
class Hybrid_Endpoint {
public static $request = NULL;
public static $initDone = FALSE;
/**
* Process the current request
*
* $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) ){
// 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 );
}
Hybrid_Endpoint::$request = $_REQUEST;
}
// If windows_live_channel requested, we return our windows_live WRAP_CHANNEL_URL
if ( isset( Hybrid_Endpoint::$request["get"] ) && Hybrid_Endpoint::$request["get"] == "windows_live_channel" ) {
Hybrid_Endpoint::processWindowsLiveChannel();
}
// 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 openid_xrds requested, we return our XRDS document
if ( isset( Hybrid_Endpoint::$request["get"] ) && Hybrid_Endpoint::$request["get"] == "openid_xrds" ) {
Hybrid_Endpoint::processOpenidXRDS();
}
// If we get a hauth.start
if ( isset( Hybrid_Endpoint::$request["hauth_start"] ) && Hybrid_Endpoint::$request["hauth_start"] ) {
Hybrid_Endpoint::processAuthStart();
}
// Else if hauth.done
elseif ( isset( Hybrid_Endpoint::$request["hauth_done"] ) && Hybrid_Endpoint::$request["hauth_done"] ) {
Hybrid_Endpoint::processAuthDone();
}
// Else we advertise our XRDS document, something supposed to be done from the Realm URL page
else {
Hybrid_Endpoint::processOpenidRealm();
}
}
/**
* Process Windows Live channel request
*/
public static function processWindowsLiveChannel()
{
$output = file_get_contents( dirname(__FILE__) . "/resources/windows_live_channel.html" );
print $output;
die();
}
/**
* Process OpenID policy request
*/
public static function processOpenidPolicy()
{
$output = file_get_contents( dirname(__FILE__) . "/resources/openid_policy.html" );
print $output;
die();
}
/**
* Process OpenID XRDS request
*/
public static 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" )
);
print $output;
die();
}
/**
* Process OpenID realm request
*/
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" )
);
print $output;
die();
}
/**
* define:endpoint step 3.
*/
public static function processAuthStart()
{
Hybrid_Endpoint::authInit();
$provider_id = trim( strip_tags( Hybrid_Endpoint::$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!" );
header( "HTTP/1.0 404 Not Found" );
die( "You cannot access this page directly." );
}
# 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: Invalide parameter on hauth_start!" );
header( "HTTP/1.0 404 Not Found" );
die( "Invalide parameter! Please return to the login page and try again." );
}
try {
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 );
$hauth->returnToCallbackUrl();
}
die();
}
/**
* define:endpoint step 3.1 and 3.2
*/
public static function processAuthDone()
{
Hybrid_Endpoint::authInit();
$provider_id = trim( strip_tags( Hybrid_Endpoint::$request["hauth_done"] ) );
$hauth = Hybrid_Auth::setup( $provider_id );
if( ! $hauth ) {
Hybrid_Logger::error( "Endpoint: Invalide parameter on hauth_done!" );
$hauth->adapter->setUserUnconnected();
header("HTTP/1.0 404 Not Found");
die( "Invalide parameter! Please return to the login page and try again." );
}
try {
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 );
$hauth->adapter->setUserUnconnected();
}
Hybrid_Logger::info( "Endpoint: job done. retrun to callback url." );
$hauth->returnToCallbackUrl();
die();
}
public static function authInit()
{
// print_a($_SESSION);
if ( ! Hybrid_Endpoint::$initDone) {
Hybrid_Endpoint::$initDone = TRUE;
// Start a new session
if ( ! session_id() ){
session_start();
}
# Init Hybrid_Auth
try {
// Check if Hybrid_Auth session already exist
if ( ! isset( $_SESSION["HA::CONFIG"] ) ) {
header( "HTTP/1.0 404 Not Found" );
die( "You cannot access this page directly." );
}
Hybrid_Auth::initialize( unserialize( $_SESSION["HA::CONFIG"] ) );
}
catch ( Exception $e ){
Hybrid_Logger::error( "Endpoint: Error while trying to init Hybrid_Auth" );
header( "HTTP/1.0 404 Not Found" );
// print_a($_SESSION);
// echo "e=".$e;
die( "Oophs. Error!" );
}
}
}
}

View File

@@ -0,0 +1,84 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | 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
{
/**
* store error in session
*/
public static function setError( $message, $code = NULL, $trace = NULL, $previous = NULL )
{
Hybrid_Logger::info( "Enter Hybrid_Error::setError( $message )" );
Hybrid_Auth::storage()->set( "hauth_session.error.status" , 1 );
Hybrid_Auth::storage()->set( "hauth_session.error.message" , $message );
Hybrid_Auth::storage()->set( "hauth_session.error.code" , $code );
Hybrid_Auth::storage()->set( "hauth_session.error.trace" , $trace );
Hybrid_Auth::storage()->set( "hauth_session.error.previous", $previous );
}
/**
* clear the last error
*/
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" );
}
/**
* Checks to see if there is a an error.
*
* @return boolean True if there is an error.
*/
public static function hasError()
{
return (bool) Hybrid_Auth::storage()->get( "hauth_session.error.status" );
}
/**
* return error message
*/
public static function getErrorMessage()
{
return Hybrid_Auth::storage()->get( "hauth_session.error.message" );
}
/**
* return error code
*/
public static function getErrorCode()
{
return Hybrid_Auth::storage()->get( "hauth_session.error.code" );
}
/**
* return string detailled error backtrace as string.
*/
public static function getErrorTrace()
{
return Hybrid_Auth::storage()->get( "hauth_session.error.trace" );
}
/**
* @return string detailled error backtrace as string.
*/
public static function getErrorPrevious()
{
return Hybrid_Auth::storage()->get( "hauth_session.error.previous" );
}
}

View File

@@ -0,0 +1,68 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Debugging and Logging manager
*/
class Hybrid_Logger
{
function __construct()
{
// if debug mode is set to true, then check for the writable log file
if ( Hybrid_Auth::$config["debug_mode"] ){
if ( ! file_exists( Hybrid_Auth::$config["debug_file"] ) ){
throw new Exception( "'debug_mode' is set to 'true', but no log file path 'debug_file' given.", 1 );
}
if ( ! 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 );
}
}
}
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 info( $message )
{
if( Hybrid_Auth::$config["debug_mode"] ){
$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 error($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"],
"ERROR -- " . $_SERVER['REMOTE_ADDR'] . " -- " . $datetime . " -- " . $message . " -- " . print_r($object, true) . "\n",
FILE_APPEND
);
}
}
}

View File

@@ -0,0 +1,283 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Provider_Adapter is the basic class which Hybrid_Auth will use
* to connect users to a given provider.
*
* Basically Hybrid_Provider_Adapterwill create a bridge from your php
* application to the provider api.
*
* Hybrid_Auth will automatically load Hybrid_Provider_Adapter and create
* an instance of it for each authenticated provider.
*/
class Hybrid_Provider_Adapter
{
/* Provider ID (or unique name) */
public $id = NULL ;
/* Provider adapter specific config */
public $config = NULL ;
/* Provider adapter extra parameters */
public $params = NULL ;
/* Provider adapter wrapper path */
public $wrapper = NULL ;
/* Provider adapter instance */
public $adapter = NULL ;
// --------------------------------------------------------------------
/**
* 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
*/
function factory( $id, $params = NULL )
{
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 );
# check the IDp id
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 );
}
# check the IDp adapter is enabled
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"] ) ){
require_once $this->config["wrapper"]["path"];
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" ;
$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 );
return $this;
}
// --------------------------------------------------------------------
/**
* Hybrid_Provider_Adapter::login(), prepare the user session and the authentification request
* for index.php
*/
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." );
}
// 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" );
}
// make a fresh start
$this->logout();
# get hybridauth base url
$HYBRID_AUTH_URL_BASE = Hybrid_Auth::$config["base_url"];
# we make use of session_id() as storage hash to identify the current user
# using session_regenerate_id() will be a problem, but ..
$this->params["hauth_token"] = session_id();
# set request timestamp
$this->params["hauth_time"] = time();
# 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"]}";
# 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}";
Hybrid_Auth::storage()->set( "hauth_session.{$this->id}.hauth_return_to" , $this->params["hauth_return_to"] );
Hybrid_Auth::storage()->set( "hauth_session.{$this->id}.hauth_endpoint" , $this->params["login_done"] );
Hybrid_Auth::storage()->set( "hauth_session.{$this->id}.id_provider_params" , $this->params );
// store config to be used by the end point
$_SESSION["HA::CONFIG"] = serialize( Hybrid_Auth::$config );
// move on
Hybrid_Logger::debug( "Hybrid_Provider_Adapter::login( {$this->id} ), redirect the user to login_start URL.", $this->params );
Hybrid_Auth::redirect( $this->params["login_start"] );
}
// --------------------------------------------------------------------
/**
* let hybridauth forget all about the user for the current provider
*/
function logout()
{
$this->adapter->logout();
}
// --------------------------------------------------------------------
/**
* return true if the user is connected to the current provider
*/
public function isUserConnected()
{
return $this->adapter->isUserConnected();
}
// --------------------------------------------------------------------
/**
* handle :
* getUserProfile()
* getUserContacts()
* getUserActivity()
* setUserStatus()
*/
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 ( ! method_exists( $this->adapter, $name ) ){
throw new Exception( "Call to undefined function Hybrid_Providers_{$this->id}::$name()." );
}
if( count( $arguments ) ){
return $this->adapter->$name( $arguments[0] );
}
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
*/
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
);
}
// --------------------------------------------------------------------
/**
* Naive getter of the current connected IDp API client
*/
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 );
}
return $this->adapter->api;
}
// --------------------------------------------------------------------
/**
* redirect the user to hauth_return_to (the callback url)
*/
function returnToCallbackUrl()
{
// get the stored callback url
$callback_url = Hybrid_Auth::storage()->get( "hauth_session.{$this->id}.hauth_return_to" );
// remove some unneed'd 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" );
// back to home
Hybrid_Auth::redirect( $callback_url );
}
// --------------------------------------------------------------------
/**
* return the provider config by id
*/
function getConfigById( $id )
{
if( isset( Hybrid_Auth::$config["providers"][$id] ) ){
return Hybrid_Auth::$config["providers"][$id];
}
return NULL;
}
// --------------------------------------------------------------------
/**
* return the provider config by id; insensitive
*/
function getProviderCiId( $id )
{
foreach( Hybrid_Auth::$config["providers"] as $idpid => $params ){
if( strtolower( $idpid ) == strtolower( $id ) ){
return $idpid;
}
}
return NULL;
}
}

View File

@@ -0,0 +1,231 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Provider_Model provide a common interface for supported IDps on HybridAuth.
*
* Basically, each provider adapter has to define at least 4 methods:
* Hybrid_Providers_{provider_name}::initialize()
* Hybrid_Providers_{provider_name}::loginBegin()
* Hybrid_Providers_{provider_name}::loginFinish()
* Hybrid_Providers_{provider_name}::getUserProfile()
*
* HybridAuth also come with three others models
* Class Hybrid_Provider_Model_OpenID for providers that uses the OpenID 1 and 2 protocol.
* Class Hybrid_Provider_Model_OAuth1 for providers that uses the OAuth 1 protocol.
* Class Hybrid_Provider_Model_OAuth2 for providers that uses the OAuth 2 protocol.
*/
abstract class Hybrid_Provider_Model
{
/* IDp ID (or unique name) */
public $providerId = NULL;
/* specific provider adapter config */
public $config = NULL;
/* provider extra parameters */
public $params = NULL;
/* Endpoint URL for that provider */
public $endpoint = NULL;
/* Hybrid_User obj, represents the current loggedin user */
public $user = NULL;
/* the provider api client (optional) */
public $api = NULL;
/**
* common providers adapter constructor
*/
function __construct( $providerId, $config, $params = NULL )
{
# init the IDp adapter parameters, get them from the cache if possible
if( ! $params ){
$this->params = Hybrid_Auth::storage()->get( "hauth_session.$providerId.id_provider_params" );
}
else{
$this->params = $params;
}
// idp id
$this->providerId = $providerId;
// set HybridAuth endpoint for this provider
$this->endpoint = Hybrid_Auth::storage()->get( "hauth_session.$providerId.hauth_endpoint" );
// idp config
$this->config = $config;
// new user instance
$this->user = new Hybrid_User();
$this->user->providerId = $providerId;
// initialize the current provider adapter
$this->initialize();
Hybrid_Logger::debug( "Hybrid_Provider_Model::__construct( $providerId ) initialized. dump current adapter instance: ", serialize( $this ) );
}
// --------------------------------------------------------------------
/**
* IDp wrappers initializer
*
* The main job of wrappers initializer is to performs (depend on the IDp api client it self):
* - include some libs nedded by this provider,
* - check IDp key and secret,
* - set some needed parameters (stored in $this->params) by this IDp api client
* - create and setup an instance of the IDp api client on $this->api
*/
abstract protected function initialize();
// --------------------------------------------------------------------
/**
* begin login
*/
abstract protected function loginBegin();
// --------------------------------------------------------------------
/**
* finish login
*/
abstract protected function loginFinish();
// --------------------------------------------------------------------
/**
* generic logout, just erase current provider adapter stored data to let Hybrid_Auth all forget about it
*/
function logout()
{
Hybrid_Logger::info( "Enter [{$this->providerId}]::logout()" );
$this->clearTokens();
return TRUE;
}
// --------------------------------------------------------------------
/**
* grab the user profile from the IDp api client
*/
function getUserProfile()
{
Hybrid_Logger::error( "HybridAuth do not provide users contats 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
*/
function getUserContacts()
{
Hybrid_Logger::error( "HybridAuth do not provide users contats list for {$this->providerId} yet." );
throw new Exception( "Provider does not support this feature.", 8 );
}
// --------------------------------------------------------------------
/**
* return the user activity stream
*/
function getUserActivity( $stream )
{
Hybrid_Logger::error( "HybridAuth do not provide user's activity stream for {$this->providerId} yet." );
throw new Exception( "Provider does not support this feature.", 8 );
}
// --------------------------------------------------------------------
/**
* return the user activity stream
*/
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 true if the user is connected to the current provider
*/
public function isUserConnected()
{
return (bool) Hybrid_Auth::storage()->get( "hauth_session.{$this->providerId}.is_logged_in" );
}
// --------------------------------------------------------------------
/**
* set user to connected
*/
public function setUserConnected()
{
Hybrid_Logger::info( "Enter [{$this->providerId}]::setUserConnected()" );
Hybrid_Auth::storage()->set( "hauth_session.{$this->providerId}.is_logged_in", 1 );
}
// --------------------------------------------------------------------
/**
* set user to unconnected
*/
public function setUserUnconnected()
{
Hybrid_Logger::info( "Enter [{$this->providerId}]::setUserUnconnected()" );
Hybrid_Auth::storage()->set( "hauth_session.{$this->providerId}.is_logged_in", 0 );
}
// --------------------------------------------------------------------
/**
* get or set a token
*/
public function token( $token, $value = NULL )
{
if( $value === NULL ){
return Hybrid_Auth::storage()->get( "hauth_session.{$this->providerId}.token.$token" );
}
else{
Hybrid_Auth::storage()->set( "hauth_session.{$this->providerId}.token.$token", $value );
}
}
// --------------------------------------------------------------------
/**
* delete a stored token
*/
public function deleteToken( $token )
{
Hybrid_Auth::storage()->delete( "hauth_session.{$this->providerId}.token.$token" );
}
// --------------------------------------------------------------------
/**
* clear all existen tokens for this provider
*/
public function clearTokens()
{
Hybrid_Auth::storage()->deleteMatch( "hauth_session.{$this->providerId}." );
}
}

View File

@@ -0,0 +1,156 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* To implement an OAuth 1 based service provider, Hybrid_Provider_Model_OAuth1
* can be used to save the hassle of the authentication flow.
*
* Each class that inherit from Hybrid_Provider_Model_OAuth1 have to implemenent
* at least 2 methods:
* Hybrid_Providers_{provider_name}::initialize() to setup the provider api end-points urls
* Hybrid_Providers_{provider_name}::getUserProfile() to grab the user profile
*
* 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
{
public $request_tokens_raw = null; // request_tokens as recived from provider
public $access_tokens_raw = null; // access_tokens as recived from provider
/**
* try to get the error message from provider api
*/
function errorMessageByStatus( $code = null ) {
$http_status_codes = ARRAY(
200 => "OK: Success!",
304 => "Not Modified: There was no new data to return.",
400 => "Bad Request: The request was invalid.",
401 => "Unauthorized.",
403 => "Forbidden: The request is understood, but it has been refused.",
404 => "Not Found: The URI requested is invalid or the resource requested does not exists.",
406 => "Not Acceptable.",
500 => "Internal Server Error: Something is broken.",
502 => "Bad Gateway.",
503 => "Service Unavailable."
);
if( ! $code && $this->api )
$code = $this->api->http_code;
if( isset( $http_status_codes[ $code ] ) )
return $code . " " . $http_status_codes[ $code ];
}
// --------------------------------------------------------------------
/**
* adapter initializer
*/
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 );
}
// 2 - include OAuth lib and client
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" ) ){
$this->api = new OAuth1Client(
$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" ) ){
$this->api = new OAuth1Client(
$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"] );
}
}
// --------------------------------------------------------------------
/**
* begin login step
*/
function loginBegin()
{
$tokens = $this->api->requestToken( $this->endpoint );
// request tokens as recived from provider
$this->request_tokens_raw = $tokens;
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Authentification failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ), 5 );
}
if ( ! isset( $tokens["oauth_token"] ) ){
throw new Exception( "Authentification 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"] );
# redirect the user to the provider authentication url
Hybrid_Auth::redirect( $this->api->authorizeUrl( $tokens ) );
}
// --------------------------------------------------------------------
/**
* finish login step
*/
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( "Authentification failed! {$this->providerId} returned an invalid oauth verifier.", 5 );
}
// request an access token
$tokens = $this->api->accessToken( $oauth_verifier );
// access tokens as recived from provider
$this->access_tokens_raw = $tokens;
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Authentification 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( "Authentification failed! {$this->providerId} returned an invalid access token.", 5 );
}
// we no more need to store requet tokens
$this->deleteToken( "request_token" );
$this->deleteToken( "request_token_secret" );
// sotre access_token for later user
$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

@@ -0,0 +1,171 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* To implement an OAuth 2 based service provider, Hybrid_Provider_Model_OAuth2
* can be used to save the hassle of the authentication flow.
*
* Each class that inherit from Hybrid_Provider_Model_OAuth2 have to implemenent
* at least 2 methods:
* Hybrid_Providers_{provider_name}::initialize() to setup the provider api end-points urls
* Hybrid_Providers_{provider_name}::getUserProfile() to grab the user profile
*
* 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
{
// default permissions
public $scope = "";
/**
* try to get the error message from provider api
*/
function errorMessageByStatus( $code = null ) {
$http_status_codes = ARRAY(
200 => "OK: Success!",
304 => "Not Modified: There was no new data to return.",
400 => "Bad Request: The request was invalid.",
401 => "Unauthorized.",
403 => "Forbidden: The request is understood, but it has been refused.",
404 => "Not Found: The URI requested is invalid or the resource requested does not exists.",
406 => "Not Acceptable.",
500 => "Internal Server Error: Something is broken.",
502 => "Bad Gateway.",
503 => "Service Unavailable."
);
if( ! $code && $this->api )
$code = $this->api->http_code;
if( isset( $http_status_codes[ $code ] ) )
return $code . " " . $http_status_codes[ $code ];
}
// --------------------------------------------------------------------
/**
* 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 );
}
// override requested scope
if( isset( $this->config["scope"] ) && ! empty( $this->config["scope"] ) ){
$this->scope = $this->config["scope"];
}
// include OAuth2 client
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 );
// 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" );
}
}
// --------------------------------------------------------------------
/**
* begin login step
*/
function loginBegin()
{
// redirect the user to the provider authentication url
Hybrid_Auth::redirect( $this->api->authorizeUrl( array( "scope" => $this->scope ) ) );
}
// --------------------------------------------------------------------
/**
* finish login step
*/
function loginFinish()
{
$error = (array_key_exists('error',$_REQUEST))?$_REQUEST['error']:"";
// check for errors
if ( $error ){
throw new Exception( "Authentification failed! {$this->providerId} returned an error: $error", 5 );
}
// try to authenicate user
$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 );
}
// check if authenticated
if ( ! $this->api->access_token ){
throw new Exception( "Authentification 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 );
// set user connected locally
$this->setUserConnected();
}
function refreshToken()
{
// have an access token?
if( $this->api->access_token ){
// have to refresh?
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( ! 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 );
}
// set new access_token
$this->api->access_token = $response->access_token;
if( isset( $response->refresh_token ) )
$this->api->refresh_token = $response->refresh_token;
if( isset( $response->expires_in ) ){
$this->api->access_token_expires_in = $response->expires_in;
// even given by some idp, we should calculate this
$this->api->access_token_expires_at = time() + $response->expires_in;
}
}
}
// re store tokens
$this->token( "access_token" , $this->api->access_token );
$this->token( "refresh_token", $this->api->refresh_token );
$this->token( "expires_in" , $this->api->access_token_expires_in );
$this->token( "expires_at" , $this->api->access_token_expires_at );
}
}
}

View File

@@ -0,0 +1,169 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* To implement an OpenID based service provider, Hybrid_Provider_Model_OpenID
* can be used to save the hassle of the authentication flow.
*
* Each class that inherit from Hybrid_Provider_Model_OAuth2 have only to define
* the provider identifier : <code>public $openidIdentifier = ""; </code>
*
* 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
{
/* Openid provider identifier */
public $openidIdentifier = "";
// --------------------------------------------------------------------
/**
* adapter initializer
*/
function initialize()
{
if( isset( $this->params["openid_identifier"] ) ){
$this->openidIdentifier = $this->params["openid_identifier"];
}
// include LightOpenID lib
require_once Hybrid_Auth::$config["path_libraries"] . "OpenID/LightOpenID.php";
$this->api = new LightOpenID( parse_url( Hybrid_Auth::$config["base_url"], PHP_URL_HOST) );
}
// --------------------------------------------------------------------
/**
* begin login step
*/
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' ,
'contact/postalCode/home',
'contact/city/home' ,
'contact/country/home' ,
'media/image/default' ,
);
# redirect the user to the provider authentication url
Hybrid_Auth::redirect( $this->api->authUrl() );
}
// --------------------------------------------------------------------
/**
* finish login step
*/
function loginFinish()
{
# if user don't garant acess of their data to your site, halt with an Exception
if( $this->api->mode == 'cancel'){
throw new Exception( "Authentification failed! User has canceled authentication!", 5 );
}
# if something goes wrong
if( ! $this->api->validate() ){
throw new Exception( "Authentification failed. Invalid request recived!", 5 );
}
# fetch recived user data
$response = $this->api->getAttributes();
# sotre 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->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( ! $this->user->profile->displayName ) {
$this->user->profile->displayName = trim( $this->user->profile->lastName . " " . $this->user->profile->firstName );
}
if( isset( $response['namePerson/friendly'] ) && ! empty( $response['namePerson/friendly'] ) && ! $this->user->profile->displayName ) {
$this->user->profile->displayName = (array_key_exists("namePerson/friendly",$response))?$response["namePerson/friendly"]:"" ;
}
if( isset( $response['birthDate'] ) && ! empty( $response['birthDate'] ) && ! $this->user->profile->birthDay ) {
list( $birthday_year, $birthday_month, $birthday_day ) = (array_key_exists('birthDate',$response))?$response['birthDate']:"";
$this->user->profile->birthDay = (int) $birthday_day;
$this->user->profile->birthMonth = (int) $birthday_month;
$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->gender == "f" ){
$this->user->profile->gender = "female";
}
if( $this->user->profile->gender == "m" ){
$this->user->profile->gender = "male";
}
// set user as logged in
$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 );
}
// --------------------------------------------------------------------
/**
* load the user profile from the IDp api client
*/
function getUserProfile()
{
// try to get the user profile from stored data
$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 );
}
return $this->user->profile;
}
}

View File

@@ -0,0 +1,16 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | 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
{
var $openidIdentifier = "http://openid.aol.com/";
}

View File

@@ -0,0 +1,259 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_Facebook provider adapter based on OAuth2 protocol
*
* Hybrid_Providers_Facebook use the Facebook PHP SDK created by Facebook
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Facebook.html
*/
class Hybrid_Providers_Facebook extends Hybrid_Provider_Model
{
// default permissions, and alot 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, offline_access, read_stream, publish_stream, read_friendlists";
public $display = "page";
/**
* IDp wrappers 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 );
}
// override requested scope
if( isset( $this->config["scope"] ) && ! empty( $this->config["scope"] ) ){
$this->scope = $this->config["scope"];
}
// override requested display
if( isset( $this->config["display"] ) && ! empty( $this->config["display"] ) ){
$this->display = $this->config["display"];
}
if ( ! class_exists('FacebookApiException') ) {
require_once Hybrid_Auth::$config["path_libraries"] . "Facebook/base_facebook.php";
require_once Hybrid_Auth::$config["path_libraries"] . "Facebook/facebook.php";
}
$this->api = new Facebook( ARRAY( 'appId' => $this->config["keys"]["id"], 'secret' => $this->config["keys"]["secret"] ) );
$this->api->getUser();
}
/**
* begin login step
*
* simply call Facebook::require_login().
*/
function loginBegin()
{
// get the login url
$url = $this->api->getLoginUrl( array( 'scope' => $this->scope, 'display' => $this->display, 'redirect_uri' => $this->endpoint ) );
// redirect to facebook
Hybrid_Auth::redirect( $url );
}
/**
* finish login step
*/
function loginFinish()
{
// in case we get error_reason=user_denied&error=access_denied
if ( isset( $_REQUEST['error'] ) && $_REQUEST['error'] == "access_denied" ){
throw new Exception( "Authentification failed! The user denied your request.", 5 );
}
// try to get the UID of the connected user from fb, should be > 0
if ( ! $this->api->getUser() ){
throw new Exception( "Authentification failed! {$this->providerId} returned an invalide user id.", 5 );
}
// set user as logged in
$this->setUserConnected();
// try to detect the access token for facebook
if( isset( $_SESSION["fb_" . $this->api->getAppId() . "_access_token" ] ) ){
$this->token( "access_token", $_SESSION["fb_" . $this->api->getAppId() . "_access_token" ] );
}
}
/**
* logout
*/
function logout()
{
$this->api->destroySession();
parent::logout();
}
/**
* load the user profile from the IDp api client
*/
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 );
}
// if the provider identifier is not recived, 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 );
}
# store the user profile.
$this->user->profile->identifier = (array_key_exists('id',$data))?$data['id']:"";
$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?type=square";
$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->description = (array_key_exists('bio',$data))?$data['bio']:"";
$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"]:"";
if( array_key_exists('birthday',$data) ) {
list($birthday_month, $birthday_day, $birthday_year) = explode( "/", $data['birthday'] );
$this->user->profile->birthDay = (int) $birthday_day;
$this->user->profile->birthMonth = (int) $birthday_month;
$this->user->profile->birthYear = (int) $birthday_year;
}
return $this->user->profile;
}
/**
* load the user contacts
*/
function getUserContacts()
{
try{
$response = $this->api->api('/me/friends');
}
catch( FacebookApiException $e ){
throw new Exception( "User contacts request failed! {$this->providerId} returned an error: $e" );
}
if( ! $response || ! count( $response["data"] ) ){
return ARRAY();
}
$contacts = ARRAY();
foreach( $response["data"] 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 = "https://www.facebook.com/profile.php?id=" . $uc->identifier;
$uc->photoURL = "https://graph.facebook.com/" . $uc->identifier . "/picture?type=square";
$contacts[] = $uc;
}
return $contacts;
}
/**
* update user status
*/
function setUserStatus( $status )
{
$parameters = array();
if( is_array( $status ) ){
$parameters = $status;
}
else{
$parameters["message"] = $status;
}
try{
$response = $this->api->api( "/me/feed", "post", $parameters );
}
catch( FacebookApiException $e ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error: $e" );
}
}
/**
* load the user latest activity
* - timeline : all the stream
* - me : the user activity only
*/
function getUserActivity( $stream )
{
try{
if( $stream == "me" ){
$response = $this->api->api( '/me/feed' );
}
else{
$response = $this->api->api('/me/home');
}
}
catch( FacebookApiException $e ){
throw new Exception( "User activity stream request failed! {$this->providerId} returned an error: $e" );
}
if( ! $response || ! count( $response['data'] ) ){
return ARRAY();
}
$activities = ARRAY();
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"]):"";
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( 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 ) ){
$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";
$activities[] = $ua;
}
}
return $activities;
}
}

View File

@@ -0,0 +1,56 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_Foursquare provider adapter based on OAuth2 protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Foursquare.html
*/
class Hybrid_Providers_Foursquare extends Hybrid_Provider_Model_OAuth2
{
/**
* IDp wrappers initializer
*/
function initialize()
{
parent::initialize();
// Provider apis end-points
$this->api->api_base_url = "https://api.foursquare.com/v2/";
$this->api->authorize_url = "https://foursquare.com/oauth2/authenticate";
$this->api->token_url = "https://foursquare.com/oauth2/access_token";
$this->api->sign_token_name = "oauth_token";
}
/**
* load the user profile from the IDp api client
*/
function getUserProfile()
{
$data = $this->api->api( "users/self" );
if ( ! isset( $data->response->user->id ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalide response.", 6 );
}
$data = $data->response->user;
$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;
$this->user->profile->profileURL = $data->canonicalUrl;
$this->user->profile->gender = $data->gender;
$this->user->profile->city = $data->homeCity;
$this->user->profile->email = $data->contact->email;
$this->user->profile->emailVerified = $data->contact->email;
return $this->user->profile;
}
}

View File

@@ -0,0 +1,105 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | 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
{
// default permissions
public $scope = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.google.com/m8/feeds/";
/**
* IDp wrappers initializer
*/
function initialize()
{
parent::initialize();
// Provider api end-points
$this->api->authorize_url = "https://accounts.google.com/o/oauth2/auth";
$this->api->token_url = "https://accounts.google.com/o/oauth2/token";
$this->api->token_info_url = "https://www.googleapis.com/oauth2/v1/tokeninfo";
}
/**
* begin login step
*/
function loginBegin()
{
Hybrid_Auth::redirect( $this->api->authorizeUrl( array( "scope" => $this->scope, "access_type" => "offline" ) ) );
}
/**
* load the user profile from the IDp api client
*/
function getUserProfile()
{
// refresh tokens if needed
$this->refreshToken();
// ask google api for user infos
$response = $this->api->api( "https://www.googleapis.com/oauth2/v1/userinfo" );
if ( ! isset( $response->id ) || isset( $response->error ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalide response.", 6 );
}
$this->user->profile->identifier = (property_exists($response,'id'))?$response->id:"";
$this->user->profile->firstName = (property_exists($response,'given_name'))?$response->given_name:"";
$this->user->profile->lastName = (property_exists($response,'family_name'))?$response->family_name:"";
$this->user->profile->displayName = (property_exists($response,'name'))?$response->name:"";
$this->user->profile->photoURL = (property_exists($response,'picture'))?$response->picture:"";
$this->user->profile->profileURL = "https://profiles.google.com/" . $this->user->profile->identifier;
$this->user->profile->gender = (property_exists($response,'gender'))?$response->gender:"";
$this->user->profile->email = (property_exists($response,'email'))?$response->email:"";
$this->user->profile->emailVerified = (property_exists($response,'email'))?$response->email:"";
$this->user->profile->language = (property_exists($response,'locale'))?$response->locale:"";
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;
}
return $this->user->profile;
}
/**
* load the user (Gmail) contacts
* ..toComplete
*/
function getUserContacts()
{
// refresh tokens if needed
$this->refreshToken();
$response = $this->api->api( "https://www.google.com/m8/feeds/contacts/default/full?alt=json" );
if( ! $response ){
return ARRAY();
}
$contacts = ARRAY();
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;
$contacts[] = $uc;
}
return $contacts;
}
}

View File

@@ -0,0 +1,40 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_Google OpenID based
*
* Provided as a way to keep backward compatibility for Google OpenID based on HybridAuth <= 2.0.8
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Google.html
*/
/**
* To replace the default google adapter, we should use this config instead:
*
* "Google" => array (
* "enabled" => true,
* "wrapper" => array( "path" => "Providers/GoogleOpenID.php", "class" => "Hybrid_Providers_Google" )
* )
*/
class Hybrid_Providers_Google extends Hybrid_Provider_Model_OpenID
{
var $openidIdentifier = "https://www.google.com/accounts/o8/id";
/**
* finish login step
*/
function loginFinish()
{
parent::loginFinish();
$this->user->profile->emailVerified = $this->user->profile->email;
// restore the user profile
Hybrid_Auth::storage()->set( "hauth_session.{$this->providerId}.user", $this->user );
}
}

View File

@@ -0,0 +1,244 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_LinkedIn provider adapter based on OAuth1 protocol
*
* Hybrid_Providers_LinkedIn use linkedinPHP library created by fiftyMission Inc.
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_LinkedIn.html
*/
class Hybrid_Providers_LinkedIn extends Hybrid_Provider_Model
{
/**
* IDp wrappers initializer
*/
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 );
}
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 ) );
if( $this->token( "access_token_linkedin" ) ){
$this->api->setTokenAccess( $this->token( "access_token_linkedin" ) );
}
}
/**
* begin login step
*/
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'] );
# redirect user to LinkedIn authorisation web page
Hybrid_Auth::redirect( LINKEDIN::_URL_AUTH . $response['linkedin']['oauth_token'] );
}
else{
throw new Exception( "Authentification failed! {$this->providerId} returned an invalid Token.", 5 );
}
}
/**
* finish login step
*/
function loginFinish()
{
$oauth_token = $_REQUEST['oauth_token'];
$oauth_verifier = $_REQUEST['oauth_verifier'];
if ( ! $oauth_verifier ){
throw new Exception( "Authentification failed! {$this->providerId} returned an invalid Token.", 5 );
}
$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( "Authentification failed! {$this->providerId} returned an invalid Token.", 5 );
}
}
/**
* load the user profile from the IDp api client
*/
function getUserProfile()
{
try{
// http://developer.linkedin.com/docs/DOC-1061
$response = $this->api->profile('~:(id,first-name,last-name,public-profile-url,picture-url,date-of-birth,phone-numbers,summary)');
}
catch( LinkedInException $e ){
throw new Exception( "User profile request failed! {$this->providerId} returned an error: $e", 6 );
}
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 invalide xml 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->photoURL = (string) $data->{'picture-url'};
$this->user->profile->profileURL = (string) $data->{'public-profile-url'};
$this->user->profile->description = (string) $data->{'summary'};
$this->user->profile->phone = (string) $data->{'phone-numbers'}->{'phone-number'}->{'phone-number'};
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 );
}
}
/**
* load the user contacts
*/
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" );
}
if( ! $response || ! $response['success'] ){
return ARRAY();
}
$connections = new SimpleXMLElement( $response['linkedin'] );
$contacts = ARRAY();
foreach( $connections->person as $connection ) {
$uc = new Hybrid_User_Contact();
$uc->identifier = (string) $connection->id;
$uc->displayName = (string) $connection->{'last-name'} . " " . $connection->{'first-name'};
$uc->profileURL = (string) $connection->{'public-profile-url'};
$uc->photoURL = (string) $connection->{'picture-url'};
$uc->description = (string) $connection->{'summary'};
$contacts[] = $uc;
}
return $contacts;
}
/**
* update user 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
}
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" );
}
if ( ! $response || ! $response['success'] )
{
throw new Exception( "Update user status update failed! {$this->providerId} returned an error." );
}
}
/**
* load the user latest activity
* - timeline : all the stream
* - me : the user activity only
*/
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' );
}
}
catch( LinkedInException $e ){
throw new Exception( "User activity stream request failed! {$this->providerId} returned an error: $e" );
}
if( ! $response || ! $response['success'] ){
return ARRAY();
}
$updates = new SimpleXMLElement( $response['linkedin'] );
$activities = ARRAY();
foreach( $updates->update as $update ) {
$person = $update->{'update-content'}->person;
$share = $update->{'update-content'}->person->{'current-share'};
$ua = new Hybrid_User_Activity();
$ua->id = (string) $update->id;
$ua->date = (string) $update->timestamp;
$ua->text = (string) $share->{'comment'};
$ua->user->identifier = (string) $person->id;
$ua->user->displayName = (string) $person->{'first-name'} . ' ' . $person->{'last-name'};
$ua->user->profileURL = (string) $person->{'site-standard-profile-request'}->url;
$ua->user->photoURL = NULL;
$activities[] = $ua;
}
return $activities;
}
}

View File

@@ -0,0 +1,117 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_Live provider adapter based on OAuth1 protocol
*
* Hybrid_Providers_Live use OAuthWrapHandler class provided by microsoft
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Live.html
*/
class Hybrid_Providers_Live extends Hybrid_Provider_Model
{
/**
* IDp wrappers 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 );
}
// Application Specific Globals
define( 'WRAP_CLIENT_ID' , $this->config["keys"]["id"] );
define( 'WRAP_CLIENT_SECRET', $this->config["keys"]["secret"] );
define( 'WRAP_CALLBACK' , $this->endpoint );
define( 'WRAP_CHANNEL_URL' , Hybrid_Auth::$config["base_url"] . "?get=windows_live_channel" );
// Live URLs required for making requests.
define('WRAP_CONSENT_URL' , 'https://consent.live.com/Connect.aspx');
define('WRAP_ACCESS_URL' , 'https://consent.live.com/AccessToken.aspx');
define('WRAP_REFRESH_URL' , 'https://consent.live.com/RefreshToken.aspx');
require_once Hybrid_Auth::$config["path_libraries"] . "WindowsLive/OAuthWrapHandler.php";
$this->api = new OAuthWrapHandler();
}
/**
* begin login step
*/
function loginBegin()
{
$this->api->ExpireCookies();
Hybrid_Auth::redirect( WRAP_CONSENT_URL . "?wrap_client_id=" . WRAP_CLIENT_ID . "&wrap_callback=" . urlencode( WRAP_CALLBACK ) . "&wrap_scope=WL_Profiles.View" );
}
/**
* finish login step
*/
function loginFinish()
{
$response = $this->api->ProcessRequest();
if ( ! isset( $response['c_uid'] ) || ! isset( $response['c_accessToken'] ) ){
throw new Exception( "Authentification failed! {$this->providerId} returned an invalid Token.", 5 );
}
// set user as logged in
$this->setUserConnected();
# store access token
$this->token( "access_token", $response['c_accessToken'] );
# store the user id.
$this->token( "user_id", $response['c_uid'] );
}
/**
* load the user profile from the IDp api client
*/
function getUserProfile()
{
try{
$access_token = $this->token( "access_token" );
$user_id = $this->token( "user_id" );
$info_url = 'http://apis.live.net/V4.1/cid-'. $user_id .'/Profiles/1-' . $user_id;
$response = $this->api->GET( $info_url, false, $access_token );
$response = json_decode( $response );
}
catch( Exception $e ){
throw new Exception( "User profile request failed! {$this->providerId} returned an error while requesting the user profile.", 6 );
}
if ( ! is_object( $response ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid user data.", 6 );
}
$this->user->profile->identifier = $user_id;
$this->user->profile->firstName = (string) $response->FirstName;
$this->user->profile->lastName = (string) $response->LastName;
$this->user->profile->profileURL = (string) $response->UxLink;
$this->user->profile->gender = (string) $response->Gender;
$this->user->profile->email = (string) $response->Emails[0]->Address;
$this->user->profile->displayName = trim( $this->user->profile->firstName . " " . $this->user->profile->lastName );
if( $this->user->profile->gender == 1 ){
$this->user->profile->gender = "female";
}
elseif( $this->user->profile->gender == 2 ){
$this->user->profile->gender = "male";
}
else{
$this->user->profile->gender = "";
}
return $this->user->profile;
}
}

View File

@@ -0,0 +1,164 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_MySpace provider adapter based on OAuth1 protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_MySpace.html
*/
class Hybrid_Providers_MySpace extends Hybrid_Provider_Model_OAuth1
{
/**
* IDp wrappers initializer
*/
function initialize()
{
parent::initialize();
// Provider api end-points
$this->api->api_endpoint_url = "http://api.myspace.com/v1/";
$this->api->authorize_url = "http://api.myspace.com/authorize";
$this->api->request_token_url = "http://api.myspace.com/request_token";
$this->api->access_token_url = "http://api.myspace.com/access_token";
}
/**
* get the connected uid from myspace api
*/
public function getCurrentUserId()
{
$response = $this->api->get( 'http://api.myspace.com/v1/user.json' );
if ( ! isset( $response->userId ) ){
throw new Exception( "User id request failed! {$this->providerId} returned an invalide response." );
}
return $response->userId;
}
/**
* load the user profile from the IDp api client
*/
function getUserProfile()
{
$userId = $this->getCurrentUserId();
$data = $this->api->get( 'http://api.myspace.com/v1/users/' . $userId . '/profile.json' );
if ( ! is_object( $data ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalide response.", 6 );
}
$this->user->profile->identifier = $userId;
$this->user->profile->displayName = $data->basicprofile->name;
$this->user->profile->description = $data->aboutme;
$this->user->profile->gender = $data->basicprofile->gender;
$this->user->profile->photoURL = $data->basicprofile->image;
$this->user->profile->profileURL = $data->basicprofile->webUri;
$this->user->profile->age = $data->age;
$this->user->profile->country = $data->country;
$this->user->profile->region = $data->region;
$this->user->profile->city = $data->city;
$this->user->profile->zip = $data->postalcode;
return $this->user->profile;
}
/**
* load the user contacts
*/
function getUserContacts()
{
$userId = $this->getCurrentUserId();
$response = $this->api->get( "http://api.myspace.com/v1/users/" . $userId . "/friends.json" );
if ( ! is_object( $response ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalide response.", 6 );
}
$contacts = ARRAY();
foreach( $response->Friends as $item ){
$uc = new Hybrid_User_Contact();
$uc->identifier = $item->userId;
$uc->displayName = $item->name;
$uc->profileURL = $item->webUri;
$uc->photoURL = $item->image;
$uc->description = $item->status;
$contacts[] = $uc;
}
return $contacts;
}
/**
* update user status
*/
function setUserStatus( $status )
{
// crappy myspace... gonna see this asaic
$userId = $this->getCurrentUserId();
$parameters = array( 'status' => $status );
$response = $this->api->api( "http://api.myspace.com/v1/users/" . $userId . "/status", 'PUT', $parameters );
// 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 ) );
}
}
/**
* load the user latest activity
* - timeline : all the stream
* - me : the user activity only
*/
function getUserActivity( $stream )
{
$userId = $this->getCurrentUserId();
if( $stream == "me" ){
$response = $this->api->get( "http://api.myspace.com/v1/users/" . $userId . "/status.json" );
}
else{
$response = $this->api->get( "http://api.myspace.com/v1/users/" . $userId . "/friends/status.json" );
}
if ( ! is_object( $response ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalide response.", 6 );
}
$activities = ARRAY();
if( $stream == "me" ){
// todo
}
else{
foreach( $response->FriendsStatus as $item ){
$ua = new Hybrid_User_Activity();
$ua->id = $item->statusId;
$ua->date = NULL; // to find out!!
$ua->text = $item->status;
$ua->user->identifier = $item->user->userId;
$ua->user->displayName = $item->user->name;
$ua->user->profileURL = $item->user->uri;
$ua->user->photoURL = $item->user->image;
$activities[] = $ua;
}
}
return $activities;
}
}

View File

@@ -0,0 +1,15 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | 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
{
}

View File

@@ -0,0 +1,165 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | 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
*/
function initialize()
{
parent::initialize();
// Provider api end-points
$this->api->api_base_url = "https://api.twitter.com/1/";
$this->api->authorize_url = "https://api.twitter.com/oauth/authenticate";
$this->api->request_token_url = "https://api.twitter.com/oauth/request_token";
$this->api->access_token_url = "https://api.twitter.com/oauth/access_token";
$this->api->curl_auth_header = false;
}
/**
* load the user profile from the IDp api client
*/
function getUserProfile()
{
$response = $this->api->get( 'account/verify_credentials.json' );
// 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 ( ! is_object( $response ) || ! isset( $response->id ) ){
throw new Exception( "User profile request failed! {$this->providerId} api returned an invalid 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'))?$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:"";
return $this->user->profile;
}
/**
* load the user contacts
*/
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( ! $response || ! count( $response->ids ) ){
return ARRAY();
}
// 75 id per time should be okey
$contactsids = array_chunk ( $response->ids, 75 );
$contacts = ARRAY();
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( $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:"";
$contacts[] = $uc;
}
}
}
return $contacts;
}
/**
* update user status
*/
function setUserStatus( $status )
{
$parameters = array( 'status' => $status );
$response = $this->api->post( 'statuses/update.json', $parameters );
// 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 ) );
}
}
/**
* load the user latest activity
* - timeline : all the stream
* - me : the user activity only
*
* by default return the timeline
*/
function getUserActivity( $stream )
{
if( $stream == "me" ){
$response = $this->api->get( 'statuses/user_timeline.json' );
}
else{
$response = $this->api->get( 'statuses/home_timeline.json' );
}
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "User activity stream request failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
if( ! $response ){
return ARRAY();
}
$activities = ARRAY();
foreach( $response as $item ){
$ua = new Hybrid_User_Activity();
$ua->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:"";
$activities[] = $ua;
}
return $activities;
}
}

View File

@@ -0,0 +1,32 @@
<?php
//!! planned to be replaced Y! openid by the oauth1 adapter soon
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_Yahoo provider adapter based on OAuth1 protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_Yahoo.html
*/
class Hybrid_Providers_Yahoo extends Hybrid_Provider_Model_OpenID
{
var $openidIdentifier = "https://open.login.yahooapis.com/openid20/www.yahoo.com/xrds";
/**
* finish login step
*/
function loginFinish()
{
parent::loginFinish();
$this->user->profile->emailVerified = $this->user->profile->email;
// restore the user profile
Hybrid_Auth::storage()->set( "hauth_session.{$this->providerId}.user", $this->user );
}
}

View File

@@ -0,0 +1,74 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* HybridAuth storage manager
*/
class Hybrid_Storage
{
function __construct()
{
if( ! session_id() ){
throw new Exception( "Hybriauth require the use of 'session_start()' at the start of your script", 1 );
}
}
public function get($key, $expiration = false)
{
$key = strtolower( $key );
if( isset( $_SESSION["HA::STORE"][$key] ) ){
return unserialize( $_SESSION["HA::STORE"][$key] );
}
return NULL;
}
public function set( $key, $value )
{
$key = strtolower( $key );
$_SESSION["HA::STORE"][$key] = serialize( $value );
}
function clear()
{
$_SESSION["HA::STORE"] = ARRAY();
}
function delete($key)
{
$key = strtolower( $key );
if( isset( $_SESSION["HA::STORE"][$key] ) ){
unset( $_SESSION["HA::STORE"][$key] );
}
}
function deleteMatch($key)
{
$key = strtolower( $key );
if( isset( $_SESSION["HA::STORE"] ) && count( $_SESSION["HA::STORE"] ) ) {
foreach( $_SESSION["HA::STORE"] as $k => $v ){
if( strstr( $k, $key ) ){
unset( $_SESSION["HA::STORE"][ $k ] );
}
}
}
}
function getSessionData()
{
return serialize( $_SESSION["HA::STORE"] );
}
function restoreSessionData( $sessiondata = NULL )
{
$_SESSION["HA::STORE"] = unserialize( $sessiondata );
}
}

View File

@@ -0,0 +1,31 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* The Hybrid_User class represents the current loggedin user
*/
class Hybrid_User
{
/* The ID (name) of the connected provider */
public $providerId = NULL;
/* timestamp connection to the provider */
public $timestamp = NULL;
/* user profile, containts the list of fields available in the normalized user profile structure used by HybridAuth. */
public $profile = NULL;
/**
* inisialize the user object,
*/
function __construct()
{
$this->timestamp = time();
$this->profile = new Hybrid_User_Profile();
}
}

View File

@@ -0,0 +1,39 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_User_Activity
*
* used to provider the connected user activity stream on a standardized structure across supported social apis.
*
* http://hybridauth.sourceforge.net/userguide/Profile_Data_User_Activity.html
*/
class Hybrid_User_Activity
{
/* activity id on the provider side, usually given as integer */
public $id = NULL;
/* activity date of creation */
public $date = NULL;
/* activity content as a string */
public $text = NULL;
/* user who created the activity */
public $user = NULL;
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;
}
}

View File

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

View File

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

View File

@@ -0,0 +1,10 @@
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>

View File

@@ -0,0 +1,78 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
// ----------------------------------------------------------------------------------------
// HybridAuth Config file: http://hybridauth.sourceforge.net/userguide/Configuration.html
// ----------------------------------------------------------------------------------------
return
array(
"base_url" => "#GLOBAL_HYBRID_AUTH_URL_BASE#",
"providers" => array (
// openid providers
"OpenID" => array (
"enabled" => #OPENID_ADAPTER_STATUS#
),
"Yahoo" => array (
"enabled" => #YAHOO_ADAPTER_STATUS#
),
"AOL" => array (
"enabled" => #AOL_ADAPTER_STATUS#
),
"Google" => array (
"enabled" => #GOOGLE_ADAPTER_STATUS#,
"keys" => array ( "id" => "#GOOGLE_APPLICATION_APP_ID#", "secret" => "#GOOGLE_APPLICATION_SECRET#" ),
"scope" => ""
),
"Facebook" => array (
"enabled" => #FACEBOOK_ADAPTER_STATUS#,
"keys" => array ( "id" => "#FACEBOOK_APPLICATION_APP_ID#", "secret" => "#FACEBOOK_APPLICATION_SECRET#" ),
// A comma-separated list of permissions you want to request from the user. See the Facebook docs for a full list of available permissions: http://developers.facebook.com/docs/reference/api/permissions.
"scope" => "",
// The display context to show the authentication page. Options are: page, popup, iframe, touch and wap. Read the Facebook docs for more details: http://developers.facebook.com/docs/reference/dialogs#display. Default: page
"display" => ""
),
"Twitter" => array (
"enabled" => #TWITTER_ADAPTER_STATUS#,
"keys" => array ( "key" => "#TWITTER_APPLICATION_KEY#", "secret" => "#TWITTER_APPLICATION_SECRET#" )
),
// windows live
"Live" => array (
"enabled" => #LIVE_ADAPTER_STATUS#,
"keys" => array ( "id" => "#LIVE_APPLICATION_APP_ID#", "secret" => "#LIVE_APPLICATION_SECRET#" )
),
"MySpace" => array (
"enabled" => #MYSPACE_ADAPTER_STATUS#,
"keys" => array ( "key" => "#MYSPACE_APPLICATION_KEY#", "secret" => "#MYSPACE_APPLICATION_SECRET#" )
),
"LinkedIn" => array (
"enabled" => #LINKEDIN_ADAPTER_STATUS#,
"keys" => array ( "key" => "#LINKEDIN_APPLICATION_KEY#", "secret" => "#LINKEDIN_APPLICATION_SECRET#" )
),
"Foursquare" => array (
"enabled" => #FOURSQUARE_ADAPTER_STATUS#,
"keys" => array ( "id" => "#FOURSQUARE_APPLICATION_APP_ID#", "secret" => "#FOURSQUARE_APPLICATION_SECRET#" )
),
),
// if you want to enable logging, set 'debug_mode' to true then provide a writable file by the web server on "debug_file"
"debug_mode" => false,
"debug_file" => "",
);

View File

@@ -0,0 +1,10 @@
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>

View File

@@ -0,0 +1,10 @@
<html>
<head>
<title>OpenID Policy</title>
</head>
<body>
<!--
Set here your OpenID Policy,
-->
</body>
</html>

View File

@@ -0,0 +1,13 @@
<html>
<head>
<title>HybridAuth Endpoint</title>
<meta name="robots" content="NOINDEX, NOFOLLOW">
<meta http-equiv="X-XRDS-Location" content="{X_XRDS_LOCATION}" />
</head>
<body>
<h3 style="margin-bottom: 2px;">HybridAuth</h3>
Open Source Social Sign On PHP Library.
<br />
<a href="http://hybridauth.sourceforge.net/" style="color:green;text-decoration:none;">hybridauth.sourceforge.net/</a>
</body>
</html>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<xrds:XRDS
xmlns:xrds="xri://$xrds"
xmlns:openid="http://openid.net/xmlns/1.0"
xmlns="xri://$xrd*($v*2.0)">
<XRD>
<Service priority="1">
<Type>http://specs.openid.net/auth/2.0/return_to</Type>
<URI>{RETURN_TO_URL}</URI>
</Service>
</XRD>
</xrds:XRDS>

View File

@@ -0,0 +1,37 @@
<html>
<head>
<meta name="ROBOTS" content="NONE" />
<script type="text/javascript">
function parseIsLiveUserResponse(e) {
var b = "isLiveUser";
if (!e) return false;
for (var d = e.substring(1).split("&"), a = [], c = 0; c < d.length; c++) {
parm = d[c].split("=");
a[unescape(parm[0])] = unescape(parm[1])
}
if (a[b] !== undefined && a[b].length != 0 && window.parent && window.parent.parent && window.parent.parent.Microsoft !== undefined) {
var f = a[b] == "true";
window.parent.parent.Microsoft.Live.App.get_auth().set_isLiveUser(f);
return true
}
return false
}
function onLoad() {
try {
var c = window.location.hash.substr(1),
d = window.location.search;
if (window.location.replace == null) window.location.replace = window.location.assign;
window.location.replace("about:blank");
if (parseIsLiveUserResponse(d)) return;
var b = c.split("/")[0],
a = null;
if (b && b != ".parent") a = window.parent.frames[b];
else a = window.parent.parent;
a.Microsoft && a.Microsoft.Live.Channels.Mux._recv_chunk(c)
} catch (e) {}
}
< /script>
</head>
<body onload="onLoad();">
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,93 @@
<?php
/**
* Copyright 2011 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
require_once "base_facebook.php";
/**
* Extends the BaseFacebook class with the intent of using
* PHP sessions to store user ids and access tokens.
*/
class Facebook extends BaseFacebook
{
/**
* Identical to the parent constructor, except that
* we start a PHP session to store the user ID and
* access token if during the course of execution
* we discover them.
*
* @param Array $config the application configuration.
* @see BaseFacebook::__construct in facebook.php
*/
public function __construct($config) {
if (!session_id()) {
session_start();
}
parent::__construct($config);
}
protected static $kSupportedKeys =
array('state', 'code', 'access_token', 'user_id');
/**
* Provides the implementations of the inherited abstract
* methods. The implementation uses PHP sessions to maintain
* a store for authorization codes, user ids, CSRF states, and
* access tokens.
*/
protected function setPersistentData($key, $value) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to setPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
$_SESSION[$session_var_name] = $value;
}
protected function getPersistentData($key, $default = false) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to getPersistentData.');
return $default;
}
$session_var_name = $this->constructSessionVariableName($key);
return isset($_SESSION[$session_var_name]) ?
$_SESSION[$session_var_name] : $default;
}
protected function clearPersistentData($key) {
if (!in_array($key, self::$kSupportedKeys)) {
self::errorLog('Unsupported key passed to clearPersistentData.');
return;
}
$session_var_name = $this->constructSessionVariableName($key);
unset($_SESSION[$session_var_name]);
}
protected function clearAllPersistentData() {
foreach (self::$kSupportedKeys as $key) {
$this->clearPersistentData($key);
}
}
protected function constructSessionVariableName($key) {
return implode('_', array('fb',
$this->getAppId(),
$key));
}
}

View File

@@ -0,0 +1,121 @@
-----BEGIN CERTIFICATE-----
MIIFgjCCBGqgAwIBAgIQDKKbZcnESGaLDuEaVk6fQjANBgkqhkiG9w0BAQUFADBm
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSUwIwYDVQQDExxEaWdpQ2VydCBIaWdoIEFzc3VyYW5j
ZSBDQS0zMB4XDTEwMDExMzAwMDAwMFoXDTEzMDQxMTIzNTk1OVowaDELMAkGA1UE
BhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExEjAQBgNVBAcTCVBhbG8gQWx0bzEX
MBUGA1UEChMORmFjZWJvb2ssIEluYy4xFzAVBgNVBAMUDiouZmFjZWJvb2suY29t
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9rzj7QIuLM3sdHu1HcI1VcR3g
b5FExKNV646agxSle1aQ/sJev1mh/u91ynwqd2BQmM0brZ1Hc3QrfYyAaiGGgEkp
xbhezyfeYhAyO0TKAYxPnm2cTjB5HICzk6xEIwFbA7SBJ2fSyW1CFhYZyo3tIBjj
19VjKyBfpRaPkzLmRwIDAQABo4ICrDCCAqgwHwYDVR0jBBgwFoAUUOpzidsp+xCP
nuUBINTeeZlIg/cwHQYDVR0OBBYEFPp+tsFBozkjrHlEnZ9J4cFj2eM0MA4GA1Ud
DwEB/wQEAwIFoDAMBgNVHRMBAf8EAjAAMF8GA1UdHwRYMFYwKaAnoCWGI2h0dHA6
Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9jYTMtZmIuY3JsMCmgJ6AlhiNodHRwOi8vY3Js
NC5kaWdpY2VydC5jb20vY2EzLWZiLmNybDCCAcYGA1UdIASCAb0wggG5MIIBtQYL
YIZIAYb9bAEDAAEwggGkMDoGCCsGAQUFBwIBFi5odHRwOi8vd3d3LmRpZ2ljZXJ0
LmNvbS9zc2wtY3BzLXJlcG9zaXRvcnkuaHRtMIIBZAYIKwYBBQUHAgIwggFWHoIB
UgBBAG4AeQAgAHUAcwBlACAAbwBmACAAdABoAGkAcwAgAEMAZQByAHQAaQBmAGkA
YwBhAHQAZQAgAGMAbwBuAHMAdABpAHQAdQB0AGUAcwAgAGEAYwBjAGUAcAB0AGEA
bgBjAGUAIABvAGYAIAB0AGgAZQAgAEQAaQBnAGkAQwBlAHIAdAAgAEMAUAAvAEMA
UABTACAAYQBuAGQAIAB0AGgAZQAgAFIAZQBsAHkAaQBuAGcAIABQAGEAcgB0AHkA
IABBAGcAcgBlAGUAbQBlAG4AdAAgAHcAaABpAGMAaAAgAGwAaQBtAGkAdAAgAGwA
aQBhAGIAaQBsAGkAdAB5ACAAYQBuAGQAIABhAHIAZQAgAGkAbgBjAG8AcgBwAG8A
cgBhAHQAZQBkACAAaABlAHIAZQBpAG4AIABiAHkAIAByAGUAZgBlAHIAZQBuAGMA
ZQAuMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjANBgkqhkiG9w0BAQUF
AAOCAQEACOkTIdxMy11+CKrbGNLBSg5xHaTvu/v1wbyn3dO/mf68pPfJnX6ShPYy
4XM4Vk0x4uaFaU4wAGke+nCKGi5dyg0Esg7nemLNKEJaFAJZ9enxZm334lSCeARy
wlDtxULGOFRyGIZZPmbV2eNq5xdU/g3IuBEhL722mTpAye9FU/J8Wsnw54/gANyO
Gzkewigua8ip8Lbs9Cht399yAfbfhUP1DrAm/xEcnHrzPr3cdCtOyJaM6SRPpRqH
ITK5Nc06tat9lXVosSinT3KqydzxBYua9gCFFiR3x3DgZfvXkC6KDdUlDrNcJUub
a1BHnLLP4mxTHL6faAXYd05IxNn/IA==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIGVTCCBT2gAwIBAgIQCFH5WYFBRcq94CTiEsnCDjANBgkqhkiG9w0BAQUFADBs
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j
ZSBFViBSb290IENBMB4XDTA3MDQwMzAwMDAwMFoXDTIyMDQwMzAwMDAwMFowZjEL
MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3
LmRpZ2ljZXJ0LmNvbTElMCMGA1UEAxMcRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug
Q0EtMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9hCikQH17+NDdR
CPge+yLtYb4LDXBMUGMmdRW5QYiXtvCgFbsIYOBC6AUpEIc2iihlqO8xB3RtNpcv
KEZmBMcqeSZ6mdWOw21PoF6tvD2Rwll7XjZswFPPAAgyPhBkWBATaccM7pxCUQD5
BUTuJM56H+2MEb0SqPMV9Bx6MWkBG6fmXcCabH4JnudSREoQOiPkm7YDr6ictFuf
1EutkozOtREqqjcYjbTCuNhcBoz4/yO9NV7UfD5+gw6RlgWYw7If48hl66l7XaAs
zPw82W3tzPpLQ4zJ1LilYRyyQLYoEt+5+F/+07LJ7z20Hkt8HEyZNp496+ynaF4d
32duXvsCAwEAAaOCAvcwggLzMA4GA1UdDwEB/wQEAwIBhjCCAcYGA1UdIASCAb0w
ggG5MIIBtQYLYIZIAYb9bAEDAAIwggGkMDoGCCsGAQUFBwIBFi5odHRwOi8vd3d3
LmRpZ2ljZXJ0LmNvbS9zc2wtY3BzLXJlcG9zaXRvcnkuaHRtMIIBZAYIKwYBBQUH
AgIwggFWHoIBUgBBAG4AeQAgAHUAcwBlACAAbwBmACAAdABoAGkAcwAgAEMAZQBy
AHQAaQBmAGkAYwBhAHQAZQAgAGMAbwBuAHMAdABpAHQAdQB0AGUAcwAgAGEAYwBj
AGUAcAB0AGEAbgBjAGUAIABvAGYAIAB0AGgAZQAgAEQAaQBnAGkAQwBlAHIAdAAg
AEMAUAAvAEMAUABTACAAYQBuAGQAIAB0AGgAZQAgAFIAZQBsAHkAaQBuAGcAIABQ
AGEAcgB0AHkAIABBAGcAcgBlAGUAbQBlAG4AdAAgAHcAaABpAGMAaAAgAGwAaQBt
AGkAdAAgAGwAaQBhAGIAaQBsAGkAdAB5ACAAYQBuAGQAIABhAHIAZQAgAGkAbgBj
AG8AcgBwAG8AcgBhAHQAZQBkACAAaABlAHIAZQBpAG4AIABiAHkAIAByAGUAZgBl
AHIAZQBuAGMAZQAuMA8GA1UdEwEB/wQFMAMBAf8wNAYIKwYBBQUHAQEEKDAmMCQG
CCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wgY8GA1UdHwSBhzCB
hDBAoD6gPIY6aHR0cDovL2NybDMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0SGlnaEFz
c3VyYW5jZUVWUm9vdENBLmNybDBAoD6gPIY6aHR0cDovL2NybDQuZGlnaWNlcnQu
Y29tL0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUVWUm9vdENBLmNybDAfBgNVHSMEGDAW
gBSxPsNpA/i/RwHUmCYaCALvY2QrwzAdBgNVHQ4EFgQUUOpzidsp+xCPnuUBINTe
eZlIg/cwDQYJKoZIhvcNAQEFBQADggEBAF1PhPGoiNOjsrycbeUpSXfh59bcqdg1
rslx3OXb3J0kIZCmz7cBHJvUV5eR13UWpRLXuT0uiT05aYrWNTf58SHEW0CtWakv
XzoAKUMncQPkvTAyVab+hA4LmzgZLEN8rEO/dTHlIxxFVbdpCJG1z9fVsV7un5Tk
1nq5GMO41lJjHBC6iy9tXcwFOPRWBW3vnuzoYTYMFEuFFFoMg08iXFnLjIpx2vrF
EIRYzwfu45DC9fkpx1ojcflZtGQriLCnNseaIGHr+k61rmsb5OPs4tk8QUmoIKRU
9ZKNu8BVIASm2LAXFszj0Mi0PeXZhMbT9m5teMl5Q+h6N/9cNUm/ocU=
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIEQjCCA6ugAwIBAgIEQoclDjANBgkqhkiG9w0BAQUFADCBwzELMAkGA1UEBhMC
VVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MTswOQYDVQQLEzJ3d3cuZW50cnVzdC5u
ZXQvQ1BTIGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxpYWIuKTElMCMGA1UECxMc
KGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDE6MDgGA1UEAxMxRW50cnVzdC5u
ZXQgU2VjdXJlIFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEy
MjIxNTI3MjdaFw0xNDA3MjIxNTU3MjdaMGwxCzAJBgNVBAYTAlVTMRUwEwYDVQQK
EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xKzApBgNV
BAMTIkRpZ2lDZXJ0IEhpZ2ggQXNzdXJhbmNlIEVWIFJvb3QgQ0EwggEiMA0GCSqG
SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDGzOVz5vvUu+UtLTKm3+WBP8nNJUm2cSrD
1ZQ0Z6IKHLBfaaZAscS3so/QmKSpQVk609yU1jzbdDikSsxNJYL3SqVTEjju80lt
cZF+Y7arpl/DpIT4T2JRvvjF7Ns4kuMG5QiRDMQoQVX7y1qJFX5x6DW/TXIJPb46
OFBbdzEbjbPHJEWap6xtABRaBLe6E+tRCphBQSJOZWGHgUFQpnlcid4ZSlfVLuZd
HFMsfpjNGgYWpGhz0DQEE1yhcdNafFXbXmThN4cwVgTlEbQpgBLxeTmIogIRfCdm
t4i3ePLKCqg4qwpkwr9mXZWEwaElHoddGlALIBLMQbtuC1E4uEvLAgMBAAGjggET
MIIBDzASBgNVHRMBAf8ECDAGAQH/AgEBMCcGA1UdJQQgMB4GCCsGAQUFBwMBBggr
BgEFBQcDAgYIKwYBBQUHAwQwMwYIKwYBBQUHAQEEJzAlMCMGCCsGAQUFBzABhhdo
dHRwOi8vb2NzcC5lbnRydXN0Lm5ldDAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8v
Y3JsLmVudHJ1c3QubmV0L3NlcnZlcjEuY3JsMB0GA1UdDgQWBBSxPsNpA/i/RwHU
mCYaCALvY2QrwzALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAU8BdiE1U9s/8KAGv7
UISX8+1i0BowGQYJKoZIhvZ9B0EABAwwChsEVjcuMQMCAIEwDQYJKoZIhvcNAQEF
BQADgYEAUuVY7HCc/9EvhaYzC1rAIo348LtGIiMduEl5Xa24G8tmJnDioD2GU06r
1kjLX/ktCdpdBgXadbjtdrZXTP59uN0AXlsdaTiFufsqVLPvkp5yMnqnuI3E2o6p
NpAkoQSbB6kUCNnXcW26valgOjDLZFOnr241QiwdBAJAAE/rRa8=
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIE2DCCBEGgAwIBAgIEN0rSQzANBgkqhkiG9w0BAQUFADCBwzELMAkGA1UEBhMC
VVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MTswOQYDVQQLEzJ3d3cuZW50cnVzdC5u
ZXQvQ1BTIGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxpYWIuKTElMCMGA1UECxMc
KGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDE6MDgGA1UEAxMxRW50cnVzdC5u
ZXQgU2VjdXJlIFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw05OTA1
MjUxNjA5NDBaFw0xOTA1MjUxNjM5NDBaMIHDMQswCQYDVQQGEwJVUzEUMBIGA1UE
ChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5j
b3JwLiBieSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBF
bnRydXN0Lm5ldCBMaW1pdGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUg
U2VydmVyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUA
A4GLADCBhwKBgQDNKIM0VBuJ8w+vN5Ex/68xYMmo6LIQaO2f55M28Qpku0f1BBc/
I0dNxScZgSYMVHINiC3ZH5oSn7yzcdOAGT9HZnuMNSjSuQrfJNqc1lB5gXpa0zf3
wkrYKZImZNHkmGw6AIr1NJtl+O3jEP/9uElY3KDegjlrgbEWGWG5VLbmQwIBA6OC
AdcwggHTMBEGCWCGSAGG+EIBAQQEAwIABzCCARkGA1UdHwSCARAwggEMMIHeoIHb
oIHYpIHVMIHSMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxOzA5
BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5jb3JwLiBieSByZWYuIChsaW1p
dHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBFbnRydXN0Lm5ldCBMaW1pdGVk
MTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENlcnRpZmljYXRp
b24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMCmgJ6AlhiNodHRwOi8vd3d3LmVu
dHJ1c3QubmV0L0NSTC9uZXQxLmNybDArBgNVHRAEJDAigA8xOTk5MDUyNTE2MDk0
MFqBDzIwMTkwNTI1MTYwOTQwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAU8Bdi
E1U9s/8KAGv7UISX8+1i0BowHQYDVR0OBBYEFPAXYhNVPbP/CgBr+1CEl/PtYtAa
MAwGA1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EABAwwChsEVjQuMAMCBJAwDQYJKoZI
hvcNAQEFBQADgYEAkNwwAvpkdMKnCqV8IY00F6j7Rw7/JXyNEwr75Ji174z4xRAN
95K+8cPV1ZVqBLssziY2ZcgxxufuP+NXdYR6Ee9GTxj005i7qIcyunL2POI9n9cd
2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G+bI=
-----END CERTIFICATE-----

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,896 @@
<?php
// http://oauth.googlecode.com/svn/code/php/OAuth.php
// rev 1261, Mar 29, 2011 morten.fangel
// vim: foldmethod=marker
/* Generic exception class
*/
class OAuthException extends Exception {
// pass
}
class OAuthConsumer {
public $key;
public $secret;
function __construct($key, $secret, $callback_url=NULL) {
$this->key = $key;
$this->secret = $secret;
$this->callback_url = $callback_url;
}
function __toString() {
return "OAuthConsumer[key=$this->key,secret=$this->secret]";
}
}
class OAuthToken {
// access tokens and request tokens
public $key;
public $secret;
/**
* key = the token
* secret = the token secret
*/
function __construct($key, $secret) {
$this->key = $key;
$this->secret = $secret;
}
/**
* generates the basic string serialization of a token that a server
* would respond to request_token and access_token calls with
*/
function to_string() {
return "oauth_token=" .
OAuthUtil::urlencode_rfc3986($this->key) .
"&oauth_token_secret=" .
OAuthUtil::urlencode_rfc3986($this->secret);
}
function __toString() {
return $this->to_string();
}
}
/**
* A class for implementing a Signature Method
* See section 9 ("Signing Requests") in the spec
*/
abstract class OAuthSignatureMethod {
/**
* Needs to return the name of the Signature Method (ie HMAC-SHA1)
* @return string
*/
abstract public function get_name();
/**
* Build up the signature
* NOTE: The output of this function MUST NOT be urlencoded.
* the encoding is handled in OAuthRequest when the final
* request is serialized
* @param OAuthRequest $request
* @param OAuthConsumer $consumer
* @param OAuthToken $token
* @return string
*/
abstract public function build_signature($request, $consumer, $token);
/**
* Verifies that a given signature is correct
* @param OAuthRequest $request
* @param OAuthConsumer $consumer
* @param OAuthToken $token
* @param string $signature
* @return bool
*/
public function check_signature($request, $consumer, $token, $signature) {
$built = $this->build_signature($request, $consumer, $token);
// Check for zero length, although unlikely here
if (strlen($built) == 0 || strlen($signature) == 0) {
return false;
}
if (strlen($built) != strlen($signature)) {
return false;
}
// Avoid a timing leak with a (hopefully) time insensitive compare
$result = 0;
for ($i = 0; $i < strlen($signature); $i++) {
$result |= ord($built{$i}) ^ ord($signature{$i});
}
return $result == 0;
}
}
/**
* The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
* where the Signature Base String is the text and the key is the concatenated values (each first
* encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
* character (ASCII code 38) even if empty.
* - Chapter 9.2 ("HMAC-SHA1")
*/
class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
function get_name() {
return "HMAC-SHA1";
}
public function build_signature($request, $consumer, $token) {
$base_string = $request->get_signature_base_string();
$request->base_string = $base_string;
$key_parts = array(
$consumer->secret,
($token) ? $token->secret : ""
);
$key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
$key = implode('&', $key_parts);
return base64_encode(hash_hmac('sha1', $base_string, $key, true));
}
}
/**
* The PLAINTEXT method does not provide any security protection and SHOULD only be used
* over a secure channel such as HTTPS. It does not use the Signature Base String.
* - Chapter 9.4 ("PLAINTEXT")
*/
class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
public function get_name() {
return "PLAINTEXT";
}
/**
* oauth_signature is set to the concatenated encoded values of the Consumer Secret and
* Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
* empty. The result MUST be encoded again.
* - Chapter 9.4.1 ("Generating Signatures")
*
* Please note that the second encoding MUST NOT happen in the SignatureMethod, as
* OAuthRequest handles this!
*/
public function build_signature($request, $consumer, $token) {
$key_parts = array(
$consumer->secret,
($token) ? $token->secret : ""
);
$key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
$key = implode('&', $key_parts);
$request->base_string = $key;
return $key;
}
}
/**
* The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
* [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
* EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
* verified way to the Service Provider, in a manner which is beyond the scope of this
* specification.
* - Chapter 9.3 ("RSA-SHA1")
*/
abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
public function get_name() {
return "RSA-SHA1";
}
// Up to the SP to implement this lookup of keys. Possible ideas are:
// (1) do a lookup in a table of trusted certs keyed off of consumer
// (2) fetch via http using a url provided by the requester
// (3) some sort of specific discovery code based on request
//
// Either way should return a string representation of the certificate
protected abstract function fetch_public_cert(&$request);
// Up to the SP to implement this lookup of keys. Possible ideas are:
// (1) do a lookup in a table of trusted certs keyed off of consumer
//
// Either way should return a string representation of the certificate
protected abstract function fetch_private_cert(&$request);
public function build_signature($request, $consumer, $token) {
$base_string = $request->get_signature_base_string();
$request->base_string = $base_string;
// Fetch the private key cert based on the request
$cert = $this->fetch_private_cert($request);
// Pull the private key ID from the certificate
$privatekeyid = openssl_get_privatekey($cert);
// Sign using the key
$ok = openssl_sign($base_string, $signature, $privatekeyid);
// Release the key resource
openssl_free_key($privatekeyid);
return base64_encode($signature);
}
public function check_signature($request, $consumer, $token, $signature) {
$decoded_sig = base64_decode($signature);
$base_string = $request->get_signature_base_string();
// Fetch the public key cert based on the request
$cert = $this->fetch_public_cert($request);
// Pull the public key ID from the certificate
$publickeyid = openssl_get_publickey($cert);
// Check the computed signature against the one passed in the query
$ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
// Release the key resource
openssl_free_key($publickeyid);
return $ok == 1;
}
}
class OAuthRequest {
protected $parameters;
protected $http_method;
protected $http_url;
// for debug purposes
public $base_string;
public static $version = '1.0';
public static $POST_INPUT = 'php://input';
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;
$this->http_method = $http_method;
$this->http_url = $http_url;
}
/**
* 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) {
$scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
? 'http'
: 'https';
$http_url = ($http_url) ? $http_url : $scheme .
'://' . $_SERVER['SERVER_NAME'] .
':' .
$_SERVER['SERVER_PORT'] .
$_SERVER['REQUEST_URI'];
$http_method = ($http_method) ? $http_method : $_SERVER['REQUEST_METHOD'];
// We weren't handed any parameters, so let's find the ones relevant to
// this request.
// If you run XML-RPC or similar you should use this to provide your own
// parsed parameter-list
if (!$parameters) {
// Find request headers
$request_headers = OAuthUtil::get_headers();
// Parse the query-string to find GET parameters
$parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
// It's a POST request of the proper content-type, so parse POST
// parameters and add those overriding any duplicates from GET
if ($http_method == "POST"
&& isset($request_headers['Content-Type'])
&& strstr($request_headers['Content-Type'],
'application/x-www-form-urlencoded')
) {
$post_data = OAuthUtil::parse_parameters(
file_get_contents(self::$POST_INPUT)
);
$parameters = array_merge($parameters, $post_data);
}
// We have a Authorization-header with OAuth data. Parse the header
// and add those overriding any duplicates from GET or POST
if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == 'OAuth ') {
$header_parameters = OAuthUtil::split_header(
$request_headers['Authorization']
);
$parameters = array_merge($parameters, $header_parameters);
}
}
return new OAuthRequest($http_method, $http_url, $parameters);
}
/**
* 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) {
$parameters = ($parameters) ? $parameters : array();
$defaults = array("oauth_version" => OAuthRequest::$version,
"oauth_nonce" => OAuthRequest::generate_nonce(),
"oauth_timestamp" => OAuthRequest::generate_timestamp(),
"oauth_consumer_key" => $consumer->key);
if ($token)
$defaults['oauth_token'] = $token->key;
$parameters = array_merge($defaults, $parameters);
return new OAuthRequest($http_method, $http_url, $parameters);
}
public function set_parameter($name, $value, $allow_duplicates = true) {
if ($allow_duplicates && isset($this->parameters[$name])) {
// We have already added parameter(s) with this name, so add to the list
if (is_scalar($this->parameters[$name])) {
// This is the first duplicate, so transform scalar (string)
// into an array so we can add the duplicates
$this->parameters[$name] = array($this->parameters[$name]);
}
$this->parameters[$name][] = $value;
} else {
$this->parameters[$name] = $value;
}
}
public function get_parameter($name) {
return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
}
public function get_parameters() {
return $this->parameters;
}
public function unset_parameter($name) {
unset($this->parameters[$name]);
}
/**
* The request parameters, sorted and concatenated into a normalized string.
* @return string
*/
public function get_signable_parameters() {
// Grab all parameters
$params = $this->parameters;
// Remove oauth_signature if present
// Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
if (isset($params['oauth_signature'])) {
unset($params['oauth_signature']);
}
return OAuthUtil::build_http_query($params);
}
/**
* Returns the base string of this request
*
* The base string defined as the method, the url
* and the parameters (normalized), each urlencoded
* and the concated with &.
*/
public function get_signature_base_string() {
$parts = array(
$this->get_normalized_http_method(),
$this->get_normalized_http_url(),
$this->get_signable_parameters()
);
$parts = OAuthUtil::urlencode_rfc3986($parts);
return implode('&', $parts);
}
/**
* just uppercases the http method
*/
public function get_normalized_http_method() {
return strtoupper($this->http_method);
}
/**
* parses the url and rebuilds it to be
* scheme://host/path
*/
public function get_normalized_http_url() {
$parts = parse_url($this->http_url);
$scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http';
$port = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80');
$host = (isset($parts['host'])) ? strtolower($parts['host']) : '';
$path = (isset($parts['path'])) ? $parts['path'] : '';
if (($scheme == 'https' && $port != '443')
|| ($scheme == 'http' && $port != '80')) {
$host = "$host:$port";
}
return "$scheme://$host$path";
}
/**
* builds a url usable for a GET request
*/
public function to_url() {
$post_data = $this->to_postdata();
$out = $this->get_normalized_http_url();
if ($post_data) {
$out .= '?'.$post_data;
}
return $out;
}
/**
* builds the data one would send in a POST request
*/
public function to_postdata() {
return OAuthUtil::build_http_query($this->parameters);
}
/**
* builds the Authorization: header
*/
public function to_header($realm=null) {
$first = true;
if($realm) {
$out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
$first = false;
} else
$out = 'Authorization: OAuth';
$total = array();
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');
}
$out .= ($first) ? ' ' : ',';
$out .= OAuthUtil::urlencode_rfc3986($k) .
'="' .
OAuthUtil::urlencode_rfc3986($v) .
'"';
$first = false;
}
return $out;
}
public function __toString() {
return $this->to_url();
}
public function sign_request($signature_method, $consumer, $token) {
$this->set_parameter(
"oauth_signature_method",
$signature_method->get_name(),
false
);
$signature = $this->build_signature($signature_method, $consumer, $token);
$this->set_parameter("oauth_signature", $signature, false);
}
public function build_signature($signature_method, $consumer, $token) {
$signature = $signature_method->build_signature($this, $consumer, $token);
return $signature;
}
/**
* util function: current timestamp
*/
private static function generate_timestamp() {
return time();
}
/**
* util function: current nonce
*/
private static function generate_nonce() {
$mt = microtime();
$rand = mt_rand();
return md5($mt . $rand); // md5s look nicer than numbers
}
}
class OAuthServer {
protected $timestamp_threshold = 300; // in seconds, five minutes
protected $version = '1.0'; // hi blaine
protected $signature_methods = array();
protected $data_store;
function __construct($data_store) {
$this->data_store = $data_store;
}
public function add_signature_method($signature_method) {
$this->signature_methods[$signature_method->get_name()] =
$signature_method;
}
// high level functions
/**
* process a request_token request
* returns the request token on success
*/
public function fetch_request_token(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
// no token required for the initial token request
$token = NULL;
$this->check_signature($request, $consumer, $token);
// Rev A change
$callback = $request->get_parameter('oauth_callback');
$new_token = $this->data_store->new_request_token($consumer, $callback);
return $new_token;
}
/**
* process an access_token request
* returns the access token on success
*/
public function fetch_access_token(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
// requires authorized request token
$token = $this->get_token($request, $consumer, "request");
$this->check_signature($request, $consumer, $token);
// Rev A change
$verifier = $request->get_parameter('oauth_verifier');
$new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
return $new_token;
}
/**
* verify an api call, checks all the parameters
*/
public function verify_request(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
$token = $this->get_token($request, $consumer, "access");
$this->check_signature($request, $consumer, $token);
return array($consumer, $token);
}
// Internals from here
/**
* version 1
*/
private function get_version(&$request) {
$version = $request->get_parameter("oauth_version");
if (!$version) {
// Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
// Chapter 7.0 ("Accessing Protected Ressources")
$version = '1.0';
}
if ($version !== $this->version) {
throw new OAuthException("OAuth version '$version' not supported");
}
return $version;
}
/**
* figure out the signature with some defaults
*/
private function get_signature_method($request) {
$signature_method = $request instanceof OAuthRequest
? $request->get_parameter("oauth_signature_method")
: NULL;
if (!$signature_method) {
// According to chapter 7 ("Accessing Protected Ressources") the signature-method
// parameter is required, and we can't just fallback to PLAINTEXT
throw new OAuthException('No signature method parameter. This parameter is required');
}
if (!in_array($signature_method,
array_keys($this->signature_methods))) {
throw new OAuthException(
"Signature method '$signature_method' not supported " .
"try one of the following: " .
implode(", ", array_keys($this->signature_methods))
);
}
return $this->signature_methods[$signature_method];
}
/**
* try to find the consumer for the provided request's consumer key
*/
private function get_consumer($request) {
$consumer_key = $request instanceof OAuthRequest
? $request->get_parameter("oauth_consumer_key")
: NULL;
if (!$consumer_key) {
throw new OAuthException("Invalid consumer key");
}
$consumer = $this->data_store->lookup_consumer($consumer_key);
if (!$consumer) {
throw new OAuthException("Invalid consumer");
}
return $consumer;
}
/**
* try to find the token for the provided request's token key
*/
private function get_token($request, $consumer, $token_type="access") {
$token_field = $request instanceof OAuthRequest
? $request->get_parameter('oauth_token')
: NULL;
$token = $this->data_store->lookup_token(
$consumer, $token_type, $token_field
);
if (!$token) {
throw new OAuthException("Invalid $token_type token: $token_field");
}
return $token;
}
/**
* all-in-one function to check the signature on a request
* should guess the signature method appropriately
*/
private function check_signature($request, $consumer, $token) {
// this should probably be in a different method
$timestamp = $request instanceof OAuthRequest
? $request->get_parameter('oauth_timestamp')
: NULL;
$nonce = $request instanceof OAuthRequest
? $request->get_parameter('oauth_nonce')
: NULL;
$this->check_timestamp($timestamp);
$this->check_nonce($consumer, $token, $nonce, $timestamp);
$signature_method = $this->get_signature_method($request);
$signature = $request->get_parameter('oauth_signature');
$valid_sig = $signature_method->check_signature(
$request,
$consumer,
$token,
$signature
);
if (!$valid_sig) {
throw new OAuthException("Invalid signature");
}
}
/**
* check that the timestamp is new enough
*/
private function check_timestamp($timestamp) {
if( ! $timestamp )
throw new OAuthException(
'Missing timestamp parameter. The parameter is required'
);
// verify that timestamp is recentish
$now = time();
if (abs($now - $timestamp) > $this->timestamp_threshold) {
throw new OAuthException(
"Expired timestamp, yours $timestamp, ours $now"
);
}
}
/**
* check that the nonce is not repeated
*/
private function check_nonce($consumer, $token, $nonce, $timestamp) {
if( ! $nonce )
throw new OAuthException(
'Missing nonce parameter. The parameter is required'
);
// verify that the nonce is uniqueish
$found = $this->data_store->lookup_nonce(
$consumer,
$token,
$nonce,
$timestamp
);
if ($found) {
throw new OAuthException("Nonce already used: $nonce");
}
}
}
class OAuthDataStore {
function lookup_consumer($consumer_key) {
// implement me
}
function lookup_token($consumer, $token_type, $token) {
// implement me
}
function lookup_nonce($consumer, $token, $nonce, $timestamp) {
// implement me
}
function new_request_token($consumer, $callback = null) {
// return a new token attached to this consumer
}
function new_access_token($token, $consumer, $verifier = null) {
// return a new access token attached to this consumer
// for the user associated with this token if the request token
// is authorized
// should also invalidate the request token
}
}
class OAuthUtil {
public static function urlencode_rfc3986($input) {
if (is_array($input)) {
return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
} else if (is_scalar($input)) {
return str_replace(
'+',
' ',
str_replace('%7E', '~', rawurlencode($input))
);
} else {
return '';
}
}
// This decode function isn't taking into consideration the above
// modifications to the encoding process. However, this method doesn't
// seem to be used anywhere so leaving it as is.
public static function urldecode_rfc3986($string) {
return urldecode($string);
}
// Utility function for turning the Authorization: header into
// parameters, has to do some unescaping
// Can filter out any non-oauth parameters if needed (default behaviour)
// May 28th, 2010 - method updated to tjerk.meesters for a speed improvement.
// see http://code.google.com/p/oauth/issues/detail?id=163
public static function split_header($header, $only_allow_oauth_parameters = true) {
$params = array();
if (preg_match_all('/('.($only_allow_oauth_parameters ? 'oauth_' : '').'[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $header, $matches)) {
foreach ($matches[1] as $i => $h) {
$params[$h] = OAuthUtil::urldecode_rfc3986(empty($matches[3][$i]) ? $matches[4][$i] : $matches[3][$i]);
}
if (isset($params['realm'])) {
unset($params['realm']);
}
}
return $params;
}
// helper to try to sort out headers for people who aren't running apache
public static function get_headers() {
if (function_exists('apache_request_headers')) {
// we need this to get the actual Authorization: header
// because apache tends to tell us it doesn't exist
$headers = apache_request_headers();
// sanitize the output of apache_request_headers because
// we always want the keys to be Cased-Like-This and arh()
// returns the headers in the same case as they are in the
// request
$out = array();
foreach ($headers AS $key => $value) {
$key = str_replace(
" ",
"-",
ucwords(strtolower(str_replace("-", " ", $key)))
);
$out[$key] = $value;
}
} else {
// otherwise we don't have apache and are just going to have to hope
// that $_SERVER actually contains what we need
$out = array();
if( isset($_SERVER['CONTENT_TYPE']) )
$out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
if( isset($_ENV['CONTENT_TYPE']) )
$out['Content-Type'] = $_ENV['CONTENT_TYPE'];
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == "HTTP_") {
// this is chaos, basically it is just there to capitalize the first
// letter of every word that is not an initial HTTP and strip HTTP
// code from przemek
$key = str_replace(
" ",
"-",
ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
);
$out[$key] = $value;
}
}
}
return $out;
}
// This function takes a input like a=b&a=c&d=e and returns the parsed
// parameters like this
// array('a' => array('b','c'), 'd' => 'e')
public static function parse_parameters( $input ) {
if (!isset($input) || !$input) return array();
$pairs = explode('&', $input);
$parsed_parameters = array();
foreach ($pairs as $pair) {
$split = explode('=', $pair, 2);
$parameter = OAuthUtil::urldecode_rfc3986($split[0]);
$value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
if (isset($parsed_parameters[$parameter])) {
// We have already recieved parameter(s) with this name, so add to the list
// of parameters with this name
if (is_scalar($parsed_parameters[$parameter])) {
// This is the first duplicate, so transform scalar (string) into an array
// so we can add the duplicates
$parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
}
$parsed_parameters[$parameter][] = $value;
} else {
$parsed_parameters[$parameter] = $value;
}
}
return $parsed_parameters;
}
public static function build_http_query($params) {
if (!$params) return '';
// Urlencode both keys and values
$keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
$values = OAuthUtil::urlencode_rfc3986(array_values($params));
$params = array_combine($keys, $values);
// Parameters are sorted by name, using lexicographical byte value ordering.
// Ref: Spec: 9.1.1 (1)
uksort($params, 'strcmp');
$pairs = array();
foreach ($params as $parameter => $value) {
if (is_array($value)) {
// If two or more parameters share the same name, they are sorted by their value
// Ref: Spec: 9.1.1 (1)
// June 12th, 2010 - changed to sort because of issue 164 by hidetaka
sort($value, SORT_STRING);
foreach ($value as $duplicate_value) {
$pairs[] = $parameter . '=' . $duplicate_value;
}
} else {
$pairs[] = $parameter . '=' . $value;
}
}
// For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
// Each name-value pair is separated by an '&' character (ASCII code 38)
return implode('&', $pairs);
}
}

View File

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

View File

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

View File

@@ -0,0 +1,794 @@
<?php
// http://gitorious.org/lightopenid
// 20/11/11
/**
* This class provides a simple interface for OpenID (1.1 and 2.0) authentication.
* Supports Yadis discovery.
* The library requires PHP >= 5.1.2 with curl or http/https stream wrappers enabled.
* @author Mewp
* @copyright Copyright (c) 2010, Mewp
* @license http://www.opensource.org/licenses/mit-license.php MIT
*/
class LightOpenID
{
public $returnUrl
, $required = array()
, $optional = array()
, $verify_peer = null
, $capath = null
, $cainfo = null
, $data;
private $identity, $claimed_id;
protected $server, $version, $trustRoot, $aliases, $identifier_select = false
, $ax = false, $sreg = false, $setup_url = null, $headers = array();
static protected $ax_to_sreg = array(
'namePerson/friendly' => 'nickname',
'contact/email' => 'email',
'namePerson' => 'fullname',
'birthDate' => 'dob',
'person/gender' => 'gender',
'contact/postalCode/home' => 'postcode',
'contact/country/home' => 'country',
'pref/language' => 'language',
'pref/timezone' => 'timezone',
);
function __construct($host)
{
$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(($host_end = strpos($this->trustRoot, '/', 8)) !== false) {
$this->trustRoot = substr($this->trustRoot, 0, $host_end);
}
$uri = rtrim(preg_replace('#((?<=\?)|&)openid\.[^&]+#', '', $_SERVER['REQUEST_URI']), '?');
$this->returnUrl = $this->trustRoot . $uri;
$this->data = ($_SERVER['REQUEST_METHOD'] === 'POST') ? $_POST : $_GET;
if(!function_exists('curl_init') && !in_array('https', stream_get_wrappers())) {
throw new ErrorException('You must have either https wrappers or curl enabled.');
}
}
function __set($name, $value)
{
switch ($name) {
case 'identity':
if (strlen($value = trim((String) $value))) {
if (preg_match('#^xri:/*#i', $value, $m)) {
$value = substr($value, strlen($m[0]));
} elseif (!preg_match('/^(?:[=@+\$!\(]|https?:)/i', $value)) {
$value = "http://$value";
}
if (preg_match('#^https?://[^/]+$#i', $value, $m)) {
$value .= '/';
}
}
$this->$name = $this->claimed_id = $value;
break;
case 'trustRoot':
case 'realm':
$this->trustRoot = trim($value);
}
}
function __get($name)
{
switch ($name) {
case 'identity':
# We return claimed_id instead of identity,
# because the developer should see the claimed identifier,
# i.e. what he set as identity, not the op-local identifier (which is what we verify)
return $this->claimed_id;
case 'trustRoot':
case 'realm':
return $this->trustRoot;
case 'mode':
return empty($this->data['openid_mode']) ? null : $this->data['openid_mode'];
}
}
/**
* Checks if the server specified in the url exists.
*
* @param $url url to check
* @return true, if the server exists; false otherwise
*/
function hostExists($url)
{
if (strpos($url, '/') === false) {
$server = $url;
} else {
$server = @parse_url($url, PHP_URL_HOST);
}
if (!$server) {
return false;
}
return !!gethostbynamel($server);
}
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_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/xrds+xml, */*'));
if($this->verify_peer !== null) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->verify_peer);
if($this->capath) {
curl_setopt($curl, CURLOPT_CAPATH, $this->capath);
}
if($this->cainfo) {
curl_setopt($curl, CURLOPT_CAINFO, $this->cainfo);
}
}
if ($method == 'POST') {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
} elseif ($method == 'HEAD') {
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_NOBODY, true);
} else {
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_HTTPGET, true);
}
$response = curl_exec($curl);
if($method == 'HEAD' && curl_getinfo($curl, CURLINFO_HTTP_CODE) == 405) {
curl_setopt($curl, CURLOPT_HTTPGET, true);
$response = curl_exec($curl);
$response = substr($response, 0, strpos($response, "\r\n\r\n"));
}
if($method == 'HEAD' || $method == 'GET') {
$header_response = $response;
# If it's a GET request, we want to only parse the header part.
if($method == 'GET') {
$header_response = substr($response, 0, strpos($response, "\r\n\r\n"));
}
$headers = array();
foreach(explode("\n", $header_response) as $header) {
$pos = strpos($header,':');
if ($pos !== false) {
$name = strtolower(trim(substr($header, 0, $pos)));
$headers[$name] = trim(substr($header, $pos+1));
}
}
if($update_claimed_id) {
# Updating claimed_id in case of redirections.
$effective_url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
if($effective_url != $url) {
$this->identity = $this->claimed_id = $effective_url;
}
}
if($method == 'HEAD') {
return $headers;
} else {
$this->headers = $headers;
}
}
if (curl_errno($curl)) {
throw new ErrorException(curl_error($curl), curl_errno($curl));
}
return $response;
}
protected function parse_header_array($array, $update_claimed_id)
{
$headers = array();
foreach($array as $header) {
$pos = strpos($header,':');
if ($pos !== false) {
$name = strtolower(trim(substr($header, 0, $pos)));
$headers[$name] = trim(substr($header, $pos+1));
# Following possible redirections. The point is just to have
# claimed_id change with them, because the redirections
# are followed automatically.
# We ignore redirections with relative paths.
# If any known provider uses them, file a bug report.
if($name == 'location' && $update_claimed_id) {
if(strpos($headers[$name], 'http') === 0) {
$this->identity = $this->claimed_id = $headers[$name];
} elseif($headers[$name][0] == '/') {
$parsed_url = parse_url($this->claimed_id);
$this->identity =
$this->claimed_id = $parsed_url['scheme'] . '://'
. $parsed_url['host']
. $headers[$name];
}
}
}
}
return $headers;
}
protected function request_streams($url, $method='GET', $params=array(), $update_claimed_id)
{
if(!$this->hostExists($url)) {
throw new ErrorException("Could not connect to $url.", 404);
}
$params = http_build_query($params, '', '&');
switch($method) {
case 'GET':
$opts = array(
'http' => array(
'method' => 'GET',
'header' => 'Accept: application/xrds+xml, */*',
'ignore_errors' => true,
), 'ssl' => array(
'CN_match' => parse_url($url, PHP_URL_HOST),
),
);
$url = $url . ($params ? '?' . $params : '');
break;
case 'POST':
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $params,
'ignore_errors' => true,
), 'ssl' => array(
'CN_match' => parse_url($url, PHP_URL_HOST),
),
);
break;
case 'HEAD':
# We want to send a HEAD request,
# but since get_headers doesn't accept $context parameter,
# we have to change the defaults.
$default = stream_context_get_options(stream_context_get_default());
stream_context_get_default(
array(
'http' => array(
'method' => 'HEAD',
'header' => 'Accept: application/xrds+xml, */*',
'ignore_errors' => true,
), 'ssl' => array(
'CN_match' => parse_url($url, PHP_URL_HOST),
),
)
);
$url = $url . ($params ? '?' . $params : '');
$headers = get_headers ($url);
if(!$headers) {
return array();
}
if(intval(substr($headers[0], strlen('HTTP/1.1 '))) == 405) {
# The server doesn't support HEAD, so let's emulate it with
# a GET.
$args = func_get_args();
$args[1] = 'GET';
call_user_func_array(array($this, 'request_streams'), $args);
return $this->headers;
}
$headers = $this->parse_header_array($headers, $update_claimed_id);
# And restore them.
stream_context_get_default($default);
return $headers;
}
if($this->verify_peer) {
$opts['ssl'] += array(
'verify_peer' => true,
'capath' => $this->capath,
'cafile' => $this->cainfo,
);
}
$context = stream_context_create ($opts);
$data = file_get_contents($url, false, $context);
# This is a hack for providers who don't support HEAD requests.
# It just creates the headers array for the last request in $this->headers.
if(isset($http_response_header)) {
$this->headers = $this->parse_header_array($http_response_header, $update_claimed_id);
}
return file_get_contents($url, false, $context);
}
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);
}
return $this->request_streams($url, $method, $params, $update_claimed_id);
}
protected function build_url($url, $parts)
{
if (isset($url['query'], $parts['query'])) {
$parts['query'] = $url['query'] . '&' . $parts['query'];
}
$url = $parts + $url;
$url = $url['scheme'] . '://'
. (empty($url['username'])?''
:(empty($url['password'])? "{$url['username']}@"
:"{$url['username']}:{$url['password']}@"))
. $url['host']
. (empty($url['port'])?'':":{$url['port']}")
. (empty($url['path'])?'':$url['path'])
. (empty($url['query'])?'':"?{$url['query']}")
. (empty($url['fragment'])?'':"#{$url['fragment']}");
return $url;
}
/**
* Helper function used to scan for <meta>/<link> tags and extract information
* from them
*/
protected function htmlTag($content, $tag, $attrName, $attrValue, $valueName)
{
preg_match_all("#<{$tag}[^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*$valueName=['\"](.+?)['\"][^>]*/?>#i", $content, $matches1);
preg_match_all("#<{$tag}[^>]*$valueName=['\"](.+?)['\"][^>]*$attrName=['\"].*?$attrValue.*?['\"][^>]*/?>#i", $content, $matches2);
$result = array_merge($matches1[1], $matches2[1]);
return empty($result)?false:$result[0];
}
/**
* Performs Yadis and HTML discovery. Normally not used.
* @param $url Identity URL.
* @return String OP Endpoint (i.e. OpenID provider address).
* @throws ErrorException
*/
function discover($url)
{
if (!$url) throw new ErrorException('No identity supplied.');
# Use xri.net proxy to resolve i-name identities
if (!preg_match('#^https?:#', $url)) {
$url = "https://xri.net/$url";
}
# We save the original url in case of Yadis discovery failure.
# It can happen when we'll be lead to an XRDS document
# which does not have any OpenID2 services.
$originalUrl = $url;
# A flag to disable yadis discovery in case of failure in headers.
$yadis = true;
# We'll jump a maximum of 5 times, to avoid endless redirections.
for ($i = 0; $i < 5; $i ++) {
if ($yadis) {
$headers = $this->request($url, 'HEAD', array(), true);
$next = false;
if (isset($headers['x-xrds-location'])) {
$url = $this->build_url(parse_url($url), parse_url(trim($headers['x-xrds-location'])));
$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.
# ---
# Found an XRDS document, now let's find the server, and optionally delegate.
$content = $this->request($url, 'GET');
preg_match_all('#<Service.*?>(.*?)</Service>#s', $content, $m);
foreach($m[1] as $content) {
$content = ' ' . $content; # The space is added, so that strpos doesn't return 0.
# OpenID 2
$ns = preg_quote('http://specs.openid.net/auth/2.0/', '#');
if(preg_match('#<Type>\s*'.$ns.'(server|signon)\s*</Type>#s', $content, $type)) {
if ($type[1] == 'server') $this->identifier_select = true;
preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
preg_match('#<(Local|Canonical)ID>(.*)</\1ID>#', $content, $delegate);
if (empty($server)) {
return false;
}
# Does the server advertise support for either AX or SREG?
$this->ax = (bool) strpos($content, '<Type>http://openid.net/srv/ax/1.0</Type>');
$this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
|| strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
$server = $server[1];
if (isset($delegate[2])) $this->identity = trim($delegate[2]);
$this->version = 2;
$this->server = $server;
return $server;
}
# OpenID 1.1
$ns = preg_quote('http://openid.net/signon/1.1', '#');
if (preg_match('#<Type>\s*'.$ns.'\s*</Type>#s', $content)) {
preg_match('#<URI.*?>(.*)</URI>#', $content, $server);
preg_match('#<.*?Delegate>(.*)</.*?Delegate>#', $content, $delegate);
if (empty($server)) {
return false;
}
# AX can be used only with OpenID 2.0, so checking only SREG
$this->sreg = strpos($content, '<Type>http://openid.net/sreg/1.0</Type>')
|| strpos($content, '<Type>http://openid.net/extensions/sreg/1.1</Type>');
$server = $server[1];
if (isset($delegate[1])) $this->identity = $delegate[1];
$this->version = 1;
$this->server = $server;
return $server;
}
}
$next = true;
$yadis = false;
$url = $originalUrl;
$content = null;
break;
}
if ($next) continue;
# There are no relevant information in headers, so we search the body.
$content = $this->request($url, 'GET', array(), true);
if (isset($this->headers['x-xrds-location'])) {
$url = $this->build_url(parse_url($url), parse_url(trim($this->headers['x-xrds-location'])));
continue;
}
$location = $this->htmlTag($content, 'meta', 'http-equiv', 'X-XRDS-Location', 'content');
if ($location) {
$url = $this->build_url(parse_url($url), parse_url($location));
continue;
}
}
if (!$content) $content = $this->request($url, 'GET');
# At this point, the YADIS Discovery has failed, so we'll switch
# to openid2 HTML discovery, then fallback to openid 1.1 discovery.
$server = $this->htmlTag($content, 'link', 'rel', 'openid2.provider', 'href');
$delegate = $this->htmlTag($content, 'link', 'rel', 'openid2.local_id', 'href');
$this->version = 2;
if (!$server) {
# The same with openid 1.1
$server = $this->htmlTag($content, 'link', 'rel', 'openid.server', 'href');
$delegate = $this->htmlTag($content, 'link', 'rel', 'openid.delegate', 'href');
$this->version = 1;
}
if ($server) {
# We found an OpenID2 OP Endpoint
if ($delegate) {
# We have also found an OP-Local ID.
$this->identity = $delegate;
}
$this->server = $server;
return $server;
}
throw new ErrorException("No OpenID Server found at $url", 404);
}
throw new ErrorException('Endless redirection!', 500);
}
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 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) {
$params['openid.sreg.required'] = array();
foreach ($this->required as $required) {
if (!isset(self::$ax_to_sreg[$required])) continue;
$params['openid.sreg.required'][] = self::$ax_to_sreg[$required];
}
$params['openid.sreg.required'] = implode(',', $params['openid.sreg.required']);
}
if ($this->optional) {
$params['openid.sreg.optional'] = array();
foreach ($this->optional as $optional) {
if (!isset(self::$ax_to_sreg[$optional])) continue;
$params['openid.sreg.optional'][] = self::$ax_to_sreg[$optional];
}
$params['openid.sreg.optional'] = implode(',', $params['openid.sreg.optional']);
}
return $params;
}
protected function axParams()
{
$params = array();
if ($this->required || $this->optional) {
$params['openid.ns.ax'] = 'http://openid.net/srv/ax/1.0';
$params['openid.ax.mode'] = 'fetch_request';
$this->aliases = array();
$counts = array();
$required = array();
$optional = array();
foreach (array('required','optional') as $type) {
foreach ($this->$type as $alias => $field) {
if (is_int($alias)) $alias = strtr($field, '/', '_');
$this->aliases[$alias] = 'http://axschema.org/' . $field;
if (empty($counts[$alias])) $counts[$alias] = 0;
$counts[$alias] += 1;
${$type}[] = $alias;
}
}
foreach ($this->aliases as $alias => $ns) {
$params['openid.ax.type.' . $alias] = $ns;
}
foreach ($counts as $alias => $count) {
if ($count == 1) continue;
$params['openid.ax.count.' . $alias] = $count;
}
# 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);
}
if($optional) {
$params['openid.ax.if_available'] = implode(',', $optional);
}
}
return $params;
}
protected function authUrl_v1($immediate)
{
$returnUrl = $this->returnUrl;
# If we have an openid.delegate that is different from our claimed id,
# we need to somehow preserve the claimed id between requests.
# The simplest way is to just send it along with the return_to url.
if($this->identity != $this->claimed_id) {
$returnUrl .= (strpos($returnUrl, '?') ? '&' : '?') . 'openid.claimed_id=' . $this->claimed_id;
}
$params = array(
'openid.return_to' => $returnUrl,
'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup',
'openid.identity' => $this->identity,
'openid.trust_root' => $this->trustRoot,
) + $this->sregParams();
return $this->build_url(parse_url($this->server)
, array('query' => http_build_query($params, '', '&')));
}
protected function authUrl_v2($immediate)
{
$params = array(
'openid.ns' => 'http://specs.openid.net/auth/2.0',
'openid.mode' => $immediate ? 'checkid_immediate' : 'checkid_setup',
'openid.return_to' => $this->returnUrl,
'openid.realm' => $this->trustRoot,
);
if ($this->ax) {
$params += $this->axParams();
}
if ($this->sreg) {
$params += $this->sregParams();
}
if (!$this->ax && !$this->sreg) {
# If OP doesn't advertise either SREG, nor AX, let's send them both
# in worst case we don't get anything in return.
$params += $this->axParams() + $this->sregParams();
}
if ($this->identifier_select) {
$params['openid.identity'] = $params['openid.claimed_id']
= 'http://specs.openid.net/auth/2.0/identifier_select';
} else {
$params['openid.identity'] = $this->identity;
$params['openid.claimed_id'] = $this->claimed_id;
}
return $this->build_url(parse_url($this->server)
, array('query' => http_build_query($params, '', '&')));
}
/**
* Returns authentication url. Usually, you want to redirect your user to it.
* @return String The authentication url.
* @param String $select_identifier Whether to request OP to select identity for an user in OpenID 2. Does not affect OpenID 1.
* @throws ErrorException
*/
function authUrl($immediate = false)
{
if ($this->setup_url && !$immediate) return $this->setup_url;
if (!$this->server) $this->discover($this->identity);
if ($this->version == 2) {
return $this->authUrl_v2($immediate);
}
return $this->authUrl_v1($immediate);
}
/**
* Performs OpenID verification with the OP.
* @return Bool Whether the verification was successful.
* @throws ErrorException
*/
function validate()
{
# If the request was using immediate mode, a failure may be reported
# by presenting user_setup_url (for 1.1) or reporting
# mode 'setup_needed' (for 2.0). Also catching all modes other than
# id_res, in order to avoid throwing errors.
if(isset($this->data['openid_user_setup_url'])) {
$this->setup_url = $this->data['openid_user_setup_url'];
return false;
}
if($this->mode != 'id_res') {
return false;
}
$this->claimed_id = isset($this->data['openid_claimed_id'])?$this->data['openid_claimed_id']:$this->data['openid_identity'];
$params = array(
'openid.assoc_handle' => $this->data['openid_assoc_handle'],
'openid.signed' => $this->data['openid_signed'],
'openid.sig' => $this->data['openid_sig'],
);
if (isset($this->data['openid_ns'])) {
# We're dealing with an OpenID 2.0 server, so let's set an ns
# Even though we should know location of the endpoint,
# we still need to verify it by discovery, so $server is not set here
$params['openid.ns'] = 'http://specs.openid.net/auth/2.0';
} elseif (isset($this->data['openid_claimed_id'])
&& $this->data['openid_claimed_id'] != $this->data['openid_identity']
) {
# If it's an OpenID 1 provider, and we've got claimed_id,
# we have to append it to the returnUrl, like authUrl_v1 does.
$this->returnUrl .= (strpos($this->returnUrl, '?') ? '&' : '?')
. 'openid.claimed_id=' . $this->claimed_id;
}
if ($this->data['openid_return_to'] != $this->returnUrl) {
# The return_to url must match the url of current request.
# I'm assuing that noone will set the returnUrl to something that doesn't make sense.
return false;
}
$server = $this->discover($this->claimed_id);
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 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.
$value = $this->data['openid_' . str_replace('.','_',$item)];
$params['openid.' . $item] = function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() ? stripslashes($value) : $value;
}
$params['openid.mode'] = 'check_authentication';
$response = $this->request($server, 'POST', $params);
return preg_match('/is_valid\s*:\s*true/i', $response);
}
protected function getAxAttributes()
{
$alias = null;
if (isset($this->data['openid_ns_ax'])
&& $this->data['openid_ns_ax'] != 'http://openid.net/srv/ax/1.0'
) { # It's the most likely case, so we'll check it before
$alias = 'ax';
} else {
# 'ax' prefix is either undefined, or points to another extension,
# so we search for another prefix
foreach ($this->data as $key => $val) {
if (substr($key, 0, strlen('openid_ns_')) == 'openid_ns_'
&& $val == 'http://openid.net/srv/ax/1.0'
) {
$alias = substr($key, strlen('openid_ns_'));
break;
}
}
}
if (!$alias) {
# An alias for AX schema has not been found,
# so there is no AX data in the OP's response
return array();
}
$attributes = array();
foreach (explode(',', $this->data['openid_signed']) as $key) {
$keyMatch = $alias . '.value.';
if (substr($key, 0, strlen($keyMatch)) != $keyMatch) {
continue;
}
$key = substr($key, strlen($keyMatch));
if (!isset($this->data['openid_' . $alias . '_type_' . $key])) {
# OP is breaking the spec by returning a field without
# associated ns. This shouldn't happen, but it's better
# to check, than cause an E_NOTICE.
continue;
}
$value = $this->data['openid_' . $alias . '_value_' . $key];
$key = substr($this->data['openid_' . $alias . '_type_' . $key],
strlen('http://axschema.org/'));
$attributes[$key] = $value;
}
return $attributes;
}
protected function getSregAttributes()
{
$attributes = array();
$sreg_to_ax = array_flip(self::$ax_to_sreg);
foreach (explode(',', $this->data['openid_signed']) as $key) {
$keyMatch = 'sreg.';
if (substr($key, 0, strlen($keyMatch)) != $keyMatch) {
continue;
}
$key = substr($key, strlen($keyMatch));
if (!isset($sreg_to_ax[$key])) {
# The field name isn't part of the SREG spec, so we ignore it.
continue;
}
$attributes[$sreg_to_ax[$key]] = $this->data['openid_sreg_' . $key];
}
return $attributes;
}
/**
* 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.
* * SREG names will be mapped to AX names.
* * @return Array Array of attributes with keys being the AX schema names, e.g. 'contact/email'
* @see http://www.axschema.org/types/
*/
function getAttributes()
{
if (isset($this->data['openid_ns'])
&& $this->data['openid_ns'] == 'http://specs.openid.net/auth/2.0'
) { # OpenID 2.0
# We search for both AX and SREG attributes, with AX taking precedence.
return $this->getAxAttributes() + $this->getSregAttributes();
}
return $this->getSregAttributes();
}
}

View File

@@ -0,0 +1,194 @@
<?php
// OAuthWrapHandler.php 1.1
/**
* FILE: OAuthWrapHandler.php
*
* DESCRIPTION: Sample implementation of OAuth WRAP Authentication protocol.
*
* VERSION: 1.1
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*
* OAuthWrapHandler
* This handler is used to both process the raw HTTP requests that generate the
* required cookies for the Windows Live javascript control to work within a
* php applicaiton.
*/
class OAuthWrapHandler
{
public function ProcessRequest()
{
$this->ExpireCookies();
$cookies_setup = $this->convertParamsToCookies($_REQUEST);
if(isset($cookies_setup['verification_code']))
{
$auth_params = $this->getAuthorizationToken(
WRAP_ACCESS_URL
, WRAP_CLIENT_ID
, WRAP_CLIENT_SECRET
, WRAP_CALLBACK
, $cookies_setup['verification_code']
);
unset($cookies_setup['verification_code']);
}
else
{
throw new Exception("No verification Code returned from Windows Live Services.");
}
$cookies_auth = $this->convertParamsToCookies($auth_params);
$cookies = array_merge($cookies_setup, $cookies_auth);
$this->setAuthCookies($cookies);
return $cookies;
}
public function ExpireCookies()
{
setcookie ("c_accessToken", "", time() - 3600);
setcookie ("c_clientId", "", time() - 3600);
setcookie ("c_clientState", "", time() - 3600);
setcookie ("c_scope", "", time() - 3600);
setcookie ("c_error", "", time() - 3600);
setcookie ("c_uid", "", time() - 3600);
setcookie ("c_expiry", "", time() - 3600);
setcookie ("lca", "", time() - 3600);
}
private function setAuthCookies($cookies)
{
foreach($cookies as $key => $value)
{
setcookie ($key, $value, time() + 36000);
}
setcookie ('c_clientId', WRAP_CLIENT_ID, time() + 36000); //clientID == appId
setcookie ('lca', 'done', time() + 36000); //lca //done
}
private function convertParamsToCookies($array)
{
$cookies = array();
foreach(array_keys($array) as $getParam)
{
$getParam = urldecode($getParam);
switch($getParam)
{
case 'wrap_client_state':
$cookies['c_clientState'] = $array['wrap_client_state'];
break;
case 'wrap_verification_code':
$cookies['verification_code'] = $array['wrap_verification_code'];
break;
case 'exp': //scope
$cookies['c_scope'] = str_replace(';', ',',$array['exp']);
break;
case 'error_code':
$cookies['c_error'] = ' ' . $array['error_code'];
break;
case 'wrap_error_reason':
$cookies['c_error'] = ' ' . $array['wrap_error_reason'];
break;
case 'wrap_access_token':
$cookies['c_accessToken']= $array['wrap_access_token'];
break;
case 'wrap_access_token_expires_in':
$cookies['c_expiry']= date('j/m/Y g:i:s A', $array['wrap_access_token_expires_in']);
break;
case 'uid':
$cookies['c_uid']= $array['uid'];
break;
}
}
return $cookies;
}
private function getAuthorizationToken($authUrl, $appId, $appSecret, $callbackUrl, $verificationCode)
{
$tokenRequest = 'wrap_client_id=' . urlencode($appId)
. '&wrap_client_secret=' . urlencode($appSecret)
. '&wrap_callback=' . urlencode($callbackUrl)
. '&wrap_verification_code=' . urlencode($verificationCode);
$response = $this->postWRAPRequest($authUrl, $tokenRequest);
return $this->parseWRAPResponse($response);
}
private function postWRAPRequest($posturl, $postvars)
{
$ch = curl_init($posturl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
@ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$Rec_Data = curl_exec($ch);
curl_close($ch);
return urldecode($Rec_Data);
}
private function parseWRAPResponse($response)
{
$pos = strpos($response, 'wrap_access_token=');
if ($pos === false)
{
$pos = strpos($response, 'wrap_error_reason=');
}
$codes = '?' . substr($response, $pos, strlen($response));
if (preg_match_all('/[?&]([^&=]+)=([^&=]+)/', $codes, $matches))
{
for($i =0; $i < count($matches[1]); $i++)
{
$contents[$matches[1][$i]] = $matches[2][$i];
}
}
else
{
throw new Exception('No matches for regular expression.');
}
return $contents;
}
public function GET($url,$params=false,$auth=false){
$url = $this->MakeUrl($url,$params);
// borrowed from Andy Langton: http://andylangton.co.uk/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HTTPHEADER,array (
"Authorization: WRAP access_token=$auth",
"Content-Type: application/json",
"Accept: application/json"
));
if ( isset($_SERVER['HTTP_USER_AGENT']) ) {
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] );
}else {
// Handle the useragent like we are Google Chrome
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.X.Y.Z Safari/525.13.');
}
curl_setopt($ch , CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result=curl_exec($ch);
$info=curl_getinfo($ch);
curl_close($ch);
return $result;
}
public function MakeUrl($url,$params){
if(!empty($params) && $params){
foreach($params as $k=>$v) $kv[] = "$k=$v";
$url_params = str_replace(" ","+",implode('&',$kv));
$url = trim($url) . '?' . $url_params;
}
return $url;
}
}

View File

@@ -0,0 +1,10 @@
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

View File

@@ -0,0 +1,15 @@
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | https://github.com/hybridauth/hybridauth
* (c) 2009-2011 HybridAuth authors | hybridauth.sourceforge.net/licenses.html
*/
// ------------------------------------------------------------------------
// HybridAuth End Point
// ------------------------------------------------------------------------
require_once("../../class2.php");
require_once( "Hybrid/Auth.php" );
require_once( "Hybrid/Endpoint.php" );
Hybrid_Endpoint::process();

View File

@@ -225,8 +225,8 @@ $SIGNUP_BEGIN = "
if(!defined($SIGNUP_BODY))
{
// TODO Add other signup options for Facebook and Twitter.
$SIGNUP_BODY = "<div class='signup-other'>{FB=login}{TW=login}</div>
$SIGNUP_BODY = "
{SIGNUP_XUP}
<div id='default'>
{SIGNUP_XUP_ACTION}