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

Revision 21010, 71.3 KB checked in by Seasoft, 13 years ago (diff)

#1373 (require_safe.php で設定している HTML_REALDIR が誤っている)

  • require.php に依存させる事で解決。

#1392 (モバイルサイトの判別に SC_Display_Ex#detectDevice を使う)
#1393 (require_safe.php で絵文字変換 (除去) フィルターの組み込み条件が誤っている)

  • require.php に依存させる事で解決。
  • 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 = SC_Display_Ex::detectDevice() == DEVICE_TYPE_MOBILE;
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        foreach($array as $key1 => $arr1) {
774            $index = 0;
775            foreach($arr1 as $key2 => $val) {
776                if ($isColumnName) {
777                    $arrRet[$key2][$key1] = $val;
778                } else {
779                    $arrRet[$index++][$key1] = $val;
780                }
781            }
782        }
783        return $arrRet;
784    }
785
786    /**
787     * 連想配列から新たな配列を生成して返す.
788     *
789     * $requires が指定された場合, $requires に含まれるキーの値のみを返す.
790     *
791     * @param array 連想配列
792     * @param array 必須キーの配列
793     * @return array 連想配列の値のみの配列
794     */
795    function getHash2Array($hash, $requires = array()) {
796        $array = array();
797        $i = 0;
798        foreach ($hash as $key => $val) {
799            if (!empty($requires)) {
800                if (in_array($key, $requires)) {
801                    $array[$i] = $val;
802                    $i++;
803                }
804            } else {
805                $array[$i] = $val;
806                $i++;
807            }
808        }
809        return $array;
810    }
811
812    /* かけ算をする(Smarty用) */
813    function sfMultiply($num1, $num2) {
814        return $num1 * $num2;
815    }
816
817    /**
818     * 加算ポイントの計算
819     *
820     * ・店舗基本情報に基づいた計算は SC_Helper_DB::sfGetAddPoint() を使用する
821     *
822     * @param integer $totalpoint
823     * @param integer $use_point
824     * @param integer $point_rate
825     * @return integer 加算ポイント
826     */
827    function sfGetAddPoint($totalpoint, $use_point, $point_rate) {
828        // 購入商品の合計ポイントから利用したポイントのポイント換算価値を引く方式
829        $add_point = $totalpoint - intval($use_point * ($point_rate / 100));
830
831        if($add_point < 0) {
832            $add_point = '0';
833        }
834        return $add_point;
835    }
836
837    /* 一意かつ予測されにくいID */
838    function sfGetUniqRandomId($head = "") {
839        // 予測されないようにランダム文字列を付与する。
840        $random = GC_Utils_Ex::gfMakePassword(8);
841        // 同一ホスト内で一意なIDを生成
842        $id = uniqid($head);
843        return $id . $random;
844    }
845
846    /* 文字列に強制的に改行を入れる */
847    function sfPutBR($str, $size) {
848        $i = 0;
849        $cnt = 0;
850        $line = array();
851        $ret = "";
852
853        while($str[$i] != "") {
854            $line[$cnt].=$str[$i];
855            $i++;
856            if(strlen($line[$cnt]) > $size) {
857                $line[$cnt].="<br />";
858                $cnt++;
859            }
860        }
861
862        foreach($line as $val) {
863            $ret.=$val;
864        }
865        return $ret;
866    }
867
868    // 二回以上繰り返されているスラッシュ[/]を一つに変換する。
869    function sfRmDupSlash($istr){
870        if(ereg("^http://", $istr)) {
871            $str = substr($istr, 7);
872            $head = "http://";
873        } else if(ereg("^https://", $istr)) {
874            $str = substr($istr, 8);
875            $head = "https://";
876        } else {
877            $str = $istr;
878        }
879        $str = ereg_replace("[/]+", "/", $str);
880        $ret = $head . $str;
881        return $ret;
882    }
883
884    /**
885     * テキストファイルの文字エンコーディングを変換する.
886     *
887     * $filepath に存在するテキストファイルの文字エンコーディングを変換する.
888     * 変換前の文字エンコーディングは, mb_detect_order で設定した順序で自動検出する.
889     * 変換後は, 変換前のファイル名に「enc_」というプレフィクスを付与し,
890     * $out_dir で指定したディレクトリへ出力する
891     *
892     * TODO $filepath のファイルがバイナリだった場合の扱い
893     * TODO fwrite などでのエラーハンドリング
894     *
895     * @access public
896     * @param string $filepath 変換するテキストファイルのパス
897     * @param string $enc_type 変換後のファイルエンコーディングの種類を表す文字列
898     * @param string $out_dir 変換後のファイルを出力するディレクトリを表す文字列
899     * @return string 変換後のテキストファイルのパス
900     */
901    function sfEncodeFile($filepath, $enc_type, $out_dir) {
902        $ifp = fopen($filepath, 'r');
903
904        // 正常にファイルオープンした場合
905        if ($ifp !== false) {
906
907            $basename = basename($filepath);
908            $outpath = $out_dir . "enc_" . $basename;
909
910            $ofp = fopen($outpath, "w+");
911
912            while(!feof($ifp)) {
913                $line = fgets($ifp);
914                $line = mb_convert_encoding($line, $enc_type, 'auto');
915                fwrite($ofp,  $line);
916            }
917
918            fclose($ofp);
919            fclose($ifp);
920        }
921        // ファイルが開けなかった場合はエラーページを表示
922          else {
923              SC_Utils_Ex::sfDispError('');
924              exit;
925        }
926        return     $outpath;
927    }
928
929    function sfCutString($str, $len, $byte = true, $commadisp = true) {
930        if($byte) {
931            if(strlen($str) > ($len + 2)) {
932                $ret =substr($str, 0, $len);
933                $cut = substr($str, $len);
934            } else {
935                $ret = $str;
936                $commadisp = false;
937            }
938        } else {
939            if(mb_strlen($str) > ($len + 1)) {
940                $ret = mb_substr($str, 0, $len);
941                $cut = mb_substr($str, $len);
942            } else {
943                $ret = $str;
944                $commadisp = false;
945            }
946        }
947
948        // 絵文字タグの途中で分断されないようにする。
949        if (isset($cut)) {
950            // 分割位置より前の最後の [ 以降を取得する。
951            $head = strrchr($ret, '[');
952
953            // 分割位置より後の最初の ] 以前を取得する。
954            $tail_pos = strpos($cut, ']');
955            if ($tail_pos !== false) {
956                $tail = substr($cut, 0, $tail_pos + 1);
957            }
958
959            // 分割位置より前に [、後に ] が見つかった場合は、[ から ] までを
960            // 接続して絵文字タグ1個分になるかどうかをチェックする。
961            if ($head !== false && $tail_pos !== false) {
962                $subject = $head . $tail;
963                if (preg_match('/^\[emoji:e?\d+\]$/', $subject)) {
964                    // 絵文字タグが見つかったので削除する。
965                    $ret = substr($ret, 0, -strlen($head));
966                }
967            }
968        }
969
970        if($commadisp){
971            $ret = $ret . "...";
972        }
973        return $ret;
974    }
975
976    // 年、月、締め日から、先月の締め日+1、今月の締め日を求める。
977    function sfTermMonth($year, $month, $close_day) {
978        $end_year = $year;
979        $end_month = $month;
980
981        // 開始月が終了月と同じか否か
982        $same_month = false;
983
984        // 該当月の末日を求める。
985        $end_last_day = date('d', mktime(0, 0, 0, $month + 1, 0, $year));
986
987        // 月の末日が締め日より少ない場合
988        if($end_last_day < $close_day) {
989            // 締め日を月末日に合わせる
990            $end_day = $end_last_day;
991        } else {
992            $end_day = $close_day;
993        }
994
995        // 前月の取得
996        $tmp_year = date('Y', mktime(0, 0, 0, $month, 0, $year));
997        $tmp_month = date('m', mktime(0, 0, 0, $month, 0, $year));
998        // 前月の末日を求める。
999        $start_last_day = date('d', mktime(0, 0, 0, $month, 0, $year));
1000
1001        // 前月の末日が締め日より少ない場合
1002        if ($start_last_day < $close_day) {
1003            // 月末日に合わせる
1004            $tmp_day = $start_last_day;
1005        } else {
1006            $tmp_day = $close_day;
1007        }
1008
1009        // 先月の末日の翌日を取得する
1010        $start_year = date('Y', mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1011        $start_month = date('m', mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1012        $start_day = date('d', mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1013
1014        // 日付の作成
1015        $start_date = sprintf("%d/%d/%d 00:00:00", $start_year, $start_month, $start_day);
1016        $end_date = sprintf("%d/%d/%d 23:59:59", $end_year, $end_month, $end_day);
1017
1018        return array($start_date, $end_date);
1019    }
1020
1021    // 再帰的に多段配列を検索して一次元配列(Hidden引渡し用配列)に変換する。
1022    function sfMakeHiddenArray($arrSrc, $arrDst = array(), $parent_key = "") {
1023        if(is_array($arrSrc)) {
1024            foreach($arrSrc as $key => $val) {
1025                if($parent_key != "") {
1026                    $keyname = $parent_key . "[". $key . "]";
1027                } else {
1028                    $keyname = $key;
1029                }
1030                if(is_array($val)) {
1031                    $arrDst = SC_Utils_Ex::sfMakeHiddenArray($val, $arrDst, $keyname);
1032                } else {
1033                    $arrDst[$keyname] = $val;
1034                }
1035            }
1036        }
1037        return $arrDst;
1038    }
1039
1040    // DB取得日時をタイムに変換
1041    function sfDBDatetoTime($db_date) {
1042        $date = ereg_replace("\..*$","",$db_date);
1043        $time = strtotime($date);
1044        return $time;
1045    }
1046
1047    // PHPのmb_convert_encoding関数をSmartyでも使えるようにする
1048    function sfMbConvertEncoding($str, $encode = 'CHAR_CODE') {
1049        return  mb_convert_encoding($str, $encode);
1050    }
1051
1052    // 2つの配列を用いて連想配列を作成する
1053    function sfArrCombine($arrKeys, $arrValues) {
1054
1055        if(count($arrKeys) <= 0 and count($arrValues) <= 0) return array();
1056
1057        $keys = array_values($arrKeys);
1058        $vals = array_values($arrValues);
1059
1060        $max = max( count( $keys ), count( $vals ) );
1061        $combine_ary = array();
1062        for($i=0; $i<$max; $i++) {
1063            $combine_ary[$keys[$i]] = $vals[$i];
1064        }
1065        if(is_array($combine_ary)) return $combine_ary;
1066
1067        return false;
1068    }
1069
1070    /* 階層構造のテーブルから与えられたIDの兄弟を取得する */
1071    function sfGetBrothersArray($arrData, $pid_name, $id_name, $arrPID) {
1072        $max = count($arrData);
1073
1074        $arrBrothers = array();
1075        foreach($arrPID as $id) {
1076            // 親IDを検索する
1077            for($i = 0; $i < $max; $i++) {
1078                if($arrData[$i][$id_name] == $id) {
1079                    $parent = $arrData[$i][$pid_name];
1080                    break;
1081                }
1082            }
1083            // 兄弟IDを検索する
1084            for($i = 0; $i < $max; $i++) {
1085                if($arrData[$i][$pid_name] == $parent) {
1086                    $arrBrothers[] = $arrData[$i][$id_name];
1087                }
1088            }
1089        }
1090        return $arrBrothers;
1091    }
1092
1093    /* 階層構造のテーブルから与えられたIDの直属の子を取得する */
1094    function sfGetUnderChildrenArray($arrData, $pid_name, $id_name, $parent) {
1095        $max = count($arrData);
1096
1097        $arrChildren = array();
1098        // 子IDを検索する
1099        for($i = 0; $i < $max; $i++) {
1100            if($arrData[$i][$pid_name] == $parent) {
1101                $arrChildren[] = $arrData[$i][$id_name];
1102            }
1103        }
1104        return $arrChildren;
1105    }
1106
1107    /**
1108     * SQLシングルクォート対応
1109     * @deprecated SC_Query::quote() を使用すること
1110     */
1111    function sfQuoteSmart($in){
1112
1113        if (is_int($in) || is_double($in)) {
1114            return $in;
1115        } elseif (is_bool($in)) {
1116            return $in ? 1 : 0;
1117        } elseif (is_null($in)) {
1118            return 'NULL';
1119        } else {
1120            return "'" . str_replace("'", "''", $in) . "'";
1121        }
1122    }
1123
1124    // ディレクトリを再帰的に生成する
1125    function sfMakeDir($path) {
1126        static $count = 0;
1127        $count++;  // 無限ループ回避
1128        $dir = dirname($path);
1129        if(ereg("^[/]$", $dir) || ereg("^[A-Z]:[\\]$", $dir) || $count > 256) {
1130            // ルートディレクトリで終了
1131            return;
1132        } else {
1133            if(is_writable(dirname($dir))) {
1134                if(!file_exists($dir)) {
1135                    mkdir($dir);
1136                    GC_Utils_Ex::gfPrintLog("mkdir $dir");
1137                }
1138            } else {
1139                SC_Utils_Ex::sfMakeDir($dir);
1140                if(is_writable(dirname($dir))) {
1141                    if(!file_exists($dir)) {
1142                        mkdir($dir);
1143                        GC_Utils_Ex::gfPrintLog("mkdir $dir");
1144                    }
1145                }
1146           }
1147        }
1148        return;
1149    }
1150
1151    // ディレクトリ以下のファイルを再帰的にコピー
1152    function sfCopyDir($src, $des, $mess = "", $override = false){
1153        if(!is_dir($src)){
1154            return false;
1155        }
1156
1157        $oldmask = umask(0);
1158        $mod= stat($src);
1159
1160        // ディレクトリがなければ作成する
1161        if(!file_exists($des)) {
1162            if(!mkdir($des, $mod[2])) {
1163                echo 'path:' . $des;
1164            }
1165        }
1166
1167        $fileArray=glob( $src."*" );
1168        if (is_array($fileArray)) {
1169            foreach( $fileArray as $key => $data_ ){
1170                // CVS管理ファイルはコピーしない
1171                if(ereg("/CVS/Entries", $data_)) {
1172                    break;
1173                }
1174                if(ereg("/CVS/Repository", $data_)) {
1175                    break;
1176                }
1177                if(ereg("/CVS/Root", $data_)) {
1178                    break;
1179                }
1180
1181                mb_ereg("^(.*[\/])(.*)",$data_, $matches);
1182                $data=$matches[2];
1183                if( is_dir( $data_ ) ){
1184                    $mess = SC_Utils_Ex::sfCopyDir( $data_.'/', $des.$data.'/', $mess);
1185                }else{
1186                    if(!$override && file_exists($des.$data)) {
1187                        $mess.= $des.$data . ":ファイルが存在します\n";
1188                    } else {
1189                        if(@copy( $data_, $des.$data)) {
1190                            $mess.= $des.$data . ":コピー成功\n";
1191                        } else {
1192                            $mess.= $des.$data . ":コピー失敗\n";
1193                        }
1194                    }
1195                    $mod=stat($data_ );
1196                }
1197            }
1198        }
1199        umask($oldmask);
1200        return $mess;
1201    }
1202
1203    // 指定したフォルダ内のファイルを全て削除する
1204    function sfDelFile($dir){
1205        if(file_exists($dir)) {
1206            $dh = opendir($dir);
1207            // フォルダ内のファイルを削除
1208            while($file = readdir($dh)){
1209                if ($file == "." or $file == "..") continue;
1210                $del_file = $dir . "/" . $file;
1211                if(is_file($del_file)){
1212                    $ret = unlink($dir . "/" . $file);
1213                }else if (is_dir($del_file)){
1214                    $ret = SC_Utils_Ex::sfDelFile($del_file);
1215                }
1216
1217                if(!$ret){
1218                    return $ret;
1219                }
1220            }
1221
1222            // 閉じる
1223            closedir($dh);
1224
1225            // フォルダを削除
1226            return rmdir($dir);
1227        }
1228    }
1229
1230    /*
1231     * 関数名:sfWriteFile
1232     * 引数1 :書き込むデータ
1233     * 引数2 :ファイルパス
1234     * 引数3 :書き込みタイプ
1235     * 引数4 :パーミッション
1236     * 戻り値:結果フラグ 成功なら true 失敗なら false
1237     * 説明 :ファイル書き出し
1238     */
1239    function sfWriteFile($str, $path, $type, $permission = "") {
1240        //ファイルを開く
1241        if (!($file = fopen ($path, $type))) {
1242            return false;
1243        }
1244
1245        //ファイルロック
1246        flock ($file, LOCK_EX);
1247        //ファイルの書き込み
1248        fputs ($file, $str);
1249        //ファイルロックの解除
1250        flock ($file, LOCK_UN);
1251        //ファイルを閉じる
1252        fclose ($file);
1253        // 権限を指定
1254        if($permission != "") {
1255            chmod($path, $permission);
1256        }
1257
1258        return true;
1259    }
1260
1261    /**
1262     * ブラウザに強制的に送出する
1263     *
1264     * @param boolean|string $output 半角スペース256文字+改行を出力するか。または、送信する文字列を指定。
1265     * @return void
1266     */
1267    function sfFlush($output = false, $sleep = 0){
1268        // 出力をバッファリングしない(==日本語自動変換もしない)
1269        while (@ob_end_flush());
1270
1271        if ($output === true) {
1272            // IEのために半角スペース256文字+改行を出力
1273            //echo str_repeat(' ', 256) . "\n";
1274            echo str_pad('', 256) . "\n";
1275        } else if ($output !== false) {
1276            echo $output;
1277        }
1278
1279        // 出力をフラッシュする
1280        flush();
1281
1282        ob_start();
1283
1284        // 時間のかかる処理
1285        sleep($sleep);
1286    }
1287
1288    // @versionの記載があるファイルからバージョンを取得する。
1289    function sfGetFileVersion($path) {
1290        if(file_exists($path)) {
1291            $src_fp = fopen($path, 'rb');
1292            if($src_fp) {
1293                while (!feof($src_fp)) {
1294                    $line = fgets($src_fp);
1295                    if(ereg("@version", $line)) {
1296                        $arrLine = explode(" ", $line);
1297                        $version = $arrLine[5];
1298                    }
1299                }
1300                fclose($src_fp);
1301            }
1302        }
1303        return $version;
1304    }
1305
1306    // 指定したURLに対してPOSTでデータを送信する
1307    function sfSendPostData($url, $arrData, $arrOkCode = array()){
1308        require_once DATA_REALDIR . 'module/Request.php';
1309
1310        // 送信インスタンス生成
1311        $req = new HTTP_Request($url);
1312
1313        $req->addHeader('User-Agent', 'DoCoMo/2.0 P2101V(c100)');
1314        $req->setMethod(HTTP_REQUEST_METHOD_POST);
1315
1316        // POSTデータ送信
1317        $req->addPostDataArray($arrData);
1318
1319        // エラーが無ければ、応答情報を取得する
1320        if (!PEAR::isError($req->sendRequest())) {
1321
1322            // レスポンスコードがエラー判定なら、空を返す
1323            $res_code = $req->getResponseCode();
1324
1325            if(!in_array($res_code, $arrOkCode)){
1326                $response = "";
1327            }else{
1328                $response = $req->getResponseBody();
1329            }
1330
1331        } else {
1332            $response = "";
1333        }
1334
1335        // POSTデータクリア
1336        $req->clearPostData();
1337
1338        return $response;
1339    }
1340
1341    /**
1342     * $array の要素を $arrConvList で指定した方式で mb_convert_kana を適用する.
1343     *
1344     * @param array $array 変換する文字列の配列
1345     * @param array $arrConvList mb_convert_kana の適用ルール
1346     * @return array 変換後の配列
1347     * @see mb_convert_kana
1348     */
1349    function mbConvertKanaWithArray($array, $arrConvList) {
1350        foreach ($arrConvList as $key => $val) {
1351            if(isset($array[$key])) {
1352                $array[$key] = mb_convert_kana($array[$key] ,$val);
1353            }
1354        }
1355        return $array;
1356    }
1357
1358    /**
1359     * 配列の添字が未定義の場合は空文字を代入して定義する.
1360     *
1361     * @param array $array 添字をチェックする配列
1362     * @param array $defineIndexes チェックする添字
1363     * @return array 添字を定義した配列
1364     */
1365    function arrayDefineIndexes($array, $defineIndexes) {
1366        foreach ($defineIndexes as $key) {
1367            if (!isset($array[$key])) $array[$key] = "";
1368        }
1369        return $array;
1370    }
1371
1372    /**
1373     * $arrSrc のうち、キーが $arrKey に含まれるものを返す
1374     *
1375     * $arrSrc に含まない要素は返されない。
1376     *
1377     * @param array $arrSrc
1378     * @param array $arrKey
1379     * @return array
1380     */
1381    function sfArrayIntersectKeys($arrSrc, $arrKey) {
1382        $arrRet = array();
1383        foreach ($arrKey as $key) {
1384            if (isset($arrSrc[$key])) $arrRet[$key] = $arrSrc[$key];
1385        }
1386        return $arrRet;
1387    }
1388
1389    /**
1390     * XML宣言を出力する.
1391     *
1392     * XML宣言があると問題が発生する UA は出力しない.
1393     *
1394     * @return string XML宣言の文字列
1395     */
1396    function printXMLDeclaration() {
1397        $ua = $_SERVER['HTTP_USER_AGENT'];
1398        if (!preg_match("/MSIE/", $ua) || preg_match("/MSIE 7/", $ua)) {
1399            echo '<?xml version="1.0" encoding="' . CHAR_CODE . '"?>' . "\n";
1400        }
1401    }
1402
1403    /*
1404     * 関数名:sfGetFileList()
1405     * 説明 :指定パス配下のディレクトリ取得
1406     * 引数1 :取得するディレクトリパス
1407     */
1408    function sfGetFileList($dir) {
1409        $arrFileList = array();
1410        $arrDirList = array();
1411
1412        if (is_dir($dir)) {
1413            if ($dh = opendir($dir)) {
1414                $cnt = 0;
1415                // 行末の/を取り除く
1416                while (($file = readdir($dh)) !== false) $arrDir[] = $file;
1417                $dir = ereg_replace("/$", "", $dir);
1418                // アルファベットと数字でソート
1419                natcasesort($arrDir);
1420                foreach($arrDir as $file) {
1421                    // ./ と ../を除くファイルのみを取得
1422                    if($file != "." && $file != "..") {
1423
1424                        $path = $dir."/".$file;
1425                        // SELECT内の見た目を整えるため指定文字数で切る
1426                        $file_name = SC_Utils_Ex::sfCutString($file, FILE_NAME_LEN);
1427                        $file_size = SC_Utils_Ex::sfCutString(SC_Utils_Ex::sfGetDirSize($path), FILE_NAME_LEN);
1428                        $file_time = date("Y/m/d", filemtime($path));
1429
1430                        // ディレクトリとファイルで格納配列を変える
1431                        if(is_dir($path)) {
1432                            $arrDirList[$cnt]['file_name'] = $file;
1433                            $arrDirList[$cnt]['file_path'] = $path;
1434                            $arrDirList[$cnt]['file_size'] = $file_size;
1435                            $arrDirList[$cnt]['file_time'] = $file_time;
1436                            $arrDirList[$cnt]['is_dir'] = true;
1437                        } else {
1438                            $arrFileList[$cnt]['file_name'] = $file;
1439                            $arrFileList[$cnt]['file_path'] = $path;
1440                            $arrFileList[$cnt]['file_size'] = $file_size;
1441                            $arrFileList[$cnt]['file_time'] = $file_time;
1442                            $arrFileList[$cnt]['is_dir'] = false;
1443                        }
1444                        $cnt++;
1445                    }
1446                }
1447                closedir($dh);
1448            }
1449        }
1450
1451        // フォルダを先頭にしてマージ
1452        return array_merge($arrDirList, $arrFileList);
1453    }
1454
1455    /*
1456     * 関数名:sfGetDirSize()
1457     * 説明 :指定したディレクトリのバイト数を取得
1458     * 引数1 :ディレクトリ
1459     */
1460    function sfGetDirSize($dir) {
1461        if(file_exists($dir)) {
1462            // ディレクトリの場合下層ファイルの総量を取得
1463            if (is_dir($dir)) {
1464                $handle = opendir($dir);
1465                while ($file = readdir($handle)) {
1466                    // 行末の/を取り除く
1467                    $dir = ereg_replace("/$", "", $dir);
1468                    $path = $dir."/".$file;
1469                    if ($file != '..' && $file != '.' && !is_dir($path)) {
1470                        $bytes += filesize($path);
1471                    } else if (is_dir($path) && $file != '..' && $file != '.') {
1472                        // 下層ファイルのバイト数を取得する為、再帰的に呼び出す。
1473                        $bytes += SC_Utils_Ex::sfGetDirSize($path);
1474                    }
1475                }
1476            } else {
1477                // ファイルの場合
1478                $bytes = filesize($dir);
1479            }
1480        }
1481        // ディレクトリ(ファイル)が存在しない場合は0byteを返す
1482        if($bytes == "") $bytes = 0;
1483
1484        return $bytes;
1485    }
1486
1487    /*
1488     * 関数名:sfDeleteDir()
1489     * 説明 :指定したディレクトリを削除
1490     * 引数1 :削除ファイル
1491     */
1492    function sfDeleteDir($dir) {
1493        $arrResult = array();
1494        if(file_exists($dir)) {
1495            // ディレクトリかチェック
1496            if (is_dir($dir)) {
1497                if ($handle = opendir("$dir")) {
1498                    $cnt = 0;
1499                    while (false !== ($item = readdir($handle))) {
1500                        if ($item != "." && $item != "..") {
1501                            if (is_dir("$dir/$item")) {
1502                                sfDeleteDir("$dir/$item");
1503                            } else {
1504                                $arrResult[$cnt]['result'] = @unlink("$dir/$item");
1505                                $arrResult[$cnt]['file_name'] = "$dir/$item";
1506                            }
1507                        }
1508                        $cnt++;
1509                    }
1510                }
1511                closedir($handle);
1512                $arrResult[$cnt]['result'] = @rmdir($dir);
1513                $arrResult[$cnt]['file_name'] = "$dir/$item";
1514            } else {
1515                // ファイル削除
1516                $arrResult[0]['result'] = @unlink("$dir");
1517                $arrResult[0]['file_name'] = "$dir";
1518            }
1519        }
1520
1521        return $arrResult;
1522    }
1523
1524    /*
1525     * 関数名:sfGetFileTree()
1526     * 説明 :ツリー生成用配列取得(javascriptに渡す用)
1527     * 引数1 :ディレクトリ
1528     * 引数2 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1529     */
1530    function sfGetFileTree($dir, $tree_status) {
1531
1532        $cnt = 0;
1533        $arrTree = array();
1534        $default_rank = count(explode('/', $dir));
1535
1536        // 文末の/を取り除く
1537        $dir = ereg_replace("/$", "", $dir);
1538        // 最上位層を格納(user_data/)
1539        if(sfDirChildExists($dir)) {
1540            $arrTree[$cnt]['type'] = "_parent";
1541        } else {
1542            $arrTree[$cnt]['type'] = "_child";
1543        }
1544        $arrTree[$cnt]['path'] = $dir;
1545        $arrTree[$cnt]['rank'] = 0;
1546        $arrTree[$cnt]['count'] = $cnt;
1547        // 初期表示はオープン
1548        if($_POST['mode'] != '') {
1549            $arrTree[$cnt]['open'] = lfIsFileOpen($dir, $tree_status);
1550        } else {
1551            $arrTree[$cnt]['open'] = true;
1552        }
1553        $cnt++;
1554
1555        sfGetFileTreeSub($dir, $default_rank, $cnt, $arrTree, $tree_status);
1556
1557        return $arrTree;
1558    }
1559
1560    /*
1561     * 関数名:sfGetFileTree()
1562     * 説明 :ツリー生成用配列取得(javascriptに渡す用)
1563     * 引数1 :ディレクトリ
1564     * 引数2 :デフォルトの階層(/区切りで 0,1,2・・・とカウント)
1565     * 引数3 :連番
1566     * 引数4 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1567     */
1568    function sfGetFileTreeSub($dir, $default_rank, &$cnt, &$arrTree, $tree_status) {
1569
1570        if(file_exists($dir)) {
1571            if ($handle = opendir("$dir")) {
1572                while (false !== ($item = readdir($handle))) $arrDir[] = $item;
1573                // アルファベットと数字でソート
1574                natcasesort($arrDir);
1575                foreach($arrDir as $item) {
1576                    if ($item != "." && $item != "..") {
1577                        // 文末の/を取り除く
1578                        $dir = ereg_replace("/$", "", $dir);
1579                        $path = $dir."/".$item;
1580                        // ディレクトリのみ取得
1581                        if (is_dir($path)) {
1582                            $arrTree[$cnt]['path'] = $path;
1583                            if(sfDirChildExists($path)) {
1584                                $arrTree[$cnt]['type'] = "_parent";
1585                            } else {
1586                                $arrTree[$cnt]['type'] = "_child";
1587                            }
1588
1589                            // 階層を割り出す
1590                            $arrCnt = explode('/', $path);
1591                            $rank = count($arrCnt);
1592                            $arrTree[$cnt]['rank'] = $rank - $default_rank + 1;
1593                            $arrTree[$cnt]['count'] = $cnt;
1594                            // フォルダが開いているか
1595                            $arrTree[$cnt]['open'] = lfIsFileOpen($path, $tree_status);
1596                            $cnt++;
1597                            // 下層ディレクトリ取得の為、再帰的に呼び出す
1598                            sfGetFileTreeSub($path, $default_rank, $cnt, $arrTree, $tree_status);
1599                        }
1600                    }
1601                }
1602            }
1603            closedir($handle);
1604        }
1605    }
1606
1607    /*
1608     * 関数名:sfDirChildExists()
1609     * 説明 :指定したディレクトリ配下にファイルがあるか
1610     * 引数1 :ディレクトリ
1611     */
1612    function sfDirChildExists($dir) {
1613        if(file_exists($dir)) {
1614            if (is_dir($dir)) {
1615                $handle = opendir($dir);
1616                while ($file = readdir($handle)) {
1617                    // 行末の/を取り除く
1618                    $dir = ereg_replace("/$", "", $dir);
1619                    $path = $dir."/".$file;
1620                    if ($file != '..' && $file != '.' && is_dir($path)) {
1621                        return true;
1622                    }
1623                }
1624            }
1625        }
1626
1627        return false;
1628    }
1629
1630    /*
1631     * 関数名:lfIsFileOpen()
1632     * 説明 :指定したファイルが前回開かれた状態にあったかチェック
1633     * 引数1 :ディレクトリ
1634     * 引数2 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1635     */
1636    function lfIsFileOpen($dir, $tree_status) {
1637        $arrTreeStatus = explode('\|', $tree_status);
1638        if(in_array($dir, $arrTreeStatus)) {
1639            return true;
1640        }
1641
1642        return false;
1643    }
1644
1645    /*
1646     * 関数名:sfDownloadFile()
1647     * 引数1 :ファイルパス
1648     * 説明 :ファイルのダウンロード
1649     */
1650    function sfDownloadFile($file) {
1651         // ファイルの場合はダウンロードさせる
1652        Header("Content-disposition: attachment; filename=".basename($file));
1653        Header("Content-type: application/octet-stream; name=".basename($file));
1654        Header("Cache-Control: ");
1655        Header("Pragma: ");
1656        echo (sfReadFile($file));
1657    }
1658
1659    /*
1660     * 関数名:sfCreateFile()
1661     * 引数1 :ファイルパス
1662     * 引数2 :パーミッション
1663     * 説明 :ファイル作成
1664     */
1665    function sfCreateFile($file, $mode = "") {
1666        // 行末の/を取り除く
1667        if($mode != "") {
1668            $ret = @mkdir($file, $mode);
1669        } else {
1670            $ret = @mkdir($file);
1671        }
1672
1673        return $ret;
1674    }
1675
1676    /*
1677     * 関数名:sfReadFile()
1678     * 引数1 :ファイルパス
1679     * 説明 :ファイル読込
1680     */
1681    function sfReadFile($filename) {
1682        $str = "";
1683        // バイナリモードでオープン
1684        $fp = @fopen($filename, 'rb' );
1685        //ファイル内容を全て変数に読み込む
1686        if($fp) {
1687            $str = @fread($fp, filesize($filename)+1);
1688        }
1689        @fclose($fp);
1690
1691        return $str;
1692    }
1693
1694   /**
1695     * CSV出力用データ取得
1696     *
1697     * @return string
1698     */
1699    function getCSVData($array, $arrayIndex) {
1700        for ($i = 0; $i < count($array); $i++){
1701            // インデックスが設定されている場合
1702            if (is_array($arrayIndex) && 0 < count($arrayIndex)){
1703                for ($j = 0; $j < count($arrayIndex); $j++ ){
1704                    if ( $j > 0 ) $return .= ",";
1705                    $return .= "\"";
1706                    $return .= mb_ereg_replace("<","<",mb_ereg_replace( "\"","\"\"",$array[$i][$arrayIndex[$j]] )) ."\"";
1707                }
1708            } else {
1709                for ($j = 0; $j < count($array[$i]); $j++ ){
1710                    if ( $j > 0 ) $return .= ",";
1711                    $return .= "\"";
1712                    $return .= mb_ereg_replace("<","<",mb_ereg_replace( "\"","\"\"",$array[$i][$j] )) ."\"";
1713                }
1714            }
1715            $return .= "\n";
1716        }
1717        return $return;
1718    }
1719
1720   /**
1721     * 配列をテーブルタグで出力する。
1722     *
1723     * @return string
1724     */
1725    function getTableTag($array) {
1726        $html = "<table>";
1727        $html.= "<tr>";
1728        foreach($array[0] as $key => $val) {
1729            $html.="<th>$key</th>";
1730        }
1731        $html.= "</tr>";
1732
1733        $cnt = count($array);
1734
1735        for($i = 0; $i < $cnt; $i++) {
1736            $html.= "<tr>";
1737            foreach($array[$i] as $val) {
1738                $html.="<td>$val</td>";
1739            }
1740            $html.= "</tr>";
1741        }
1742        return $html;
1743    }
1744
1745   /**
1746     * 一覧-メイン画像のファイル指定がない場合、専用の画像ファイルに書き換える。
1747     *
1748     * @param string &$filename ファイル名
1749     * @return string
1750     */
1751    function sfNoImageMainList($filename = '') {
1752        if (strlen($filename) == 0 || substr($filename, -1, 1) == '/') {
1753            $filename .= 'noimage_main_list.jpg';
1754        }
1755        return $filename;
1756    }
1757
1758   /**
1759     * 詳細-メイン画像のファイル指定がない場合、専用の画像ファイルに書き換える。
1760     *
1761     * @param string &$filename ファイル名
1762     * @return string
1763     */
1764    function sfNoImageMain($filename = '') {
1765        if (strlen($filename) == 0 || substr($filename, -1, 1) == '/') {
1766            $filename .= 'noimage_main.png';
1767        }
1768        return $filename;
1769    }
1770
1771    /* デバッグ用 ------------------------------------------------------------------------------------------------*/
1772    function sfPrintR($obj) {
1773        echo '<div style="font-size: 12px;color: #00FF00;">' . "\n";
1774        echo '<strong>**デバッグ中**</strong><br />' . "\n";
1775        echo '<pre>' . "\n";
1776        var_dump($obj);
1777        echo '</pre>' . "\n";
1778        echo '<strong>**デバッグ中**</strong></div>' . "\n";
1779    }
1780
1781    /**
1782     * ランダムな文字列を取得する
1783     *
1784     * @param integer $length 文字数
1785     * @return string ランダムな文字列
1786     */
1787    function sfGetRandomString($length = 1) {
1788        require_once dirname(__FILE__) . '/../../module/Text/Password.php';
1789        return Text_Password::create($length);
1790    }
1791
1792    /**
1793     * 現在の URL を取得する
1794     *
1795     * @return string 現在のURL
1796     */
1797    function sfGetUrl() {
1798        $url = '';
1799
1800        if (SC_Utils_Ex::sfIsHTTPS()) {
1801            $url = "https://";
1802        } else {
1803            $url = "http://";
1804        }
1805
1806        $url .= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?' . $_SERVER['QUERY_STRING'];
1807
1808        return $url;
1809    }
1810
1811    /**
1812     * バックトレースをテキスト形式で出力する
1813     *
1814     * @return string テキストで表現したバックトレース
1815     */
1816    function sfBacktraceToString($arrBacktrace) {
1817        $string = '';
1818
1819        foreach (array_reverse($arrBacktrace) as $backtrace) {
1820            if (strlen($backtrace['class']) >= 1) {
1821                $func = $backtrace['class'] . $backtrace['type'] . $backtrace['function'];
1822            } else {
1823                $func = $backtrace['function'];
1824            }
1825
1826            $string .= $backtrace['file'] . " " . $backtrace['line'] . ":" . $func . "\n";
1827        }
1828
1829        return $string;
1830    }
1831
1832    /**
1833     * 管理機能かを判定
1834     *
1835     * @return bool 管理機能か
1836     */
1837    function sfIsAdminFunction() {
1838        return defined('ADMIN_FUNCTION') && ADMIN_FUNCTION;
1839    }
1840
1841    /**
1842     * フロント機能かを判定
1843     *
1844     * @return bool フロント機能か
1845     */
1846    function sfIsFrontFunction() {
1847        return defined('FRONT_FUNCTION') && FRONT_FUNCTION;
1848    }
1849
1850    /**
1851     * インストール機能かを判定
1852     *
1853     * @return bool インストール機能か
1854     */
1855    function sfIsInstallFunction() {
1856        return defined('INSTALL_FUNCTION') && INSTALL_FUNCTION;
1857    }
1858
1859    // 郵便番号から住所の取得
1860    function sfGetAddress($zipcode) {
1861
1862        $objQuery = new SC_Query_Ex(ZIP_DSN);
1863
1864        $masterData = new SC_DB_MasterData_Ex();
1865        $arrPref = $masterData->getMasterData('mtb_pref');
1866        // インデックスと値を反転させる。
1867        $arrREV_PREF = array_flip($arrPref);
1868
1869        // 郵便番号検索文作成
1870        $zipcode = mb_convert_kana($zipcode ,'n');
1871        $sqlse = "SELECT state, city, town FROM mtb_zip WHERE zipcode = ?";
1872
1873        $data_list = $objQuery->getAll($sqlse, array($zipcode));
1874        if (empty($data_list)) return array();
1875
1876        /*
1877         総務省からダウンロードしたデータをそのままインポートすると
1878         以下のような文字列が入っているので 対策する。
1879         ・(1・19丁目)
1880         ・以下に掲載がない場合
1881        */
1882        $town =  $data_list[0]['town'];
1883        $town = ereg_replace("(.*)$","",$town);
1884        $town = ereg_replace("以下に掲載がない場合","",$town);
1885        $data_list[0]['town'] = $town;
1886        $data_list[0]['state'] = $arrREV_PREF[$data_list[0]['state']];
1887
1888        return $data_list;
1889    }
1890
1891    /**
1892     * プラグインが配置されているディレクトリ(フルパス)を取得する
1893     *
1894     * @param string $file プラグイン情報ファイル(info.php)のパス
1895     * @return SimpleXMLElement プラグイン XML
1896     */
1897    function sfGetPluginFullPathByRequireFilePath($file) {
1898        return str_replace('\\', '/', dirname($file)) . '/';
1899    }
1900
1901    /**
1902     * プラグインのパスを取得する
1903     *
1904     * @param string $pluginFullPath プラグインが配置されているディレクトリ(フルパス)
1905     * @return SimpleXMLElement プラグイン XML
1906     */
1907    function sfGetPluginPathByPluginFullPath($pluginFullPath) {
1908        return basename(rtrim($pluginFullPath, '/'));
1909    }
1910
1911    /**
1912     * プラグイン情報配列の基本形を作成する
1913     *
1914     * @param string $file プラグイン情報ファイル(info.php)のパス
1915     * @return array プラグイン情報配列
1916     */
1917    function sfMakePluginInfoArray($file) {
1918        $fullPath = SC_Utils_Ex::sfGetPluginFullPathByRequireFilePath($file);
1919
1920        return
1921            array(
1922                // パス
1923                'path' => SC_Utils_Ex::sfGetPluginPathByPluginFullPath($fullPath),
1924                // プラグイン名
1925                'name' => '未定義',
1926                // フルパス
1927                'fullpath' => $fullPath,
1928                // バージョン
1929                'version' => null,
1930                // 著作者
1931                'auther' => '未定義',
1932            )
1933        ;
1934    }
1935
1936    /**
1937     * プラグイン情報配列を取得する
1938     *
1939     * TODO include_once を利用することで例外対応をサボタージュしているのを改善する。
1940     *
1941     * @param string $path プラグインのディレクトリ名
1942     * @return array プラグイン情報配列
1943     */
1944    function sfGetPluginInfoArray($path) {
1945        return (array)include_once(PLUGIN_REALDIR . "$path/plugin_info.php");
1946    }
1947
1948    /**
1949     * プラグイン XML を読み込む
1950     *
1951     * TODO 空だったときを考慮
1952     *
1953     * @return SimpleXMLElement プラグイン XML
1954     */
1955    function sfGetPluginsXml() {
1956        return simplexml_load_file(PLUGIN_REALDIR . 'plugins.xml');
1957    }
1958
1959    /**
1960     * プラグイン XML を書き込む
1961     *
1962     * @param SimpleXMLElement $pluginsXml プラグイン XML
1963     * @return integer ファイルに書き込まれたバイト数を返します。
1964     */
1965    function sfPutPluginsXml($pluginsXml) {
1966        if (version_compare(PHP_VERSION, '5.0.0', '>')) {
1967           return;
1968        }
1969
1970        $xml = $pluginsXml->asXML();
1971        if (strlen($xml) == 0) SC_Utils_Ex::sfDispException();
1972
1973        $return = file_put_contents(PLUGIN_REALDIR . 'plugins.xml', $pluginsXml->asXML());
1974        if ($return === false) SC_Utils_Ex::sfDispException();
1975        return $return;
1976    }
1977
1978    function sfLoadPluginInfo($filenamePluginInfo) {
1979        return (array)include_once $filenamePluginInfo;
1980    }
1981
1982    /**
1983     * 現在の Unix タイムスタンプを float (秒単位) でマイクロ秒まで返す
1984     *
1985     * PHP4の上位互換用途。
1986     * FIXME PHP4でテストする。(現状全くテストしていない。)
1987     * @param SimpleXMLElement $pluginsXml プラグイン XML
1988     * @return integer ファイルに書き込まれたバイト数を返します。
1989     */
1990    function sfMicrotimeFloat() {
1991        $microtime = microtime(true);
1992        if (is_string($microtime)) {
1993            list($usec, $sec) = explode(" ", microtime());
1994            return (float)$usec + (float)$sec;
1995        }
1996        return $microtime;
1997    }
1998
1999    /**
2000     * 変数が空白かどうかをチェックする.
2001     *
2002     * 引数 $val が空白かどうかをチェックする. 空白の場合は true.
2003     * 以下の文字は空白と判断する.
2004     * - " " (ASCII 32 (0x20)), 通常の空白
2005     * - "\t" (ASCII 9 (0x09)), タブ
2006     * - "\n" (ASCII 10 (0x0A)), リターン
2007     * - "\r" (ASCII 13 (0x0D)), 改行
2008     * - "\0" (ASCII 0 (0x00)), NULバイト
2009     * - "\x0B" (ASCII 11 (0x0B)), 垂直タブ
2010     *
2011     * 引数 $val が配列の場合は, 空の配列の場合 true を返す.
2012     *
2013     * 引数 $greedy が true の場合は, 全角スペース, ネストした空の配列も
2014     * 空白と判断する.
2015     *
2016     * @param mixed $val チェック対象の変数
2017     * @param boolean $greedy "貧欲"にチェックを行う場合 true
2018     * @return boolean $val が空白と判断された場合 true
2019     */
2020    function isBlank($val, $greedy = true) {
2021        if (is_array($val)) {
2022            if ($greedy) {
2023                if (empty($val)) {
2024                    return true;
2025                }
2026                foreach ($val as $in) {
2027                    /*
2028                     * SC_Utils_Ex への再帰は無限ループやメモリリークの懸念
2029                     * 自クラスへ再帰する.
2030                     */
2031                    if (!SC_Utils::isBlank($in, $greedy)) {
2032                        return false;
2033                    }
2034                }
2035            } else {
2036                return empty($val);
2037            }
2038        }
2039
2040        if ($greedy) {
2041            $val = preg_replace("/ /", "", $val);
2042        }
2043
2044        $val = trim($val);
2045        if (strlen($val) > 0) {
2046            return false;
2047        }
2048        return true;
2049    }
2050
2051    /**
2052     * 指定されたURLのドメインが一致するかを返す
2053     *
2054     * 戻り値:一致(true) 不一致(false)
2055     *
2056     * @param string $url
2057     * @return boolean
2058     */
2059    function sfIsInternalDomain($url) {
2060        $netURL = new Net_URL(HTTP_URL);
2061        $host = $netURL->host;
2062        if (!$host) return false;
2063        $host = preg_quote($host, "#");
2064        if (!preg_match("#^(http|https)://{$host}#i", $url)) return false;
2065        return true;
2066    }
2067
2068    /**
2069     * パスワードのハッシュ化
2070     *
2071     * @param string $str 暗号化したい文言
2072     * @param string $salt salt
2073     * @return string ハッシュ暗号化された文字列
2074     */
2075    function sfGetHashString($str, $salt) {
2076        $res = '';
2077        if ($salt == '') {
2078            $salt = AUTH_MAGIC;
2079        }
2080        if ( AUTH_TYPE == 'PLAIN') {
2081            $res = $str;
2082        } else {
2083            $res = hash_hmac(PASSWORD_HASH_ALGOS, $str . ":" . AUTH_MAGIC, $salt);
2084        }
2085        return $res;
2086    }
2087
2088    /**
2089     * パスワード文字列のハッシュ一致判定
2090     *
2091     * @param string $pass 確認したいパスワード文字列
2092     * @param string $hashpass 確認したいパスワードハッシュ文字列
2093     * @param string $salt salt
2094     * @return boolean 一致判定
2095     */
2096    function sfIsMatchHashPassword($pass, $hashpass, $salt) {
2097        $res = false;
2098        if ($hashpass != '') {
2099            if (AUTH_TYPE == 'PLAIN') {
2100                if($pass === $hashpass) {
2101                    $res = true;
2102                }
2103            } else {
2104                if (empty($salt)) {
2105                    // 旧バージョン(2.11未満)からの移行を考慮
2106                    $hash = sha1($pass . ":" . AUTH_MAGIC);
2107                } else {
2108                    $hash = SC_Utils_Ex::sfGetHashString($pass, $salt);
2109                }
2110                if($hash === $hashpass) {
2111                    $res = true;
2112                }
2113            }
2114        }
2115        return $res;
2116    }
2117
2118    /**
2119     * 検索結果の1ページあたりの最大表示件数を取得する
2120     *
2121     * フォームの入力値から最大表示件数を取得する
2122     * 取得できなかった場合は, 定数 SEARCH_PMAX の値を返す
2123     *
2124     * @param string $search_page_max 表示件数の選択値
2125     * @return integer 1ページあたりの最大表示件数
2126     */
2127    function sfGetSearchPageMax($search_page_max) {
2128        if (SC_Utils_Ex::sfIsInt($search_page_max) && $search_page_max > 0) {
2129            $page_max = intval($search_page_max);
2130        } else {
2131            $page_max = SEARCH_PMAX;
2132        }
2133        return $page_max;
2134    }
2135
2136    /**
2137     * 値を JSON 形式にして返す.
2138     *
2139     * この関数は, json_encode() 又は Services_JSON::encode() のラッパーです.
2140     * json_encode() 関数が使用可能な場合は json_encode() 関数を使用する.
2141     * 使用できない場合は, Services_JSON::encode() 関数を使用する.
2142     *
2143     * @param mixed $value JSON 形式にエンコードする値
2144     * @return string JSON 形式にした文字列
2145     * @see json_encode()
2146     * @see Services_JSON::encode()
2147     */
2148    function jsonEncode($value) {
2149        if (function_exists('json_encode')) {
2150            return json_encode($value);
2151        } else {
2152            require_once dirname(__FILE__) . '/../../module/Services/JSON.php';
2153            GC_Utils_Ex::gfPrintLog(' *use Services_JSON::encode(). faster than using the json_encode!');
2154            $objJson = new Services_JSON();
2155            return $objJson->encode($value);
2156        }
2157    }
2158
2159    /**
2160     * JSON 文字列をデコードする.
2161     *
2162     * この関数は, json_decode() 又は Services_JSON::decode() のラッパーです.
2163     * json_decode() 関数が使用可能な場合は json_decode() 関数を使用する.
2164     * 使用できない場合は, Services_JSON::decode() 関数を使用する.
2165     *
2166     * @param string $json JSON 形式にエンコードされた文字列
2167     * @return mixed デコードされた PHP の型
2168     * @see json_decode()
2169     * @see Services_JSON::decode()
2170     */
2171    function jsonDecode($json) {
2172        if (function_exists('json_decode')) {
2173            return json_decode($json);
2174        } else {
2175            require_once dirname(__FILE__) . '/../../module/Services/JSON.php';
2176            GC_Utils_Ex::gfPrintLog(' *use Services_JSON::decode(). faster than using the json_decode!');
2177            $objJson = new Services_JSON();
2178            return $objJson->decode($json);
2179        }
2180    }
2181
2182    /**
2183     * パスが絶対パスかどうかをチェックする.
2184     *
2185     * 引数のパスが絶対パスの場合は true を返す.
2186     * この関数は, パスの存在チェックを行なわないため注意すること.
2187     *
2188     * @param string チェック対象のパス
2189     * @return boolean 絶対パスの場合 true
2190     */
2191    function isAbsoluteRealPath($realpath) {
2192        if (strpos(PHP_OS, 'WIN') === false) {
2193            return (substr($realpath, 0, 1) == '/');
2194        } else {
2195            return preg_match('/^[a-zA-Z]:(\\\|\/)/', $realpath) ? true : false;
2196        }
2197    }
2198
2199    /**
2200     * ディレクトリを再帰的に作成する.
2201     *
2202     * mkdir 関数の $recursive パラメーターを PHP4 でサポートする.
2203     *
2204     * @param string $pathname ディレクトリのパス
2205     * @param integer $mode 作成するディレクトリのパーミッション
2206     * @return boolean 作成に成功した場合 true; 失敗した場合 false
2207     * @see http://jp.php.net/mkdir
2208     */
2209    function recursiveMkdir($pathname, $mode = 0777) {
2210        /*
2211         * SC_Utils_Ex への再帰は無限ループやメモリリークの懸念
2212         * 自クラスへ再帰する.
2213         */
2214        is_dir(dirname($pathname)) || SC_Utils::recursiveMkdir(dirname($pathname), $mode);
2215        return is_dir($pathname) || @mkdir($pathname, $mode);
2216    }
2217}
2218?>
Note: See TracBrowser for help on using the repository browser.