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

Revision 19675, 74.0 KB checked in by nanasess, 16 years ago (diff)
  • PHP4対応(#854)
    • MDB2 の PostgreSQL 用ドライバを修正したため, パッチを添付
  • r19661 で発生した typo 修正
  • 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 = ""){
397echo "sfGetCSVData()に移行してね。";
398exit;
399
400        if($prefix == "") {
401            $dir_name = SC_Utils::sfUpDirName();
402            $file_name = $dir_name . date("ymdHis") .".csv";
403        } else {
404            $file_name = $prefix . date("ymdHis") .".csv";
405        }
406
407        /* HTTPヘッダの出力 */
408        Header("Content-disposition: attachment; filename=${file_name}");
409        Header("Content-type: application/octet-stream; name=${file_name}");
410        Header("Cache-Control: ");
411        Header("Pragma: ");
412
413        if (mb_internal_encoding() == CHAR_CODE){
414            $data = mb_convert_encoding($data,'SJIS-Win',CHAR_CODE);
415        }
416
417        /* データを出力 */
418        echo $data;
419    }
420
421    function sfGetCSVData($data, $prefix = ""){
422        if($prefix == "") {
423            $dir_name = SC_Utils::sfUpDirName();
424            $file_name = $dir_name . date("ymdHis") .".csv";
425        } else {
426            $file_name = $prefix . date("ymdHis") .".csv";
427        }
428
429        if (mb_internal_encoding() == CHAR_CODE){
430            $data = mb_convert_encoding($data,'SJIS-Win',CHAR_CODE);
431        }
432
433        /* データを出力 */
434        return array($file_name, $data);
435    }
436
437    /* 1階層上のディレクトリ名を取得する */
438    function sfUpDirName() {
439        $path = $_SERVER['PHP_SELF'];
440        $arrVal = split("/", $path);
441        $cnt = count($arrVal);
442        return $arrVal[($cnt - 2)];
443    }
444
445
446
447
448    /**
449     * 現在のサイトを更新(ただしポストは行わない)
450     *
451     * @deprecated LC_Page::reload() を使用して下さい.
452     */
453    function sfReload($get = "") {
454        if ($_SERVER["SERVER_PORT"] == "443" ){
455            $url = ereg_replace(URL_DIR . "$", "", SSL_URL);
456        } else {
457            $url = ereg_replace(URL_DIR . "$", "", SITE_URL);
458        }
459
460        if($get != "") {
461            header("Location: ". $url . $_SERVER['PHP_SELF'] . "?" . $get);
462        } else {
463            header("Location: ". $url . $_SERVER['PHP_SELF']);
464        }
465        exit;
466    }
467
468    // チェックボックスの値をマージ
469    function sfMergeCBValue($keyname, $max) {
470        $conv = "";
471        $cnt = 1;
472        for($cnt = 1; $cnt <= $max; $cnt++) {
473            if ($_POST[$keyname . $cnt] == "1") {
474                $conv.= "1";
475            } else {
476                $conv.= "0";
477            }
478        }
479        return $conv;
480    }
481
482    // html_checkboxesの値をマージして2進数形式に変更する。
483    function sfMergeCheckBoxes($array, $max) {
484        $ret = "";
485        if(is_array($array)) {
486            foreach($array as $val) {
487                $arrTmp[$val] = "1";
488            }
489        }
490        for($i = 1; $i <= $max; $i++) {
491            if(isset($arrTmp[$i]) && $arrTmp[$i] == "1") {
492                $ret.= "1";
493            } else {
494                $ret.= "0";
495            }
496        }
497        return $ret;
498    }
499
500
501    // html_checkboxesの値をマージして「-」でつなげる。
502    function sfMergeParamCheckBoxes($array) {
503        $ret = '';
504        if(is_array($array)) {
505            foreach($array as $val) {
506                if($ret != "") {
507                    $ret.= "-$val";
508                } else {
509                    $ret = $val;
510                }
511            }
512        } else {
513            $ret = $array;
514        }
515        return $ret;
516    }
517
518    // html_checkboxesの値をマージしてSQL検索用に変更する。
519    function sfSearchCheckBoxes($array) {
520        $max = max($array);
521        $ret = '';
522        for ($i = 1; $i <= $max; $i++) {
523            $ret .= in_array($i, $array) ? '1' : '_';
524        }
525        if (strlen($ret) != 0) {
526            $ret .= '%';
527        }
528        return $ret;
529    }
530
531    // 2進数形式の値をhtml_checkboxes対応の値に切り替える
532    function sfSplitCheckBoxes($val) {
533        $arrRet = array();
534        $len = strlen($val);
535        for($i = 0; $i < $len; $i++) {
536            if(substr($val, $i, 1) == "1") {
537                $arrRet[] = ($i + 1);
538            }
539        }
540        return $arrRet;
541    }
542
543    // チェックボックスの値をマージ
544    function sfMergeCBSearchValue($keyname, $max) {
545        $conv = "";
546        $cnt = 1;
547        for($cnt = 1; $cnt <= $max; $cnt++) {
548            if ($_POST[$keyname . $cnt] == "1") {
549                $conv.= "1";
550            } else {
551                $conv.= "_";
552            }
553        }
554        return $conv;
555    }
556
557    // チェックボックスの値を分解
558    function sfSplitCBValue($val, $keyname = "") {
559        $arr = array();
560        $len = strlen($val);
561        $no = 1;
562        for ($cnt = 0; $cnt < $len; $cnt++) {
563            if($keyname != "") {
564                $arr[$keyname . $no] = substr($val, $cnt, 1);
565            } else {
566                $arr[] = substr($val, $cnt, 1);
567            }
568            $no++;
569        }
570        return $arr;
571    }
572
573    // キーと値をセットした配列を取得
574    function sfArrKeyValue($arrList, $keyname, $valname, $len_max = "", $keysize = "") {
575        $arrRet = array();
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(!isset($arrRet[$key])) {
591                $arrRet[$key] = $val;
592            }
593
594        }
595        return $arrRet;
596    }
597
598    // キーと値をセットした配列を取得(値が複数の場合)
599    function sfArrKeyValues($arrList, $keyname, $valname, $len_max = "", $keysize = "", $connect = "") {
600
601        $max = count($arrList);
602
603        if($len_max != "" && $max > $len_max) {
604            $max = $len_max;
605        }
606
607        for($cnt = 0; $cnt < $max; $cnt++) {
608            if($keysize != "") {
609                $key = SC_Utils::sfCutString($arrList[$cnt][$keyname], $keysize);
610            } else {
611                $key = $arrList[$cnt][$keyname];
612            }
613            $val = $arrList[$cnt][$valname];
614
615            if($connect != "") {
616                $arrRet[$key].= "$val".$connect;
617            } else {
618                $arrRet[$key][] = $val;
619            }
620        }
621        return $arrRet;
622    }
623
624    // 配列の値をカンマ区切りで返す。
625    function sfGetCommaList($array, $space=true, $arrPop = array()) {
626        if (count($array) > 0) {
627            $line = "";
628            foreach($array as $val) {
629                if (!in_array($val, $arrPop)) {
630                    if ($space) {
631                        $line .= $val . ", ";
632                    } else {
633                        $line .= $val . ",";
634                    }
635                }
636            }
637            if ($space) {
638                $line = ereg_replace(", $", "", $line);
639            } else {
640                $line = ereg_replace(",$", "", $line);
641            }
642            return $line;
643        } else {
644            return false;
645        }
646
647    }
648
649    /* 配列の要素をCSVフォーマットで出力する。*/
650    function sfGetCSVList($array) {
651        $line = "";
652        if (count($array) > 0) {
653            foreach($array as $key => $val) {
654                $val = mb_convert_encoding($val, CHAR_CODE, CHAR_CODE);
655                $line .= "\"".$val."\",";
656            }
657            $line = ereg_replace(",$", "\r\n", $line);
658        }else{
659            return false;
660        }
661        return $line;
662    }
663
664    /* 配列の要素をPDFフォーマットで出力する。*/
665    function sfGetPDFList($array) {
666        foreach($array as $key => $val) {
667            $line .= "\t".$val;
668        }
669        $line.="\n";
670        return $line;
671    }
672
673
674
675    /*-----------------------------------------------------------------*/
676    /*    check_set_term
677    /*    年月日に別れた2つの期間の妥当性をチェックし、整合性と期間を返す
678    /* 引数 (開始年,開始月,開始日,終了年,終了月,終了日)
679    /* 戻値 array(1,2,3)
680    /*          1.開始年月日 (YYYY/MM/DD 000000)
681    /*            2.終了年月日 (YYYY/MM/DD 235959)
682    /*            3.エラー ( 0 = OK, 1 = NG )
683    /*-----------------------------------------------------------------*/
684    function sfCheckSetTerm ( $start_year, $start_month, $start_day, $end_year, $end_month, $end_day ) {
685
686        // 期間指定
687        $error = 0;
688        if ( $start_month || $start_day || $start_year){
689            if ( ! checkdate($start_month, $start_day , $start_year) ) $error = 1;
690        } else {
691            $error = 1;
692        }
693        if ( $end_month || $end_day || $end_year){
694            if ( ! checkdate($end_month ,$end_day ,$end_year) ) $error = 2;
695        }
696        if ( ! $error ){
697            $date1 = $start_year ."/".sprintf("%02d",$start_month) ."/".sprintf("%02d",$start_day) ." 000000";
698            $date2 = $end_year   ."/".sprintf("%02d",$end_month)   ."/".sprintf("%02d",$end_day)   ." 235959";
699            if ($date1 > $date2) $error = 3;
700        } else {
701            $error = 1;
702        }
703        return array($date1, $date2, $error);
704    }
705
706    // エラー箇所の背景色を変更するためのfunction SC_Viewで読み込む
707    function sfSetErrorStyle(){
708        return 'style="background-color:'.ERR_COLOR.'"';
709    }
710
711    /* DBに渡す数値のチェック
712     * 10桁以上はオーバーフローエラーを起こすので。
713     */
714    function sfCheckNumLength( $value ){
715        if ( ! is_numeric($value)  ){
716            return false;
717        }
718
719        if ( strlen($value) > 9 ) {
720            return false;
721        }
722
723        return true;
724    }
725
726    // 一致した値のキー名を取得
727    function sfSearchKey($array, $word, $default) {
728        foreach($array as $key => $val) {
729            if($val == $word) {
730                return $key;
731            }
732        }
733        return $default;
734    }
735
736    function sfGetErrorColor($val) {
737        if($val != "") {
738            return "background-color:" . ERR_COLOR;
739        }
740        return "";
741    }
742
743    function sfGetEnabled($val) {
744        if( ! $val ) {
745            return " disabled=\"disabled\"";
746        }
747        return "";
748    }
749
750    function sfGetChecked($param, $value) {
751        if ((string)$param === (string)$value) {
752            return "checked=\"checked\"";
753        }
754        return "";
755    }
756
757    function sfTrim($str) {
758        $ret = mb_ereg_replace("^[  \n\r]*", "", $str);
759        $ret = mb_ereg_replace("[  \n\r]*$", "", $ret);
760        return $ret;
761    }
762
763    /**
764     * 税金額を返す
765     *
766     * ・店舗基本情報に基づいた計算は SC_Helper_DB::sfTax() を使用する
767     *
768     * @param integer $price 計算対象の金額
769     * @param integer $tax 税率(%単位)
770     *     XXX integer のみか不明
771     * @param integer $tax_rule 端数処理
772     * @return integer 税金額
773     */
774    function sfTax($price, $tax, $tax_rule) {
775        $real_tax = $tax / 100;
776        $ret = $price * $real_tax;
777        switch($tax_rule) {
778        // 四捨五入
779        case 1:
780            $ret = round($ret);
781            break;
782        // 切り捨て
783        case 2:
784            $ret = floor($ret);
785            break;
786        // 切り上げ
787        case 3:
788            $ret = ceil($ret);
789            break;
790        // デフォルト:切り上げ
791        default:
792            $ret = ceil($ret);
793            break;
794        }
795        return $ret;
796    }
797
798    /**
799     * 税金付与した金額を返す
800     *
801     * ・店舗基本情報に基づいた計算は SC_Helper_DB::sfTax() を使用する
802     *
803     * @param integer $price 計算対象の金額
804     * @param integer $tax 税率(%単位)
805     *     XXX integer のみか不明
806     * @param integer $tax_rule 端数処理
807     * @return integer 税金付与した金額
808     */
809    function sfPreTax($price, $tax, $tax_rule) {
810        return $price + SC_Utils_Ex::sfTax($price, $tax, $tax_rule);
811    }
812
813    // 桁数を指定して四捨五入
814    function sfRound($value, $pow = 0){
815        $adjust = pow(10 ,$pow-1);
816
817        // 整数且つ0出なければ桁数指定を行う
818        if(SC_Utils::sfIsInt($adjust) and $pow > 1){
819            $ret = (round($value * $adjust)/$adjust);
820        }
821
822        $ret = round($ret);
823
824        return $ret;
825    }
826
827    /* ポイント付与 */
828    function sfPrePoint($price, $point_rate, $rule = POINT_RULE, $product_id = "") {
829        $real_point = $point_rate / 100;
830        $ret = $price * $real_point;
831        switch($rule) {
832        // 四捨五入
833        case 1:
834            $ret = round($ret);
835            break;
836        // 切り捨て
837        case 2:
838            $ret = floor($ret);
839            break;
840        // 切り上げ
841        case 3:
842            $ret = ceil($ret);
843            break;
844        // デフォルト:切り上げ
845        default:
846            $ret = ceil($ret);
847            break;
848        }
849        return $ret;
850    }
851
852    /* 規格分類の件数取得 */
853    function sfGetClassCatCount() {
854        $sql = "select count(dtb_class.class_id) as count, dtb_class.class_id ";
855        $sql.= "from dtb_class inner join dtb_classcategory on dtb_class.class_id = dtb_classcategory.class_id ";
856        $sql.= "where dtb_class.del_flg = 0 AND dtb_classcategory.del_flg = 0 ";
857        $sql.= "group by dtb_class.class_id, dtb_class.name";
858        $objQuery = new SC_Query();
859        $arrList = $objQuery->getAll($sql);
860        // キーと値をセットした配列を取得
861        $arrRet = SC_Utils::sfArrKeyValue($arrList, 'class_id', 'count');
862
863        return $arrRet;
864    }
865
866    function sfGetProductClassId($product_id, $classcategory_id1, $classcategory_id2) {
867        // $where = "product_id = ? AND classcategory_id1 = ? AND classcategory_id2 = ?";
868        $where = "product_id = ?";
869        $objQuery = new SC_Query();
870        // $ret = $objQuery->get("dtb_products_class", "product_class_id", $where, Array($product_id, $classcategory_id1, $classcategory_id2));
871        $ret = $objQuery->get("dtb_products_class", "product_class_id", $where, Array($product_id));
872        return $ret;
873    }
874
875    /* 文末の「/」をなくす */
876    function sfTrimURL($url) {
877        $ret = ereg_replace("[/]+$", "", $url);
878        return $ret;
879    }
880
881    /* DBから取り出した日付の文字列を調整する。*/
882    function sfDispDBDate($dbdate, $time = true) {
883        list($y, $m, $d, $H, $M) = split("[- :]", $dbdate);
884
885        if(strlen($y) > 0 && strlen($m) > 0 && strlen($d) > 0) {
886            if ($time) {
887                $str = sprintf("%04d/%02d/%02d %02d:%02d", $y, $m, $d, $H, $M);
888            } else {
889                $str = sprintf("%04d/%02d/%02d", $y, $m, $d, $H, $M);
890            }
891        } else {
892            $str = "";
893        }
894        return $str;
895    }
896
897    /* 配列をキー名ごとの配列に変更する */
898    function sfSwapArray($array, $isColumnName = true) {
899        $arrRet = array();
900        $max = count($array);
901        for($i = 0; $i < $max; $i++) {
902            $j = 0;
903            foreach($array[$i] as $key => $val) {
904                if ($isColumnName) {
905                    $arrRet[$key][] = $val;
906                } else {
907                    $arrRet[$j][] = $val;
908                }
909                $j++;
910            }
911        }
912        return $arrRet;
913    }
914
915    /**
916     * 連想配列から新たな配列を生成して返す.
917     *
918     * $requires が指定された場合, $requires に含まれるキーの値のみを返す.
919     *
920     * @param array 連想配列
921     * @param array 必須キーの配列
922     * @return array 連想配列の値のみの配列
923     */
924    function getHash2Array($hash, $requires = array()) {
925        $array = array();
926        $i = 0;
927        foreach ($hash as $key => $val) {
928            if (!empty($requires)) {
929                if (in_array($key, $requires)) {
930                    $array[$i] = $val;
931                    $i++;
932                }
933            } else {
934                $array[$i] = $val;
935                $i++;
936            }
937        }
938        return $array;
939    }
940
941    /* かけ算をする(Smarty用) */
942    function sfMultiply($num1, $num2) {
943        return ($num1 * $num2);
944    }
945
946    /**
947     * 加算ポイントの計算
948     *
949     * ・店舗基本情報に基づいた計算は SC_Helper_DB::sfGetAddPoint() を使用する
950     *
951     * @param integer $totalpoint
952     * @param integer $use_point
953     * @param integer $point_rate
954     * @return integer 加算ポイント
955     */
956    function sfGetAddPoint($totalpoint, $use_point, $point_rate) {
957        // 購入商品の合計ポイントから利用したポイントのポイント換算価値を引く方式
958        $add_point = $totalpoint - intval($use_point * ($point_rate / 100));
959
960        if($add_point < 0) {
961            $add_point = '0';
962        }
963        return $add_point;
964    }
965
966    /* 一意かつ予測されにくいID */
967    function sfGetUniqRandomId($head = "") {
968        // 予測されないようにランダム文字列を付与する。
969        $random = GC_Utils_Ex::gfMakePassword(8);
970        // 同一ホスト内で一意なIDを生成
971        $id = uniqid($head);
972        return ($id . $random);
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 (version_compare(PHP_VERSION, '5.0.0', '>')) {
2250           return;
2251        }
2252
2253        $xml = $pluginsXml->asXML();
2254        if (strlen($xml) == 0) SC_Utils_Ex::sfDispException();
2255
2256        $return = file_put_contents(PLUGIN_PATH . 'plugins.xml', $pluginsXml->asXML());
2257        if ($return === false) SC_Utils_Ex::sfDispException();
2258        return $return;
2259    }
2260
2261    function sfLoadPluginInfo($filenamePluginInfo) {
2262        return (array)include_once $filenamePluginInfo;
2263    }
2264
2265    /**
2266     * 現在の Unix タイムスタンプを float (秒単位) でマイクロ秒まで返す
2267     *
2268     * PHP4の上位互換用途。
2269     * FIXME PHP4でテストする。(現状全くテストしていない。)
2270     * @param SimpleXMLElement $pluginsXml プラグイン XML
2271     * @return integer ファイルに書き込まれたバイト数を返します。
2272     */
2273    function sfMicrotimeFloat() {
2274        $microtime = microtime(true);
2275        if (is_string($microtime)) {
2276            list($usec, $sec) = explode(" ", microtime());
2277            return ((float)$usec + (float)$sec);
2278        }
2279        return $microtime;
2280    }
2281
2282    /**
2283     * 変数が空白かどうかをチェックする.
2284     *
2285     * 引数 $val が空白かどうかをチェックする. 空白の場合は true.
2286     * 以下の文字は空白と判断する.
2287     * - " " (ASCII 32 (0x20)), 通常の空白
2288     * - "\t" (ASCII 9 (0x09)), タブ
2289     * - "\n" (ASCII 10 (0x0A)), リターン
2290     * - "\r" (ASCII 13 (0x0D)), 改行
2291     * - "\0" (ASCII 0 (0x00)), NULバイト
2292     * - "\x0B" (ASCII 11 (0x0B)), 垂直タブ
2293     *
2294     * 引数 $val が配列の場合は, 空の配列の場合 true を返す.
2295     *
2296     * 引数 $greedy が true の場合は, 全角スペース, ネストした空の配列も
2297     * 空白と判断する.
2298     *
2299     * @param mixed $val チェック対象の変数
2300     * @param boolean $greedy "貧欲"にチェックを行う場合 true
2301     * @return boolean $val が空白と判断された場合 true
2302     */
2303    function isBlank($val, $greedy = true) {
2304        if (is_array($val)) {
2305            if ($greedy) {
2306                foreach ($val as $in) {
2307                    if (!SC_Utils::isBlank($in, $greedy)) {
2308                        return false;
2309                    }
2310                }
2311            } else {
2312                return empty($val);
2313            }
2314        }
2315
2316        if ($greedy) {
2317            $val = preg_replace("/ /", "", $val);
2318        }
2319
2320        $val = trim($val);
2321        if (strlen($val) > 0) {
2322            return false;
2323        }
2324        return true;
2325    }
2326}
2327?>
Note: See TracBrowser for help on using the repository browser.