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

Revision 18820, 75.1 KB checked in by nanasess, 14 years ago (diff)

#781(規格のデータベースを木構造に)

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