You are here

function autologout_init in Automated Logout 7.2

Same name and namespace in other branches
  1. 6.4 autologout.module \autologout_init()
  2. 6.2 autologout.module \autologout_init()
  3. 6.3 autologout.module \autologout_init()
  4. 7.4 autologout.module \autologout_init()

Implements hook_init().

File

./autologout.module, line 175
Used to automagically log out a user after a preset time, AjK May 2006

Code

function autologout_init() {
  global $user;
  if ($user->uid < 1 || _autologout_by_role()) {
    _autologout_debug("block doesn't apply");
    return;
  }
  if (_autologout_local_settings('enabled')) {
    $timeout = (int) _autologout_local_settings('timeout');
    $nowtime = REQUEST_TIME;
    if (!isset($_SESSION['lastaccess'])) {
      $_SESSION['lastaccess'] = $nowtime;
    }

    // update lastaccess from any cache hits which wouldn't have been processed by hook_init()
    if (isset($_SESSION['autologout_hits'])) {
      foreach ($_SESSION['autologout_hits'] as $hit) {
        if ((int) $hit - (int) $_SESSION['lastaccess'] > 0) {

          // if hit wouldn't have timedout, update lastaccess
          if ((int) $hit - (int) $_SESSION['lastaccess'] < $timeout) {

            // rebase lastaccess
            $_SESSION['lastaccess'] = $hit;
          }
        }
      }
    }

    // now normal processing because the cache hits have been accounted for.
    if ($nowtime - (int) $_SESSION['lastaccess'] < $timeout) {

      // the timeout has not yet occurred.
      $_SESSION['lastaccess'] = $nowtime;
      $_SESSION['autologout_hits'] = array(
        $nowtime,
      );
      $refresh = (int) _autologout_local_settings('refresh_delta');
      if ($refresh >= 0) {
        $force_refresh = $timeout + $refresh;
        $this_header = "<meta http-equiv=\"refresh\" content=\"{$force_refresh};\" />";
        $element = array(
          '#type' => 'markup',
          '#markup' => $this_header,
        );
        $this_head = drupal_add_html_head($element, 'refresh-header');
      }
    }
    else {

      // timeout occured, logout and end session
      unset($_SESSION['lastaccess']);

      // code from core(user.pages.inc), can't use it directly because we need need a custom goto
      watchdog('user', 'Session closed for %name.', array(
        '%name' => $user->name,
      ));
      module_invoke_all('user_logout', $user);

      // Destroy the current session, and reset $user to the anonymous user.
      session_destroy();
      $redirect_url = filter_xss_admin(_autologout_local_settings('redirect_url'));
      if ($redirect_url != '') {
        drupal_goto($redirect_url);
      }
      else {
        drupal_goto('autologout/logout', drupal_get_destination());
      }
      return;
    }
  }
}