You are here

function throttle_exit in Drupal 4

Same name and namespace in other branches
  1. 5 modules/throttle/throttle.module \throttle_exit()
  2. 6 modules/throttle/throttle.module \throttle_exit()

Implementation of hook_exit().

Changes the current throttle level based on page hits.

File

modules/throttle.module, line 31
Allows configuration of congestion control auto-throttle mechanism.

Code

function throttle_exit() {

  // The following logic determines what the current throttle level should
  //  be, and can be disabled by the admin.  If enabled, the mt_rand() function
  //  returns a number between 0 and N, N being specified by the admin. If
  //  0 is returned, the throttle logic is run, adding two additional database
  //  queries.  Otherwise, the following logic is skipped.  This mechanism is
  //  referred to in the admin page as the 'probability limiter', roughly
  //  limiting throttle related database calls to 1 in N.
  if (!mt_rand(0, variable_get('throttle_probability_limiter', 9))) {

    // Count users with activity in the past n seconds, defined in user module
    $time_period = variable_get('user_block_seconds_online', 2700);
    $throttle = module_invoke('throttle', 'status');
    if ($max_guests = variable_get('throttle_anonymous', 0)) {
      $guests = db_result(db_query('SELECT COUNT(sid) AS count FROM {sessions} WHERE timestamp >= %d AND uid = 0', time() - $time_period));
    }
    else {
      $guests = 0;
    }
    if ($max_users = variable_get('throttle_user', 0)) {
      $users = db_result(db_query('SELECT COUNT(DISTINCT(uid)) AS count FROM {sessions} WHERE timestamp >= %d AND uid != 0', time() - $time_period));
    }
    else {
      $users = 0;
    }

    // update the throttle status
    $message = '';
    if ($max_users && $users > $max_users) {
      if (!$throttle) {
        variable_set('throttle_level', 1);
        $message = format_plural($users, '1 user accessing site; throttle enabled.', '%count users accessing site; throttle enabled.');
      }
    }
    elseif ($max_guests && $guests > $max_guests) {
      if (!$throttle) {
        variable_set('throttle_level', 1);
        $message = format_plural($guests, '1 guest accessing site; throttle enabled.', '%count guests accessing site; throttle enabled.');
      }
    }
    else {
      if ($throttle) {
        variable_set('throttle_level', 0);

        // Note: unorthodox format_plural() usage due to Gettext plural limitations.
        $message = format_plural($users, '1 user', '%count users') . ', ';
        $message .= format_plural($guests, '1 guest accessing site; throttle disabled', '%count guests accessing site; throttle disabled');
      }
    }
    if ($message) {
      cache_clear_all();
      watchdog('throttle', t('Throttle') . ': ' . $message);
    }
  }
}