<?php
// $Id: mail_wrapper.inc,v 1.1.2.2 2008/07/25 16:03:50 z0rac Exp $

function _jbox_mime_encode($text, $pre, $cs = 'UTF-8') {
  static $pat = '/^([^\x80-\xFF]*[\t ]+)?((?:[\t ]*[^\t ]*[\x80-\xFF][^\t ]*)+)/s';
  $b64s = strlen($cs) + 7; // '=??B??='
  $line = array();
  while (preg_match($pat, $text, $word)) {
    if ($word[1] != '') {
      if ($pre != '' && strlen($pre) + strlen($word[1]) > 76) {
        $line[] = $pre;
        $pre = ' ';
        if (strspn($word[1], "\t ")) {
          $pre = $word[1];
          $word[1] = '';
        }
      }
      $pre .= $word[1];
      if (strlen($pre) + $b64s > 64) {
        $line[] = substr($pre, 0, -1);
        $pre = substr($pre, -1);
      }
    }
    for ($len = drupal_strlen($word[2]); $len; $len -= $n) {
      $limit = 76 - strlen($pre) - $b64s;
      if ($limit < 12) {
        $line[] = $pre;
        $pre = ' ';
        $limit = 75 - $b64s;
      }
      $n = $len;
      $chunk = base64_encode(jbox_convert_encoding($word[2], $cs));
      while ($n > 1 && strlen($chunk) > $limit) {
        $n = intval($n * 2 / 3);
        $chunk = base64_encode(jbox_convert_encoding(drupal_substr($word[2], 0, $n), $cs));
      }
      $word[2] = drupal_substr($word[2], $n);
      $line[] = $pre .'=?'. $cs .'?B?'. $chunk .'?=';
      $pre = ' ';
    }
    $pre = array_pop($line);
    $text = substr($text, strlen($word[0]));
  }
  if ($text != '' && $pre != '' && strlen($pre) + strlen($text) > 76) {
    $line[] = $pre;
    $pre = ' ';
  }
  $line[] = $pre . $text;
  return $line;
}

function _jbox_mime_header($field, $indent, $cs = 'UTF-8') {
  $field = str_replace("\r", '', $field);
  if (preg_match('/[\x80-\xFF]/', $field)) {
    $line = array();
    $pre = str_repeat(' ', $indent);
    while ($field != '') {
      if ($n = strcspn($field, "\n()<>,\\\"")) {
        $line = array_merge($line, _jbox_mime_encode(substr($field, 0, $n), $pre, $cs));
        $pre = array_pop($line);
        $field = substr($field, $n);
        if ($field == '') break;
      }
      $shift = 1;
      if ($field[0] === "\n") {
        $line[] = $pre;
        $pre = '';
      }
      elseif (preg_match('/^"(?:\\\\.|.+)*"/Us', $field, $text)) {
        $shift = strlen($text[0]);
        $text = explode("\n", $text[0]);
        $quo = array_shift($text);
        if ($pre != '' && strlen($pre) + strlen($quo) > 76) {
          $line[] = $pre;
          $pre = ' ';
        }
        $line[] = $pre . $quo;
        $line = array_merge($line, $text);
        $pre = array_pop($line);
      }
      else {
        if ($field[0] === '\\') {
          $shift = 2;
        }
        elseif (preg_match('/^<[^\n()<\\\\"\x80-\xFF]*>/U', $field, $text)) {
          $shift = strlen($text[0]);
        }
        if ($pre != '' && strlen($pre) + $shift > 76) {
          $line[] = $pre;
          $pre = ' ';
        }
        $pre .= substr($field, 0, $shift);
      }
      $field = substr($field, $shift);
    }
    $line[] = $pre;
    $field = substr(implode("\n", $line), $indent);
  }
  return rtrim($field);
}

function drupal_mail_wrapper($mailkey, $to, $subject, $body, $from, $headers) {
  $charset = 'ISO-2022-JP';
  $ct = array(
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/plain; charset='. $charset,
    'Content-Transfer-Encoding' => '7bit'
  );
  $ha = array();
  foreach ($headers as $name => $value) {
    if (!isset($ct[$name])) {
      $ha[] = $name .': '. _jbox_mime_header($value, strlen($name) + 2, $charset);
    }
  }
  $to = _jbox_mime_header($to, 4, $charset);
  $body = str_replace("\r", '', $body);

  if (function_exists('mb_send_mail')) {
    $lang = mb_language();
    mb_language('ja');
    $ok = mb_send_mail($to, $subject, $body, join("\n", $ha));
    mb_language($lang);
    return $ok;
  }

  foreach ($ct as $name => $value) {
    $ha[] = $name .': '. $value;
  }
  $subject = _jbox_mime_header($subject, 9, $charset);
  $body = jbox_convert_encoding($body, $charset);

  if ($sendmail = ini_get('sendmail_path') and $h = popen($sendmail, 'w')) {
    $ok = fwrite($h, 'To: '. $to ."\nSubject: ". $subject ."\n". join("\n", $ha) ."\n");
    $ok = $ok && fwrite($h, "\n". $body ."\n");
    pclose($h);
    return $ok;
  }
  return mail(
    str_replace("\n", "\r\n", $to),
    str_replace("\n", "\r\n", $subject),
    str_replace("\n", "\r\n", $body),
    str_replace("\n", "\r\n", join("\n", $ha))
  );
}
