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

Revision 23477, 64.2 KB checked in by pineray, 10 years ago (diff)

#2448 typo修正・ソース整形・ソースコメントの改善 for 2.13.3

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