#!/usr/bin/php -q
<?php

require_once("Mail.php");
require_once("Mail/mime.php");
require_once("Mail/mimeDecode2.php");

ini_set("memory_limit","1024M");

mb_language('ja');
mb_internal_encoding("utf-8");

$scriptname = $argv[0];

if (!isset($argv[1]))
{
	 throw new Exception('From address not set!');
}else
{
	$laddr = $argv[1];
}

list($username,$domain) = split("@",$laddr);

$smtp_ct_file = "/etc/mail/mailalert/mailalert.conf";

$modekeyval = "MODE";
$own_master_domain = "DOMAINMASTERNAME";
$master_name = "";
$ownhostname = "";
$mode =  1;
$envfrom = '';

/*

 mode 1 NULL
 mode 2 DOMAINADMIN
 mode 3 OWNUSER
 mode 4 USER( .mailalert.msg from header)
*/

$modearray = array( 'NULL' => 1,'DOMAINADMIN' => 2 , 'OWNUSER' => 3 , 'USER' => 4 );
$modearray = array_change_key_case($modearray, CASE_UPPER);

if (($smtpfile_rs = fopen ($smtp_ct_file, "r"))) {
        while (!feof($smtpfile_rs)) {
                $alert_ct_line = "";
                $alert_ct_line_val = "";
                $alert_ct_line = fgets ($smtpfile_rs);
                $alert_ct_line = preg_replace('/\s+/', ' ', $alert_ct_line);
                $alert_ct_line_val = explode(" ", $alert_ct_line);
                $eo = count($alert_ct_line_val);


                if ( count($alert_ct_line_val) >= 3 ){
                        if ((strcasecmp($alert_ct_line_val[0],$modekeyval) == 0))
                        {
                                $modename = $alert_ct_line_val[1];
                                $modename = str_replace(array("\r\n","\r","\n"), '', $modename);
                                $mode = $modearray[$modename];
                                if ($mode != $modearray['DOMAINADMIN'])
                                {
                                         break;
                                 }

                        }
                        if ((strcasecmp($alert_ct_line_val[0],$own_master_domain) == 0)){

                                    $master_name = $alert_ct_line_val[1];
                                    $master_name = str_replace(array("\r\n","\r","\n"), '', $master_name);
                        }
                }
        }
}

fclose($smtpfile_rs);

$messfilename = "/home/web/".$domain."/users/". $username ."/.mailalert.msg";

$charset_order = 'ISO-2022-JP, SJIS, EUC-JP, UTF-8';
mb_detect_order($charset_order);

$flag = 'on';

// メール取得
if ( ($stdin=fopen("php://stdin",'r')) == true ){
        while( !feof($stdin) ){
                $line_tmp = fgets($stdin,4096);
                $line .= $line_tmp;
        }
}
fclose($stdin);

$decoder = & new Mail_mimeDecode( $line ); // MIMEを分解
$parts = $decoder->getSendArray();
list( $recipients, $headers, $body ) = $parts;

$smtparam = array (
	'host' => 'localhost',
	'port' => '25',
	'auth' => false,
	'username' => '',
	'password' => '', 
);

$mailmw = Mail::factory('smtp2',$smtparam);
$headers2 = array_change_key_case($headers, CASE_LOWER);
$subject2 = mb_decode_mimeheader( $headers2['subject'] ) ;


$from = $headers2['from'];
$date_header = $headers2['date'];
	
$bodymw = mb_convert_encoding($str_body,"JIS","UTF-8");

if ( !($fp2 = fopen ($messfilename , "r"))) {

	throw new Exception('Forward address not $essfilename set!');

}
$alertbody = "";
$truncateline = 0;
while (! feof ($fp2)) {
	$read_now_line = fgets ($fp2, 4096);
	if (preg_match("/^(\s)*(\r|\n|\r\n)/m",$read_now_line))
	{
		$truncateline = 1;
		next;
	}
	
	if ($truncateline == 0 ){
	
		if (preg_match("/^To:\s*(.+)\s*/i",$read_now_line, $matches))
		{
			 $to = $matches[1];
		}
		if (preg_match("/^From:\s*\<(.+)\>\s*/i",$read_now_line, $matches))
		{
			$fromhead = $matches[1];
		}
		if ( preg_match("/^Subject:\s*(.+)$/i",$read_now_line, $matches))
		{
			$subject = $matches[1];
		}	

	}else{
		 $alertbody .= $read_now_line;
	}
}	
fclose ($fp2);

$subject = ereg_replace("\r|\n","",$subject);

if ( !isset($fromhead)) 
{
	$fromhead = $laddr;
}

$headersmw = array(
          "To" => $to,
          "From" => $fromhead,
         "Subject" => mb_encode_mimeheader(mb_convert_encoding($subject,"JIS","UTF-8")),
	 "Content-Type" => "text/plain; charset=ISO-2022-JP"
);

mb_convert_encoding($alertbody, mb_internal_encoding(), mb_detect_order());

$from_decode = mb_decode_mimeheader( $from );

$alertbody = str_replace("%%SUBJECT%%", $subject2, $alertbody);
$alertbody = str_replace("%%FROM%%", $from_decode,$alertbody);
$alertbody = str_replace("%%DATE%%", $date_header,$alertbody);

$bodyalert = mb_convert_encoding($alertbody,"JIS","UTF-8");

$BodyParam = array(
 	"head_charset" => "ISO-2022-JP",
	"text_charset" => "ISO-2022-JP",
	"html_charset" => "ISO-2022-JP"
);

$mimemw = new Mail_Mime("\n");
$mimemw->setTxtBody($bodyalert);
$str_body = $mimemw->get($BodyParam);


switch ($mode){
	case 1:
	  $envfrom = '';
	  break;
	case 2:
	  $envfrom = "$master_name@$domain";
	  if ( (strcasecmp($master_name,"") == 0) || (strcasecmp($domain,'') == 0))
	  {
		$envfrom = '';
       	        $mode = 1;
	  }
	   break;
	case 3:
	  $envfrom = $laddr;
	  break;
	case 4:
	  $envfrom = '';
	  break;
	default:
	   $envfrom = '';
}

$return = $mailmw->send($to,$headersmw,$str_body,$envfrom,$mode);

if (PEAR::isError($return)){
        openlog("mailalertlog", LOG_PID | LOG_PERROR, LOG_LOCAL0);
	$errors = $return->getMessage();
	syslog(LOG_WARNING, "mailalert Send error: $errors");
	closelog();
}

?>

