You are here

domain_registration.module in Restrict Domain Registration 8

Same filename and directory in other branches
  1. 7 domain_registration.module

Domain Registration module file.

File

domain_registration.module
View source
<?php

/**
 * @file
 * Domain Registration module file.
 */
const DOMAIN_REGISTRATION_ALLOW = 0;
const DOMAIN_REGISTRATION_DENY = 1;

/**
 * Implements hook_form_form_id_form_alter().
 */
function domain_registration_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'domain_registration_user_register_validate';
}

/**
 * Custom validation function.
 *
 * Checks if the domain in the email address is on a list of allowed domains.
 */
function domain_registration_user_register_validate(&$form, &$form_state) {

  // Ignore validation if mail already has an error.
  $errors = $form_state
    ->getErrors();
  if (!empty($errors['mail'])) {
    return;
  }
  $mail = explode('@', $form_state
    ->getValue('mail'));
  $domains = \Drupal::service('domain_registration.pattern')
    ->getPatterns();

  // Only attempt to validate if we have a list of domains.
  if ($domains) {

    // Determine if we have matches.
    $match = count(array_filter($domains, function ($domain) use (&$mail) {
      return domain_registration_wildcard_match($domain, $mail[1]);
    }));
    switch (\Drupal::config('domain_registration.settings')
      ->get('method')) {

      // Allow only domains listed to register.
      case DOMAIN_REGISTRATION_ALLOW:
        if (!$match) {
          $form_state
            ->setErrorByName('account', \Drupal::config('domain_registration.settings')
            ->get('message'));
        }
        break;

      // Prevent domains listed from registering.
      case DOMAIN_REGISTRATION_DENY:
        if ($match) {
          $form_state
            ->setErrorByName('account', \Drupal::config('domain_registration.settings')
            ->get('message'));
        }
        break;
    }
  }
}

/**
 * Pattern Match wildcard addresses.
 */
function domain_registration_wildcard_match($pattern, $string) {
  return preg_match("#^" . strtr(preg_quote($pattern, '#'), [
    '\\*' => '.*',
    '\\?' => '.',
  ]) . "\$#i", $string);
}

Functions

Namesort descending Description
domain_registration_form_user_register_form_alter Implements hook_form_form_id_form_alter().
domain_registration_user_register_validate Custom validation function.
domain_registration_wildcard_match Pattern Match wildcard addresses.

Constants

Namesort descending Description
DOMAIN_REGISTRATION_ALLOW @file Domain Registration module file.
DOMAIN_REGISTRATION_DENY