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

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

Revision 23461, 64.8 KB checked in by pineray, 10 years ago (diff)

#2560 pageクラスからdtb_reviewテーブルを直接指定している箇所をなくす

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