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

Revision 23447, 64.7 KB checked in by pineray, 10 years ago (diff)

#2481 管理者にログインしていない場合にadmin=onにすると管理画面が表示されてしまう不具合を修正.

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