You are here

function mail_logger_mail_alter in Mail Logger 7

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

Implements hook_mail_alter().

Purpose of this function is to log all outgoing mail

File

./mail_logger.module, line 101
Mail Logger module logs all outgoing mail that passes through the drupal_mail function.

Code

function mail_logger_mail_alter(&$message) {
  if (!empty($message['send'])) {
    $system = drupal_mail_system($message['module'], $message['key']);
    $mail_system = get_class($system);
    $logger = $system
      ->format($message);
    $logger['date_sent'] = REQUEST_TIME;
    if (!isset($logger['language'])) {
      $language = LANGUAGE_NONE;
    }
    else {
      $language = is_object($logger['language']) ? $logger['language']->language : $logger['language'];
    }

    // Process headers with mime_header_decode() in case they are encoded.
    $empty = variable_get('mail_logger_log_empty_to', '* empty *');
    $logger['to'] = mime_header_decode(empty($logger['to']) ? t($empty) : $logger['to']);
    $logger['from'] = mime_header_decode($logger['from']);
    foreach ($logger['headers'] as $key => $val) {
      $logger['headers'][$key] = mime_header_decode($val);
    }
    $record = array(
      'mailkey' => $logger['id'],
      'mailto' => $logger['to'],
      'subject' => $logger['subject'],
      'body' => variable_get('mail_logger_log_mail_body', TRUE) ? $logger['body'] : t(variable_get('mail_logger_log_exclude_text', '[MESSAGE BODY EXCLUDED]')),
      'mailfrom' => $logger['from'],
      'headers' => serialize($logger['headers']),
      'date_sent' => $logger['date_sent'],
      'language' => $language,
      'ipaddr' => $_SERVER['REMOTE_ADDR'],
      'mail_system' => $mail_system,
    );
    $db_specs = drupal_get_schema('mail_logger');

    // Allow record to be altered.
    $context = array(
      'operation' => 'write',
    );
    drupal_alter('mail_logger_record', $record, $context);
    foreach ($record as $field_name => $value) {
      if (isset($db_specs[$field_name]['length'])) {
        $record[$field_name] = substr($value, $db_specs[$field_name]['length']);
      }
    }
    db_insert('mail_logger')
      ->fields($record)
      ->execute();

    // Fire 'mail_logger' 'mail_sent' action.
    module_invoke_all('mail_logger', 'mail_sent', $message, user_load_by_mail($message['from']), user_load_by_mail($message['to']));
  }
}