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

Revision 21659, 68.2 KB checked in by Seasoft, 12 years ago (diff)

#1613 (typo修正・ソース整形・ソースコメントの改善)

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