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

Revision 20437, 74.4 KB checked in by nanasess, 13 years ago (diff)

#793 (非推奨機能の削除)

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