You are here

mass_contact.module in Mass Contact 8

This is the main code file for the Mass Contact module.

This is primarily where all the hooks are implemented.

File

mass_contact.module
View source
<?php

/**
 * @file
 * This is the main code file for the Mass Contact module.
 *
 * This is primarily where all the hooks are implemented.
 */
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultForbidden;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\mass_contact\MassContactInterface;

/**
 * Implements hook_help().
 */
function mass_contact_help($route_name, RouteMatchInterface $route_match) {
  $output = '';
  switch ($route_name) {
    case 'help.page.mass_contact':
      $output .= '<h3>' . t('Related tasks:') . '</h3><ul>';
      $output .= '<li>' . Link::createFromRoute(t('Configure the module'), 'mass_contact.settings')
        ->toString() . '</li>';
      $output .= '<li>' . Link::createFromRoute(t('Add new category'), 'entity.mass_contact_category.add_form')
        ->toString() . '</li>';
      $output .= '<li>' . Link::createFromRoute(t('List current categories'), 'entity.mass_contact_category.collection')
        ->toString() . '</li>';
      if (\Drupal::currentUser()
        ->hasPermission('administer permissions')) {
        $output .= '<li>' . Link::createFromRoute(t('Set Mass Contact permissions'), 'user.admin_permissions', [], [
          'fragment' => 'module-mass_contact',
        ])
          ->toString() . '</li>';
      }
      $output .= '<li>' . Link::createFromRoute(t('Send a mass email message'), 'entity.mass_contact_message.add_form')
        ->toString() . '</li></ul>';
      $output .= '<h3>' . t('Configuration and setup') . '</h3>';
      $output .= '<p>' . t('While an attempt has been made at setting sensible defaults, the configuration should be reviewed and tweaked before sending any messages.') . '</p>';
      $output .= '<p>' . t('Before sending any mass email messages, at least one category needs to be created, which can be done at the same location where the administrative settings are.') . '</p>';
      $output .= '<p>' . t("By default, the email messages are sent as plain text. If the Mime Mail module is enabled, the email messages may be sent as HTML and may include one or more binary file attachments (if permitted by admin).") . '</p>';
      $output .= '<h3>' . t('Miscelaneous information') . '</h3>';
      $output .= '<p>' . t("This module works by sending a single email to your mail server with all of the recipients' email addresses in either the 'To:' or 'Bcc:' field. The mail server is then responsible for parsing out the recipients' addresses and forwarding the message along to everyone.") . '</p>';
      $output .= '<p>' . t("When using the Bcc option, recipients are not potentially left open to abuse due to their email addresses being visible to all other recipients.") . '</p>';
      $output .= '<h3>' . t('Troubleshooting') . '</h3>';
      $output .= '<p>' . t('Verify the permission set correctly.') . '</p>';
      $output .= '<p>' . t('When sending messages as Bcc (hiding the recipients from each other) and breaking up a large recipient list into smaller chunks or sending to multiple categories while retaining the category name in the subject, keep in mind that the sender will receive a copy of the message for every group of recipients the list is broken up into. That is normal behavior and cannot be changed.') . '</p>';
      $output .= '<p>' . t('If your category permissions are not showing up correctly, check your category name and make sure you do not have any stray characters or any characters that Drupal does not allow.') . '</p>';
      $output .= '<p>' . t('If you experience "return-path" errors when sending email, you can try the @returnpath module to see if that solves your problem.', [
        '@returnpath' => Link::fromTextAndUrl(t('Return-Path'), Url::fromUri('http://drupal.org/project/returnpath'))
          ->toString(),
      ]) . '</p>';
      if (\Drupal::currentUser()
        ->hasPermission('access site reports')) {
        $output .= '<p>' . t("If PHP's mail() function encounters an error, it just returns FALSE and Drupal presents a message like this: 'Unable to send email. Contact the site administrator if the problem persists.' To find what the cause of the error is, you may need to reference a number of logs:");
        $output .= '<ul><li>' . t('Drupal\'s <a href="@logs">log messages</a> in the <a href="@reports">reports section</a>', [
          '@logs' => Url::fromRoute('dblog.overview')
            ->toString(),
          '@reports' => Url::fromRoute('system.admin_reports')
            ->toString(),
        ]) . '</li>';
        $output .= '<li>' . t("The host server's system logs. For most Linux systems, the log files are usually stored in /var/log. The system messages are usually stored in /var/log/messages or /var/log/syslog.") . '</li>';
        $output .= '<li>' . t("The HTTP server software's logs. For Apache on Linux, it's log files are usually found in /var/log/httpd, /var/log/apache or /var/log/apache2.") . '</li>';
        $output .= '<li>' . t("The mail server software's logs. Most mail servers store thier logs in /var/log/mail*, where 'mail*' might be a directory or it might be a number of files in /var/log, including (but not limited to) mail.log, mail.info, mail.warn and mail.err.") . '</li></ul></p>';
      }
      $output .= '<p>' . t('If you are also using other mail related modules on your Drupal installation (i.e.: @htmlmail module, @mimemail module, @phpmailer module, @smtp module, etc.), be sure to check the issue queues for those modules for solutions, as well.', [
        '@htmlmail' => Link::fromTextAndUrl(t('HTML Mail'), Url::fromUri('http://drupal.org/project/htmlmail')),
        '@mimemail' => Link::fromTextAndUrl(t('Mime Mail'), Url::fromUri('http://drupal.org/project/mimemail')),
        '@phpmailer' => Link::fromTextAndUrl(t('PHPMailer'), Url::fromUri('http://drupal.org/project/phpmailer')),
        '@smtp' => Link::fromTextAndUrl(t('SMTP Authentication Support'), Url::fromUri('http://drupal.org/project/smtp')),
      ]) . '</p>';
      break;
  }
  return $output;
}

