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

Revision 18815, 76.4 KB checked in by nanasess, 14 years ago (diff)

規格まわりの内部構成変更に伴う修正(#781)

  • 規格のデータ構造を木構造へ変更
  • 商品検索ロジックを SC_Product クラスへできるだけ集約
  • 以下の VIEW を削除
    • vw_category_count;
    • vw_product_class;
    • vw_products_nonclass;
    • vw_cross_products_class;
    • vw_cross_class;
    • vw_download_class;
  • 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        $where = "product_id = ?";
862        $objQuery = new SC_Query();
863        // $ret = $objQuery->get("dtb_products_class", "product_class_id", $where, Array($product_id, $classcategory_id1, $classcategory_id2));
864        $ret = $objQuery->get("dtb_products_class", "product_class_id", $where, Array($product_id));
865        return $ret;
866    }
867
868    /* 文末の「/」をなくす */
869    function sfTrimURL($url) {
870        $ret = ereg_replace("[/]+$", "", $url);
871        return $ret;
872    }
873
874    /* DBから取り出した日付の文字列を調整する。*/
875    function sfDispDBDate($dbdate, $time = true) {
876        list($y, $m, $d, $H, $M) = split("[- :]", $dbdate);
877
878        if(strlen($y) > 0 && strlen($m) > 0 && strlen($d) > 0) {
879            if ($time) {
880                $str = sprintf("%04d/%02d/%02d %02d:%02d", $y, $m, $d, $H, $M);
881            } else {
882                $str = sprintf("%04d/%02d/%02d", $y, $m, $d, $H, $M);
883            }
884        } else {
885            $str = "";
886        }
887        return $str;
888    }
889
890    /* 配列をキー名ごとの配列に変更する */
891    function sfSwapArray($array, $isColumnName = true) {
892        $arrRet = array();
893        $max = count($array);
894        for($i = 0; $i < $max; $i++) {
895            $j = 0;
896            foreach($array[$i] as $key => $val) {
897                if ($isColumnName) {
898                    $arrRet[$key][] = $val;
899                } else {
900                    $arrRet[$j][] = $val;
901                }
902                $j++;
903            }
904        }
905        return $arrRet;
906    }
907
908    /**
909     * 連想配列から新たな配列を生成して返す.
910     *
911     * $requires が指定された場合, $requires に含まれるキーの値のみを返す.
912     *
913     * @param array 連想配列
914     * @param array 必須キーの配列
915     * @return array 連想配列の値のみの配列
916     */
917    function getHash2Array($hash, $requires = array()) {
918        $array = array();
919        $i = 0;
920        foreach ($hash as $key => $val) {
921            if (!empty($requires)) {
922                if (in_array($key, $requires)) {
923                    $array[$i] = $val;
924                    $i++;
925                }
926            } else {
927                $array[$i] = $val;
928                $i++;
929            }
930        }
931        return $array;
932    }
933
934    /* かけ算をする(Smarty用) */
935    function sfMultiply($num1, $num2) {
936        return ($num1 * $num2);
937    }
938
939    // カードの処理結果を返す
940    function sfGetAuthonlyResult($dir, $file_name, $name01, $name02, $card_no, $card_exp, $amount, $order_id, $jpo_info = "10"){
941
942        $path = $dir .$file_name;        // cgiファイルのフルパス生成
943        $now_dir = getcwd();            // requireがうまくいかないので、cgi実行ディレクトリに移動する
944        chdir($dir);
945
946        // パイプ渡しでコマンドラインからcgi起動
947        $cmd = "$path card_no=$card_no name01=$name01 name02=$name02 card_exp=$card_exp amount=$amount order_id=$order_id jpo_info=$jpo_info";
948
949        $tmpResult = popen($cmd, "r");
950
951        // 結果取得
952        while( ! FEOF ( $tmpResult ) ) {
953            $result .= FGETS($tmpResult);
954        }
955        pclose($tmpResult);                //     パイプを閉じる
956        chdir($now_dir);                // 元にいたディレクトリに帰る
957
958        // 結果を連想配列へ格納
959        $result = ereg_replace("&$", "", $result);
960        foreach (explode("&",$result) as $data) {
961            list($key, $val) = explode("=", $data, 2);
962            $return[$key] = $val;
963        }
964
965        return $return;
966    }
967
968    /**
969     * 加算ポイントの計算
970     *
971     * ・店舗基本情報に基づいた計算は SC_Helper_DB::sfGetAddPoint() を使用する
972     *
973     * @param integer $totalpoint
974     * @param integer $use_point
975     * @param integer $point_rate
976     * @return integer 加算ポイント
977     */
978    function sfGetAddPoint($totalpoint, $use_point, $point_rate) {
979        // 購入商品の合計ポイントから利用したポイントのポイント換算価値を引く方式
980        $add_point = $totalpoint - intval($use_point * ($point_rate / 100));
981
982        if($add_point < 0) {
983            $add_point = '0';
984        }
985        return $add_point;
986    }
987
988    /* 一意かつ予測されにくいID */
989    function sfGetUniqRandomId($head = "") {
990        // 予測されないようにランダム文字列を付与する。
991        $random = GC_Utils_Ex::gfMakePassword(8);
992        // 同一ホスト内で一意なIDを生成
993        $id = uniqid($head);
994        return ($id . $random);
995    }
996
997    /**
998     * ドメイン間で有効なセッションのスタート
999     * 共有SSL対応のための修正により、この関数は廃止します。
1000     * セッションはrequire.phpを読み込んだ際に開始されます。
1001     */
1002    function sfDomainSessionStart() {
1003        /**
1004         * 2.1.1ベータからはSC_SessionFactory_UseCookie::initSession()で処理するため、
1005         * ここでは何も処理しない
1006         */
1007        if (defined('SESSION_KEEP_METHOD')) {
1008            return;
1009        }
1010
1011        if (session_id() === "") {
1012
1013            session_set_cookie_params(0, "/", DOMAIN_NAME);
1014
1015            if (!ini_get("session.auto_start")) {
1016                // セッション開始
1017                session_start();
1018            }
1019        }
1020    }
1021
1022    /* 文字列に強制的に改行を入れる */
1023    function sfPutBR($str, $size) {
1024        $i = 0;
1025        $cnt = 0;
1026        $line = array();
1027        $ret = "";
1028
1029        while($str[$i] != "") {
1030            $line[$cnt].=$str[$i];
1031            $i++;
1032            if(strlen($line[$cnt]) > $size) {
1033                $line[$cnt].="<br />";
1034                $cnt++;
1035            }
1036        }
1037
1038        foreach($line as $val) {
1039            $ret.=$val;
1040        }
1041        return $ret;
1042    }
1043
1044    // 二回以上繰り返されているスラッシュ[/]を一つに変換する。
1045    function sfRmDupSlash($istr){
1046        if(ereg("^http://", $istr)) {
1047            $str = substr($istr, 7);
1048            $head = "http://";
1049        } else if(ereg("^https://", $istr)) {
1050            $str = substr($istr, 8);
1051            $head = "https://";
1052        } else {
1053            $str = $istr;
1054        }
1055        $str = ereg_replace("[/]+", "/", $str);
1056        $ret = $head . $str;
1057        return $ret;
1058    }
1059
1060    /**
1061     * テキストファイルの文字エンコーディングを変換する.
1062     *
1063     * $filepath に存在するテキストファイルの文字エンコーディングを変換する.
1064     * 変換前の文字エンコーディングは, mb_detect_order で設定した順序で自動検出する.
1065     * 変換後は, 変換前のファイル名に「enc_」というプレフィクスを付与し,
1066     * $out_dir で指定したディレクトリへ出力する
1067     *
1068     * TODO $filepath のファイルがバイナリだった場合の扱い
1069     * TODO fwrite などでのエラーハンドリング
1070     *
1071     * @access public
1072     * @param string $filepath 変換するテキストファイルのパス
1073     * @param string $enc_type 変換後のファイルエンコーディングの種類を表す文字列
1074     * @param string $out_dir 変換後のファイルを出力するディレクトリを表す文字列
1075     * @return string 変換後のテキストファイルのパス
1076     */
1077    function sfEncodeFile($filepath, $enc_type, $out_dir) {
1078        $ifp = fopen($filepath, "r");
1079
1080        // 正常にファイルオープンした場合
1081        if ($ifp !== false) {
1082
1083            $basename = basename($filepath);
1084            $outpath = $out_dir . "enc_" . $basename;
1085
1086            $ofp = fopen($outpath, "w+");
1087
1088            while(!feof($ifp)) {
1089                $line = fgets($ifp);
1090                $line = mb_convert_encoding($line, $enc_type, "auto");
1091                fwrite($ofp,  $line);
1092            }
1093
1094            fclose($ofp);
1095            fclose($ifp);
1096        }
1097        // ファイルが開けなかった場合はエラーページを表示
1098          else {
1099              SC_Utils::sfDispError('');
1100              exit;
1101        }
1102        return     $outpath;
1103    }
1104
1105    function sfCutString($str, $len, $byte = true, $commadisp = true) {
1106        if($byte) {
1107            if(strlen($str) > ($len + 2)) {
1108                $ret =substr($str, 0, $len);
1109                $cut = substr($str, $len);
1110            } else {
1111                $ret = $str;
1112                $commadisp = false;
1113            }
1114        } else {
1115            if(mb_strlen($str) > ($len + 1)) {
1116                $ret = mb_substr($str, 0, $len);
1117                $cut = mb_substr($str, $len);
1118            } else {
1119                $ret = $str;
1120                $commadisp = false;
1121            }
1122        }
1123
1124        // 絵文字タグの途中で分断されないようにする。
1125        if (isset($cut)) {
1126            // 分割位置より前の最後の [ 以降を取得する。
1127            $head = strrchr($ret, '[');
1128
1129            // 分割位置より後の最初の ] 以前を取得する。
1130            $tail_pos = strpos($cut, ']');
1131            if ($tail_pos !== false) {
1132                $tail = substr($cut, 0, $tail_pos + 1);
1133            }
1134
1135            // 分割位置より前に [、後に ] が見つかった場合は、[ から ] までを
1136            // 接続して絵文字タグ1個分になるかどうかをチェックする。
1137            if ($head !== false && $tail_pos !== false) {
1138                $subject = $head . $tail;
1139                if (preg_match('/^\[emoji:e?\d+\]$/', $subject)) {
1140                    // 絵文字タグが見つかったので削除する。
1141                    $ret = substr($ret, 0, -strlen($head));
1142                }
1143            }
1144        }
1145
1146        if($commadisp){
1147            $ret = $ret . "...";
1148        }
1149        return $ret;
1150    }
1151
1152    // 年、月、締め日から、先月の締め日+1、今月の締め日を求める。
1153    function sfTermMonth($year, $month, $close_day) {
1154        $end_year = $year;
1155        $end_month = $month;
1156
1157        // 開始月が終了月と同じか否か
1158        $same_month = false;
1159
1160        // 該当月の末日を求める。
1161        $end_last_day = date("d", mktime(0, 0, 0, $month + 1, 0, $year));
1162
1163        // 月の末日が締め日より少ない場合
1164        if($end_last_day < $close_day) {
1165            // 締め日を月末日に合わせる
1166            $end_day = $end_last_day;
1167        } else {
1168            $end_day = $close_day;
1169        }
1170
1171        // 前月の取得
1172        $tmp_year = date("Y", mktime(0, 0, 0, $month, 0, $year));
1173        $tmp_month = date("m", mktime(0, 0, 0, $month, 0, $year));
1174        // 前月の末日を求める。
1175        $start_last_day = date("d", mktime(0, 0, 0, $month, 0, $year));
1176
1177        // 前月の末日が締め日より少ない場合
1178        if ($start_last_day < $close_day) {
1179            // 月末日に合わせる
1180            $tmp_day = $start_last_day;
1181        } else {
1182            $tmp_day = $close_day;
1183        }
1184
1185        // 先月の末日の翌日を取得する
1186        $start_year = date("Y", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1187        $start_month = date("m", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1188        $start_day = date("d", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1189
1190        // 日付の作成
1191        $start_date = sprintf("%d/%d/%d 00:00:00", $start_year, $start_month, $start_day);
1192        $end_date = sprintf("%d/%d/%d 23:59:59", $end_year, $end_month, $end_day);
1193
1194        return array($start_date, $end_date);
1195    }
1196
1197    // PDF用のRGBカラーを返す
1198    function sfGetPdfRgb($hexrgb) {
1199        $hex = substr($hexrgb, 0, 2);
1200        $r = hexdec($hex) / 255;
1201
1202        $hex = substr($hexrgb, 2, 2);
1203        $g = hexdec($hex) / 255;
1204
1205        $hex = substr($hexrgb, 4, 2);
1206        $b = hexdec($hex) / 255;
1207
1208        return array($r, $g, $b);
1209    }
1210
1211    // 再帰的に多段配列を検索して一次元配列(Hidden引渡し用配列)に変換する。
1212    function sfMakeHiddenArray($arrSrc, $arrDst = array(), $parent_key = "") {
1213        if(is_array($arrSrc)) {
1214            foreach($arrSrc as $key => $val) {
1215                if($parent_key != "") {
1216                    $keyname = $parent_key . "[". $key . "]";
1217                } else {
1218                    $keyname = $key;
1219                }
1220                if(is_array($val)) {
1221                    $arrDst = SC_Utils::sfMakeHiddenArray($val, $arrDst, $keyname);
1222                } else {
1223                    $arrDst[$keyname] = $val;
1224                }
1225            }
1226        }
1227        return $arrDst;
1228    }
1229
1230    // DB取得日時をタイムに変換
1231    function sfDBDatetoTime($db_date) {
1232        $date = ereg_replace("\..*$","",$db_date);
1233        $time = strtotime($date);
1234        return $time;
1235    }
1236
1237    /**
1238     * テンプレートを切り替えて出力する
1239     *
1240     * @deprecated 2008/04/02以降使用不可
1241     */
1242    function sfCustomDisplay(&$objPage, $is_mobile = false) {
1243        $basename = basename($_SERVER["REQUEST_URI"]);
1244
1245        if($basename == "") {
1246            $path = $_SERVER["REQUEST_URI"] . DIR_INDEX_URL;
1247        } else {
1248            $path = $_SERVER["REQUEST_URI"];
1249        }
1250
1251        if(isset($_GET['tpl']) && $_GET['tpl'] != "") {
1252            $tpl_name = $_GET['tpl'];
1253        } else {
1254            $tpl_name = ereg_replace("^/", "", $path);
1255            $tpl_name = ereg_replace("/", "_", $tpl_name);
1256            $tpl_name = ereg_replace("(\.php$|\.html$)", ".tpl", $tpl_name);
1257        }
1258
1259        $template_path = TEMPLATE_FTP_DIR . $tpl_name;
1260echo $template_path;
1261        if($is_mobile === true) {
1262            $objView = new SC_MobileView();
1263            $objView->assignobj($objPage);
1264            $objView->display(SITE_FRAME);
1265        } else if(file_exists($template_path)) {
1266            $objView = new SC_UserView(TEMPLATE_FTP_DIR, COMPILE_FTP_DIR);
1267            $objView->assignobj($objPage);
1268            $objView->display($tpl_name);
1269        } else {
1270            $objView = new SC_SiteView();
1271            $objView->assignobj($objPage);
1272            $objView->display(SITE_FRAME);
1273        }
1274    }
1275
1276    // PHPのmb_convert_encoding関数をSmartyでも使えるようにする
1277    function sf_mb_convert_encoding($str, $encode = 'CHAR_CODE') {
1278        return  mb_convert_encoding($str, $encode);
1279    }
1280
1281    // PHPのmktime関数をSmartyでも使えるようにする
1282    function sf_mktime($format, $hour=0, $minute=0, $second=0, $month=1, $day=1, $year=1999) {
1283        return  date($format,mktime($hour, $minute, $second, $month, $day, $year));
1284    }
1285
1286    // PHPのdate関数をSmartyでも使えるようにする
1287    function sf_date($format, $timestamp = '') {
1288        return  date( $format, $timestamp);
1289    }
1290
1291    // チェックボックスの型を変換する
1292    function sfChangeCheckBox($data , $tpl = false){
1293        if ($tpl) {
1294            if ($data == 1){
1295                return 'checked';
1296            }else{
1297                return "";
1298            }
1299        }else{
1300            if ($data == "on"){
1301                return 1;
1302            }else{
1303                return 2;
1304            }
1305        }
1306    }
1307
1308    // 2つの配列を用いて連想配列を作成する
1309    function sfarrCombine($arrKeys, $arrValues) {
1310
1311        if(count($arrKeys) <= 0 and count($arrValues) <= 0) return array();
1312
1313        $keys = array_values($arrKeys);
1314        $vals = array_values($arrValues);
1315
1316        $max = max( count( $keys ), count( $vals ) );
1317        $combine_ary = array();
1318        for($i=0; $i<$max; $i++) {
1319            $combine_ary[$keys[$i]] = $vals[$i];
1320        }
1321        if(is_array($combine_ary)) return $combine_ary;
1322
1323        return false;
1324    }
1325
1326    /* 子ID所属する親IDを取得する */
1327    function sfGetParentsArraySub($arrData, $pid_name, $id_name, $child) {
1328        $max = count($arrData);
1329        $parent = "";
1330        for($i = 0; $i < $max; $i++) {
1331            if($arrData[$i][$id_name] == $child) {
1332                $parent = $arrData[$i][$pid_name];
1333                break;
1334            }
1335        }
1336        return $parent;
1337    }
1338
1339    /* 階層構造のテーブルから与えられたIDの兄弟を取得する */
1340    function sfGetBrothersArray($arrData, $pid_name, $id_name, $arrPID) {
1341        $max = count($arrData);
1342
1343        $arrBrothers = array();
1344        foreach($arrPID as $id) {
1345            // 親IDを検索する
1346            for($i = 0; $i < $max; $i++) {
1347                if($arrData[$i][$id_name] == $id) {
1348                    $parent = $arrData[$i][$pid_name];
1349                    break;
1350                }
1351            }
1352            // 兄弟IDを検索する
1353            for($i = 0; $i < $max; $i++) {
1354                if($arrData[$i][$pid_name] == $parent) {
1355                    $arrBrothers[] = $arrData[$i][$id_name];
1356                }
1357            }
1358        }
1359        return $arrBrothers;
1360    }
1361
1362    /* 階層構造のテーブルから与えられたIDの直属の子を取得する */
1363    function sfGetUnderChildrenArray($arrData, $pid_name, $id_name, $parent) {
1364        $max = count($arrData);
1365
1366        $arrChildren = array();
1367        // 子IDを検索する
1368        for($i = 0; $i < $max; $i++) {
1369            if($arrData[$i][$pid_name] == $parent) {
1370                $arrChildren[] = $arrData[$i][$id_name];
1371            }
1372        }
1373        return $arrChildren;
1374    }
1375
1376    /**
1377     * SQLシングルクォート対応
1378     * @deprecated SC_Query::quote() を使用すること
1379     */
1380    function sfQuoteSmart($in){
1381
1382        if (is_int($in) || is_double($in)) {
1383            return $in;
1384        } elseif (is_bool($in)) {
1385            return $in ? 1 : 0;
1386        } elseif (is_null($in)) {
1387            return 'NULL';
1388        } else {
1389            return "'" . str_replace("'", "''", $in) . "'";
1390        }
1391    }
1392
1393    // ディレクトリを再帰的に生成する
1394    function sfMakeDir($path) {
1395        static $count = 0;
1396        $count++;  // 無限ループ回避
1397        $dir = dirname($path);
1398        if(ereg("^[/]$", $dir) || ereg("^[A-Z]:[\\]$", $dir) || $count > 256) {
1399            // ルートディレクトリで終了
1400            return;
1401        } else {
1402            if(is_writable(dirname($dir))) {
1403                if(!file_exists($dir)) {
1404                    mkdir($dir);
1405                    GC_Utils::gfPrintLog("mkdir $dir");
1406                }
1407            } else {
1408                SC_Utils::sfMakeDir($dir);
1409                if(is_writable(dirname($dir))) {
1410                    if(!file_exists($dir)) {
1411                        mkdir($dir);
1412                        GC_Utils::gfPrintLog("mkdir $dir");
1413                    }
1414                }
1415           }
1416        }
1417        return;
1418    }
1419
1420    // ディレクトリ以下のファイルを再帰的にコピー
1421    function sfCopyDir($src, $des, $mess = "", $override = false){
1422        if(!is_dir($src)){
1423            return false;
1424        }
1425
1426        $oldmask = umask(0);
1427        $mod= stat($src);
1428
1429        // ディレクトリがなければ作成する
1430        if(!file_exists($des)) {
1431            if(!mkdir($des, $mod[2])) {
1432                print("path:" . $des);
1433            }
1434        }
1435
1436        $fileArray=glob( $src."*" );
1437        if (is_array($fileArray)) {
1438            foreach( $fileArray as $key => $data_ ){
1439                // CVS管理ファイルはコピーしない
1440                if(ereg("/CVS/Entries", $data_)) {
1441                    break;
1442                }
1443                if(ereg("/CVS/Repository", $data_)) {
1444                    break;
1445                }
1446                if(ereg("/CVS/Root", $data_)) {
1447                    break;
1448                }
1449
1450                mb_ereg("^(.*[\/])(.*)",$data_, $matches);
1451                $data=$matches[2];
1452                if( is_dir( $data_ ) ){
1453                    $mess = SC_Utils::sfCopyDir( $data_.'/', $des.$data.'/', $mess);
1454                }else{
1455                    if(!$override && file_exists($des.$data)) {
1456                        $mess.= $des.$data . ":ファイルが存在します\n";
1457                    } else {
1458                        if(@copy( $data_, $des.$data)) {
1459                            $mess.= $des.$data . ":コピー成功\n";
1460                        } else {
1461                            $mess.= $des.$data . ":コピー失敗\n";
1462                        }
1463                    }
1464                    $mod=stat($data_ );
1465                }
1466            }
1467        }
1468        umask($oldmask);
1469        return $mess;
1470    }
1471
1472    // 指定したフォルダ内のファイルを全て削除する
1473    function sfDelFile($dir){
1474        if(file_exists($dir)) {
1475            $dh = opendir($dir);
1476            // フォルダ内のファイルを削除
1477            while($file = readdir($dh)){
1478                if ($file == "." or $file == "..") continue;
1479                $del_file = $dir . "/" . $file;
1480                if(is_file($del_file)){
1481                    $ret = unlink($dir . "/" . $file);
1482                }else if (is_dir($del_file)){
1483                    $ret = SC_Utils::sfDelFile($del_file);
1484                }
1485
1486                if(!$ret){
1487                    return $ret;
1488                }
1489            }
1490
1491            // 閉じる
1492            closedir($dh);
1493
1494            // フォルダを削除
1495            return rmdir($dir);
1496        }
1497    }
1498
1499    /*
1500     * 関数名:sfWriteFile
1501     * 引数1 :書き込むデータ
1502     * 引数2 :ファイルパス
1503     * 引数3 :書き込みタイプ
1504     * 引数4 :パーミッション
1505     * 戻り値:結果フラグ 成功なら true 失敗なら false
1506     * 説明 :ファイル書き出し
1507     */
1508    function sfWriteFile($str, $path, $type, $permission = "") {
1509        //ファイルを開く
1510        if (!($file = fopen ($path, $type))) {
1511            return false;
1512        }
1513
1514        //ファイルロック
1515        flock ($file, LOCK_EX);
1516        //ファイルの書き込み
1517        fputs ($file, $str);
1518        //ファイルロックの解除
1519        flock ($file, LOCK_UN);
1520        //ファイルを閉じる
1521        fclose ($file);
1522        // 権限を指定
1523        if($permission != "") {
1524            chmod($path, $permission);
1525        }
1526
1527        return true;
1528    }
1529
1530    /**
1531     * ブラウザに強制的に送出する
1532     *
1533     * @param boolean|string $output 半角スペース256文字+改行を出力するか。または、送信する文字列を指定。
1534     * @return void
1535     */
1536    function sfFlush($output = false, $sleep = 0){
1537        // 出力をバッファリングしない(==日本語自動変換もしない)
1538        while (@ob_end_flush());
1539
1540        if ($output === true) {
1541            // IEのために半角スペース256文字+改行を出力
1542            //echo str_repeat(' ', 256) . "\n";
1543            echo str_pad('', 256) . "\n";
1544        } else if ($output !== false) {
1545            echo $output;
1546        }
1547
1548        // 出力をフラッシュする
1549        flush();
1550
1551        ob_start();
1552
1553        // 時間のかかる処理
1554        sleep($sleep);
1555    }
1556
1557    // @versionの記載があるファイルからバージョンを取得する。
1558    function sfGetFileVersion($path) {
1559        if(file_exists($path)) {
1560            $src_fp = fopen($path, "rb");
1561            if($src_fp) {
1562                while (!feof($src_fp)) {
1563                    $line = fgets($src_fp);
1564                    if(ereg("@version", $line)) {
1565                        $arrLine = split(" ", $line);
1566                        $version = $arrLine[5];
1567                    }
1568                }
1569                fclose($src_fp);
1570            }
1571        }
1572        return $version;
1573    }
1574
1575    // 指定したURLに対してPOSTでデータを送信する
1576    function sfSendPostData($url, $arrData, $arrOkCode = array()){
1577        require_once(DATA_PATH . "module/Request.php");
1578
1579        // 送信インスタンス生成
1580        $req = new HTTP_Request($url);
1581
1582        $req->addHeader('User-Agent', 'DoCoMo/2.0 P2101V(c100)');
1583        $req->setMethod(HTTP_REQUEST_METHOD_POST);
1584
1585        // POSTデータ送信
1586        $req->addPostDataArray($arrData);
1587
1588        // エラーが無ければ、応答情報を取得する
1589        if (!PEAR::isError($req->sendRequest())) {
1590
1591            // レスポンスコードがエラー判定なら、空を返す
1592            $res_code = $req->getResponseCode();
1593
1594            if(!in_array($res_code, $arrOkCode)){
1595                $response = "";
1596            }else{
1597                $response = $req->getResponseBody();
1598            }
1599
1600        } else {
1601            $response = "";
1602        }
1603
1604        // POSTデータクリア
1605        $req->clearPostData();
1606
1607        return $response;
1608    }
1609
1610    /**
1611     * $array の要素を $arrConvList で指定した方式で mb_convert_kana を適用する.
1612     *
1613     * @param array $array 変換する文字列の配列
1614     * @param array $arrConvList mb_convert_kana の適用ルール
1615     * @return array 変換後の配列
1616     * @see mb_convert_kana
1617     */
1618    function mbConvertKanaWithArray($array, $arrConvList) {
1619        foreach ($arrConvList as $key => $val) {
1620            if(isset($array[$key])) {
1621                $array[$key] = mb_convert_kana($array[$key] ,$val);
1622            }
1623        }
1624        return $array;
1625    }
1626
1627    /**
1628     * 配列の添字が未定義の場合は空文字を代入して定義する.
1629     *
1630     * @param array $array 添字をチェックする配列
1631     * @param array $defineIndexes チェックする添字
1632     * @return array 添字を定義した配列
1633     */
1634    function arrayDefineIndexes($array, $defineIndexes) {
1635        foreach ($defineIndexes as $key) {
1636            if (!isset($array[$key])) $array[$key] = "";
1637        }
1638        return $array;
1639    }
1640
1641    /**
1642     * $arrSrc のうち、キーが $arrKey に含まれるものを返す
1643     *
1644     * $arrSrc に含まない要素は返されない。
1645     *
1646     * @param array $arrSrc
1647     * @param array $arrKey
1648     * @return array
1649     */
1650    function sfArrayIntersectKeys($arrSrc, $arrKey) {
1651        $arrRet = array();
1652        foreach ($arrKey as $key) {
1653            if (isset($arrSrc[$key])) $arrRet[$key] = $arrSrc[$key];
1654        }
1655        return $arrRet;
1656    }
1657
1658    /**
1659     * XML宣言を出力する.
1660     *
1661     * XML宣言があると問題が発生する UA は出力しない.
1662     *
1663     * @return string XML宣言の文字列
1664     */
1665    function printXMLDeclaration() {
1666        $ua = $_SERVER['HTTP_USER_AGENT'];
1667        if (!preg_match("/MSIE/", $ua) || preg_match("/MSIE 7/", $ua)) {
1668            print("<?xml version='1.0' encoding='" . CHAR_CODE . "'?>\n");
1669        }
1670    }
1671
1672    /*
1673     * 関数名:sfGetFileList()
1674     * 説明 :指定パス配下のディレクトリ取得
1675     * 引数1 :取得するディレクトリパス
1676     */
1677    function sfGetFileList($dir) {
1678        $arrFileList = array();
1679        $arrDirList = array();
1680
1681        if (is_dir($dir)) {
1682            if ($dh = opendir($dir)) {
1683                $cnt = 0;
1684                // 行末の/を取り除く
1685                while (($file = readdir($dh)) !== false) $arrDir[] = $file;
1686                $dir = ereg_replace("/$", "", $dir);
1687                // アルファベットと数字でソート
1688                natcasesort($arrDir);
1689                foreach($arrDir as $file) {
1690                    // ./ と ../を除くファイルのみを取得
1691                    if($file != "." && $file != "..") {
1692
1693                        $path = $dir."/".$file;
1694                        // SELECT内の見た目を整えるため指定文字数で切る
1695                        $file_name = SC_Utils::sfCutString($file, FILE_NAME_LEN);
1696                        $file_size = SC_Utils::sfCutString(SC_Utils::sfGetDirSize($path), FILE_NAME_LEN);
1697                        $file_time = date("Y/m/d", filemtime($path));
1698
1699                        // ディレクトリとファイルで格納配列を変える
1700                        if(is_dir($path)) {
1701                            $arrDirList[$cnt]['file_name'] = $file;
1702                            $arrDirList[$cnt]['file_path'] = $path;
1703                            $arrDirList[$cnt]['file_size'] = $file_size;
1704                            $arrDirList[$cnt]['file_time'] = $file_time;
1705                            $arrDirList[$cnt]['is_dir'] = true;
1706                        } else {
1707                            $arrFileList[$cnt]['file_name'] = $file;
1708                            $arrFileList[$cnt]['file_path'] = $path;
1709                            $arrFileList[$cnt]['file_size'] = $file_size;
1710                            $arrFileList[$cnt]['file_time'] = $file_time;
1711                            $arrFileList[$cnt]['is_dir'] = false;
1712                        }
1713                        $cnt++;
1714                    }
1715                }
1716                closedir($dh);
1717            }
1718        }
1719
1720        // フォルダを先頭にしてマージ
1721        return array_merge($arrDirList, $arrFileList);
1722    }
1723
1724    /*
1725     * 関数名:sfGetDirSize()
1726     * 説明 :指定したディレクトリのバイト数を取得
1727     * 引数1 :ディレクトリ
1728     */
1729    function sfGetDirSize($dir) {
1730        if(file_exists($dir)) {
1731            // ディレクトリの場合下層ファイルの総量を取得
1732            if (is_dir($dir)) {
1733                $handle = opendir($dir);
1734                while ($file = readdir($handle)) {
1735                    // 行末の/を取り除く
1736                    $dir = ereg_replace("/$", "", $dir);
1737                    $path = $dir."/".$file;
1738                    if ($file != '..' && $file != '.' && !is_dir($path)) {
1739                        $bytes += filesize($path);
1740                    } else if (is_dir($path) && $file != '..' && $file != '.') {
1741                        // 下層ファイルのバイト数を取得する為、再帰的に呼び出す。
1742                        $bytes += SC_Utils::sfGetDirSize($path);
1743                    }
1744                }
1745            } else {
1746                // ファイルの場合
1747                $bytes = filesize($dir);
1748            }
1749        }
1750        // ディレクトリ(ファイル)が存在しない場合は0byteを返す
1751        if($bytes == "") $bytes = 0;
1752
1753        return $bytes;
1754    }
1755
1756    /*
1757     * 関数名:sfDeleteDir()
1758     * 説明 :指定したディレクトリを削除
1759     * 引数1 :削除ファイル
1760     */
1761    function sfDeleteDir($dir) {
1762        $arrResult = array();
1763        if(file_exists($dir)) {
1764            // ディレクトリかチェック
1765            if (is_dir($dir)) {
1766                if ($handle = opendir("$dir")) {
1767                    $cnt = 0;
1768                    while (false !== ($item = readdir($handle))) {
1769                        if ($item != "." && $item != "..") {
1770                            if (is_dir("$dir/$item")) {
1771                                sfDeleteDir("$dir/$item");
1772                            } else {
1773                                $arrResult[$cnt]['result'] = @unlink("$dir/$item");
1774                                $arrResult[$cnt]['file_name'] = "$dir/$item";
1775                            }
1776                        }
1777                        $cnt++;
1778                    }
1779                }
1780                closedir($handle);
1781                $arrResult[$cnt]['result'] = @rmdir($dir);
1782                $arrResult[$cnt]['file_name'] = "$dir/$item";
1783            } else {
1784                // ファイル削除
1785                $arrResult[0]['result'] = @unlink("$dir");
1786                $arrResult[0]['file_name'] = "$dir";
1787            }
1788        }
1789
1790        return $arrResult;
1791    }
1792
1793    /*
1794     * 関数名:sfGetFileTree()
1795     * 説明 :ツリー生成用配列取得(javascriptに渡す用)
1796     * 引数1 :ディレクトリ
1797     * 引数2 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1798     */
1799    function sfGetFileTree($dir, $tree_status) {
1800
1801        $cnt = 0;
1802        $arrTree = array();
1803        $default_rank = count(split('/', $dir));
1804
1805        // 文末の/を取り除く
1806        $dir = ereg_replace("/$", "", $dir);
1807        // 最上位層を格納(user_data/)
1808        if(sfDirChildExists($dir)) {
1809            $arrTree[$cnt]['type'] = "_parent";
1810        } else {
1811            $arrTree[$cnt]['type'] = "_child";
1812        }
1813        $arrTree[$cnt]['path'] = $dir;
1814        $arrTree[$cnt]['rank'] = 0;
1815        $arrTree[$cnt]['count'] = $cnt;
1816        // 初期表示はオープン
1817        if($_POST['mode'] != '') {
1818            $arrTree[$cnt]['open'] = lfIsFileOpen($dir, $tree_status);
1819        } else {
1820            $arrTree[$cnt]['open'] = true;
1821        }
1822        $cnt++;
1823
1824        sfGetFileTreeSub($dir, $default_rank, $cnt, $arrTree, $tree_status);
1825
1826        return $arrTree;
1827    }
1828
1829    /*
1830     * 関数名:sfGetFileTree()
1831     * 説明 :ツリー生成用配列取得(javascriptに渡す用)
1832     * 引数1 :ディレクトリ
1833     * 引数2 :デフォルトの階層(/区切りで 0,1,2・・・とカウント)
1834     * 引数3 :連番
1835     * 引数4 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1836     */
1837    function sfGetFileTreeSub($dir, $default_rank, &$cnt, &$arrTree, $tree_status) {
1838
1839        if(file_exists($dir)) {
1840            if ($handle = opendir("$dir")) {
1841                while (false !== ($item = readdir($handle))) $arrDir[] = $item;
1842                // アルファベットと数字でソート
1843                natcasesort($arrDir);
1844                foreach($arrDir as $item) {
1845                    if ($item != "." && $item != "..") {
1846                        // 文末の/を取り除く
1847                        $dir = ereg_replace("/$", "", $dir);
1848                        $path = $dir."/".$item;
1849                        // ディレクトリのみ取得
1850                        if (is_dir($path)) {
1851                            $arrTree[$cnt]['path'] = $path;
1852                            if(sfDirChildExists($path)) {
1853                                $arrTree[$cnt]['type'] = "_parent";
1854                            } else {
1855                                $arrTree[$cnt]['type'] = "_child";
1856                            }
1857
1858                            // 階層を割り出す
1859                            $arrCnt = split('/', $path);
1860                            $rank = count($arrCnt);
1861                            $arrTree[$cnt]['rank'] = $rank - $default_rank + 1;
1862                            $arrTree[$cnt]['count'] = $cnt;
1863                            // フォルダが開いているか
1864                            $arrTree[$cnt]['open'] = lfIsFileOpen($path, $tree_status);
1865                            $cnt++;
1866                            // 下層ディレクトリ取得の為、再帰的に呼び出す
1867                            sfGetFileTreeSub($path, $default_rank, $cnt, $arrTree, $tree_status);
1868                        }
1869                    }
1870                }
1871            }
1872            closedir($handle);
1873        }
1874    }
1875
1876    /*
1877     * 関数名:sfDirChildExists()
1878     * 説明 :指定したディレクトリ配下にファイルがあるか
1879     * 引数1 :ディレクトリ
1880     */
1881    function sfDirChildExists($dir) {
1882        if(file_exists($dir)) {
1883            if (is_dir($dir)) {
1884                $handle = opendir($dir);
1885                while ($file = readdir($handle)) {
1886                    // 行末の/を取り除く
1887                    $dir = ereg_replace("/$", "", $dir);
1888                    $path = $dir."/".$file;
1889                    if ($file != '..' && $file != '.' && is_dir($path)) {
1890                        return true;
1891                    }
1892                }
1893            }
1894        }
1895
1896        return false;
1897    }
1898
1899    /*
1900     * 関数名:lfIsFileOpen()
1901     * 説明 :指定したファイルが前回開かれた状態にあったかチェック
1902     * 引数1 :ディレクトリ
1903     * 引数2 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1904     */
1905    function lfIsFileOpen($dir, $tree_status) {
1906        $arrTreeStatus = split('\|', $tree_status);
1907        if(in_array($dir, $arrTreeStatus)) {
1908            return true;
1909        }
1910
1911        return false;
1912    }
1913
1914    /*
1915     * 関数名:sfDownloadFile()
1916     * 引数1 :ファイルパス
1917     * 説明 :ファイルのダウンロード
1918     */
1919    function sfDownloadFile($file) {
1920         // ファイルの場合はダウンロードさせる
1921        Header("Content-disposition: attachment; filename=".basename($file));
1922        Header("Content-type: application/octet-stream; name=".basename($file));
1923        Header("Cache-Control: ");
1924        Header("Pragma: ");
1925        echo (sfReadFile($file));
1926    }
1927
1928    /*
1929     * 関数名:sfCreateFile()
1930     * 引数1 :ファイルパス
1931     * 引数2 :パーミッション
1932     * 説明 :ファイル作成
1933     */
1934    function sfCreateFile($file, $mode = "") {
1935        // 行末の/を取り除く
1936        if($mode != "") {
1937            $ret = @mkdir($file, $mode);
1938        } else {
1939            $ret = @mkdir($file);
1940        }
1941
1942        return $ret;
1943    }
1944
1945    /*
1946     * 関数名:sfReadFile()
1947     * 引数1 :ファイルパス
1948     * 説明 :ファイル読込
1949     */
1950    function sfReadFile($filename) {
1951        $str = "";
1952        // バイナリモードでオープン
1953        $fp = @fopen($filename, "rb" );
1954        //ファイル内容を全て変数に読み込む
1955        if($fp) {
1956            $str = @fread($fp, filesize($filename)+1);
1957        }
1958        @fclose($fp);
1959
1960        return $str;
1961    }
1962
1963   /**
1964     * CSV出力用データ取得
1965     *
1966     * @return string
1967     */
1968    function getCSVData($array, $arrayIndex) {
1969        for ($i = 0; $i < count($array); $i++){
1970            // インデックスが設定されている場合
1971            if (is_array($arrayIndex) && 0 < count($arrayIndex)){
1972                for ($j = 0; $j < count($arrayIndex); $j++ ){
1973                    if ( $j > 0 ) $return .= ",";
1974                    $return .= "\"";
1975                    $return .= mb_ereg_replace("<","<",mb_ereg_replace( "\"","\"\"",$array[$i][$arrayIndex[$j]] )) ."\"";
1976                }
1977            } else {
1978                for ($j = 0; $j < count($array[$i]); $j++ ){
1979                    if ( $j > 0 ) $return .= ",";
1980                    $return .= "\"";
1981                    $return .= mb_ereg_replace("<","<",mb_ereg_replace( "\"","\"\"",$array[$i][$j] )) ."\"";
1982                }
1983            }
1984            $return .= "\n";
1985        }
1986        return $return;
1987    }
1988
1989   /**
1990     * 配列をテーブルタグで出力する。
1991     *
1992     * @return string
1993     */
1994    function getTableTag($array) {
1995        $html = "<table>";
1996        $html.= "<tr>";
1997        foreach($array[0] as $key => $val) {
1998            $html.="<th>$key</th>";
1999        }
2000        $html.= "</tr>";
2001
2002        $cnt = count($array);
2003
2004        for($i = 0; $i < $cnt; $i++) {
2005            $html.= "<tr>";
2006            foreach($array[$i] as $val) {
2007                $html.="<td>$val</td>";
2008            }
2009            $html.= "</tr>";
2010        }
2011        return $html;
2012    }
2013
2014   /**
2015     * 一覧-メイン画像のファイル指定がない場合、専用の画像ファイルに書き換える。
2016     *
2017     * @param string &$filename ファイル名
2018     * @return string
2019     */
2020    function sfNoImageMainList($filename = '') {
2021        if (strlen($filename) == 0 || substr($filename, -1, 1) == '/') {
2022            $filename .= 'noimage_main_list.jpg';
2023        }
2024        return $filename;
2025    }
2026
2027   /**
2028     * 詳細-メイン画像のファイル指定がない場合、専用の画像ファイルに書き換える。
2029     *
2030     * @param string &$filename ファイル名
2031     * @return string
2032     */
2033    function sfNoImageMain($filename = '') {
2034        if (strlen($filename) == 0 || substr($filename, -1, 1) == '/') {
2035            $filename .= 'noimage_main.png';
2036        }
2037        return $filename;
2038    }
2039
2040    /* デバッグ用 ------------------------------------------------------------------------------------------------*/
2041    function sfPrintR($obj) {
2042        print("<div style='font-size: 12px;color: #00FF00;'>\n");
2043        print("<strong>**デバッグ中**</strong><br />\n");
2044        print("<pre>\n");
2045        //print_r($obj);
2046        var_dump($obj);
2047        print("</pre>\n");
2048        print("<strong>**デバッグ中**</strong></div>\n");
2049    }
2050
2051    /**
2052     * ポイント使用するかの判定
2053     *
2054     * @param integer $status 対応状況
2055     * @return boolean 使用するか(顧客テーブルから減算するか)
2056     */
2057    function sfIsUsePoint($status) {
2058        switch ($status) {
2059            case ORDER_CANCEL:      // キャンセル
2060                return false;
2061            default:
2062                break;
2063        }
2064
2065        return true;
2066    }
2067
2068    /**
2069     * ポイント加算するかの判定
2070     *
2071     * @param integer $status 対応状況
2072     * @return boolean 加算するか
2073     */
2074    function sfIsAddPoint($status) {
2075        switch ($status) {
2076            case ORDER_NEW:         // 新規注文
2077            case ORDER_PAY_WAIT:    // 入金待ち
2078            case ORDER_PRE_END:     // 入金済み
2079            case ORDER_CANCEL:      // キャンセル
2080            case ORDER_BACK_ORDER:  // 取り寄せ中
2081                return false;
2082           
2083            case ORDER_DELIV:       // 発送済み
2084                return true;
2085           
2086            default:
2087                break;
2088        }
2089
2090        return false;
2091    }
2092
2093    /**
2094     * ランダムな文字列を取得する
2095     *
2096     * @param integer $length 文字数
2097     * @return string ランダムな文字列
2098     */
2099    function sfGetRandomString($length = 1) {
2100        require_once(dirname(__FILE__) . '/../../module/Text/Password.php');
2101        return Text_Password::create($length);
2102    }
2103   
2104    /**
2105     * 現在の URL を取得する
2106     *
2107     * @return string 現在のURL
2108     */
2109    function sfGetUrl() {
2110        $url = '';
2111       
2112        if (SC_Utils_Ex::sfIsHTTPS()) {
2113            $url = "https://";
2114        } else {
2115            $url = "http://";
2116        }
2117       
2118        $url .= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?' . $_SERVER['QUERY_STRING'];
2119       
2120        return $url;
2121    }
2122   
2123    /**
2124     * バックトレースをテキスト形式で出力する
2125     *
2126     * @return string テキストで表現したバックトレース
2127     */
2128    function sfBacktraceToString($arrBacktrace) {
2129        $string = '';
2130       
2131        foreach (array_reverse($arrBacktrace) as $backtrace) {
2132            if (strlen($backtrace['class']) >= 1) {
2133                $func = $backtrace['class'] . $backtrace['type'] . $backtrace['function'];
2134            } else {
2135                $func = $backtrace['function'];
2136            }
2137           
2138            $string .= $backtrace['file'] . " " . $backtrace['line'] . ":" . $func . "\n";
2139        }
2140       
2141        return $string;
2142    }
2143
2144    /**
2145     * 管理機能かを判定
2146     *
2147     * @return bool 管理機能か
2148     */
2149    function sfIsAdminFunction() {
2150        return defined('ADMIN_FUNCTION') && ADMIN_FUNCTION;
2151    }
2152
2153    /**
2154     * フロント機能かを判定
2155     *
2156     * @return bool フロント機能か
2157     */
2158    function sfIsFrontFunction() {
2159        return SC_Utils_Ex::sfIsPcSite() || SC_Utils_Ex::sfIsMobileSite();
2160    }
2161
2162    /**
2163     * フロント機能PCサイトかを判定
2164     *
2165     * @return bool フロント機能PCサイトか
2166     */
2167    function sfIsPcSite() {
2168        return defined('FRONT_FUNCTION_PC_SITE') && FRONT_FUNCTION_PC_SITE;
2169    }
2170
2171    /**
2172     * フロント機能モバイル機能かを判定
2173     *
2174     * @return bool フロント機能モバイル機能か
2175     */
2176    function sfIsMobileSite() {
2177        return defined('MOBILE_SITE') && MOBILE_SITE;
2178    }
2179
2180    /**
2181     * インストール機能かを判定
2182     *
2183     * @return bool インストール機能か
2184     */
2185    function sfIsInstallFunction() {
2186        return defined('INSTALL_FUNCTION') && INSTALL_FUNCTION;
2187    }
2188
2189    // 郵便番号から住所の取得
2190    function sfGetAddress($zipcode) {
2191
2192        $objQuery = new SC_Query(ZIP_DSN);
2193
2194        $masterData = new SC_DB_MasterData_Ex();
2195        $arrPref = $masterData->getMasterData("mtb_pref", array("pref_id", "pref_name", "rank"));
2196        // インデックスと値を反転させる。
2197        $arrREV_PREF = array_flip($arrPref);
2198
2199        // 郵便番号検索文作成
2200        $zipcode = mb_convert_kana($zipcode ,"n");
2201        $sqlse = "SELECT state, city, town FROM mtb_zip WHERE zipcode = ?";
2202
2203        $data_list = $objQuery->getAll($sqlse, array($zipcode));
2204        if (empty($data_list)) return array();
2205
2206        /*
2207         総務省からダウンロードしたデータをそのままインポートすると
2208         以下のような文字列が入っているので 対策する。
2209         ・(1・19丁目)
2210         ・以下に掲載がない場合
2211        */
2212        $town =  $data_list[0]['town'];
2213        $town = ereg_replace("(.*)$","",$town);
2214        $town = ereg_replace("以下に掲載がない場合","",$town);
2215        $data_list[0]['town'] = $town;
2216        $data_list[0]['state'] = $arrREV_PREF[$data_list[0]['state']];
2217
2218        return $data_list;
2219    }
2220
2221    /**
2222     * プラグインが配置されているディレクトリ(フルパス)を取得する
2223     *
2224     * @param string $file プラグイン情報ファイル(info.php)のパス
2225     * @return SimpleXMLElement プラグイン XML
2226     */
2227    function sfGetPluginFullPathByRequireFilePath($file) {
2228        return str_replace('\\', '/', dirname($file)) . '/';
2229    }
2230
2231    /**
2232     * プラグインのパスを取得する
2233     *
2234     * @param string $pluginFullPath プラグインが配置されているディレクトリ(フルパス)
2235     * @return SimpleXMLElement プラグイン XML
2236     */
2237    function sfGetPluginPathByPluginFullPath($pluginFullPath) {
2238        return basename(rtrim($pluginFullPath, '/'));
2239    }
2240
2241    /**
2242     * プラグイン情報配列の基本形を作成する
2243     *
2244     * @param string $file プラグイン情報ファイル(info.php)のパス
2245     * @return array プラグイン情報配列
2246     */
2247    function sfMakePluginInfoArray($file) {
2248        $fullPath = SC_Utils_Ex::sfGetPluginFullPathByRequireFilePath($file);
2249
2250        return
2251            array(
2252                // パス
2253                'path' => SC_Utils_Ex::sfGetPluginPathByPluginFullPath($fullPath),
2254                // プラグイン名
2255                'name' => '未定義',
2256                // フルパス
2257                'fullpath' => $fullPath,
2258                // バージョン
2259                'version' => null,
2260                // 著作者
2261                'auther' => '未定義',
2262            )
2263        ;
2264    }
2265
2266    /**
2267     * プラグイン情報配列を取得する
2268     *
2269     * TODO include_once を利用することで例外対応をサボタージュしているのを改善する。
2270     *
2271     * @param string $path プラグインのディレクトリ名
2272     * @return array プラグイン情報配列
2273     */
2274    function sfGetPluginInfoArray($path) {
2275        return (array)include_once(PLUGIN_PATH . "$path/plugin_info.php");
2276    }
2277
2278    /**
2279     * プラグイン XML を読み込む
2280     *
2281     * TODO 空だったときを考慮
2282     *
2283     * @return SimpleXMLElement プラグイン XML
2284     */
2285    function sfGetPluginsXml() {
2286        return simplexml_load_file(PLUGIN_PATH . 'plugins.xml');
2287    }
2288
2289    /**
2290     * プラグイン XML を書き込む
2291     *
2292     * @param SimpleXMLElement $pluginsXml プラグイン XML
2293     * @return integer ファイルに書き込まれたバイト数を返します。
2294     */
2295    function sfPutPluginsXml($pluginsXml) {
2296        if (!($pluginsXml instanceof SimpleXMLElement)) SC_Utils_Ex::sfDispException();
2297
2298        $xml = $pluginsXml->asXML();
2299        if (strlen($xml) == 0) SC_Utils_Ex::sfDispException();
2300
2301        $return = file_put_contents(PLUGIN_PATH . 'plugins.xml', $pluginsXml->asXML());
2302        if ($return === false) SC_Utils_Ex::sfDispException();
2303
2304        return $return;
2305    }
2306
2307    function sfLoadPluginInfo($filenamePluginInfo) {
2308        return (array)include_once $filenamePluginInfo;
2309    }
2310
2311    /**
2312     * 現在の Unix タイムスタンプを float (秒単位) でマイクロ秒まで返す
2313     *
2314     * PHP4の上位互換用途。
2315     * FIXME PHP4でテストする。(現状全くテストしていない。)
2316     * @param SimpleXMLElement $pluginsXml プラグイン XML
2317     * @return integer ファイルに書き込まれたバイト数を返します。
2318     */
2319    function sfMicrotimeFloat() {
2320        $microtime = microtime(true);
2321        if (is_string($microtime)) {
2322            list($usec, $sec) = explode(" ", microtime());
2323            return ((float)$usec + (float)$sec);
2324        }
2325        return $microtime;
2326    }
2327
2328    /**
2329     * 変数が空白かどうかをチェックする.
2330     *
2331     * 引数 $val が空白かどうかをチェックする. 空白の場合は true.
2332     * 以下の文字は空白と判断する.
2333     * - " " (ASCII 32 (0x20)), 通常の空白
2334     * - "\t" (ASCII 9 (0x09)), タブ
2335     * - "\n" (ASCII 10 (0x0A)), リターン
2336     * - "\r" (ASCII 13 (0x0D)), 改行
2337     * - "\0" (ASCII 0 (0x00)), NULバイト
2338     * - "\x0B" (ASCII 11 (0x0B)), 垂直タブ
2339     *
2340     * 引数 $val が配列の場合は, 空の配列の場合 true を返す.
2341     *
2342     * 引数 $greedy が true の場合は, 全角スペース, ネストした空の配列も
2343     * 空白と判断する.
2344     *
2345     * @param mixed $val チェック対象の変数
2346     * @param boolean $greedy "貧欲"にチェックを行う場合 true
2347     * @return boolean $val が空白と判断された場合 true
2348     */
2349    function isBlank($val, $greedy = true) {
2350        if (is_array($val)) {
2351            if ($greedy) {
2352                foreach ($val as $in) {
2353                    if (!SC_Utils::isBlank($in, $greedy)) {
2354                        return false;
2355                    }
2356                }
2357            } else {
2358                return empty($val);
2359            }
2360        }
2361
2362        if ($greedy) {
2363            $val = preg_replace("/ /", "", $val);
2364        }
2365
2366        $val = trim($val);
2367        if (strlen($val) > 0) {
2368            return false;
2369        }
2370        return true;
2371    }
2372}
2373?>
Note: See TracBrowser for help on using the repository browser.