source: branches/version-2_13-dev/data/class/helper/SC_Helper_DB.php @ 23459

Revision 23459, 54.6 KB checked in by pineray, 10 years ago (diff)

#2515 無駄な処理を改善する for 2.13.3

カテゴリーID取得部分の処理を整理.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
  • 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-2013 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    /** ルートカテゴリ取得フラグ */
34    public $g_root_on;
35
36    /** ルートカテゴリID */
37    public $g_root_id;
38
39    /** 選択中カテゴリ取得フラグ */
40    public $g_category_on;
41
42    /** 選択中カテゴリID */
43    public $g_category_id;
44
45    /**
46     * カラムの存在チェックと作成を行う.
47     *
48     * チェック対象のテーブルに, 該当のカラムが存在するかチェックする.
49     * 引数 $add が true の場合, 該当のカラムが存在しない場合は, カラムの生成を行う.
50     * カラムの生成も行う場合は, $col_type も必須となる.
51     *
52     * @param  string $$tableName  テーブル名
53     * @param  string $column_name カラム名
54     * @param  string $col_type    カラムのデータ型
55     * @param  string $dsn         データソース名
56     * @param  bool   $add         カラムの作成も行う場合 true
57     * @return bool   カラムが存在する場合とカラムの生成に成功した場合 true,
58     *               テーブルが存在しない場合 false,
59     *               引数 $add == false でカラムが存在しない場合 false
60     */
61    public function sfColumnExists($tableName, $colName, $colType = '', $dsn = '', $add = false)
62    {
63        $dbFactory = SC_DB_DBFactory_Ex::getInstance();
64        $dsn = $dbFactory->getDSN($dsn);
65
66        $objQuery =& SC_Query_Ex::getSingletonInstance($dsn);
67
68        // テーブルが無ければエラー
69        if (!in_array($tableName, $objQuery->listTables())) return false;
70
71        // 正常に接続されている場合
72        if (!$objQuery->isError()) {
73            // カラムリストを取得
74            $columns = $objQuery->listTableFields($tableName);
75
76            if (in_array($colName, $columns)) {
77                return true;
78            }
79        }
80
81        // カラムを追加する
82        if ($add) {
83            return $this->sfColumnAdd($tableName, $colName, $colType);
84        }
85
86        return false;
87    }
88
89    public function sfColumnAdd($tableName, $colName, $colType)
90    {
91        $objQuery =& SC_Query_Ex::getSingletonInstance($dsn);
92
93        return $objQuery->query("ALTER TABLE $tableName ADD $colName $colType ");
94    }
95
96    /**
97     * データの存在チェックを行う.
98     *
99     * @param  string $tableName   テーブル名
100     * @param  string $where       データを検索する WHERE 句
101     * @param  array  $arrWhereVal WHERE句のプレースホルダ値
102     * @return bool   データが存在する場合 true, データの追加に成功した場合 true,
103     *               $add == false で, データが存在しない場合 false
104     */
105    public static function sfDataExists($tableName, $where, $arrWhereVal)
106    {
107        $dbFactory = SC_DB_DBFactory_Ex::getInstance();
108        $dsn = $dbFactory->getDSN($dsn);
109
110        $objQuery =& SC_Query_Ex::getSingletonInstance();
111        $exists = $objQuery->exists($tableName, $where, $arrWhereVal);
112
113        // データが存在する場合 TRUE
114        if ($exists) {
115            return TRUE;
116        } else {
117            return FALSE;
118        }
119    }
120
121    /**
122     * 店舗基本情報を取得する.
123     *
124     * 引数 $force が false の場合は, 初回のみ DB 接続し,
125     * 2回目以降はキャッシュされた結果を使用する.
126     *
127     * @param  boolean $force 強制的にDB取得するか
128     * @return array   店舗基本情報の配列
129     */
130    public function sfGetBasisData($force = false)
131    {
132        static $arrData = null;
133
134        if ($force || is_null($arrData)) {
135            $objQuery =& SC_Query_Ex::getSingletonInstance();
136
137            $arrData = $objQuery->getRow('*', 'dtb_baseinfo');
138        }
139
140        return $arrData;
141    }
142
143    /**
144     * 基本情報のキャッシュデータを取得する
145     *
146     * @param  boolean $generate キャッシュファイルが無い時、DBのデータを基にキャッシュを生成するか
147     * @return array   店舗基本情報の配列
148     */
149    public function sfGetBasisDataCache($generate = false)
150    {
151        // テーブル名
152        $name = 'dtb_baseinfo';
153        // キャッシュファイルパス
154        $filepath = MASTER_DATA_REALDIR . $name . '.serial';
155        // ファイル存在確認
156        if (!file_exists($filepath) && $generate) {
157            // 存在していなければキャッシュ生成
158            $this->sfCreateBasisDataCache();
159        }
160        // 戻り値初期化
161        $cacheData = array();
162        // キャッシュファイルが存在すれば読み込む
163        if (file_exists($filepath)) {
164            // キャッシュデータファイルを読み込みアンシリアライズした配列を取得
165            $cacheData = unserialize(file_get_contents($filepath));
166        }
167        // return
168        return $cacheData;
169    }
170
171    /**
172     * 基本情報のキャッシュデータファイルを生成する
173     * データはsfGetBasisDataより取得。
174     *
175     * このメソッドが直接呼ばれるのは、
176     *「基本情報管理>SHOPマスター」の更新完了後。
177     * sfGetBasisDataCacheでは、
178     * キャッシュデータファイルが無い場合に呼ばれます。
179     *
180     * @return bool キャッシュデータファイル生成結果
181     */
182    public function sfCreateBasisDataCache()
183    {
184        // テーブル名
185        $name = 'dtb_baseinfo';
186        // キャッシュファイルパス
187        $filepath = MASTER_DATA_REALDIR . $name . '.serial';
188        // データ取得
189        $arrData = $this->sfGetBasisData(true);
190        // シリアライズ
191        $data = serialize($arrData);
192        // ファイルを書き出しモードで開く
193        $handle = fopen($filepath, 'w');
194        if (!$handle) {
195            // ファイル生成失敗
196            return false;
197        }
198        // ファイルの内容を書き出す.
199        $res = fwrite($handle, $data);
200        // ファイルを閉じる
201        fclose($handle);
202        if ($res === false) {
203            // ファイル生成失敗
204            return false;
205        }
206        // ファイル生成成功
207        return true;
208    }
209
210    /**
211     * 基本情報の登録数を取得する
212     *
213     * @return int
214     * @deprecated
215     */
216    public function sfGetBasisCount()
217    {
218        $objQuery =& SC_Query_Ex::getSingletonInstance();
219
220        return $objQuery->count('dtb_baseinfo');
221    }
222
223    /**
224     * 基本情報の登録有無を取得する
225     *
226     * @return boolean 有無
227     */
228    public function sfGetBasisExists()
229    {
230        $objQuery =& SC_Query_Ex::getSingletonInstance();
231
232        return $objQuery->exists('dtb_baseinfo');
233    }
234
235    /* 選択中のアイテムのルートカテゴリIDを取得する */
236    public function sfGetRootId()
237    {
238        if (!$this->g_root_on) {
239            $this->g_root_on = true;
240
241            if (!isset($_GET['product_id'])) $_GET['product_id'] = '';
242            if (!isset($_GET['category_id'])) $_GET['category_id'] = '';
243
244            if (!empty($_GET['product_id']) || !empty($_GET['category_id'])) {
245                // 選択中のカテゴリIDを判定する
246                $category_id = $this->sfGetCategoryId($_GET['product_id'], $_GET['category_id']);
247                // ROOTカテゴリIDの取得
248                if (count($category_id) > 0) {
249                    $arrRet = $this->sfGetParents('dtb_category', 'parent_category_id', 'category_id', $category_id);
250                    $root_id = isset($arrRet[0]) ? $arrRet[0] : '';
251                } else {
252                    $root_id = '';
253                }
254            } else {
255                // ROOTカテゴリIDをなしに設定する
256                $root_id = '';
257            }
258            $this->g_root_id = $root_id;
259        }
260
261        return $this->g_root_id;
262    }
263
264    /**
265     * 受注番号、最終ポイント、加算ポイント、利用ポイントから「オーダー前ポイント」を取得する
266     *
267     * @param  integer $order_id     受注番号
268     * @param  integer $use_point    利用ポイント
269     * @param  integer $add_point    加算ポイント
270     * @param  integer $order_status 対応状況
271     * @return array   オーダー前ポイントの配列
272     */
273    public function sfGetRollbackPoint($order_id, $use_point, $add_point, $order_status)
274    {
275        $objQuery =& SC_Query_Ex::getSingletonInstance();
276        $arrRet = $objQuery->select('customer_id', 'dtb_order', 'order_id = ?', array($order_id));
277        $customer_id = $arrRet[0]['customer_id'];
278        if ($customer_id != '' && $customer_id >= 1) {
279            $arrRet = $objQuery->select('point', 'dtb_customer', 'customer_id = ?', array($customer_id));
280            $point = $arrRet[0]['point'];
281            $rollback_point = $arrRet[0]['point'];
282
283            // 対応状況がポイント利用対象の場合、使用ポイント分を戻す
284            if (SC_Helper_Purchase_Ex::isUsePoint($order_status)) {
285                $rollback_point += $use_point;
286            }
287
288            // 対応状況がポイント加算対象の場合、加算ポイント分を戻す
289            if (SC_Helper_Purchase_Ex::isAddPoint($order_status)) {
290                $rollback_point -= $add_point;
291            }
292        } else {
293            $rollback_point = '';
294            $point = '';
295        }
296
297        return array($point, $rollback_point);
298    }
299
300    /**
301     * カテゴリツリーの取得を行う.
302     *
303     * @param  integer $parent_category_id 親カテゴリID
304     * @param  bool    $count_check        登録商品数のチェックを行う場合 true
305     * @return array   カテゴリツリーの配列
306     */
307    public function sfGetCatTree($parent_category_id, $count_check = false)
308    {
309        $objQuery =& SC_Query_Ex::getSingletonInstance();
310        $col = '';
311        $col .= ' cat.category_id,';
312        $col .= ' cat.category_name,';
313        $col .= ' cat.parent_category_id,';
314        $col .= ' cat.level,';
315        $col .= ' cat.rank,';
316        $col .= ' cat.creator_id,';
317        $col .= ' cat.create_date,';
318        $col .= ' cat.update_date,';
319        $col .= ' cat.del_flg, ';
320        $col .= ' ttl.product_count';
321        $from = 'dtb_category as cat left join dtb_category_total_count as ttl on ttl.category_id = cat.category_id';
322        // 登録商品数のチェック
323        if ($count_check) {
324            $where = 'del_flg = 0 AND product_count > 0';
325        } else {
326            $where = 'del_flg = 0';
327        }
328        $objQuery->setOption('ORDER BY rank DESC');
329        $arrRet = $objQuery->select($col, $from, $where);
330
331        $arrParentID = SC_Utils_Ex::getTreeTrail($parent_category_id, 'category_id', 'parent_category_id', $arrRet);
332
333        foreach ($arrRet as $key => $array) {
334            foreach ($arrParentID as $val) {
335                if ($array['category_id'] == $val) {
336                    $arrRet[$key]['display'] = 1;
337                    break;
338                }
339            }
340        }
341
342        return $arrRet;
343    }
344
345    /**
346     * カテゴリツリーを走査し, パンくずリスト用の配列を生成する.
347     *
348     * @param array カテゴリの配列
349     * @param integer $parent 上位カテゴリID
350     * @param array パンくずリスト用の配列
351     * @result void
352     * @see sfGetCatTree()
353     */
354    public function findTree(&$arrTree, $parent, &$result)
355    {
356        if ($result[count($result) - 1]['parent_category_id'] === 0) {
357            return;
358        } else {
359            foreach ($arrTree as $val) {
360                if ($val['category_id'] == $parent) {
361                    $result[] = array(
362                        'category_id' => $val['category_id'],
363                        'parent_category_id' => (int) $val['parent_category_id'],
364                        'category_name' => $val['category_name'],
365                    );
366                    $this->findTree($arrTree, $val['parent_category_id'], $result);
367                }
368            }
369        }
370    }
371
372    /**
373     * 親カテゴリを連結した文字列を取得する.
374     *
375     * @param  integer $category_id カテゴリID
376     * @return string  親カテゴリを連結した文字列
377     */
378    public function sfGetCatCombName($category_id)
379    {
380        // 商品が属するカテゴリIDを縦に取得
381        $objQuery =& SC_Query_Ex::getSingletonInstance();
382        $arrCatID = $this->sfGetParents('dtb_category', 'parent_category_id', 'category_id', $category_id);
383        $ConbName = '';
384
385        // カテゴリ名称を取得する
386        foreach ($arrCatID as $val) {
387            $sql = 'SELECT category_name FROM dtb_category WHERE category_id = ?';
388            $arrVal = array($val);
389            $CatName = $objQuery->getOne($sql,$arrVal);
390            $ConbName .= $CatName . ' | ';
391        }
392        // 最後の | をカットする
393        $ConbName = substr_replace($ConbName, '', strlen($ConbName) - 2, 2);
394
395        return $ConbName;
396    }
397
398    /**
399     * 指定したカテゴリIDの大カテゴリを取得する.
400     *
401     * @param  integer $category_id カテゴリID
402     * @return array   指定したカテゴリIDの大カテゴリ
403     */
404    public function sfGetFirstCat($category_id)
405    {
406        // 商品が属するカテゴリIDを縦に取得
407        $objQuery =& SC_Query_Ex::getSingletonInstance();
408        $arrRet = array();
409        $arrCatID = $this->sfGetParents('dtb_category', 'parent_category_id', 'category_id', $category_id);
410        $arrRet['id'] = $arrCatID[0];
411
412        // カテゴリ名称を取得する
413        $sql = 'SELECT category_name FROM dtb_category WHERE category_id = ?';
414        $arrVal = array($arrRet['id']);
415        $arrRet['name'] = $objQuery->getOne($sql,$arrVal);
416
417        return $arrRet;
418    }
419
420    /**
421     * カテゴリツリーの取得を行う.
422     *
423     * $products_check:true商品登録済みのものだけ取得する
424     *
425     * @param  string $addwhere       追加する WHERE 句
426     * @param  bool   $products_check 商品の存在するカテゴリのみ取得する場合 true
427     * @param  string $head           カテゴリ名のプレフィックス文字列
428     * @return array  カテゴリツリーの配列
429     */
430    public function sfGetCategoryList($addwhere = '', $products_check = false, $head = CATEGORY_HEAD)
431    {
432        $objQuery =& SC_Query_Ex::getSingletonInstance();
433        $where = 'del_flg = 0';
434
435        if ($addwhere != '') {
436            $where.= " AND $addwhere";
437        }
438
439        $objQuery->setOption('ORDER BY rank DESC');
440
441        if ($products_check) {
442            $col = 'T1.category_id, category_name, level';
443            $from = 'dtb_category AS T1 LEFT JOIN dtb_category_total_count AS T2 ON T1.category_id = T2.category_id';
444            $where .= ' AND product_count > 0';
445        } else {
446            $col = 'category_id, category_name, level';
447            $from = 'dtb_category';
448        }
449
450        $arrRet = $objQuery->select($col, $from, $where);
451
452        $max = count($arrRet);
453        $arrList = array();
454        for ($cnt = 0; $cnt < $max; $cnt++) {
455            $id = $arrRet[$cnt]['category_id'];
456            $name = $arrRet[$cnt]['category_name'];
457            $arrList[$id] = str_repeat($head, $arrRet[$cnt]['level']) . $name;
458        }
459
460        return $arrList;
461    }
462
463    /**
464     * カテゴリツリーの取得を行う.
465     *
466     * 親カテゴリの Value=0 を対象とする
467     *
468     * @param  bool  $parent_zero 親カテゴリの Value=0 の場合 true
469     * @return array カテゴリツリーの配列
470     */
471    public function sfGetLevelCatList($parent_zero = true)
472    {
473        $objQuery =& SC_Query_Ex::getSingletonInstance();
474
475        // カテゴリ名リストを取得
476        $col = 'category_id, parent_category_id, category_name';
477        $where = 'del_flg = 0';
478        $objQuery->setOption('ORDER BY level');
479        $arrRet = $objQuery->select($col, 'dtb_category', $where);
480        $arrCatName = array();
481        foreach ($arrRet as $arrTmp) {
482            $arrCatName[$arrTmp['category_id']] =
483                (($arrTmp['parent_category_id'] > 0)?
484                    $arrCatName[$arrTmp['parent_category_id']] : '')
485                . CATEGORY_HEAD . $arrTmp['category_name'];
486        }
487
488        $col = 'category_id, parent_category_id, category_name, level';
489        $where = 'del_flg = 0';
490        $objQuery->setOption('ORDER BY rank DESC');
491        $arrRet = $objQuery->select($col, 'dtb_category', $where);
492        $max = count($arrRet);
493
494        $arrValue = array();
495        $arrOutput = array();
496        for ($cnt = 0; $cnt < $max; $cnt++) {
497            if ($parent_zero) {
498                if ($arrRet[$cnt]['level'] == LEVEL_MAX) {
499                    $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
500                } else {
501                    $arrValue[$cnt] = '';
502                }
503            } else {
504                $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
505            }
506
507            $arrOutput[$cnt] = $arrCatName[$arrRet[$cnt]['category_id']];
508        }
509
510        return array($arrValue, $arrOutput);
511    }
512
513    /**
514     * 選択中の商品のカテゴリを取得する.
515     *
516     * @param   int $product_id     プロダクトID
517     * @param   int $category_id    カテゴリID
518     * @param   bool $closed        非表示の商品を含む場合はtrue
519     * @return  array   選択中の商品のカテゴリIDの配列
520     *
521     */
522    public function sfGetCategoryId($product_id, $category_id = 0, $closed = false)
523    {
524        $category_id = (int) $category_id;
525        $product_id = (int) $product_id;
526        $objCategory = new SC_Helper_Category_Ex();
527        if ($objCategory->isValidCategoryId($category_id, $closed)) {
528            $category_id = array($category_id);
529        } else {
530            $objProduct = new SC_Product_Ex();
531            $category_id = $objProduct->getCategoryIds($product_id, $closed);
532        }
533
534        return $category_id;
535    }
536
537    /**
538     * 商品をカテゴリの先頭に追加する.
539     *
540     * @param  integer $category_id カテゴリID
541     * @param  integer $product_id  プロダクトID
542     * @return void
543     */
544    public function addProductBeforCategories($category_id, $product_id)
545    {
546        $objQuery =& SC_Query_Ex::getSingletonInstance();
547
548        $sqlval = array('category_id' => $category_id,
549                        'product_id' => $product_id);
550
551        $arrSql = array();
552        $arrSql['rank'] = '(SELECT COALESCE(MAX(rank), 0) FROM dtb_product_categories sub WHERE category_id = ?) + 1';
553
554        $from_and_where = $objQuery->dbFactory->getDummyFromClauseSql();
555        $from_and_where .= ' WHERE NOT EXISTS(SELECT * FROM dtb_product_categories WHERE category_id = ? AND product_id = ?)';
556        $objQuery->insert('dtb_product_categories', $sqlval, $arrSql, array($category_id), $from_and_where, array($category_id, $product_id));
557    }
558
559    /**
560     * 商品をカテゴリの末尾に追加する.
561     *
562     * @param  integer $category_id カテゴリID
563     * @param  integer $product_id  プロダクトID
564     * @return void
565     */
566    public function addProductAfterCategories($category_id, $product_id)
567    {
568        $sqlval = array('category_id' => $category_id,
569                        'product_id' => $product_id);
570
571        $objQuery =& SC_Query_Ex::getSingletonInstance();
572
573        // 現在の商品カテゴリを取得
574        $arrCat = $objQuery->select('product_id, category_id, rank',
575                                    'dtb_product_categories',
576                                    'category_id = ?',
577                                    array($category_id));
578
579        $min = 0;
580        foreach ($arrCat as $val) {
581            // 同一商品が存在する場合は登録しない
582            if ($val['product_id'] == $product_id) {
583                return;
584            }
585            // 最下位ランクを取得
586            $min = ($min < $val['rank']) ? $val['rank'] : $min;
587        }
588        $sqlval['rank'] = $min;
589        $objQuery->insert('dtb_product_categories', $sqlval);
590    }
591
592    /**
593     * 商品をカテゴリから削除する.
594     *
595     * @param  integer $category_id カテゴリID
596     * @param  integer $product_id  プロダクトID
597     * @return void
598     */
599    public function removeProductByCategories($category_id, $product_id)
600    {
601        $objQuery =& SC_Query_Ex::getSingletonInstance();
602        $objQuery->delete('dtb_product_categories',
603                          'category_id = ? AND product_id = ?', array($category_id, $product_id));
604    }
605
606    /**
607     * 商品カテゴリを更新する.
608     *
609     * @param  array   $arrCategory_id 登録するカテゴリIDの配列
610     * @param  integer $product_id     プロダクトID
611     * @return void
612     */
613    public function updateProductCategories($arrCategory_id, $product_id)
614    {
615        $objQuery =& SC_Query_Ex::getSingletonInstance();
616
617        // 現在のカテゴリ情報を取得
618        $arrCurrentCat = $objQuery->getCol('category_id',
619                                           'dtb_product_categories',
620                                           'product_id = ?',
621                                           array($product_id));
622
623        // 登録するカテゴリ情報と比較
624        foreach ($arrCurrentCat as $category_id) {
625            // 登録しないカテゴリを削除
626            if (!in_array($category_id, $arrCategory_id)) {
627                $this->removeProductByCategories($category_id, $product_id);
628            }
629        }
630
631        // カテゴリを登録
632        foreach ($arrCategory_id as $category_id) {
633            $this->addProductBeforCategories($category_id, $product_id);
634            SC_Utils_Ex::extendTimeOut();
635        }
636    }
637
638    /**
639     * カテゴリ数の登録を行う.
640     *
641     *
642     * @param  SC_Query $objQuery           SC_Query インスタンス
643     * @param  boolean  $is_force_all_count 全カテゴリの集計を強制する場合 true
644     * @return void
645     */
646    public function sfCountCategory($objQuery = NULL, $is_force_all_count = false)
647    {
648        $objProduct = new SC_Product_Ex();
649
650        if ($objQuery == NULL) {
651            $objQuery =& SC_Query_Ex::getSingletonInstance();
652        }
653
654        $is_out_trans = false;
655        if (!$objQuery->inTransaction()) {
656            $objQuery->begin();
657            $is_out_trans = true;
658        }
659
660        //共通のfrom/where文の構築
661        $sql_where = SC_Product_Ex::getProductDispConditions('alldtl');
662        // 在庫無し商品の非表示
663        if (NOSTOCK_HIDDEN) {
664            $where_products_class = '(stock >= 1 OR stock_unlimited = 1)';
665            $from = $objProduct->alldtlSQL($where_products_class);
666        } else {
667            $from = 'dtb_products as alldtl';
668        }
669
670        //dtb_category_countの構成
671        // 各カテゴリに所属する商品の数を集計。集計対象には子カテゴリを含まない。
672
673        //まずテーブル内容の元を取得
674        if (!$is_force_all_count) {
675            $arrCategoryCountOld = $objQuery->select('category_id,product_count','dtb_category_count');
676        } else {
677            $arrCategoryCountOld = array();
678        }
679
680        //各カテゴリ内の商品数を数えて取得
681        $sql = <<< __EOS__
682            SELECT T1.category_id, count(T2.category_id) as product_count
683            FROM dtb_category AS T1
684                LEFT JOIN dtb_product_categories AS T2
685                    ON T1.category_id = T2.category_id
686                LEFT JOIN $from
687                    ON T2.product_id = alldtl.product_id
688            WHERE $sql_where
689            GROUP BY T1.category_id, T2.category_id
690__EOS__;
691
692        $arrCategoryCountNew = $objQuery->getAll($sql);
693        // 各カテゴリに所属する商品の数を集計。集計対象には子カテゴリを「含む」。
694        //差分を取得して、更新対象カテゴリだけを確認する。
695
696        //各カテゴリ毎のデータ値において以前との差を見る
697        //古いデータの構造入れ替え
698        $arrOld = array();
699        foreach ($arrCategoryCountOld as $item) {
700            $arrOld[$item['category_id']] = $item['product_count'];
701        }
702        //新しいデータの構造入れ替え
703        $arrNew = array();
704        foreach ($arrCategoryCountNew as $item) {
705            $arrNew[$item['category_id']] = $item['product_count'];
706        }
707
708        unset($arrCategoryCountOld);
709        unset($arrCategoryCountNew);
710
711        $arrDiffCategory_id = array();
712        //新しいカテゴリ一覧から見て商品数が異なるデータが無いか確認
713        foreach ($arrNew as $cid => $count) {
714            if ($arrOld[$cid] != $count) {
715                $arrDiffCategory_id[] = $cid;
716            }
717        }
718        //削除カテゴリを想定して、古いカテゴリ一覧から見て商品数が異なるデータが無いか確認。
719        foreach ($arrOld as $cid => $count) {
720            if ($arrNew[$cid] != $count && $count > 0) {
721                $arrDiffCategory_id[] = $cid;
722            }
723        }
724
725        //対象IDが無ければ終了
726        if (count($arrDiffCategory_id) == 0) {
727            if ($is_out_trans) {
728                $objQuery->commit();
729            }
730
731            return;
732        }
733
734        //差分対象カテゴリIDの重複を除去
735        $arrDiffCategory_id = array_unique($arrDiffCategory_id);
736
737        //dtb_category_countの更新 差分のあったカテゴリだけ更新する。
738        foreach ($arrDiffCategory_id as $cid) {
739            $sqlval = array();
740            $sqlval['create_date'] = 'CURRENT_TIMESTAMP';
741            $sqlval['product_count'] = (string) $arrNew[$cid];
742            if ($sqlval['product_count'] =='') {
743                $sqlval['product_count'] = (string) '0';
744            }
745            if (isset($arrOld[$cid])) {
746                $objQuery->update('dtb_category_count', $sqlval, 'category_id = ?', array($cid));
747            } else {
748                if ($is_force_all_count) {
749                    $ret = $objQuery->update('dtb_category_count', $sqlval, 'category_id = ?', array($cid));
750                    if ($ret > 0) {
751                        continue;
752                    }
753                }
754                $sqlval['category_id'] = $cid;
755                $objQuery->insert('dtb_category_count', $sqlval);
756            }
757        }
758
759        unset($arrOld);
760        unset($arrNew);
761
762        //差分があったIDとその親カテゴリIDのリストを取得する
763        $arrTgtCategory_id = array();
764        foreach ($arrDiffCategory_id as $parent_category_id) {
765            $arrTgtCategory_id[] = $parent_category_id;
766            $arrParentID = $this->sfGetParents('dtb_category', 'parent_category_id', 'category_id', $parent_category_id);
767            $arrTgtCategory_id = array_unique(array_merge($arrTgtCategory_id, $arrParentID));
768        }
769
770        unset($arrDiffCategory_id);
771
772        //dtb_category_total_count 集計処理開始
773        //更新対象カテゴリIDだけ集計しなおす。
774        $arrUpdateData = array();
775        $where_products_class = '';
776        if (NOSTOCK_HIDDEN) {
777            $where_products_class .= '(stock >= 1 OR stock_unlimited = 1)';
778        }
779        $from = $objProduct->alldtlSQL($where_products_class);
780        foreach ($arrTgtCategory_id as $category_id) {
781            $arrWhereVal = array();
782            list($tmp_where, $arrTmpVal) = $this->sfGetCatWhere($category_id);
783            if ($tmp_where != '') {
784                $sql_where_product_ids = 'product_id IN (SELECT product_id FROM dtb_product_categories WHERE ' . $tmp_where . ')';
785                $arrWhereVal = $arrTmpVal;
786            } else {
787                $sql_where_product_ids = '0<>0'; // 一致させない
788            }
789            $where = "($sql_where) AND ($sql_where_product_ids)";
790
791            $arrUpdateData[$category_id] = $objQuery->count($from, $where, $arrWhereVal);
792        }
793
794        unset($arrTgtCategory_id);
795
796        // 更新対象だけを更新。
797        foreach ($arrUpdateData as $cid => $count) {
798            $sqlval = array();
799            $sqlval['create_date'] = 'CURRENT_TIMESTAMP';
800            $sqlval['product_count'] = $count;
801            if ($sqlval['product_count'] =='') {
802                $sqlval['product_count'] = (string) '0';
803            }
804            $ret = $objQuery->update('dtb_category_total_count', $sqlval, 'category_id = ?', array($cid));
805            if (!$ret) {
806                $sqlval['category_id'] = $cid;
807                $ret = $objQuery->insert('dtb_category_total_count', $sqlval);
808            }
809        }
810        // トランザクション終了処理
811        if ($is_out_trans) {
812            $objQuery->commit();
813        }
814    }
815
816    /**
817     * 子IDの配列を返す.
818     *
819     * @param string  $table    テーブル名
820     * @param string  $pid_name 親ID名
821     * @param string  $id_name  ID名
822     * @param integer $id       ID
823     * @param array 子ID の配列
824     */
825    public function sfGetChildsID($table, $pid_name, $id_name, $id)
826    {
827        $arrRet = $this->sfGetChildrenArray($table, $pid_name, $id_name, $id);
828
829        return $arrRet;
830    }
831
832    /**
833     * 階層構造のテーブルから子ID配列を取得する.
834     *
835     * @param  string  $table    テーブル名
836     * @param  string  $pid_name 親ID名
837     * @param  string  $id_name  ID名
838     * @param  integer $id       ID番号
839     * @return array   子IDの配列
840     */
841    public function sfGetChildrenArray($table, $pid_name, $id_name, $id)
842    {
843        $arrChildren = array();
844        $arrRet = array($id);
845
846        while (count($arrRet) > 0) {
847            $arrChildren = array_merge($arrChildren, $arrRet);
848            $arrRet = SC_Helper_DB_Ex::sfGetChildrenArraySub($table, $pid_name, $id_name, $arrRet);
849        }
850
851        return $arrChildren;
852    }
853
854    /**
855     * 親ID直下の子IDを全て取得する.
856     *
857     * @param  array  $arrData  親カテゴリの配列
858     * @param  string $pid_name 親ID名
859     * @param  string $id_name  ID名
860     * @param  array  $arrPID   親IDの配列
861     * @return array  子IDの配列
862     */
863    public function sfGetChildrenArraySub($table, $pid_name, $id_name, $arrPID)
864    {
865        $objQuery =& SC_Query_Ex::getSingletonInstance();
866
867        $where = "$pid_name IN (" . SC_Utils_Ex::repeatStrWithSeparator('?', count($arrPID)) . ')';
868
869        $return = $objQuery->getCol($id_name, $table, $where, $arrPID);
870
871        return $return;
872    }
873
874    /**
875     * 所属する全ての階層の親IDを配列で返す.
876     *
877     * @param  SC_Query $objQuery SC_Query インスタンス
878     * @param  string   $table    テーブル名
879     * @param  string   $pid_name 親ID名
880     * @param  string   $id_name  ID名
881     * @param  integer  $id       ID
882     * @return array    親IDの配列
883     */
884    public function sfGetParents($table, $pid_name, $id_name, $id)
885    {
886        $arrRet = SC_Helper_DB_Ex::sfGetParentsArray($table, $pid_name, $id_name, $id);
887
888        return $arrRet;
889    }
890
891    /**
892     * 階層構造のテーブルから親ID配列を取得する.
893     *
894     * @param  string  $table    テーブル名
895     * @param  string  $pid_name 親ID名
896     * @param  string  $id_name  ID名
897     * @param  integer $id       ID
898     * @return array   親IDの配列
899     */
900    public function sfGetParentsArray($table, $pid_name, $id_name, $id)
901    {
902        $arrParents = array();
903        $ret = $id;
904
905        while ($ret != '0' && !SC_Utils_Ex::isBlank($ret)) {
906            $arrParents[] = $ret;
907            $ret = SC_Helper_DB_Ex::sfGetParentsArraySub($table, $pid_name, $id_name, $ret);
908        }
909
910        $arrParents = array_reverse($arrParents);
911
912        return $arrParents;
913    }
914
915    /* 子ID所属する親IDを取得する */
916    public function sfGetParentsArraySub($table, $pid_name, $id_name, $child)
917    {
918        if (SC_Utils_Ex::isBlank($child)) {
919            return false;
920        }
921        $objQuery =& SC_Query_Ex::getSingletonInstance();
922        if (!is_array($child)) {
923            $child = array($child);
924        }
925        $parent = $objQuery->get($pid_name, $table, "$id_name = ?", $child);
926
927        return $parent;
928    }
929
930    /**
931     * カテゴリから商品を検索する場合のWHERE文と値を返す.
932     *
933     * @param  integer $category_id カテゴリID
934     * @return array   商品を検索する場合の配列
935     */
936    public function sfGetCatWhere($category_id)
937    {
938        // 子カテゴリIDの取得
939        $arrRet = SC_Helper_DB_Ex::sfGetChildrenArray('dtb_category', 'parent_category_id', 'category_id', $category_id);
940
941        $where = 'category_id IN (' . SC_Utils_Ex::repeatStrWithSeparator('?', count($arrRet)) . ')';
942
943        return array($where, $arrRet);
944    }
945
946    /**
947     * SELECTボックス用リストを作成する.
948     *
949     * @param  string $table       テーブル名
950     * @param  string $keyname     プライマリーキーのカラム名
951     * @param  string $valname     データ内容のカラム名
952     * @param  string $where       WHERE句
953     * @param  array  $arrVal プレースホルダ
954     * @return array  SELECT ボックス用リストの配列
955     */
956    public static function sfGetIDValueList($table, $keyname, $valname, $where = '', $arrVal = array())
957    {
958        $objQuery =& SC_Query_Ex::getSingletonInstance();
959        $col = "$keyname, $valname";
960        $objQuery->setWhere('del_flg = 0');
961        $objQuery->setOrder('rank DESC');
962        $arrList = $objQuery->select($col, $table, $where, $arrVal);
963        $count = count($arrList);
964        $arrRet = array();
965        for ($cnt = 0; $cnt < $count; $cnt++) {
966            $key = $arrList[$cnt][$keyname];
967            $val = $arrList[$cnt][$valname];
968            $arrRet[$key] = $val;
969        }
970
971        return $arrRet;
972    }
973
974    /**
975     * ランキングを上げる.
976     *
977     * @param  string         $table    テーブル名
978     * @param  string         $colname  カラム名
979     * @param  string|integer $id       テーブルのキー
980     * @param  string         $andwhere SQL の AND 条件である WHERE 句
981     * @return void
982     */
983    public function sfRankUp($table, $colname, $id, $andwhere = '')
984    {
985        $objQuery =& SC_Query_Ex::getSingletonInstance();
986        $objQuery->begin();
987        $where = "$colname = ?";
988        if ($andwhere != '') {
989            $where.= " AND $andwhere";
990        }
991        // 対象項目のランクを取得
992        $rank = $objQuery->get('rank', $table, $where, array($id));
993        // ランクの最大値を取得
994        $maxrank = $objQuery->max('rank', $table, $andwhere);
995        // ランクが最大値よりも小さい場合に実行する。
996        if ($rank < $maxrank) {
997            // ランクが一つ上のIDを取得する。
998            $where = 'rank = ?';
999            if ($andwhere != '') {
1000                $where.= " AND $andwhere";
1001            }
1002            $uprank = $rank + 1;
1003            $up_id = $objQuery->get($colname, $table, $where, array($uprank));
1004
1005            // ランク入れ替えの実行
1006            $where = "$colname = ?";
1007            if ($andwhere != '') {
1008                $where .= " AND $andwhere";
1009            }
1010
1011            $sqlval = array(
1012                'rank' => $rank + 1,
1013            );
1014            $arrWhereVal = array($id);
1015            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1016
1017            $sqlval = array(
1018                'rank' => $rank,
1019            );
1020            $arrWhereVal = array($up_id);
1021            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1022        }
1023        $objQuery->commit();
1024    }
1025
1026    /**
1027     * ランキングを下げる.
1028     *
1029     * @param  string         $table    テーブル名
1030     * @param  string         $colname  カラム名
1031     * @param  string|integer $id       テーブルのキー
1032     * @param  string         $andwhere SQL の AND 条件である WHERE 句
1033     * @return void
1034     */
1035    public function sfRankDown($table, $colname, $id, $andwhere = '')
1036    {
1037        $objQuery =& SC_Query_Ex::getSingletonInstance();
1038        $objQuery->begin();
1039        $where = "$colname = ?";
1040        if ($andwhere != '') {
1041            $where.= " AND $andwhere";
1042        }
1043        // 対象項目のランクを取得
1044        $rank = $objQuery->get('rank', $table, $where, array($id));
1045
1046        // ランクが1(最小値)よりも大きい場合に実行する。
1047        if ($rank > 1) {
1048            // ランクが一つ下のIDを取得する。
1049            $where = 'rank = ?';
1050            if ($andwhere != '') {
1051                $where.= " AND $andwhere";
1052            }
1053            $downrank = $rank - 1;
1054            $down_id = $objQuery->get($colname, $table, $where, array($downrank));
1055
1056            // ランク入れ替えの実行
1057            $where = "$colname = ?";
1058            if ($andwhere != '') {
1059                $where .= " AND $andwhere";
1060            }
1061
1062            $sqlval = array(
1063                'rank' => $rank - 1,
1064            );
1065            $arrWhereVal = array($id);
1066            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1067
1068            $sqlval = array(
1069                'rank' => $rank,
1070            );
1071            $arrWhereVal = array($down_id);
1072            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1073        }
1074        $objQuery->commit();
1075    }
1076
1077    /**
1078     * 指定順位へ移動する.
1079     *
1080     * @param  string         $tableName   テーブル名
1081     * @param  string         $keyIdColumn キーを保持するカラム名
1082     * @param  string|integer $keyId       キーの値
1083     * @param  integer        $pos         指定順位
1084     * @param  string         $where       SQL の AND 条件である WHERE 句
1085     * @return void
1086     */
1087    public function sfMoveRank($tableName, $keyIdColumn, $keyId, $pos, $where = '')
1088    {
1089        $objQuery =& SC_Query_Ex::getSingletonInstance();
1090        $objQuery->begin();
1091
1092        // 自身のランクを取得する
1093        if ($where != '') {
1094            $getWhere = "$keyIdColumn = ? AND " . $where;
1095        } else {
1096            $getWhere = "$keyIdColumn = ?";
1097        }
1098        $oldRank = $objQuery->get('rank', $tableName, $getWhere, array($keyId));
1099
1100        $max = $objQuery->max('rank', $tableName, $where);
1101
1102        // 更新するランク値を取得
1103        $newRank = $this->getNewRank($pos, $max);
1104        // 他のItemのランクを調整する
1105        $ret = $this->moveOtherItemRank($newRank, $oldRank, $objQuery, $tableName, $where);
1106        if (!$ret) {
1107            // 他のランク変更がなければ処理を行わない
1108            return;
1109        }
1110
1111        // 指定した順位へrankを書き換える。
1112        $sqlval = array(
1113            'rank' => $newRank,
1114        );
1115        $str_where = "$keyIdColumn = ?";
1116        if ($where != '') {
1117            $str_where .= " AND $where";
1118        }
1119        $arrWhereVal = array($keyId);
1120        $objQuery->update($tableName, $sqlval, $str_where, $arrWhereVal);
1121
1122        $objQuery->commit();
1123    }
1124
1125    /**
1126     * 指定された位置の値をDB用のRANK値に変換する
1127     * 指定位置が1番目に移動なら、newRankは最大値
1128     * 指定位置が1番下へ移動なら、newRankは1
1129     *
1130     * @param  int $position 指定された位置
1131     * @param  int $maxRank  現在のランク最大値
1132     * @return int $newRank DBに登録するRANK値
1133     */
1134    public function getNewRank($position, $maxRank)
1135    {
1136        if ($position > $maxRank) {
1137            $newRank = 1;
1138        } elseif ($position < 1) {
1139            $newRank = $maxRank;
1140        } else {
1141            $newRank = $maxRank - $position + 1;
1142        }
1143
1144        return $newRank;
1145    }
1146
1147    /**
1148     * 指定した順位の商品から移動させる商品までのrankを1つずらす
1149     *
1150     * @param  int     $newRank
1151     * @param  int     $oldRank
1152     * @param  object  $objQuery
1153     * @param  string  $where
1154     * @return boolean
1155     */
1156    public function moveOtherItemRank($newRank, $oldRank, &$objQuery, $tableName, $addWhere)
1157    {
1158        $sqlval = array();
1159        $arrRawSql = array();
1160        $where = 'rank BETWEEN ? AND ?';
1161        if ($addWhere != '') {
1162            $where .= " AND $addWhere";
1163        }
1164        if ($newRank > $oldRank) {
1165            //位置を上げる場合、他の商品の位置を1つ下げる(ランクを1下げる)
1166            $arrRawSql['rank'] = 'rank - 1';
1167            $arrWhereVal = array($oldRank + 1, $newRank);
1168        } elseif ($newRank < $oldRank) {
1169            //位置を下げる場合、他の商品の位置を1つ上げる(ランクを1上げる)
1170            $arrRawSql['rank'] = 'rank + 1';
1171            $arrWhereVal = array($newRank, $oldRank - 1);
1172        } else {
1173            //入れ替え先の順位が入れ替え元の順位と同じ場合なにもしない
1174            return false;
1175        }
1176
1177        return $objQuery->update($tableName, $sqlval, $where, $arrWhereVal, $arrRawSql);
1178    }
1179
1180    /**
1181     * ランクを含むレコードを削除する.
1182     *
1183     * レコードごと削除する場合は、$deleteをtrueにする
1184     *
1185     * @param string         $table    テーブル名
1186     * @param string         $colname  カラム名
1187     * @param string|integer $id       テーブルのキー
1188     * @param string         $andwhere SQL の AND 条件である WHERE 句
1189     * @param bool           $delete   レコードごと削除する場合 true,
1190     *                     レコードごと削除しない場合 false
1191     * @return void
1192     */
1193    public function sfDeleteRankRecord($table, $colname, $id, $andwhere = '',
1194                                $delete = false) {
1195        $objQuery =& SC_Query_Ex::getSingletonInstance();
1196        $objQuery->begin();
1197        // 削除レコードのランクを取得する。
1198        $where = "$colname = ?";
1199        if ($andwhere != '') {
1200            $where.= " AND $andwhere";
1201        }
1202        $rank = $objQuery->get('rank', $table, $where, array($id));
1203
1204        if (!$delete) {
1205            // ランクを最下位にする、DELフラグON
1206            $sqlval = array(
1207                'rank'      => 0,
1208                'del_flg'   => 1,
1209            );
1210            $where = "$colname = ?";
1211            $arrWhereVal = array($id);
1212            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1213        } else {
1214            $objQuery->delete($table, "$colname = ?", array($id));
1215        }
1216
1217        // 追加レコードのランクより上のレコードを一つずらす。
1218        $sqlval = array();
1219        $where = 'rank > ?';
1220        if ($andwhere != '') {
1221            $where .= " AND $andwhere";
1222        }
1223        $arrWhereVal = array($rank);
1224        $arrRawSql = array(
1225            'rank' => '(rank - 1)',
1226        );
1227        $objQuery->update($table, $sqlval, $where, $arrWhereVal, $arrRawSql);
1228
1229        $objQuery->commit();
1230    }
1231
1232    /**
1233     * 親IDの配列を元に特定のカラムを取得する.
1234     *
1235     * @param  SC_Query $objQuery SC_Query インスタンス
1236     * @param  string   $table    テーブル名
1237     * @param  string   $id_name  ID名
1238     * @param  string   $col_name カラム名
1239     * @param  array    $arrId    IDの配列
1240     * @return array    特定のカラムの配列
1241     */
1242    public function sfGetParentsCol($objQuery, $table, $id_name, $col_name, $arrId)
1243    {
1244        $col = $col_name;
1245        $len = count($arrId);
1246        $where = '';
1247
1248        for ($cnt = 0; $cnt < $len; $cnt++) {
1249            if ($where == '') {
1250                $where = "$id_name = ?";
1251            } else {
1252                $where.= " OR $id_name = ?";
1253            }
1254        }
1255
1256        $objQuery->setOrder('level');
1257        $arrRet = $objQuery->select($col, $table, $where, $arrId);
1258
1259        return $arrRet;
1260    }
1261
1262    /**
1263     * カテゴリ変更時の移動処理を行う.
1264     *
1265     * ※この関数って、どこからも呼ばれていないのでは??
1266     *
1267     * @param  SC_Query $objQuery  SC_Query インスタンス
1268     * @param  string   $table     テーブル名
1269     * @param  string   $id_name   ID名
1270     * @param  string   $cat_name  カテゴリ名
1271     * @param  integer  $old_catid 旧カテゴリID
1272     * @param  integer  $new_catid 新カテゴリID
1273     * @param  integer  $id        ID
1274     * @return void
1275     */
1276    public function sfMoveCatRank($objQuery, $table, $id_name, $cat_name, $old_catid, $new_catid, $id)
1277    {
1278        if ($old_catid == $new_catid) {
1279            return;
1280        }
1281        // 旧カテゴリでのランク削除処理
1282        // 移動レコードのランクを取得する。
1283        $sqlval = array();
1284        $where = "$id_name = ?";
1285        $rank = $objQuery->get('rank', $table, $where, array($id));
1286        // 削除レコードのランクより上のレコードを一つ下にずらす。
1287        $where = "rank > ? AND $cat_name = ?";
1288        $arrWhereVal = array($rank, $old_catid);
1289        $arrRawSql = array(
1290            'rank' => '(rank - 1)',
1291        );
1292        $objQuery->update($table, $sqlval, $where, $arrWhereVal, $arrRawSql);
1293
1294        // 新カテゴリでの登録処理
1295        // 新カテゴリの最大ランクを取得する。
1296        $max_rank = $objQuery->max('rank', $table, "$cat_name = ?", array($new_catid)) + 1;
1297        $sqlval = array(
1298            'rank' => $max_rank,
1299        );
1300        $where = "$id_name = ?";
1301        $arrWhereVal = array($id);
1302        $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1303    }
1304
1305    /**
1306     * レコードの存在チェックを行う.
1307     *
1308     * TODO SC_Query に移行するべきか?
1309     *
1310     * @param  string $table    テーブル名
1311     * @param  string $col      カラム名
1312     * @param  array  $arrVal   要素の配列
1313     * @param  string  $addwhere SQL の AND 条件である WHERE 句
1314     * @return bool   レコードが存在する場合 true
1315     */
1316    public static function sfIsRecord($table, $col, $arrVal, $addwhere = '')
1317    {
1318        $objQuery =& SC_Query_Ex::getSingletonInstance();
1319        $arrCol = preg_split('/[, ]/', $col);
1320
1321        $where = 'del_flg = 0';
1322
1323        if ($addwhere != '') {
1324            $where.= " AND $addwhere";
1325        }
1326
1327        foreach ($arrCol as $val) {
1328            if ($val != '') {
1329                if ($where == '') {
1330                    $where = "$val = ?";
1331                } else {
1332                    $where.= " AND $val = ?";
1333                }
1334            }
1335        }
1336        $ret = $objQuery->get($col, $table, $where, $arrVal);
1337
1338        if ($ret != '') {
1339            return true;
1340        }
1341
1342        return false;
1343    }
1344
1345    /**
1346     * メーカー商品数数の登録を行う.
1347     *
1348     * @param  SC_Query $objQuery SC_Query インスタンス
1349     * @return void
1350     */
1351    public function sfCountMaker($objQuery)
1352    {
1353        $sql = '';
1354
1355        //テーブル内容の削除
1356        $objQuery->query('DELETE FROM dtb_maker_count');
1357
1358        //各メーカーの商品数を数えて格納
1359        $sql = ' INSERT INTO dtb_maker_count(maker_id, product_count, create_date) ';
1360        $sql .= ' SELECT T1.maker_id, count(T2.maker_id), CURRENT_TIMESTAMP ';
1361        $sql .= ' FROM dtb_maker AS T1 LEFT JOIN dtb_products AS T2';
1362        $sql .= ' ON T1.maker_id = T2.maker_id ';
1363        $sql .= ' WHERE T2.del_flg = 0 AND T2.status = 1 ';
1364        $sql .= ' GROUP BY T1.maker_id, T2.maker_id ';
1365        $objQuery->query($sql);
1366    }
1367
1368    /**
1369     * 選択中の商品のメーカーを取得する.
1370     *
1371     * @param  integer $product_id プロダクトID
1372     * @param  integer $maker_id   メーカーID
1373     * @return array   選択中の商品のメーカーIDの配列
1374     *
1375     */
1376    public function sfGetMakerId($product_id, $maker_id = 0, $closed = false)
1377    {
1378        if ($closed) {
1379            $status = '';
1380        } else {
1381            $status = 'status = 1';
1382        }
1383
1384        if (!$this->g_maker_on) {
1385            $this->g_maker_on = true;
1386            $maker_id = (int) $maker_id;
1387            $product_id = (int) $product_id;
1388            if (SC_Utils_Ex::sfIsInt($maker_id) && $maker_id != 0 && $this->sfIsRecord('dtb_maker','maker_id', $maker_id)) {
1389                $this->g_maker_id = array($maker_id);
1390            } elseif (SC_Utils_Ex::sfIsInt($product_id) && $product_id != 0 && $this->sfIsRecord('dtb_products','product_id', $product_id, $status)) {
1391                $objQuery =& SC_Query_Ex::getSingletonInstance();
1392                $maker_id = $objQuery->getCol('maker_id', 'dtb_products', 'product_id = ?', array($product_id));
1393                $this->g_maker_id = $maker_id;
1394            } else {
1395                // 不正な場合は、空の配列を返す。
1396                $this->g_maker_id = array();
1397            }
1398        }
1399
1400        return $this->g_maker_id;
1401    }
1402
1403    /**
1404     * メーカーの取得を行う.
1405     *
1406     * $products_check:true商品登録済みのものだけ取得する
1407     *
1408     * @param  string $addwhere       追加する WHERE 句
1409     * @param  bool   $products_check 商品の存在するカテゴリのみ取得する場合 true
1410     * @return array  カテゴリツリーの配列
1411     */
1412    public function sfGetMakerList($addwhere = '', $products_check = false)
1413    {
1414        $objQuery =& SC_Query_Ex::getSingletonInstance();
1415        $where = 'del_flg = 0';
1416
1417        if ($addwhere != '') {
1418            $where.= " AND $addwhere";
1419        }
1420
1421        $objQuery->setOption('ORDER BY rank DESC');
1422
1423        if ($products_check) {
1424            $col = 'T1.maker_id, name';
1425            $from = 'dtb_maker AS T1 LEFT JOIN dtb_maker_count AS T2 ON T1.maker_id = T2.maker_id';
1426            $where .= ' AND product_count > 0';
1427        } else {
1428            $col = 'maker_id, name';
1429            $from = 'dtb_maker';
1430        }
1431
1432        $arrRet = $objQuery->select($col, $from, $where);
1433
1434        $max = count($arrRet);
1435        $arrList = array();
1436        for ($cnt = 0; $cnt < $max; $cnt++) {
1437            $id = $arrRet[$cnt]['maker_id'];
1438            $name = $arrRet[$cnt]['name'];
1439            $arrList[$id] = $name;
1440        }
1441
1442        return $arrList;
1443    }
1444
1445    /**
1446     * 店舗基本情報に基づいて税金額を返す
1447     *
1448     * @param  integer $price 計算対象の金額
1449     * @return integer 税金額
1450     */
1451    public function sfTax($price)
1452    {
1453        // 店舗基本情報を取得
1454        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1455
1456        return SC_Utils_Ex::sfTax($price, $CONF['tax'], $CONF['tax_rule']);
1457    }
1458
1459    /**
1460     * 店舗基本情報に基づいて税金付与した金額を返す
1461     * SC_Utils_Ex::sfCalcIncTax とどちらか統一したほうが良い
1462     *
1463     * @param  integer $price 計算対象の金額
1464     * @return integer 税金付与した金額
1465     */
1466    public function sfCalcIncTax($price, $tax = null, $tax_rule = null)
1467    {
1468        // 店舗基本情報を取得
1469        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1470        $tax      = $tax      === null ? $CONF['tax']      : $tax;
1471        $tax_rule = $tax_rule === null ? $CONF['tax_rule'] : $tax_rule;
1472
1473        return SC_Utils_Ex::sfCalcIncTax($price, $tax, $tax_rule);
1474    }
1475
1476    /**
1477     * 店舗基本情報に基づいて加算ポイントを返す
1478     *
1479     * @param  integer $totalpoint
1480     * @param  integer $use_point
1481     * @return integer 加算ポイント
1482     */
1483    public function sfGetAddPoint($totalpoint, $use_point)
1484    {
1485        // 店舗基本情報を取得
1486        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1487
1488        return SC_Utils_Ex::sfGetAddPoint($totalpoint, $use_point, $CONF['point_rate']);
1489    }
1490
1491    /**
1492     * 指定ファイルが存在する場合 SQL として実行
1493     *
1494     * XXX プラグイン用に追加。将来消すかも。
1495     *
1496     * @param  string $sqlFilePath SQL ファイルのパス
1497     * @return void
1498     */
1499    public function sfExecSqlByFile($sqlFilePath)
1500    {
1501        if (file_exists($sqlFilePath)) {
1502            $objQuery =& SC_Query_Ex::getSingletonInstance();
1503
1504            $sqls = file_get_contents($sqlFilePath);
1505            if ($sqls === false) trigger_error('ファイルは存在するが読み込めない', E_USER_ERROR);
1506
1507            foreach (explode(';', $sqls) as $sql) {
1508                $sql = trim($sql);
1509                if (strlen($sql) == 0) continue;
1510                $objQuery->query($sql);
1511            }
1512        }
1513    }
1514
1515    /**
1516     * 商品規格を設定しているか
1517     *
1518     * @param  integer $product_id 商品ID
1519     * @return bool    商品規格が存在する場合:true, それ以外:false
1520     */
1521    public function sfHasProductClass($product_id)
1522    {
1523        if (!SC_Utils_Ex::sfIsInt($product_id)) return false;
1524
1525        $objQuery =& SC_Query_Ex::getSingletonInstance();
1526        $where = 'product_id = ? AND del_flg = 0 AND (classcategory_id1 != 0 OR classcategory_id2 != 0)';
1527        $exists = $objQuery->exists('dtb_products_class', $where, array($product_id));
1528
1529        return $exists;
1530    }
1531
1532    /**
1533     * 店舗基本情報を登録する
1534     *
1535     * @param  array $arrData 登録するデータ
1536     * @return void
1537     */
1538    public static function registerBasisData($arrData)
1539    {
1540        $objQuery =& SC_Query_Ex::getSingletonInstance();
1541
1542        $arrData = $objQuery->extractOnlyColsOf('dtb_baseinfo', $arrData);
1543
1544        if (isset($arrData['regular_holiday_ids']) && is_array($arrData['regular_holiday_ids'])) {
1545            // 定休日をパイプ区切りの文字列に変換
1546            $arrData['regular_holiday_ids'] = implode('|', $arrData['regular_holiday_ids']);
1547        }
1548
1549        $arrData['update_date'] = 'CURRENT_TIMESTAMP';
1550
1551        // UPDATEの実行
1552        $ret = $objQuery->update('dtb_baseinfo', $arrData);
1553        GC_Utils_Ex::gfPrintLog('dtb_baseinfo に UPDATE を実行しました。');
1554
1555        // UPDATE できなかった場合、INSERT
1556        if ($ret == 0) {
1557            $arrData['id'] = 1;
1558            $ret = $objQuery->insert('dtb_baseinfo', $arrData);
1559            GC_Utils_Ex::gfPrintLog('dtb_baseinfo に INSERT を実行しました。');
1560        }
1561    }
1562
1563    /**
1564     * レコード件数を計算.
1565     *
1566     * @param  string  $table
1567     * @param  string  $where
1568     * @param  array   $arrval
1569     * @return integer レコード件数
1570     */
1571    public function countRecords($table, $where = '', $arrval = array())
1572    {
1573        $objQuery =& SC_Query_Ex::getSingletonInstance();
1574        $col = 'COUNT(*)';
1575
1576        return $objQuery->get($col, $table, $where, $arrval);
1577    }
1578}
Note: See TracBrowser for help on using the repository browser.