+# Get CAS handler and service URI
+sub _get_cas_and_service {
+ my $query = shift;
+ my $key = shift; # optional
+ my $type = shift;
+
+ my $uri = _url_with_get_params($query, $type);
+
+ my $casparam = $defaultcasserver;
+ $casparam = $query->param('cas') if defined $query->param('cas');
+ $casparam = $key if defined $key;
+ my $cas = Authen::CAS::Client->new( $casservers->{$casparam} );
+
+ return ( $cas, $uri );
+}
+
+# Get the current URL with parameters contained directly into URL (GET params)
+# This method replaces $query->url() which will give both GET and POST params
+sub _url_with_get_params {
+ my $query = shift;
+ my $type = shift;
+
+ my $uri_base_part =
+ ( $type eq 'opac' )
+ ? C4::Context->preference('OPACBaseURL')
+ : C4::Context->preference('staffClientBaseURL');
+ $uri_base_part .= get_script_name();
+
+ my $uri_params_part = '';
+ foreach my $param ( $query->url_param() ) {
+ # url_param() always returns parameters that were deleted by delete()
+ # This additional check ensure that parameter was not deleted.
+ my $uriPiece = $query->param($param);
+ if ($uriPiece) {
+ $uri_params_part .= '&' if $uri_params_part;
+ $uri_params_part .= $param . '=';
+ $uri_params_part .= URI::Escape::uri_escape( $uriPiece );
+ }
+ }
+ $uri_base_part .= '?' if $uri_params_part;
+
+ return $uri_base_part . $uri_params_part;
+}
+
+=head2 logout_if_required
+
+ If using CAS, this subroutine will trigger single-signout of the CAS server.
+
+=cut
+
+sub logout_if_required {
+ my ( $query ) = @_;
+ # Check we havent been hit by a logout call
+ my $xml = $query->param('logoutRequest');
+ return 0 unless $xml;
+
+ my $dom = XML::LibXML->load_xml(string => $xml);
+ my $ticket;
+ foreach my $node ($dom->findnodes('/samlp:LogoutRequest')){
+ # We got a cas single logout request from a cas server;
+ $ticket = $node->findvalue('./samlp:SessionIndex');
+ }
+
+ return 0 unless $ticket;
+
+ # We've been called as part of the single logout destroy the session associated with the cas ticket
+ my $params = C4::Auth::_get_session_params();
+ my $success = CGI::Session->find( $params->{dsn}, sub {delete_cas_session(@_, $ticket)}, $params->{dsn_args} );
+
+ sub delete_cas_session {
+ my $session = shift;
+ my $ticket = shift;
+ if ($session->param('cas_ticket') && $session->param('cas_ticket') eq $ticket ) {
+ $session->delete;
+ $session->flush;
+ }
+ }
+
+ print $query->header;
+ exit;
+}