You are here

function _contact_attach_process_attachments in Contact Attach 7

Same name and namespace in other branches
  1. 5 contact_attach.module \_contact_attach_process_attachments()
  2. 6 contact_attach.module \_contact_attach_process_attachments()

Checks for attachments and processes them, if one or more exist.

Parameters

array $message: The message, as it exists so far.

Return value

array The message, including processed attachment(s).

1 call to _contact_attach_process_attachments()
contact_attach_mail_alter in ./contact_attach.module
Implements hook_mail_alter().

File

./contact_attach.module, line 326
Allows attaching files to messages sent using contact forms.

Code

function _contact_attach_process_attachments($message) {
  $return_message = array();
  if ($message['params']['file_field_type'] === 'managed_file') {

    // Loop through each possible attachment when using managed_file fields.
    for ($i = 1; $i <= $message['params']['attachments_allowed']; $i++) {
      if ($message['params']['contact_attach_' . $i] !== 0) {

        // An attachment exists, so save it to an array for later processing.
        $files[] = file_load($message['params']['contact_attach_' . $i]);
      }
    }
  }
  else {

    // Loop through each possible attachment when using simple file fields.
    foreach ($_FILES['files']['name'] as $temp_name => $file_name) {
      if ($file = file_save_upload($temp_name)) {

        // Check to see if the attachment exists.
        if ($file->filesize > 0) {

          // An attachment exists, so save it to an array for later processing.
          $files[] = $file;
        }
      }
    }
  }

  // If the array contains something, we have one or more attachments to
  // process. If it does not contain anything, we send back an empty $body,
  // indicating no attachments exist.
  if (!empty($files)) {

    // Set initial values.
    $attachments = '';
    $body_text = '';
    $boundary_id = md5(uniqid(time()));
    $mail_system = variable_get('mail_system', array());
    $message['headers']['Content-Type'] = 'multipart/mixed; boundary="' . $boundary_id . '"';

    // Add the body text.
    $body_text = "\n--{$boundary_id}\n";
    $body_text .= "Content-Type: text/plain; charset=UTF-8; format=flowed;\n\n";
    $body_text .= implode("\n\n", $message['body']);
    $body_text .= "\n\n\n";

    // Add the attachments.
    // Loop through each possible attachment.
    foreach ($files as $file_object) {

      // Process the attachment.
      $attachments .= "--{$boundary_id}\n";
      $attachments .= _contact_attach_add_attachment($file_object, $mail_system);
      $attachments .= "\n\n";
    }
    $attachments .= "--{$boundary_id}--\n\n";
    $return_message['headers'] = $message['headers'];
    $return_message['body'][0] = $body_text;
    $return_message['body'][1] = $attachments;
  }
  return $return_message;
}