<?php
/*
 * member/scripts/send.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/02/18
 */
// コマンド共通モジュール取り込み
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.'DaoMember.class.php');
require_once(dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'DaoMemberMail.class.php');
require_once(dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'DaoMemberMailReject.class.php');
require_once(dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'DaoMemberMailRejectMember.class.php');
require_once(dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'DaoMemberMailLog.class.php');
require_once(dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'DaoMemberMailTemplate.class.php');
// ユーティリティの読み込み
require_once(dirname(dirname(dirname(__FILE__)))
.DIRECTORY_SEPARATOR.'util'
.DIRECTORY_SEPARATOR.'Mail.class.php');
require_once(dirname(dirname(dirname(__FILE__)))
.DIRECTORY_SEPARATOR.'util'
.DIRECTORY_SEPARATOR.'mobile'
.DIRECTORY_SEPARATOR.'PictCharConverter.class.php');
// 送信実行オブジェクトの読み込み
require_once(dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'mail'
.DIRECTORY_SEPARATOR.'Send.class.php');

// 実行開始の取得
$start_time			= time();
$max_execution_time	= ceil( ( ini_get('max_execution_time') / 4 ) * 3 );
$max_execution_time	= 5;
$mail_send_object	= new member_mail_Send();
$log_file			= $mail_send_object->getSentLogPath();
ob_implicit_flush(true);

// phpのインストール種別を確認
$is_cli		= false;
if( preg_match('/[cC][lL][iI]/',php_sapi_name()) > 0 ) {
	$is_cli	= true;
	$mail_send_object->writeSentLog('this process called by php cli version.',true);
} else if( preg_match('/[hH][aA][nN][dD][lL][eE][rR]/',php_sapi_name()) > 0 ) {
	header('Content-Type: text/plain; charset=UTF-8;');
	$mail_send_object->writeSentLog('this process called by php spi version.',true);
	$mail_send_object->writeSentLog('please call on commandline.',true);
	$mail_send_object->writeSentLog('exit.',true);
	exit(-1);
} else {
	header('Content-Type: text/plain; charset=UTF-8;');
	$mail_send_object->writeSentLog('this process called by php cgi version.',true);
	$mail_send_object->writeSentLog('max execution_time is '.ini_get('max_execution_time').'sec.',true);
	$mail_send_object->writeSentLog('execute process '.$max_execution_time.'sec at once.',true);
}

// コマンド引数の処理
$send_once			= 10;
$nolist_sleep_sec	= 300;
if( is_array( $argv ) ) {
	foreach( $argv as $key => $val ) {
		if( preg_match('/^\\-o|\\-\\-sendonce$/', $val ) > 0 ) {
			$nval	= $argv[$key+1];
			if( preg_match('/^[0-9]{1,3}$/',$nval) > 0 && $nval > 0 && $nval < 100 ) {
				$send_once	= $nval;
			}
		} else if( preg_match('/^\\-[i]|\\-\\-sleep$/', $val ) > 0 ) {
			$nval	= $argv[$key+1];
			if( preg_match('/^[0-9]{1,4}$/',$nval) > 0 && $nval > 0 && $nval < 60 * 60 ) {
				$nolist_sleep_sec	= $nval;
			}
		}
	}
}
// PIDファイルのパス定義が不正なら中断
if( !defined('MEMBER_MAIL_FILE_PATH_DELIVERY_RUNNING_PID')
	|| !defined('DIR_PATH_TMP')
	|| strlen(MEMBER_MAIL_FILE_PATH_DELIVERY_RUNNING_PID) < strlen(DIR_PATH_TMP) ) {
	$mail_send_object->writeSentLog('Fatal Error! Can\'t create Process File! Please confirm permittion! '.MEMBER_MAIL_FILE_PATH_DELIVERY_RUNNING_PID,true);
	exit(-1);
} else {
	@touch( MEMBER_MAIL_FILE_PATH_DELIVERY_RUNNING_PID );
	@chmod( MEMBER_MAIL_FILE_PATH_DELIVERY_RUNNING_PID, SPIDER_PERMITTION_DATA_FILE );
}

// ログファイルの作成に失敗していたら中断
if( false === $log_file ) {
	$mail_send_object->writeSentLog('Fatal Error! Can\'t create Log File! Please confirm permittion! '.DIR_PATH_LOG,true);
	exit(-1);
}

// 実行中ロックファイルの確認
if( false === $mail_send_object->getDeliveryLock() ) {
	$mail_send_object->writeSentLog('stopped. another process is delivering or can\'t create lock file!',true);
	exit(0);
}

// DB接続
$connector	= new database2_Connect();
$connector->execute($GLOBALS['request']);
$dbo		= $GLOBALS['request']->getAttribute( 'database.connection' );
if( false === $dbo || is_null($dbo) ) {
	$mail_send_object->writeSentLog('Fatal Error! Can\'t connect database! ',true);
	exit(-1);
}

$mail_send_object->writeSentLog( 'starting delivery...', true );

// 配信に利用するメールオブジェクトのハッシュmail_id => object
while( true ) {
	if( !file_exists(MEMBER_MAIL_FILE_PATH_DELIVERY_RUNNING_PID) ) {
		// 動作プロセスファイルがないなら停止
		$mail_send_object->writeSentLog( 'process is stoped!', true );
		break;
	} if( !$is_cli && time() - $start_time > $max_execution_time ) {
		// cliでない場合実行時間が$max_execution_time秒を過ぎたらbreak
		$mail_send_object->writeSentLog( 'past max execution time!', true );
		break;
	} else {
		$mail_send_object->writeSentLog( 'load undeliveried mail list..', true );
		@touch(MEMBER_MAIL_FILE_PATH_DELIVERY_RUNNING_PID);
	}
	// 準備済みで未送信のメール送信
	$mail_send_object->execute_send_mail( $GLOBALS['request'], $send_once, true, $nolist_sleep_sec );
	
	$sql	= 'SELECT COUNT( DISTINCT '.TABLE_NAME_MEMBER_MAIL_LOG.'.log_number)'
		.' FROM '.TABLE_NAME_MEMBER_MAIL_LOG
		.' LEFT OUTER JOIN '.TABLE_NAME_MEMBER_MAIL
		.' ON '.TABLE_NAME_MEMBER_MAIL.'.mail_id='.TABLE_NAME_MEMBER_MAIL_LOG.'.mail_id'
		.' WHERE '
		.TABLE_NAME_MEMBER_MAIL_LOG.'.delivery_status=0'
		.' AND '
		.TABLE_NAME_MEMBER_MAIL.'.status_flag=1'
		.' AND '
		.TABLE_NAME_MEMBER_MAIL.'.reserve_date<NOW()'
	;
	$remainCount	= $dbo->queryOne($sql,'hash');
	if( $rows === false ) {
		$mail_send_object->writeSentLog( 'exit program! sql error! : '.$sql, true );
	} else if( $remainCount == 0 ) {
		break;
	} else {
		sleep(1);
	}
}
$mail_send_object->writeSentLog( 'exit program! ready to end...', true );

// DB切断
$dbo->disconnect();
// 実行ロック解除
$mail_send_object->releaseDeliveryLock();
// スクリプト自体の実行ロック解除
@unlink( MEMBER_MAIL_FILE_PATH_DELIVERY_RUNNING_PID );

?>