source: branches/version-2_13-dev/data/class/util/SC_Utils.php @ 23590

Revision 23590, 64.6 KB checked in by kimoto, 10 years ago (diff)

recursiveMkDirのPHP4サポートは不要
Windows環境の場合はmkdirのmodeは効かないのでテストを変更する
isAbsoluteRealPathの修正

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