Warning: Can't use blame annotator:
svn blame failed on branches/version-2_13-dev/data/class/util/SC_Utils.php: バイナリファイル 'file:///home/svn/open/branches/version-2_13-dev/data/class/util/SC_Utils.php' に対しては blame で各行の最終変更者を計算できません 195004

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

Revision 23609, 65.1 KB checked in by kimoto, 10 years ago (diff)

#150 ユニットテスト環境の整備
isAbsoluteRealPathが相対パス混じりでもtrueを返していたのでテストの追加

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