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

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