You are here

function restrict_ip_init in Restrict IP 7

Same name and namespace in other branches
  1. 6 restrict_ip.module \restrict_ip_init()

Implementation of hook_init()

This function determines whether or not the user should be whitelisted, and if they should, it sets a flag indicating so

File

./restrict_ip.module, line 166

Code

function restrict_ip_init() {
  global $restricted_ip;
  $restricted_ip = FALSE;
  $ip_addresses = trim(variable_get('restrict_ip_address_list', ''));
  if (strlen($ip_addresses)) {
    $ip_addresses = explode(PHP_EOL, $ip_addresses);
    $users_ip = ip_address();
    $access_denied = TRUE;
    foreach ($ip_addresses as $ip_address) {
      if (!preg_match('~^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$~', trim($ip_address)) && $ip_address != '::1') {
        $pieces = explode('-', trim($ip_address));
        $ip1_pieces = explode('.', trim($pieces[0]));
        $users_ip_pieces = explode('.', $users_ip);
        $first_parts_equal = TRUE;
        for ($i = 0; $i < 3; $i++) {
          if ($users_ip_pieces[$i] != $ip1_pieces[$i]) {
            $first_parts_equal = FALSE;
          }
          if ($first_parts_equal) {
            $ip1_end = $ip1_pieces[3];
            $ip2_pieces = explode('.', trim($pieces[1]));
            $ip2_end = $ip2_pieces[3];
            $user_end = $users_ip_pieces[3];
            if ($user_end >= $ip1_end && $user_end <= $ip2_end) {
              $access_denied = FALSE;
              break;
            }
          }
        }
      }
      elseif (trim($ip_address) == $users_ip) {
        $access_denied = FALSE;
        break;
      }
    }
    if ($access_denied) {
      if (current_path() != 'restrict_ip/access_denied') {
        drupal_goto('restrict_ip/access_denied');
      }
      $contact_mail = trim(variable_get('restrict_ip_mail_address', ''));
      if (strlen($contact_mail)) {
        $contact_mail = str_replace('@', '[at]', $contact_mail);
      }
      $contact_text = strlen($contact_mail) ? ' ' . t('If you feel this is in error, please contact an administrator at !email.', array(
        '!email' => '<span id="restrict_ip_contact_mail">' . $contact_mail . '</span>',
      )) : FALSE;
      drupal_set_message(t('This site cannot be accessed from your IP address.') . $contact_text, 'error', FALSE);
      restrict_ip_value(TRUE);
      drupal_add_js(drupal_get_path('module', 'restrict_ip') . '/js/restrict_ip.js');
    }
    elseif (current_path() == drupal_get_normal_path('restrict_ip/access_denied')) {
      drupal_goto('<front>');
    }
  }
}