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 @ 23463

Revision 23463, 64.0 KB checked in by shutta, 10 years ago (diff)

#2562 課税規則による端数処理ルーチンの共通関数化
課税規則に応じた端数処理ルーチンを共通関数にまとめた。

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