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

Revision 21203, 70.9 KB checked in by shutta, 13 years ago (diff)

refs #1449 (不要な関数・処理の整理)
SC_Utils::sfReload()を削除。

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