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

Revision 15340, 80.3 KB checked in by nanasess, 17 years ago (diff)

未定義変数を修正

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