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

Revision 22856, 55.8 KB checked in by Seasoft, 11 years ago (diff)

#2043 (typo修正・ソース整形・ソースコメントの改善 for 2.13.0)

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