You are here

function mass_contact_mail_page_submit in Mass Contact 6

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. 7 mass_contact.page.inc \mass_contact_mail_page_submit()

Processes the main Mass Contact mail form.

Parameters

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

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

File

./mass_contact.module, line 1428
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, &$form_state) {

  // Initialize some variables.
  $character_set = variable_get('mass_contact_character_set', '') ? variable_get('mass_contact_character_set', '') : 'UTF-8';
  $body_plain = '';
  $boundary_html = md5(uniqid(mt_rand()));
  $body_html = '';
  $message = '';
  $has_attachments = 0;
  $boundary_attachment = md5(uniqid(mt_rand()));
  $message_attachment = array();
  $params = array();
  $send_error = 0;
  $bcc = variable_get('mass_contact_bcc_d', 1);

  // Only set $bcc if the user is allowed to override the BCC setting.
  if (variable_get('mass_contact_bcc_d_override', 0) == 1) {

    // The user is allowed to override the setting, so use that one instead.
    $bcc = $form_state['values']['bcc'];
  }
  $nodecc = variable_get('mass_contact_nodecc_d', 1);

  // Only set $nodecc if the user is allowed to override the archive setting.
  if (variable_get('mass_contact_nodecc_d_override', 0) == 1) {

    // The user is allowed to override the setting, so use that one instead.
    $nodecc = $form_state['values']['nodecc'];
  }

  // Specify the sender's name.
  $from_name = variable_get('mass_contact_default_sender_name', '');

  // Specify the sender's email address.
  $from_email = variable_get('mass_contact_default_sender_email', '');
  if (empty($from_name) || empty($from_email) || variable_get('mass_contact_default_sender_changable', 0) == 1) {

    // User is allowed to change the default from address and name,
    // so we check the form for submitted values.
    if (isset($form_state['values']['name']) && !empty($form_state['values']['name'])) {

      // The user is allowed to override the setting, so use that one instead.
      $from_name = $form_state['values']['name'];
    }
    if (isset($form_state['values']['mail']) && !empty($form_state['values']['mail'])) {

      // The user is allowed to override the setting, so use that one instead.
      $from_email = $form_state['values']['mail'];
    }
  }
  if (variable_get('mass_contact_include_from_name', 0) == 1 && !empty($from_name)) {
    $from_address = '"' . $from_name . '" <' . $from_email . '>';
  }
  else {
    $from_address = $from_email;
  }
  $html = variable_get('mass_contact_html_d', 1);

  // Check if the user is allowed override the HTML setting.
  if (variable_get('mass_contact_html_d_override', 0) == 1) {

    // The user is allowed to override the setting, so use that one instead.
    $html = $form_state['values']['html'];
  }
  $html_format = variable_get('mass_contact_html_format', FILTER_FORMAT_DEFAULT);

  // Check if the user is allowed to override the input format setting.
  if (variable_get('mass_contact_html_format_override', 0)) {

    // The user is allowed to override the setting, so use that one instead.
    $html_format = $form_state['values']['mass_contact_html_format'];
  }

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

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

  // Create the body part(s) of the message.
  // Intialize some variables for use during the creation of the message body.
  $message_prefix = variable_get('mass_contact_message_prefix', '');
  $prefix_format = variable_get('mass_contact_prefix_format', FILTER_FORMAT_DEFAULT);
  $message_suffix = variable_get('mass_contact_message_suffix', '');
  $suffix_format = variable_get('mass_contact_suffix_format', FILTER_FORMAT_DEFAULT);
  $token_module_exists = module_exists('token');
  $check_markup = variable_get('mass_contact_check_markup', 1);

  // Create the plain text body. We now always create a plain text body.
  if ($html) {

    // If this is supposed to be an HTML e-mail, we need to process the plain
    // text part differently.
    // Start with the message prefix.
    if ($message_prefix) {
      if ($token_module_exists) {
        if ($check_markup) {
          $body_plain .= drupal_html_to_text(check_markup(token_replace($message_prefix), $prefix_format)) . "\n";
        }
        else {
          $body_plain .= drupal_html_to_text(token_replace($message_prefix)) . "\n";
        }
      }
      elseif ($check_markup) {
        $body_plain .= drupal_html_to_text(check_markup($message_prefix, $prefix_format)) . "\n";
      }
      else {
        $body_plain .= drupal_html_to_text($message_prefix) . "\n";
      }
    }

    // Add in the actual message.
    if ($check_markup) {
      $body_plain .= drupal_html_to_text(check_markup($form_state['values']['message'], $html_format)) . "\n";
    }
    else {
      $body_plain .= drupal_html_to_text($form_state['values']['message']) . "\n";
    }

    // End with the message suffix.
    if ($message_suffix) {
      if ($token_module_exists) {
        if ($check_markup) {
          $body_plain .= drupal_html_to_text(check_markup(token_replace($message_suffix), $suffix_format));
        }
        else {
          $body_plain .= drupal_html_to_text(token_replace($message_suffix));
        }
      }
      elseif (variable_get('mass_contact_check_markup', 1)) {
        $body_plain .= drupal_html_to_text(check_markup($message_suffix, $suffix_format));
      }
      else {
        $body_plain .= drupal_html_to_text($message_suffix);
      }
    }
  }
  else {

    // Start with the message prefix.
    if ($message_prefix) {
      if ($token_module_exists) {
        $body_plain .= wordwrap(token_replace($message_prefix)) . "\n";
      }
      else {
        $body_plain .= wordwrap($message_prefix) . "\n";
      }
    }

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

    // End with the message suffix.
    if ($message_suffix) {
      if ($token_module_exists) {
        $body_plain .= wordwrap(token_replace($message_suffix));
      }
      else {
        $body_plain .= wordwrap($message_suffix);
      }
    }
  }

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

    // Start with the message prefix.
    if ($message_prefix) {
      if ($token_module_exists) {
        if ($check_markup) {
          $body_html .= check_markup(token_replace($message_prefix), $prefix_format);
        }
        else {
          $body_html .= token_replace($message_prefix);
        }
      }
      elseif ($check_markup) {
        $body_html .= check_markup($message_prefix, $prefix_format);
      }
      else {
        $body_html .= $message_prefix;
      }
    }

    // Add in the actual message.
    if ($check_markup) {
      $body_html .= check_markup($form_state['values']['message'], $html_format);
    }
    else {
      $body_html .= $form_state['values']['message'];
    }

    // End with the message suffix.
    if ($message_suffix) {
      if ($token_module_exists) {
        if ($check_markup) {
          $body_html .= check_markup(token_replace($message_suffix), $suffix_format);
        }
        else {
          $body_html .= token_replace($message_suffix);
        }
      }
      elseif ($check_markup) {
        $body_html .= check_markup($message_suffix, $suffix_format);
      }
      else {
        $body_html .= $message_suffix;
      }
    }
  }

  // Put it all together.
  // Check to see if we have either an attachment or an HTML message.
  if ($has_attachments || $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 && $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 ($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 ($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";
    }
  }
  $params['body'] = $message;

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

  //
  //  @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.
  $cids = array();
  foreach ($form_state['values']['cid'] as $cid) {
    $cids[] = $cid;
  }
  $result = db_query("SELECT * FROM {mass_contact} WHERE cid IN(" . db_placeholders($cids) . ")", $cids);
  while ($contact = db_fetch_object($result)) {
    if (!user_access('send to users in the ' . $contact->category . ' category')) {
      break;
    }

    // Format the subject line.
    if (variable_get('mass_contact_category_override', 1)) {
      $params['subject'] = t('[!category] !subject', array(
        '!category' => $contact->category,
        '!subject' => $form_state['values']['subject'],
      ));
    }
    else {
      $params['subject'] = $form_state['values']['subject'];
    }
    $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_state['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 <> %d AND uid > %d", 0, 0);
        while ($obj = db_fetch_object($recipients)) {
          $rname = $obj->name;
          $rmail = $obj->mail;
          $ruid = $obj->uid;
          if ($rname != $user->name && !$uidooa[$ruid]) {

            //          if (!$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 <> %d", $r, 0);
        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]) {

              //            if (!$uidooa[$ruid]) {
              $recipientouta[$rname] = $rmail;
            }
          }
          else {
            if ($rname != $user->name) {
              $recipientouta[$rname] = $rmail;
            }
          }
        }
      }
    }

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

    // Check for empty recipient list.
    if (count($recipientouta) == 0) {
      drupal_set_message(t('Either there are no users in the "!category" category, or you are the only user in that category, and therefore, the message was not sent to that category.', array(
        '!category' => $contact->category,
      )));
      $form_state['redirect'] = '';
    }
    else {
      $recipientout = array();
      if (count($recipientouta) > $recip_limit && $recip_limit != 0) {
        $countrecip = 0;
        $ccc = 0;
        foreach ($recipientouta as $rnamea => $rmaila) {
          if (variable_get('mass_contact_include_to_name', 0) == 1) {
            $recipientout[] = '"' . $rnamea . '" <' . $rmaila . '>';
            $recipient_temp[] = '"' . $rnamea . '" <' . $rmaila . '>';
          }
          else {
            $recipientout[] = $rmaila;
            $recipient_temp[] = $rmaila;
          }
          $countrecip = count($recipient_temp);
          if ($countrecip == $recip_limit) {
            $recipient_send = implode(', ', $recipient_temp);

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

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

            // Send the e-mail to the recipients:

            /*
                        if (module_exists('mimemail') && variable_get('mimemail_alter', 0) == 1) {
                          $body = implode("\n\n", $params['body']);
                          if ($html == 1) {
                            $success = mimemail($from_address, $to, $params['subject'], $body, NULL, $params['headers'], NULL, $message_attachment);
                          }
                          else {
                            $success = mimemail($from_address, $to, $params['subject'], $body, TRUE, $params['headers'], $body, $message_attachment);
                          }
                        }
                        else {
            */
            if (empty($send_with_cron)) {

              // Send the message. Save the inverse of the result for tallying.
              $success = _mass_contact_send_message('mail_page_' . $ccc, $to, $params, $from_address, '[Success] Sent batch #' . $ccc . '.');
              if ($success['result']) {
                drupal_set_message(t('[Success] Send #!ccc: -e-mails', array(
                  '!ccc' => $ccc,
                  '-e-mails' => $recipient_send,
                )));
              }
              else {
                ++$send_error;
              }
            }
            else {

              // Create the queue.
              include_once drupal_get_path('module', 'drupal_queue') . '/drupal_queue.inc';
              $queue = new SystemQueue('mass_contact');

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

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

              // Inform the user.
              drupal_set_message(t('Batch #' . $ccc . ' was queued for delivery.'));
            }

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

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

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

          // Send the e-mail to the recipients:

          /*
                    if (module_exists('mimemail') && variable_get('mimemail_alter', 0) == 1) {
                      $body = implode("\n\n", $params['body']);
                      if ($html == 1) {
                        $success = mimemail($from_address, $to, $params['subject'], $body, NULL, $params['headers'], NULL, $message_attachment);
                      }
                      else {
                        $success = mimemail($from_address, $to, $params['subject'], $body, TRUE, $params['headers'], $body, $message_attachment);
                      }
                    }
                    else {
          */
          if (empty($send_with_cron)) {

            // Send the message. Save the inverse of the result for tallying.
            $success = _mass_contact_send_message('mail_page_last', $to, $params, $from_address, '[Success] Sent the remainder.');
            if ($success['result']) {
              drupal_set_message(t('[Success] Send Remainder: -e-mails', array(
                '-e-mails' => $recipient_send,
              )));
            }
            else {
              ++$send_error;
            }
          }
          else {

            // Create the queue.
            include_once drupal_get_path('module', 'drupal_queue') . '/drupal_queue.inc';
            $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);

            // Inform the user.
            drupal_set_message(t('The final batch was queued for delivery.'));
          }

          //          }
        }
        $total_recip = count($recipientout);
        $recipientout = implode(', ', $recipientout);
      }
      else {
        foreach ($recipientouta as $rnamea => $rmaila) {
          if (variable_get('mass_contact_include_to_name', 0) == 1) {
            $recipientout[] = '"' . $rnamea . '" <' . $rmaila . '>';
          }
          else {
            $recipientout[] = $rmaila;
          }
        }
        $total_recip = count($recipientout);
        $recipientout = implode(', ', $recipientout);

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

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

        // Send the e-mail to the recipients.

        /*
                if (module_exists('mimemail') && variable_get('mimemail_alter', 0) == 1) {
                  $body = implode("\n\n", $params['body']);
                  if ($html == 1) {
                    $success = mimemail($from_address, $to, $params['subject'], $body, NULL, $params['headers'], NULL, $message_attachment);
                  }
                  else {
                    $success = mimemail($from_address, $to, $params['subject'], $body, TRUE, $params['headers'], $body, $message_attachment);
                  }
                }
                else {
        */

        // This call was changed from drupal_mail() due to this bug report:
        // http://drupal.org/node/473838
        if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) {
          $success = drupal_mail('mass_contact', 'mail_page', $to, language_default(), $params, $from_address);
        }
        else {
          $success = _mass_contact_mail('mass_contact', 'mail_page', $to, language_default(), $params, $from_address);
        }

        //        }
        if ($success['result']) {
          drupal_set_message(t('[Success] Send Once: -e-mails', array(
            '-e-mails' => $recipientout,
          )));
        }
        else {
          ++$send_error;
        }
      }
    }

    // Send a copy to self, if requested.
    if ($form_state['values']['copy'] && !$bcc) {
      if (empty($recipient_limit) && empty($send_with_cron)) {
        $copy_results = _mass_contact_send_message('user-copy', $from_address, $params, $from_address, 'A copy was sent to you.');

        // Inform the user.
        if ($copy_results['result']) {
          drupal_set_message(t('A copy was sent to you.'));
        }
        else {
          if (user_access('access site reports')) {
            drupal_set_message(t('A copy could not be sent to you. Please check the !logs for errors.', array(
              '!logs' => l('logs', 'admin/reports/dblog'),
            )));
          }
          else {
            drupal_set_message(t('A copy could not be sent to you. Please have a system administrator check the logs for errors.'));
          }
        }
      }
      else {

        // Create the queue.
        include_once drupal_get_path('module', 'drupal_queue') . '/drupal_queue.inc';
        $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);

        // Inform the user.
        drupal_set_message(t('A copy to yourself was queued for delivery.'));
      }
    }

    // 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) {

        // Save the message as a node.
        _mass_contact_save_node($params['subject'], $node_message, $recipientout, $contact->category, $roles, $user->uid, $has_attachments, $bcc);
      }

      // Log the operation.
      flood_register_event('mass_contact');
      watchdog('mass_contact', '%name-from sent an e-mail to the %category group.', array(
        '%name-from' => $from_address,
        '%category' => $contact->category,
      ));

      // Inform the user.
      if (count($recipientouta) > 0) {
        drupal_set_message(t('Message sent successfully to !total users: -e-mails', array(
          '!total' => $total_recip,
          '-e-mails' => $recipientout,
        )));
      }
    }
    else {
      if (user_access('access site reports')) {
        drupal_set_message(t('!errors error(s) were encountered sending the message. Please check the !logs for errors.', array(
          '!errors' => $send_error,
          '!logs' => l('logs', 'admin/reports/dblog'),
        )));
      }
      else {
        drupal_set_message(t('!errors error(s) were encountered sending the message. Please have a system administrator check the logs for errors.', 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'] = '';
}