source: branches/version-2_4-dev/data/class/util/SC_Utils.php @ 18565

Revision 18565, 66.6 KB checked in by shutta, 16 years ago (diff)

r18564 の修正。
HTML_PATH=DOCUMENT_ROOTかつ、DOCUMENT_ROOTの設定が/で終わっている場合に不具合があったので修正。

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