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

Revision 23599, 54.7 KB checked in by kimoto, 10 years ago (diff)

r23598のミス修正

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