<?php
// $Id: mail_wrapper.inc,v 1.1.2.1 2007/03/26 17:30:20 z0rac Exp $

function _jbox_mime_header($string, $encoding = 'UTF-8', $indent = 1) {
  if (preg_match('/[^\x20-\x7E]/', $string)) {
    $limit = 76 - strlen('=?'. $encoding .'?B??=');
    $output = '';
    for ($len = drupal_strlen($string); $len > 0; $len -= $c) {
      $c = $len;
      $chunk = base64_encode(jbox_convert_encoding($string, $encoding));
      while ($c > 1 && strlen($chunk) + $indent > $limit) {
        $c = intval($c * 2 / 3);
        $chunk = base64_encode(jbox_convert_encoding(drupal_substr($string, 0, $c), $encoding));
      }
      $output .= ' =?'. $encoding .'?B?'. $chunk ."?=\n";
      $string = drupal_substr($string, $c);
      $indent = 1;
    }
    return trim($output);
  }
  return $string;
}

function drupal_mail_wrapper($mailkey, $to, $subject, $body, $from, $headers) {
  $encoding = 'ISO-2022-JP';
  $ct = array(
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/plain; charset='. $encoding,
    'Content-Transfer-Encoding' => '7bit'
  );

  if (function_exists('mb_send_mail')) {
    foreach ($headers as $name => $value) {
      if (isset($ct[$name])) continue;
      $ha[] = $name .': '. $value;
    }
    $lang = mb_language();
    mb_language('ja');
    $ok = mb_send_mail($to, $subject, str_replace("\r", '', $body), join("\n", $ha));
    mb_language($lang);
    return $ok;
  }
  $subject = _jbox_mime_header($subject, $encoding, strlen('Subject: '));
  $body = jbox_convert_encoding(str_replace("\r", '', $body), $encoding);
  foreach (array_merge($headers, $ct) as $name => $value) {
    $ha[] = $name .': '. _jbox_mime_header($value, $encoding, strlen($name) + 2);
  }

  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(
    $to,
    str_replace("\n", "\r\n", $subject),
    str_replace("\n", "\r\n", $body),
    str_replace("\n", "\r\n", join("\n", $ha))
  );
}
