source: branches/version-2_12-dev/data/class/util/SC_Utils.php @ 21755

Revision 21755, 68.9 KB checked in by shutta, 12 years ago (diff)

#515 PHP 5.3.0対応
PHP5.3以降で、非推奨関数となるereg系関数を書き換えた。

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