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

Revision 15293, 80.4 KB checked in by nanasess, 17 years ago (diff)

DB 関連の関数を SC_Helper_DB クラスへ移動

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