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

Revision 23573, 54.8 KB checked in by shutta, 10 years ago (diff)

#2596 (SC_Helper_DB::sfGetParentsArray()の無限ループの予防)
最大階層(LEVEL_MAX)回以上ループさせないようにした。

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