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

Revision 23606, 54.8 KB checked in by kimoto, 10 years ago (diff)

#2448 typo修正・ソース整形・ソースコメントの改善 for 2.13.3

 https://scrutinizer-ci.com/g/nobuhiko/EC-CUBE/inspections/e0f27994-b3c7-4fc6-ad70-55d3cd63769b/patches

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