You are here

function mass_contact_mail_page_submit in Mass Contact 7

Same name and namespace in other branches
  1. 5.2 mass_contact.module \mass_contact_mail_page_submit()
  2. 5 mass_contact.module \mass_contact_mail_page_submit()
  3. 6 mass_contact.module \mass_contact_mail_page_submit()

Processes the main Mass Contact mail form.

Parameters

array $form: An associative array containing the structure of the form.

array $form_state: A keyed array containing the current state of the form.

File

./mass_contact.page.inc, line 398
The main form for creating and sending the messages.

Code

function mass_contact_mail_page_submit(array $form, array &$form_state) {
  $send_error = 0;
  $recipient_lists = array();
  $empty_lists = 0;

  // Set wether the recipients will be BCC or not.
  $bcc = variable_get('mass_contact_bcc_d', 1);
  if (user_access('mass contact override bcc')) {
    $bcc = $form_state['values']['bcc'];
  }

  // Set whether a copy will be archived as a node.
  $nodecc = variable_get('mass_contact_nodecc_d', 1);
  if (user_access('mass contact archive messages') && user_access('mass contact override archiving')) {

    // Only set $nodecc if the user is allowed to archive messages AND
    // override the archive setting.
    $nodecc = $form_state['values']['nodecc'];
  }

  // Set the input filter format.
  $format = _mass_contact_compute_default_filter_format();
  if (user_access('mass contact override text format')) {

    // Allow the form data to determine the message format, if the user has the
    // appropriate permissions.
    if (is_array($form_state['values']['message'])) {
      $format = $form_state['values']['message']['format'];
    }
    else {
      $format = $form_state['values']['body_filter_format']->format;
    }
  }

  // Process some parts of the message header (more will be processed later).
  $params = _mass_contact_prepare_header($format);

  // Get the admin specified default sender's name.
  $from_name = variable_get('mass_contact_default_sender_name');

  // Get the admin specified default sender's email address.
  $from_email = variable_get('mass_contact_default_sender_email');

  // Set the sender name and email address.
  if (empty($from_name) || empty($from_email) || user_access('mass contact change default sender information')) {

    // Either the admin has not specified a default name and email address or
    // the user is allowed to change them, so we check the form for submitted
    // values.
    if (isset($form_state['values']['name']) && !empty($form_state['values']['name'])) {
      $from_name = $form_state['values']['name'];
    }
    if (isset($form_state['values']['mail']) && !empty($form_state['values']['mail'])) {
      $from_email = $form_state['values']['mail'];
    }
  }

  // Format the sender name and email address.
  if (variable_get('mass_contact_include_from_name', 0) == 1 && !empty($from_name)) {
    $from_address = '"' . $from_name . '" <' . $from_email . '>';
  }
  else {
    $from_address = $from_email;
  }

  // Process the message body.
  $params['body'] = _mass_contact_prepare_bodies($form_state['values'], $format);

  // If there are attachments, and the user is allowed, add them.
  if (user_access('mass contact include attachments') && module_exists('mimemail')) {
    for ($i = 1; $i <= variable_get('mass_contact_number_of_attachments', '3'); $i++) {
      if (!empty($_FILES['files']['size']['attachment_' . $i])) {
        $files_array = _mass_contact_process_mime_mail_attachments($nodecc);
        $params['attachments'] = $files_array['files'];
        if (!empty($files_array['node_files'])) {
          $params['node_attachments'] = $files_array['node_files'];
        }
        break;
      }
    }
  }

  // Process the recipients (some more of the message header).
  // Get the IDs of the chosen categories.
  $cids = array();
  foreach ($form_state['values']['cid'] as $cid) {
    $cids[] = $cid;
  }

  // Get the category objects, based on the IDs, and save them into an array
  // for later use.
  $results = db_query("SELECT * FROM {mass_contact} WHERE cid IN(:cids)", array(
    ':cids' => $cids,
  ));
  foreach ($results as $category) {
    $permission = 'mass contact send to users in the ';
    $permission .= $category->category;
    $permission .= ' category';
    if (user_access($permission)) {

      // Only allow categories the user has permission to send to.
      $categories[] = $category;
    }
  }

  // Create the recipient lists, based on category.
  foreach ($categories as $category) {

    // Create the recipient lists, per category.
    $recipient_lists[$category->category] = array(
      // Set the recipients.
      'recipients' => _mass_contact_create_recipient_list($category, $form_state['values']['optout']),
      // Set the subject.
      'subject' => t('[@category] !subject', array(
        '@category' => $category->category,
        '!subject' => filter_xss($form_state['values']['subject']),
      )),
    );
  }

  // Iterate through each recipient list to verify there are recipients
  // somewhere.
  if (!empty($recipient_lists)) {
    foreach ($recipient_lists as $recipient_list) {

      // Check for empty recipient list.
      if (count($recipient_list['recipients']) == 0) {
        $empty_lists++;
      }
    }
  }

  // There are categories selected, but all of them are empty.
  if (count($recipient_lists) == $empty_lists) {

    // Post a message to the user and exit.
    drupal_set_message(t('No users were in the selected category(ies), and therefore, the message was not sent.'));
  }
  else {

    // Initialize more variables.
    // The count of all email addresses the message is sent to.
    $total_recipients = 0;

    // An array of all categories and email addresses thie message is sent to.
    $all_recipients = array();

    // If the module is configured to not include the category in the subject,
    // combine all users in all categories into a single listing of recpients.
    if (!variable_get('mass_contact_category_override', 1)) {
      $new_recipient_list = array(
        'All categories combined' => array(),
      );

      // Cycle through all the categories adding all the recipients to the one
      // list.
      foreach ($recipient_lists as $category) {
        if (!empty($new_recipient_list['All categories combined']['recipients'])) {
          $new_recipient_list['All categories combined']['recipients'] = array_merge($new_recipient_list['All categories combined']['recipients'], $category['recipients']);
        }
        else {
          $new_recipient_list['All categories combined']['recipients'] = $category['recipients'];
        }
      }

      // Add the subject.
      $new_recipient_list['All categories combined']['subject'] = filter_xss($form_state['values']['subject'], array());

      // Set the original list to the new combined, unduplicated list.
      $new_recipient_list['All categories combined']['recipients'] = array_unique($new_recipient_list['All categories combined']['recipients']);
      $recipient_lists = $new_recipient_list;
    }

    // Capture the rate limiting information.
    $recipient_limit = variable_get('mass_contact_recipient_limit', 0);
    $send_with_cron = variable_get('mass_contact_send_with_cron', 0);

    // Iterate through each recipient list.
    foreach ($recipient_lists as $category => $recipient_list) {

      // Only process this recipient list if it is not empty.
      if (count($recipient_list['recipients']) > 0) {
        if (count($recipient_list['recipients']) > $recipient_limit && $recipient_limit != 0) {

          // Initialize still more variables.
          // The count of current recipients.
          $recipient_count = 0;

          // The batch count.
          $batch = 0;

          // An array of the current grouping of categories and email addresses
          // the message is sent to.
          $current_recipients = array();
          foreach ($recipient_list['recipients'] as $recipient_name => $recipient_address) {
            if (variable_get('mass_contact_include_to_name', 0) == 1) {
              $current_recipients[] = '"' . $recipient_name . '" <' . $recipient_address . '>';
              $partial_list[] = '"' . $recipient_name . '" <' . $recipient_address . '>';
            }
            else {
              $current_recipients[] = $recipient_address;
              $partial_list[] = $recipient_address;
            }
            $recipient_count = count($partial_list);
            if ($recipient_count == $recipient_limit) {

              // Increment the batch count.
              ++$batch;

              // Finalizes the headers, by setting the To, Subject, and
              // possibly, Bcc fields.
              $to = _mass_contact_finalize_headers($bcc, implode(', ', $partial_list), $params, $from_address, $recipient_list['subject']);
              if (empty($send_with_cron)) {

                // Send the message. Save the inverse of the result for
                // tallying.
                $send_result = _mass_contact_send_message('mail_page_' . $batch, $to, $params, $from_address, '[Success] Sent batch #' . $batch . '.');
                if ($send_result === FALSE) {
                  $send_error++;
                }
              }
              else {

                // Create the queue.
                $queue = new SystemQueue('mass_contact');

                // Create the queue item.
                $message = array(
                  'message_key' => 'mail_page_' . $batch,
                  'to' => $to,
                  'params' => $params,
                  'from_email' => $from_address,
                  'success_message' => '[Success] Sent batch #' . $batch . '.',
                );

                // Add the item to the queue.
                $queue
                  ->createItem($message);
              }

              // Reset the variables.
              $partial_list = array();
              $recipient_count = 0;
            }
          }

          // Send the remainder.
          if ($recipient_count != 0) {

            // Finalizes the headers, by setting the To, Subject, and possibly,
            // Bcc fields.
            $to = _mass_contact_finalize_headers($bcc, implode(', ', $partial_list), $params, $from_address, $recipient_list['subject']);
            if (empty($send_with_cron)) {

              // Send the message. Save the inverse of the result for tallying.
              $send_result = _mass_contact_send_message('mail_page_last', $to, $params, $from_address, '[Success] Sent the remainder.');
              if ($send_result === FALSE) {
                $send_error++;
              }
            }
            else {

              // Create the queue.
              $queue = new SystemQueue('mass_contact');

              // Create the queue item.
              $message = array(
                'message_key' => 'mail_page_last',
                'to' => $to,
                'params' => $params,
                'from_email' => $from_address,
                'success_message' => '[Success] Sent the remainder.',
              );

              // Add the item to the queue.
              $queue
                ->createItem($message);
            }
          }
          $total_recipients = count($current_recipients);
          $listed_recipients = implode(', ', $current_recipients);
          $all_recipients = array_merge($all_recipients, $current_recipients);
        }
        else {

          // An array of the current grouping of categories and email addresses
          // the message is being sent to.
          $current_recipients = array();
          foreach ($recipient_list['recipients'] as $recipient_name => $recipient_address) {
            if (variable_get('mass_contact_include_to_name', 0) == 1) {
              $current_recipients[] = '"' . $recipient_name . '" <' . $recipient_address . '>';
            }
            else {
              $current_recipients[] = $recipient_address;
            }
          }
          $total_recipients = count($current_recipients);
          $listed_recipients = implode(', ', $current_recipients);
          $all_recipients = array_merge($all_recipients, $current_recipients);

          // Finalizes the headers, by setting the To, Subject, and possibly,
          // Bcc fields.
          $to = _mass_contact_finalize_headers($bcc, implode(', ', $current_recipients), $params, $from_address, $recipient_list['subject']);

          // Send the message. Save the inverse of the result for tallying.
          $send_result = _mass_contact_send_message('mail_page', $to, $params, $from_address, '[Success] Sent all at once.');
          if ($send_result === FALSE) {
            $send_error++;
          }
        }

        // Archive the message as a node.
        if ($nodecc) {
          _mass_contact_save_node($params, $format, $from_address, $category, $to, !$send_error);
        }
      }
    }

    // If there were no errors, do the final operations.
    if (!$send_error) {

      // If the sender requested a copy, send it.
      if (!empty($form_state['values']['copy']) && !$bcc) {
        if (empty($recipient_limit) && empty($send_with_cron)) {
          $send_result = _mass_contact_send_message('user-copy', $from_address, $params, $from_address, 'A copy was sent to you.');
          if ($send_result === FALSE) {

            // There was an error, so inform the user.
            if (!module_exists('help')) {
              drupal_set_message(t("A copy could not be sent to you. Check the logs for error messages. For more information, see the Troubleshooting secion of Mass Contact's !help page or README.txt.", array(
                '!help' => l(t('help'), 'admin/help/mass_contact'),
              )));
            }
            else {
              drupal_set_message(t("A copy could not be sent to you. Check the logs for error messages. For more information, see the Troubleshooting secion of Mass Contact's README.txt."));
            }
          }
        }
        else {

          // Create the queue.
          $queue = new SystemQueue('mass_contact');

          // Create the queue item.
          $message = array(
            'message_key' => 'user-copy',
            'to' => $from_address,
            'params' => $params,
            'from_email' => $from_address,
            'success_message' => 'A copy was sent to you.',
          );

          // Add the item to the queue.
          $queue
            ->createItem($message);
        }
      }

      // Register this message send to the flood control mechanism.
      flood_register_event('mass_contact');

      // Log the operation.
      watchdog('mass_contact', '%name-from sent a message to the %category group, which included these recipients: @emails.', array(
        '%name-from' => $from_address,
        '%category' => $category,
        '@emails' => $listed_recipients,
      ));

      // Prepare some variables for the printing of the final results.
      $total_recipients = count($all_recipients);
      $unique_addresses_count = count(array_unique($all_recipients));
      $listed_recipients = implode(', ', $all_recipients);

      // Print out the final results of the complete operation.
      if ($total_recipients == $unique_addresses_count) {
        drupal_set_message(t('Your message was successfully sent to a total of @total email addresses.', array(
          '@total' => $total_recipients,
        )));
      }
      else {
        drupal_set_message(t('Your message was successfully sent to a total of @total email addresses, of which, there may have been !dups duplicates.', array(
          '@total' => $total_recipients,
          '!dups' => $total_recipients - $unique_addresses_count,
        )));
      }
    }
    else {

      // Otherwise, inform the user that there were error(s).
      if (module_exists('help')) {
        drupal_set_message(t("@errors error(s) were encountered sending the message. Check the logs for error messages. For more information, see the Troubleshooting section of Mass Contact's !help page or README.txt.", array(
          '@errors' => $send_error,
          '!help' => l(t('help'), 'admin/help/mass_contact'),
        )));
      }
      else {
        drupal_set_message(t("@errors error(s) were encountered sending the message. Check the logs for error messages. For more information, see the Troubleshooting section of Mass Contact's README.txt.", array(
          '@errors' => $send_error,
        )));
      }
    }
  }

  // Redirect to the home page, rather than back to the mail page, to avoid
  // contradictory messages if flood control has been activated.
  $form_state['redirect'] = '/';
}