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

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

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

LC_Page_Products_Detail での関連カテゴリーの取得を、SC_Helper_Category を使った形に変更.

  • 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        if (SC_Utils_Ex::sfIsInt($category_id) && $category_id != 0 && SC_Helper_DB_Ex::sfIsRecord('dtb_category','category_id', array($category_id))) {
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        while ($ret != '0' && !SC_Utils_Ex::isBlank($ret)) {
905            $arrParents[] = $ret;
906            $ret = SC_Helper_DB_Ex::sfGetParentsArraySub($table, $pid_name, $id_name, $ret);
907        }
908
909        $arrParents = array_reverse($arrParents);
910
911        return $arrParents;
912    }
913
914    /* 子ID所属する親IDを取得する */
915    public function sfGetParentsArraySub($table, $pid_name, $id_name, $child)
916    {
917        if (SC_Utils_Ex::isBlank($child)) {
918            return false;
919        }
920        $objQuery =& SC_Query_Ex::getSingletonInstance();
921        if (!is_array($child)) {
922            $child = array($child);
923        }
924        $parent = $objQuery->get($pid_name, $table, "$id_name = ?", $child);
925
926        return $parent;
927    }
928
929    /**
930     * カテゴリから商品を検索する場合のWHERE文と値を返す.
931     *
932     * @param  integer $category_id カテゴリID
933     * @return array   商品を検索する場合の配列
934     */
935    public function sfGetCatWhere($category_id)
936    {
937        // 子カテゴリIDの取得
938        $arrRet = SC_Helper_DB_Ex::sfGetChildrenArray('dtb_category', 'parent_category_id', 'category_id', $category_id);
939
940        $where = 'category_id IN (' . SC_Utils_Ex::repeatStrWithSeparator('?', count($arrRet)) . ')';
941
942        return array($where, $arrRet);
943    }
944
945    /**
946     * SELECTボックス用リストを作成する.
947     *
948     * @param  string $table       テーブル名
949     * @param  string $keyname     プライマリーキーのカラム名
950     * @param  string $valname     データ内容のカラム名
951     * @param  string $where       WHERE句
952     * @param  array  $arrVal プレースホルダ
953     * @return array  SELECT ボックス用リストの配列
954     */
955    public static function sfGetIDValueList($table, $keyname, $valname, $where = '', $arrVal = array())
956    {
957        $objQuery =& SC_Query_Ex::getSingletonInstance();
958        $col = "$keyname, $valname";
959        $objQuery->setWhere('del_flg = 0');
960        $objQuery->setOrder('rank DESC');
961        $arrList = $objQuery->select($col, $table, $where, $arrVal);
962        $count = count($arrList);
963        $arrRet = array();
964        for ($cnt = 0; $cnt < $count; $cnt++) {
965            $key = $arrList[$cnt][$keyname];
966            $val = $arrList[$cnt][$valname];
967            $arrRet[$key] = $val;
968        }
969
970        return $arrRet;
971    }
972
973    /**
974     * ランキングを上げる.
975     *
976     * @param  string         $table    テーブル名
977     * @param  string         $colname  カラム名
978     * @param  string|integer $id       テーブルのキー
979     * @param  string         $andwhere SQL の AND 条件である WHERE 句
980     * @return void
981     */
982    public function sfRankUp($table, $colname, $id, $andwhere = '')
983    {
984        $objQuery =& SC_Query_Ex::getSingletonInstance();
985        $objQuery->begin();
986        $where = "$colname = ?";
987        if ($andwhere != '') {
988            $where.= " AND $andwhere";
989        }
990        // 対象項目のランクを取得
991        $rank = $objQuery->get('rank', $table, $where, array($id));
992        // ランクの最大値を取得
993        $maxrank = $objQuery->max('rank', $table, $andwhere);
994        // ランクが最大値よりも小さい場合に実行する。
995        if ($rank < $maxrank) {
996            // ランクが一つ上のIDを取得する。
997            $where = 'rank = ?';
998            if ($andwhere != '') {
999                $where.= " AND $andwhere";
1000            }
1001            $uprank = $rank + 1;
1002            $up_id = $objQuery->get($colname, $table, $where, array($uprank));
1003
1004            // ランク入れ替えの実行
1005            $where = "$colname = ?";
1006            if ($andwhere != '') {
1007                $where .= " AND $andwhere";
1008            }
1009
1010            $sqlval = array(
1011                'rank' => $rank + 1,
1012            );
1013            $arrWhereVal = array($id);
1014            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1015
1016            $sqlval = array(
1017                'rank' => $rank,
1018            );
1019            $arrWhereVal = array($up_id);
1020            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1021        }
1022        $objQuery->commit();
1023    }
1024
1025    /**
1026     * ランキングを下げる.
1027     *
1028     * @param  string         $table    テーブル名
1029     * @param  string         $colname  カラム名
1030     * @param  string|integer $id       テーブルのキー
1031     * @param  string         $andwhere SQL の AND 条件である WHERE 句
1032     * @return void
1033     */
1034    public function sfRankDown($table, $colname, $id, $andwhere = '')
1035    {
1036        $objQuery =& SC_Query_Ex::getSingletonInstance();
1037        $objQuery->begin();
1038        $where = "$colname = ?";
1039        if ($andwhere != '') {
1040            $where.= " AND $andwhere";
1041        }
1042        // 対象項目のランクを取得
1043        $rank = $objQuery->get('rank', $table, $where, array($id));
1044
1045        // ランクが1(最小値)よりも大きい場合に実行する。
1046        if ($rank > 1) {
1047            // ランクが一つ下のIDを取得する。
1048            $where = 'rank = ?';
1049            if ($andwhere != '') {
1050                $where.= " AND $andwhere";
1051            }
1052            $downrank = $rank - 1;
1053            $down_id = $objQuery->get($colname, $table, $where, array($downrank));
1054
1055            // ランク入れ替えの実行
1056            $where = "$colname = ?";
1057            if ($andwhere != '') {
1058                $where .= " AND $andwhere";
1059            }
1060
1061            $sqlval = array(
1062                'rank' => $rank - 1,
1063            );
1064            $arrWhereVal = array($id);
1065            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1066
1067            $sqlval = array(
1068                'rank' => $rank,
1069            );
1070            $arrWhereVal = array($down_id);
1071            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1072        }
1073        $objQuery->commit();
1074    }
1075
1076    /**
1077     * 指定順位へ移動する.
1078     *
1079     * @param  string         $tableName   テーブル名
1080     * @param  string         $keyIdColumn キーを保持するカラム名
1081     * @param  string|integer $keyId       キーの値
1082     * @param  integer        $pos         指定順位
1083     * @param  string         $where       SQL の AND 条件である WHERE 句
1084     * @return void
1085     */
1086    public function sfMoveRank($tableName, $keyIdColumn, $keyId, $pos, $where = '')
1087    {
1088        $objQuery =& SC_Query_Ex::getSingletonInstance();
1089        $objQuery->begin();
1090
1091        // 自身のランクを取得する
1092        if ($where != '') {
1093            $getWhere = "$keyIdColumn = ? AND " . $where;
1094        } else {
1095            $getWhere = "$keyIdColumn = ?";
1096        }
1097        $oldRank = $objQuery->get('rank', $tableName, $getWhere, array($keyId));
1098
1099        $max = $objQuery->max('rank', $tableName, $where);
1100
1101        // 更新するランク値を取得
1102        $newRank = $this->getNewRank($pos, $max);
1103        // 他のItemのランクを調整する
1104        $ret = $this->moveOtherItemRank($newRank, $oldRank, $objQuery, $tableName, $where);
1105        if (!$ret) {
1106            // 他のランク変更がなければ処理を行わない
1107            return;
1108        }
1109
1110        // 指定した順位へrankを書き換える。
1111        $sqlval = array(
1112            'rank' => $newRank,
1113        );
1114        $str_where = "$keyIdColumn = ?";
1115        if ($where != '') {
1116            $str_where .= " AND $where";
1117        }
1118        $arrWhereVal = array($keyId);
1119        $objQuery->update($tableName, $sqlval, $str_where, $arrWhereVal);
1120
1121        $objQuery->commit();
1122    }
1123
1124    /**
1125     * 指定された位置の値をDB用のRANK値に変換する
1126     * 指定位置が1番目に移動なら、newRankは最大値
1127     * 指定位置が1番下へ移動なら、newRankは1
1128     *
1129     * @param  int $position 指定された位置
1130     * @param  int $maxRank  現在のランク最大値
1131     * @return int $newRank DBに登録するRANK値
1132     */
1133    public function getNewRank($position, $maxRank)
1134    {
1135        if ($position > $maxRank) {
1136            $newRank = 1;
1137        } elseif ($position < 1) {
1138            $newRank = $maxRank;
1139        } else {
1140            $newRank = $maxRank - $position + 1;
1141        }
1142
1143        return $newRank;
1144    }
1145
1146    /**
1147     * 指定した順位の商品から移動させる商品までのrankを1つずらす
1148     *
1149     * @param  int     $newRank
1150     * @param  int     $oldRank
1151     * @param  object  $objQuery
1152     * @param  string  $where
1153     * @return boolean
1154     */
1155    public function moveOtherItemRank($newRank, $oldRank, &$objQuery, $tableName, $addWhere)
1156    {
1157        $sqlval = array();
1158        $arrRawSql = array();
1159        $where = 'rank BETWEEN ? AND ?';
1160        if ($addWhere != '') {
1161            $where .= " AND $addWhere";
1162        }
1163        if ($newRank > $oldRank) {
1164            //位置を上げる場合、他の商品の位置を1つ下げる(ランクを1下げる)
1165            $arrRawSql['rank'] = 'rank - 1';
1166            $arrWhereVal = array($oldRank + 1, $newRank);
1167        } elseif ($newRank < $oldRank) {
1168            //位置を下げる場合、他の商品の位置を1つ上げる(ランクを1上げる)
1169            $arrRawSql['rank'] = 'rank + 1';
1170            $arrWhereVal = array($newRank, $oldRank - 1);
1171        } else {
1172            //入れ替え先の順位が入れ替え元の順位と同じ場合なにもしない
1173            return false;
1174        }
1175
1176        return $objQuery->update($tableName, $sqlval, $where, $arrWhereVal, $arrRawSql);
1177    }
1178
1179    /**
1180     * ランクを含むレコードを削除する.
1181     *
1182     * レコードごと削除する場合は、$deleteをtrueにする
1183     *
1184     * @param string         $table    テーブル名
1185     * @param string         $colname  カラム名
1186     * @param string|integer $id       テーブルのキー
1187     * @param string         $andwhere SQL の AND 条件である WHERE 句
1188     * @param bool           $delete   レコードごと削除する場合 true,
1189     *                     レコードごと削除しない場合 false
1190     * @return void
1191     */
1192    public function sfDeleteRankRecord($table, $colname, $id, $andwhere = '',
1193                                $delete = false) {
1194        $objQuery =& SC_Query_Ex::getSingletonInstance();
1195        $objQuery->begin();
1196        // 削除レコードのランクを取得する。
1197        $where = "$colname = ?";
1198        if ($andwhere != '') {
1199            $where.= " AND $andwhere";
1200        }
1201        $rank = $objQuery->get('rank', $table, $where, array($id));
1202
1203        if (!$delete) {
1204            // ランクを最下位にする、DELフラグON
1205            $sqlval = array(
1206                'rank'      => 0,
1207                'del_flg'   => 1,
1208            );
1209            $where = "$colname = ?";
1210            $arrWhereVal = array($id);
1211            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1212        } else {
1213            $objQuery->delete($table, "$colname = ?", array($id));
1214        }
1215
1216        // 追加レコードのランクより上のレコードを一つずらす。
1217        $sqlval = array();
1218        $where = 'rank > ?';
1219        if ($andwhere != '') {
1220            $where .= " AND $andwhere";
1221        }
1222        $arrWhereVal = array($rank);
1223        $arrRawSql = array(
1224            'rank' => '(rank - 1)',
1225        );
1226        $objQuery->update($table, $sqlval, $where, $arrWhereVal, $arrRawSql);
1227
1228        $objQuery->commit();
1229    }
1230
1231    /**
1232     * 親IDの配列を元に特定のカラムを取得する.
1233     *
1234     * @param  SC_Query $objQuery SC_Query インスタンス
1235     * @param  string   $table    テーブル名
1236     * @param  string   $id_name  ID名
1237     * @param  string   $col_name カラム名
1238     * @param  array    $arrId    IDの配列
1239     * @return array    特定のカラムの配列
1240     */
1241    public function sfGetParentsCol($objQuery, $table, $id_name, $col_name, $arrId)
1242    {
1243        $col = $col_name;
1244        $len = count($arrId);
1245        $where = '';
1246
1247        for ($cnt = 0; $cnt < $len; $cnt++) {
1248            if ($where == '') {
1249                $where = "$id_name = ?";
1250            } else {
1251                $where.= " OR $id_name = ?";
1252            }
1253        }
1254
1255        $objQuery->setOrder('level');
1256        $arrRet = $objQuery->select($col, $table, $where, $arrId);
1257
1258        return $arrRet;
1259    }
1260
1261    /**
1262     * カテゴリ変更時の移動処理を行う.
1263     *
1264     * ※この関数って、どこからも呼ばれていないのでは??
1265     *
1266     * @param  SC_Query $objQuery  SC_Query インスタンス
1267     * @param  string   $table     テーブル名
1268     * @param  string   $id_name   ID名
1269     * @param  string   $cat_name  カテゴリ名
1270     * @param  integer  $old_catid 旧カテゴリID
1271     * @param  integer  $new_catid 新カテゴリID
1272     * @param  integer  $id        ID
1273     * @return void
1274     */
1275    public function sfMoveCatRank($objQuery, $table, $id_name, $cat_name, $old_catid, $new_catid, $id)
1276    {
1277        if ($old_catid == $new_catid) {
1278            return;
1279        }
1280        // 旧カテゴリでのランク削除処理
1281        // 移動レコードのランクを取得する。
1282        $sqlval = array();
1283        $where = "$id_name = ?";
1284        $rank = $objQuery->get('rank', $table, $where, array($id));
1285        // 削除レコードのランクより上のレコードを一つ下にずらす。
1286        $where = "rank > ? AND $cat_name = ?";
1287        $arrWhereVal = array($rank, $old_catid);
1288        $arrRawSql = array(
1289            'rank' => '(rank - 1)',
1290        );
1291        $objQuery->update($table, $sqlval, $where, $arrWhereVal, $arrRawSql);
1292
1293        // 新カテゴリでの登録処理
1294        // 新カテゴリの最大ランクを取得する。
1295        $max_rank = $objQuery->max('rank', $table, "$cat_name = ?", array($new_catid)) + 1;
1296        $sqlval = array(
1297            'rank' => $max_rank,
1298        );
1299        $where = "$id_name = ?";
1300        $arrWhereVal = array($id);
1301        $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1302    }
1303
1304    /**
1305     * レコードの存在チェックを行う.
1306     *
1307     * TODO SC_Query に移行するべきか?
1308     *
1309     * @param  string $table    テーブル名
1310     * @param  string $col      カラム名
1311     * @param  array  $arrVal   要素の配列
1312     * @param  string  $addwhere SQL の AND 条件である WHERE 句
1313     * @return bool   レコードが存在する場合 true
1314     */
1315    public static function sfIsRecord($table, $col, $arrVal, $addwhere = '')
1316    {
1317        $objQuery =& SC_Query_Ex::getSingletonInstance();
1318        $arrCol = preg_split('/[, ]/', $col);
1319
1320        $where = 'del_flg = 0';
1321
1322        if ($addwhere != '') {
1323            $where.= " AND $addwhere";
1324        }
1325
1326        foreach ($arrCol as $val) {
1327            if ($val != '') {
1328                if ($where == '') {
1329                    $where = "$val = ?";
1330                } else {
1331                    $where.= " AND $val = ?";
1332                }
1333            }
1334        }
1335        $ret = $objQuery->get($col, $table, $where, $arrVal);
1336
1337        if ($ret != '') {
1338            return true;
1339        }
1340
1341        return false;
1342    }
1343
1344    /**
1345     * メーカー商品数数の登録を行う.
1346     *
1347     * @param  SC_Query $objQuery SC_Query インスタンス
1348     * @return void
1349     */
1350    public function sfCountMaker($objQuery)
1351    {
1352        $sql = '';
1353
1354        //テーブル内容の削除
1355        $objQuery->query('DELETE FROM dtb_maker_count');
1356
1357        //各メーカーの商品数を数えて格納
1358        $sql = ' INSERT INTO dtb_maker_count(maker_id, product_count, create_date) ';
1359        $sql .= ' SELECT T1.maker_id, count(T2.maker_id), CURRENT_TIMESTAMP ';
1360        $sql .= ' FROM dtb_maker AS T1 LEFT JOIN dtb_products AS T2';
1361        $sql .= ' ON T1.maker_id = T2.maker_id ';
1362        $sql .= ' WHERE T2.del_flg = 0 AND T2.status = 1 ';
1363        $sql .= ' GROUP BY T1.maker_id, T2.maker_id ';
1364        $objQuery->query($sql);
1365    }
1366
1367    /**
1368     * 選択中の商品のメーカーを取得する.
1369     *
1370     * @param  integer $product_id プロダクトID
1371     * @param  integer $maker_id   メーカーID
1372     * @return array   選択中の商品のメーカーIDの配列
1373     *
1374     */
1375    public function sfGetMakerId($product_id, $maker_id = 0, $closed = false)
1376    {
1377        if ($closed) {
1378            $status = '';
1379        } else {
1380            $status = 'status = 1';
1381        }
1382
1383        if (!$this->g_maker_on) {
1384            $this->g_maker_on = true;
1385            $maker_id = (int) $maker_id;
1386            $product_id = (int) $product_id;
1387            if (SC_Utils_Ex::sfIsInt($maker_id) && $maker_id != 0 && $this->sfIsRecord('dtb_maker','maker_id', $maker_id)) {
1388                $this->g_maker_id = array($maker_id);
1389            } elseif (SC_Utils_Ex::sfIsInt($product_id) && $product_id != 0 && $this->sfIsRecord('dtb_products','product_id', $product_id, $status)) {
1390                $objQuery =& SC_Query_Ex::getSingletonInstance();
1391                $maker_id = $objQuery->getCol('maker_id', 'dtb_products', 'product_id = ?', array($product_id));
1392                $this->g_maker_id = $maker_id;
1393            } else {
1394                // 不正な場合は、空の配列を返す。
1395                $this->g_maker_id = array();
1396            }
1397        }
1398
1399        return $this->g_maker_id;
1400    }
1401
1402    /**
1403     * メーカーの取得を行う.
1404     *
1405     * $products_check:true商品登録済みのものだけ取得する
1406     *
1407     * @param  string $addwhere       追加する WHERE 句
1408     * @param  bool   $products_check 商品の存在するカテゴリのみ取得する場合 true
1409     * @return array  カテゴリツリーの配列
1410     */
1411    public function sfGetMakerList($addwhere = '', $products_check = false)
1412    {
1413        $objQuery =& SC_Query_Ex::getSingletonInstance();
1414        $where = 'del_flg = 0';
1415
1416        if ($addwhere != '') {
1417            $where.= " AND $addwhere";
1418        }
1419
1420        $objQuery->setOption('ORDER BY rank DESC');
1421
1422        if ($products_check) {
1423            $col = 'T1.maker_id, name';
1424            $from = 'dtb_maker AS T1 LEFT JOIN dtb_maker_count AS T2 ON T1.maker_id = T2.maker_id';
1425            $where .= ' AND product_count > 0';
1426        } else {
1427            $col = 'maker_id, name';
1428            $from = 'dtb_maker';
1429        }
1430
1431        $arrRet = $objQuery->select($col, $from, $where);
1432
1433        $max = count($arrRet);
1434        $arrList = array();
1435        for ($cnt = 0; $cnt < $max; $cnt++) {
1436            $id = $arrRet[$cnt]['maker_id'];
1437            $name = $arrRet[$cnt]['name'];
1438            $arrList[$id] = $name;
1439        }
1440
1441        return $arrList;
1442    }
1443
1444    /**
1445     * 店舗基本情報に基づいて税金額を返す
1446     *
1447     * @param  integer $price 計算対象の金額
1448     * @return integer 税金額
1449     */
1450    public function sfTax($price)
1451    {
1452        // 店舗基本情報を取得
1453        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1454
1455        return SC_Utils_Ex::sfTax($price, $CONF['tax'], $CONF['tax_rule']);
1456    }
1457
1458    /**
1459     * 店舗基本情報に基づいて税金付与した金額を返す
1460     * SC_Utils_Ex::sfCalcIncTax とどちらか統一したほうが良い
1461     *
1462     * @param  integer $price 計算対象の金額
1463     * @return integer 税金付与した金額
1464     */
1465    public function sfCalcIncTax($price, $tax = null, $tax_rule = null)
1466    {
1467        // 店舗基本情報を取得
1468        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1469        $tax      = $tax      === null ? $CONF['tax']      : $tax;
1470        $tax_rule = $tax_rule === null ? $CONF['tax_rule'] : $tax_rule;
1471
1472        return SC_Utils_Ex::sfCalcIncTax($price, $tax, $tax_rule);
1473    }
1474
1475    /**
1476     * 店舗基本情報に基づいて加算ポイントを返す
1477     *
1478     * @param  integer $totalpoint
1479     * @param  integer $use_point
1480     * @return integer 加算ポイント
1481     */
1482    public function sfGetAddPoint($totalpoint, $use_point)
1483    {
1484        // 店舗基本情報を取得
1485        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1486
1487        return SC_Utils_Ex::sfGetAddPoint($totalpoint, $use_point, $CONF['point_rate']);
1488    }
1489
1490    /**
1491     * 指定ファイルが存在する場合 SQL として実行
1492     *
1493     * XXX プラグイン用に追加。将来消すかも。
1494     *
1495     * @param  string $sqlFilePath SQL ファイルのパス
1496     * @return void
1497     */
1498    public function sfExecSqlByFile($sqlFilePath)
1499    {
1500        if (file_exists($sqlFilePath)) {
1501            $objQuery =& SC_Query_Ex::getSingletonInstance();
1502
1503            $sqls = file_get_contents($sqlFilePath);
1504            if ($sqls === false) trigger_error('ファイルは存在するが読み込めない', E_USER_ERROR);
1505
1506            foreach (explode(';', $sqls) as $sql) {
1507                $sql = trim($sql);
1508                if (strlen($sql) == 0) continue;
1509                $objQuery->query($sql);
1510            }
1511        }
1512    }
1513
1514    /**
1515     * 商品規格を設定しているか
1516     *
1517     * @param  integer $product_id 商品ID
1518     * @return bool    商品規格が存在する場合:true, それ以外:false
1519     */
1520    public function sfHasProductClass($product_id)
1521    {
1522        if (!SC_Utils_Ex::sfIsInt($product_id)) return false;
1523
1524        $objQuery =& SC_Query_Ex::getSingletonInstance();
1525        $where = 'product_id = ? AND del_flg = 0 AND (classcategory_id1 != 0 OR classcategory_id2 != 0)';
1526        $exists = $objQuery->exists('dtb_products_class', $where, array($product_id));
1527
1528        return $exists;
1529    }
1530
1531    /**
1532     * 店舗基本情報を登録する
1533     *
1534     * @param  array $arrData 登録するデータ
1535     * @return void
1536     */
1537    public static function registerBasisData($arrData)
1538    {
1539        $objQuery =& SC_Query_Ex::getSingletonInstance();
1540
1541        $arrData = $objQuery->extractOnlyColsOf('dtb_baseinfo', $arrData);
1542
1543        if (isset($arrData['regular_holiday_ids']) && is_array($arrData['regular_holiday_ids'])) {
1544            // 定休日をパイプ区切りの文字列に変換
1545            $arrData['regular_holiday_ids'] = implode('|', $arrData['regular_holiday_ids']);
1546        }
1547
1548        $arrData['update_date'] = 'CURRENT_TIMESTAMP';
1549
1550        // UPDATEの実行
1551        $ret = $objQuery->update('dtb_baseinfo', $arrData);
1552        GC_Utils_Ex::gfPrintLog('dtb_baseinfo に UPDATE を実行しました。');
1553
1554        // UPDATE できなかった場合、INSERT
1555        if ($ret == 0) {
1556            $arrData['id'] = 1;
1557            $ret = $objQuery->insert('dtb_baseinfo', $arrData);
1558            GC_Utils_Ex::gfPrintLog('dtb_baseinfo に INSERT を実行しました。');
1559        }
1560    }
1561
1562    /**
1563     * レコード件数を計算.
1564     *
1565     * @param  string  $table
1566     * @param  string  $where
1567     * @param  array   $arrval
1568     * @return integer レコード件数
1569     */
1570    public function countRecords($table, $where = '', $arrval = array())
1571    {
1572        $objQuery =& SC_Query_Ex::getSingletonInstance();
1573        $col = 'COUNT(*)';
1574
1575        return $objQuery->get($col, $table, $where, $arrval);
1576    }
1577}
Note: See TracBrowser for help on using the repository browser.