source: branches/version-2_5-dev/data/class/util/SC_Utils.php @ 18792

Revision 18792, 76.2 KB checked in by nanasess, 14 years ago (diff)

r18789 の変更に伴い SC_Utils::sfManualEscape() が不具合を発生していたので, 使用しないように修正(#801)

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