Index: cas.module
===================================================================
--- cas.module	(revision 1465)
+++ cas.module	(working copy)
@@ -467,7 +467,7 @@
     '#type' => 'checkbox',
     '#title' => t('Redirect user on logout'),
     '#default_value' => variable_get('cas_logout_redirect', 0),
-    '#description' => t("Activate this option if you want a user to be directed to the following page after logging out of CAS. The logout destination must be specified below."),
+    '#description' => t("Activate this option if you want a user to be directed after logging out of CAS. If this option is enabled, but the logout destination is not specified below, we redirect back to this site."),
   );
 
   $form['pages']['cas_logout_destination'] = array(
@@ -582,6 +582,7 @@
  */
 function cas_logout() {
   global $user;
+  global $base_url;
 
   watchdog('user', t('Session closed for %name.', array('%name' => theme('placeholder', $user->name))));
 
@@ -598,16 +599,39 @@
 
   // Begin constructing logout destination
   $logout_destination = 'https://'. $server;
+
   // Add abnormal port
   if ($port != '443') {
     $logout_destination .= ':'. $port;
   }
+
   // Add logout
-  $logout_destination .= '/'. $uri .'/logout';
-  // If admin has set and enabled a logout destination, add it
-  if (variable_get('cas_logout_redirect', 0) && variable_get('cas_logout_destination', '')) {
-    $logout_destination .= '?service='. variable_get('cas_logout_destination', '');
+  $logout_destination .= $uri .'/logout';
+
+  // Add destination override so that a destination can be specified on the logout link
+  // e.g. caslogout?desination=http://foo.bar.com/foobar
+  // do not accept caslogout as a valid sestination, since that may cause a redirect loop
+  $destination = preg_replace("/(destination=|caslogout)/", "", drupal_get_destination());
+
+  // make sure the destination is an absolute path as this is going off to another server
+  if (!empty($destination) && (!preg_match("|http(s)?\:\/\/|", $destination))) {
+    $destination = $base_url .'/'. $destination;
+  }
+
+  // If there was no override and admin has set and enabled a logout destination, look for it
+  if (empty($destination) && variable_get('cas_logout_redirect', 0)) {
+    $destination = variable_get('cas_logout_destination', '');
+    // redirecti is enabled but no url is given - default to baseurl
+    if (empty($destination)) {
+      $destination = $base_url;
+    }
   }
+
+  // Add the log out destination if we have one
+  if (!empty($destination)) {
+    $logout_destination .= '?service='. $destination ;
+  }
+
   // Go to the constructed logout destination
   drupal_goto($logout_destination);
 }
