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

Revision 19909, 77.4 KB checked in by uemoto, 13 years ago (diff)

#382(管理画面XHTMLに変更)

  • デザインを刷新
  • 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 integer $order_id 受注番号
439     * @param integer $use_point 利用ポイント
440     * @param integer $add_point 加算ポイント
441     * @return array オーダー前ポイントの配列
442     */
443    function sfGetRollbackPoint($order_id, $use_point, $add_point) {
444        $objQuery = new SC_Query();
445        $arrRet = $objQuery->select("customer_id", "dtb_order", "order_id = ?", array($order_id));
446        $customer_id = $arrRet[0]['customer_id'];
447        if($customer_id != "" && $customer_id >= 1) {
448            $arrRet = $objQuery->select("point", "dtb_customer", "customer_id = ?", array($customer_id));
449            $point = $arrRet[0]['point'];
450            $rollback_point = $arrRet[0]['point'] + $use_point - $add_point;
451        } else {
452            $rollback_point = "";
453            $point = "";
454        }
455        return array($point, $rollback_point);
456    }
457   
458
459
460    /**
461     * カテゴリツリーの取得を行う.
462     *
463     * @param integer $parent_category_id 親カテゴリID
464     * @param bool $count_check 登録商品数のチェックを行う場合 true
465     * @return array カテゴリツリーの配列
466     */
467    function sfGetCatTree($parent_category_id, $count_check = false) {
468        $objQuery =& SC_Query::getSingletonInstance();
469        $col = "";
470        $col .= " cat.category_id,";
471        $col .= " cat.category_name,";
472        $col .= " cat.parent_category_id,";
473        $col .= " cat.level,";
474        $col .= " cat.rank,";
475        $col .= " cat.creator_id,";
476        $col .= " cat.create_date,";
477        $col .= " cat.update_date,";
478        $col .= " cat.del_flg, ";
479        $col .= " ttl.product_count";
480        $from = "dtb_category as cat left join dtb_category_total_count as ttl on ttl.category_id = cat.category_id";
481        // 登録商品数のチェック
482        if($count_check) {
483            $where = "del_flg = 0 AND product_count > 0";
484        } else {
485            $where = "del_flg = 0";
486        }
487        $objQuery->setOption("ORDER BY rank DESC");
488        $arrRet = $objQuery->select($col, $from, $where);
489
490        $arrParentID = $this->sfGetParents($objQuery, 'dtb_category', 'parent_category_id', 'category_id', $parent_category_id);
491
492        foreach($arrRet as $key => $array) {
493            foreach($arrParentID as $val) {
494                if($array['category_id'] == $val) {
495                    $arrRet[$key]['display'] = 1;
496                    break;
497                }
498            }
499        }
500
501        return $arrRet;
502    }
503
504    /**
505     * カテゴリツリーを走査し, パンくずリスト用の配列を生成する.
506     *
507     * @param array カテゴリの配列
508     * @param integer $parent 上位カテゴリID
509     * @param array パンくずリスト用の配列
510     * @result void
511     * @see sfGetCatTree()
512     */
513    function findTree(&$arrTree, $parent, &$result) {
514        if ($result[count($result) - 1]['parent_category_id'] === 0) {
515            return;
516        } else {
517            foreach ($arrTree as $key => $val) {
518               if ($val['category_id'] == $parent) {
519                    $result[] = array('category_id' => $val['category_id'],
520                                      'parent_category_id' => (int) $val['parent_category_id'],
521                                      'category_name' => $val['category_name']);
522                    $this->findTree($arrTree, $val['parent_category_id'], $result);
523               }
524            }
525        }
526    }
527
528    /**
529     * カテゴリツリーの取得を複数カテゴリーで行う.
530     *
531     * @param integer $product_id 商品ID
532     * @param bool $count_check 登録商品数のチェックを行う場合 true
533     * @return array カテゴリツリーの配列
534     */
535    function sfGetMultiCatTree($product_id, $count_check = false) {
536        $objQuery =& SC_Query::getSingletonInstance();
537        $col = "";
538        $col .= " cat.category_id,";
539        $col .= " cat.category_name,";
540        $col .= " cat.parent_category_id,";
541        $col .= " cat.level,";
542        $col .= " cat.rank,";
543        $col .= " cat.creator_id,";
544        $col .= " cat.create_date,";
545        $col .= " cat.update_date,";
546        $col .= " cat.del_flg, ";
547        $col .= " ttl.product_count";
548        $from = "dtb_category as cat left join dtb_category_total_count as ttl on ttl.category_id = cat.category_id";
549        // 登録商品数のチェック
550        if($count_check) {
551            $where = "del_flg = 0 AND product_count > 0";
552        } else {
553            $where = "del_flg = 0";
554        }
555        $objQuery->setOption("ORDER BY rank DESC");
556        $arrRet = $objQuery->select($col, $from, $where);
557
558        $arrCategory_id = $this->sfGetCategoryId($product_id);
559
560        $arrCatTree = array();
561        foreach ($arrCategory_id as $pkey => $parent_category_id) {
562            $arrParentID = $this->sfGetParents($objQuery, 'dtb_category', 'parent_category_id', 'category_id', $parent_category_id);
563
564            foreach($arrParentID as $pid) {
565                foreach($arrRet as $key => $array) {
566                    if($array['category_id'] == $pid) {
567                        $arrCatTree[$pkey][] = $arrRet[$key];
568                        break;
569                    }
570                }
571            }
572        }
573
574        return $arrCatTree;
575    }
576
577    /**
578     * 親カテゴリーを連結した文字列を取得する.
579     *
580     * @param integer $category_id カテゴリID
581     * @return string 親カテゴリーを連結した文字列
582     */
583    function sfGetCatCombName($category_id){
584        // 商品が属するカテゴリIDを縦に取得
585        $objQuery =& SC_Query::getSingletonInstance();
586        $arrCatID = $this->sfGetParents($objQuery, "dtb_category", "parent_category_id", "category_id", $category_id);
587        $ConbName = "";
588
589        // カテゴリー名称を取得する
590        foreach($arrCatID as $key => $val){
591            $sql = "SELECT category_name FROM dtb_category WHERE category_id = ?";
592            $arrVal = array($val);
593            $CatName = $objQuery->getOne($sql,$arrVal);
594            $ConbName .= $CatName . ' | ';
595        }
596        // 最後の | をカットする
597        $ConbName = substr_replace($ConbName, "", strlen($ConbName) - 2, 2);
598
599        return $ConbName;
600    }
601
602    /**
603     * 指定したカテゴリーIDのカテゴリーを取得する.
604     *
605     * @param integer $category_id カテゴリID
606     * @return array 指定したカテゴリーIDのカテゴリー
607     */
608    function sfGetCat($category_id){
609        $objQuery =& SC_Query::getSingletonInstance();
610
611        // カテゴリーを取得する
612        $arrVal = array($category_id);
613        $res = $objQuery->select('category_id AS id, category_name AS name', 'dtb_category', 'category_id = ?', $arrVal);
614
615        return $res[0];
616    }
617
618    /**
619     * 指定したカテゴリーIDの大カテゴリーを取得する.
620     *
621     * @param integer $category_id カテゴリID
622     * @return array 指定したカテゴリーIDの大カテゴリー
623     */
624    function sfGetFirstCat($category_id){
625        // 商品が属するカテゴリIDを縦に取得
626        $objQuery =& SC_Query::getSingletonInstance();
627        $arrRet = array();
628        $arrCatID = $this->sfGetParents($objQuery, "dtb_category", "parent_category_id", "category_id", $category_id);
629        $arrRet['id'] = $arrCatID[0];
630
631        // カテゴリー名称を取得する
632        $sql = "SELECT category_name FROM dtb_category WHERE category_id = ?";
633        $arrVal = array($arrRet['id']);
634        $arrRet['name'] = $objQuery->getOne($sql,$arrVal);
635
636        return $arrRet;
637    }
638
639    /**
640     * カテゴリツリーの取得を行う.
641     *
642     * $products_check:true商品登録済みのものだけ取得する
643     *
644     * @param string $addwhere 追加する WHERE 句
645     * @param bool $products_check 商品の存在するカテゴリのみ取得する場合 true
646     * @param string $head カテゴリ名のプレフィックス文字列
647     * @return array カテゴリツリーの配列
648     */
649    function sfGetCategoryList($addwhere = "", $products_check = false, $head = CATEGORY_HEAD) {
650        $objQuery =& SC_Query::getSingletonInstance();
651        $where = "del_flg = 0";
652
653        if($addwhere != "") {
654            $where.= " AND $addwhere";
655        }
656
657        $objQuery->setOption("ORDER BY rank DESC");
658
659        if($products_check) {
660            $col = "T1.category_id, category_name, level";
661            $from = "dtb_category AS T1 LEFT JOIN dtb_category_total_count AS T2 ON T1.category_id = T2.category_id";
662            $where .= " AND product_count > 0";
663        } else {
664            $col = "category_id, category_name, level";
665            $from = "dtb_category";
666        }
667
668        $arrRet = $objQuery->select($col, $from, $where);
669
670        $max = count($arrRet);
671        for($cnt = 0; $cnt < $max; $cnt++) {
672            $id = $arrRet[$cnt]['category_id'];
673            $name = $arrRet[$cnt]['category_name'];
674            $arrList[$id] = str_repeat($head, $arrRet[$cnt]['level']) . $name;
675        }
676        return $arrList;
677    }
678
679    /**
680     * カテゴリーツリーの取得を行う.
681     *
682     * 親カテゴリの Value=0 を対象とする
683     *
684     * @param bool $parent_zero 親カテゴリの Value=0 の場合 true
685     * @return array カテゴリツリーの配列
686     */
687    function sfGetLevelCatList($parent_zero = true) {
688        $objQuery =& SC_Query::getSingletonInstance();
689
690        // カテゴリ名リストを取得
691        $col = "category_id, parent_category_id, category_name";
692        $where = "del_flg = 0";
693        $objQuery->setOption("ORDER BY level");
694        $arrRet = $objQuery->select($col, "dtb_category", $where);
695        $arrCatName = array();
696        foreach ($arrRet as $arrTmp) {
697            $arrCatName[$arrTmp['category_id']] =
698                (($arrTmp['parent_category_id'] > 0)?
699                    $arrCatName[$arrTmp['parent_category_id']] : "")
700                . CATEGORY_HEAD . $arrTmp['category_name'];
701        }
702
703        $col = "category_id, parent_category_id, category_name, level";
704        $where = "del_flg = 0";
705        $objQuery->setOption("ORDER BY rank DESC");
706        $arrRet = $objQuery->select($col, "dtb_category", $where);
707        $max = count($arrRet);
708
709        for($cnt = 0; $cnt < $max; $cnt++) {
710            if($parent_zero) {
711                if($arrRet[$cnt]['level'] == LEVEL_MAX) {
712                    $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
713                } else {
714                    $arrValue[$cnt] = "";
715                }
716            } else {
717                $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
718            }
719
720            $arrOutput[$cnt] = $arrCatName[$arrRet[$cnt]['category_id']];
721        }
722
723        return array($arrValue, $arrOutput);
724    }
725
726    /**
727     * 選択中の商品のカテゴリを取得する.
728     *
729     * @param integer $product_id プロダクトID
730     * @param integer $category_id カテゴリID
731     * @return array 選択中の商品のカテゴリIDの配列
732     *
733     */
734    function sfGetCategoryId($product_id, $category_id = 0, $closed = false) {
735        if ($closed) {
736            $status = "";
737        } else {
738            $status = "status = 1";
739        }
740
741        if(!$this->g_category_on) {
742            $this->g_category_on = true;
743            $category_id = (int) $category_id;
744            $product_id = (int) $product_id;
745            if (SC_Utils_Ex::sfIsInt($category_id) && $category_id != 0 && $this->sfIsRecord("dtb_category","category_id", $category_id)) {
746                $this->g_category_id = array($category_id);
747            } else if (SC_Utils_Ex::sfIsInt($product_id) && $product_id != 0 && $this->sfIsRecord("dtb_products","product_id", $product_id, $status)) {
748                $objQuery =& SC_Query::getSingletonInstance();
749                $where = "product_id = ?";
750                $category_id = $objQuery->getCol("category_id", "dtb_product_categories", "product_id = ?", array($product_id));
751                $this->g_category_id = $category_id;
752            } else {
753                // 不正な場合は、空の配列を返す。
754                $this->g_category_id = array();
755            }
756        }
757        return $this->g_category_id;
758    }
759
760    /**
761     * 商品をカテゴリの先頭に追加する.
762     *
763     * @param integer $category_id カテゴリID
764     * @param integer $product_id プロダクトID
765     * @return void
766     */
767    function addProductBeforCategories($category_id, $product_id) {
768
769        $sqlval = array("category_id" => $category_id,
770                        "product_id" => $product_id);
771
772        $objQuery =& SC_Query::getSingletonInstance();
773
774        // 現在の商品カテゴリを取得
775        $arrCat = $objQuery->select("product_id, category_id, rank",
776                                    "dtb_product_categories",
777                                    "category_id = ?",
778                                    array($category_id));
779
780        $max = "0";
781        foreach ($arrCat as $val) {
782            // 同一商品が存在する場合は登録しない
783            if ($val["product_id"] == $product_id) {
784                return;
785            }
786            // 最上位ランクを取得
787            $max = ($max < $val["rank"]) ? $val["rank"] : $max;
788        }
789        $sqlval["rank"] = $max + 1;
790        $objQuery->insert("dtb_product_categories", $sqlval);
791    }
792
793    /**
794     * 商品をカテゴリの末尾に追加する.
795     *
796     * @param integer $category_id カテゴリID
797     * @param integer $product_id プロダクトID
798     * @return void
799     */
800    function addProductAfterCategories($category_id, $product_id) {
801        $sqlval = array("category_id" => $category_id,
802                        "product_id" => $product_id);
803
804        $objQuery =& SC_Query::getSingletonInstance();
805
806        // 現在の商品カテゴリを取得
807        $arrCat = $objQuery->select("product_id, category_id, rank",
808                                    "dtb_product_categories",
809                                    "category_id = ?",
810                                    array($category_id));
811
812        $min = 0;
813        foreach ($arrCat as $val) {
814            // 同一商品が存在する場合は登録しない
815            if ($val["product_id"] == $product_id) {
816                return;
817            }
818            // 最下位ランクを取得
819            $min = ($min < $val["rank"]) ? $val["rank"] : $min;
820        }
821        $sqlval["rank"] = $min;
822        $objQuery->insert("dtb_product_categories", $sqlval);
823    }
824
825    /**
826     * 商品をカテゴリから削除する.
827     *
828     * @param integer $category_id カテゴリID
829     * @param integer $product_id プロダクトID
830     * @return void
831     */
832    function removeProductByCategories($category_id, $product_id) {
833        $objQuery =& SC_Query::getSingletonInstance();
834        $objQuery->delete("dtb_product_categories",
835                          "category_id = ? AND product_id = ?", array($category_id, $product_id));
836    }
837
838    /**
839     * 商品カテゴリを更新する.
840     *
841     * @param array $arrCategory_id 登録するカテゴリIDの配列
842     * @param integer $product_id プロダクトID
843     * @return void
844     */
845    function updateProductCategories($arrCategory_id, $product_id) {
846        $objQuery =& SC_Query::getSingletonInstance();
847
848        // 現在のカテゴリ情報を取得
849        $arrCurrentCat = $objQuery->select("product_id, category_id, rank",
850                                           "dtb_product_categories",
851                                           "product_id = ?",
852                                           array($product_id));
853
854        // 登録するカテゴリ情報と比較
855        foreach ($arrCurrentCat as $val) {
856
857            // 登録しないカテゴリを削除
858            if (!in_array($val["category_id"], $arrCategory_id)) {
859                $this->removeProductByCategories($val["category_id"], $product_id);
860            }
861        }
862
863        // カテゴリを登録
864        foreach ($arrCategory_id as $category_id) {
865            $this->addProductBeforCategories($category_id, $product_id);
866        }
867    }
868
869    /**
870     * カテゴリ数の登録を行う.
871     *
872     *
873     * @param SC_Query $objQuery SC_Query インスタンス
874     * @param boolean $is_force_all_count 全カテゴリの集計を強制する場合 true
875     * @return void
876     */
877    function sfCategory_Count($objQuery = NULL, $is_force_all_count = false){
878        $objProduct = new SC_Product();
879       
880        if($objQuery == NULL) {
881            $objQuery =& SC_Query::getSingletonInstance();
882        }
883       
884        $is_out_trans = false;
885        if(!$objQuery->inTransaction()){
886            $objQuery->begin();
887            $is_out_trans = true;
888        }
889       
890        //共通のfrom/where文の構築
891        $sql_where = 'alldtl.del_flg = 0 AND alldtl.status = 1';
892        // 在庫無し商品の非表示
893        if (NOSTOCK_HIDDEN === true) {
894            $sql_where_dtl = 'stock_max >= 1 OR stock_unlimited_max = 1';
895            $from = $objProduct->alldtlSQL($sql_where_dtl);
896        }else{
897            $from = " dtb_products as alldtl ";
898        }
899       
900        //dtb_category_countの構成
901        // 各カテゴリに所属する商品の数を集計。集計対象には子カテゴリを含まない。
902        // 2.5で消える予定だったが復活させます。DELETE処理は無くしました。
903       
904        //まずテーブル内容の元を取得
905        if(!$is_force_all_count) {
906            $arrCategoryCountOld = $objQuery->select('category_id,product_count','dtb_category_count');
907        }else{
908            $arrCategoryCountOld = array();
909        }
910
911        //各カテゴリ内の商品数を数えて取得
912        $sql = <<< __EOS__
913            SELECT T1.category_id, count(T2.category_id) as product_count
914            FROM dtb_category AS T1
915                LEFT JOIN dtb_product_categories AS T2
916                    ON T1.category_id = T2.category_id
917                LEFT JOIN $from
918                    ON T2.product_id = alldtl.product_id
919            WHERE $sql_where
920            GROUP BY T1.category_id, T2.category_id
921__EOS__;
922
923        $arrCategoryCountNew = $objQuery->getAll($sql);
924        // 各カテゴリに所属する商品の数を集計。集計対象には子カテゴリを「含む」。       
925        //差分を取得して、更新対象カテゴリだけを確認する。
926
927        //各カテゴリ毎のデータ値において以前との差を見る       
928        //古いデータの構造入れ替え
929        $arrOld = array();
930        foreach($arrCategoryCountOld as $item){
931            $arrOld[$item['category_id']] = $item['product_count'];
932        }
933        //新しいデータの構造入れ替え
934        $arrNew = array();
935        foreach($arrCategoryCountNew as $item){
936            $arrNew[$item['category_id']] = $item['product_count'];
937        }
938
939        $arrDiffCategory_id = array();
940        //新しいカテゴリ一覧から見て商品数が異なるデータが無いか確認
941        foreach($arrNew as $cid => $count){
942            if($arrOld[$cid] != $count){
943                $arrDiffCategory_id[] = $cid;
944            }
945        }
946        //削除カテゴリを想定して、古いカテゴリ一覧から見て商品数が異なるデータが無いか確認。
947        foreach($arrOld as $cid => $count){
948            if($arrNew[$cid] != $count){
949                $arrDiffCategory_id[] = $cid;
950            }
951        }
952       
953        //対象IDが無ければ終了
954        if(count($arrDiffCategory_id) == 0){
955            if($is_out_trans) {
956                $objQuery->commit();
957            }
958            return;
959        }
960
961        //差分対象カテゴリIDの重複を除去
962        $arrDiffCategory_id = array_unique($arrDiffCategory_id);
963       
964        //dtb_category_countの更新 差分のあったカテゴリだけ更新する。
965        foreach($arrDiffCategory_id as $cid) {
966            $sqlval = array();
967            $sqlval['create_date'] = 'Now()';
968            $sqlval['product_count'] = (string)$arrNew[$cid];
969            if($sqlval['product_count'] =="") {
970                $sqlval['product_count'] = (string)'0';
971            }
972            if(isset($arrOld[$cid])) {
973                $objQuery->update('dtb_category_count', $sqlval, 'category_id = ?', array($cid));
974            }else{
975                $sqlval['category_id'] = $cid;
976                $objQuery->insert('dtb_category_count', $sqlval);
977            }
978        }
979       
980        //差分があったIDとその親カテゴリIDのリストを取得する
981        $arrTgtCategory_id = array();
982        foreach ($arrDiffCategory_id as $parent_category_id) {
983            $arrTgtCategory_id[] = $parent_category_id;
984            $arrParentID = $this->sfGetParents($objQuery, 'dtb_category', 'parent_category_id', 'category_id', $parent_category_id);
985            foreach($arrParentID as $pid) {
986                $arrTgtCategory_id[] = $pid;
987            }
988        }
989       
990        //重複を取り除く
991        $arrTgtCategory_id = array_unique($arrTgtCategory_id);
992
993        //dtb_category_total_count 集計処理開始
994        //更新対象カテゴリIDだけ集計しなおす。
995        $arrUpdateData = array();
996        foreach ($arrTgtCategory_id as $category_id) {
997            $arrval = array();
998            $arrval[] = $category_id;
999            list($tmp_where, $tmp_arrval) = $this->sfGetCatWhere($category_id);
1000            if ($tmp_where != "") {
1001                $sql_where_product_ids = "product_id IN (SELECT product_id FROM dtb_product_categories WHERE " . $tmp_where . ")";
1002                $arrval = array_merge((array)$arrval, (array)$tmp_arrval, (array)$tmp_arrval);
1003            } else {
1004                $sql_where_product_ids = '0<>0'; // 一致させない
1005            }
1006            $where = "($sql_where) AND ($sql_where_product_ids)";
1007
1008            $from = $objProduct->alldtlSQL($sql_where_product_ids);
1009            $sql = "SELECT count(*) FROM $from WHERE $where ";
1010            $arrUpdateData[ $category_id ] = $objQuery->getOne($sql, $arrval);
1011        }
1012        // 更新対象だけを更新。
1013        foreach($arrUpdateData as $cid => $count) {
1014            $sqlval = array();
1015            $sqlval['create_date'] = 'Now()';
1016            $sqlval['product_count'] = $count;
1017            if($sqlval['product_count'] =="") {
1018                $sqlval['product_count'] = (string)'0';
1019            }
1020            $ret = $objQuery->update('dtb_category_total_count', $sqlval, 'category_id = ?', array($cid));
1021            if(!$ret) {
1022                $sqlval['category_id'] = $cid;
1023                $ret = $objQuery->insert('dtb_category_total_count', $sqlval);
1024            }
1025        }
1026        // トランザクション音終了処理
1027        if($is_out_trans) {
1028            $objQuery->commit();
1029        }
1030    }
1031
1032    /**
1033     * 子IDの配列を返す.
1034     *
1035     * @param string $table テーブル名
1036     * @param string $pid_name 親ID名
1037     * @param string $id_name ID名
1038     * @param integer $id ID
1039     * @param array 子ID の配列
1040     */
1041    function sfGetChildsID($table, $pid_name, $id_name, $id) {
1042        $arrRet = $this->sfGetChildrenArray($table, $pid_name, $id_name, $id);
1043        return $arrRet;
1044    }
1045
1046    /**
1047     * 階層構造のテーブルから子ID配列を取得する.
1048     *
1049     * @param string $table テーブル名
1050     * @param string $pid_name 親ID名
1051     * @param string $id_name ID名
1052     * @param integer $id ID番号
1053     * @return array 子IDの配列
1054     */
1055    function sfGetChildrenArray($table, $pid_name, $id_name, $id) {
1056        $objQuery =& SC_Query::getSingletonInstance();
1057        $col = $pid_name . "," . $id_name;
1058        $arrData = $objQuery->select($col, $table);
1059
1060        $arrPID = array();
1061        $arrPID[] = $id;
1062        $arrChildren = array();
1063        $arrChildren[] = $id;
1064
1065        $arrRet = $this->sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrPID);
1066
1067        while(count($arrRet) > 0) {
1068            $arrChildren = array_merge($arrChildren, $arrRet);
1069            $arrRet = $this->sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrRet);
1070        }
1071
1072        return $arrChildren;
1073    }
1074
1075    /**
1076     * 親ID直下の子IDをすべて取得する.
1077     *
1078     * @param array $arrData 親カテゴリの配列
1079     * @param string $pid_name 親ID名
1080     * @param string $id_name ID名
1081     * @param array $arrPID 親IDの配列
1082     * @return array 子IDの配列
1083     */
1084    function sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrPID) {
1085        $arrChildren = array();
1086        $max = count($arrData);
1087
1088        for($i = 0; $i < $max; $i++) {
1089            foreach($arrPID as $val) {
1090                if($arrData[$i][$pid_name] == $val) {
1091                    $arrChildren[] = $arrData[$i][$id_name];
1092                }
1093            }
1094        }
1095        return $arrChildren;
1096    }
1097
1098    /**
1099     * 所属するすべての階層の親IDを配列で返す.
1100     *
1101     * @param SC_Query $objQuery SC_Query インスタンス
1102     * @param string $table テーブル名
1103     * @param string $pid_name 親ID名
1104     * @param string $id_name ID名
1105     * @param integer $id ID
1106     * @return array 親IDの配列
1107     */
1108    function sfGetParents($objQuery, $table, $pid_name, $id_name, $id) {
1109        $arrRet = $this->sfGetParentsArray($table, $pid_name, $id_name, $id);
1110        // 配列の先頭1つを削除する。
1111        array_shift($arrRet);
1112        return $arrRet;
1113    }
1114
1115    /**
1116     * 階層構造のテーブルから親ID配列を取得する.
1117     *
1118     * @param string $table テーブル名
1119     * @param string $pid_name 親ID名
1120     * @param string $id_name ID名
1121     * @param integer $id ID
1122     * @return array 親IDの配列
1123     */
1124    function sfGetParentsArray($table, $pid_name, $id_name, $id) {
1125        $objQuery =& SC_Query::getSingletonInstance();
1126        $col = $pid_name . "," . $id_name;
1127        $arrData = $objQuery->select($col, $table);
1128
1129        $arrParents = array();
1130        $arrParents[] = $id;
1131        $child = $id;
1132
1133        $ret = SC_Utils::sfGetParentsArraySub($arrData, $pid_name, $id_name, $child);
1134
1135        while($ret != "") {
1136            $arrParents[] = $ret;
1137            $ret = SC_Utils::sfGetParentsArraySub($arrData, $pid_name, $id_name, $ret);
1138        }
1139
1140        $arrParents = array_reverse($arrParents);
1141
1142        return $arrParents;
1143    }
1144
1145    /**
1146     * カテゴリから商品を検索する場合のWHERE文と値を返す.
1147     *
1148     * @param integer $category_id カテゴリID
1149     * @return array 商品を検索する場合の配列
1150     */
1151    function sfGetCatWhere($category_id) {
1152        // 子カテゴリIDの取得
1153        $arrRet = $this->sfGetChildsID("dtb_category", "parent_category_id", "category_id", $category_id);
1154        $tmp_where = "";
1155        foreach ($arrRet as $val) {
1156            if($tmp_where == "") {
1157                $tmp_where.= "category_id IN ( ?";
1158            } else {
1159                $tmp_where.= ",? ";
1160            }
1161            $arrval[] = $val;
1162        }
1163        $tmp_where.= " ) ";
1164        return array($tmp_where, $arrval);
1165    }
1166
1167    /**
1168     * 受注一時テーブルから情報を取得する.
1169     *
1170     * @param integer $order_temp_id 受注一時ID
1171     * @return array 受注一時情報の配列
1172     * @deprecated SC_Helper_Purchase::getOrderTemp() を使用して下さい
1173     */
1174    function sfGetOrderTemp($order_temp_id) {
1175        $objQuery =& SC_Query::getSingletonInstance();
1176        $where = "order_temp_id = ?";
1177        $arrRet = $objQuery->select("*", "dtb_order_temp", $where, array($order_temp_id));
1178        return $arrRet[0];
1179    }
1180
1181    /**
1182     * SELECTボックス用リストを作成する.
1183     *
1184     * @param string $table テーブル名
1185     * @param string $keyname プライマリーキーのカラム名
1186     * @param string $valname データ内容のカラム名
1187     * @param string $where WHERE句
1188     * @param array $arrval プレースホルダ
1189     * @return array SELECT ボックス用リストの配列
1190     */
1191    function sfGetIDValueList($table, $keyname, $valname, $where = '', $arrVal = array()) {
1192        $objQuery =& SC_Query::getSingletonInstance();
1193        $col = "$keyname, $valname";
1194        $objQuery->setWhere("del_flg = 0");
1195        $objQuery->setOrder("rank DESC");
1196        $arrList = $objQuery->select($col, $table, $where, $arrVal);
1197        $count = count($arrList);
1198        for($cnt = 0; $cnt < $count; $cnt++) {
1199            $key = $arrList[$cnt][$keyname];
1200            $val = $arrList[$cnt][$valname];
1201            $arrRet[$key] = $val;
1202        }
1203        return $arrRet;
1204    }
1205
1206    /**
1207     * ランキングを上げる.
1208     *
1209     * @param string $table テーブル名
1210     * @param string $colname カラム名
1211     * @param string|integer $id テーブルのキー
1212     * @param string $andwhere SQL の AND 条件である WHERE 句
1213     * @return void
1214     */
1215    function sfRankUp($table, $colname, $id, $andwhere = "") {
1216        $objQuery =& SC_Query::getSingletonInstance();
1217        $objQuery->begin();
1218        $where = "$colname = ?";
1219        if($andwhere != "") {
1220            $where.= " AND $andwhere";
1221        }
1222        // 対象項目のランクを取得
1223        $rank = $objQuery->get("rank", $table, $where, array($id));
1224        // ランクの最大値を取得
1225        $maxrank = $objQuery->max("rank", $table, $andwhere);
1226        // ランクが最大値よりも小さい場合に実行する。
1227        if($rank < $maxrank) {
1228            // ランクが一つ上のIDを取得する。
1229            $where = "rank = ?";
1230            if($andwhere != "") {
1231                $where.= " AND $andwhere";
1232            }
1233            $uprank = $rank + 1;
1234            $up_id = $objQuery->get($colname, $table, $where, array($uprank));
1235            // ランク入れ替えの実行
1236            $sqlup = "UPDATE $table SET rank = ? WHERE $colname = ?";
1237            if($andwhere != "") {
1238                $sqlup.= " AND $andwhere";
1239            }
1240            $objQuery->exec($sqlup, array($rank + 1, $id));
1241            $objQuery->exec($sqlup, array($rank, $up_id));
1242        }
1243        $objQuery->commit();
1244    }
1245
1246    /**
1247     * ランキングを下げる.
1248     *
1249     * @param string $table テーブル名
1250     * @param string $colname カラム名
1251     * @param string|integer $id テーブルのキー
1252     * @param string $andwhere SQL の AND 条件である WHERE 句
1253     * @return void
1254     */
1255    function sfRankDown($table, $colname, $id, $andwhere = "") {
1256        $objQuery =& SC_Query::getSingletonInstance();
1257        $objQuery->begin();
1258        $where = "$colname = ?";
1259        if($andwhere != "") {
1260            $where.= " AND $andwhere";
1261        }
1262        // 対象項目のランクを取得
1263        $rank = $objQuery->get("rank", $table, $where, array($id));
1264
1265        // ランクが1(最小値)よりも大きい場合に実行する。
1266        if($rank > 1) {
1267            // ランクが一つ下のIDを取得する。
1268            $where = "rank = ?";
1269            if($andwhere != "") {
1270                $where.= " AND $andwhere";
1271            }
1272            $downrank = $rank - 1;
1273            $down_id = $objQuery->get($colname, $table, $where, array($downrank));
1274            // ランク入れ替えの実行
1275            $sqlup = "UPDATE $table SET rank = ? WHERE $colname = ?";
1276            if($andwhere != "") {
1277                $sqlup.= " AND $andwhere";
1278            }
1279            $objQuery->exec($sqlup, array($rank - 1, $id));
1280            $objQuery->exec($sqlup, array($rank, $down_id));
1281        }
1282        $objQuery->commit();
1283    }
1284
1285    /**
1286     * 指定順位へ移動する.
1287     *
1288     * @param string $tableName テーブル名
1289     * @param string $keyIdColumn キーを保持するカラム名
1290     * @param string|integer $keyId キーの値
1291     * @param integer $pos 指定順位
1292     * @param string $where SQL の AND 条件である WHERE 句
1293     * @return void
1294     */
1295    function sfMoveRank($tableName, $keyIdColumn, $keyId, $pos, $where = "") {
1296        $objQuery =& SC_Query::getSingletonInstance();
1297        $objQuery->begin();
1298
1299        // 自身のランクを取得する
1300        if($where != "") {
1301            $getWhere = "$keyIdColumn = ? AND " . $where;
1302        } else {
1303            $getWhere = "$keyIdColumn = ?";
1304        }
1305        $rank = $objQuery->get("rank", $tableName, $getWhere, array($keyId));
1306
1307        $max = $objQuery->max("rank", $tableName, $where);
1308
1309        // 値の調整(逆順)
1310        if($pos > $max) {
1311            $position = 1;
1312        } else if($pos < 1) {
1313            $position = $max;
1314        } else {
1315            $position = $max - $pos + 1;
1316        }
1317
1318        //入れ替え先の順位が入れ換え元の順位より大きい場合
1319        if( $position > $rank ) $term = "rank - 1";
1320
1321        //入れ替え先の順位が入れ換え元の順位より小さい場合
1322        if( $position < $rank ) $term = "rank + 1";
1323
1324        // XXX 入れ替え先の順位が入れ替え元の順位と同じ場合
1325        if (!isset($term)) $term = "rank";
1326
1327        // 指定した順位の商品から移動させる商品までのrankを1つずらす
1328        $sql = "UPDATE $tableName SET rank = $term WHERE rank BETWEEN ? AND ?";
1329        if($where != "") {
1330            $sql.= " AND $where";
1331        }
1332
1333        if( $position > $rank ) $objQuery->exec( $sql, array( $rank + 1, $position ));
1334        if( $position < $rank ) $objQuery->exec( $sql, array( $position, $rank - 1 ));
1335
1336        // 指定した順位へrankを書き換える。
1337        $sql  = "UPDATE $tableName SET rank = ? WHERE $keyIdColumn = ? ";
1338        if($where != "") {
1339            $sql.= " AND $where";
1340        }
1341
1342        $objQuery->exec( $sql, array( $position, $keyId ) );
1343        $objQuery->commit();
1344    }
1345
1346    /**
1347     * ランクを含むレコードを削除する.
1348     *
1349     * レコードごと削除する場合は、$deleteをtrueにする
1350     *
1351     * @param string $table テーブル名
1352     * @param string $colname カラム名
1353     * @param string|integer $id テーブルのキー
1354     * @param string $andwhere SQL の AND 条件である WHERE 句
1355     * @param bool $delete レコードごと削除する場合 true,
1356     *                     レコードごと削除しない場合 false
1357     * @return void
1358     */
1359    function sfDeleteRankRecord($table, $colname, $id, $andwhere = "",
1360                                $delete = false) {
1361        $objQuery =& SC_Query::getSingletonInstance();
1362        $objQuery->begin();
1363        // 削除レコードのランクを取得する。
1364        $where = "$colname = ?";
1365        if($andwhere != "") {
1366            $where.= " AND $andwhere";
1367        }
1368        $rank = $objQuery->get("rank", $table, $where, array($id));
1369
1370        if(!$delete) {
1371            // ランクを最下位にする、DELフラグON
1372            $sqlup = "UPDATE $table SET rank = 0, del_flg = 1 ";
1373            $sqlup.= "WHERE $colname = ?";
1374            // UPDATEの実行
1375            $objQuery->exec($sqlup, array($id));
1376        } else {
1377            $objQuery->delete($table, "$colname = ?", array($id));
1378        }
1379
1380        // 追加レコードのランクより上のレコードを一つずらす。
1381        $where = "rank > ?";
1382        if($andwhere != "") {
1383            $where.= " AND $andwhere";
1384        }
1385        $sqlup = "UPDATE $table SET rank = (rank - 1) WHERE $where";
1386        $objQuery->exec($sqlup, array($rank));
1387        $objQuery->commit();
1388    }
1389
1390    /**
1391     * 親IDの配列を元に特定のカラムを取得する.
1392     *
1393     * @param SC_Query $objQuery SC_Query インスタンス
1394     * @param string $table テーブル名
1395     * @param string $id_name ID名
1396     * @param string $col_name カラム名
1397     * @param array $arrId IDの配列
1398     * @return array 特定のカラムの配列
1399     */
1400    function sfGetParentsCol($objQuery, $table, $id_name, $col_name, $arrId ) {
1401        $col = $col_name;
1402        $len = count($arrId);
1403        $where = "";
1404
1405        for($cnt = 0; $cnt < $len; $cnt++) {
1406            if($where == "") {
1407                $where = "$id_name = ?";
1408            } else {
1409                $where.= " OR $id_name = ?";
1410            }
1411        }
1412
1413        $objQuery->setOrder("level");
1414        $arrRet = $objQuery->select($col, $table, $where, $arrId);
1415        return $arrRet;
1416    }
1417
1418    /**
1419     * カテゴリ変更時の移動処理を行う.
1420     *
1421     * @param SC_Query $objQuery SC_Query インスタンス
1422     * @param string $table テーブル名
1423     * @param string $id_name ID名
1424     * @param string $cat_name カテゴリ名
1425     * @param integer $old_catid 旧カテゴリID
1426     * @param integer $new_catid 新カテゴリID
1427     * @param integer $id ID
1428     * @return void
1429     */
1430    function sfMoveCatRank($objQuery, $table, $id_name, $cat_name, $old_catid, $new_catid, $id) {
1431        if ($old_catid == $new_catid) {
1432            return;
1433        }
1434        // 旧カテゴリでのランク削除処理
1435        // 移動レコードのランクを取得する。
1436        $where = "$id_name = ?";
1437        $rank = $objQuery->get("rank", $table, $where, array($id));
1438        // 削除レコードのランクより上のレコードを一つ下にずらす。
1439        $where = "rank > ? AND $cat_name = ?";
1440        $sqlup = "UPDATE $table SET rank = (rank - 1) WHERE $where";
1441        $objQuery->exec($sqlup, array($rank, $old_catid));
1442        // 新カテゴリでの登録処理
1443        // 新カテゴリの最大ランクを取得する。
1444        $max_rank = $objQuery->max("rank", $table, "$cat_name = ?", array($new_catid)) + 1;
1445        $where = "$id_name = ?";
1446        $sqlup = "UPDATE $table SET rank = ? WHERE $where";
1447        $objQuery->exec($sqlup, array($max_rank, $id));
1448    }
1449
1450    /**
1451     * FIXME 商品種別からお届け時間を取得する.
1452     *
1453     * @param integer $productTypeId 商品種別ID
1454     * @return array お届け時間の配列
1455     * @deprecated SC_Purchase::getDelivTime() を使用して下さい
1456     */
1457    function sfGetDelivTime($productTypeId) {
1458        $objQuery =& SC_Query::getSingletonInstance();
1459
1460        $deliv_id = "";
1461        $arrRet = array();
1462
1463        if($payment_id != "") {
1464            $where = "del_flg = 0 AND product_type_id = ?";
1465            $arrRet = $objQuery->select("deliv_id", "dtb_payment", $where, array($productTypeId));
1466            $deliv_id = $arrRet[0]['deliv_id'];
1467        }
1468
1469        if($deliv_id != "") {
1470            $objQuery->setOrder("time_id");
1471            $where = "deliv_id = ?";
1472            $arrRet= $objQuery->select("time_id, deliv_time", "dtb_delivtime", $where, array($deliv_id));
1473        }
1474
1475        return $arrRet;
1476    }
1477
1478    /**
1479     * 都道府県、支払い方法から配送料金を取得する.
1480     *
1481     * @param array $arrData 各種情報
1482     * @return string 指定の都道府県, 支払い方法の配送料金
1483     */
1484    function sfGetDelivFee($pref_id, $product_type_id) {
1485        $objQuery =& SC_Query::getSingletonInstance();
1486
1487        // 配送業者から配送料を取得
1488        if($deliv_id != "") {
1489
1490            // 都道府県が指定されていない場合は、東京都の番号を指定しておく
1491            if($pref_id == "") {
1492                $pref_id = 13;
1493            }
1494
1495            $objQuery =& SC_Query::getSingletonInstance();
1496            $where = "product_type_id = ? AND pref = ?";
1497            $arrRet= $objQuery->select("fee", "dtb_delivfee", $where, array($product_type_id, $pref_id));
1498        }
1499        return $arrRet[0]['fee'];
1500    }
1501
1502    /**
1503     * 集計情報を元に最終計算を行う.
1504     *
1505     * @param array $arrData 各種情報
1506     * @param LC_Page $objPage LC_Page インスタンス
1507     * @param SC_CartSession $objCartSess SC_CartSession インスタンス
1508     * @param null $dummy1 互換性確保用(決済モジュール互換のため)
1509     * @param SC_Customer $objCustomer SC_Customer インスタンス
1510     * @return array 最終計算後の配列
1511     * @deprecated SC_CartSession::calculate() を使用して下さい
1512     */
1513    function sfTotalConfirm($arrData, &$objPage, &$objCartSess, $dummy1 = null, $objCustomer = "", $key = "") {
1514        // 店舗基本情報を取得する
1515        $arrInfo = SC_Helper_DB_Ex::sfGetBasisData();
1516
1517        // 未定義変数を定義
1518        if (!isset($arrData['deliv_pref'])) $arrData['deliv_pref'] = "";
1519        if (!isset($arrData['payment_id'])) $arrData['payment_id'] = "";
1520        if (!isset($arrData['charge'])) $arrData['charge'] = "";
1521        if (!isset($arrData['use_point'])) $arrData['use_point'] = "";
1522        if (!isset($arrData['add_point'])) $arrData['add_point'] = 0;
1523
1524        // 税金の取得
1525        $arrData['tax'] = $objPage->tpl_total_tax[$key];
1526        // 小計の取得
1527        $arrData['subtotal'] = $objPage->tpl_total_inctax[$key];
1528
1529        // 合計送料の取得
1530        $arrData['deliv_fee'] = 0;
1531
1532        // 商品ごとの送料が有効の場合
1533        if (OPTION_PRODUCT_DELIV_FEE == 1) {
1534            // 全商品の合計送料を加算する
1535            $this->lfAddAllProductsDelivFee($arrData, $objPage, $objCartSess);
1536        }
1537
1538        // 配送業者の送料が有効の場合
1539        if (OPTION_DELIV_FEE == 1) {
1540            // 都道府県、支払い方法から配送料金を加算する
1541            // FIXME ここでしか使ってない
1542            $this->lfAddDelivFee($arrData);
1543        }
1544
1545        // 送料無料の購入数が設定されている場合
1546        if (DELIV_FREE_AMOUNT > 0) {
1547            // 商品の合計数量
1548            $total_quantity = $objCartSess->getTotalQuantity(true);
1549
1550            if($total_quantity >= DELIV_FREE_AMOUNT) {
1551                $arrData['deliv_fee'] = 0;
1552            }
1553        }
1554
1555        // ダウンロード商品のみの場合は送料無料
1556        if($this->chkCartDown($objCartSess)==2){
1557            $arrData['deliv_fee'] = 0;
1558        }
1559
1560        // 送料無料条件が設定されている場合
1561        if($arrInfo['free_rule'] > 0) {
1562            // 小計が無料条件を超えている場合
1563            if($arrData['subtotal'] >= $arrInfo['free_rule']) {
1564                $arrData['deliv_fee'] = 0;
1565            }
1566        }
1567
1568        // 合計の計算
1569        $arrData['total'] = $objPage->tpl_total_inctax[$key]; // 商品合計
1570        $arrData['total']+= $arrData['deliv_fee'];      // 送料
1571        $arrData['total']+= $arrData['charge'];         // 手数料
1572        // お支払い合計
1573        $arrData['payment_total'] = $arrData['total'] - ($arrData['use_point'] * POINT_VALUE);
1574        // 加算ポイントの計算
1575        if (USE_POINT !== false) {
1576            $arrData['add_point'] = SC_Helper_DB_Ex::sfGetAddPoint($objPage->tpl_total_point[$key], $arrData['use_point']);
1577
1578            if($objCustomer != "") {
1579                // 誕生日月であった場合
1580                if($objCustomer->isBirthMonth()) {
1581                    $arrData['birth_point'] = BIRTH_MONTH_POINT;
1582                    $arrData['add_point'] += $arrData['birth_point'];
1583                }
1584            }
1585        }
1586
1587        if($arrData['add_point'] < 0) {
1588            $arrData['add_point'] = 0;
1589        }
1590        return $arrData;
1591    }
1592
1593    /**
1594     * レコードの存在チェックを行う.
1595     *
1596     * @param string $table テーブル名
1597     * @param string $col カラム名
1598     * @param array $arrval 要素の配列
1599     * @param array $addwhere SQL の AND 条件である WHERE 句
1600     * @return bool レコードが存在する場合 true
1601     */
1602    function sfIsRecord($table, $col, $arrval, $addwhere = "") {
1603        $objQuery =& SC_Query::getSingletonInstance();
1604        $arrCol = split("[, ]", $col);
1605
1606        $where = "del_flg = 0";
1607
1608        if($addwhere != "") {
1609            $where.= " AND $addwhere";
1610        }
1611
1612        foreach($arrCol as $val) {
1613            if($val != "") {
1614                if($where == "") {
1615                    $where = "$val = ?";
1616                } else {
1617                    $where.= " AND $val = ?";
1618                }
1619            }
1620        }
1621        $ret = $objQuery->get($col, $table, $where, $arrval);
1622
1623        if($ret != "") {
1624            return true;
1625        }
1626        return false;
1627    }
1628
1629    /**
1630     * メーカー商品数数の登録を行う.
1631     *
1632     * @param SC_Query $objQuery SC_Query インスタンス
1633     * @return void
1634     */
1635    function sfMaker_Count($objQuery){
1636        $sql = "";
1637
1638        //テーブル内容の削除
1639        $objQuery->query("DELETE FROM dtb_maker_count");
1640
1641        //各メーカーの商品数を数えて格納
1642        $sql = " INSERT INTO dtb_maker_count(maker_id, product_count, create_date) ";
1643        $sql .= " SELECT T1.maker_id, count(T2.maker_id), now() ";
1644        $sql .= " FROM dtb_maker AS T1 LEFT JOIN dtb_products AS T2";
1645        $sql .= " ON T1.maker_id = T2.maker_id ";
1646        $sql .= " WHERE T2.del_flg = 0 AND T2.status = 1 ";
1647        $sql .= " GROUP BY T1.maker_id, T2.maker_id ";
1648        $objQuery->query($sql);
1649    }
1650
1651    /**
1652     * 選択中の商品のメーカーを取得する.
1653     *
1654     * @param integer $product_id プロダクトID
1655     * @param integer $maker_id メーカーID
1656     * @return array 選択中の商品のメーカーIDの配列
1657     *
1658     */
1659    function sfGetMakerId($product_id, $maker_id = 0, $closed = false) {
1660        if ($closed) {
1661            $status = "";
1662        } else {
1663            $status = "status = 1";
1664        }
1665
1666        if (!$this->g_maker_on) {
1667            $this->g_maker_on = true;
1668            $maker_id = (int) $maker_id;
1669            $product_id = (int) $product_id;
1670            if (SC_Utils_Ex::sfIsInt($maker_id) && $maker_id != 0 && $this->sfIsRecord("dtb_maker","maker_id", $maker_id)) {
1671                $this->g_maker_id = array($maker_id);
1672            } else if (SC_Utils_Ex::sfIsInt($product_id) && $product_id != 0 && $this->sfIsRecord("dtb_products","product_id", $product_id, $status)) {
1673                $objQuery =& SC_Query::getSingletonInstance();
1674                $where = "product_id = ?";
1675                $maker_id = $objQuery->getCol("maker_id", "dtb_products", "product_id = ?", array($product_id));
1676                $this->g_maker_id = $maker_id;
1677            } else {
1678                // 不正な場合は、空の配列を返す。
1679                $this->g_maker_id = array();
1680            }
1681        }
1682        return $this->g_maker_id;
1683    }
1684
1685    /**
1686     * メーカーの取得を行う.
1687     *
1688     * $products_check:true商品登録済みのものだけ取得する
1689     *
1690     * @param string $addwhere 追加する WHERE 句
1691     * @param bool $products_check 商品の存在するカテゴリのみ取得する場合 true
1692     * @return array カテゴリツリーの配列
1693     */
1694    function sfGetMakerList($addwhere = "", $products_check = false) {
1695        $objQuery =& SC_Query::getSingletonInstance();
1696        $where = "del_flg = 0";
1697
1698        if($addwhere != "") {
1699            $where.= " AND $addwhere";
1700        }
1701
1702        $objQuery->setOption("ORDER BY rank DESC");
1703
1704        if($products_check) {
1705            $col = "T1.maker_id, name";
1706            $from = "dtb_maker AS T1 LEFT JOIN dtb_maker_count AS T2 ON T1.maker_id = T2.maker_id";
1707            $where .= " AND product_count > 0";
1708        } else {
1709            $col = "maker_id, name";
1710            $from = "dtb_maker";
1711        }
1712
1713        $arrRet = $objQuery->select($col, $from, $where);
1714
1715        $max = count($arrRet);
1716        for($cnt = 0; $cnt < $max; $cnt++) {
1717            $id = $arrRet[$cnt]['maker_id'];
1718            $name = $arrRet[$cnt]['name'];
1719            $arrList[$id] = $name;
1720        }
1721        return $arrList;
1722    }
1723
1724    /**
1725     * 全商品の合計送料を加算する
1726     */
1727    function lfAddAllProductsDelivFee(&$arrData, &$objPage, &$objCartSess) {
1728        $arrData['deliv_fee'] += $this->lfCalcAllProductsDelivFee($arrData, $objCartSess);
1729    }
1730
1731    /**
1732     * 全商品の合計送料を計算する
1733     */
1734    function lfCalcAllProductsDelivFee(&$arrData, &$objCartSess) {
1735        $objQuery =& SC_Query::getSingletonInstance();
1736        $deliv_fee_total = 0;
1737        $max = $objCartSess->getMax();
1738        for ($i = 0; $i <= $max; $i++) {
1739            // 商品送料
1740            $deliv_fee = $objQuery->getOne('SELECT deliv_fee FROM dtb_products WHERE product_id = ?', array($_SESSION[$objCartSess->key][$i]['id'][0]));
1741            // 数量
1742            $quantity = $_SESSION[$objCartSess->key][$i]['quantity'];
1743            // 累積
1744            $deliv_fee_total += $deliv_fee * $quantity;
1745        }
1746        return $deliv_fee_total;
1747    }
1748
1749    /**
1750     * 都道府県、支払い方法から配送料金を加算する.
1751     *
1752     * @param array $arrData 各種情報
1753     */
1754    function lfAddDelivFee(&$arrData) {
1755        $arrData['deliv_fee'] += $this->sfGetDelivFee($arrData);
1756    }
1757
1758    /**
1759     * 受注の名称列を更新する
1760     *
1761     * @param integer $order_id 更新対象の注文番号
1762     * @param boolean $temp_table 更新対象は「受注_Temp」か
1763     * @static
1764     */
1765    function sfUpdateOrderNameCol($order_id, $temp_table = false) {
1766        $objQuery =& SC_Query::getSingletonInstance();
1767
1768        if ($temp_table) {
1769            $tgt_table = 'dtb_order_temp';
1770            $sql_where = 'WHERE order_temp_id = ?';
1771        } else {
1772            $tgt_table = 'dtb_order';
1773            $sql_where = 'WHERE order_id = ?';
1774        }
1775
1776        $sql = <<< __EOS__
1777            UPDATE
1778                {$tgt_table}
1779            SET
1780                 payment_method = (SELECT payment_method FROM dtb_payment WHERE payment_id = {$tgt_table}.payment_id)
1781                ,deliv_time = (SELECT deliv_time FROM dtb_delivtime WHERE time_id = {$tgt_table}.deliv_time_id AND deliv_id = {$tgt_table}.deliv_id)
1782            $sql_where
1783__EOS__;
1784
1785        $objQuery->query($sql, array($order_id));
1786    }
1787
1788    /**
1789     * 店舗基本情報に基づいて税金額を返す
1790     *
1791     * @param integer $price 計算対象の金額
1792     * @return integer 税金額
1793     */
1794    function sfTax($price) {
1795        // 店舗基本情報を取得
1796        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1797
1798        return SC_Utils_Ex::sfTax($price, $CONF['tax'], $CONF['tax_rule']);
1799    }
1800
1801    /**
1802     * 店舗基本情報に基づいて税金付与した金額を返す
1803     *
1804     * @param integer $price 計算対象の金額
1805     * @return integer 税金付与した金額
1806     */
1807    function sfCalcIncTax($price, $tax = null, $tax_rule = null) {
1808        // 店舗基本情報を取得
1809        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1810
1811        return SC_Utils_Ex::sfCalcIncTax($price, $CONF['tax'], $CONF['tax_rule']);
1812    }
1813
1814    /**
1815     * 店舗基本情報に基づいて加算ポイントを返す
1816     *
1817     * @param integer $totalpoint
1818     * @param integer $use_point
1819     * @return integer 加算ポイント
1820     */
1821    function sfGetAddPoint($totalpoint, $use_point) {
1822        // 店舗基本情報を取得
1823        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1824
1825        return SC_Utils_Ex::sfGetAddPoint($totalpoint, $use_point, $CONF['point_rate']);
1826    }
1827
1828    /**
1829     * 受注.対応状況の更新
1830     *
1831     * ・必ず呼び出し元でトランザクションブロックを開いておくこと。
1832     *
1833     * @param integer $orderId 注文番号
1834     * @param integer|null $newStatus 対応状況 (null=変更無し)
1835     * @param integer|null $newAddPoint 加算ポイント (null=変更無し)
1836     * @param integer|null $newUsePoint 使用ポイント (null=変更無し)
1837     * @return void
1838     */
1839    function sfUpdateOrderStatus($orderId, $newStatus = null, $newAddPoint = null, $newUsePoint = null) {
1840        $objQuery =& SC_Query::getSingletonInstance();
1841
1842        $arrOrderOld = $objQuery->getRow('status, add_point, use_point, customer_id', 'dtb_order', 'order_id = ?', array($orderId));
1843
1844        // 対応状況が変更無しの場合、DB値を引き継ぐ
1845        if (is_null($newStatus)) {
1846            $newStatus = $arrOrderOld['status'];
1847        }
1848
1849        // 使用ポイント、DB値を引き継ぐ
1850        if (is_null($newUsePoint)) {
1851            $newUsePoint = $arrOrderOld['use_point'];
1852        }
1853
1854        // 加算ポイント、DB値を引き継ぐ
1855        if (is_null($newAddPoint)) {
1856            $newAddPoint = $arrOrderOld['add_point'];
1857        }
1858
1859        if (USE_POINT !== false) {
1860            // 顧客.ポイントの加減値
1861            $addCustomerPoint = 0;
1862
1863            // ▼使用ポイント
1864            // 変更前の対応状況が利用対象の場合、変更前の使用ポイント分を戻す
1865            if (SC_Utils_Ex::sfIsUsePoint($arrOrderOld['status'])) {
1866                $addCustomerPoint += $arrOrderOld['use_point'];
1867            }
1868
1869            // 変更後の対応状況が利用対象の場合、変更後の使用ポイント分を引く
1870            if (SC_Utils_Ex::sfIsUsePoint($newStatus)) {
1871                $addCustomerPoint -= $newUsePoint;
1872            }
1873            // ▲使用ポイント
1874
1875            // ▼加算ポイント
1876            // 変更前の対応状況が加算対象の場合、変更前の加算ポイント分を戻す
1877            if (SC_Utils_Ex::sfIsAddPoint($arrOrderOld['status'])) {
1878                $addCustomerPoint -= $arrOrderOld['add_point'];
1879            }
1880
1881            // 変更後の対応状況が加算対象の場合、変更後の加算ポイント分を足す
1882            if (SC_Utils_Ex::sfIsAddPoint($newStatus)) {
1883                $addCustomerPoint += $newAddPoint;
1884            }
1885            // ▲加算ポイント
1886
1887            if ($addCustomerPoint != 0) {
1888                // ▼顧客テーブルの更新
1889                $sqlval = array();
1890                $where = '';
1891                $arrVal = array();
1892                $arrRawSql = array();
1893                $arrRawSqlVal = array();
1894
1895                $sqlval['update_date'] = 'Now()';
1896                $arrRawSql['point'] = 'point + ?';
1897                $arrRawSqlVal[] = $addCustomerPoint;
1898                $where .= 'customer_id = ?';
1899                $arrVal[] = $arrOrderOld['customer_id'];
1900
1901                $objQuery->update('dtb_customer', $sqlval, $where, $arrVal, $arrRawSql, $arrRawSqlVal);
1902                // ▲顧客テーブルの更新
1903
1904                // 顧客.ポイントをマイナスした場合、
1905                if ($addCustomerPoint < 0) {
1906                    $sql = 'SELECT point FROM dtb_customer WHERE customer_id = ?';
1907                    $point = $objQuery->getOne($sql, array($arrOrderOld['customer_id']));
1908                    // 変更後の顧客.ポイントがマイナスの場合、
1909                    if ($point < 0) {
1910                        // ロールバック
1911                        $objQuery->rollback();
1912                        // エラー
1913                        SC_Utils_Ex::sfDispSiteError(LACK_POINT);
1914                    }
1915                }
1916            }
1917        }
1918
1919        // ▼受注テーブルの更新
1920        $sqlval = array();
1921        if (USE_POINT !== false) {
1922            $sqlval['add_point'] = $newAddPoint;
1923            $sqlval['use_point'] = $newUsePoint;
1924        }
1925        // ステータスが発送済みに変更の場合、発送日を更新
1926        if ($arrOrderOld['status'] != ORDER_DELIV && $newStatus == ORDER_DELIV) {
1927            $sqlval['commit_date'] = 'Now()';
1928        }
1929        // ステータスが入金済みに変更の場合、入金日を更新
1930        elseif ($arrOrderOld['status'] != ORDER_PRE_END && $newStatus == ORDER_PRE_END) {
1931            $sqlval['payment_date'] = 'Now()';
1932        }
1933
1934        $sqlval['status'] = $newStatus;
1935        $sqlval['update_date'] = 'Now()';
1936
1937        $objQuery->update('dtb_order', $sqlval, 'order_id = ?', array($orderId));
1938        // ▲受注テーブルの更新
1939    }
1940
1941    /**
1942     * 指定ファイルが存在する場合 SQL として実行
1943     *
1944     * XXX プラグイン用に追加。将来消すかも。
1945     *
1946     * @param string $sqlFilePath SQL ファイルのパス
1947     * @return void
1948     */
1949    function sfExecSqlByFile($sqlFilePath) {
1950        if (file_exists($sqlFilePath)) {
1951            $objQuery =& SC_Query::getSingletonInstance();
1952
1953            $sqls = file_get_contents($sqlFilePath);
1954            if ($sqls === false) SC_Utils_Ex::sfDispException('ファイルは存在するが読み込めない');
1955
1956            foreach (explode(';', $sqls) as $sql) {
1957                $sql = trim($sql);
1958                if (strlen($sql) == 0) continue;
1959                $objQuery->query($sql);
1960            }
1961        }
1962    }
1963
1964    /**
1965     * 商品規格を設定しているか
1966     *
1967     * @param integer $product_id 商品ID
1968     * @return bool 商品規格が存在する場合:true, それ以外:false
1969     */
1970    function sfHasProductClass($product_id) {
1971        if (!SC_Utils_Ex::sfIsInt($product_id)) return false;
1972
1973        $objQuery =& SC_Query::getSingletonInstance();
1974        $where = 'product_id = ? AND class_combination_id IS NOT NULL';
1975        $count = $objQuery->count('dtb_products_class', $where, array($product_id));
1976
1977        return $count >= 1;
1978    }
1979    /**
1980     * カート内の商品の販売方法判定処理
1981     *
1982     * @param $objCartSess  SC_CartSession  カートセッション
1983     * @return  bool        0:実商品のみ 1:ダウンロード販売と実商品混在 2:全てダウンロード販売
1984     */
1985    function chkCartDown(&$objCartSess, $cartKey = 1) {
1986        $objQuery =& SC_Query::getSingletonInstance();
1987        $down = false;
1988        $nodown = false;
1989        $ret = 0;
1990        $arrID = $objCartSess->getAllProductID();
1991        $table = "dtb_products_class pc";
1992        $where = "pc.product_class_id = ?";
1993        if(!is_null($arrID)){
1994            //カート内のIDから販売方法を取得
1995            foreach ($arrID as $rec) {
1996                $arrRet = $objQuery->select("pc.down AS down", $table, $where, array($rec));
1997                if ($arrRet[0]['down'] == "2"){
1998                    $down = true;
1999                }else{
2000                    $nodown = true;
2001                }
2002            }
2003        }
2004        //混在
2005        if($nodown && $down){
2006            $ret = 1;
2007        //全てダウンロード商品
2008        }else if(!$nodown && $down){
2009            $ret = 2;
2010        }
2011        return $ret;
2012    }
2013
2014    /* 会員情報の住所を一時受注テーブルへ */
2015    function sfRegistDelivData($uniqid, $objCustomer) {
2016
2017        // 登録データの作成
2018        $sqlval['order_temp_id'] = $uniqid;
2019        $sqlval['update_date'] = 'Now()';
2020        $sqlval['customer_id'] = $objCustomer->getValue('customer_id');
2021        $sqlval['deliv_check'] = '-1';
2022        $sqlval['order_name01'] = $objCustomer->getValue('name01');
2023        $sqlval['order_name02'] = $objCustomer->getValue('name02');
2024        $sqlval['order_kana01'] = $objCustomer->getValue('kana01');
2025        $sqlval['order_kana02'] = $objCustomer->getValue('kana02');
2026        $sqlval['order_zip01'] = $objCustomer->getValue('zip01');
2027        $sqlval['order_zip02'] = $objCustomer->getValue('zip02');
2028        $sqlval['order_pref'] = $objCustomer->getValue('pref');
2029        $sqlval['order_addr01'] = $objCustomer->getValue('addr01');
2030        $sqlval['order_addr02'] = $objCustomer->getValue('addr02');
2031        $sqlval['order_tel01'] = $objCustomer->getValue('tel01');
2032        $sqlval['order_tel02'] = $objCustomer->getValue('tel02');
2033        $sqlval['order_tel03'] = $objCustomer->getValue('tel03');
2034        $sqlval['order_fax01'] = $objCustomer->getValue('fax01');
2035        $sqlval['order_fax02'] = $objCustomer->getValue('fax02');
2036        $sqlval['order_fax03'] = $objCustomer->getValue('fax03');
2037        $sqlval['deliv_name01'] = $objCustomer->getValue('name01');
2038        $sqlval['deliv_name02'] = $objCustomer->getValue('name02');
2039        $sqlval['deliv_kana01'] = $objCustomer->getValue('kana01');
2040        $sqlval['deliv_kana02'] = $objCustomer->getValue('kana02');
2041        $sqlval['deliv_zip01'] = $objCustomer->getValue('zip01');
2042        $sqlval['deliv_zip02'] = $objCustomer->getValue('zip02');
2043        $sqlval['deliv_pref'] = $objCustomer->getValue('pref');
2044        $sqlval['deliv_addr01'] = $objCustomer->getValue('addr01');
2045        $sqlval['deliv_addr02'] = $objCustomer->getValue('addr02');
2046        $sqlval['deliv_tel01'] = $objCustomer->getValue('tel01');
2047        $sqlval['deliv_tel02'] = $objCustomer->getValue('tel02');
2048        $sqlval['deliv_tel03'] = $objCustomer->getValue('tel03');
2049        $sqlval['deliv_fax01'] = $objCustomer->getValue('fax01');
2050        $sqlval['deliv_fax02'] = $objCustomer->getValue('fax02');
2051        $sqlval['deliv_fax03'] = $objCustomer->getValue('fax03');
2052
2053        $this->sfRegistTempOrder($uniqid, $sqlval);
2054    }
2055}
2056?>
Note: See TracBrowser for help on using the repository browser.