source: branches/version-2_12-dev/data/class/helper/SC_Helper_DB.php @ 22595

Revision 22595, 55.5 KB checked in by pineray, 11 years ago (diff)

#2166 カテゴリー情報の取得処理をヘルパークラスへ移動

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