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

Revision 18432, 67.9 KB checked in by kajiwara, 14 years ago (diff)

EC-CUBE Ver2.4.2 分コミット。詳細はこちら( http://www.ec-cube.net/release/detail.php?release_id=207

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