#!/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[2]))
{
        $flag = 'on';
}else{
        $flag = $argv[2];
}

if (!isset($argv[3]))
{
        $maxlength = 0;
}else{
        $maxlength = $argv[3];
}

if (!isset($argv[1]))
{
         throw new Exception('Forward address is not specified!');
}else{

        $to = $argv[1];
}

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

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

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

/*
 mode 1 NULL
 mode 2 DOMAINADMIN
 mode 3 OWNUSER
*/

$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);

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

// メール取得
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();

if (!PEAR::isError($parts)) {
	list( $recipients, $headers, $body ) = $parts;
}else{
       throw new Exception('This mail headers is broken!');
}

$headernom = $headers;

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

$mailmw = Mail::factory("smtp2",$smtparam);

$headcon_para['include_bodies'] = false;
$headcon_para['decode_bodies'] = false;
$headcon_para['decode_headers'] = true;

$headcon = $decoder->decode($headcon_para);

$params['include_bodies'] = true;
$params['decode_bodies'] = true;
$params['decode_headers'] = true;
$structure = $decoder->decode($params);

// $subject = mb_decode_mimeheader( $structure->headers['subject'] ) ;
$subject = $structure->headers['subject'];
$from = $structure->headers['from'];

$body_re = getbody($structure);
$str_body = $body_re['body'];

$headers2 = array_change_key_case($headers, CASE_LOWER);

$headersmw = array(
          "To" => $to,
	 "From" => $headers2['from'],
         "Subject" => $headers2['subject']	
);

$headersmw2 = array(
   	"To" => $to,
	"From" => $headers2['from'],
        "Subject" => $headers2['subject'],	
);


if (array_key_exists('mime-version', $structure->headers)) {
	$headersmw2 += array("Mime-Version" => $structure->headers['mime-version']);
}

if (array_key_exists('content-transfer-encoding', $structure->headers)) {
        $headersmw2 += array("Content-Transfer-Encoding" => $structure->headers['content-transfer-encoding']);
}


if (array_key_exists('content-type', $structure->headers)) {
        $headersmw2 += array("Content-Type" => $structure->headers['content-type']);
}

if (array_key_exists('content-disposition', $structure->headers)) {
        $headersmw2 += array("Content-Disposition" => $structure->headers['content-disposition']);
}

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 = '';
}


