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

Revision 18856, 74.1 KB checked in by Seasoft, 14 years ago (diff)

#628(未使用処理・定義などの削除)

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