source: branches/version-2_11-dev/data/class/util/SC_Utils.php @ 20847

Revision 20847, 71.8 KB checked in by nanasess, 13 years ago (diff)

#972 (リファクタリング開発:[管理画面]デザイン管理)

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