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
318 * @param $renew true to force the authentication with the CAS server
319 * NOTE : It is recommended that CAS implementations ignore the
320 "gateway" parameter if "renew" is set
324 function getServerLoginURL($gateway=false,$renew=false) {
325 phpCAS::traceBegin();
326 // the URL is build only when needed
327 if ( empty($this->_server['login_url']) ) {
328 $this->_server['login_url'] = $this->getServerBaseURL();
329 $this->_server['login_url'] .= 'login?service=';
330 // $this->_server['login_url'] .= preg_replace('/&/','%26',$this->getURL());
331 $this->_server['login_url'] .= urlencode($this->getURL());
333 // It is recommended that when the "renew" parameter is set, its value be "true"
334 $this->_server['login_url'] .= '&renew=true';
335 } elseif ($gateway) {
336 // It is recommended that when the "gateway" parameter is set, its value be "true"
337 $this->_server['login_url'] .= '&gateway=true';
340 phpCAS::traceEnd($this->_server['login_url']);
341 return $this->_server['login_url'];
345 * This method sets the login URL of the CAS server.
346 * @param $url the login URL
348 * @since 0.4.21 by Wyman Chan
350 function setServerLoginURL($url)
352 return $this->_server['login_url'] = $url;
356 * This method is used to retrieve the service validating URL of the CAS server.
360 function getServerServiceValidateURL()
362 // the URL is build only when needed
363 if ( empty($this->_server['service_validate_url']) ) {
364 switch ($this->getServerVersion()) {
365 case CAS_VERSION_1_0:
366 $this->_server['service_validate_url'] = $this->getServerBaseURL().'validate';
368 case CAS_VERSION_2_0:
369 $this->_server['service_validate_url'] = $this->getServerBaseURL().'serviceValidate';
373 // return $this->_server['service_validate_url'].'?service='.preg_replace('/&/','%26',$this->getURL());
374 return $this->_server['service_validate_url'].'?service='.urlencode($this->getURL());
378 * This method is used to retrieve the proxy validating URL of the CAS server.
382 function getServerProxyValidateURL()
384 // the URL is build only when needed
385 if ( empty($this->_server['proxy_validate_url']) ) {
386 switch ($this->getServerVersion()) {
387 case CAS_VERSION_1_0:
388 $this->_server['proxy_validate_url'] = '';
390 case CAS_VERSION_2_0:
391 $this->_server['proxy_validate_url'] = $this->getServerBaseURL().'proxyValidate';
395 // return $this->_server['proxy_validate_url'].'?service='.preg_replace('/&/','%26',$this->getURL());
396 return $this->_server['proxy_validate_url'].'?service='.urlencode($this->getURL());
400 * This method is used to retrieve the proxy URL of the CAS server.
404 function getServerProxyURL()
406 // the URL is build only when needed
407 if ( empty($this->_server['proxy_url']) ) {
408 switch ($this->getServerVersion()) {
409 case CAS_VERSION_1_0:
410 $this->_server['proxy_url'] = '';
412 case CAS_VERSION_2_0:
413 $this->_server['proxy_url'] = $this->getServerBaseURL().'proxy';
417 return $this->_server['proxy_url'];
421 * This method is used to retrieve the logout URL of the CAS server.
425 function getServerLogoutURL()
427 // the URL is build only when needed
428 if ( empty($this->_server['logout_url']) ) {
429 $this->_server['logout_url'] = $this->getServerBaseURL().'logout';
431 return $this->_server['logout_url'];
435 * This method sets the logout URL of the CAS server.
436 * @param $url the logout URL
438 * @since 0.4.21 by Wyman Chan
440 function setServerLogoutURL($url)
442 return $this->_server['logout_url'] = $url;
446 * An array to store extra curl options.
448 var $_curl_options = array();
451 * This method is used to set additional user curl options.
453 function setExtraCurlOption($key, $value)
455 $this->_curl_options[$key] = $value;
459 * This method checks to see if the request is secured via HTTPS
460 * @return true if https, false otherwise
464 //if ( isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ) {
466 if ( isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
473 // ########################################################################
475 // ########################################################################
477 * CASClient constructor.
479 * @param $server_version the version of the CAS server
480 * @param $proxy TRUE if the CAS client is a CAS proxy, FALSE otherwise
481 * @param $server_hostname the hostname of the CAS server
482 * @param $server_port the port the CAS server is running on
483 * @param $server_uri the URI the CAS server is responding on
484 * @param $start_session Have phpCAS start PHP sessions (default true)
486 * @return a newly created CASClient object
496 $start_session = true) {
498 phpCAS::traceBegin();
500 if (!$this->isLogoutRequest() && !empty($_GET['ticket']) && $start_session) {
501 // copy old session vars and destroy the current session
502 if (!isset($_SESSION)) {
505 $old_session = $_SESSION;
507 // set up a new session, of name based on the ticket
508 $session_id = preg_replace('/[^\w]/','',$_GET['ticket']);
509 phpCAS::LOG("Session ID: " . $session_id);
510 session_id($session_id);
511 if (!isset($_SESSION)) {
514 // restore old session vars
515 $_SESSION = $old_session;
516 // Redirect to location without ticket.
517 header('Location: '.$this->getURL());
520 //activate session mechanism if desired
521 if (!$this->isLogoutRequest() && $start_session) {
525 $this->_proxy = $proxy;
528 switch ($server_version) {
529 case CAS_VERSION_1_0:
530 if ( $this->isProxy() )
531 phpCAS::error('CAS proxies are not supported in CAS '
534 case CAS_VERSION_2_0:
537 phpCAS::error('this version of CAS (`'
539 .'\') is not supported by phpCAS '
540 .phpCAS::getVersion());
542 $this->_server['version'] = $server_version;
545 if ( empty($server_hostname)
546 || !preg_match('/[\.\d\-abcdefghijklmnopqrstuvwxyz]*/',$server_hostname) ) {
547 phpCAS::error('bad CAS server hostname (`'.$server_hostname.'\')');
549 $this->_server['hostname'] = $server_hostname;
552 if ( $server_port == 0
553 || !is_int($server_port) ) {
554 phpCAS::error('bad CAS server port (`'.$server_hostname.'\')');
556 $this->_server['port'] = $server_port;
559 if ( !preg_match('/[\.\d\-_abcdefghijklmnopqrstuvwxyz\/]*/',$server_uri) ) {
560 phpCAS::error('bad CAS server URI (`'.$server_uri.'\')');
562 //add leading and trailing `/' and remove doubles
563 $server_uri = preg_replace('/\/\//','/','/'.$server_uri.'/');
564 $this->_server['uri'] = $server_uri;
566 //set to callback mode if PgtIou and PgtId CGI GET parameters are provided
567 if ( $this->isProxy() ) {
568 $this->setCallbackMode(!empty($_GET['pgtIou'])&&!empty($_GET['pgtId']));
571 if ( $this->isCallbackMode() ) {
572 //callback mode: check that phpCAS is secured
573 if ( !$this->isHttps() ) {
574 phpCAS::error('CAS proxies must be secured to use phpCAS; PGT\'s will not be received from the CAS server');
577 //normal mode: get ticket and remove it from CGI parameters for developpers
578 $ticket = (isset($_GET['ticket']) ? $_GET['ticket'] : null);
579 switch ($this->getServerVersion()) {
580 case CAS_VERSION_1_0: // check for a Service Ticket
581 if( preg_match('/^ST-/',$ticket) ) {
582 phpCAS::trace('ST \''.$ticket.'\' found');
584 $this->setST($ticket);
585 //ticket has been taken into account, unset it to hide it to applications
586 unset($_GET['ticket']);
587 } else if ( !empty($ticket) ) {
588 //ill-formed ticket, halt
589 phpCAS::error('ill-formed ticket found in the URL (ticket=`'.htmlentities($ticket).'\')');
592 case CAS_VERSION_2_0: // check for a Service or Proxy Ticket
593 if( preg_match('/^[SP]T-/',$ticket) ) {
594 phpCAS::trace('ST or PT \''.$ticket.'\' found');
595 $this->setPT($ticket);
596 unset($_GET['ticket']);
597 } else if ( !empty($ticket) ) {
598 //ill-formed ticket, halt
599 phpCAS::error('ill-formed ticket found in the URL (ticket=`'.htmlentities($ticket).'\')');
609 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
611 // XX AUTHENTICATION XX
613 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
616 * @addtogroup internalAuthentication
621 * The Authenticated user. Written by CASClient::setUser(), read by CASClient::getUser().
622 * @attention client applications should use phpCAS::getUser().
630 * This method sets the CAS user's login name.
632 * @param $user the login name of the authenticated user.
636 function setUser($user)
638 $this->_user = $user;
642 * This method returns the CAS user's login name.
643 * @warning should be called only after CASClient::forceAuthentication() or
644 * CASClient::isAuthenticated(), otherwise halt with an error.
646 * @return the login name of the authenticated user
650 if ( empty($this->_user) ) {
651 phpCAS::error('this method should be used only after '.__CLASS__.'::forceAuthentication() or '.__CLASS__.'::isAuthenticated()');
657 * This method is called to renew the authentication of the user
658 * If the user is authenticated, renew the connection
659 * If not, redirect to CAS
662 function renewAuthentication(){
663 phpCAS::traceBegin();
664 // Either way, the user is authenticated by CAS
665 if( isset( $_SESSION['phpCAS']['auth_checked'] ) )
666 unset($_SESSION['phpCAS']['auth_checked']);
667 if ( $this->isAuthenticated() ) {
668 phpCAS::trace('user already authenticated; renew');
669 $this->redirectToCas(false,true);
671 $this->redirectToCas();
677 * This method is called to be sure that the user is authenticated. When not
678 * authenticated, halt by redirecting to the CAS server; otherwise return TRUE.
679 * @return TRUE when the user is authenticated; otherwise halt.
682 function forceAuthentication()
684 phpCAS::traceBegin();
686 if ( $this->isAuthenticated() ) {
687 // the user is authenticated, nothing to be done.
688 phpCAS::trace('no need to authenticate');
691 // the user is not authenticated, redirect to the CAS server
692 if (isset($_SESSION['phpCAS']['auth_checked'])) {
693 unset($_SESSION['phpCAS']['auth_checked']);
695 $this->redirectToCas(FALSE/* no gateway */);
699 phpCAS::traceEnd($res);
704 * An integer that gives the number of times authentication will be cached before rechecked.
709 var $_cache_times_for_auth_recheck = 0;
712 * Set the number of times authentication will be cached before rechecked.
714 * @param $n an integer.
718 function setCacheTimesForAuthRecheck($n)
720 $this->_cache_times_for_auth_recheck = $n;
724 * This method is called to check whether the user is authenticated or not.
725 * @return TRUE when the user is authenticated, FALSE otherwise.
728 function checkAuthentication()
730 phpCAS::traceBegin();
732 if ( $this->isAuthenticated() ) {
733 phpCAS::trace('user is authenticated');
735 } else if (isset($_SESSION['phpCAS']['auth_checked'])) {
736 // the previous request has redirected the client to the CAS server with gateway=true
737 unset($_SESSION['phpCAS']['auth_checked']);
740 // $_SESSION['phpCAS']['auth_checked'] = true;
741 // $this->redirectToCas(TRUE/* gateway */);
744 // avoid a check against CAS on every request
745 if (! isset($_SESSION['phpCAS']['unauth_count']) )
746 $_SESSION['phpCAS']['unauth_count'] = -2; // uninitialized
748 if (($_SESSION['phpCAS']['unauth_count'] != -2 && $this->_cache_times_for_auth_recheck == -1)
749 || ($_SESSION['phpCAS']['unauth_count'] >= 0 && $_SESSION['phpCAS']['unauth_count'] < $this->_cache_times_for_auth_recheck))
753 if ($this->_cache_times_for_auth_recheck != -1)
755 $_SESSION['phpCAS']['unauth_count']++;
756 phpCAS::trace('user is not authenticated (cached for '.$_SESSION['phpCAS']['unauth_count'].' times of '.$this->_cache_times_for_auth_recheck.')');
760 phpCAS::trace('user is not authenticated (cached for until login pressed)');
765 $_SESSION['phpCAS']['unauth_count'] = 0;
766 $_SESSION['phpCAS']['auth_checked'] = true;
767 phpCAS::trace('user is not authenticated (cache reset)');
768 $this->redirectToCas(TRUE/* gateway */);
773 phpCAS::traceEnd($res);
778 * This method is called to check if the user is authenticated (previously or by
779 * tickets given in the URL).
781 * @return TRUE when the user is authenticated.
785 function isAuthenticated()
787 phpCAS::traceBegin();
791 if ( $this->wasPreviouslyAuthenticated() ) {
792 // the user has already (previously during the session) been
793 // authenticated, nothing to be done.
794 phpCAS::trace('user was already authenticated, no need to look for tickets');
797 elseif ( $this->hasST() ) {
798 // if a Service Ticket was given, validate it
799 phpCAS::trace('ST `'.$this->getST().'\' is present');
800 $this->validateST($validate_url,$text_response,$tree_response); // if it fails, it halts
801 phpCAS::trace('ST `'.$this->getST().'\' was validated');
802 if ( $this->isProxy() ) {
803 $this->validatePGT($validate_url,$text_response,$tree_response); // idem
804 phpCAS::trace('PGT `'.$this->getPGT().'\' was validated');
805 $_SESSION['phpCAS']['pgt'] = $this->getPGT();
807 $_SESSION['phpCAS']['user'] = $this->getUser();
810 elseif ( $this->hasPT() ) {
811 // if a Proxy Ticket was given, validate it
812 phpCAS::trace('PT `'.$this->getPT().'\' is present');
813 $this->validatePT($validate_url,$text_response,$tree_response); // note: if it fails, it halts
814 phpCAS::trace('PT `'.$this->getPT().'\' was validated');
815 if ( $this->isProxy() ) {
816 $this->validatePGT($validate_url,$text_response,$tree_response); // idem
817 phpCAS::trace('PGT `'.$this->getPGT().'\' was validated');
818 $_SESSION['phpCAS']['pgt'] = $this->getPGT();
820 $_SESSION['phpCAS']['user'] = $this->getUser();
824 // no ticket given, not authenticated
825 phpCAS::trace('no ticket found');
828 phpCAS::traceEnd($res);
833 * This method tells if the current session is authenticated.
834 * @return true if authenticated based soley on $_SESSION variable
835 * @since 0.4.22 by Brendan Arnold
837 function isSessionAuthenticated ()
839 return !empty($_SESSION['phpCAS']['user']);
843 * This method tells if the user has already been (previously) authenticated
844 * by looking into the session variables.
846 * @note This function switches to callback mode when needed.
848 * @return TRUE when the user has already been authenticated; FALSE otherwise.
852 function wasPreviouslyAuthenticated()
854 phpCAS::traceBegin();
856 if ( $this->isCallbackMode() ) {
862 if ( $this->isProxy() ) {
863 // CAS proxy: username and PGT must be present
864 if ( $this->isSessionAuthenticated() && !empty($_SESSION['phpCAS']['pgt']) ) {
865 // authentication already done
866 $this->setUser($_SESSION['phpCAS']['user']);
867 $this->setPGT($_SESSION['phpCAS']['pgt']);
868 phpCAS::trace('user = `'.$_SESSION['phpCAS']['user'].'\', PGT = `'.$_SESSION['phpCAS']['pgt'].'\'');
870 } elseif ( $this->isSessionAuthenticated() && empty($_SESSION['phpCAS']['pgt']) ) {
871 // these two variables should be empty or not empty at the same time
872 phpCAS::trace('username found (`'.$_SESSION['phpCAS']['user'].'\') but PGT is empty');
873 // unset all tickets to enforce authentication
874 unset($_SESSION['phpCAS']);
877 } elseif ( !$this->isSessionAuthenticated() && !empty($_SESSION['phpCAS']['pgt']) ) {
878 // these two variables should be empty or not empty at the same time
879 phpCAS::trace('PGT found (`'.$_SESSION['phpCAS']['pgt'].'\') but username is empty');
880 // unset all tickets to enforce authentication
881 unset($_SESSION['phpCAS']);
885 phpCAS::trace('neither user not PGT found');
888 // `simple' CAS client (not a proxy): username must be present
889 if ( $this->isSessionAuthenticated() ) {
890 // authentication already done
891 $this->setUser($_SESSION['phpCAS']['user']);
892 phpCAS::trace('user = `'.$_SESSION['phpCAS']['user'].'\'');
895 phpCAS::trace('no user found');
899 phpCAS::traceEnd($auth);
904 * This method is used to redirect the client to the CAS server.
905 * It is used by CASClient::forceAuthentication() and CASClient::checkAuthentication().
906 * @param $gateway true to check authentication, false to force it
907 * @param $renew true to force the authentication with the CAS server
910 function redirectToCas($gateway=false,$renew=false){
911 phpCAS::traceBegin();
912 $cas_url = $this->getServerLoginURL($gateway,$renew);
913 header('Location: '.$cas_url);
914 phpCAS::log( "Redirect to : ".$cas_url );
916 $this->printHTMLHeader($this->getString(CAS_STR_AUTHENTICATION_WANTED));
918 printf('<p>'.$this->getString(CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED).'</p>',$cas_url);
919 $this->printHTMLFooter();
925 // * This method is used to logout from CAS.
926 // * @param $url a URL that will be transmitted to the CAS server (to come back to when logged out)
929 // function logout($url = "") {
930 // phpCAS::traceBegin();
931 // $cas_url = $this->getServerLogoutURL();
932 // // v0.4.14 sebastien.gougeon at univ-rennes1.fr
933 // // header('Location: '.$cas_url);
934 // if ( $url != "" ) {
935 // // Adam Moore 1.0.0RC2
936 // $url = '?service=' . $url . '&url=' . $url;
938 // header('Location: '.$cas_url . $url);
940 // session_destroy();
941 // $this->printHTMLHeader($this->getString(CAS_STR_LOGOUT));
942 // printf('<p>'.$this->getString(CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED).'</p>',$cas_url);
943 // $this->printHTMLFooter();
944 // phpCAS::traceExit();
949 * This method is used to logout from CAS.
950 * @params $params an array that contains the optional url and service parameters that will be passed to the CAS server
953 function logout($params) {
954 phpCAS::traceBegin();
955 $cas_url = $this->getServerLogoutURL();
956 $paramSeparator = '?';
957 if (isset($params['url'])) {
958 $cas_url = $cas_url . $paramSeparator . "url=" . urlencode($params['url']);
959 $paramSeparator = '&';
961 if (isset($params['service'])) {
962 $cas_url = $cas_url . $paramSeparator . "service=" . urlencode($params['service']);
964 header('Location: '.$cas_url);
967 $this->printHTMLHeader($this->getString(CAS_STR_LOGOUT));
968 printf('<p>'.$this->getString(CAS_STR_SHOULD_HAVE_BEEN_REDIRECTED).'</p>',$cas_url);
969 $this->printHTMLFooter();
975 * @return true if the current request is a logout request.
978 function isLogoutRequest() {
979 return !empty($_POST['logoutRequest']);
983 * @return true if a logout request is allowed.
986 function isLogoutRequestAllowed() {
990 * This method handles logout requests.
991 * @param $check_client true to check the client bofore handling the request,
992 * false not to perform any access control. True by default.
993 * @param $allowed_clients an array of host names allowed to send logout requests.
994 * By default, only the CAs server (declared in the constructor) will be allowed.
997 function handleLogoutRequests($check_client=true, $allowed_clients=false) {
998 phpCAS::traceBegin();
999 if (!$this->isLogoutRequest()) {
1000 phpCAS::log("Not a logout request");
1004 phpCAS::log("Logout requested");
1005 phpCAS::log("SAML REQUEST: ".$_POST['logoutRequest']);
1006 if ($check_client) {
1007 if (!$allowed_clients) {
1008 $allowed_clients = array( $this->getServerHostname() );
1010 $client_ip = $_SERVER['REMOTE_ADDR'];
1011 $client = gethostbyaddr($client_ip);
1012 phpCAS::log("Client: ".$client);
1014 foreach ($allowed_clients as $allowed_client) {
1015 if ($client == $allowed_client) {
1016 phpCAS::log("Allowed client '".$allowed_client."' matches, logout request is allowed");
1020 phpCAS::log("Allowed client '".$allowed_client."' does not match");
1024 phpCAS::error("Unauthorized logout request from client '".$client."'");
1025 printf("Unauthorized!");
1026 phpCAS::traceExit();
1030 phpCAS::log("No access control set");
1032 // Extract the ticket from the SAML Request
1033 preg_match("|<samlp:SessionIndex>(.*)</samlp:SessionIndex>|", $_POST['logoutRequest'], $tick, PREG_OFFSET_CAPTURE, 3);
1034 $wrappedSamlSessionIndex = preg_replace('|<samlp:SessionIndex>|','',$tick[0][0]);
1035 $ticket2logout = preg_replace('|</samlp:SessionIndex>|','',$wrappedSamlSessionIndex);
1036 phpCAS::log("Ticket to logout: ".$ticket2logout);
1037 $session_id = preg_replace('/[^\w]/','',$ticket2logout);
1038 phpCAS::log("Session id: ".$session_id);
1040 // fix New session ID
1041 session_id($session_id);
1042 $_COOKIE[session_name()]=$session_id;
1043 $_GET[session_name()]=$session_id;
1045 // Overwrite session
1049 printf("Disconnected!");
1050 phpCAS::traceExit();
1056 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1058 // XX BASIC CLIENT FEATURES (CAS 1.0) XX
1060 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1062 // ########################################################################
1064 // ########################################################################
1066 * @addtogroup internalBasic
1071 * the Service Ticket provided in the URL of the request if present
1072 * (empty otherwise). Written by CASClient::CASClient(), read by
1073 * CASClient::getST() and CASClient::hasPGT().
1081 * This method returns the Service Ticket provided in the URL of the request.
1082 * @return The service ticket.
1086 { return $this->_st; }
1089 * This method stores the Service Ticket.
1090 * @param $st The Service Ticket.
1094 { $this->_st = $st; }
1097 * This method tells if a Service Ticket was stored.
1098 * @return TRUE if a Service Ticket has been stored.
1102 { return !empty($this->_st); }
1106 // ########################################################################
1108 // ########################################################################
1110 * @addtogroup internalBasic
1115 * the certificate of the CAS server.
1120 var $_cas_server_cert = '';
1123 * the certificate of the CAS server CA.
1128 var $_cas_server_ca_cert = '';
1131 * Set to true not to validate the CAS server.
1136 var $_no_cas_server_validation = false;
1139 * Set the certificate of the CAS server.
1141 * @param $cert the PEM certificate
1143 function setCasServerCert($cert)
1145 $this->_cas_server_cert = $cert;
1149 * Set the CA certificate of the CAS server.
1151 * @param $cert the PEM certificate of the CA that emited the cert of the server
1153 function setCasServerCACert($cert)
1155 $this->_cas_server_ca_cert = $cert;
1159 * Set no SSL validation for the CAS server.
1161 function setNoCasServerValidation()
1163 $this->_no_cas_server_validation = true;
1167 * This method is used to validate a ST; halt on failure, and sets $validate_url,
1168 * $text_reponse and $tree_response on success. These parameters are used later
1169 * by CASClient::validatePGT() for CAS proxies.
1171 * @param $validate_url the URL of the request to the CAS server.
1172 * @param $text_response the response of the CAS server, as is (XML text).
1173 * @param $tree_response the response of the CAS server, as a DOM XML tree.
1175 * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError().
1179 function validateST($validate_url,&$text_response,&$tree_response)
1181 phpCAS::traceBegin();
1182 // build the URL to validate the ticket
1183 $validate_url = $this->getServerServiceValidateURL().'&ticket='.$this->getST();
1184 if ( $this->isProxy() ) {
1185 // pass the callback url for CAS proxies
1186 $validate_url .= '&pgtUrl='.$this->getCallbackURL();
1189 // open and read the URL
1190 if ( !$this->readURL($validate_url,''/*cookies*/,$headers,$text_response,$err_msg) ) {
1191 phpCAS::trace('could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')');
1192 $this->authError('ST not validated',
1194 TRUE/*$no_response*/);
1197 // analyze the result depending on the version
1198 switch ($this->getServerVersion()) {
1199 case CAS_VERSION_1_0:
1200 if (preg_match('/^no\n/',$text_response)) {
1201 phpCAS::trace('ST has not been validated');
1202 $this->authError('ST not validated',
1204 FALSE/*$no_response*/,
1205 FALSE/*$bad_response*/,
1208 if (!preg_match('/^yes\n/',$text_response)) {
1209 phpCAS::trace('ill-formed response');
1210 $this->authError('ST not validated',
1212 FALSE/*$no_response*/,
1213 TRUE/*$bad_response*/,
1216 // ST has been validated, extract the user name
1217 $arr = preg_split('/\n/',$text_response);
1218 $this->setUser(trim($arr[1]));
1220 case CAS_VERSION_2_0:
1221 // read the response of the CAS server into a DOM object
1222 if ( !($dom = domxml_open_mem($text_response))) {
1223 phpCAS::trace('domxml_open_mem() failed');
1224 $this->authError('ST not validated',
1226 FALSE/*$no_response*/,
1227 TRUE/*$bad_response*/,
1230 // read the root node of the XML tree
1231 if ( !($tree_response = $dom->document_element()) ) {
1232 phpCAS::trace('document_element() failed');
1233 $this->authError('ST not validated',
1235 FALSE/*$no_response*/,
1236 TRUE/*$bad_response*/,
1239 // insure that tag name is 'serviceResponse'
1240 if ( $tree_response->node_name() != 'serviceResponse' ) {
1241 phpCAS::trace('bad XML root node (should be `serviceResponse\' instead of `'.$tree_response->node_name().'\'');
1242 $this->authError('ST not validated',
1244 FALSE/*$no_response*/,
1245 TRUE/*$bad_response*/,
1248 if ( sizeof($success_elements = $tree_response->get_elements_by_tagname("authenticationSuccess")) != 0) {
1249 // authentication succeded, extract the user name
1250 if ( sizeof($user_elements = $success_elements[0]->get_elements_by_tagname("user")) == 0) {
1251 phpCAS::trace('<authenticationSuccess> found, but no <user>');
1252 $this->authError('ST not validated',
1254 FALSE/*$no_response*/,
1255 TRUE/*$bad_response*/,
1258 $user = trim($user_elements[0]->get_content());
1259 phpCAS::trace('user = `'.$user);
1260 $this->setUser($user);
1262 } else if ( sizeof($failure_elements = $tree_response->get_elements_by_tagname("authenticationFailure")) != 0) {
1263 phpCAS::trace('<authenticationFailure> found');
1264 // authentication failed, extract the error code and message
1265 $this->authError('ST not validated',
1267 FALSE/*$no_response*/,
1268 FALSE/*$bad_response*/,
1270 $failure_elements[0]->get_attribute('code')/*$err_code*/,
1271 trim($failure_elements[0]->get_content())/*$err_msg*/);
1273 phpCAS::trace('neither <authenticationSuccess> nor <authenticationFailure> found');
1274 $this->authError('ST not validated',
1276 FALSE/*$no_response*/,
1277 TRUE/*$bad_response*/,
1283 // at this step, ST has been validated and $this->_user has been set,
1284 phpCAS::traceEnd(TRUE);
1290 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1292 // XX PROXY FEATURES (CAS 2.0) XX
1294 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1296 // ########################################################################
1298 // ########################################################################
1300 * @addtogroup internalProxy
1305 * A boolean telling if the client is a CAS proxy or not. Written by CASClient::CASClient(),
1306 * read by CASClient::isProxy().
1313 * Tells if a CAS client is a CAS proxy or not
1315 * @return TRUE when the CAS client is a CAs proxy, FALSE otherwise
1321 return $this->_proxy;
1325 // ########################################################################
1327 // ########################################################################
1329 * @addtogroup internalProxy
1334 * the Proxy Grnting Ticket given by the CAS server (empty otherwise).
1335 * Written by CASClient::setPGT(), read by CASClient::getPGT() and CASClient::hasPGT().
1343 * This method returns the Proxy Granting Ticket given by the CAS server.
1344 * @return The Proxy Granting Ticket.
1348 { return $this->_pgt; }
1351 * This method stores the Proxy Granting Ticket.
1352 * @param $pgt The Proxy Granting Ticket.
1355 function setPGT($pgt)
1356 { $this->_pgt = $pgt; }
1359 * This method tells if a Proxy Granting Ticket was stored.
1360 * @return TRUE if a Proxy Granting Ticket has been stored.
1364 { return !empty($this->_pgt); }
1368 // ########################################################################
1370 // ########################################################################
1372 * @addtogroup internalCallback
1376 * each PHP script using phpCAS in proxy mode is its own callback to get the
1377 * PGT back from the CAS server. callback_mode is detected by the constructor
1378 * thanks to the GET parameters.
1382 * a boolean to know if the CAS client is running in callback mode. Written by
1383 * CASClient::setCallBackMode(), read by CASClient::isCallbackMode().
1388 var $_callback_mode = FALSE;
1391 * This method sets/unsets callback mode.
1393 * @param $callback_mode TRUE to set callback mode, FALSE otherwise.
1397 function setCallbackMode($callback_mode)
1399 $this->_callback_mode = $callback_mode;
1403 * This method returns TRUE when the CAs client is running i callback mode,
1406 * @return A boolean.
1410 function isCallbackMode()
1412 return $this->_callback_mode;
1416 * the URL that should be used for the PGT callback (in fact the URL of the
1417 * current request without any CGI parameter). Written and read by
1418 * CASClient::getCallbackURL().
1423 var $_callback_url = '';
1426 * This method returns the URL that should be used for the PGT callback (in
1427 * fact the URL of the current request without any CGI parameter, except if
1428 * phpCAS::setFixedCallbackURL() was used).
1430 * @return The callback URL
1434 function getCallbackURL()
1436 // the URL is built when needed only
1437 if ( empty($this->_callback_url) ) {
1439 // remove the ticket if present in the URL
1440 $final_uri = 'https://';
1441 /* replaced by Julien Marchal - v0.4.6
1442 * $this->uri .= $_SERVER['SERVER_NAME'];
1444 if(empty($_SERVER['HTTP_X_FORWARDED_SERVER'])){
1445 /* replaced by teedog - v0.4.12
1446 * $final_uri .= $_SERVER['SERVER_NAME'];
1448 if (empty($_SERVER['SERVER_NAME'])) {
1449 $final_uri .= $_SERVER['HTTP_HOST'];
1451 $final_uri .= $_SERVER['SERVER_NAME'];
1454 $final_uri .= $_SERVER['HTTP_X_FORWARDED_SERVER'];
1456 if ( ($this->isHttps() && $_SERVER['SERVER_PORT']!=443)
1457 || (!$this->isHttps() && $_SERVER['SERVER_PORT']!=80) ) {
1459 $final_uri .= $_SERVER['SERVER_PORT'];
1461 $request_uri = $_SERVER['REQUEST_URI'];
1462 $request_uri = preg_replace('/\?.*$/','',$request_uri);
1463 $final_uri .= $request_uri;
1464 $this->setCallbackURL($final_uri);
1466 return $this->_callback_url;
1470 * This method sets the callback url.
1472 * @param $callback_url url to set callback
1476 function setCallbackURL($url)
1478 return $this->_callback_url = $url;
1482 * This method is called by CASClient::CASClient() when running in callback
1483 * mode. It stores the PGT and its PGT Iou, prints its output and halts.
1489 phpCAS::traceBegin();
1490 $this->printHTMLHeader('phpCAS callback');
1491 $pgt_iou = $_GET['pgtIou'];
1492 $pgt = $_GET['pgtId'];
1493 phpCAS::trace('Storing PGT `'.$pgt.'\' (id=`'.$pgt_iou.'\')');
1494 echo '<p>Storing PGT `'.$pgt.'\' (id=`'.$pgt_iou.'\').</p>';
1495 $this->storePGT($pgt,$pgt_iou);
1496 $this->printHTMLFooter();
1497 phpCAS::traceExit();
1502 // ########################################################################
1504 // ########################################################################
1506 * @addtogroup internalPGTStorage
1511 * an instance of a class inheriting of PGTStorage, used to deal with PGT
1512 * storage. Created by CASClient::setPGTStorageFile() or CASClient::setPGTStorageDB(), used
1513 * by CASClient::setPGTStorageFile(), CASClient::setPGTStorageDB() and CASClient::initPGTStorage().
1518 var $_pgt_storage = null;
1521 * This method is used to initialize the storage of PGT's.
1526 function initPGTStorage()
1528 // if no SetPGTStorageXxx() has been used, default to file
1529 if ( !is_object($this->_pgt_storage) ) {
1530 $this->setPGTStorageFile();
1533 // initializes the storage
1534 $this->_pgt_storage->init();
1538 * This method stores a PGT. Halts on error.
1540 * @param $pgt the PGT to store
1541 * @param $pgt_iou its corresponding Iou
1545 function storePGT($pgt,$pgt_iou)
1547 // ensure that storage is initialized
1548 $this->initPGTStorage();
1550 $this->_pgt_storage->write($pgt,$pgt_iou);
1554 * This method reads a PGT from its Iou and deletes the corresponding storage entry.
1556 * @param $pgt_iou the PGT Iou
1558 * @return The PGT corresponding to the Iou, FALSE when not found.
1562 function loadPGT($pgt_iou)
1564 // ensure that storage is initialized
1565 $this->initPGTStorage();
1567 return $this->_pgt_storage->read($pgt_iou);
1571 * This method is used to tell phpCAS to store the response of the
1572 * CAS server to PGT requests onto the filesystem.
1574 * @param $format the format used to store the PGT's (`plain' and `xml' allowed)
1575 * @param $path the path where the PGT's should be stored
1579 function setPGTStorageFile($format='',
1582 // check that the storage has not already been set
1583 if ( is_object($this->_pgt_storage) ) {
1584 phpCAS::error('PGT storage already defined');
1587 // create the storage object
1588 $this->_pgt_storage = &new PGTStorageFile($this,$format,$path);
1592 * This method is used to tell phpCAS to store the response of the
1593 * CAS server to PGT requests into a database.
1594 * @note The connection to the database is done only when needed.
1595 * As a consequence, bad parameters are detected only when
1596 * initializing PGT storage.
1598 * @param $user the user to access the data with
1599 * @param $password the user's password
1600 * @param $database_type the type of the database hosting the data
1601 * @param $hostname the server hosting the database
1602 * @param $port the port the server is listening on
1603 * @param $database the name of the database
1604 * @param $table the name of the table storing the data
1608 function setPGTStorageDB($user,
1616 // check that the storage has not already been set
1617 if ( is_object($this->_pgt_storage) ) {
1618 phpCAS::error('PGT storage already defined');
1621 // warn the user that he should use file storage...
1622 trigger_error('PGT storage into database is an experimental feature, use at your own risk',E_USER_WARNING);
1624 // create the storage object
1625 $this->_pgt_storage = & new PGTStorageDB($this,$user,$password,$database_type,$hostname,$port,$database,$table);
1628 // ########################################################################
1630 // ########################################################################
1632 * This method is used to validate a PGT; halt on failure.
1634 * @param $validate_url the URL of the request to the CAS server.
1635 * @param $text_response the response of the CAS server, as is (XML text); result
1636 * of CASClient::validateST() or CASClient::validatePT().
1637 * @param $tree_response the response of the CAS server, as a DOM XML tree; result
1638 * of CASClient::validateST() or CASClient::validatePT().
1640 * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError().
1644 function validatePGT(&$validate_url,$text_response,$tree_response)
1646 phpCAS::traceBegin();
1647 if ( sizeof($arr = $tree_response->get_elements_by_tagname("proxyGrantingTicket")) == 0) {
1648 phpCAS::trace('<proxyGrantingTicket> not found');
1649 // authentication succeded, but no PGT Iou was transmitted
1650 $this->authError('Ticket validated but no PGT Iou transmitted',
1652 FALSE/*$no_response*/,
1653 FALSE/*$bad_response*/,
1656 // PGT Iou transmitted, extract it
1657 $pgt_iou = trim($arr[0]->get_content());
1658 $pgt = $this->loadPGT($pgt_iou);
1659 if ( $pgt == FALSE ) {
1660 phpCAS::trace('could not load PGT');
1661 $this->authError('PGT Iou was transmitted but PGT could not be retrieved',
1663 FALSE/*$no_response*/,
1664 FALSE/*$bad_response*/,
1667 $this->setPGT($pgt);
1669 phpCAS::traceEnd(TRUE);
1673 // ########################################################################
1675 // ########################################################################
1678 * This method is used to retrieve PT's from the CAS server thanks to a PGT.
1680 * @param $target_service the service to ask for with the PT.
1681 * @param $err_code an error code (PHPCAS_SERVICE_OK on success).
1682 * @param $err_msg an error message (empty on success).
1684 * @return a Proxy Ticket, or FALSE on error.
1688 function retrievePT($target_service,&$err_code,&$err_msg)
1690 phpCAS::traceBegin();
1692 // by default, $err_msg is set empty and $pt to TRUE. On error, $pt is
1693 // set to false and $err_msg to an error message. At the end, if $pt is FALSE
1694 // and $error_msg is still empty, it is set to 'invalid response' (the most
1695 // commonly encountered error).
1698 // build the URL to retrieve the PT
1699 // $cas_url = $this->getServerProxyURL().'?targetService='.preg_replace('/&/','%26',$target_service).'&pgt='.$this->getPGT();
1700 $cas_url = $this->getServerProxyURL().'?targetService='.urlencode($target_service).'&pgt='.$this->getPGT();
1702 // open and read the URL
1703 if ( !$this->readURL($cas_url,''/*cookies*/,$headers,$cas_response,$err_msg) ) {
1704 phpCAS::trace('could not open URL \''.$cas_url.'\' to validate ('.$err_msg.')');
1705 $err_code = PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE;
1706 $err_msg = 'could not retrieve PT (no response from the CAS server)';
1707 phpCAS::traceEnd(FALSE);
1711 $bad_response = FALSE;
1713 if ( !$bad_response ) {
1714 // read the response of the CAS server into a DOM object
1715 if ( !($dom = @domxml_open_mem($cas_response))) {
1716 phpCAS::trace('domxml_open_mem() failed');
1718 $bad_response = TRUE;
1722 if ( !$bad_response ) {
1723 // read the root node of the XML tree
1724 if ( !($root = $dom->document_element()) ) {
1725 phpCAS::trace('document_element() failed');
1727 $bad_response = TRUE;
1731 if ( !$bad_response ) {
1732 // insure that tag name is 'serviceResponse'
1733 if ( $root->node_name() != 'serviceResponse' ) {
1734 phpCAS::trace('node_name() failed');
1736 $bad_response = TRUE;
1740 if ( !$bad_response ) {
1741 // look for a proxySuccess tag
1742 if ( sizeof($arr = $root->get_elements_by_tagname("proxySuccess")) != 0) {
1743 // authentication succeded, look for a proxyTicket tag
1744 if ( sizeof($arr = $root->get_elements_by_tagname("proxyTicket")) != 0) {
1745 $err_code = PHPCAS_SERVICE_OK;
1747 phpCAS::trace('original PT: '.trim($arr[0]->get_content()));
1748 $pt = trim($arr[0]->get_content());
1749 phpCAS::traceEnd($pt);
1752 phpCAS::trace('<proxySuccess> was found, but not <proxyTicket>');
1755 // look for a proxyFailure tag
1756 else if ( sizeof($arr = $root->get_elements_by_tagname("proxyFailure")) != 0) {
1757 // authentication failed, extract the error
1758 $err_code = PHPCAS_SERVICE_PT_FAILURE;
1759 $err_msg = 'PT retrieving failed (code=`'
1760 .$arr[0]->get_attribute('code')
1762 .trim($arr[0]->get_content())
1764 phpCAS::traceEnd(FALSE);
1767 phpCAS::trace('neither <proxySuccess> nor <proxyFailure> found');
1771 // at this step, we are sure that the response of the CAS server was ill-formed
1772 $err_code = PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE;
1773 $err_msg = 'Invalid response from the CAS server (response=`'.$cas_response.'\')';
1775 phpCAS::traceEnd(FALSE);
1779 // ########################################################################
1780 // ACCESS TO EXTERNAL SERVICES
1781 // ########################################################################
1784 * This method is used to acces a remote URL.
1786 * @param $url the URL to access.
1787 * @param $cookies an array containing cookies strings such as 'name=val'
1788 * @param $headers an array containing the HTTP header lines of the response
1789 * (an empty array on failure).
1790 * @param $body the body of the response, as a string (empty on failure).
1791 * @param $err_msg an error message, filled on failure.
1793 * @return TRUE on success, FALSE otherwise (in this later case, $err_msg
1794 * contains an error message).
1798 function readURL($url,$cookies,&$headers,&$body,&$err_msg)
1800 phpCAS::traceBegin();
1807 // initialize the CURL session
1808 $ch = curl_init($url);
1810 if (version_compare(PHP_VERSION,'5.1.3','>=')) {
1811 //only avaible in php5
1812 curl_setopt_array($ch, $this->_curl_options);
1814 foreach ($this->_curl_options as $key => $value) {
1815 curl_setopt($ch, $key, $value);
1819 if ($this->_cas_server_cert == '' && $this->_cas_server_ca_cert == '' && !$this->_no_cas_server_validation) {
1820 phpCAS::error('one of the methods phpCAS::setCasServerCert(), phpCAS::setCasServerCACert() or phpCAS::setNoCasServerValidation() must be called.');
1822 if ($this->_cas_server_cert != '' ) {
1823 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
1824 curl_setopt($ch, CURLOPT_SSLCERT, $this->_cas_server_cert);
1825 } else if ($this->_cas_server_ca_cert != '') {
1826 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
1827 curl_setopt($ch, CURLOPT_CAINFO, $this->_cas_server_ca_cert);
1829 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
1830 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
1833 // return the CURL output into a variable
1834 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1835 // get the HTTP header with a callback
1836 $this->_curl_headers = array(); // empty the headers array
1837 curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, '_curl_read_headers'));
1838 // add cookies headers
1839 if ( is_array($cookies) ) {
1840 curl_setopt($ch,CURLOPT_COOKIE,implode(';',$cookies));
1842 // perform the query
1843 $buf = curl_exec ($ch);
1844 if ( $buf === FALSE ) {
1845 phpCAS::trace('curl_exec() failed');
1846 $err_msg = 'CURL error #'.curl_errno($ch).': '.curl_error($ch);
1847 // close the CURL session
1851 // close the CURL session
1854 $headers = $this->_curl_headers;
1858 phpCAS::traceEnd($res);
1863 * This method is the callback used by readURL method to request HTTP headers.
1865 var $_curl_headers = array();
1866 function _curl_read_headers($ch, $header)
1868 $this->_curl_headers[] = $header;
1869 return strlen($header);
1873 * This method is used to access an HTTP[S] service.
1875 * @param $url the service to access.
1876 * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on
1877 * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE,
1878 * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE.
1879 * @param $output the output of the service (also used to give an error
1880 * message on failure).
1882 * @return TRUE on success, FALSE otherwise (in this later case, $err_code
1883 * gives the reason why it failed and $output contains an error message).
1887 function serviceWeb($url,&$err_code,&$output)
1889 phpCAS::traceBegin();
1890 // at first retrieve a PT
1891 $pt = $this->retrievePT($url,$err_code,$output);
1895 // test if PT was retrieved correctly
1897 // note: $err_code and $err_msg are filled by CASClient::retrievePT()
1898 phpCAS::trace('PT was not retrieved correctly');
1901 // add cookies if necessary
1902 if ( is_array($_SESSION['phpCAS']['services'][$url]['cookies']) ) {
1903 foreach ( $_SESSION['phpCAS']['services'][$url]['cookies'] as $name => $val ) {
1904 $cookies[] = $name.'='.$val;
1908 // build the URL including the PT
1909 if ( strstr($url,'?') === FALSE ) {
1910 $service_url = $url.'?ticket='.$pt;
1912 $service_url = $url.'&ticket='.$pt;
1915 phpCAS::trace('reading URL`'.$service_url.'\'');
1916 if ( !$this->readURL($service_url,$cookies,$headers,$output,$err_msg) ) {
1917 phpCAS::trace('could not read URL`'.$service_url.'\'');
1918 $err_code = PHPCAS_SERVICE_NOT_AVAILABLE;
1919 // give an error message
1920 $output = sprintf($this->getString(CAS_STR_SERVICE_UNAVAILABLE),
1925 // URL has been fetched, extract the cookies
1926 phpCAS::trace('URL`'.$service_url.'\' has been read, storing cookies:');
1927 foreach ( $headers as $header ) {
1928 // test if the header is a cookie
1929 if ( preg_match('/^Set-Cookie:/',$header) ) {
1930 // the header is a cookie, remove the beginning
1931 $header_val = preg_replace('/^Set-Cookie: */','',$header);
1932 // extract interesting information
1933 $name_val = strtok($header_val,'; ');
1934 // extract the name and the value of the cookie
1935 $cookie_name = strtok($name_val,'=');
1936 $cookie_val = strtok('=');
1938 $_SESSION['phpCAS']['services'][$url]['cookies'][$cookie_name] = $cookie_val;
1939 phpCAS::trace($cookie_name.' -> '.$cookie_val);
1945 phpCAS::traceEnd($res);
1950 * This method is used to access an IMAP/POP3/NNTP service.
1952 * @param $url a string giving the URL of the service, including the mailing box
1953 * for IMAP URLs, as accepted by imap_open().
1954 * @param $flags options given to imap_open().
1955 * @param $err_code an error code Possible values are PHPCAS_SERVICE_OK (on
1956 * success), PHPCAS_SERVICE_PT_NO_SERVER_RESPONSE, PHPCAS_SERVICE_PT_BAD_SERVER_RESPONSE,
1957 * PHPCAS_SERVICE_PT_FAILURE, PHPCAS_SERVICE_NOT AVAILABLE.
1958 * @param $err_msg an error message on failure
1959 * @param $pt the Proxy Ticket (PT) retrieved from the CAS server to access the URL
1960 * on success, FALSE on error).
1962 * @return an IMAP stream on success, FALSE otherwise (in this later case, $err_code
1963 * gives the reason why it failed and $err_msg contains an error message).
1967 function serviceMail($url,$flags,&$err_code,&$err_msg,&$pt)
1969 phpCAS::traceBegin();
1970 // at first retrieve a PT
1971 $pt = $this->retrievePT($target_service,$err_code,$output);
1975 // test if PT was retrieved correctly
1977 // note: $err_code and $err_msg are filled by CASClient::retrievePT()
1978 phpCAS::trace('PT was not retrieved correctly');
1980 phpCAS::trace('opening IMAP URL `'.$url.'\'...');
1981 $stream = @imap_open($url,$this->getUser(),$pt,$flags);
1983 phpCAS::trace('could not open URL');
1984 $err_code = PHPCAS_SERVICE_NOT_AVAILABLE;
1985 // give an error message
1986 $err_msg = sprintf($this->getString(CAS_STR_SERVICE_UNAVAILABLE),
1988 var_export(imap_errors(),TRUE));
1992 phpCAS::trace('ok');
1996 phpCAS::traceEnd($stream);
2002 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2004 // XX PROXIED CLIENT FEATURES (CAS 2.0) XX
2006 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2008 // ########################################################################
2010 // ########################################################################
2012 * @addtogroup internalProxied
2017 * the Proxy Ticket provided in the URL of the request if present
2018 * (empty otherwise). Written by CASClient::CASClient(), read by
2019 * CASClient::getPT() and CASClient::hasPGT().
2027 * This method returns the Proxy Ticket provided in the URL of the request.
2028 * @return The proxy ticket.
2033 // return 'ST'.substr($this->_pt, 2);
2038 * This method stores the Proxy Ticket.
2039 * @param $pt The Proxy Ticket.
2043 { $this->_pt = $pt; }
2046 * This method tells if a Proxy Ticket was stored.
2047 * @return TRUE if a Proxy Ticket has been stored.
2051 { return !empty($this->_pt); }
2054 // ########################################################################
2056 // ########################################################################
2058 * @addtogroup internalProxied
2063 * This method is used to validate a PT; halt on failure
2065 * @return bool TRUE when successfull, halt otherwise by calling CASClient::authError().
2069 function validatePT(&$validate_url,&$text_response,&$tree_response)
2071 phpCAS::traceBegin();
2072 // build the URL to validate the ticket
2073 $validate_url = $this->getServerProxyValidateURL().'&ticket='.$this->getPT();
2075 if ( $this->isProxy() ) {
2076 // pass the callback url for CAS proxies
2077 $validate_url .= '&pgtUrl='.$this->getCallbackURL();
2080 // open and read the URL
2081 if ( !$this->readURL($validate_url,''/*cookies*/,$headers,$text_response,$err_msg) ) {
2082 phpCAS::trace('could not open URL \''.$validate_url.'\' to validate ('.$err_msg.')');
2083 $this->authError('PT not validated',
2085 TRUE/*$no_response*/);
2088 // read the response of the CAS server into a DOM object
2089 if ( !($dom = domxml_open_mem($text_response))) {
2091 $this->authError('PT not validated',
2093 FALSE/*$no_response*/,
2094 TRUE/*$bad_response*/,
2097 // read the root node of the XML tree
2098 if ( !($tree_response = $dom->document_element()) ) {
2100 $this->authError('PT not validated',
2102 FALSE/*$no_response*/,
2103 TRUE/*$bad_response*/,
2106 // insure that tag name is 'serviceResponse'
2107 if ( $tree_response->node_name() != 'serviceResponse' ) {
2109 $this->authError('PT not validated',
2111 FALSE/*$no_response*/,
2112 TRUE/*$bad_response*/,
2115 if ( sizeof($arr = $tree_response->get_elements_by_tagname("authenticationSuccess")) != 0) {
2116 // authentication succeded, extract the user name
2117 if ( sizeof($arr = $tree_response->get_elements_by_tagname("user")) == 0) {
2118 // no user specified => error
2119 $this->authError('PT not validated',
2121 FALSE/*$no_response*/,
2122 TRUE/*$bad_response*/,
2125 $this->setUser(trim($arr[0]->get_content()));
2127 } else if ( sizeof($arr = $tree_response->get_elements_by_tagname("authenticationFailure")) != 0) {
2128 // authentication succeded, extract the error code and message
2129 $this->authError('PT not validated',
2131 FALSE/*$no_response*/,
2132 FALSE/*$bad_response*/,
2134 $arr[0]->get_attribute('code')/*$err_code*/,
2135 trim($arr[0]->get_content())/*$err_msg*/);
2137 $this->authError('PT not validated',
2139 FALSE/*$no_response*/,
2140 TRUE/*$bad_response*/,
2144 // at this step, PT has been validated and $this->_user has been set,
2146 phpCAS::traceEnd(TRUE);
2152 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2156 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2159 * @addtogroup internalMisc
2163 // ########################################################################
2165 // ########################################################################
2167 * the URL of the current request (without any ticket CGI parameter). Written
2168 * and read by CASClient::getURL().
2176 * This method returns the URL of the current request (without any ticket
2185 phpCAS::traceBegin();
2186 // the URL is built when needed only
2187 if ( empty($this->_url) ) {
2189 // remove the ticket if present in the URL
2190 $final_uri = ($this->isHttps()) ? 'https' : 'http';
2191 $final_uri .= '://';
2192 /* replaced by Julien Marchal - v0.4.6
2193 * $this->_url .= $_SERVER['SERVER_NAME'];
2195 if(empty($_SERVER['HTTP_X_FORWARDED_SERVER'])){
2196 /* replaced by teedog - v0.4.12
2197 * $this->_url .= $_SERVER['SERVER_NAME'];
2199 if (empty($_SERVER['SERVER_NAME'])) {
2200 $server_name = $_SERVER['HTTP_HOST'];
2202 $server_name = $_SERVER['SERVER_NAME'];
2205 $server_name = $_SERVER['HTTP_X_FORWARDED_SERVER'];
2207 $final_uri .= $server_name;
2208 if (!strpos($server_name, ':')) {
2209 if ( ($this->isHttps() && $_SERVER['SERVER_PORT']!=443)
2210 || (!$this->isHttps() && $_SERVER['SERVER_PORT']!=80) ) {
2212 $final_uri .= $_SERVER['SERVER_PORT'];
2216 $final_uri .= strtok($_SERVER['REQUEST_URI'],"?");
2217 $cgi_params = '?'.strtok("?");
2218 // remove the ticket if present in the CGI parameters
2219 $cgi_params = preg_replace('/&ticket=[^&]*/','',$cgi_params);
2220 $cgi_params = preg_replace('/\?ticket=[^&;]*/','?',$cgi_params);
2221 $cgi_params = preg_replace('/\?%26/','?',$cgi_params);
2222 $cgi_params = preg_replace('/\?&/','?',$cgi_params);
2223 $cgi_params = preg_replace('/\?$/','',$cgi_params);
2224 $final_uri .= $cgi_params;
2225 $this->setURL($final_uri);
2227 phpCAS::traceEnd($this->_url);
2232 * This method sets the URL of the current request
2234 * @param $url url to set for service
2238 function setURL($url)
2243 // ########################################################################
2244 // AUTHENTICATION ERROR HANDLING
2245 // ########################################################################
2247 * This method is used to print the HTML output when the user was not authenticated.
2249 * @param $failure the failure that occured
2250 * @param $cas_url the URL the CAS server was asked for
2251 * @param $no_response the response from the CAS server (other
2252 * parameters are ignored if TRUE)
2253 * @param $bad_response bad response from the CAS server ($err_code
2254 * and $err_msg ignored if TRUE)
2255 * @param $cas_response the response of the CAS server
2256 * @param $err_code the error code given by the CAS server
2257 * @param $err_msg the error message given by the CAS server
2261 function authError($failure,$cas_url,$no_response,$bad_response='',$cas_response='',$err_code='',$err_msg='')
2263 phpCAS::traceBegin();
2265 $this->printHTMLHeader($this->getString(CAS_STR_AUTHENTICATION_FAILED));
2266 printf($this->getString(CAS_STR_YOU_WERE_NOT_AUTHENTICATED),$this->getURL(),$_SERVER['SERVER_ADMIN']);
2267 phpCAS::trace('CAS URL: '.$cas_url);
2268 phpCAS::trace('Authentication failure: '.$failure);
2269 if ( $no_response ) {
2270 phpCAS::trace('Reason: no response from the CAS server');
2272 if ( $bad_response ) {
2273 phpCAS::trace('Reason: bad response from the CAS server');
2275 switch ($this->getServerVersion()) {
2276 case CAS_VERSION_1_0:
2277 phpCAS::trace('Reason: CAS error');
2279 case CAS_VERSION_2_0:
2280 if ( empty($err_code) )
2281 phpCAS::trace('Reason: no CAS error');
2283 phpCAS::trace('Reason: ['.$err_code.'] CAS error: '.$err_msg);
2287 phpCAS::trace('CAS response: '.$cas_response);
2289 $this->printHTMLFooter();
2290 phpCAS::traceExit();