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

Revision 18530, 68.7 KB checked in by nanasess, 14 years ago (diff)

merged r18482, r18492

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