5 * Main class of the phpCAS library
8 // include internationalization stuff
9 include_once(dirname(__FILE__
).'/languages/languages.php');
11 // include PGT storage classes
12 include_once(dirname(__FILE__
).'/PGTStorage/pgt-main.php');
16 * The CASClient class is a client interface that provides CAS authentication
17 * to PHP applications.
19 * @author Pascal Aubry <pascal.aubry at univ-rennes1.fr>
25 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
27 // XX CONFIGURATION XX
29 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
31 // ########################################################################
33 // ########################################################################
35 * @addtogroup internalOutput
40 * This method filters a string by replacing special tokens by appropriate values
41 * and prints it. The corresponding tokens are taken into account:
43 * - __PHPCAS_VERSION__
44 * - __SERVER_BASE_URL__
46 * Used by CASClient::PrintHTMLHeader() and CASClient::printHTMLFooter().
48 * @param $str the string to filter and output
52 function HTMLFilterOutput($str)
54 $str = str_replace('__CAS_VERSION__',$this->getServerVersion(),$str);
55 $str = str_replace('__PHPCAS_VERSION__',phpCAS
::getVersion(),$str);
56 $str = str_replace('__SERVER_BASE_URL__',$this->getServerBaseURL(),$str);
61 * A string used to print the header of HTML pages. Written by CASClient::setHTMLHeader(),
62 * read by CASClient::printHTMLHeader().
66 * @see CASClient::setHTMLHeader, CASClient::printHTMLHeader()
68 var $_output_header = '';
71 * This method prints the header of the HTML output (after filtering). If
72 * CASClient::setHTMLHeader() was not used, a default header is output.
74 * @param $title the title of the page
76 * @see HTMLFilterOutput()
79 function printHTMLHeader($title)
81 $this->HTMLFilterOutput(str_replace('__TITLE__',
83 (empty($this->_output_header
)
84 ?
'<html><head><title>__TITLE__</title></head><body><h1>__TITLE__</h1>'
85 : $this->_output_header
)
91 * A string used to print the footer of HTML pages. Written by CASClient::setHTMLFooter(),
92 * read by printHTMLFooter().
96 * @see CASClient::setHTMLFooter, CASClient::printHTMLFooter()
98 var $_output_footer = '';
101 * This method prints the footer of the HTML output (after filtering). If
102 * CASClient::setHTMLFooter() was not used, a default footer is output.
104 * @see HTMLFilterOutput()
107 function printHTMLFooter()
109 $this->HTMLFilterOutput(empty($this->_output_footer
)
110 ?
('<hr><address>phpCAS __PHPCAS_VERSION__ '.$this->getString(CAS_STR_USING_SERVER
).' <a href="__SERVER_BASE_URL__">__SERVER_BASE_URL__</a> (CAS __CAS_VERSION__)</a></address></body></html>')
111 :$this->_output_footer
);
115 * This method set the HTML header used for all outputs.
117 * @param $header the HTML header.
121 function setHTMLHeader($header)
123 $this->_output_header
= $header;
127 * This method set the HTML footer used for all outputs.
129 * @param $footer the HTML footer.
133 function setHTMLFooter($footer)
135 $this->_output_footer
= $footer;
139 // ########################################################################
140 // INTERNATIONALIZATION
141 // ########################################################################
143 * @addtogroup internalLang
147 * A string corresponding to the language used by phpCAS. Written by
148 * CASClient::setLang(), read by CASClient::getLang().
150 * @note debugging information is always in english (debug purposes only).
154 * @sa CASClient::_strings, CASClient::getString()
159 * This method returns the language used by phpCAS.
161 * @return a string representing the language
167 if ( empty($this->_lang
) )
168 $this->setLang(PHPCAS_LANG_DEFAULT
);
173 * array containing the strings used by phpCAS. Written by CASClient::setLang(), read by
174 * CASClient::getString() and used by CASClient::setLang().
176 * @note This array is filled by instructions in CAS/languages/<$this->_lang>.php
179 * @see CASClient::_lang, CASClient::getString(), CASClient::setLang(), CASClient::getLang()
184 * This method returns a string depending on the language.
186 * @param $str the index of the string in $_string.
188 * @return the string corresponding to $index in $string.
192 function getString($str)
194 // call CASclient::getLang() to be sure the language is initialized
197 if ( !isset($this->_strings
[$str]) ) {
198 trigger_error('string `'.$str.'\' not defined for language `'.$this->getLang().'\'',E_USER_ERROR
);
200 return $this->_strings
[$str];
204 * This method is used to set the language used by phpCAS.
205 * @note Can be called only once.
207 * @param $lang a string representing the language.
210 * @sa CAS_LANG_FRENCH, CAS_LANG_ENGLISH
212 function setLang($lang)
214 // include the corresponding language file
215 include_once(dirname(__FILE__
).'/languages/'.$lang.'.php');
217 if ( !is_array($this->_strings
) ) {
218 trigger_error('language `'.$lang.'\' is not implemented',E_USER_ERROR
);
220 $this->_lang
= $lang;
224 // ########################################################################
226 // ########################################################################
228 * @addtogroup internalConfig
233 * a record to store information about the CAS server.
234 * - $_server["version"]: the version of the CAS server
235 * - $_server["hostname"]: the hostname of the CAS server
236 * - $_server["port"]: the port the CAS server is running on
237 * - $_server["uri"]: the base URI the CAS server is responding on
238 * - $_server["base_url"]: the base URL of the CAS server
239 * - $_server["login_url"]: the login URL of the CAS server
240 * - $_server["service_validate_url"]: the service validating URL of the CAS server
241 * - $_server["proxy_url"]: the proxy URL of the CAS server
242 * - $_server["proxy_validate_url"]: the proxy validating URL of the CAS server
243 * - $_server["logout_url"]: the logout URL of the CAS server
245 * $_server["version"], $_server["hostname"], $_server["port"] and $_server["uri"]
246 * are written by CASClient::CASClient(), read by CASClient::getServerVersion(),
247 * CASClient::getServerHostname(), CASClient::getServerPort() and CASClient::getServerURI().
249 * The other fields are written and read by CASClient::getServerBaseURL(),
250 * CASClient::getServerLoginURL(), CASClient::getServerServiceValidateURL(),
251 * CASClient::getServerProxyValidateURL() and CASClient::getServerLogoutURL().
256 var $_server = array(
258 'hostname' => 'none',
264 * This method is used to retrieve the version of the CAS server.
265 * @return the version of the CAS server.
268 function getServerVersion()
270 return $this->_server
['version'];
274 * This method is used to retrieve the hostname of the CAS server.
275 * @return the hostname of the CAS server.
278 function getServerHostname()
279 { return $this->_server
['hostname']; }
282 * This method is used to retrieve the port of the CAS server.
283 * @return the port of the CAS server.
286 function getServerPort()
287 { return $this->_server
['port']; }
290 * This method is used to retrieve the URI of the CAS server.
294 function getServerURI()
295 { return $this->_server
['uri']; }
298 * This method is used to retrieve the base URL of the CAS server.
302 function getServerBaseURL()
304 // the URL is build only when needed
305 if ( empty($this->_server
['base_url']) ) {
306 $this->_server
['base_url'] = 'https://'
307 .$this->getServerHostname()
309 .$this->getServerPort()
310 .$this->getServerURI();
312 return $this->_server
['base_url'];
316 * This method is used to retrieve the login URL of the CAS server.
317 * @param $gateway true to check authentication, false to force it
321 function getServerLoginURL($gateway=false)
323 phpCAS
::traceBegin();
324 // the URL is build only when needed
325 if ( empty($this->_server
['login_url']) ) {
326 $this->_server
['login_url'] = $this->getServerBaseURL();
327 $this->_server
['login_url'] .= 'login?service=';
328 // $this->_server['login_url'] .= preg_replace('/&/','%26',$this->getURL());
329 $this->_server
['login_url'] .= urlencode($this->getURL());
331 $this->_server
['login_url'] .= '&gateway=true';
334 phpCAS
::traceEnd($this->_server
['login_url']);
335 return $this->_server
['login_url'];
339 * This method sets the login URL of the CAS server.
340 * @param $url the login URL
342 * @since 0.4.21 by Wyman Chan
344 function setServerLoginURL($url)
346 return $this->_server
['login_url'] = $url;
350 * This method is used to retrieve the service validating URL of the CAS server.
354 function getServerServiceValidateURL()
356 // the URL is build only when needed
357 if ( empty($this->_server
['service_validate_url']) ) {
358 switch ($this->getServerVersion()) {
359 case CAS_VERSION_1_0
:
360 $this->_server
['service_validate_url'] = $this->getServerBaseURL().'validate';
362 case CAS_VERSION_2_0
:
363 $this->_server
['service_validate_url'] = $this->getServerBaseURL().'serviceValidate';
367 // return $this->_server['service_validate_url'].'?service='.preg_replace('/&/','%26',$this->getURL());
368 return $this->_server
['service_validate_url'].'?service='.urlencode($this->getURL());
372 * This method is used to retrieve the proxy validating URL of the CAS server.
376 function getServerProxyValidateURL()
378 // the URL is build only when needed
379 if ( empty($this->_server
['proxy_validate_url']) ) {
380 switch ($this->getServerVersion()) {
381 case CAS_VERSION_1_0
:
382 $this->_server
['proxy_validate_url'] = '';
384 case CAS_VERSION_2_0
:
385 $this->_server
['proxy_validate_url'] = $this->getServerBaseURL().'proxyValidate';
389 // return $this->_server['proxy_validate_url'].'?service='.preg_replace('/&/','%26',$this->getURL());
390 return $this->_server
['proxy_validate_url'].'?service='.urlencode($this->getURL());
394 * This method is used to retrieve the proxy URL of the CAS server.
398 function getServerProxyURL()
400 // the URL is build only when needed
401 if ( empty($this->_server
['proxy_url']) ) {
402 switch ($this->getServerVersion()) {
403 case CAS_VERSION_1_0
:
404 $this->_server
['proxy_url'] = '';
406 case CAS_VERSION_2_0
:
407 $this->_server
['proxy_url'] = $this->getServerBaseURL().'proxy';
411 return $this->_server
['proxy_url'];
415 * This method is used to retrieve the logout URL of the CAS server.
419 function getServerLogoutURL()
421 // the URL is build only when needed
422 if ( empty($this->_server
['logout_url']) ) {
423 $this->_server
['logout_url'] = $this->getServerBaseURL().'logout';
425 return $this->_server
['logout_url'];
429 * This method sets the logout URL of the CAS server.
430 * @param $url the logout URL
432 * @since 0.4.21 by Wyman Chan
434 function setServerLogoutURL($url)
436 return $this->_server
['logout_url'] = $url;
440 * This method checks to see if the request is secured via HTTPS
441 * @return true if https, false otherwise
445 //if ( isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ) {
447 if ( isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
454 // ########################################################################
456 // ########################################################################
458 * CASClient constructor.
460 * @param $server_version the version of the CAS server
461 * @param $proxy TRUE if the CAS client is a CAS proxy, FALSE otherwise
462 * @param $server_hostname the hostname of the CAS server
463 * @param $server_port the port the CAS server is running on
464 * @param $server_uri the URI the CAS server is responding on
465 * @param $start_session Have phpCAS start PHP sessions (default true)
467 * @return a newly created CASClient object
477 $start_session = true) {
479 phpCAS
::traceBegin();
481 //activate session mechanism if desired
482 if ($start_session) {
486 $this->_proxy
= $proxy;
489 switch ($server_version) {
490 case CAS_VERSION_1_0
:
491 if ( $this->isProxy() )
492 phpCAS
::error('CAS proxies are not supported in CAS '
495 case CAS_VERSION_2_0
:
498 phpCAS
::error('this version of CAS (`'
500 .'\') is not supported by phpCAS '
501 .phpCAS
::getVersion());
503 $this->_server
['version'] = $server_version;
506 if ( empty($server_hostname)
507 ||
!preg_match('/[\.\d\-abcdefghijklmnopqrstuvwxyz]*/',$server_hostname) ) {
508 phpCAS
::error('bad CAS server hostname (`'.$server_hostname.'\')');
510 $this->_server
['hostname'] = $server_hostname;
513 if ( $server_port == 0
514 ||
!is_int($server_port) ) {
515 phpCAS
::error('bad CAS server port (`'.$server_hostname.'\')');
517 $this->_server
['port'] = $server_port;
520 if ( !preg_match('/[\.\d\-_abcdefghijklmnopqrstuvwxyz\/]*/',$server_uri) ) {
521 phpCAS
::error('bad CAS server URI (`'.$server_uri.'\')');
523 //add leading and trailing `/' and remove doubles
524 $server_uri = preg_replace('/\/\//','/','/'.$server_uri.'/');
525 $this->_server
['uri'] = $server_uri;
527 //set to callback mode if PgtIou and PgtId CGI GET parameters are provided
528 if ( $this->isProxy() ) {
529 $this->setCallbackMode(!empty($_GET['pgtIou'])&&!empty($_GET['pgtId']));
532 if ( $this->isCallbackMode() ) {
533 //callback mode: check that phpCAS is secured
534 if ( !$this->isHttps() ) {
535 phpCAS
::error('CAS proxies must be secured to use phpCAS; PGT\'s will not be received from the CAS server');
538 //normal mode: get ticket and remove it from CGI parameters for developpers
539 $ticket = (isset($_GET['ticket']) ?
$_GET['ticket'] : null);
540 switch ($this->getServerVersion()) {
541 case CAS_VERSION_1_0
: // check for a Service Ticket
542 if( preg_match('/^ST-/',$ticket) ) {
543 phpCAS
::trace('ST \''.$ticket.'\' found');
545 $this->setST($ticket);
546 //ticket has been taken into account, unset it to hide it to applications
547 unset($_GET['ticket']);
548 } else if ( !empty($ticket) ) {
549 //ill-formed ticket, halt
550 phpCAS
::error('ill-formed ticket found in the URL (ticket=`'.htmlentities($ticket).'\')');
553 case CAS_VERSION_2_0
: // check for a Service or Proxy Ticket
554 if( preg_match('/^[SP]T-/',$ticket) ) {
555 phpCAS
::trace('ST or PT \''.$ticket.'\' found');
556 $this->setPT($ticket);
557 unset($_GET['ticket']);
558 } else if ( !empty($ticket) ) {
559 //ill-formed ticket, halt
560 phpCAS
::error('ill-formed ticket found in the URL (ticket=`'.htmlentities($ticket).'\')');
570 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
572 // XX AUTHENTICATION XX
574 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
577 * @addtogroup internalAuthentication
582 * The Authenticated user. Written by CASClient::setUser(), read by CASClient::getUser().
583 * @attention client applications should use phpCAS::getUser().
591 * This method sets the CAS user's login name.
593 * @param $user the login name of the authenticated user.
597 function setUser($user)
599 $this->_user
= $user;
603 * This method returns the CAS user's login name.
604 * @warning should be called only after CASClient::forceAuthentication() or
605 * CASClient::isAuthenticated(), otherwise halt with an error.
607 * @return the login name of the authenticated user
611 if ( empty($this->_user
) ) {
612 phpCAS
::error('this method should be used only after '.__CLASS__
.'::forceAuthentication() or '.__CLASS__
.'::isAuthenticated()');
618 * This method is called to be sure that the user is authenticated. When not
619 * authenticated, halt by redirecting to the CAS server; otherwise return TRUE.
620 * @return TRUE when the user is authenticated; otherwise halt.
623 function forceAuthentication()
625 phpCAS
::traceBegin();
627 if ( $this->isAuthenticated() ) {
628 // the user is authenticated, nothing to be done.
629 phpCAS
::trace('no need to authenticate');
633 // the user is not authenticated, redirect to the CAS server
634 unset($_SESSION['phpCAS']['auth_checked']);
635 $this->redirectToCas(FALSE/* no gateway */);
639 phpCAS
::traceEnd($res);
644 * An integer that gives the number of times authentication will be cached before rechecked.
649 var $_cache_times_for_auth_recheck = 0;
652 * Set the number of times authentication will be cached before rechecked.
654 * @param $n an integer.
658 function setCacheTimesForAuthRequest($n)
660 $this->_cache_times_for_auth_recheck
= n
;
664 * This method is called to check whether the user is authenticated or not.
665 * @return TRUE when the user is authenticated, FALSE otherwise.
668 function checkAuthentication()
670 phpCAS
::traceBegin();
672 if ( $this->isAuthenticated() ) {
673 phpCAS
::trace('user is authenticated');
675 } else if (isset($_SESSION['phpCAS']['auth_checked'])) {
676 // the previous request has redirected the client to the CAS server with gateway=true
677 unset($_SESSION['phpCAS']['auth_checked']);
680 // $_SESSION['phpCAS']['auth_checked'] = true;
681 // $this->redirectToCas(TRUE/* gateway */);
684 // avoid a check against CAS on every request
685 if (! isset($_SESSION['phpCAS']['unauth_count']) )
686 $_SESSION['phpCAS']['unauth_count'] = -2; // uninitialized
688 if (($_SESSION['phpCAS']['unauth_count'] != -2 && $this->_cache_times_for_auth_recheck
== -1)
689 ||
($_SESSION['phpCAS']['unauth_count'] >= 0 && $_SESSION['phpCAS']['unauth_count'] < $this->_cache_times_for_auth_recheck
))
693 if ($this->_cache_times_for_auth_recheck
!= -1)
695 $_SESSION['phpCAS']['unauth_count']++
;
696 phpCAS
::trace('user is not authenticated (cached for '.$_SESSION['phpCAS']['unauth_count'].' times of '.$this->_cache_times_for_auth_recheck
.')');
700 phpCAS
::trace('user is not authenticated (cached for until login pressed)');
705 $_SESSION['phpCAS']['unauth_count'] = 0;
706 $_SESSION['phpCAS']['auth_checked'] = true;
707 phpCAS
::trace('user is not authenticated (cache reset)');
708 $this->redirectToCas(TRUE/* gateway */);
713 phpCAS
::traceEnd($res);
718 * This method is called to check if the user is authenticated (previously or by
719 * tickets given in the URL).
721 * @return TRUE when the user is authenticated.
725 function isAuthenticated()
727 phpCAS
::traceBegin();
731 if ( $this->wasPreviouslyAuthenticated() ) {
732 // the user has already (previously during the session) been
733 // authenticated, nothing to be done.
734 phpCAS
::trace('user was already authenticated, no need to look for tickets');
737 elseif ( $this->hasST() ) {
738 // if a Service Ticket was given, validate it
739 phpCAS
::trace('ST `'.$this->getST().'\' is present');
740 $this->validateST($validate_url,$text_response,$tree_response); // if it fails, it halts
741 phpCAS
::trace('ST `'.$this->getST().'\' was validated');
742 if ( $this->isProxy() ) {
743 $this->validatePGT($validate_url,$text_response,$tree_response); // idem
744 phpCAS
::trace('PGT `'.$this->getPGT().'\' was validated');
745 $_SESSION['phpCAS']['pgt'] = $this->getPGT();
747 $_SESSION['phpCAS']['user'] = $this->getUser();
750 elseif ( $this->hasPT() ) {
751 // if a Proxy Ticket was given, validate it
752 phpCAS
::trace('PT `'.$this->getPT().'\' is present');
753 $this->validatePT($validate_url,$text_response,$tree_response); // note: if it fails, it halts
754 phpCAS
::trace('PT `'.$this->getPT().'\' was validated');
756 if ( $this->isProxy() ) {
758 $this->validatePGT($validate_url,$text_response,$tree_response); // idem
759 phpCAS
::trace('PGT `'.$this->getPGT().'\' was validated');
760 $_SESSION['phpCAS']['pgt'] = $this->getPGT();
762 $_SESSION['phpCAS']['user'] = $this->getUser();
766 // no ticket given, not authenticated
767 phpCAS
::trace('no ticket found');
770 phpCAS
::traceEnd($res);
775 * This method tells if the current session is authenticated.
776 * @return true if authenticated based soley on $_SESSION variable
777 * @since 0.4.22 by Brendan Arnold
779 function isSessionAuthenticated ()
781 return !empty($_SESSION['phpCAS']['user']);
785 * This method tells if the user has already been (previously) authenticated
786 * by looking into the session variables.
788 * @note This function switches to callback mode when needed.
790 * @return TRUE when the user has already been authenticated; FALSE otherwise.
794 function wasPreviouslyAuthenticated()
796 phpCAS
::traceBegin();
798 if ( $this->isCallbackMode() ) {
805 if ( $this->isProxy() ) {
806 // CAS proxy: username and PGT must be present
807 if ( $this->isSessionAuthenticated() && !empty($_SESSION['phpCAS']['pgt']) ) {
808 // authentication already done
809 $this->setUser($_SESSION['phpCAS']['user']);
810 $this->setPGT($_SESSION['phpCAS']['pgt']);
811 phpCAS
::trace('user = `'.$_SESSION['phpCAS']['user'].'\', PGT = `'.$_SESSION['phpCAS']['pgt'].'\'');
813 } elseif ( $this->isSessionAuthenticated() && empty($_SESSION['phpCAS']['pgt']) ) {
814 // these two variables should be empty or not empty at the same time
815 phpCAS
::trace('username found (`'.$_SESSION['phpCAS']['user'].'\') but PGT is empty');
816 // unset all tickets to enforce authentication
817 unset($_SESSION['phpCAS']);
820 } elseif ( !$this->isSessionAuthenticated() && !empty($_SESSION['phpCAS']['pgt']) ) {
821 // these two variables should be empty or not empty at the same time
822 phpCAS
::trace('PGT found (`'.$_SESSION['phpCAS']['pgt'].'\') but username is empty');
823 // unset all tickets to enforce authentication
824 unset($_SESSION['phpCAS']);
828 phpCAS
::trace('neither user not PGT found');
831 // `simple' CAS client (not a proxy): username must be present
832 if ( $this->isSessionAuthenticated() ) {
833 // authentication already done
834 $this->setUser($_SESSION['phpCAS']['user']);
835 phpCAS
::trace('user = `'.$_SESSION['phpCAS']['user'].'\'');
838 phpCAS
::trace('no user found');
842 phpCAS
::traceEnd($auth);
847 * This method is used to redirect the client to the CAS server.
848 * It is used by CASClient::forceAuthentication() and CASClient::checkAuthentication().
849 * @param $gateway true to check authentication, false to force it
852 function redirectToCas($gateway=false)
854 phpCAS
::traceBegin();
855 $cas_url = $this->getServerLoginURL($gateway);
856 header('Location: '.$cas_url);
857 $this->printHTMLHeader($this->getString(CAS_STR_AUTHENTICATION_WANTED
));
858 printf('<p>'.$this->getString(CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED
).'</p>',$cas_url);
859 $this->printHTMLFooter();
865 * This method is used to logout from CAS.
866 * @param $url a URL that will be transmitted to the CAS server (to come back to when logged out)
869 function logout($url = "")
871 phpCAS
::traceBegin();
872 $cas_url = $this->getServerLogoutURL();
873 // v0.4.14 sebastien.gougeon at univ-rennes1.fr
874 // header('Location: '.$cas_url);
876 $url = '?service=' . $url;
878 header('Location: '.$cas_url . $url);
881 $this->printHTMLHeader($this->getString(CAS_STR_LOGOUT
));
882 printf('<p>'.$this->getString(CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED
).'</p>',$cas_url);
883 $this->printHTMLFooter();
890 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
892 // XX BASIC CLIENT FEATURES (CAS 1.0) XX
894 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
896 // ########################################################################
898 // ########################################################################
900 * @addtogroup internalBasic
905 * the Service Ticket provided in the URL of the request if present
906 * (empty otherwise). Written by CASClient::CASClient(), read by
907 * CASClient::getST() and CASClient::hasPGT().
915 * This method returns the Service Ticket provided in the URL of the request.
916 * @return The service ticket.
920 { return $this->_st
; }
923 * This method stores the Service Ticket.
924 * @param $st The Service Ticket.
928 { $this->_st
= $st; }
931 * This method tells if a Service Ticket was stored.
932 * @return TRUE if a Service Ticket has been stored.
936 { return !empty($this->_st
); }
940 // ########################################################################
942 // ########################################################################
944 * @addtogroup internalBasic
949 * This method is used to validate a ST; halt on failure, and sets $validate_url,
950 * $text_reponse and $tree_response on success. These parameters are used later
951 * by CASClient::validatePGT() for CAS proxies.
953 * @param $validate_url the URL of the request to the CAS server.
954 * @param $text_response the response of the CAS server, as is (XML text).
955 * @param $tree_response the response of the CAS server, as a DOM XML tree.
957 * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError().
961 function validateST($validate_url,&$text_response,&$tree_response)
963 phpCAS
::traceBegin();
964 // build the URL to validate the ticket
965 $validate_url = $this->getServerServiceValidateURL().'&ticket='.$this->getST();
966 if ( $this->isProxy() ) {
967 // pass the callback url for CAS proxies
968 $validate_url .= '&pgtUrl='.$this->getCallbackURL();
971 // open and read the URL
972 if ( !$this->readURL($validate_url,''/*cookies*/,$headers,$text_response,$err_msg) ) {
973 phpCAS
::trace('could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')');
974 $this->authError('ST not validated',
976 TRUE/*$no_response*/);
979 // analyze the result depending on the version
980 switch ($this->getServerVersion()) {
981 case CAS_VERSION_1_0
:
982 if (preg_match('/^no\n/',$text_response)) {
983 phpCAS
::trace('ST has not been validated');
984 $this->authError('ST not validated',
986 FALSE/*$no_response*/,
987 FALSE/*$bad_response*/,
990 if (!preg_match('/^yes\n/',$text_response)) {
991 phpCAS
::trace('ill-formed response');
992 $this->authError('ST not validated',
994 FALSE/*$no_response*/,
995 TRUE/*$bad_response*/,
998 // ST has been validated, extract the user name
999 $arr = preg_split('/\n/',$text_response);
1000 $this->setUser(trim($arr[1]));
1002 case CAS_VERSION_2_0
:
1003 // read the response of the CAS server into a DOM object
1004 if ( !($dom = domxml_open_mem($text_response))) {
1005 phpCAS
::trace('domxml_open_mem() failed');
1006 $this->authError('ST not validated',
1008 FALSE/*$no_response*/,
1009 TRUE/*$bad_response*/,
1012 // read the root node of the XML tree
1013 if ( !($tree_response = $dom->document_element()) ) {
1014 phpCAS
::trace('document_element() failed');
1015 $this->authError('ST not validated',
1017 FALSE/*$no_response*/,
1018 TRUE/*$bad_response*/,
1021 // insure that tag name is 'serviceResponse'
1022 if ( $tree_response->node_name() != 'serviceResponse' ) {
1023 phpCAS
::trace('bad XML root node (should be `serviceResponse\' instead of `'.$tree_response->node_name().'\'');
1024 $this->authError('ST not validated',
1026 FALSE/*$no_response*/,
1027 TRUE/*$bad_response*/,
1030 if ( sizeof($success_elements = $tree_response->get_elements_by_tagname("authenticationSuccess")) != 0) {
1031 // authentication succeded, extract the user name
1032 if ( sizeof($user_elements = $success_elements[0]->get_elements_by_tagname("user")) == 0) {
1033 phpCAS
::trace('<authenticationSuccess> found, but no <user>');
1034 $this->authError('ST not validated',
1036 FALSE/*$no_response*/,
1037 TRUE/*$bad_response*/,
1040 $user = trim($user_elements[0]->get_content());
1041 phpCAS
::trace('user = `'.$user);
1042 $this->setUser($user);
1044 } else if ( sizeof($failure_elements = $tree_response->get_elements_by_tagname("authenticationFailure")) != 0) {
1045 phpCAS
::trace('<authenticationFailure> found');
1046 // authentication failed, extract the error code and message
1047 $this->authError('ST not validated',
1049 FALSE/*$no_response*/,
1050 FALSE/*$bad_response*/,
1052 $failure_elements[0]->get_attribute('code')/*$err_code*/,
1053 trim($failure_elements[0]->get_content())/*$err_msg*/);
1055 phpCAS
::trace('neither <authenticationSuccess> nor <authenticationFailure> found');
1056 $this->authError('ST not validated',
1058 FALSE/*$no_response*/,
1059 TRUE/*$bad_response*/,
1065 // at this step, ST has been validated and $this->_user has been set,
1066 phpCAS
::traceEnd(TRUE);
1072 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1074 // XX PROXY FEATURES (CAS 2.0) XX
1076 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1078 // ########################################################################
1080 // ########################################################################
1082 * @addtogroup internalProxy
1087 * A boolean telling if the client is a CAS proxy or not. Written by CASClient::CASClient(),
1088 * read by CASClient::isProxy().
1095 * Tells if a CAS client is a CAS proxy or not
1097 * @return TRUE when the CAS client is a CAs proxy, FALSE otherwise
1103 return $this->_proxy
;
1107 // ########################################################################
1109 // ########################################################################
1111 * @addtogroup internalProxy
1116 * the Proxy Grnting Ticket given by the CAS server (empty otherwise).
1117 * Written by CASClient::setPGT(), read by CASClient::getPGT() and CASClient::hasPGT().
1125 * This method returns the Proxy Granting Ticket given by the CAS server.
1126 * @return The Proxy Granting Ticket.
1130 { return $this->_pgt
; }
1133 * This method stores the Proxy Granting Ticket.
1134 * @param $pgt The Proxy Granting Ticket.
1137 function setPGT($pgt)
1138 { $this->_pgt
= $pgt; }
1141 * This method tells if a Proxy Granting Ticket was stored.
1142 * @return TRUE if a Proxy Granting Ticket has been stored.
1146 { return !empty($this->_pgt
); }
1150 // ########################################################################
1152 // ########################################################################
1154 * @addtogroup internalCallback
1158 * each PHP script using phpCAS in proxy mode is its own callback to get the
1159 * PGT back from the CAS server. callback_mode is detected by the constructor
1160 * thanks to the GET parameters.
1164 * a boolean to know if the CAS client is running in callback mode. Written by
1165 * CASClient::setCallBackMode(), read by CASClient::isCallbackMode().
1170 var $_callback_mode = FALSE;
1173 * This method sets/unsets callback mode.
1175 * @param $callback_mode TRUE to set callback mode, FALSE otherwise.
1179 function setCallbackMode($callback_mode)
1181 $this->_callback_mode
= $callback_mode;
1185 * This method returns TRUE when the CAs client is running i callback mode,
1188 * @return A boolean.
1192 function isCallbackMode()
1194 return $this->_callback_mode
;
1198 * the URL that should be used for the PGT callback (in fact the URL of the
1199 * current request without any CGI parameter). Written and read by
1200 * CASClient::getCallbackURL().
1205 var $_callback_url = '';
1208 * This method returns the URL that should be used for the PGT callback (in
1209 * fact the URL of the current request without any CGI parameter, except if
1210 * phpCAS::setFixedCallbackURL() was used).
1212 * @return The callback URL
1216 function getCallbackURL()
1218 // the URL is built when needed only
1219 if ( empty($this->_callback_url
) ) {
1221 // remove the ticket if present in the URL
1222 $final_uri = 'https://';
1223 /* replaced by Julien Marchal - v0.4.6
1224 * $this->uri .= $_SERVER['SERVER_NAME'];
1226 if(empty($_SERVER['HTTP_X_FORWARDED_SERVER'])){
1227 /* replaced by teedog - v0.4.12
1228 * $final_uri .= $_SERVER['SERVER_NAME'];
1230 if (empty($_SERVER['SERVER_NAME'])) {
1231 $final_uri .= $_SERVER['HTTP_HOST'];
1233 $final_uri .= $_SERVER['SERVER_NAME'];
1236 $final_uri .= $_SERVER['HTTP_X_FORWARDED_SERVER'];
1238 if ( ($this->isHttps() && $_SERVER['SERVER_PORT']!=443)
1239 ||
(!$this->isHttps() && $_SERVER['SERVER_PORT']!=80) ) {
1241 $final_uri .= $_SERVER['SERVER_PORT'];
1243 $request_uri = $_SERVER['REQUEST_URI'];
1244 $request_uri = preg_replace('/\?.*$/','',$request_uri);
1245 $final_uri .= $request_uri;
1246 $this->setCallbackURL($final_uri);
1248 return $this->_callback_url
;
1252 * This method sets the callback url.
1254 * @param $callback_url url to set callback
1258 function setCallbackURL($url)
1260 return $this->_callback_url
= $url;
1264 * This method is called by CASClient::CASClient() when running in callback
1265 * mode. It stores the PGT and its PGT Iou, prints its output and halts.
1271 phpCAS
::traceBegin();
1272 $this->printHTMLHeader('phpCAS callback');
1273 $pgt_iou = $_GET['pgtIou'];
1274 $pgt = $_GET['pgtId'];
1275 phpCAS
::trace('Storing PGT `'.$pgt.'\' (id=`'.$pgt_iou.'\')');
1276 echo '<p>Storing PGT `'.$pgt.'\' (id=`'.$pgt_iou.'\').</p>';
1277 $this->storePGT($pgt,$pgt_iou);
1278 $this->printHTMLFooter();
1279 phpCAS
::traceExit();
1284 // ########################################################################
1286 // ########################################################################
1288 * @addtogroup internalPGTStorage
1293 * an instance of a class inheriting of PGTStorage, used to deal with PGT
1294 * storage. Created by CASClient::setPGTStorageFile() or CASClient::setPGTStorageDB(), used
1295 * by CASClient::setPGTStorageFile(), CASClient::setPGTStorageDB() and CASClient::initPGTStorage().
1300 var $_pgt_storage = null;
1303 * This method is used to initialize the storage of PGT's.
1308 function initPGTStorage()
1310 // if no SetPGTStorageXxx() has been used, default to file
1311 if ( !is_object($this->_pgt_storage
) ) {
1312 $this->setPGTStorageFile();
1315 // initializes the storage
1316 $this->_pgt_storage
->init();
1320 * This method stores a PGT. Halts on error.
1322 * @param $pgt the PGT to store
1323 * @param $pgt_iou its corresponding Iou
1327 function storePGT($pgt,$pgt_iou)
1329 // ensure that storage is initialized
1330 $this->initPGTStorage();
1333 $this->_pgt_storage
->write($pgt,$pgt_iou);
1337 * This method reads a PGT from its Iou and deletes the corresponding storage entry.
1339 * @param $pgt_iou the PGT Iou
1341 * @return The PGT corresponding to the Iou, FALSE when not found.
1345 function loadPGT($pgt_iou)
1347 // ensure that storage is initialized
1348 $this->initPGTStorage();
1351 return $this->_pgt_storage
->read($pgt_iou);
1355 * This method is used to tell phpCAS to store the response of the
1356 * CAS server to PGT requests onto the filesystem.
1358 * @param $format the format used to store the PGT's (`plain' and `xml' allowed)
1359 * @param $path the path where the PGT's should be stored
1363 function setPGTStorageFile($format='',
1366 // check that the storage has not already been set
1367 if ( is_object($this->_pgt_storage
) ) {
1368 phpCAS
::error('PGT storage already defined');
1371 // create the storage object
1372 $this->_pgt_storage
= &new PGTStorageFile($this,$format,$path);
1376 * This method is used to tell phpCAS to store the response of the
1377 * CAS server to PGT requests into a database.
1378 * @note The connection to the database is done only when needed.
1379 * As a consequence, bad parameters are detected only when
1380 * initializing PGT storage.
1382 * @param $user the user to access the data with
1383 * @param $password the user's password
1384 * @param $database_type the type of the database hosting the data
1385 * @param $hostname the server hosting the database
1386 * @param $port the port the server is listening on
1387 * @param $database the name of the database
1388 * @param $table the name of the table storing the data
1392 function setPGTStorageDB($user,
1400 // check that the storage has not already been set
1401 if ( is_object($this->_pgt_storage
) ) {
1402 phpCAS
::error('PGT storage already defined');
1405 // warn the user that he should use file storage...
1406 trigger_error('PGT storage into database is an experimental feature, use at your own risk',E_USER_WARNING
);
1408 // create the storage object
1409 $this->_pgt_storage
= & new PGTStorageDB($this,$user,$password,$database_type,$hostname,$port,$database,$table);
1412 // ########################################################################
1414 // ########################################################################
1416 * This method is used to validate a PGT; halt on failure.
1418 * @param $validate_url the URL of the request to the CAS server.
1419 * @param $text_response the response of the CAS server, as is (XML text); result
1420 * of CASClient::validateST() or CASClient::validatePT().
1421 * @param $tree_response the response of the CAS server, as a DOM XML tree; result
1422 * of CASClient::validateST() or CASClient::validatePT().
1424 * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError().
1428 function validatePGT(&$validate_url,$text_response,$tree_response)
1430 phpCAS
::traceBegin();
1431 if ( sizeof($arr = $tree_response->get_elements_by_tagname("proxyGrantingTicket")) == 0) {
1432 phpCAS
::trace('<proxyGrantingTicket> not found');
1433 // authentication succeded, but no PGT Iou was transmitted
1434 $this->authError('Ticket validated but no PGT Iou transmitted',
1436 FALSE/*$no_response*/,
1437 FALSE/*$bad_response*/,
1440 // PGT Iou transmitted, extract it
1441 $pgt_iou = trim($arr[0]->get_content());
1442 $pgt = $this->loadPGT($pgt_iou);
1443 if ( $pgt == FALSE ) {
1445 phpCAS
::trace('could not load PGT');
1447 $this->authError('PGT Iou was transmitted but PGT could not be retrieved',
1449 FALSE/*$no_response*/,
1450 FALSE/*$bad_response*/,
1455 $this->setPGT($pgt);
1457 phpCAS
::traceEnd(TRUE);
1461 // ########################################################################
1463 // ########################################################################
1466 * This method is used to retrieve PT's from the CAS server thanks to a PGT.
1468 * @param $target_service the service to ask for with the PT.
1469 * @param $err_code an error code (PHPCAS_SERVICE_OK on success).
1470 * @param $err_msg an error message (empty on success).
1472 * @return a Proxy Ticket, or FALSE on error.
1476 function retrievePT($target_service,&$err_code,&$err_msg)
1478 phpCAS
::traceBegin();
1480 // by default, $err_msg is set empty and $pt to TRUE. On error, $pt is
1481 // set to false and $err_msg to an error message. At the end, if $pt is FALSE
1482 // and $error_msg is still empty, it is set to 'invalid response' (the most
1483 // commonly encountered error).
1486 // build the URL to retrieve the PT
1487 // $cas_url = $this->getServerProxyURL().'?targetService='.preg_replace('/&/','%26',$target_service).'&pgt='.$this->getPGT();
1488 $cas_url = $this->getServerProxyURL().'?targetService='.urlencode($target_service).'&pgt='.$this->getPGT();
1490 // open and read the URL
1491 if ( !$this->readURL($cas_url,''/*cookies*/,$headers,$cas_response,$err_msg) ) {
1492 phpCAS
::trace('could not open URL \''.$cas_url.'\' to validate ('.$err_msg.')');
1493 $err_code = PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE
;
1494 $err_msg = 'could not retrieve PT (no response from the CAS server)';
1495 phpCAS
::traceEnd(FALSE);
1499 $bad_response = FALSE;
1501 if ( !$bad_response ) {
1502 // read the response of the CAS server into a DOM object
1503 if ( !($dom = @domxml_open_mem
($cas_response))) {
1504 phpCAS
::trace('domxml_open_mem() failed');
1506 $bad_response = TRUE;
1510 if ( !$bad_response ) {
1511 // read the root node of the XML tree
1512 if ( !($root = $dom->document_element()) ) {
1513 phpCAS
::trace('document_element() failed');
1515 $bad_response = TRUE;
1519 if ( !$bad_response ) {
1520 // insure that tag name is 'serviceResponse'
1521 if ( $root->node_name() != 'serviceResponse' ) {
1522 phpCAS
::trace('node_name() failed');
1524 $bad_response = TRUE;
1528 if ( !$bad_response ) {
1529 // look for a proxySuccess tag
1530 if ( sizeof($arr = $root->get_elements_by_tagname("proxySuccess")) != 0) {
1531 // authentication succeded, look for a proxyTicket tag
1532 if ( sizeof($arr = $root->get_elements_by_tagname("proxyTicket")) != 0) {
1533 $err_code = PHPCAS_SERVICE_OK
;
1535 phpCAS
::trace('original PT: '.trim($arr[0]->get_content()));
1536 $pt = trim($arr[0]->get_content());
1537 phpCAS
::traceEnd($pt);
1540 phpCAS
::trace('<proxySuccess> was found, but not <proxyTicket>');
1543 // look for a proxyFailure tag
1544 else if ( sizeof($arr = $root->get_elements_by_tagname("proxyFailure")) != 0) {
1545 // authentication failed, extract the error
1546 $err_code = PHPCAS_SERVICE_PT_FAILURE
;
1547 $err_msg = 'PT retrieving failed (code=`'
1548 .$arr[0]->get_attribute('code')
1550 .trim($arr[0]->get_content())
1552 phpCAS
::traceEnd(FALSE);
1555 phpCAS
::trace('neither <proxySuccess> nor <proxyFailure> found');
1559 // at this step, we are sure that the response of the CAS server was ill-formed
1560 $err_code = PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE
;
1561 $err_msg = 'Invalid response from the CAS server (response=`'.$cas_response.'\')';
1563 phpCAS
::traceEnd(FALSE);
1567 // ########################################################################
1568 // ACCESS TO EXTERNAL SERVICES
1569 // ########################################################################
1572 * This method is used to acces a remote URL.
1574 * @param $url the URL to access.
1575 * @param $cookies an array containing cookies strings such as 'name=val'
1576 * @param $headers an array containing the HTTP header lines of the response
1577 * (an empty array on failure).
1578 * @param $body the body of the response, as a string (empty on failure).
1579 * @param $err_msg an error message, filled on failure.
1581 * @return TRUE on success, FALSE otherwise (in this later case, $err_msg
1582 * contains an error message).
1586 function readURL($url,$cookies,&$headers,&$body,&$err_msg)
1588 phpCAS
::traceBegin();
1595 // initialize the CURL session
1596 $ch = curl_init($url);
1598 // verify the the server's certificate corresponds to its name
1599 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, 1);
1600 // but do not verify the certificate itself
1601 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, 0);
1603 // return the CURL output into a variable
1604 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
1605 // include the HTTP header with the body
1606 curl_setopt($ch, CURLOPT_HEADER
, 1);
1607 // add cookies headers
1608 if ( is_array($cookies) ) {
1609 curl_setopt($ch,CURLOPT_COOKIE
,implode(';',$cookies));
1611 // perform the query
1612 $buf = curl_exec ($ch);
1613 if ( $buf === FALSE ) {
1614 phpCAS
::trace('cur_exec() failed');
1615 $err_msg = 'CURL error #'.curl_errno($ch).': '.curl_error($ch);
1616 // close the CURL session
1620 // close the CURL session
1623 // find the end of the headers
1624 // note: strpos($str,"\n\r\n\r") does not work (?)
1626 for ($i=0; $i<strlen($buf); $i++
) {
1627 if ( $buf[$i] == chr(13) )
1628 if ( $buf[$i+
1] == chr(10) )
1629 if ( $buf[$i+
2] == chr(13) )
1630 if ( $buf[$i+
3] == chr(10) ) {
1637 if ( $pos === FALSE ) {
1638 // end of header not found
1639 $err_msg = 'no header found';
1640 phpCAS
::trace($err_msg);
1643 // extract headers into an array
1644 $headers = preg_split ("/[\n\r]+/",substr($buf,0,$pos));
1645 // extract body into a string
1646 $body = substr($buf,$pos+
4);
1650 phpCAS
::traceEnd($res);
1655 * This method is used to access an HTTP[S] service.
1657 * @param $url the service to access.
1658 * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on
1659 * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE,
1660 * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE.
1661 * @param $output the output of the service (also used to give an error
1662 * message on failure).
1664 * @return TRUE on success, FALSE otherwise (in this later case, $err_code
1665 * gives the reason why it failed and $output contains an error message).
1669 function serviceWeb($url,&$err_code,&$output)
1671 phpCAS
::traceBegin();
1672 // at first retrieve a PT
1673 $pt = $this->retrievePT($url,$err_code,$output);
1677 // test if PT was retrieved correctly
1679 // note: $err_code and $err_msg are filled by CASClient::retrievePT()
1680 phpCAS
::trace('PT was not retrieved correctly');
1683 // add cookies if necessary
1684 if ( is_array($_SESSION['phpCAS']['services'][$url]['cookies']) ) {
1685 foreach ( $_SESSION['phpCAS']['services'][$url]['cookies'] as $name => $val ) {
1686 $cookies[] = $name.'='.$val;
1690 // build the URL including the PT
1691 if ( strstr($url,'?') === FALSE ) {
1692 $service_url = $url.'?ticket='.$pt;
1694 $service_url = $url.'&ticket='.$pt;
1697 phpCAS
::trace('reading URL`'.$service_url.'\'');
1698 if ( !$this->readURL($service_url,$cookies,$headers,$output,$err_msg) ) {
1699 phpCAS
::trace('could not read URL`'.$service_url.'\'');
1700 $err_code = PHPCAS_SERVICE_NOT_AVAILABLE
;
1701 // give an error message
1702 $output = sprintf($this->getString(CAS_STR_SERVICE_UNAVAILABLE
),
1707 // URL has been fetched, extract the cookies
1708 phpCAS
::trace('URL`'.$service_url.'\' has been read, storing cookies:');
1709 foreach ( $headers as $header ) {
1710 // test if the header is a cookie
1711 if ( preg_match('/^Set-Cookie:/',$header) ) {
1712 // the header is a cookie, remove the beginning
1713 $header_val = preg_replace('/^Set-Cookie: */','',$header);
1714 // extract interesting information
1715 $name_val = strtok($header_val,'; ');
1716 // extract the name and the value of the cookie
1717 $cookie_name = strtok($name_val,'=');
1718 $cookie_val = strtok('=');
1720 $_SESSION['phpCAS']['services'][$url]['cookies'][$cookie_name] = $cookie_val;
1721 phpCAS
::trace($cookie_name.' -> '.$cookie_val);
1727 phpCAS
::traceEnd($res);
1732 * This method is used to access an IMAP/POP3/NNTP service.
1734 * @param $url a string giving the URL of the service, including the mailing box
1735 * for IMAP URLs, as accepted by imap_open().
1736 * @param $flags options given to imap_open().
1737 * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on
1738 * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE,
1739 * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE.
1740 * @param $err_msg an error message on failure
1741 * @param $pt the Proxy Ticket (PT) retrieved from the CAS server to access the URL
1742 * on success, FALSE on error).
1744 * @return an IMAP stream on success, FALSE otherwise (in this later case, $err_code
1745 * gives the reason why it failed and $err_msg contains an error message).
1749 function serviceMail($url,$flags,&$err_code,&$err_msg,&$pt)
1751 phpCAS
::traceBegin();
1752 // at first retrieve a PT
1753 $pt = $this->retrievePT($target_service,$err_code,$output);
1757 // test if PT was retrieved correctly
1759 // note: $err_code and $err_msg are filled by CASClient::retrievePT()
1760 phpCAS
::trace('PT was not retrieved correctly');
1762 phpCAS
::trace('opening IMAP URL `'.$url.'\'...');
1763 $stream = @imap_open
($url,$this->getUser(),$pt,$flags);
1765 phpCAS
::trace('could not open URL');
1766 $err_code = PHPCAS_SERVICE_NOT_AVAILABLE
;
1767 // give an error message
1768 $err_msg = sprintf($this->getString(CAS_STR_SERVICE_UNAVAILABLE
),
1770 var_export(imap_errors(),TRUE));
1774 phpCAS
::trace('ok');
1778 phpCAS
::traceEnd($stream);
1784 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1786 // XX PROXIED CLIENT FEATURES (CAS 2.0) XX
1788 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1790 // ########################################################################
1792 // ########################################################################
1794 * @addtogroup internalProxied
1799 * the Proxy Ticket provided in the URL of the request if present
1800 * (empty otherwise). Written by CASClient::CASClient(), read by
1801 * CASClient::getPT() and CASClient::hasPGT().
1809 * This method returns the Proxy Ticket provided in the URL of the request.
1810 * @return The proxy ticket.
1815 return 'ST'.substr($this->_pt
, 2);
1819 * This method stores the Proxy Ticket.
1820 * @param $pt The Proxy Ticket.
1824 { $this->_pt
= $pt; }
1827 * This method tells if a Proxy Ticket was stored.
1828 * @return TRUE if a Proxy Ticket has been stored.
1832 { return !empty($this->_pt
); }
1835 // ########################################################################
1837 // ########################################################################
1839 * @addtogroup internalProxied
1844 * This method is used to validate a PT; halt on failure
1846 * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError().
1850 function validatePT(&$validate_url,&$text_response,&$tree_response)
1852 phpCAS
::traceBegin();
1853 // build the URL to validate the ticket
1854 $validate_url = $this->getServerProxyValidateURL().'&ticket='.$this->getPT();
1856 if ( $this->isProxy() ) {
1857 // pass the callback url for CAS proxies
1858 $validate_url .= '&pgtUrl='.$this->getCallbackURL();
1861 // open and read the URL
1862 if ( !$this->readURL($validate_url,''/*cookies*/,$headers,$text_response,$err_msg) ) {
1863 phpCAS
::trace('could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')');
1864 $this->authError('PT not validated',
1866 TRUE/*$no_response*/);
1869 // read the response of the CAS server into a DOM object
1870 if ( !($dom = domxml_open_mem($text_response))) {
1872 $this->authError('PT not validated',
1874 FALSE/*$no_response*/,
1875 TRUE/*$bad_response*/,
1878 // read the root node of the XML tree
1879 if ( !($tree_response = $dom->document_element()) ) {
1881 $this->authError('PT not validated',
1883 FALSE/*$no_response*/,
1884 TRUE/*$bad_response*/,
1887 // insure that tag name is 'serviceResponse'
1888 if ( $tree_response->node_name() != 'serviceResponse' ) {
1890 $this->authError('PT not validated',
1892 FALSE/*$no_response*/,
1893 TRUE/*$bad_response*/,
1896 if ( sizeof($arr = $tree_response->get_elements_by_tagname("authenticationSuccess")) != 0) {
1897 // authentication succeded, extract the user name
1898 if ( sizeof($arr = $tree_response->get_elements_by_tagname("user")) == 0) {
1899 // no user specified => error
1900 $this->authError('PT not validated',
1902 FALSE/*$no_response*/,
1903 TRUE/*$bad_response*/,
1906 $this->setUser(trim($arr[0]->get_content()));
1908 } else if ( sizeof($arr = $tree_response->get_elements_by_tagname("authenticationFailure")) != 0) {
1909 // authentication succeded, extract the error code and message
1910 $this->authError('PT not validated',
1912 FALSE/*$no_response*/,
1913 FALSE/*$bad_response*/,
1915 $arr[0]->get_attribute('code')/*$err_code*/,
1916 trim($arr[0]->get_content())/*$err_msg*/);
1918 $this->authError('PT not validated',
1920 FALSE/*$no_response*/,
1921 TRUE/*$bad_response*/,
1925 // at this step, PT has been validated and $this->_user has been set,
1927 phpCAS
::traceEnd(TRUE);
1933 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1937 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1940 * @addtogroup internalMisc
1944 // ########################################################################
1946 // ########################################################################
1948 * the URL of the current request (without any ticket CGI parameter). Written
1949 * and read by CASClient::getURL().
1957 * This method returns the URL of the current request (without any ticket
1966 phpCAS
::traceBegin();
1967 // the URL is built when needed only
1968 if ( empty($this->_url
) ) {
1970 // remove the ticket if present in the URL
1971 $final_uri = ($this->isHttps()) ?
'https' : 'http';
1972 $final_uri .= '://';
1973 /* replaced by Julien Marchal - v0.4.6
1974 * $this->_url .= $_SERVER['SERVER_NAME'];
1976 if(empty($_SERVER['HTTP_X_FORWARDED_SERVER'])){
1977 /* replaced by teedog - v0.4.12
1978 * $this->_url .= $_SERVER['SERVER_NAME'];
1980 if (empty($_SERVER['SERVER_NAME'])) {
1981 $server_name = $_SERVER['HTTP_HOST'];
1983 $server_name = $_SERVER['SERVER_NAME'];
1986 $server_name = $_SERVER['HTTP_X_FORWARDED_SERVER'];
1988 $final_uri .= $server_name;
1989 if (!strpos($server_name, ':')) {
1990 if ( ($this->isHttps() && $_SERVER['SERVER_PORT']!=443)
1991 ||
(!$this->isHttps() && $_SERVER['SERVER_PORT']!=80) ) {
1993 $final_uri .= $_SERVER['SERVER_PORT'];
1997 $final_uri .= strtok($_SERVER['REQUEST_URI'],"?");
1998 $cgi_params = '?'.strtok("?");
1999 // remove the ticket if present in the CGI parameters
2000 $cgi_params = preg_replace('/&ticket=[^&]*/','',$cgi_params);
2001 $cgi_params = preg_replace('/\?ticket=[^&;]*/','?',$cgi_params);
2002 $cgi_params = preg_replace('/\?%26/','?',$cgi_params);
2003 $cgi_params = preg_replace('/\?&/','?',$cgi_params);
2004 $cgi_params = preg_replace('/\?$/','',$cgi_params);
2005 $final_uri .= $cgi_params;
2006 $this->setURL($final_uri);
2008 phpCAS
::traceEnd($this->_url
);
2013 * This method sets the URL of the current request
2015 * @param $url url to set for service
2019 function setURL($url)
2024 // ########################################################################
2025 // AUTHENTICATION ERROR HANDLING
2026 // ########################################################################
2028 * This method is used to print the HTML output when the user was not authenticated.
2030 * @param $failure the failure that occured
2031 * @param $cas_url the URL the CAS server was asked for
2032 * @param $no_response the response from the CAS server (other
2033 * parameters are ignored if TRUE)
2034 * @param $bad_response bad response from the CAS server ($err_code
2035 * and $err_msg ignored if TRUE)
2036 * @param $cas_response the response of the CAS server
2037 * @param $err_code the error code given by the CAS server
2038 * @param $err_msg the error message given by the CAS server
2042 function authError($failure,$cas_url,$no_response,$bad_response='',$cas_response='',$err_code='',$err_msg='')
2044 phpCAS
::traceBegin();
2046 $this->printHTMLHeader($this->getString(CAS_STR_AUTHENTICATION_FAILED
));
2047 printf($this->getString(CAS_STR_YOU_WERE_NOT_AUTHENTICATED
),$this->getURL(),$_SERVER['SERVER_ADMIN']);
2048 phpCAS
::trace('CAS URL: '.$cas_url);
2049 phpCAS
::trace('Authentication failure: '.$failure);
2050 if ( $no_response ) {
2051 phpCAS
::trace('Reason: no response from the CAS server');
2053 if ( $bad_response ) {
2054 phpCAS
::trace('Reason: bad response from the CAS server');
2056 switch ($this->getServerVersion()) {
2057 case CAS_VERSION_1_0
:
2058 phpCAS
::trace('Reason: CAS error');
2060 case CAS_VERSION_2_0
:
2061 if ( empty($err_code) )
2062 phpCAS
::trace('Reason: no CAS error');
2064 phpCAS
::trace('Reason: ['.$err_code.'] CAS error: '.$err_msg);
2068 phpCAS
::trace('CAS response: '.$cas_response);
2070 $this->printHTMLFooter();
2071 phpCAS
::traceExit();