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

Revision 18871, 74.3 KB checked in by nanasess, 16 years ago (diff)

決済フローの改善(#844)

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