You are here

function restrict_ip_init in Restrict IP 6

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

File

./restrict_ip.module, line 114

Code

function restrict_ip_init() {
  global $restricted_ip;
  $restricted_ip = FALSE;
  $ip_addresses = trim(variable_get('restrict_ip_address_list', ''));
  if (strlen($ip_addresses)) {
    $contact_mail = trim(variable_get('restrict_ip_mail_address', ''));
    $contact_text = strlen($contact_mail) ? ' ' . t('If you feel this is in error, please contact an administrator at !email.', array(
      '!email' => $contact_mail,
    )) : FALSE;
    $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))) {
        $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 ($_GET['q'] != 'restrict_ip/access_denied') {
        drupal_goto('restrict_ip/access_denied');
      }
      drupal_set_message(t('This site cannot be accessed from your IP address.') . $contact_text);
      $restricted_ip = TRUE;
    }
  }
}