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

Revision 17118, 63.1 KB checked in by adachi, 15 years ago (diff)

共有SSL対応

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