/**
 * Implements hook_mail().
 */
function mass_contact_mail($key, &$message, $params) {
  if (!empty($params['headers'])) {
    foreach ($params['headers'] as $key => $value) {
      $message['headers'][$key] = $params['headers'][$key];
    }
  }
  $message['subject'] = $params['subject'];

  // Message prefix.
  $config = \Drupal::config('mass_contact.settings');
  if ($config
    ->get('message_prefix.value')) {
    $message['body'][] = check_markup($config
      ->get('message_prefix.value'), $config
      ->get('message_prefix.format'));
  }
  $message['body'][] = check_markup($params['body'], $params['format']);

  // Message suffix.
  if ($config
    ->get('message_suffix.value')) {
    $message['body'][] = check_markup($config
      ->get('message_suffix.value'), $config
      ->get('message_suffix.format'));
  }

  // Update the 'From' address.
  $message['from'] = $params['configuration']['sender_mail'];

  // Unset the format so the correct format configured for site's mail can take
  // effect.
  unset($message['params']['format']);
}

/**
 * Implements hook_entity_field_access().
 */
function mass_contact_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
  if ($field_definition
    ->getName() === MassContactInterface::OPT_OUT_FIELD_ID) {

    // Only allow access if there are any categories, and site is configured
    // to allow opt-out.
    if (\Drupal::config('mass_contact.settings')
      ->get('optout_enabled') === MassContactInterface::OPT_OUT_DISABLED) {
      return AccessResultForbidden::forbidden('Opt out is disabled');
    }
    if (\Drupal::config('mass_contact.settings')
      ->get('optout_enabled') === MassContactInterface::OPT_OUT_CATEGORY && empty(\Drupal::entityTypeManager()
      ->getStorage('mass_contact_category')
      ->loadMultiple())) {
      return AccessResultForbidden::forbidden('Opt out is setup to allow configuration by categories, but no categories were found');
    }
  }
  return AccessResult::neutral();
}

/**
 * Implements callback_allowed_values_function().
 */
function mass_contact_opt_out_allowed_values_callback(FieldStorageDefinitionInterface $definition, FieldableEntityInterface $entity = NULL, &$cacheable = NULL) {
  $opt_out = \Drupal::config('mass_contact.settings')
    ->get('optout_enabled');
  if ($opt_out === MassContactInterface::OPT_OUT_DISABLED) {

    // Opt-out is disabled.
    return [];
  }
  $values = [
    1 => t('Opt-out of all emails'),
  ];
  if ($opt_out === MassContactInterface::OPT_OUT_GLOBAL) {

    // Return a simple global opt-out checkbox.
    return $values;
  }

  // Per-category opt-out is enabled, so return all categories.

  /** @var \Drupal\mass_contact\Entity\MassContactCategoryInterface[] $categories */
  $categories = \Drupal::entityTypeManager()
    ->getStorage('mass_contact_category')
    ->loadMultiple();
  foreach ($categories as $category) {
    $values[$category
      ->id()] = $category
      ->label();
  }
  return $values;
}