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

Revision 17199, 63.7 KB checked in by satou, 16 years ago (diff)

SC_Utils::sfCustomDisplay@deprecated

  • 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         * 2.1.1ベータからはSC_SessionFactory_UseCookie::initSession()で処理するため、
966         * ここでは何も処理しない
967         */
968        if (defined('SESSION_KEEP_METHOD')) {
969            return;
970        }
971
972        if (session_id() === "") {
973
974            session_set_cookie_params(0, "/", DOMAIN_NAME);
975
976            if (!ini_get("session.auto_start")) {
977                // セッション開始
978                session_start();
979            }
980        }
981    }
982
983    /* 文字列に強制的に改行を入れる */
984    function sfPutBR($str, $size) {
985        $i = 0;
986        $cnt = 0;
987        $line = array();
988        $ret = "";
989
990        while($str[$i] != "") {
991            $line[$cnt].=$str[$i];
992            $i++;
993            if(strlen($line[$cnt]) > $size) {
994                $line[$cnt].="<br />";
995                $cnt++;
996            }
997        }
998
999        foreach($line as $val) {
1000            $ret.=$val;
1001        }
1002        return $ret;
1003    }
1004
1005    // 二回以上繰り返されているスラッシュ[/]を一つに変換する。
1006    function sfRmDupSlash($istr){
1007        if(ereg("^http://", $istr)) {
1008            $str = substr($istr, 7);
1009            $head = "http://";
1010        } else if(ereg("^https://", $istr)) {
1011            $str = substr($istr, 8);
1012            $head = "https://";
1013        } else {
1014            $str = $istr;
1015        }
1016        $str = ereg_replace("[/]+", "/", $str);
1017        $ret = $head . $str;
1018        return $ret;
1019    }
1020
1021    function sfEncodeFile($filepath, $enc_type, $out_dir) {
1022        $ifp = fopen($filepath, "r");
1023
1024        $basename = basename($filepath);
1025        $outpath = $out_dir . "enc_" . $basename;
1026
1027        $ofp = fopen($outpath, "w+");
1028
1029        while(!feof($ifp)) {
1030            $line = fgets($ifp);
1031            $line = mb_convert_encoding($line, $enc_type, "auto");
1032            fwrite($ofp,  $line);
1033        }
1034
1035        fclose($ofp);
1036        fclose($ifp);
1037
1038        return     $outpath;
1039    }
1040
1041    function sfCutString($str, $len, $byte = true, $commadisp = true) {
1042        if($byte) {
1043            if(strlen($str) > ($len + 2)) {
1044                $ret =substr($str, 0, $len);
1045                $cut = substr($str, $len);
1046            } else {
1047                $ret = $str;
1048                $commadisp = false;
1049            }
1050        } else {
1051            if(mb_strlen($str) > ($len + 1)) {
1052                $ret = mb_substr($str, 0, $len);
1053                $cut = mb_substr($str, $len);
1054            } else {
1055                $ret = $str;
1056                $commadisp = false;
1057            }
1058        }
1059
1060        // 絵文字タグの途中で分断されないようにする。
1061        if (isset($cut)) {
1062            // 分割位置より前の最後の [ 以降を取得する。
1063            $head = strrchr($ret, '[');
1064
1065            // 分割位置より後の最初の ] 以前を取得する。
1066            $tail_pos = strpos($cut, ']');
1067            if ($tail_pos !== false) {
1068                $tail = substr($cut, 0, $tail_pos + 1);
1069            }
1070
1071            // 分割位置より前に [、後に ] が見つかった場合は、[ から ] までを
1072            // 接続して絵文字タグ1個分になるかどうかをチェックする。
1073            if ($head !== false && $tail_pos !== false) {
1074                $subject = $head . $tail;
1075                if (preg_match('/^\[emoji:e?\d+\]$/', $subject)) {
1076                    // 絵文字タグが見つかったので削除する。
1077                    $ret = substr($ret, 0, -strlen($head));
1078                }
1079            }
1080        }
1081
1082        if($commadisp){
1083            $ret = $ret . "...";
1084        }
1085        return $ret;
1086    }
1087
1088    // 年、月、締め日から、先月の締め日+1、今月の締め日を求める。
1089    function sfTermMonth($year, $month, $close_day) {
1090        $end_year = $year;
1091        $end_month = $month;
1092
1093        // 開始月が終了月と同じか否か
1094        $same_month = false;
1095
1096        // 該当月の末日を求める。
1097        $end_last_day = date("d", mktime(0, 0, 0, $month + 1, 0, $year));
1098
1099        // 月の末日が締め日より少ない場合
1100        if($end_last_day < $close_day) {
1101            // 締め日を月末日に合わせる
1102            $end_day = $end_last_day;
1103        } else {
1104            $end_day = $close_day;
1105        }
1106
1107        // 前月の取得
1108        $tmp_year = date("Y", mktime(0, 0, 0, $month, 0, $year));
1109        $tmp_month = date("m", mktime(0, 0, 0, $month, 0, $year));
1110        // 前月の末日を求める。
1111        $start_last_day = date("d", mktime(0, 0, 0, $month, 0, $year));
1112
1113        // 前月の末日が締め日より少ない場合
1114        if ($start_last_day < $close_day) {
1115            // 月末日に合わせる
1116            $tmp_day = $start_last_day;
1117        } else {
1118            $tmp_day = $close_day;
1119        }
1120
1121        // 先月の末日の翌日を取得する
1122        $start_year = date("Y", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1123        $start_month = date("m", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1124        $start_day = date("d", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1125
1126        // 日付の作成
1127        $start_date = sprintf("%d/%d/%d 00:00:00", $start_year, $start_month, $start_day);
1128        $end_date = sprintf("%d/%d/%d 23:59:59", $end_year, $end_month, $end_day);
1129
1130        return array($start_date, $end_date);
1131    }
1132
1133    // PDF用のRGBカラーを返す
1134    function sfGetPdfRgb($hexrgb) {
1135        $hex = substr($hexrgb, 0, 2);
1136        $r = hexdec($hex) / 255;
1137
1138        $hex = substr($hexrgb, 2, 2);
1139        $g = hexdec($hex) / 255;
1140
1141        $hex = substr($hexrgb, 4, 2);
1142        $b = hexdec($hex) / 255;
1143
1144        return array($r, $g, $b);
1145    }
1146
1147    //メルマガ仮登録とメール配信
1148    /*
1149     * FIXME
1150     */
1151    function sfRegistTmpMailData($mail_flag, $email){
1152        $objQuery = new SC_Query();
1153        $objConn = new SC_DBConn();
1154        $objPage = new LC_Page();
1155
1156        $random_id = sfGetUniqRandomId();
1157        $arrRegistMailMagazine["mail_flag"] = $mail_flag;
1158        $arrRegistMailMagazine["email"] = $email;
1159        $arrRegistMailMagazine["temp_id"] =$random_id;
1160        $arrRegistMailMagazine["end_flag"]='0';
1161        $arrRegistMailMagazine["update_date"] = 'now()';
1162
1163        //メルマガ仮登録用フラグ
1164        $flag = $objQuery->count("dtb_customer_mail_temp", "email=?", array($email));
1165        $objConn->query("BEGIN");
1166        switch ($flag){
1167            case '0':
1168            $objConn->autoExecute("dtb_customer_mail_temp",$arrRegistMailMagazine);
1169            break;
1170
1171            case '1':
1172                $objConn->autoExecute("dtb_customer_mail_temp",$arrRegistMailMagazine, "email = " .SC_Utils::sfQuoteSmart($email));
1173            break;
1174        }
1175        $objConn->query("COMMIT");
1176        $subject = sfMakeSubject('メルマガ仮登録が完了しました。');
1177        $objPage->tpl_url = SSL_URL."mailmagazine/regist.php?temp_id=".$arrRegistMailMagazine['temp_id'];
1178        switch ($mail_flag){
1179            case '1':
1180            $objPage->tpl_name = "登録";
1181            $objPage->tpl_kindname = "HTML";
1182            break;
1183
1184            case '2':
1185            $objPage->tpl_name = "登録";
1186            $objPage->tpl_kindname = "テキスト";
1187            break;
1188
1189            case '3':
1190            $objPage->tpl_name = "解除";
1191            break;
1192        }
1193            $objPage->tpl_email = $email;
1194        sfSendTplMail($email, $subject, 'mail_templates/mailmagazine_temp.tpl', $objPage);
1195    }
1196
1197    // 再帰的に多段配列を検索して一次元配列(Hidden引渡し用配列)に変換する。
1198    function sfMakeHiddenArray($arrSrc, $arrDst = array(), $parent_key = "") {
1199        if(is_array($arrSrc)) {
1200            foreach($arrSrc as $key => $val) {
1201                if($parent_key != "") {
1202                    $keyname = $parent_key . "[". $key . "]";
1203                } else {
1204                    $keyname = $key;
1205                }
1206                if(is_array($val)) {
1207                    $arrDst = SC_Utils::sfMakeHiddenArray($val, $arrDst, $keyname);
1208                } else {
1209                    $arrDst[$keyname] = $val;
1210                }
1211            }
1212        }
1213        return $arrDst;
1214    }
1215
1216    // DB取得日時をタイムに変換
1217    function sfDBDatetoTime($db_date) {
1218        $date = ereg_replace("\..*$","",$db_date);
1219        $time = strtotime($date);
1220        return $time;
1221    }
1222
1223    /**
1224     * テンプレートを切り替えて出力する
1225     *
1226     * @deprecated 2008/04/02以降使用不可
1227     */
1228    function sfCustomDisplay(&$objPage, $is_mobile = false) {
1229        $basename = basename($_SERVER["REQUEST_URI"]);
1230
1231        if($basename == "") {
1232            $path = $_SERVER["REQUEST_URI"] . "index.php";
1233        } else {
1234            $path = $_SERVER["REQUEST_URI"];
1235        }
1236
1237        if(isset($_GET['tpl']) && $_GET['tpl'] != "") {
1238            $tpl_name = $_GET['tpl'];
1239        } else {
1240            $tpl_name = ereg_replace("^/", "", $path);
1241            $tpl_name = ereg_replace("/", "_", $tpl_name);
1242            $tpl_name = ereg_replace("(\.php$|\.html$)", ".tpl", $tpl_name);
1243        }
1244
1245        $template_path = TEMPLATE_FTP_DIR . $tpl_name;
1246echo $template_path;
1247        if($is_mobile === true) {
1248            $objView = new SC_MobileView();
1249            $objView->assignobj($objPage);
1250            $objView->display(SITE_FRAME);
1251        } else if(file_exists($template_path)) {
1252            $objView = new SC_UserView(TEMPLATE_FTP_DIR, COMPILE_FTP_DIR);
1253            $objView->assignobj($objPage);
1254            $objView->display($tpl_name);
1255        } else {
1256            $objView = new SC_SiteView();
1257            $objView->assignobj($objPage);
1258            $objView->display(SITE_FRAME);
1259        }
1260    }
1261
1262    // PHPのmb_convert_encoding関数をSmartyでも使えるようにする
1263    function sf_mb_convert_encoding($str, $encode = 'CHAR_CODE') {
1264        return  mb_convert_encoding($str, $encode);
1265    }
1266
1267    // PHPのmktime関数をSmartyでも使えるようにする
1268    function sf_mktime($format, $hour=0, $minute=0, $second=0, $month=1, $day=1, $year=1999) {
1269        return  date($format,mktime($hour, $minute, $second, $month, $day, $year));
1270    }
1271
1272    // PHPのdate関数をSmartyでも使えるようにする
1273    function sf_date($format, $timestamp = '') {
1274        return  date( $format, $timestamp);
1275    }
1276
1277    // チェックボックスの型を変換する
1278    function sfChangeCheckBox($data , $tpl = false){
1279        if ($tpl) {
1280            if ($data == 1){
1281                return 'checked';
1282            }else{
1283                return "";
1284            }
1285        }else{
1286            if ($data == "on"){
1287                return 1;
1288            }else{
1289                return 2;
1290            }
1291        }
1292    }
1293
1294    // 2つの配列を用いて連想配列を作成する
1295    function sfarrCombine($arrKeys, $arrValues) {
1296
1297        if(count($arrKeys) <= 0 and count($arrValues) <= 0) return array();
1298
1299        $keys = array_values($arrKeys);
1300        $vals = array_values($arrValues);
1301
1302        $max = max( count( $keys ), count( $vals ) );
1303        $combine_ary = array();
1304        for($i=0; $i<$max; $i++) {
1305            $combine_ary[$keys[$i]] = $vals[$i];
1306        }
1307        if(is_array($combine_ary)) return $combine_ary;
1308
1309        return false;
1310    }
1311
1312    /* 子ID所属する親IDを取得する */
1313    function sfGetParentsArraySub($arrData, $pid_name, $id_name, $child) {
1314        $max = count($arrData);
1315        $parent = "";
1316        for($i = 0; $i < $max; $i++) {
1317            if($arrData[$i][$id_name] == $child) {
1318                $parent = $arrData[$i][$pid_name];
1319                break;
1320            }
1321        }
1322        return $parent;
1323    }
1324
1325    /* 階層構造のテーブルから与えられたIDの兄弟を取得する */
1326    function sfGetBrothersArray($arrData, $pid_name, $id_name, $arrPID) {
1327        $max = count($arrData);
1328
1329        $arrBrothers = array();
1330        foreach($arrPID as $id) {
1331            // 親IDを検索する
1332            for($i = 0; $i < $max; $i++) {
1333                if($arrData[$i][$id_name] == $id) {
1334                    $parent = $arrData[$i][$pid_name];
1335                    break;
1336                }
1337            }
1338            // 兄弟IDを検索する
1339            for($i = 0; $i < $max; $i++) {
1340                if($arrData[$i][$pid_name] == $parent) {
1341                    $arrBrothers[] = $arrData[$i][$id_name];
1342                }
1343            }
1344        }
1345        return $arrBrothers;
1346    }
1347
1348    /* 階層構造のテーブルから与えられたIDの直属の子を取得する */
1349    function sfGetUnderChildrenArray($arrData, $pid_name, $id_name, $parent) {
1350        $max = count($arrData);
1351
1352        $arrChildren = array();
1353        // 子IDを検索する
1354        for($i = 0; $i < $max; $i++) {
1355            if($arrData[$i][$pid_name] == $parent) {
1356                $arrChildren[] = $arrData[$i][$id_name];
1357            }
1358        }
1359        return $arrChildren;
1360    }
1361
1362    // SQLシングルクォート対応
1363    function sfQuoteSmart($in){
1364
1365        if (is_int($in) || is_double($in)) {
1366            return $in;
1367        } elseif (is_bool($in)) {
1368            return $in ? 1 : 0;
1369        } elseif (is_null($in)) {
1370            return 'NULL';
1371        } else {
1372            return "'" . str_replace("'", "''", $in) . "'";
1373        }
1374    }
1375
1376    // ディレクトリを再帰的に生成する
1377    function sfMakeDir($path) {
1378        static $count = 0;
1379        $count++;  // 無限ループ回避
1380        $dir = dirname($path);
1381        if(ereg("^[/]$", $dir) || ereg("^[A-Z]:[\\]$", $dir) || $count > 256) {
1382            // ルートディレクトリで終了
1383            return;
1384        } else {
1385            if(is_writable(dirname($dir))) {
1386                if(!file_exists($dir)) {
1387                    mkdir($dir);
1388                    GC_Utils::gfPrintLog("mkdir $dir");
1389                }
1390            } else {
1391                SC_Utils::sfMakeDir($dir);
1392                if(is_writable(dirname($dir))) {
1393                    if(!file_exists($dir)) {
1394                        mkdir($dir);
1395                        GC_Utils::gfPrintLog("mkdir $dir");
1396                    }
1397                }
1398           }
1399        }
1400        return;
1401    }
1402
1403    // ディレクトリ以下のファイルを再帰的にコピー
1404    function sfCopyDir($src, $des, $mess = "", $override = false){
1405        if(!is_dir($src)){
1406            return false;
1407        }
1408
1409        $oldmask = umask(0);
1410        $mod= stat($src);
1411
1412        // ディレクトリがなければ作成する
1413        if(!file_exists($des)) {
1414            if(!mkdir($des, $mod[2])) {
1415                print("path:" . $des);
1416            }
1417        }
1418
1419        $fileArray=glob( $src."*" );
1420        foreach( $fileArray as $key => $data_ ){
1421            // CVS管理ファイルはコピーしない
1422            if(ereg("/CVS/Entries", $data_)) {
1423                break;
1424            }
1425            if(ereg("/CVS/Repository", $data_)) {
1426                break;
1427            }
1428            if(ereg("/CVS/Root", $data_)) {
1429                break;
1430            }
1431
1432            mb_ereg("^(.*[\/])(.*)",$data_, $matches);
1433            $data=$matches[2];
1434            if( is_dir( $data_ ) ){
1435                $mess = SC_Utils::sfCopyDir( $data_.'/', $des.$data.'/', $mess);
1436            }else{
1437                if(!$override && file_exists($des.$data)) {
1438                    $mess.= $des.$data . ":ファイルが存在します\n";
1439                } else {
1440                    if(@copy( $data_, $des.$data)) {
1441                        $mess.= $des.$data . ":コピー成功\n";
1442                    } else {
1443                        $mess.= $des.$data . ":コピー失敗\n";
1444                    }
1445                }
1446                $mod=stat($data_ );
1447            }
1448        }
1449        umask($oldmask);
1450        return $mess;
1451    }
1452
1453    // 指定したフォルダ内のファイルを全て削除する
1454    function sfDelFile($dir){
1455        if(file_exists($dir)) {
1456            $dh = opendir($dir);
1457            // フォルダ内のファイルを削除
1458            while($file = readdir($dh)){
1459                if ($file == "." or $file == "..") continue;
1460                $del_file = $dir . "/" . $file;
1461                if(is_file($del_file)){
1462                    $ret = unlink($dir . "/" . $file);
1463                }else if (is_dir($del_file)){
1464                    $ret = SC_Utils::sfDelFile($del_file);
1465                }
1466
1467                if(!$ret){
1468                    return $ret;
1469                }
1470            }
1471
1472            // 閉じる
1473            closedir($dh);
1474
1475            // フォルダを削除
1476            return rmdir($dir);
1477        }
1478    }
1479
1480    /*
1481     * 関数名:sfWriteFile
1482     * 引数1 :書き込むデータ
1483     * 引数2 :ファイルパス
1484     * 引数3 :書き込みタイプ
1485     * 引数4 :パーミッション
1486     * 戻り値:結果フラグ 成功なら true 失敗なら false
1487     * 説明 :ファイル書き出し
1488     */
1489    function sfWriteFile($str, $path, $type, $permission = "") {
1490        //ファイルを開く
1491        if (!($file = fopen ($path, $type))) {
1492            return false;
1493        }
1494
1495        //ファイルロック
1496        flock ($file, LOCK_EX);
1497        //ファイルの書き込み
1498        fputs ($file, $str);
1499        //ファイルロックの解除
1500        flock ($file, LOCK_UN);
1501        //ファイルを閉じる
1502        fclose ($file);
1503        // 権限を指定
1504        if($permission != "") {
1505            chmod($path, $permission);
1506        }
1507
1508        return true;
1509    }
1510
1511    function sfFlush($output = " ", $sleep = 0){
1512        // 実行時間を制限しない
1513        set_time_limit(0);
1514        // 出力をバッファリングしない(==日本語自動変換もしない)
1515        ob_end_clean();
1516
1517        // IEのために256バイト空文字出力
1518        echo str_pad('',256);
1519
1520        // 出力はブランクだけでもいいと思う
1521        echo $output;
1522        // 出力をフラッシュする
1523        flush();
1524
1525        ob_flush();
1526        ob_start();
1527
1528        // 時間のかかる処理
1529        sleep($sleep);
1530    }
1531
1532    // @versionの記載があるファイルからバージョンを取得する。
1533    function sfGetFileVersion($path) {
1534        if(file_exists($path)) {
1535            $src_fp = fopen($path, "rb");
1536            if($src_fp) {
1537                while (!feof($src_fp)) {
1538                    $line = fgets($src_fp);
1539                    if(ereg("@version", $line)) {
1540                        $arrLine = split(" ", $line);
1541                        $version = $arrLine[5];
1542                    }
1543                }
1544                fclose($src_fp);
1545            }
1546        }
1547        return $version;
1548    }
1549
1550    // 指定したURLに対してPOSTでデータを送信する
1551    function sfSendPostData($url, $arrData, $arrOkCode = array()){
1552        require_once(DATA_PATH . "module/Request.php");
1553
1554        // 送信インスタンス生成
1555        $req = new HTTP_Request($url);
1556
1557        $req->addHeader('User-Agent', 'DoCoMo/2.0 P2101V(c100)');
1558        $req->setMethod(HTTP_REQUEST_METHOD_POST);
1559
1560        // POSTデータ送信
1561        $req->addPostDataArray($arrData);
1562
1563        // エラーが無ければ、応答情報を取得する
1564        if (!PEAR::isError($req->sendRequest())) {
1565
1566            // レスポンスコードがエラー判定なら、空を返す
1567            $res_code = $req->getResponseCode();
1568
1569            if(!in_array($res_code, $arrOkCode)){
1570                $response = "";
1571            }else{
1572                $response = $req->getResponseBody();
1573            }
1574
1575        } else {
1576            $response = "";
1577        }
1578
1579        // POSTデータクリア
1580        $req->clearPostData();
1581
1582        return $response;
1583    }
1584
1585    /**
1586     * $array の要素を $arrConvList で指定した方式で mb_convert_kana を適用する.
1587     *
1588     * @param array $array 変換する文字列の配列
1589     * @param array $arrConvList mb_convert_kana の適用ルール
1590     * @return array 変換後の配列
1591     * @see mb_convert_kana
1592     */
1593    function mbConvertKanaWithArray($array, $arrConvList) {
1594        foreach ($arrConvList as $key => $val) {
1595            if(isset($array[$key])) {
1596                $array[$key] = mb_convert_kana($array[$key] ,$val);
1597            }
1598        }
1599        return $array;
1600    }
1601
1602    /**
1603     * 配列の添字が未定義の場合は空文字を代入して定義する.
1604     *
1605     * @param array $array 添字をチェックする配列
1606     * @param array $defineIndexes チェックする添字
1607     * @return array 添字を定義した配列
1608     */
1609    function arrayDefineIndexes($array, $defineIndexes) {
1610        foreach ($defineIndexes as $key) {
1611            if (!isset($array[$key])) $array[$key] = "";
1612        }
1613        return $array;
1614    }
1615
1616    /**
1617     * XML宣言を出力する.
1618     *
1619     * XML宣言があると問題が発生する UA は出力しない.
1620     *
1621     * @return string XML宣言の文字列
1622     */
1623    function printXMLDeclaration() {
1624        $ua = $_SERVER['HTTP_USER_AGENT'];
1625        if (!preg_match("/MSIE/", $ua) || preg_match("/MSIE 7/", $ua)) {
1626            print("<?xml version='1.0' encoding='" . CHAR_CODE . "'?>\n");
1627        }
1628    }
1629
1630    /*
1631     * 関数名:sfGetFileList()
1632     * 説明 :指定パス配下のディレクトリ取得
1633     * 引数1 :取得するディレクトリパス
1634     */
1635    function sfGetFileList($dir) {
1636        $arrFileList = array();
1637        $arrDirList = array();
1638
1639        if (is_dir($dir)) {
1640            if ($dh = opendir($dir)) {
1641                $cnt = 0;
1642                // 行末の/を取り除く
1643                while (($file = readdir($dh)) !== false) $arrDir[] = $file;
1644                $dir = ereg_replace("/$", "", $dir);
1645                // アルファベットと数字でソート
1646                natcasesort($arrDir);
1647                foreach($arrDir as $file) {
1648                    // ./ と ../を除くファイルのみを取得
1649                    if($file != "." && $file != "..") {
1650
1651                        $path = $dir."/".$file;
1652                        // SELECT内の見た目を整えるため指定文字数で切る
1653                        $file_name = SC_Utils::sfCutString($file, FILE_NAME_LEN);
1654                        $file_size = SC_Utils::sfCutString(SC_Utils::sfGetDirSize($path), FILE_NAME_LEN);
1655                        $file_time = date("Y/m/d", filemtime($path));
1656
1657                        // ディレクトリとファイルで格納配列を変える
1658                        if(is_dir($path)) {
1659                            $arrDirList[$cnt]['file_name'] = $file;
1660                            $arrDirList[$cnt]['file_path'] = $path;
1661                            $arrDirList[$cnt]['file_size'] = $file_size;
1662                            $arrDirList[$cnt]['file_time'] = $file_time;
1663                            $arrDirList[$cnt]['is_dir'] = true;
1664                        } else {
1665                            $arrFileList[$cnt]['file_name'] = $file;
1666                            $arrFileList[$cnt]['file_path'] = $path;
1667                            $arrFileList[$cnt]['file_size'] = $file_size;
1668                            $arrFileList[$cnt]['file_time'] = $file_time;
1669                            $arrFileList[$cnt]['is_dir'] = false;
1670                        }
1671                        $cnt++;
1672                    }
1673                }
1674                closedir($dh);
1675            }
1676        }
1677
1678        // フォルダを先頭にしてマージ
1679        return array_merge($arrDirList, $arrFileList);
1680    }
1681
1682    /*
1683     * 関数名:sfGetDirSize()
1684     * 説明 :指定したディレクトリのバイト数を取得
1685     * 引数1 :ディレクトリ
1686     */
1687    function sfGetDirSize($dir) {
1688        if(file_exists($dir)) {
1689            // ディレクトリの場合下層ファイルの総量を取得
1690            if (is_dir($dir)) {
1691                $handle = opendir($dir);
1692                while ($file = readdir($handle)) {
1693                    // 行末の/を取り除く
1694                    $dir = ereg_replace("/$", "", $dir);
1695                    $path = $dir."/".$file;
1696                    if ($file != '..' && $file != '.' && !is_dir($path)) {
1697                        $bytes += filesize($path);
1698                    } else if (is_dir($path) && $file != '..' && $file != '.') {
1699                        // 下層ファイルのバイト数を取得する為、再帰的に呼び出す。
1700                        $bytes += SC_Utils::sfGetDirSize($path);
1701                    }
1702                }
1703            } else {
1704                // ファイルの場合
1705                $bytes = filesize($dir);
1706            }
1707        }
1708        // ディレクトリ(ファイル)が存在しない場合は0byteを返す
1709        if($bytes == "") $bytes = 0;
1710
1711        return $bytes;
1712    }
1713
1714    /*
1715     * 関数名:sfDeleteDir()
1716     * 説明 :指定したディレクトリを削除
1717     * 引数1 :削除ファイル
1718     */
1719    function sfDeleteDir($dir) {
1720        $arrResult = array();
1721        if(file_exists($dir)) {
1722            // ディレクトリかチェック
1723            if (is_dir($dir)) {
1724                if ($handle = opendir("$dir")) {
1725                    $cnt = 0;
1726                    while (false !== ($item = readdir($handle))) {
1727                        if ($item != "." && $item != "..") {
1728                            if (is_dir("$dir/$item")) {
1729                                sfDeleteDir("$dir/$item");
1730                            } else {
1731                                $arrResult[$cnt]['result'] = @unlink("$dir/$item");
1732                                $arrResult[$cnt]['file_name'] = "$dir/$item";
1733                            }
1734                        }
1735                        $cnt++;
1736                    }
1737                }
1738                closedir($handle);
1739                $arrResult[$cnt]['result'] = @rmdir($dir);
1740                $arrResult[$cnt]['file_name'] = "$dir/$item";
1741            } else {
1742                // ファイル削除
1743                $arrResult[0]['result'] = @unlink("$dir");
1744                $arrResult[0]['file_name'] = "$dir";
1745            }
1746        }
1747
1748        return $arrResult;
1749    }
1750
1751    /*
1752     * 関数名:sfGetFileTree()
1753     * 説明 :ツリー生成用配列取得(javascriptに渡す用)
1754     * 引数1 :ディレクトリ
1755     * 引数2 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1756     */
1757    function sfGetFileTree($dir, $tree_status) {
1758
1759        $cnt = 0;
1760        $arrTree = array();
1761        $default_rank = count(split('/', $dir));
1762
1763        // 文末の/を取り除く
1764        $dir = ereg_replace("/$", "", $dir);
1765        // 最上位層を格納(user_data/)
1766        if(sfDirChildExists($dir)) {
1767            $arrTree[$cnt]['type'] = "_parent";
1768        } else {
1769            $arrTree[$cnt]['type'] = "_child";
1770        }
1771        $arrTree[$cnt]['path'] = $dir;
1772        $arrTree[$cnt]['rank'] = 0;
1773        $arrTree[$cnt]['count'] = $cnt;
1774        // 初期表示はオープン
1775        if($_POST['mode'] != '') {
1776            $arrTree[$cnt]['open'] = lfIsFileOpen($dir, $tree_status);
1777        } else {
1778            $arrTree[$cnt]['open'] = true;
1779        }
1780        $cnt++;
1781
1782        sfGetFileTreeSub($dir, $default_rank, $cnt, $arrTree, $tree_status);
1783
1784        return $arrTree;
1785    }
1786
1787    /*
1788     * 関数名:sfGetFileTree()
1789     * 説明 :ツリー生成用配列取得(javascriptに渡す用)
1790     * 引数1 :ディレクトリ
1791     * 引数2 :デフォルトの階層(/区切りで 0,1,2・・・とカウント)
1792     * 引数3 :連番
1793     * 引数4 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1794     */
1795    function sfGetFileTreeSub($dir, $default_rank, &$cnt, &$arrTree, $tree_status) {
1796
1797        if(file_exists($dir)) {
1798            if ($handle = opendir("$dir")) {
1799                while (false !== ($item = readdir($handle))) $arrDir[] = $item;
1800                // アルファベットと数字でソート
1801                natcasesort($arrDir);
1802                foreach($arrDir as $item) {
1803                    if ($item != "." && $item != "..") {
1804                        // 文末の/を取り除く
1805                        $dir = ereg_replace("/$", "", $dir);
1806                        $path = $dir."/".$item;
1807                        // ディレクトリのみ取得
1808                        if (is_dir($path)) {
1809                            $arrTree[$cnt]['path'] = $path;
1810                            if(sfDirChildExists($path)) {
1811                                $arrTree[$cnt]['type'] = "_parent";
1812                            } else {
1813                                $arrTree[$cnt]['type'] = "_child";
1814                            }
1815
1816                            // 階層を割り出す
1817                            $arrCnt = split('/', $path);
1818                            $rank = count($arrCnt);
1819                            $arrTree[$cnt]['rank'] = $rank - $default_rank + 1;
1820                            $arrTree[$cnt]['count'] = $cnt;
1821                            // フォルダが開いているか
1822                            $arrTree[$cnt]['open'] = lfIsFileOpen($path, $tree_status);
1823                            $cnt++;
1824                            // 下層ディレクトリ取得の為、再帰的に呼び出す
1825                            sfGetFileTreeSub($path, $default_rank, $cnt, $arrTree, $tree_status);
1826                        }
1827                    }
1828                }
1829            }
1830            closedir($handle);
1831        }
1832    }
1833
1834    /*
1835     * 関数名:sfDirChildExists()
1836     * 説明 :指定したディレクトリ配下にファイルがあるか
1837     * 引数1 :ディレクトリ
1838     */
1839    function sfDirChildExists($dir) {
1840        if(file_exists($dir)) {
1841            if (is_dir($dir)) {
1842                $handle = opendir($dir);
1843                while ($file = readdir($handle)) {
1844                    // 行末の/を取り除く
1845                    $dir = ereg_replace("/$", "", $dir);
1846                    $path = $dir."/".$file;
1847                    if ($file != '..' && $file != '.' && is_dir($path)) {
1848                        return true;
1849                    }
1850                }
1851            }
1852        }
1853
1854        return false;
1855    }
1856
1857    /*
1858     * 関数名:lfIsFileOpen()
1859     * 説明 :指定したファイルが前回開かれた状態にあったかチェック
1860     * 引数1 :ディレクトリ
1861     * 引数2 :現在のツリーの状態開いているフォルダのパスが | 区切りで格納
1862     */
1863    function lfIsFileOpen($dir, $tree_status) {
1864        $arrTreeStatus = split('\|', $tree_status);
1865        if(in_array($dir, $arrTreeStatus)) {
1866            return true;
1867        }
1868
1869        return false;
1870    }
1871
1872    /*
1873     * 関数名:sfDownloadFile()
1874     * 引数1 :ファイルパス
1875     * 説明 :ファイルのダウンロード
1876     */
1877    function sfDownloadFile($file) {
1878         // ファイルの場合はダウンロードさせる
1879        Header("Content-disposition: attachment; filename=".basename($file));
1880        Header("Content-type: application/octet-stream; name=".basename($file));
1881        Header("Cache-Control: ");
1882        Header("Pragma: ");
1883        echo (sfReadFile($file));
1884    }
1885
1886    /*
1887     * 関数名:sfCreateFile()
1888     * 引数1 :ファイルパス
1889     * 引数2 :パーミッション
1890     * 説明 :ファイル作成
1891     */
1892    function sfCreateFile($file, $mode = "") {
1893        // 行末の/を取り除く
1894        if($mode != "") {
1895            $ret = @mkdir($file, $mode);
1896        } else {
1897            $ret = @mkdir($file);
1898        }
1899
1900        return $ret;
1901    }
1902
1903    /*
1904     * 関数名:sfReadFile()
1905     * 引数1 :ファイルパス
1906     * 説明 :ファイル読込
1907     */
1908    function sfReadFile($filename) {
1909        $str = "";
1910        // バイナリモードでオープン
1911        $fp = @fopen($filename, "rb" );
1912        //ファイル内容を全て変数に読み込む
1913        if($fp) {
1914            $str = @fread($fp, filesize($filename)+1);
1915        }
1916        @fclose($fp);
1917
1918        return $str;
1919    }
1920
1921   /**
1922     * 配列をテーブルタグで出力する。
1923     *
1924     * @return string
1925     */
1926    function getTableTag($array) {
1927        $html = "<table>";
1928        $html.= "<tr>";
1929        foreach($array[0] as $key => $val) {
1930            $html.="<th>$key</th>";
1931        }
1932        $html.= "</tr>";
1933
1934        $cnt = count($array);
1935
1936        for($i = 0; $i < $cnt; $i++) {
1937            $html.= "<tr>";
1938            foreach($array[$i] as $val) {
1939                $html.="<td>$val</td>";
1940            }
1941            $html.= "</tr>";
1942        }
1943        return $html;
1944    }
1945
1946    /**
1947     * 出力バッファをフラッシュし, バッファリングを開始する.
1948     *
1949     * @return void
1950     */
1951    function flush() {
1952        flush();
1953        ob_end_flush();
1954        ob_start();
1955    }
1956
1957    /* デバッグ用 ------------------------------------------------------------------------------------------------*/
1958    function sfPrintR($obj) {
1959        print("<div style='font-size: 12px;color: #00FF00;'>\n");
1960        print("<strong>**デバッグ中**</strong><br />\n");
1961        print("<pre>\n");
1962        //print_r($obj);
1963        var_dump($obj);
1964        print("</pre>\n");
1965        print("<strong>**デバッグ中**</strong></div>\n");
1966    }
1967}
1968?>
Note: See TracBrowser for help on using the repository browser.