source: branches/comu-ver2/data/class/util/SC_Utils.php @ 17155

Revision 17155, 63.7 KB checked in by Yammy, 16 years ago (diff)

管理画面の商品CSV出力で規格名1、規格名2、カテゴリIDが強制出力される
http://svn.ec-cube.net/open_trac/ticket/250
修正済

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