source: branches/version-2_5-dev/data/class/helper/SC_Helper_DB.php @ 19860

Revision 19860, 79.8 KB checked in by nanasess, 13 years ago (diff)

#843(複数配送先の指定)

  • とりあえず通常配送が通るように修正
  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id Revision Date
  • Property svn:mime-type set to text/x-httpd-php; charset=UTF-8
Line 
1<?php
2/*
3 * This file is part of EC-CUBE
4 *
5 * Copyright(c) 2000-2010 LOCKON CO.,LTD. All Rights Reserved.
6 *
7 * http://www.lockon.co.jp/
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22 */
23
24/**
25 * DB関連のヘルパークラス.
26 *
27 * @package Helper
28 * @author LOCKON CO.,LTD.
29 * @version $Id:SC_Helper_DB.php 15532 2007-08-31 14:39:46Z nanasess $
30 */
31class SC_Helper_DB {
32
33    // {{{ properties
34
35    /** ルートカテゴリ取得フラグ */
36    var $g_root_on;
37
38    /** ルートカテゴリID */
39    var $g_root_id;
40
41    /** 選択中カテゴリ取得フラグ */
42    var $g_category_on;
43
44    /** 選択中カテゴリID */
45    var $g_category_id;
46
47    // }}}
48    // {{{ functions
49
50    /**
51     * データベースのバージョンを所得する.
52     *
53     * @param string $dsn データソース名
54     * @return string データベースのバージョン
55     */
56    function sfGetDBVersion($dsn = "") {
57        $dbFactory = SC_DB_DBFactory_Ex::getInstance();
58        return $dbFactory->sfGetDBVersion($dsn);
59    }
60
61    /**
62     * カラムの存在チェックと作成を行う.
63     *
64     * チェック対象のテーブルに, 該当のカラムが存在するかチェックする.
65     * 引数 $add が true の場合, 該当のカラムが存在しない場合は, カラムの生成を行う.
66     * カラムの生成も行う場合は, $col_type も必須となる.
67     *
68     * @param string $table_name テーブル名
69     * @param string $column_name カラム名
70     * @param string $col_type カラムのデータ型
71     * @param string $dsn データソース名
72     * @param bool $add カラムの作成も行う場合 true
73     * @return bool カラムが存在する場合とカラムの生成に成功した場合 true,
74     *               テーブルが存在しない場合 false,
75     *               引数 $add == false でカラムが存在しない場合 false
76     */
77    function sfColumnExists($table_name, $col_name, $col_type = "", $dsn = "", $add = false) {
78        $dbFactory = SC_DB_DBFactory_Ex::getInstance();
79        $dsn = $dbFactory->getDSN($dsn);
80
81        $objQuery =& SC_Query::getSingletonInstance($dsn);
82
83        // テーブルが無ければエラー
84        if(!in_array($table_name, $objQuery->listTables())) return false;
85
86        // 正常に接続されている場合
87        if(!$objQuery->isError()) {
88            list($db_type) = split(":", $dsn);
89
90            // カラムリストを取得
91            $columns = $objQuery->listTableFields($table_name);
92
93            if(in_array($col_name, $columns)){
94                return true;
95            }
96        }
97
98        // カラムを追加する
99        if($add){
100            $objQuery->query("ALTER TABLE $table_name ADD $col_name $col_type ");
101            return true;
102        }
103        return false;
104    }
105
106    /**
107     * データの存在チェックを行う.
108     *
109     * @param string $table_name テーブル名
110     * @param string $where データを検索する WHERE 句
111     * @param string $dsn データソース名
112     * @param string $sql データの追加を行う場合の SQL文
113     * @param bool $add データの追加も行う場合 true
114     * @return bool データが存在する場合 true, データの追加に成功した場合 true,
115     *               $add == false で, データが存在しない場合 false
116     */
117    function sfDataExists($table_name, $where, $arrval, $dsn = "", $sql = "", $add = false) {
118        $dbFactory = SC_DB_DBFactory_Ex::getInstance();
119        $dsn = $dbFactory->getDSN($dsn);
120
121        $objQuery =& SC_Query::getSingletonInstance();
122        $count = $objQuery->count($table_name, $where, $arrval);
123
124        if($count > 0) {
125            $ret = true;
126        } else {
127            $ret = false;
128        }
129        // データを追加する
130        if(!$ret && $add) {
131            $objQuery->exec($sql);
132        }
133        return $ret;
134    }
135
136    /**
137     * 店舗基本情報を取得する.
138     *
139     * @param boolean $force 強制的にDB取得するか
140     * @return array 店舗基本情報の配列
141     */
142    function sfGetBasisData($force = false) {
143        static $data;
144
145        if ($force || !isset($data)) {
146            $objQuery =& SC_Query::getSingletonInstance();
147            $arrRet = $objQuery->select('*', 'dtb_baseinfo');
148
149            if (isset($arrRet[0])) {
150                $data = $arrRet[0];
151            } else {
152                $data = array();
153            }
154        }
155
156        return $data;
157    }
158
159    /* 選択中のアイテムのルートカテゴリIDを取得する */
160    function sfGetRootId() {
161
162        if(!$this->g_root_on)   {
163            $this->g_root_on = true;
164            $objQuery =& SC_Query::getSingletonInstance();
165
166            if (!isset($_GET['product_id'])) $_GET['product_id'] = "";
167            if (!isset($_GET['category_id'])) $_GET['category_id'] = "";
168
169            if(!empty($_GET['product_id']) || !empty($_GET['category_id'])) {
170                // 選択中のカテゴリIDを判定する
171                $category_id = $this->sfGetCategoryId($_GET['product_id'], $_GET['category_id']);
172                // ROOTカテゴリIDの取得
173                $arrRet = $this->sfGetParents($objQuery, 'dtb_category', 'parent_category_id', 'category_id', $category_id);
174                $root_id = isset($arrRet[0]) ? $arrRet[0] : "";
175            } else {
176                // ROOTカテゴリIDをなしに設定する
177                $root_id = "";
178            }
179            $this->g_root_id = $root_id;
180        }
181        return $this->g_root_id;
182    }
183
184    /**
185     * 商品規格情報を取得する.
186     *
187     * TODO SC_Product クラスへ移動
188     *
189     * @param array $arrID 規格ID
190     * @param boolean $includePrivateProducts 非公開商品を含むか
191     * @return array 規格情報の配列
192     */
193    function sfGetProductsClass($arrID, $includePrivateProducts = false) {
194        list($product_id, $classcategory_id1, $classcategory_id2) = $arrID;
195
196        if (strlen($classcategory_id1) == 0) {
197            $classcategory_id1 = null;
198        }
199        if (strlen($classcategory_id2) == 0) {
200            $classcategory_id2 = null;
201        }
202
203        // 商品規格取得
204        $objProduct = new SC_Product();
205        $detail = $objProduct->getDetail($product_id);
206        $productsClass = $objProduct->getProductsClassFullByProductId($product_id);
207        foreach ($productsClass as $val) {
208
209            if ($val['classcategory_id1'] == $classcategory_id1
210                && $val['classcategory_id2'] == $classcategory_id2) {
211
212                $detail = array_merge($val, $detail);
213                if (!$includePrivateProducts) {
214                    if ($detail['status'] == 1) {
215                        return $detail;
216                    }
217                }
218                return $detail;
219            }
220        }
221    }
222
223    /**
224     * 支払い方法を取得する.
225     *
226     * @return void
227     */
228    function sfGetPayment() {
229        $objQuery =& SC_Query::getSingletonInstance();
230        // 購入金額が条件額以下の項目を取得
231        $where = "del_flg = 0";
232        $objQuery->setOrder("fix, rank DESC");
233        $arrRet = $objQuery->select("payment_id, payment_method, rule", "dtb_payment", $where);
234        return $arrRet;
235    }
236
237    /**
238     * カート内商品の集計処理を行う.
239     *
240     * 管理機能での利用は想定していないので注意。(非公開商品は除外される。)
241     *
242     * @param LC_Page $objPage ページクラスのインスタンス
243     * @param SC_CartSession $objCartSess カートセッションのインスタンス
244     * @param null $dummy1 互換性確保用(決済モジュール互換のため)
245     * @return LC_Page 集計処理後のページクラスインスタンス
246     *
247     * @deprecated SC_CartSession::checkProducts(),
248     *             SC_CartSession::getAllProductsTotal(),
249     *             SC_CartSession::getAllProductsTax(),
250     *             SC_CartSession::getAllProductsPoint() を使用して下さい
251     */
252    function sfTotalCart(&$objPage, $objCartSess, $dummy1 = null, $key = "") {
253
254        $objPage->tpl_total_inctax[$key] = 0;     // 費用合計(税込み)
255        $objPage->tpl_total_tax[$key] = 0;        // 消費税合計
256        $objPage->tpl_total_point[$key] = 0;      // ポイント合計
257
258        $objProduct = new SC_Product();
259        // カート内情報の取得
260        $arrQuantityInfo_by_product = array();
261        $cnt = 0;
262        foreach ($objCartSess->getCartList() as $arrCart) {
263            // 商品規格情報の取得
264            $arrData = $objProduct->getDetailAndProductsClass($arrCart['id']);
265            $limit = null;
266            // DBに存在する商品
267            if (count($arrData) > 0) {
268
269                // 購入制限数を求める。
270                if ($arrData['stock_unlimited'] != '1' && SC_Utils_Ex::sfIsInt($arrData['sale_limit'])) {
271                    $limit = min($arrData['sale_limit'], $arrData['stock']);
272                } elseif (SC_Utils_Ex::sfIsInt($arrData['sale_limit'])) {
273                    $limit = $arrData['sale_limit'];
274                } elseif ($arrData['stock_unlimited'] != '1') {
275                    $limit = $arrData['stock'];
276                }
277
278                if (!is_null($limit) && $arrCart['quantity'] > $limit) {
279                    if ($limit > 0) {
280                        // カート内商品数を制限に合わせる
281                        $objCartSess->setProductValue($arrCart['id'], 'quantity', $limit);
282                        $quantity = $limit;
283                        $objPage->tpl_message .= "※「" . $arrData['name'] . "」は販売制限(または在庫が不足)しております。一度に数量{$limit}以上の購入はできません。\n";
284                    } else {
285                        // 売り切れ商品をカートから削除する
286                        $objCartSess->delProduct($arrCart['cart_no']);
287                        $objPage->tpl_message .= "※「" . $arrData['name'] . "」は売り切れました。\n";
288                        continue;
289                    }
290                } else {
291                    $quantity = $arrCart['quantity'];
292                }
293
294                // (商品規格単位でなく)商品単位での評価のための準備
295                $product_id = $arrData['product_id'];
296                $arrQuantityInfo_by_product[$product_id]['quantity'] += $quantity;
297                $arrQuantityInfo_by_product[$product_id]['sale_limit'] = $arrData['sale_limit'];
298                $arrQuantityInfo_by_product[$product_id]['name'] = $arrData['name'];
299
300                $objPage->arrProductsClass[$cnt][$key] = $arrData;
301                $objPage->arrProductsClass[$cnt]['quantity'][$key] = $quantity;
302                $objPage->arrProductsClass[$cnt]['cart_no'][$key] = $arrCart['cart_no'];
303                $objPage->arrProductsClass[$cnt]['class_name1'][$key] =
304                    isset($arrData['class_name1'])
305                        ? $arrData['class_name1'] : "";
306
307                $objPage->arrProductsClass[$cnt]['class_name2'][$key] =
308                    isset($arrData['class_name2'])
309                        ? $arrData['class_name2'] : "";
310
311                $objPage->arrProductsClass[$cnt]['classcategory_name1'][$key] = $arrData['name1'];
312
313                $objPage->arrProductsClass[$cnt]['classcategory_name2'][$key] = $arrData['name2'];
314                // 価格の登録
315                $objCartSess->setProductValue($arrCart['id'], 'price', $arrData['price02']);
316                $objPage->arrProductsClass[$cnt]['uniq_price'][$key] = $arrData['price02'];
317                // ポイント付与率の登録
318                if (USE_POINT !== false) {
319                    $objCartSess->setProductValue($arrCart['id'], 'point_rate', $arrData['point_rate']);
320                }
321                // 商品ごとの合計金額
322                $objPage->arrProductsClass[$cnt]['total_inctax'][$key] = $objCartSess->getProductTotal($arrCart['id']);
323                // 送料の合計を計算する
324                $objPage->tpl_total_deliv_fee[$key] += ($arrData['deliv_fee'] * $arrCart['quantity']);
325                $cnt++;
326            } else { // DBに商品が見つからない場合、
327                $objPage->tpl_message .= "※ 現時点で販売していない商品が含まれておりました。該当商品をカートから削除しました。\n";
328                // カート商品の削除
329                $objCartSess->delProduct($arrCart['cart_no']);
330            }
331        }
332
333        foreach ($arrQuantityInfo_by_product as $product_id => $quantityInfo) {
334            if (SC_Utils_Ex::sfIsInt($quantityInfo['sale_limit']) && $quantityInfo['quantity'] > $quantityInfo['sale_limit']) {
335                $objPage->tpl_error = "※「{$quantityInfo['name']}」は数量「{$quantityInfo['sale_limit']}」以下に販売制限しております。一度にこれ以上の購入はできません。\n";
336                // 販売制限に引っかかった商品をマークする
337                foreach (array_keys($objPage->arrProductsClass) as $k) {
338                    $ProductsClass =& $objPage->arrProductsClass[$k];
339                    if ($ProductsClass['product_id'] == $product_id) {
340                        $ProductsClass['error'] = true;
341                    }
342                }
343            }
344        }
345
346        // 全商品合計金額(税込み)
347        $objPage->tpl_total_inctax[$key] = $objCartSess->getAllProductsTotal();
348        // 全商品合計消費税
349        $objPage->tpl_total_tax[$key] = $objCartSess->getAllProductsTax();
350        // 全商品合計ポイント
351        if (USE_POINT !== false) {
352            $objPage->tpl_total_point[$key] = $objCartSess->getAllProductsPoint();
353        }
354
355        return $objPage;
356    }
357
358    /**
359     * 受注一時テーブルへの書き込み処理を行う.
360     *
361     * @param string $uniqid ユニークID
362     * @param array $sqlval SQLの値の配列
363     * @return void
364     * @deprecated SC_Helper_Purchase::saveOrderTemp() を使用して下さい
365     */
366    function sfRegistTempOrder($uniqid, $sqlval) {
367        if($uniqid != "") {
368            $sqlval['session'] = serialize($_SESSION);
369            // 既存データのチェック
370            $objQuery =& SC_Query::getSingletonInstance();
371            $where = "order_temp_id = ?";
372            $cnt = $objQuery->count("dtb_order_temp", $where, array($uniqid));
373            // 既存データがない場合
374            if ($cnt == 0) {
375                // 初回書き込み時に会員の登録済み情報を取り込む
376                $sqlval = $this->sfGetCustomerSqlVal($uniqid, $sqlval);
377                $sqlval['order_temp_id'] = $uniqid;
378                $sqlval['create_date'] = "now()";
379                $objQuery->insert("dtb_order_temp", $sqlval);
380            } else {
381                $objQuery->update("dtb_order_temp", $sqlval, $where, array($uniqid));
382            }
383
384            // 受注_Tempテーブルの名称列を更新
385            // ・決済モジュールに対応するため、static メソッドとして扱う
386            //SC_Helper_DB_Ex::sfUpdateOrderNameCol($uniqid, true);
387        }
388    }
389
390    /**
391     * 会員情報から SQL文の値を生成する.
392     *
393     * @param string $uniqid ユニークID
394     * @param array $sqlval SQL の値の配列
395     * @return array 会員情報を含んだ SQL の値の配列
396     * @deprecated SC_Helper_Purchase::copyFromCustomer() を使用して下さい
397     */
398    function sfGetCustomerSqlVal($uniqid, $sqlval) {
399
400        $objCustomer = new SC_Customer();
401        // 会員情報登録処理
402        if ($objCustomer->isLoginSuccess(true)) {
403            // 登録データの作成
404            $sqlval['update_date'] = 'Now()';
405            $sqlval['customer_id'] = $objCustomer->getValue('customer_id');
406            $sqlval['order_name01'] = $objCustomer->getValue('name01');
407            $sqlval['order_name02'] = $objCustomer->getValue('name02');
408            $sqlval['order_kana01'] = $objCustomer->getValue('kana01');
409            $sqlval['order_kana02'] = $objCustomer->getValue('kana02');
410            $sqlval['order_sex'] = $objCustomer->getValue('sex');
411            $sqlval['order_zip01'] = $objCustomer->getValue('zip01');
412            $sqlval['order_zip02'] = $objCustomer->getValue('zip02');
413            $sqlval['order_pref'] = $objCustomer->getValue('pref');
414            $sqlval['order_addr01'] = $objCustomer->getValue('addr01');
415            $sqlval['order_addr02'] = $objCustomer->getValue('addr02');
416            $sqlval['order_tel01'] = $objCustomer->getValue('tel01');
417            $sqlval['order_tel02'] = $objCustomer->getValue('tel02');
418            $sqlval['order_tel03'] = $objCustomer->getValue('tel03');
419            if (defined('MOBILE_SITE')) {
420                $email_mobile = $objCustomer->getValue('email_mobile');
421                if (empty($email_mobile)) {
422                    $sqlval['order_email'] = $objCustomer->getValue('email');
423                } else {
424                    $sqlval['order_email'] = $email_mobile;
425                }
426            } else {
427                $sqlval['order_email'] = $objCustomer->getValue('email');
428            }
429            $sqlval['order_job'] = $objCustomer->getValue('job');
430            $sqlval['order_birth'] = $objCustomer->getValue('birth');
431        }
432        return $sqlval;
433    }
434
435    /**
436     * 会員編集登録処理を行う.
437     *
438     * @param array $array パラメータの配列
439     * @param array $arrRegistColumn 登録するカラムの配列
440     * @return void
441     */
442    function sfEditCustomerData($array, $arrRegistColumn) {
443        $objQuery =& SC_Query::getSingletonInstance();
444
445        foreach ($arrRegistColumn as $data) {
446            if ($data["column"] != "password") {
447                if($array[ $data['column'] ] != "") {
448                    $arrRegist[ $data["column"] ] = $array[ $data["column"] ];
449                } else {
450                    $arrRegist[ $data['column'] ] = NULL;
451                }
452            }
453        }
454        if (strlen($array["year"]) > 0 && strlen($array["month"]) > 0 && strlen($array["day"]) > 0) {
455            $arrRegist["birth"] = $array["year"] ."/". $array["month"] ."/". $array["day"] ." 00:00:00";
456        } else {
457            $arrRegist["birth"] = NULL;
458        }
459
460        //-- パスワードの更新がある場合は暗号化。(更新がない場合はUPDATE文を構成しない)
461        if ($array["password"] != DEFAULT_PASSWORD) $arrRegist["password"] = sha1($array["password"] . ":" . AUTH_MAGIC);
462        $arrRegist["update_date"] = "NOW()";
463
464        //-- 編集登録実行
465        $objQuery->update("dtb_customer", $arrRegist, "customer_id = ? ", array($array['customer_id']));
466    }
467
468    /**
469     * 受注番号、最終ポイント、加算ポイント、利用ポイントから「オーダー前ポイント」を取得する
470     *
471     * @param integer $order_id 受注番号
472     * @param integer $use_point 利用ポイント
473     * @param integer $add_point 加算ポイント
474     * @return array オーダー前ポイントの配列
475     */
476    function sfGetRollbackPoint($order_id, $use_point, $add_point) {
477        $objQuery = new SC_Query();
478        $arrRet = $objQuery->select("customer_id", "dtb_order", "order_id = ?", array($order_id));
479        $customer_id = $arrRet[0]['customer_id'];
480        if($customer_id != "" && $customer_id >= 1) {
481            $arrRet = $objQuery->select("point", "dtb_customer", "customer_id = ?", array($customer_id));
482            $point = $arrRet[0]['point'];
483            $rollback_point = $arrRet[0]['point'] + $use_point - $add_point;
484        } else {
485            $rollback_point = "";
486            $point = "";
487        }
488        return array($point, $rollback_point);
489    }
490   
491    /**
492     * 注文番号、利用ポイント、加算ポイントから最終ポイントを取得する.
493     *
494     * @param integer $order_id 注文番号
495     * @param integer $use_point 利用ポイント
496     * @param integer $add_point 加算ポイント
497     * @return array 最終ポイントの配列
498     */
499    function sfGetCustomerPoint($order_id, $use_point, $add_point) {
500        $objQuery =& SC_Query::getSingletonInstance();
501        $arrRet = $objQuery->select("customer_id", "dtb_order", "order_id = ?", array($order_id));
502        $customer_id = $arrRet[0]['customer_id'];
503        if ($customer_id != "" && $customer_id >= 1) {
504            if (USE_POINT !== false) {
505                $arrRet = $objQuery->select("point", "dtb_customer", "customer_id = ?", array($customer_id));
506                $point = $arrRet[0]['point'];
507                $total_point = $arrRet[0]['point'] - $use_point + $add_point;
508            } else {
509                $total_point = 0;
510                $point = 0;
511            }
512        } else {
513            $total_point = "";
514            $point = "";
515        }
516        return array($point, $total_point);
517    }
518
519    /**
520     * 顧客番号、利用ポイント、加算ポイントから最終ポイントを取得する.
521     *
522     * @param integer $customer_id 顧客番号
523     * @param integer $use_point 利用ポイント
524     * @param integer $add_point 加算ポイント
525     * @return array 最終ポイントの配列
526     */
527    function sfGetCustomerPointFromCid($customer_id, $use_point, $add_point) {
528        $objQuery =& SC_Query::getSingletonInstance();
529        if (USE_POINT !== false) {
530            $arrRet = $objQuery->select("point", "dtb_customer", "customer_id = ?", array($customer_id));
531            $point = $arrRet[0]['point'];
532            $total_point = $arrRet[0]['point'] - $use_point + $add_point;
533        } else {
534            $total_point = 0;
535            $point = 0;
536        }
537        return array($point, $total_point);
538    }
539    /**
540     * カテゴリツリーの取得を行う.
541     *
542     * @param integer $parent_category_id 親カテゴリID
543     * @param bool $count_check 登録商品数のチェックを行う場合 true
544     * @return array カテゴリツリーの配列
545     */
546    function sfGetCatTree($parent_category_id, $count_check = false) {
547        $objQuery =& SC_Query::getSingletonInstance();
548        $col = "";
549        $col .= " cat.category_id,";
550        $col .= " cat.category_name,";
551        $col .= " cat.parent_category_id,";
552        $col .= " cat.level,";
553        $col .= " cat.rank,";
554        $col .= " cat.creator_id,";
555        $col .= " cat.create_date,";
556        $col .= " cat.update_date,";
557        $col .= " cat.del_flg, ";
558        $col .= " ttl.product_count";
559        $from = "dtb_category as cat left join dtb_category_total_count as ttl on ttl.category_id = cat.category_id";
560        // 登録商品数のチェック
561        if($count_check) {
562            $where = "del_flg = 0 AND product_count > 0";
563        } else {
564            $where = "del_flg = 0";
565        }
566        $objQuery->setOption("ORDER BY rank DESC");
567        $arrRet = $objQuery->select($col, $from, $where);
568
569        $arrParentID = $this->sfGetParents($objQuery, 'dtb_category', 'parent_category_id', 'category_id', $parent_category_id);
570
571        foreach($arrRet as $key => $array) {
572            foreach($arrParentID as $val) {
573                if($array['category_id'] == $val) {
574                    $arrRet[$key]['display'] = 1;
575                    break;
576                }
577            }
578        }
579
580        return $arrRet;
581    }
582
583    /**
584     * カテゴリツリーの取得を複数カテゴリーで行う.
585     *
586     * @param integer $product_id 商品ID
587     * @param bool $count_check 登録商品数のチェックを行う場合 true
588     * @return array カテゴリツリーの配列
589     */
590    function sfGetMultiCatTree($product_id, $count_check = false) {
591        $objQuery =& SC_Query::getSingletonInstance();
592        $col = "";
593        $col .= " cat.category_id,";
594        $col .= " cat.category_name,";
595        $col .= " cat.parent_category_id,";
596        $col .= " cat.level,";
597        $col .= " cat.rank,";
598        $col .= " cat.creator_id,";
599        $col .= " cat.create_date,";
600        $col .= " cat.update_date,";
601        $col .= " cat.del_flg, ";
602        $col .= " ttl.product_count";
603        $from = "dtb_category as cat left join dtb_category_total_count as ttl on ttl.category_id = cat.category_id";
604        // 登録商品数のチェック
605        if($count_check) {
606            $where = "del_flg = 0 AND product_count > 0";
607        } else {
608            $where = "del_flg = 0";
609        }
610        $objQuery->setOption("ORDER BY rank DESC");
611        $arrRet = $objQuery->select($col, $from, $where);
612
613        $arrCategory_id = $this->sfGetCategoryId($product_id);
614
615        $arrCatTree = array();
616        foreach ($arrCategory_id as $pkey => $parent_category_id) {
617            $arrParentID = $this->sfGetParents($objQuery, 'dtb_category', 'parent_category_id', 'category_id', $parent_category_id);
618
619            foreach($arrParentID as $pid) {
620                foreach($arrRet as $key => $array) {
621                    if($array['category_id'] == $pid) {
622                        $arrCatTree[$pkey][] = $arrRet[$key];
623                        break;
624                    }
625                }
626            }
627        }
628
629        return $arrCatTree;
630    }
631
632    /**
633     * 親カテゴリーを連結した文字列を取得する.
634     *
635     * @param integer $category_id カテゴリID
636     * @return string 親カテゴリーを連結した文字列
637     */
638    function sfGetCatCombName($category_id){
639        // 商品が属するカテゴリIDを縦に取得
640        $objQuery =& SC_Query::getSingletonInstance();
641        $arrCatID = $this->sfGetParents($objQuery, "dtb_category", "parent_category_id", "category_id", $category_id);
642        $ConbName = "";
643
644        // カテゴリー名称を取得する
645        foreach($arrCatID as $key => $val){
646            $sql = "SELECT category_name FROM dtb_category WHERE category_id = ?";
647            $arrVal = array($val);
648            $CatName = $objQuery->getOne($sql,$arrVal);
649            $ConbName .= $CatName . ' | ';
650        }
651        // 最後の | をカットする
652        $ConbName = substr_replace($ConbName, "", strlen($ConbName) - 2, 2);
653
654        return $ConbName;
655    }
656
657    /**
658     * 指定したカテゴリーIDのカテゴリーを取得する.
659     *
660     * @param integer $category_id カテゴリID
661     * @return array 指定したカテゴリーIDのカテゴリー
662     */
663    function sfGetCat($category_id){
664        $objQuery =& SC_Query::getSingletonInstance();
665
666        // カテゴリーを取得する
667        $arrVal = array($category_id);
668        $res = $objQuery->select('category_id AS id, category_name AS name', 'dtb_category', 'category_id = ?', $arrVal);
669
670        return $res[0];
671    }
672
673    /**
674     * 指定したカテゴリーIDの大カテゴリーを取得する.
675     *
676     * @param integer $category_id カテゴリID
677     * @return array 指定したカテゴリーIDの大カテゴリー
678     */
679    function sfGetFirstCat($category_id){
680        // 商品が属するカテゴリIDを縦に取得
681        $objQuery =& SC_Query::getSingletonInstance();
682        $arrRet = array();
683        $arrCatID = $this->sfGetParents($objQuery, "dtb_category", "parent_category_id", "category_id", $category_id);
684        $arrRet['id'] = $arrCatID[0];
685
686        // カテゴリー名称を取得する
687        $sql = "SELECT category_name FROM dtb_category WHERE category_id = ?";
688        $arrVal = array($arrRet['id']);
689        $arrRet['name'] = $objQuery->getOne($sql,$arrVal);
690
691        return $arrRet;
692    }
693
694    /**
695     * カテゴリツリーの取得を行う.
696     *
697     * $products_check:true商品登録済みのものだけ取得する
698     *
699     * @param string $addwhere 追加する WHERE 句
700     * @param bool $products_check 商品の存在するカテゴリのみ取得する場合 true
701     * @param string $head カテゴリ名のプレフィックス文字列
702     * @return array カテゴリツリーの配列
703     */
704    function sfGetCategoryList($addwhere = "", $products_check = false, $head = CATEGORY_HEAD) {
705        $objQuery =& SC_Query::getSingletonInstance();
706        $where = "del_flg = 0";
707
708        if($addwhere != "") {
709            $where.= " AND $addwhere";
710        }
711
712        $objQuery->setOption("ORDER BY rank DESC");
713
714        if($products_check) {
715            $col = "T1.category_id, category_name, level";
716            $from = "dtb_category AS T1 LEFT JOIN dtb_category_total_count AS T2 ON T1.category_id = T2.category_id";
717            $where .= " AND product_count > 0";
718        } else {
719            $col = "category_id, category_name, level";
720            $from = "dtb_category";
721        }
722
723        $arrRet = $objQuery->select($col, $from, $where);
724
725        $max = count($arrRet);
726        for($cnt = 0; $cnt < $max; $cnt++) {
727            $id = $arrRet[$cnt]['category_id'];
728            $name = $arrRet[$cnt]['category_name'];
729            $arrList[$id] = str_repeat($head, $arrRet[$cnt]['level']) . $name;
730        }
731        return $arrList;
732    }
733
734    /**
735     * カテゴリーツリーの取得を行う.
736     *
737     * 親カテゴリの Value=0 を対象とする
738     *
739     * @param bool $parent_zero 親カテゴリの Value=0 の場合 true
740     * @return array カテゴリツリーの配列
741     */
742    function sfGetLevelCatList($parent_zero = true) {
743        $objQuery =& SC_Query::getSingletonInstance();
744
745        // カテゴリ名リストを取得
746        $col = "category_id, parent_category_id, category_name";
747        $where = "del_flg = 0";
748        $objQuery->setOption("ORDER BY level");
749        $arrRet = $objQuery->select($col, "dtb_category", $where);
750        $arrCatName = array();
751        foreach ($arrRet as $arrTmp) {
752            $arrCatName[$arrTmp['category_id']] =
753                (($arrTmp['parent_category_id'] > 0)?
754                    $arrCatName[$arrTmp['parent_category_id']] : "")
755                . CATEGORY_HEAD . $arrTmp['category_name'];
756        }
757
758        $col = "category_id, parent_category_id, category_name, level";
759        $where = "del_flg = 0";
760        $objQuery->setOption("ORDER BY rank DESC");
761        $arrRet = $objQuery->select($col, "dtb_category", $where);
762        $max = count($arrRet);
763
764        for($cnt = 0; $cnt < $max; $cnt++) {
765            if($parent_zero) {
766                if($arrRet[$cnt]['level'] == LEVEL_MAX) {
767                    $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
768                } else {
769                    $arrValue[$cnt] = "";
770                }
771            } else {
772                $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
773            }
774
775            $arrOutput[$cnt] = $arrCatName[$arrRet[$cnt]['category_id']];
776        }
777
778        return array($arrValue, $arrOutput);
779    }
780
781    /**
782     * 選択中の商品のカテゴリを取得する.
783     *
784     * @param integer $product_id プロダクトID
785     * @param integer $category_id カテゴリID
786     * @return array 選択中の商品のカテゴリIDの配列
787     *
788     */
789    function sfGetCategoryId($product_id, $category_id = 0, $closed = false) {
790        if ($closed) {
791            $status = "";
792        } else {
793            $status = "status = 1";
794        }
795
796        if(!$this->g_category_on) {
797            $this->g_category_on = true;
798            $category_id = (int) $category_id;
799            $product_id = (int) $product_id;
800            if (SC_Utils_Ex::sfIsInt($category_id) && $category_id != 0 && $this->sfIsRecord("dtb_category","category_id", $category_id)) {
801                $this->g_category_id = array($category_id);
802            } else if (SC_Utils_Ex::sfIsInt($product_id) && $product_id != 0 && $this->sfIsRecord("dtb_products","product_id", $product_id, $status)) {
803                $objQuery =& SC_Query::getSingletonInstance();
804                $where = "product_id = ?";
805                $category_id = $objQuery->getCol("category_id", "dtb_product_categories", "product_id = ?", array($product_id));
806                $this->g_category_id = $category_id;
807            } else {
808                // 不正な場合は、空の配列を返す。
809                $this->g_category_id = array();
810            }
811        }
812        return $this->g_category_id;
813    }
814
815    /**
816     * 商品をカテゴリの先頭に追加する.
817     *
818     * @param integer $category_id カテゴリID
819     * @param integer $product_id プロダクトID
820     * @return void
821     */
822    function addProductBeforCategories($category_id, $product_id) {
823
824        $sqlval = array("category_id" => $category_id,
825                        "product_id" => $product_id);
826
827        $objQuery =& SC_Query::getSingletonInstance();
828
829        // 現在の商品カテゴリを取得
830        $arrCat = $objQuery->select("product_id, category_id, rank",
831                                    "dtb_product_categories",
832                                    "category_id = ?",
833                                    array($category_id));
834
835        $max = "0";
836        foreach ($arrCat as $val) {
837            // 同一商品が存在する場合は登録しない
838            if ($val["product_id"] == $product_id) {
839                return;
840            }
841            // 最上位ランクを取得
842            $max = ($max < $val["rank"]) ? $val["rank"] : $max;
843        }
844        $sqlval["rank"] = $max + 1;
845        $objQuery->insert("dtb_product_categories", $sqlval);
846    }
847
848    /**
849     * 商品をカテゴリの末尾に追加する.
850     *
851     * @param integer $category_id カテゴリID
852     * @param integer $product_id プロダクトID
853     * @return void
854     */
855    function addProductAfterCategories($category_id, $product_id) {
856        $sqlval = array("category_id" => $category_id,
857                        "product_id" => $product_id);
858
859        $objQuery =& SC_Query::getSingletonInstance();
860
861        // 現在の商品カテゴリを取得
862        $arrCat = $objQuery->select("product_id, category_id, rank",
863                                    "dtb_product_categories",
864                                    "category_id = ?",
865                                    array($category_id));
866
867        $min = 0;
868        foreach ($arrCat as $val) {
869            // 同一商品が存在する場合は登録しない
870            if ($val["product_id"] == $product_id) {
871                return;
872            }
873            // 最下位ランクを取得
874            $min = ($min < $val["rank"]) ? $val["rank"] : $min;
875        }
876        $sqlval["rank"] = $min;
877        $objQuery->insert("dtb_product_categories", $sqlval);
878    }
879
880    /**
881     * 商品をカテゴリから削除する.
882     *
883     * @param integer $category_id カテゴリID
884     * @param integer $product_id プロダクトID
885     * @return void
886     */
887    function removeProductByCategories($category_id, $product_id) {
888        $objQuery =& SC_Query::getSingletonInstance();
889        $objQuery->delete("dtb_product_categories",
890                          "category_id = ? AND product_id = ?", array($category_id, $product_id));
891    }
892
893    /**
894     * 商品カテゴリを更新する.
895     *
896     * @param array $arrCategory_id 登録するカテゴリIDの配列
897     * @param integer $product_id プロダクトID
898     * @return void
899     */
900    function updateProductCategories($arrCategory_id, $product_id) {
901        $objQuery =& SC_Query::getSingletonInstance();
902
903        // 現在のカテゴリ情報を取得
904        $arrCurrentCat = $objQuery->select("product_id, category_id, rank",
905                                           "dtb_product_categories",
906                                           "product_id = ?",
907                                           array($product_id));
908
909        // 登録するカテゴリ情報と比較
910        foreach ($arrCurrentCat as $val) {
911
912            // 登録しないカテゴリを削除
913            if (!in_array($val["category_id"], $arrCategory_id)) {
914                $this->removeProductByCategories($val["category_id"], $product_id);
915            }
916        }
917
918        // カテゴリを登録
919        foreach ($arrCategory_id as $category_id) {
920            $this->addProductBeforCategories($category_id, $product_id);
921        }
922    }
923
924    /**
925     * カテゴリ数の登録を行う.
926     *
927     *
928     * @param SC_Query $objQuery SC_Query インスタンス
929     * @param boolean $is_force_all_count 全カテゴリの集計を強制する場合 true
930     * @return void
931     */
932    function sfCategory_Count($objQuery = NULL, $is_force_all_count = false){
933        $objProduct = new SC_Product();
934       
935        if($objQuery == NULL) {
936            $objQuery =& SC_Query::getSingletonInstance();
937        }
938       
939        $is_out_trans = false;
940        if(!$objQuery->inTransaction()){
941            $objQuery->begin();
942            $is_out_trans = true;
943        }
944       
945        //共通のfrom/where文の構築
946        $sql_where = 'alldtl.del_flg = 0 AND alldtl.status = 1';
947        // 在庫無し商品の非表示
948        if (NOSTOCK_HIDDEN === true) {
949            $sql_where_dtl = 'stock_max >= 1 OR stock_unlimited_max = 1';
950            $from = $objProduct->alldtlSQL($sql_where_dtl);
951        }else{
952            $from = " dtb_products as alldtl ";
953        }
954       
955        //dtb_category_countの構成
956        // 各カテゴリに所属する商品の数を集計。集計対象には子カテゴリを含まない。
957        // 2.5で消える予定だったが復活させます。DELETE処理は無くしました。
958       
959        //まずテーブル内容の元を取得
960        if(!$is_force_all_count) {
961            $arrCategoryCountOld = $objQuery->select('category_id,product_count','dtb_category_count');
962        }else{
963            $arrCategoryCountOld = array();
964        }
965
966        //各カテゴリ内の商品数を数えて取得
967        $sql = <<< __EOS__
968            SELECT T1.category_id, count(T2.category_id) as product_count
969            FROM dtb_category AS T1
970                LEFT JOIN dtb_product_categories AS T2
971                    ON T1.category_id = T2.category_id
972                LEFT JOIN $from
973                    ON T2.product_id = alldtl.product_id
974            WHERE $sql_where
975            GROUP BY T1.category_id, T2.category_id
976__EOS__;
977
978        $arrCategoryCountNew = $objQuery->getAll($sql);
979        // 各カテゴリに所属する商品の数を集計。集計対象には子カテゴリを「含む」。       
980        //差分を取得して、更新対象カテゴリだけを確認する。
981
982        //各カテゴリ毎のデータ値において以前との差を見る       
983        //古いデータの構造入れ替え
984        $arrOld = array();
985        foreach($arrCategoryCountOld as $item){
986            $arrOld[$item['category_id']] = $item['product_count'];
987        }
988        //新しいデータの構造入れ替え
989        $arrNew = array();
990        foreach($arrCategoryCountNew as $item){
991            $arrNew[$item['category_id']] = $item['product_count'];
992        }
993
994        $arrDiffCategory_id = array();
995        //新しいカテゴリ一覧から見て商品数が異なるデータが無いか確認
996        foreach($arrNew as $cid => $count){
997            if($arrOld[$cid] != $count){
998                $arrDiffCategory_id[] = $cid;
999            }
1000        }
1001        //削除カテゴリを想定して、古いカテゴリ一覧から見て商品数が異なるデータが無いか確認。
1002        foreach($arrOld as $cid => $count){
1003            if($arrNew[$cid] != $count){
1004                $arrDiffCategory_id[] = $cid;
1005            }
1006        }
1007       
1008        //対象IDが無ければ終了
1009        if(count($arrDiffCategory_id) == 0){
1010            if($is_out_trans) {
1011                $objQuery->commit();
1012            }
1013            return;
1014        }
1015
1016        //差分対象カテゴリIDの重複を除去
1017        $arrDiffCategory_id = array_unique($arrDiffCategory_id);
1018       
1019        //dtb_category_countの更新 差分のあったカテゴリだけ更新する。
1020        foreach($arrDiffCategory_id as $cid) {
1021            $sqlval = array();
1022            $sqlval['create_date'] = 'Now()';
1023            $sqlval['product_count'] = (string)$arrNew[$cid];
1024            if($sqlval['product_count'] =="") {
1025                $sqlval['product_count'] = (string)'0';
1026            }
1027            if(isset($arrOld[$cid])) {
1028                $objQuery->update('dtb_category_count', $sqlval, 'category_id = ?', array($cid));
1029            }else{
1030                $sqlval['category_id'] = $cid;
1031                $objQuery->insert('dtb_category_count', $sqlval);
1032            }
1033        }
1034       
1035        //差分があったIDとその親カテゴリIDのリストを取得する
1036        $arrTgtCategory_id = array();
1037        foreach ($arrDiffCategory_id as $parent_category_id) {
1038            $arrTgtCategory_id[] = $parent_category_id;
1039            $arrParentID = $this->sfGetParents($objQuery, 'dtb_category', 'parent_category_id', 'category_id', $parent_category_id);
1040            foreach($arrParentID as $pid) {
1041                $arrTgtCategory_id[] = $pid;
1042            }
1043        }
1044       
1045        //重複を取り除く
1046        $arrTgtCategory_id = array_unique($arrTgtCategory_id);
1047
1048        //dtb_category_total_count 集計処理開始
1049        //更新対象カテゴリIDだけ集計しなおす。
1050        $arrUpdateData = array();
1051        foreach ($arrTgtCategory_id as $category_id) {
1052            $arrval = array();
1053            $arrval[] = $category_id;
1054            list($tmp_where, $tmp_arrval) = $this->sfGetCatWhere($category_id);
1055            if ($tmp_where != "") {
1056                $sql_where_product_ids = "product_id IN (SELECT product_id FROM dtb_product_categories WHERE " . $tmp_where . ")";
1057                $arrval = array_merge((array)$arrval, (array)$tmp_arrval, (array)$tmp_arrval);
1058            } else {
1059                $sql_where_product_ids = '0<>0'; // 一致させない
1060            }
1061            $where = "($sql_where) AND ($sql_where_product_ids)";
1062
1063            $from = $objProduct->alldtlSQL($sql_where_product_ids);
1064            $sql = "SELECT count(*) FROM $from WHERE $where ";
1065            $arrUpdateData[ $category_id ] = $objQuery->getOne($sql, $arrval);
1066        }
1067        // 更新対象だけを更新。
1068        foreach($arrUpdateData as $cid => $count) {
1069            $sqlval = array();
1070            $sqlval['create_date'] = 'Now()';
1071            $sqlval['product_count'] = $count;
1072            if($sqlval['product_count'] =="") {
1073                $sqlval['product_count'] = (string)'0';
1074            }
1075            $ret = $objQuery->update('dtb_category_total_count', $sqlval, 'category_id = ?', array($cid));
1076            if(!$ret) {
1077                $sqlval['category_id'] = $cid;
1078                $ret = $objQuery->insert('dtb_category_total_count', $sqlval);
1079            }
1080        }
1081        // トランザクション音終了処理
1082        if($is_out_trans) {
1083            $objQuery->commit();
1084        }
1085    }
1086
1087    /**
1088     * 子IDの配列を返す.
1089     *
1090     * @param string $table テーブル名
1091     * @param string $pid_name 親ID名
1092     * @param string $id_name ID名
1093     * @param integer $id ID
1094     * @param array 子ID の配列
1095     */
1096    function sfGetChildsID($table, $pid_name, $id_name, $id) {
1097        $arrRet = $this->sfGetChildrenArray($table, $pid_name, $id_name, $id);
1098        return $arrRet;
1099    }
1100
1101    /**
1102     * 階層構造のテーブルから子ID配列を取得する.
1103     *
1104     * @param string $table テーブル名
1105     * @param string $pid_name 親ID名
1106     * @param string $id_name ID名
1107     * @param integer $id ID番号
1108     * @return array 子IDの配列
1109     */
1110    function sfGetChildrenArray($table, $pid_name, $id_name, $id) {
1111        $objQuery =& SC_Query::getSingletonInstance();
1112        $col = $pid_name . "," . $id_name;
1113        $arrData = $objQuery->select($col, $table);
1114
1115        $arrPID = array();
1116        $arrPID[] = $id;
1117        $arrChildren = array();
1118        $arrChildren[] = $id;
1119
1120        $arrRet = $this->sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrPID);
1121
1122        while(count($arrRet) > 0) {
1123            $arrChildren = array_merge($arrChildren, $arrRet);
1124            $arrRet = $this->sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrRet);
1125        }
1126
1127        return $arrChildren;
1128    }
1129
1130    /**
1131     * 親ID直下の子IDをすべて取得する.
1132     *
1133     * @param array $arrData 親カテゴリの配列
1134     * @param string $pid_name 親ID名
1135     * @param string $id_name ID名
1136     * @param array $arrPID 親IDの配列
1137     * @return array 子IDの配列
1138     */
1139    function sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrPID) {
1140        $arrChildren = array();
1141        $max = count($arrData);
1142
1143        for($i = 0; $i < $max; $i++) {
1144            foreach($arrPID as $val) {
1145                if($arrData[$i][$pid_name] == $val) {
1146                    $arrChildren[] = $arrData[$i][$id_name];
1147                }
1148            }
1149        }
1150        return $arrChildren;
1151    }
1152
1153    /**
1154     * 所属するすべての階層の親IDを配列で返す.
1155     *
1156     * @param SC_Query $objQuery SC_Query インスタンス
1157     * @param string $table テーブル名
1158     * @param string $pid_name 親ID名
1159     * @param string $id_name ID名
1160     * @param integer $id ID
1161     * @return array 親IDの配列
1162     */
1163    function sfGetParents($objQuery, $table, $pid_name, $id_name, $id) {
1164        $arrRet = $this->sfGetParentsArray($table, $pid_name, $id_name, $id);
1165        // 配列の先頭1つを削除する。
1166        array_shift($arrRet);
1167        return $arrRet;
1168    }
1169
1170    /**
1171     * 階層構造のテーブルから親ID配列を取得する.
1172     *
1173     * @param string $table テーブル名
1174     * @param string $pid_name 親ID名
1175     * @param string $id_name ID名
1176     * @param integer $id ID
1177     * @return array 親IDの配列
1178     */
1179    function sfGetParentsArray($table, $pid_name, $id_name, $id) {
1180        $objQuery =& SC_Query::getSingletonInstance();
1181        $col = $pid_name . "," . $id_name;
1182        $arrData = $objQuery->select($col, $table);
1183
1184        $arrParents = array();
1185        $arrParents[] = $id;
1186        $child = $id;
1187
1188        $ret = SC_Utils::sfGetParentsArraySub($arrData, $pid_name, $id_name, $child);
1189
1190        while($ret != "") {
1191            $arrParents[] = $ret;
1192            $ret = SC_Utils::sfGetParentsArraySub($arrData, $pid_name, $id_name, $ret);
1193        }
1194
1195        $arrParents = array_reverse($arrParents);
1196
1197        return $arrParents;
1198    }
1199
1200    /**
1201     * カテゴリから商品を検索する場合のWHERE文と値を返す.
1202     *
1203     * @param integer $category_id カテゴリID
1204     * @return array 商品を検索する場合の配列
1205     */
1206    function sfGetCatWhere($category_id) {
1207        // 子カテゴリIDの取得
1208        $arrRet = $this->sfGetChildsID("dtb_category", "parent_category_id", "category_id", $category_id);
1209        $tmp_where = "";
1210        foreach ($arrRet as $val) {
1211            if($tmp_where == "") {
1212                $tmp_where.= "category_id IN ( ?";
1213            } else {
1214                $tmp_where.= ",? ";
1215            }
1216            $arrval[] = $val;
1217        }
1218        $tmp_where.= " ) ";
1219        return array($tmp_where, $arrval);
1220    }
1221
1222    /**
1223     * 受注一時テーブルから情報を取得する.
1224     *
1225     * @param integer $order_temp_id 受注一時ID
1226     * @return array 受注一時情報の配列
1227     * @deprecated SC_Helper_Purchase::getOrderTemp() を使用して下さい
1228     */
1229    function sfGetOrderTemp($order_temp_id) {
1230        $objQuery =& SC_Query::getSingletonInstance();
1231        $where = "order_temp_id = ?";
1232        $arrRet = $objQuery->select("*", "dtb_order_temp", $where, array($order_temp_id));
1233        return $arrRet[0];
1234    }
1235
1236    /**
1237     * SELECTボックス用リストを作成する.
1238     *
1239     * @param string $table テーブル名
1240     * @param string $keyname プライマリーキーのカラム名
1241     * @param string $valname データ内容のカラム名
1242     * @param string $where WHERE句
1243     * @param array $arrval プレースホルダ
1244     * @return array SELECT ボックス用リストの配列
1245     */
1246    function sfGetIDValueList($table, $keyname, $valname, $where = '', $arrVal = array()) {
1247        $objQuery =& SC_Query::getSingletonInstance();
1248        $col = "$keyname, $valname";
1249        $objQuery->setWhere("del_flg = 0");
1250        $objQuery->setOrder("rank DESC");
1251        $arrList = $objQuery->select($col, $table, $where, $arrVal);
1252        $count = count($arrList);
1253        for($cnt = 0; $cnt < $count; $cnt++) {
1254            $key = $arrList[$cnt][$keyname];
1255            $val = $arrList[$cnt][$valname];
1256            $arrRet[$key] = $val;
1257        }
1258        return $arrRet;
1259    }
1260
1261    /**
1262     * ランキングを上げる.
1263     *
1264     * @param string $table テーブル名
1265     * @param string $colname カラム名
1266     * @param string|integer $id テーブルのキー
1267     * @param string $andwhere SQL の AND 条件である WHERE 句
1268     * @return void
1269     */
1270    function sfRankUp($table, $colname, $id, $andwhere = "") {
1271        $objQuery =& SC_Query::getSingletonInstance();
1272        $objQuery->begin();
1273        $where = "$colname = ?";
1274        if($andwhere != "") {
1275            $where.= " AND $andwhere";
1276        }
1277        // 対象項目のランクを取得
1278        $rank = $objQuery->get("rank", $table, $where, array($id));
1279        // ランクの最大値を取得
1280        $maxrank = $objQuery->max("rank", $table, $andwhere);
1281        // ランクが最大値よりも小さい場合に実行する。
1282        if($rank < $maxrank) {
1283            // ランクが一つ上のIDを取得する。
1284            $where = "rank = ?";
1285            if($andwhere != "") {
1286                $where.= " AND $andwhere";
1287            }
1288            $uprank = $rank + 1;
1289            $up_id = $objQuery->get($colname, $table, $where, array($uprank));
1290            // ランク入れ替えの実行
1291            $sqlup = "UPDATE $table SET rank = ? WHERE $colname = ?";
1292            if($andwhere != "") {
1293                $sqlup.= " AND $andwhere";
1294            }
1295            $objQuery->exec($sqlup, array($rank + 1, $id));
1296            $objQuery->exec($sqlup, array($rank, $up_id));
1297        }
1298        $objQuery->commit();
1299    }
1300
1301    /**
1302     * ランキングを下げる.
1303     *
1304     * @param string $table テーブル名
1305     * @param string $colname カラム名
1306     * @param string|integer $id テーブルのキー
1307     * @param string $andwhere SQL の AND 条件である WHERE 句
1308     * @return void
1309     */
1310    function sfRankDown($table, $colname, $id, $andwhere = "") {
1311        $objQuery =& SC_Query::getSingletonInstance();
1312        $objQuery->begin();
1313        $where = "$colname = ?";
1314        if($andwhere != "") {
1315            $where.= " AND $andwhere";
1316        }
1317        // 対象項目のランクを取得
1318        $rank = $objQuery->get("rank", $table, $where, array($id));
1319
1320        // ランクが1(最小値)よりも大きい場合に実行する。
1321        if($rank > 1) {
1322            // ランクが一つ下のIDを取得する。
1323            $where = "rank = ?";
1324            if($andwhere != "") {
1325                $where.= " AND $andwhere";
1326            }
1327            $downrank = $rank - 1;
1328            $down_id = $objQuery->get($colname, $table, $where, array($downrank));
1329            // ランク入れ替えの実行
1330            $sqlup = "UPDATE $table SET rank = ? WHERE $colname = ?";
1331            if($andwhere != "") {
1332                $sqlup.= " AND $andwhere";
1333            }
1334            $objQuery->exec($sqlup, array($rank - 1, $id));
1335            $objQuery->exec($sqlup, array($rank, $down_id));
1336        }
1337        $objQuery->commit();
1338    }
1339
1340    /**
1341     * 指定順位へ移動する.
1342     *
1343     * @param string $tableName テーブル名
1344     * @param string $keyIdColumn キーを保持するカラム名
1345     * @param string|integer $keyId キーの値
1346     * @param integer $pos 指定順位
1347     * @param string $where SQL の AND 条件である WHERE 句
1348     * @return void
1349     */
1350    function sfMoveRank($tableName, $keyIdColumn, $keyId, $pos, $where = "") {
1351        $objQuery =& SC_Query::getSingletonInstance();
1352        $objQuery->begin();
1353
1354        // 自身のランクを取得する
1355        if($where != "") {
1356            $getWhere = "$keyIdColumn = ? AND " . $where;
1357        } else {
1358            $getWhere = "$keyIdColumn = ?";
1359        }
1360        $rank = $objQuery->get("rank", $tableName, $getWhere, array($keyId));
1361
1362        $max = $objQuery->max("rank", $tableName, $where);
1363
1364        // 値の調整(逆順)
1365        if($pos > $max) {
1366            $position = 1;
1367        } else if($pos < 1) {
1368            $position = $max;
1369        } else {
1370            $position = $max - $pos + 1;
1371        }
1372
1373        //入れ替え先の順位が入れ換え元の順位より大きい場合
1374        if( $position > $rank ) $term = "rank - 1";
1375
1376        //入れ替え先の順位が入れ換え元の順位より小さい場合
1377        if( $position < $rank ) $term = "rank + 1";
1378
1379        // XXX 入れ替え先の順位が入れ替え元の順位と同じ場合
1380        if (!isset($term)) $term = "rank";
1381
1382        // 指定した順位の商品から移動させる商品までのrankを1つずらす
1383        $sql = "UPDATE $tableName SET rank = $term WHERE rank BETWEEN ? AND ?";
1384        if($where != "") {
1385            $sql.= " AND $where";
1386        }
1387
1388        if( $position > $rank ) $objQuery->exec( $sql, array( $rank + 1, $position ));
1389        if( $position < $rank ) $objQuery->exec( $sql, array( $position, $rank - 1 ));
1390
1391        // 指定した順位へrankを書き換える。
1392        $sql  = "UPDATE $tableName SET rank = ? WHERE $keyIdColumn = ? ";
1393        if($where != "") {
1394            $sql.= " AND $where";
1395        }
1396
1397        $objQuery->exec( $sql, array( $position, $keyId ) );
1398        $objQuery->commit();
1399    }
1400
1401    /**
1402     * ランクを含むレコードを削除する.
1403     *
1404     * レコードごと削除する場合は、$deleteをtrueにする
1405     *
1406     * @param string $table テーブル名
1407     * @param string $colname カラム名
1408     * @param string|integer $id テーブルのキー
1409     * @param string $andwhere SQL の AND 条件である WHERE 句
1410     * @param bool $delete レコードごと削除する場合 true,
1411     *                     レコードごと削除しない場合 false
1412     * @return void
1413     */
1414    function sfDeleteRankRecord($table, $colname, $id, $andwhere = "",
1415                                $delete = false) {
1416        $objQuery =& SC_Query::getSingletonInstance();
1417        $objQuery->begin();
1418        // 削除レコードのランクを取得する。
1419        $where = "$colname = ?";
1420        if($andwhere != "") {
1421            $where.= " AND $andwhere";
1422        }
1423        $rank = $objQuery->get("rank", $table, $where, array($id));
1424
1425        if(!$delete) {
1426            // ランクを最下位にする、DELフラグON
1427            $sqlup = "UPDATE $table SET rank = 0, del_flg = 1 ";
1428            $sqlup.= "WHERE $colname = ?";
1429            // UPDATEの実行
1430            $objQuery->exec($sqlup, array($id));
1431        } else {
1432            $objQuery->delete($table, "$colname = ?", array($id));
1433        }
1434
1435        // 追加レコードのランクより上のレコードを一つずらす。
1436        $where = "rank > ?";
1437        if($andwhere != "") {
1438            $where.= " AND $andwhere";
1439        }
1440        $sqlup = "UPDATE $table SET rank = (rank - 1) WHERE $where";
1441        $objQuery->exec($sqlup, array($rank));
1442        $objQuery->commit();
1443    }
1444
1445    /**
1446     * 親IDの配列を元に特定のカラムを取得する.
1447     *
1448     * @param SC_Query $objQuery SC_Query インスタンス
1449     * @param string $table テーブル名
1450     * @param string $id_name ID名
1451     * @param string $col_name カラム名
1452     * @param array $arrId IDの配列
1453     * @return array 特定のカラムの配列
1454     */
1455    function sfGetParentsCol($objQuery, $table, $id_name, $col_name, $arrId ) {
1456        $col = $col_name;
1457        $len = count($arrId);
1458        $where = "";
1459
1460        for($cnt = 0; $cnt < $len; $cnt++) {
1461            if($where == "") {
1462                $where = "$id_name = ?";
1463            } else {
1464                $where.= " OR $id_name = ?";
1465            }
1466        }
1467
1468        $objQuery->setOrder("level");
1469        $arrRet = $objQuery->select($col, $table, $where, $arrId);
1470        return $arrRet;
1471    }
1472
1473    /**
1474     * カテゴリ変更時の移動処理を行う.
1475     *
1476     * @param SC_Query $objQuery SC_Query インスタンス
1477     * @param string $table テーブル名
1478     * @param string $id_name ID名
1479     * @param string $cat_name カテゴリ名
1480     * @param integer $old_catid 旧カテゴリID
1481     * @param integer $new_catid 新カテゴリID
1482     * @param integer $id ID
1483     * @return void
1484     */
1485    function sfMoveCatRank($objQuery, $table, $id_name, $cat_name, $old_catid, $new_catid, $id) {
1486        if ($old_catid == $new_catid) {
1487            return;
1488        }
1489        // 旧カテゴリでのランク削除処理
1490        // 移動レコードのランクを取得する。
1491        $where = "$id_name = ?";
1492        $rank = $objQuery->get("rank", $table, $where, array($id));
1493        // 削除レコードのランクより上のレコードを一つ下にずらす。
1494        $where = "rank > ? AND $cat_name = ?";
1495        $sqlup = "UPDATE $table SET rank = (rank - 1) WHERE $where";
1496        $objQuery->exec($sqlup, array($rank, $old_catid));
1497        // 新カテゴリでの登録処理
1498        // 新カテゴリの最大ランクを取得する。
1499        $max_rank = $objQuery->max("rank", $table, "$cat_name = ?", array($new_catid)) + 1;
1500        $where = "$id_name = ?";
1501        $sqlup = "UPDATE $table SET rank = ? WHERE $where";
1502        $objQuery->exec($sqlup, array($max_rank, $id));
1503    }
1504
1505    /**
1506     * FIXME 商品種別からお届け時間を取得する.
1507     *
1508     * @param integer $productTypeId 商品種別ID
1509     * @return array お届け時間の配列
1510     * @deprecated SC_Purchase::getDelivTime() を使用して下さい
1511     */
1512    function sfGetDelivTime($productTypeId) {
1513        $objQuery =& SC_Query::getSingletonInstance();
1514
1515        $deliv_id = "";
1516        $arrRet = array();
1517
1518        if($payment_id != "") {
1519            $where = "del_flg = 0 AND product_type_id = ?";
1520            $arrRet = $objQuery->select("deliv_id", "dtb_payment", $where, array($productTypeId));
1521            $deliv_id = $arrRet[0]['deliv_id'];
1522        }
1523
1524        if($deliv_id != "") {
1525            $objQuery->setOrder("time_id");
1526            $where = "deliv_id = ?";
1527            $arrRet= $objQuery->select("time_id, deliv_time", "dtb_delivtime", $where, array($deliv_id));
1528        }
1529
1530        return $arrRet;
1531    }
1532
1533    /**
1534     * 都道府県、支払い方法から配送料金を取得する.
1535     *
1536     * @param array $arrData 各種情報
1537     * @return string 指定の都道府県, 支払い方法の配送料金
1538     */
1539    function sfGetDelivFee($pref_id, $product_type_id) {
1540        $objQuery =& SC_Query::getSingletonInstance();
1541
1542        // 配送業者から配送料を取得
1543        if($deliv_id != "") {
1544
1545            // 都道府県が指定されていない場合は、東京都の番号を指定しておく
1546            if($pref_id == "") {
1547                $pref_id = 13;
1548            }
1549
1550            $objQuery =& SC_Query::getSingletonInstance();
1551            $where = "product_type_id = ? AND pref = ?";
1552            $arrRet= $objQuery->select("fee", "dtb_delivfee", $where, array($product_type_id, $pref_id));
1553        }
1554        return $arrRet[0]['fee'];
1555    }
1556
1557    /**
1558     * 集計情報を元に最終計算を行う.
1559     *
1560     * @param array $arrData 各種情報
1561     * @param LC_Page $objPage LC_Page インスタンス
1562     * @param SC_CartSession $objCartSess SC_CartSession インスタンス
1563     * @param null $dummy1 互換性確保用(決済モジュール互換のため)
1564     * @param SC_Customer $objCustomer SC_Customer インスタンス
1565     * @return array 最終計算後の配列
1566     * @deprecated SC_CartSession::calculate() を使用して下さい
1567     */
1568    function sfTotalConfirm($arrData, &$objPage, &$objCartSess, $dummy1 = null, $objCustomer = "", $key = "") {
1569        // 店舗基本情報を取得する
1570        $arrInfo = SC_Helper_DB_Ex::sfGetBasisData();
1571
1572        // 未定義変数を定義
1573        if (!isset($arrData['deliv_pref'])) $arrData['deliv_pref'] = "";
1574        if (!isset($arrData['payment_id'])) $arrData['payment_id'] = "";
1575        if (!isset($arrData['charge'])) $arrData['charge'] = "";
1576        if (!isset($arrData['use_point'])) $arrData['use_point'] = "";
1577        if (!isset($arrData['add_point'])) $arrData['add_point'] = 0;
1578
1579        // 税金の取得
1580        $arrData['tax'] = $objPage->tpl_total_tax[$key];
1581        // 小計の取得
1582        $arrData['subtotal'] = $objPage->tpl_total_inctax[$key];
1583
1584        // 合計送料の取得
1585        $arrData['deliv_fee'] = 0;
1586
1587        // 商品ごとの送料が有効の場合
1588        if (OPTION_PRODUCT_DELIV_FEE == 1) {
1589            // 全商品の合計送料を加算する
1590            $this->lfAddAllProductsDelivFee($arrData, $objPage, $objCartSess);
1591        }
1592
1593        // 配送業者の送料が有効の場合
1594        if (OPTION_DELIV_FEE == 1) {
1595            // 都道府県、支払い方法から配送料金を加算する
1596            // FIXME ここでしか使ってない
1597            $this->lfAddDelivFee($arrData);
1598        }
1599
1600        // 送料無料の購入数が設定されている場合
1601        if (DELIV_FREE_AMOUNT > 0) {
1602            // 商品の合計数量
1603            $total_quantity = $objCartSess->getTotalQuantity(true);
1604
1605            if($total_quantity >= DELIV_FREE_AMOUNT) {
1606                $arrData['deliv_fee'] = 0;
1607            }
1608        }
1609
1610        // ダウンロード商品のみの場合は送料無料
1611        if($this->chkCartDown($objCartSess)==2){
1612            $arrData['deliv_fee'] = 0;
1613        }
1614
1615        // 送料無料条件が設定されている場合
1616        if($arrInfo['free_rule'] > 0) {
1617            // 小計が無料条件を超えている場合
1618            if($arrData['subtotal'] >= $arrInfo['free_rule']) {
1619                $arrData['deliv_fee'] = 0;
1620            }
1621        }
1622
1623        // 合計の計算
1624        $arrData['total'] = $objPage->tpl_total_inctax[$key]; // 商品合計
1625        $arrData['total']+= $arrData['deliv_fee'];      // 送料
1626        $arrData['total']+= $arrData['charge'];         // 手数料
1627        // お支払い合計
1628        $arrData['payment_total'] = $arrData['total'] - ($arrData['use_point'] * POINT_VALUE);
1629        // 加算ポイントの計算
1630        if (USE_POINT !== false) {
1631            $arrData['add_point'] = SC_Helper_DB_Ex::sfGetAddPoint($objPage->tpl_total_point[$key], $arrData['use_point']);
1632
1633            if($objCustomer != "") {
1634                // 誕生日月であった場合
1635                if($objCustomer->isBirthMonth()) {
1636                    $arrData['birth_point'] = BIRTH_MONTH_POINT;
1637                    $arrData['add_point'] += $arrData['birth_point'];
1638                }
1639            }
1640        }
1641
1642        if($arrData['add_point'] < 0) {
1643            $arrData['add_point'] = 0;
1644        }
1645        return $arrData;
1646    }
1647
1648    /**
1649     * レコードの存在チェックを行う.
1650     *
1651     * @param string $table テーブル名
1652     * @param string $col カラム名
1653     * @param array $arrval 要素の配列
1654     * @param array $addwhere SQL の AND 条件である WHERE 句
1655     * @return bool レコードが存在する場合 true
1656     */
1657    function sfIsRecord($table, $col, $arrval, $addwhere = "") {
1658        $objQuery =& SC_Query::getSingletonInstance();
1659        $arrCol = split("[, ]", $col);
1660
1661        $where = "del_flg = 0";
1662
1663        if($addwhere != "") {
1664            $where.= " AND $addwhere";
1665        }
1666
1667        foreach($arrCol as $val) {
1668            if($val != "") {
1669                if($where == "") {
1670                    $where = "$val = ?";
1671                } else {
1672                    $where.= " AND $val = ?";
1673                }
1674            }
1675        }
1676        $ret = $objQuery->get($col, $table, $where, $arrval);
1677
1678        if($ret != "") {
1679            return true;
1680        }
1681        return false;
1682    }
1683
1684    /**
1685     * メーカー商品数数の登録を行う.
1686     *
1687     * @param SC_Query $objQuery SC_Query インスタンス
1688     * @return void
1689     */
1690    function sfMaker_Count($objQuery){
1691        $sql = "";
1692
1693        //テーブル内容の削除
1694        $objQuery->query("DELETE FROM dtb_maker_count");
1695
1696        //各メーカーの商品数を数えて格納
1697        $sql = " INSERT INTO dtb_maker_count(maker_id, product_count, create_date) ";
1698        $sql .= " SELECT T1.maker_id, count(T2.maker_id), now() ";
1699        $sql .= " FROM dtb_maker AS T1 LEFT JOIN dtb_products AS T2";
1700        $sql .= " ON T1.maker_id = T2.maker_id ";
1701        $sql .= " WHERE T2.del_flg = 0 AND T2.status = 1 ";
1702        $sql .= " GROUP BY T1.maker_id, T2.maker_id ";
1703        $objQuery->query($sql);
1704    }
1705
1706    /**
1707     * 選択中の商品のメーカーを取得する.
1708     *
1709     * @param integer $product_id プロダクトID
1710     * @param integer $maker_id メーカーID
1711     * @return array 選択中の商品のメーカーIDの配列
1712     *
1713     */
1714    function sfGetMakerId($product_id, $maker_id = 0, $closed = false) {
1715        if ($closed) {
1716            $status = "";
1717        } else {
1718            $status = "status = 1";
1719        }
1720
1721        if (!$this->g_maker_on) {
1722            $this->g_maker_on = true;
1723            $maker_id = (int) $maker_id;
1724            $product_id = (int) $product_id;
1725            if (SC_Utils_Ex::sfIsInt($maker_id) && $maker_id != 0 && $this->sfIsRecord("dtb_maker","maker_id", $maker_id)) {
1726                $this->g_maker_id = array($maker_id);
1727            } else if (SC_Utils_Ex::sfIsInt($product_id) && $product_id != 0 && $this->sfIsRecord("dtb_products","product_id", $product_id, $status)) {
1728                $objQuery =& SC_Query::getSingletonInstance();
1729                $where = "product_id = ?";
1730                $maker_id = $objQuery->getCol("maker_id", "dtb_products", "product_id = ?", array($product_id));
1731                $this->g_maker_id = $maker_id;
1732            } else {
1733                // 不正な場合は、空の配列を返す。
1734                $this->g_maker_id = array();
1735            }
1736        }
1737        return $this->g_maker_id;
1738    }
1739
1740    /**
1741     * メーカーの取得を行う.
1742     *
1743     * $products_check:true商品登録済みのものだけ取得する
1744     *
1745     * @param string $addwhere 追加する WHERE 句
1746     * @param bool $products_check 商品の存在するカテゴリのみ取得する場合 true
1747     * @return array カテゴリツリーの配列
1748     */
1749    function sfGetMakerList($addwhere = "", $products_check = false) {
1750        $objQuery =& SC_Query::getSingletonInstance();
1751        $where = "del_flg = 0";
1752
1753        if($addwhere != "") {
1754            $where.= " AND $addwhere";
1755        }
1756
1757        $objQuery->setOption("ORDER BY rank DESC");
1758
1759        if($products_check) {
1760            $col = "T1.maker_id, name";
1761            $from = "dtb_maker AS T1 LEFT JOIN dtb_maker_count AS T2 ON T1.maker_id = T2.maker_id";
1762            $where .= " AND product_count > 0";
1763        } else {
1764            $col = "maker_id, name";
1765            $from = "dtb_maker";
1766        }
1767
1768        $arrRet = $objQuery->select($col, $from, $where);
1769
1770        $max = count($arrRet);
1771        for($cnt = 0; $cnt < $max; $cnt++) {
1772            $id = $arrRet[$cnt]['maker_id'];
1773            $name = $arrRet[$cnt]['name'];
1774            $arrList[$id] = $name;
1775        }
1776        return $arrList;
1777    }
1778
1779    /**
1780     * 全商品の合計送料を加算する
1781     */
1782    function lfAddAllProductsDelivFee(&$arrData, &$objPage, &$objCartSess) {
1783        $arrData['deliv_fee'] += $this->lfCalcAllProductsDelivFee($arrData, $objCartSess);
1784    }
1785
1786    /**
1787     * 全商品の合計送料を計算する
1788     */
1789    function lfCalcAllProductsDelivFee(&$arrData, &$objCartSess) {
1790        $objQuery =& SC_Query::getSingletonInstance();
1791        $deliv_fee_total = 0;
1792        $max = $objCartSess->getMax();
1793        for ($i = 0; $i <= $max; $i++) {
1794            // 商品送料
1795            $deliv_fee = $objQuery->getOne('SELECT deliv_fee FROM dtb_products WHERE product_id = ?', array($_SESSION[$objCartSess->key][$i]['id'][0]));
1796            // 数量
1797            $quantity = $_SESSION[$objCartSess->key][$i]['quantity'];
1798            // 累積
1799            $deliv_fee_total += $deliv_fee * $quantity;
1800        }
1801        return $deliv_fee_total;
1802    }
1803
1804    /**
1805     * 都道府県、支払い方法から配送料金を加算する.
1806     *
1807     * @param array $arrData 各種情報
1808     */
1809    function lfAddDelivFee(&$arrData) {
1810        $arrData['deliv_fee'] += $this->sfGetDelivFee($arrData);
1811    }
1812
1813    /**
1814     * 受注の名称列を更新する
1815     *
1816     * @param integer $order_id 更新対象の注文番号
1817     * @param boolean $temp_table 更新対象は「受注_Temp」か
1818     * @static
1819     */
1820    function sfUpdateOrderNameCol($order_id, $temp_table = false) {
1821        $objQuery =& SC_Query::getSingletonInstance();
1822
1823        if ($temp_table) {
1824            $tgt_table = 'dtb_order_temp';
1825            $sql_where = 'WHERE order_temp_id = ?';
1826        } else {
1827            $tgt_table = 'dtb_order';
1828            $sql_where = 'WHERE order_id = ?';
1829        }
1830
1831        $sql = <<< __EOS__
1832            UPDATE
1833                {$tgt_table}
1834            SET
1835                 payment_method = (SELECT payment_method FROM dtb_payment WHERE payment_id = {$tgt_table}.payment_id)
1836                ,deliv_time = (SELECT deliv_time FROM dtb_delivtime WHERE time_id = {$tgt_table}.deliv_time_id AND deliv_id = {$tgt_table}.deliv_id)
1837            $sql_where
1838__EOS__;
1839
1840        $objQuery->query($sql, array($order_id));
1841    }
1842
1843    /**
1844     * 店舗基本情報に基づいて税金額を返す
1845     *
1846     * @param integer $price 計算対象の金額
1847     * @return integer 税金額
1848     */
1849    function sfTax($price) {
1850        // 店舗基本情報を取得
1851        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1852
1853        return SC_Utils_Ex::sfTax($price, $CONF['tax'], $CONF['tax_rule']);
1854    }
1855
1856    /**
1857     * 店舗基本情報に基づいて税金付与した金額を返す
1858     *
1859     * @param integer $price 計算対象の金額
1860     * @return integer 税金付与した金額
1861     */
1862    function sfCalcIncTax($price, $tax = null, $tax_rule = null) {
1863        // 店舗基本情報を取得
1864        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1865
1866        return SC_Utils_Ex::sfCalcIncTax($price, $CONF['tax'], $CONF['tax_rule']);
1867    }
1868
1869    /**
1870     * 店舗基本情報に基づいて加算ポイントを返す
1871     *
1872     * @param integer $totalpoint
1873     * @param integer $use_point
1874     * @return integer 加算ポイント
1875     */
1876    function sfGetAddPoint($totalpoint, $use_point) {
1877        // 店舗基本情報を取得
1878        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1879
1880        return SC_Utils_Ex::sfGetAddPoint($totalpoint, $use_point, $CONF['point_rate']);
1881    }
1882
1883    /**
1884     * 受注.対応状況の更新
1885     *
1886     * ・必ず呼び出し元でトランザクションブロックを開いておくこと。
1887     *
1888     * @param integer $orderId 注文番号
1889     * @param integer|null $newStatus 対応状況 (null=変更無し)
1890     * @param integer|null $newAddPoint 加算ポイント (null=変更無し)
1891     * @param integer|null $newUsePoint 使用ポイント (null=変更無し)
1892     * @return void
1893     */
1894    function sfUpdateOrderStatus($orderId, $newStatus = null, $newAddPoint = null, $newUsePoint = null) {
1895        $objQuery =& SC_Query::getSingletonInstance();
1896
1897        $arrOrderOld = $objQuery->getRow('status, add_point, use_point, customer_id', 'dtb_order', 'order_id = ?', array($orderId));
1898
1899        // 対応状況が変更無しの場合、DB値を引き継ぐ
1900        if (is_null($newStatus)) {
1901            $newStatus = $arrOrderOld['status'];
1902        }
1903
1904        // 使用ポイント、DB値を引き継ぐ
1905        if (is_null($newUsePoint)) {
1906            $newUsePoint = $arrOrderOld['use_point'];
1907        }
1908
1909        // 加算ポイント、DB値を引き継ぐ
1910        if (is_null($newAddPoint)) {
1911            $newAddPoint = $arrOrderOld['add_point'];
1912        }
1913
1914        if (USE_POINT !== false) {
1915            // 顧客.ポイントの加減値
1916            $addCustomerPoint = 0;
1917
1918            // ▼使用ポイント
1919            // 変更前の対応状況が利用対象の場合、変更前の使用ポイント分を戻す
1920            if (SC_Utils_Ex::sfIsUsePoint($arrOrderOld['status'])) {
1921                $addCustomerPoint += $arrOrderOld['use_point'];
1922            }
1923
1924            // 変更後の対応状況が利用対象の場合、変更後の使用ポイント分を引く
1925            if (SC_Utils_Ex::sfIsUsePoint($newStatus)) {
1926                $addCustomerPoint -= $newUsePoint;
1927            }
1928            // ▲使用ポイント
1929
1930            // ▼加算ポイント
1931            // 変更前の対応状況が加算対象の場合、変更前の加算ポイント分を戻す
1932            if (SC_Utils_Ex::sfIsAddPoint($arrOrderOld['status'])) {
1933                $addCustomerPoint -= $arrOrderOld['add_point'];
1934            }
1935
1936            // 変更後の対応状況が加算対象の場合、変更後の加算ポイント分を足す
1937            if (SC_Utils_Ex::sfIsAddPoint($newStatus)) {
1938                $addCustomerPoint += $newAddPoint;
1939            }
1940            // ▲加算ポイント
1941
1942            if ($addCustomerPoint != 0) {
1943                // ▼顧客テーブルの更新
1944                $sqlval = array();
1945                $where = '';
1946                $arrVal = array();
1947                $arrRawSql = array();
1948                $arrRawSqlVal = array();
1949
1950                $sqlval['update_date'] = 'Now()';
1951                $arrRawSql['point'] = 'point + ?';
1952                $arrRawSqlVal[] = $addCustomerPoint;
1953                $where .= 'customer_id = ?';
1954                $arrVal[] = $arrOrderOld['customer_id'];
1955
1956                $objQuery->update('dtb_customer', $sqlval, $where, $arrVal, $arrRawSql, $arrRawSqlVal);
1957                // ▲顧客テーブルの更新
1958
1959                // 顧客.ポイントをマイナスした場合、
1960                if ($addCustomerPoint < 0) {
1961                    $sql = 'SELECT point FROM dtb_customer WHERE customer_id = ?';
1962                    $point = $objQuery->getOne($sql, array($arrOrderOld['customer_id']));
1963                    // 変更後の顧客.ポイントがマイナスの場合、
1964                    if ($point < 0) {
1965                        // ロールバック
1966                        $objQuery->rollback();
1967                        // エラー
1968                        SC_Utils_Ex::sfDispSiteError(LACK_POINT);
1969                    }
1970                }
1971            }
1972        }
1973
1974        // ▼受注テーブルの更新
1975        $sqlval = array();
1976        if (USE_POINT !== false) {
1977            $sqlval['add_point'] = $newAddPoint;
1978            $sqlval['use_point'] = $newUsePoint;
1979        }
1980        // ステータスが発送済みに変更の場合、発送日を更新
1981        if ($arrOrderOld['status'] != ORDER_DELIV && $newStatus == ORDER_DELIV) {
1982            $sqlval['commit_date'] = 'Now()';
1983        }
1984        // ステータスが入金済みに変更の場合、入金日を更新
1985        elseif ($arrOrderOld['status'] != ORDER_PRE_END && $newStatus == ORDER_PRE_END) {
1986            $sqlval['payment_date'] = 'Now()';
1987        }
1988
1989        $sqlval['status'] = $newStatus;
1990        $sqlval['update_date'] = 'Now()';
1991
1992        $objQuery->update('dtb_order', $sqlval, 'order_id = ?', array($orderId));
1993        // ▲受注テーブルの更新
1994    }
1995
1996    /**
1997     * 指定ファイルが存在する場合 SQL として実行
1998     *
1999     * XXX プラグイン用に追加。将来消すかも。
2000     *
2001     * @param string $sqlFilePath SQL ファイルのパス
2002     * @return void
2003     */
2004    function sfExecSqlByFile($sqlFilePath) {
2005        if (file_exists($sqlFilePath)) {
2006            $objQuery =& SC_Query::getSingletonInstance();
2007
2008            $sqls = file_get_contents($sqlFilePath);
2009            if ($sqls === false) SC_Utils_Ex::sfDispException('ファイルは存在するが読み込めない');
2010
2011            foreach (explode(';', $sqls) as $sql) {
2012                $sql = trim($sql);
2013                if (strlen($sql) == 0) continue;
2014                $objQuery->query($sql);
2015            }
2016        }
2017    }
2018
2019    /**
2020     * 商品規格を設定しているか
2021     *
2022     * @param integer $product_id 商品ID
2023     * @return bool 商品規格が存在する場合:true, それ以外:false
2024     */
2025    function sfHasProductClass($product_id) {
2026        if (!SC_Utils_Ex::sfIsInt($product_id)) return false;
2027
2028        $objQuery =& SC_Query::getSingletonInstance();
2029        $where = 'product_id = ? AND class_combination_id IS NOT NULL';
2030        $count = $objQuery->count('dtb_products_class', $where, array($product_id));
2031
2032        return $count >= 1;
2033    }
2034    /**
2035     * カート内の商品の販売方法判定処理
2036     *
2037     * @param $objCartSess  SC_CartSession  カートセッション
2038     * @return  bool        0:実商品のみ 1:ダウンロード販売と実商品混在 2:全てダウンロード販売
2039     */
2040    function chkCartDown(&$objCartSess, $cartKey = 1) {
2041        $objQuery =& SC_Query::getSingletonInstance();
2042        $down = false;
2043        $nodown = false;
2044        $ret = 0;
2045        $arrID = $objCartSess->getAllProductID();
2046        $table = "dtb_products_class pc";
2047        $where = "pc.product_class_id = ?";
2048        if(!is_null($arrID)){
2049            //カート内のIDから販売方法を取得
2050            foreach ($arrID as $rec) {
2051                $arrRet = $objQuery->select("pc.down AS down", $table, $where, array($rec));
2052                if ($arrRet[0]['down'] == "2"){
2053                    $down = true;
2054                }else{
2055                    $nodown = true;
2056                }
2057            }
2058        }
2059        //混在
2060        if($nodown && $down){
2061            $ret = 1;
2062        //全てダウンロード商品
2063        }else if(!$nodown && $down){
2064            $ret = 2;
2065        }
2066        return $ret;
2067    }
2068
2069    /* 会員情報の住所を一時受注テーブルへ */
2070    function sfRegistDelivData($uniqid, $objCustomer) {
2071
2072        // 登録データの作成
2073        $sqlval['order_temp_id'] = $uniqid;
2074        $sqlval['update_date'] = 'Now()';
2075        $sqlval['customer_id'] = $objCustomer->getValue('customer_id');
2076        $sqlval['deliv_check'] = '-1';
2077        $sqlval['order_name01'] = $objCustomer->getValue('name01');
2078        $sqlval['order_name02'] = $objCustomer->getValue('name02');
2079        $sqlval['order_kana01'] = $objCustomer->getValue('kana01');
2080        $sqlval['order_kana02'] = $objCustomer->getValue('kana02');
2081        $sqlval['order_zip01'] = $objCustomer->getValue('zip01');
2082        $sqlval['order_zip02'] = $objCustomer->getValue('zip02');
2083        $sqlval['order_pref'] = $objCustomer->getValue('pref');
2084        $sqlval['order_addr01'] = $objCustomer->getValue('addr01');
2085        $sqlval['order_addr02'] = $objCustomer->getValue('addr02');
2086        $sqlval['order_tel01'] = $objCustomer->getValue('tel01');
2087        $sqlval['order_tel02'] = $objCustomer->getValue('tel02');
2088        $sqlval['order_tel03'] = $objCustomer->getValue('tel03');
2089        $sqlval['order_fax01'] = $objCustomer->getValue('fax01');
2090        $sqlval['order_fax02'] = $objCustomer->getValue('fax02');
2091        $sqlval['order_fax03'] = $objCustomer->getValue('fax03');
2092        $sqlval['deliv_name01'] = $objCustomer->getValue('name01');
2093        $sqlval['deliv_name02'] = $objCustomer->getValue('name02');
2094        $sqlval['deliv_kana01'] = $objCustomer->getValue('kana01');
2095        $sqlval['deliv_kana02'] = $objCustomer->getValue('kana02');
2096        $sqlval['deliv_zip01'] = $objCustomer->getValue('zip01');
2097        $sqlval['deliv_zip02'] = $objCustomer->getValue('zip02');
2098        $sqlval['deliv_pref'] = $objCustomer->getValue('pref');
2099        $sqlval['deliv_addr01'] = $objCustomer->getValue('addr01');
2100        $sqlval['deliv_addr02'] = $objCustomer->getValue('addr02');
2101        $sqlval['deliv_tel01'] = $objCustomer->getValue('tel01');
2102        $sqlval['deliv_tel02'] = $objCustomer->getValue('tel02');
2103        $sqlval['deliv_tel03'] = $objCustomer->getValue('tel03');
2104        $sqlval['deliv_fax01'] = $objCustomer->getValue('fax01');
2105        $sqlval['deliv_fax02'] = $objCustomer->getValue('fax02');
2106        $sqlval['deliv_fax03'] = $objCustomer->getValue('fax03');
2107
2108        $this->sfRegistTempOrder($uniqid, $sqlval);
2109    }
2110}
2111?>
Note: See TracBrowser for help on using the repository browser.