<?php
/**
 * @copyright ONE/DEPO Project
 * @license   PHP License 3.01 <http://www.php.net/license/3_01.txt>
 */

# マーチャントの設定ファイルを読み込む
include_once BASE_DIR . "/webapp/config/merchant.inc.php";

#Yamato送料計算
include_once 'payment/_yamato.php';

# 携帯判別
require_once 'Net/UserAgent/Mobile.php';

if (PAY_MERCHANT!='veritrans') {
    define("REQ_ORDER_ID",  "order-id");
    define("REQ_CVS_TYPE",  "cvs-type");
    define("REQ_AMOUNT",    "amount");
    define("REQ_PAY_LIMIT", "pay-limit");
    define("REQ_NAME1",     "name1");
    define("REQ_NAME2",     "name2");
    define("REQ_TEL_NO",    "tel-no");
    define("REQ_KANA",      "kana");
}

/**
 * 決済
 *
 * @package     Payment
 * @author      netnee T.Ototgawa <tomokauzu.otogawa@netnee.jp>
 * @access      public
 */
class Onedepo_Logic_Payment {

    var $dbaccess;
    var $c_consumer;
    var $c_deposit;
    var $c_stock;
    var $l_mail;           //メール送信ロジック
    var $c_pref;
    var $c_member;
    var $c_bank;
    var $c_cart;
    var $dlitem;
    var $c_systeminfo;
    var $order_lgc;

    var $item;
    var $t;
    var $cvs;

    var $data;

    // カード決済用
    var $merchant_id;
    var $pass_phrase;
    var $encode;
    var $paytourl;
    var $txn_type;
    var $MIblock;
    var $MI;
    var $MI_SIG;
    var $QUERY_MI;
    var $dt;

    // コンビニ決済用
    var $cvs_merchant_id;
    var $cvs_sig_key;
    var $cvs_encode;


    var $card_number;
    var $card_exp;
    var $card_name;
    var $bankdata;
    var $bankmessage;
    var $cardmessage;
    var $cardtotalprice;
    var $daibikimessage;
    var $takkyubinprc;

    var $dlperiodend;
    var $download_url;

    var $cvsinfo;
    var $cvsmessage;

    var $orderno_ary;
    var $totalp;
    var $tp = 0;

    var $yuubinmessage;

    var $souryou;

    var $dl = 0;

    var $trackerdata;

    function Onedepo_Logic_Payment() {
        $this->souryou = new _Yamato('yamato','宅急便');
        $this->souryou->SetOrigin(YAMATO_SOURYOU_CHIIKI, 'JP'); // 送付元はconfig.inc.php内で設定
        $this->souryou->SetSize(YAMATO_SOURYOU_SIZE, 0, 0);     // サイズ

        switch (PAY_MERCHANT) {
        case 'veritrans':
        // ベリトランス
        $this->t = new Veritrans;
        break;

        case 'remise':
        // ルミーズ
        $this->t = new Remise;
        break;

        default:
        // カード利用なし
        $this->t = false;
        break;
        }
    }

    function getOrderid($dt) {
        if (!$this->t) return "";

        $this->dt = $this->t->getOrderid($dt);
        return $this->dt;
    }


    function getMi($price, $dt="") {
        if (!$this->t) return "";

        $this->dt = $this->t->getMi($price, $dt);

        return $this->dt;
    }


    function getMiSig($MI="")
    {
        if (!$this->t) return "";

        $this->MI_SIG = $this->t->getMiSig($MI);

        return $this->MI_SIG;
    }

    function checkSignature($price="") {
        if (!$this->t) return "";
        return $this->t->checkSignature($price);
    }


    function getCVSSig ($amount, $dt="") {
        if (!$this->t) return "";
        return $this->t->getCVSSig($amount, $dt);
    }
    function checkCVSSig () {
        if (!$this->t) return "";
        return $this->t->checkCVSSig();
    }


    // 送料の送付先都道府県設定
    function setSouryouDest($souryoudest) {
        $this->souryou->SetDest(sprintf("%02d", $souryoudest), 'JP');
    }

    // 代引手数料
    function getDaibikiCost ($totalprice=0) {
        return $this->souryou->calcDaibikiCost($totalprice);
    }

