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

Revision 22567, 55.6 KB checked in by shutta, 11 years ago (diff)

#2043 (typo修正・ソース整形・ソースコメントの改善 for 2.12.4)
Zend Framework PHP 標準コーディング規約のコーディングスタイルへ準拠。
classおよびfunctionの開始波括弧「{」のスタイルを修正。

  • 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_Helper_DB_Ex::sfGetParents('dtb_category', 'parent_category_id', 'category_id', $parent_category_id);
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 sfGetCat($category_id)
469    {
470        $objQuery =& SC_Query_Ex::getSingletonInstance();
471
472        // カテゴリを取得する
473        $arrVal = array($category_id);
474        $res = $objQuery->select('category_id AS id, category_name AS name', 'dtb_category', 'category_id = ?', $arrVal);
475
476        return $res[0];
477    }
478
479    /**
480     * 指定したカテゴリIDの大カテゴリを取得する.
481     *
482     * @param integer $category_id カテゴリID
483     * @return array 指定したカテゴリIDの大カテゴリ
484     */
485    function sfGetFirstCat($category_id)
486    {
487        // 商品が属するカテゴリIDを縦に取得
488        $objQuery =& SC_Query_Ex::getSingletonInstance();
489        $arrRet = array();
490        $arrCatID = $this->sfGetParents('dtb_category', 'parent_category_id', 'category_id', $category_id);
491        $arrRet['id'] = $arrCatID[0];
492
493        // カテゴリ名称を取得する
494        $sql = 'SELECT category_name FROM dtb_category WHERE category_id = ?';
495        $arrVal = array($arrRet['id']);
496        $arrRet['name'] = $objQuery->getOne($sql,$arrVal);
497
498        return $arrRet;
499    }
500
501    /**
502     * カテゴリツリーの取得を行う.
503     *
504     * $products_check:true商品登録済みのものだけ取得する
505     *
506     * @param string $addwhere 追加する WHERE 句
507     * @param bool $products_check 商品の存在するカテゴリのみ取得する場合 true
508     * @param string $head カテゴリ名のプレフィックス文字列
509     * @return array カテゴリツリーの配列
510     */
511    function sfGetCategoryList($addwhere = '', $products_check = false, $head = CATEGORY_HEAD)
512    {
513        $objQuery =& SC_Query_Ex::getSingletonInstance();
514        $where = 'del_flg = 0';
515
516        if ($addwhere != '') {
517            $where.= " AND $addwhere";
518        }
519
520        $objQuery->setOption('ORDER BY rank DESC');
521
522        if ($products_check) {
523            $col = 'T1.category_id, category_name, level';
524            $from = 'dtb_category AS T1 LEFT JOIN dtb_category_total_count AS T2 ON T1.category_id = T2.category_id';
525            $where .= ' AND product_count > 0';
526        } else {
527            $col = 'category_id, category_name, level';
528            $from = 'dtb_category';
529        }
530
531        $arrRet = $objQuery->select($col, $from, $where);
532
533        $max = count($arrRet);
534        $arrList = array();
535        for ($cnt = 0; $cnt < $max; $cnt++) {
536            $id = $arrRet[$cnt]['category_id'];
537            $name = $arrRet[$cnt]['category_name'];
538            $arrList[$id] = str_repeat($head, $arrRet[$cnt]['level']) . $name;
539        }
540        return $arrList;
541    }
542
543    /**
544     * カテゴリツリーの取得を行う.
545     *
546     * 親カテゴリの Value=0 を対象とする
547     *
548     * @param bool $parent_zero 親カテゴリの Value=0 の場合 true
549     * @return array カテゴリツリーの配列
550     */
551    function sfGetLevelCatList($parent_zero = true)
552    {
553        $objQuery =& SC_Query_Ex::getSingletonInstance();
554
555        // カテゴリ名リストを取得
556        $col = 'category_id, parent_category_id, category_name';
557        $where = 'del_flg = 0';
558        $objQuery->setOption('ORDER BY level');
559        $arrRet = $objQuery->select($col, 'dtb_category', $where);
560        $arrCatName = array();
561        foreach ($arrRet as $arrTmp) {
562            $arrCatName[$arrTmp['category_id']] =
563                (($arrTmp['parent_category_id'] > 0)?
564                    $arrCatName[$arrTmp['parent_category_id']] : '')
565                . CATEGORY_HEAD . $arrTmp['category_name'];
566        }
567
568        $col = 'category_id, parent_category_id, category_name, level';
569        $where = 'del_flg = 0';
570        $objQuery->setOption('ORDER BY rank DESC');
571        $arrRet = $objQuery->select($col, 'dtb_category', $where);
572        $max = count($arrRet);
573
574        $arrValue = array();
575        $arrOutput = array();
576        for ($cnt = 0; $cnt < $max; $cnt++) {
577            if ($parent_zero) {
578                if ($arrRet[$cnt]['level'] == LEVEL_MAX) {
579                    $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
580                } else {
581                    $arrValue[$cnt] = '';
582                }
583            } else {
584                $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
585            }
586
587            $arrOutput[$cnt] = $arrCatName[$arrRet[$cnt]['category_id']];
588        }
589
590        return array($arrValue, $arrOutput);
591    }
592
593    /**
594     * 選択中の商品のカテゴリを取得する.
595     *
596     * @param integer $product_id プロダクトID
597     * @param integer $category_id カテゴリID
598     * @return array 選択中の商品のカテゴリIDの配列
599     *
600     */
601    function sfGetCategoryId($product_id, $category_id = 0, $closed = false)
602    {
603        if ($closed) {
604            $status = '';
605        } else {
606            $status = 'status = 1';
607        }
608        $category_id = (int) $category_id;
609        $product_id = (int) $product_id;
610        if (SC_Utils_Ex::sfIsInt($category_id) && $category_id != 0 && SC_Helper_DB_Ex::sfIsRecord('dtb_category','category_id', $category_id)) {
611            $category_id = array($category_id);
612        } else if (SC_Utils_Ex::sfIsInt($product_id) && $product_id != 0 && SC_Helper_DB_Ex::sfIsRecord('dtb_products','product_id', $product_id, $status)) {
613            $objQuery =& SC_Query_Ex::getSingletonInstance();
614            $category_id = $objQuery->getCol('category_id', 'dtb_product_categories', 'product_id = ?', array($product_id));
615        } else {
616            // 不正な場合は、空の配列を返す。
617            $category_id = array();
618        }
619        return $category_id;
620    }
621
622    /**
623     * 商品をカテゴリの先頭に追加する.
624     *
625     * @param integer $category_id カテゴリID
626     * @param integer $product_id プロダクトID
627     * @return void
628     */
629    function addProductBeforCategories($category_id, $product_id)
630    {
631        $objQuery =& SC_Query_Ex::getSingletonInstance();
632
633        $sqlval = array('category_id' => $category_id,
634                        'product_id' => $product_id);
635
636        $arrSql = array();
637        $arrSql['rank'] = '(SELECT COALESCE(MAX(rank), 0) FROM dtb_product_categories sub WHERE category_id = ?) + 1';
638
639        $from_and_where = $objQuery->dbFactory->getDummyFromClauseSql();
640        $from_and_where .= ' WHERE NOT EXISTS(SELECT * FROM dtb_product_categories WHERE category_id = ? AND product_id = ?)';
641        $objQuery->insert('dtb_product_categories', $sqlval, $arrSql, array($category_id), $from_and_where, array($category_id, $product_id));
642    }
643
644    /**
645     * 商品をカテゴリの末尾に追加する.
646     *
647     * @param integer $category_id カテゴリID
648     * @param integer $product_id プロダクトID
649     * @return void
650     */
651    function addProductAfterCategories($category_id, $product_id)
652    {
653        $sqlval = array('category_id' => $category_id,
654                        'product_id' => $product_id);
655
656        $objQuery =& SC_Query_Ex::getSingletonInstance();
657
658        // 現在の商品カテゴリを取得
659        $arrCat = $objQuery->select('product_id, category_id, rank',
660                                    'dtb_product_categories',
661                                    'category_id = ?',
662                                    array($category_id));
663
664        $min = 0;
665        foreach ($arrCat as $val) {
666            // 同一商品が存在する場合は登録しない
667            if ($val['product_id'] == $product_id) {
668                return;
669            }
670            // 最下位ランクを取得
671            $min = ($min < $val['rank']) ? $val['rank'] : $min;
672        }
673        $sqlval['rank'] = $min;
674        $objQuery->insert('dtb_product_categories', $sqlval);
675    }
676
677    /**
678     * 商品をカテゴリから削除する.
679     *
680     * @param integer $category_id カテゴリID
681     * @param integer $product_id プロダクトID
682     * @return void
683     */
684    function removeProductByCategories($category_id, $product_id)
685    {
686        $objQuery =& SC_Query_Ex::getSingletonInstance();
687        $objQuery->delete('dtb_product_categories',
688                          'category_id = ? AND product_id = ?', array($category_id, $product_id));
689    }
690
691    /**
692     * 商品カテゴリを更新する.
693     *
694     * @param array $arrCategory_id 登録するカテゴリIDの配列
695     * @param integer $product_id プロダクトID
696     * @return void
697     */
698    function updateProductCategories($arrCategory_id, $product_id)
699    {
700        $objQuery =& SC_Query_Ex::getSingletonInstance();
701
702        // 現在のカテゴリ情報を取得
703        $arrCurrentCat = $objQuery->getCol('category_id',
704                                           'dtb_product_categories',
705                                           'product_id = ?',
706                                           array($product_id));
707
708        // 登録するカテゴリ情報と比較
709        foreach ($arrCurrentCat as $category_id) {
710
711            // 登録しないカテゴリを削除
712            if (!in_array($category_id, $arrCategory_id)) {
713                $this->removeProductByCategories($category_id, $product_id);
714            }
715        }
716
717        // カテゴリを登録
718        foreach ($arrCategory_id as $category_id) {
719            $this->addProductBeforCategories($category_id, $product_id);
720            SC_Utils_Ex::extendTimeOut();
721        }
722    }
723
724    /**
725     * カテゴリ数の登録を行う.
726     *
727     *
728     * @param SC_Query $objQuery SC_Query インスタンス
729     * @param boolean $is_force_all_count 全カテゴリの集計を強制する場合 true
730     * @return void
731     */
732    function sfCountCategory($objQuery = NULL, $is_force_all_count = false)
733    {
734        $objProduct = new SC_Product_Ex();
735
736        if ($objQuery == NULL) {
737            $objQuery =& SC_Query_Ex::getSingletonInstance();
738        }
739
740        $is_out_trans = false;
741        if (!$objQuery->inTransaction()) {
742            $objQuery->begin();
743            $is_out_trans = true;
744        }
745
746        //共通のfrom/where文の構築
747        $sql_where = 'alldtl.del_flg = 0 AND alldtl.status = 1';
748        // 在庫無し商品の非表示
749        if (NOSTOCK_HIDDEN) {
750            $where_products_class = '(stock >= 1 OR stock_unlimited = 1)';
751            $from = $objProduct->alldtlSQL($where_products_class);
752        } else {
753            $from = 'dtb_products as alldtl';
754        }
755
756        //dtb_category_countの構成
757        // 各カテゴリに所属する商品の数を集計。集計対象には子カテゴリを含まない。
758
759        //まずテーブル内容の元を取得
760        if (!$is_force_all_count) {
761            $arrCategoryCountOld = $objQuery->select('category_id,product_count','dtb_category_count');
762        } else {
763            $arrCategoryCountOld = array();
764        }
765
766        //各カテゴリ内の商品数を数えて取得
767        $sql = <<< __EOS__
768            SELECT T1.category_id, count(T2.category_id) as product_count
769            FROM dtb_category AS T1
770                LEFT JOIN dtb_product_categories AS T2
771                    ON T1.category_id = T2.category_id
772                LEFT JOIN $from
773                    ON T2.product_id = alldtl.product_id
774            WHERE $sql_where
775            GROUP BY T1.category_id, T2.category_id
776__EOS__;
777
778        $arrCategoryCountNew = $objQuery->getAll($sql);
779        // 各カテゴリに所属する商品の数を集計。集計対象には子カテゴリを「含む」。
780        //差分を取得して、更新対象カテゴリだけを確認する。
781
782        //各カテゴリ毎のデータ値において以前との差を見る
783        //古いデータの構造入れ替え
784        $arrOld = array();
785        foreach ($arrCategoryCountOld as $item) {
786            $arrOld[$item['category_id']] = $item['product_count'];
787        }
788        //新しいデータの構造入れ替え
789        $arrNew = array();
790        foreach ($arrCategoryCountNew as $item) {
791            $arrNew[$item['category_id']] = $item['product_count'];
792        }
793
794        unset($arrCategoryCountOld);
795        unset($arrCategoryCountNew);
796
797        $arrDiffCategory_id = array();
798        //新しいカテゴリ一覧から見て商品数が異なるデータが無いか確認
799        foreach ($arrNew as $cid => $count) {
800            if ($arrOld[$cid] != $count) {
801                $arrDiffCategory_id[] = $cid;
802            }
803        }
804        //削除カテゴリを想定して、古いカテゴリ一覧から見て商品数が異なるデータが無いか確認。
805        foreach ($arrOld as $cid => $count) {
806            if ($arrNew[$cid] != $count && $count > 0) {
807                $arrDiffCategory_id[] = $cid;
808            }
809        }
810
811        //対象IDが無ければ終了
812        if (count($arrDiffCategory_id) == 0) {
813            if ($is_out_trans) {
814                $objQuery->commit();
815            }
816            return;
817        }
818
819        //差分対象カテゴリIDの重複を除去
820        $arrDiffCategory_id = array_unique($arrDiffCategory_id);
821
822        //dtb_category_countの更新 差分のあったカテゴリだけ更新する。
823        foreach ($arrDiffCategory_id as $cid) {
824            $sqlval = array();
825            $sqlval['create_date'] = 'CURRENT_TIMESTAMP';
826            $sqlval['product_count'] = (string)$arrNew[$cid];
827            if ($sqlval['product_count'] =='') {
828                $sqlval['product_count'] = (string)'0';
829            }
830            if (isset($arrOld[$cid])) {
831                $objQuery->update('dtb_category_count', $sqlval, 'category_id = ?', array($cid));
832            } else {
833                if ($is_force_all_count) {
834                    $ret = $objQuery->update('dtb_category_count', $sqlval, 'category_id = ?', array($cid));
835                    if ($ret > 0) {
836                        continue;
837                    }
838                }
839                $sqlval['category_id'] = $cid;
840                $objQuery->insert('dtb_category_count', $sqlval);
841            }
842        }
843
844        unset($arrOld);
845        unset($arrNew);
846
847        //差分があったIDとその親カテゴリIDのリストを取得する
848        $arrTgtCategory_id = array();
849        foreach ($arrDiffCategory_id as $parent_category_id) {
850            $arrTgtCategory_id[] = $parent_category_id;
851            $arrParentID = $this->sfGetParents('dtb_category', 'parent_category_id', 'category_id', $parent_category_id);
852            $arrTgtCategory_id = array_unique(array_merge($arrTgtCategory_id, $arrParentID));
853        }
854
855        unset($arrDiffCategory_id);
856
857        //dtb_category_total_count 集計処理開始
858        //更新対象カテゴリIDだけ集計しなおす。
859        $arrUpdateData = array();
860        $where_products_class = '';
861        if (NOSTOCK_HIDDEN) {
862            $where_products_class .= '(stock >= 1 OR stock_unlimited = 1)';
863        }
864        $from = $objProduct->alldtlSQL($where_products_class);
865        foreach ($arrTgtCategory_id as $category_id) {
866            $arrWhereVal = array();
867            list($tmp_where, $arrTmpVal) = $this->sfGetCatWhere($category_id);
868            if ($tmp_where != '') {
869                $sql_where_product_ids = 'product_id IN (SELECT product_id FROM dtb_product_categories WHERE ' . $tmp_where . ')';
870                $arrWhereVal = $arrTmpVal;
871            } else {
872                $sql_where_product_ids = '0<>0'; // 一致させない
873            }
874            $where = "($sql_where) AND ($sql_where_product_ids)";
875
876            $arrUpdateData[$category_id] = $objQuery->count($from, $where, $arrWhereVal);
877        }
878
879        unset($arrTgtCategory_id);
880
881        // 更新対象だけを更新。
882        foreach ($arrUpdateData as $cid => $count) {
883            $sqlval = array();
884            $sqlval['create_date'] = 'CURRENT_TIMESTAMP';
885            $sqlval['product_count'] = $count;
886            if ($sqlval['product_count'] =='') {
887                $sqlval['product_count'] = (string)'0';
888            }
889            $ret = $objQuery->update('dtb_category_total_count', $sqlval, 'category_id = ?', array($cid));
890            if (!$ret) {
891                $sqlval['category_id'] = $cid;
892                $ret = $objQuery->insert('dtb_category_total_count', $sqlval);
893            }
894        }
895        // トランザクション終了処理
896        if ($is_out_trans) {
897            $objQuery->commit();
898        }
899    }
900
901    /**
902     * 子IDの配列を返す.
903     *
904     * @param string $table テーブル名
905     * @param string $pid_name 親ID名
906     * @param string $id_name ID名
907     * @param integer $id ID
908     * @param array 子ID の配列
909     */
910    function sfGetChildsID($table, $pid_name, $id_name, $id)
911    {
912        $arrRet = $this->sfGetChildrenArray($table, $pid_name, $id_name, $id);
913        return $arrRet;
914    }
915
916    /**
917     * 階層構造のテーブルから子ID配列を取得する.
918     *
919     * @param string $table テーブル名
920     * @param string $pid_name 親ID名
921     * @param string $id_name ID名
922     * @param integer $id ID番号
923     * @return array 子IDの配列
924     */
925    function sfGetChildrenArray($table, $pid_name, $id_name, $id)
926    {
927        $arrChildren = array();
928        $arrRet = array($id);
929
930        while (count($arrRet) > 0) {
931            $arrChildren = array_merge($arrChildren, $arrRet);
932            $arrRet = SC_Helper_DB_Ex::sfGetChildrenArraySub($table, $pid_name, $id_name, $arrRet);
933        }
934
935        return $arrChildren;
936    }
937
938    /**
939     * 親ID直下の子IDをすべて取得する.
940     *
941     * @param array $arrData 親カテゴリの配列
942     * @param string $pid_name 親ID名
943     * @param string $id_name ID名
944     * @param array $arrPID 親IDの配列
945     * @return array 子IDの配列
946     */
947    function sfGetChildrenArraySub($table, $pid_name, $id_name, $arrPID)
948    {
949        $objQuery =& SC_Query_Ex::getSingletonInstance();
950
951        $where = "$pid_name IN (" . SC_Utils_Ex::repeatStrWithSeparator('?', count($arrPID)) . ')';
952
953        $return = $objQuery->getCol($id_name, $table, $where, $arrPID);
954
955        return $return;
956    }
957
958    /**
959     * 所属するすべての階層の親IDを配列で返す.
960     *
961     * @param SC_Query $objQuery SC_Query インスタンス
962     * @param string $table テーブル名
963     * @param string $pid_name 親ID名
964     * @param string $id_name ID名
965     * @param integer $id ID
966     * @return array 親IDの配列
967     */
968    function sfGetParents($table, $pid_name, $id_name, $id)
969    {
970        $arrRet = SC_Helper_DB_Ex::sfGetParentsArray($table, $pid_name, $id_name, $id);
971        return $arrRet;
972    }
973
974    /**
975     * 階層構造のテーブルから親ID配列を取得する.
976     *
977     * @param string $table テーブル名
978     * @param string $pid_name 親ID名
979     * @param string $id_name ID名
980     * @param integer $id ID
981     * @return array 親IDの配列
982     */
983    function sfGetParentsArray($table, $pid_name, $id_name, $id)
984    {
985        $arrParents = array();
986        $ret = $id;
987
988        while ($ret != '0' && !SC_Utils_Ex::isBlank($ret)) {
989            $arrParents[] = $ret;
990            $ret = SC_Helper_DB_Ex::sfGetParentsArraySub($table, $pid_name, $id_name, $ret);
991        }
992
993        $arrParents = array_reverse($arrParents);
994
995        return $arrParents;
996    }
997
998    /* 子ID所属する親IDを取得する */
999    function sfGetParentsArraySub($table, $pid_name, $id_name, $child)
1000    {
1001        if (SC_Utils_Ex::isBlank($child)) {
1002            return false;
1003        }
1004        $objQuery =& SC_Query_Ex::getSingletonInstance();
1005        if (!is_array($child)) {
1006            $child = array($child);
1007        }
1008        $parent = $objQuery->get($pid_name, $table, "$id_name = ?", $child);
1009        return $parent;
1010    }
1011
1012    /**
1013     * カテゴリから商品を検索する場合のWHERE文と値を返す.
1014     *
1015     * @param integer $category_id カテゴリID
1016     * @return array 商品を検索する場合の配列
1017     */
1018    function sfGetCatWhere($category_id)
1019    {
1020        // 子カテゴリIDの取得
1021        $arrRet = SC_Helper_DB_Ex::sfGetChildrenArray('dtb_category', 'parent_category_id', 'category_id', $category_id);
1022
1023        $where = 'category_id IN (' . SC_Utils_Ex::repeatStrWithSeparator('?', count($arrRet)) . ')';
1024
1025        return array($where, $arrRet);
1026    }
1027
1028    /**
1029     * SELECTボックス用リストを作成する.
1030     *
1031     * @param string $table テーブル名
1032     * @param string $keyname プライマリーキーのカラム名
1033     * @param string $valname データ内容のカラム名
1034     * @param string $where WHERE句
1035     * @param array $arrWhereVal プレースホルダ
1036     * @return array SELECT ボックス用リストの配列
1037     */
1038    function sfGetIDValueList($table, $keyname, $valname, $where = '', $arrVal = array())
1039    {
1040        $objQuery =& SC_Query_Ex::getSingletonInstance();
1041        $col = "$keyname, $valname";
1042        $objQuery->setWhere('del_flg = 0');
1043        $objQuery->setOrder('rank DESC');
1044        $arrList = $objQuery->select($col, $table, $where, $arrVal);
1045        $count = count($arrList);
1046        $arrRet = array();
1047        for ($cnt = 0; $cnt < $count; $cnt++) {
1048            $key = $arrList[$cnt][$keyname];
1049            $val = $arrList[$cnt][$valname];
1050            $arrRet[$key] = $val;
1051        }
1052        return $arrRet;
1053    }
1054
1055    /**
1056     * ランキングを上げる.
1057     *
1058     * @param string $table テーブル名
1059     * @param string $colname カラム名
1060     * @param string|integer $id テーブルのキー
1061     * @param string $andwhere SQL の AND 条件である WHERE 句
1062     * @return void
1063     */
1064    function sfRankUp($table, $colname, $id, $andwhere = '')
1065    {
1066        $objQuery =& SC_Query_Ex::getSingletonInstance();
1067        $objQuery->begin();
1068        $where = "$colname = ?";
1069        if ($andwhere != '') {
1070            $where.= " AND $andwhere";
1071        }
1072        // 対象項目のランクを取得
1073        $rank = $objQuery->get('rank', $table, $where, array($id));
1074        // ランクの最大値を取得
1075        $maxrank = $objQuery->max('rank', $table, $andwhere);
1076        // ランクが最大値よりも小さい場合に実行する。
1077        if ($rank < $maxrank) {
1078            // ランクが一つ上のIDを取得する。
1079            $where = 'rank = ?';
1080            if ($andwhere != '') {
1081                $where.= " AND $andwhere";
1082            }
1083            $uprank = $rank + 1;
1084            $up_id = $objQuery->get($colname, $table, $where, array($uprank));
1085
1086            // ランク入れ替えの実行
1087            $where = "$colname = ?";
1088            if ($andwhere != '') {
1089                $where .= " AND $andwhere";
1090            }
1091
1092            $sqlval = array(
1093                'rank' => $rank + 1,
1094            );
1095            $arrWhereVal = array($id);
1096            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1097
1098            $sqlval = array(
1099                'rank' => $rank,
1100            );
1101            $arrWhereVal = array($up_id);
1102            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1103        }
1104        $objQuery->commit();
1105    }
1106
1107    /**
1108     * ランキングを下げる.
1109     *
1110     * @param string $table テーブル名
1111     * @param string $colname カラム名
1112     * @param string|integer $id テーブルのキー
1113     * @param string $andwhere SQL の AND 条件である WHERE 句
1114     * @return void
1115     */
1116    function sfRankDown($table, $colname, $id, $andwhere = '')
1117    {
1118        $objQuery =& SC_Query_Ex::getSingletonInstance();
1119        $objQuery->begin();
1120        $where = "$colname = ?";
1121        if ($andwhere != '') {
1122            $where.= " AND $andwhere";
1123        }
1124        // 対象項目のランクを取得
1125        $rank = $objQuery->get('rank', $table, $where, array($id));
1126
1127        // ランクが1(最小値)よりも大きい場合に実行する。
1128        if ($rank > 1) {
1129            // ランクが一つ下のIDを取得する。
1130            $where = 'rank = ?';
1131            if ($andwhere != '') {
1132                $where.= " AND $andwhere";
1133            }
1134            $downrank = $rank - 1;
1135            $down_id = $objQuery->get($colname, $table, $where, array($downrank));
1136
1137            // ランク入れ替えの実行
1138            $where = "$colname = ?";
1139            if ($andwhere != '') {
1140                $where .= " AND $andwhere";
1141            }
1142
1143            $sqlval = array(
1144                'rank' => $rank - 1,
1145            );
1146            $arrWhereVal = array($id);
1147            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1148
1149            $sqlval = array(
1150                'rank' => $rank,
1151            );
1152            $arrWhereVal = array($down_id);
1153            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1154        }
1155        $objQuery->commit();
1156    }
1157
1158    /**
1159     * 指定順位へ移動する.
1160     *
1161     * @param string $tableName テーブル名
1162     * @param string $keyIdColumn キーを保持するカラム名
1163     * @param string|integer $keyId キーの値
1164     * @param integer $pos 指定順位
1165     * @param string $where SQL の AND 条件である WHERE 句
1166     * @return void
1167     */
1168    function sfMoveRank($tableName, $keyIdColumn, $keyId, $pos, $where = '')
1169    {
1170        $objQuery =& SC_Query_Ex::getSingletonInstance();
1171        $objQuery->begin();
1172
1173        // 自身のランクを取得する
1174        if ($where != '') {
1175            $getWhere = "$keyIdColumn = ? AND " . $where;
1176        } else {
1177            $getWhere = "$keyIdColumn = ?";
1178        }
1179        $rank = $objQuery->get('rank', $tableName, $getWhere, array($keyId));
1180
1181        $max = $objQuery->max('rank', $tableName, $where);
1182
1183        // 値の調整(逆順)
1184        if ($pos > $max) {
1185            $position = 1;
1186        } else if ($pos < 1) {
1187            $position = $max;
1188        } else {
1189            $position = $max - $pos + 1;
1190        }
1191
1192        //入れ替え先の順位が入れ換え元の順位より大きい場合
1193        if ($position > $rank) $term = 'rank - 1';
1194
1195        //入れ替え先の順位が入れ換え元の順位より小さい場合
1196        if ($position < $rank) $term = 'rank + 1';
1197
1198        // XXX 入れ替え先の順位が入れ替え元の順位と同じ場合
1199        if (!isset($term)) $term = 'rank';
1200
1201        // 指定した順位の商品から移動させる商品までのrankを1つずらす
1202        $sqlval = array();
1203        $arrRawSql = array(
1204            'rank' => $term,
1205        );
1206        $str_where = 'rank BETWEEN ? AND ?';
1207        if ($where != '') {
1208            $str_where .= " AND $where";
1209        }
1210
1211        if ($position > $rank) {
1212            $arrWhereVal = array($rank + 1, $position);
1213            $objQuery->update($tableName, $sqlval, $str_where, $arrWhereVal, $arrRawSql);
1214        }
1215        if ($position < $rank) {
1216            $arrWhereVal = array($position, $rank - 1);
1217            $objQuery->update($tableName, $sqlval, $str_where, $arrWhereVal, $arrRawSql);
1218        }
1219
1220        // 指定した順位へrankを書き換える。
1221        $sqlval = array(
1222            'rank' => $position,
1223        );
1224        $str_where = "$keyIdColumn = ?";
1225        if ($where != '') {
1226            $str_where .= " AND $where";
1227        }
1228        $arrWhereVal = array($keyId);
1229        $objQuery->update($tableName, $sqlval, $str_where, $arrWhereVal);
1230
1231        $objQuery->commit();
1232    }
1233
1234    /**
1235     * ランクを含むレコードを削除する.
1236     *
1237     * レコードごと削除する場合は、$deleteをtrueにする
1238     *
1239     * @param string $table テーブル名
1240     * @param string $colname カラム名
1241     * @param string|integer $id テーブルのキー
1242     * @param string $andwhere SQL の AND 条件である WHERE 句
1243     * @param bool $delete レコードごと削除する場合 true,
1244     *                     レコードごと削除しない場合 false
1245     * @return void
1246     */
1247    function sfDeleteRankRecord($table, $colname, $id, $andwhere = '',
1248                                $delete = false) {
1249        $objQuery =& SC_Query_Ex::getSingletonInstance();
1250        $objQuery->begin();
1251        // 削除レコードのランクを取得する。
1252        $where = "$colname = ?";
1253        if ($andwhere != '') {
1254            $where.= " AND $andwhere";
1255        }
1256        $rank = $objQuery->get('rank', $table, $where, array($id));
1257
1258        if (!$delete) {
1259            // ランクを最下位にする、DELフラグON
1260            $sqlval = array(
1261                'rank'      => 0,
1262                'del_flg'   => 1,
1263            );
1264            $where = "$colname = ?";
1265            $arrWhereVal = array($id);
1266            $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1267        } else {
1268            $objQuery->delete($table, "$colname = ?", array($id));
1269        }
1270
1271        // 追加レコードのランクより上のレコードを一つずらす。
1272        $sqlval = array();
1273        $where = 'rank > ?';
1274        if ($andwhere != '') {
1275            $where .= " AND $andwhere";
1276        }
1277        $arrWhereVal = array($rank);
1278        $arrRawSql = array(
1279            'rank' => '(rank - 1)',
1280        );
1281        $objQuery->update($table, $sqlval, $where, $arrWhereVal, $arrRawSql);
1282
1283        $objQuery->commit();
1284    }
1285
1286    /**
1287     * 親IDの配列を元に特定のカラムを取得する.
1288     *
1289     * @param SC_Query $objQuery SC_Query インスタンス
1290     * @param string $table テーブル名
1291     * @param string $id_name ID名
1292     * @param string $col_name カラム名
1293     * @param array $arrId IDの配列
1294     * @return array 特定のカラムの配列
1295     */
1296    function sfGetParentsCol($objQuery, $table, $id_name, $col_name, $arrId)
1297    {
1298        $col = $col_name;
1299        $len = count($arrId);
1300        $where = '';
1301
1302        for ($cnt = 0; $cnt < $len; $cnt++) {
1303            if ($where == '') {
1304                $where = "$id_name = ?";
1305            } else {
1306                $where.= " OR $id_name = ?";
1307            }
1308        }
1309
1310        $objQuery->setOrder('level');
1311        $arrRet = $objQuery->select($col, $table, $where, $arrId);
1312        return $arrRet;
1313    }
1314
1315    /**
1316     * カテゴリ変更時の移動処理を行う.
1317     *
1318     * ※この関数って、どこからも呼ばれていないのでは??
1319     *
1320     * @param SC_Query $objQuery SC_Query インスタンス
1321     * @param string $table テーブル名
1322     * @param string $id_name ID名
1323     * @param string $cat_name カテゴリ名
1324     * @param integer $old_catid 旧カテゴリID
1325     * @param integer $new_catid 新カテゴリID
1326     * @param integer $id ID
1327     * @return void
1328     */
1329    function sfMoveCatRank($objQuery, $table, $id_name, $cat_name, $old_catid, $new_catid, $id)
1330    {
1331        if ($old_catid == $new_catid) {
1332            return;
1333        }
1334        // 旧カテゴリでのランク削除処理
1335        // 移動レコードのランクを取得する。
1336        $sqlval = array();
1337        $where = "$id_name = ?";
1338        $rank = $objQuery->get('rank', $table, $where, array($id));
1339        // 削除レコードのランクより上のレコードを一つ下にずらす。
1340        $where = "rank > ? AND $cat_name = ?";
1341        $arrWhereVal = array($rank, $old_catid);
1342        $arrRawSql = array(
1343            'rank' => '(rank - 1)',
1344        );
1345        $objQuery->update($table, $sqlval, $where, $arrWhereVal, $arrRawSql);
1346
1347        // 新カテゴリでの登録処理
1348        // 新カテゴリの最大ランクを取得する。
1349        $max_rank = $objQuery->max('rank', $table, "$cat_name = ?", array($new_catid)) + 1;
1350        $sqlval = array(
1351            'rank' => $max_rank,
1352        );
1353        $where = "$id_name = ?";
1354        $arrWhereVal = array($id);
1355        $objQuery->update($table, $sqlval, $where, $arrWhereVal);
1356    }
1357
1358    /**
1359     * レコードの存在チェックを行う.
1360     *
1361     * TODO SC_Query に移行するべきか?
1362     *
1363     * @param string $table テーブル名
1364     * @param string $col カラム名
1365     * @param array $arrVal 要素の配列
1366     * @param array $addwhere SQL の AND 条件である WHERE 句
1367     * @return bool レコードが存在する場合 true
1368     */
1369    function sfIsRecord($table, $col, $arrVal, $addwhere = '')
1370    {
1371        $objQuery =& SC_Query_Ex::getSingletonInstance();
1372        $arrCol = preg_split('/[, ]/', $col);
1373
1374        $where = 'del_flg = 0';
1375
1376        if ($addwhere != '') {
1377            $where.= " AND $addwhere";
1378        }
1379
1380        foreach ($arrCol as $val) {
1381            if ($val != '') {
1382                if ($where == '') {
1383                    $where = "$val = ?";
1384                } else {
1385                    $where.= " AND $val = ?";
1386                }
1387            }
1388        }
1389        $ret = $objQuery->get($col, $table, $where, $arrVal);
1390
1391        if ($ret != '') {
1392            return true;
1393        }
1394        return false;
1395    }
1396
1397    /**
1398     * メーカー商品数数の登録を行う.
1399     *
1400     * @param SC_Query $objQuery SC_Query インスタンス
1401     * @return void
1402     */
1403    function sfCountMaker($objQuery)
1404    {
1405        $sql = '';
1406
1407        //テーブル内容の削除
1408        $objQuery->query('DELETE FROM dtb_maker_count');
1409
1410        //各メーカーの商品数を数えて格納
1411        $sql = ' INSERT INTO dtb_maker_count(maker_id, product_count, create_date) ';
1412        $sql .= ' SELECT T1.maker_id, count(T2.maker_id), CURRENT_TIMESTAMP ';
1413        $sql .= ' FROM dtb_maker AS T1 LEFT JOIN dtb_products AS T2';
1414        $sql .= ' ON T1.maker_id = T2.maker_id ';
1415        $sql .= ' WHERE T2.del_flg = 0 AND T2.status = 1 ';
1416        $sql .= ' GROUP BY T1.maker_id, T2.maker_id ';
1417        $objQuery->query($sql);
1418    }
1419
1420    /**
1421     * 選択中の商品のメーカーを取得する.
1422     *
1423     * @param integer $product_id プロダクトID
1424     * @param integer $maker_id メーカーID
1425     * @return array 選択中の商品のメーカーIDの配列
1426     *
1427     */
1428    function sfGetMakerId($product_id, $maker_id = 0, $closed = false)
1429    {
1430        if ($closed) {
1431            $status = '';
1432        } else {
1433            $status = 'status = 1';
1434        }
1435
1436        if (!$this->g_maker_on) {
1437            $this->g_maker_on = true;
1438            $maker_id = (int) $maker_id;
1439            $product_id = (int) $product_id;
1440            if (SC_Utils_Ex::sfIsInt($maker_id) && $maker_id != 0 && $this->sfIsRecord('dtb_maker','maker_id', $maker_id)) {
1441                $this->g_maker_id = array($maker_id);
1442            } else if (SC_Utils_Ex::sfIsInt($product_id) && $product_id != 0 && $this->sfIsRecord('dtb_products','product_id', $product_id, $status)) {
1443                $objQuery =& SC_Query_Ex::getSingletonInstance();
1444                $maker_id = $objQuery->getCol('maker_id', 'dtb_products', 'product_id = ?', array($product_id));
1445                $this->g_maker_id = $maker_id;
1446            } else {
1447                // 不正な場合は、空の配列を返す。
1448                $this->g_maker_id = array();
1449            }
1450        }
1451        return $this->g_maker_id;
1452    }
1453
1454    /**
1455     * メーカーの取得を行う.
1456     *
1457     * $products_check:true商品登録済みのものだけ取得する
1458     *
1459     * @param string $addwhere 追加する WHERE 句
1460     * @param bool $products_check 商品の存在するカテゴリのみ取得する場合 true
1461     * @return array カテゴリツリーの配列
1462     */
1463    function sfGetMakerList($addwhere = '', $products_check = false)
1464    {
1465        $objQuery =& SC_Query_Ex::getSingletonInstance();
1466        $where = 'del_flg = 0';
1467
1468        if ($addwhere != '') {
1469            $where.= " AND $addwhere";
1470        }
1471
1472        $objQuery->setOption('ORDER BY rank DESC');
1473
1474        if ($products_check) {
1475            $col = 'T1.maker_id, name';
1476            $from = 'dtb_maker AS T1 LEFT JOIN dtb_maker_count AS T2 ON T1.maker_id = T2.maker_id';
1477            $where .= ' AND product_count > 0';
1478        } else {
1479            $col = 'maker_id, name';
1480            $from = 'dtb_maker';
1481        }
1482
1483        $arrRet = $objQuery->select($col, $from, $where);
1484
1485        $max = count($arrRet);
1486        $arrList = array();
1487        for ($cnt = 0; $cnt < $max; $cnt++) {
1488            $id = $arrRet[$cnt]['maker_id'];
1489            $name = $arrRet[$cnt]['name'];
1490            $arrList[$id] = $name;
1491        }
1492        return $arrList;
1493    }
1494
1495    /**
1496     * 店舗基本情報に基づいて税金額を返す
1497     *
1498     * @param integer $price 計算対象の金額
1499     * @return integer 税金額
1500     */
1501    function sfTax($price)
1502    {
1503        // 店舗基本情報を取得
1504        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1505
1506        return SC_Utils_Ex::sfTax($price, $CONF['tax'], $CONF['tax_rule']);
1507    }
1508
1509    /**
1510     * 店舗基本情報に基づいて税金付与した金額を返す
1511     * SC_Utils_Ex::sfCalcIncTax とどちらか統一したほうが良い
1512     *
1513     * @param integer $price 計算対象の金額
1514     * @return integer 税金付与した金額
1515     */
1516    function sfCalcIncTax($price, $tax = null, $tax_rule = null)
1517    {
1518        // 店舗基本情報を取得
1519        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1520        $tax      = $tax      === null ? $CONF['tax']      : $tax;
1521        $tax_rule = $tax_rule === null ? $CONF['tax_rule'] : $tax_rule;
1522
1523        return SC_Utils_Ex::sfCalcIncTax($price, $tax, $tax_rule);
1524    }
1525
1526    /**
1527     * 店舗基本情報に基づいて加算ポイントを返す
1528     *
1529     * @param integer $totalpoint
1530     * @param integer $use_point
1531     * @return integer 加算ポイント
1532     */
1533    function sfGetAddPoint($totalpoint, $use_point)
1534    {
1535        // 店舗基本情報を取得
1536        $CONF = SC_Helper_DB_Ex::sfGetBasisData();
1537
1538        return SC_Utils_Ex::sfGetAddPoint($totalpoint, $use_point, $CONF['point_rate']);
1539    }
1540
1541    /**
1542     * 指定ファイルが存在する場合 SQL として実行
1543     *
1544     * XXX プラグイン用に追加。将来消すかも。
1545     *
1546     * @param string $sqlFilePath SQL ファイルのパス
1547     * @return void
1548     */
1549    function sfExecSqlByFile($sqlFilePath)
1550    {
1551        if (file_exists($sqlFilePath)) {
1552            $objQuery =& SC_Query_Ex::getSingletonInstance();
1553
1554            $sqls = file_get_contents($sqlFilePath);
1555            if ($sqls === false) trigger_error('ファイルは存在するが読み込めない', E_USER_ERROR);
1556
1557            foreach (explode(';', $sqls) as $sql) {
1558                $sql = trim($sql);
1559                if (strlen($sql) == 0) continue;
1560                $objQuery->query($sql);
1561            }
1562        }
1563    }
1564
1565    /**
1566     * 商品規格を設定しているか
1567     *
1568     * @param integer $product_id 商品ID
1569     * @return bool 商品規格が存在する場合:true, それ以外:false
1570     */
1571    function sfHasProductClass($product_id)
1572    {
1573        if (!SC_Utils_Ex::sfIsInt($product_id)) return false;
1574
1575        $objQuery =& SC_Query_Ex::getSingletonInstance();
1576        $where = 'product_id = ? AND del_flg = 0 AND (classcategory_id1 != 0 OR classcategory_id2 != 0)';
1577        $exists = $objQuery->exists('dtb_products_class', $where, array($product_id));
1578
1579        return $exists;
1580    }
1581
1582    /**
1583     * 店舗基本情報を登録する
1584     *
1585     * @param array $arrData 登録するデータ
1586     * @return void
1587     */
1588    static function registerBasisData($arrData)
1589    {
1590        $objQuery =& SC_Query_Ex::getSingletonInstance();
1591
1592        $arrData = $objQuery->extractOnlyColsOf('dtb_baseinfo', $arrData);
1593
1594        if (isset($arrData['regular_holiday_ids']) && is_array($arrData['regular_holiday_ids'])) {
1595            // 定休日をパイプ区切りの文字列に変換
1596            $arrData['regular_holiday_ids'] = implode('|', $arrData['regular_holiday_ids']);
1597        }
1598
1599        $arrData['update_date'] = 'CURRENT_TIMESTAMP';
1600
1601        // UPDATEの実行
1602        $ret = $objQuery->update('dtb_baseinfo', $arrData);
1603        GC_Utils_Ex::gfPrintLog('dtb_baseinfo に UPDATE を実行しました。');
1604
1605        // UPDATE できなかった場合、INSERT
1606        if ($ret == 0) {
1607            $arrData['id'] = 1;
1608            $ret = $objQuery->insert('dtb_baseinfo', $arrData);
1609            GC_Utils_Ex::gfPrintLog('dtb_baseinfo に INSERT を実行しました。');
1610        }
1611    }
1612}
Note: See TracBrowser for help on using the repository browser.