Warning: Can't use blame annotator:
svn blame failed on branches/version-2_13-dev/data/class/helper/SC_Helper_DB.php: バイナリファイル 'file:///home/svn/open/branches/version-2_13-dev/data/class/helper/SC_Helper_DB.php' に対しては blame で各行の最終変更者を計算できません 195004

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

Revision 22735, 56.3 KB checked in by h_yoshimoto, 11 years ago (diff)

#2193 ユニットテストチームのコミットをマージ(from camp/camp-2_13-tests)

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