]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/Auth/OpenID/Consumer.php
include external libs in a subdir to make install easier
[quix0rs-gnu-social.git] / extlib / Auth / OpenID / Consumer.php
1 <?php
2
3 /**
4  * This module documents the main interface with the OpenID consumer
5  * library.  The only part of the library which has to be used and
6  * isn't documented in full here is the store required to create an
7  * Auth_OpenID_Consumer instance.  More on the abstract store type and
8  * concrete implementations of it that are provided in the
9  * documentation for the Auth_OpenID_Consumer constructor.
10  *
11  * OVERVIEW
12  *
13  * The OpenID identity verification process most commonly uses the
14  * following steps, as visible to the user of this library:
15  *
16  *   1. The user enters their OpenID into a field on the consumer's
17  *      site, and hits a login button.
18  *   2. The consumer site discovers the user's OpenID server using the
19  *      YADIS protocol.
20  *   3. The consumer site sends the browser a redirect to the identity
21  *      server.  This is the authentication request as described in
22  *      the OpenID specification.
23  *   4. The identity server's site sends the browser a redirect back
24  *      to the consumer site.  This redirect contains the server's
25  *      response to the authentication request.
26  *
27  * The most important part of the flow to note is the consumer's site
28  * must handle two separate HTTP requests in order to perform the full
29  * identity check.
30  *
31  * LIBRARY DESIGN
32  * 
33  * This consumer library is designed with that flow in mind.  The goal
34  * is to make it as easy as possible to perform the above steps
35  * securely.
36  *
37  * At a high level, there are two important parts in the consumer
38  * library.  The first important part is this module, which contains
39  * the interface to actually use this library.  The second is the
40  * Auth_OpenID_Interface class, which describes the interface to use
41  * if you need to create a custom method for storing the state this
42  * library needs to maintain between requests.
43  *
44  * In general, the second part is less important for users of the
45  * library to know about, as several implementations are provided
46  * which cover a wide variety of situations in which consumers may use
47  * the library.
48  *
49  * This module contains a class, Auth_OpenID_Consumer, with methods
50  * corresponding to the actions necessary in each of steps 2, 3, and 4
51  * described in the overview.  Use of this library should be as easy
52  * as creating an Auth_OpenID_Consumer instance and calling the
53  * methods appropriate for the action the site wants to take.
54  *
55  * STORES AND DUMB MODE
56  *
57  * OpenID is a protocol that works best when the consumer site is able
58  * to store some state.  This is the normal mode of operation for the
59  * protocol, and is sometimes referred to as smart mode.  There is
60  * also a fallback mode, known as dumb mode, which is available when
61  * the consumer site is not able to store state.  This mode should be
62  * avoided when possible, as it leaves the implementation more
63  * vulnerable to replay attacks.
64  *
65  * The mode the library works in for normal operation is determined by
66  * the store that it is given.  The store is an abstraction that
67  * handles the data that the consumer needs to manage between http
68  * requests in order to operate efficiently and securely.
69  *
70  * Several store implementation are provided, and the interface is
71  * fully documented so that custom stores can be used as well.  See
72  * the documentation for the Auth_OpenID_Consumer class for more
73  * information on the interface for stores.  The implementations that
74  * are provided allow the consumer site to store the necessary data in
75  * several different ways, including several SQL databases and normal
76  * files on disk.
77  *
78  * There is an additional concrete store provided that puts the system
79  * in dumb mode.  This is not recommended, as it removes the library's
80  * ability to stop replay attacks reliably.  It still uses time-based
81  * checking to make replay attacks only possible within a small
82  * window, but they remain possible within that window.  This store
83  * should only be used if the consumer site has no way to retain data
84  * between requests at all.
85  *
86  * IMMEDIATE MODE
87  *
88  * In the flow described above, the user may need to confirm to the
89  * lidentity server that it's ok to authorize his or her identity.
90  * The server may draw pages asking for information from the user
91  * before it redirects the browser back to the consumer's site.  This
92  * is generally transparent to the consumer site, so it is typically
93  * ignored as an implementation detail.
94  *
95  * There can be times, however, where the consumer site wants to get a
96  * response immediately.  When this is the case, the consumer can put
97  * the library in immediate mode.  In immediate mode, there is an
98  * extra response possible from the server, which is essentially the
99  * server reporting that it doesn't have enough information to answer
100  * the question yet.
101  *
102  * USING THIS LIBRARY
103  *
104  * Integrating this library into an application is usually a
105  * relatively straightforward process.  The process should basically
106  * follow this plan:
107  *
108  * Add an OpenID login field somewhere on your site.  When an OpenID
109  * is entered in that field and the form is submitted, it should make
110  * a request to the your site which includes that OpenID URL.
111  *
112  * First, the application should instantiate the Auth_OpenID_Consumer
113  * class using the store of choice (Auth_OpenID_FileStore or one of
114  * the SQL-based stores).  If the application has a custom
115  * session-management implementation, an object implementing the
116  * {@link Auth_Yadis_PHPSession} interface should be passed as the
117  * second parameter.  Otherwise, the default uses $_SESSION.
118  *
119  * Next, the application should call the Auth_OpenID_Consumer object's
120  * 'begin' method.  This method takes the OpenID URL.  The 'begin'
121  * method returns an Auth_OpenID_AuthRequest object.
122  *
123  * Next, the application should call the 'redirectURL' method of the
124  * Auth_OpenID_AuthRequest object.  The 'return_to' URL parameter is
125  * the URL that the OpenID server will send the user back to after
126  * attempting to verify his or her identity.  The 'trust_root' is the
127  * URL (or URL pattern) that identifies your web site to the user when
128  * he or she is authorizing it.  Send a redirect to the resulting URL
129  * to the user's browser.
130  *
131  * That's the first half of the authentication process.  The second
132  * half of the process is done after the user's ID server sends the
133  * user's browser a redirect back to your site to complete their
134  * login.
135  *
136  * When that happens, the user will contact your site at the URL given
137  * as the 'return_to' URL to the Auth_OpenID_AuthRequest::redirectURL
138  * call made above.  The request will have several query parameters
139  * added to the URL by the identity server as the information
140  * necessary to finish the request.
141  *
142  * Lastly, instantiate an Auth_OpenID_Consumer instance as above and
143  * call its 'complete' method, passing in all the received query
144  * arguments.
145  *
146  * There are multiple possible return types possible from that
147  * method. These indicate the whether or not the login was successful,
148  * and include any additional information appropriate for their type.
149  *
150  * PHP versions 4 and 5
151  *
152  * LICENSE: See the COPYING file included in this distribution.
153  *
154  * @package OpenID
155  * @author JanRain, Inc. <openid@janrain.com>
156  * @copyright 2005-2008 Janrain, Inc.
157  * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
158  */
159
160 /**
161  * Require utility classes and functions for the consumer.
162  */
163 require_once "Auth/OpenID.php";
164 require_once "Auth/OpenID/Message.php";
165 require_once "Auth/OpenID/HMAC.php";
166 require_once "Auth/OpenID/Association.php";
167 require_once "Auth/OpenID/CryptUtil.php";
168 require_once "Auth/OpenID/DiffieHellman.php";
169 require_once "Auth/OpenID/KVForm.php";
170 require_once "Auth/OpenID/Nonce.php";
171 require_once "Auth/OpenID/Discover.php";
172 require_once "Auth/OpenID/URINorm.php";
173 require_once "Auth/Yadis/Manager.php";
174 require_once "Auth/Yadis/XRI.php";
175
176 /**
177  * This is the status code returned when the complete method returns
178  * successfully.
179  */
180 define('Auth_OpenID_SUCCESS', 'success');
181
182 /**
183  * Status to indicate cancellation of OpenID authentication.
184  */
185 define('Auth_OpenID_CANCEL', 'cancel');
186
187 /**
188  * This is the status code completeAuth returns when the value it
189  * received indicated an invalid login.
190  */
191 define('Auth_OpenID_FAILURE', 'failure');
192
193 /**
194  * This is the status code completeAuth returns when the
195  * {@link Auth_OpenID_Consumer} instance is in immediate mode, and the
196  * identity server sends back a URL to send the user to to complete his
197  * or her login.
198  */
199 define('Auth_OpenID_SETUP_NEEDED', 'setup needed');
200
201 /**
202  * This is the status code beginAuth returns when the page fetched
203  * from the entered OpenID URL doesn't contain the necessary link tags
204  * to function as an identity page.
205  */
206 define('Auth_OpenID_PARSE_ERROR', 'parse error');
207
208 /**
209  * An OpenID consumer implementation that performs discovery and does
210  * session management.  See the Consumer.php file documentation for
211  * more information.
212  *
213  * @package OpenID
214  */
215 class Auth_OpenID_Consumer {
216
217     /**
218      * @access private
219      */
220     var $discoverMethod = 'Auth_OpenID_discover';
221
222     /**
223      * @access private
224      */
225     var $session_key_prefix = "_openid_consumer_";
226
227     /**
228      * @access private
229      */
230     var $_token_suffix = "last_token";
231
232     /**
233      * Initialize a Consumer instance.
234      *
235      * You should create a new instance of the Consumer object with
236      * every HTTP request that handles OpenID transactions.
237      *
238      * @param Auth_OpenID_OpenIDStore $store This must be an object
239      * that implements the interface in {@link
240      * Auth_OpenID_OpenIDStore}.  Several concrete implementations are
241      * provided, to cover most common use cases.  For stores backed by
242      * MySQL, PostgreSQL, or SQLite, see the {@link
243      * Auth_OpenID_SQLStore} class and its sublcasses.  For a
244      * filesystem-backed store, see the {@link Auth_OpenID_FileStore}
245      * module.  As a last resort, if it isn't possible for the server
246      * to store state at all, an instance of {@link
247      * Auth_OpenID_DumbStore} can be used.
248      *
249      * @param mixed $session An object which implements the interface
250      * of the {@link Auth_Yadis_PHPSession} class.  Particularly, this
251      * object is expected to have these methods: get($key), set($key),
252      * $value), and del($key).  This defaults to a session object
253      * which wraps PHP's native session machinery.  You should only
254      * need to pass something here if you have your own sessioning
255      * implementation.
256      *
257      * @param str $consumer_cls The name of the class to instantiate
258      * when creating the internal consumer object.  This is used for
259      * testing.
260      */
261     function Auth_OpenID_Consumer(&$store, $session = null,
262                                   $consumer_cls = null)
263     {
264         if ($session === null) {
265             $session = new Auth_Yadis_PHPSession();
266         }
267
268         $this->session =& $session;
269
270         if ($consumer_cls !== null) {
271             $this->consumer =& new $consumer_cls($store);
272         } else {
273             $this->consumer =& new Auth_OpenID_GenericConsumer($store);
274         }
275
276         $this->_token_key = $this->session_key_prefix . $this->_token_suffix;
277     }
278
279     /**
280      * Used in testing to define the discovery mechanism.
281      *
282      * @access private
283      */
284     function getDiscoveryObject(&$session, $openid_url,
285                                 $session_key_prefix)
286     {
287         return new Auth_Yadis_Discovery($session, $openid_url,
288                                         $session_key_prefix);
289     }
290
291     /**
292      * Start the OpenID authentication process. See steps 1-2 in the
293      * overview at the top of this file.
294      *
295      * @param string $user_url Identity URL given by the user. This
296      * method performs a textual transformation of the URL to try and
297      * make sure it is normalized. For example, a user_url of
298      * example.com will be normalized to http://example.com/
299      * normalizing and resolving any redirects the server might issue.
300      *
301      * @param bool $anonymous True if the OpenID request is to be sent
302      * to the server without any identifier information.  Use this
303      * when you want to transport data but don't want to do OpenID
304      * authentication with identifiers.
305      *
306      * @return Auth_OpenID_AuthRequest $auth_request An object
307      * containing the discovered information will be returned, with a
308      * method for building a redirect URL to the server, as described
309      * in step 3 of the overview. This object may also be used to add
310      * extension arguments to the request, using its 'addExtensionArg'
311      * method.
312      */
313     function begin($user_url, $anonymous=false)
314     {
315         $openid_url = $user_url;
316
317         $disco = $this->getDiscoveryObject($this->session,
318                                            $openid_url,
319                                            $this->session_key_prefix);
320
321         // Set the 'stale' attribute of the manager.  If discovery
322         // fails in a fatal way, the stale flag will cause the manager
323         // to be cleaned up next time discovery is attempted.
324
325         $m = $disco->getManager();
326         $loader = new Auth_Yadis_ManagerLoader();
327
328         if ($m) {
329             if ($m->stale) {
330                 $disco->destroyManager();
331             } else {
332                 $m->stale = true;
333                 $disco->session->set($disco->session_key,
334                                      serialize($loader->toSession($m)));
335             }
336         }
337
338         $endpoint = $disco->getNextService($this->discoverMethod,
339                                            $this->consumer->fetcher);
340
341         // Reset the 'stale' attribute of the manager.
342         $m =& $disco->getManager();
343         if ($m) {
344             $m->stale = false;
345             $disco->session->set($disco->session_key,
346                                  serialize($loader->toSession($m)));
347         }
348
349         if ($endpoint === null) {
350             return null;
351         } else {
352             return $this->beginWithoutDiscovery($endpoint,
353                                                 $anonymous);
354         }
355     }
356
357     /**
358      * Start OpenID verification without doing OpenID server
359      * discovery. This method is used internally by Consumer.begin
360      * after discovery is performed, and exists to provide an
361      * interface for library users needing to perform their own
362      * discovery.
363      *
364      * @param Auth_OpenID_ServiceEndpoint $endpoint an OpenID service
365      * endpoint descriptor.
366      *
367      * @param bool anonymous Set to true if you want to perform OpenID
368      * without identifiers.
369      *
370      * @return Auth_OpenID_AuthRequest $auth_request An OpenID
371      * authentication request object.
372      */
373     function &beginWithoutDiscovery($endpoint, $anonymous=false)
374     {
375         $loader = new Auth_OpenID_ServiceEndpointLoader();
376         $auth_req = $this->consumer->begin($endpoint);
377         $this->session->set($this->_token_key,
378               $loader->toSession($auth_req->endpoint));
379         if (!$auth_req->setAnonymous($anonymous)) {
380             return new Auth_OpenID_FailureResponse(null,
381               "OpenID 1 requests MUST include the identifier " .
382               "in the request.");
383         }
384         return $auth_req;
385     }
386
387     /**
388      * Called to interpret the server's response to an OpenID
389      * request. It is called in step 4 of the flow described in the
390      * consumer overview.
391      *
392      * @param string $current_url The URL used to invoke the application.
393      * Extract the URL from your application's web
394      * request framework and specify it here to have it checked
395      * against the openid.current_url value in the response.  If
396      * the current_url URL check fails, the status of the
397      * completion will be FAILURE.
398      *
399      * @param array $query An array of the query parameters (key =>
400      * value pairs) for this HTTP request.  Defaults to null.  If
401      * null, the GET or POST data are automatically gotten from the
402      * PHP environment.  It is only useful to override $query for
403      * testing.
404      *
405      * @return Auth_OpenID_ConsumerResponse $response A instance of an
406      * Auth_OpenID_ConsumerResponse subclass. The type of response is
407      * indicated by the status attribute, which will be one of
408      * SUCCESS, CANCEL, FAILURE, or SETUP_NEEDED.
409      */
410     function complete($current_url, $query=null)
411     {
412         if ($current_url && !is_string($current_url)) {
413             // This is ugly, but we need to complain loudly when
414             // someone uses the API incorrectly.
415             trigger_error("current_url must be a string; see NEWS file " .
416                           "for upgrading notes.",
417                           E_USER_ERROR);
418         }
419
420         if ($query === null) {
421             $query = Auth_OpenID::getQuery();
422         }
423
424         $loader = new Auth_OpenID_ServiceEndpointLoader();
425         $endpoint_data = $this->session->get($this->_token_key);
426         $endpoint =
427             $loader->fromSession($endpoint_data);
428
429         $message = Auth_OpenID_Message::fromPostArgs($query);
430         $response = $this->consumer->complete($message, $endpoint, 
431                                               $current_url);
432         $this->session->del($this->_token_key);
433
434         if (in_array($response->status, array(Auth_OpenID_SUCCESS,
435                                               Auth_OpenID_CANCEL))) {
436             if ($response->identity_url !== null) {
437                 $disco = $this->getDiscoveryObject($this->session,
438                                                    $response->identity_url,
439                                                    $this->session_key_prefix);
440                 $disco->cleanup(true);
441             }
442         }
443
444         return $response;
445     }
446 }
447
448 /**
449  * A class implementing HMAC/DH-SHA1 consumer sessions.
450  *
451  * @package OpenID
452  */
453 class Auth_OpenID_DiffieHellmanSHA1ConsumerSession {
454     var $session_type = 'DH-SHA1';
455     var $hash_func = 'Auth_OpenID_SHA1';
456     var $secret_size = 20;
457     var $allowed_assoc_types = array('HMAC-SHA1');
458
459     function Auth_OpenID_DiffieHellmanSHA1ConsumerSession($dh = null)
460     {
461         if ($dh === null) {
462             $dh = new Auth_OpenID_DiffieHellman();
463         }
464
465         $this->dh = $dh;
466     }
467
468     function getRequest()
469     {
470         $math =& Auth_OpenID_getMathLib();
471
472         $cpub = $math->longToBase64($this->dh->public);
473
474         $args = array('dh_consumer_public' => $cpub);
475
476         if (!$this->dh->usingDefaultValues()) {
477             $args = array_merge($args, array(
478                 'dh_modulus' =>
479                      $math->longToBase64($this->dh->mod),
480                 'dh_gen' =>
481                      $math->longToBase64($this->dh->gen)));
482         }
483
484         return $args;
485     }
486
487     function extractSecret($response)
488     {
489         if (!$response->hasKey(Auth_OpenID_OPENID_NS,
490                                'dh_server_public')) {
491             return null;
492         }
493
494         if (!$response->hasKey(Auth_OpenID_OPENID_NS,
495                                'enc_mac_key')) {
496             return null;
497         }
498
499         $math =& Auth_OpenID_getMathLib();
500
501         $spub = $math->base64ToLong($response->getArg(Auth_OpenID_OPENID_NS,
502                                                       'dh_server_public'));
503         $enc_mac_key = base64_decode($response->getArg(Auth_OpenID_OPENID_NS,
504                                                        'enc_mac_key'));
505
506         return $this->dh->xorSecret($spub, $enc_mac_key, $this->hash_func);
507     }
508 }
509
510 /**
511  * A class implementing HMAC/DH-SHA256 consumer sessions.
512  *
513  * @package OpenID
514  */
515 class Auth_OpenID_DiffieHellmanSHA256ConsumerSession extends
516       Auth_OpenID_DiffieHellmanSHA1ConsumerSession {
517     var $session_type = 'DH-SHA256';
518     var $hash_func = 'Auth_OpenID_SHA256';
519     var $secret_size = 32;
520     var $allowed_assoc_types = array('HMAC-SHA256');
521 }
522
523 /**
524  * A class implementing plaintext consumer sessions.
525  *
526  * @package OpenID
527  */
528 class Auth_OpenID_PlainTextConsumerSession {
529     var $session_type = 'no-encryption';
530     var $allowed_assoc_types =  array('HMAC-SHA1', 'HMAC-SHA256');
531
532     function getRequest()
533     {
534         return array();
535     }
536
537     function extractSecret($response)
538     {
539         if (!$response->hasKey(Auth_OpenID_OPENID_NS, 'mac_key')) {
540             return null;
541         }
542
543         return base64_decode($response->getArg(Auth_OpenID_OPENID_NS,
544                                                'mac_key'));
545     }
546 }
547
548 /**
549  * Returns available session types.
550  */
551 function Auth_OpenID_getAvailableSessionTypes()
552 {
553     $types = array(
554       'no-encryption' => 'Auth_OpenID_PlainTextConsumerSession',
555       'DH-SHA1' => 'Auth_OpenID_DiffieHellmanSHA1ConsumerSession',
556       'DH-SHA256' => 'Auth_OpenID_DiffieHellmanSHA256ConsumerSession');
557
558     return $types;
559 }
560
561 /**
562  * This class is the interface to the OpenID consumer logic.
563  * Instances of it maintain no per-request state, so they can be
564  * reused (or even used by multiple threads concurrently) as needed.
565  *
566  * @package OpenID
567  */
568 class Auth_OpenID_GenericConsumer {
569     /**
570      * @access private
571      */
572     var $discoverMethod = 'Auth_OpenID_discover';
573
574     /**
575      * This consumer's store object.
576      */
577     var $store;
578
579     /**
580      * @access private
581      */
582     var $_use_assocs;
583
584     /**
585      * @access private
586      */
587     var $openid1_nonce_query_arg_name = 'janrain_nonce';
588
589     /**
590      * Another query parameter that gets added to the return_to for
591      * OpenID 1; if the user's session state is lost, use this claimed
592      * identifier to do discovery when verifying the response.
593      */
594     var $openid1_return_to_identifier_name = 'openid1_claimed_id';
595
596     /**
597      * This method initializes a new {@link Auth_OpenID_Consumer}
598      * instance to access the library.
599      *
600      * @param Auth_OpenID_OpenIDStore $store This must be an object
601      * that implements the interface in {@link Auth_OpenID_OpenIDStore}.
602      * Several concrete implementations are provided, to cover most common use
603      * cases.  For stores backed by MySQL, PostgreSQL, or SQLite, see
604      * the {@link Auth_OpenID_SQLStore} class and its sublcasses.  For a
605      * filesystem-backed store, see the {@link Auth_OpenID_FileStore} module.
606      * As a last resort, if it isn't possible for the server to store
607      * state at all, an instance of {@link Auth_OpenID_DumbStore} can be used.
608      *
609      * @param bool $immediate This is an optional boolean value.  It
610      * controls whether the library uses immediate mode, as explained
611      * in the module description.  The default value is False, which
612      * disables immediate mode.
613      */
614     function Auth_OpenID_GenericConsumer(&$store)
615     {
616         $this->store =& $store;
617         $this->negotiator =& Auth_OpenID_getDefaultNegotiator();
618         $this->_use_assocs = ($this->store ? true : false);
619
620         $this->fetcher = Auth_Yadis_Yadis::getHTTPFetcher();
621
622         $this->session_types = Auth_OpenID_getAvailableSessionTypes();
623     }
624
625     /**
626      * Called to begin OpenID authentication using the specified
627      * {@link Auth_OpenID_ServiceEndpoint}.
628      *
629      * @access private
630      */
631     function begin($service_endpoint)
632     {
633         $assoc = $this->_getAssociation($service_endpoint);
634         $r = new Auth_OpenID_AuthRequest($service_endpoint, $assoc);
635         $r->return_to_args[$this->openid1_nonce_query_arg_name] =
636             Auth_OpenID_mkNonce();
637
638         if ($r->message->isOpenID1()) {
639             $r->return_to_args[$this->openid1_return_to_identifier_name] =
640                 $r->endpoint->claimed_id;
641         }
642
643         return $r;
644     }
645
646     /**
647      * Given an {@link Auth_OpenID_Message}, {@link
648      * Auth_OpenID_ServiceEndpoint} and optional return_to URL,
649      * complete OpenID authentication.
650      *
651      * @access private
652      */
653     function complete($message, $endpoint, $return_to)
654     {
655         $mode = $message->getArg(Auth_OpenID_OPENID_NS, 'mode',
656                                  '<no mode set>');
657
658         $mode_methods = array(
659                               'cancel' => '_complete_cancel',
660                               'error' => '_complete_error',
661                               'setup_needed' => '_complete_setup_needed',
662                               'id_res' => '_complete_id_res',
663                               );
664
665         $method = Auth_OpenID::arrayGet($mode_methods, $mode,
666                                         '_completeInvalid');
667
668         return call_user_func_array(array(&$this, $method),
669                                     array($message, $endpoint, $return_to));
670     }
671
672     /**
673      * @access private
674      */
675     function _completeInvalid($message, &$endpoint, $unused)
676     {
677         $mode = $message->getArg(Auth_OpenID_OPENID_NS, 'mode',
678                                  '<No mode set>');
679
680         return new Auth_OpenID_FailureResponse($endpoint,
681                     sprintf("Invalid openid.mode '%s'", $mode));
682     }
683
684     /**
685      * @access private
686      */
687     function _complete_cancel($message, &$endpoint, $unused)
688     {
689         return new Auth_OpenID_CancelResponse($endpoint);
690     }
691
692     /**
693      * @access private
694      */
695     function _complete_error($message, &$endpoint, $unused)
696     {
697         $error = $message->getArg(Auth_OpenID_OPENID_NS, 'error');
698         $contact = $message->getArg(Auth_OpenID_OPENID_NS, 'contact');
699         $reference = $message->getArg(Auth_OpenID_OPENID_NS, 'reference');
700
701         return new Auth_OpenID_FailureResponse($endpoint, $error,
702                                                $contact, $reference);
703     }
704
705     /**
706      * @access private
707      */
708     function _complete_setup_needed($message, &$endpoint, $unused)
709     {
710         if (!$message->isOpenID2()) {
711             return $this->_completeInvalid($message, $endpoint);
712         }
713
714         return new Auth_OpenID_SetupNeededResponse($endpoint);
715     }
716
717     /**
718      * @access private
719      */
720     function _complete_id_res($message, &$endpoint, $return_to)
721     {
722         $user_setup_url = $message->getArg(Auth_OpenID_OPENID1_NS,
723                                            'user_setup_url');
724
725         if ($this->_checkSetupNeeded($message)) {
726             return new Auth_OpenID_SetupNeededResponse(
727                 $endpoint, $user_setup_url);
728         } else {
729             return $this->_doIdRes($message, $endpoint, $return_to);
730         }
731     }
732
733     /**
734      * @access private
735      */
736     function _checkSetupNeeded($message)
737     {
738         // In OpenID 1, we check to see if this is a cancel from
739         // immediate mode by the presence of the user_setup_url
740         // parameter.
741         if ($message->isOpenID1()) {
742             $user_setup_url = $message->getArg(Auth_OpenID_OPENID1_NS,
743                                                'user_setup_url');
744             if ($user_setup_url !== null) {
745                 return true;
746             }
747         }
748
749         return false;
750     }
751
752     /**
753      * @access private
754      */
755     function _doIdRes($message, $endpoint, $return_to)
756     {
757         // Checks for presence of appropriate fields (and checks
758         // signed list fields)
759         $result = $this->_idResCheckForFields($message);
760
761         if (Auth_OpenID::isFailure($result)) {
762             return $result;
763         }
764
765         if (!$this->_checkReturnTo($message, $return_to)) {
766             return new Auth_OpenID_FailureResponse(null,
767             sprintf("return_to does not match return URL. Expected %s, got %s",
768                     $return_to,
769                     $message->getArg(Auth_OpenID_OPENID_NS, 'return_to')));
770         }
771
772         // Verify discovery information:
773         $result = $this->_verifyDiscoveryResults($message, $endpoint);
774
775         if (Auth_OpenID::isFailure($result)) {
776             return $result;
777         }
778
779         $endpoint = $result;
780
781         $result = $this->_idResCheckSignature($message,
782                                               $endpoint->server_url);
783
784         if (Auth_OpenID::isFailure($result)) {
785             return $result;
786         }
787
788         $result = $this->_idResCheckNonce($message, $endpoint);
789
790         if (Auth_OpenID::isFailure($result)) {
791             return $result;
792         }
793
794         $signed_list_str = $message->getArg(Auth_OpenID_OPENID_NS, 'signed',
795                                             Auth_OpenID_NO_DEFAULT);
796         if (Auth_OpenID::isFailure($signed_list_str)) {
797             return $signed_list_str;
798         }
799         $signed_list = explode(',', $signed_list_str);
800
801         $signed_fields = Auth_OpenID::addPrefix($signed_list, "openid.");
802
803         return new Auth_OpenID_SuccessResponse($endpoint, $message,
804                                                $signed_fields);
805
806     }
807
808     /**
809      * @access private
810      */
811     function _checkReturnTo($message, $return_to)
812     {
813         // Check an OpenID message and its openid.return_to value
814         // against a return_to URL from an application.  Return True
815         // on success, False on failure.
816
817         // Check the openid.return_to args against args in the
818         // original message.
819         $result = Auth_OpenID_GenericConsumer::_verifyReturnToArgs(
820                                            $message->toPostArgs());
821         if (Auth_OpenID::isFailure($result)) {
822             return false;
823         }
824
825         // Check the return_to base URL against the one in the
826         // message.
827         $msg_return_to = $message->getArg(Auth_OpenID_OPENID_NS,
828                                           'return_to');
829         if (Auth_OpenID::isFailure($return_to)) {
830             // XXX log me
831             return false;
832         }
833
834         $return_to_parts = parse_url(Auth_OpenID_urinorm($return_to));
835         $msg_return_to_parts = parse_url(Auth_OpenID_urinorm($msg_return_to));
836
837         // If port is absent from both, add it so it's equal in the
838         // check below.
839         if ((!array_key_exists('port', $return_to_parts)) &&
840             (!array_key_exists('port', $msg_return_to_parts))) {
841             $return_to_parts['port'] = null;
842             $msg_return_to_parts['port'] = null;
843         }
844
845         // If path is absent from both, add it so it's equal in the
846         // check below.
847         if ((!array_key_exists('path', $return_to_parts)) &&
848             (!array_key_exists('path', $msg_return_to_parts))) {
849             $return_to_parts['path'] = null;
850             $msg_return_to_parts['path'] = null;
851         }
852
853         // The URL scheme, authority, and path MUST be the same
854         // between the two URLs.
855         foreach (array('scheme', 'host', 'port', 'path') as $component) {
856             // If the url component is absent in either URL, fail.
857             // There should always be a scheme, host, port, and path.
858             if (!array_key_exists($component, $return_to_parts)) {
859                 return false;
860             }
861
862             if (!array_key_exists($component, $msg_return_to_parts)) {
863                 return false;
864             }
865
866             if (Auth_OpenID::arrayGet($return_to_parts, $component) !==
867                 Auth_OpenID::arrayGet($msg_return_to_parts, $component)) {
868                 return false;
869             }
870         }
871
872         return true;
873     }
874
875     /**
876      * @access private
877      */
878     function _verifyReturnToArgs($query)
879     {
880         // Verify that the arguments in the return_to URL are present in this
881         // response.
882
883         $message = Auth_OpenID_Message::fromPostArgs($query);
884         $return_to = $message->getArg(Auth_OpenID_OPENID_NS, 'return_to');
885
886         if (Auth_OpenID::isFailure($return_to)) {
887             return $return_to;
888         }
889         // XXX: this should be checked by _idResCheckForFields
890         if (!$return_to) {
891             return new Auth_OpenID_FailureResponse(null,
892                            "Response has no return_to");
893         }
894
895         $parsed_url = parse_url($return_to);
896
897         $q = array();
898         if (array_key_exists('query', $parsed_url)) {
899             $rt_query = $parsed_url['query'];
900             $q = Auth_OpenID::parse_str($rt_query);
901         }
902
903         foreach ($q as $rt_key => $rt_value) {
904             if (!array_key_exists($rt_key, $query)) {
905                 return new Auth_OpenID_FailureResponse(null,
906                   sprintf("return_to parameter %s absent from query", $rt_key));
907             } else {
908                 $value = $query[$rt_key];
909                 if ($rt_value != $value) {
910                     return new Auth_OpenID_FailureResponse(null,
911                       sprintf("parameter %s value %s does not match " .
912                               "return_to value %s", $rt_key,
913                               $value, $rt_value));
914                 }
915             }
916         }
917
918         // Make sure all non-OpenID arguments in the response are also
919         // in the signed return_to.
920         $bare_args = $message->getArgs(Auth_OpenID_BARE_NS);
921         foreach ($bare_args as $key => $value) {
922             if (Auth_OpenID::arrayGet($q, $key) != $value) {
923                 return new Auth_OpenID_FailureResponse(null,
924                   sprintf("Parameter %s = %s not in return_to URL",
925                           $key, $value));
926             }
927         }
928
929         return true;
930     }
931
932     /**
933      * @access private
934      */
935     function _idResCheckSignature($message, $server_url)
936     {
937         $assoc_handle = $message->getArg(Auth_OpenID_OPENID_NS,
938                                          'assoc_handle');
939         if (Auth_OpenID::isFailure($assoc_handle)) {
940             return $assoc_handle;
941         }
942
943         $assoc = $this->store->getAssociation($server_url, $assoc_handle);
944
945         if ($assoc) {
946             if ($assoc->getExpiresIn() <= 0) {
947                 // XXX: It might be a good idea sometimes to re-start
948                 // the authentication with a new association. Doing it
949                 // automatically opens the possibility for
950                 // denial-of-service by a server that just returns
951                 // expired associations (or really short-lived
952                 // associations)
953                 return new Auth_OpenID_FailureResponse(null,
954                              'Association with ' . $server_url . ' expired');
955             }
956
957             if (!$assoc->checkMessageSignature($message)) {
958                 return new Auth_OpenID_FailureResponse(null,
959                                                        "Bad signature");
960             }
961         } else {
962             // It's not an association we know about.  Stateless mode
963             // is our only possible path for recovery.  XXX - async
964             // framework will not want to block on this call to
965             // _checkAuth.
966             if (!$this->_checkAuth($message, $server_url)) {
967                 return new Auth_OpenID_FailureResponse(null,
968                              "Server denied check_authentication");
969             }
970         }
971
972         return null;
973     }
974
975     /**
976      * @access private
977      */
978     function _verifyDiscoveryResults($message, $endpoint=null)
979     {
980         if ($message->getOpenIDNamespace() == Auth_OpenID_OPENID2_NS) {
981             return $this->_verifyDiscoveryResultsOpenID2($message,
982                                                          $endpoint);
983         } else {
984             return $this->_verifyDiscoveryResultsOpenID1($message,
985                                                          $endpoint);
986         }
987     }
988
989     /**
990      * @access private
991      */
992     function _verifyDiscoveryResultsOpenID1($message, $endpoint)
993     {
994         $claimed_id = $message->getArg(Auth_OpenID_BARE_NS,
995                                 $this->openid1_return_to_identifier_name);
996
997         if (($endpoint === null) && ($claimed_id === null)) {
998             return new Auth_OpenID_FailureResponse($endpoint,
999               'When using OpenID 1, the claimed ID must be supplied, ' .
1000               'either by passing it through as a return_to parameter ' .
1001               'or by using a session, and supplied to the GenericConsumer ' .
1002               'as the argument to complete()');
1003         } else if (($endpoint !== null) && ($claimed_id === null)) {
1004             $claimed_id = $endpoint->claimed_id;
1005         }
1006
1007         $to_match = new Auth_OpenID_ServiceEndpoint();
1008         $to_match->type_uris = array(Auth_OpenID_TYPE_1_1);
1009         $to_match->local_id = $message->getArg(Auth_OpenID_OPENID1_NS,
1010                                                'identity');
1011
1012         // Restore delegate information from the initiation phase
1013         $to_match->claimed_id = $claimed_id;
1014
1015         if ($to_match->local_id === null) {
1016             return new Auth_OpenID_FailureResponse($endpoint,
1017                          "Missing required field openid.identity");
1018         }
1019
1020         $to_match_1_0 = $to_match->copy();
1021         $to_match_1_0->type_uris = array(Auth_OpenID_TYPE_1_0);
1022
1023         if ($endpoint !== null) {
1024             $result = $this->_verifyDiscoverySingle($endpoint, $to_match);
1025
1026             if (is_a($result, 'Auth_OpenID_TypeURIMismatch')) {
1027                 $result = $this->_verifyDiscoverySingle($endpoint,
1028                                                         $to_match_1_0);
1029             }
1030
1031             if (Auth_OpenID::isFailure($result)) {
1032                 // oidutil.log("Error attempting to use stored
1033                 //             discovery information: " + str(e))
1034                 //             oidutil.log("Attempting discovery to
1035                 //             verify endpoint")
1036             } else {
1037                 return $endpoint;
1038             }
1039         }
1040
1041         // Endpoint is either bad (failed verification) or None
1042         return $this->_discoverAndVerify($to_match->claimed_id,
1043                                          array($to_match, $to_match_1_0));
1044     }
1045
1046     /**
1047      * @access private
1048      */
1049     function _verifyDiscoverySingle($endpoint, $to_match)
1050     {
1051         // Every type URI that's in the to_match endpoint has to be
1052         // present in the discovered endpoint.
1053         foreach ($to_match->type_uris as $type_uri) {
1054             if (!$endpoint->usesExtension($type_uri)) {
1055                 return new Auth_OpenID_TypeURIMismatch($endpoint,
1056                              "Required type ".$type_uri." not present");
1057             }
1058         }
1059
1060         // Fragments do not influence discovery, so we can't compare a
1061         // claimed identifier with a fragment to discovered
1062         // information.
1063         list($defragged_claimed_id, $_) =
1064             Auth_OpenID::urldefrag($to_match->claimed_id);
1065
1066         if ($defragged_claimed_id != $endpoint->claimed_id) {
1067             return new Auth_OpenID_FailureResponse($endpoint,
1068               sprintf('Claimed ID does not match (different subjects!), ' .
1069                       'Expected %s, got %s', $defragged_claimed_id,
1070                       $endpoint->claimed_id));
1071         }
1072
1073         if ($to_match->getLocalID() != $endpoint->getLocalID()) {
1074             return new Auth_OpenID_FailureResponse($endpoint,
1075               sprintf('local_id mismatch. Expected %s, got %s',
1076                       $to_match->getLocalID(), $endpoint->getLocalID()));
1077         }
1078
1079         // If the server URL is None, this must be an OpenID 1
1080         // response, because op_endpoint is a required parameter in
1081         // OpenID 2. In that case, we don't actually care what the
1082         // discovered server_url is, because signature checking or
1083         // check_auth should take care of that check for us.
1084         if ($to_match->server_url === null) {
1085             if ($to_match->preferredNamespace() != Auth_OpenID_OPENID1_NS) {
1086                 return new Auth_OpenID_FailureResponse($endpoint,
1087                              "Preferred namespace mismatch (bug)");
1088             }
1089         } else if ($to_match->server_url != $endpoint->server_url) {
1090             return new Auth_OpenID_FailureResponse($endpoint,
1091               sprintf('OP Endpoint mismatch. Expected %s, got %s',
1092                       $to_match->server_url, $endpoint->server_url));
1093         }
1094
1095         return null;
1096     }
1097
1098     /**
1099      * @access private
1100      */
1101     function _verifyDiscoveryResultsOpenID2($message, $endpoint)
1102     {
1103         $to_match = new Auth_OpenID_ServiceEndpoint();
1104         $to_match->type_uris = array(Auth_OpenID_TYPE_2_0);
1105         $to_match->claimed_id = $message->getArg(Auth_OpenID_OPENID2_NS,
1106                                                  'claimed_id');
1107
1108         $to_match->local_id = $message->getArg(Auth_OpenID_OPENID2_NS,
1109                                                 'identity');
1110
1111         $to_match->server_url = $message->getArg(Auth_OpenID_OPENID2_NS,
1112                                                  'op_endpoint');
1113
1114         if ($to_match->server_url === null) {
1115             return new Auth_OpenID_FailureResponse($endpoint,
1116                          "OP Endpoint URL missing");
1117         }
1118
1119         // claimed_id and identifier must both be present or both be
1120         // absent
1121         if (($to_match->claimed_id === null) &&
1122             ($to_match->local_id !== null)) {
1123             return new Auth_OpenID_FailureResponse($endpoint,
1124               'openid.identity is present without openid.claimed_id');
1125         }
1126
1127         if (($to_match->claimed_id !== null) &&
1128             ($to_match->local_id === null)) {
1129             return new Auth_OpenID_FailureResponse($endpoint,
1130               'openid.claimed_id is present without openid.identity');
1131         }
1132
1133         if ($to_match->claimed_id === null) {
1134             // This is a response without identifiers, so there's
1135             // really no checking that we can do, so return an
1136             // endpoint that's for the specified `openid.op_endpoint'
1137             return Auth_OpenID_ServiceEndpoint::fromOPEndpointURL(
1138                                                 $to_match->server_url);
1139         }
1140
1141         if (!$endpoint) {
1142             // The claimed ID doesn't match, so we have to do
1143             // discovery again. This covers not using sessions, OP
1144             // identifier endpoints and responses that didn't match
1145             // the original request.
1146             // oidutil.log('No pre-discovered information supplied.')
1147             return $this->_discoverAndVerify($to_match->claimed_id,
1148                                              array($to_match));
1149         } else {
1150
1151             // The claimed ID matches, so we use the endpoint that we
1152             // discovered in initiation. This should be the most
1153             // common case.
1154             $result = $this->_verifyDiscoverySingle($endpoint, $to_match);
1155
1156             if (Auth_OpenID::isFailure($result)) {
1157                 $endpoint = $this->_discoverAndVerify($to_match->claimed_id,
1158                                                       array($to_match));
1159                 if (Auth_OpenID::isFailure($endpoint)) {
1160                     return $endpoint;
1161                 }
1162             }
1163         }
1164
1165         // The endpoint we return should have the claimed ID from the
1166         // message we just verified, fragment and all.
1167         if ($endpoint->claimed_id != $to_match->claimed_id) {
1168             $endpoint->claimed_id = $to_match->claimed_id;
1169         }
1170
1171         return $endpoint;
1172     }
1173
1174     /**
1175      * @access private
1176      */
1177     function _discoverAndVerify($claimed_id, $to_match_endpoints)
1178     {
1179         // oidutil.log('Performing discovery on %s' % (claimed_id,))
1180         list($unused, $services) = call_user_func($this->discoverMethod,
1181                                                   $claimed_id,
1182                                                   $this->fetcher);
1183
1184         if (!$services) {
1185             return new Auth_OpenID_FailureResponse(null,
1186               sprintf("No OpenID information found at %s",
1187                       $claimed_id));
1188         }
1189
1190         return $this->_verifyDiscoveryServices($claimed_id, $services,
1191                                                $to_match_endpoints);
1192     }
1193
1194     /**
1195      * @access private
1196      */
1197     function _verifyDiscoveryServices($claimed_id, 
1198                                       &$services, &$to_match_endpoints)
1199     {
1200         // Search the services resulting from discovery to find one
1201         // that matches the information from the assertion
1202
1203         foreach ($services as $endpoint) {
1204             foreach ($to_match_endpoints as $to_match_endpoint) {
1205                 $result = $this->_verifyDiscoverySingle($endpoint, 
1206                                                         $to_match_endpoint);
1207
1208                 if (!Auth_OpenID::isFailure($result)) {
1209                     // It matches, so discover verification has
1210                     // succeeded. Return this endpoint.
1211                     return $endpoint;
1212                 }
1213             }
1214         }
1215
1216         return new Auth_OpenID_FailureResponse(null,
1217           sprintf('No matching endpoint found after discovering %s',
1218                   $claimed_id));
1219     }
1220
1221     /**
1222      * Extract the nonce from an OpenID 1 response.  Return the nonce
1223      * from the BARE_NS since we independently check the return_to
1224      * arguments are the same as those in the response message.
1225      *
1226      * See the openid1_nonce_query_arg_name class variable
1227      *
1228      * @returns $nonce The nonce as a string or null
1229      *
1230      * @access private
1231      */
1232     function _idResGetNonceOpenID1($message, $endpoint)
1233     {
1234         return $message->getArg(Auth_OpenID_BARE_NS,
1235                                 $this->openid1_nonce_query_arg_name);
1236     }
1237
1238     /**
1239      * @access private
1240      */
1241     function _idResCheckNonce($message, $endpoint)
1242     {
1243         if ($message->isOpenID1()) {
1244             // This indicates that the nonce was generated by the consumer
1245             $nonce = $this->_idResGetNonceOpenID1($message, $endpoint);
1246             $server_url = '';
1247         } else {
1248             $nonce = $message->getArg(Auth_OpenID_OPENID2_NS,
1249                                       'response_nonce');
1250
1251             $server_url = $endpoint->server_url;
1252         }
1253
1254         if ($nonce === null) {
1255             return new Auth_OpenID_FailureResponse($endpoint,
1256                                      "Nonce missing from response");
1257         }
1258
1259         $parts = Auth_OpenID_splitNonce($nonce);
1260
1261         if ($parts === null) {
1262             return new Auth_OpenID_FailureResponse($endpoint,
1263                                      "Malformed nonce in response");
1264         }
1265
1266         list($timestamp, $salt) = $parts;
1267
1268         if (!$this->store->useNonce($server_url, $timestamp, $salt)) {
1269             return new Auth_OpenID_FailureResponse($endpoint,
1270                          "Nonce already used or out of range");
1271         }
1272
1273         return null;
1274     }
1275
1276     /**
1277      * @access private
1278      */
1279     function _idResCheckForFields($message)
1280     {
1281         $basic_fields = array('return_to', 'assoc_handle', 'sig', 'signed');
1282         $basic_sig_fields = array('return_to', 'identity');
1283
1284         $require_fields = array(
1285             Auth_OpenID_OPENID2_NS => array_merge($basic_fields,
1286                                                   array('op_endpoint')),
1287
1288             Auth_OpenID_OPENID1_NS => array_merge($basic_fields,
1289                                                   array('identity'))
1290             );
1291
1292         $require_sigs = array(
1293             Auth_OpenID_OPENID2_NS => array_merge($basic_sig_fields,
1294                                                   array('response_nonce',
1295                                                         'claimed_id',
1296                                                         'assoc_handle')),
1297             Auth_OpenID_OPENID1_NS => array_merge($basic_sig_fields,
1298                                                   array('nonce'))
1299             );
1300
1301         foreach ($require_fields[$message->getOpenIDNamespace()] as $field) {
1302             if (!$message->hasKey(Auth_OpenID_OPENID_NS, $field)) {
1303                 return new Auth_OpenID_FailureResponse(null,
1304                              "Missing required field '".$field."'");
1305             }
1306         }
1307
1308         $signed_list_str = $message->getArg(Auth_OpenID_OPENID_NS,
1309                                             'signed',
1310                                             Auth_OpenID_NO_DEFAULT);
1311         if (Auth_OpenID::isFailure($signed_list_str)) {
1312             return $signed_list_str;
1313         }
1314         $signed_list = explode(',', $signed_list_str);
1315
1316         foreach ($require_sigs[$message->getOpenIDNamespace()] as $field) {
1317             // Field is present and not in signed list
1318             if ($message->hasKey(Auth_OpenID_OPENID_NS, $field) &&
1319                 (!in_array($field, $signed_list))) {
1320                 return new Auth_OpenID_FailureResponse(null,
1321                              "'".$field."' not signed");
1322             }
1323         }
1324
1325         return null;
1326     }
1327
1328     /**
1329      * @access private
1330      */
1331     function _checkAuth($message, $server_url)
1332     {
1333         $request = $this->_createCheckAuthRequest($message);
1334         if ($request === null) {
1335             return false;
1336         }
1337
1338         $resp_message = $this->_makeKVPost($request, $server_url);
1339         if (($resp_message === null) ||
1340             (is_a($resp_message, 'Auth_OpenID_ServerErrorContainer'))) {
1341             return false;
1342         }
1343
1344         return $this->_processCheckAuthResponse($resp_message, $server_url);
1345     }
1346
1347     /**
1348      * @access private
1349      */
1350     function _createCheckAuthRequest($message)
1351     {
1352         $signed = $message->getArg(Auth_OpenID_OPENID_NS, 'signed');
1353         if ($signed) {
1354             foreach (explode(',', $signed) as $k) {
1355                 $value = $message->getAliasedArg($k);
1356                 if ($value === null) {
1357                     return null;
1358                 }
1359             }
1360         }
1361         $ca_message = $message->copy();
1362         $ca_message->setArg(Auth_OpenID_OPENID_NS, 'mode', 
1363                             'check_authentication');
1364         return $ca_message;
1365     }
1366
1367     /**
1368      * @access private
1369      */
1370     function _processCheckAuthResponse($response, $server_url)
1371     {
1372         $is_valid = $response->getArg(Auth_OpenID_OPENID_NS, 'is_valid',
1373                                       'false');
1374
1375         $invalidate_handle = $response->getArg(Auth_OpenID_OPENID_NS,
1376                                                'invalidate_handle');
1377
1378         if ($invalidate_handle !== null) {
1379             $this->store->removeAssociation($server_url,
1380                                             $invalidate_handle);
1381         }
1382
1383         if ($is_valid == 'true') {
1384             return true;
1385         }
1386
1387         return false;
1388     }
1389
1390     /**
1391      * Adapt a POST response to a Message.
1392      *
1393      * @param $response Result of a POST to an OpenID endpoint.
1394      *
1395      * @access private
1396      */
1397     function _httpResponseToMessage($response, $server_url)
1398     {
1399         // Should this function be named Message.fromHTTPResponse instead?
1400         $response_message = Auth_OpenID_Message::fromKVForm($response->body);
1401
1402         if ($response->status == 400) {
1403             return Auth_OpenID_ServerErrorContainer::fromMessage(
1404                         $response_message);
1405         } else if ($response->status != 200 and $response->status != 206) {
1406             return null;
1407         }
1408
1409         return $response_message;
1410     }
1411
1412     /**
1413      * @access private
1414      */
1415     function _makeKVPost($message, $server_url)
1416     {
1417         $body = $message->toURLEncoded();
1418         $resp = $this->fetcher->post($server_url, $body);
1419
1420         if ($resp === null) {
1421             return null;
1422         }
1423
1424         return $this->_httpResponseToMessage($resp, $server_url);
1425     }
1426
1427     /**
1428      * @access private
1429      */
1430     function _getAssociation($endpoint)
1431     {
1432         if (!$this->_use_assocs) {
1433             return null;
1434         }
1435
1436         $assoc = $this->store->getAssociation($endpoint->server_url);
1437
1438         if (($assoc === null) ||
1439             ($assoc->getExpiresIn() <= 0)) {
1440
1441             $assoc = $this->_negotiateAssociation($endpoint);
1442
1443             if ($assoc !== null) {
1444                 $this->store->storeAssociation($endpoint->server_url,
1445                                                $assoc);
1446             }
1447         }
1448
1449         return $assoc;
1450     }
1451
1452     /**
1453      * Handle ServerErrors resulting from association requests.
1454      *
1455      * @return $result If server replied with an C{unsupported-type}
1456      * error, return a tuple of supported C{association_type},
1457      * C{session_type}.  Otherwise logs the error and returns null.
1458      *
1459      * @access private
1460      */
1461     function _extractSupportedAssociationType(&$server_error, &$endpoint,
1462                                               $assoc_type)
1463     {
1464         // Any error message whose code is not 'unsupported-type'
1465         // should be considered a total failure.
1466         if (($server_error->error_code != 'unsupported-type') ||
1467             ($server_error->message->isOpenID1())) {
1468             return null;
1469         }
1470
1471         // The server didn't like the association/session type that we
1472         // sent, and it sent us back a message that might tell us how
1473         // to handle it.
1474
1475         // Extract the session_type and assoc_type from the error
1476         // message
1477         $assoc_type = $server_error->message->getArg(Auth_OpenID_OPENID_NS,
1478                                                      'assoc_type');
1479
1480         $session_type = $server_error->message->getArg(Auth_OpenID_OPENID_NS,
1481                                                        'session_type');
1482
1483         if (($assoc_type === null) || ($session_type === null)) {
1484             return null;
1485         } else if (!$this->negotiator->isAllowed($assoc_type,
1486                                                  $session_type)) {
1487             return null;
1488         } else {
1489           return array($assoc_type, $session_type);
1490         }
1491     }
1492
1493     /**
1494      * @access private
1495      */
1496     function _negotiateAssociation($endpoint)
1497     {
1498         // Get our preferred session/association type from the negotiatior.
1499         list($assoc_type, $session_type) = $this->negotiator->getAllowedType();
1500
1501         $assoc = $this->_requestAssociation(
1502                            $endpoint, $assoc_type, $session_type);
1503
1504         if (Auth_OpenID::isFailure($assoc)) {
1505             return null;
1506         }
1507
1508         if (is_a($assoc, 'Auth_OpenID_ServerErrorContainer')) {
1509             $why = $assoc;
1510
1511             $supportedTypes = $this->_extractSupportedAssociationType(
1512                                      $why, $endpoint, $assoc_type);
1513
1514             if ($supportedTypes !== null) {
1515                 list($assoc_type, $session_type) = $supportedTypes;
1516
1517                 // Attempt to create an association from the assoc_type
1518                 // and session_type that the server told us it
1519                 // supported.
1520                 $assoc = $this->_requestAssociation(
1521                                    $endpoint, $assoc_type, $session_type);
1522
1523                 if (is_a($assoc, 'Auth_OpenID_ServerErrorContainer')) {
1524                     // Do not keep trying, since it rejected the
1525                     // association type that it told us to use.
1526                     // oidutil.log('Server %s refused its suggested association
1527                     //             'type: session_type=%s, assoc_type=%s'
1528                     //             % (endpoint.server_url, session_type,
1529                     //                assoc_type))
1530                     return null;
1531                 } else {
1532                     return $assoc;
1533                 }
1534             } else {
1535                 return null;
1536             }
1537         } else {
1538             return $assoc;
1539         }
1540     }
1541
1542     /**
1543      * @access private
1544      */
1545     function _requestAssociation($endpoint, $assoc_type, $session_type)
1546     {
1547         list($assoc_session, $args) = $this->_createAssociateRequest(
1548                                       $endpoint, $assoc_type, $session_type);
1549
1550         $response_message = $this->_makeKVPost($args, $endpoint->server_url);
1551
1552         if ($response_message === null) {
1553             // oidutil.log('openid.associate request failed: %s' % (why[0],))
1554             return null;
1555         } else if (is_a($response_message,
1556                         'Auth_OpenID_ServerErrorContainer')) {
1557             return $response_message;
1558         }
1559
1560         return $this->_extractAssociation($response_message, $assoc_session);
1561     }
1562
1563     /**
1564      * @access private
1565      */
1566     function _extractAssociation(&$assoc_response, &$assoc_session)
1567     {
1568         // Extract the common fields from the response, raising an
1569         // exception if they are not found
1570         $assoc_type = $assoc_response->getArg(
1571                          Auth_OpenID_OPENID_NS, 'assoc_type',
1572                          Auth_OpenID_NO_DEFAULT);
1573
1574         if (Auth_OpenID::isFailure($assoc_type)) {
1575             return $assoc_type;
1576         }
1577
1578         $assoc_handle = $assoc_response->getArg(
1579                            Auth_OpenID_OPENID_NS, 'assoc_handle',
1580                            Auth_OpenID_NO_DEFAULT);
1581
1582         if (Auth_OpenID::isFailure($assoc_handle)) {
1583             return $assoc_handle;
1584         }
1585
1586         // expires_in is a base-10 string. The Python parsing will
1587         // accept literals that have whitespace around them and will
1588         // accept negative values. Neither of these are really in-spec,
1589         // but we think it's OK to accept them.
1590         $expires_in_str = $assoc_response->getArg(
1591                              Auth_OpenID_OPENID_NS, 'expires_in',
1592                              Auth_OpenID_NO_DEFAULT);
1593
1594         if (Auth_OpenID::isFailure($expires_in_str)) {
1595             return $expires_in_str;
1596         }
1597
1598         $expires_in = Auth_OpenID::intval($expires_in_str);
1599         if ($expires_in === false) {
1600             
1601             $err = sprintf("Could not parse expires_in from association ".
1602                            "response %s", print_r($assoc_response, true));
1603             return new Auth_OpenID_FailureResponse(null, $err);
1604         }
1605
1606         // OpenID 1 has funny association session behaviour.
1607         if ($assoc_response->isOpenID1()) {
1608             $session_type = $this->_getOpenID1SessionType($assoc_response);
1609         } else {
1610             $session_type = $assoc_response->getArg(
1611                                Auth_OpenID_OPENID2_NS, 'session_type',
1612                                Auth_OpenID_NO_DEFAULT);
1613
1614             if (Auth_OpenID::isFailure($session_type)) {
1615                 return $session_type;
1616             }
1617         }
1618
1619         // Session type mismatch
1620         if ($assoc_session->session_type != $session_type) {
1621             if ($assoc_response->isOpenID1() &&
1622                 ($session_type == 'no-encryption')) {
1623                 // In OpenID 1, any association request can result in
1624                 // a 'no-encryption' association response. Setting
1625                 // assoc_session to a new no-encryption session should
1626                 // make the rest of this function work properly for
1627                 // that case.
1628                 $assoc_session = new Auth_OpenID_PlainTextConsumerSession();
1629             } else {
1630                 // Any other mismatch, regardless of protocol version
1631                 // results in the failure of the association session
1632                 // altogether.
1633                 return null;
1634             }
1635         }
1636
1637         // Make sure assoc_type is valid for session_type
1638         if (!in_array($assoc_type, $assoc_session->allowed_assoc_types)) {
1639             return null;
1640         }
1641
1642         // Delegate to the association session to extract the secret
1643         // from the response, however is appropriate for that session
1644         // type.
1645         $secret = $assoc_session->extractSecret($assoc_response);
1646
1647         if ($secret === null) {
1648             return null;
1649         }
1650
1651         return Auth_OpenID_Association::fromExpiresIn(
1652                  $expires_in, $assoc_handle, $secret, $assoc_type);
1653     }
1654
1655     /**
1656      * @access private
1657      */
1658     function _createAssociateRequest($endpoint, $assoc_type, $session_type)
1659     {
1660         if (array_key_exists($session_type, $this->session_types)) {
1661             $session_type_class = $this->session_types[$session_type];
1662
1663             if (is_callable($session_type_class)) {
1664                 $assoc_session = $session_type_class();
1665             } else {
1666                 $assoc_session = new $session_type_class();
1667             }
1668         } else {
1669             return null;
1670         }
1671
1672         $args = array(
1673             'mode' => 'associate',
1674             'assoc_type' => $assoc_type);
1675
1676         if (!$endpoint->compatibilityMode()) {
1677             $args['ns'] = Auth_OpenID_OPENID2_NS;
1678         }
1679
1680         // Leave out the session type if we're in compatibility mode
1681         // *and* it's no-encryption.
1682         if ((!$endpoint->compatibilityMode()) ||
1683             ($assoc_session->session_type != 'no-encryption')) {
1684             $args['session_type'] = $assoc_session->session_type;
1685         }
1686
1687         $args = array_merge($args, $assoc_session->getRequest());
1688         $message = Auth_OpenID_Message::fromOpenIDArgs($args);
1689         return array($assoc_session, $message);
1690     }
1691
1692     /**
1693      * Given an association response message, extract the OpenID 1.X
1694      * session type.
1695      *
1696      * This function mostly takes care of the 'no-encryption' default
1697      * behavior in OpenID 1.
1698      *
1699      * If the association type is plain-text, this function will
1700      * return 'no-encryption'
1701      *
1702      * @access private
1703      * @return $typ The association type for this message
1704      */
1705     function _getOpenID1SessionType($assoc_response)
1706     {
1707         // If it's an OpenID 1 message, allow session_type to default
1708         // to None (which signifies "no-encryption")
1709         $session_type = $assoc_response->getArg(Auth_OpenID_OPENID1_NS,
1710                                                 'session_type');
1711
1712         // Handle the differences between no-encryption association
1713         // respones in OpenID 1 and 2:
1714
1715         // no-encryption is not really a valid session type for OpenID
1716         // 1, but we'll accept it anyway, while issuing a warning.
1717         if ($session_type == 'no-encryption') {
1718             // oidutil.log('WARNING: OpenID server sent "no-encryption"'
1719             //             'for OpenID 1.X')
1720         } else if (($session_type == '') || ($session_type === null)) {
1721             // Missing or empty session type is the way to flag a
1722             // 'no-encryption' response. Change the session type to
1723             // 'no-encryption' so that it can be handled in the same
1724             // way as OpenID 2 'no-encryption' respones.
1725             $session_type = 'no-encryption';
1726         }
1727
1728         return $session_type;
1729     }
1730 }
1731
1732 /**
1733  * This class represents an authentication request from a consumer to
1734  * an OpenID server.
1735  *
1736  * @package OpenID
1737  */
1738 class Auth_OpenID_AuthRequest {
1739
1740     /**
1741      * Initialize an authentication request with the specified token,
1742      * association, and endpoint.
1743      *
1744      * Users of this library should not create instances of this
1745      * class.  Instances of this class are created by the library when
1746      * needed.
1747      */
1748     function Auth_OpenID_AuthRequest(&$endpoint, $assoc)
1749     {
1750         $this->assoc = $assoc;
1751         $this->endpoint =& $endpoint;
1752         $this->return_to_args = array();
1753         $this->message = new Auth_OpenID_Message(
1754             $endpoint->preferredNamespace());
1755         $this->_anonymous = false;
1756     }
1757
1758     /**
1759      * Add an extension to this checkid request.
1760      *
1761      * $extension_request: An object that implements the extension
1762      * request interface for adding arguments to an OpenID message.
1763      */
1764     function addExtension(&$extension_request)
1765     {
1766         $extension_request->toMessage($this->message);
1767     }
1768
1769     /**
1770      * Add an extension argument to this OpenID authentication
1771      * request.
1772      *
1773      * Use caution when adding arguments, because they will be
1774      * URL-escaped and appended to the redirect URL, which can easily
1775      * get quite long.
1776      *
1777      * @param string $namespace The namespace for the extension. For
1778      * example, the simple registration extension uses the namespace
1779      * 'sreg'.
1780      *
1781      * @param string $key The key within the extension namespace. For
1782      * example, the nickname field in the simple registration
1783      * extension's key is 'nickname'.
1784      *
1785      * @param string $value The value to provide to the server for
1786      * this argument.
1787      */
1788     function addExtensionArg($namespace, $key, $value)
1789     {
1790         return $this->message->setArg($namespace, $key, $value);
1791     }
1792
1793     /**
1794      * Set whether this request should be made anonymously. If a
1795      * request is anonymous, the identifier will not be sent in the
1796      * request. This is only useful if you are making another kind of
1797      * request with an extension in this request.
1798      *
1799      * Anonymous requests are not allowed when the request is made
1800      * with OpenID 1.
1801      */
1802     function setAnonymous($is_anonymous)
1803     {
1804         if ($is_anonymous && $this->message->isOpenID1()) {
1805             return false;
1806         } else {
1807             $this->_anonymous = $is_anonymous;
1808             return true;
1809         }
1810     }
1811
1812     /**
1813      * Produce a {@link Auth_OpenID_Message} representing this
1814      * request.
1815      *
1816      * @param string $realm The URL (or URL pattern) that identifies
1817      * your web site to the user when she is authorizing it.
1818      *
1819      * @param string $return_to The URL that the OpenID provider will
1820      * send the user back to after attempting to verify her identity.
1821      *
1822      * Not specifying a return_to URL means that the user will not be
1823      * returned to the site issuing the request upon its completion.
1824      *
1825      * @param bool $immediate If true, the OpenID provider is to send
1826      * back a response immediately, useful for behind-the-scenes
1827      * authentication attempts.  Otherwise the OpenID provider may
1828      * engage the user before providing a response.  This is the
1829      * default case, as the user may need to provide credentials or
1830      * approve the request before a positive response can be sent.
1831      */
1832     function getMessage($realm, $return_to=null, $immediate=false)
1833     {
1834         if ($return_to) {
1835             $return_to = Auth_OpenID::appendArgs($return_to,
1836                                                  $this->return_to_args);
1837         } else if ($immediate) {
1838             // raise ValueError(
1839             //     '"return_to" is mandatory when
1840             //using "checkid_immediate"')
1841             return new Auth_OpenID_FailureResponse(null,
1842               "'return_to' is mandatory when using checkid_immediate");
1843         } else if ($this->message->isOpenID1()) {
1844             // raise ValueError('"return_to" is
1845             // mandatory for OpenID 1 requests')
1846             return new Auth_OpenID_FailureResponse(null,
1847               "'return_to' is mandatory for OpenID 1 requests");
1848         } else if ($this->return_to_args) {
1849             // raise ValueError('extra "return_to" arguments
1850             // were specified, but no return_to was specified')
1851             return new Auth_OpenID_FailureResponse(null,
1852               "extra 'return_to' arguments where specified, " .
1853               "but no return_to was specified");
1854         }
1855
1856         if ($immediate) {
1857             $mode = 'checkid_immediate';
1858         } else {
1859             $mode = 'checkid_setup';
1860         }
1861
1862         $message = $this->message->copy();
1863         if ($message->isOpenID1()) {
1864             $realm_key = 'trust_root';
1865         } else {
1866             $realm_key = 'realm';
1867         }
1868
1869         $message->updateArgs(Auth_OpenID_OPENID_NS,
1870                              array(
1871                                    $realm_key => $realm,
1872                                    'mode' => $mode,
1873                                    'return_to' => $return_to));
1874
1875         if (!$this->_anonymous) {
1876             if ($this->endpoint->isOPIdentifier()) {
1877                 // This will never happen when we're in compatibility
1878                 // mode, as long as isOPIdentifier() returns False
1879                 // whenever preferredNamespace() returns OPENID1_NS.
1880                 $claimed_id = $request_identity =
1881                     Auth_OpenID_IDENTIFIER_SELECT;
1882             } else {
1883                 $request_identity = $this->endpoint->getLocalID();
1884                 $claimed_id = $this->endpoint->claimed_id;
1885             }
1886
1887             // This is true for both OpenID 1 and 2
1888             $message->setArg(Auth_OpenID_OPENID_NS, 'identity',
1889                              $request_identity);
1890
1891             if ($message->isOpenID2()) {
1892                 $message->setArg(Auth_OpenID_OPENID2_NS, 'claimed_id',
1893                                  $claimed_id);
1894             }
1895         }
1896
1897         if ($this->assoc) {
1898             $message->setArg(Auth_OpenID_OPENID_NS, 'assoc_handle',
1899                              $this->assoc->handle);
1900         }
1901
1902         return $message;
1903     }
1904
1905     function redirectURL($realm, $return_to = null,
1906                          $immediate = false)
1907     {
1908         $message = $this->getMessage($realm, $return_to, $immediate);
1909
1910         if (Auth_OpenID::isFailure($message)) {
1911             return $message;
1912         }
1913
1914         return $message->toURL($this->endpoint->server_url);
1915     }
1916
1917     /**
1918      * Get html for a form to submit this request to the IDP.
1919      *
1920      * form_tag_attrs: An array of attributes to be added to the form
1921      * tag. 'accept-charset' and 'enctype' have defaults that can be
1922      * overridden. If a value is supplied for 'action' or 'method', it
1923      * will be replaced.
1924      */
1925     function formMarkup($realm, $return_to=null, $immediate=false,
1926                         $form_tag_attrs=null)
1927     {
1928         $message = $this->getMessage($realm, $return_to, $immediate);
1929
1930         if (Auth_OpenID::isFailure($message)) {
1931             return $message;
1932         }
1933
1934         return $message->toFormMarkup($this->endpoint->server_url,
1935                                       $form_tag_attrs);
1936     }
1937
1938     /**
1939      * Get a complete html document that will autosubmit the request
1940      * to the IDP.
1941      *
1942      * Wraps formMarkup.  See the documentation for that function.
1943      */
1944     function htmlMarkup($realm, $return_to=null, $immediate=false,
1945                         $form_tag_attrs=null)
1946     {
1947         $form = $this->formMarkup($realm, $return_to, $immediate, 
1948                                   $form_tag_attrs);
1949
1950         if (Auth_OpenID::isFailure($form)) {
1951             return $form;
1952         }
1953         return Auth_OpenID::autoSubmitHTML($form);
1954     }
1955
1956     function shouldSendRedirect()
1957     {
1958         return $this->endpoint->compatibilityMode();
1959     }
1960 }
1961
1962 /**
1963  * The base class for responses from the Auth_OpenID_Consumer.
1964  *
1965  * @package OpenID
1966  */
1967 class Auth_OpenID_ConsumerResponse {
1968     var $status = null;
1969
1970     function setEndpoint($endpoint)
1971     {
1972         $this->endpoint = $endpoint;
1973         if ($endpoint === null) {
1974             $this->identity_url = null;
1975         } else {
1976             $this->identity_url = $endpoint->claimed_id;
1977         }
1978     }
1979
1980     /**
1981      * Return the display identifier for this response.
1982      *
1983      * The display identifier is related to the Claimed Identifier, but the
1984      * two are not always identical.  The display identifier is something the
1985      * user should recognize as what they entered, whereas the response's
1986      * claimed identifier (in the identity_url attribute) may have extra
1987      * information for better persistence.
1988      *
1989      * URLs will be stripped of their fragments for display.  XRIs will
1990      * display the human-readable identifier (i-name) instead of the
1991      * persistent identifier (i-number).
1992      *
1993      * Use the display identifier in your user interface.  Use
1994      * identity_url for querying your database or authorization server.
1995      *
1996      */
1997     function getDisplayIdentifier()
1998     {
1999         if ($this->endpoint !== null) {
2000             return $this->endpoint->getDisplayIdentifier();
2001         }
2002         return null;
2003     }
2004 }
2005
2006 /**
2007  * A response with a status of Auth_OpenID_SUCCESS. Indicates that
2008  * this request is a successful acknowledgement from the OpenID server
2009  * that the supplied URL is, indeed controlled by the requesting
2010  * agent.  This has three relevant attributes:
2011  *
2012  * claimed_id - The identity URL that has been authenticated
2013  *
2014  * signed_args - The arguments in the server's response that were
2015  * signed and verified.
2016  *
2017  * status - Auth_OpenID_SUCCESS.
2018  *
2019  * @package OpenID
2020  */
2021 class Auth_OpenID_SuccessResponse extends Auth_OpenID_ConsumerResponse {
2022     var $status = Auth_OpenID_SUCCESS;
2023
2024     /**
2025      * @access private
2026      */
2027     function Auth_OpenID_SuccessResponse($endpoint, $message, $signed_args=null)
2028     {
2029         $this->endpoint = $endpoint;
2030         $this->identity_url = $endpoint->claimed_id;
2031         $this->signed_args = $signed_args;
2032         $this->message = $message;
2033
2034         if ($this->signed_args === null) {
2035             $this->signed_args = array();
2036         }
2037     }
2038
2039     /**
2040      * Extract signed extension data from the server's response.
2041      *
2042      * @param string $prefix The extension namespace from which to
2043      * extract the extension data.
2044      */
2045     function extensionResponse($namespace_uri, $require_signed)
2046     {
2047         if ($require_signed) {
2048             return $this->getSignedNS($namespace_uri);
2049         } else {
2050             return $this->message->getArgs($namespace_uri);
2051         }
2052     }
2053
2054     function isOpenID1()
2055     {
2056         return $this->message->isOpenID1();
2057     }
2058
2059     function isSigned($ns_uri, $ns_key)
2060     {
2061         // Return whether a particular key is signed, regardless of
2062         // its namespace alias
2063         return in_array($this->message->getKey($ns_uri, $ns_key),
2064                         $this->signed_args);
2065     }
2066
2067     function getSigned($ns_uri, $ns_key, $default = null)
2068     {
2069         // Return the specified signed field if available, otherwise
2070         // return default
2071         if ($this->isSigned($ns_uri, $ns_key)) {
2072             return $this->message->getArg($ns_uri, $ns_key, $default);
2073         } else {
2074             return $default;
2075         }
2076     }
2077
2078     function getSignedNS($ns_uri)
2079     {
2080         $args = array();
2081
2082         $msg_args = $this->message->getArgs($ns_uri);
2083         if (Auth_OpenID::isFailure($msg_args)) {
2084             return null;
2085         }
2086
2087         foreach ($msg_args as $key => $value) {
2088             if (!$this->isSigned($ns_uri, $key)) {
2089                 return null;
2090             }
2091         }
2092
2093         return $msg_args;
2094     }
2095
2096     /**
2097      * Get the openid.return_to argument from this response.
2098      *
2099      * This is useful for verifying that this request was initiated by
2100      * this consumer.
2101      *
2102      * @return string $return_to The return_to URL supplied to the
2103      * server on the initial request, or null if the response did not
2104      * contain an 'openid.return_to' argument.
2105     */
2106     function getReturnTo()
2107     {
2108         return $this->getSigned(Auth_OpenID_OPENID_NS, 'return_to');
2109     }
2110 }
2111
2112 /**
2113  * A response with a status of Auth_OpenID_FAILURE. Indicates that the
2114  * OpenID protocol has failed. This could be locally or remotely
2115  * triggered.  This has three relevant attributes:
2116  *
2117  * claimed_id - The identity URL for which authentication was
2118  * attempted, if it can be determined.  Otherwise, null.
2119  *
2120  * message - A message indicating why the request failed, if one is
2121  * supplied.  Otherwise, null.
2122  *
2123  * status - Auth_OpenID_FAILURE.
2124  *
2125  * @package OpenID
2126  */
2127 class Auth_OpenID_FailureResponse extends Auth_OpenID_ConsumerResponse {
2128     var $status = Auth_OpenID_FAILURE;
2129
2130     function Auth_OpenID_FailureResponse($endpoint, $message = null,
2131                                          $contact = null, $reference = null)
2132     {
2133         $this->setEndpoint($endpoint);
2134         $this->message = $message;
2135         $this->contact = $contact;
2136         $this->reference = $reference;
2137     }
2138 }
2139
2140 /**
2141  * A specific, internal failure used to detect type URI mismatch.
2142  *
2143  * @package OpenID
2144  */
2145 class Auth_OpenID_TypeURIMismatch extends Auth_OpenID_FailureResponse {
2146 }
2147
2148 /**
2149  * Exception that is raised when the server returns a 400 response
2150  * code to a direct request.
2151  *
2152  * @package OpenID
2153  */
2154 class Auth_OpenID_ServerErrorContainer {
2155     function Auth_OpenID_ServerErrorContainer($error_text,
2156                                               $error_code,
2157                                               $message)
2158     {
2159         $this->error_text = $error_text;
2160         $this->error_code = $error_code;
2161         $this->message = $message;
2162     }
2163
2164     /**
2165      * @access private
2166      */
2167     function fromMessage($message)
2168     {
2169         $error_text = $message->getArg(
2170            Auth_OpenID_OPENID_NS, 'error', '<no error message supplied>');
2171         $error_code = $message->getArg(Auth_OpenID_OPENID_NS, 'error_code');
2172         return new Auth_OpenID_ServerErrorContainer($error_text,
2173                                                     $error_code,
2174                                                     $message);
2175     }
2176 }
2177
2178 /**
2179  * A response with a status of Auth_OpenID_CANCEL. Indicates that the
2180  * user cancelled the OpenID authentication request.  This has two
2181  * relevant attributes:
2182  *
2183  * claimed_id - The identity URL for which authentication was
2184  * attempted, if it can be determined.  Otherwise, null.
2185  *
2186  * status - Auth_OpenID_SUCCESS.
2187  *
2188  * @package OpenID
2189  */
2190 class Auth_OpenID_CancelResponse extends Auth_OpenID_ConsumerResponse {
2191     var $status = Auth_OpenID_CANCEL;
2192
2193     function Auth_OpenID_CancelResponse($endpoint)
2194     {
2195         $this->setEndpoint($endpoint);
2196     }
2197 }
2198
2199 /**
2200  * A response with a status of Auth_OpenID_SETUP_NEEDED. Indicates
2201  * that the request was in immediate mode, and the server is unable to
2202  * authenticate the user without further interaction.
2203  *
2204  * claimed_id - The identity URL for which authentication was
2205  * attempted.
2206  *
2207  * setup_url - A URL that can be used to send the user to the server
2208  * to set up for authentication. The user should be redirected in to
2209  * the setup_url, either in the current window or in a new browser
2210  * window.  Null in OpenID 2.
2211  *
2212  * status - Auth_OpenID_SETUP_NEEDED.
2213  *
2214  * @package OpenID
2215  */
2216 class Auth_OpenID_SetupNeededResponse extends Auth_OpenID_ConsumerResponse {
2217     var $status = Auth_OpenID_SETUP_NEEDED;
2218
2219     function Auth_OpenID_SetupNeededResponse($endpoint,
2220                                              $setup_url = null)
2221     {
2222         $this->setEndpoint($endpoint);
2223         $this->setup_url = $setup_url;
2224     }
2225 }
2226
2227 ?>