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