source: branches/comu-ver2/data/class/util/SC_Utils.php @ 18566

Revision 18566, 74.9 KB checked in by shutta, 14 years ago (diff)

#603 を反映。

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
  • Property svn:mime-type set to text/x-httpd-php; charset=UTF-8
Line 
1<?php
2/*
3 * This file is part of EC-CUBE
4 *
5 * Copyright(c) 2000-2007 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     * サイト管理情報から値を取得する。
39     * データが存在する場合、必ず1以上の数値が設定されている。
40     * 0を返した場合は、呼び出し元で対応すること。
41     *
42     * @param $control_id 管理ID
43     * @param $dsn DataSource
44     * @return $control_flg フラグ
45     */
46    function sfGetSiteControlFlg($control_id, $dsn = "") {
47
48        // データソース
49        if($dsn == "") {
50            if(defined('DEFAULT_DSN')) {
51                $dsn = DEFAULT_DSN;
52            } else {
53                return;
54            }
55        }
56
57        // クエリ生成
58        $target_column = "control_flg";
59        $table_name = "dtb_site_control";
60        $where = "control_id = ?";
61        $arrval = array($control_id);
62        $control_flg = 0;
63
64        // クエリ発行
65        $objQuery = new SC_Query($dsn, true, true);
66        $arrSiteControl = $objQuery->select($target_column, $table_name, $where, $arrval);
67
68        // データが存在すればフラグを取得する
69        if (count($arrSiteControl) > 0) {
70            $control_flg = $arrSiteControl[0]["control_flg"];
71        }
72
73        return $control_flg;
74    }
75
76    // インストール初期処理
77    function sfInitInstall() {
78        // インストール済みが定義されていない。
79        if (!defined('ECCUBE_INSTALL')) {
80            // ここから2つ上はdataディレクトリ
81            $eccube_data_dir = realpath(dirname(__FILE__) . '/../../');
82            // dataディレクトリとDATA_DIR2HTMLからhtmlディレクトリを取得。
83            $eccube_html_dir = realpath($eccube_data_dir . '/' . DATA_DIR2HTML);
84            // htmlディレクトリとDOCUMENT_ROOTの相対パスがURL_DIR
85            $document_root = realpath($_SERVER['DOCUMENT_ROOT']);
86            $url_dir = preg_replace('|^' . preg_quote($document_root) . '|', '', $eccube_html_dir);
87            // installページへのURLを生成。
88            $location = realpath('/' . $url_dir . '/install/index.php');
89
90            header('Location: ' . $location);
91            exit;
92        }
93        $path = HTML_PATH . "install/index.php";
94        if(file_exists($path)) {
95            SC_Utils::sfErrorHeader("&gt;&gt; /install/index.phpは、インストール完了後にファイルを削除してください。");
96        }
97    }
98
99    // 装飾付きエラーメッセージの表示
100    function sfErrorHeader($mess, $print = false) {
101        global $GLOBAL_ERR;
102        $GLOBAL_ERR.="<div style='color: #F00; font-weight: bold; font-size: 12px;"
103            . "background-color: #FEB; text-align: center; padding: 5px;'>";
104        $GLOBAL_ERR.= $mess;
105        $GLOBAL_ERR.= "</div>";
106        if($print) {
107            print($GLOBAL_ERR);
108        }
109    }
110
111    /* エラーページの表示 */
112    function sfDispError($type) {
113
114        require_once(CLASS_EX_PATH . "page_extends/error/LC_Page_Error_DispError_Ex.php");
115
116        $objPage = new LC_Page_Error_DispError_Ex();
117        register_shutdown_function(array($objPage, "destroy"));
118        $objPage->init();
119        $objPage->type = $type;
120        $objPage->process();
121        exit;
122    }
123
124    /* サイトエラーページの表示 */
125    function sfDispSiteError($type, $objSiteSess = "", $return_top = false, $err_msg = "") {
126        global $objCampaignSess;
127
128        require_once(CLASS_EX_PATH . "page_extends/error/LC_Page_Error_Ex.php");
129
130        $objPage = new LC_Page_Error_Ex();
131        register_shutdown_function(array($objPage, "destroy"));
132        $objPage->init();
133        $objPage->type = $type;
134        $objPage->objSiteSess = $objSiteSess;
135        $objPage->return_top = $return_top;
136        $objPage->err_msg = $err_msg;
137        $objPage->is_mobile = (defined('MOBILE_SITE')) ? true : false;
138        $objPage->process();
139        exit;
140    }
141
142    /**
143     * 例外エラーページの表示
144     *
145     * @param string $debugMsg デバッグ用のメッセージ
146     * @return void
147     */
148    function sfDispException($debugMsg = null) {
149        require_once(CLASS_EX_PATH . "page_extends/error/LC_Page_Error_SystemError_Ex.php");
150       
151        $objPage = new LC_Page_Error_SystemError_Ex();
152        register_shutdown_function(array($objPage, "destroy"));
153        $objPage->init();
154        if (!is_null($debugMsg)) {
155            $objPage->addDebugMsg($debugMsg);
156        }
157        if (function_exists("debug_backtrace")) {
158            $objPage->backtrace = debug_backtrace();
159        }
160        GC_Utils_Ex::gfPrintLog($objPage->sfGetErrMsg());
161        $objPage->process();
162       
163        exit();
164    }
165
166    /* 認証の可否判定 */
167    function sfIsSuccess($objSess, $disp_error = true) {
168        $ret = $objSess->IsSuccess();
169        if($ret != SUCCESS) {
170            if($disp_error) {
171                // エラーページの表示
172                SC_Utils::sfDispError($ret);
173            }
174            return false;
175        }
176        // リファラーチェック(CSRFの暫定的な対策)
177        // 「リファラ無」 の場合はスルー
178        // 「リファラ有」 かつ 「管理画面からの遷移でない」 場合にエラー画面を表示する
179        if ( empty($_SERVER['HTTP_REFERER']) ) {
180            // TODO 警告表示させる?
181            // sfErrorHeader('>> referrerが無効になっています。');
182        } else {
183            $domain  = SC_Utils::sfIsHTTPS() ? SSL_URL : SITE_URL;
184            $pattern = sprintf('|^%s.*|', $domain);
185            $referer = $_SERVER['HTTP_REFERER'];
186
187            // 管理画面から以外の遷移の場合はエラー画面を表示
188            if (!preg_match($pattern, $referer)) {
189                if ($disp_error) SC_Utils::sfDispError(INVALID_MOVE_ERRORR);
190                return false;
191            }
192        }
193        return true;
194    }
195
196    /**
197     * 文字列をアスタリスクへ変換する.
198     *
199     * @param string $passlen 変換する文字列
200     * @return string アスタリスクへ変換した文字列
201     */
202    function lfPassLen($passlen){
203        $ret = "";
204        for ($i=0;$i<$passlen;true){
205            $ret.="*";
206            $i++;
207        }
208        return $ret;
209    }
210
211    /**
212     * HTTPSかどうかを判定
213     *
214     * @return bool
215     */
216    function sfIsHTTPS () {
217        // HTTPS時には$_SERVER['HTTPS']には空でない値が入る
218        // $_SERVER['HTTPS'] != 'off' はIIS用
219        if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
220            return true;
221        } else {
222            return false;
223        }
224    }
225
226    /**
227     *  正規の遷移がされているかを判定
228     *  前画面でuniqidを埋め込んでおく必要がある
229     *  @param  obj  SC_Session, SC_SiteSession
230     *  @return bool
231     */
232    function sfIsValidTransition($objSess) {
233        // 前画面からPOSTされるuniqidが正しいものかどうかをチェック
234        $uniqid = $objSess->getUniqId();
235        if ( !empty($_POST['uniqid']) && ($_POST['uniqid'] === $uniqid) ) {
236            return true;
237        } else {
238            return false;
239        }
240    }
241
242    /* 前のページで正しく登録が行われたか判定 */
243    function sfIsPrePage(&$objSiteSess) {
244        $ret = $objSiteSess->isPrePage();
245        if($ret != true) {
246            // エラーページの表示
247            SC_Utils::sfDispSiteError(PAGE_ERROR, $objSiteSess);
248        }
249    }
250
251    function sfCheckNormalAccess(&$objSiteSess, &$objCartSess) {
252        // ユーザユニークIDの取得
253        $uniqid = $objSiteSess->getUniqId();
254        // 購入ボタンを押した時のカート内容がコピーされていない場合のみコピーする。
255        $objCartSess->saveCurrentCart($uniqid);
256        // POSTのユニークIDとセッションのユニークIDを比較(ユニークIDがPOSTされていない場合はスルー)
257        $ret = $objSiteSess->checkUniqId();
258        if($ret != true) {
259            // エラーページの表示
260            SC_Utils_Ex::sfDispSiteError(CANCEL_PURCHASE, $objSiteSess);
261        }
262
263        // カート内が空でないか || 購入ボタンを押してから変化がないか
264        $quantity = $objCartSess->getTotalQuantity();
265        $ret = $objCartSess->checkChangeCart();
266        if($ret == true || !($quantity > 0)) {
267            // カート情報表示に強制移動する
268            // FIXME false を返して, Page クラスで遷移させるべき...
269            if (defined("MOBILE_SITE")) {
270                header("Location: ". MOBILE_URL_CART_TOP
271                       . "?" . session_name() . "=" . session_id());
272            } else {
273                header("Location: ".URL_CART_TOP);
274            }
275            exit;
276        }
277        return $uniqid;
278    }
279
280    /* DB用日付文字列取得 */
281    function sfGetTimestamp($year, $month, $day, $last = false) {
282        if($year != "" && $month != "" && $day != "") {
283            if($last) {
284                $time = "23:59:59";
285            } else {
286                $time = "00:00:00";
287            }
288            $date = $year."-".$month."-".$day." ".$time;
289        } else {
290            $date = "";
291        }
292        return     $date;
293    }
294
295    /**
296     *  INT型の数値チェック
297     *  ・FIXME: マイナス値の扱いが不明確
298     *  ・XXX: INT_LENには収まるが、INT型の範囲を超えるケースに対応できないのでは?
299     * 
300     *  @param mixed $value
301     *  @return bool
302     */
303    //
304    function sfIsInt($value) {
305        if (strlen($value) >= 1 && strlen($value) <= INT_LEN && is_numeric($value)) {
306            return true;
307        }
308        return false;
309    }
310
311    /*
312     * 桁が0で埋められているかを判定する
313     *
314     * @param string $value 検査対象
315     * @return boolean 0で埋められている
316     */
317    function sfIsZeroFilling($value) {
318        if (strlen($value) > 1 && $value{0} === '0')
319            return true;
320        return false;
321    }
322
323    function sfCSVDownload($data, $prefix = ""){
324
325        if($prefix == "") {
326            $dir_name = SC_Utils::sfUpDirName();
327            $file_name = $dir_name . date("ymdHis") .".csv";
328        } else {
329            $file_name = $prefix . date("ymdHis") .".csv";
330        }
331
332        /* HTTPヘッダの出力 */
333        Header("Content-disposition: attachment; filename=${file_name}");
334        Header("Content-type: application/octet-stream; name=${file_name}");
335        Header("Cache-Control: ");
336        Header("Pragma: ");
337
338        if (mb_internal_encoding() == CHAR_CODE){
339            $data = mb_convert_encoding($data,'SJIS-Win',CHAR_CODE);
340        }
341
342        /* データを出力 */
343        echo $data;
344    }
345
346    /* 1階層上のディレクトリ名を取得する */
347    function sfUpDirName() {
348        $path = $_SERVER['PHP_SELF'];
349        $arrVal = split("/", $path);
350        $cnt = count($arrVal);
351        return $arrVal[($cnt - 2)];
352    }
353
354
355
356
357    /**
358     * 現在のサイトを更新(ただしポストは行わない)
359     *
360     * @deprecated LC_Page::reload() を使用して下さい.
361     */
362    function sfReload($get = "") {
363        if ($_SERVER["SERVER_PORT"] == "443" ){
364            $url = ereg_replace(URL_DIR . "$", "", SSL_URL);
365        } else {
366            $url = ereg_replace(URL_DIR . "$", "", SITE_URL);
367        }
368
369        if($get != "") {
370            header("Location: ". $url . $_SERVER['PHP_SELF'] . "?" . $get);
371        } else {
372            header("Location: ". $url . $_SERVER['PHP_SELF']);
373        }
374        exit;
375    }
376
377    // チェックボックスの値をマージ
378    function sfMergeCBValue($keyname, $max) {
379        $conv = "";
380        $cnt = 1;
381        for($cnt = 1; $cnt <= $max; $cnt++) {
382            if ($_POST[$keyname . $cnt] == "1") {
383                $conv.= "1";
384            } else {
385                $conv.= "0";
386            }
387        }
388        return $conv;
389    }
390
391    // html_checkboxesの値をマージして2進数形式に変更する。
392    function sfMergeCheckBoxes($array, $max) {
393        $ret = "";
394        if(is_array($array)) {
395            foreach($array as $val) {
396                $arrTmp[$val] = "1";
397            }
398        }
399        for($i = 1; $i <= $max; $i++) {
400            if(isset($arrTmp[$i]) && $arrTmp[$i] == "1") {
401                $ret.= "1";
402            } else {
403                $ret.= "0";
404            }
405        }
406        return $ret;
407    }
408
409
410    // html_checkboxesの値をマージして「-」でつなげる。
411    function sfMergeParamCheckBoxes($array) {
412        $ret = '';
413        if(is_array($array)) {
414            foreach($array as $val) {
415                if($ret != "") {
416                    $ret.= "-$val";
417                } else {
418                    $ret = $val;
419                }
420            }
421        } else {
422            $ret = $array;
423        }
424        return $ret;
425    }
426
427    // html_checkboxesの値をマージしてSQL検索用に変更する。
428    function sfSearchCheckBoxes($array) {
429        $max = max($array);
430        $ret = '';
431        for ($i = 1; $i <= $max; $i++) {
432            $ret .= in_array($i, $array) ? '1' : '_';
433        }
434        if (strlen($ret) != 0) {
435            $ret .= '%';
436        }
437        return $ret;
438    }
439
440    // 2進数形式の値をhtml_checkboxes対応の値に切り替える
441    function sfSplitCheckBoxes($val) {
442        $arrRet = array();
443        $len = strlen($val);
444        for($i = 0; $i < $len; $i++) {
445            if(substr($val, $i, 1) == "1") {
446                $arrRet[] = ($i + 1);
447            }
448        }
449        return $arrRet;
450    }
451
452    // チェックボックスの値をマージ
453    function sfMergeCBSearchValue($keyname, $max) {
454        $conv = "";
455        $cnt = 1;
456        for($cnt = 1; $cnt <= $max; $cnt++) {
457            if ($_POST[$keyname . $cnt] == "1") {
458                $conv.= "1";
459            } else {
460                $conv.= "_";
461            }
462        }
463        return $conv;
464    }
465
466    // チェックボックスの値を分解
467    function sfSplitCBValue($val, $keyname = "") {
468        $arr = array();
469        $len = strlen($val);
470        $no = 1;
471        for ($cnt = 0; $cnt < $len; $cnt++) {
472            if($keyname != "") {
473                $arr[$keyname . $no] = substr($val, $cnt, 1);
474            } else {
475                $arr[] = substr($val, $cnt, 1);
476            }
477            $no++;
478        }
479        return $arr;
480    }
481
482    // キーと値をセットした配列を取得
483    function sfArrKeyValue($arrList, $keyname, $valname, $len_max = "", $keysize = "") {
484        $arrRet = array();
485        $max = count($arrList);
486
487        if($len_max != "" && $max > $len_max) {
488            $max = $len_max;
489        }
490
491        for($cnt = 0; $cnt < $max; $cnt++) {
492            if($keysize != "") {
493                $key = SC_Utils::sfCutString($arrList[$cnt][$keyname], $keysize);
494            } else {
495                $key = $arrList[$cnt][$keyname];
496            }
497            $val = $arrList[$cnt][$valname];
498
499            if(!isset($arrRet[$key])) {
500                $arrRet[$key] = $val;
501            }
502
503        }
504        return $arrRet;
505    }
506
507    // キーと値をセットした配列を取得(値が複数の場合)
508    function sfArrKeyValues($arrList, $keyname, $valname, $len_max = "", $keysize = "", $connect = "") {
509
510        $max = count($arrList);
511
512        if($len_max != "" && $max > $len_max) {
513            $max = $len_max;
514        }
515
516        for($cnt = 0; $cnt < $max; $cnt++) {
517            if($keysize != "") {
518                $key = SC_Utils::sfCutString($arrList[$cnt][$keyname], $keysize);
519            } else {
520                $key = $arrList[$cnt][$keyname];
521            }
522            $val = $arrList[$cnt][$valname];
523
524            if($connect != "") {
525                $arrRet[$key].= "$val".$connect;
526            } else {
527                $arrRet[$key][] = $val;
528            }
529        }
530        return $arrRet;
531    }
532
533    // 配列の値をカンマ区切りで返す。
534    function sfGetCommaList($array, $space=true, $arrPop = array()) {
535        if (count($array) > 0) {
536            $line = "";
537            foreach($array as $val) {
538                if (!in_array($val, $arrPop)) {
539                    if ($space) {
540                        $line .= $val . ", ";
541                    } else {
542                        $line .= $val . ",";
543                    }
544                }
545            }
546            if ($space) {
547                $line = ereg_replace(", $", "", $line);
548            } else {
549                $line = ereg_replace(",$", "", $line);
550            }
551            return $line;
552        } else {
553            return false;
554        }
555
556    }
557
558    /* 配列の要素をCSVフォーマットで出力する。*/
559    function sfGetCSVList($array) {
560        $line = "";
561        if (count($array) > 0) {
562            foreach($array as $key => $val) {
563                $val = mb_convert_encoding($val, CHAR_CODE, CHAR_CODE);
564                $line .= "\"".$val."\",";
565            }
566            $line = ereg_replace(",$", "\r\n", $line);
567        }else{
568            return false;
569        }
570        return $line;
571    }
572
573    /* 配列の要素をPDFフォーマットで出力する。*/
574    function sfGetPDFList($array) {
575        foreach($array as $key => $val) {
576            $line .= "\t".$val;
577        }
578        $line.="\n";
579        return $line;
580    }
581
582
583
584    /*-----------------------------------------------------------------*/
585    /*    check_set_term
586    /*    年月日に別れた2つの期間の妥当性をチェックし、整合性と期間を返す
587    /* 引数 (開始年,開始月,開始日,終了年,終了月,終了日)
588    /* 戻値 array(1,2,3)
589    /*          1.開始年月日 (YYYY/MM/DD 000000)
590    /*            2.終了年月日 (YYYY/MM/DD 235959)
591    /*            3.エラー ( 0 = OK, 1 = NG )
592    /*-----------------------------------------------------------------*/
593    function sfCheckSetTerm ( $start_year, $start_month, $start_day, $end_year, $end_month, $end_day ) {
594
595        // 期間指定
596        $error = 0;
597        if ( $start_month || $start_day || $start_year){
598            if ( ! checkdate($start_month, $start_day , $start_year) ) $error = 1;
599        } else {
600            $error = 1;
601        }
602        if ( $end_month || $end_day || $end_year){
603            if ( ! checkdate($end_month ,$end_day ,$end_year) ) $error = 2;
604        }
605        if ( ! $error ){
606            $date1 = $start_year ."/".sprintf("%02d",$start_month) ."/".sprintf("%02d",$start_day) ." 000000";
607            $date2 = $end_year   ."/".sprintf("%02d",$end_month)   ."/".sprintf("%02d",$end_day)   ." 235959";
608            if ($date1 > $date2) $error = 3;
609        } else {
610            $error = 1;
611        }
612        return array($date1, $date2, $error);
613    }
614
615    // エラー箇所の背景色を変更するためのfunction SC_Viewで読み込む
616    function sfSetErrorStyle(){
617        return 'style="background-color:'.ERR_COLOR.'"';
618    }
619
620    /* DBに渡す数値のチェック
621     * 10桁以上はオーバーフローエラーを起こすので。
622     */
623    function sfCheckNumLength( $value ){
624        if ( ! is_numeric($value)  ){
625            return false;
626        }
627
628        if ( strlen($value) > 9 ) {
629            return false;
630        }
631
632        return true;
633    }
634
635    // 一致した値のキー名を取得
636    function sfSearchKey($array, $word, $default) {
637        foreach($array as $key => $val) {
638            if($val == $word) {
639                return $key;
640            }
641        }
642        return $default;
643    }
644
645    function sfGetErrorColor($val) {
646        if($val != "") {
647            return "background-color:" . ERR_COLOR;
648        }
649        return "";
650    }
651
652    function sfGetEnabled($val) {
653        if( ! $val ) {
654            return " disabled=\"disabled\"";
655        }
656        return "";
657    }
658
659    function sfGetChecked($param, $value) {
660        if($param == $value) {
661            return "checked=\"checked\"";
662        }
663        return "";
664    }
665
666    function sfTrim($str) {
667        $ret = mb_ereg_replace("^[  \n\r]*", "", $str);
668        $ret = mb_ereg_replace("[  \n\r]*$", "", $ret);
669        return $ret;
670    }
671
672    /**
673     * 税金額を返す
674     *
675     * ・店舗基本情報に基づいた計算は SC_Helper_DB::sfTax() を使用する
676     *
677     * @param integer $price 計算対象の金額
678     * @param integer $tax 税率(%単位)
679     *     XXX integer のみか不明
680     * @param integer $tax_rule 端数処理
681     * @return integer 税金額
682     */
683    function sfTax($price, $tax, $tax_rule) {
684        $real_tax = $tax / 100;
685        $ret = $price * $real_tax;
686        switch($tax_rule) {
687        // 四捨五入
688        case 1:
689            $ret = round($ret);
690            break;
691        // 切り捨て
692        case 2:
693            $ret = floor($ret);
694            break;
695        // 切り上げ
696        case 3:
697            $ret = ceil($ret);
698            break;
699        // デフォルト:切り上げ
700        default:
701            $ret = ceil($ret);
702            break;
703        }
704        return $ret;
705    }
706
707    /**
708     * 税金付与した金額を返す
709     *
710     * ・店舗基本情報に基づいた計算は SC_Helper_DB::sfTax() を使用する
711     *
712     * @param integer $price 計算対象の金額
713     * @param integer $tax 税率(%単位)
714     *     XXX integer のみか不明
715     * @param integer $tax_rule 端数処理
716     * @return integer 税金付与した金額
717     */
718    function sfPreTax($price, $tax, $tax_rule) {
719        return $price + SC_Utils_Ex::sfTax($price, $tax, $tax_rule);
720    }
721
722    // 桁数を指定して四捨五入
723    function sfRound($value, $pow = 0){
724        $adjust = pow(10 ,$pow-1);
725
726        // 整数且つ0出なければ桁数指定を行う
727        if(SC_Utils::sfIsInt($adjust) and $pow > 1){
728            $ret = (round($value * $adjust)/$adjust);
729        }
730
731        $ret = round($ret);
732
733        return $ret;
734    }
735
736    /* ポイント付与 */
737    function sfPrePoint($price, $point_rate, $rule = POINT_RULE, $product_id = "") {
738        if(SC_Utils::sfIsInt($product_id)) {
739            $objQuery = new SC_Query();
740            $where = "now() >= cast(start_date as date) AND ";
741            $where .= "now() < cast(end_date as date) AND ";
742
743            $where .= "del_flg = 0 AND campaign_id IN (SELECT campaign_id FROM dtb_campaign_detail where product_id = ? )";
744            //登録(更新)日付順
745            $objQuery->setorder('update_date DESC');
746            //キャンペーンポイントの取得
747            $arrRet = $objQuery->select("campaign_name, campaign_point_rate", "dtb_campaign", $where, array($product_id));
748        }
749        //複数のキャンペーンに登録されている商品は、最新のキャンペーンからポイントを取得
750        if(isset($arrRet[0]['campaign_point_rate'])
751           && $arrRet[0]['campaign_point_rate'] != "") {
752
753            $campaign_point_rate = $arrRet[0]['campaign_point_rate'];
754            $real_point = $campaign_point_rate / 100;
755        } else {
756            $real_point = $point_rate / 100;
757        }
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        if(isset($campaign_point_rate) && $campaign_point_rate != "") {
779            $ret = "(".$arrRet[0]['campaign_name']."ポイント率".$campaign_point_rate."%)".$ret;
780        }
781        return $ret;
782    }
783
784    /* 規格分類の件数取得 */
785    function sfGetClassCatCount() {
786        $sql = "select count(dtb_class.class_id) as count, dtb_class.class_id ";
787        $sql.= "from dtb_class inner join dtb_classcategory on dtb_class.class_id = dtb_classcategory.class_id ";
788        $sql.= "where dtb_class.del_flg = 0 AND dtb_classcategory.del_flg = 0 ";
789        $sql.= "group by dtb_class.class_id, dtb_class.name";
790        $objQuery = new SC_Query();
791        $arrList = $objQuery->getall($sql);
792        // キーと値をセットした配列を取得
793        $arrRet = SC_Utils::sfArrKeyValue($arrList, 'class_id', 'count');
794
795        return $arrRet;
796    }
797
798    function sfGetProductClassId($product_id, $classcategory_id1, $classcategory_id2) {
799        $where = "product_id = ? AND classcategory_id1 = ? AND classcategory_id2 = ?";
800        $objQuery = new SC_Query();
801        $ret = $objQuery->get("dtb_products_class", "product_class_id", $where, Array($product_id, $classcategory_id1, $classcategory_id2));
802        return $ret;
803    }
804
805    /* 文末の「/」をなくす */
806    function sfTrimURL($url) {
807        $ret = ereg_replace("[/]+$", "", $url);
808        return $ret;
809    }
810
811    /* DBから取り出した日付の文字列を調整する。*/
812    function sfDispDBDate($dbdate, $time = true) {
813        list($y, $m, $d, $H, $M) = split("[- :]", $dbdate);
814
815        if(strlen($y) > 0 && strlen($m) > 0 && strlen($d) > 0) {
816            if ($time) {
817                $str = sprintf("%04d/%02d/%02d %02d:%02d", $y, $m, $d, $H, $M);
818            } else {
819                $str = sprintf("%04d/%02d/%02d", $y, $m, $d, $H, $M);
820            }
821        } else {
822            $str = "";
823        }
824        return $str;
825    }
826
827    /* 配列をキー名ごとの配列に変更する */
828    function sfSwapArray($array, $isColumnName = true) {
829        $arrRet = array();
830        $max = count($array);
831        for($i = 0; $i < $max; $i++) {
832            $j = 0;
833            foreach($array[$i] as $key => $val) {
834                if ($isColumnName) {
835                    $arrRet[$key][] = $val;
836                } else {
837                    $arrRet[$j][] = $val;
838                }
839                $j++;
840            }
841        }
842        return $arrRet;
843    }
844
845    /**
846     * 連想配列から新たな配列を生成して返す.
847     *
848     * $requires が指定された場合, $requires に含まれるキーの値のみを返す.
849     *
850     * @param array 連想配列
851     * @param array 必須キーの配列
852     * @return array 連想配列の値のみの配列
853     */
854    function getHash2Array($hash, $requires = array()) {
855        $array = array();
856        $i = 0;
857        foreach ($hash as $key => $val) {
858            if (!empty($requires)) {
859                if (in_array($key, $requires)) {
860                    $array[$i] = $val;
861                    $i++;
862                }
863            } else {
864                $array[$i] = $val;
865                $i++;
866            }
867        }
868        return $array;
869    }
870
871    /* かけ算をする(Smarty用) */
872    function sfMultiply($num1, $num2) {
873        return ($num1 * $num2);
874    }
875
876    // カードの処理結果を返す
877    function sfGetAuthonlyResult($dir, $file_name, $name01, $name02, $card_no, $card_exp, $amount, $order_id, $jpo_info = "10"){
878
879        $path = $dir .$file_name;        // cgiファイルのフルパス生成
880        $now_dir = getcwd();            // requireがうまくいかないので、cgi実行ディレクトリに移動する
881        chdir($dir);
882
883        // パイプ渡しでコマンドラインからcgi起動
884        $cmd = "$path card_no=$card_no name01=$name01 name02=$name02 card_exp=$card_exp amount=$amount order_id=$order_id jpo_info=$jpo_info";
885
886        $tmpResult = popen($cmd, "r");
887
888        // 結果取得
889        while( ! FEOF ( $tmpResult ) ) {
890            $result .= FGETS($tmpResult);
891        }
892        pclose($tmpResult);                //     パイプを閉じる
893        chdir($now_dir);                // 元にいたディレクトリに帰る
894
895        // 結果を連想配列へ格納
896        $result = ereg_replace("&$", "", $result);
897        foreach (explode("&",$result) as $data) {
898            list($key, $val) = explode("=", $data, 2);
899            $return[$key] = $val;
900        }
901
902        return $return;
903    }
904
905    /**
906     * 加算ポイントの計算
907     *
908     * ・店舗基本情報に基づいた計算は SC_Helper_DB::sfGetAddPoint() を使用する
909     *
910     * @param integer $totalpoint
911     * @param integer $use_point
912     * @param integer $point_rate
913     * @return integer 加算ポイント
914     */
915    function sfGetAddPoint($totalpoint, $use_point, $point_rate) {
916        // 購入商品の合計ポイントから利用したポイントのポイント換算価値を引く方式
917        $add_point = $totalpoint - intval($use_point * ($point_rate / 100));
918
919        if($add_point < 0) {
920            $add_point = '0';
921        }
922        return $add_point;
923    }
924
925    /* 一意かつ予測されにくいID */
926    function sfGetUniqRandomId($head = "") {
927        // 予測されないようにランダム文字列を付与する。
928        $random = GC_Utils_Ex::gfMakePassword(8);
929        // 同一ホスト内で一意なIDを生成
930        $id = uniqid($head);
931        return ($id . $random);
932    }
933
934    // 特殊制御文字の手動エスケープ
935    function sfManualEscape($data) {
936        // 配列でない場合
937        if(!is_array($data)) {
938            if (DB_TYPE == "pgsql") {
939                $ret = pg_escape_string($data);
940            }else if(DB_TYPE == "mysql"){
941                $ret = mysql_real_escape_string($data);
942            }
943            $ret = ereg_replace("%", "\\%", $ret);
944            $ret = ereg_replace("_", "\\_", $ret);
945            return $ret;
946        }
947
948        // 配列の場合
949        foreach($data as $val) {
950            if (DB_TYPE == "pgsql") {
951                $ret = pg_escape_string($val);
952            }else if(DB_TYPE == "mysql"){
953                $ret = mysql_real_escape_string($val);
954            }
955
956            $ret = ereg_replace("%", "\\%", $ret);
957            $ret = ereg_replace("_", "\\_", $ret);
958            $arrRet[] = $ret;
959        }
960
961        return $arrRet;
962    }
963
964    /**
965     * ドメイン間で有効なセッションのスタート
966     * 共有SSL対応のための修正により、この関数は廃止します。
967     * セッションはrequire.phpを読み込んだ際に開始されます。
968     */
969    function sfDomainSessionStart() {
970        /**
971         * 2.1.1ベータからはSC_SessionFactory_UseCookie::initSession()で処理するため、
972         * ここでは何も処理しない
973         */
974        if (defined('SESSION_KEEP_METHOD')) {
975            return;
976        }
977
978        if (session_id() === "") {
979
980            session_set_cookie_params(0, "/", DOMAIN_NAME);
981
982            if (!ini_get("session.auto_start")) {
983                // セッション開始
984                session_start();
985            }
986        }
987    }
988
989    /* 文字列に強制的に改行を入れる */
990    function sfPutBR($str, $size) {
991        $i = 0;
992        $cnt = 0;
993        $line = array();
994        $ret = "";
995
996        while($str[$i] != "") {
997            $line[$cnt].=$str[$i];
998            $i++;
999            if(strlen($line[$cnt]) > $size) {
1000                $line[$cnt].="<br />";
1001                $cnt++;
1002            }
1003        }
1004
1005        foreach($line as $val) {
1006            $ret.=$val;
1007        }
1008        return $ret;
1009    }
1010
1011    // 二回以上繰り返されているスラッシュ[/]を一つに変換する。
1012    function sfRmDupSlash($istr){
1013        if(ereg("^http://", $istr)) {
1014            $str = substr($istr, 7);
1015            $head = "http://";
1016        } else if(ereg("^https://", $istr)) {
1017            $str = substr($istr, 8);
1018            $head = "https://";
1019        } else {
1020            $str = $istr;
1021        }
1022        $str = ereg_replace("[/]+", "/", $str);
1023        $ret = $head . $str;
1024        return $ret;
1025    }
1026
1027    /**
1028     * テキストファイルの文字エンコーディングを変換する.
1029     *
1030     * $filepath に存在するテキストファイルの文字エンコーディングを変換する.
1031     * 変換前の文字エンコーディングは, mb_detect_order で設定した順序で自動検出する.
1032     * 変換後は, 変換前のファイル名に「enc_」というプレフィクスを付与し,
1033     * $out_dir で指定したディレクトリへ出力する
1034     *
1035     * TODO $filepath のファイルがバイナリだった場合の扱い
1036     * TODO fwrite などでのエラーハンドリング
1037     *
1038     * @access public
1039     * @param string $filepath 変換するテキストファイルのパス
1040     * @param string $enc_type 変換後のファイルエンコーディングの種類を表す文字列
1041     * @param string $out_dir 変換後のファイルを出力するディレクトリを表す文字列
1042     * @return string 変換後のテキストファイルのパス
1043     */
1044    function sfEncodeFile($filepath, $enc_type, $out_dir) {
1045        $ifp = fopen($filepath, "r");
1046
1047        // 正常にファイルオープンした場合
1048        if ($ifp !== false) {
1049
1050            $basename = basename($filepath);
1051            $outpath = $out_dir . "enc_" . $basename;
1052
1053            $ofp = fopen($outpath, "w+");
1054
1055            while(!feof($ifp)) {
1056                $line = fgets($ifp);
1057                $line = mb_convert_encoding($line, $enc_type, "auto");
1058                fwrite($ofp,  $line);
1059            }
1060
1061            fclose($ofp);
1062            fclose($ifp);
1063        }
1064        // ファイルが開けなかった場合はエラーページを表示
1065          else {
1066              SC_Utils::sfDispError('');
1067              exit;
1068        }
1069        return     $outpath;
1070    }
1071
1072    function sfCutString($str, $len, $byte = true, $commadisp = true) {
1073        if($byte) {
1074            if(strlen($str) > ($len + 2)) {
1075                $ret =substr($str, 0, $len);
1076                $cut = substr($str, $len);
1077            } else {
1078                $ret = $str;
1079                $commadisp = false;
1080            }
1081        } else {
1082            if(mb_strlen($str) > ($len + 1)) {
1083                $ret = mb_substr($str, 0, $len);
1084                $cut = mb_substr($str, $len);
1085            } else {
1086                $ret = $str;
1087                $commadisp = false;
1088            }
1089        }
1090
1091        // 絵文字タグの途中で分断されないようにする。
1092        if (isset($cut)) {
1093            // 分割位置より前の最後の [ 以降を取得する。
1094            $head = strrchr($ret, '[');
1095
1096            // 分割位置より後の最初の ] 以前を取得する。
1097            $tail_pos = strpos($cut, ']');
1098            if ($tail_pos !== false) {
1099                $tail = substr($cut, 0, $tail_pos + 1);
1100            }
1101
1102            // 分割位置より前に [、後に ] が見つかった場合は、[ から ] までを
1103            // 接続して絵文字タグ1個分になるかどうかをチェックする。
1104            if ($head !== false && $tail_pos !== false) {
1105                $subject = $head . $tail;
1106                if (preg_match('/^\[emoji:e?\d+\]$/', $subject)) {
1107                    // 絵文字タグが見つかったので削除する。
1108                    $ret = substr($ret, 0, -strlen($head));
1109                }
1110            }
1111        }
1112
1113        if($commadisp){
1114            $ret = $ret . "...";
1115        }
1116        return $ret;
1117    }
1118
1119    // 年、月、締め日から、先月の締め日+1、今月の締め日を求める。
1120    function sfTermMonth($year, $month, $close_day) {
1121        $end_year = $year;
1122        $end_month = $month;
1123
1124        // 開始月が終了月と同じか否か
1125        $same_month = false;
1126
1127        // 該当月の末日を求める。
1128        $end_last_day = date("d", mktime(0, 0, 0, $month + 1, 0, $year));
1129
1130        // 月の末日が締め日より少ない場合
1131        if($end_last_day < $close_day) {
1132            // 締め日を月末日に合わせる
1133            $end_day = $end_last_day;
1134        } else {
1135            $end_day = $close_day;
1136        }
1137
1138        // 前月の取得
1139        $tmp_year = date("Y", mktime(0, 0, 0, $month, 0, $year));
1140        $tmp_month = date("m", mktime(0, 0, 0, $month, 0, $year));
1141        // 前月の末日を求める。
1142        $start_last_day = date("d", mktime(0, 0, 0, $month, 0, $year));
1143
1144        // 前月の末日が締め日より少ない場合
1145        if ($start_last_day < $close_day) {
1146            // 月末日に合わせる
1147            $tmp_day = $start_last_day;
1148        } else {
1149            $tmp_day = $close_day;
1150        }
1151
1152        // 先月の末日の翌日を取得する
1153        $start_year = date("Y", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1154        $start_month = date("m", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1155        $start_day = date("d", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1156
1157        // 日付の作成
1158        $start_date = sprintf("%d/%d/%d 00:00:00", $start_year, $start_month, $start_day);
1159        $end_date = sprintf("%d/%d/%d 23:59:59", $end_year, $end_month, $end_day);
1160
1161        return array($start_date, $end_date);
1162    }
1163
1164    // PDF用のRGBカラーを返す
1165    function sfGetPdfRgb($hexrgb) {
1166        $hex = substr($hexrgb, 0, 2);
1167        $r = hexdec($hex) / 255;
1168
1169        $hex = substr($hexrgb, 2, 2);
1170        $g = hexdec($hex) / 255;
1171
1172        $hex = substr($hexrgb, 4, 2);
1173        $b = hexdec($hex) / 255;
1174
1175        return array($r, $g, $b);
1176    }
1177
1178    //メルマガ仮登録とメール配信
1179    /*
1180     * FIXME
1181     */
1182    function sfRegistTmpMailData($mail_flag, $email){
1183        $objQuery = new SC_Query();
1184        $objConn = new SC_DBConn();
1185        $objPage = new LC_Page();
1186
1187        $random_id = sfGetUniqRandomId();
1188        $arrRegistMailMagazine["mail_flag"] = $mail_flag;
1189        $arrRegistMailMagazine["email"] = $email;
1190        $arrRegistMailMagazine["temp_id"] =$random_id;
1191        $arrRegistMailMagazine["end_flag"]='0';
1192        $arrRegistMailMagazine["update_date"] = 'now()';
1193
1194        //メルマガ仮登録用フラグ
1195        $flag = $objQuery->count("dtb_customer_mail_temp", "email=?", array($email));
1196        $objConn->query("BEGIN");
1197        switch ($flag){
1198            case '0':
1199            $objConn->autoExecute("dtb_customer_mail_temp",$arrRegistMailMagazine);
1200            break;
1201
1202            case '1':
1203                $objConn->autoExecute("dtb_customer_mail_temp",$arrRegistMailMagazine, "email = " .SC_Utils::sfQuoteSmart($email));
1204            break;
1205        }
1206        $objConn->query("COMMIT");
1207        $subject = 'メルマガ仮登録が完了しました';
1208        $objPage->tpl_url = SSL_URL."mailmagazine/regist.php?temp_id=".$arrRegistMailMagazine['temp_id'];
1209        switch ($mail_flag){
1210            case '1':
1211            $objPage->tpl_name = "登録";
1212            $objPage->tpl_kindname = "HTML";
1213            break;
1214
1215            case '2':
1216            $objPage->tpl_name = "登録";
1217            $objPage->tpl_kindname = "テキスト";
1218            break;
1219
1220            case '3':
1221            $objPage->tpl_name = "解除";
1222            break;
1223        }
1224        $objPage->tpl_email = $email;
1225        sfSendTplMail($email, $subject, 'mail_templates/mailmagazine_temp.tpl', $objPage);
1226    }
1227
1228    // 再帰的に多段配列を検索して一次元配列(Hidden引渡し用配列)に変換する。
1229    function sfMakeHiddenArray($arrSrc, $arrDst = array(), $parent_key = "") {
1230        if(is_array($arrSrc)) {
1231            foreach($arrSrc as $key => $val) {
1232                if($parent_key != "") {
1233                    $keyname = $parent_key . "[". $key . "]";
1234                } else {
1235                    $keyname = $key;
1236                }
1237                if(is_array($val)) {
1238                    $arrDst = SC_Utils::sfMakeHiddenArray($val, $arrDst, $keyname);
1239                } else {
1240                    $arrDst[$keyname] = $val;
1241                }
1242            }
1243        }
1244        return $arrDst;
1245    }
1246
1247    // DB取得日時をタイムに変換
1248    function sfDBDatetoTime($db_date) {
1249        $date = ereg_replace("\..*$","",$db_date);
1250        $time = strtotime($date);
1251        return $time;
1252    }
1253
1254    /**
1255     * テンプレートを切り替えて出力する
1256     *
1257     * @deprecated 2008/04/02以降使用不可
1258     */
1259    function sfCustomDisplay(&$objPage, $is_mobile = false) {
1260        $basename = basename($_SERVER["REQUEST_URI"]);
1261
1262        if($basename == "") {
1263            $path = $_SERVER["REQUEST_URI"] . DIR_INDEX_URL;
1264        } else {
1265            $path = $_SERVER["REQUEST_URI"];
1266        }
1267
1268        if(isset($_GET['tpl']) && $_GET['tpl'] != "") {
1269            $tpl_name = $_GET['tpl'];
1270        } else {
1271            $tpl_name = ereg_replace("^/", "", $path);
1272            $tpl_name = ereg_replace("/", "_", $tpl_name);
1273            $tpl_name = ereg_replace("(\.php$|\.html$)", ".tpl", $tpl_name);
1274        }
1275
1276        $template_path = TEMPLATE_FTP_DIR . $tpl_name;
1277echo $template_path;
1278        if($is_mobile === true) {
1279            $objView = new SC_MobileView();
1280            $objView->assignobj($objPage);
1281            $objView->display(SITE_FRAME);
1282        } else if(file_exists($template_path)) {
1283            $objView = new SC_UserView(TEMPLATE_FTP_DIR, COMPILE_FTP_DIR);
1284            $objView->assignobj($objPage);
1285            $objView->display($tpl_name);
1286        } else {
1287            $objView = new SC_SiteView();
1288            $objView->assignobj($objPage);
1289            $objView->display(SITE_FRAME);
1290        }
1291    }
1292
1293    // PHPのmb_convert_encoding関数をSmartyでも使えるようにする
1294    function sf_mb_convert_encoding($str, $encode = 'CHAR_CODE') {
1295        return  mb_convert_encoding($str, $encode);
1296    }
1297
1298    // PHPのmktime関数をSmartyでも使えるようにする
1299    function sf_mktime($format, $hour=0, $minute=0, $second=0, $month=1, $day=1, $year=1999) {
1300        return  date($format,mktime($hour, $minute, $second, $month, $day, $year));
1301    }
1302
1303    // PHPのdate関数をSmartyでも使えるようにする
1304    function sf_date($format, $timestamp = '') {
1305        return  date( $format, $timestamp);
1306    }
1307
1308    // チェックボックスの型を変換する
1309    function sfChangeCheckBox($data , $tpl = false){
1310        if ($tpl) {
1311            if ($data == 1){
1312                return 'checked';
1313            }else{
1314                return "";
1315            }
1316        }else{
1317            if ($data == "on"){
1318                return 1;
1319            }else{
1320                return 2;
1321            }
1322        }
1323    }
1324
1325    // 2つの配列を用いて連想配列を作成する
1326    function sfarrCombine($arrKeys, $arrValues) {
1327
1328        if(count($arrKeys) <= 0 and count($arrValues) <= 0) return array();
1329
1330        $keys = array_values($arrKeys);
1331        $vals = array_values($arrValues);
1332
1333        $max = max( count( $keys ), count( $vals ) );
1334        $combine_ary = array();
1335        for($i=0; $i<$max; $i++) {
1336            $combine_ary[$keys[$i]] = $vals[$i];
1337        }
1338        if(is_array($combine_ary)) return $combine_ary;
1339
1340        return false;
1341    }
1342
1343    /* 子ID所属する親IDを取得する */
1344    function sfGetParentsArraySub($arrData, $pid_name, $id_name, $child) {
1345        $max = count($arrData);
1346        $parent = "";
1347        for($i = 0; $i < $max; $i++) {
1348            if($arrData[$i][$id_name] == $child) {
1349                $parent = $arrData[$i][$pid_name];
1350                break;
1351            }
1352        }
1353        return $parent;
1354    }
1355
1356    /* 階層構造のテーブルから与えられたIDの兄弟を取得する */
1357    function sfGetBrothersArray($arrData, $pid_name, $id_name, $arrPID) {
1358        $max = count($arrData);
1359
1360        $arrBrothers = array();
1361        foreach($arrPID as $id) {
1362            // 親IDを検索する
1363            for($i = 0; $i < $max; $i++) {
1364                if($arrData[$i][$id_name] == $id) {
1365                    $parent = $arrData[$i][$pid_name];
1366                    break;
1367                }
1368            }
1369            // 兄弟IDを検索する
1370            for($i = 0; $i < $max; $i++) {
1371                if($arrData[$i][$pid_name] == $parent) {
1372                    $arrBrothers[] = $arrData[$i][$id_name];
1373                }
1374            }
1375        }
1376        return $arrBrothers;
1377    }
1378
1379    /* 階層構造のテーブルから与えられたIDの直属の子を取得する */
1380    function sfGetUnderChildrenArray($arrData, $pid_name, $id_name, $parent) {
1381        $max = count($arrData);
1382
1383        $arrChildren = array();
1384        // 子IDを検索する
1385        for($i = 0; $i < $max; $i++) {
1386            if($arrData[$i][$pid_name] == $parent) {
1387                $arrChildren[] = $arrData[$i][$id_name];
1388            }
1389        }
1390        return $arrChildren;
1391    }
1392
1393    // SQLシングルクォート対応
1394    function sfQuoteSmart($in){
1395
1396        if (is_int($in) || is_double($in)) {
1397            return $in;
1398        } elseif (is_bool($in)) {
1399            return $in ? 1 : 0;
1400        } elseif (is_null($in)) {
1401            return 'NULL';
1402        } else {
1403            return "'" . str_replace("'", "''", $in) . "'";
1404        }
1405    }
1406
1407    // ディレクトリを再帰的に生成する
1408    function sfMakeDir($path) {
1409        static $count = 0;
1410        $count++;  // 無限ループ回避
1411        $dir = dirname($path);
1412        if(ereg("^[/]$", $dir) || ereg("^[A-Z]:[\\]$", $dir) || $count > 256) {
1413            // ルートディレクトリで終了
1414            return;
1415        } else {
1416            if(is_writable(dirname($dir))) {
1417                if(!file_exists($dir)) {
1418                    mkdir($dir);
1419                    GC_Utils::gfPrintLog("mkdir $dir");
1420                }
1421            } else {
1422                SC_Utils::sfMakeDir($dir);
1423                if(is_writable(dirname($dir))) {
1424                    if(!file_exists($dir)) {
1425                        mkdir($dir);
1426                        GC_Utils::gfPrintLog("mkdir $dir");
1427                    }
1428                }
1429           }
1430        }
1431        return;
1432    }
1433
1434    // ディレクトリ以下のファイルを再帰的にコピー
1435    function sfCopyDir($src, $des, $mess = "", $override = false){
1436        if(!is_dir($src)){
1437            return false;
1438        }
1439
1440        $oldmask = umask(0);
1441        $mod= stat($src);
1442
1443        // ディレクトリがなければ作成する
1444        if(!file_exists($des)) {
1445            if(!mkdir($des, $mod[2])) {
1446                print("path:" . $des);
1447            }
1448        }
1449
1450        $fileArray=glob( $src."*" );
1451        if (is_array($fileArray)) {
1452            foreach( $fileArray as $key => $data_ ){
1453                // CVS管理ファイルはコピーしない
1454                if(ereg("/CVS/Entries", $data_)) {
1455                    break;
1456                }
1457                if(ereg("/CVS/Repository", $data_)) {
1458                    break;
1459                }
1460                if(ereg("/CVS/Root", $data_)) {
1461                    break;
1462                }
1463
1464                mb_ereg("^(.*[\/])(.*)",$data_, $matches);
1465                $data=$matches[2];
1466                if( is_dir( $data_ ) ){
1467                    $mess = SC_Utils::sfCopyDir( $data_.'/', $des.$data.'/', $mess);
1468                }else{
1469                    if(!$override && file_exists($des.$data)) {
1470                        $mess.= $des.$data . ":ファイルが存在します\n";
1471                    } else {
1472                        if(@copy( $data_, $des.$data)) {
1473                            $mess.= $des.$data . ":コピー成功\n";
1474                        } else {
1475                            $mess.= $des.$data . ":コピー失敗\n";
1476                        }
1477                    }
1478                    $mod=stat($data_ );
1479                }
1480            }
1481        }
1482        umask($oldmask);
1483        return $mess;
1484    }
1485
1486    // 指定したフォルダ内のファイルを全て削除する
1487    function sfDelFile($dir){
1488        if(file_exists($dir)) {
1489            $dh = opendir($dir);
1490            // フォルダ内のファイルを削除
1491            while($file = readdir($dh)){
1492                if ($file == "." or $file == "..") continue;
1493                $del_file = $dir . "/" . $file;
1494                if(is_file($del_file)){
1495                    $ret = unlink($dir . "/" . $file);
1496                }else if (is_dir($del_file)){
1497                    $ret = SC_Utils::sfDelFile($del_file);
1498                }
1499
1500                if(!$ret){
1501                    return $ret;
1502                }
1503            }
1504
1505            // 閉じる
1506            closedir($dh);
1507
1508            // フォルダを削除
1509            return rmdir($dir);
1510        }
1511    }
1512
1513    /*
1514     * 関数名:sfWriteFile
1515     * 引数1 :書き込むデータ
1516     * 引数2 :ファイルパス
1517     * 引数3 :書き込みタイプ
1518     * 引数4 :パーミッション
1519     * 戻り値:結果フラグ 成功なら true 失敗なら false
1520     * 説明 :ファイル書き出し
1521     */
1522    function sfWriteFile($str, $path, $type, $permission = "") {
1523        //ファイルを開く
1524        if (!($file = fopen ($path, $type))) {
1525            return false;
1526        }
1527
1528        //ファイルロック
1529        flock ($file, LOCK_EX);
1530        //ファイルの書き込み
1531        fputs ($file, $str);
1532        //ファイルロックの解除
1533        flock ($file, LOCK_UN);
1534        //ファイルを閉じる
1535        fclose ($file);
1536        // 権限を指定
1537        if($permission != "") {
1538            chmod($path, $permission);
1539        }
1540
1541        return true;
1542    }
1543
1544    /**
1545     * ブラウザに強制的に送出する
1546     *
1547     * @param boolean|string $output 半角スペース256文字+改行を出力するか。または、送信する文字列を指定。
1548     * @return void
1549     */
1550    function sfFlush($output = false, $sleep = 0){
1551        // 出力をバッファリングしない(==日本語自動変換もしない)
1552        while (@ob_end_flush());
1553
1554        if ($output === true) {
1555            // IEのために半角スペース256文字+改行を出力
1556            //echo str_repeat(' ', 256) . "\n";
1557            echo str_pad('', 256) . "\n";
1558        } else if ($output !== false) {
1559            echo $output;
1560        }
1561
1562        // 出力をフラッシュする
1563        flush();
1564
1565        ob_start();
1566
1567        // 時間のかかる処理
1568        sleep($sleep);
1569    }
1570
1571    // @versionの記載があるファイルからバージョンを取得する。
1572    function sfGetFileVersion($path) {
1573        if(file_exists($path)) {
1574            $src_fp = fopen($path, "rb");
1575            if($src_fp) {
1576                while (!feof($src_fp)) {
1577                    $line = fgets($src_fp);
1578                    if(ereg("@version", $line)) {
1579                        $arrLine = split(" ", $line);
1580                        $version = $arrLine[5];
1581                    }
1582                }
1583                fclose($src_fp);
1584            }
1585        }
1586        return $version;
1587    }
1588
1589    // 指定したURLに対してPOSTでデータを送信する
1590    function sfSendPostData($url, $arrData, $arrOkCode = array()){
1591        require_once(DATA_PATH . "module/Request.php");
1592
1593        // 送信インスタンス生成
1594        $req = new HTTP_Request($url);
1595
1596        $req->addHeader('User-Agent', 'DoCoMo/2.0 P2101V(c100)');
1597        $req->setMethod(HTTP_REQUEST_METHOD_POST);
1598
1599        // POSTデータ送信
1600        $req->addPostDataArray($arrData);
1601
1602        // エラーが無ければ、応答情報を取得する
1603        if (!PEAR::isError($req->sendRequest())) {
1604
1605            // レスポンスコードがエラー判定なら、空を返す
1606            $res_code = $req->getResponseCode();
1607
1608            if(!in_array($res_code, $arrOkCode)){
1609                $response = "";
1610            }else{
1611                $response = $req->getResponseBody();
1612            }
1613
1614        } else {
1615            $response = "";
1616        }
1617
1618        // POSTデータクリア
1619        $req->clearPostData();
1620
1621        return $response;
1622    }
1623
1624    /**
1625     * $array の要素を $arrConvList で指定した方式で mb_convert_kana を適用する.
1626     *
1627     * @param array $array 変換する文字列の配列
1628     * @param array $arrConvList mb_convert_kana の適用ルール
1629     * @return array 変換後の配列
1630     * @see mb_convert_kana
1631     */
1632    function mbConvertKanaWithArray($array, $arrConvList) {
1633        foreach ($arrConvList as $key => $val) {
1634            if(isset($array[$key])) {
1635                $array[$key] = mb_convert_kana($array[$key] ,$val);
1636            }
1637        }
1638        return $array;
1639    }
1640
1641    /**
1642     * 配列の添字が未定義の場合は空文字を代入して定義する.
1643     *
1644     * @param array $array 添字をチェックする配列
1645     * @param array $defineIndexes チェックする添字
1646     * @return array 添字を定義した配列
1647     */
1648    function arrayDefineIndexes($array, $defineIndexes) {
1649        foreach ($defineIndexes as $key) {
1650            if (!isset($array[$key])) $array[$key] = "";
1651        }
1652        return $array;
1653    }
1654
1655    /**
1656     * $arrSrc のうち、キーが $arrKey に含まれるものを返す
1657     *
1658     * $arrSrc に含まない要素は返されない。
1659     *
1660     * @param array $arrSrc
1661     * @param array $arrKey
1662     * @return array
1663     */
1664    function sfArrayIntersectKeys($arrSrc, $arrKey) {
1665        $arrRet = array();
1666        foreach ($arrKey as $key) {
1667            if (isset($arrSrc[$key])) $arrRet[$key] = $arrSrc[$key];
1668        }
1669        return $arrRet;
1670    }
1671
1672    /**
1673     * XML宣言を出力する.
1674     *
1675     * XML宣言があると問題が発生する UA は出力しない.
1676     *
1677     * @return string XML宣言の文字列
1678     */
1679    function printXMLDeclaration() {
1680        $ua = $_SERVER['HTTP_USER_AGENT'];
1681        if (!preg_match("/MSIE/", $ua) || preg_match("/MSIE 7/", $ua)) {
1682            print("<?xml version='1.0' encoding='" . CHAR_CODE . "'?>\n");
1683        }
1684    }
1685
1686    /*
1687     * 関数名:sfGetFileList()
1688     * 説明 :指定パス配下のディレクトリ取得
1689     * 引数1 :取得するディレクトリパス
1690     */
1691    function sfGetFileList($dir) {
1692        $arrFileList = array();
1693        $arrDirList = array();
1694
1695        if (is_dir($dir)) {
1696            if ($dh = opendir($dir)) {
1697                $cnt = 0;
1698                // 行末の/を取り除く
1699                while (($file = readdir($dh)) !== false) $arrDir[] = $file;
1700                $dir = ereg_replace("/$", "", $dir);
1701                // アルファベットと数字でソート
1702                natcasesort($arrDir);
1703                foreach($arrDir as $file) {
1704                    // ./ と ../を除くファイルのみを取得
1705                    if($file != "." && $file != "..") {
1706
1707                        $path = $dir."/".$file;
1708                        // SELECT内の見た目を整えるため指定文字数で切る
1709                        $file_name = SC_Utils::sfCutString($file, FILE_NAME_LEN);
1710                        $file_size = SC_Utils::sfCutString(SC_Utils::sfGetDirSize($path), FILE_NAME_LEN);
1711                        $file_time = date("Y/m/d", filemtime($path));
1712
1713                        // ディレクトリとファイルで格納配列を変える
1714                        if(is_dir($path)) {
1715                            $arrDirList[$cnt]['file_name'] = $file;
1716                            $arrDirList[$cnt]['file_path'] = $path;
1717                            $arrDirList[$cnt]['file_size'] = $file_size;
1718                            $arrDirList[$cnt]['file_time'] = $file_time;
1719                            $arrDirList[$cnt]['is_dir'] = true;
1720                        } else {
1721                            $arrFileList[$cnt]['file_name'] = $file;
1722                            $arrFileList[$cnt]['file_path'] = $path;
1723                            $arrFileList[$cnt]['file_size'] = $file_size;
1724                            $arrFileList[$cnt]['file_time'] = $file_time;
1725                            $arrFileList[$cnt]['is_dir'] = false;
1726                        }
1727                        $cnt++;
1728                    }
1729                }
1730                closedir($dh);
1731            }
1732        }
1733
1734        // フォルダを先頭にしてマージ
1735        return array_merge($arrDirList, $arrFileList);
1736    }
1737
1738    /*
1739     * 関数名:sfGetDirSize()
1740     * 説明 :指定したディレクトリのバイト数を取得
1741     * 引数1 :ディレクトリ
1742     */
1743    function sfGetDirSize($dir) {
1744        if(file_exists($dir)) {
1745            // ディレクトリの場合下層ファイルの総量を取得
1746            if (is_dir($dir)) {
1747                $handle = opendir($dir);
1748                while ($file = readdir($handle)) {
1749                    // 行末の/を取り除く
1750                    $dir = ereg_replace("/$", "", $dir);
1751                    $path = $dir."/".$file;
1752                    if ($file != '..' && $file != '.' && !is_dir($path)) {
1753                        $bytes += filesize($path);
1754                    } else if (is_dir($path) && $file != '..' && $file != '.') {
1755                        // 下層ファイルのバイト数を取得する為、再帰的に呼び出す。
1756                        $bytes += SC_Utils::sfGetDirSize($path);
1757                    }
1758                }
1759            } else {
1760                // ファイルの場合
1761                $bytes = filesize($dir);
1762            }
1763        }
1764        // ディレクトリ(ファイル)が存在しない場合は0byteを返す
1765        if($bytes == "") $bytes = 0;
1766
1767        return $bytes;
1768    }
1769
1770    /*
1771     * 関数名:sfDeleteDir()
1772     * 説明 :指定したディレクトリを削除
1773     * 引数1 :削除ファイル
1774     */
1775    function sfDeleteDir($dir) {
1776        $arrResult = array();
1777        if(file_exists($dir)) {
1778            // ディレクトリかチェック
1779            if (is_dir($dir)) {
1780                if ($handle = opendir("$dir")) {
1781                    $cnt = 0;
1782                    while (false !== ($item = readdir($handle))) {
1783                        if ($item != "." && $item != "..") {
1784                            if (is_dir("$dir/$item")) {
1785                                sfDeleteDir("$dir/$item");
1786                            } else {
1787                                $arrResult[$cnt]['result'] = @unlink("$dir/$item");
1788                                $arrResult[$cnt]['file_name'] = "$dir/$item";
1789                            }
1790                        }
1791                        $cnt++;
1792                    }
1793                }
1794                closedir($handle);
1795                $arrResult[$cnt]['result'] = @rmdir($dir);
1796                $arrResult[$cnt]['file_name'] = "$dir/$item";
1797            } else {
1798                // ファイル削除
1799                $arrResult[0]['result'] = @unlink("$dir");
1800                $arrResult[0]['file_name'] = "$dir";
1801            }
1802        }
1803
1804        return $arrResult;
1805    }
1806
1807    /*
1808     * 関数名:sfGetFileTree()
1809     * 説明 :ツリー生成用配列取得(javascriptに渡す用)
1810     * 引数1 :ディレクトリ
1811     * 引数2 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1812     */
1813    function sfGetFileTree($dir, $tree_status) {
1814
1815        $cnt = 0;
1816        $arrTree = array();
1817        $default_rank = count(split('/', $dir));
1818
1819        // 文末の/を取り除く
1820        $dir = ereg_replace("/$", "", $dir);
1821        // 最上位層を格納(user_data/)
1822        if(sfDirChildExists($dir)) {
1823            $arrTree[$cnt]['type'] = "_parent";
1824        } else {
1825            $arrTree[$cnt]['type'] = "_child";
1826        }
1827        $arrTree[$cnt]['path'] = $dir;
1828        $arrTree[$cnt]['rank'] = 0;
1829        $arrTree[$cnt]['count'] = $cnt;
1830        // 初期表示はオープン
1831        if($_POST['mode'] != '') {
1832            $arrTree[$cnt]['open'] = lfIsFileOpen($dir, $tree_status);
1833        } else {
1834            $arrTree[$cnt]['open'] = true;
1835        }
1836        $cnt++;
1837
1838        sfGetFileTreeSub($dir, $default_rank, $cnt, $arrTree, $tree_status);
1839
1840        return $arrTree;
1841    }
1842
1843    /*
1844     * 関数名:sfGetFileTree()
1845     * 説明 :ツリー生成用配列取得(javascriptに渡す用)
1846     * 引数1 :ディレクトリ
1847     * 引数2 :デフォルトの階層(/区切りで 0,1,2・・・とカウント)
1848     * 引数3 :連番
1849     * 引数4 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1850     */
1851    function sfGetFileTreeSub($dir, $default_rank, &$cnt, &$arrTree, $tree_status) {
1852
1853        if(file_exists($dir)) {
1854            if ($handle = opendir("$dir")) {
1855                while (false !== ($item = readdir($handle))) $arrDir[] = $item;
1856                // アルファベットと数字でソート
1857                natcasesort($arrDir);
1858                foreach($arrDir as $item) {
1859                    if ($item != "." && $item != "..") {
1860                        // 文末の/を取り除く
1861                        $dir = ereg_replace("/$", "", $dir);
1862                        $path = $dir."/".$item;
1863                        // ディレクトリのみ取得
1864                        if (is_dir($path)) {
1865                            $arrTree[$cnt]['path'] = $path;
1866                            if(sfDirChildExists($path)) {
1867                                $arrTree[$cnt]['type'] = "_parent";
1868                            } else {
1869                                $arrTree[$cnt]['type'] = "_child";
1870                            }
1871
1872                            // 階層を割り出す
1873                            $arrCnt = split('/', $path);
1874                            $rank = count($arrCnt);
1875                            $arrTree[$cnt]['rank'] = $rank - $default_rank + 1;
1876                            $arrTree[$cnt]['count'] = $cnt;
1877                            // フォルダが開いているか
1878                            $arrTree[$cnt]['open'] = lfIsFileOpen($path, $tree_status);
1879                            $cnt++;
1880                            // 下層ディレクトリ取得の為、再帰的に呼び出す
1881                            sfGetFileTreeSub($path, $default_rank, $cnt, $arrTree, $tree_status);
1882                        }
1883                    }
1884                }
1885            }
1886            closedir($handle);
1887        }
1888    }
1889
1890    /*
1891     * 関数名:sfDirChildExists()
1892     * 説明 :指定したディレクトリ配下にファイルがあるか
1893     * 引数1 :ディレクトリ
1894     */
1895    function sfDirChildExists($dir) {
1896        if(file_exists($dir)) {
1897            if (is_dir($dir)) {
1898                $handle = opendir($dir);
1899                while ($file = readdir($handle)) {
1900                    // 行末の/を取り除く
1901                    $dir = ereg_replace("/$", "", $dir);
1902                    $path = $dir."/".$file;
1903                    if ($file != '..' && $file != '.' && is_dir($path)) {
1904                        return true;
1905                    }
1906                }
1907            }
1908        }
1909
1910        return false;
1911    }
1912
1913    /*
1914     * 関数名:lfIsFileOpen()
1915     * 説明 :指定したファイルが前回開かれた状態にあったかチェック
1916     * 引数1 :ディレクトリ
1917     * 引数2 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1918     */
1919    function lfIsFileOpen($dir, $tree_status) {
1920        $arrTreeStatus = split('\|', $tree_status);
1921        if(in_array($dir, $arrTreeStatus)) {
1922            return true;
1923        }
1924
1925        return false;
1926    }
1927
1928    /*
1929     * 関数名:sfDownloadFile()
1930     * 引数1 :ファイルパス
1931     * 説明 :ファイルのダウンロード
1932     */
1933    function sfDownloadFile($file) {
1934         // ファイルの場合はダウンロードさせる
1935        Header("Content-disposition: attachment; filename=".basename($file));
1936        Header("Content-type: application/octet-stream; name=".basename($file));
1937        Header("Cache-Control: ");
1938        Header("Pragma: ");
1939        echo (sfReadFile($file));
1940    }
1941
1942    /*
1943     * 関数名:sfCreateFile()
1944     * 引数1 :ファイルパス
1945     * 引数2 :パーミッション
1946     * 説明 :ファイル作成
1947     */
1948    function sfCreateFile($file, $mode = "") {
1949        // 行末の/を取り除く
1950        if($mode != "") {
1951            $ret = @mkdir($file, $mode);
1952        } else {
1953            $ret = @mkdir($file);
1954        }
1955
1956        return $ret;
1957    }
1958
1959    /*
1960     * 関数名:sfReadFile()
1961     * 引数1 :ファイルパス
1962     * 説明 :ファイル読込
1963     */
1964    function sfReadFile($filename) {
1965        $str = "";
1966        // バイナリモードでオープン
1967        $fp = @fopen($filename, "rb" );
1968        //ファイル内容を全て変数に読み込む
1969        if($fp) {
1970            $str = @fread($fp, filesize($filename)+1);
1971        }
1972        @fclose($fp);
1973
1974        return $str;
1975    }
1976
1977   /**
1978     * CSV出力用データ取得
1979     *
1980     * @return string
1981     */
1982    function getCSVData($array, $arrayIndex) {
1983        for ($i = 0; $i < count($array); $i++){
1984            // インデックスが設定されている場合
1985            if (is_array($arrayIndex) && 0 < count($arrayIndex)){
1986                for ($j = 0; $j < count($arrayIndex); $j++ ){
1987                    if ( $j > 0 ) $return .= ",";
1988                    $return .= "\"";
1989                    $return .= mb_ereg_replace("<","<",mb_ereg_replace( "\"","\"\"",$array[$i][$arrayIndex[$j]] )) ."\"";
1990                }
1991            } else {
1992                for ($j = 0; $j < count($array[$i]); $j++ ){
1993                    if ( $j > 0 ) $return .= ",";
1994                    $return .= "\"";
1995                    $return .= mb_ereg_replace("<","<",mb_ereg_replace( "\"","\"\"",$array[$i][$j] )) ."\"";
1996                }
1997            }
1998            $return .= "\n";
1999        }
2000        return $return;
2001    }
2002
2003   /**
2004     * 配列をテーブルタグで出力する。
2005     *
2006     * @return string
2007     */
2008    function getTableTag($array) {
2009        $html = "<table>";
2010        $html.= "<tr>";
2011        foreach($array[0] as $key => $val) {
2012            $html.="<th>$key</th>";
2013        }
2014        $html.= "</tr>";
2015
2016        $cnt = count($array);
2017
2018        for($i = 0; $i < $cnt; $i++) {
2019            $html.= "<tr>";
2020            foreach($array[$i] as $val) {
2021                $html.="<td>$val</td>";
2022            }
2023            $html.= "</tr>";
2024        }
2025        return $html;
2026    }
2027
2028   /**
2029     * 一覧-メイン画像のファイル指定がない場合、専用の画像ファイルに書き換える。
2030     *
2031     * @param string &$filename ファイル名
2032     * @return string
2033     */
2034    function sfNoImageMainList($filename = '') {
2035        if (strlen($filename) == 0 || substr($filename, -1, 1) == '/') {
2036            $filename .= 'noimage_main_list.jpg';
2037        }
2038        return $filename;
2039    }
2040
2041   /**
2042     * 詳細-メイン画像のファイル指定がない場合、専用の画像ファイルに書き換える。
2043     *
2044     * @param string &$filename ファイル名
2045     * @return string
2046     */
2047    function sfNoImageMain($filename = '') {
2048        if (strlen($filename) == 0 || substr($filename, -1, 1) == '/') {
2049            $filename .= 'noimage_main.png';
2050        }
2051        return $filename;
2052    }
2053
2054    /* デバッグ用 ------------------------------------------------------------------------------------------------*/
2055    function sfPrintR($obj) {
2056        print("<div style='font-size: 12px;color: #00FF00;'>\n");
2057        print("<strong>**デバッグ中**</strong><br />\n");
2058        print("<pre>\n");
2059        //print_r($obj);
2060        var_dump($obj);
2061        print("</pre>\n");
2062        print("<strong>**デバッグ中**</strong></div>\n");
2063    }
2064
2065    /**
2066     * ポイント使用するかの判定
2067     *
2068     * @param integer $status 対応状況
2069     * @return boolean 使用するか(顧客テーブルから減算するか)
2070     */
2071    function sfIsUsePoint($status) {
2072        switch ($status) {
2073            case ORDER_CANCEL:      // キャンセル
2074                return false;
2075            default:
2076                break;
2077        }
2078
2079        return true;
2080    }
2081
2082    /**
2083     * ポイント加算するかの判定
2084     *
2085     * @param integer $status 対応状況
2086     * @return boolean 加算するか
2087     */
2088    function sfIsAddPoint($status) {
2089        switch ($status) {
2090            case ORDER_NEW:         // 新規注文
2091            case ORDER_PAY_WAIT:    // 入金待ち
2092            case ORDER_PRE_END:     // 入金済み
2093            case ORDER_CANCEL:      // キャンセル
2094            case ORDER_BACK_ORDER:  // 取り寄せ中
2095                return false;
2096           
2097            case ORDER_DELIV:       // 発送済み
2098                return true;
2099           
2100            default:
2101                break;
2102        }
2103
2104        return false;
2105    }
2106
2107    /**
2108     * ランダムな文字列を取得する
2109     *
2110     * @param integer $length 文字数
2111     * @return string ランダムな文字列
2112     */
2113    function sfGetRandomString($length = 1) {
2114        require_once(dirname(__FILE__) . '/../../module/Text/Password.php');
2115        return Text_Password::create($length);
2116    }
2117   
2118    /**
2119     * 現在の URL を取得する
2120     *
2121     * @return string 現在のURL
2122     */
2123    function sfGetUrl() {
2124        $url = '';
2125       
2126        if (SC_Utils_Ex::sfIsHTTPS()) {
2127            $url = "https://";
2128        } else {
2129            $url = "http://";
2130        }
2131       
2132        $url .= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?' . $_SERVER['QUERY_STRING'];
2133       
2134        return $url;
2135    }
2136   
2137    /**
2138     * バックトレースをテキスト形式で出力する
2139     *
2140     * @return string テキストで表現したバックトレース
2141     */
2142    function sfBacktraceToString($arrBacktrace) {
2143        $string = '';
2144       
2145        foreach ($arrBacktrace as $backtrace) {
2146            if (strlen($backtrace['class']) >= 1) {
2147                $func = $backtrace['class'] . $backtrace['type'] . $backtrace['function'];
2148            } else {
2149                $func = $backtrace['function'];
2150            }
2151           
2152            $string .= $backtrace['file'] . " " . $backtrace['line'] . ":" . $func . "\n";
2153        }
2154       
2155        return $string;
2156    }
2157
2158    /**
2159     * 管理機能かを判定
2160     *
2161     * @return bool 管理機能か
2162     */
2163    function sfIsAdminFunction() {
2164        return defined('ADMIN_FUNCTION') && ADMIN_FUNCTION;
2165    }
2166
2167    /**
2168     * フロント機能かを判定
2169     *
2170     * @return bool フロント機能か
2171     */
2172    function sfIsFrontFunction() {
2173        return SC_Utils_Ex::sfIsPcSite() || SC_Utils_Ex::sfIsMobileSite();
2174    }
2175
2176    /**
2177     * フロント機能PCサイトかを判定
2178     *
2179     * @return bool フロント機能PCサイトか
2180     */
2181    function sfIsPcSite() {
2182        return defined('FRONT_FUNCTION_PC_SITE') && FRONT_FUNCTION_PC_SITE;
2183    }
2184
2185    /**
2186     * フロント機能モバイル機能かを判定
2187     *
2188     * @return bool フロント機能モバイル機能か
2189     */
2190    function sfIsMobileSite() {
2191        return defined('MOBILE_SITE') && MOBILE_SITE;
2192    }
2193
2194    /**
2195     * インストール機能かを判定
2196     *
2197     * @return bool インストール機能か
2198     */
2199    function sfIsInstallFunction() {
2200        return defined('INSTALL_FUNCTION') && INSTALL_FUNCTION;
2201    }
2202
2203    // 郵便番号から住所の取得
2204    function sfGetAddress($zipcode) {
2205
2206        $conn = new SC_DBconn(ZIP_DSN);
2207
2208        $masterData = new SC_DB_MasterData_Ex();
2209        $arrPref = $masterData->getMasterData("mtb_pref", array("pref_id", "pref_name", "rank"));
2210        // インデックスと値を反転させる。
2211        $arrREV_PREF = array_flip($arrPref);
2212
2213        // 郵便番号検索文作成
2214        $zipcode = mb_convert_kana($zipcode ,"n");
2215        $sqlse = "SELECT state, city, town FROM mtb_zip WHERE zipcode = ?";
2216
2217        $data_list = $conn->getAll($sqlse, array($zipcode));
2218        if (empty($data_list)) return array();
2219
2220        /*
2221         総務省からダウンロードしたデータをそのままインポートすると
2222         以下のような文字列が入っているので 対策する。
2223         ・(1・19丁目)
2224         ・以下に掲載がない場合
2225        */
2226        $town =  $data_list[0]['town'];
2227        $town = ereg_replace("(.*)$","",$town);
2228        $town = ereg_replace("以下に掲載がない場合","",$town);
2229        $data_list[0]['town'] = $town;
2230        $data_list[0]['state'] = $arrREV_PREF[$data_list[0]['state']];
2231
2232        return $data_list;
2233    }
2234
2235    /**
2236     * プラグインが配置されているディレクトリ(フルパス)を取得する
2237     *
2238     * @param string $file プラグイン情報ファイル(info.php)のパス
2239     * @return SimpleXMLElement プラグイン XML
2240     */
2241    function sfGetPluginFullPathByRequireFilePath($file) {
2242        return str_replace('\\', '/', dirname($file)) . '/';
2243    }
2244
2245    /**
2246     * プラグインのパスを取得する
2247     *
2248     * @param string $pluginFullPath プラグインが配置されているディレクトリ(フルパス)
2249     * @return SimpleXMLElement プラグイン XML
2250     */
2251    function sfGetPluginPathByPluginFullPath($pluginFullPath) {
2252        return basename(rtrim($pluginFullPath, '/'));
2253    }
2254
2255    /**
2256     * プラグイン情報配列の基本形を作成する
2257     *
2258     * @param string $file プラグイン情報ファイル(info.php)のパス
2259     * @return array プラグイン情報配列
2260     */
2261    function sfMakePluginInfoArray($file) {
2262        $fullPath = SC_Utils_Ex::sfGetPluginFullPathByRequireFilePath($file);
2263
2264        return
2265            array(
2266                // パス
2267                'path' => SC_Utils_Ex::sfGetPluginPathByPluginFullPath($fullPath),
2268                // プラグイン名
2269                'name' => '未定義',
2270                // フルパス
2271                'fullpath' => $fullPath,
2272                // バージョン
2273                'version' => null,
2274                // 著作者
2275                'auther' => '未定義',
2276            )
2277        ;
2278    }
2279
2280    /**
2281     * プラグイン情報配列を取得する
2282     *
2283     * TODO include_once を利用することで例外対応をサボタージュしているのを改善する。
2284     *
2285     * @param string $path プラグインのディレクトリ名
2286     * @return array プラグイン情報配列
2287     */
2288    function sfGetPluginInfoArray($path) {
2289        return (array)include_once(PLUGIN_PATH . "$path/plugin_info.php");
2290    }
2291
2292    /**
2293     * プラグイン XML を読み込む
2294     *
2295     * TODO 空だったときを考慮
2296     *
2297     * @return SimpleXMLElement プラグイン XML
2298     */
2299    function sfGetPluginsXml() {
2300        return simplexml_load_file(PLUGIN_PATH . 'plugins.xml');
2301    }
2302
2303    /**
2304     * プラグイン XML を書き込む
2305     *
2306     * @param SimpleXMLElement $pluginsXml プラグイン XML
2307     * @return integer ファイルに書き込まれたバイト数を返します。
2308     */
2309    function sfPutPluginsXml($pluginsXml) {
2310        if (!($pluginsXml instanceof SimpleXMLElement)) SC_Utils_Ex::sfDispException();
2311
2312        $xml = $pluginsXml->asXML();
2313        if (strlen($xml) == 0) SC_Utils_Ex::sfDispException();
2314
2315        $return = file_put_contents(PLUGIN_PATH . 'plugins.xml', $pluginsXml->asXML());
2316        if ($return === false) SC_Utils_Ex::sfDispException();
2317
2318        return $return;
2319    }
2320
2321    function sfLoadPluginInfo($filenamePluginInfo) {
2322        return (array)include_once $filenamePluginInfo;
2323    }
2324}
2325?>
Note: See TracBrowser for help on using the repository browser.