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

Revision 15155, 105.0 KB checked in by nanasess, 17 years ago (diff)

slib.php のクラス化対応

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