source: branches/comu-ver2/data/class/util/SC_Utils.php @ 18569

Revision 18569, 75.4 KB checked in by shutta, 14 years ago (diff)

r18568 をマージ。

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