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

Revision 18699, 67.3 KB checked in by nanasess, 14 years ago (diff)

Copyright の更新(#601)

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