<?php
/*
 * member/scripts/return.cmd.php
 * 
 * CopyRight(C) 2010 Shopformer Development Team. All Right Reserved
 * URL: http://sourceforge.jp/projects/shopformer/
 * 
 * 
 * Mail: m_nakashima@users.sourceforge.jp
 * Auther: Masanori Nakashima
 * Last Update: 2010-06-18
 * 
 * リターンメールを処理するコマンドスクリプト
 * 2009/03/05
 */
// コマンド共通モジュール取り込み
require_once(dirname(dirname(dirname(__FILE__)))
.DIRECTORY_SEPARATOR.'spider'
.DIRECTORY_SEPARATOR.'spider.cmd.php');
// システム設定クラスの読み込み
require_once(dirname(dirname(dirname(__FILE__)))
.DIRECTORY_SEPARATOR.'system'.DIRECTORY_SEPARATOR.'PackageConfig.class.php');
// DB接続モジュールの読み込み
require_once(dirname(dirname(dirname(__FILE__)))
.DIRECTORY_SEPARATOR.'database2'.DIRECTORY_SEPARATOR.'Connect.class.php');
// 会員パッケージのクラス群取り込み
require_once(dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'PackageConfig.class.php');
// 会員パッケージ共通関数ファイルの読み込み
require_once(dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'functions.inc.php');

//システム設定の取得
$systemConfigurationObject	= new system_PackageConfig();
if( $systemConfigurationObject->load( $GLOBALS['request'] ) ) {
} else {
	echo "Can't load system configuration!\n";
	exit(0);
}
// 設定の取得
$memberConfigurationObject	= new member_PackageConfig();
if( $memberConfigurationObject->load($GLOBALS['request']) ) {
} else {
	echo "Can't load configuration!\n";
	exit(0);
}
// スタンダードインからメールデータを取得
$mail_data		= file_get_contents("php://stdin");
$elements		= explode("\r\n\r\n",$mail_data);
// メールヘッダの取り出し
$header_str		= array_shift($elements);
$header_str		= str_replace("\r\n","\n",$header_str);
$header_str		= str_replace("\n","\n",$header_str);
$header_lines	= explode("\n",$header_str);
$headers		= array();
foreach( $header_lines as $line ) {
	$line		= trim($line);
	$cols		= explode(':',$line);
	$name		= '';
	if( count($cols) > 1 ) {
		$name	= trim(array_shift($cols));
		$val	= trim(implode(':',$cols));
		$headers[$name]	= $val;
	} else if( count($cols) == 1 && strlen(trim($before_name)) > 0 ){
		$val	= trim(array_shift($cols));
		$headers[$before_name]	.= "\n".$val;
	}
	if( strlen($name) > 0 ) {
		$before_name	= $name;
	}
}

// 戻ってきたアドレスを取得
$return_address		= $headers['To'];
if( strlen($return_address) == 0 ) {
	$return_address		= $headers['to'];
	if( strlen($return_address) == 0 ) {
		$return_address		= $headers['TO'];
	}
}
// 戻り先アドレスの連番取得
list( $account, $domain )		= explode('@',$return_address);
list( $prefix, $unique_number, $timestamp )	= explode('-',$account);
// ユニーク番号があるなら処理
if( $prefix == $memberConfigurationObject->definitionHash['MEMBER_RETURN_MAIL_PREFIX']
	&& preg_match('/^[0-9]+$/',$unique_number) > 0
	&& preg_match('/^[0-9]+$/',$timestamp) > 0
	) {
	$unique_number	= sprintf('%01d',$unique_number);
	$deliberyDate	= date('Y-m-d H:i:s',$timestamp);
	// データベースに接続する
	database2_Connect::execute( $GLOBALS['request'] );
	$dbo	= $GLOBALS['request']->getAttribute('dbo');
	if( false === $dbo ) {
		echo "Can't connect database!\n";
		exit(0);
	}
	$dbo->beginTransaction();
	$is_error	= false;
	// メールログをリターンステータスに変更
	$sql	= 'SELECT * FROM '.TABLE_NAME_MEMBER_MAIL_LOG
		.' WHERE log_number='.$unique_number
		.' AND delivery_date='.$dbo->quote($deliberyDate)
	;
	$logArray	= $dbo->queryAll($sql,'hash');
	if( false !== $logArray ) {
		foreach( $logArray as $row ) {
			$email	= $row['delivery_address'];
			// PCメールエラー記録
			$sql	= 'SELECT member_id FROM '.TABLE_NAME_MEMBER.' WHERE pc_mail='.$dbo->quote($email);
			$memberInfoHash	= $dbo->queryAll($sql,'hash');

			if( false !== $memberIdArray ) {
				$memberIdConditionArray	= array();
				foreach( $memberInfoHash as $memberInfoHash ) {
					$memberId	= $memberInfoHash['member_id'];
					if( strlen($memberId) > 0 ) {
						array_push($memberIdConditionArray,$dbo->quote($memberId) );
					}
				}
				if( count($memberIdConditionArray) > 0 ) {
					$sql	= 'UPDATE '.TABLE_NAME_MEMBER_ERROR_COUNT.' SET '
						.'pc_mail_error_count=pc_mail_error_count+1, pc_mail_error_date=NOW() '
						.' WHERE member_id IN('.implode(',',$memberIdConditionArray).')';
					$dbo->query($sql);
				}
			}
			// モバイルメールエラー記録
			$sql	= 'SELECT member_id FROM '.TABLE_NAME_MEMBER.' WHERE mb_mail='.$dbo->quote($email);
			$memberInfoHash	= $dbo->queryAll($sql,'hash');
			if( false !== $memberIdArray ) {
				$memberIdConditionArray	= array();
				foreach( $memberInfoHash as $memberInfo ) {
					$memberId	= $memberInfoHash['member_id'];
					if( strlen($memberId) > 0 ) {
						array_push($memberIdConditionArray,$dbo->quote($memberId) );
					}
				}
				if( count($memberIdConditionArray) > 0 ) {
					$sql	= 'UPDATE '.TABLE_NAME_MEMBER_ERROR_COUNT.' SET '
						.'mb_mail_error_count=mb_mail_error_count+1, mb_mail_error_date=NOW() '
						.' WHERE member_id IN('.implode(',',$memberIdConditionArray).')';
					$dbo->query($sql);
				}
			}
		}
		$sql	= 'UPDATE '.TABLE_NAME_MEMBER_MAIL_LOG.' SET delivery_status=211'
			.' WHERE log_number='.$unique_number
			.' AND delivery_date='.$dbo->quote($deliberyDate)
		;
		$result = $dbo->query($sql);
		if( false !== $result ) {
		} else {
			$is_error	= true;
		}
	}
	if ( $is_error ) {
		echo "sql error!!\n";
		$dbo->rollback();
	} else {
		echo "ok\n";
		$dbo->commit();
	}
	// データベース切断
	database2_Connect::post_process( $GLOBALS['request'] );
}
ob_flush();
exit(0);
?>