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