    /**
     * 決済
     *
     * params: $retarr         返却配列(受注番号などを格納)
     *         $payment_data   支払い方法
     *         $item           購入商品
     *         $membercd       購入者コード
     *         $select_address 送付先住所選択
     *         $beforeorder    前回購入情報
     *         $takkyubin      宅急便使用フラグ
     *         $reauth         前回と同じ購入情報で購入
     *         $nonmemberdata  非会員者の購入情報($membercd==NULLの時、使用
     *         $note           備考
     *
     **/
    function doTransaction(&$retarr,
                           $payment_data,
                           $item,
                           $membercd,
                           $select_address,
                           $beforeorder,
                           $takkyubin,
                           $reauth=0,
                           $nonmemberdata=NULL,
                           $note=NULL) {

        if (!$this->t) return "";

        $func_name = "Onedepo_Logic_Payment#doTransaction";
        $log =& LogFactory::getLog();
        $this->totalp = 0;

        $this->t->setCardinfo($this->card_number, $this->card_name, $this->card_exp);

        //
        if (!$r_array = $this->makeItemArray($item, $retarr)) {
            return false;
        }
        //--

        if (!empty($membercd)) {
            if (!empty($reauth)) {
                $reorderid = $beforeorder["orderno"];
            }
            // 購入者情報
            $member_data = $this->c_consumer->select_one($membercd);
        } else {
            // 会員未登録
            $membercd = NULL;
            $select_address = NULL;
            $member_data["mailaddr"] = $nonmemberdata["sendmailaddr_user"] ."@". $nonmemberdata["sendmailaddr_domain"];
            $member_data["buyername"] = $nonmemberdata["buyername"];
            $member_data["postalcd"] = implode("-", $nonmemberdata["sendpost"]);
            $member_data["prefcd"] = $nonmemberdata["sendpref"];
            $member_data["addr1"] = $nonmemberdata["sendaddr1"];
            $member_data["addr2"] = $nonmemberdata["sendaddr2"];
            $member_data["telno1"] = implode("-", $nonmemberdata["sendtelno1"]);
            $member_data["addressee"] = (empty($nonmemberdata["addressee"])) ?
                                         $nonmemberdata["buyername"] : $nonmemberdata["addressee"];
        }
        // 備考
        $member_data["note"] = $note;

        $db = $this->dbaccess->doConnect();
        $db->setFetchMode(DB_FETCHMODE_ASSOC);
        $db->autoCommit(false);

        
        foreach ($r_array as $key => $val) {

            $db->query('BEGIN;');
            // 受注ヘッダのクエリとパラメータを取得(初期ヘッダ)
            $res = $this->getOrderTitleQuery($db, $select_address, $membercd, $member_data, $beforeorder, $takkyubin);
            //--
            if (!$res) {
	      //$retarr["MErrMsg"] ="購入に失敗しました";
                return false;
            }
            $retarr["order-id"] = $orderid = $res["code"];

            $totalprice = 0;
            $j = 0;
            if(!is_null($val)) {
                foreach($val as $k => $item) {
                    switch ($key) {
                        case 0: // 在庫
                        if (!$this->getOrderDetail($db, $membercd, $orderid, $item, $totalprice, $k)) {
			  //$retarr["MErrMsg"] ="購入に失敗しました";
                            return false;
                        }
                        break;

                        case 1: // 予約
                        $totalprice = 0;
                        // 予約はタイトルごとにヘッダを作成
                        if ($k > 0) {
                            $db->query('BEGIN;');
                            // 受注ヘッダのクエリとパラメータを取得
                            $res = $this->getOrderTitleQuery($db, $select_address, $membercd, $member_data, $beforeorder, $takkyubin);
                            //--
                            if (!$res) {
			      //$retarr["MErrMsg"] ="購入に失敗しました";
                                return false;
                            }
                        }
                        $retarr["order-id"] = $orderid = $res["code"];
                        $this->orderno_ary[] = $orderid;

                        if (PAY_MERCHANT!='veritrans') {
                            $totalprice += $item[5];
                        } else {
                            if (!$this->getOrderDetailReserve($db, $membercd, $orderid, $item, $totalprice, $k)) {
			  //$retarr["MErrMsg"] ="購入に失敗しました";
                                return false;
                            }
                        }
                        $this->totalp += $totalprice;
                        // 予約は明細ごとに決済を行う
                        $txn_type = $request = "";
                        if ($payment_data[0] == 1) {
                            if (!empty($reauth)) {

                            // 取引タイプ
                            $txn_type = "re-authonly";
                            // リクエスト
                            $amount = $totalprice;
                            $request = array(
                                 "re-order-id"   =>  $reorderid,
                                 "order-id"      =>  $orderid,
                                 "amount"        =>  $amount
                            );
                            $reorderid = $orderid;
                            } else {

                            // 取引タイプ
                            // 契約によっては、authcaptureが使えない場合がある
                            if ($this->t->txn_type=='authonly') {
                                $txn_type = "authonly";
                            } else {
                                $txn_type = "authonly";
                            }
                            // リクエスト
                            $amount = $totalprice;
                            $request = array(
                                 "order-id"      =>  $orderid,
                                 "amount"        =>  $amount,
                                 "card-number"   =>  $this->card_number,
                                 "card-exp"      =>  $this->card_exp
                            );
                            }
                        } else if ($payment_data[0] == 3) {
                            //$this->bankdata = $this->c_bank->selectOne();
                    
                            $bankinfo = $this->c_bank->selectOne();
                            $sysinfo = $this->c_systeminfo->selectAll();
                            unset($sysinfo[0]['updcnt']);
                            unset($sysinfo[0]['shitennumberkey']);
                            unset($sysinfo[0]['kouzanumberkey']);
                    
                            $this->bankdata = array_merge_recursive($bankinfo, $sysinfo[0]);

                            if (!$this->bankdata) {
                                $log->error("rollback nobankdata", $func_name);
                                $db->query('ROLLBACK;');
                                $db->rollback();
                                $this->dbaccess->doClose($db);
                                //$retarr["MErrMsg"] ="購入に失敗しました";
                                return false;
                            }
                        } else if ($payment_data[0] == 4) {
                            $amount = $totalprice;
                            $request = array(
                            # 取引 ID
                            REQ_ORDER_ID => $orderid,
                            # CVSタイプ(店)
                            REQ_CVS_TYPE => $payment_data[9],
                            # 金額
                            REQ_AMOUNT => $amount,
                            # 支払期限
                            REQ_PAY_LIMIT => date("Y/m/d", mktime(0,0,0,date("m"),date("d")+CVS_PAY_LIMIT,date("Y"))),
                            # 氏名（注意：ベリトランスコンビニゲートウェイは UTF-8 の文字のみを
                            # 受け付けるため、ゲートウェイ接続の前に UTF-8 コードへ変換）
                            REQ_NAME1 => $this->t->jCode($payment_data[10]),
                            REQ_NAME2 => $this->t->jCode($payment_data[11]),
                            # 電話番号
                            REQ_TEL_NO => $payment_data[14]
                            );
                            if ($payment_data[9]=="03") {
                                $request[REQ_KANA] = $this->t->jCode($payment_data[12]) . $this->t->jCode($payment_data[13]);
                            }
                        } else if (($payment_data[0] == 2 || $payment_data[0] == 5) && (SELLER_PAY_ETC || USE_BANK_SELLER_ITEM)) {
                        } else {
                            $log->error("rollback donot payment", $func_name);
                            $db->query('ROLLBACK;');
                            $db->rollback();
                            $this->dbaccess->doClose($db);
                            //$retarr["MErrMsg"] ="購入に失敗しました";
                            return false;
                        }
                        if (!empty($reauth)) {
                            $info = $beforeorder;
                        } else {
                            $info = array(
                                "cardcompany" => $payment_data[1], 
                                "cardnumber"  => substr($this->card_number, -4),
                                "cardname"    => $this->card_name,
                                "cardexp"     => $payment_data[4]."/".$payment_data[5]
                            );
                        }
                        if (PAY_MERCHANT!='veritrans' && ($payment_data[0]==1 || $payment_data[0]==4)) {
                            if (!$this->makePayInfoTmp($orderid, $payment_data, $info, $txn_type, $request, 1, $item)) {
                                return false;
                            }
                        } else {
                            if (!$this->insertDepositAndPayment($db, $retarr, $orderid, $payment_data,
                                                                $info, $txn_type, $request)) {
                                return false;
                            }
                        }

                        $db->query('COMMIT;');
                        $db->commit();
                        break;

                        case 2: // 出品
                        // 出品はタイトルごとにヘッダを作成
                        if ($j > 0) {
                            $totalprice = 0;
                            $db->query('BEGIN;');
                            // 受注ヘッダのクエリとパラメータを取得
                            $res = $this->getOrderTitleQuery($db, $select_address, $membercd, $member_data, $beforeorder, $takkyubin);
                            //--
                            if (!$res) {
			      //$retarr["MErrMsg"] ="購入に失敗しました";
                                return false;
                            }
                        }
                        $retarr["order-id"] = $orderid = $res["code"];
                        $this->orderno_ary[] = $orderid;

                        foreach ($item as $kk => $val) {
                            if (!$this->getOrderDetailSell($db, $membercd, $orderid, $val, $totalprice, $kk)) {
			      //$retarr["MErrMsg"] ="購入に失敗しました";
                                return false;
                            }
                        }
                        $this->totalp += $totalprice;
                        // 出品手数料
                        $commission = (int)round($totalprice * EXHIBIT_COMMISSION);
                        $params = array($orderid, $commission, '', $_SERVER['REMOTE_ADDR']);
                        $sql  = "SELECT * FROM f_order_detail_update";
                        $sql .= "(1,?,NULL,4,NULL,NULL,NULL,?,1,?,?)";
                        $res = $db->getRow($sql, $params);

                        if (DB::isError($res) || $res['errcd'] < 0) {
                            $log->error("commission rollback ".$res->userinfo, $func_name);
                            $db->query('ROLLBACK;');
                            $db->rollback();
                            $this->dbaccess->doClose($db);
                            return false;
                        }
                        // 出品はタイトルごとに決済を行う
                        $txn_type = $request = "";
                        if ($payment_data[0] == 1) {
                            if (!empty($reauth)) {
                            // 取引タイプ
                            $txn_type = "re-authcapture";
                            // リクエスト
                            $amount = $totalprice;
                            $request = array(
                                 "re-order-id"   =>  $reorderid,
                                 "order-id"      =>  $orderid,
                                 "amount"        =>  $amount
                            );
                            $reorderid = $orderid;
                            } else {
                            // 取引タイプ
                            // 契約によっては、authcaptureが使えない場合がある
                            if ($this->t->txn_type=='authonly') {
                                $txn_type = "authonly";
                            } else {
                                $txn_type = "authcapture";
                            }
                            // リクエスト
                            $amount = $totalprice;
                            $request = array(
                                 "order-id"      =>  $orderid,
                                 "amount"        =>  $amount,
                                 "card-number"   =>  $this->card_number,
                                 "card-exp"      =>  $this->card_exp
//                               "card-name"     =>  $mi['card-name']
                            );
                            }
                        } else if ($payment_data[0] == 3 && (SELLER_PAY_ETC || USE_BANK_SELLER_ITEM)) {
                            //$this->bankdata = $this->c_bank->selectOne();
                    
                            $bankinfo = $this->c_bank->selectOne();
                            $sysinfo = $this->c_systeminfo->selectAll();
                            unset($sysinfo[0]['updcnt']);
                            unset($sysinfo[0]['shitennumberkey']);
                            unset($sysinfo[0]['kouzanumberkey']);
                    
                            $this->bankdata = array_merge_recursive($bankinfo, $sysinfo[0]);

                            if (!$this->bankdata) {
                                $log->error("rollback nobankdata", $func_name);
                                $db->query('ROLLBACK;');
                                $db->rollback();
                                $this->dbaccess->doClose($db);
                                //$retarr["MErrMsg"] ="購入に失敗しました";
                                return false;
                            }
                        } else if ($payment_data[0] == 4 && (SELLER_PAY_ETC || USE_BANK_SELLER_ITEM)) {
                            $amount = $totalprice;
                            $request = array(
                            # 取引 ID
                            REQ_ORDER_ID => $orderid,
                            # CVSタイプ(店)
                            REQ_CVS_TYPE => $payment_data[9],
                            # 金額
                            REQ_AMOUNT => $amount,
                            # 支払期限
                            REQ_PAY_LIMIT => date("Y/m/d", mktime(0,0,0,date("m"),date("d")+CVS_PAY_LIMIT,date("Y"))),
                            # 氏名（注意：ベリトランスコンビニゲートウェイは UTF-8 の文字のみを
                            # 受け付けるため、ゲートウェイ接続の前に UTF-8 コードへ変換）
                            REQ_NAME1 => $this->t->jCode($payment_data[10]),
                            REQ_NAME2 => $this->t->jCode($payment_data[11]),
                            # 電話番号
                            REQ_TEL_NO => $payment_data[14]
                            );
                            if ($payment_data[9]=="03") {
                                $request[REQ_KANA] = $this->t->jCode($payment_data[12]) . $this->t->jCode($payment_data[13]);
                            }
                        } else if (($payment_data[0] == 2 || $payment_data[0] == 5) && (SELLER_PAY_ETC || USE_BANK_SELLER_ITEM)) {
                        } else {
                            $log->error("rollback donot payment", $func_name);
                            $db->query('ROLLBACK;');
                            $db->rollback();
                            $this->dbaccess->doClose($db);
                            //$retarr["MErrMsg"] ="購入に失敗しました";
                            return false;
                        }
                        if (!empty($reauth)) {
                            $info = $beforeorder;
                        } else {
                            $info = array(
                                "cardcompany" => $payment_data[1], 
                                "cardnumber"  => substr($this->card_number, -4),
                                "cardname"    => $this->card_name,
                                "cardexp"     => $payment_data[4]."/".$payment_data[5]
                            );
                        }
                        if (PAY_MERCHANT!='veritrans' && ($payment_data[0]==1 || $payment_data[0]==4)) {
                            if (!$this->makePayInfoTmp($orderid, $payment_data, $info, $txn_type, $request, 2)) {
                                return false;
                            }
                        } else {
                            if (!$this->insertDepositAndPayment($db, $retarr, $orderid, $payment_data,
                                                                $info, $txn_type, $request)) {
                                return false;
                            }
                        }
                        $db->query('COMMIT;');
                        $db->commit();
                        $j++;
                        break;

                        case 3: // ダウンロード
                        $totalprice = 0;
                        // ダウンロードはタイトルごとにヘッダを作成
                        if ($k > 0) {
                            $db->query('BEGIN;');
                            // 受注ヘッダのクエリとパラメータを取得
                            $res = $this->getOrderTitleQuery($db, $select_address, $membercd, $member_data, $beforeorder, $takkyubin);
                            //--
                            if (!$res) {
			      //$retarr["MErrMsg"] ="購入に失敗しました";
                                return false;
                            }
                        }
                        $retarr["order-id"] = $orderid = $res["code"];
                        $this->orderno_ary[] = $orderid;

                        if (!$this->getOrderDetailDL($db, $membercd, $orderid, $item, $totalprice, $k)) {
			      //$retarr["MErrMsg"] ="購入に失敗しました";
                            return false;
                        }
                        $this->totalp += $totalprice;

                        // 出品はタイトルごとに決済を行う
                        $txn_type = $request = "";
                        if ($payment_data[0] == 1) {
                            if (!empty($reauth)) {
                            // 取引タイプ
                            $txn_type = "re-authcapture";
                            // リクエスト
                            $amount = $totalprice;
                            $request = array(
                                 "re-order-id"   =>  $reorderid,
                                 "order-id"      =>  $orderid,
                                 "amount"        =>  $amount
                            );
                            $reorderid = $orderid;
                            } else {
                            // 取引タイプ
                            // 契約によっては、authcaptureが使えない場合がある
                            if ($this->t->txn_type=='authonly') {
                                $txn_type = "authonly";
                            } else {
                                $txn_type = "authcapture";
                            }
                            // リクエスト
                            $amount = $totalprice;
                            $request = array(
                                 "order-id"      =>  $orderid,
                                 "amount"        =>  $amount,
                                 "card-number"   =>  $this->card_number,
                                 "card-exp"      =>  $this->card_exp
//                               "card-name"     =>  $mi['card-name']
                            );
                            }
                        } else {
                            $log->error("rollback donot payment", $func_name);
                            $db->query('ROLLBACK;');
                            $db->rollback();
                            $this->dbaccess->doClose($db);
                            //$retarr["MErrMsg"] ="購入に失敗しました";
                            return false;
                        }
                        if (!empty($reauth)) {
                            $info = $beforeorder;
                        } else {
                            $info = array(
                                "cardcompany" => $payment_data[1], 
                                "cardnumber"  => substr($this->card_number, -4),
                                "cardname"    => $this->card_name,
                                "cardexp"     => $payment_data[4]."/".$payment_data[5]
                            );
                        }
                        if (PAY_MERCHANT!='veritrans' && ($payment_data[0]==1 || $payment_data[0]==4)) {
                            if (!$this->makePayInfoTmp($orderid, $payment_data, $info, $txn_type, $request, 3)) {
                                return false;
                            }
                        } else {
                            if (!$this->makeDownloadOrder($db, $orderid, $membercd, $item[0], $item[1])) {
                                return false;
                            }
                            if (!$this->insertDepositAndPayment($db, $retarr, $orderid, $payment_data,
                                                                $info, $txn_type, $request)) {
                                return false;
                            }
                        }

                        $db->query('COMMIT;');
                        $db->commit();
                        break;
                    }
                }
            } else {
                $log->error("rollback nodata", $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                //$retarr["MErrMsg"] ="購入に失敗しました";
                return false;
            }
            if ($key==0) {
                // 在庫は一度に決済を行う
                $this->orderno_ary[] = $orderid;
                $this->totalp += $totalprice;
                $txn_type = $request = "";
                if ($payment_data[0] == 1) {
                    if (!empty($reauth)) {
                    // 取引タイプ
                    $txn_type = "re-authcapture";
                    // リクエスト
                    $amount = $totalprice;
                    $request = array(
                        "re-order-id"   =>  $reorderid,
                        "order-id"      =>  $orderid,
                        "amount"        =>  $amount
                    );
                    $reorderid = $orderid;
                    } else {
                    // 取引タイプ
                    // 契約によっては、authcaptureが使えない場合がある
                    if ($this->t->txn_type=='authonly') {
                        $txn_type = "authonly";
                    } else {
                        $txn_type = "authcapture";
                    }
                    // リクエスト
                    $amount = $totalprice;
                    $request = array(
                        "order-id"      =>  $orderid,
                        "amount"        =>  $amount,
                        "card-number"   =>  $this->card_number,
                        "card-exp"      =>  $this->card_exp
//                      "card-name"     =>  $mi['card-name']
                    );
                    }
                } else if ($payment_data[0] == 3) {
                    //$this->bankdata = $this->c_bank->selectOne();
                    
                    $bankinfo = $this->c_bank->selectOne();
                    $sysinfo = $this->c_systeminfo->selectAll();
                    unset($sysinfo[0]['updcnt']);
                    unset($sysinfo[0]['shitennumberkey']);
                    unset($sysinfo[0]['kouzanumberkey']);
                    
                    $this->bankdata = array_merge_recursive($bankinfo, $sysinfo[0]);
                    
                    if (!$this->bankdata) {
                        $log->error("rollback nobankdata", $func_name);
                        $db->query('ROLLBACK;');
                        $db->rollback();
                        $this->dbaccess->doClose($db);
                        //$retarr["MErrMsg"] ="購入に失敗しました";
                        return false;
                    }
                }
                else if ($payment_data[0] == 4) {
                    $amount = $totalprice;
                    $request = array(
                        # 取引 ID
                        REQ_ORDER_ID => $orderid,
                        # CVSタイプ(店)
                        REQ_CVS_TYPE => $payment_data[9],
                        # 金額
                        REQ_AMOUNT => $amount,
                        # 支払期限
                        REQ_PAY_LIMIT => date("Y/m/d", mktime(0,0,0,date("m"),date("d")+CVS_PAY_LIMIT,date("Y"))),
                        # 氏名（注意：ベリトランスコンビニゲートウェイは UTF-8 の文字のみを
                        # 受け付けるため、ゲートウェイ接続の前に UTF-8 コードへ変換）
                        REQ_NAME1 => $this->t->jCode($payment_data[10]),
                        REQ_NAME2 => $this->t->jCode($payment_data[11]),
                        # 電話番号
                        REQ_TEL_NO => $payment_data[14]
                    );
                    if ($payment_data[9]=="03") {
                        $request[REQ_KANA] = $this->t->jCode($payment_data[12]) . $this->t->jCode($payment_data[13]);
                    }
                }
                if (!empty($reauth)) {
                    $info = $beforeorder;
                } else {
                    $info = array(
                        "cardcompany" => $payment_data[1], 
                        "cardnumber"  => substr($this->card_number, -4),
                        "cardname"    => $this->card_name,
                        "cardexp"     => $payment_data[4]."/".$payment_data[5]
                    );
                }
                if (PAY_MERCHANT!='veritrans' && ($payment_data[0]==1 || $payment_data[0]==4)) {
                    if (!$this->makePayInfoTmp($orderid, $payment_data, $info, $txn_type, $request, 0)) {
                        return false;
                    }
                } else {
                    if (!$this->insertDepositAndPayment($db, $retarr, $orderid, $payment_data,
                                                        $info, $txn_type, $request)) {
                        return false;
                    }
                }

                $db->query('COMMIT;');
                $db->commit();
            }
        }

        if (PAY_MERCHANT!='veritrans') {
            // ルミーズ決済用
            if ($payment_data[0] == 1) {
                if ($this->totalp>0) {
                    if (!empty($membercd)) {
                        $m = $this->c_member->select_one($membercd);
                    } else {
                        $m = $member_data;
                    }
                    $request["MAIL"] = $m['mailaddr'];
                    $request["amount"] = $this->totalp;
                    $request["OPT"] = implode("-", $this->orderno_ary);
                    $r = $this->t->doCardTransaction($result, $txn_type, $request, $info);
                    $retarr = $result;

                    if (!$r) {
                        $log->error(print_r($result, true), $func_name);

                        $db->query('ROLLBACK;');
                        $db->rollback();
                        $this->dbaccess->doClose($db);
                        return false;
                    }
                } else { // 無料ダウンロードのみ購入した時の処理
                    $log->error(print_r($this->orderno_ary, true), $func_name);
                    $db->query('BEGIN;');
                    foreach ($this->orderno_ary as $ono) {
                        if (!$this->updatePreOrderFlg($db, $ono)) {
                            return false;
                        }
                    }
                    $db->query('COMMIT;');
                    $db->commit();
                }
            } else if ($payment_data[0] == 4) {
                if (!empty($membercd)) {
                    $m = $this->c_member->select_one($membercd);
                } else {
                    $m = $member_data;
                }
                $request = array(
                    "ORDER_ID" => $orderid,
                    "NAME1" => $payment_data[10],
                    "NAME2" => $payment_data[11],
                    "KANA1" => $payment_data[12],
                    "KANA2" => $payment_data[13],
                    "PAY_LIMIT" => date("Ymd", mktime(0,0,0,date("m"),date("d")+CVS_PAY_LIMIT,date("Y"))),
                    "TEL" => $payment_data[14],
                    "MAIL" => $m['mailaddr'],
                    "TOTAL" => $this->totalp
                    );
                $r = $this->t->doCvsTransaction($result, $request, $info);
            }
        }

        $this->dbaccess->doClose($db);
        return true;
    }


    /**
     * 購入した商品を、在庫分、予約分、出品分にわける
     * $re_array[0] : 在庫分
     * $re_array[1] : 予約分
     * $re_array[2] : 出品分
     **/
    function makeItemArray($item, &$retarr) {
        $re_array = array();
        if(!is_null($item)) {
        foreach ($item as $key => $val) {
            if ($key < 2) {
                foreach($val as $k => $v) {
                    if ($k==="totalprice") continue;
                    if ($k==="souryouprc") {
                        $re_array[$key]["souryouprc"] = $v;
                        continue;
                    }
                    /*
                    if ($k==="takkyubinprc") {
                        $re_array[$key]["takkyubinprc"] = $v;
                        continue;
                    }
                    */
                    if ($k==="daibiki") {
                        $re_array[$key]["daibiki"] = $v;
                        continue;
                    }
                    if ($k==="yuubin") {
                        $re_array[$key]["yuubin"] = $v;
                        continue;
                    }
                    $temp = array();
                    $s = $this->c_stock->getStockData($v[0], $v[1], $v[2]);
                    if (!$s || ($s["exhibitcount"] < $v[3] && $s["reserveflg"]!=1)) {
                        $it=$this->c_stock->getStockSelect($v[0],$v[1],$v[2]);
                        $retarr["MErrMsg"]  = "在庫がありません<br />";
                        $retarr["MErrMsg"] .= "「". $it["itemnm"] ."（". $it["itemcd"] ."）」 ". $v[3] ."個";
                        return false;
                    }
                    $temp = $v;
                    $temp["stockcd"] = $s["stockcd"];

                    $re_array[$key][] = $temp;
                }
            } elseif ($key == 2) {
                foreach($val as $k => $v) {
                    foreach ($v as $k2 => $v2) {
                        $k = (string)$k;
                        if ($k2==="souryoumax") {
                            continue;
                        }
                        if ($k2==="souryouprc") {
                            $re_array[$key][$k]["souryouprc"] = $v2;
                            continue;
                        }
                        if ($k2==="daibiki") { 
                            $re_array[$key][$k]["daibiki"] = $v2; 
                            continue; 
                        } 
                        if ($k2==="yuubin") { 
                            $re_array[$key][$k]["yuubin"] = $v2; 
                            continue; 
                        }
                        /*
                        if ($k2==="takkyubinprc") {
                            $re_array[$key][$k]["takkyubinprc"] = $v2;
                            continue;
                        }
                        */
                        $temp = array();
                        $s = $this->c_stock->getStockData($v2[0], $v2[1], $v2[2]);
                        if (!$s || ($s["exhibitcount"] < intval($v2[3]) && $s["reserveflg"]!=1)) {
                            $it=$this->c_stock->getStockSelect($v2[0],$v2[1],$v2[2]);
                            $retarr["MErrMsg"]  = "在庫がありません<br />";
                            $retarr["MErrMsg"] .= "「". $it["itemnm"] ."（". $it["itemcd"] ."）」 ". $v2[3] ."個";
                            return false;
                        }
                        $temp = $v2;
                        $temp["stockcd"] = $s["stockcd"];

                        $re_array[$key][$k][] = $temp;
                    }
                }
            } else {
                foreach($val as $k => $v) {
                    if ($k==="totalprice") continue;
                    /*
                    if ($k==="takkyubinprc") {
                        $re_array[$key]["takkyubinprc"] = $v;
                        continue;
                    }
                    */

                    $temp = array();
                    $s = $this->c_stock->getStockData($v[0], $v[1], $v[2]);
                    if (!$s || ($s["exhibitcount"] < $v[3] && $s["reserveflg"]!=1)) {
                        $it=$this->c_stock->getStockSelect($v[0],$v[1],$v[2]);
                        $retarr["MErrMsg"]  = "在庫がありません<br />";
                        $retarr["MErrMsg"] .= "「". $it["itemnm"] ."（". $it["itemcd"] ."）」 ". $v[3] ."個";
                        return false;
                    }
                    $download_file = $this->dlitem->getDownloadFile($v[0], $v[1]);
                    if (!is_file($download_file)) {
                        $it=$this->c_stock->getStockSelect($v[0],$v[1],$v[2]);
                        $retarr["MErrMsg"]  = "まだ購入できない商品です<br />";
                        $retarr["MErrMsg"] .= "「". $it["itemnm"] ."（". $it["itemcd"] ."）」 ";
                        return false;
                    }

                    $temp = $v;
                    $temp["stockcd"] = $s["stockcd"];

                    $re_array[$key][] = $temp;
                }
            }
        }
        }

        return $re_array;
    }

    /**
     *
     **/
    function getOrderTitleQuery(&$db, $select_address, $membercd, $member_data, $beforeorder, $takkyubin) {
        $func_name = "Onedepo_Logic_Payment#getOrderTitleQuery";
        $log =& LogFactory::getLog();

        if (!empty($membercd)) {
            $m = $this->c_member->select_one($membercd);
            switch ($select_address) {
                case 1:
                $addressee = $m["lastnm"] ." ". $m["firstnm"];
                $params = array(
                    $membercd,
                    $m['mailaddr'],   // メールアドレス
                    $m["lastnm"] ." ". $m["firstnm"],     // 購入者氏名
                    $member_data['postalcd'],   // 郵便番号
                    $member_data['prefcd'],     // 都道府県
                    $member_data['addr1'],      // 住所
                    $member_data['addr2'],      // 住所2
                    $member_data['telno1'],     // 電話番号1
                    $addressee,                 // 宛名
                    ($takkyubin=='') ? 0 : $takkyubin,
                    $member_data['note'],
                    '',
                    $_SERVER['REMOTE_ADDR'] );
                break;

                case 2:
                $addressee = (empty($member_data['addressee'])) ? $m["lastnm"] ." ". $m["firstnm"] : $member_data['addressee'];
                $params = array(
                    $membercd,
                    $m['mailaddr'],   // メールアドレス
                    $m["lastnm"] ." ". $m["firstnm"],     // 購入者氏名
                    $member_data['sendpostalcd'],
                    $member_data['sendprefcd'],
                    $member_data['sendaddr1'],
                    $member_data['sendaddr2'],
                    $member_data['sendtelno1'],
                    $addressee,
                    ($takkyubin=='') ? 0 : $takkyubin,
                    $member_data['note'],
                    '',
                    $_SERVER['REMOTE_ADDR'] );
                break;
 
                case '':
                $params = array(
                    $membercd,
                    $beforeorder['sendmailaddr'],   // メールアドレス
                    $beforeorder['sendbuyer'],     // 購入者氏名
                    $beforeorder['sendpostalcd'],
                    $beforeorder['sendprefcd'],
                    $beforeorder['sendaddr1'],
                    $beforeorder['sendaddr2'],
                    $beforeorder['sendtelno1'],
                    $beforeorder['addressee'],
                    ($takkyubin=='') ? 0 : $takkyubin,
                    $member_data['note'],
                    '',
                    $_SERVER['REMOTE_ADDR'] );
                break;
            }
        } else {
            $params = array(
                NULL,
                $member_data['mailaddr'],
                $member_data['buyername'],
                $member_data['postalcd'],
                $member_data['prefcd'],
                $member_data['addr1'],
                $member_data['addr2'],
                $member_data['telno1'],
                $member_data['addressee'],
                ($takkyubin=='') ? 0 : $takkyubin,
                $member_data['note'],
                '',
                $_SERVER['REMOTE_ADDR'] );
        }

        $sql = "SELECT * FROM f_order_title_update(1, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $res = $db->getRow($sql, $params);
        if (DB::isError($res) || $res["errcd"] < 0) {
            $db->query('ROLLBACK;');
            $db->rollback();
            $log->error("ordertitle rollback " . $res->userinfo, $func_name);
            $this->dbaccess->doClose($db);
            return false;
        }

    return $res;
    }

    /**
     * 受注明細、在庫商品購入時
     **/
    function getOrderDetail(&$db, $membercd, $orderid, $item, &$totalprice, $k) {
        $func_name = "Onedepo_Logic_Payment#getOrderDetail";
        $log =& LogFactory::getLog();

        // 宅急便料金
        if (!is_array($item) && $k==="takkyubinprc") {
            $takkyubinprc = $item;
            $totalprice += $takkyubinprc;
            $params = array($orderid, $takkyubinprc, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,3,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("takkyubin rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
            return true;
        }
        // 送料
        if (!is_array($item) && $k==="souryouprc") {
            $souryouprc = $item;
            $totalprice += $souryouprc;
            $params = array($orderid, $souryouprc, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,2,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("souryou rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
            return true;
        }
        // 代引手数料
        if (!is_array($item) && $k==="daibiki") {
            $daibiki = $item;
            $totalprice += $daibiki;
            $params = array($orderid, $daibiki, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,10,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("daibiki rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
            return true;
        }
        // 郵便振替手数料
        if (!is_array($item) && $k==="yuubin") {
            $yuubin = $item;
            $totalprice += $yuubin;
            $params = array($orderid, $yuubin, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,11,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("yuubin rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
            return true;
        }

        for ($i=0; $i < $item[3]; $i++) {
            $totalprice += $prc = intval($item[5]);
            $params = array($orderid, 
                            $item[0], //品目C
                            $item[1], //構成C
                            $item["stockcd"][$i], //在庫C
                            $prc, //金額
                            1, //数量
                            '',
                            $_SERVER['REMOTE_ADDR']);
                
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,1,?,?,?,?,?,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("orderdetail rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
        }
        return true;
    }

    /**
     * 受注明細、出品商品購入時
     **/
    function getOrderDetailSell(&$db, $membercd, $orderid, $item, &$totalprice, $k) {
        $func_name = "Onedepo_Logic_Payment#geOrderDetailSell";
        $log =& LogFactory::getLog();


        // 宅急便料金
        if (!is_array($item) && $k==="takkyubinprc") {
            $takkyubinprc = $item;
            $totalprice += $takkyubinprc;
            $params = array($orderid, $takkyubinprc, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,3,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("takkyubin rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
            return true;
        }
        // 送料
        if (!is_array($item) && $k==="souryouprc") {
            $souryouprc = $item;
            $totalprice += $souryouprc;
            $params = array($orderid, $souryouprc, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,2,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("souryou rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
            return true;
        }
        // 代引手数料
        if (!is_array($item) && $k==="daibiki") {
            $daibiki = $item;
            $totalprice += $daibiki;
            $params = array($orderid, $daibiki, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,10,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("daibiki rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
            return true;
        }
        // 郵便振替手数料
        if (!is_array($item) && $k==="yuubin") {
            $yuubin = $item;
            $totalprice += $yuubin;
            $params = array($orderid, $yuubin, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,11,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("yuubin rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
            return true;
        }


        $totalprice += $prc = intval($item[3]) * intval($item[5]);
        $params = array($orderid, 
                        $item[0], //品目C
                        $item[1], //構成C
                        $item["stockcd"][0], //在庫C
                        $prc, //金額
                        $item[3], //数量
                        '',
                        $_SERVER['REMOTE_ADDR']);
                
        $sql  = "SELECT * FROM f_order_detail_update";
        $sql .= "(1,?,NULL,1,?,?,?,?,?,?,?)";
        $res = $db->getRow($sql, $params);

        if (DB::isError($res) || $res['errcd'] < 0) {
            $log->error("orderdetail rollback ".$res->userinfo, $func_name);
            $db->query('ROLLBACK;');
            $db->rollback();
            $this->dbaccess->doClose($db);
            return false;
        }
        return true;
    }

    /**
     * 受注明細、ダウンロード商品購入時
     **/
    function getOrderDetailDL(&$db, $membercd, $orderid, $item, &$totalprice, $k) {
        $func_name = "Onedepo_Logic_Payment#geOrderDetailDL";
        $log =& LogFactory::getLog();


        $totalprice += $prc = intval($item[3]) * intval($item[5]);
        $params = array($orderid, 
                        $item[0], //品目C
                        $item[1], //構成C
                        $item["stockcd"][0], //在庫C
                        $prc, //金額
                        $item[3], //数量
                        '',
                        $_SERVER['REMOTE_ADDR']);
                
        $sql  = "SELECT * FROM f_order_detail_update";
        $sql .= "(1,?,NULL,1,?,?,?,?,?,?,?)";
        $res = $db->getRow($sql, $params);

        if (DB::isError($res) || $res['errcd'] < 0) {
            $log->error("orderdetail rollback ".$res->userinfo, $func_name);
            $db->query('ROLLBACK;');
            $db->rollback();
            $this->dbaccess->doClose($db);
            return false;
        }
        return true;
    }

    /**
     * 受注明細、予約商品購入時
     **/
    function getOrderDetailReserve(&$db, $membercd, $orderid, $item, &$totalprice) {
        $func_name = "Onedepo_Logic_Payment#getOrderDetailReserve";
        $log =& LogFactory::getLog();

        $stockcd = $item["stockcd"][0];
        for ($i=0; $i < $item[3]; $i++) {

            // 購入した予約商品のコピーを作成
            $sql  = "INSERT INTO t_ex_stock_detail (";
            $sql .= "SELECT itemcd, structcd, NULL, sellercd, stocktitlecd, ";
            $sql .= "0, condition, sellingprice, souryouprc, ";
            $sql .= "stockstate, scdstartdate, scdcompdate, itemexp, ";
            $sql .= "rackid, managecd, costprice, ntcostprice, consignment, ";
            $sql .= "arrivaldate, delflg, adddate, upddate, updusrnm, ";
            $sql .= "updpcnm, updcnt FROM t_ex_stock_detail ";
            $sql .= "WHERE itemcd=? AND structcd=? AND stockcd=?)";
            $params = array($item[0], $item[1], $stockcd);
            $res = $db->query($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("stockdetail rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }

            // 新しく作成された在庫コードを取得
            //$oldstockcd = $stockcd;
            $sql  = "SELECT stockcd ";
            $sql .= "FROM v_stock_list WHERE stocktitlecd=";
            $sql .= "(SELECT stocktitlecd FROM v_stock_list ";
            $sql .= "WHERE itemcd = ? AND structcd = ? AND stockcd = ?)";
            $sql .= "ORDER BY stockcd desc limit 1";
            $stockcd = $db->getOne($sql, $params);
            if (empty($stockcd)) {
                $log->error("stockcd error ".$sql, $func_name);
                $log->error("stockcd error ".print_r($params, true), $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }

            // 使い終わった予約商品の在庫数を1に変更
            $sql  = "UPDATE t_ex_stock_detail SET exhibitcount=1 ";
            $sql .= "WHERE itemcd=? AND structcd=? AND stockcd=?";
            //$params = array($item[0], $item[1], $oldstockcd);
            $params = array($item[0], $item[1], $stockcd);
            $res = $db->query($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("stockdetail update rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }

            $totalprice += $prc = intval($item[5]);
            $params = array($orderid, 
                            $item[0], //品目C
                            $item[1], //構成C
                            $stockcd, //在庫C
                            $prc, //金額
                            1, //数量
                            '',
                            $_SERVER['REMOTE_ADDR']);
                
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,1,?,?,?,?,?,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("orderdetail rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
            $sql  = "SELECT orderrowno ";
            $sql .= "FROM t_order_detail WHERE orderno=? AND itemcd=? ";
            $sql .= "AND structcd=? AND stockcd=? ";
            $sql .= "ORDER BY adddate desc LIMIT 1";
            $p = array($orderid, $item[0], $item[1], $stockcd);
            $orderrowno = $db->getOne($sql, $p);

            if (PAY_MERCHANT!='veritrans') {
                // 出荷明細を作成
                $sql  = "SELECT * FROM f_forward_detail_update ";
                $sql .= "(2,?,?,?,?,?,?,?)";
                $p = array($orderid, $orderrowno, NULL, 1, NULL, '',$_SERVER['REMOTE_ADDR']); 
                $res = $db->getRow($sql, $p);

                if (DB::isError($res) || $res['errcd'] < 0) {
                    $log->error("forward rollback ".$res->userinfo, $func_name);
                    $db->query('ROLLBACK;');
                    $db->rollback();
                    $this->dbaccess->doClose($db);
                    return false;
                }
            }
        }

        // 宅急便料金
        if (isset($item["takkyubinprc"])) {
            $takkyubinprc = $item["takkyubinprc"];
            $totalprice += $takkyubinprc;
            $params = array($orderid, $takkyubinprc, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,3,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("orderdetail rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
        }
        // 送料
        if (isset($item["souryouprc"])) {
            $souryouprc = $item["souryouprc"];
            $totalprice += $souryouprc;
            $params = array($orderid, $souryouprc, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,2,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("orderdetail rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
        }
        // 代引手数料
        if (isset($item["daibiki"])) {
            $daibiki = $item["daibiki"];
            $totalprice += $daibiki;
            $params = array($orderid, $daibiki, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,10,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("daibiki rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
        }
        // 郵便振替手数料
        if (isset($item["yuubin"])) {
            $yuubin = $item["yuubin"];
            $totalprice += $yuubin;
            $params = array($orderid, $yuubin, '', $_SERVER['REMOTE_ADDR']);
            $sql  = "SELECT * FROM f_order_detail_update";
            $sql .= "(1,?,NULL,11,NULL,NULL,NULL,?,1,?,?)";
            $res = $db->getRow($sql, $params);

            if (DB::isError($res) || $res['errcd'] < 0) {
                $log->error("yuubin rollback ".$res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
        }
        return true;
    }

    function makeDownloadOrder(&$db, $orderid, $membercd, $itemcd, $structcd) {
        $func_name = "Onedepo_Logic_Payment#makeDownloadOrder";
        $log =& LogFactory::getLog();

        // 受注明細番号を取得
        $sql = "SELECT orderrowno FROM t_order_detail WHERE orderno=? AND typediv=1";
        $params = array($orderid);
        $rowno = $db->getOne($sql, $params);
        //--

        // 購入後、即出荷済みに
        $params = array(intval($orderid), intval($rowno), date("Y-m-d"), 4, '', '', $_SERVER['REMOTE_ADDR'], NULL);
        $sql  = "SELECT * FROM f_forward_detail_state_update(?, ?, ?, ?, ?, ?, ?, ?);";
        $res = $db->getRow($sql, $params);
        if (DB::isError($res) || $res['errcd'] < 0) {
            $log->error("forword rollback ".$res->userinfo, $func_name);
            $db->query('ROLLBACK;');
            $db->rollback();
            $this->dbaccess->doClose($db);
            return false;
        }
        //--

        // ダウンロード用受注データを作成
        $dl = $this->dlitem->getDownloadItem($itemcd, $structcd);
        $this->dlperiodend = date("Y-m-d", mktime(0,0,0,date("m"),date("d")+$dl["dlperioddays"],date("Y")));

        $params = array(intval($orderid), intval($rowno), $membercd, $dl["dlcount"], $this->dlperiodend, '', $_SERVER['REMOTE_ADDR']);
        $sql  = "SELECT * FROM f_dl_order_update(1, ?, ?, ?, ?, ?, ?, ?);";
        $res = $db->getRow($sql, $params);
        if (DB::isError($res) || $res['errcd'] < 0) {
            $log->error("dl_order rollback ".$res->userinfo, $func_name);
            $db->query('ROLLBACK;');
            $db->rollback();
            $this->dbaccess->doClose($db);
            return false;
        }
        //--

        $fid_key = $orderid ."_". $rowno ."_". $membercd;
        $download_file = $this->dlitem->getDownloadFile($itemcd, $structcd);
        if (!is_file($download_file)) {
            $log->error("download_file is not exist ", $func_name);
            $db->query('ROLLBACK;');
            $db->rollback();
            $this->dbaccess->doClose($db);
            return false;
        }
        $fid = sha1($fid_key);
        $this->download_url = $this->dlitem->getDownloadURL($fid, $orderid, $rowno);

        return true;
    }

    /**
     *
     **/
    function makePayInfoTmp($orderid, $payment_data, $cardinfo="", $txn_type="", $request="", $buystate, $itemdata="") {
        $func_name = "Onedepo_Logic_Payment#makePayInfoTmp";
        $log =& LogFactory::getLog();

        $payinfo = array("orderno"      => $orderid,
                         "payment_data" => $payment_data,
                         "cardinfo"     => $cardinfo,
                         "txn_type"     => $txn_type,
                         "request"      => $request,
                         "buystate"     => $buystate);
        if (!empty($itemdata)) {
            $payinfo["itemdata"] = $itemdata;
        }

        $payinfo_str = serialize($payinfo);

        if (!is_dir(PAY_INFO_TMPDIR)) {
            mkdir(PAY_INFO_TMPDIR);
            chmod(PAY_INFO_TMPDIR, 0777);
            chown(PAY_INFO_TMPDIR, 'apache');
            chgrp(PAY_INFO_TMPDIR, 'apache');
        }

        $filename = PAY_INFO_TMPDIR . $orderid .".txt";
        if (!$fp = fopen($filename, 'w')) {
            $log->error("fopen ". $filename, $func_name);
            return false;
        }
        if (fwrite($fp, $payinfo_str) === FALSE) {
            $log->error("fwrite ". $payinfo_str, $func_name);
            return false;
        }
        fclose($fp);

        return true;
    }

    /**
     *
     **/
    function insertDepositAndPayment(&$db, &$retarr, $orderid, $payment_data, $cardinfo="", $txn_type="", $request="") { 
        $func_name = "Onedepo_Logic_Payment#insertDepositAndPayment";
        $log =& LogFactory::getLog();

        if (!$this->t) return "";

        switch ($payment_data[0]) {

        case 1:
            $depositstate = 2;  //カード決済は「予約のみ未入金」に
            if ($txn_type == "authonly" || $txn_type == "re-authonly") $depositstate = 1;
            if (PAY_MERCHANT=='veritrans') {
                $params = array($orderid, date("Y-m-d"), 1, $depositstate, $cardinfo["cardcompany"], $cardinfo["cardnumber"], $cardinfo["cardname"], $cardinfo["cardexp"], NULL, NULL, '',$_SERVER['REMOTE_ADDR']);
            } else {
                $params = array($orderid, date("Y-m-d"), 1, $depositstate, '', '', '', '', NULL, NULL, '',$_SERVER['REMOTE_ADDR']);
            }

            $sql = "SELECT * FROM f_deposit_update(1,?,?,?,?,?,?,?,?,?,?,?,?,NULL)";
            $res = $db->getRow($sql, $params);
            if (DB::isError($res) || $res < 0) {
                $log->error("deposit rollback " . $res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                //$retarr["MErrMsg"] ="購入に失敗しました";
                return false;
            }

            if (PAY_MERCHANT=='veritrans') {

                if ($request['amount']>0) {
                    $r = $this->t->doCardTransaction($result, $txn_type, $request, $cardinfo);
                    $retarr = $result;
                    if (!$r) {
                        $log->error(print_r($result, true), $func_name);

                        $db->query('ROLLBACK;');
                        $db->rollback();
                        $this->dbaccess->doClose($db);
                        return false;
                    }
                }

            }
            break;

        case 2:
            $params = array($orderid, NULL, 3, 1, NULL, NULL, NULL, NULL, NULL, NULL, '',$_SERVER['REMOTE_ADDR']);
            //$params = array($orderid, date("Y-m-d"), 3, 2, NULL, NULL, NULL, NULL, NULL, NULL, '',$_SERVER['REMOTE_ADDR']);

            $sql = "SELECT * FROM f_deposit_update(1,?,?,?,?,?,?,?,?,?,?,?,?,NULL)";
            $res = $db->getRow($sql, $params);
            if (DB::isError($res) || $res < 0) {
                $log->error("deposit rollback " . $res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                //$retarr["MErrMsg"] ="購入に失敗しました";
                return false;
            }
            break;

        case 3:
            $params = array($orderid, NULL, 4, 1, NULL, NULL, NULL, NULL, $this->bankdata["shitennumberkey"], $this->bankdata["kouzanumberkey"], '',$_SERVER['REMOTE_ADDR']);

            $sql = "SELECT * FROM f_deposit_update(1,?,?,?,?,?,?,?,?,?,?,?,?,NULL)";
            $res = $db->getRow($sql, $params);
            if (DB::isError($res) || $res < 0) {
                $log->error("deposit rollback " . $res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                //$retarr["MErrMsg"] ="購入に失敗しました";
                return false;
            }

            $params = array($this->bankdata["shitennumberkey"], $this->bankdata["kouzanumberkey"], '', $_SERVER['REMOTE_ADDR'], $this->bankdata["updcnt"]);
            $sql  = "SELECT * FROM f_bank_update(?, ?, ?, ?, ?)";
            $res = $db->getRow($sql, $params);
            if (DB::isError($res) || $res < 0) {
                $log->error("bank rollback " . $res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                //$retarr["MErrMsg"] ="購入に失敗しました";
                return false;
            }
            break;

        case 4:

            $params = array($orderid, NULL, 2, 1, NULL, NULL, NULL, NULL, NULL, NULL, '',$_SERVER['REMOTE_ADDR']);
            $sql = "SELECT * FROM f_deposit_update(1,?,?,?,?,?,?,?,?,?,?,?,?,NULL)";
            $res = $db->getRow($sql, $params);
            if (DB::isError($res) || $res < 0) {
                $log->error("deposit rollback " . $res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                //$retarr["MErrMsg"] ="購入に失敗しました";
                return false;
            }

            // コンビニ決済の情報を保存
            $this->cvsinfo = array();
            if (!empty($payment_data[9])) {
                $this->cvsinfo["cvs_shop"] = $payment_data[9];
            }
            $this->cvsinfo["cvs_name1"] = $payment_data[10];
            $this->cvsinfo["cvs_name2"] = $payment_data[11];
            $this->cvsinfo["cvs_kana"] = $payment_data[12].$payment_data[13];
            $this->cvsinfo["cvs_tel"] = $payment_data[14];
            $this->cvsinfo["amount"] = $request[REQ_AMOUNT];
            $this->cvsinfo["pay_limit"] = $request[REQ_PAY_LIMIT];
            $info = array();
            foreach ($this->cvsinfo as $k => $v) {
                $info[] = $k ."=". $v;
            }
            $params = array($orderid, implode("&", $info), '',$_SERVER['REMOTE_ADDR']);
            $sql = "SELECT * FROM f_deposit_cvsinfo_update(2,?,?,?,?)";
            $res = $db->getRow($sql, $params);
            if (DB::isError($res) || $res < 0) {
                $log->error("deposit cvsinfo rollback " . $res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                //$retarr["MErrMsg"] ="購入に失敗しました";
                return false;
            }

            if (PAY_MERCHANT=='veritrans') {

            $retarr = $result = $this->t->doCVSTransaction(CMD_ENTRY, $request);

            # レスポンス値を取得する
            $MStatus = $result[RES_MSTATUS];
            if ($MStatus == 'success') {
                $retarr["amount"] = $request[REQ_AMOUNT];
                $retarr["pay_limit"] =  $request[REQ_PAY_LIMIT];

                // コンビニ決済の情報で、決済処理後の情報を保存
                $this->cvsinfo["receipt_no"] = $result[RES_RECEIPT_NO];
                $this->cvsinfo["haraikomi_url"] = urlencode($result[RES_HARAIKOMI_URL]);
                $info = array();
                foreach ($this->cvsinfo as $k => $v) {
                    $info[] = $k ."=". $v;
                }
                $params = array($orderid, implode("&", $info), '',$_SERVER['REMOTE_ADDR']);
                $sql = "SELECT * FROM f_deposit_cvsinfo_update(2,?,?,?,?)";
                $res = $db->getRow($sql, $params);
                // エラーが出ても決済処理が完了しているので、ログだけ残す
                if (DB::isError($res) || $res < 0) {
                    $log->error("deposit cvsinfo rollback " . $res->userinfo, $func_name);
                    return false;
                }

            } else {
                $retarr[RES_MERRMSG] = "";

                $log->error(print_r($result, true), $func_name);

                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }

            }
            break;

        case 5:
            $params = array($orderid, NULL, 5, 1, NULL, NULL, NULL, NULL, NULL, NULL, '',$_SERVER['REMOTE_ADDR']);
            //$params = array($orderid, date("Y-m-d"), 3, 2, NULL, NULL, NULL, NULL, NULL, NULL, '',$_SERVER['REMOTE_ADDR']);

            $sql = "SELECT * FROM f_deposit_update(1,?,?,?,?,?,?,?,?,?,?,?,?,NULL)";
            $res = $db->getRow($sql, $params);
            if (DB::isError($res) || $res < 0) {
                $log->error("deposit rollback " . $res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                //$retarr["MErrMsg"] ="購入に失敗しました";
                return false;
            }
            break;

        }

        if (PAY_MERCHANT=='veritrans' || ($payment_data[0] != 1 && $payment_data[0] != 4)) {
            // 仮受注フラグを本受注に
            if (!$this->updatePreOrderFlg($db, $orderid)) {
                return false;
            }
            // --
        }

        return true;
    }

    function sendMailOrder($template, $no)
    {
        $results   = $this->order_lgc->OrderdetailviewMail($no);

        foreach($results as $key => $value){
            if ($results[$key]["typediv"] == 3) $takkyubin = true;
            if ($results[$key]["typediv"] == 10) {
                $daibiki_cost = $results[$key]["price"];
            }
            $type[]=$results[$key]["typediv"];
            $price[] = $results[$key]["price"];
        }

        foreach($type as $key => $value){
            if($value >= 1 and $value <= 3 || $value==10 || $value==11)
                $salesprice[] = $price[$key];
            else
                $otherprice[] = $price[$key];
        }

        $sumprice = array_sum($salesprice);
        if ($template != 'sellout_information') {
            $this->tp += $sumprice;
        }

        $orderno   = $results[0]["orderno"];
        $orderdate = substr($results[0]["orderdate"], 0, 10);
        $lastnm    = $results[0]["lastnm"];
        $firstnm   = $results[0]["firstnm"];
        $sendbuyername   = $results[0]["sendbuyer"];
        $sendpostalcd = $results[0]["sendpostalcd"];
        $prefnm       = $results[0]["prefnm"];
        $sendaddr1    = $results[0]["sendaddr1"];
        $sendaddr2    = $results[0]["sendaddr2"];
        $sendtelno1   = $results[0]["sendtelno1"];
        $addressee    = $results[0]["addressee"];
        $mail           = (!empty($results[0]["mailaddr"])) ?
                           $results[0]["mailaddr"] : $results[0]["sendmailaddr"];
        $usernote = $results[0]["note"];

        // ダウンロード販売以外
        if (empty($this->download_url) && empty($this->dlperiodend)) {

        $sellercd = $results[0]["sellercd"];
        if (!empty($sellercd)) {
            $seller = $this->c_member->select_one($sellercd);
            if( empty($seller["nicknm"]) ) {
                $nicknm = $seller["lastnm"] ." ". $seller["firstnm"];
            } else {
                $nicknm = $seller["nicknm"];
            }
            $mail = $seller['mailaddr'];
			if ($template=="sellout_information") { 
				$mail  = $seller['mailaddr']; 
			} else { 
				$mailaddr  = $seller['mailaddr']; 
			}

        }

        }
        switch ($results[0]["depositdiv"]) {
        case 1:
        $payment[0] = $results[0]["depositdiv"];
        $payment[1] = $results[0]["cardcompany"];
        $payment[2] = $results[0]["cardnumber"];
        $payment[3] = $results[0]["cardname"];
        $exp = explode('/', $results[0]["cardexp"]);
        $payment[4] = $exp[0];
        $payment[5] = $exp[1];
        switch ($payment[1]) {
            case 1:
            $this->cardmessage = "カード会社：VISA\n";
            break;
            case 2:
            $this->cardmessage = "カード会社：MASTER\n";
            break;
            case 3:
            $this->cardmessage = "カード会社：NICOS\n";
            break;
            case 4:
            $this->cardmessage = "カード会社：JCB\n";
            break;
            case 5:
            $this->cardmessage = "カード会社：アメックス\n";
            break;
        }
        $this->cardmessage .= "下４桁：".$payment[2]."\n";
        $this->cardmessage .= "お支払額：###PRICE###円";
        if ($sumprice==0) {
            $this->cardmessage = "";
        }
        break;
        case 2: // コンビニ決済
        $payment[0] = 4;
        parse_str($results[0]["cvsinfo"], $cvsinfo);
        $this->cvsmessage  = "支払いコンビニ店名：";
        switch($cvsinfo["cvs_shop"]) {
            case "01":
            $this->cvsmessage .= "セブンイレブン\n";
            $this->cvsmessage .= "受付番号：".$cvsinfo["receipt_no"] ."\n";

            $note  = "払込票を印刷、もしくは払込票番号を紙などに控えて全国のセブンイレブンにてお支払ください。\n";
            $note .= "払込票番号を紙などでお持ちの場合は、お客様から店員に提示の際に「インターネット代金の支払い」とお伝え下さい。\n";
            $note .= "詳しくは以下のページにてご確認ください。\n";
            $note .= "http://pr.sej.co.jp/in/system.html \n";
            break;

            case "02":
            $this->cvsmessage .= "ローソン・セイコーマート\n";
            $this->cvsmessage .= "受付番号：".$cvsinfo["receipt_no"] ."\n";
            $this->cvsmessage .= "電話番号：".$cvsinfo["cvs_tel"] ."\n";
            $note = "受付番号を紙などに控えて全国のローソンまたはセイコーマートにてお支払ください。\n";
            break;

            case "03":
            $this->cvsmessage .= "ファミリーマート\n";
            $company_code = substr($cvsinfo["receipt_no"], 0, 5);
            $order_no = substr($cvsinfo["receipt_no"], 6, 12);
            $this->cvsmessage .= "受付番号：".$cvsinfo["receipt_no"] ."\n";
            $this->cvsmessage .= "企業コード：".$company_code ."\n";
            $this->cvsmessage .= "注文番号：".$order_no ."\n";
            $note = "企業コード、注文番号を紙などに控えて全国のファミリーマートにてお支払ください。\n";
            break;

            case "04":
            $this->cvsmessage .= "サークルKサンクス・デイリーヤマザキ・ヤマザキデイリーストアー・タイムリー・ミニストップ\n";
            $this->cvsmessage .= "受付番号：".$cvsinfo["receipt_no"] ."\n";
            $mobile_url = preg_replace("/https:\/\/.+?\/JLPcon/",
                                       "https://w2.kessai.info/JLM/JLMcon",
                                       urldecode($cvsinfo["haraikomi_url"]));
            $note  = "統合決済画面を印刷、もしくはオンライン決済番号を紙などに控えて全国のサークルK、サンクス、\n";
            $note .= "デイリーヤマザキ、ヤマザキデイリーストアー、タイムリー、ミニストップ にてお支払ください。\n";
            $note .= "オンライン決済番号のみを紙などでお持ちの場合は、お客様から店員に提示の際に「オンライン決済」である旨お伝え下さい。\n";
            break;
        }
        $this->cvsmessage .= "支払い金額：###PRICE### 円　\n";
        $this->cvsmessage .= "支払い期限：". $cvsinfo["pay_limit"]."\n";

        if (!empty($cvsinfo["haraikomi_url"])) {
            $this->cvsmessage .= "払込票URL：". urldecode($cvsinfo["haraikomi_url"]) ."\n";
        }
        if (!empty($mobile_url)) {
            $this->cvsmessage .= "払込票URL(携帯用)：". $mobile_url ."\n";
        }
        $this->cvsmessage .= "\n". $note;

        $payment["message"] = "【お支払い】\n". str_replace("###PRICE###", $cvsinfo["amount"], $this->cvsmessage);
        break;
        case 3:
        $payment[0] = 2;
        $this->daibikimessage  = "運送会社　：ヤマト運輸\n";
        $this->daibikimessage .= "お支払い　：現金（代金引換払いでは、クレジットはお取扱いしておりません）\n";
        $this->daibikimessage .= "代引手数料：".$daibiki_cost."円\n";
        $this->daibikimessage .= "お支払い額：###PRICE###円";
        $payment["message"] = "【お支払い】\n". str_replace("###PRICE###", $sumprice, $this->daibikimessage);
        break;
        case 4:
        $payment[0] = 3;
        $payment["shiten"] = $results[0]["shitennumberkey"];
        $payment["kouza"] = $results[0]["kouzanumberkey"];
        $sysinfo = $this->c_systeminfo->selectAll();
        $payment["bank_name"] = $sysinfo[0]["bankname"];
        $payment["shiten_name"] = $sysinfo[0]["shitenname"];
        $kouza_div = ($sysinfo[0]["kouzadiv"] == 1) ? "口座" : "当座";
        $payment["kouza_div"] = $kouza_div;
        $payment["kouza_name"] = $sysinfo[0]["kouzaname"];

        $this->bankmessage  = "銀行名：". $sysinfo[0]["bankname"] ."\n";
        //$this->bankmessage .= "銀行コード：0036\n";
        $this->bankmessage .= "支店名：". $sysinfo[0]["shitenname"] ."\n";
        //$this->bankmessage .= "支店番号：". $results[0]["shitennumberkey"] ."\n";
        $this->bankmessage .= "口座種類：". $kouza_div ."\n";
        $this->bankmessage .= "口座番号：". $results[0]["kouzanumberkey"]  ."\n";
        $this->bankmessage .= "口座名義：". $sysinfo[0]["kouzaname"] ."\n";
        $this->bankmessage .= "お支払額：###PRICE###円\n";
        $this->bankmessage .= "※振込み手数料はお客様でご負担下さい。";
        $payment["message"] = "【お支払い】". str_replace("###PRICE###", $sumprice, $this->bankmessage);
        break;
        case 5:
        $payment[0] = 5;
        $this->yuubinmessage = "";
        //$params["payment"]["message"] = "【お支払い】\n". $this->yuubinmessage;
        break;
        }
   
        $from        = MAIL_FROM;

        $params = array("username"        => (empty($results[0]["ordermember"])) ? $sendbuyername : $lastnm." ".$firstnm,
                        "takkyubin"       => $takkyubin,
                        "orderdate"       => $orderdate,
                        "orderid"         => $orderno,
                        "payment"         => $payment,
                        "post"            => $sendpostalcd,
                        "address"         => $prefnm . $sendaddr1,
                        "address2"        => $sendaddr2,
                        "tel"             => $sendtelno1,
                        "addressee"       => $addressee,
                        "nicknm"          => $nicknm,
                        "mailaddr"        => $mailaddr,
                        "usernote"        => $usernote
                       );
        if ($template=="sellout_information") {
            $params["username"] = $nicknm;
            $params["ordername"] = (empty($results[0]["ordermember"])) ? $sendbuyername : $lastnm." ".$firstnm;
        }
        $params["totalprice"] = $sumprice;

        foreach ($results as $key => $val) {
            $itemlist = array();
            if ($val["typediv"]<>1) {
                if ($val["typediv"] == 2 && $val["price"]>0)
                    $souryou = $val["price"];
                if ($val["typediv"] == 3 && $val["price"]>0)
                    $takkyubin = $val["price"];
                if ($val["typediv"] == 10 && $val["price"]>0)
                    $daibiki = $val["price"];
                if ($val["typediv"] == 11 && $val["price"]>0)
                    $yuubin = $val["price"];
            } else {
                $itemlist["itemnm"] = $val["itemnm"] ." ". $val["variationnm"];
                $itemlist["count"]  = $val["count"];
                $itemlist["price"]  = $val["price"];
            }
            if (!empty($itemlist)) $params["order"][] = $itemlist;
 
            // Google analytics トラッキングコード用の変数設定 
            if ($template!="sellout_information") {
                if ($val["typediv"]==1) { 
                    $additem[] = array("orderid" => $orderno, 
                                       "sku" => "", 
                                       "productname" => $val["itemnm"] ." ". $val["variationnm"], 
                                       "category" => "", 
                                       "price" => $val["price"], 
                                       "quantity" => $val["count"]); 
                } 
            }

        }
        $params["souryou"] = $souryou;
        $params["takkyubin"] = $takkyubin;
        $params["daibiki"] = $daibiki;
        $params["yuubin"] = $yuubin;

        if (!empty($this->download_url) && !empty($this->dlperiodend)) {
            $params["download_url"] = $this->download_url;
            $params["dlperiodend"] = $this->dlperiodend;
        }

        // Google analytics トラッキングコード用の変数設定 
        if ($template!="sellout_information") {
            $trackerdata["trans"] = array("orderid" => $orderno, 
                                          "total" => $sumprice, 
                                          "tax" => 0, 
                                          "shipping" => $souryou + $takkyubin + $daibiki + $yuubin, 
                                          "city" => $sendaddr1, 
                                          "state" => $prefnm, 
                                          "country" => "Japan"); 
            $trackerdata["item"] = $additem; 
            $this->trackerdata[] = $trackerdata; 
        }

        return $this->l_mail->sendFromTemplate($template, $mail, $from, $params);
    }

    function getCardmessages() {
        return str_replace("###PRICE###", $this->tp, $this->cardmessage);
    }
    function getDaibikimessages() {
        return str_replace("###PRICE###", $this->tp, $this->daibikimessage);
    }
    function getBankmessages() {
        return str_replace("###PRICE###", $this->tp, $this->bankmessage);
    }
    function getCVSmessages() {
        return str_replace("###PRICE###", $this->tp, $this->cvsmessage);
    }
    function getYuubinmessages() {
        return str_replace("###PRICE###", $this->tp, $this->yuubinmessage);
    }
    function getDl() {
        return $this->dl;
    }
    function getTrackerdata() {
        return $this->trackerdata;
    }


    /**
     * 確認画面用の商品配列作成
     *
     * params: $item_array    元になる商品の配列
     *         $re_itemarray 確認画面で使用する商品の配列
     *         $pricedata    料金計算
     *         $totalprice   総合計金額
     *         $paymentflg   支払い方法フラグ true だとカード決済のみ
     *         $sellerflg    出品者フラグ
     *         $takkyubin    宅急便フラグ
     *
     **/
    function makeItemArrayForCheck($item_array,&$re_itemarray,&$pricedata,&$totalprice,&$paymentflg,&$sellerflg,$takkyubin) {
        $souryou = $this->souryou->GetQuote();

        if($item_array != NULL)
        {
            $totalprice_arr = array(0,array(),array());
            for($i=0; $i<count($item_array); $i++)
            {
//品名コード・構成コード・在庫コードを元にテーブルから商品名と価格を入手　Item_arrayに挿入
                $params = $this->c_cart->selectOne($item_array[$i][0], $item_array[$i][1], $item_array[$i][2]);
                if($params) {
                    //購入できない商品がある
                    if (empty($params['itemnm']) && empty($params['totalprice'])) return 'error';
                    //--
                    if (!empty($params["sellercd"])) $sellerflg = true;

                    $souryouflg = $params["souryouprc"];

                    $pd = array();
                    $d = array(
                         $item_array[$i][0], 
                         $item_array[$i][1],
                         $item_array[$i][2],
                         $item_array[$i][3],
                         $params['itemnm'] ." ". $params['variationnm'],
                         intval($params['sellingprice']),
                         intval(($params['sellingprice'] + $params['souryouprc']) * $item_array[$i][3]),
                         intval($params['souryouprc']),
                         $params['sellernm'],
                         $params['itemexp'],
                         $params['mediacd'],
                         intval($params['sellingprice'] * $item_array[$i][3]));

                    if (empty($params["sellercd"]) && $params["reserveflg"]==0) {
                        $key = 0; //在庫
                        $re_itemarray[$key][] = $d;
                        //if($takkyubin==1) $takkyubinprc = intval($params['takkyubinprc']);
                        $pricedata[$key]["totalprice"] += intval($d[3]) * intval($d[5]);
                        // 送料計算用
                        $totalprice_arr[0] += intval($d[3]) * intval($d[5]);
                        //--
                        //$pricedata[$key]["souryouprc"] += intval($d[3]) * intval($params['souryouprc']);
                        //$pricedata[$key]["souryouprc"] = SITE_SOURYOU;
                        // 商品に個別の送料が設定されている場合は個別送料を優先
                        if($souryouflg < 0)
                        {
                            // 宅急便料金を利用
                            $pricedata[$key]["souryouprc"] = intval($souryou['cost']);
                        }
                        else
                        {
                            if ($souryouflg == 0)
                                // 送料ゼロ円
                                $pricedata[$key]["souryouprc"] = 0;
                            else
                                // 入力料金を利用
                                $pricedata[$key]["souryouprc"] = $params["souryouprc"];
                        }
                        $totalprice += intval($d[3]) * intval($d[5]);
                    } else if (empty($params["sellercd"]) && $params["reserveflg"]==1) {
                        if (!$paymentflg) {
                            $paymentflg = true;
                            if ((SELLER_PAY_ETC || USE_BANK_SELLER_ITEM)) $paymentflg = false;
                        }
                        $key = 1; //予約
                        $re_itemarray[$key][] = $d;
                        $pd["totalprice"] += intval($d[3]) * intval($d[5]);
                        // 送料計算用
                        $totalprice_arr[1][] += intval($d[3]) * intval($d[5]);
                        //--
                        //$pd["souryouprc"] = intval($d[3]) * intval($params['souryouprc']);
                        //$pd["souryouprc"] = SITE_SOURYOU;
                        $pd["souryouprc"] = $souryou['cost'];
                        $totalprice += intval($d[3]) * intval($d[5]);
                        /*
                        if($takkyubin==1) {
                            $pd["takkyubinprc"] = intval($params['takkyubinprc']);
                            $pd["totalprice"] += intval($params['takkyubinprc']);
                            $totalprice += intval($params['takkyubinprc']);
                        }
                        */
                        $pricedata[$key][] = $pd;
                    } else if (!empty($params["sellercd"])) {
                        if (!$paymentflg) {
                            $paymentflg = true;
                            if ((SELLER_PAY_ETC || USE_BANK_SELLER_ITEM)) $paymentflg = false;
                        }
                        $data = $this->dlitem->getDownloadItem($item_array[$i][0], $item_array[$i][1]);
                        if ($data!==FALSE && !is_null($data)) {
                            $mobile = &Net_UserAgent_Mobile::isMobile();
                            if ($mobile) return 'error';
                        }

                        if ($data===FALSE || is_null($data)) {
                            $key = 2; //出品
                            $sellercd = (string)$params["sellercd"];
                            $re_itemarray[$key][$sellercd][] = $d;
                            // 商品に個別の送料が設定されている場合は個別送料を優先
                            if($souryouflg < 0)
                            {
                                // 宅急便料金を利用
                                $pricedata[$key][$sellercd]["souryouprc"] = intval($params["sellersouryou"]);
                            }
                            else
                            {
                                if($souryouflg == 0)
                                    // 送料ゼロ円
                                    $pricedata[$key][$sellercd]["souryouprc"] = 0;
                                else
                                    // 入力料金を利用
                                    $pricedata[$key][$sellercd]["souryouprc"] = $params["souryouprc"];
                            }
                            $pricedata[$key][$sellercd]["souryoumax"] = intval($params["sellersouryoumax"]);
                            $pricedata[$key][$sellercd]["totalprice"] += intval($d[3]) * intval($d[5]);

                            $totalprice += intval($d[3]) * intval($d[5]);
                            /*
                            if($takkyubin==1) {
                                $sell_takkyubinprc[$sellercd] = intval($params['takkyubinprc']);
                            }
                            */
                        } elseif ($data["fileexistence"]==="t") {
                            if (!$paymentflg) $paymentflg = true;
                            $key = 3; //ダウンロード商品
                            $sellercd = (string)$params["sellercd"];
                            $re_itemarray[$key][] = $d;
                            $pricedata[$key][]["totalprice"] += intval($d[3]) * intval($d[5]);

                            $totalprice += intval($d[3]) * intval($d[5]);
                        }
                    }
                }
            }
            /*
            if (!empty($takkyubinprc)) {
                if($takkyubin==1) {
                    $pricedata[0]["takkyubinprc"] = $takkyubinprc;
                    $pricedata[0]["totalprice"] += $takkyubinprc;
                    $totalprice += $takkyubinprc;
                }
            }
            if (!empty($sell_takkyubinprc)) {
                if($takkyubin==1) {
                  while (list($sellercd, $takkyubinprc) = each($sell_takkyubinprc)) {
                    $pricedata[2][$sellercd]["takkyubinprc"] = $takkyubinprc;
                    $pricedata[2][$sellercd]["totalprice"] += $takkyubinprc;
                    $totalprice += $takkyubinprc;
                  }
                }
            }
            */
        }
        ///*
        if ($totalprice_arr[0] >= SOURYOU_MAX) {
            $pricedata[0]["souryouprc"] = 0;
        }
        //*/
        if (!empty($pricedata[0]["souryouprc"])) {
            $pricedata[0]["totalprice"] += $pricedata[0]["souryouprc"];
            $totalprice += $pricedata[0]["souryouprc"];
        }
        for ($i=0; $i < count($pricedata[1]); $i++) {
            $total = $totalprice_arr[1][$i];
            ///*
            if ($total >= SOURYOU_MAX) {
                $pricedata[1][$i]["souryouprc"] = 0;
            }
            //*/
            $pricedata[1][$i]["totalprice"] += $pricedata[1][$i]["souryouprc"];
            $totalprice += $pricedata[1][$i]["souryouprc"];
        }

        foreach ($pricedata[2] as $key => $val) {
            $total = $val["totalprice"];
            ///*
            if (!empty($pricedata[2][$key]["souryoumax"]) && $total >= $pricedata[2][$key]["souryoumax"]) {
                $pricedata[2][$key]["souryouprc"] = 0;
            }
            //*/
            $pricedata[2][$key]["totalprice"] += $pricedata[2][$key]["souryouprc"];
            $totalprice += $pricedata[2][$key]["souryouprc"];
        }
        //--
        arsort($re_itemarray, SORT_NUMERIC);
        return;
    }


    /**
     * 購入完了画面用の商品配列作成
     *
     * params: $item_array    元になる商品の配列
     *         $re_itemarray 確認画面で使用する商品の配列
     *         $payment   支払い方法フラグ true だとカード決済のみ
     *         $takkyubin    宅急便フラグ
     *
     **/
    function makeItemArrayForDone($item_array,&$re_itemarray,$pa,$takkyubin) {
        $souryou = $this->souryou->GetQuote();

        if($item_array != NULL)
        {
            for($i=0; $i<count($item_array); $i++)
            {
//品名コード・構成コード・在庫コードを元にテーブルから商品名と価格を入手　Item_arrayに挿入
                $params = $this->c_cart->selectOne($item_array[$i][0], $item_array[$i][1], $item_array[$i][2]);
                if($params) {
                    //購入できない商品がある
                    if (empty($params['itemnm']) && empty($params['totalprice']))
                    {
                    	return 'error';
                    }
                    //--
                    $pd = array();
                    $d = array(
                         $item_array[$i][0], 
                         $item_array[$i][1],
                         $item_array[$i][2],
                         $item_array[$i][3],
                         $params['itemnm'] ." ". $params['variationnm'],
                         intval($params['sellingprice']));

                    if (empty($params["sellercd"]) && $params["reserveflg"]==0) {
                        $key = 0; //在庫
                        //if($takkyubin==1) $re_itemarray[$key]["takkyubinprc"] = intval($params['takkyubinprc']);
                        //$re_itemarray[$key]["souryouprc"] += $d[3] * intval($params['souryouprc']);
                        //$re_itemarray[$key]["souryouprc"] = SITE_SOURYOU;
                        $re_itemarray[$key]["souryouprc"] = $souryou['cost'];
                        $re_itemarray[$key]["totalprice"] += $d[3] * intval($d[5]);
                        $re_itemarray[$key][] = $d;
                    } else if (empty($params["sellercd"]) && $params["reserveflg"]==1) {
                        $key = 1; //予約
                        if ($pa[0]!=1 && !SELLER_PAY_ETC)
                        {
                        	return "error";
                        }
                        //$d["souryouprc"] = $d[3] * intval($params['souryouprc']);
                        //$d["souryouprc"] = SITE_SOURYOU;
                        $d["souryouprc"] = $souryou['cost'];
                        $d["totalprice"] += intval($d[3]) * intval($d[5]);
                        /*
                        if($takkyubin==1) {
                            $d["takkyubinprc"] = intval($params['takkyubinprc']);
                        }
                        */
                        $re_itemarray[$key][] = $d;
                    } else if (!empty($params["sellercd"])) {
                        $data = $this->dlitem->getDownloadItem($item_array[$i][0], $item_array[$i][1]);
                        if ($data!==FALSE && !is_null($data)) {
                            $mobile = &Net_UserAgent_Mobile::isMobile();
                            if ($mobile)
                            {
           	                	return 'error';
                            }
                        }

                        if ($data===FALSE || is_null($data)) {
                        $key = 2; //出品
                        /**
                        if ($pa[0]!=1 && !SELLER_PAY_ETC) return "error";
                         */

                            if (SELLER_PAY_ETC || USE_BANK_SELLER_ITEM)
                            {
                                $sellercd = (string)$params["sellercd"];
                                $re_itemarray[$key][$sellercd]["souryouprc"] = intval($params["sellersouryou"]);
                                $re_itemarray[$key][$sellercd]["souryoumax"] = intval($params["sellersouryoumax"]);
                                $d["totalprice"] += intval($d[3]) * intval($d[5]);
                                $re_itemarray[$key][$sellercd][] = $d;
                                /*
                                if($takkyubin==1) {
                                    $re_itemarray[$key][$sellercd]["takkyubinprc"] = intval($params['takkyubinprc']);
                                }
                                */
                            }
                            else
                            {
                                return "error";
                            }
                        } elseif ($data["fileexistence"]==="t") {
                        $key = 3; //ダウンロード商品
                        if ($pa[0]!=1)
                        {
                        	return "error";
                        }
                        $d["totalprice"] += intval($d[3]) * intval($d[5]);
                        $re_itemarray[$key][] = $d;
                        }
                    }
                }
            }
        }
        ///*
        if (($re_itemarray[0]["totalprice"]) >= SOURYOU_MAX) {
            $re_itemarray[0]["souryouprc"] = 0;
        }
        //*/
        for ($i=0; $i < count($re_itemarray[1]); $i++) {
            $total = $re_itemarray[1][$i]["totalprice"];
            ///*
            if ($total >= SOURYOU_MAX) {
                $re_itemarray[1][$i]["souryouprc"] = 0;
            }
            //*/
        }
        foreach ($re_itemarray[2] as $key => $val) {
            $total = 0;
            for ($i=0; $i < count($val); $i++) {
                $total = $val[$i]["totalprice"];
            }
            ///*
            if (!empty($re_itemarray[2][$key]["souryoumax"]) && $total >= $re_itemarray[2][$key]["souryoumax"]) {
                $re_itemarray[2][$key]["souryouprc"] = 0;
            }
            //*/
        }
        //--
        arsort($re_itemarray, SORT_NUMERIC);
        return;
    }


    function updateRemise($opt, $data, &$cardmessage) {
        if (!$this->t) return "";

        $log =& LogFactory::getLog();
        $db = $this->dbaccess->doConnect();
        $db->setFetchMode(DB_FETCHMODE_ASSOC);
        $db->autoCommit(false);
        $db->query('BEGIN;');

        $id = explode("-", $opt);
        foreach ($id as $orderno) {
            $info  = "payquickid:". $data["payquickid"] ."\n";
            $info .= "受注番号:";
            $info .= str_replace("-", ",", $opt);

            $cardcompany = $this->t->getCardCompany($data["cardcompany"]);

            // 仮受注フラグ
            if (!$this->updatePreOrderFlg($db, $orderno)) {
                return false;
            }
            // --

            $params = array($orderno, $info, $cardcompany, $data["cardnumber"], $data["cardname"], $data["cardexp"], '',$_SERVER['REMOTE_ADDR']);
            $sql = "SELECT * FROM f_deposit_remiseinfo_update(2,?,?,?,?,?,?,?,?)";
            $res = $db->getRow($sql, $params);
            if (DB::isError($res) || $res < 0) {
                $log->error("remiseinfo rollback " . $res->userinfo, $func_name);
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
        }

        $cardmessage  = "カード会社：". $cardcompany ."\n";
        $cardmessage .= "下4桁：". $data["cardnumber"] ."\n";

        $db->query('COMMIT;');
        $db->commit();
        $this->dbaccess->doClose($db);
        return true;
    }

    function updateRemiseCvs($orderno, $data, &$cvsmessage) {
        if (!$this->t) return "";

        $log =& LogFactory::getLog();
        $db = $this->dbaccess->doConnect();
        $db->setFetchMode(DB_FETCHMODE_ASSOC);
        $db->autoCommit(false);
        $db->query('BEGIN;');

        $cvsshop = $this->t->getCvsCompany($data["pay_cvs"]);
        $info["cvs_shop"] = $cvsshop;
        $info["receipt_no"] = $data["no1"];
        $info["haraikomi_url"] = $data["no2"];
        foreach ($info as $k => $v) {
            $s[] = $k ."=". $v;
        }

        // 仮受注フラグ
        if (!$this->updatePreOrderFlg($db, $orderno)) {
            return false;
        }
        // --

        $sql = "SELECT cvsinfo FROM t_deposit WHERE orderno=?";
        $str = $db->getOne($sql, array($orderno));

        $str .= "&". implode("&", $s);
        $params = array($orderno, $str, '',$_SERVER['REMOTE_ADDR']);
        $sql = "SELECT * FROM f_deposit_cvsinfo_update(2,?,?,?,?)";
        $res = $db->getRow($sql, $params);
        if (DB::isError($res) || $res < 0) {
            $log->error("cvsinfo rollback " . $res->userinfo, $func_name);
            $this->dbaccess->doClose($db);
            return false;
        }
        $this->dbaccess->doClose($db);

        $cvsmessage  = $info["cvs_shop"] ."\n";
        if ($data["pay_cvs"]=="D030") { // ファミリーマート
            $cvsmessage .= "企業コード：" . $info["receipt_no"] ."\n";
            $cvsmessage .= "注文番号：" . $info["haraikomi_url"] ."\n";
        } else {
            $cvsmessage .= "受付番号：" . $info["receipt_no"] ."\n";
            $cvsmessage .= "払込票URL：<a href='" . $info["haraikomi_url"] ."'>". $info["haraikomi_url"] ."</a>\n";
        }
        return true;
    }

    // 仮受注フラグを本受注に
    function updatePreOrderFlg(&$db, $orderno) 
    {
	    $this->download_url = $this->dlperiodend = ""; 
        $log =& LogFactory::getLog();
        // 仮受注状態のデータを取得
        // 見出し
        $sql = "SELECT * FROM t_order_title WHERE orderno = ? AND preorderflg = TRUE AND delflg = FALSE";
        $t_data = $db->getRow($sql, array($orderno));
        if (empty($t_data)) {
            $log->error("t_order_title preorderdata rollback " . $t_data->userinfo, $func_name);
            $db->query('ROLLBACK;');
            $db->rollback();
            $this->dbaccess->doClose($db);
            return false;
        }
        //--

        // 仮受注フラグ
        $sql = "UPDATE t_order_title SET preorderflg = FALSE, orderprocessflg = FALSE WHERE orderno = ? AND preorderflg = TRUE AND delflg = FALSE";
        $res = $db->query($sql, array($orderno));
        if (DB::isError($res)) {
            $log->error("t_order_title preorderflg rollback " . $res->userinfo, $func_name);
            $db->query('ROLLBACK;');
            $db->rollback();
            $this->dbaccess->doClose($db);
            return false;
        }
        $sql = "UPDATE t_order_detail SET preorderflg = FALSE WHERE orderno = ? AND preorderflg = TRUE AND delflg = FALSE";
        $res = $db->query($sql, array($orderno));
        if (DB::isError($res)) {
            $log->error("t_order_detail preorderflg rollback " . $res->userinfo, $func_name);
            $db->query('ROLLBACK;');
            $db->rollback();
            $this->dbaccess->doClose($db);
            return false;
        }
        // --

        // 本受注になった時に作成するデータ
        $filename = PAY_INFO_TMPDIR . $t_data["orderno"] .".txt";
        if (is_file($filename)) {
            $payinfo_str = file_get_contents($filename);
            if (empty($payinfo_str)) {
                $db->query('ROLLBACK;');
                $db->rollback();
                $this->dbaccess->doClose($db);
                return false;
            }
            $payinfo = unserialize($payinfo_str);

            // 予約受注データ
            if ($payinfo["buystate"] == 1) {
                if (!$this->getOrderDetailReserve($db, $t_data["ordermember"], $payinfo["orderno"], $payinfo["itemdata"], $prc)) {
                    return false;
                }

                $params = array($payinfo["orderno"]);
                $sql  = "SELECT * FROM v_order_detail_list WHERE orderno = ?";
                $data = $db->getAll($sql, $params);

                // 出荷明細を作成
                foreach ($data as $val) {
                    if ($val["typediv"]==1) {
                        $sql  = "SELECT * FROM f_forward_detail_update ";
                        $sql .= "(2,?,?,?,?,?,?,?)";
                        $p = array($payinfo["orderno"], $val["orderrowno"], NULL, 1, NULL, '',$_SERVER['REMOTE_ADDR']); 
                        $res = $db->getRow($sql, $p);

                        if (DB::isError($res) || $res['errcd'] < 0) {
                            $log->error("forward rollback ".$res->userinfo, $func_name);
                            $db->query('ROLLBACK;');
                            $db->rollback();
                            $this->dbaccess->doClose($db);
                            return false;
                        }
                    }
                }
                // --
            }
            //--

            // 入金データ
            if (!$this->insertDepositAndPayment($db, $retarr, $payinfo["orderno"], $payinfo["payment_data"],
                                                $payinfo["cardinfo"], $payinfo["txn_type"], $payinfo["request"])) {
                return false;
            }
            //--
            unlink($filename);

            // ダウンロード受注データ
            if ($payinfo["buystate"] == 3) {
                $params = array($t_data["orderno"]);
                $sql  = "SELECT * FROM v_order_detail_list WHERE orderno = ?";
                $data = $db->getAll($sql, $params);
                if (!empty($t_data["ordermember"])) {
                    if (!$this->makeDownloadOrder($db, $payinfo["orderno"], $t_data["ordermember"], $data[0]["itemcd"], $data[0]["structcd"])) {
                        return false;
                    }
                    //--
                }
            }
            //--
        }

        $params = array($t_data["orderno"]);
        $sql  = "SELECT * FROM v_order_detail_list WHERE orderno = ?";
        $data = $db->getAll($sql, $params);
        if (!empty($t_data["ordermember"])) {

            foreach ($data as $d) {
                if (empty($d["itemcd"]) && empty($d["structcd"])) {
                    continue;
                }

                // カートの中の商品を削除
                $params = array($t_data["ordermember"], $d["itemcd"], $d["structcd"], '', $_SERVER["REMOTE_ADDR"]);
                $sql = "SELECT * FROM f_pre_order_detail_update(5,?,NULL,?,?,NULL,NULL,?,?)";
                $res = $db->getRow($sql, $params);
                if (DB::isError($res) || $res < 0) {
                    $log->error("preorder rollback " . $res->userinfo, $func_name);
                    $db->query('ROLLBACK;');
                    $db->rollback();
                    $this->dbaccess->doClose($db);
                    return false;
                }
                //--

            }
        }

        // ダウンロード商品
        $dl = $this->dlitem->getDownloadItem($data[0]["itemcd"], $data[0]["structcd"]);
        if (!empty($dl)) {
            $dlorder = $this->dlitem->getDownloadOrder($data[0]["orderno"], $data[0]["orderrowno"]);

            $fid_key = $dlorder["orderno"] ."_". $dlorder["orderrowno"] ."_". $dlorder["membercd"];
            $this->download_url = $this->dlitem->getDownloadURL(sha1($fid_key), $dlorder["orderno"], $dlorder["orderrowno"]);
            $this->dlperiodend = $dlorder["dlperiodend"];
        }

        // メール送信
        if (!empty($dl)) {
            $this->dl++;
            $this->sendMailOrder("buy_complete_dl", $t_data["orderno"]);
        } else {

            if ($data[0]["stockstate"]==1) {
                $this->sendMailOrder("buy_complete_reserve", $t_data["orderno"]);
            } else if ($data[0]["stockstate"]==3 && !empty($data[0]["sellercd"])) {
                $this->sendMailOrder("buy_complete_sell", $t_data["orderno"]);
                $this->sendMailOrder("sellout_information", $t_data["orderno"]);
            } else if ($data[0]["stockstate"]==3 && empty($data[0]["sellercd"])) {
                $this->sendMailOrder("buy_complete", $t_data["orderno"]);
            }
        }
        //--

        return true;
    }
}
?>