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

Revision 21583, 68.9 KB checked in by Seasoft, 12 years ago (diff)

#1603 (プラグイン機能(エンジン部分))

  • 互換性のない旧プラグイン機能を削除

#1607 (未使用定義の削除)
#1605 (PHP4向けコードの除去、PHP5向けのコード最適化)

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