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

Revision 23124, 56.8 KB checked in by kimoto, 11 years ago (diff)

#2043 typo修正・ソース整形・ソースコメントの改善 for 2.13.0
PHP4的な書き方の修正

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