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

Revision 18052, 67.7 KB checked in by Seasoft, 15 years ago (diff)

・店舗基本情報の取得処理にランタイムのキャッシュ機構を設け、店舗基本情報を深く渡し回す実装を改めた。
・SC_Utils 冒頭のコメントに従い、インスタンスを生成していた処理を、Helper クラスへ移す。計算処理のみ SC_Utils に残す。

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