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

Revision 18735, 68.4 KB checked in by nanasess, 14 years ago (diff)

関数の命名規則の統一(#700)

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