<?php
// $Id: htmlmail.module,v 1.9.2.28 2010/02/26 06:15:52 chrisherberte Exp $

/**
 * @file
 * Send system emails in HTML
 */

/**
 * Implementation of hook_help().
 */
function htmlmail_help($path, $arg) {
  switch ($path) {
    case 'admin/help#htmlmail':
    case 'admin/settings/htmlmail':
      $output = '<p>' . t("HTML Mail provides formatting and semantic markup capabilities in e-mail that are not available with plain text. All system emails are effected if this module is enabled.") . '</p>';
    return $output;
  }
}

/**
 * Implementation of hook_menu().
 */
function htmlmail_menu() {
  $items['admin/settings/htmlmail'] = array(
    'title' => 'HTML Mail',
    'description' => 'Configure HTML Mail system-wide settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('htmlmail_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'htmlmail.admin.inc',
   );
  $items['admin/settings/htmlmail/settings'] = array(
    'title' => 'Settings',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => '-2'
  );
  $items['admin/settings/htmlmail/template'] = array(
     'title' => 'Template',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('htmlmail_template_settings'),
     'access arguments' => array('access administration pages'),
     'type' => MENU_LOCAL_TASK,
     'weight' => '-1',
     'file' => 'htmlmail.admin.inc',
   );
  $items['admin/settings/htmlmail/test'] = array(
     'title' => 'Send Test',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('htmlmail_test_form'),
     'access arguments' => array('access administration pages'),
     'type' => MENU_LOCAL_TASK,
     'file' => 'htmlmail.admin.inc',
   );
  return $items;
}

/**
 * Implementation of hook_mail_alter().
 */
function htmlmail_mail_alter(&$message) {

	//ALOPEZ:11/05/2010
  //$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed;';
	$message['headers']['Content-Type'] = 'text/html; charset=ISO-8859-1; format=flowed;';
  
  // message body may be an array
  $message['body'] = is_array($message['body']) ? implode("\n\n", $message['body']) : $message['body'];

  // The paragraph an break stuff
  if (variable_get('htmlmail_autop', '1')) {
    $message['body'] = _filter_autop($message['body']);
  }

  if (variable_get('htmlmail_urlfilter', '1')) {
  // defaults to 72 as there is no filter 0 -- make filters a configuration option?
    $message['body'] = _filter_url($message['body'], 0);
  }

  // Theme from template htmlmail.tpl.php
  $message['body'] = theme('htmlmail', $message['body']);

  if (variable_get('htmlmail_emogrifier', '0')) {
    $message['body'] = _htmlmail_emogrify($message);
  }

  // Convert relative urls to absolute if rel_to_abs is enabled.
  if (module_exists('rel_to_abs') && variable_get('htmlmail_rel_to_abs', 1)) {
    $message['body'] = rel_to_abs_filter('prepare', 0, -1, $message['body']);
  }
}

/**
 * Implementation of hook_theme().
 */
function htmlmail_theme() {
  $items['htmlmail'] = array(
    'template' => 'htmlmail',
    'arguments' => array('body' => NULL),
  );
  
  if (module_exists('token')) {
    $items['htmlmail_token_help'] = array(
      'arguments' => array('prefix' => '[', 'suffix' => ']'),
    );
  }
  return $items;
}

/**
 *  Token support
 */ 
function theme_htmlmail_token_help($prefix = '[', $suffix = ']') {
  token_include();

  $full_list = array_merge(token_get_list('user'), token_get_list('profile'));

  $headers = array(t('Token'), t('Replacement value'));
  $rows = array();
  foreach ($full_list as $key => $category) {
    $rows[] = array(array('data' => drupal_ucfirst($key) .' '. t('tokens'), 'class' => 'region', 'colspan' => 2));
    foreach ($category as $token => $description) {
      $row = array();
      $row[] = $prefix . $token . $suffix;
      $row[] = $description;
      $rows[] = $row;
    }
  }
  $output = theme('table', $headers, $rows, array('class' => 'description'));
  return $output;
}


/**
 * Process variables to format e-mail.
 *
 * @see htmlmail.tpl.php
 */
function template_preprocess_htmlmail(&$variables) {
  // path for linking images -- do we need this with tokens??
  $variables['path'] = url($variables['directory'], array('absolute' => TRUE));
  if (module_exists('token') && variable_get('htmlmail_token', '0')) {
    global $user;
    $types = array('user' => $user, 'profile' => $user);
  
    $variables['header'] = token_replace_multiple(variable_get('htmlmail_header', ''), $types);
    $variables['footer'] = token_replace_multiple(variable_get('htmlmail_footer', ''), $types);
  }
  else {
    $variables['header'] = variable_get('htmlmail_header', '');
    $variables['footer'] = variable_get('htmlmail_footer', '');
  }
  $variables['css'] = variable_get('htmlmail_css', '');
}


/**
 * Implementation of hook_mail().
 */
function htmlmail_mail($key, &$message, $params) {
  switch ($key) {
  case 'htmlmail_test':
    $message['subject'] = $params['subject'];
    $message['body'] = $params['body'];
    break;
  }
}

/**
 * If the Emogrifier <http://www.pelagodesign.com/sidecar/emogrifier/> exists,
 * the CSS styles inside the the $message['body'] are inserted into the other
 * HTML tags within the same $message['body'] as inline style attributes, 
 * based on CSS selectors.
 *
 * This function is based on code in the simplenews_template module.
 *
 * This emogrifier differs from that of simplenews_template in that it permits
 * modules or users to adjoin CSS into the $message['body'] using the HTML 
 * <style> tag.  The function searches the entire body for style tags, 
 * concatenates them in order of appearance in the file, then sends them to
 * the Emogrifier script. 
 *
 * Note that the method modifies the $message['body'] directly, and the 
 * return value is the modified $message['body'] string as well. 
 *
 * @param $message
 *           The message array to be sent. This function works directly 
 *           on the $message['body'].
 * @return $message['body']
 *           The modified message body string with inlined CSS applied.
 */
function _htmlmail_emogrify(&$message) {
  $path = drupal_get_path('module', 'htmlmail') . '/emogrifier/emogrifier.php';
  if (is_file($path)) {
    $style = array();
    // Pull out the contents of any style tags
    if (preg_match_all("@<style[^>]*>(.*)</style>@Usi", $message['body'], $matches, PREG_PATTERN_ORDER)) {
      $style = $matches[1];
    }
    // Emogrify can't handle several CSS rules on one line. As a precaution,
    // we therefore insert LF after each closing bracket.
    $style = preg_replace('/}\s*/', "}\n", implode("\n", $style));

    // Inline the CSS rules.
    include_once $path;
    // get and reset error levels so we dont get DOMDocument::loadHTML() errors
    $errorlevel = error_reporting();
    error_reporting(0);
    $emogrifier = new Emogrifier($message['body'], $style);
    $message['body'] = $emogrifier->emogrify();
    error_reporting($errorlevel);
  }
  return $message['body'];
}
