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

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

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

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