source: extensions/oAuth/include/hybridauth/Hybrid/Auth.php @ 20293

Last change on this file since 20293 was 20293, checked in by mistic100, 11 years ago

first commit of oAuth plugin, still in developpement

File size: 12.7 KB
Line 
1<?php
2/*!
3* HybridAuth
4* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
5* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
6*/
7
8/**
9 * Hybrid_Auth class
10 *
11 * Hybrid_Auth class provide a simple way to authenticate users via OpenID and OAuth.
12 *
13 * Generally, Hybrid_Auth is the only class you should instanciate and use throughout your application.
14 */
15class Hybrid_Auth 
16{
17        public static $version = "2.1.1-dev";
18
19        public static $config  = array();
20
21        public static $store   = NULL;
22
23        public static $error   = NULL;
24
25        public static $logger  = NULL;
26
27        // --------------------------------------------------------------------
28
29        /**
30        * Try to start a new session of none then initialize Hybrid_Auth
31        *
32        * Hybrid_Auth constructor will require either a valid config array or
33        * a path for a configuration file as parameter. To know more please
34        * refer to the Configuration section:
35        * http://hybridauth.sourceforge.net/userguide/Configuration.html
36        */
37        function __construct( $config )
38        { 
39                Hybrid_Auth::initialize( $config ); 
40        }
41
42        // --------------------------------------------------------------------
43
44        /**
45        * Try to initialize Hybrid_Auth with given $config hash or file
46        */
47        public static function initialize( $config )
48        {
49                if( ! is_array( $config ) && ! file_exists( $config ) ){
50                        throw new Exception( "Hybriauth config does not exist on the given path.", 1 );
51                }
52
53                if( ! is_array( $config ) ){
54                        $config = include $config;
55                }
56
57                // build some need'd paths
58                $config["path_base"]        = realpath( dirname( __FILE__ ) )  . "/"; 
59                $config["path_libraries"]   = $config["path_base"] . "thirdparty/";
60                $config["path_resources"]   = $config["path_base"] . "resources/";
61                $config["path_providers"]   = $config["path_base"] . "Providers/";
62
63                // reset debug mode
64                if( ! isset( $config["debug_mode"] ) ){
65                        $config["debug_mode"] = false;
66                        $config["debug_file"] = null;
67                }
68
69                # load hybridauth required files, a autoload is on the way...
70                require_once $config["path_base"] . "Error.php";
71                require_once $config["path_base"] . "Logger.php";
72
73                require_once $config["path_base"] . "Storage.php";
74
75                require_once $config["path_base"] . "Provider_Adapter.php";
76
77                require_once $config["path_base"] . "Provider_Model.php";
78                require_once $config["path_base"] . "Provider_Model_OpenID.php";
79                require_once $config["path_base"] . "Provider_Model_OAuth1.php";
80                require_once $config["path_base"] . "Provider_Model_OAuth2.php";
81
82                require_once $config["path_base"] . "User.php";
83                require_once $config["path_base"] . "User_Profile.php";
84                require_once $config["path_base"] . "User_Contact.php";
85                require_once $config["path_base"] . "User_Activity.php";
86
87                // hash given config
88                Hybrid_Auth::$config = $config;
89
90                // instace of log mng
91                Hybrid_Auth::$logger = new Hybrid_Logger();
92
93                // instace of errors mng
94                Hybrid_Auth::$error = new Hybrid_Error();
95
96                // start session storage mng
97                Hybrid_Auth::$store = new Hybrid_Storage();
98
99                Hybrid_Logger::info( "Enter Hybrid_Auth::initialize()"); 
100                Hybrid_Logger::info( "Hybrid_Auth::initialize(). PHP version: " . PHP_VERSION ); 
101                Hybrid_Logger::info( "Hybrid_Auth::initialize(). Hybrid_Auth version: " . Hybrid_Auth::$version ); 
102                Hybrid_Logger::info( "Hybrid_Auth::initialize(). Hybrid_Auth called from: " . Hybrid_Auth::getCurrentUrl() ); 
103
104                // PHP Curl extension [http://www.php.net/manual/en/intro.curl.php]
105                if ( ! function_exists('curl_init') ) {
106                        Hybrid_Logger::error('Hybridauth Library needs the CURL PHP extension.');
107                        throw new Exception('Hybridauth Library needs the CURL PHP extension.');
108                }
109
110                // PHP JSON extension [http://php.net/manual/en/book.json.php]
111                if ( ! function_exists('json_decode') ) {
112                        Hybrid_Logger::error('Hybridauth Library needs the JSON PHP extension.');
113                        throw new Exception('Hybridauth Library needs the JSON PHP extension.');
114                } 
115
116                // session.name
117                if( session_name() != "PHPSESSID" ){
118                        Hybrid_Logger::info('PHP session.name diff from default PHPSESSID. http://php.net/manual/en/session.configuration.php#ini.session.name.');
119                }
120
121                // safe_mode is on
122                if( ini_get('safe_mode') ){
123                        Hybrid_Logger::info('PHP safe_mode is on. http://php.net/safe-mode.');
124                }
125
126                // open basedir is on
127                if( ini_get('open_basedir') ){
128                        Hybrid_Logger::info('PHP open_basedir is on. http://php.net/open-basedir.');
129                }
130
131                Hybrid_Logger::debug( "Hybrid_Auth initialize. dump used config: ", serialize( $config ) );
132                Hybrid_Logger::debug( "Hybrid_Auth initialize. dump current session: ", Hybrid_Auth::storage()->getSessionData() ); 
133                Hybrid_Logger::info( "Hybrid_Auth initialize: check if any error is stored on the endpoint..." );
134
135                if( Hybrid_Error::hasError() ){ 
136                        $m = Hybrid_Error::getErrorMessage();
137                        $c = Hybrid_Error::getErrorCode();
138                        $p = Hybrid_Error::getErrorPrevious();
139
140                        Hybrid_Logger::error( "Hybrid_Auth initialize: A stored Error found, Throw an new Exception and delete it from the store: Error#$c, '$m'" );
141
142                        Hybrid_Error::clearError();
143
144                        // try to provide the previous if any
145                        // Exception::getPrevious (PHP 5 >= 5.3.0) http://php.net/manual/en/exception.getprevious.php
146                        if ( version_compare( PHP_VERSION, '5.3.0', '>=' ) && ($p instanceof Exception) ) { 
147                                throw new Exception( $m, $c, $p );
148                        }
149                        else{
150                                throw new Exception( $m, $c );
151                        }
152                }
153
154                Hybrid_Logger::info( "Hybrid_Auth initialize: no error found. initialization succeed." );
155
156                // Endof initialize
157        }
158
159        // --------------------------------------------------------------------
160
161        /**
162        * Hybrid storage system accessor
163        *
164        * Users sessions are stored using HybridAuth storage system ( HybridAuth 2.0 handle PHP Session only) and can be acessed directly by
165        * Hybrid_Auth::storage()->get($key) to retrieves the data for the given key, or calling
166        * Hybrid_Auth::storage()->set($key, $value) to store the key => $value set.
167        */
168        public static function storage()
169        {
170                return Hybrid_Auth::$store;
171        }
172
173        // --------------------------------------------------------------------
174
175        /**
176        * Get hybridauth session data.
177        */
178        function getSessionData()
179        { 
180                return Hybrid_Auth::storage()->getSessionData();
181        }
182
183        // --------------------------------------------------------------------
184
185        /**
186        * restore hybridauth session data.
187        */
188        function restoreSessionData( $sessiondata = NULL )
189        { 
190                Hybrid_Auth::storage()->restoreSessionData( $sessiondata );
191        }
192
193        // --------------------------------------------------------------------
194
195        /**
196        * Try to authenticate the user with a given provider.
197        *
198        * If the user is already connected we just return and instance of provider adapter,
199        * ELSE, try to authenticate and authorize the user with the provider.
200        *
201        * $params is generally an array with required info in order for this provider and HybridAuth to work,
202        *  like :
203        *          hauth_return_to: URL to call back after authentication is done
204        *        openid_identifier: The OpenID identity provider identifier
205        *           google_service: can be "Users" for Google user accounts service or "Apps" for Google hosted Apps
206        */
207        public static function authenticate( $providerId, $params = NULL )
208        {
209                Hybrid_Logger::info( "Enter Hybrid_Auth::authenticate( $providerId )" );
210
211                // if user not connected to $providerId then try setup a new adapter and start the login process for this provider
212                if( ! Hybrid_Auth::storage()->get( "hauth_session.$providerId.is_logged_in" ) ){ 
213                        Hybrid_Logger::info( "Hybrid_Auth::authenticate( $providerId ), User not connected to the provider. Try to authenticate.." );
214
215                        $provider_adapter = Hybrid_Auth::setup( $providerId, $params );
216
217                        $provider_adapter->login();
218                }
219
220                // else, then return the adapter instance for the given provider
221                else{
222                        Hybrid_Logger::info( "Hybrid_Auth::authenticate( $providerId ), User is already connected to this provider. Return the adapter instance." );
223
224                        return Hybrid_Auth::getAdapter( $providerId );
225                }
226        }
227
228        // --------------------------------------------------------------------
229
230        /**
231        * Return the adapter instance for an authenticated provider
232        */ 
233        public static function getAdapter( $providerId = NULL )
234        {
235                Hybrid_Logger::info( "Enter Hybrid_Auth::getAdapter( $providerId )" );
236
237                return Hybrid_Auth::setup( $providerId );
238        }
239
240        // --------------------------------------------------------------------
241
242        /**
243        * Setup an adapter for a given provider
244        */ 
245        public static function setup( $providerId, $params = NULL )
246        {
247                Hybrid_Logger::debug( "Enter Hybrid_Auth::setup( $providerId )", $params );
248
249                if( ! $params ){ 
250                        $params = Hybrid_Auth::storage()->get( "hauth_session.$providerId.id_provider_params" );
251                       
252                        Hybrid_Logger::debug( "Hybrid_Auth::setup( $providerId ), no params given. Trying to get the stored for this provider.", $params );
253                }
254
255                if( ! $params ){ 
256                        $params = ARRAY();
257                       
258                        Hybrid_Logger::info( "Hybrid_Auth::setup( $providerId ), no stored params found for this provider. Initialize a new one for new session" );
259                }
260
261                if( ! isset( $params["hauth_return_to"] ) ){
262                        $params["hauth_return_to"] = Hybrid_Auth::getCurrentUrl(); 
263                }
264
265                Hybrid_Logger::debug( "Hybrid_Auth::setup( $providerId ). HybridAuth Callback URL set to: ", $params["hauth_return_to"] );
266
267                # instantiate a new IDProvider Adapter
268                $provider   = new Hybrid_Provider_Adapter();
269
270                $provider->factory( $providerId, $params );
271
272                return $provider;
273        } 
274
275        // --------------------------------------------------------------------
276
277        /**
278        * Check if the current user is connected to a given provider
279        */
280        public static function isConnectedWith( $providerId )
281        {
282                return (bool) Hybrid_Auth::storage()->get( "hauth_session.{$providerId}.is_logged_in" );
283        }
284
285        // --------------------------------------------------------------------
286
287        /**
288        * Return array listing all authenticated providers
289        */ 
290        public static function getConnectedProviders()
291        {
292                $idps = array();
293
294                foreach( Hybrid_Auth::$config["providers"] as $idpid => $params ){
295                        if( Hybrid_Auth::isConnectedWith( $idpid ) ){
296                                $idps[] = $idpid;
297                        }
298                }
299
300                return $idps;
301        }
302
303        // --------------------------------------------------------------------
304
305        /**
306        * Return array listing all enabled providers as well as a flag if you are connected.
307        */ 
308        public static function getProviders()
309        {
310                $idps = array();
311
312                foreach( Hybrid_Auth::$config["providers"] as $idpid => $params ){
313                        if($params['enabled']) {
314                                $idps[$idpid] = array( 'connected' => false );
315
316                                if( Hybrid_Auth::isConnectedWith( $idpid ) ){
317                                        $idps[$idpid]['connected'] = true;
318                                }
319                        }
320                }
321
322                return $idps;
323        }
324
325        // --------------------------------------------------------------------
326
327        /**
328        * A generic function to logout all connected provider at once
329        */ 
330        public static function logoutAllProviders()
331        {
332                $idps = Hybrid_Auth::getConnectedProviders();
333
334                foreach( $idps as $idp ){
335                        $adapter = Hybrid_Auth::getAdapter( $idp );
336
337                        $adapter->logout();
338                }
339        }
340
341        // --------------------------------------------------------------------
342
343        /**
344        * Utility function, redirect to a given URL with php header or using javascript location.href
345        */
346        public static function redirect( $url, $mode = "PHP" )
347        {
348                Hybrid_Logger::info( "Enter Hybrid_Auth::redirect( $url, $mode )" );
349
350                if( $mode == "PHP" ){
351                        header( "Location: $url" ) ;
352                }
353                elseif( $mode == "JS" ){
354                        echo '<html>';
355                        echo '<head>';
356                        echo '<script type="text/javascript">';
357                        echo 'function redirect(){ window.top.location.href="' . $url . '"; }';
358                        echo '</script>';
359                        echo '</head>';
360                        echo '<body onload="redirect()">';
361                        echo 'Redirecting, please wait...';
362                        echo '</body>';
363                        echo '</html>'; 
364                }
365
366                die();
367        }
368
369        // --------------------------------------------------------------------
370
371        /**
372        * Utility function, return the current url. TRUE to get $_SERVER['REQUEST_URI'], FALSE for $_SERVER['PHP_SELF']
373        */
374        public static function getCurrentUrl( $request_uri = true ) 
375        {
376                if(
377                        isset( $_SERVER['HTTPS'] ) && ( $_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 )
378                ||      isset( $_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
379                ){
380                        $protocol = 'https://';
381                }
382                else {
383                        $protocol = 'http://';
384                }
385
386                $url = $protocol . $_SERVER['HTTP_HOST'];
387
388                // use port if non default
389                $url .= 
390                        isset( $_SERVER['SERVER_PORT'] ) 
391                        &&( ($protocol === 'http://' && $_SERVER['SERVER_PORT'] != 80) || ($protocol === 'https://' && $_SERVER['SERVER_PORT'] != 443) )
392                        ? ':' . $_SERVER['SERVER_PORT'] 
393                        : '';
394
395                if( $request_uri ){
396                        $url .= $_SERVER['REQUEST_URI'];
397                }
398                else{
399                        $url .= $_SERVER['PHP_SELF'];
400                }
401
402                // return current url
403                return $url;
404        }
405}
Note: See TracBrowser for help on using the repository browser.