source: branches/feature-module-update/data/class/util/SC_Utils.php @ 15115

Revision 15115, 104.3 KB checked in by nanasess, 17 years ago (diff)

FIXME コメント追加

  • Property svn:keywords set to Id
  • Property svn:mime-type set to application/x-httpd-php; charset=UTF-8
Line 
1<?php
2/*
3 * Copyright(c) 2000-2007 LOCKON CO.,LTD. All Rights Reserved.
4 *
5 * http://www.lockon.co.jp/
6 */
7
8/**
9 * 各種ユーティリティクラス.
10 *
11 * 主に static 参照するユーティリティ系の関数群
12 *
13 * @package Util
14 * @author LOCKON CO.,LTD.
15 * @version $Id$
16 */
17class SC_Utils {
18
19    /* データベースのバージョン所得 */
20    function sfGetDBVersion($dsn = "") {
21        if($dsn == "") {
22            if(defined('DEFAULT_DSN')) {
23                $dsn = DEFAULT_DSN;
24            } else {
25                return;
26            }
27        }
28
29        $objQuery = new SC_Query($dsn, true, true);
30        list($db_type) = split(":", $dsn);
31        if($db_type == 'mysql') {
32            $val = $objQuery->getOne("select version()");
33            $version = "MySQL " . $val;
34        }
35        if($db_type == 'pgsql') {
36            $val = $objQuery->getOne("select version()");
37            $arrLine = split(" " , $val);
38            $version = $arrLine[0] . " " . $arrLine[1];
39        }
40        return $version;
41    }
42
43    /* テーブルの存在チェック */
44    function sfTabaleExists($table_name, $dsn = "") {
45        if($dsn == "") {
46            if(defined('DEFAULT_DSN')) {
47                $dsn = DEFAULT_DSN;
48            } else {
49                return;
50            }
51        }
52
53        $objQuery = new SC_Query($dsn, true, true);
54        // 正常に接続されている場合
55        if(!$objQuery->isError()) {
56            list($db_type) = split(":", $dsn);
57            // postgresqlとmysqlとで処理を分ける
58            if ($db_type == "pgsql") {
59                $sql = "SELECT
60                            relname
61                        FROM
62                            pg_class
63                        WHERE
64                            (relkind = 'r' OR relkind = 'v') AND
65                            relname = ?
66                        GROUP BY
67                            relname";
68                $arrRet = $objQuery->getAll($sql, array($table_name));
69                if(count($arrRet) > 0) {
70                    return true;
71                }
72            }else if ($db_type == "mysql") {
73                $sql = "SHOW TABLE STATUS LIKE ?";
74                $arrRet = $objQuery->getAll($sql, array($table_name));
75                if(count($arrRet) > 0) {
76                    return true;
77                }
78            }
79        }
80        return false;
81    }
82
83    // カラムの存在チェックと作成
84    function sfColumnExists($table_name, $col_name, $col_type = "", $dsn = "", $add = false) {
85        if($dsn == "") {
86            if(defined('DEFAULT_DSN')) {
87                $dsn = DEFAULT_DSN;
88            } else {
89                return;
90            }
91        }
92
93        // テーブルが無ければエラー
94        if(!sfTabaleExists($table_name, $dsn)) return false;
95
96        $objQuery = new SC_Query($dsn, true, true);
97        // 正常に接続されている場合
98        if(!$objQuery->isError()) {
99            list($db_type) = split(":", $dsn);
100
101            // カラムリストを取得
102            $arrRet = sfGetColumnList($table_name, $objQuery, $db_type);
103            if(count($arrRet) > 0) {
104                if(in_array($col_name, $arrRet)){
105                    return true;
106                }
107            }
108        }
109
110        // カラムを追加する
111        if($add){
112            $objQuery->query("ALTER TABLE $table_name ADD $col_name $col_type ");
113            return true;
114        }
115
116        return false;
117    }
118
119    // インデックスの存在チェックと作成
120    function sfIndexExists($table_name, $col_name, $index_name, $length = "", $dsn = "", $add = false) {
121        if($dsn == "") {
122            if(defined('DEFAULT_DSN')) {
123                $dsn = DEFAULT_DSN;
124            } else {
125                return;
126            }
127        }
128
129        // テーブルが無ければエラー
130        if(!sfTabaleExists($table_name, $dsn)) return false;
131
132        $objQuery = new SC_Query($dsn, true, true);
133        // 正常に接続されている場合
134        if(!$objQuery->isError()) {
135            list($db_type) = split(":", $dsn);
136            switch($db_type) {
137            case 'pgsql':
138                // インデックスの存在確認
139                $arrRet = $objQuery->getAll("SELECT relname FROM pg_class WHERE relname = ?", array($index_name));
140                break;
141            case 'mysql':
142                // インデックスの存在確認
143                $arrRet = $objQuery->getAll("SHOW INDEX FROM ? WHERE Key_name = ?", array($table_name, $index_name));
144                break;
145            default:
146                return false;
147            }
148            // すでにインデックスが存在する場合
149            if(count($arrRet) > 0) {
150                return true;
151            }
152        }
153
154        // インデックスを作成する
155        if($add){
156            switch($db_type) {
157            case 'pgsql':
158                $objQuery->query("CREATE INDEX ? ON ? (?)", array($index_name, $table_name, $col_name));
159                break;
160            case 'mysql':
161                $objQuery->query("CREATE INDEX ? ON ? (?(?))", array($index_name, $table_name, $col_name, $length));
162                break;
163            default:
164                return false;
165            }
166            return true;
167        }
168        return false;
169    }
170
171    // データの存在チェック
172    function sfDataExists($table_name, $where, $arrval, $dsn = "", $sql = "", $add = false) {
173        if($dsn == "") {
174            if(defined('DEFAULT_DSN')) {
175                $dsn = DEFAULT_DSN;
176            } else {
177                return;
178            }
179        }
180        $objQuery = new SC_Query($dsn, true, true);
181        $count = $objQuery->count($table_name, $where, $arrval);
182
183        if($count > 0) {
184            $ret = true;
185        } else {
186            $ret = false;
187        }
188        // データを追加する
189        if(!$ret && $add) {
190            $objQuery->exec($sql);
191        }
192
193        return $ret;
194    }
195
196    /*
197     * サイト管理情報から値を取得する。
198     * データが存在する場合、必ず1以上の数値が設定されている。
199     * 0を返した場合は、呼び出し元で対応すること。
200     *
201     * @param $control_id 管理ID
202     * @param $dsn DataSource
203     * @return $control_flg フラグ
204     */
205    function sfGetSiteControlFlg($control_id, $dsn = "") {
206
207        // データソース
208        if($dsn == "") {
209            if(defined('DEFAULT_DSN')) {
210                $dsn = DEFAULT_DSN;
211            } else {
212                return;
213            }
214        }
215
216        // クエリ生成
217        $target_column = "control_flg";
218        $table_name = "dtb_site_control";
219        $where = "control_id = ?";
220        $arrval = array($control_id);
221        $control_flg = 0;
222
223        // クエリ発行
224        $objQuery = new SC_Query($dsn, true, true);
225        $arrSiteControl = $objQuery->select($target_column, $table_name, $where, $arrval);
226
227        // データが存在すればフラグを取得する
228        if (count($arrSiteControl) > 0) {
229            $control_flg = $arrSiteControl[0]["control_flg"];
230        }
231
232        return $control_flg;
233    }
234
235    // テーブルのカラム一覧を取得する
236    function sfGetColumnList($table_name, $objQuery = "", $db_type = DB_TYPE){
237        if($objQuery == "") $objQuery = new SC_Query();
238        $arrRet = array();
239
240        // postgresqlとmysqlとで処理を分ける
241        if ($db_type == "pgsql") {
242            $sql = "SELECT a.attname FROM pg_class c, pg_attribute a WHERE c.relname=? AND c.oid=a.attrelid AND a.attnum > 0 AND not a.attname like '........pg.dropped.%........' ORDER BY a.attnum";
243            $arrColList = $objQuery->getAll($sql, array($table_name));
244            $arrColList = sfswaparray($arrColList);
245            $arrRet = $arrColList["attname"];
246        }else if ($db_type == "mysql") {
247            $sql = "SHOW COLUMNS FROM $table_name";
248            $arrColList = $objQuery->getAll($sql);
249            $arrColList = sfswaparray($arrColList);
250            $arrRet = $arrColList["Field"];
251        }
252        return $arrRet;
253    }
254
255    // インストール初期処理
256    function sfInitInstall() {
257        // インストール済みが定義されていない。
258        if(!defined('ECCUBE_INSTALL')) {
259            if(!ereg("/install/", $_SERVER['PHP_SELF'])) {
260                header("Location: ./install/");
261            }
262        } else {
263            $path = HTML_PATH . "install/index.php";
264            if(file_exists($path)) {
265                sfErrorHeader(">> /install/index.phpは、インストール完了後にファイルを削除してください。");
266            }
267
268            // 旧バージョンのinstall.phpのチェック
269            $path = HTML_PATH . "install.php";
270            if(file_exists($path)) {
271                sfErrorHeader(">> /install.phpはセキュリティーホールとなります。削除してください。");
272            }
273        }
274    }
275
276    // アップデートで生成されたPHPを読み出し
277    function sfLoadUpdateModule() {
278        // URL設定ディレクトリを削除
279        $main_php = ereg_replace(URL_DIR, "", $_SERVER['PHP_SELF']);
280        $extern_php = UPDATE_PATH . $main_php;
281        if(file_exists($extern_php)) {
282            require_once($extern_php);
283        }
284    }
285
286    function sf_getBasisData() {
287        //DBから設定情報を取得
288        $objConn = new SC_DbConn(DEFAULT_DSN);
289        $result = $objConn->getAll("SELECT * FROM dtb_baseinfo");
290        if(is_array($result[0])) {
291            foreach ( $result[0] as $key=>$value ){
292                $CONF["$key"] = $value;
293            }
294        }
295        return $CONF;
296    }
297
298    // 装飾付きエラーメッセージの表示
299    function sfErrorHeader($mess, $print = false) {
300        global $GLOBAL_ERR;
301        if($GLOBAL_ERR == "") {
302            $GLOBAL_ERR = "<meta http-equiv='Content-Type' content='text/html; charset=" . CHAR_CODE . "'>\n";
303        }
304        $GLOBAL_ERR.= "<table width='100%' border='0' cellspacing='0' cellpadding='0' summary=' '>\n";
305        $GLOBAL_ERR.= "<tr>\n";
306        $GLOBAL_ERR.= "<td bgcolor='#ffeebb' height='25' colspan='2' align='center'>\n";
307        $GLOBAL_ERR.= "<SPAN style='color:red; font-size:12px'><strong>" . $mess . "</strong></span>\n";
308        $GLOBAL_ERR.= "</td>\n";
309        $GLOBAL_ERR.= " </tr>\n";
310        $GLOBAL_ERR.= "</table>\n";
311
312        if($print) {
313            print($GLOBAL_ERR);
314        }
315    }
316
317    /* エラーページの表示 */
318    function sfDispError($type) {
319// FIXME
320//        class LC_ErrorPage {
321//            function LC_ErrorPage() {
322//                $this->tpl_mainpage = 'login_error.tpl';
323//                $this->tpl_title = 'エラー';
324//            }
325//        }
326
327        //$objPage = new LC_ErrorPage();
328        $objPage = new LC_Page();
329        $objView = new SC_AdminView();
330
331        switch ($type) {
332            case LOGIN_ERROR:
333                $objPage->tpl_error="IDまたはパスワードが正しくありません。<br />もう一度ご確認のうえ、再度入力してください。";
334                break;
335            case ACCESS_ERROR:
336                $objPage->tpl_error="ログイン認証の有効期限切れの可能性があります。<br />もう一度ご確認のうえ、再度ログインしてください。";
337                break;
338            case AUTH_ERROR:
339                $objPage->tpl_error="このファイルにはアクセス権限がありません。<br />もう一度ご確認のうえ、再度ログインしてください。";
340                break;
341            case INVALID_MOVE_ERRORR:
342                $objPage->tpl_error="不正なページ移動です。<br />もう一度ご確認のうえ、再度入力してください。";
343                break;
344            default:
345                $objPage->tpl_error="エラーが発生しました。<br />もう一度ご確認のうえ、再度ログインしてください。";
346                break;
347        }
348
349        $objView->assignobj($objPage);
350        $objView->display(LOGIN_FRAME);
351
352        exit;
353    }
354
355    /* サイトエラーページの表示 */
356    function sfDispSiteError($type, $objSiteSess = "", $return_top = false, $err_msg = "", $is_mobile = false) {
357        global $objCampaignSess;
358
359        if ($objSiteSess != "") {
360            $objSiteSess->setNowPage('error');
361        }
362// FIXME
363//        class LC_ErrorPage {
364//            function LC_ErrorPage() {
365//                $this->tpl_mainpage = 'error.tpl';
366//                $this->tpl_css = URL_DIR.'css/layout/error.css';
367//                $this->tpl_title = 'エラー';
368//            }
369//        }
370
371        //$objPage = new LC_ErrorPage();
372        $objPage = new LC_Page();
373
374        if($is_mobile === true) {
375            $objView = new SC_MobileView();
376        } else {
377            $objView = new SC_SiteView();
378        }
379
380        switch ($type) {
381            case PRODUCT_NOT_FOUND:
382                $objPage->tpl_error="ご指定のページはございません。";
383                break;
384            case PAGE_ERROR:
385                $objPage->tpl_error="不正なページ移動です。";
386                break;
387            case CART_EMPTY:
388                $objPage->tpl_error="カートに商品ががありません。";
389                break;
390            case CART_ADD_ERROR:
391                $objPage->tpl_error="購入処理中は、カートに商品を追加することはできません。";
392                break;
393            case CANCEL_PURCHASE:
394                $objPage->tpl_error="この手続きは無効となりました。以下の要因が考えられます。<br />・セッション情報の有効期限が切れてる場合<br />・購入手続き中に新しい購入手続きを実行した場合<br />・すでに購入手続きを完了している場合";
395                break;
396            case CATEGORY_NOT_FOUND:
397                $objPage->tpl_error="ご指定のカテゴリは存在しません。";
398                break;
399            case SITE_LOGIN_ERROR:
400                $objPage->tpl_error="メールアドレスもしくはパスワードが正しくありません。";
401                break;
402            case TEMP_LOGIN_ERROR:
403                $objPage->tpl_error="メールアドレスもしくはパスワードが正しくありません。<br />本登録がお済みでない場合は、仮登録メールに記載されている<br />URLより本登録を行ってください。";
404                break;
405            case CUSTOMER_ERROR:
406                $objPage->tpl_error="不正なアクセスです。";
407                break;
408            case SOLD_OUT:
409                $objPage->tpl_error="申し訳ございませんが、ご購入の直前で売り切れた商品があります。この手続きは無効となりました。";
410                break;
411            case CART_NOT_FOUND:
412                $objPage->tpl_error="申し訳ございませんが、カート内の商品情報の取得に失敗しました。この手続きは無効となりました。";
413                break;
414            case LACK_POINT:
415                $objPage->tpl_error="申し訳ございませんが、ポイントが不足しております。この手続きは無効となりました。";
416                break;
417            case FAVORITE_ERROR:
418                $objPage->tpl_error="既にお気に入りに追加されている商品です。";
419                break;
420            case EXTRACT_ERROR:
421                $objPage->tpl_error="ファイルの解凍に失敗しました。\n指定のディレクトリに書き込み権限が与えられていない可能性があります。";
422                break;
423            case FTP_DOWNLOAD_ERROR:
424                $objPage->tpl_error="ファイルのFTPダウンロードに失敗しました。";
425                break;
426            case FTP_LOGIN_ERROR:
427                $objPage->tpl_error="FTPログインに失敗しました。";
428                break;
429            case FTP_CONNECT_ERROR:
430                $objPage->tpl_error="FTPログインに失敗しました。";
431                break;
432            case CREATE_DB_ERROR:
433                $objPage->tpl_error="DBの作成に失敗しました。\n指定のユーザーには、DB作成の権限が与えられていない可能性があります。";
434                break;
435            case DB_IMPORT_ERROR:
436                $objPage->tpl_error="データベース構造のインポートに失敗しました。\nsqlファイルが壊れている可能性があります。";
437                break;
438            case FILE_NOT_FOUND:
439                $objPage->tpl_error="指定のパスに、設定ファイルが存在しません。";
440                break;
441            case WRITE_FILE_ERROR:
442                $objPage->tpl_error="設定ファイルに書き込めません。\n設定ファイルに書き込み権限を与えてください。";
443                break;
444            case FREE_ERROR_MSG:
445                $objPage->tpl_error=$err_msg;
446                break;
447             default:
448                $objPage->tpl_error="エラーが発生しました。";
449                break;
450        }
451
452        $objPage->return_top = $return_top;
453
454        $objView->assignobj($objPage);
455
456        if(is_object($objCampaignSess)) {
457            // フレームを選択(キャンペーンページから遷移なら変更)
458            $objCampaignSess->pageView($objView);
459        } else {
460            $objView->display(SITE_FRAME);
461        }
462        exit;
463    }
464
465    /* 認証の可否判定 */
466    function sfIsSuccess($objSess, $disp_error = true) {
467        $ret = $objSess->IsSuccess();
468        if($ret != SUCCESS) {
469            if($disp_error) {
470                // エラーページの表示
471                sfDispError($ret);
472            }
473            return false;
474        }
475        // リファラーチェック(CSRFの暫定的な対策)
476        // 「リファラ無」 の場合はスルー
477        // 「リファラ有」 かつ 「管理画面からの遷移でない」 場合にエラー画面を表示する
478        if ( empty($_SERVER['HTTP_REFERER']) ) {
479            // 警告表示させる?
480            // sfErrorHeader('>> referrerが無効になっています。');
481        } else {
482            $domain  = sfIsHTTPS() ? SSL_URL : SITE_URL;
483            $pattern = sprintf('|^%s.*|', $domain);
484            $referer = $_SERVER['HTTP_REFERER'];
485
486            // 管理画面から以外の遷移の場合はエラー画面を表示
487            if (!preg_match($pattern, $referer)) {
488                if ($disp_error) sfDispError(INVALID_MOVE_ERRORR);
489                return false;
490            }
491        }
492        return true;
493    }
494
495    /**
496     * HTTPSかどうかを判定
497     *
498     * @return bool
499     */
500    function sfIsHTTPS () {
501        // HTTPS時には$_SERVER['HTTPS']には空でない値が入る
502        // $_SERVER['HTTPS'] != 'off' はIIS用
503        if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
504            return true;
505        } else {
506            return false;
507        }
508    }
509
510    /**
511     *  正規の遷移がされているかを判定
512     *  前画面でuniqidを埋め込んでおく必要がある
513     *  @param  obj  SC_Session, SC_SiteSession
514     *  @return bool
515     */
516    function sfIsValidTransition($objSess) {
517        // 前画面からPOSTされるuniqidが正しいものかどうかをチェック
518        $uniqid = $objSess->getUniqId();
519        if ( !empty($_POST['uniqid']) && ($_POST['uniqid'] === $uniqid) ) {
520            return true;
521        } else {
522            return false;
523        }
524    }
525
526    /* 前のページで正しく登録が行われたか判定 */
527    function sfIsPrePage($objSiteSess, $is_mobile = false) {
528        $ret = $objSiteSess->isPrePage();
529        if($ret != true) {
530            // エラーページの表示
531            sfDispSiteError(PAGE_ERROR, $objSiteSess, false, "", $is_mobile);
532        }
533    }
534
535    function sfCheckNormalAccess($objSiteSess, $objCartSess) {
536        // ユーザユニークIDの取得
537        $uniqid = $objSiteSess->getUniqId();
538        // 購入ボタンを押した時のカート内容がコピーされていない場合のみコピーする。
539        $objCartSess->saveCurrentCart($uniqid);
540        // POSTのユニークIDとセッションのユニークIDを比較(ユニークIDがPOSTされていない場合はスルー)
541        $ret = $objSiteSess->checkUniqId();
542        if($ret != true) {
543            // エラーページの表示
544            sfDispSiteError(CANCEL_PURCHASE, $objSiteSess);
545        }
546
547        // カート内が空でないか || 購入ボタンを押してから変化がないか
548        $quantity = $objCartSess->getTotalQuantity();
549        $ret = $objCartSess->checkChangeCart();
550        if($ret == true || !($quantity > 0)) {
551            // カート情報表示に強制移動する
552            header("Location: ".URL_CART_TOP);
553            exit;
554        }
555        return $uniqid;
556    }
557
558    /* DB用日付文字列取得 */
559    function sfGetTimestamp($year, $month, $day, $last = false) {
560        if($year != "" && $month != "" && $day != "") {
561            if($last) {
562                $time = "23:59:59";
563            } else {
564                $time = "00:00:00";
565            }
566            $date = $year."-".$month."-".$day." ".$time;
567        } else {
568            $date = "";
569        }
570        return  $date;
571    }
572
573    // INT型の数値チェック
574    function sfIsInt($value) {
575        if($value != "" && strlen($value) <= INT_LEN && is_numeric($value)) {
576            return true;
577        }
578        return false;
579    }
580
581    function sfCSVDownload($data, $prefix = ""){
582
583        if($prefix == "") {
584            $dir_name = sfUpDirName();
585            $file_name = $dir_name . date("ymdHis") .".csv";
586        } else {
587            $file_name = $prefix . date("ymdHis") .".csv";
588        }
589
590        /* HTTPヘッダの出力 */
591        Header("Content-disposition: attachment; filename=${file_name}");
592        Header("Content-type: application/octet-stream; name=${file_name}");
593        Header("Cache-Control: ");
594        Header("Pragma: ");
595
596        /* i18n~ だと正常に動作しないため、mb~ に変更
597        if (i18n_discover_encoding($data) == CHAR_CODE){
598            $data = i18n_convert($data,'SJIS',CHAR_CODE);
599        }
600        */
601        if (mb_internal_encoding() == CHAR_CODE){
602            $data = mb_convert_encoding($data,'SJIS',CHAR_CODE);
603        }
604
605        /* データを出力 */
606        echo $data;
607    }
608
609    /* 1階層上のディレクトリ名を取得する */
610    function sfUpDirName() {
611        $path = $_SERVER['PHP_SELF'];
612        $arrVal = split("/", $path);
613        $cnt = count($arrVal);
614        return $arrVal[($cnt - 2)];
615    }
616
617    // 現在のサイトを更新(ただしポストは行わない)
618    function sfReload($get = "") {
619        if ($_SERVER["SERVER_PORT"] == "443" ){
620            $url = ereg_replace(URL_DIR . "$", "", SSL_URL);
621        } else {
622            $url = ereg_replace(URL_DIR . "$", "", SITE_URL);
623        }
624
625        if($get != "") {
626            header("Location: ". $url . $_SERVER['PHP_SELF'] . "?" . $get);
627        } else {
628            header("Location: ". $url . $_SERVER['PHP_SELF']);
629        }
630        exit;
631    }
632
633    // ランキングを上げる。
634    function sfRankUp($table, $colname, $id, $andwhere = "") {
635        $objQuery = new SC_Query();
636        $objQuery->begin();
637        $where = "$colname = ?";
638        if($andwhere != "") {
639            $where.= " AND $andwhere";
640        }
641        // 対象項目のランクを取得
642        $rank = $objQuery->get($table, "rank", $where, array($id));
643        // ランクの最大値を取得
644        $maxrank = $objQuery->max($table, "rank", $andwhere);
645        // ランクが最大値よりも小さい場合に実行する。
646        if($rank < $maxrank) {
647            // ランクが一つ上のIDを取得する。
648            $where = "rank = ?";
649            if($andwhere != "") {
650                $where.= " AND $andwhere";
651            }
652            $uprank = $rank + 1;
653            $up_id = $objQuery->get($table, $colname, $where, array($uprank));
654            // ランク入れ替えの実行
655            $sqlup = "UPDATE $table SET rank = ?, update_date = Now() WHERE $colname = ?";
656            $objQuery->exec($sqlup, array($rank + 1, $id));
657            $objQuery->exec($sqlup, array($rank, $up_id));
658        }
659        $objQuery->commit();
660    }
661
662    // ランキングを下げる。
663    function sfRankDown($table, $colname, $id, $andwhere = "") {
664        $objQuery = new SC_Query();
665        $objQuery->begin();
666        $where = "$colname = ?";
667        if($andwhere != "") {
668            $where.= " AND $andwhere";
669        }
670        // 対象項目のランクを取得
671        $rank = $objQuery->get($table, "rank", $where, array($id));
672
673        // ランクが1(最小値)よりも大きい場合に実行する。
674        if($rank > 1) {
675            // ランクが一つ下のIDを取得する。
676            $where = "rank = ?";
677            if($andwhere != "") {
678                $where.= " AND $andwhere";
679            }
680            $downrank = $rank - 1;
681            $down_id = $objQuery->get($table, $colname, $where, array($downrank));
682            // ランク入れ替えの実行
683            $sqlup = "UPDATE $table SET rank = ?, update_date = Now() WHERE $colname = ?";
684            $objQuery->exec($sqlup, array($rank - 1, $id));
685            $objQuery->exec($sqlup, array($rank, $down_id));
686        }
687        $objQuery->commit();
688    }
689
690    //---- 指定順位へ移動
691    function sfMoveRank($tableName, $keyIdColumn, $keyId, $pos, $where = "") {
692        $objQuery = new SC_Query();
693        $objQuery->begin();
694
695        // 自身のランクを取得する
696        $rank = $objQuery->get($tableName, "rank", "$keyIdColumn = ?", array($keyId));
697        $max = $objQuery->max($tableName, "rank", $where);
698
699        // 値の調整(逆順)
700        if($pos > $max) {
701            $position = 1;
702        } else if($pos < 1) {
703            $position = $max;
704        } else {
705            $position = $max - $pos + 1;
706        }
707
708        if( $position > $rank ) $term = "rank - 1"; //入れ替え先の順位が入れ換え元の順位より大きい場合
709        if( $position < $rank ) $term = "rank + 1"; //入れ替え先の順位が入れ換え元の順位より小さい場合
710
711        //-- 指定した順位の商品から移動させる商品までのrankを1つずらす
712        $sql = "UPDATE $tableName SET rank = $term, update_date = NOW() WHERE rank BETWEEN ? AND ? AND del_flg = 0";
713        if($where != "") {
714            $sql.= " AND $where";
715        }
716
717        if( $position > $rank ) $objQuery->exec( $sql, array( $rank + 1, $position ));
718        if( $position < $rank ) $objQuery->exec( $sql, array( $position, $rank - 1 ));
719
720        //-- 指定した順位へrankを書き換える。
721        $sql  = "UPDATE $tableName SET rank = ?, update_date = NOW() WHERE $keyIdColumn = ? AND del_flg = 0 ";
722        if($where != "") {
723            $sql.= " AND $where";
724        }
725
726        $objQuery->exec( $sql, array( $position, $keyId ) );
727        $objQuery->commit();
728    }
729
730    // ランクを含むレコードの削除
731    // レコードごと削除する場合は、$deleteをtrueにする。
732    function sfDeleteRankRecord($table, $colname, $id, $andwhere = "", $delete = false) {
733        $objQuery = new SC_Query();
734        $objQuery->begin();
735        // 削除レコードのランクを取得する。
736        $where = "$colname = ?";
737        if($andwhere != "") {
738            $where.= " AND $andwhere";
739        }
740        $rank = $objQuery->get($table, "rank", $where, array($id));
741
742        if(!$delete) {
743            // ランクを最下位にする、DELフラグON
744            $sqlup = "UPDATE $table SET rank = 0, del_flg = 1, update_date = Now() ";
745            $sqlup.= "WHERE $colname = ?";
746            // UPDATEの実行
747            $objQuery->exec($sqlup, array($id));
748        } else {
749            $objQuery->delete($table, "$colname = ?", array($id));
750        }
751
752        // 追加レコードのランクより上のレコードを一つずらす。
753        $where = "rank > ?";
754        if($andwhere != "") {
755            $where.= " AND $andwhere";
756        }
757        $sqlup = "UPDATE $table SET rank = (rank - 1) WHERE $where";
758        $objQuery->exec($sqlup, array($rank));
759        $objQuery->commit();
760    }
761
762    // レコードの存在チェック
763    function sfIsRecord($table, $col, $arrval, $addwhere = "") {
764        $objQuery = new SC_Query();
765        $arrCol = split("[, ]", $col);
766
767        $where = "del_flg = 0";
768
769        if($addwhere != "") {
770            $where.= " AND $addwhere";
771        }
772
773        foreach($arrCol as $val) {
774            if($val != "") {
775                if($where == "") {
776                    $where = "$val = ?";
777                } else {
778                    $where.= " AND $val = ?";
779                }
780            }
781        }
782        $ret = $objQuery->get($table, $col, $where, $arrval);
783
784        if($ret != "") {
785            return true;
786        }
787        return false;
788    }
789
790    // チェックボックスの値をマージ
791    function sfMergeCBValue($keyname, $max) {
792        $conv = "";
793        $cnt = 1;
794        for($cnt = 1; $cnt <= $max; $cnt++) {
795            if ($_POST[$keyname . $cnt] == "1") {
796                $conv.= "1";
797            } else {
798                $conv.= "0";
799            }
800        }
801        return $conv;
802    }
803
804    // html_checkboxesの値をマージして2進数形式に変更する。
805    function sfMergeCheckBoxes($array, $max) {
806        $ret = "";
807        if(is_array($array)) {
808            foreach($array as $val) {
809                $arrTmp[$val] = "1";
810            }
811        }
812        for($i = 1; $i <= $max; $i++) {
813            if($arrTmp[$i] == "1") {
814                $ret.= "1";
815            } else {
816                $ret.= "0";
817            }
818        }
819        return $ret;
820    }
821
822
823    // html_checkboxesの値をマージして「-」でつなげる。
824    function sfMergeParamCheckBoxes($array) {
825        $ret = '';
826        if(is_array($array)) {
827            foreach($array as $val) {
828                if($ret != "") {
829                    $ret.= "-$val";
830                } else {
831                    $ret = $val;
832                }
833            }
834        } else {
835            $ret = $array;
836        }
837        return $ret;
838    }
839
840    // html_checkboxesの値をマージしてSQL検索用に変更する。
841    function sfSearchCheckBoxes($array) {
842        $max = 0;
843        $ret = "";
844        foreach($array as $val) {
845            $arrTmp[$val] = "1";
846            if($val > $max) {
847                $max = $val;
848            }
849        }
850        for($i = 1; $i <= $max; $i++) {
851            if($arrTmp[$i] == "1") {
852                $ret.= "1";
853            } else {
854                $ret.= "_";
855            }
856        }
857
858        if($ret != "") {
859            $ret.= "%";
860        }
861        return $ret;
862    }
863
864    // 2進数形式の値をhtml_checkboxes対応の値に切り替える
865    function sfSplitCheckBoxes($val) {
866        $len = strlen($val);
867        for($i = 0; $i < $len; $i++) {
868            if(substr($val, $i, 1) == "1") {
869                $arrRet[] = ($i + 1);
870            }
871        }
872        return $arrRet;
873    }
874
875    // チェックボックスの値をマージ
876    function sfMergeCBSearchValue($keyname, $max) {
877        $conv = "";
878        $cnt = 1;
879        for($cnt = 1; $cnt <= $max; $cnt++) {
880            if ($_POST[$keyname . $cnt] == "1") {
881                $conv.= "1";
882            } else {
883                $conv.= "_";
884            }
885        }
886        return $conv;
887    }
888
889    // チェックボックスの値を分解
890    function sfSplitCBValue($val, $keyname = "") {
891        $len = strlen($val);
892        $no = 1;
893        for ($cnt = 0; $cnt < $len; $cnt++) {
894            if($keyname != "") {
895                $arr[$keyname . $no] = substr($val, $cnt, 1);
896            } else {
897                $arr[] = substr($val, $cnt, 1);
898            }
899            $no++;
900        }
901        return $arr;
902    }
903
904    // キーと値をセットした配列を取得
905    function sfArrKeyValue($arrList, $keyname, $valname, $len_max = "", $keysize = "") {
906
907        $max = count($arrList);
908
909        if($len_max != "" && $max > $len_max) {
910            $max = $len_max;
911        }
912
913        for($cnt = 0; $cnt < $max; $cnt++) {
914            if($keysize != "") {
915                $key = sfCutString($arrList[$cnt][$keyname], $keysize);
916            } else {
917                $key = $arrList[$cnt][$keyname];
918            }
919            $val = $arrList[$cnt][$valname];
920
921            if(!isset($arrRet[$key])) {
922                $arrRet[$key] = $val;
923            }
924
925        }
926        return $arrRet;
927    }
928
929    // キーと値をセットした配列を取得(値が複数の場合)
930    function sfArrKeyValues($arrList, $keyname, $valname, $len_max = "", $keysize = "", $connect = "") {
931
932        $max = count($arrList);
933
934        if($len_max != "" && $max > $len_max) {
935            $max = $len_max;
936        }
937
938        for($cnt = 0; $cnt < $max; $cnt++) {
939            if($keysize != "") {
940                $key = sfCutString($arrList[$cnt][$keyname], $keysize);
941            } else {
942                $key = $arrList[$cnt][$keyname];
943            }
944            $val = $arrList[$cnt][$valname];
945
946            if($connect != "") {
947                $arrRet[$key].= "$val".$connect;
948            } else {
949                $arrRet[$key][] = $val;
950            }
951        }
952        return $arrRet;
953    }
954
955    // 配列の値をカンマ区切りで返す。
956    function sfGetCommaList($array, $space=true) {
957        if (count($array) > 0) {
958            $line = "";
959            foreach($array as $val) {
960                if ($space) {
961                    $line .= $val . ", ";
962                }else{
963                    $line .= $val . ",";
964                }
965            }
966            if ($space) {
967                $line = ereg_replace(", $", "", $line);
968            }else{
969                $line = ereg_replace(",$", "", $line);
970            }
971            return $line;
972        }else{
973            return false;
974        }
975
976    }
977
978    /* 配列の要素をCSVフォーマットで出力する。*/
979    function sfGetCSVList($array) {
980        if (count($array) > 0) {
981            foreach($array as $key => $val) {
982                $val = mb_convert_encoding($val, CHAR_CODE, CHAR_CODE);
983                $line .= "\"".$val."\",";
984            }
985            $line = ereg_replace(",$", "\n", $line);
986        }else{
987            return false;
988        }
989        return $line;
990    }
991
992    /* 配列の要素をPDFフォーマットで出力する。*/
993    function sfGetPDFList($array) {
994        foreach($array as $key => $val) {
995            $line .= "\t".$val;
996        }
997        $line.="\n";
998        return $line;
999    }
1000
1001
1002
1003    /*-----------------------------------------------------------------*/
1004    /*  check_set_term
1005    /*  年月日に別れた2つの期間の妥当性をチェックし、整合性と期間を返す
1006    /* 引数 (開始年,開始月,開始日,終了年,終了月,終了日)
1007    /* 戻値 array(1,2,3)
1008    /*          1.開始年月日 (YYYY/MM/DD 000000)
1009    /*          2.終了年月日 (YYYY/MM/DD 235959)
1010    /*          3.エラー ( 0 = OK, 1 = NG )
1011    /*-----------------------------------------------------------------*/
1012    function sfCheckSetTerm ( $start_year, $start_month, $start_day, $end_year, $end_month, $end_day ) {
1013
1014        // 期間指定
1015        $error = 0;
1016        if ( $start_month || $start_day || $start_year){
1017            if ( ! checkdate($start_month, $start_day , $start_year) ) $error = 1;
1018        } else {
1019            $error = 1;
1020        }
1021        if ( $end_month || $end_day || $end_year){
1022            if ( ! checkdate($end_month ,$end_day ,$end_year) ) $error = 2;
1023        }
1024        if ( ! $error ){
1025            $date1 = $start_year ."/".sprintf("%02d",$start_month) ."/".sprintf("%02d",$start_day) ." 000000";
1026            $date2 = $end_year   ."/".sprintf("%02d",$end_month)   ."/".sprintf("%02d",$end_day)   ." 235959";
1027            if ($date1 > $date2) $error = 3;
1028        } else {
1029            $error = 1;
1030        }
1031        return array($date1, $date2, $error);
1032    }
1033
1034    // エラー箇所の背景色を変更するためのfunction SC_Viewで読み込む
1035    function sfSetErrorStyle(){
1036        return 'style="background-color:'.ERR_COLOR.'"';
1037    }
1038
1039    /* DBに渡す数値のチェック
1040     * 10桁以上はオーバーフローエラーを起こすので。
1041     */
1042    function sfCheckNumLength( $value ){
1043        if ( ! is_numeric($value)  ){
1044            return false;
1045        }
1046
1047        if ( strlen($value) > 9 ) {
1048            return false;
1049        }
1050
1051        return true;
1052    }
1053
1054    // 一致した値のキー名を取得
1055    function sfSearchKey($array, $word, $default) {
1056        foreach($array as $key => $val) {
1057            if($val == $word) {
1058                return $key;
1059            }
1060        }
1061        return $default;
1062    }
1063
1064    // カテゴリツリーの取得($products_check:true商品登録済みのものだけ取得)
1065    function sfGetCategoryList($addwhere = "", $products_check = false, $head = CATEGORY_HEAD) {
1066        $objQuery = new SC_Query();
1067        $where = "del_flg = 0";
1068
1069        if($addwhere != "") {
1070            $where.= " AND $addwhere";
1071        }
1072
1073        $objQuery->setoption("ORDER BY rank DESC");
1074
1075        if($products_check) {
1076            $col = "T1.category_id, category_name, level";
1077            $from = "dtb_category AS T1 LEFT JOIN dtb_category_total_count AS T2 ON T1.category_id = T2.category_id";
1078            $where .= " AND product_count > 0";
1079        } else {
1080            $col = "category_id, category_name, level";
1081            $from = "dtb_category";
1082        }
1083
1084        $arrRet = $objQuery->select($col, $from, $where);
1085
1086        $max = count($arrRet);
1087        for($cnt = 0; $cnt < $max; $cnt++) {
1088            $id = $arrRet[$cnt]['category_id'];
1089            $name = $arrRet[$cnt]['category_name'];
1090            $arrList[$id] = "";
1091            /*
1092            for($n = 1; $n < $arrRet[$cnt]['level']; $n++) {
1093                $arrList[$id].= " ";
1094            }
1095            */
1096            for($cat_cnt = 0; $cat_cnt < $arrRet[$cnt]['level']; $cat_cnt++) {
1097                $arrList[$id].= $head;
1098            }
1099            $arrList[$id].= $name;
1100        }
1101        return $arrList;
1102    }
1103
1104    // カテゴリツリーの取得(親カテゴリのValue:0)
1105    function sfGetLevelCatList($parent_zero = true) {
1106        $objQuery = new SC_Query();
1107        $col = "category_id, category_name, level";
1108        $where = "del_flg = 0";
1109        $objQuery->setoption("ORDER BY rank DESC");
1110        $arrRet = $objQuery->select($col, "dtb_category", $where);
1111        $max = count($arrRet);
1112
1113        for($cnt = 0; $cnt < $max; $cnt++) {
1114            if($parent_zero) {
1115                if($arrRet[$cnt]['level'] == LEVEL_MAX) {
1116                    $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
1117                } else {
1118                    $arrValue[$cnt] = "";
1119                }
1120            } else {
1121                $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
1122            }
1123
1124            $arrOutput[$cnt] = "";
1125            /*
1126            for($n = 1; $n < $arrRet[$cnt]['level']; $n++) {
1127                $arrOutput[$cnt].= " ";
1128            }
1129            */
1130            for($cat_cnt = 0; $cat_cnt < $arrRet[$cnt]['level']; $cat_cnt++) {
1131                $arrOutput[$cnt].= CATEGORY_HEAD;
1132            }
1133            $arrOutput[$cnt].= $arrRet[$cnt]['category_name'];
1134        }
1135        return array($arrValue, $arrOutput);
1136    }
1137
1138    function sfGetErrorColor($val) {
1139        if($val != "") {
1140            return "background-color:" . ERR_COLOR;
1141        }
1142        return "";
1143    }
1144
1145
1146    function sfGetEnabled($val) {
1147        if( ! $val ) {
1148            return " disabled=\"disabled\"";
1149        }
1150        return "";
1151    }
1152
1153    function sfGetChecked($param, $value) {
1154        if($param == $value) {
1155            return "checked=\"checked\"";
1156        }
1157        return "";
1158    }
1159
1160    // SELECTボックス用リストの作成
1161    function sfGetIDValueList($table, $keyname, $valname) {
1162        $objQuery = new SC_Query();
1163        $col = "$keyname, $valname";
1164        $objQuery->setwhere("del_flg = 0");
1165        $objQuery->setorder("rank DESC");
1166        $arrList = $objQuery->select($col, $table);
1167        $count = count($arrList);
1168        for($cnt = 0; $cnt < $count; $cnt++) {
1169            $key = $arrList[$cnt][$keyname];
1170            $val = $arrList[$cnt][$valname];
1171            $arrRet[$key] = $val;
1172        }
1173        return $arrRet;
1174    }
1175
1176    function sfTrim($str) {
1177        $ret = ereg_replace("^[  \n\r]*", "", $str);
1178        $ret = ereg_replace("[  \n\r]*$", "", $ret);
1179        return $ret;
1180    }
1181
1182    /* 所属するすべての階層の親IDを配列で返す */
1183    function sfGetParents($objQuery, $table, $pid_name, $id_name, $id) {
1184        $arrRet = SC_Utils::sfGetParentsArray($table, $pid_name, $id_name, $id);
1185        // 配列の先頭1つを削除する。
1186        array_shift($arrRet);
1187        return $arrRet;
1188    }
1189
1190
1191    /* 親IDの配列を元に特定のカラムを取得する。*/
1192    function sfGetParentsCol($objQuery, $table, $id_name, $col_name, $arrId ) {
1193        $col = $col_name;
1194        $len = count($arrId);
1195        $where = "";
1196
1197        for($cnt = 0; $cnt < $len; $cnt++) {
1198            if($where == "") {
1199                $where = "$id_name = ?";
1200            } else {
1201                $where.= " OR $id_name = ?";
1202            }
1203        }
1204
1205        $objQuery->setorder("level");
1206        $arrRet = $objQuery->select($col, $table, $where, $arrId);
1207        return $arrRet;
1208    }
1209
1210    /* 子IDの配列を返す */
1211    function sfGetChildsID($table, $pid_name, $id_name, $id) {
1212        $arrRet = sfGetChildrenArray($table, $pid_name, $id_name, $id);
1213        return $arrRet;
1214    }
1215
1216    /* カテゴリ変更時の移動処理 */
1217    function sfMoveCatRank($objQuery, $table, $id_name, $cat_name, $old_catid, $new_catid, $id) {
1218        if ($old_catid == $new_catid) {
1219            return;
1220        }
1221        // 旧カテゴリでのランク削除処理
1222        // 移動レコードのランクを取得する。
1223        $where = "$id_name = ?";
1224        $rank = $objQuery->get($table, "rank", $where, array($id));
1225        // 削除レコードのランクより上のレコードを一つ下にずらす。
1226        $where = "rank > ? AND $cat_name = ?";
1227        $sqlup = "UPDATE $table SET rank = (rank - 1) WHERE $where";
1228        $objQuery->exec($sqlup, array($rank, $old_catid));
1229        // 新カテゴリでの登録処理
1230        // 新カテゴリの最大ランクを取得する。
1231        $max_rank = $objQuery->max($table, "rank", "$cat_name = ?", array($new_catid)) + 1;
1232        $where = "$id_name = ?";
1233        $sqlup = "UPDATE $table SET rank = ? WHERE $where";
1234        $objQuery->exec($sqlup, array($max_rank, $id));
1235    }
1236
1237    /* 税金計算 */
1238    function sfTax($price, $tax, $tax_rule) {
1239        $real_tax = $tax / 100;
1240        $ret = $price * $real_tax;
1241        switch($tax_rule) {
1242        // 四捨五入
1243        case 1:
1244            $ret = round($ret);
1245            break;
1246        // 切り捨て
1247        case 2:
1248            $ret = floor($ret);
1249            break;
1250        // 切り上げ
1251        case 3:
1252            $ret = ceil($ret);
1253            break;
1254        // デフォルト:切り上げ
1255        default:
1256            $ret = ceil($ret);
1257            break;
1258        }
1259        return $ret;
1260    }
1261
1262    /* 税金付与 */
1263    function sfPreTax($price, $tax, $tax_rule) {
1264        $real_tax = $tax / 100;
1265        $ret = $price * (1 + $real_tax);
1266
1267        switch($tax_rule) {
1268        // 四捨五入
1269        case 1:
1270            $ret = round($ret);
1271            break;
1272        // 切り捨て
1273        case 2:
1274            $ret = floor($ret);
1275            break;
1276        // 切り上げ
1277        case 3:
1278            $ret = ceil($ret);
1279            break;
1280        // デフォルト:切り上げ
1281        default:
1282            $ret = ceil($ret);
1283            break;
1284        }
1285        return $ret;
1286    }
1287
1288    // 桁数を指定して四捨五入
1289    function sfRound($value, $pow = 0){
1290        $adjust = pow(10 ,$pow-1);
1291
1292        // 整数且つ0出なければ桁数指定を行う
1293        if(sfIsInt($adjust) and $pow > 1){
1294            $ret = (round($value * $adjust)/$adjust);
1295        }
1296
1297        $ret = round($ret);
1298
1299        return $ret;
1300    }
1301
1302    /* ポイント付与 */
1303    function sfPrePoint($price, $point_rate, $rule = POINT_RULE, $product_id = "") {
1304        if(sfIsInt($product_id)) {
1305            $objQuery = new SC_Query();
1306            $where = "now() >= cast(start_date as date) AND ";
1307            $where .= "now() < cast(end_date as date) AND ";
1308
1309            $where .= "del_flg = 0 AND campaign_id IN (SELECT campaign_id FROM dtb_campaign_detail where product_id = ? )";
1310            //登録(更新)日付順
1311            $objQuery->setorder('update_date DESC');
1312            //キャンペーンポイントの取得
1313            $arrRet = $objQuery->select("campaign_name, campaign_point_rate", "dtb_campaign", $where, array($product_id));
1314        }
1315        //複数のキャンペーンに登録されている商品は、最新のキャンペーンからポイントを取得
1316        if($arrRet[0]['campaign_point_rate'] != "") {
1317            $campaign_point_rate = $arrRet[0]['campaign_point_rate'];
1318            $real_point = $campaign_point_rate / 100;
1319        } else {
1320            $real_point = $point_rate / 100;
1321        }
1322        $ret = $price * $real_point;
1323        switch($rule) {
1324        // 四捨五入
1325        case 1:
1326            $ret = round($ret);
1327            break;
1328        // 切り捨て
1329        case 2:
1330            $ret = floor($ret);
1331            break;
1332        // 切り上げ
1333        case 3:
1334            $ret = ceil($ret);
1335            break;
1336        // デフォルト:切り上げ
1337        default:
1338            $ret = ceil($ret);
1339            break;
1340        }
1341        //キャンペーン商品の場合
1342        if($campaign_point_rate != "") {
1343            $ret = "(".$arrRet[0]['campaign_name']."ポイント率".$campaign_point_rate."%)".$ret;
1344        }
1345        return $ret;
1346    }
1347
1348    /* 規格分類の件数取得 */
1349    function sfGetClassCatCount() {
1350        $sql = "select count(dtb_class.class_id) as count, dtb_class.class_id ";
1351        $sql.= "from dtb_class inner join dtb_classcategory on dtb_class.class_id = dtb_classcategory.class_id ";
1352        $sql.= "where dtb_class.del_flg = 0 AND dtb_classcategory.del_flg = 0 ";
1353        $sql.= "group by dtb_class.class_id, dtb_class.name";
1354        $objQuery = new SC_Query();
1355        $arrList = $objQuery->getall($sql);
1356        // キーと値をセットした配列を取得
1357        $arrRet = sfArrKeyValue($arrList, 'class_id', 'count');
1358
1359        return $arrRet;
1360    }
1361
1362    /* 規格の登録 */
1363    function sfInsertProductClass($objQuery, $arrList, $product_id) {
1364        // すでに規格登録があるかどうかをチェックする。
1365        $where = "product_id = ? AND classcategory_id1 <> 0 AND classcategory_id1 <> 0";
1366        $count = $objQuery->count("dtb_products_class", $where,  array($product_id));
1367
1368        // すでに規格登録がない場合
1369        if($count == 0) {
1370            // 既存規格の削除
1371            $where = "product_id = ?";
1372            $objQuery->delete("dtb_products_class", $where, array($product_id));
1373            $sqlval['product_id'] = $product_id;
1374            $sqlval['classcategory_id1'] = '0';
1375            $sqlval['classcategory_id2'] = '0';
1376            $sqlval['product_code'] = $arrList["product_code"];
1377            $sqlval['stock'] = $arrList["stock"];
1378            $sqlval['stock_unlimited'] = $arrList["stock_unlimited"];
1379            $sqlval['price01'] = $arrList['price01'];
1380            $sqlval['price02'] = $arrList['price02'];
1381            $sqlval['creator_id'] = $_SESSION['member_id'];
1382            $sqlval['create_date'] = "now()";
1383
1384            if($_SESSION['member_id'] == "") {
1385                $sqlval['creator_id'] = '0';
1386            }
1387
1388            // INSERTの実行
1389            $objQuery->insert("dtb_products_class", $sqlval);
1390        }
1391    }
1392
1393    function sfGetProductClassId($product_id, $classcategory_id1, $classcategory_id2) {
1394        $where = "product_id = ? AND classcategory_id1 = ? AND classcategory_id2 = ?";
1395        $objQuery = new SC_Query();
1396        $ret = $objQuery->get("dtb_products_class", "product_class_id", $where, Array($product_id, $classcategory_id1, $classcategory_id2));
1397        return $ret;
1398    }
1399
1400    /* 文末の「/」をなくす */
1401    function sfTrimURL($url) {
1402        $ret = ereg_replace("[/]+$", "", $url);
1403        return $ret;
1404    }
1405
1406    /* 商品規格情報の取得 */
1407    function sfGetProductsClass($arrID) {
1408        list($product_id, $classcategory_id1, $classcategory_id2) = $arrID;
1409
1410        if($classcategory_id1 == "") {
1411            $classcategory_id1 = '0';
1412        }
1413        if($classcategory_id2 == "") {
1414            $classcategory_id2 = '0';
1415        }
1416
1417        // 商品規格取得
1418        $objQuery = new SC_Query();
1419        $col = "product_id, deliv_fee, name, product_code, main_list_image, main_image, price01, price02, point_rate, product_class_id, classcategory_id1, classcategory_id2, class_id1, class_id2, stock, stock_unlimited, sale_limit, sale_unlimited";
1420        $table = "vw_product_class AS prdcls";
1421        $where = "product_id = ? AND classcategory_id1 = ? AND classcategory_id2 = ?";
1422        $objQuery->setorder("rank1 DESC, rank2 DESC");
1423        $arrRet = $objQuery->select($col, $table, $where, array($product_id, $classcategory_id1, $classcategory_id2));
1424        return $arrRet[0];
1425    }
1426
1427    /* 集計情報を元に最終計算 */
1428    function sfTotalConfirm($arrData, $objPage, $objCartSess, $arrInfo, $objCustomer = "") {
1429        // 商品の合計個数
1430        $total_quantity = $objCartSess->getTotalQuantity(true);
1431
1432        // 税金の取得
1433        $arrData['tax'] = $objPage->tpl_total_tax;
1434        // 小計の取得
1435        $arrData['subtotal'] = $objPage->tpl_total_pretax;
1436
1437        // 合計送料の取得
1438        $arrData['deliv_fee'] = 0;
1439
1440        // 商品ごとの送料が有効の場合
1441        if (OPTION_PRODUCT_DELIV_FEE == 1) {
1442            $arrData['deliv_fee']+= $objCartSess->getAllProductsDelivFee();
1443        }
1444
1445        // 配送業者の送料が有効の場合
1446        if (OPTION_DELIV_FEE == 1) {
1447            // 送料の合計を計算する
1448            $arrData['deliv_fee']+= sfGetDelivFee($arrData['deliv_pref'], $arrData['payment_id']);
1449        }
1450
1451        // 送料無料の購入数が設定されている場合
1452        if(DELIV_FREE_AMOUNT > 0) {
1453            if($total_quantity >= DELIV_FREE_AMOUNT) {
1454                $arrData['deliv_fee'] = 0;
1455            }
1456        }
1457
1458        // 送料無料条件が設定されている場合
1459        if($arrInfo['free_rule'] > 0) {
1460            // 小計が無料条件を超えている場合
1461            if($arrData['subtotal'] >= $arrInfo['free_rule']) {
1462                $arrData['deliv_fee'] = 0;
1463            }
1464        }
1465
1466        // 合計の計算
1467        $arrData['total'] = $objPage->tpl_total_pretax; // 商品合計
1468        $arrData['total']+= $arrData['deliv_fee'];      // 送料
1469        $arrData['total']+= $arrData['charge'];         // 手数料
1470        // お支払い合計
1471        $arrData['payment_total'] = $arrData['total'] - ($arrData['use_point'] * POINT_VALUE);
1472        // 加算ポイントの計算
1473        $arrData['add_point'] = sfGetAddPoint($objPage->tpl_total_point, $arrData['use_point'], $arrInfo);
1474
1475        if($objCustomer != "") {
1476            // 誕生日月であった場合
1477            if($objCustomer->isBirthMonth()) {
1478                $arrData['birth_point'] = BIRTH_MONTH_POINT;
1479                $arrData['add_point'] += $arrData['birth_point'];
1480            }
1481        }
1482
1483        if($arrData['add_point'] < 0) {
1484            $arrData['add_point'] = 0;
1485        }
1486
1487        return $arrData;
1488    }
1489
1490    /* カート内商品の集計処理 */
1491    function sfTotalCart($objPage, $objCartSess, $arrInfo) {
1492        // 規格名一覧
1493        $arrClassName = sfGetIDValueList("dtb_class", "class_id", "name");
1494        // 規格分類名一覧
1495        $arrClassCatName = sfGetIDValueList("dtb_classcategory", "classcategory_id", "name");
1496
1497        $objPage->tpl_total_pretax = 0;     // 費用合計(税込み)
1498        $objPage->tpl_total_tax = 0;        // 消費税合計
1499        $objPage->tpl_total_point = 0;      // ポイント合計
1500
1501        // カート内情報の取得
1502        $arrCart = $objCartSess->getCartList();
1503        $max = count($arrCart);
1504        $cnt = 0;
1505
1506        for ($i = 0; $i < $max; $i++) {
1507            // 商品規格情報の取得
1508            $arrData = sfGetProductsClass($arrCart[$i]['id']);
1509            $limit = "";
1510            // DBに存在する商品
1511            if (count($arrData) > 0) {
1512
1513                // 購入制限数を求める。
1514                if ($arrData['stock_unlimited'] != '1' && $arrData['sale_unlimited'] != '1') {
1515                    if($arrData['sale_limit'] < $arrData['stock']) {
1516                        $limit = $arrData['sale_limit'];
1517                    } else {
1518                        $limit = $arrData['stock'];
1519                    }
1520                } else {
1521                    if ($arrData['sale_unlimited'] != '1') {
1522                        $limit = $arrData['sale_limit'];
1523                    }
1524                    if ($arrData['stock_unlimited'] != '1') {
1525                        $limit = $arrData['stock'];
1526                    }
1527                }
1528
1529                if($limit != "" && $limit < $arrCart[$i]['quantity']) {
1530                    // カート内商品数を制限に合わせる
1531                    $objCartSess->setProductValue($arrCart[$i]['id'], 'quantity', $limit);
1532                    $quantity = $limit;
1533                    $objPage->tpl_message = "※「" . $arrData['name'] . "」は販売制限しております、一度にこれ以上の購入はできません。";
1534                } else {
1535                    $quantity = $arrCart[$i]['quantity'];
1536                }
1537
1538                $objPage->arrProductsClass[$cnt] = $arrData;
1539                $objPage->arrProductsClass[$cnt]['quantity'] = $quantity;
1540                $objPage->arrProductsClass[$cnt]['cart_no'] = $arrCart[$i]['cart_no'];
1541                $objPage->arrProductsClass[$cnt]['class_name1'] = $arrClassName[$arrData['class_id1']];
1542                $objPage->arrProductsClass[$cnt]['class_name2'] = $arrClassName[$arrData['class_id2']];
1543                $objPage->arrProductsClass[$cnt]['classcategory_name1'] = $arrClassCatName[$arrData['classcategory_id1']];
1544                $objPage->arrProductsClass[$cnt]['classcategory_name2'] = $arrClassCatName[$arrData['classcategory_id2']];
1545
1546                // 画像サイズ
1547                list($image_width, $image_height) = getimagesize(IMAGE_SAVE_DIR . basename($objPage->arrProductsClass[$cnt]["main_image"]));
1548                $objPage->arrProductsClass[$cnt]["tpl_image_width"] = $image_width + 60;
1549                $objPage->arrProductsClass[$cnt]["tpl_image_height"] = $image_height + 80;
1550
1551                // 価格の登録
1552                if ($arrData['price02'] != "") {
1553                    $objCartSess->setProductValue($arrCart[$i]['id'], 'price', $arrData['price02']);
1554                    $objPage->arrProductsClass[$cnt]['uniq_price'] = $arrData['price02'];
1555                } else {
1556                    $objCartSess->setProductValue($arrCart[$i]['id'], 'price', $arrData['price01']);
1557                    $objPage->arrProductsClass[$cnt]['uniq_price'] = $arrData['price01'];
1558                }
1559                // ポイント付与率の登録
1560                $objCartSess->setProductValue($arrCart[$i]['id'], 'point_rate', $arrData['point_rate']);
1561                // 商品ごとの合計金額
1562                $objPage->arrProductsClass[$cnt]['total_pretax'] = $objCartSess->getProductTotal($arrInfo, $arrCart[$i]['id']);
1563                // 送料の合計を計算する
1564                $objPage->tpl_total_deliv_fee+= ($arrData['deliv_fee'] * $arrCart[$i]['quantity']);
1565                $cnt++;
1566            } else {
1567                // DBに商品が見つからない場合はカート商品の削除
1568                $objCartSess->delProductKey('id', $arrCart[$i]['id']);
1569            }
1570        }
1571
1572        // 全商品合計金額(税込み)
1573        $objPage->tpl_total_pretax = $objCartSess->getAllProductsTotal($arrInfo);
1574        // 全商品合計消費税
1575        $objPage->tpl_total_tax = $objCartSess->getAllProductsTax($arrInfo);
1576        // 全商品合計ポイント
1577        $objPage->tpl_total_point = $objCartSess->getAllProductsPoint();
1578
1579        return $objPage;
1580    }
1581
1582    /* DBから取り出した日付の文字列を調整する。*/
1583    function sfDispDBDate($dbdate, $time = true) {
1584        list($y, $m, $d, $H, $M) = split("[- :]", $dbdate);
1585
1586        if(strlen($y) > 0 && strlen($m) > 0 && strlen($d) > 0) {
1587            if ($time) {
1588                $str = sprintf("%04d/%02d/%02d %02d:%02d", $y, $m, $d, $H, $M);
1589            } else {
1590                $str = sprintf("%04d/%02d/%02d", $y, $m, $d, $H, $M);
1591            }
1592        } else {
1593            $str = "";
1594        }
1595        return $str;
1596    }
1597
1598    function sfGetDelivTime($payment_id = "") {
1599        $objQuery = new SC_Query();
1600
1601        $deliv_id = "";
1602
1603        if($payment_id != "") {
1604            $where = "del_flg = 0 AND payment_id = ?";
1605            $arrRet = $objQuery->select("deliv_id", "dtb_payment", $where, array($payment_id));
1606            $deliv_id = $arrRet[0]['deliv_id'];
1607        }
1608
1609        if($deliv_id != "") {
1610            $objQuery->setorder("time_id");
1611            $where = "deliv_id = ?";
1612            $arrRet= $objQuery->select("time_id, deliv_time", "dtb_delivtime", $where, array($deliv_id));
1613        }
1614
1615        return $arrRet;
1616    }
1617
1618
1619    // 都道府県、支払い方法から配送料金を取得する
1620    function sfGetDelivFee($pref, $payment_id = "") {
1621        $objQuery = new SC_Query();
1622
1623        $deliv_id = "";
1624
1625        // 支払い方法が指定されている場合は、対応した配送業者を取得する
1626        if($payment_id != "") {
1627            $where = "del_flg = 0 AND payment_id = ?";
1628            $arrRet = $objQuery->select("deliv_id", "dtb_payment", $where, array($payment_id));
1629            $deliv_id = $arrRet[0]['deliv_id'];
1630        // 支払い方法が指定されていない場合は、先頭の配送業者を取得する
1631        } else {
1632            $where = "del_flg = 0";
1633            $objQuery->setOrder("rank DESC");
1634            $objQuery->setLimitOffset(1);
1635            $arrRet = $objQuery->select("deliv_id", "dtb_deliv", $where);
1636            $deliv_id = $arrRet[0]['deliv_id'];
1637        }
1638
1639        // 配送業者から配送料を取得
1640        if($deliv_id != "") {
1641
1642            // 都道府県が指定されていない場合は、東京都の番号を指定しておく
1643            if($pref == "") {
1644                $pref = 13;
1645            }
1646
1647            $objQuery = new SC_Query();
1648            $where = "deliv_id = ? AND pref = ?";
1649            $arrRet= $objQuery->select("fee", "dtb_delivfee", $where, array($deliv_id, $pref));
1650        }
1651        return $arrRet[0]['fee'];
1652    }
1653
1654    /* 支払い方法の取得 */
1655    function sfGetPayment() {
1656        $objQuery = new SC_Query();
1657        // 購入金額が条件額以下の項目を取得
1658        $where = "del_flg = 0";
1659        $objQuery->setorder("fix, rank DESC");
1660        $arrRet = $objQuery->select("payment_id, payment_method, rule", "dtb_payment", $where);
1661        return $arrRet;
1662    }
1663
1664    /* 配列をキー名ごとの配列に変更する */
1665    function sfSwapArray($array) {
1666        $max = count($array);
1667        for($i = 0; $i < $max; $i++) {
1668            foreach($array[$i] as $key => $val) {
1669                $arrRet[$key][] = $val;
1670            }
1671        }
1672        return $arrRet;
1673    }
1674
1675    /* かけ算をする(Smarty用) */
1676    function sfMultiply($num1, $num2) {
1677        return ($num1 * $num2);
1678    }
1679
1680    /* DBに登録されたテンプレートメールの送信 */
1681    function sfSendTemplateMail($to, $to_name, $template_id, $objPage) {
1682        global $arrMAILTPLPATH;
1683        $objQuery = new SC_Query();
1684        // メールテンプレート情報の取得
1685        $where = "template_id = ?";
1686        $arrRet = $objQuery->select("subject, header, footer", "dtb_mailtemplate", $where, array($template_id));
1687        $objPage->tpl_header = $arrRet[0]['header'];
1688        $objPage->tpl_footer = $arrRet[0]['footer'];
1689        $tmp_subject = $arrRet[0]['subject'];
1690
1691        $objSiteInfo = new SC_SiteInfo();
1692        $arrInfo = $objSiteInfo->data;
1693
1694        $objMailView = new SC_SiteView();
1695        // メール本文の取得
1696        $objMailView->assignobj($objPage);
1697        $body = $objMailView->fetch($arrMAILTPLPATH[$template_id]);
1698
1699        // メール送信処理
1700        $objSendMail = new GC_SendMail();
1701        $from = $arrInfo['email03'];
1702        $error = $arrInfo['email04'];
1703        $tosubject = $tmp_subject;
1704        $objSendMail->setItem('', $tosubject, $body, $from, $arrInfo['shop_name'], $from, $error, $error);
1705        $objSendMail->setTo($to, $to_name);
1706        $objSendMail->sendMail();   // メール送信
1707    }
1708
1709    /* 受注完了メール送信 */
1710    function sfSendOrderMail($order_id, $template_id, $subject = "", $header = "", $footer = "", $send = true) {
1711        global $arrMAILTPLPATH;
1712
1713        $objPage = new LC_Page();
1714        $objSiteInfo = new SC_SiteInfo();
1715        $arrInfo = $objSiteInfo->data;
1716        $objPage->arrInfo = $arrInfo;
1717
1718        $objQuery = new SC_Query();
1719
1720        if($subject == "" && $header == "" && $footer == "") {
1721            // メールテンプレート情報の取得
1722            $where = "template_id = ?";
1723            $arrRet = $objQuery->select("subject, header, footer", "dtb_mailtemplate", $where, array('1'));
1724            $objPage->tpl_header = $arrRet[0]['header'];
1725            $objPage->tpl_footer = $arrRet[0]['footer'];
1726            $tmp_subject = $arrRet[0]['subject'];
1727        } else {
1728            $objPage->tpl_header = $header;
1729            $objPage->tpl_footer = $footer;
1730            $tmp_subject = $subject;
1731        }
1732
1733        // 受注情報の取得
1734        $where = "order_id = ?";
1735        $arrRet = $objQuery->select("*", "dtb_order", $where, array($order_id));
1736        $arrOrder = $arrRet[0];
1737        $arrOrderDetail = $objQuery->select("*", "dtb_order_detail", $where, array($order_id));
1738
1739        $objPage->Message_tmp = $arrOrder['message'];
1740
1741        // 顧客情報の取得
1742        $customer_id = $arrOrder['customer_id'];
1743        $arrRet = $objQuery->select("point", "dtb_customer", "customer_id = ?", array($customer_id));
1744        $arrCustomer = $arrRet[0];
1745
1746        $objPage->arrCustomer = $arrCustomer;
1747        $objPage->arrOrder = $arrOrder;
1748
1749        //その他決済情報
1750        if($arrOrder['memo02'] != "") {
1751            $arrOther = unserialize($arrOrder['memo02']);
1752
1753            foreach($arrOther as $other_key => $other_val){
1754                if(sfTrim($other_val["value"]) == ""){
1755                    $arrOther[$other_key]["value"] = "";
1756                }
1757            }
1758
1759            $objPage->arrOther = $arrOther;
1760        }
1761
1762        // 都道府県変換
1763        global $arrPref;
1764        $objPage->arrOrder['deliv_pref'] = $arrPref[$objPage->arrOrder['deliv_pref']];
1765
1766        $objPage->arrOrderDetail = $arrOrderDetail;
1767
1768        $objCustomer = new SC_Customer();
1769        $objPage->tpl_user_point = $objCustomer->getValue('point');
1770
1771        $objMailView = new SC_SiteView();
1772        // メール本文の取得
1773        $objMailView->assignobj($objPage);
1774        $body = $objMailView->fetch($arrMAILTPLPATH[$template_id]);
1775
1776        // メール送信処理
1777        $objSendMail = new GC_SendMail();
1778        $bcc = $arrInfo['email01'];
1779        $from = $arrInfo['email03'];
1780        $error = $arrInfo['email04'];
1781
1782        $tosubject = sfMakeSubject($tmp_subject);
1783
1784        $objSendMail->setItem('', $tosubject, $body, $from, $arrInfo['shop_name'], $from, $error, $error, $bcc);
1785        $objSendMail->setTo($arrOrder["order_email"], $arrOrder["order_name01"] . " ". $arrOrder["order_name02"] ." 様");
1786
1787
1788        // 送信フラグ:trueの場合は、送信する。
1789        if($send) {
1790            if ($objSendMail->sendMail()) {
1791                sfSaveMailHistory($order_id, $template_id, $tosubject, $body);
1792            }
1793        }
1794
1795        return $objSendMail;
1796    }
1797
1798    // テンプレートを使用したメールの送信
1799    function sfSendTplMail($to, $subject, $tplpath, $objPage) {
1800        $objMailView = new SC_SiteView();
1801        $objSiteInfo = new SC_SiteInfo();
1802        $arrInfo = $objSiteInfo->data;
1803        // メール本文の取得
1804        $objPage->tpl_shopname=$arrInfo['shop_name'];
1805        $objPage->tpl_infoemail = $arrInfo['email02'];
1806        $objMailView->assignobj($objPage);
1807        $body = $objMailView->fetch($tplpath);
1808        // メール送信処理
1809        $objSendMail = new GC_SendMail();
1810        $to = mb_encode_mimeheader($to);
1811        $bcc = $arrInfo['email01'];
1812        $from = $arrInfo['email03'];
1813        $error = $arrInfo['email04'];
1814        $objSendMail->setItem($to, $subject, $body, $from, $arrInfo['shop_name'], $from, $error, $error, $bcc);
1815        $objSendMail->sendMail();
1816    }
1817
1818    // 通常のメール送信
1819    function sfSendMail($to, $subject, $body) {
1820        $objSiteInfo = new SC_SiteInfo();
1821        $arrInfo = $objSiteInfo->data;
1822        // メール送信処理
1823        $objSendMail = new GC_SendMail();
1824        $bcc = $arrInfo['email01'];
1825        $from = $arrInfo['email03'];
1826        $error = $arrInfo['email04'];
1827        $objSendMail->setItem($to, $subject, $body, $from, $arrInfo['shop_name'], $from, $error, $error, $bcc);
1828        $objSendMail->sendMail();
1829    }
1830
1831    //件名にテンプレートを用いる
1832    function sfMakeSubject($subject){
1833
1834        $objQuery = new SC_Query();
1835        $objMailView = new SC_SiteView();
1836        $objPage = new LC_Page();
1837
1838        $arrInfo = $objQuery->select("*","dtb_baseinfo");
1839        $arrInfo = $arrInfo[0];
1840        $objPage->tpl_shopname=$arrInfo['shop_name'];
1841        $objPage->tpl_infoemail=$subject;
1842        $objMailView->assignobj($objPage);
1843        $mailtitle = $objMailView->fetch('mail_templates/mail_title.tpl');
1844        $ret = $mailtitle.$subject;
1845        return $ret;
1846    }
1847
1848    // メール配信履歴への登録
1849    function sfSaveMailHistory($order_id, $template_id, $subject, $body) {
1850        $sqlval['subject'] = $subject;
1851        $sqlval['order_id'] = $order_id;
1852        $sqlval['template_id'] = $template_id;
1853        $sqlval['send_date'] = "Now()";
1854        if($_SESSION['member_id'] != "") {
1855            $sqlval['creator_id'] = $_SESSION['member_id'];
1856        } else {
1857            $sqlval['creator_id'] = '0';
1858        }
1859        $sqlval['mail_body'] = $body;
1860
1861        $objQuery = new SC_Query();
1862        $objQuery->insert("dtb_mail_history", $sqlval);
1863    }
1864
1865    /* 会員情報を一時受注テーブルへ */
1866    function sfGetCustomerSqlVal($uniqid, $sqlval) {
1867        $objCustomer = new SC_Customer();
1868        // 会員情報登録処理
1869        if ($objCustomer->isLoginSuccess()) {
1870            // 登録データの作成
1871            $sqlval['order_temp_id'] = $uniqid;
1872            $sqlval['update_date'] = 'Now()';
1873            $sqlval['customer_id'] = $objCustomer->getValue('customer_id');
1874            $sqlval['order_name01'] = $objCustomer->getValue('name01');
1875            $sqlval['order_name02'] = $objCustomer->getValue('name02');
1876            $sqlval['order_kana01'] = $objCustomer->getValue('kana01');
1877            $sqlval['order_kana02'] = $objCustomer->getValue('kana02');
1878            $sqlval['order_sex'] = $objCustomer->getValue('sex');
1879            $sqlval['order_zip01'] = $objCustomer->getValue('zip01');
1880            $sqlval['order_zip02'] = $objCustomer->getValue('zip02');
1881            $sqlval['order_pref'] = $objCustomer->getValue('pref');
1882            $sqlval['order_addr01'] = $objCustomer->getValue('addr01');
1883            $sqlval['order_addr02'] = $objCustomer->getValue('addr02');
1884            $sqlval['order_tel01'] = $objCustomer->getValue('tel01');
1885            $sqlval['order_tel02'] = $objCustomer->getValue('tel02');
1886            $sqlval['order_tel03'] = $objCustomer->getValue('tel03');
1887            if (defined('MOBILE_SITE')) {
1888                $sqlval['order_email'] = $objCustomer->getValue('email_mobile');
1889            } else {
1890                $sqlval['order_email'] = $objCustomer->getValue('email');
1891            }
1892            $sqlval['order_job'] = $objCustomer->getValue('job');
1893            $sqlval['order_birth'] = $objCustomer->getValue('birth');
1894        }
1895        return $sqlval;
1896    }
1897
1898    // 受注一時テーブルへの書き込み処理
1899    function sfRegistTempOrder($uniqid, $sqlval) {
1900        if($uniqid != "") {
1901            // 既存データのチェック
1902            $objQuery = new SC_Query();
1903            $where = "order_temp_id = ?";
1904            $cnt = $objQuery->count("dtb_order_temp", $where, array($uniqid));
1905            // 既存データがない場合
1906            if ($cnt == 0) {
1907                // 初回書き込み時に会員の登録済み情報を取り込む
1908                $sqlval = sfGetCustomerSqlVal($uniqid, $sqlval);
1909                $sqlval['create_date'] = "now()";
1910                $objQuery->insert("dtb_order_temp", $sqlval);
1911            } else {
1912                $objQuery->update("dtb_order_temp", $sqlval, $where, array($uniqid));
1913            }
1914        }
1915    }
1916
1917    /* 会員のメルマガ登録があるかどうかのチェック(仮会員を含まない) */
1918    function sfCheckCustomerMailMaga($email) {
1919        $col = "email, mailmaga_flg, customer_id";
1920        $from = "dtb_customer";
1921        $where = "email = ? AND status = 2";
1922        $objQuery = new SC_Query();
1923        $arrRet = $objQuery->select($col, $from, $where, array($email));
1924        // 会員のメールアドレスが登録されている
1925        if($arrRet[0]['customer_id'] != "") {
1926            return true;
1927        }
1928        return false;
1929    }
1930
1931    // カードの処理結果を返す
1932    function sfGetAuthonlyResult($dir, $file_name, $name01, $name02, $card_no, $card_exp, $amount, $order_id, $jpo_info = "10"){
1933
1934        $path = $dir .$file_name;       // cgiファイルのフルパス生成
1935        $now_dir = getcwd();            // requireがうまくいかないので、cgi実行ディレクトリに移動する
1936        chdir($dir);
1937
1938        // パイプ渡しでコマンドラインからcgi起動
1939        $cmd = "$path card_no=$card_no name01=$name01 name02=$name02 card_exp=$card_exp amount=$amount order_id=$order_id jpo_info=$jpo_info";
1940
1941        $tmpResult = popen($cmd, "r");
1942
1943        // 結果取得
1944        while( ! FEOF ( $tmpResult ) ) {
1945            $result .= FGETS($tmpResult);
1946        }
1947        pclose($tmpResult);             //  パイプを閉じる
1948        chdir($now_dir);                // 元にいたディレクトリに帰る
1949
1950        // 結果を連想配列へ格納
1951        $result = ereg_replace("&$", "", $result);
1952        foreach (explode("&",$result) as $data) {
1953            list($key, $val) = explode("=", $data, 2);
1954            $return[$key] = $val;
1955        }
1956
1957        return $return;
1958    }
1959
1960    // 受注一時テーブルから情報を取得する
1961    function sfGetOrderTemp($order_temp_id) {
1962        $objQuery = new SC_Query();
1963        $where = "order_temp_id = ?";
1964        $arrRet = $objQuery->select("*", "dtb_order_temp", $where, array($order_temp_id));
1965        return $arrRet[0];
1966    }
1967
1968    // カテゴリID取得判定用のグローバル変数(一度取得されていたら再取得しないようにする)
1969    //$g_category_on = false;
1970    //$g_category_id = "";
1971
1972    /* 選択中のカテゴリを取得する */
1973    function sfGetCategoryId($product_id, $category_id) {
1974        global $g_category_on;
1975        global $g_category_id;
1976        if(!$g_category_on) {
1977            $g_category_on = true;
1978            $category_id = (int) $category_id;
1979            $product_id = (int) $product_id;
1980            if(SC_Utils::sfIsInt($category_id) && sfIsRecord("dtb_category","category_id", $category_id)) {
1981                $g_category_id = $category_id;
1982            } else if (SC_Utils::sfIsInt($product_id) && sfIsRecord("dtb_products","product_id", $product_id, "status = 1")) {
1983                $objQuery = new SC_Query();
1984                $where = "product_id = ?";
1985                $category_id = $objQuery->get("dtb_products", "category_id", $where, array($product_id));
1986                $g_category_id = $category_id;
1987            } else {
1988                // 不正な場合は、0を返す。
1989                $g_category_id = 0;
1990            }
1991        }
1992        return $g_category_id;
1993    }
1994
1995    // ROOTID取得判定用のグローバル変数(一度取得されていたら再取得しないようにする)
1996    //$g_root_on = false;
1997    //$g_root_id = "";
1998
1999    /* 選択中のアイテムのルートカテゴリIDを取得する */
2000    function sfGetRootId() {
2001        global $g_root_on;
2002        global $g_root_id;
2003        if(!$g_root_on) {
2004            $g_root_on = true;
2005            $objQuery = new SC_Query();
2006            if($_GET['product_id'] != "" || $_GET['category_id'] != "") {
2007                // 選択中のカテゴリIDを判定する
2008                $category_id = sfGetCategoryId($_GET['product_id'], $_GET['category_id']);
2009                // ROOTカテゴリIDの取得
2010                 $arrRet = sfGetParents($objQuery, 'dtb_category', 'parent_category_id', 'category_id', $category_id);
2011                 $root_id = $arrRet[0];
2012            } else {
2013                // ROOTカテゴリIDをなしに設定する
2014                $root_id = "";
2015            }
2016            $g_root_id = $root_id;
2017        }
2018        return $g_root_id;
2019    }
2020
2021    /* カテゴリから商品を検索する場合のWHERE文と値を返す */
2022    function sfGetCatWhere($category_id) {
2023        // 子カテゴリIDの取得
2024        $arrRet = sfGetChildsID("dtb_category", "parent_category_id", "category_id", $category_id);
2025        $tmp_where = "";
2026        foreach ($arrRet as $val) {
2027            if($tmp_where == "") {
2028                $tmp_where.= " category_id IN ( ?";
2029            } else {
2030                $tmp_where.= ",? ";
2031            }
2032            $arrval[] = $val;
2033        }
2034        $tmp_where.= " ) ";
2035        return array($tmp_where, $arrval);
2036    }
2037
2038    /* 加算ポイントの計算式 */
2039    function sfGetAddPoint($totalpoint, $use_point, $arrInfo) {
2040        // 購入商品の合計ポイントから利用したポイントのポイント換算価値を引く方式
2041        $add_point = $totalpoint - intval($use_point * ($arrInfo['point_rate'] / 100));
2042
2043        if($add_point < 0) {
2044            $add_point = '0';
2045        }
2046        return $add_point;
2047    }
2048
2049    /* 一意かつ予測されにくいID */
2050    function sfGetUniqRandomId($head = "") {
2051        // 予測されないようにランダム文字列を付与する。
2052        $random = gfMakePassword(8);
2053        // 同一ホスト内で一意なIDを生成
2054        $id = uniqid($head);
2055        return ($id . $random);
2056    }
2057
2058    // カテゴリ別オススメ品の取得
2059    function sfGetBestProducts( $conn, $category_id = 0){
2060        // 既に登録されている内容を取得する
2061        $sql = "SELECT name, main_image, main_list_image, price01_min, price01_max, price02_min, price02_max, point_rate,
2062                 A.product_id, A.comment FROM dtb_best_products as A LEFT JOIN vw_products_allclass AS allcls
2063                USING (product_id) WHERE A.category_id = ? AND A.del_flg = 0 AND status = 1 ORDER BY A.rank";
2064        $arrItems = $conn->getAll($sql, array($category_id));
2065
2066        return $arrItems;
2067    }
2068
2069    // 特殊制御文字の手動エスケープ
2070    function sfManualEscape($data) {
2071        // 配列でない場合
2072        if(!is_array($data)) {
2073            if (DB_TYPE == "pgsql") {
2074                $ret = pg_escape_string($data);
2075            }else if(DB_TYPE == "mysql"){
2076                $ret = mysql_real_escape_string($data);
2077            }
2078            $ret = ereg_replace("%", "\\%", $ret);
2079            $ret = ereg_replace("_", "\\_", $ret);
2080            return $ret;
2081        }
2082
2083        // 配列の場合
2084        foreach($data as $val) {
2085            if (DB_TYPE == "pgsql") {
2086                $ret = pg_escape_string($val);
2087            }else if(DB_TYPE == "mysql"){
2088                $ret = mysql_real_escape_string($val);
2089            }
2090
2091            $ret = ereg_replace("%", "\\%", $ret);
2092            $ret = ereg_replace("_", "\\_", $ret);
2093            $arrRet[] = $ret;
2094        }
2095
2096        return $arrRet;
2097    }
2098
2099    // 受注番号、利用ポイント、加算ポイントから最終ポイントを取得
2100    function sfGetCustomerPoint($order_id, $use_point, $add_point) {
2101        $objQuery = new SC_Query();
2102        $arrRet = $objQuery->select("customer_id", "dtb_order", "order_id = ?", array($order_id));
2103        $customer_id = $arrRet[0]['customer_id'];
2104        if($customer_id != "" && $customer_id >= 1) {
2105            $arrRet = $objQuery->select("point", "dtb_customer", "customer_id = ?", array($customer_id));
2106            $point = $arrRet[0]['point'];
2107            $total_point = $arrRet[0]['point'] - $use_point + $add_point;
2108        } else {
2109            $total_point = "";
2110            $point = "";
2111        }
2112        return array($point, $total_point);
2113    }
2114
2115    /* ドメイン間で有効なセッションのスタート */
2116    function sfDomainSessionStart() {
2117        $ret = session_id();
2118    /*
2119        ヘッダーを送信していてもsession_start()が必要なページがあるので
2120        コメントアウトしておく
2121        if($ret == "" && !headers_sent()) {
2122    */
2123        if($ret == "") {
2124            /* セッションパラメータの指定
2125             ・ブラウザを閉じるまで有効
2126             ・すべてのパスで有効
2127             ・同じドメイン間で共有 */
2128            session_set_cookie_params (0, "/", DOMAIN_NAME);
2129
2130            if(!ini_get("session.auto_start")){
2131                // セッション開始
2132                session_start();
2133            }
2134        }
2135    }
2136
2137    /* 文字列に強制的に改行を入れる */
2138    function sfPutBR($str, $size) {
2139        $i = 0;
2140        $cnt = 0;
2141        $line = array();
2142        $ret = "";
2143
2144        while($str[$i] != "") {
2145            $line[$cnt].=$str[$i];
2146            $i++;
2147            if(strlen($line[$cnt]) > $size) {
2148                $line[$cnt].="<br />";
2149                $cnt++;
2150            }
2151        }
2152
2153        foreach($line as $val) {
2154            $ret.=$val;
2155        }
2156        return $ret;
2157    }
2158
2159    // 二回以上繰り返されているスラッシュ[/]を一つに変換する。
2160    function sfRmDupSlash($istr){
2161        if(ereg("^http://", $istr)) {
2162            $str = substr($istr, 7);
2163            $head = "http://";
2164        } else if(ereg("^https://", $istr)) {
2165            $str = substr($istr, 8);
2166            $head = "https://";
2167        } else {
2168            $str = $istr;
2169        }
2170        $str = ereg_replace("[/]+", "/", $str);
2171        $ret = $head . $str;
2172        return $ret;
2173    }
2174
2175    function sfEncodeFile($filepath, $enc_type, $out_dir) {
2176        $ifp = fopen($filepath, "r");
2177
2178        $basename = basename($filepath);
2179        $outpath = $out_dir . "enc_" . $basename;
2180
2181        $ofp = fopen($outpath, "w+");
2182
2183        while(!feof($ifp)) {
2184            $line = fgets($ifp);
2185            $line = mb_convert_encoding($line, $enc_type, "auto");
2186            fwrite($ofp,  $line);
2187        }
2188
2189        fclose($ofp);
2190        fclose($ifp);
2191
2192        return  $outpath;
2193    }
2194
2195    function sfCutString($str, $len, $byte = true, $commadisp = true) {
2196        if($byte) {
2197            if(strlen($str) > ($len + 2)) {
2198                $ret =substr($str, 0, $len);
2199                $cut = substr($str, $len);
2200            } else {
2201                $ret = $str;
2202                $commadisp = false;
2203            }
2204        } else {
2205            if(mb_strlen($str) > ($len + 1)) {
2206                $ret = mb_substr($str, 0, $len);
2207                $cut = mb_substr($str, $len);
2208            } else {
2209                $ret = $str;
2210                $commadisp = false;
2211            }
2212        }
2213
2214        // 絵文字タグの途中で分断されないようにする。
2215        if (isset($cut)) {
2216            // 分割位置より前の最後の [ 以降を取得する。
2217            $head = strrchr($ret, '[');
2218
2219            // 分割位置より後の最初の ] 以前を取得する。
2220            $tail_pos = strpos($cut, ']');
2221            if ($tail_pos !== false) {
2222                $tail = substr($cut, 0, $tail_pos + 1);
2223            }
2224
2225            // 分割位置より前に [、後に ] が見つかった場合は、[ から ] までを
2226            // 接続して絵文字タグ1個分になるかどうかをチェックする。
2227            if ($head !== false && $tail_pos !== false) {
2228                $subject = $head . $tail;
2229                if (preg_match('/^\[emoji:e?\d+\]$/', $subject)) {
2230                    // 絵文字タグが見つかったので削除する。
2231                    $ret = substr($ret, 0, -strlen($head));
2232                }
2233            }
2234        }
2235
2236        if($commadisp){
2237            $ret = $ret . "...";
2238        }
2239        return $ret;
2240    }
2241
2242    // 年、月、締め日から、先月の締め日+1、今月の締め日を求める。
2243    function sfTermMonth($year, $month, $close_day) {
2244        $end_year = $year;
2245        $end_month = $month;
2246
2247        // 開始月が終了月と同じか否か
2248        $same_month = false;
2249
2250        // 該当月の末日を求める。
2251        $end_last_day = date("d", mktime(0, 0, 0, $month + 1, 0, $year));
2252
2253        // 月の末日が締め日より少ない場合
2254        if($end_last_day < $close_day) {
2255            // 締め日を月末日に合わせる
2256            $end_day = $end_last_day;
2257        } else {
2258            $end_day = $close_day;
2259        }
2260
2261        // 前月の取得
2262        $tmp_year = date("Y", mktime(0, 0, 0, $month, 0, $year));
2263        $tmp_month = date("m", mktime(0, 0, 0, $month, 0, $year));
2264        // 前月の末日を求める。
2265        $start_last_day = date("d", mktime(0, 0, 0, $month, 0, $year));
2266
2267        // 前月の末日が締め日より少ない場合
2268        if ($start_last_day < $close_day) {
2269            // 月末日に合わせる
2270            $tmp_day = $start_last_day;
2271        } else {
2272            $tmp_day = $close_day;
2273        }
2274
2275        // 先月の末日の翌日を取得する
2276        $start_year = date("Y", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
2277        $start_month = date("m", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
2278        $start_day = date("d", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
2279
2280        // 日付の作成
2281        $start_date = sprintf("%d/%d/%d 00:00:00", $start_year, $start_month, $start_day);
2282        $end_date = sprintf("%d/%d/%d 23:59:59", $end_year, $end_month, $end_day);
2283
2284        return array($start_date, $end_date);
2285    }
2286
2287    // PDF用のRGBカラーを返す
2288    function sfGetPdfRgb($hexrgb) {
2289        $hex = substr($hexrgb, 0, 2);
2290        $r = hexdec($hex) / 255;
2291
2292        $hex = substr($hexrgb, 2, 2);
2293        $g = hexdec($hex) / 255;
2294
2295        $hex = substr($hexrgb, 4, 2);
2296        $b = hexdec($hex) / 255;
2297
2298        return array($r, $g, $b);
2299    }
2300
2301    //メルマガ仮登録とメール配信
2302    function sfRegistTmpMailData($mail_flag, $email){
2303        $objQuery = new SC_Query();
2304        $objConn = new SC_DBConn();
2305        $objPage = new LC_Page();
2306
2307        $random_id = sfGetUniqRandomId();
2308        $arrRegistMailMagazine["mail_flag"] = $mail_flag;
2309        $arrRegistMailMagazine["email"] = $email;
2310        $arrRegistMailMagazine["temp_id"] =$random_id;
2311        $arrRegistMailMagazine["end_flag"]='0';
2312        $arrRegistMailMagazine["update_date"] = 'now()';
2313
2314        //メルマガ仮登録用フラグ
2315        $flag = $objQuery->count("dtb_customer_mail_temp", "email=?", array($email));
2316        $objConn->query("BEGIN");
2317        switch ($flag){
2318            case '0':
2319            $objConn->autoExecute("dtb_customer_mail_temp",$arrRegistMailMagazine);
2320            break;
2321
2322            case '1':
2323            $objConn->autoExecute("dtb_customer_mail_temp",$arrRegistMailMagazine, "email = '" .addslashes($email). "'");
2324            break;
2325        }
2326        $objConn->query("COMMIT");
2327        $subject = sfMakeSubject('メルマガ仮登録が完了しました。');
2328        $objPage->tpl_url = SSL_URL."mailmagazine/regist.php?temp_id=".$arrRegistMailMagazine['temp_id'];
2329        switch ($mail_flag){
2330            case '1':
2331            $objPage->tpl_name = "登録";
2332            $objPage->tpl_kindname = "HTML";
2333            break;
2334
2335            case '2':
2336            $objPage->tpl_name = "登録";
2337            $objPage->tpl_kindname = "テキスト";
2338            break;
2339
2340            case '3':
2341            $objPage->tpl_name = "解除";
2342            break;
2343        }
2344            $objPage->tpl_email = $email;
2345        sfSendTplMail($email, $subject, 'mail_templates/mailmagazine_temp.tpl', $objPage);
2346    }
2347
2348    // 再帰的に多段配列を検索して一次元配列(Hidden引渡し用配列)に変換する。
2349    function sfMakeHiddenArray($arrSrc, $arrDst = array(), $parent_key = "") {
2350        if(is_array($arrSrc)) {
2351            foreach($arrSrc as $key => $val) {
2352                if($parent_key != "") {
2353                    $keyname = $parent_key . "[". $key . "]";
2354                } else {
2355                    $keyname = $key;
2356                }
2357                if(is_array($val)) {
2358                    $arrDst = sfMakeHiddenArray($val, $arrDst, $keyname);
2359                } else {
2360                    $arrDst[$keyname] = $val;
2361                }
2362            }
2363        }
2364        return $arrDst;
2365    }
2366
2367    // DB取得日時をタイムに変換
2368    function sfDBDatetoTime($db_date) {
2369        $date = ereg_replace("\..*$","",$db_date);
2370        $time = strtotime($date);
2371        return $time;
2372    }
2373
2374    // 出力の際にテンプレートを切り替えられる
2375    /*
2376        index.php?tpl=test.tpl
2377    */
2378    function sfCustomDisplay($objPage, $is_mobile = false) {
2379        $basename = basename($_SERVER["REQUEST_URI"]);
2380
2381        if($basename == "") {
2382            $path = $_SERVER["REQUEST_URI"] . "index.php";
2383        } else {
2384            $path = $_SERVER["REQUEST_URI"];
2385        }
2386
2387        if($_GET['tpl'] != "") {
2388            $tpl_name = $_GET['tpl'];
2389        } else {
2390            $tpl_name = ereg_replace("^/", "", $path);
2391            $tpl_name = ereg_replace("/", "_", $tpl_name);
2392            $tpl_name = ereg_replace("(\.php$|\.html$)", ".tpl", $tpl_name);
2393        }
2394
2395        $template_path = TEMPLATE_FTP_DIR . $tpl_name;
2396
2397        if($is_mobile === true) {
2398            $objView = new SC_MobileView();
2399            $objView->assignobj($objPage);
2400            $objView->display(SITE_FRAME);
2401        } else if(file_exists($template_path)) {
2402            $objView = new SC_UserView(TEMPLATE_FTP_DIR, COMPILE_FTP_DIR);
2403            $objView->assignobj($objPage);
2404            $objView->display($tpl_name);
2405        } else {
2406            $objView = new SC_SiteView();
2407            $objView->assignobj($objPage);
2408            $objView->display(SITE_FRAME);
2409        }
2410    }
2411
2412    //会員編集登録処理
2413    function sfEditCustomerData($array, $arrRegistColumn) {
2414        $objQuery = new SC_Query();
2415
2416        foreach ($arrRegistColumn as $data) {
2417            if ($data["column"] != "password") {
2418                if($array[ $data['column'] ] != "") {
2419                    $arrRegist[ $data["column"] ] = $array[ $data["column"] ];
2420                } else {
2421                    $arrRegist[ $data['column'] ] = NULL;
2422                }
2423            }
2424        }
2425        if (strlen($array["year"]) > 0 && strlen($array["month"]) > 0 && strlen($array["day"]) > 0) {
2426            $arrRegist["birth"] = $array["year"] ."/". $array["month"] ."/". $array["day"] ." 00:00:00";
2427        } else {
2428            $arrRegist["birth"] = NULL;
2429        }
2430
2431        //-- パスワードの更新がある場合は暗号化。(更新がない場合はUPDATE文を構成しない)
2432        if ($array["password"] != DEFAULT_PASSWORD) $arrRegist["password"] = sha1($array["password"] . ":" . AUTH_MAGIC);
2433        $arrRegist["update_date"] = "NOW()";
2434
2435        //-- 編集登録実行
2436        if (defined('MOBILE_SITE')) {
2437            $arrRegist['email_mobile'] = $arrRegist['email'];
2438            unset($arrRegist['email']);
2439        }
2440        $objQuery->begin();
2441        $objQuery->update("dtb_customer", $arrRegist, "customer_id = ? ", array($array['customer_id']));
2442        $objQuery->commit();
2443    }
2444
2445    // PHPのmb_convert_encoding関数をSmartyでも使えるようにする
2446    function sf_mb_convert_encoding($str, $encode = 'CHAR_CODE') {
2447        return  mb_convert_encoding($str, $encode);
2448    }
2449
2450    // PHPのmktime関数をSmartyでも使えるようにする
2451    function sf_mktime($format, $hour=0, $minute=0, $second=0, $month=1, $day=1, $year=1999) {
2452        return  date($format,mktime($hour, $minute, $second, $month, $day, $year));
2453    }
2454
2455    // PHPのdate関数をSmartyでも使えるようにする
2456    function sf_date($format, $timestamp = '') {
2457        return  date( $format, $timestamp);
2458    }
2459
2460    // チェックボックスの型を変換する
2461    function sfChangeCheckBox($data , $tpl = false){
2462        if ($tpl) {
2463            if ($data == 1){
2464                return 'checked';
2465            }else{
2466                return "";
2467            }
2468        }else{
2469            if ($data == "on"){
2470                return 1;
2471            }else{
2472                return 2;
2473            }
2474        }
2475    }
2476
2477    function sfCategory_Count($objQuery){
2478        $sql = "";
2479
2480        //テーブル内容の削除
2481        $objQuery->query("DELETE FROM dtb_category_count");
2482        $objQuery->query("DELETE FROM dtb_category_total_count");
2483
2484        //各カテゴリ内の商品数を数えて格納
2485        $sql = " INSERT INTO dtb_category_count(category_id, product_count, create_date) ";
2486        $sql .= " SELECT T1.category_id, count(T2.category_id), now() FROM dtb_category AS T1 LEFT JOIN dtb_products AS T2 ";
2487        $sql .= " ON T1.category_id = T2.category_id  ";
2488        $sql .= " WHERE T2.del_flg = 0 AND T2.status = 1 ";
2489        $sql .= " GROUP BY T1.category_id, T2.category_id ";
2490        $objQuery->query($sql);
2491
2492        //子カテゴリ内の商品数を集計する
2493        $arrCat = $objQuery->getAll("SELECT * FROM dtb_category");
2494
2495        $sql = "";
2496        foreach($arrCat as $key => $val){
2497
2498            // 子ID一覧を取得
2499            $arrRet = sfGetChildrenArray('dtb_category', 'parent_category_id', 'category_id', $val['category_id']);
2500            $line = sfGetCommaList($arrRet);
2501
2502            $sql = " INSERT INTO dtb_category_total_count(category_id, product_count, create_date) ";
2503            $sql .= " SELECT ?, SUM(product_count), now() FROM dtb_category_count ";
2504            $sql .= " WHERE category_id IN (" . $line . ")";
2505
2506            $objQuery->query($sql, array($val['category_id']));
2507        }
2508    }
2509
2510    // 2つの配列を用いて連想配列を作成する
2511    function sfarrCombine($arrKeys, $arrValues) {
2512
2513        if(count($arrKeys) <= 0 and count($arrValues) <= 0) return array();
2514
2515        $keys = array_values($arrKeys);
2516        $vals = array_values($arrValues);
2517
2518        $max = max( count( $keys ), count( $vals ) );
2519        $combine_ary = array();
2520        for($i=0; $i<$max; $i++) {
2521            $combine_ary[$keys[$i]] = $vals[$i];
2522        }
2523        if(is_array($combine_ary)) return $combine_ary;
2524
2525        return false;
2526    }
2527
2528    /* 階層構造のテーブルから子ID配列を取得する */
2529    function sfGetChildrenArray($table, $pid_name, $id_name, $id) {
2530        $objQuery = new SC_Query();
2531        $col = $pid_name . "," . $id_name;
2532         $arrData = $objQuery->select($col, $table);
2533
2534        $arrPID = array();
2535        $arrPID[] = $id;
2536        $arrChildren = array();
2537        $arrChildren[] = $id;
2538
2539        $arrRet = sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrPID);
2540
2541        while(count($arrRet) > 0) {
2542            $arrChildren = array_merge($arrChildren, $arrRet);
2543            $arrRet = sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrRet);
2544        }
2545
2546        return $arrChildren;
2547    }
2548
2549    /* 親ID直下の子IDをすべて取得する */
2550    function sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrPID) {
2551        $arrChildren = array();
2552        $max = count($arrData);
2553
2554        for($i = 0; $i < $max; $i++) {
2555            foreach($arrPID as $val) {
2556                if($arrData[$i][$pid_name] == $val) {
2557                    $arrChildren[] = $arrData[$i][$id_name];
2558                }
2559            }
2560        }
2561        return $arrChildren;
2562    }
2563
2564
2565    /* 階層構造のテーブルから親ID配列を取得する */
2566    function sfGetParentsArray($table, $pid_name, $id_name, $id) {
2567        $objQuery = new SC_Query();
2568        $col = $pid_name . "," . $id_name;
2569         $arrData = $objQuery->select($col, $table);
2570
2571        $arrParents = array();
2572        $arrParents[] = $id;
2573        $child = $id;
2574
2575        $ret = SC_Utils::sfGetParentsArraySub($arrData, $pid_name, $id_name, $child);
2576
2577        while($ret != "") {
2578            $arrParents[] = $ret;
2579            $ret = SC_Utils::sfGetParentsArraySub($arrData, $pid_name, $id_name, $ret);
2580        }
2581
2582        $arrParents = array_reverse($arrParents);
2583
2584        return $arrParents;
2585    }
2586
2587    /* 子ID所属する親IDを取得する */
2588    function sfGetParentsArraySub($arrData, $pid_name, $id_name, $child) {
2589        $max = count($arrData);
2590        $parent = "";
2591        for($i = 0; $i < $max; $i++) {
2592            if($arrData[$i][$id_name] == $child) {
2593                $parent = $arrData[$i][$pid_name];
2594                break;
2595            }
2596        }
2597        return $parent;
2598    }
2599
2600    /* 階層構造のテーブルから与えられたIDの兄弟を取得する */
2601    function sfGetBrothersArray($arrData, $pid_name, $id_name, $arrPID) {
2602        $max = count($arrData);
2603
2604        $arrBrothers = array();
2605        foreach($arrPID as $id) {
2606            // 親IDを検索する
2607            for($i = 0; $i < $max; $i++) {
2608                if($arrData[$i][$id_name] == $id) {
2609                    $parent = $arrData[$i][$pid_name];
2610                    break;
2611                }
2612            }
2613            // 兄弟IDを検索する
2614            for($i = 0; $i < $max; $i++) {
2615                if($arrData[$i][$pid_name] == $parent) {
2616                    $arrBrothers[] = $arrData[$i][$id_name];
2617                }
2618            }
2619        }
2620        return $arrBrothers;
2621    }
2622
2623    /* 階層構造のテーブルから与えられたIDの直属の子を取得する */
2624    function sfGetUnderChildrenArray($arrData, $pid_name, $id_name, $parent) {
2625        $max = count($arrData);
2626
2627        $arrChildren = array();
2628        // 子IDを検索する
2629        for($i = 0; $i < $max; $i++) {
2630            if($arrData[$i][$pid_name] == $parent) {
2631                $arrChildren[] = $arrData[$i][$id_name];
2632            }
2633        }
2634        return $arrChildren;
2635    }
2636
2637
2638    // カテゴリツリーの取得
2639    function sfGetCatTree($parent_category_id, $count_check = false) {
2640        $objQuery = new SC_Query();
2641        $col = "";
2642        $col .= " cat.category_id,";
2643        $col .= " cat.category_name,";
2644        $col .= " cat.parent_category_id,";
2645        $col .= " cat.level,";
2646        $col .= " cat.rank,";
2647        $col .= " cat.creator_id,";
2648        $col .= " cat.create_date,";
2649        $col .= " cat.update_date,";
2650        $col .= " cat.del_flg, ";
2651        $col .= " ttl.product_count";
2652        $from = "dtb_category as cat left join dtb_category_total_count as ttl on ttl.category_id = cat.category_id";
2653        // 登録商品数のチェック
2654        if($count_check) {
2655            $where = "del_flg = 0 AND product_count > 0";
2656        } else {
2657            $where = "del_flg = 0";
2658        }
2659        $objQuery->setoption("ORDER BY rank DESC");
2660        $arrRet = $objQuery->select($col, $from, $where);
2661
2662        $arrParentID = sfGetParents($objQuery, 'dtb_category', 'parent_category_id', 'category_id', $parent_category_id);
2663
2664        foreach($arrRet as $key => $array) {
2665            foreach($arrParentID as $val) {
2666                if($array['category_id'] == $val) {
2667                    $arrRet[$key]['display'] = 1;
2668                    break;
2669                }
2670            }
2671        }
2672
2673        return $arrRet;
2674    }
2675
2676    // 親カテゴリーを連結した文字列を取得する
2677    function sfGetCatCombName($category_id){
2678        // 商品が属するカテゴリIDを縦に取得
2679        $objQuery = new SC_Query();
2680        $arrCatID = sfGetParents($objQuery, "dtb_category", "parent_category_id", "category_id", $category_id);
2681        $ConbName = "";
2682
2683        // カテゴリー名称を取得する
2684        foreach($arrCatID as $key => $val){
2685            $sql = "SELECT category_name FROM dtb_category WHERE category_id = ?";
2686            $arrVal = array($val);
2687            $CatName = $objQuery->getOne($sql,$arrVal);
2688            $ConbName .= $CatName . ' | ';
2689        }
2690        // 最後の | をカットする
2691        $ConbName = substr_replace($ConbName, "", strlen($ConbName) - 2, 2);
2692
2693        return $ConbName;
2694    }
2695
2696    // 指定したカテゴリーIDの大カテゴリーを取得する
2697    function sfGetFirstCat($category_id){
2698        // 商品が属するカテゴリIDを縦に取得
2699        $objQuery = new SC_Query();
2700        $arrRet = array();
2701        $arrCatID = sfGetParents($objQuery, "dtb_category", "parent_category_id", "category_id", $category_id);
2702        $arrRet['id'] = $arrCatID[0];
2703
2704        // カテゴリー名称を取得する
2705        $sql = "SELECT category_name FROM dtb_category WHERE category_id = ?";
2706        $arrVal = array($arrRet['id']);
2707        $arrRet['name'] = $objQuery->getOne($sql,$arrVal);
2708
2709        return $arrRet;
2710    }
2711
2712    //MySQL用のSQL文に変更する
2713    function sfChangeMySQL($sql){
2714        // 改行、タブを1スペースに変換
2715        $sql = preg_replace("/[\r\n\t]/"," ",$sql);
2716
2717        $sql = sfChangeView($sql);      // view表をインラインビューに変換する
2718        $sql = sfChangeILIKE($sql);     // ILIKE検索をLIKE検索に変換する
2719        $sql = sfChangeRANDOM($sql);    // RANDOM()をRAND()に変換する
2720
2721        return $sql;
2722    }
2723
2724    // SQLの中にviewが存在しているかチェックを行う。
2725    function sfInArray($sql){
2726        global $arrView;
2727
2728        foreach($arrView as $key => $val){
2729            if (strcasecmp($sql, $val) == 0){
2730                $changesql = eregi_replace("($key)", "$val", $sql);
2731                sfInArray($changesql);
2732            }
2733        }
2734        return false;
2735    }
2736
2737    // SQLシングルクォート対応
2738    function sfQuoteSmart($in){
2739
2740        if (is_int($in) || is_double($in)) {
2741            return $in;
2742        } elseif (is_bool($in)) {
2743            return $in ? 1 : 0;
2744        } elseif (is_null($in)) {
2745            return 'NULL';
2746        } else {
2747            return "'" . str_replace("'", "''", $in) . "'";
2748        }
2749    }
2750
2751    // view表をインラインビューに変換する
2752    function sfChangeView($sql){
2753        global $arrView;
2754        global $arrViewWhere;
2755
2756        $arrViewTmp = $arrView;
2757
2758        // viewのwhereを変換
2759        foreach($arrViewTmp as $key => $val){
2760            $arrViewTmp[$key] = strtr($arrViewTmp[$key], $arrViewWhere);
2761        }
2762
2763        // viewを変換
2764        $changesql = strtr($sql, $arrViewTmp);
2765
2766        return $changesql;
2767    }
2768
2769    // ILIKE検索をLIKE検索に変換する
2770    function sfChangeILIKE($sql){
2771        $changesql = eregi_replace("(ILIKE )", "LIKE BINARY ", $sql);
2772        return $changesql;
2773    }
2774
2775    // RANDOM()をRAND()に変換する
2776    function sfChangeRANDOM($sql){
2777        $changesql = eregi_replace("( RANDOM)", " RAND", $sql);
2778        return $changesql;
2779    }
2780
2781    // viewのwhereを置換する
2782    function sfViewWhere($target, $where = "", $arrval = array(), $option = ""){
2783        global $arrViewWhere;
2784        $arrWhere = split("[?]", $where);
2785        $where_tmp = " WHERE " . $arrWhere[0];
2786        for($i = 1; $i < count($arrWhere); $i++){
2787            $where_tmp .= sfQuoteSmart($arrval[$i - 1]) . $arrWhere[$i];
2788        }
2789        $arrViewWhere[$target] = $where_tmp . " " . $option;
2790    }
2791
2792    // ディレクトリ以下のファイルを再帰的にコピー
2793    function sfCopyDir($src, $des, $mess, $override = false){
2794        if(!is_dir($src)){
2795            return false;
2796        }
2797
2798        $oldmask = umask(0);
2799        $mod= stat($src);
2800
2801        // ディレクトリがなければ作成する
2802        if(!file_exists($des)) {
2803            if(!mkdir($des, $mod[2])) {
2804                print("path:" . $des);
2805            }
2806        }
2807
2808        $fileArray=glob( $src."*" );
2809        foreach( $fileArray as $key => $data_ ){
2810            // CVS管理ファイルはコピーしない
2811            if(ereg("/CVS/Entries", $data_)) {
2812                break;
2813            }
2814            if(ereg("/CVS/Repository", $data_)) {
2815                break;
2816            }
2817            if(ereg("/CVS/Root", $data_)) {
2818                break;
2819            }
2820
2821            mb_ereg("^(.*[\/])(.*)",$data_, $matches);
2822            $data=$matches[2];
2823            if( is_dir( $data_ ) ){
2824                $mess = sfCopyDir( $data_.'/', $des.$data.'/', $mess);
2825            }else{
2826                if(!$override && file_exists($des.$data)) {
2827                    $mess.= $des.$data . ":ファイルが存在します\n";
2828                } else {
2829                    if(@copy( $data_, $des.$data)) {
2830                        $mess.= $des.$data . ":コピー成功\n";
2831                    } else {
2832                        $mess.= $des.$data . ":コピー失敗\n";
2833                    }
2834                }
2835                $mod=stat($data_ );
2836            }
2837        }
2838        umask($oldmask);
2839        return $mess;
2840    }
2841
2842    // 指定したフォルダ内のファイルを全て削除する
2843    function sfDelFile($dir){
2844        $dh = opendir($dir);
2845        // フォルダ内のファイルを削除
2846        while($file = readdir($dh)){
2847            if ($file == "." or $file == "..") continue;
2848            $del_file = $dir . "/" . $file;
2849            if(is_file($del_file)){
2850                $ret = unlink($dir . "/" . $file);
2851            }else if (is_dir($del_file)){
2852                $ret = sfDelFile($del_file);
2853            }
2854
2855            if(!$ret){
2856                return $ret;
2857            }
2858        }
2859
2860        // 閉じる
2861        closedir($dh);
2862
2863        // フォルダを削除
2864        return rmdir($dir);
2865    }
2866
2867    /*
2868     * 関数名:sfWriteFile
2869     * 引数1 :書き込むデータ
2870     * 引数2 :ファイルパス
2871     * 引数3 :書き込みタイプ
2872     * 引数4 :パーミッション
2873     * 戻り値:結果フラグ 成功なら true 失敗なら false
2874     * 説明 :ファイル書き出し
2875     */
2876    function sfWriteFile($str, $path, $type, $permission = "") {
2877        //ファイルを開く
2878        if (!($file = fopen ($path, $type))) {
2879            return false;
2880        }
2881
2882        //ファイルロック
2883        flock ($file, LOCK_EX);
2884        //ファイルの書き込み
2885        fputs ($file, $str);
2886        //ファイルロックの解除
2887        flock ($file, LOCK_UN);
2888        //ファイルを閉じる
2889        fclose ($file);
2890        // 権限を指定
2891        if($permission != "") {
2892            chmod($path, $permission);
2893        }
2894
2895        return true;
2896    }
2897
2898    function sfFlush($output = " ", $sleep = 0){
2899        // 実行時間を制限しない
2900        set_time_limit(0);
2901        // 出力をバッファリングしない(==日本語自動変換もしない)
2902        ob_end_clean();
2903
2904        // IEのために256バイト空文字出力
2905        echo str_pad('',256);
2906
2907        // 出力はブランクだけでもいいと思う
2908        echo $output;
2909        // 出力をフラッシュする
2910        flush();
2911
2912        ob_end_flush();
2913        ob_start();
2914
2915        // 時間のかかる処理
2916        sleep($sleep);
2917    }
2918
2919    // @versionの記載があるファイルからバージョンを取得する。
2920    function sfGetFileVersion($path) {
2921        if(file_exists($path)) {
2922            $src_fp = fopen($path, "rb");
2923            if($src_fp) {
2924                while (!feof($src_fp)) {
2925                    $line = fgets($src_fp);
2926                    if(ereg("@version", $line)) {
2927                        $arrLine = split(" ", $line);
2928                        $version = $arrLine[5];
2929                    }
2930                }
2931                fclose($src_fp);
2932            }
2933        }
2934        return $version;
2935    }
2936
2937    // 指定したURLに対してPOSTでデータを送信する
2938    function sfSendPostData($url, $arrData, $arrOkCode = array()){
2939        require_once(DATA_PATH . "module/Request.php");
2940
2941        // 送信インスタンス生成
2942        $req = new HTTP_Request($url);
2943
2944        $req->addHeader('User-Agent', 'DoCoMo/2.0 P2101V(c100)');
2945        $req->setMethod(HTTP_REQUEST_METHOD_POST);
2946
2947        // POSTデータ送信
2948        $req->addPostDataArray($arrData);
2949
2950        // エラーが無ければ、応答情報を取得する
2951        if (!PEAR::isError($req->sendRequest())) {
2952
2953            // レスポンスコードがエラー判定なら、空を返す
2954            $res_code = $req->getResponseCode();
2955
2956            if(!in_array($res_code, $arrOkCode)){
2957                $response = "";
2958            }else{
2959                $response = $req->getResponseBody();
2960            }
2961
2962        } else {
2963            $response = "";
2964        }
2965
2966        // POSTデータクリア
2967        $req->clearPostData();
2968
2969        return $response;
2970    }
2971
2972    /* デバッグ用 ------------------------------------------------------------------------------------------------*/
2973    function sfPrintR($obj) {
2974        print("<div style='font-size: 12px;color: #00FF00;'>\n");
2975        print("<strong>**デバッグ中**</strong><br />\n");
2976        print("<pre>\n");
2977        print_r($obj);
2978        print("</pre>\n");
2979        print("<strong>**デバッグ中**</strong></div>\n");
2980    }
2981}
2982?>
Note: See TracBrowser for help on using the repository browser.