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

Revision 20541, 74.1 KB checked in by Seasoft, 13 years ago (diff)

#627(ソース整形・ソースコメントの改善)

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