TYPO3 API  SVNRelease
Consumer.php
Go to the documentation of this file.
00001 <?php
00002 
00003 /**
00004  * This module documents the main interface with the OpenID consumer
00005  * library.  The only part of the library which has to be used and
00006  * isn't documented in full here is the store required to create an
00007  * Auth_OpenID_Consumer instance.  More on the abstract store type and
00008  * concrete implementations of it that are provided in the
00009  * documentation for the Auth_OpenID_Consumer constructor.
00010  *
00011  * OVERVIEW
00012  *
00013  * The OpenID identity verification process most commonly uses the
00014  * following steps, as visible to the user of this library:
00015  *
00016  *   1. The user enters their OpenID into a field on the consumer's
00017  *      site, and hits a login button.
00018  *   2. The consumer site discovers the user's OpenID server using the
00019  *      YADIS protocol.
00020  *   3. The consumer site sends the browser a redirect to the identity
00021  *      server.  This is the authentication request as described in
00022  *      the OpenID specification.
00023  *   4. The identity server's site sends the browser a redirect back
00024  *      to the consumer site.  This redirect contains the server's
00025  *      response to the authentication request.
00026  *
00027  * The most important part of the flow to note is the consumer's site
00028  * must handle two separate HTTP requests in order to perform the full
00029  * identity check.
00030  *
00031  * LIBRARY DESIGN
00032  *
00033  * This consumer library is designed with that flow in mind.  The goal
00034  * is to make it as easy as possible to perform the above steps
00035  * securely.
00036  *
00037  * At a high level, there are two important parts in the consumer
00038  * library.  The first important part is this module, which contains
00039  * the interface to actually use this library.  The second is the
00040  * Auth_OpenID_Interface class, which describes the interface to use
00041  * if you need to create a custom method for storing the state this
00042  * library needs to maintain between requests.
00043  *
00044  * In general, the second part is less important for users of the
00045  * library to know about, as several implementations are provided
00046  * which cover a wide variety of situations in which consumers may use
00047  * the library.
00048  *
00049  * This module contains a class, Auth_OpenID_Consumer, with methods
00050  * corresponding to the actions necessary in each of steps 2, 3, and 4
00051  * described in the overview.  Use of this library should be as easy
00052  * as creating an Auth_OpenID_Consumer instance and calling the
00053  * methods appropriate for the action the site wants to take.
00054  *
00055  * STORES AND DUMB MODE
00056  *
00057  * OpenID is a protocol that works best when the consumer site is able
00058  * to store some state.  This is the normal mode of operation for the
00059  * protocol, and is sometimes referred to as smart mode.  There is
00060  * also a fallback mode, known as dumb mode, which is available when
00061  * the consumer site is not able to store state.  This mode should be
00062  * avoided when possible, as it leaves the implementation more
00063  * vulnerable to replay attacks.
00064  *
00065  * The mode the library works in for normal operation is determined by
00066  * the store that it is given.  The store is an abstraction that
00067  * handles the data that the consumer needs to manage between http
00068  * requests in order to operate efficiently and securely.
00069  *
00070  * Several store implementation are provided, and the interface is
00071  * fully documented so that custom stores can be used as well.  See
00072  * the documentation for the Auth_OpenID_Consumer class for more
00073  * information on the interface for stores.  The implementations that
00074  * are provided allow the consumer site to store the necessary data in
00075  * several different ways, including several SQL databases and normal
00076  * files on disk.
00077  *
00078  * There is an additional concrete store provided that puts the system
00079  * in dumb mode.  This is not recommended, as it removes the library's
00080  * ability to stop replay attacks reliably.  It still uses time-based
00081  * checking to make replay attacks only possible within a small
00082  * window, but they remain possible within that window.  This store
00083  * should only be used if the consumer site has no way to retain data
00084  * between requests at all.
00085  *
00086  * IMMEDIATE MODE
00087  *
00088  * In the flow described above, the user may need to confirm to the
00089  * lidentity server that it's ok to authorize his or her identity.
00090  * The server may draw pages asking for information from the user
00091  * before it redirects the browser back to the consumer's site.  This
00092  * is generally transparent to the consumer site, so it is typically
00093  * ignored as an implementation detail.
00094  *
00095  * There can be times, however, where the consumer site wants to get a
00096  * response immediately.  When this is the case, the consumer can put
00097  * the library in immediate mode.  In immediate mode, there is an
00098  * extra response possible from the server, which is essentially the
00099  * server reporting that it doesn't have enough information to answer
00100  * the question yet.
00101  *
00102  * USING THIS LIBRARY
00103  *
00104  * Integrating this library into an application is usually a
00105  * relatively straightforward process.  The process should basically
00106  * follow this plan:
00107  *
00108  * Add an OpenID login field somewhere on your site.  When an OpenID
00109  * is entered in that field and the form is submitted, it should make
00110  * a request to the your site which includes that OpenID URL.
00111  *
00112  * First, the application should instantiate the Auth_OpenID_Consumer
00113  * class using the store of choice (Auth_OpenID_FileStore or one of
00114  * the SQL-based stores).  If the application has a custom
00115  * session-management implementation, an object implementing the
00116  * {@link Auth_Yadis_PHPSession} interface should be passed as the
00117  * second parameter.  Otherwise, the default uses $_SESSION.
00118  *
00119  * Next, the application should call the Auth_OpenID_Consumer object's
00120  * 'begin' method.  This method takes the OpenID URL.  The 'begin'
00121  * method returns an Auth_OpenID_AuthRequest object.
00122  *
00123  * Next, the application should call the 'redirectURL' method of the
00124  * Auth_OpenID_AuthRequest object.  The 'return_to' URL parameter is
00125  * the URL that the OpenID server will send the user back to after
00126  * attempting to verify his or her identity.  The 'trust_root' is the
00127  * URL (or URL pattern) that identifies your web site to the user when
00128  * he or she is authorizing it.  Send a redirect to the resulting URL
00129  * to the user's browser.
00130  *
00131  * That's the first half of the authentication process.  The second
00132  * half of the process is done after the user's ID server sends the
00133  * user's browser a redirect back to your site to complete their
00134  * login.
00135  *
00136  * When that happens, the user will contact your site at the URL given
00137  * as the 'return_to' URL to the Auth_OpenID_AuthRequest::redirectURL
00138  * call made above.  The request will have several query parameters
00139  * added to the URL by the identity server as the information
00140  * necessary to finish the request.
00141  *
00142  * Lastly, instantiate an Auth_OpenID_Consumer instance as above and
00143  * call its 'complete' method, passing in all the received query
00144  * arguments.
00145  *
00146  * There are multiple possible return types possible from that
00147  * method. These indicate the whether or not the login was successful,
00148  * and include any additional information appropriate for their type.
00149  *
00150  * PHP versions 4 and 5
00151  *
00152  * LICENSE: See the COPYING file included in this distribution.
00153  *
00154  * @package OpenID
00155  * @author JanRain, Inc. <openid@janrain.com>
00156  * @copyright 2005-2008 Janrain, Inc.
00157  * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
00158  */
00159 
00160 /**
00161  * Require utility classes and functions for the consumer.
00162  */
00163 require_once "Auth/OpenID.php";
00164 require_once "Auth/OpenID/Message.php";
00165 require_once "Auth/OpenID/HMAC.php";
00166 require_once "Auth/OpenID/Association.php";
00167 require_once "Auth/OpenID/CryptUtil.php";
00168 require_once "Auth/OpenID/DiffieHellman.php";
00169 require_once "Auth/OpenID/KVForm.php";
00170 require_once "Auth/OpenID/Nonce.php";
00171 require_once "Auth/OpenID/Discover.php";
00172 require_once "Auth/OpenID/URINorm.php";
00173 require_once "Auth/Yadis/Manager.php";
00174 require_once "Auth/Yadis/XRI.php";
00175 
00176 /**
00177  * This is the status code returned when the complete method returns
00178  * successfully.
00179  */
00180 define('Auth_OpenID_SUCCESS', 'success');
00181 
00182 /**
00183  * Status to indicate cancellation of OpenID authentication.
00184  */
00185 define('Auth_OpenID_CANCEL', 'cancel');
00186 
00187 /**
00188  * This is the status code completeAuth returns when the value it
00189  * received indicated an invalid login.
00190  */
00191 define('Auth_OpenID_FAILURE', 'failure');
00192 
00193 /**
00194  * This is the status code completeAuth returns when the
00195  * {@link Auth_OpenID_Consumer} instance is in immediate mode, and the
00196  * identity server sends back a URL to send the user to to complete his
00197  * or her login.
00198  */
00199 define('Auth_OpenID_SETUP_NEEDED', 'setup needed');
00200 
00201 /**
00202  * This is the status code beginAuth returns when the page fetched
00203  * from the entered OpenID URL doesn't contain the necessary link tags
00204  * to function as an identity page.
00205  */
00206 define('Auth_OpenID_PARSE_ERROR', 'parse error');
00207 
00208 /**
00209  * An OpenID consumer implementation that performs discovery and does
00210  * session management.  See the Consumer.php file documentation for
00211  * more information.
00212  *
00213  * @package OpenID
00214  */
00215 class Auth_OpenID_Consumer {
00216 
00217     /**
00218      * @access private
00219      */
00220     var $discoverMethod = 'Auth_OpenID_discover';
00221 
00222     /**
00223      * @access private
00224      */
00225     var $session_key_prefix = "_openid_consumer_";
00226 
00227     /**
00228      * @access private
00229      */
00230     var $_token_suffix = "last_token";
00231 
00232     /**
00233      * Initialize a Consumer instance.
00234      *
00235      * You should create a new instance of the Consumer object with
00236      * every HTTP request that handles OpenID transactions.
00237      *
00238      * @param Auth_OpenID_OpenIDStore $store This must be an object
00239      * that implements the interface in {@link
00240      * Auth_OpenID_OpenIDStore}.  Several concrete implementations are
00241      * provided, to cover most common use cases.  For stores backed by
00242      * MySQL, PostgreSQL, or SQLite, see the {@link
00243      * Auth_OpenID_SQLStore} class and its sublcasses.  For a
00244      * filesystem-backed store, see the {@link Auth_OpenID_FileStore}
00245      * module.  As a last resort, if it isn't possible for the server
00246      * to store state at all, an instance of {@link
00247      * Auth_OpenID_DumbStore} can be used.
00248      *
00249      * @param mixed $session An object which implements the interface
00250      * of the {@link Auth_Yadis_PHPSession} class.  Particularly, this
00251      * object is expected to have these methods: get($key), set($key),
00252      * $value), and del($key).  This defaults to a session object
00253      * which wraps PHP's native session machinery.  You should only
00254      * need to pass something here if you have your own sessioning
00255      * implementation.
00256      *
00257      * @param str $consumer_cls The name of the class to instantiate
00258      * when creating the internal consumer object.  This is used for
00259      * testing.
00260      */
00261     function Auth_OpenID_Consumer($store, $session = null,
00262                                   $consumer_cls = null)
00263     {
00264         if ($session === null) {
00265             $session = new Auth_Yadis_PHPSession();
00266         }
00267 
00268         $this->session =& $session;
00269 
00270         if ($consumer_cls !== null) {
00271             $this->consumer = new $consumer_cls($store);
00272         } else {
00273             $this->consumer = new Auth_OpenID_GenericConsumer($store);
00274         }
00275 
00276         $this->_token_key = $this->session_key_prefix . $this->_token_suffix;
00277     }
00278 
00279     /**
00280      * Used in testing to define the discovery mechanism.
00281      *
00282      * @access private
00283      */
00284     function getDiscoveryObject($session, $openid_url,
00285                                 $session_key_prefix)
00286     {
00287         return new Auth_Yadis_Discovery($session, $openid_url,
00288                                         $session_key_prefix);
00289     }
00290 
00291     /**
00292      * Start the OpenID authentication process. See steps 1-2 in the
00293      * overview at the top of this file.
00294      *
00295      * @param string $user_url Identity URL given by the user. This
00296      * method performs a textual transformation of the URL to try and
00297      * make sure it is normalized. For example, a user_url of
00298      * example.com will be normalized to http://example.com/
00299      * normalizing and resolving any redirects the server might issue.
00300      *
00301      * @param bool $anonymous True if the OpenID request is to be sent
00302      * to the server without any identifier information.  Use this
00303      * when you want to transport data but don't want to do OpenID
00304      * authentication with identifiers.
00305      *
00306      * @return Auth_OpenID_AuthRequest $auth_request An object
00307      * containing the discovered information will be returned, with a
00308      * method for building a redirect URL to the server, as described
00309      * in step 3 of the overview. This object may also be used to add
00310      * extension arguments to the request, using its 'addExtensionArg'
00311      * method.
00312      */
00313     function begin($user_url, $anonymous=false)
00314     {
00315         $openid_url = $user_url;
00316 
00317         $disco = $this->getDiscoveryObject($this->session,
00318                                            $openid_url,
00319                                            $this->session_key_prefix);
00320 
00321         // Set the 'stale' attribute of the manager.  If discovery
00322         // fails in a fatal way, the stale flag will cause the manager
00323         // to be cleaned up next time discovery is attempted.
00324 
00325         $m = $disco->getManager();
00326         $loader = new Auth_Yadis_ManagerLoader();
00327 
00328         if ($m) {
00329             if ($m->stale) {
00330                 $disco->destroyManager();
00331             } else {
00332                 $m->stale = true;
00333                 $disco->session->set($disco->session_key,
00334                                      serialize($loader->toSession($m)));
00335             }
00336         }
00337 
00338         $endpoint = $disco->getNextService($this->discoverMethod,
00339                                            $this->consumer->fetcher);
00340 
00341         // Reset the 'stale' attribute of the manager.
00342         $m =& $disco->getManager();
00343         if ($m) {
00344             $m->stale = false;
00345             $disco->session->set($disco->session_key,
00346                                  serialize($loader->toSession($m)));
00347         }
00348 
00349         if ($endpoint === null) {
00350             return null;
00351         } else {
00352             return $this->beginWithoutDiscovery($endpoint,
00353                                                 $anonymous);
00354         }
00355     }
00356 
00357     /**
00358      * Start OpenID verification without doing OpenID server
00359      * discovery. This method is used internally by Consumer.begin
00360      * after discovery is performed, and exists to provide an
00361      * interface for library users needing to perform their own
00362      * discovery.
00363      *
00364      * @param Auth_OpenID_ServiceEndpoint $endpoint an OpenID service
00365      * endpoint descriptor.
00366      *
00367      * @param bool anonymous Set to true if you want to perform OpenID
00368      * without identifiers.
00369      *
00370      * @return Auth_OpenID_AuthRequest $auth_request An OpenID
00371      * authentication request object.
00372      */
00373     function &beginWithoutDiscovery($endpoint, $anonymous=false)
00374     {
00375         $loader = new Auth_OpenID_ServiceEndpointLoader();
00376         $auth_req = $this->consumer->begin($endpoint);
00377         $this->session->set($this->_token_key,
00378               $loader->toSession($auth_req->endpoint));
00379         if (!$auth_req->setAnonymous($anonymous)) {
00380             return new Auth_OpenID_FailureResponse(null,
00381               "OpenID 1 requests MUST include the identifier " .
00382               "in the request.");
00383         }
00384         return $auth_req;
00385     }
00386 
00387     /**
00388      * Called to interpret the server's response to an OpenID
00389      * request. It is called in step 4 of the flow described in the
00390      * consumer overview.
00391      *
00392      * @param string $current_url The URL used to invoke the application.
00393      * Extract the URL from your application's web
00394      * request framework and specify it here to have it checked
00395      * against the openid.current_url value in the response.  If
00396      * the current_url URL check fails, the status of the
00397      * completion will be FAILURE.
00398      *
00399      * @param array $query An array of the query parameters (key =>
00400      * value pairs) for this HTTP request.  Defaults to null.  If
00401      * null, the GET or POST data are automatically gotten from the
00402      * PHP environment.  It is only useful to override $query for
00403      * testing.
00404      *
00405      * @return Auth_OpenID_ConsumerResponse $response A instance of an
00406      * Auth_OpenID_ConsumerResponse subclass. The type of response is
00407      * indicated by the status attribute, which will be one of
00408      * SUCCESS, CANCEL, FAILURE, or SETUP_NEEDED.
00409      */
00410     function complete($current_url, $query=null)
00411     {
00412         if ($current_url && !is_string($current_url)) {
00413             // This is ugly, but we need to complain loudly when
00414             // someone uses the API incorrectly.
00415             trigger_error("current_url must be a string; see NEWS file " .
00416                           "for upgrading notes.",
00417                           E_USER_ERROR);
00418         }
00419 
00420         if ($query === null) {
00421             $query = Auth_OpenID::getQuery();
00422         }
00423 
00424         $loader = new Auth_OpenID_ServiceEndpointLoader();
00425         $endpoint_data = $this->session->get($this->_token_key);
00426         $endpoint =
00427             $loader->fromSession($endpoint_data);
00428 
00429         $message = Auth_OpenID_Message::fromPostArgs($query);
00430         $response = $this->consumer->complete($message, $endpoint,
00431                                               $current_url);
00432         $this->session->del($this->_token_key);
00433 
00434         if (in_array($response->status, array(Auth_OpenID_SUCCESS,
00435                                               Auth_OpenID_CANCEL))) {
00436             if ($response->identity_url !== null) {
00437                 $disco = $this->getDiscoveryObject($this->session,
00438                                                    $response->identity_url,
00439                                                    $this->session_key_prefix);
00440                 $disco->cleanup(true);
00441             }
00442         }
00443 
00444         return $response;
00445     }
00446 }
00447 
00448 /**
00449  * A class implementing HMAC/DH-SHA1 consumer sessions.
00450  *
00451  * @package OpenID
00452  */
00453 class Auth_OpenID_DiffieHellmanSHA1ConsumerSession {
00454     var $session_type = 'DH-SHA1';
00455     var $hash_func = 'Auth_OpenID_SHA1';
00456     var $secret_size = 20;
00457     var $allowed_assoc_types = array('HMAC-SHA1');
00458 
00459     function Auth_OpenID_DiffieHellmanSHA1ConsumerSession($dh = null)
00460     {
00461         if ($dh === null) {
00462             $dh = new Auth_OpenID_DiffieHellman();
00463         }
00464 
00465         $this->dh = $dh;
00466     }
00467 
00468     function getRequest()
00469     {
00470         $math =& Auth_OpenID_getMathLib();
00471 
00472         $cpub = $math->longToBase64($this->dh->public);
00473 
00474         $args = array('dh_consumer_public' => $cpub);
00475 
00476         if (!$this->dh->usingDefaultValues()) {
00477             $args = array_merge($args, array(
00478                 'dh_modulus' =>
00479                      $math->longToBase64($this->dh->mod),
00480                 'dh_gen' =>
00481                      $math->longToBase64($this->dh->gen)));
00482         }
00483 
00484         return $args;
00485     }
00486 
00487     function extractSecret($response)
00488     {
00489         if (!$response->hasKey(Auth_OpenID_OPENID_NS,
00490                                'dh_server_public')) {
00491             return null;
00492         }
00493 
00494         if (!$response->hasKey(Auth_OpenID_OPENID_NS,
00495                                'enc_mac_key')) {
00496             return null;
00497         }
00498 
00499         $math =& Auth_OpenID_getMathLib();
00500 
00501         $spub = $math->base64ToLong($response->getArg(Auth_OpenID_OPENID_NS,
00502                                                       'dh_server_public'));
00503         $enc_mac_key = base64_decode($response->getArg(Auth_OpenID_OPENID_NS,
00504                                                        'enc_mac_key'));
00505 
00506         return $this->dh->xorSecret($spub, $enc_mac_key, $this->hash_func);
00507     }
00508 }
00509 
00510 /**
00511  * A class implementing HMAC/DH-SHA256 consumer sessions.
00512  *
00513  * @package OpenID
00514  */
00515 class Auth_OpenID_DiffieHellmanSHA256ConsumerSession extends
00516       Auth_OpenID_DiffieHellmanSHA1ConsumerSession {
00517     var $session_type = 'DH-SHA256';
00518     var $hash_func = 'Auth_OpenID_SHA256';
00519     var $secret_size = 32;
00520     var $allowed_assoc_types = array('HMAC-SHA256');
00521 }
00522 
00523 /**
00524  * A class implementing plaintext consumer sessions.
00525  *
00526  * @package OpenID
00527  */
00528 class Auth_OpenID_PlainTextConsumerSession {
00529     var $session_type = 'no-encryption';
00530     var $allowed_assoc_types =  array('HMAC-SHA1', 'HMAC-SHA256');
00531 
00532     function getRequest()
00533     {
00534         return array();
00535     }
00536 
00537     function extractSecret($response)
00538     {
00539         if (!$response->hasKey(Auth_OpenID_OPENID_NS, 'mac_key')) {
00540             return null;
00541         }
00542 
00543         return base64_decode($response->getArg(Auth_OpenID_OPENID_NS,
00544                                                'mac_key'));
00545     }
00546 }
00547 
00548 /**
00549  * Returns available session types.
00550  */
00551 function Auth_OpenID_getAvailableSessionTypes()
00552 {
00553     $types = array(
00554       'no-encryption' => 'Auth_OpenID_PlainTextConsumerSession',
00555       'DH-SHA1' => 'Auth_OpenID_DiffieHellmanSHA1ConsumerSession',
00556       'DH-SHA256' => 'Auth_OpenID_DiffieHellmanSHA256ConsumerSession');
00557 
00558     return $types;
00559 }
00560 
00561 /**
00562  * This class is the interface to the OpenID consumer logic.
00563  * Instances of it maintain no per-request state, so they can be
00564  * reused (or even used by multiple threads concurrently) as needed.
00565  *
00566  * @package OpenID
00567  */
00568 class Auth_OpenID_GenericConsumer {
00569     /**
00570      * @access private
00571      */
00572     var $discoverMethod = 'Auth_OpenID_discover';
00573 
00574     /**
00575      * This consumer's store object.
00576      */
00577     var $store;
00578 
00579     /**
00580      * @access private
00581      */
00582     var $_use_assocs;
00583 
00584     /**
00585      * @access private
00586      */
00587     var $openid1_nonce_query_arg_name = 'janrain_nonce';
00588 
00589     /**
00590      * Another query parameter that gets added to the return_to for
00591      * OpenID 1; if the user's session state is lost, use this claimed
00592      * identifier to do discovery when verifying the response.
00593      */
00594     var $openid1_return_to_identifier_name = 'openid1_claimed_id';
00595 
00596     /**
00597      * This method initializes a new {@link Auth_OpenID_Consumer}
00598      * instance to access the library.
00599      *
00600      * @param Auth_OpenID_OpenIDStore $store This must be an object
00601      * that implements the interface in {@link Auth_OpenID_OpenIDStore}.
00602      * Several concrete implementations are provided, to cover most common use
00603      * cases.  For stores backed by MySQL, PostgreSQL, or SQLite, see
00604      * the {@link Auth_OpenID_SQLStore} class and its sublcasses.  For a
00605      * filesystem-backed store, see the {@link Auth_OpenID_FileStore} module.
00606      * As a last resort, if it isn't possible for the server to store
00607      * state at all, an instance of {@link Auth_OpenID_DumbStore} can be used.
00608      *
00609      * @param bool $immediate This is an optional boolean value.  It
00610      * controls whether the library uses immediate mode, as explained
00611      * in the module description.  The default value is False, which
00612      * disables immediate mode.
00613      */
00614     function Auth_OpenID_GenericConsumer($store)
00615     {
00616         $this->store =& $store;
00617         $this->negotiator =& Auth_OpenID_getDefaultNegotiator();
00618         $this->_use_assocs = ($this->store ? true : false);
00619 
00620         $this->fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
00621 
00622         $this->session_types = Auth_OpenID_getAvailableSessionTypes();
00623     }
00624 
00625     /**
00626      * Called to begin OpenID authentication using the specified
00627      * {@link Auth_OpenID_ServiceEndpoint}.
00628      *
00629      * @access private
00630      */
00631     function begin($service_endpoint)
00632     {
00633         $assoc = $this->_getAssociation($service_endpoint);
00634         $r = new Auth_OpenID_AuthRequest($service_endpoint, $assoc);
00635         $r->return_to_args[$this->openid1_nonce_query_arg_name] =
00636             Auth_OpenID_mkNonce();
00637 
00638         if ($r->message->isOpenID1()) {
00639             $r->return_to_args[$this->openid1_return_to_identifier_name] =
00640                 $r->endpoint->claimed_id;
00641         }
00642 
00643         return $r;
00644     }
00645 
00646     /**
00647      * Given an {@link Auth_OpenID_Message}, {@link
00648      * Auth_OpenID_ServiceEndpoint} and optional return_to URL,
00649      * complete OpenID authentication.
00650      *
00651      * @access private
00652      */
00653     function complete($message, $endpoint, $return_to)
00654     {
00655         $mode = $message->getArg(Auth_OpenID_OPENID_NS, 'mode',
00656                                  '<no mode set>');
00657 
00658         $mode_methods = array(
00659                               'cancel' => '_complete_cancel',
00660                               'error' => '_complete_error',
00661                               'setup_needed' => '_complete_setup_needed',
00662                               'id_res' => '_complete_id_res',
00663                               );
00664 
00665         $method = Auth_OpenID::arrayGet($mode_methods, $mode,
00666                                         '_completeInvalid');
00667 
00668         return call_user_func_array(array($this, $method),
00669                                     array($message, $endpoint, $return_to));
00670     }
00671 
00672     /**
00673      * @access private
00674      */
00675     function _completeInvalid($message, $endpoint, $unused)
00676     {
00677         $mode = $message->getArg(Auth_OpenID_OPENID_NS, 'mode',
00678                                  '<No mode set>');
00679 
00680         return new Auth_OpenID_FailureResponse($endpoint,
00681                     sprintf("Invalid openid.mode '%s'", $mode));
00682     }
00683 
00684     /**
00685      * @access private
00686      */
00687     function _complete_cancel($message, $endpoint, $unused)
00688     {
00689         return new Auth_OpenID_CancelResponse($endpoint);
00690     }
00691 
00692     /**
00693      * @access private
00694      */
00695     function _complete_error($message, $endpoint, $unused)
00696     {
00697         $error = $message->getArg(Auth_OpenID_OPENID_NS, 'error');
00698         $contact = $message->getArg(Auth_OpenID_OPENID_NS, 'contact');
00699         $reference = $message->getArg(Auth_OpenID_OPENID_NS, 'reference');
00700 
00701         return new Auth_OpenID_FailureResponse($endpoint, $error,
00702                                                $contact, $reference);
00703     }
00704 
00705     /**
00706      * @access private
00707      */
00708     function _complete_setup_needed($message, $endpoint, $unused)
00709     {
00710         if (!$message->isOpenID2()) {
00711             return $this->_completeInvalid($message, $endpoint);
00712         }
00713 
00714         $user_setup_url = $message->getArg(Auth_OpenID_OPENID2_NS,
00715                                            'user_setup_url');
00716         return new Auth_OpenID_SetupNeededResponse($endpoint, $user_setup_url);
00717     }
00718 
00719     /**
00720      * @access private
00721      */
00722     function _complete_id_res($message, $endpoint, $return_to)
00723     {
00724         $user_setup_url = $message->getArg(Auth_OpenID_OPENID1_NS,
00725                                            'user_setup_url');
00726 
00727         if ($this->_checkSetupNeeded($message)) {
00728             return new Auth_OpenID_SetupNeededResponse(
00729                 $endpoint, $user_setup_url);
00730         } else {
00731             return $this->_doIdRes($message, $endpoint, $return_to);
00732         }
00733     }
00734 
00735     /**
00736      * @access private
00737      */
00738     function _checkSetupNeeded($message)
00739     {
00740         // In OpenID 1, we check to see if this is a cancel from
00741         // immediate mode by the presence of the user_setup_url
00742         // parameter.
00743         if ($message->isOpenID1()) {
00744             $user_setup_url = $message->getArg(Auth_OpenID_OPENID1_NS,
00745                                                'user_setup_url');
00746             if ($user_setup_url !== null) {
00747                 return true;
00748             }
00749         }
00750 
00751         return false;
00752     }
00753 
00754     /**
00755      * @access private
00756      */
00757     function _doIdRes($message, $endpoint, $return_to)
00758     {
00759         // Checks for presence of appropriate fields (and checks
00760         // signed list fields)
00761         $result = $this->_idResCheckForFields($message);
00762 
00763         if (Auth_OpenID::isFailure($result)) {
00764             return $result;
00765         }
00766 
00767         if (!$this->_checkReturnTo($message, $return_to)) {
00768             return new Auth_OpenID_FailureResponse(null,
00769             sprintf("return_to does not match return URL. Expected %s, got %s",
00770                     $return_to,
00771                     $message->getArg(Auth_OpenID_OPENID_NS, 'return_to')));
00772         }
00773 
00774         // Verify discovery information:
00775         $result = $this->_verifyDiscoveryResults($message, $endpoint);
00776 
00777         if (Auth_OpenID::isFailure($result)) {
00778             return $result;
00779         }
00780 
00781         $endpoint = $result;
00782 
00783         $result = $this->_idResCheckSignature($message,
00784                                               $endpoint->server_url);
00785 
00786         if (Auth_OpenID::isFailure($result)) {
00787             return $result;
00788         }
00789 
00790         $result = $this->_idResCheckNonce($message, $endpoint);
00791 
00792         if (Auth_OpenID::isFailure($result)) {
00793             return $result;
00794         }
00795 
00796         $signed_list_str = $message->getArg(Auth_OpenID_OPENID_NS, 'signed',
00797                                             Auth_OpenID_NO_DEFAULT);
00798         if (Auth_OpenID::isFailure($signed_list_str)) {
00799             return $signed_list_str;
00800         }
00801         $signed_list = explode(',', $signed_list_str);
00802 
00803         $signed_fields = Auth_OpenID::addPrefix($signed_list, "openid.");
00804 
00805         return new Auth_OpenID_SuccessResponse($endpoint, $message,
00806                                                $signed_fields);
00807 
00808     }
00809 
00810     /**
00811      * @access private
00812      */
00813     function _checkReturnTo($message, $return_to)
00814     {
00815         // Check an OpenID message and its openid.return_to value
00816         // against a return_to URL from an application.  Return True
00817         // on success, False on failure.
00818 
00819         // Check the openid.return_to args against args in the
00820         // original message.
00821         $result = Auth_OpenID_GenericConsumer::_verifyReturnToArgs(
00822                                            $message->toPostArgs());
00823         if (Auth_OpenID::isFailure($result)) {
00824             return false;
00825         }
00826 
00827         // Check the return_to base URL against the one in the
00828         // message.
00829         $msg_return_to = $message->getArg(Auth_OpenID_OPENID_NS,
00830                                           'return_to');
00831         if (Auth_OpenID::isFailure($return_to)) {
00832             // XXX log me
00833             return false;
00834         }
00835 
00836         $return_to_parts = parse_url(Auth_OpenID_urinorm($return_to));
00837         $msg_return_to_parts = parse_url(Auth_OpenID_urinorm($msg_return_to));
00838 
00839         // If port is absent from both, add it so it's equal in the
00840         // check below.
00841         if ((!array_key_exists('port', $return_to_parts)) &&
00842             (!array_key_exists('port', $msg_return_to_parts))) {
00843             $return_to_parts['port'] = null;
00844             $msg_return_to_parts['port'] = null;
00845         }
00846 
00847         // If path is absent from both, add it so it's equal in the
00848         // check below.
00849         if ((!array_key_exists('path', $return_to_parts)) &&
00850             (!array_key_exists('path', $msg_return_to_parts))) {
00851             $return_to_parts['path'] = null;
00852             $msg_return_to_parts['path'] = null;
00853         }
00854 
00855         // The URL scheme, authority, and path MUST be the same
00856         // between the two URLs.
00857         foreach (array('scheme', 'host', 'port', 'path') as $component) {
00858             // If the url component is absent in either URL, fail.
00859             // There should always be a scheme, host, port, and path.
00860             if (!array_key_exists($component, $return_to_parts)) {
00861                 return false;
00862             }
00863 
00864             if (!array_key_exists($component, $msg_return_to_parts)) {
00865                 return false;
00866             }
00867 
00868             if (Auth_OpenID::arrayGet($return_to_parts, $component) !==
00869                 Auth_OpenID::arrayGet($msg_return_to_parts, $component)) {
00870                 return false;
00871             }
00872         }
00873 
00874         return true;
00875     }
00876 
00877     /**
00878      * @access private
00879      */
00880     function _verifyReturnToArgs($query)
00881     {
00882         // Verify that the arguments in the return_to URL are present in this
00883         // response.
00884 
00885         $message = Auth_OpenID_Message::fromPostArgs($query);
00886         $return_to = $message->getArg(Auth_OpenID_OPENID_NS, 'return_to');
00887 
00888         if (Auth_OpenID::isFailure($return_to)) {
00889             return $return_to;
00890         }
00891         // XXX: this should be checked by _idResCheckForFields
00892         if (!$return_to) {
00893             return new Auth_OpenID_FailureResponse(null,
00894                            "Response has no return_to");
00895         }
00896 
00897         $parsed_url = parse_url($return_to);
00898 
00899         $q = array();
00900         if (array_key_exists('query', $parsed_url)) {
00901             $rt_query = $parsed_url['query'];
00902             $q = Auth_OpenID::parse_str($rt_query);
00903         }
00904 
00905         foreach ($q as $rt_key => $rt_value) {
00906             if (!array_key_exists($rt_key, $query)) {
00907                 return new Auth_OpenID_FailureResponse(null,
00908                   sprintf("return_to parameter %s absent from query", $rt_key));
00909             } else {
00910                 $value = $query[$rt_key];
00911                 if ($rt_value != $value) {
00912                     return new Auth_OpenID_FailureResponse(null,
00913                       sprintf("parameter %s value %s does not match " .
00914                               "return_to value %s", $rt_key,
00915                               $value, $rt_value));
00916                 }
00917             }
00918         }
00919 
00920         // Make sure all non-OpenID arguments in the response are also
00921         // in the signed return_to.
00922         $bare_args = $message->getArgs(Auth_OpenID_BARE_NS);
00923         foreach ($bare_args as $key => $value) {
00924             if (Auth_OpenID::arrayGet($q, $key) != $value) {
00925                 return new Auth_OpenID_FailureResponse(null,
00926                   sprintf("Parameter %s = %s not in return_to URL",
00927                           $key, $value));
00928             }
00929         }
00930 
00931         return true;
00932     }
00933 
00934     /**
00935      * @access private
00936      */
00937     function _idResCheckSignature($message, $server_url)
00938     {
00939         $assoc_handle = $message->getArg(Auth_OpenID_OPENID_NS,
00940                                          'assoc_handle');
00941         if (Auth_OpenID::isFailure($assoc_handle)) {
00942             return $assoc_handle;
00943         }
00944 
00945         $assoc = $this->store->getAssociation($server_url, $assoc_handle);
00946 
00947         if ($assoc) {
00948             if ($assoc->getExpiresIn() <= 0) {
00949                 // XXX: It might be a good idea sometimes to re-start
00950                 // the authentication with a new association. Doing it
00951                 // automatically opens the possibility for
00952                 // denial-of-service by a server that just returns
00953                 // expired associations (or really short-lived
00954                 // associations)
00955                 return new Auth_OpenID_FailureResponse(null,
00956                              'Association with ' . $server_url . ' expired');
00957             }
00958 
00959             if (!$assoc->checkMessageSignature($message)) {
00960                 // If we get a "bad signature" here, it means that the association
00961                 // is unrecoverabley corrupted in some way. Any futher attempts
00962                 // to login with this association is likely to fail. Drop it.
00963                 $this->store->removeAssociation($server_url, $assoc_handle);
00964                 return new Auth_OpenID_FailureResponse(null,
00965                                                        "Bad signature");
00966             }
00967         } else {
00968             // It's not an association we know about.  Stateless mode
00969             // is our only possible path for recovery.  XXX - async
00970             // framework will not want to block on this call to
00971             // _checkAuth.
00972             if (!$this->_checkAuth($message, $server_url)) {
00973                 return new Auth_OpenID_FailureResponse(null,
00974                              "Server denied check_authentication");
00975             }
00976         }
00977 
00978         return null;
00979     }
00980 
00981     /**
00982      * @access private
00983      */
00984     function _verifyDiscoveryResults($message, $endpoint=null)
00985     {
00986         if ($message->getOpenIDNamespace() == Auth_OpenID_OPENID2_NS) {
00987             return $this->_verifyDiscoveryResultsOpenID2($message,
00988                                                          $endpoint);
00989         } else {
00990             return $this->_verifyDiscoveryResultsOpenID1($message,
00991                                                          $endpoint);
00992         }
00993     }
00994 
00995     /**
00996      * @access private
00997      */
00998     function _verifyDiscoveryResultsOpenID1($message, $endpoint)
00999     {
01000         $claimed_id = $message->getArg(Auth_OpenID_BARE_NS,
01001                                 $this->openid1_return_to_identifier_name);
01002 
01003         if (($endpoint === null) && ($claimed_id === null)) {
01004             return new Auth_OpenID_FailureResponse($endpoint,
01005               'When using OpenID 1, the claimed ID must be supplied, ' .
01006               'either by passing it through as a return_to parameter ' .
01007               'or by using a session, and supplied to the GenericConsumer ' .
01008               'as the argument to complete()');
01009         } else if (($endpoint !== null) && ($claimed_id === null)) {
01010             $claimed_id = $endpoint->claimed_id;
01011         }
01012 
01013         $to_match = new Auth_OpenID_ServiceEndpoint();
01014         $to_match->type_uris = array(Auth_OpenID_TYPE_1_1);
01015         $to_match->local_id = $message->getArg(Auth_OpenID_OPENID1_NS,
01016                                                'identity');
01017 
01018         // Restore delegate information from the initiation phase
01019         $to_match->claimed_id = $claimed_id;
01020 
01021         if ($to_match->local_id === null) {
01022             return new Auth_OpenID_FailureResponse($endpoint,
01023                          "Missing required field openid.identity");
01024         }
01025 
01026         $to_match_1_0 = $to_match->copy();
01027         $to_match_1_0->type_uris = array(Auth_OpenID_TYPE_1_0);
01028 
01029         if ($endpoint !== null) {
01030             $result = $this->_verifyDiscoverySingle($endpoint, $to_match);
01031 
01032             if (is_a($result, 'Auth_OpenID_TypeURIMismatch')) {
01033                 $result = $this->_verifyDiscoverySingle($endpoint,
01034                                                         $to_match_1_0);
01035             }
01036 
01037             if (Auth_OpenID::isFailure($result)) {
01038                 // oidutil.log("Error attempting to use stored
01039                 //             discovery information: " + str(e))
01040                 //             oidutil.log("Attempting discovery to
01041                 //             verify endpoint")
01042             } else {
01043                 return $endpoint;
01044             }
01045         }
01046 
01047         // Endpoint is either bad (failed verification) or None
01048         return $this->_discoverAndVerify($to_match->claimed_id,
01049                                          array($to_match, $to_match_1_0));
01050     }
01051 
01052     /**
01053      * @access private
01054      */
01055     function _verifyDiscoverySingle($endpoint, $to_match)
01056     {
01057         // Every type URI that's in the to_match endpoint has to be
01058         // present in the discovered endpoint.
01059         foreach ($to_match->type_uris as $type_uri) {
01060             if (!$endpoint->usesExtension($type_uri)) {
01061                 return new Auth_OpenID_TypeURIMismatch($endpoint,
01062                              "Required type ".$type_uri." not present");
01063             }
01064         }
01065 
01066         // Fragments do not influence discovery, so we can't compare a
01067         // claimed identifier with a fragment to discovered
01068         // information.
01069         list($defragged_claimed_id, $_) =
01070             Auth_OpenID::urldefrag($to_match->claimed_id);
01071 
01072         if ($defragged_claimed_id != $endpoint->claimed_id) {
01073             return new Auth_OpenID_FailureResponse($endpoint,
01074               sprintf('Claimed ID does not match (different subjects!), ' .
01075                       'Expected %s, got %s', $defragged_claimed_id,
01076                       $endpoint->claimed_id));
01077         }
01078 
01079         if ($to_match->getLocalID() != $endpoint->getLocalID()) {
01080             return new Auth_OpenID_FailureResponse($endpoint,
01081               sprintf('local_id mismatch. Expected %s, got %s',
01082                       $to_match->getLocalID(), $endpoint->getLocalID()));
01083         }
01084 
01085         // If the server URL is None, this must be an OpenID 1
01086         // response, because op_endpoint is a required parameter in
01087         // OpenID 2. In that case, we don't actually care what the
01088         // discovered server_url is, because signature checking or
01089         // check_auth should take care of that check for us.
01090         if ($to_match->server_url === null) {
01091             if ($to_match->preferredNamespace() != Auth_OpenID_OPENID1_NS) {
01092                 return new Auth_OpenID_FailureResponse($endpoint,
01093                              "Preferred namespace mismatch (bug)");
01094             }
01095         } else if ($to_match->server_url != $endpoint->server_url) {
01096             return new Auth_OpenID_FailureResponse($endpoint,
01097               sprintf('OP Endpoint mismatch. Expected %s, got %s',
01098                       $to_match->server_url, $endpoint->server_url));
01099         }
01100 
01101         return null;
01102     }
01103 
01104     /**
01105      * @access private
01106      */
01107     function _verifyDiscoveryResultsOpenID2($message, $endpoint)
01108     {
01109         $to_match = new Auth_OpenID_ServiceEndpoint();
01110         $to_match->type_uris = array(Auth_OpenID_TYPE_2_0);
01111         $to_match->claimed_id = $message->getArg(Auth_OpenID_OPENID2_NS,
01112                                                  'claimed_id');
01113 
01114         $to_match->local_id = $message->getArg(Auth_OpenID_OPENID2_NS,
01115                                                 'identity');
01116 
01117         $to_match->server_url = $message->getArg(Auth_OpenID_OPENID2_NS,
01118                                                  'op_endpoint');
01119 
01120         if ($to_match->server_url === null) {
01121             return new Auth_OpenID_FailureResponse($endpoint,
01122                          "OP Endpoint URL missing");
01123         }
01124 
01125         // claimed_id and identifier must both be present or both be
01126         // absent
01127         if (($to_match->claimed_id === null) &&
01128             ($to_match->local_id !== null)) {
01129             return new Auth_OpenID_FailureResponse($endpoint,
01130               'openid.identity is present without openid.claimed_id');
01131         }
01132 
01133         if (($to_match->claimed_id !== null) &&
01134             ($to_match->local_id === null)) {
01135             return new Auth_OpenID_FailureResponse($endpoint,
01136               'openid.claimed_id is present without openid.identity');
01137         }
01138 
01139         if ($to_match->claimed_id === null) {
01140             // This is a response without identifiers, so there's
01141             // really no checking that we can do, so return an
01142             // endpoint that's for the specified `openid.op_endpoint'
01143             return Auth_OpenID_ServiceEndpoint::fromOPEndpointURL(
01144                                                 $to_match->server_url);
01145         }
01146 
01147         if (!$endpoint) {
01148             // The claimed ID doesn't match, so we have to do
01149             // discovery again. This covers not using sessions, OP
01150             // identifier endpoints and responses that didn't match
01151             // the original request.
01152             // oidutil.log('No pre-discovered information supplied.')
01153             return $this->_discoverAndVerify($to_match->claimed_id,
01154                                              array($to_match));
01155         } else {
01156 
01157             // The claimed ID matches, so we use the endpoint that we
01158             // discovered in initiation. This should be the most
01159             // common case.
01160             $result = $this->_verifyDiscoverySingle($endpoint, $to_match);
01161 
01162             if (Auth_OpenID::isFailure($result)) {
01163                 $endpoint = $this->_discoverAndVerify($to_match->claimed_id,
01164                                                       array($to_match));
01165                 if (Auth_OpenID::isFailure($endpoint)) {
01166                     return $endpoint;
01167                 }
01168             }
01169         }
01170 
01171         // The endpoint we return should have the claimed ID from the
01172         // message we just verified, fragment and all.
01173         if ($endpoint->claimed_id != $to_match->claimed_id) {
01174             $endpoint->claimed_id = $to_match->claimed_id;
01175         }
01176 
01177         return $endpoint;
01178     }
01179 
01180     /**
01181      * @access private
01182      */
01183     function _discoverAndVerify($claimed_id, $to_match_endpoints)
01184     {
01185 
01186 
01187         // oidutil.log('Performing discovery on %s' % (claimed_id,))
01188         list($unused, $services) = call_user_func($this->discoverMethod,
01189                                                   $claimed_id,
01190                                                   $this->fetcher);
01191 
01192         if (!$services) {
01193             return new Auth_OpenID_FailureResponse(null,
01194               sprintf("No OpenID information found at %s",
01195                       $claimed_id));
01196         }
01197 
01198         return $this->_verifyDiscoveryServices($claimed_id, $services,
01199                                                $to_match_endpoints);
01200     }
01201 
01202     /**
01203      * @access private
01204      */
01205     function _verifyDiscoveryServices($claimed_id,
01206                                       $services, $to_match_endpoints)
01207     {
01208         // Search the services resulting from discovery to find one
01209         // that matches the information from the assertion
01210 
01211         foreach ($services as $endpoint) {
01212             foreach ($to_match_endpoints as $to_match_endpoint) {
01213                 $result = $this->_verifyDiscoverySingle($endpoint,
01214                                                         $to_match_endpoint);
01215 
01216                 if (!Auth_OpenID::isFailure($result)) {
01217                     // It matches, so discover verification has
01218                     // succeeded. Return this endpoint.
01219                     return $endpoint;
01220                 }
01221             }
01222         }
01223 
01224         return new Auth_OpenID_FailureResponse(null,
01225           sprintf('No matching endpoint found after discovering %s',
01226                   $claimed_id));
01227     }
01228 
01229     /**
01230      * Extract the nonce from an OpenID 1 response.  Return the nonce
01231      * from the BARE_NS since we independently check the return_to
01232      * arguments are the same as those in the response message.
01233      *
01234      * See the openid1_nonce_query_arg_name class variable
01235      *
01236      * @returns $nonce The nonce as a string or null
01237      *
01238      * @access private
01239      */
01240     function _idResGetNonceOpenID1($message, $endpoint)
01241     {
01242         return $message->getArg(Auth_OpenID_BARE_NS,
01243                                 $this->openid1_nonce_query_arg_name);
01244     }
01245 
01246     /**
01247      * @access private
01248      */
01249     function _idResCheckNonce($message, $endpoint)
01250     {
01251         if ($message->isOpenID1()) {
01252             // This indicates that the nonce was generated by the consumer
01253             $nonce = $this->_idResGetNonceOpenID1($message, $endpoint);
01254             $server_url = '';
01255         } else {
01256             $nonce = $message->getArg(Auth_OpenID_OPENID2_NS,
01257                                       'response_nonce');
01258 
01259             $server_url = $endpoint->server_url;
01260         }
01261 
01262         if ($nonce === null) {
01263             return new Auth_OpenID_FailureResponse($endpoint,
01264                                      "Nonce missing from response");
01265         }
01266 
01267         $parts = Auth_OpenID_splitNonce($nonce);
01268 
01269         if ($parts === null) {
01270             return new Auth_OpenID_FailureResponse($endpoint,
01271                                      "Malformed nonce in response");
01272         }
01273 
01274         list($timestamp, $salt) = $parts;
01275 
01276         if (!$this->store->useNonce($server_url, $timestamp, $salt)) {
01277             return new Auth_OpenID_FailureResponse($endpoint,
01278                          "Nonce already used or out of range");
01279         }
01280 
01281         return null;
01282     }
01283 
01284     /**
01285      * @access private
01286      */
01287     function _idResCheckForFields($message)
01288     {
01289         $basic_fields = array('return_to', 'assoc_handle', 'sig', 'signed');
01290         $basic_sig_fields = array('return_to', 'identity');
01291 
01292         $require_fields = array(
01293             Auth_OpenID_OPENID2_NS => array_merge($basic_fields,
01294                                                   array('op_endpoint')),
01295 
01296             Auth_OpenID_OPENID1_NS => array_merge($basic_fields,
01297                                                   array('identity'))
01298             );
01299 
01300         $require_sigs = array(
01301             Auth_OpenID_OPENID2_NS => array_merge($basic_sig_fields,
01302                                                   array('response_nonce',
01303                                                         'claimed_id',
01304                                                         'assoc_handle')),
01305             Auth_OpenID_OPENID1_NS => array_merge($basic_sig_fields,
01306                                                   array('nonce'))
01307             );
01308 
01309         foreach ($require_fields[$message->getOpenIDNamespace()] as $field) {
01310             if (!$message->hasKey(Auth_OpenID_OPENID_NS, $field)) {
01311                 return new Auth_OpenID_FailureResponse(null,
01312                              "Missing required field '".$field."'");
01313             }
01314         }
01315 
01316         $signed_list_str = $message->getArg(Auth_OpenID_OPENID_NS,
01317                                             'signed',
01318                                             Auth_OpenID_NO_DEFAULT);
01319         if (Auth_OpenID::isFailure($signed_list_str)) {
01320             return $signed_list_str;
01321         }
01322         $signed_list = explode(',', $signed_list_str);
01323 
01324         foreach ($require_sigs[$message->getOpenIDNamespace()] as $field) {
01325             // Field is present and not in signed list
01326             if ($message->hasKey(Auth_OpenID_OPENID_NS, $field) &&
01327                 (!in_array($field, $signed_list))) {
01328                 return new Auth_OpenID_FailureResponse(null,
01329                              "'".$field."' not signed");
01330             }
01331         }
01332 
01333         return null;
01334     }
01335 
01336     /**
01337      * @access private
01338      */
01339     function _checkAuth($message, $server_url)
01340     {
01341         $request = $this->_createCheckAuthRequest($message);
01342         if ($request === null) {
01343             return false;
01344         }
01345 
01346         $resp_message = $this->_makeKVPost($request, $server_url);
01347         if (($resp_message === null) ||
01348             (is_a($resp_message, 'Auth_OpenID_ServerErrorContainer'))) {
01349             return false;
01350         }
01351 
01352         return $this->_processCheckAuthResponse($resp_message, $server_url);
01353     }
01354 
01355     /**
01356      * @access private
01357      */
01358     function _createCheckAuthRequest($message)
01359     {
01360         $signed = $message->getArg(Auth_OpenID_OPENID_NS, 'signed');
01361         if ($signed) {
01362             foreach (explode(',', $signed) as $k) {
01363                 $value = $message->getAliasedArg($k);
01364                 if ($value === null) {
01365                     return null;
01366                 }
01367             }
01368         }
01369         $ca_message = $message->copy();
01370         $ca_message->setArg(Auth_OpenID_OPENID_NS, 'mode',
01371                             'check_authentication');
01372         return $ca_message;
01373     }
01374 
01375     /**
01376      * @access private
01377      */
01378     function _processCheckAuthResponse($response, $server_url)
01379     {
01380         $is_valid = $response->getArg(Auth_OpenID_OPENID_NS, 'is_valid',
01381                                       'false');
01382 
01383         $invalidate_handle = $response->getArg(Auth_OpenID_OPENID_NS,
01384                                                'invalidate_handle');
01385 
01386         if ($invalidate_handle !== null) {
01387             $this->store->removeAssociation($server_url,
01388                                             $invalidate_handle);
01389         }
01390 
01391         if ($is_valid == 'true') {
01392             return true;
01393         }
01394 
01395         return false;
01396     }
01397 
01398     /**
01399      * Adapt a POST response to a Message.
01400      *
01401      * @param $response Result of a POST to an OpenID endpoint.
01402      *
01403      * @access private
01404      */
01405     function _httpResponseToMessage($response, $server_url)
01406     {
01407         // Should this function be named Message.fromHTTPResponse instead?
01408         $response_message = Auth_OpenID_Message::fromKVForm($response->body);
01409 
01410         if ($response->status == 400) {
01411             return Auth_OpenID_ServerErrorContainer::fromMessage(
01412                         $response_message);
01413         } else if ($response->status != 200 and $response->status != 206) {
01414             return null;
01415         }
01416 
01417         return $response_message;
01418     }
01419 
01420     /**
01421      * @access private
01422      */
01423     function _makeKVPost($message, $server_url)
01424     {
01425         $body = $message->toURLEncoded();
01426         $resp = $this->fetcher->post($server_url, $body);
01427 
01428         if ($resp === null) {
01429             return null;
01430         }
01431 
01432         return $this->_httpResponseToMessage($resp, $server_url);
01433     }
01434 
01435     /**
01436      * @access private
01437      */
01438     function _getAssociation($endpoint)
01439     {
01440         if (!$this->_use_assocs) {
01441             return null;
01442         }
01443 
01444         $assoc = $this->store->getAssociation($endpoint->server_url);
01445 
01446         if (($assoc === null) ||
01447             ($assoc->getExpiresIn() <= 0)) {
01448 
01449             $assoc = $this->_negotiateAssociation($endpoint);
01450 
01451             if ($assoc !== null) {
01452                 $this->store->storeAssociation($endpoint->server_url,
01453                                                $assoc);
01454             }
01455         }
01456 
01457         return $assoc;
01458     }
01459 
01460     /**
01461      * Handle ServerErrors resulting from association requests.
01462      *
01463      * @return $result If server replied with an C{unsupported-type}
01464      * error, return a tuple of supported C{association_type},
01465      * C{session_type}.  Otherwise logs the error and returns null.
01466      *
01467      * @access private
01468      */
01469     function _extractSupportedAssociationType($server_error, $endpoint,
01470                                               $assoc_type)
01471     {
01472         // Any error message whose code is not 'unsupported-type'
01473         // should be considered a total failure.
01474         if (($server_error->error_code != 'unsupported-type') ||
01475             ($server_error->message->isOpenID1())) {
01476             return null;
01477         }
01478 
01479         // The server didn't like the association/session type that we
01480         // sent, and it sent us back a message that might tell us how
01481         // to handle it.
01482 
01483         // Extract the session_type and assoc_type from the error
01484         // message
01485         $assoc_type = $server_error->message->getArg(Auth_OpenID_OPENID_NS,
01486                                                      'assoc_type');
01487 
01488         $session_type = $server_error->message->getArg(Auth_OpenID_OPENID_NS,
01489                                                        'session_type');
01490 
01491         if (($assoc_type === null) || ($session_type === null)) {
01492             return null;
01493         } else if (!$this->negotiator->isAllowed($assoc_type,
01494                                                  $session_type)) {
01495             return null;
01496         } else {
01497           return array($assoc_type, $session_type);
01498         }
01499     }
01500 
01501     /**
01502      * @access private
01503      */
01504     function _negotiateAssociation($endpoint)
01505     {
01506         // Get our preferred session/association type from the negotiatior.
01507         list($assoc_type, $session_type) = $this->negotiator->getAllowedType();
01508 
01509         $assoc = $this->_requestAssociation(
01510                            $endpoint, $assoc_type, $session_type);
01511 
01512         if (Auth_OpenID::isFailure($assoc)) {
01513             return null;
01514         }
01515 
01516         if (is_a($assoc, 'Auth_OpenID_ServerErrorContainer')) {
01517             $why = $assoc;
01518 
01519             $supportedTypes = $this->_extractSupportedAssociationType(
01520                                      $why, $endpoint, $assoc_type);
01521 
01522             if ($supportedTypes !== null) {
01523                 list($assoc_type, $session_type) = $supportedTypes;
01524 
01525                 // Attempt to create an association from the assoc_type
01526                 // and session_type that the server told us it
01527                 // supported.
01528                 $assoc = $this->_requestAssociation(
01529                                    $endpoint, $assoc_type, $session_type);
01530 
01531                 if (is_a($assoc, 'Auth_OpenID_ServerErrorContainer')) {
01532                     // Do not keep trying, since it rejected the
01533                     // association type that it told us to use.
01534                     // oidutil.log('Server %s refused its suggested association
01535                     //             'type: session_type=%s, assoc_type=%s'
01536                     //             % (endpoint.server_url, session_type,
01537                     //                assoc_type))
01538                     return null;
01539                 } else {
01540                     return $assoc;
01541                 }
01542             } else {
01543                 return null;
01544             }
01545         } else {
01546             return $assoc;
01547         }
01548     }
01549 
01550     /**
01551      * @access private
01552      */
01553     function _requestAssociation($endpoint, $assoc_type, $session_type)
01554     {
01555         list($assoc_session, $args) = $this->_createAssociateRequest(
01556                                       $endpoint, $assoc_type, $session_type);
01557 
01558         $response_message = $this->_makeKVPost($args, $endpoint->server_url);
01559 
01560         if ($response_message === null) {
01561             // oidutil.log('openid.associate request failed: %s' % (why[0],))
01562             return null;
01563         } else if (is_a($response_message,
01564                         'Auth_OpenID_ServerErrorContainer')) {
01565             return $response_message;
01566         }
01567 
01568         return $this->_extractAssociation($response_message, $assoc_session);
01569     }
01570 
01571     /**
01572      * @access private
01573      */
01574     function _extractAssociation($assoc_response, $assoc_session)
01575     {
01576         // Extract the common fields from the response, raising an
01577         // exception if they are not found
01578         $assoc_type = $assoc_response->getArg(
01579                          Auth_OpenID_OPENID_NS, 'assoc_type',
01580                          Auth_OpenID_NO_DEFAULT);
01581 
01582         if (Auth_OpenID::isFailure($assoc_type)) {
01583             return $assoc_type;
01584         }
01585 
01586         $assoc_handle = $assoc_response->getArg(
01587                            Auth_OpenID_OPENID_NS, 'assoc_handle',
01588                            Auth_OpenID_NO_DEFAULT);
01589 
01590         if (Auth_OpenID::isFailure($assoc_handle)) {
01591             return $assoc_handle;
01592         }
01593 
01594         // expires_in is a base-10 string. The Python parsing will
01595         // accept literals that have whitespace around them and will
01596         // accept negative values. Neither of these are really in-spec,
01597         // but we think it's OK to accept them.
01598         $expires_in_str = $assoc_response->getArg(
01599                              Auth_OpenID_OPENID_NS, 'expires_in',
01600                              Auth_OpenID_NO_DEFAULT);
01601 
01602         if (Auth_OpenID::isFailure($expires_in_str)) {
01603             return $expires_in_str;
01604         }
01605 
01606         $expires_in = Auth_OpenID::intval($expires_in_str);
01607         if ($expires_in === false) {
01608 
01609             $err = sprintf("Could not parse expires_in from association ".
01610                            "response %s", print_r($assoc_response, true));
01611             return new Auth_OpenID_FailureResponse(null, $err);
01612         }
01613 
01614         // OpenID 1 has funny association session behaviour.
01615         if ($assoc_response->isOpenID1()) {
01616             $session_type = $this->_getOpenID1SessionType($assoc_response);
01617         } else {
01618             $session_type = $assoc_response->getArg(
01619                                Auth_OpenID_OPENID2_NS, 'session_type',
01620                                Auth_OpenID_NO_DEFAULT);
01621 
01622             if (Auth_OpenID::isFailure($session_type)) {
01623                 return $session_type;
01624             }
01625         }
01626 
01627         // Session type mismatch
01628         if ($assoc_session->session_type != $session_type) {
01629             if ($assoc_response->isOpenID1() &&
01630                 ($session_type == 'no-encryption')) {
01631                 // In OpenID 1, any association request can result in
01632                 // a 'no-encryption' association response. Setting
01633                 // assoc_session to a new no-encryption session should
01634                 // make the rest of this function work properly for
01635                 // that case.
01636                 $assoc_session = new Auth_OpenID_PlainTextConsumerSession();
01637             } else {
01638                 // Any other mismatch, regardless of protocol version
01639                 // results in the failure of the association session
01640                 // altogether.
01641                 return null;
01642             }
01643         }
01644 
01645         // Make sure assoc_type is valid for session_type
01646         if (!in_array($assoc_type, $assoc_session->allowed_assoc_types)) {
01647             return null;
01648         }
01649 
01650         // Delegate to the association session to extract the secret
01651         // from the response, however is appropriate for that session
01652         // type.
01653         $secret = $assoc_session->extractSecret($assoc_response);
01654 
01655         if ($secret === null) {
01656             return null;
01657         }
01658 
01659         return Auth_OpenID_Association::fromExpiresIn(
01660                  $expires_in, $assoc_handle, $secret, $assoc_type);
01661     }
01662 
01663     /**
01664      * @access private
01665      */
01666     function _createAssociateRequest($endpoint, $assoc_type, $session_type)
01667     {
01668         if (array_key_exists($session_type, $this->session_types)) {
01669             $session_type_class = $this->session_types[$session_type];
01670 
01671             if (is_callable($session_type_class)) {
01672                 $assoc_session = $session_type_class();
01673             } else {
01674                 $assoc_session = new $session_type_class();
01675             }
01676         } else {
01677             return null;
01678         }
01679 
01680         $args = array(
01681             'mode' => 'associate',
01682             'assoc_type' => $assoc_type);
01683 
01684         if (!$endpoint->compatibilityMode()) {
01685             $args['ns'] = Auth_OpenID_OPENID2_NS;
01686         }
01687 
01688         // Leave out the session type if we're in compatibility mode
01689         // *and* it's no-encryption.
01690         if ((!$endpoint->compatibilityMode()) ||
01691             ($assoc_session->session_type != 'no-encryption')) {
01692             $args['session_type'] = $assoc_session->session_type;
01693         }
01694 
01695         $args = array_merge($args, $assoc_session->getRequest());
01696         $message = Auth_OpenID_Message::fromOpenIDArgs($args);
01697         return array($assoc_session, $message);
01698     }
01699 
01700     /**
01701      * Given an association response message, extract the OpenID 1.X
01702      * session type.
01703      *
01704      * This function mostly takes care of the 'no-encryption' default
01705      * behavior in OpenID 1.
01706      *
01707      * If the association type is plain-text, this function will
01708      * return 'no-encryption'
01709      *
01710      * @access private
01711      * @return $typ The association type for this message
01712      */
01713     function _getOpenID1SessionType($assoc_response)
01714     {
01715         // If it's an OpenID 1 message, allow session_type to default
01716         // to None (which signifies "no-encryption")
01717         $session_type = $assoc_response->getArg(Auth_OpenID_OPENID1_NS,
01718                                                 'session_type');
01719 
01720         // Handle the differences between no-encryption association
01721         // respones in OpenID 1 and 2:
01722 
01723         // no-encryption is not really a valid session type for OpenID
01724         // 1, but we'll accept it anyway, while issuing a warning.
01725         if ($session_type == 'no-encryption') {
01726             // oidutil.log('WARNING: OpenID server sent "no-encryption"'
01727             //             'for OpenID 1.X')
01728         } else if (($session_type == '') || ($session_type === null)) {
01729             // Missing or empty session type is the way to flag a
01730             // 'no-encryption' response. Change the session type to
01731             // 'no-encryption' so that it can be handled in the same
01732             // way as OpenID 2 'no-encryption' respones.
01733             $session_type = 'no-encryption';
01734         }
01735 
01736         return $session_type;
01737     }
01738 }
01739 
01740 /**
01741  * This class represents an authentication request from a consumer to
01742  * an OpenID server.
01743  *
01744  * @package OpenID
01745  */
01746 class Auth_OpenID_AuthRequest {
01747 
01748     /**
01749      * Initialize an authentication request with the specified token,
01750      * association, and endpoint.
01751      *
01752      * Users of this library should not create instances of this
01753      * class.  Instances of this class are created by the library when
01754      * needed.
01755      */
01756     function Auth_OpenID_AuthRequest($endpoint, $assoc)
01757     {
01758         $this->assoc = $assoc;
01759         $this->endpoint =& $endpoint;
01760         $this->return_to_args = array();
01761         $this->message = new Auth_OpenID_Message(
01762             $endpoint->preferredNamespace());
01763         $this->_anonymous = false;
01764     }
01765 
01766     /**
01767      * Add an extension to this checkid request.
01768      *
01769      * $extension_request: An object that implements the extension
01770      * request interface for adding arguments to an OpenID message.
01771      */
01772     function addExtension($extension_request)
01773     {
01774         $extension_request->toMessage($this->message);
01775     }
01776 
01777     /**
01778      * Add an extension argument to this OpenID authentication
01779      * request.
01780      *
01781      * Use caution when adding arguments, because they will be
01782      * URL-escaped and appended to the redirect URL, which can easily
01783      * get quite long.
01784      *
01785      * @param string $namespace The namespace for the extension. For
01786      * example, the simple registration extension uses the namespace
01787      * 'sreg'.
01788      *
01789      * @param string $key The key within the extension namespace. For
01790      * example, the nickname field in the simple registration
01791      * extension's key is 'nickname'.
01792      *
01793      * @param string $value The value to provide to the server for
01794      * this argument.
01795      */
01796     function addExtensionArg($namespace, $key, $value)
01797     {
01798         return $this->message->setArg($namespace, $key, $value);
01799     }
01800 
01801     /**
01802      * Set whether this request should be made anonymously. If a
01803      * request is anonymous, the identifier will not be sent in the
01804      * request. This is only useful if you are making another kind of
01805      * request with an extension in this request.
01806      *
01807      * Anonymous requests are not allowed when the request is made
01808      * with OpenID 1.
01809      */
01810     function setAnonymous($is_anonymous)
01811     {
01812         if ($is_anonymous && $this->message->isOpenID1()) {
01813             return false;
01814         } else {
01815             $this->_anonymous = $is_anonymous;
01816             return true;
01817         }
01818     }
01819 
01820     /**
01821      * Produce a {@link Auth_OpenID_Message} representing this
01822      * request.
01823      *
01824      * @param string $realm The URL (or URL pattern) that identifies
01825      * your web site to the user when she is authorizing it.
01826      *
01827      * @param string $return_to The URL that the OpenID provider will
01828      * send the user back to after attempting to verify her identity.
01829      *
01830      * Not specifying a return_to URL means that the user will not be
01831      * returned to the site issuing the request upon its completion.
01832      *
01833      * @param bool $immediate If true, the OpenID provider is to send
01834      * back a response immediately, useful for behind-the-scenes
01835      * authentication attempts.  Otherwise the OpenID provider may
01836      * engage the user before providing a response.  This is the
01837      * default case, as the user may need to provide credentials or
01838      * approve the request before a positive response can be sent.
01839      */
01840     function getMessage($realm, $return_to=null, $immediate=false)
01841     {
01842         if ($return_to) {
01843             $return_to = Auth_OpenID::appendArgs($return_to,
01844                                                  $this->return_to_args);
01845         } else if ($immediate) {
01846             // raise ValueError(
01847             //     '"return_to" is mandatory when
01848             //using "checkid_immediate"')
01849             return new Auth_OpenID_FailureResponse(null,
01850               "'return_to' is mandatory when using checkid_immediate");
01851         } else if ($this->message->isOpenID1()) {
01852             // raise ValueError('"return_to" is
01853             // mandatory for OpenID 1 requests')
01854             return new Auth_OpenID_FailureResponse(null,
01855               "'return_to' is mandatory for OpenID 1 requests");
01856         } else if ($this->return_to_args) {
01857             // raise ValueError('extra "return_to" arguments
01858             // were specified, but no return_to was specified')
01859             return new Auth_OpenID_FailureResponse(null,
01860               "extra 'return_to' arguments where specified, " .
01861               "but no return_to was specified");
01862         }
01863 
01864         if ($immediate) {
01865             $mode = 'checkid_immediate';
01866         } else {
01867             $mode = 'checkid_setup';
01868         }
01869 
01870         $message = $this->message->copy();
01871         if ($message->isOpenID1()) {
01872             $realm_key = 'trust_root';
01873         } else {
01874             $realm_key = 'realm';
01875         }
01876 
01877         $message->updateArgs(Auth_OpenID_OPENID_NS,
01878                              array(
01879                                    $realm_key => $realm,
01880                                    'mode' => $mode,
01881                                    'return_to' => $return_to));
01882 
01883         if (!$this->_anonymous) {
01884             if ($this->endpoint->isOPIdentifier()) {
01885                 // This will never happen when we're in compatibility
01886                 // mode, as long as isOPIdentifier() returns False
01887                 // whenever preferredNamespace() returns OPENID1_NS.
01888                 $claimed_id = $request_identity =
01889                     Auth_OpenID_IDENTIFIER_SELECT;
01890             } else {
01891                 $request_identity = $this->endpoint->getLocalID();
01892                 $claimed_id = $this->endpoint->claimed_id;
01893             }
01894 
01895             // This is true for both OpenID 1 and 2
01896             $message->setArg(Auth_OpenID_OPENID_NS, 'identity',
01897                              $request_identity);
01898 
01899             if ($message->isOpenID2()) {
01900                 $message->setArg(Auth_OpenID_OPENID2_NS, 'claimed_id',
01901                                  $claimed_id);
01902             }
01903         }
01904 
01905         if ($this->assoc) {
01906             $message->setArg(Auth_OpenID_OPENID_NS, 'assoc_handle',
01907                              $this->assoc->handle);
01908         }
01909 
01910         return $message;
01911     }
01912 
01913     function redirectURL($realm, $return_to = null,
01914                          $immediate = false)
01915     {
01916         $message = $this->getMessage($realm, $return_to, $immediate);
01917 
01918         if (Auth_OpenID::isFailure($message)) {
01919             return $message;
01920         }
01921 
01922         return $message->toURL($this->endpoint->server_url);
01923     }
01924 
01925     /**
01926      * Get html for a form to submit this request to the IDP.
01927      *
01928      * form_tag_attrs: An array of attributes to be added to the form
01929      * tag. 'accept-charset' and 'enctype' have defaults that can be
01930      * overridden. If a value is supplied for 'action' or 'method', it
01931      * will be replaced.
01932      */
01933     function formMarkup($realm, $return_to=null, $immediate=false,
01934                         $form_tag_attrs=null)
01935     {
01936         $message = $this->getMessage($realm, $return_to, $immediate);
01937 
01938         if (Auth_OpenID::isFailure($message)) {
01939             return $message;
01940         }
01941 
01942         return $message->toFormMarkup($this->endpoint->server_url,
01943                                       $form_tag_attrs);
01944     }
01945 
01946     /**
01947      * Get a complete html document that will autosubmit the request
01948      * to the IDP.
01949      *
01950      * Wraps formMarkup.  See the documentation for that function.
01951      */
01952     function htmlMarkup($realm, $return_to=null, $immediate=false,
01953                         $form_tag_attrs=null)
01954     {
01955         $form = $this->formMarkup($realm, $return_to, $immediate,
01956                                   $form_tag_attrs);
01957 
01958         if (Auth_OpenID::isFailure($form)) {
01959             return $form;
01960         }
01961         return Auth_OpenID::autoSubmitHTML($form);
01962     }
01963 
01964     function shouldSendRedirect()
01965     {
01966         return $this->endpoint->compatibilityMode();
01967     }
01968 }
01969 
01970 /**
01971  * The base class for responses from the Auth_OpenID_Consumer.
01972  *
01973  * @package OpenID
01974  */
01975 class Auth_OpenID_ConsumerResponse {
01976     var $status = null;
01977 
01978     function setEndpoint($endpoint)
01979     {
01980         $this->endpoint = $endpoint;
01981         if ($endpoint === null) {
01982             $this->identity_url = null;
01983         } else {
01984             $this->identity_url = $endpoint->claimed_id;
01985         }
01986     }
01987 
01988     /**
01989      * Return the display identifier for this response.
01990      *
01991      * The display identifier is related to the Claimed Identifier, but the
01992      * two are not always identical.  The display identifier is something the
01993      * user should recognize as what they entered, whereas the response's
01994      * claimed identifier (in the identity_url attribute) may have extra
01995      * information for better persistence.
01996      *
01997      * URLs will be stripped of their fragments for display.  XRIs will
01998      * display the human-readable identifier (i-name) instead of the
01999      * persistent identifier (i-number).
02000      *
02001      * Use the display identifier in your user interface.  Use
02002      * identity_url for querying your database or authorization server.
02003      *
02004      */
02005     function getDisplayIdentifier()
02006     {
02007         if ($this->endpoint !== null) {
02008             return $this->endpoint->getDisplayIdentifier();
02009         }
02010         return null;
02011     }
02012 }
02013 
02014 /**
02015  * A response with a status of Auth_OpenID_SUCCESS. Indicates that
02016  * this request is a successful acknowledgement from the OpenID server
02017  * that the supplied URL is, indeed controlled by the requesting
02018  * agent.  This has three relevant attributes:
02019  *
02020  * claimed_id - The identity URL that has been authenticated
02021  *
02022  * signed_args - The arguments in the server's response that were
02023  * signed and verified.
02024  *
02025  * status - Auth_OpenID_SUCCESS.
02026  *
02027  * @package OpenID
02028  */
02029 class Auth_OpenID_SuccessResponse extends Auth_OpenID_ConsumerResponse {
02030     var $status = Auth_OpenID_SUCCESS;
02031 
02032     /**
02033      * @access private
02034      */
02035     function Auth_OpenID_SuccessResponse($endpoint, $message, $signed_args=null)
02036     {
02037         $this->endpoint = $endpoint;
02038         $this->identity_url = $endpoint->claimed_id;
02039         $this->signed_args = $signed_args;
02040         $this->message = $message;
02041 
02042         if ($this->signed_args === null) {
02043             $this->signed_args = array();
02044         }
02045     }
02046 
02047     /**
02048      * Extract signed extension data from the server's response.
02049      *
02050      * @param string $prefix The extension namespace from which to
02051      * extract the extension data.
02052      */
02053     function extensionResponse($namespace_uri, $require_signed)
02054     {
02055         if ($require_signed) {
02056             return $this->getSignedNS($namespace_uri);
02057         } else {
02058             return $this->message->getArgs($namespace_uri);
02059         }
02060     }
02061 
02062     function isOpenID1()
02063     {
02064         return $this->message->isOpenID1();
02065     }
02066 
02067     function isSigned($ns_uri, $ns_key)
02068     {
02069         // Return whether a particular key is signed, regardless of
02070         // its namespace alias
02071         return in_array($this->message->getKey($ns_uri, $ns_key),
02072                         $this->signed_args);
02073     }
02074 
02075     function getSigned($ns_uri, $ns_key, $default = null)
02076     {
02077         // Return the specified signed field if available, otherwise
02078         // return default
02079         if ($this->isSigned($ns_uri, $ns_key)) {
02080             return $this->message->getArg($ns_uri, $ns_key, $default);
02081         } else {
02082             return $default;
02083         }
02084     }
02085 
02086     function getSignedNS($ns_uri)
02087     {
02088         $args = array();
02089 
02090         $msg_args = $this->message->getArgs($ns_uri);
02091         if (Auth_OpenID::isFailure($msg_args)) {
02092             return null;
02093         }
02094 
02095         foreach ($msg_args as $key => $value) {
02096             if (!$this->isSigned($ns_uri, $key)) {
02097                 return null;
02098             }
02099         }
02100 
02101         return $msg_args;
02102     }
02103 
02104     /**
02105      * Get the openid.return_to argument from this response.
02106      *
02107      * This is useful for verifying that this request was initiated by
02108      * this consumer.
02109      *
02110      * @return string $return_to The return_to URL supplied to the
02111      * server on the initial request, or null if the response did not
02112      * contain an 'openid.return_to' argument.
02113     */
02114     function getReturnTo()
02115     {
02116         return $this->getSigned(Auth_OpenID_OPENID_NS, 'return_to');
02117     }
02118 }
02119 
02120 /**
02121  * A response with a status of Auth_OpenID_FAILURE. Indicates that the
02122  * OpenID protocol has failed. This could be locally or remotely
02123  * triggered.  This has three relevant attributes:
02124  *
02125  * claimed_id - The identity URL for which authentication was
02126  * attempted, if it can be determined.  Otherwise, null.
02127  *
02128  * message - A message indicating why the request failed, if one is
02129  * supplied.  Otherwise, null.
02130  *
02131  * status - Auth_OpenID_FAILURE.
02132  *
02133  * @package OpenID
02134  */
02135 class Auth_OpenID_FailureResponse extends Auth_OpenID_ConsumerResponse {
02136     var $status = Auth_OpenID_FAILURE;
02137 
02138     function Auth_OpenID_FailureResponse($endpoint, $message = null,
02139                                          $contact = null, $reference = null)
02140     {
02141         $this->setEndpoint($endpoint);
02142         $this->message = $message;
02143         $this->contact = $contact;
02144         $this->reference = $reference;
02145     }
02146 }
02147 
02148 /**
02149  * A specific, internal failure used to detect type URI mismatch.
02150  *
02151  * @package OpenID
02152  */
02153 class Auth_OpenID_TypeURIMismatch extends Auth_OpenID_FailureResponse {
02154 }
02155 
02156 /**
02157  * Exception that is raised when the server returns a 400 response
02158  * code to a direct request.
02159  *
02160  * @package OpenID
02161  */
02162 class Auth_OpenID_ServerErrorContainer {
02163     function Auth_OpenID_ServerErrorContainer($error_text,
02164                                               $error_code,
02165                                               $message)
02166     {
02167         $this->error_text = $error_text;
02168         $this->error_code = $error_code;
02169         $this->message = $message;
02170     }
02171 
02172     /**
02173      * @access private
02174      */
02175     function fromMessage($message)
02176     {
02177         $error_text = $message->getArg(
02178            Auth_OpenID_OPENID_NS, 'error', '<no error message supplied>');
02179         $error_code = $message->getArg(Auth_OpenID_OPENID_NS, 'error_code');
02180         return new Auth_OpenID_ServerErrorContainer($error_text,
02181                                                     $error_code,
02182                                                     $message);
02183     }
02184 }
02185 
02186 /**
02187  * A response with a status of Auth_OpenID_CANCEL. Indicates that the
02188  * user cancelled the OpenID authentication request.  This has two
02189  * relevant attributes:
02190  *
02191  * claimed_id - The identity URL for which authentication was
02192  * attempted, if it can be determined.  Otherwise, null.
02193  *
02194  * status - Auth_OpenID_SUCCESS.
02195  *
02196  * @package OpenID
02197  */
02198 class Auth_OpenID_CancelResponse extends Auth_OpenID_ConsumerResponse {
02199     var $status = Auth_OpenID_CANCEL;
02200 
02201     function Auth_OpenID_CancelResponse($endpoint)
02202     {
02203         $this->setEndpoint($endpoint);
02204     }
02205 }
02206 
02207 /**
02208  * A response with a status of Auth_OpenID_SETUP_NEEDED. Indicates
02209  * that the request was in immediate mode, and the server is unable to
02210  * authenticate the user without further interaction.
02211  *
02212  * claimed_id - The identity URL for which authentication was
02213  * attempted.
02214  *
02215  * setup_url - A URL that can be used to send the user to the server
02216  * to set up for authentication. The user should be redirected in to
02217  * the setup_url, either in the current window or in a new browser
02218  * window.  Null in OpenID 2.
02219  *
02220  * status - Auth_OpenID_SETUP_NEEDED.
02221  *
02222  * @package OpenID
02223  */
02224 class Auth_OpenID_SetupNeededResponse extends Auth_OpenID_ConsumerResponse {
02225     var $status = Auth_OpenID_SETUP_NEEDED;
02226 
02227     function Auth_OpenID_SetupNeededResponse($endpoint,
02228                                              $setup_url = null)
02229     {
02230         $this->setEndpoint($endpoint);
02231         $this->setup_url = $setup_url;
02232     }
02233 }
02234 
02235 ?>