if (preg_match("/on/",$flag)){

        // メールの内容 （タイトル・送信者・メール本文）

	
//	$subject = mb_decode_mimeheader( $headers['Subject'] ) ;
//        #$from = mb_decode_mimeheader( $headers['From'] ) ;
//        $from = $headers['From'];

//        $params['include_bodies'] = true;
//        $params['decode_bodies'] = true;
//        $params['decode_headers'] = true;
//        $structure = $decoder->decode($params);
//        $body_re = getbody($structure);
//       	 $str_body = $body_re['body'];
        
	 $fp = fopen("file8.eaml","w");
         fputs($fp,$str_body);
         fputs($fp,"ggg:\n");

        $bodymw = mb_convert_encoding($str_body,"JIS","UTF-8");

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

         fputs($fp,$body_re['bodyflag']);
         fputs($fp,"ggg:\n");
         fputs($fp,$body_re['htmlflag']);
         fputs($fp,"\n");
         fclose($fp);
	
        // ##### attachmen remove #######
        // #$### char count ########################
        if ($body_re['bodyflag'] == 1 && $body_re['htmlflag'] == 1){
                $parammw['content_type'] = 'multipart/mixed';
                $mime32 = new Mail_mimePart('', $parammw);
                $mime32->_headers['Subject'] =  mb_encode_mimeheader(mb_convert_encoding($subject,"JIS","UTF-8"));
       		$mime32->_headers['From'] = mb_convert_encoding($headers['From'],"JIS","UTF-8");
                $mime32->_headers['To'] = $to;

                $parammw['content_type'] = 'text/plain';
                $parammw['encoding'] = '7bit';
                $mime32->addSubPart($bodymw, $parammw);

                $html_body = $body_re['html'];
                $html_body = mb_convert_encoding($html_body,"JIS","UTF-8");
                $parammw['content_type'] = 'text/html';
                $parammw['encoding'] = '7bit';
                $htmlre = & $mime32->addSubPart($html_body, $parammw);
                $str_body = $mime32->encode();
                $str_bodyf = $str_body['body'];

                if ($maxlength != 0 ) {
                        $size_len2 = 0;
                        $size_len2 = mb_strlen($str_bodyf);
                        if ($size_len2 > $maxlength){
                                $str_bodyf = substr($str_bodyf,0,$maxlength);
                        }
                }		
                $return = $mailmw->send($to,$str_body['headers'],$str_bodyf,$envfrom,$mode);
        }else if($body_re['bodyflag'] == 1)
        {
                $mimemw = new Mail_Mime("\n");
                $mimemw->setTxtBody($bodymw);

                $str_body = $mimemw->get($BodyParam);

                if ($maxlength != 0 ) {
                        $size_len2 = 0;
                        $size_len2 = mb_strlen($str_body);
                        if ($size_len2 > $maxlength){
                                $str_body = substr($str_body,0,$maxlength);
                        }
                }

                $return = $mailmw->send($to,$headersmw,$str_body,$envfrom,$mode);
        }else if($body_re['htmlflag'] == 1){

                $mimemw = new Mail_Mime("\n");
                $html_body = $body_re['html'];
                $html_body = mb_convert_encoding($html_body,"JIS","UTF-8");

                $mimemw->setHTMLBody($html_body);
                $str_body = $mimemw->get($BodyParam);

                $headershtml = $mimemw -> headers($headersmw);

                if ($maxlength != 0 ) {
                        $size_len2 = 0;
                        $size_len2 = mb_strlen($str_body);
                        if ($size_len2 > $maxlength){
                                $str_body = substr($str_body,0,$maxlength);
                        }
                }
                $return = $mailmw->send($to,$headershtml,$str_body,$envfrom,$mode);
        }
}else{

                if ($maxlength != 0){
                        $size_len2 = 0;
                        $size_len2 = mb_strlen($body);

                        if ($size_len2 > $maxlength){
                                $body = mb_substr($body,0,$maxlength);
                        }
                }

                $return = $mailmw->send($to,$headersmw2,$body,$envfrom,$mode);
}

function getbody($structure) {
	static	$bodyflag =0,$htmlflag	= 0;
	static	$ary = array();
	static	$bodydata,$htmldata;
	
	$cprimary =	trim($structure->ctype_primary);
	if (strcasecmp($cprimary,"text") ==	0) {
		if(strcasecmp($structure->ctype_secondary,"html") == 0)	{
			$htmldata .= multi_encode($structure->body);
			$htmlflag  = 1;
		}else {
			$bodydata  .= multi_encode($structure->body);
			$bodyflag =	1;
		}
	}elseif	(strcasecmp($cprimary,"multipart") == 0) {
		foreach	($structure->parts as $part) {
			if ((!isset($part->disposition)) &  strcasecmp($part->disposition,"attachment") != 0) {
				if (strcasecmp($part->ctype_primary,"text")	== 0) {
					if (strcasecmp($part->ctype_secondary,"plain") == 0) {
						$bodydata .= multi_encode($part->body);
						$bodydata .= "\n";
						$bodyflag =	1;
						} else {
						$htmldata .= multi_encode($part->body);
						$htmldata .= "\n";
						$htmlflag =	1;
						}
					}elseif(strcasecmp($part->ctype_primary,"multipart") ==	0 ){
					if(is_array($part->parts)){
						foreach($part->parts as	$ix => $sub_part){
							getbody($sub_part);
							}
						}
					}
			}
		}
	}
	$resdata = array("body"=> $bodydata, "bodyflag"	=> $bodyflag, "html" =>	$htmldata, "htmlflag" => $htmlflag);
	return $resdata;
}
function multi_encode($data){
	$data1 = "";
	$data1 = mb_convert_encoding($data,"UTF-8",mb_detect_order());
	return $data1;
}
?>


