You are here

function reroute_email_check in Reroute Email 7

Same name and namespace in other branches
  1. 8 reroute_email.module \reroute_email_check()
  2. 2.x reroute_email.module \reroute_email_check()

Helper function to determine a need to reroute.

Parameters

array $message: A message array, as described in hook_mail_alter().

Return value

bool Return TRUE if should be rerouted, FALSE otherwise.

1 call to reroute_email_check()
reroute_email_mail_alter in ./reroute_email.module
Implements hook_mail_alter().

File

./reroute_email.module, line 238
Intercepts all outgoing emails to be rerouted to a configurable destination.

Code

function reroute_email_check(array $message) {

  // Disable rerouting according to admin settings.
  if (!variable_get(REROUTE_EMAIL_ENABLE, FALSE)) {
    return FALSE;
  }

  // Check configured mail keys filters.
  $keys = reroute_email_split_string(variable_get(REROUTE_EMAIL_MAIL_KEYS, ''));
  if (!empty($keys) && !(in_array($message['id'], $keys, TRUE) || in_array($message['module'], $keys, TRUE))) {
    $message['header']['X-Reroute-Status'] = 'MAILKEY-IGNORED';
    return FALSE;
  }

  // Split addresses into arrays.
  $original_addresses = reroute_email_split_string($message['to']);
  $whitelisted_addresses = reroute_email_split_string(variable_get(REROUTE_EMAIL_WHITELIST, ''));
  $whitelisted_domains = array();

  // Split whitelisted domains from whitelisted addresses.
  foreach ($whitelisted_addresses as $key => $email) {
    if (preg_match('/^\\*@(.*)$/', $email, $matches)) {

      // The part after the @ sign is the domain and according to RFC 1035,
      // section 3.1: "Name servers and resolvers must compare [domains] in a
      // case-insensitive manner".
      $domain = drupal_strtolower($matches[1]);
      $whitelisted_domains[$domain] = $domain;
      unset($whitelisted_addresses[$key]);
    }
  }

  // Compare original addresses with whitelisted.
  $invalid = 0;
  foreach ($original_addresses as $email) {

    // Check whitelisted emails and domains.
    $domain = drupal_strtolower(drupal_substr(strrchr($email, '@'), 1));
    if (in_array($email, $whitelisted_addresses, TRUE) || in_array($domain, $whitelisted_domains, TRUE)) {
      continue;
    }

    // Just ignore all invalid email addresses.
    if (valid_email_address($email) === FALSE) {
      $invalid++;
      continue;
    }

    // No need to continue if at least one address should be rerouted.
    $message['header']['X-Reroute-Status'] = 'REROUTED';
    return TRUE;
  }

  // Reroute if all addresses are invalid.
  if (count($original_addresses) === $invalid) {
    $message['header']['X-Reroute-Status'] = 'INVALID-ADDRESSES';
    return TRUE;
  }

  // All addresses passes whitelist checks.
  $message['header']['X-Reroute-Status'] = 'WHITELISTED';
  return FALSE;
}