]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/CasAuthentication/extlib/CAS/client.php
Removed unused stub class
[quix0rs-gnu-social.git] / plugins / CasAuthentication / extlib / CAS / client.php
1 <?php
2
3 /**
4  * @file CAS/client.php
5  * Main class of the phpCAS library
6  */
7
8 // include internationalization stuff
9 include_once(dirname(__FILE__).'/languages/languages.php');
10
11 // include PGT storage classes
12 include_once(dirname(__FILE__).'/PGTStorage/pgt-main.php');
13
14 /**
15  * @class CASClient
16  * The CASClient class is a client interface that provides CAS authentication
17  * to PHP applications.
18  *
19  * @author Pascal Aubry <pascal.aubry at univ-rennes1.fr>
20  */
21
22 class CASClient
23 {
24         
25         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
26         // XX                                                                    XX
27         // XX                          CONFIGURATION                             XX
28         // XX                                                                    XX
29         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
30         
31         // ########################################################################
32         //  HTML OUTPUT
33         // ########################################################################
34         /**
35          * @addtogroup internalOutput
36          * @{
37          */  
38         
39         /**
40          * This method filters a string by replacing special tokens by appropriate values
41          * and prints it. The corresponding tokens are taken into account:
42          * - __CAS_VERSION__
43          * - __PHPCAS_VERSION__
44          * - __SERVER_BASE_URL__
45          *
46          * Used by CASClient::PrintHTMLHeader() and CASClient::printHTMLFooter().
47          *
48          * @param $str the string to filter and output
49          *
50          * @private
51          */
52         function HTMLFilterOutput($str)
53                 {
54                 $str = str_replace('__CAS_VERSION__',$this->getServerVersion(),$str);
55                 $str = str_replace('__PHPCAS_VERSION__',phpCAS::getVersion(),$str);
56                 $str = str_replace('__SERVER_BASE_URL__',$this->getServerBaseURL(),$str);
57                 echo $str;
58                 }
59         
60         /**
61          * A string used to print the header of HTML pages. Written by CASClient::setHTMLHeader(),
62          * read by CASClient::printHTMLHeader().
63          *
64          * @hideinitializer
65          * @private
66          * @see CASClient::setHTMLHeader, CASClient::printHTMLHeader()
67          */
68         var $_output_header = '';
69         
70         /**
71          * This method prints the header of the HTML output (after filtering). If
72          * CASClient::setHTMLHeader() was not used, a default header is output.
73          *
74          * @param $title the title of the page
75          *
76          * @see HTMLFilterOutput()
77          * @private
78          */
79         function printHTMLHeader($title)
80                 {
81                 $this->HTMLFilterOutput(str_replace('__TITLE__',
82                         $title,
83                         (empty($this->_output_header)
84                                         ? '<html><head><title>__TITLE__</title></head><body><h1>__TITLE__</h1>'
85                                                         : $this->_output_header)
86                 )
87                 );
88                 }
89         
90         /**
91          * A string used to print the footer of HTML pages. Written by CASClient::setHTMLFooter(),
92          * read by printHTMLFooter().
93          *
94          * @hideinitializer
95          * @private
96          * @see CASClient::setHTMLFooter, CASClient::printHTMLFooter()
97          */
98         var $_output_footer = '';
99         
100         /**
101          * This method prints the footer of the HTML output (after filtering). If
102          * CASClient::setHTMLFooter() was not used, a default footer is output.
103          *
104          * @see HTMLFilterOutput()
105          * @private
106          */
107         function printHTMLFooter()
108                 {
109                 $this->HTMLFilterOutput(empty($this->_output_footer)
110                         ?('<hr><address>phpCAS __PHPCAS_VERSION__ '.$this->getString(CAS_STR_USING_SERVER).' <a href="__SERVER_BASE_URL__">__SERVER_BASE_URL__</a> (CAS __CAS_VERSION__)</a></address></body></html>')
111                                         :$this->_output_footer);
112                 }
113         
114         /**
115          * This method set the HTML header used for all outputs.
116          *
117          * @param $header the HTML header.
118          *
119          * @public
120          */
121         function setHTMLHeader($header)
122                 {
123                 $this->_output_header = $header;
124                 }
125         
126         /**
127          * This method set the HTML footer used for all outputs.
128          *
129          * @param $footer the HTML footer.
130          *
131          * @public
132          */
133         function setHTMLFooter($footer)
134                 {
135                 $this->_output_footer = $footer;
136                 }
137         
138         /** @} */
139         // ########################################################################
140         //  INTERNATIONALIZATION
141         // ########################################################################
142         /**
143          * @addtogroup internalLang
144          * @{
145          */  
146         /**
147          * A string corresponding to the language used by phpCAS. Written by 
148          * CASClient::setLang(), read by CASClient::getLang().
149          
150          * @note debugging information is always in english (debug purposes only).
151          *
152          * @hideinitializer
153          * @private
154          * @sa CASClient::_strings, CASClient::getString()
155          */
156         var $_lang = '';
157         
158         /**
159          * This method returns the language used by phpCAS.
160          *
161          * @return a string representing the language
162          *
163          * @private
164          */
165         function getLang()
166                 {
167                 if ( empty($this->_lang) )
168                         $this->setLang(PHPCAS_LANG_DEFAULT);
169                 return $this->_lang;
170                 }
171         
172         /**
173          * array containing the strings used by phpCAS. Written by CASClient::setLang(), read by 
174          * CASClient::getString() and used by CASClient::setLang().
175          *
176          * @note This array is filled by instructions in CAS/languages/<$this->_lang>.php
177          *
178          * @private
179          * @see CASClient::_lang, CASClient::getString(), CASClient::setLang(), CASClient::getLang()
180          */
181         var $_strings;
182         
183         /**
184          * This method returns a string depending on the language.
185          *
186          * @param $str the index of the string in $_string.
187          *
188          * @return the string corresponding to $index in $string.
189          *
190          * @private
191          */
192         function getString($str)
193                 {
194                 // call CASclient::getLang() to be sure the language is initialized
195                 $this->getLang();
196                 
197                 if ( !isset($this->_strings[$str]) ) {
198                         trigger_error('string `'.$str.'\' not defined for language `'.$this->getLang().'\'',E_USER_ERROR);
199                 }
200                 return $this->_strings[$str];
201                 }
202         
203         /**
204          * This method is used to set the language used by phpCAS. 
205          * @note Can be called only once.
206          *
207          * @param $lang a string representing the language.
208          *
209          * @public
210          * @sa CAS_LANG_FRENCH, CAS_LANG_ENGLISH
211          */
212         function setLang($lang)
213                 {
214                 // include the corresponding language file
215                 include_once(dirname(__FILE__).'/languages/'.$lang.'.php');
216                 
217                 if ( !is_array($this->_strings) ) {
218                         trigger_error('language `'.$lang.'\' is not implemented',E_USER_ERROR);
219                 }
220                 $this->_lang = $lang;
221                 }
222         
223         /** @} */
224         // ########################################################################
225         //  CAS SERVER CONFIG
226         // ########################################################################
227         /**
228          * @addtogroup internalConfig
229          * @{
230          */  
231         
232         /**
233          * a record to store information about the CAS server.
234          * - $_server["version"]: the version of the CAS server
235          * - $_server["hostname"]: the hostname of the CAS server
236          * - $_server["port"]: the port the CAS server is running on
237          * - $_server["uri"]: the base URI the CAS server is responding on
238          * - $_server["base_url"]: the base URL of the CAS server
239          * - $_server["login_url"]: the login URL of the CAS server
240          * - $_server["service_validate_url"]: the service validating URL of the CAS server
241          * - $_server["proxy_url"]: the proxy URL of the CAS server
242          * - $_server["proxy_validate_url"]: the proxy validating URL of the CAS server
243          * - $_server["logout_url"]: the logout URL of the CAS server
244          *
245          * $_server["version"], $_server["hostname"], $_server["port"] and $_server["uri"]
246          * are written by CASClient::CASClient(), read by CASClient::getServerVersion(), 
247          * CASClient::getServerHostname(), CASClient::getServerPort() and CASClient::getServerURI().
248          *
249          * The other fields are written and read by CASClient::getServerBaseURL(), 
250          * CASClient::getServerLoginURL(), CASClient::getServerServiceValidateURL(), 
251          * CASClient::getServerProxyValidateURL() and CASClient::getServerLogoutURL().
252          *
253          * @hideinitializer
254          * @private
255          */
256         var $_server = array(
257                 'version' => -1,
258                 'hostname' => 'none',
259                 'port' => -1,
260                 'uri' => 'none'
261         );
262         
263         /**
264          * This method is used to retrieve the version of the CAS server.
265          * @return the version of the CAS server.
266          * @private
267          */
268         function getServerVersion()
269                 { 
270                 return $this->_server['version']; 
271                 }
272         
273         /**
274          * This method is used to retrieve the hostname of the CAS server.
275          * @return the hostname of the CAS server.
276          * @private
277          */
278         function getServerHostname()
279                 { return $this->_server['hostname']; }
280         
281         /**
282          * This method is used to retrieve the port of the CAS server.
283          * @return the port of the CAS server.
284          * @private
285          */
286         function getServerPort()
287                 { return $this->_server['port']; }
288         
289         /**
290          * This method is used to retrieve the URI of the CAS server.
291          * @return a URI.
292          * @private
293          */
294         function getServerURI()
295                 { return $this->_server['uri']; }
296         
297         /**
298          * This method is used to retrieve the base URL of the CAS server.
299          * @return a URL.
300          * @private
301          */
302         function getServerBaseURL()
303                 { 
304                 // the URL is build only when needed
305                 if ( empty($this->_server['base_url']) ) {
306                         $this->_server['base_url'] = 'https://'
307                                 .$this->getServerHostname()
308                                 .':'
309                                 .$this->getServerPort()
310                                 .$this->getServerURI();
311                 }
312                 return $this->_server['base_url']; 
313                 }
314         
315         /**
316          * This method is used to retrieve the login URL of the CAS server.
317          * @param $gateway true to check authentication, false to force it
318          * @param $renew true to force the authentication with the CAS server
319          * NOTE : It is recommended that CAS implementations ignore the
320          "gateway" parameter if "renew" is set
321          * @return a URL.
322          * @private
323          */
324         function getServerLoginURL($gateway=false,$renew=false) {
325                 phpCAS::traceBegin();
326                 // the URL is build only when needed
327                 if ( empty($this->_server['login_url']) ) {
328                         $this->_server['login_url'] = $this->getServerBaseURL();
329                         $this->_server['login_url'] .= 'login?service=';
330                         // $this->_server['login_url'] .= preg_replace('/&/','%26',$this->getURL());
331                         $this->_server['login_url'] .= urlencode($this->getURL());
332                         if($renew) {
333                                 // It is recommended that when the "renew" parameter is set, its value be "true"
334                                 $this->_server['login_url'] .= '&renew=true';
335                         } elseif ($gateway) {
336                                 // It is recommended that when the "gateway" parameter is set, its value be "true"
337                                 $this->_server['login_url'] .= '&gateway=true';
338                         }
339                 }
340                 phpCAS::traceEnd($this->_server['login_url']);
341                 return $this->_server['login_url'];
342         } 
343         
344         /**
345          * This method sets the login URL of the CAS server.
346          * @param $url the login URL
347          * @private
348          * @since 0.4.21 by Wyman Chan
349          */
350         function setServerLoginURL($url)
351                 {
352                 return $this->_server['login_url'] = $url;
353                 }
354         
355         /**
356          * This method is used to retrieve the service validating URL of the CAS server.
357          * @return a URL.
358          * @private
359          */
360         function getServerServiceValidateURL()
361                 { 
362                 // the URL is build only when needed
363                 if ( empty($this->_server['service_validate_url']) ) {
364                         switch ($this->getServerVersion()) {
365                                 case CAS_VERSION_1_0:
366                                         $this->_server['service_validate_url'] = $this->getServerBaseURL().'validate';
367                                         break;
368                                 case CAS_VERSION_2_0:
369                                         $this->_server['service_validate_url'] = $this->getServerBaseURL().'serviceValidate';
370                                         break;
371                         }
372                 }
373                 //      return $this->_server['service_validate_url'].'?service='.preg_replace('/&/','%26',$this->getURL()); 
374                 return $this->_server['service_validate_url'].'?service='.urlencode($this->getURL()); 
375                 }
376         
377         /**
378          * This method is used to retrieve the proxy validating URL of the CAS server.
379          * @return a URL.
380          * @private
381          */
382         function getServerProxyValidateURL()
383                 { 
384                 // the URL is build only when needed
385                 if ( empty($this->_server['proxy_validate_url']) ) {
386                         switch ($this->getServerVersion()) {
387                                 case CAS_VERSION_1_0:
388                                         $this->_server['proxy_validate_url'] = '';
389                                         break;
390                                 case CAS_VERSION_2_0:
391                                         $this->_server['proxy_validate_url'] = $this->getServerBaseURL().'proxyValidate';
392                                         break;
393                         }
394                 }
395                 //      return $this->_server['proxy_validate_url'].'?service='.preg_replace('/&/','%26',$this->getURL()); 
396                 return $this->_server['proxy_validate_url'].'?service='.urlencode($this->getURL()); 
397                 }
398         
399         /**
400          * This method is used to retrieve the proxy URL of the CAS server.
401          * @return a URL.
402          * @private
403          */
404         function getServerProxyURL()
405                 { 
406                 // the URL is build only when needed
407                 if ( empty($this->_server['proxy_url']) ) {
408                         switch ($this->getServerVersion()) {
409                                 case CAS_VERSION_1_0:
410                                         $this->_server['proxy_url'] = '';
411                                         break;
412                                 case CAS_VERSION_2_0:
413                                         $this->_server['proxy_url'] = $this->getServerBaseURL().'proxy';
414                                         break;
415                         }
416                 }
417                 return $this->_server['proxy_url']; 
418                 }
419         
420         /**
421          * This method is used to retrieve the logout URL of the CAS server.
422          * @return a URL.
423          * @private
424          */
425         function getServerLogoutURL()
426                 { 
427                 // the URL is build only when needed
428                 if ( empty($this->_server['logout_url']) ) {
429                         $this->_server['logout_url'] = $this->getServerBaseURL().'logout';
430                 }
431                 return $this->_server['logout_url']; 
432                 }
433         
434         /**
435          * This method sets the logout URL of the CAS server.
436          * @param $url the logout URL
437          * @private
438          * @since 0.4.21 by Wyman Chan
439          */
440         function setServerLogoutURL($url)
441                 {
442                 return $this->_server['logout_url'] = $url;
443                 }
444
445         /**
446          * An array to store extra curl options.
447          */     
448         var $_curl_options = array();
449
450         /**
451          * This method is used to set additional user curl options.
452          */
453         function setExtraCurlOption($key, $value)
454         {
455                 $this->_curl_options[$key] = $value;
456         }
457  
458         /**
459          * This method checks to see if the request is secured via HTTPS
460          * @return true if https, false otherwise
461          * @private
462          */
463         function isHttps() {
464                 //if ( isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ) {
465                 //0.4.24 by Hinnack
466                 if ( isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
467                         return true;
468                 } else {
469                         return false;
470                 }
471         }
472         
473         // ########################################################################
474         //  CONSTRUCTOR
475         // ########################################################################
476         /**
477          * CASClient constructor.
478          *
479          * @param $server_version the version of the CAS server
480          * @param $proxy TRUE if the CAS client is a CAS proxy, FALSE otherwise
481          * @param $server_hostname the hostname of the CAS server
482          * @param $server_port the port the CAS server is running on
483          * @param $server_uri the URI the CAS server is responding on
484          * @param $start_session Have phpCAS start PHP sessions (default true)
485          *
486          * @return a newly created CASClient object
487          *
488          * @public
489          */
490         function CASClient(
491                                            $server_version,
492                                            $proxy,
493                                            $server_hostname,
494                                            $server_port,
495                                            $server_uri,
496                                            $start_session = true) {
497                 
498                 phpCAS::traceBegin();
499                 
500                 if (!$this->isLogoutRequest() && !empty($_GET['ticket']) && $start_session) {
501             // copy old session vars and destroy the current session
502             if (!isset($_SESSION)) {
503                 session_start();
504             }
505             $old_session = $_SESSION;
506             session_destroy();
507             // set up a new session, of name based on the ticket
508                         $session_id = preg_replace('/[^\w]/','',$_GET['ticket']);
509                         phpCAS::LOG("Session ID: " . $session_id);
510                         session_id($session_id);
511             if (!isset($_SESSION)) {
512                 session_start();
513             }
514             // restore old session vars
515             $_SESSION = $old_session;
516             // Redirect to location without ticket.
517             header('Location: '.$this->getURL());
518                 }
519                 
520                 //activate session mechanism if desired
521                 if (!$this->isLogoutRequest() && $start_session) {
522                         session_start();
523                 }
524                 
525                 $this->_proxy = $proxy;
526                 
527                 //check version
528                 switch ($server_version) {
529                         case CAS_VERSION_1_0:
530                                 if ( $this->isProxy() )
531                                         phpCAS::error('CAS proxies are not supported in CAS '
532                                                 .$server_version);
533                                 break;
534                         case CAS_VERSION_2_0:
535                                 break;
536                         default:
537                                 phpCAS::error('this version of CAS (`'
538                                         .$server_version
539                                         .'\') is not supported by phpCAS '
540                                         .phpCAS::getVersion());
541                 }
542                 $this->_server['version'] = $server_version;
543                 
544                 //check hostname
545                 if ( empty($server_hostname) 
546                                 || !preg_match('/[\.\d\-abcdefghijklmnopqrstuvwxyz]*/',$server_hostname) ) {
547                         phpCAS::error('bad CAS server hostname (`'.$server_hostname.'\')');
548                 }
549                 $this->_server['hostname'] = $server_hostname;
550                 
551                 //check port
552                 if ( $server_port == 0 
553                         || !is_int($server_port) ) {
554                         phpCAS::error('bad CAS server port (`'.$server_hostname.'\')');
555                 }
556                 $this->_server['port'] = $server_port;
557                 
558                 //check URI
559                 if ( !preg_match('/[\.\d\-_abcdefghijklmnopqrstuvwxyz\/]*/',$server_uri) ) {
560                         phpCAS::error('bad CAS server URI (`'.$server_uri.'\')');
561                 }
562                 //add leading and trailing `/' and remove doubles      
563                 $server_uri = preg_replace('/\/\//','/','/'.$server_uri.'/');
564                 $this->_server['uri'] = $server_uri;
565                 
566                 //set to callback mode if PgtIou and PgtId CGI GET parameters are provided 
567                 if ( $this->isProxy() ) {
568                         $this->setCallbackMode(!empty($_GET['pgtIou'])&&!empty($_GET['pgtId']));
569                 }
570                 
571                 if ( $this->isCallbackMode() ) {
572                         //callback mode: check that phpCAS is secured
573                         if ( !$this->isHttps() ) {
574                                 phpCAS::error('CAS proxies must be secured to use phpCAS; PGT\'s will not be received from the CAS server');
575                         }
576                 } else {
577                         //normal mode: get ticket and remove it from CGI parameters for developpers
578                         $ticket = (isset($_GET['ticket']) ? $_GET['ticket'] : null);
579                         switch ($this->getServerVersion()) {
580                                 case CAS_VERSION_1_0: // check for a Service Ticket
581                                         if( preg_match('/^ST-/',$ticket) ) {
582                                                 phpCAS::trace('ST \''.$ticket.'\' found');
583                                                 //ST present
584                                                 $this->setST($ticket);
585                                                 //ticket has been taken into account, unset it to hide it to applications
586                                                 unset($_GET['ticket']);
587                                         } else if ( !empty($ticket) ) {
588                                                 //ill-formed ticket, halt
589                                                 phpCAS::error('ill-formed ticket found in the URL (ticket=`'.htmlentities($ticket).'\')');
590                                         }
591                                         break;
592                                 case CAS_VERSION_2_0: // check for a Service or Proxy Ticket
593                                         if( preg_match('/^[SP]T-/',$ticket) ) {
594                                                 phpCAS::trace('ST or PT \''.$ticket.'\' found');
595                                                 $this->setPT($ticket);
596                                                 unset($_GET['ticket']);
597                                         } else if ( !empty($ticket) ) {
598                                                 //ill-formed ticket, halt
599                                                 phpCAS::error('ill-formed ticket found in the URL (ticket=`'.htmlentities($ticket).'\')');
600                                         } 
601                                         break;
602                         }
603                 }
604                 phpCAS::traceEnd();
605         }
606         
607         /** @} */
608         
609         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
610         // XX                                                                    XX
611         // XX                           AUTHENTICATION                           XX
612         // XX                                                                    XX
613         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
614         
615         /**
616          * @addtogroup internalAuthentication
617          * @{
618          */  
619         
620         /**
621          * The Authenticated user. Written by CASClient::setUser(), read by CASClient::getUser().
622          * @attention client applications should use phpCAS::getUser().
623          *
624          * @hideinitializer
625          * @private
626          */
627         var $_user = '';
628         
629         /**
630          * This method sets the CAS user's login name.
631          *
632          * @param $user the login name of the authenticated user.
633          *
634          * @private
635          */
636         function setUser($user)
637                 {
638                 $this->_user = $user;
639                 }
640         
641         /**
642          * This method returns the CAS user's login name.
643          * @warning should be called only after CASClient::forceAuthentication() or 
644          * CASClient::isAuthenticated(), otherwise halt with an error.
645          *
646          * @return the login name of the authenticated user
647          */
648         function getUser()
649                 {
650                 if ( empty($this->_user) ) {
651                         phpCAS::error('this method should be used only after '.__CLASS__.'::forceAuthentication() or '.__CLASS__.'::isAuthenticated()');
652                 }
653                 return $this->_user;
654                 }
655         
656         /**
657          * This method is called to renew the authentication of the user
658          * If the user is authenticated, renew the connection
659          * If not, redirect to CAS
660          * @public
661          */
662         function renewAuthentication(){
663                 phpCAS::traceBegin();
664                 // Either way, the user is authenticated by CAS
665                 if( isset( $_SESSION['phpCAS']['auth_checked'] ) )
666                         unset($_SESSION['phpCAS']['auth_checked']);
667                 if ( $this->isAuthenticated() ) {
668                         phpCAS::trace('user already authenticated; renew');
669                         $this->redirectToCas(false,true);
670                 } else {
671                         $this->redirectToCas();
672                 }
673                 phpCAS::traceEnd();
674         }
675
676         /**
677          * This method is called to be sure that the user is authenticated. When not 
678          * authenticated, halt by redirecting to the CAS server; otherwise return TRUE.
679          * @return TRUE when the user is authenticated; otherwise halt.
680          * @public
681          */
682         function forceAuthentication()
683                 {
684                 phpCAS::traceBegin();
685                 
686                 if ( $this->isAuthenticated() ) {
687                         // the user is authenticated, nothing to be done.
688                         phpCAS::trace('no need to authenticate');
689                         $res = TRUE;
690                 } else {
691                         // the user is not authenticated, redirect to the CAS server
692                         if (isset($_SESSION['phpCAS']['auth_checked'])) {
693                                 unset($_SESSION['phpCAS']['auth_checked']);
694                         }
695                         $this->redirectToCas(FALSE/* no gateway */);    
696                         // never reached
697                         $res = FALSE;
698                 }
699                 phpCAS::traceEnd($res);
700                 return $res;
701                 }
702         
703         /**
704          * An integer that gives the number of times authentication will be cached before rechecked.
705          *
706          * @hideinitializer
707          * @private
708          */
709         var $_cache_times_for_auth_recheck = 0;
710         
711         /**
712          * Set the number of times authentication will be cached before rechecked.
713          *
714          * @param $n an integer.
715          *
716          * @public
717          */
718         function setCacheTimesForAuthRecheck($n)
719                 {
720                 $this->_cache_times_for_auth_recheck = $n;
721                 }
722         
723         /**
724          * This method is called to check whether the user is authenticated or not.
725          * @return TRUE when the user is authenticated, FALSE otherwise.
726          * @public
727          */
728         function checkAuthentication()
729                 {
730                 phpCAS::traceBegin();
731                 
732                 if ( $this->isAuthenticated() ) {
733                         phpCAS::trace('user is authenticated');
734                         $res = TRUE;
735                 } else if (isset($_SESSION['phpCAS']['auth_checked'])) {
736                         // the previous request has redirected the client to the CAS server with gateway=true
737                         unset($_SESSION['phpCAS']['auth_checked']);
738                         $res = FALSE;
739                 } else {
740                         //        $_SESSION['phpCAS']['auth_checked'] = true;
741                         //          $this->redirectToCas(TRUE/* gateway */);    
742                         //          // never reached
743                         //          $res = FALSE;
744                         // avoid a check against CAS on every request
745                         if (! isset($_SESSION['phpCAS']['unauth_count']) )
746                                 $_SESSION['phpCAS']['unauth_count'] = -2; // uninitialized
747                         
748                         if (($_SESSION['phpCAS']['unauth_count'] != -2 && $this->_cache_times_for_auth_recheck == -1) 
749                                         || ($_SESSION['phpCAS']['unauth_count'] >= 0 && $_SESSION['phpCAS']['unauth_count'] < $this->_cache_times_for_auth_recheck))
750                         {
751                                 $res = FALSE;
752                                 
753                                 if ($this->_cache_times_for_auth_recheck != -1)
754                                 {
755                                         $_SESSION['phpCAS']['unauth_count']++;
756                                         phpCAS::trace('user is not authenticated (cached for '.$_SESSION['phpCAS']['unauth_count'].' times of '.$this->_cache_times_for_auth_recheck.')');
757                                 }
758                                 else
759                                 {
760                                         phpCAS::trace('user is not authenticated (cached for until login pressed)');
761                                 }
762                         }
763                         else
764                         {
765                                 $_SESSION['phpCAS']['unauth_count'] = 0;
766                                 $_SESSION['phpCAS']['auth_checked'] = true;
767                                 phpCAS::trace('user is not authenticated (cache reset)');
768                                 $this->redirectToCas(TRUE/* gateway */);        
769                                 // never reached
770                                 $res = FALSE;
771                         }
772                 }
773                 phpCAS::traceEnd($res);
774                 return $res;
775                 }
776         
777         /**
778          * This method is called to check if the user is authenticated (previously or by
779          * tickets given in the URL).
780          *
781          * @return TRUE when the user is authenticated.
782          *
783          * @public
784          */
785         function isAuthenticated()
786                 {
787                 phpCAS::traceBegin();
788                 $res = FALSE;
789                 $validate_url = '';
790                 
791                 if ( $this->wasPreviouslyAuthenticated() ) {
792                         // the user has already (previously during the session) been 
793                         // authenticated, nothing to be done.
794                         phpCAS::trace('user was already authenticated, no need to look for tickets');
795                         $res = TRUE;
796                 } 
797                 elseif ( $this->hasST() ) {
798                         // if a Service Ticket was given, validate it
799                         phpCAS::trace('ST `'.$this->getST().'\' is present');
800                         $this->validateST($validate_url,$text_response,$tree_response); // if it fails, it halts
801                         phpCAS::trace('ST `'.$this->getST().'\' was validated');
802                         if ( $this->isProxy() ) {
803                                 $this->validatePGT($validate_url,$text_response,$tree_response); // idem
804                                 phpCAS::trace('PGT `'.$this->getPGT().'\' was validated');
805                                 $_SESSION['phpCAS']['pgt'] = $this->getPGT();
806                         }
807                         $_SESSION['phpCAS']['user'] = $this->getUser();
808                         $res = TRUE;
809                 }
810                 elseif ( $this->hasPT() ) {
811                         // if a Proxy Ticket was given, validate it
812                         phpCAS::trace('PT `'.$this->getPT().'\' is present');
813                         $this->validatePT($validate_url,$text_response,$tree_response); // note: if it fails, it halts
814                         phpCAS::trace('PT `'.$this->getPT().'\' was validated');
815                         if ( $this->isProxy() ) {
816                                 $this->validatePGT($validate_url,$text_response,$tree_response); // idem
817                                 phpCAS::trace('PGT `'.$this->getPGT().'\' was validated');
818                                 $_SESSION['phpCAS']['pgt'] = $this->getPGT();
819                         }
820                         $_SESSION['phpCAS']['user'] = $this->getUser();
821                         $res = TRUE;
822                 } 
823                 else {
824                         // no ticket given, not authenticated
825                         phpCAS::trace('no ticket found');
826                 }
827                 
828                 phpCAS::traceEnd($res);
829                 return $res;
830                 }
831         
832         /**
833          * This method tells if the current session is authenticated.
834          * @return true if authenticated based soley on $_SESSION variable
835          * @since 0.4.22 by Brendan Arnold
836          */
837         function isSessionAuthenticated ()
838                 {
839                 return !empty($_SESSION['phpCAS']['user']);
840                 }
841         
842         /**
843          * This method tells if the user has already been (previously) authenticated
844          * by looking into the session variables.
845          *
846          * @note This function switches to callback mode when needed.
847          *
848          * @return TRUE when the user has already been authenticated; FALSE otherwise.
849          *
850          * @private
851          */
852         function wasPreviouslyAuthenticated()
853                 {
854                 phpCAS::traceBegin();
855                 
856                 if ( $this->isCallbackMode() ) {
857                         $this->callback();
858                 }
859                 
860                 $auth = FALSE;
861                 
862                 if ( $this->isProxy() ) {
863                         // CAS proxy: username and PGT must be present
864                         if ( $this->isSessionAuthenticated() && !empty($_SESSION['phpCAS']['pgt']) ) {
865                                 // authentication already done
866                                 $this->setUser($_SESSION['phpCAS']['user']);
867                                 $this->setPGT($_SESSION['phpCAS']['pgt']);
868                                 phpCAS::trace('user = `'.$_SESSION['phpCAS']['user'].'\', PGT = `'.$_SESSION['phpCAS']['pgt'].'\''); 
869                                 $auth = TRUE;
870                         } elseif ( $this->isSessionAuthenticated() && empty($_SESSION['phpCAS']['pgt']) ) {
871                                 // these two variables should be empty or not empty at the same time
872                                 phpCAS::trace('username found (`'.$_SESSION['phpCAS']['user'].'\') but PGT is empty');
873                                 // unset all tickets to enforce authentication
874                                 unset($_SESSION['phpCAS']);
875                                 $this->setST('');
876                                 $this->setPT('');
877                         } elseif ( !$this->isSessionAuthenticated() && !empty($_SESSION['phpCAS']['pgt']) ) {
878                                 // these two variables should be empty or not empty at the same time
879                                 phpCAS::trace('PGT found (`'.$_SESSION['phpCAS']['pgt'].'\') but username is empty'); 
880                                 // unset all tickets to enforce authentication
881                                 unset($_SESSION['phpCAS']);
882                                 $this->setST('');
883                                 $this->setPT('');
884                         } else {
885                                 phpCAS::trace('neither user not PGT found'); 
886                         }
887                 } else {
888                         // `simple' CAS client (not a proxy): username must be present
889                         if ( $this->isSessionAuthenticated() ) {
890                                 // authentication already done
891                                 $this->setUser($_SESSION['phpCAS']['user']);
892                                 phpCAS::trace('user = `'.$_SESSION['phpCAS']['user'].'\''); 
893                                 $auth = TRUE;
894                         } else {
895                                 phpCAS::trace('no user found');
896                         }
897                 }
898                 
899                 phpCAS::traceEnd($auth);
900                 return $auth;
901                 }
902         
903         /**
904          * This method is used to redirect the client to the CAS server.
905          * It is used by CASClient::forceAuthentication() and CASClient::checkAuthentication().
906          * @param $gateway true to check authentication, false to force it
907          * @param $renew true to force the authentication with the CAS server
908          * @public
909          */
910         function redirectToCas($gateway=false,$renew=false){
911                 phpCAS::traceBegin();
912                 $cas_url = $this->getServerLoginURL($gateway,$renew);
913                 header('Location: '.$cas_url);
914                 phpCAS::log( "Redirect to : ".$cas_url );
915                 
916                 $this->printHTMLHeader($this->getString(CAS_STR_AUTHENTICATION_WANTED));
917                 
918                 printf('<p>'.$this->getString(CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED).'</p>',$cas_url);
919                 $this->printHTMLFooter();
920                 phpCAS::traceExit();
921                 exit();
922         }
923
924 //      /**
925 //       * This method is used to logout from CAS.
926 //       * @param $url a URL that will be transmitted to the CAS server (to come back to when logged out)
927 //       * @public
928 //       */
929 //      function logout($url = "") {
930 //              phpCAS::traceBegin();
931 //              $cas_url = $this->getServerLogoutURL();
932 //              // v0.4.14 sebastien.gougeon at univ-rennes1.fr
933 //              // header('Location: '.$cas_url);
934 //              if ( $url != "" ) {
935 //                      // Adam Moore 1.0.0RC2
936 //                      $url = '?service=' . $url . '&url=' . $url;
937 //              }
938 //              header('Location: '.$cas_url . $url);
939 //              session_unset();
940 //              session_destroy();
941 //              $this->printHTMLHeader($this->getString(CAS_STR_LOGOUT));
942 //              printf('<p>'.$this->getString(CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED).'</p>',$cas_url);
943 //              $this->printHTMLFooter();
944 //              phpCAS::traceExit();
945 //              exit();
946 //      }
947         
948         /**
949          * This method is used to logout from CAS.
950          * @params $params an array that contains the optional url and service parameters that will be passed to the CAS server
951          * @public
952          */
953         function logout($params) {
954                 phpCAS::traceBegin();
955                 $cas_url = $this->getServerLogoutURL();
956                 $paramSeparator = '?';
957                 if (isset($params['url'])) {
958                         $cas_url = $cas_url . $paramSeparator . "url=" . urlencode($params['url']); 
959                         $paramSeparator = '&';
960                 }
961                 if (isset($params['service'])) {
962                         $cas_url = $cas_url . $paramSeparator . "service=" . urlencode($params['service']); 
963                 }
964                 header('Location: '.$cas_url);
965                 session_unset();
966                 session_destroy();
967                 $this->printHTMLHeader($this->getString(CAS_STR_LOGOUT));
968                 printf('<p>'.$this->getString(CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED).'</p>',$cas_url);
969                 $this->printHTMLFooter();
970                 phpCAS::traceExit();
971                 exit();
972         }
973         
974         /**
975          * @return true if the current request is a logout request.
976          * @private
977          */
978         function isLogoutRequest() {
979                 return !empty($_POST['logoutRequest']);
980         }
981         
982         /**
983          * @return true if a logout request is allowed.
984          * @private
985          */
986         function isLogoutRequestAllowed() {
987         }
988         
989         /**
990          * This method handles logout requests.
991          * @param $check_client true to check the client bofore handling the request, 
992          * false not to perform any access control. True by default.
993          * @param $allowed_clients an array of host names allowed to send logout requests. 
994          * By default, only the CAs server (declared in the constructor) will be allowed.
995          * @public
996          */
997         function handleLogoutRequests($check_client=true, $allowed_clients=false) {
998                 phpCAS::traceBegin();
999                 if (!$this->isLogoutRequest()) {
1000                         phpCAS::log("Not a logout request");
1001                         phpCAS::traceEnd();
1002                         return;
1003                 }
1004                 phpCAS::log("Logout requested");
1005                 phpCAS::log("SAML REQUEST: ".$_POST['logoutRequest']);
1006                 if ($check_client) {
1007                         if (!$allowed_clients) {
1008                                 $allowed_clients = array( $this->getServerHostname() ); 
1009                         }
1010                         $client_ip = $_SERVER['REMOTE_ADDR'];
1011                         $client = gethostbyaddr($client_ip);
1012                         phpCAS::log("Client: ".$client);
1013                         $allowed = false;
1014                         foreach ($allowed_clients as $allowed_client) {
1015                                 if ($client == $allowed_client) {
1016                                         phpCAS::log("Allowed client '".$allowed_client."' matches, logout request is allowed");
1017                                         $allowed = true;
1018                                         break;
1019                                 } else {
1020                                         phpCAS::log("Allowed client '".$allowed_client."' does not match");
1021                                 }
1022                         }
1023                         if (!$allowed) {
1024                                 phpCAS::error("Unauthorized logout request from client '".$client."'");
1025                             printf("Unauthorized!");
1026                                 phpCAS::traceExit();
1027                                 exit();
1028                         }
1029                 } else {
1030                         phpCAS::log("No access control set");
1031                 }
1032                 // Extract the ticket from the SAML Request
1033                 preg_match("|<samlp:SessionIndex>(.*)</samlp:SessionIndex>|", $_POST['logoutRequest'], $tick, PREG_OFFSET_CAPTURE, 3);
1034                 $wrappedSamlSessionIndex = preg_replace('|<samlp:SessionIndex>|','',$tick[0][0]);
1035                 $ticket2logout = preg_replace('|</samlp:SessionIndex>|','',$wrappedSamlSessionIndex);
1036                 phpCAS::log("Ticket to logout: ".$ticket2logout);
1037                 $session_id = preg_replace('/[^\w]/','',$ticket2logout);
1038                 phpCAS::log("Session id: ".$session_id);
1039
1040                 // fix New session ID
1041                 session_id($session_id);
1042                 $_COOKIE[session_name()]=$session_id;
1043                 $_GET[session_name()]=$session_id;
1044                 
1045                 // Overwrite session
1046                 session_start();        
1047                 session_unset();
1048             session_destroy();
1049             printf("Disconnected!");
1050                 phpCAS::traceExit();
1051                 exit();
1052         }
1053         
1054         /** @} */
1055         
1056         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1057         // XX                                                                    XX
1058         // XX                  BASIC CLIENT FEATURES (CAS 1.0)                   XX
1059         // XX                                                                    XX
1060         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1061         
1062         // ########################################################################
1063         //  ST
1064         // ########################################################################
1065         /**
1066          * @addtogroup internalBasic
1067          * @{
1068          */  
1069         
1070         /**
1071          * the Service Ticket provided in the URL of the request if present
1072          * (empty otherwise). Written by CASClient::CASClient(), read by 
1073          * CASClient::getST() and CASClient::hasPGT().
1074          *
1075          * @hideinitializer
1076          * @private
1077          */
1078         var $_st = '';
1079         
1080         /**
1081          * This method returns the Service Ticket provided in the URL of the request.
1082          * @return The service ticket.
1083          * @private
1084          */
1085         function getST()
1086                 { return $this->_st; }
1087         
1088         /**
1089          * This method stores the Service Ticket.
1090          * @param $st The Service Ticket.
1091          * @private
1092          */
1093         function setST($st)
1094                 { $this->_st = $st; }
1095         
1096         /**
1097          * This method tells if a Service Ticket was stored.
1098          * @return TRUE if a Service Ticket has been stored.
1099          * @private
1100          */
1101         function hasST()
1102                 { return !empty($this->_st); }
1103         
1104         /** @} */
1105         
1106         // ########################################################################
1107         //  ST VALIDATION
1108         // ########################################################################
1109         /**
1110          * @addtogroup internalBasic
1111          * @{
1112          */  
1113         
1114         /**
1115          * the certificate of the CAS server.
1116          *
1117          * @hideinitializer
1118          * @private
1119          */
1120         var $_cas_server_cert = '';
1121         
1122         /**
1123          * the certificate of the CAS server CA.
1124          *
1125          * @hideinitializer
1126          * @private
1127          */
1128         var $_cas_server_ca_cert = '';
1129         
1130         /**
1131          * Set to true not to validate the CAS server.
1132          *
1133          * @hideinitializer
1134          * @private
1135          */
1136         var $_no_cas_server_validation = false;
1137         
1138         /**
1139          * Set the certificate of the CAS server.
1140          *
1141          * @param $cert the PEM certificate
1142          */
1143         function setCasServerCert($cert)
1144                 {
1145                 $this->_cas_server_cert = $cert;
1146                 }
1147         
1148         /**
1149          * Set the CA certificate of the CAS server.
1150          *
1151          * @param $cert the PEM certificate of the CA that emited the cert of the server
1152          */
1153         function setCasServerCACert($cert)
1154                 {
1155                 $this->_cas_server_ca_cert = $cert;
1156                 }
1157         
1158         /**
1159          * Set no SSL validation for the CAS server.
1160          */
1161         function setNoCasServerValidation()
1162                 {
1163                 $this->_no_cas_server_validation = true;
1164                 }
1165         
1166         /**
1167          * This method is used to validate a ST; halt on failure, and sets $validate_url,
1168          * $text_reponse and $tree_response on success. These parameters are used later
1169          * by CASClient::validatePGT() for CAS proxies.
1170          * 
1171          * @param $validate_url the URL of the request to the CAS server.
1172          * @param $text_response the response of the CAS server, as is (XML text).
1173          * @param $tree_response the response of the CAS server, as a DOM XML tree.
1174          *
1175          * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError().
1176          *
1177          * @private
1178          */
1179         function validateST($validate_url,&$text_response,&$tree_response)
1180                 {
1181                 phpCAS::traceBegin();
1182                 // build the URL to validate the ticket
1183                 $validate_url = $this->getServerServiceValidateURL().'&ticket='.$this->getST();
1184                 if ( $this->isProxy() ) {
1185                         // pass the callback url for CAS proxies
1186                         $validate_url .= '&pgtUrl='.$this->getCallbackURL();
1187                 }
1188                 
1189                 // open and read the URL
1190                 if ( !$this->readURL($validate_url,''/*cookies*/,$headers,$text_response,$err_msg) ) {
1191                         phpCAS::trace('could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')');
1192                         $this->authError('ST not validated',
1193                                 $validate_url,
1194                                 TRUE/*$no_response*/);
1195                 }
1196                 
1197                 // analyze the result depending on the version
1198                 switch ($this->getServerVersion()) {
1199                         case CAS_VERSION_1_0:
1200                                 if (preg_match('/^no\n/',$text_response)) {
1201                                         phpCAS::trace('ST has not been validated');
1202                                         $this->authError('ST not validated',
1203                                                 $validate_url,
1204                                                 FALSE/*$no_response*/,
1205                                                 FALSE/*$bad_response*/,
1206                                                 $text_response);
1207                                 }
1208                                 if (!preg_match('/^yes\n/',$text_response)) {
1209                                         phpCAS::trace('ill-formed response');
1210                                         $this->authError('ST not validated',
1211                                                 $validate_url,
1212                                                 FALSE/*$no_response*/,
1213                                                 TRUE/*$bad_response*/,
1214                                                 $text_response);
1215                                 }
1216                                 // ST has been validated, extract the user name
1217                                 $arr = preg_split('/\n/',$text_response);
1218                                 $this->setUser(trim($arr[1]));
1219                                 break;
1220                         case CAS_VERSION_2_0:
1221                                 // read the response of the CAS server into a DOM object
1222                                 if ( !($dom = domxml_open_mem($text_response))) {
1223                                         phpCAS::trace('domxml_open_mem() failed');
1224                                         $this->authError('ST not validated',
1225                                                 $validate_url,
1226                                                 FALSE/*$no_response*/,
1227                                                 TRUE/*$bad_response*/,
1228                                                 $text_response);
1229                                 }
1230                                 // read the root node of the XML tree
1231                                 if ( !($tree_response = $dom->document_element()) ) {
1232                                         phpCAS::trace('document_element() failed');
1233                                         $this->authError('ST not validated',
1234                                                 $validate_url,
1235                                                 FALSE/*$no_response*/,
1236                                                 TRUE/*$bad_response*/,
1237                                                 $text_response);
1238                                 }
1239                                 // insure that tag name is 'serviceResponse'
1240                                 if ( $tree_response->node_name() != 'serviceResponse' ) {
1241                                         phpCAS::trace('bad XML root node (should be `serviceResponse\' instead of `'.$tree_response->node_name().'\'');
1242                                         $this->authError('ST not validated',
1243                                                 $validate_url,
1244                                                 FALSE/*$no_response*/,
1245                                                 TRUE/*$bad_response*/,
1246                                                 $text_response);
1247                                 }
1248                                 if ( sizeof($success_elements = $tree_response->get_elements_by_tagname("authenticationSuccess")) != 0) {
1249                                         // authentication succeded, extract the user name
1250                                         if ( sizeof($user_elements = $success_elements[0]->get_elements_by_tagname("user")) == 0) {
1251                                                 phpCAS::trace('<authenticationSuccess> found, but no <user>');
1252                                                 $this->authError('ST not validated',
1253                                                         $validate_url,
1254                                                         FALSE/*$no_response*/,
1255                                                         TRUE/*$bad_response*/,
1256                                                         $text_response);
1257                                         }
1258                                         $user = trim($user_elements[0]->get_content());
1259                                         phpCAS::trace('user = `'.$user);
1260                                         $this->setUser($user);
1261                                         
1262                                 } else if ( sizeof($failure_elements = $tree_response->get_elements_by_tagname("authenticationFailure")) != 0) {
1263                                         phpCAS::trace('<authenticationFailure> found');
1264                                         // authentication failed, extract the error code and message
1265                                         $this->authError('ST not validated',
1266                                                 $validate_url,
1267                                                 FALSE/*$no_response*/,
1268                                                 FALSE/*$bad_response*/,
1269                                                 $text_response,
1270                                                 $failure_elements[0]->get_attribute('code')/*$err_code*/,
1271                                                 trim($failure_elements[0]->get_content())/*$err_msg*/);
1272                                 } else {
1273                                         phpCAS::trace('neither <authenticationSuccess> nor <authenticationFailure> found');
1274                                         $this->authError('ST not validated',
1275                                                 $validate_url,
1276                                                 FALSE/*$no_response*/,
1277                                                 TRUE/*$bad_response*/,
1278                                                 $text_response);
1279                                 }
1280                                 break;
1281                 }
1282                 
1283                 // at this step, ST has been validated and $this->_user has been set,
1284                 phpCAS::traceEnd(TRUE);
1285                 return TRUE;
1286                 }
1287         
1288         /** @} */
1289         
1290         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1291         // XX                                                                    XX
1292         // XX                     PROXY FEATURES (CAS 2.0)                       XX
1293         // XX                                                                    XX
1294         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1295         
1296         // ########################################################################
1297         //  PROXYING
1298         // ########################################################################
1299         /**
1300          * @addtogroup internalProxy
1301          * @{
1302          */
1303         
1304         /**
1305          * A boolean telling if the client is a CAS proxy or not. Written by CASClient::CASClient(), 
1306          * read by CASClient::isProxy().
1307          *
1308          * @private
1309          */
1310         var $_proxy;
1311         
1312         /**
1313          * Tells if a CAS client is a CAS proxy or not
1314          *
1315          * @return TRUE when the CAS client is a CAs proxy, FALSE otherwise
1316          *
1317          * @private
1318          */
1319         function isProxy()
1320                 {
1321                 return $this->_proxy;
1322                 }
1323         
1324         /** @} */
1325         // ########################################################################
1326         //  PGT
1327         // ########################################################################
1328         /**
1329          * @addtogroup internalProxy
1330          * @{
1331          */  
1332         
1333         /**
1334          * the Proxy Grnting Ticket given by the CAS server (empty otherwise). 
1335          * Written by CASClient::setPGT(), read by CASClient::getPGT() and CASClient::hasPGT().
1336          *
1337          * @hideinitializer
1338          * @private
1339          */
1340         var $_pgt = '';
1341         
1342         /**
1343          * This method returns the Proxy Granting Ticket given by the CAS server.
1344          * @return The Proxy Granting Ticket.
1345          * @private
1346          */
1347         function getPGT()
1348                 { return $this->_pgt; }
1349         
1350         /**
1351          * This method stores the Proxy Granting Ticket.
1352          * @param $pgt The Proxy Granting Ticket.
1353          * @private
1354          */
1355         function setPGT($pgt)
1356                 { $this->_pgt = $pgt; }
1357         
1358         /**
1359          * This method tells if a Proxy Granting Ticket was stored.
1360          * @return TRUE if a Proxy Granting Ticket has been stored.
1361          * @private
1362          */
1363         function hasPGT()
1364                 { return !empty($this->_pgt); }
1365         
1366         /** @} */
1367         
1368         // ########################################################################
1369         //  CALLBACK MODE
1370         // ########################################################################
1371         /**
1372          * @addtogroup internalCallback
1373          * @{
1374          */  
1375         /**
1376          * each PHP script using phpCAS in proxy mode is its own callback to get the
1377          * PGT back from the CAS server. callback_mode is detected by the constructor
1378          * thanks to the GET parameters.
1379          */
1380         
1381         /**
1382          * a boolean to know if the CAS client is running in callback mode. Written by
1383          * CASClient::setCallBackMode(), read by CASClient::isCallbackMode().
1384          *
1385          * @hideinitializer
1386          * @private
1387          */
1388         var $_callback_mode = FALSE;
1389         
1390         /**
1391          * This method sets/unsets callback mode.
1392          *
1393          * @param $callback_mode TRUE to set callback mode, FALSE otherwise.
1394          *
1395          * @private
1396          */
1397         function setCallbackMode($callback_mode)
1398                 {
1399                 $this->_callback_mode = $callback_mode;
1400                 }
1401         
1402         /**
1403          * This method returns TRUE when the CAs client is running i callback mode, 
1404          * FALSE otherwise.
1405          *
1406          * @return A boolean.
1407          *
1408          * @private
1409          */
1410         function isCallbackMode()
1411                 {
1412                 return $this->_callback_mode;
1413                 }
1414         
1415         /**
1416          * the URL that should be used for the PGT callback (in fact the URL of the 
1417          * current request without any CGI parameter). Written and read by 
1418          * CASClient::getCallbackURL().
1419          *
1420          * @hideinitializer
1421          * @private
1422          */
1423         var $_callback_url = '';
1424         
1425         /**
1426          * This method returns the URL that should be used for the PGT callback (in
1427          * fact the URL of the current request without any CGI parameter, except if
1428          * phpCAS::setFixedCallbackURL() was used).
1429          *
1430          * @return The callback URL
1431          *
1432          * @private
1433          */
1434         function getCallbackURL()
1435                 {
1436                 // the URL is built when needed only
1437                 if ( empty($this->_callback_url) ) {
1438                         $final_uri = '';
1439                         // remove the ticket if present in the URL
1440                         $final_uri = 'https://';
1441                         /* replaced by Julien Marchal - v0.4.6
1442                          * $this->uri .= $_SERVER['SERVER_NAME'];
1443                          */
1444                         if(empty($_SERVER['HTTP_X_FORWARDED_SERVER'])){
1445                                 /* replaced by teedog - v0.4.12
1446                                  * $final_uri .= $_SERVER['SERVER_NAME'];
1447                                  */
1448                                 if (empty($_SERVER['SERVER_NAME'])) {
1449                                         $final_uri .= $_SERVER['HTTP_HOST'];
1450                                 } else {
1451                                         $final_uri .= $_SERVER['SERVER_NAME'];
1452                                 }
1453                         } else {
1454                                 $final_uri .= $_SERVER['HTTP_X_FORWARDED_SERVER'];
1455                         }
1456                         if ( ($this->isHttps() && $_SERVER['SERVER_PORT']!=443)
1457                                         || (!$this->isHttps() && $_SERVER['SERVER_PORT']!=80) ) {
1458                                 $final_uri .= ':';
1459                                 $final_uri .= $_SERVER['SERVER_PORT'];
1460                         }
1461                         $request_uri = $_SERVER['REQUEST_URI'];
1462                         $request_uri = preg_replace('/\?.*$/','',$request_uri);
1463                         $final_uri .= $request_uri;
1464                         $this->setCallbackURL($final_uri);
1465                 }
1466                 return $this->_callback_url;
1467                 }
1468         
1469         /**
1470          * This method sets the callback url.
1471          *
1472          * @param $callback_url url to set callback 
1473          *
1474          * @private
1475          */
1476         function setCallbackURL($url)
1477                 {
1478                 return $this->_callback_url = $url;
1479                 }
1480         
1481         /**
1482          * This method is called by CASClient::CASClient() when running in callback
1483          * mode. It stores the PGT and its PGT Iou, prints its output and halts.
1484          *
1485          * @private
1486          */
1487         function callback()
1488                 {
1489                 phpCAS::traceBegin();
1490                 $this->printHTMLHeader('phpCAS callback');
1491                 $pgt_iou = $_GET['pgtIou'];
1492                 $pgt = $_GET['pgtId'];
1493                 phpCAS::trace('Storing PGT `'.$pgt.'\' (id=`'.$pgt_iou.'\')');
1494                 echo '<p>Storing PGT `'.$pgt.'\' (id=`'.$pgt_iou.'\').</p>';
1495                 $this->storePGT($pgt,$pgt_iou);
1496                 $this->printHTMLFooter();
1497                 phpCAS::traceExit();
1498                 }
1499         
1500         /** @} */
1501         
1502         // ########################################################################
1503         //  PGT STORAGE
1504         // ########################################################################
1505         /**
1506          * @addtogroup internalPGTStorage
1507          * @{
1508          */  
1509         
1510         /**
1511          * an instance of a class inheriting of PGTStorage, used to deal with PGT
1512          * storage. Created by CASClient::setPGTStorageFile() or CASClient::setPGTStorageDB(), used 
1513          * by CASClient::setPGTStorageFile(), CASClient::setPGTStorageDB() and CASClient::initPGTStorage().
1514          *
1515          * @hideinitializer
1516          * @private
1517          */
1518         var $_pgt_storage = null;
1519         
1520         /**
1521          * This method is used to initialize the storage of PGT's.
1522          * Halts on error.
1523          *
1524          * @private
1525          */
1526         function initPGTStorage()
1527                 {
1528                 // if no SetPGTStorageXxx() has been used, default to file
1529                 if ( !is_object($this->_pgt_storage) ) {
1530                         $this->setPGTStorageFile();
1531                 }
1532                 
1533                 // initializes the storage
1534                 $this->_pgt_storage->init();
1535                 }
1536         
1537         /**
1538          * This method stores a PGT. Halts on error.
1539          *
1540          * @param $pgt the PGT to store
1541          * @param $pgt_iou its corresponding Iou
1542          *
1543          * @private
1544          */
1545         function storePGT($pgt,$pgt_iou)
1546                 {
1547                 // ensure that storage is initialized
1548                 $this->initPGTStorage();
1549                 // writes the PGT
1550                 $this->_pgt_storage->write($pgt,$pgt_iou);
1551                 }
1552         
1553         /**
1554          * This method reads a PGT from its Iou and deletes the corresponding storage entry.
1555          *
1556          * @param $pgt_iou the PGT Iou
1557          *
1558          * @return The PGT corresponding to the Iou, FALSE when not found.
1559          *
1560          * @private
1561          */
1562         function loadPGT($pgt_iou)
1563                 {
1564                 // ensure that storage is initialized
1565                 $this->initPGTStorage();
1566                 // read the PGT
1567                 return $this->_pgt_storage->read($pgt_iou);
1568                 }
1569         
1570         /**
1571          * This method is used to tell phpCAS to store the response of the
1572          * CAS server to PGT requests onto the filesystem. 
1573          *
1574          * @param $format the format used to store the PGT's (`plain' and `xml' allowed)
1575          * @param $path the path where the PGT's should be stored
1576          *
1577          * @public
1578          */
1579         function setPGTStorageFile($format='',
1580                 $path='')
1581                 {
1582                 // check that the storage has not already been set
1583                 if ( is_object($this->_pgt_storage) ) {
1584                         phpCAS::error('PGT storage already defined');
1585                 }
1586                 
1587                 // create the storage object
1588                 $this->_pgt_storage = &new PGTStorageFile($this,$format,$path);
1589                 }
1590         
1591         /**
1592          * This method is used to tell phpCAS to store the response of the
1593          * CAS server to PGT requests into a database. 
1594          * @note The connection to the database is done only when needed. 
1595          * As a consequence, bad parameters are detected only when 
1596          * initializing PGT storage.
1597          *
1598          * @param $user the user to access the data with
1599          * @param $password the user's password
1600          * @param $database_type the type of the database hosting the data
1601          * @param $hostname the server hosting the database
1602          * @param $port the port the server is listening on
1603          * @param $database the name of the database
1604          * @param $table the name of the table storing the data
1605          *
1606          * @public
1607          */
1608         function setPGTStorageDB($user,
1609                                                          $password,
1610                                                          $database_type,
1611                                                          $hostname,
1612                                                          $port,
1613                                                          $database,
1614                                                          $table)
1615                 {
1616                 // check that the storage has not already been set
1617                 if ( is_object($this->_pgt_storage) ) {
1618                         phpCAS::error('PGT storage already defined');
1619                 }
1620                 
1621                 // warn the user that he should use file storage...
1622                 trigger_error('PGT storage into database is an experimental feature, use at your own risk',E_USER_WARNING);
1623                 
1624                 // create the storage object
1625                 $this->_pgt_storage = & new PGTStorageDB($this,$user,$password,$database_type,$hostname,$port,$database,$table);
1626                 }
1627         
1628         // ########################################################################
1629         //  PGT VALIDATION
1630         // ########################################################################
1631         /**
1632          * This method is used to validate a PGT; halt on failure.
1633          * 
1634          * @param $validate_url the URL of the request to the CAS server.
1635          * @param $text_response the response of the CAS server, as is (XML text); result
1636          * of CASClient::validateST() or CASClient::validatePT().
1637          * @param $tree_response the response of the CAS server, as a DOM XML tree; result
1638          * of CASClient::validateST() or CASClient::validatePT().
1639          *
1640          * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError().
1641          *
1642          * @private
1643          */
1644         function validatePGT(&$validate_url,$text_response,$tree_response)
1645                 {
1646                 phpCAS::traceBegin();
1647                 if ( sizeof($arr = $tree_response->get_elements_by_tagname("proxyGrantingTicket")) == 0) {
1648                         phpCAS::trace('<proxyGrantingTicket> not found');
1649                         // authentication succeded, but no PGT Iou was transmitted
1650                         $this->authError('Ticket validated but no PGT Iou transmitted',
1651                                 $validate_url,
1652                                 FALSE/*$no_response*/,
1653                                 FALSE/*$bad_response*/,
1654                                 $text_response);
1655                 } else {
1656                         // PGT Iou transmitted, extract it
1657                         $pgt_iou = trim($arr[0]->get_content());
1658                         $pgt = $this->loadPGT($pgt_iou);
1659                         if ( $pgt == FALSE ) {
1660                                 phpCAS::trace('could not load PGT');
1661                                 $this->authError('PGT Iou was transmitted but PGT could not be retrieved',
1662                                         $validate_url,
1663                                         FALSE/*$no_response*/,
1664                                         FALSE/*$bad_response*/,
1665                                         $text_response);
1666                         }
1667                         $this->setPGT($pgt);
1668                 }
1669                 phpCAS::traceEnd(TRUE);
1670                 return TRUE;
1671                 }
1672         
1673         // ########################################################################
1674         //  PGT VALIDATION
1675         // ########################################################################
1676         
1677         /**
1678          * This method is used to retrieve PT's from the CAS server thanks to a PGT.
1679          * 
1680          * @param $target_service the service to ask for with the PT.
1681          * @param $err_code an error code (PHPCAS_SERVICE_OK on success).
1682          * @param $err_msg an error message (empty on success).
1683          *
1684          * @return a Proxy Ticket, or FALSE on error.
1685          *
1686          * @private
1687          */
1688         function retrievePT($target_service,&$err_code,&$err_msg)
1689                 {
1690                 phpCAS::traceBegin();
1691                 
1692                 // by default, $err_msg is set empty and $pt to TRUE. On error, $pt is
1693                 // set to false and $err_msg to an error message. At the end, if $pt is FALSE 
1694                 // and $error_msg is still empty, it is set to 'invalid response' (the most
1695                 // commonly encountered error).
1696                 $err_msg = '';
1697                 
1698                 // build the URL to retrieve the PT
1699                 //      $cas_url = $this->getServerProxyURL().'?targetService='.preg_replace('/&/','%26',$target_service).'&pgt='.$this->getPGT();
1700                 $cas_url = $this->getServerProxyURL().'?targetService='.urlencode($target_service).'&pgt='.$this->getPGT();
1701                 
1702                 // open and read the URL
1703                 if ( !$this->readURL($cas_url,''/*cookies*/,$headers,$cas_response,$err_msg) ) {
1704                         phpCAS::trace('could not open URL \''.$cas_url.'\' to validate ('.$err_msg.')');
1705                         $err_code = PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE;
1706                         $err_msg = 'could not retrieve PT (no response from the CAS server)';
1707                         phpCAS::traceEnd(FALSE);
1708                         return FALSE;
1709                 }
1710                 
1711                 $bad_response = FALSE;
1712                 
1713                 if ( !$bad_response ) {
1714                         // read the response of the CAS server into a DOM object
1715                         if ( !($dom = @domxml_open_mem($cas_response))) {
1716                                 phpCAS::trace('domxml_open_mem() failed');
1717                                 // read failed
1718                                 $bad_response = TRUE;
1719                         } 
1720                 }
1721                 
1722                 if ( !$bad_response ) {
1723                         // read the root node of the XML tree
1724                         if ( !($root = $dom->document_element()) ) {
1725                                 phpCAS::trace('document_element() failed');
1726                                 // read failed
1727                                 $bad_response = TRUE;
1728                         } 
1729                 }
1730                 
1731                 if ( !$bad_response ) {
1732                         // insure that tag name is 'serviceResponse'
1733                         if ( $root->node_name() != 'serviceResponse' ) {
1734                                 phpCAS::trace('node_name() failed');
1735                                 // bad root node
1736                                 $bad_response = TRUE;
1737                         } 
1738                 }
1739                 
1740                 if ( !$bad_response ) {
1741                         // look for a proxySuccess tag
1742                         if ( sizeof($arr = $root->get_elements_by_tagname("proxySuccess")) != 0) {
1743                                 // authentication succeded, look for a proxyTicket tag
1744                                 if ( sizeof($arr = $root->get_elements_by_tagname("proxyTicket")) != 0) {
1745                                         $err_code = PHPCAS_SERVICE_OK;
1746                                         $err_msg = '';
1747                                         phpCAS::trace('original PT: '.trim($arr[0]->get_content()));
1748                                         $pt = trim($arr[0]->get_content());
1749                                         phpCAS::traceEnd($pt);
1750                                         return $pt;
1751                                 } else {
1752                                         phpCAS::trace('<proxySuccess> was found, but not <proxyTicket>');
1753                                 }
1754                         } 
1755                         // look for a proxyFailure tag
1756                         else if ( sizeof($arr = $root->get_elements_by_tagname("proxyFailure")) != 0) {
1757                                 // authentication failed, extract the error
1758                                 $err_code = PHPCAS_SERVICE_PT_FAILURE;
1759                                 $err_msg = 'PT retrieving failed (code=`'
1760                                         .$arr[0]->get_attribute('code')
1761                                         .'\', message=`'
1762                                         .trim($arr[0]->get_content())
1763                                         .'\')';
1764                                 phpCAS::traceEnd(FALSE);
1765                                 return FALSE;
1766                         } else {
1767                                 phpCAS::trace('neither <proxySuccess> nor <proxyFailure> found');
1768                         }
1769                 }
1770                 
1771                 // at this step, we are sure that the response of the CAS server was ill-formed
1772                 $err_code = PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE;
1773                 $err_msg = 'Invalid response from the CAS server (response=`'.$cas_response.'\')';
1774                 
1775                 phpCAS::traceEnd(FALSE);
1776                 return FALSE;
1777                 }
1778         
1779         // ########################################################################
1780         // ACCESS TO EXTERNAL SERVICES
1781         // ########################################################################
1782         
1783         /**
1784          * This method is used to acces a remote URL.
1785          *
1786          * @param $url the URL to access.
1787          * @param $cookies an array containing cookies strings such as 'name=val'
1788          * @param $headers an array containing the HTTP header lines of the response
1789          * (an empty array on failure).
1790          * @param $body the body of the response, as a string (empty on failure).
1791          * @param $err_msg an error message, filled on failure.
1792          *
1793          * @return TRUE on success, FALSE otherwise (in this later case, $err_msg
1794          * contains an error message).
1795          *
1796          * @private
1797          */
1798         function readURL($url,$cookies,&$headers,&$body,&$err_msg)
1799                 {
1800                 phpCAS::traceBegin();
1801                 $headers = '';
1802                 $body = '';
1803                 $err_msg = '';
1804                 
1805                 $res = TRUE;
1806                 
1807                 // initialize the CURL session
1808                 $ch = curl_init($url);
1809                 
1810                 if (version_compare(PHP_VERSION,'5.1.3','>=')) {
1811                         //only avaible in php5
1812                         curl_setopt_array($ch, $this->_curl_options);
1813                 } else {
1814                         foreach ($this->_curl_options as $key => $value) {
1815                                 curl_setopt($ch, $key, $value);
1816                         }
1817                 }
1818
1819                 if ($this->_cas_server_cert == '' && $this->_cas_server_ca_cert == '' && !$this->_no_cas_server_validation) {
1820                         phpCAS::error('one of the methods phpCAS::setCasServerCert(), phpCAS::setCasServerCACert() or phpCAS::setNoCasServerValidation() must be called.');
1821                 }
1822                 if ($this->_cas_server_cert != '' ) {
1823                         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
1824                         curl_setopt($ch, CURLOPT_SSLCERT, $this->_cas_server_cert);
1825                 } else if ($this->_cas_server_ca_cert != '') {
1826                         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
1827                         curl_setopt($ch, CURLOPT_CAINFO, $this->_cas_server_ca_cert);
1828                 } else {
1829                         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
1830                         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
1831                 }
1832                 
1833                 // return the CURL output into a variable
1834                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1835                 // get the HTTP header with a callback
1836                 $this->_curl_headers = array(); // empty the headers array
1837                 curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, '_curl_read_headers'));
1838                 // add cookies headers
1839                 if ( is_array($cookies) ) {
1840                         curl_setopt($ch,CURLOPT_COOKIE,implode(';',$cookies));
1841                 }
1842                 // perform the query
1843                 $buf = curl_exec ($ch);
1844                 if ( $buf === FALSE ) {
1845                         phpCAS::trace('curl_exec() failed');
1846                         $err_msg = 'CURL error #'.curl_errno($ch).': '.curl_error($ch);
1847                         // close the CURL session
1848                         curl_close ($ch);
1849                         $res = FALSE;
1850                 } else {
1851                         // close the CURL session
1852                         curl_close ($ch);
1853                         
1854                         $headers = $this->_curl_headers;
1855                         $body = $buf;
1856                 }
1857                 
1858                 phpCAS::traceEnd($res);
1859                 return $res;
1860         }
1861         
1862         /**
1863          * This method is the callback used by readURL method to request HTTP headers.
1864          */
1865         var $_curl_headers = array();
1866         function _curl_read_headers($ch, $header)
1867         {
1868                 $this->_curl_headers[] = $header;
1869                 return strlen($header);
1870         }
1871
1872         /**
1873          * This method is used to access an HTTP[S] service.
1874          * 
1875          * @param $url the service to access.
1876          * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on
1877          * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE,
1878          * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE.
1879          * @param $output the output of the service (also used to give an error
1880          * message on failure).
1881          *
1882          * @return TRUE on success, FALSE otherwise (in this later case, $err_code
1883          * gives the reason why it failed and $output contains an error message).
1884          *
1885          * @public
1886          */
1887         function serviceWeb($url,&$err_code,&$output)
1888                 {
1889                 phpCAS::traceBegin();
1890                 // at first retrieve a PT
1891                 $pt = $this->retrievePT($url,$err_code,$output);
1892                 
1893                 $res = TRUE;
1894                 
1895                 // test if PT was retrieved correctly
1896                 if ( !$pt ) {
1897                         // note: $err_code and $err_msg are filled by CASClient::retrievePT()
1898                         phpCAS::trace('PT was not retrieved correctly');
1899                         $res = FALSE;
1900                 } else {
1901                         // add cookies if necessary
1902                         if ( is_array($_SESSION['phpCAS']['services'][$url]['cookies']) ) {
1903                                 foreach ( $_SESSION['phpCAS']['services'][$url]['cookies'] as $name => $val ) { 
1904                                         $cookies[] = $name.'='.$val;
1905                                 }
1906                         }
1907                         
1908                         // build the URL including the PT
1909                         if ( strstr($url,'?') === FALSE ) {
1910                                 $service_url = $url.'?ticket='.$pt;
1911                         } else {
1912                                 $service_url = $url.'&ticket='.$pt;
1913                         }
1914                         
1915                         phpCAS::trace('reading URL`'.$service_url.'\'');
1916                         if ( !$this->readURL($service_url,$cookies,$headers,$output,$err_msg) ) {
1917                                 phpCAS::trace('could not read URL`'.$service_url.'\'');
1918                                 $err_code = PHPCAS_SERVICE_NOT_AVAILABLE;
1919                                 // give an error message
1920                                 $output = sprintf($this->getString(CAS_STR_SERVICE_UNAVAILABLE),
1921                                         $service_url,
1922                                         $err_msg);
1923                                 $res = FALSE;
1924                         } else {
1925                                 // URL has been fetched, extract the cookies
1926                                 phpCAS::trace('URL`'.$service_url.'\' has been read, storing cookies:');
1927                                 foreach ( $headers as $header ) {
1928                                         // test if the header is a cookie
1929                                         if ( preg_match('/^Set-Cookie:/',$header) ) {
1930                                                 // the header is a cookie, remove the beginning
1931                                                 $header_val = preg_replace('/^Set-Cookie: */','',$header);
1932                                                 // extract interesting information
1933                                                 $name_val = strtok($header_val,'; ');
1934                                                 // extract the name and the value of the cookie
1935                                                 $cookie_name = strtok($name_val,'=');
1936                                                 $cookie_val = strtok('=');
1937                                                 // store the cookie 
1938                                                 $_SESSION['phpCAS']['services'][$url]['cookies'][$cookie_name] = $cookie_val;
1939                                                 phpCAS::trace($cookie_name.' -> '.$cookie_val);
1940                                         }
1941                                 }
1942                         }
1943                 }
1944                 
1945                 phpCAS::traceEnd($res);
1946                 return $res;
1947                 }
1948         
1949         /**
1950          * This method is used to access an IMAP/POP3/NNTP service.
1951          * 
1952          * @param $url a string giving the URL of the service, including the mailing box
1953          * for IMAP URLs, as accepted by imap_open().
1954          * @param $flags options given to imap_open().
1955          * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on
1956          * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE,
1957          * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE.
1958          * @param $err_msg an error message on failure
1959          * @param $pt the Proxy Ticket (PT) retrieved from the CAS server to access the URL
1960          * on success, FALSE on error).
1961          *
1962          * @return an IMAP stream on success, FALSE otherwise (in this later case, $err_code
1963          * gives the reason why it failed and $err_msg contains an error message).
1964          *
1965          * @public
1966          */
1967         function serviceMail($url,$flags,&$err_code,&$err_msg,&$pt)
1968                 {
1969                 phpCAS::traceBegin();
1970                 // at first retrieve a PT
1971                 $pt = $this->retrievePT($target_service,$err_code,$output);
1972                 
1973                 $stream = FALSE;
1974                 
1975                 // test if PT was retrieved correctly
1976                 if ( !$pt ) {
1977                         // note: $err_code and $err_msg are filled by CASClient::retrievePT()
1978                         phpCAS::trace('PT was not retrieved correctly');
1979                 } else {
1980                         phpCAS::trace('opening IMAP URL `'.$url.'\'...');
1981                         $stream = @imap_open($url,$this->getUser(),$pt,$flags);
1982                         if ( !$stream ) {
1983                                 phpCAS::trace('could not open URL');
1984                                 $err_code = PHPCAS_SERVICE_NOT_AVAILABLE;
1985                                 // give an error message
1986                                 $err_msg = sprintf($this->getString(CAS_STR_SERVICE_UNAVAILABLE),
1987                                         $service_url,
1988                                         var_export(imap_errors(),TRUE));
1989                                 $pt = FALSE;
1990                                 $stream = FALSE;
1991                         } else {
1992                                 phpCAS::trace('ok');
1993                         }
1994                 }
1995                 
1996                 phpCAS::traceEnd($stream);
1997                 return $stream;
1998                 }
1999         
2000         /** @} */
2001         
2002         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2003         // XX                                                                    XX
2004         // XX                  PROXIED CLIENT FEATURES (CAS 2.0)                 XX
2005         // XX                                                                    XX
2006         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2007         
2008         // ########################################################################
2009         //  PT
2010         // ########################################################################
2011         /**
2012          * @addtogroup internalProxied
2013          * @{
2014          */  
2015         
2016         /**
2017          * the Proxy Ticket provided in the URL of the request if present
2018          * (empty otherwise). Written by CASClient::CASClient(), read by 
2019          * CASClient::getPT() and CASClient::hasPGT().
2020          *
2021          * @hideinitializer
2022          * @private
2023          */
2024         var $_pt = '';
2025         
2026         /**
2027          * This method returns the Proxy Ticket provided in the URL of the request.
2028          * @return The proxy ticket.
2029          * @private
2030          */
2031         function getPT()
2032                 {
2033                 //      return 'ST'.substr($this->_pt, 2);
2034                 return $this->_pt;
2035                 }
2036         
2037         /**
2038          * This method stores the Proxy Ticket.
2039          * @param $pt The Proxy Ticket.
2040          * @private
2041          */
2042         function setPT($pt)
2043                 { $this->_pt = $pt; }
2044         
2045         /**
2046          * This method tells if a Proxy Ticket was stored.
2047          * @return TRUE if a Proxy Ticket has been stored.
2048          * @private
2049          */
2050         function hasPT()
2051                 { return !empty($this->_pt); }
2052         
2053         /** @} */
2054         // ########################################################################
2055         //  PT VALIDATION
2056         // ########################################################################
2057         /**
2058          * @addtogroup internalProxied
2059          * @{
2060          */  
2061         
2062         /**
2063          * This method is used to validate a PT; halt on failure
2064          * 
2065          * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError().
2066          *
2067          * @private
2068          */
2069         function validatePT(&$validate_url,&$text_response,&$tree_response)
2070                 {
2071                 phpCAS::traceBegin();
2072                 // build the URL to validate the ticket
2073                 $validate_url = $this->getServerProxyValidateURL().'&ticket='.$this->getPT();
2074                 
2075                 if ( $this->isProxy() ) {
2076                         // pass the callback url for CAS proxies
2077                         $validate_url .= '&pgtUrl='.$this->getCallbackURL();
2078                 }
2079                 
2080                 // open and read the URL
2081                 if ( !$this->readURL($validate_url,''/*cookies*/,$headers,$text_response,$err_msg) ) {
2082                         phpCAS::trace('could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')');
2083                         $this->authError('PT not validated',
2084                                 $validate_url,
2085                                 TRUE/*$no_response*/);
2086                 }
2087                 
2088                 // read the response of the CAS server into a DOM object
2089                 if ( !($dom = domxml_open_mem($text_response))) {
2090                         // read failed
2091                         $this->authError('PT not validated',
2092                                 $validate_url,
2093                                 FALSE/*$no_response*/,
2094                                 TRUE/*$bad_response*/,
2095                                 $text_response);
2096                 }
2097                 // read the root node of the XML tree
2098                 if ( !($tree_response = $dom->document_element()) ) {
2099                         // read failed
2100                         $this->authError('PT not validated',
2101                                 $validate_url,
2102                                 FALSE/*$no_response*/,
2103                                 TRUE/*$bad_response*/,
2104                                 $text_response);
2105                 }
2106                 // insure that tag name is 'serviceResponse'
2107                 if ( $tree_response->node_name() != 'serviceResponse' ) {
2108                         // bad root node
2109                         $this->authError('PT not validated',
2110                                 $validate_url,
2111                                 FALSE/*$no_response*/,
2112                                 TRUE/*$bad_response*/,
2113                                 $text_response);
2114                 }
2115                 if ( sizeof($arr = $tree_response->get_elements_by_tagname("authenticationSuccess")) != 0) {
2116                         // authentication succeded, extract the user name
2117                         if ( sizeof($arr = $tree_response->get_elements_by_tagname("user")) == 0) {
2118                                 // no user specified => error
2119                                 $this->authError('PT not validated',
2120                                         $validate_url,
2121                                         FALSE/*$no_response*/,
2122                                         TRUE/*$bad_response*/,
2123                                         $text_response);
2124                         }
2125                         $this->setUser(trim($arr[0]->get_content()));
2126                         
2127                 } else if ( sizeof($arr = $tree_response->get_elements_by_tagname("authenticationFailure")) != 0) {
2128                         // authentication succeded, extract the error code and message
2129                         $this->authError('PT not validated',
2130                                 $validate_url,
2131                                 FALSE/*$no_response*/,
2132                                 FALSE/*$bad_response*/,
2133                                 $text_response,
2134                                 $arr[0]->get_attribute('code')/*$err_code*/,
2135                                 trim($arr[0]->get_content())/*$err_msg*/);
2136                 } else {
2137                         $this->authError('PT not validated',
2138                                 $validate_url,  
2139                                 FALSE/*$no_response*/,
2140                                 TRUE/*$bad_response*/,
2141                                 $text_response);
2142                 }
2143                 
2144                 // at this step, PT has been validated and $this->_user has been set,
2145                 
2146                 phpCAS::traceEnd(TRUE);
2147                 return TRUE;
2148                 }
2149         
2150         /** @} */
2151         
2152         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2153         // XX                                                                    XX
2154         // XX                               MISC                                 XX
2155         // XX                                                                    XX
2156         // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2157         
2158         /**
2159          * @addtogroup internalMisc
2160          * @{
2161          */  
2162         
2163         // ########################################################################
2164         //  URL
2165         // ########################################################################
2166         /**
2167          * the URL of the current request (without any ticket CGI parameter). Written 
2168          * and read by CASClient::getURL().
2169          *
2170          * @hideinitializer
2171          * @private
2172          */
2173         var $_url = '';
2174         
2175         /**
2176          * This method returns the URL of the current request (without any ticket
2177          * CGI parameter).
2178          *
2179          * @return The URL
2180          *
2181          * @private
2182          */
2183         function getURL()
2184                 {
2185                 phpCAS::traceBegin();
2186                 // the URL is built when needed only
2187                 if ( empty($this->_url) ) {
2188                         $final_uri = '';
2189                         // remove the ticket if present in the URL
2190                         $final_uri = ($this->isHttps()) ? 'https' : 'http';
2191                         $final_uri .= '://';
2192                         /* replaced by Julien Marchal - v0.4.6
2193                          * $this->_url .= $_SERVER['SERVER_NAME'];
2194                          */
2195                         if(empty($_SERVER['HTTP_X_FORWARDED_SERVER'])){
2196                                 /* replaced by teedog - v0.4.12
2197                                  * $this->_url .= $_SERVER['SERVER_NAME'];
2198                                  */
2199                                 if (empty($_SERVER['SERVER_NAME'])) {
2200                                         $server_name = $_SERVER['HTTP_HOST'];
2201                                 } else {
2202                                         $server_name = $_SERVER['SERVER_NAME'];
2203                                 }
2204                         } else {
2205                                 $server_name = $_SERVER['HTTP_X_FORWARDED_SERVER'];
2206                         }
2207                         $final_uri .= $server_name;
2208                         if (!strpos($server_name, ':')) {
2209                                 if ( ($this->isHttps() && $_SERVER['SERVER_PORT']!=443)
2210                                                 || (!$this->isHttps() && $_SERVER['SERVER_PORT']!=80) ) {
2211                                         $final_uri .= ':';
2212                                         $final_uri .= $_SERVER['SERVER_PORT'];
2213                                 }
2214                         }
2215                         
2216                         $final_uri .= strtok($_SERVER['REQUEST_URI'],"?");
2217                         $cgi_params = '?'.strtok("?");
2218                         // remove the ticket if present in the CGI parameters
2219                         $cgi_params = preg_replace('/&ticket=[^&]*/','',$cgi_params);
2220                         $cgi_params = preg_replace('/\?ticket=[^&;]*/','?',$cgi_params);
2221                         $cgi_params = preg_replace('/\?%26/','?',$cgi_params);
2222                         $cgi_params = preg_replace('/\?&/','?',$cgi_params);
2223                         $cgi_params = preg_replace('/\?$/','',$cgi_params);
2224                         $final_uri .= $cgi_params;
2225                         $this->setURL($final_uri);
2226                 }
2227                 phpCAS::traceEnd($this->_url);
2228                 return $this->_url;
2229                 }
2230         
2231         /**
2232          * This method sets the URL of the current request 
2233          *
2234          * @param $url url to set for service
2235          *
2236          * @private
2237          */
2238         function setURL($url)
2239                 {
2240                 $this->_url = $url;
2241                 }
2242         
2243         // ########################################################################
2244         //  AUTHENTICATION ERROR HANDLING
2245         // ########################################################################
2246         /**
2247          * This method is used to print the HTML output when the user was not authenticated.
2248          *
2249          * @param $failure the failure that occured
2250          * @param $cas_url the URL the CAS server was asked for
2251          * @param $no_response the response from the CAS server (other 
2252          * parameters are ignored if TRUE)
2253          * @param $bad_response bad response from the CAS server ($err_code
2254          * and $err_msg ignored if TRUE)
2255          * @param $cas_response the response of the CAS server
2256          * @param $err_code the error code given by the CAS server
2257          * @param $err_msg the error message given by the CAS server
2258          *
2259          * @private
2260          */
2261         function authError($failure,$cas_url,$no_response,$bad_response='',$cas_response='',$err_code='',$err_msg='')
2262                 {
2263                 phpCAS::traceBegin();
2264                 
2265                 $this->printHTMLHeader($this->getString(CAS_STR_AUTHENTICATION_FAILED));
2266                 printf($this->getString(CAS_STR_YOU_WERE_NOT_AUTHENTICATED),$this->getURL(),$_SERVER['SERVER_ADMIN']);
2267                 phpCAS::trace('CAS URL: '.$cas_url);
2268                 phpCAS::trace('Authentication failure: '.$failure);
2269                 if ( $no_response ) {
2270                         phpCAS::trace('Reason: no response from the CAS server');
2271                 } else {
2272                         if ( $bad_response ) {
2273                                 phpCAS::trace('Reason: bad response from the CAS server');
2274                         } else {
2275                                 switch ($this->getServerVersion()) {
2276                                         case CAS_VERSION_1_0:
2277                                                 phpCAS::trace('Reason: CAS error');
2278                                                 break;
2279                                         case CAS_VERSION_2_0:
2280                                                 if ( empty($err_code) )
2281                                                         phpCAS::trace('Reason: no CAS error');
2282                                                 else
2283                                                         phpCAS::trace('Reason: ['.$err_code.'] CAS error: '.$err_msg);
2284                                                 break;
2285                                 }
2286                         }
2287                         phpCAS::trace('CAS response: '.$cas_response);
2288                 }
2289                 $this->printHTMLFooter();
2290                 phpCAS::traceExit();
2291                 exit();
2292                 }
2293         
2294         /** @} */
2295 }
2296
2297 ?>