You are here

function mass_contact_mail_page_submit in Mass Contact 5.2

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

Processes the main Mass Contact mail form.

Parameters

form_id: The unique string identifying the form.

form_values: The array of values returned by the form.

File

./mass_contact.module, line 996
This is the main code file for the Mass Contact module. This module enables users to contact multiple users through selected roles.

Code

function mass_contact_mail_page_submit($form_id, $form_values) {
  $headers = array();
  $character_set = variable_get('mass_contact_character_set', '') ? variable_get('mass_contact_character_set', '') : 'UTF-8';
  $bcc = $form_values['bcc'];
  $nodecc = $form_values['nodecc'];
  $from = $form_values['mail'];
  $body_plain = '';
  $boundary_html = md5(uniqid(mt_rand()));
  $body_html = '';
  $message = '';
  $has_attachments = FALSE;
  $boundary_attachment = md5(uniqid(mt_rand()));
  $message_attachments = array();
  $send_error = 0;

  // Check for the exsistance of attachments.
  for ($i = 1; $i <= variable_get('mass_contact_number_of_attachments', '3'); $i++) {
    if ($_FILES['files']['size']['attachment_' . $i] > 0) {
      $has_attachments = TRUE;
      break;
    }
  }

  // Set the "Content-Type" header based on the presence or absence of an
  // attachment and the HTML setting.
  if ($has_attachments) {
    $headers['Content-Type'] = 'multipart/mixed; boundary="' . $boundary_attachment . '"';
  }
  elseif ($form_values['html']) {
    $headers['Content-Type'] = 'multipart/alternative; boundary="' . $boundary_html . '"';
  }
  else {
    $headers['Content-Type'] = 'text/plain; charset=' . $character_set . '; format=flowed';
  }

  // Create the body part(s) of the message.
  // Create the plain text body. We now always create a plain text body.
  if ($form_values['html']) {

    // If this is supposed to be an HTML e-mail, we need to process the plain
    // text part differently.
    // Make this process better, by utilizing existing modules. This will
    // become the norm, eliminating the need for the module check.
    if (module_exists('html_to_text')) {

      // Start with the message prefix.
      if (variable_get('mass_contact_message_prefix', '')) {
        if (module_exists('token')) {
          $body_plain .= drupal_html_to_text(check_markup(token_replace(variable_get('mass_contact_message_prefix', '')), $form_values['format'])) . "\n";
        }
        else {
          $body_plain .= drupal_html_to_text(check_markup(variable_get('mass_contact_message_prefix', ''), $form_values['format'])) . "\n";
        }
      }

      // Add in the actual message.
      $body_plain .= drupal_html_to_text(check_markup($form_values['message'], $form_values['format'])) . "\n";

      // End with the message suffix.
      if (variable_get('mass_contact_message_suffix', '')) {
        if (module_exists('token')) {
          $body_plain .= drupal_html_to_text(check_markup(token_replace(variable_get('mass_contact_message_suffix', '')), $form_values['format']));
        }
        else {
          $body_plain .= drupal_html_to_text(check_markup(variable_get('mass_contact_message_suffix', ''), $form_values['format']));
        }
      }
    }
    else {

      // Start with the message prefix.
      if (variable_get('mass_contact_message_prefix', '')) {
        if (module_exists('token')) {
          $body_plain .= wordwrap(strip_tags(check_markup(token_replace(variable_get('mass_contact_message_prefix', '')), $form_values['format']))) . "\n";
        }
        else {
          $body_plain .= wordwrap(strip_tags(check_markup(variable_get('mass_contact_message_prefix', ''), $form_values['format']))) . "\n";
        }
      }

      // Add in the actual message.
      $body_plain .= wordwrap(strip_tags(check_markup($form_values['message'], $form_values['format']))) . "\n";

      // End with the message suffix.
      if (variable_get('mass_contact_message_suffix', '')) {
        if (module_exists('token')) {
          $body_plain .= wordwrap(strip_tags(check_markup(token_replace(variable_get('mass_contact_message_suffix', '')), $form_values['format'])));
        }
        else {
          $body_plain .= wordwrap(strip_tags(check_markup(variable_get('mass_contact_message_suffix', ''), $form_values['format'])));
        }
      }
    }
  }
  else {

    // Start with the message prefix.
    if (variable_get('mass_contact_message_prefix', '')) {
      if (module_exists('token')) {
        $body_plain .= wordwrap(token_replace(variable_get('mass_contact_message_prefix', ''))) . "\n";
      }
      else {
        $body_plain .= wordwrap(variable_get('mass_contact_message_prefix', '')) . "\n";
      }
    }

    // Add in the actual message.
    $body_plain .= wordwrap($form_values['message']) . "\n";

    // End with the message suffix.
    if (variable_get('mass_contact_message_suffix', '')) {
      if (module_exists('token')) {
        $body_plain .= wordwrap(token_replace(variable_get('mass_contact_message_suffix', '')));
      }
      else {
        $body_plain .= wordwrap(variable_get('mass_contact_message_suffix', ''));
      }
    }
  }

  // If this is an HTML message, create the HTML body part.
  if ($form_values['html']) {

    // Start with the message prefix.
    if (variable_get('mass_contact_message_prefix', '')) {
      if (module_exists('token')) {
        $body_html .= check_markup(token_replace(variable_get('mass_contact_message_prefix', '')), $form_values['format']);
      }
      else {
        $body_html .= check_markup(variable_get('mass_contact_message_prefix', ''), $form_values['format']);
      }
    }

    // Add in the actual message.
    $body_html .= check_markup($form_values['message'], $form_values['format']);

    // End with the message suffix.
    if (variable_get('mass_contact_message_suffix', '')) {
      if (module_exists('token')) {
        $body_html .= check_markup(token_replace(variable_get('mass_contact_message_suffix', '')), $form_values['format']);
      }
      else {
        $body_html .= check_markup(variable_get('mass_contact_message_suffix', ''), $form_values['format']);
      }
    }
  }

  // Put it all together.
  // Check to see if we have either an attachment or an HTML message.
  if ($has_attachments || $form_values['html']) {

    // If we have either, we add the following.
    $message .= "\nThis is a MIME-formatted multipart message.\n\nIf you see this text it means that your e-mail software does not support MIME-formatted multipart messages.\n\nYou might want to consider changing your e-mail software to one that understands how to properly display MIME-formatted multipart messages.\n";

    // Add our boundary, based on the content.
    if ($has_attachments) {
      $message .= "\n--{$boundary_attachment}\n";
    }
    else {
      $message .= "\n--{$boundary_html}\n";
    }

    // If we have both an attachment and an HTML message, we need the following.
    if ($has_attachments && $form_values['html']) {
      $message .= 'Content-Type: multipart/alternative; boundary="' . $boundary_html . '"' . "\n";
      $message .= "\n--{$boundary_html}\n";
    }

    // Add the plain text part to the message.
    $message .= "Content-Type: text/plain; charset={$character_set}; format=flowed\n";

    // The 8bit Data mechanism is similar to 7bit, except that it allows for
    // character sets other than US-ASCII to be used (RFC 2045, sections 2.7
    // and 2.8).
    // When the Content-Transfer-Encoding is not specified, "7bit" is the
    // default mechanism (RFC 2045, sections 6 and 6.1).
    $message .= "Content-Transfer-Encoding: 8bit\n\n";
    $message .= $body_plain;

    // If there is an HTML part, add it to the message.
    if ($form_values['html']) {
      $message .= "\n--{$boundary_html}\n";
      $message .= "Content-Type: text/html; charset={$character_set}; format=flowed\n";

      // The 8bit Data mechanism is similar to 7bit, except that it allows for
      // character sets other than US-ASCII to be used (RFC 2045, sections 2.7
      // and 2.8).
      // When the Content-Transfer-Encoding is not specified, "7bit" is the
      // default mechanism (RFC 2045, sections 6 and 6.1).
      $message .= "Content-Transfer-Encoding: 8bit\n\n";
      $message .= $body_html;

      // Add the closing boundary line (RFC 2046, section 5.1 and 5.1.1).
      $message .= "\n--{$boundary_html}--\n";
    }
  }
  else {

    // There is neither an attachment nor an HTML message, so this is not a
    // multipart message, and we just add the plain text part.
    $message = $body_plain;
  }

  // For the node copy, we want to handle attachments differently, so we'll
  // save the message as it currently stands.
  if (variable_get('mass_contact_nodecc_d', 1) || $form_values['nodecc'] == 1) {
    $node_message = $message;
  }

  // If there are attachments, add them.
  if ($has_attachments) {
    if (module_exists('mimemail') && variable_get('mimemail_alter', 0) == 1) {
      $message_attachments = _mass_contact_process_mime_mail_attachments();
    }
    else {
      $message = _mass_contact_process_attachments($message, $boundary_attachment);

      // Add the closing boundary line (RFC 2046, section 5.1 and 5.1.1).
      $message .= "--{$boundary_attachment}--\n";
    }
  }

  ///////////////////////////////////////////////////////////////////////////

  //
  //  @TODO:  The whole rest of this function needs to be re-thought out and
  //          refactored, possibly separating some of it out into other
  //          functions.
  //

  ///////////////////////////////////////////////////////////////////////////

  /*
   Task order:
     Create the e-mail message, starting w/the header
     Get the list of categories
     Create the list of recipients
     Add the list of recipients to the e-mail message
  */

  // Load the category information.
  foreach ($form_values['cid'] as $cid) {
    $cids .= $cid;
    if (next($form_values['cid'])) {
      $cids .= ", ";
    }
  }
  $result = db_query("SELECT * FROM {mass_contact} WHERE cid IN (%s)", $cids);
  while ($contact = db_fetch_object($result)) {

    // Format the subject line.
    if (variable_get('mass_contact_category_override', 1)) {
      $subject = t('[!category] !subject', array(
        '!category' => $contact->category,
        '!subject' => $form_values['subject'],
      ));
    }
    else {
      $subject = $form_values['subject'];
    }

    // Prepare the body.
    $body = $message;
    $node_body = $node_message;
    $uidooa = array();

    // Check for opt-out unless overridden by admin.
    $optout_setting = variable_get('mass_contact_optout_d', 0);
    if ($optout_setting == 1 || $optout_setting == 2) {
      if ($form_values['optout'] == 1) {
        $ooresult = db_query("SELECT uid FROM {users} WHERE status <> %d", 0);
        while ($oouid = db_fetch_object($ooresult)) {
          $account = user_load(array(
            'uid' => $oouid->uid,
            'status' => 1,
          ));
          if ($optout_setting == 1 && $account->mass_contact_optout == 1) {
            $uidoo = $oouid->uid;
            $uidooa[$uidoo] = 1;
          }
          elseif ($optout_setting == 2) {
            $optout_cid = 'mass_contact_optout_' . $contact->cid;
            if ($account->{$optout_cid} == 1) {
              $uidoo = $oouid->uid;
              $uidooa[$uidoo] = 1;
            }
          }
        }
      }
    }
    global $user;

    // Create the recipient list.
    $recipientouta = array();
    $roles = explode(',', $contact->recipients);
    foreach ($roles as $r) {
      if ($r == 2) {

        // all users
        $recipients = db_query("SELECT name, mail, uid FROM {users} WHERE status <> 0 AND uid > 0");
        while ($obj = db_fetch_object($recipients)) {
          $rname = $obj->name;
          $rmail = $obj->mail;
          $ruid = $obj->uid;
          if ($rname != $user->name && !$uidooa[$ruid]) {
            $recipientouta[$rname] = $rmail;
          }
        }
        break;
      }
      else {

        // Get from users_roles, then role -> user.
        $uids = db_query("SELECT ur.uid FROM {users_roles} ur LEFT JOIN {users} u ON ur.uid = u.uid WHERE ur.rid = %d AND u.status <> 0", $r);
        while ($obj = db_fetch_object($uids)) {
          $ruid = $obj->uid;
          $userobj = db_fetch_object(db_query("SELECT name, mail FROM {users} WHERE uid = %d", $ruid));
          $rname = $userobj->name;
          $rmail = $userobj->mail;
          if (isset($uidooa[$ruid])) {
            if ($rname != $user->name && !$uidooa[$ruid]) {
              $recipientouta[$rname] = $rmail;
            }
          }
          else {
            if ($rname != $user->name) {
              $recipientouta[$rname] = $rmail;
            }
          }
        }
      }
    }

    // Check for empty recipient list.
    if (count($recipientouta) == 0) {
      drupal_set_message(t('There are no users in this category. Mail not sent.'));
      return '';
    }
    $recipientout = array();

    // Check for recipient limit and break up recipient list, if necessary.
    $recip_limit = variable_get('mass_contact_recipient_limit', 0);
    if (count($recipientouta) > $recip_limit && $recip_limit != 0) {
      $countrecip = 0;
      $ccc = 0;
      foreach ($recipientouta as $rnamea => $rmaila) {

        //        $recipientout[] = $rnamea ." <". $rmaila .">";
        $recipientout[] = $rmaila;

        //        $recipient_temp[] = $rnamea ." <". $rmaila .">";
        $recipient_temp[] = $rmaila;
        $countrecip = count($recipient_temp);
        if ($countrecip == $recip_limit) {
          $recipient_send = implode(', ', $recipient_temp);

          // set bcc
          if ($bcc == 1) {

            // hidden recipients
            $headers['Bcc'] = $recipient_send;
            $to = $from;
          }
          else {
            $to = $recipient_send;
          }
          ++$ccc;

          // Send the e-mail to the recipients:
          if (module_exists('mimemail') && variable_get('mimemail_alter', 0) == 1) {
            if ($form_values['html']) {
              $success = mimemail($from, $to, $subject, $body_html, NULL, $headers, $body_plain, $message_attachments, 'mass-contact-page-mail');
            }
            else {
              $success = mimemail($from, $to, $subject, $body_html, TRUE, $headers, $body_plain, $message_attachments, 'mass-contact-page-mail');
            }
          }
          else {
            $success = drupal_mail('mass-contact-page-mail', $to, $subject, $body, $from, $headers);
          }
          if ($success) {
            watchdog('mass_contact', t('[Success] Send #@ccc: -e-mails', array(
              '@ccc' => $ccc,
              '-e-mails' => $recipient_send,
            )), WATCHDOG_NOTICE);
          }
          else {
            watchdog('mass_contact', t('There was a problem sending batch #@ccc to: -e-mails: -e-mails', array(
              '@ccc' => $ccc,
              '-e-mails' => $recipient_send,
            )), WATCHDOG_ERROR);
            ++$send_error;
          }

          // reset array
          $recipient_temp = array();
          $countrecip = 0;
        }
      }

      // Send the remainder.
      if ($countrecip != 0) {
        $recipient_send = implode(', ', $recipient_temp);
        if ($bcc == 1) {

          // hidden recipients
          $headers['Bcc'] = $recipient_send;
          $to = $from;
        }
        else {
          $to = $recipient_send;
        }
        ++$ccc;

        // Send the e-mail to the recipients:
        if (module_exists('mimemail') && variable_get('mimemail_alter', 0) == 1) {
          if ($form_values['html']) {
            $success = mimemail($from, $to, $subject, $body_html, NULL, $headers, $body_plain, $message_attachments, 'mass-contact-page-mail');
          }
          else {
            $success = mimemail($from, $to, $subject, $body_html, TRUE, $headers, $body_plain, $message_attachments, 'mass-contact-page-mail');
          }
        }
        else {
          $success = drupal_mail('mass-contact-page-mail', $to, $subject, $body, $from, $headers);
        }

        // Send a copy to self, if requested.
        if ($form_values['copy'] && !$bcc) {
          drupal_mail('mass-contact-user-copy', $from, $subject, $body, $from, $headers);
        }
        if ($success) {
          watchdog('mass_contact', t('[Success] Send Remainder: -e-mails', array(
            '-e-mails' => $recipient_send,
          )), WATCHDOG_NOTICE);
        }
        else {
          watchdog('mass_contact', t('There was a problem sending remaining batch to: -e-mails', array(
            '@ccc' => $ccc,
            '-e-mails' => $recipient_send,
          )), WATCHDOG_ERROR);
          ++$send_error;
        }
      }
      $total_recip = count($recipientout);
      $recipientout = implode(', ', $recipientout);
    }
    else {
      foreach ($recipientouta as $rnamea => $rmaila) {

        //        $recipientout[] = $rnamea ." <". $rmaila .">";
        $recipientout[] = $rmaila;
      }
      $total_recip = count($recipientout);
      $recipientout = implode(', ', $recipientout);

      // set bcc
      if ($bcc == 1) {

        // hidden recipients
        $headers['Bcc'] = $recipientout;
        $to = $from;
      }
      else {
        $to = $recipientout;
      }

      // Send the e-mail to the recipients.
      if (module_exists('mimemail') && variable_get('mimemail_alter', 0) == 1) {
        if ($form_values['html']) {
          $success = mimemail($from, $to, $subject, $body_html, NULL, $headers, $body_plain, $message_attachments, 'mass-contact-page-mail');
        }
        else {
          $success = mimemail($from, $to, $subject, $body_html, TRUE, $headers, $body_plain, $message_attachments, 'mass-contact-page-mail');
        }
      }
      else {
        $success = drupal_mail('mass-contact-page-mail', $to, $subject, $body, $from, $headers);
      }

      // Send a copy to self, if requested.
      if ($form_values['copy'] && !$bcc) {
        drupal_mail('mass-contact-user-copy', $from, $subject, $body, $from, $headers);
      }
      if ($success) {
        watchdog('mass_contact', t('[Success] Send Once: -e-mails', array(
          '-e-mails' => $recipientout,
        )), WATCHDOG_NOTICE);
      }
      else {
        watchdog('mass_contact', t('There was a problem sending e-mail to: -e-mails', array(
          '-e-mails' => $recipientout,
        )), WATCHDOG_ERROR);
        ++$send_error;
      }
    }

    // Error checking & reporting and node saving.
    // Check for errors.
    if ($send_error == 0) {

      // If there are no errors, check to see if we need to save the message as a node.
      if ($nodecc == 1) {

        // Check to see if the node type exists.
        $check = db_fetch_array(db_query("SELECT * FROM {node_type} WHERE type = 'mass_contact'"));
        if (!$check) {

          // If the node type does not exist, create it.
          _mass_contact_create_node_type();
        }

        // Save the message as a node.
        _mass_contact_save_node($subject, $node_body, $recipientout, $contact->category, $roles, $user->uid, $has_attachments);
      }

      // Log the operation.
      flood_register_event('mass_contact');
      watchdog('mass_contact', t('%name-from sent an e-mail to the %category group.', array(
        '%name-from' => $form_values['name'] . " <{$from}>",
        '%category' => $contact->category,
      )));

      // Inform the user.
      drupal_set_message(t('The message was successfully sent to @total user(s). (See <a href="@log_link">Drupal\'s logs</a> for the list of recepients.)', array(
        '@total' => $total_recip,
        '@log_link' => url('admin/logs/watchdog'),
      )));
    }
    else {
      drupal_set_message(t('One or more errors were encountered sending the message. Check <a href="@log_link">Drupal\'s logs</a> and the mail server\'s logs and try again.', array(
        '@log_link' => url('admin/logs/watchdog'),
      )));
    }
  }

  // Jump to home page rather than back to mail page to avoid
  // contradictory messages if flood control has been activated.
  return '';
}