source: branches/feature-module-update/data/class/util/SC_Utils.php @ 15238

Revision 15238, 87.5 KB checked in by nanasess, 17 years ago (diff)

DBインスタンスを生成する関数を SC_Helper_DB クラスへ移動

  • Property svn:keywords set to Id
  • Property svn:mime-type set to application/x-httpd-php; charset=UTF-8
Line 
1<?php
2/*
3 * Copyright(c) 2000-2007 LOCKON CO.,LTD. All Rights Reserved.
4 *
5 * http://www.lockon.co.jp/
6 */
7
8// {{{ requires
9require_once(CLASS_PATH . "page_extends/error/LC_Page_Error_Ex.php");
10
11/**
12 * 各種ユーティリティクラス.
13 *
14 * 主に static 参照するユーティリティ系の関数群
15 *
16 * @package Util
17 * @author LOCKON CO.,LTD.
18 * @version $Id$
19 */
20class SC_Utils {
21
22    /**
23     * サイト管理情報から値を取得する。
24     * データが存在する場合、必ず1以上の数値が設定されている。
25     * 0を返した場合は、呼び出し元で対応すること。
26     *
27     * @param $control_id 管理ID
28     * @param $dsn DataSource
29     * @return $control_flg フラグ
30     */
31    function sfGetSiteControlFlg($control_id, $dsn = "") {
32
33        // データソース
34        if($dsn == "") {
35            if(defined('DEFAULT_DSN')) {
36                $dsn = DEFAULT_DSN;
37            } else {
38                return;
39            }
40        }
41
42        // クエリ生成
43        $target_column = "control_flg";
44        $table_name = "dtb_site_control";
45        $where = "control_id = ?";
46        $arrval = array($control_id);
47        $control_flg = 0;
48
49        // クエリ発行
50        $objQuery = new SC_Query($dsn, true, true);
51        $arrSiteControl = $objQuery->select($target_column, $table_name, $where, $arrval);
52
53        // データが存在すればフラグを取得する
54        if (count($arrSiteControl) > 0) {
55            $control_flg = $arrSiteControl[0]["control_flg"];
56        }
57
58        return $control_flg;
59    }
60
61    // インストール初期処理
62    function sfInitInstall() {
63        // インストール済みが定義されていない。
64        if(!defined('ECCUBE_INSTALL')) {
65            if(!ereg("/install/", $_SERVER['PHP_SELF'])) {
66                header("Location: ./install/");
67            }
68        } else {
69            $path = HTML_PATH . "install/index.php";
70            if(file_exists($path)) {
71                sfErrorHeader(">> /install/index.phpは、インストール完了後にファイルを削除してください。");
72            }
73
74            // 旧バージョンのinstall.phpのチェック
75            $path = HTML_PATH . "install.php";
76            if(file_exists($path)) {
77                sfErrorHeader(">> /install.phpはセキュリティーホールとなります。削除してください。");
78            }
79        }
80    }
81
82    // アップデートで生成されたPHPを読み出し
83    function sfLoadUpdateModule() {
84        // URL設定ディレクトリを削除
85        $main_php = ereg_replace(URL_DIR, "", $_SERVER['PHP_SELF']);
86        $extern_php = UPDATE_PATH . $main_php;
87        if(file_exists($extern_php)) {
88            require_once($extern_php);
89        }
90    }
91
92    function sf_getBasisData() {
93        //DBから設定情報を取得
94        $objConn = new SC_DbConn(DEFAULT_DSN);
95        $result = $objConn->getAll("SELECT * FROM dtb_baseinfo");
96        if(is_array($result[0])) {
97            foreach ( $result[0] as $key=>$value ){
98                $CONF["$key"] = $value;
99            }
100        }
101        return $CONF;
102    }
103
104    // 装飾付きエラーメッセージの表示
105    function sfErrorHeader($mess, $print = false) {
106        global $GLOBAL_ERR;
107        if($GLOBAL_ERR == "") {
108            $GLOBAL_ERR = "<meta http-equiv='Content-Type' content='text/html; charset=" . CHAR_CODE . "'>\n";
109        }
110        $GLOBAL_ERR.= "<table width='100%' border='0' cellspacing='0' cellpadding='0' summary=' '>\n";
111        $GLOBAL_ERR.= "<tr>\n";
112        $GLOBAL_ERR.= "<td bgcolor='#ffeebb' height='25' colspan='2' align='center'>\n";
113        $GLOBAL_ERR.= "<SPAN style='color:red; font-size:12px'><strong>" . $mess . "</strong></span>\n";
114        $GLOBAL_ERR.= "</td>\n";
115        $GLOBAL_ERR.= " </tr>\n";
116        $GLOBAL_ERR.= "</table>\n";
117
118        if($print) {
119            print($GLOBAL_ERR);
120        }
121    }
122
123    /* エラーページの表示 */
124    function sfDispError($type) {
125// FIXME
126//        class LC_ErrorPage {
127//            function LC_ErrorPage() {
128//                $this->tpl_mainpage = 'login_error.tpl';
129//                $this->tpl_title = 'エラー';
130//            }
131//        }
132
133        //$objPage = new LC_ErrorPage();
134        $objPage = new LC_Page();
135        $objView = new SC_AdminView();
136
137        switch ($type) {
138            case LOGIN_ERROR:
139                $objPage->tpl_error="IDまたはパスワードが正しくありません。<br />もう一度ご確認のうえ、再度入力してください。";
140                break;
141            case ACCESS_ERROR:
142                $objPage->tpl_error="ログイン認証の有効期限切れの可能性があります。<br />もう一度ご確認のうえ、再度ログインしてください。";
143                break;
144            case AUTH_ERROR:
145                $objPage->tpl_error="このファイルにはアクセス権限がありません。<br />もう一度ご確認のうえ、再度ログインしてください。";
146                break;
147            case INVALID_MOVE_ERRORR:
148                $objPage->tpl_error="不正なページ移動です。<br />もう一度ご確認のうえ、再度入力してください。";
149                break;
150            default:
151                $objPage->tpl_error="エラーが発生しました。<br />もう一度ご確認のうえ、再度ログインしてください。";
152                break;
153        }
154
155        $objView->assignobj($objPage);
156        $objView->display(LOGIN_FRAME);
157
158        exit;
159    }
160
161    /* サイトエラーページの表示 */
162    function sfDispSiteError($type, $objSiteSess = "", $return_top = false, $err_msg = "", $is_mobile = false) {
163        global $objCampaignSess;
164
165        if ($objSiteSess != "") {
166            $objSiteSess->setNowPage('error');
167        }
168// FIXME
169//        class LC_ErrorPage {
170//            function LC_ErrorPage() {
171//                $this->tpl_mainpage = 'error.tpl';
172//                $this->tpl_css = URL_DIR.'css/layout/error.css';
173//                $this->tpl_title = 'エラー';
174//            }
175//        }
176
177        //$objPage = new LC_ErrorPage();
178        $objPage = new LC_Page_Error_Ex();
179        $objPage->init();
180
181
182        if($is_mobile === true) {
183            $objView = new SC_MobileView();
184        } else {
185            $objView = new SC_SiteView();
186        }
187
188        switch ($type) {
189            case PRODUCT_NOT_FOUND:
190                $objPage->tpl_error="ご指定のページはございません。";
191                break;
192            case PAGE_ERROR:
193                $objPage->tpl_error="不正なページ移動です。";
194                break;
195            case CART_EMPTY:
196                $objPage->tpl_error="カートに商品ががありません。";
197                break;
198            case CART_ADD_ERROR:
199                $objPage->tpl_error="購入処理中は、カートに商品を追加することはできません。";
200                break;
201            case CANCEL_PURCHASE:
202                $objPage->tpl_error="この手続きは無効となりました。以下の要因が考えられます。<br />・セッション情報の有効期限が切れてる場合<br />・購入手続き中に新しい購入手続きを実行した場合<br />・すでに購入手続きを完了している場合";
203                break;
204            case CATEGORY_NOT_FOUND:
205                $objPage->tpl_error="ご指定のカテゴリは存在しません。";
206                break;
207            case SITE_LOGIN_ERROR:
208                $objPage->tpl_error="メールアドレスもしくはパスワードが正しくありません。";
209                break;
210            case TEMP_LOGIN_ERROR:
211                $objPage->tpl_error="メールアドレスもしくはパスワードが正しくありません。<br />本登録がお済みでない場合は、仮登録メールに記載されている<br />URLより本登録を行ってください。";
212                break;
213            case CUSTOMER_ERROR:
214                $objPage->tpl_error="不正なアクセスです。";
215                break;
216            case SOLD_OUT:
217                $objPage->tpl_error="申し訳ございませんが、ご購入の直前で売り切れた商品があります。この手続きは無効となりました。";
218                break;
219            case CART_NOT_FOUND:
220                $objPage->tpl_error="申し訳ございませんが、カート内の商品情報の取得に失敗しました。この手続きは無効となりました。";
221                break;
222            case LACK_POINT:
223                $objPage->tpl_error="申し訳ございませんが、ポイントが不足しております。この手続きは無効となりました。";
224                break;
225            case FAVORITE_ERROR:
226                $objPage->tpl_error="既にお気に入りに追加されている商品です。";
227                break;
228            case EXTRACT_ERROR:
229                $objPage->tpl_error="ファイルの解凍に失敗しました。\n指定のディレクトリに書き込み権限が与えられていない可能性があります。";
230                break;
231            case FTP_DOWNLOAD_ERROR:
232                $objPage->tpl_error="ファイルのFTPダウンロードに失敗しました。";
233                break;
234            case FTP_LOGIN_ERROR:
235                $objPage->tpl_error="FTPログインに失敗しました。";
236                break;
237            case FTP_CONNECT_ERROR:
238                $objPage->tpl_error="FTPログインに失敗しました。";
239                break;
240            case CREATE_DB_ERROR:
241                $objPage->tpl_error="DBの作成に失敗しました。\n指定のユーザーには、DB作成の権限が与えられていない可能性があります。";
242                break;
243            case DB_IMPORT_ERROR:
244                $objPage->tpl_error="データベース構造のインポートに失敗しました。\nsqlファイルが壊れている可能性があります。";
245                break;
246            case FILE_NOT_FOUND:
247                $objPage->tpl_error="指定のパスに、設定ファイルが存在しません。";
248                break;
249            case WRITE_FILE_ERROR:
250                $objPage->tpl_error="設定ファイルに書き込めません。\n設定ファイルに書き込み権限を与えてください。";
251                break;
252            case FREE_ERROR_MSG:
253                $objPage->tpl_error=$err_msg;
254                break;
255             default:
256                $objPage->tpl_error="エラーが発生しました。";
257                break;
258        }
259
260        $objPage->return_top = $return_top;
261
262        $objView->assignobj($objPage);
263
264        if(is_object($objCampaignSess)) {
265            // フレームを選択(キャンペーンページから遷移なら変更)
266            $objCampaignSess->pageView($objView);
267        } else {
268            $objView->display(SITE_FRAME);
269        }
270        register_shutdown_function(array($objPage, "destroy"));
271        exit;
272    }
273
274    /* 認証の可否判定 */
275    function sfIsSuccess($objSess, $disp_error = true) {
276        $ret = $objSess->IsSuccess();
277        if($ret != SUCCESS) {
278            if($disp_error) {
279                // エラーページの表示
280                SC_Utils::sfDispError($ret);
281            }
282            return false;
283        }
284        // リファラーチェック(CSRFの暫定的な対策)
285        // 「リファラ無」 の場合はスルー
286        // 「リファラ有」 かつ 「管理画面からの遷移でない」 場合にエラー画面を表示する
287        if ( empty($_SERVER['HTTP_REFERER']) ) {
288            // 警告表示させる?
289            // sfErrorHeader('>> referrerが無効になっています。');
290        } else {
291            $domain  = SC_Utils::sfIsHTTPS() ? SSL_URL : SITE_URL;
292            $pattern = sprintf('|^%s.*|', $domain);
293            $referer = $_SERVER['HTTP_REFERER'];
294
295            // 管理画面から以外の遷移の場合はエラー画面を表示
296            if (!preg_match($pattern, $referer)) {
297                if ($disp_error) SC_Utils::sfDispError(INVALID_MOVE_ERRORR);
298                return false;
299            }
300        }
301        return true;
302    }
303
304    /**
305     * 文字列をアスタリスクへ変換する.
306     *
307     * @param string $passlen 変換する文字列
308     * @return string アスタリスクへ変換した文字列
309     */
310    function lfPassLen($passlen){
311        $ret = "";
312        for ($i=0;$i<$passlen;true){
313            $ret.="*";
314            $i++;
315        }
316        return $ret;
317    }
318
319    /**
320     * HTTPSかどうかを判定
321     *
322     * @return bool
323     */
324    function sfIsHTTPS () {
325        // HTTPS時には$_SERVER['HTTPS']には空でない値が入る
326        // $_SERVER['HTTPS'] != 'off' はIIS用
327        if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
328            return true;
329        } else {
330            return false;
331        }
332    }
333
334    /**
335     *  正規の遷移がされているかを判定
336     *  前画面でuniqidを埋め込んでおく必要がある
337     *  @param  obj  SC_Session, SC_SiteSession
338     *  @return bool
339     */
340    function sfIsValidTransition($objSess) {
341        // 前画面からPOSTされるuniqidが正しいものかどうかをチェック
342        $uniqid = $objSess->getUniqId();
343        if ( !empty($_POST['uniqid']) && ($_POST['uniqid'] === $uniqid) ) {
344            return true;
345        } else {
346            return false;
347        }
348    }
349
350    /* 前のページで正しく登録が行われたか判定 */
351    function sfIsPrePage($objSiteSess, $is_mobile = false) {
352        $ret = $objSiteSess->isPrePage();
353        if($ret != true) {
354            // エラーページの表示
355            sfDispSiteError(PAGE_ERROR, $objSiteSess, false, "", $is_mobile);
356        }
357    }
358
359    function sfCheckNormalAccess($objSiteSess, $objCartSess) {
360        // ユーザユニークIDの取得
361        $uniqid = $objSiteSess->getUniqId();
362        // 購入ボタンを押した時のカート内容がコピーされていない場合のみコピーする。
363        $objCartSess->saveCurrentCart($uniqid);
364        // POSTのユニークIDとセッションのユニークIDを比較(ユニークIDがPOSTされていない場合はスルー)
365        $ret = $objSiteSess->checkUniqId();
366        if($ret != true) {
367            // エラーページの表示
368            sfDispSiteError(CANCEL_PURCHASE, $objSiteSess);
369        }
370
371        // カート内が空でないか || 購入ボタンを押してから変化がないか
372        $quantity = $objCartSess->getTotalQuantity();
373        $ret = $objCartSess->checkChangeCart();
374        if($ret == true || !($quantity > 0)) {
375            // カート情報表示に強制移動する
376            header("Location: ".URL_CART_TOP);
377            exit;
378        }
379        return $uniqid;
380    }
381
382    /* DB用日付文字列取得 */
383    function sfGetTimestamp($year, $month, $day, $last = false) {
384        if($year != "" && $month != "" && $day != "") {
385            if($last) {
386                $time = "23:59:59";
387            } else {
388                $time = "00:00:00";
389            }
390            $date = $year."-".$month."-".$day." ".$time;
391        } else {
392            $date = "";
393        }
394        return  $date;
395    }
396
397    // INT型の数値チェック
398    function sfIsInt($value) {
399        if($value != "" && strlen($value) <= INT_LEN && is_numeric($value)) {
400            return true;
401        }
402        return false;
403    }
404
405    function sfCSVDownload($data, $prefix = ""){
406
407        if($prefix == "") {
408            $dir_name = sfUpDirName();
409            $file_name = $dir_name . date("ymdHis") .".csv";
410        } else {
411            $file_name = $prefix . date("ymdHis") .".csv";
412        }
413
414        /* HTTPヘッダの出力 */
415        Header("Content-disposition: attachment; filename=${file_name}");
416        Header("Content-type: application/octet-stream; name=${file_name}");
417        Header("Cache-Control: ");
418        Header("Pragma: ");
419
420        /* i18n~ だと正常に動作しないため、mb~ に変更
421        if (i18n_discover_encoding($data) == CHAR_CODE){
422            $data = i18n_convert($data,'SJIS',CHAR_CODE);
423        }
424        */
425        if (mb_internal_encoding() == CHAR_CODE){
426            $data = mb_convert_encoding($data,'SJIS',CHAR_CODE);
427        }
428
429        /* データを出力 */
430        echo $data;
431    }
432
433    /* 1階層上のディレクトリ名を取得する */
434    function sfUpDirName() {
435        $path = $_SERVER['PHP_SELF'];
436        $arrVal = split("/", $path);
437        $cnt = count($arrVal);
438        return $arrVal[($cnt - 2)];
439    }
440
441    // 現在のサイトを更新(ただしポストは行わない)
442    function sfReload($get = "") {
443        if ($_SERVER["SERVER_PORT"] == "443" ){
444            $url = ereg_replace(URL_DIR . "$", "", SSL_URL);
445        } else {
446            $url = ereg_replace(URL_DIR . "$", "", SITE_URL);
447        }
448
449        if($get != "") {
450            header("Location: ". $url . $_SERVER['PHP_SELF'] . "?" . $get);
451        } else {
452            header("Location: ". $url . $_SERVER['PHP_SELF']);
453        }
454        exit;
455    }
456
457    // ランキングを上げる。
458    function sfRankUp($table, $colname, $id, $andwhere = "") {
459        $objQuery = new SC_Query();
460        $objQuery->begin();
461        $where = "$colname = ?";
462        if($andwhere != "") {
463            $where.= " AND $andwhere";
464        }
465        // 対象項目のランクを取得
466        $rank = $objQuery->get($table, "rank", $where, array($id));
467        // ランクの最大値を取得
468        $maxrank = $objQuery->max($table, "rank", $andwhere);
469        // ランクが最大値よりも小さい場合に実行する。
470        if($rank < $maxrank) {
471            // ランクが一つ上のIDを取得する。
472            $where = "rank = ?";
473            if($andwhere != "") {
474                $where.= " AND $andwhere";
475            }
476            $uprank = $rank + 1;
477            $up_id = $objQuery->get($table, $colname, $where, array($uprank));
478            // ランク入れ替えの実行
479            $sqlup = "UPDATE $table SET rank = ?, update_date = Now() WHERE $colname = ?";
480            $objQuery->exec($sqlup, array($rank + 1, $id));
481            $objQuery->exec($sqlup, array($rank, $up_id));
482        }
483        $objQuery->commit();
484    }
485
486    // ランキングを下げる。
487    function sfRankDown($table, $colname, $id, $andwhere = "") {
488        $objQuery = new SC_Query();
489        $objQuery->begin();
490        $where = "$colname = ?";
491        if($andwhere != "") {
492            $where.= " AND $andwhere";
493        }
494        // 対象項目のランクを取得
495        $rank = $objQuery->get($table, "rank", $where, array($id));
496
497        // ランクが1(最小値)よりも大きい場合に実行する。
498        if($rank > 1) {
499            // ランクが一つ下のIDを取得する。
500            $where = "rank = ?";
501            if($andwhere != "") {
502                $where.= " AND $andwhere";
503            }
504            $downrank = $rank - 1;
505            $down_id = $objQuery->get($table, $colname, $where, array($downrank));
506            // ランク入れ替えの実行
507            $sqlup = "UPDATE $table SET rank = ?, update_date = Now() WHERE $colname = ?";
508            $objQuery->exec($sqlup, array($rank - 1, $id));
509            $objQuery->exec($sqlup, array($rank, $down_id));
510        }
511        $objQuery->commit();
512    }
513
514    //---- 指定順位へ移動
515    function sfMoveRank($tableName, $keyIdColumn, $keyId, $pos, $where = "") {
516        $objQuery = new SC_Query();
517        $objQuery->begin();
518
519        // 自身のランクを取得する
520        $rank = $objQuery->get($tableName, "rank", "$keyIdColumn = ?", array($keyId));
521        $max = $objQuery->max($tableName, "rank", $where);
522
523        // 値の調整(逆順)
524        if($pos > $max) {
525            $position = 1;
526        } else if($pos < 1) {
527            $position = $max;
528        } else {
529            $position = $max - $pos + 1;
530        }
531
532        if( $position > $rank ) $term = "rank - 1"; //入れ替え先の順位が入れ換え元の順位より大きい場合
533        if( $position < $rank ) $term = "rank + 1"; //入れ替え先の順位が入れ換え元の順位より小さい場合
534
535        //-- 指定した順位の商品から移動させる商品までのrankを1つずらす
536        $sql = "UPDATE $tableName SET rank = $term, update_date = NOW() WHERE rank BETWEEN ? AND ? AND del_flg = 0";
537        if($where != "") {
538            $sql.= " AND $where";
539        }
540
541        if( $position > $rank ) $objQuery->exec( $sql, array( $rank + 1, $position ));
542        if( $position < $rank ) $objQuery->exec( $sql, array( $position, $rank - 1 ));
543
544        //-- 指定した順位へrankを書き換える。
545        $sql  = "UPDATE $tableName SET rank = ?, update_date = NOW() WHERE $keyIdColumn = ? AND del_flg = 0 ";
546        if($where != "") {
547            $sql.= " AND $where";
548        }
549
550        $objQuery->exec( $sql, array( $position, $keyId ) );
551        $objQuery->commit();
552    }
553
554    // ランクを含むレコードの削除
555    // レコードごと削除する場合は、$deleteをtrueにする。
556    function sfDeleteRankRecord($table, $colname, $id, $andwhere = "", $delete = false) {
557        $objQuery = new SC_Query();
558        $objQuery->begin();
559        // 削除レコードのランクを取得する。
560        $where = "$colname = ?";
561        if($andwhere != "") {
562            $where.= " AND $andwhere";
563        }
564        $rank = $objQuery->get($table, "rank", $where, array($id));
565
566        if(!$delete) {
567            // ランクを最下位にする、DELフラグON
568            $sqlup = "UPDATE $table SET rank = 0, del_flg = 1, update_date = Now() ";
569            $sqlup.= "WHERE $colname = ?";
570            // UPDATEの実行
571            $objQuery->exec($sqlup, array($id));
572        } else {
573            $objQuery->delete($table, "$colname = ?", array($id));
574        }
575
576        // 追加レコードのランクより上のレコードを一つずらす。
577        $where = "rank > ?";
578        if($andwhere != "") {
579            $where.= " AND $andwhere";
580        }
581        $sqlup = "UPDATE $table SET rank = (rank - 1) WHERE $where";
582        $objQuery->exec($sqlup, array($rank));
583        $objQuery->commit();
584    }
585
586    // レコードの存在チェック
587    function sfIsRecord($table, $col, $arrval, $addwhere = "") {
588        $objQuery = new SC_Query();
589        $arrCol = split("[, ]", $col);
590
591        $where = "del_flg = 0";
592
593        if($addwhere != "") {
594            $where.= " AND $addwhere";
595        }
596
597        foreach($arrCol as $val) {
598            if($val != "") {
599                if($where == "") {
600                    $where = "$val = ?";
601                } else {
602                    $where.= " AND $val = ?";
603                }
604            }
605        }
606        $ret = $objQuery->get($table, $col, $where, $arrval);
607
608        if($ret != "") {
609            return true;
610        }
611        return false;
612    }
613
614    // チェックボックスの値をマージ
615    function sfMergeCBValue($keyname, $max) {
616        $conv = "";
617        $cnt = 1;
618        for($cnt = 1; $cnt <= $max; $cnt++) {
619            if ($_POST[$keyname . $cnt] == "1") {
620                $conv.= "1";
621            } else {
622                $conv.= "0";
623            }
624        }
625        return $conv;
626    }
627
628    // html_checkboxesの値をマージして2進数形式に変更する。
629    function sfMergeCheckBoxes($array, $max) {
630        $ret = "";
631        if(is_array($array)) {
632            foreach($array as $val) {
633                $arrTmp[$val] = "1";
634            }
635        }
636        for($i = 1; $i <= $max; $i++) {
637            if($arrTmp[$i] == "1") {
638                $ret.= "1";
639            } else {
640                $ret.= "0";
641            }
642        }
643        return $ret;
644    }
645
646
647    // html_checkboxesの値をマージして「-」でつなげる。
648    function sfMergeParamCheckBoxes($array) {
649        $ret = '';
650        if(is_array($array)) {
651            foreach($array as $val) {
652                if($ret != "") {
653                    $ret.= "-$val";
654                } else {
655                    $ret = $val;
656                }
657            }
658        } else {
659            $ret = $array;
660        }
661        return $ret;
662    }
663
664    // html_checkboxesの値をマージしてSQL検索用に変更する。
665    function sfSearchCheckBoxes($array) {
666        $max = 0;
667        $ret = "";
668        foreach($array as $val) {
669            $arrTmp[$val] = "1";
670            if($val > $max) {
671                $max = $val;
672            }
673        }
674        for($i = 1; $i <= $max; $i++) {
675            if($arrTmp[$i] == "1") {
676                $ret.= "1";
677            } else {
678                $ret.= "_";
679            }
680        }
681
682        if($ret != "") {
683            $ret.= "%";
684        }
685        return $ret;
686    }
687
688    // 2進数形式の値をhtml_checkboxes対応の値に切り替える
689    function sfSplitCheckBoxes($val) {
690        $len = strlen($val);
691        for($i = 0; $i < $len; $i++) {
692            if(substr($val, $i, 1) == "1") {
693                $arrRet[] = ($i + 1);
694            }
695        }
696        return $arrRet;
697    }
698
699    // チェックボックスの値をマージ
700    function sfMergeCBSearchValue($keyname, $max) {
701        $conv = "";
702        $cnt = 1;
703        for($cnt = 1; $cnt <= $max; $cnt++) {
704            if ($_POST[$keyname . $cnt] == "1") {
705                $conv.= "1";
706            } else {
707                $conv.= "_";
708            }
709        }
710        return $conv;
711    }
712
713    // チェックボックスの値を分解
714    function sfSplitCBValue($val, $keyname = "") {
715        $len = strlen($val);
716        $no = 1;
717        for ($cnt = 0; $cnt < $len; $cnt++) {
718            if($keyname != "") {
719                $arr[$keyname . $no] = substr($val, $cnt, 1);
720            } else {
721                $arr[] = substr($val, $cnt, 1);
722            }
723            $no++;
724        }
725        return $arr;
726    }
727
728    // キーと値をセットした配列を取得
729    function sfArrKeyValue($arrList, $keyname, $valname, $len_max = "", $keysize = "") {
730
731        $max = count($arrList);
732
733        if($len_max != "" && $max > $len_max) {
734            $max = $len_max;
735        }
736
737        for($cnt = 0; $cnt < $max; $cnt++) {
738            if($keysize != "") {
739                $key = $this->sfCutString($arrList[$cnt][$keyname], $keysize);
740            } else {
741                $key = $arrList[$cnt][$keyname];
742            }
743            $val = $arrList[$cnt][$valname];
744
745            if(!isset($arrRet[$key])) {
746                $arrRet[$key] = $val;
747            }
748
749        }
750        return $arrRet;
751    }
752
753    // キーと値をセットした配列を取得(値が複数の場合)
754    function sfArrKeyValues($arrList, $keyname, $valname, $len_max = "", $keysize = "", $connect = "") {
755
756        $max = count($arrList);
757
758        if($len_max != "" && $max > $len_max) {
759            $max = $len_max;
760        }
761
762        for($cnt = 0; $cnt < $max; $cnt++) {
763            if($keysize != "") {
764                $key = $this->sfCutString($arrList[$cnt][$keyname], $keysize);
765            } else {
766                $key = $arrList[$cnt][$keyname];
767            }
768            $val = $arrList[$cnt][$valname];
769
770            if($connect != "") {
771                $arrRet[$key].= "$val".$connect;
772            } else {
773                $arrRet[$key][] = $val;
774            }
775        }
776        return $arrRet;
777    }
778
779    // 配列の値をカンマ区切りで返す。
780    function sfGetCommaList($array, $space=true) {
781        if (count($array) > 0) {
782            $line = "";
783            foreach($array as $val) {
784                if ($space) {
785                    $line .= $val . ", ";
786                }else{
787                    $line .= $val . ",";
788                }
789            }
790            if ($space) {
791                $line = ereg_replace(", $", "", $line);
792            }else{
793                $line = ereg_replace(",$", "", $line);
794            }
795            return $line;
796        }else{
797            return false;
798        }
799
800    }
801
802    /* 配列の要素をCSVフォーマットで出力する。*/
803    function sfGetCSVList($array) {
804        if (count($array) > 0) {
805            foreach($array as $key => $val) {
806                $val = mb_convert_encoding($val, CHAR_CODE, CHAR_CODE);
807                $line .= "\"".$val."\",";
808            }
809            $line = ereg_replace(",$", "\n", $line);
810        }else{
811            return false;
812        }
813        return $line;
814    }
815
816    /* 配列の要素をPDFフォーマットで出力する。*/
817    function sfGetPDFList($array) {
818        foreach($array as $key => $val) {
819            $line .= "\t".$val;
820        }
821        $line.="\n";
822        return $line;
823    }
824
825
826
827    /*-----------------------------------------------------------------*/
828    /*  check_set_term
829    /*  年月日に別れた2つの期間の妥当性をチェックし、整合性と期間を返す
830    /* 引数 (開始年,開始月,開始日,終了年,終了月,終了日)
831    /* 戻値 array(1,2,3)
832    /*          1.開始年月日 (YYYY/MM/DD 000000)
833    /*          2.終了年月日 (YYYY/MM/DD 235959)
834    /*          3.エラー ( 0 = OK, 1 = NG )
835    /*-----------------------------------------------------------------*/
836    function sfCheckSetTerm ( $start_year, $start_month, $start_day, $end_year, $end_month, $end_day ) {
837
838        // 期間指定
839        $error = 0;
840        if ( $start_month || $start_day || $start_year){
841            if ( ! checkdate($start_month, $start_day , $start_year) ) $error = 1;
842        } else {
843            $error = 1;
844        }
845        if ( $end_month || $end_day || $end_year){
846            if ( ! checkdate($end_month ,$end_day ,$end_year) ) $error = 2;
847        }
848        if ( ! $error ){
849            $date1 = $start_year ."/".sprintf("%02d",$start_month) ."/".sprintf("%02d",$start_day) ." 000000";
850            $date2 = $end_year   ."/".sprintf("%02d",$end_month)   ."/".sprintf("%02d",$end_day)   ." 235959";
851            if ($date1 > $date2) $error = 3;
852        } else {
853            $error = 1;
854        }
855        return array($date1, $date2, $error);
856    }
857
858    // エラー箇所の背景色を変更するためのfunction SC_Viewで読み込む
859    function sfSetErrorStyle(){
860        return 'style="background-color:'.ERR_COLOR.'"';
861    }
862
863    /* DBに渡す数値のチェック
864     * 10桁以上はオーバーフローエラーを起こすので。
865     */
866    function sfCheckNumLength( $value ){
867        if ( ! is_numeric($value)  ){
868            return false;
869        }
870
871        if ( strlen($value) > 9 ) {
872            return false;
873        }
874
875        return true;
876    }
877
878    // 一致した値のキー名を取得
879    function sfSearchKey($array, $word, $default) {
880        foreach($array as $key => $val) {
881            if($val == $word) {
882                return $key;
883            }
884        }
885        return $default;
886    }
887
888    // カテゴリツリーの取得($products_check:true商品登録済みのものだけ取得)
889    function sfGetCategoryList($addwhere = "", $products_check = false, $head = CATEGORY_HEAD) {
890        $objQuery = new SC_Query();
891        $where = "del_flg = 0";
892
893        if($addwhere != "") {
894            $where.= " AND $addwhere";
895        }
896
897        $objQuery->setoption("ORDER BY rank DESC");
898
899        if($products_check) {
900            $col = "T1.category_id, category_name, level";
901            $from = "dtb_category AS T1 LEFT JOIN dtb_category_total_count AS T2 ON T1.category_id = T2.category_id";
902            $where .= " AND product_count > 0";
903        } else {
904            $col = "category_id, category_name, level";
905            $from = "dtb_category";
906        }
907
908        $arrRet = $objQuery->select($col, $from, $where);
909
910        $max = count($arrRet);
911        for($cnt = 0; $cnt < $max; $cnt++) {
912            $id = $arrRet[$cnt]['category_id'];
913            $name = $arrRet[$cnt]['category_name'];
914            $arrList[$id] = "";
915            /*
916            for($n = 1; $n < $arrRet[$cnt]['level']; $n++) {
917                $arrList[$id].= " ";
918            }
919            */
920            for($cat_cnt = 0; $cat_cnt < $arrRet[$cnt]['level']; $cat_cnt++) {
921                $arrList[$id].= $head;
922            }
923            $arrList[$id].= $name;
924        }
925        return $arrList;
926    }
927
928    // カテゴリツリーの取得(親カテゴリのValue:0)
929    function sfGetLevelCatList($parent_zero = true) {
930        $objQuery = new SC_Query();
931        $col = "category_id, category_name, level";
932        $where = "del_flg = 0";
933        $objQuery->setoption("ORDER BY rank DESC");
934        $arrRet = $objQuery->select($col, "dtb_category", $where);
935        $max = count($arrRet);
936
937        for($cnt = 0; $cnt < $max; $cnt++) {
938            if($parent_zero) {
939                if($arrRet[$cnt]['level'] == LEVEL_MAX) {
940                    $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
941                } else {
942                    $arrValue[$cnt] = "";
943                }
944            } else {
945                $arrValue[$cnt] = $arrRet[$cnt]['category_id'];
946            }
947
948            $arrOutput[$cnt] = "";
949            /*
950            for($n = 1; $n < $arrRet[$cnt]['level']; $n++) {
951                $arrOutput[$cnt].= " ";
952            }
953            */
954            for($cat_cnt = 0; $cat_cnt < $arrRet[$cnt]['level']; $cat_cnt++) {
955                $arrOutput[$cnt].= CATEGORY_HEAD;
956            }
957            $arrOutput[$cnt].= $arrRet[$cnt]['category_name'];
958        }
959        return array($arrValue, $arrOutput);
960    }
961
962    function sfGetErrorColor($val) {
963        if($val != "") {
964            return "background-color:" . ERR_COLOR;
965        }
966        return "";
967    }
968
969
970    function sfGetEnabled($val) {
971        if( ! $val ) {
972            return " disabled=\"disabled\"";
973        }
974        return "";
975    }
976
977    function sfGetChecked($param, $value) {
978        if($param == $value) {
979            return "checked=\"checked\"";
980        }
981        return "";
982    }
983
984    function sfTrim($str) {
985        $ret = ereg_replace("^[  \n\r]*", "", $str);
986        $ret = ereg_replace("[  \n\r]*$", "", $ret);
987        return $ret;
988    }
989
990    /* 所属するすべての階層の親IDを配列で返す */
991    function sfGetParents($objQuery, $table, $pid_name, $id_name, $id) {
992        $arrRet = SC_Utils::sfGetParentsArray($table, $pid_name, $id_name, $id);
993        // 配列の先頭1つを削除する。
994        array_shift($arrRet);
995        return $arrRet;
996    }
997
998
999    /* 親IDの配列を元に特定のカラムを取得する。*/
1000    function sfGetParentsCol($objQuery, $table, $id_name, $col_name, $arrId ) {
1001        $col = $col_name;
1002        $len = count($arrId);
1003        $where = "";
1004
1005        for($cnt = 0; $cnt < $len; $cnt++) {
1006            if($where == "") {
1007                $where = "$id_name = ?";
1008            } else {
1009                $where.= " OR $id_name = ?";
1010            }
1011        }
1012
1013        $objQuery->setorder("level");
1014        $arrRet = $objQuery->select($col, $table, $where, $arrId);
1015        return $arrRet;
1016    }
1017
1018    /* 子IDの配列を返す */
1019    function sfGetChildsID($table, $pid_name, $id_name, $id) {
1020        $arrRet = SC_Utils::sfGetChildrenArray($table, $pid_name, $id_name, $id);
1021        return $arrRet;
1022    }
1023
1024    /* カテゴリ変更時の移動処理 */
1025    function sfMoveCatRank($objQuery, $table, $id_name, $cat_name, $old_catid, $new_catid, $id) {
1026        if ($old_catid == $new_catid) {
1027            return;
1028        }
1029        // 旧カテゴリでのランク削除処理
1030        // 移動レコードのランクを取得する。
1031        $where = "$id_name = ?";
1032        $rank = $objQuery->get($table, "rank", $where, array($id));
1033        // 削除レコードのランクより上のレコードを一つ下にずらす。
1034        $where = "rank > ? AND $cat_name = ?";
1035        $sqlup = "UPDATE $table SET rank = (rank - 1) WHERE $where";
1036        $objQuery->exec($sqlup, array($rank, $old_catid));
1037        // 新カテゴリでの登録処理
1038        // 新カテゴリの最大ランクを取得する。
1039        $max_rank = $objQuery->max($table, "rank", "$cat_name = ?", array($new_catid)) + 1;
1040        $where = "$id_name = ?";
1041        $sqlup = "UPDATE $table SET rank = ? WHERE $where";
1042        $objQuery->exec($sqlup, array($max_rank, $id));
1043    }
1044
1045    /* 税金計算 */
1046    function sfTax($price, $tax, $tax_rule) {
1047        $real_tax = $tax / 100;
1048        $ret = $price * $real_tax;
1049        switch($tax_rule) {
1050        // 四捨五入
1051        case 1:
1052            $ret = round($ret);
1053            break;
1054        // 切り捨て
1055        case 2:
1056            $ret = floor($ret);
1057            break;
1058        // 切り上げ
1059        case 3:
1060            $ret = ceil($ret);
1061            break;
1062        // デフォルト:切り上げ
1063        default:
1064            $ret = ceil($ret);
1065            break;
1066        }
1067        return $ret;
1068    }
1069
1070    /* 税金付与 */
1071    function sfPreTax($price, $tax, $tax_rule) {
1072        $real_tax = $tax / 100;
1073        $ret = $price * (1 + $real_tax);
1074
1075        switch($tax_rule) {
1076        // 四捨五入
1077        case 1:
1078            $ret = round($ret);
1079            break;
1080        // 切り捨て
1081        case 2:
1082            $ret = floor($ret);
1083            break;
1084        // 切り上げ
1085        case 3:
1086            $ret = ceil($ret);
1087            break;
1088        // デフォルト:切り上げ
1089        default:
1090            $ret = ceil($ret);
1091            break;
1092        }
1093        return $ret;
1094    }
1095
1096    // 桁数を指定して四捨五入
1097    function sfRound($value, $pow = 0){
1098        $adjust = pow(10 ,$pow-1);
1099
1100        // 整数且つ0出なければ桁数指定を行う
1101        if(SC_Utils::sfIsInt($adjust) and $pow > 1){
1102            $ret = (round($value * $adjust)/$adjust);
1103        }
1104
1105        $ret = round($ret);
1106
1107        return $ret;
1108    }
1109
1110    /* ポイント付与 */
1111    function sfPrePoint($price, $point_rate, $rule = POINT_RULE, $product_id = "") {
1112        if(SC_Utils::sfIsInt($product_id)) {
1113            $objQuery = new SC_Query();
1114            $where = "now() >= cast(start_date as date) AND ";
1115            $where .= "now() < cast(end_date as date) AND ";
1116
1117            $where .= "del_flg = 0 AND campaign_id IN (SELECT campaign_id FROM dtb_campaign_detail where product_id = ? )";
1118            //登録(更新)日付順
1119            $objQuery->setorder('update_date DESC');
1120            //キャンペーンポイントの取得
1121            $arrRet = $objQuery->select("campaign_name, campaign_point_rate", "dtb_campaign", $where, array($product_id));
1122        }
1123        //複数のキャンペーンに登録されている商品は、最新のキャンペーンからポイントを取得
1124        if($arrRet[0]['campaign_point_rate'] != "") {
1125            $campaign_point_rate = $arrRet[0]['campaign_point_rate'];
1126            $real_point = $campaign_point_rate / 100;
1127        } else {
1128            $real_point = $point_rate / 100;
1129        }
1130        $ret = $price * $real_point;
1131        switch($rule) {
1132        // 四捨五入
1133        case 1:
1134            $ret = round($ret);
1135            break;
1136        // 切り捨て
1137        case 2:
1138            $ret = floor($ret);
1139            break;
1140        // 切り上げ
1141        case 3:
1142            $ret = ceil($ret);
1143            break;
1144        // デフォルト:切り上げ
1145        default:
1146            $ret = ceil($ret);
1147            break;
1148        }
1149        //キャンペーン商品の場合
1150        if($campaign_point_rate != "") {
1151            $ret = "(".$arrRet[0]['campaign_name']."ポイント率".$campaign_point_rate."%)".$ret;
1152        }
1153        return $ret;
1154    }
1155
1156    /* 規格分類の件数取得 */
1157    function sfGetClassCatCount() {
1158        $sql = "select count(dtb_class.class_id) as count, dtb_class.class_id ";
1159        $sql.= "from dtb_class inner join dtb_classcategory on dtb_class.class_id = dtb_classcategory.class_id ";
1160        $sql.= "where dtb_class.del_flg = 0 AND dtb_classcategory.del_flg = 0 ";
1161        $sql.= "group by dtb_class.class_id, dtb_class.name";
1162        $objQuery = new SC_Query();
1163        $arrList = $objQuery->getall($sql);
1164        // キーと値をセットした配列を取得
1165        $arrRet = sfArrKeyValue($arrList, 'class_id', 'count');
1166
1167        return $arrRet;
1168    }
1169
1170    /* 規格の登録 */
1171    function sfInsertProductClass($objQuery, $arrList, $product_id) {
1172        // すでに規格登録があるかどうかをチェックする。
1173        $where = "product_id = ? AND classcategory_id1 <> 0 AND classcategory_id1 <> 0";
1174        $count = $objQuery->count("dtb_products_class", $where,  array($product_id));
1175
1176        // すでに規格登録がない場合
1177        if($count == 0) {
1178            // 既存規格の削除
1179            $where = "product_id = ?";
1180            $objQuery->delete("dtb_products_class", $where, array($product_id));
1181            $sqlval['product_id'] = $product_id;
1182            $sqlval['classcategory_id1'] = '0';
1183            $sqlval['classcategory_id2'] = '0';
1184            $sqlval['product_code'] = $arrList["product_code"];
1185            $sqlval['stock'] = $arrList["stock"];
1186            $sqlval['stock_unlimited'] = $arrList["stock_unlimited"];
1187            $sqlval['price01'] = $arrList['price01'];
1188            $sqlval['price02'] = $arrList['price02'];
1189            $sqlval['creator_id'] = $_SESSION['member_id'];
1190            $sqlval['create_date'] = "now()";
1191
1192            if($_SESSION['member_id'] == "") {
1193                $sqlval['creator_id'] = '0';
1194            }
1195
1196            // INSERTの実行
1197            $objQuery->insert("dtb_products_class", $sqlval);
1198        }
1199    }
1200
1201    function sfGetProductClassId($product_id, $classcategory_id1, $classcategory_id2) {
1202        $where = "product_id = ? AND classcategory_id1 = ? AND classcategory_id2 = ?";
1203        $objQuery = new SC_Query();
1204        $ret = $objQuery->get("dtb_products_class", "product_class_id", $where, Array($product_id, $classcategory_id1, $classcategory_id2));
1205        return $ret;
1206    }
1207
1208    /* 文末の「/」をなくす */
1209    function sfTrimURL($url) {
1210        $ret = ereg_replace("[/]+$", "", $url);
1211        return $ret;
1212    }
1213
1214    /* 集計情報を元に最終計算 */
1215    function sfTotalConfirm($arrData, $objPage, $objCartSess, $arrInfo, $objCustomer = "") {
1216        // 商品の合計個数
1217        $total_quantity = $objCartSess->getTotalQuantity(true);
1218
1219        // 税金の取得
1220        $arrData['tax'] = $objPage->tpl_total_tax;
1221        // 小計の取得
1222        $arrData['subtotal'] = $objPage->tpl_total_pretax;
1223
1224        // 合計送料の取得
1225        $arrData['deliv_fee'] = 0;
1226
1227        // 商品ごとの送料が有効の場合
1228        if (OPTION_PRODUCT_DELIV_FEE == 1) {
1229            $arrData['deliv_fee']+= $objCartSess->getAllProductsDelivFee();
1230        }
1231
1232        // 配送業者の送料が有効の場合
1233        if (OPTION_DELIV_FEE == 1) {
1234            // 送料の合計を計算する
1235            $arrData['deliv_fee']+= SC_Utils::sfGetDelivFee($arrData['deliv_pref'], $arrData['payment_id']);
1236        }
1237
1238        // 送料無料の購入数が設定されている場合
1239        if(DELIV_FREE_AMOUNT > 0) {
1240            if($total_quantity >= DELIV_FREE_AMOUNT) {
1241                $arrData['deliv_fee'] = 0;
1242            }
1243        }
1244
1245        // 送料無料条件が設定されている場合
1246        if($arrInfo['free_rule'] > 0) {
1247            // 小計が無料条件を超えている場合
1248            if($arrData['subtotal'] >= $arrInfo['free_rule']) {
1249                $arrData['deliv_fee'] = 0;
1250            }
1251        }
1252
1253        // 合計の計算
1254        $arrData['total'] = $objPage->tpl_total_pretax; // 商品合計
1255        $arrData['total']+= $arrData['deliv_fee'];      // 送料
1256        $arrData['total']+= $arrData['charge'];         // 手数料
1257        // お支払い合計
1258        $arrData['payment_total'] = $arrData['total'] - ($arrData['use_point'] * POINT_VALUE);
1259        // 加算ポイントの計算
1260        $arrData['add_point'] = SC_Utils::sfGetAddPoint($objPage->tpl_total_point, $arrData['use_point'], $arrInfo);
1261
1262        if($objCustomer != "") {
1263            // 誕生日月であった場合
1264            if($objCustomer->isBirthMonth()) {
1265                $arrData['birth_point'] = BIRTH_MONTH_POINT;
1266                $arrData['add_point'] += $arrData['birth_point'];
1267            }
1268        }
1269
1270        if($arrData['add_point'] < 0) {
1271            $arrData['add_point'] = 0;
1272        }
1273
1274        return $arrData;
1275    }
1276
1277    /* DBから取り出した日付の文字列を調整する。*/
1278    function sfDispDBDate($dbdate, $time = true) {
1279        list($y, $m, $d, $H, $M) = split("[- :]", $dbdate);
1280
1281        if(strlen($y) > 0 && strlen($m) > 0 && strlen($d) > 0) {
1282            if ($time) {
1283                $str = sprintf("%04d/%02d/%02d %02d:%02d", $y, $m, $d, $H, $M);
1284            } else {
1285                $str = sprintf("%04d/%02d/%02d", $y, $m, $d, $H, $M);
1286            }
1287        } else {
1288            $str = "";
1289        }
1290        return $str;
1291    }
1292
1293    function sfGetDelivTime($payment_id = "") {
1294        $objQuery = new SC_Query();
1295
1296        $deliv_id = "";
1297
1298        if($payment_id != "") {
1299            $where = "del_flg = 0 AND payment_id = ?";
1300            $arrRet = $objQuery->select("deliv_id", "dtb_payment", $where, array($payment_id));
1301            $deliv_id = $arrRet[0]['deliv_id'];
1302        }
1303
1304        if($deliv_id != "") {
1305            $objQuery->setorder("time_id");
1306            $where = "deliv_id = ?";
1307            $arrRet= $objQuery->select("time_id, deliv_time", "dtb_delivtime", $where, array($deliv_id));
1308        }
1309
1310        return $arrRet;
1311    }
1312
1313
1314    // 都道府県、支払い方法から配送料金を取得する
1315    function sfGetDelivFee($pref, $payment_id = "") {
1316        $objQuery = new SC_Query();
1317
1318        $deliv_id = "";
1319
1320        // 支払い方法が指定されている場合は、対応した配送業者を取得する
1321        if($payment_id != "") {
1322            $where = "del_flg = 0 AND payment_id = ?";
1323            $arrRet = $objQuery->select("deliv_id", "dtb_payment", $where, array($payment_id));
1324            $deliv_id = $arrRet[0]['deliv_id'];
1325        // 支払い方法が指定されていない場合は、先頭の配送業者を取得する
1326        } else {
1327            $where = "del_flg = 0";
1328            $objQuery->setOrder("rank DESC");
1329            $objQuery->setLimitOffset(1);
1330            $arrRet = $objQuery->select("deliv_id", "dtb_deliv", $where);
1331            $deliv_id = $arrRet[0]['deliv_id'];
1332        }
1333
1334        // 配送業者から配送料を取得
1335        if($deliv_id != "") {
1336
1337            // 都道府県が指定されていない場合は、東京都の番号を指定しておく
1338            if($pref == "") {
1339                $pref = 13;
1340            }
1341
1342            $objQuery = new SC_Query();
1343            $where = "deliv_id = ? AND pref = ?";
1344            $arrRet= $objQuery->select("fee", "dtb_delivfee", $where, array($deliv_id, $pref));
1345        }
1346        return $arrRet[0]['fee'];
1347    }
1348
1349    /* 支払い方法の取得 */
1350    function sfGetPayment() {
1351        $objQuery = new SC_Query();
1352        // 購入金額が条件額以下の項目を取得
1353        $where = "del_flg = 0";
1354        $objQuery->setorder("fix, rank DESC");
1355        $arrRet = $objQuery->select("payment_id, payment_method, rule", "dtb_payment", $where);
1356        return $arrRet;
1357    }
1358
1359    /* 配列をキー名ごとの配列に変更する */
1360    function sfSwapArray($array) {
1361        $max = count($array);
1362        for($i = 0; $i < $max; $i++) {
1363            foreach($array[$i] as $key => $val) {
1364                $arrRet[$key][] = $val;
1365            }
1366        }
1367        return $arrRet;
1368    }
1369
1370    /* かけ算をする(Smarty用) */
1371    function sfMultiply($num1, $num2) {
1372        return ($num1 * $num2);
1373    }
1374
1375    /* DBに登録されたテンプレートメールの送信 */
1376    function sfSendTemplateMail($to, $to_name, $template_id, $objPage) {
1377        global $arrMAILTPLPATH;
1378        $objQuery = new SC_Query();
1379        // メールテンプレート情報の取得
1380        $where = "template_id = ?";
1381        $arrRet = $objQuery->select("subject, header, footer", "dtb_mailtemplate", $where, array($template_id));
1382        $objPage->tpl_header = $arrRet[0]['header'];
1383        $objPage->tpl_footer = $arrRet[0]['footer'];
1384        $tmp_subject = $arrRet[0]['subject'];
1385
1386        $objSiteInfo = new SC_SiteInfo();
1387        $arrInfo = $objSiteInfo->data;
1388
1389        $objMailView = new SC_SiteView();
1390        // メール本文の取得
1391        $objMailView->assignobj($objPage);
1392        $body = $objMailView->fetch($arrMAILTPLPATH[$template_id]);
1393
1394        // メール送信処理
1395        $objSendMail = new GC_SendMail();
1396        $from = $arrInfo['email03'];
1397        $error = $arrInfo['email04'];
1398        $tosubject = $tmp_subject;
1399        $objSendMail->setItem('', $tosubject, $body, $from, $arrInfo['shop_name'], $from, $error, $error);
1400        $objSendMail->setTo($to, $to_name);
1401        $objSendMail->sendMail();   // メール送信
1402    }
1403
1404    /* 受注完了メール送信 */
1405    function sfSendOrderMail($order_id, $template_id, $subject = "", $header = "", $footer = "", $send = true) {
1406        global $arrMAILTPLPATH;
1407
1408        $objPage = new LC_Page();
1409        $objSiteInfo = new SC_SiteInfo();
1410        $arrInfo = $objSiteInfo->data;
1411        $objPage->arrInfo = $arrInfo;
1412
1413        $objQuery = new SC_Query();
1414
1415        if($subject == "" && $header == "" && $footer == "") {
1416            // メールテンプレート情報の取得
1417            $where = "template_id = ?";
1418            $arrRet = $objQuery->select("subject, header, footer", "dtb_mailtemplate", $where, array('1'));
1419            $objPage->tpl_header = $arrRet[0]['header'];
1420            $objPage->tpl_footer = $arrRet[0]['footer'];
1421            $tmp_subject = $arrRet[0]['subject'];
1422        } else {
1423            $objPage->tpl_header = $header;
1424            $objPage->tpl_footer = $footer;
1425            $tmp_subject = $subject;
1426        }
1427
1428        // 受注情報の取得
1429        $where = "order_id = ?";
1430        $arrRet = $objQuery->select("*", "dtb_order", $where, array($order_id));
1431        $arrOrder = $arrRet[0];
1432        $arrOrderDetail = $objQuery->select("*", "dtb_order_detail", $where, array($order_id));
1433
1434        $objPage->Message_tmp = $arrOrder['message'];
1435
1436        // 顧客情報の取得
1437        $customer_id = $arrOrder['customer_id'];
1438        $arrRet = $objQuery->select("point", "dtb_customer", "customer_id = ?", array($customer_id));
1439        $arrCustomer = $arrRet[0];
1440
1441        $objPage->arrCustomer = $arrCustomer;
1442        $objPage->arrOrder = $arrOrder;
1443
1444        //その他決済情報
1445        if($arrOrder['memo02'] != "") {
1446            $arrOther = unserialize($arrOrder['memo02']);
1447
1448            foreach($arrOther as $other_key => $other_val){
1449                if(sfTrim($other_val["value"]) == ""){
1450                    $arrOther[$other_key]["value"] = "";
1451                }
1452            }
1453
1454            $objPage->arrOther = $arrOther;
1455        }
1456
1457        // 都道府県変換
1458        global $arrPref;
1459        $objPage->arrOrder['deliv_pref'] = $arrPref[$objPage->arrOrder['deliv_pref']];
1460
1461        $objPage->arrOrderDetail = $arrOrderDetail;
1462
1463        $objCustomer = new SC_Customer();
1464        $objPage->tpl_user_point = $objCustomer->getValue('point');
1465
1466        $objMailView = new SC_SiteView();
1467        // メール本文の取得
1468        $objMailView->assignobj($objPage);
1469        $body = $objMailView->fetch($arrMAILTPLPATH[$template_id]);
1470
1471        // メール送信処理
1472        $objSendMail = new GC_SendMail();
1473        $bcc = $arrInfo['email01'];
1474        $from = $arrInfo['email03'];
1475        $error = $arrInfo['email04'];
1476
1477        $tosubject = sfMakeSubject($tmp_subject);
1478
1479        $objSendMail->setItem('', $tosubject, $body, $from, $arrInfo['shop_name'], $from, $error, $error, $bcc);
1480        $objSendMail->setTo($arrOrder["order_email"], $arrOrder["order_name01"] . " ". $arrOrder["order_name02"] ." 様");
1481
1482
1483        // 送信フラグ:trueの場合は、送信する。
1484        if($send) {
1485            if ($objSendMail->sendMail()) {
1486                sfSaveMailHistory($order_id, $template_id, $tosubject, $body);
1487            }
1488        }
1489
1490        return $objSendMail;
1491    }
1492
1493    // テンプレートを使用したメールの送信
1494    function sfSendTplMail($to, $subject, $tplpath, $objPage) {
1495        $objMailView = new SC_SiteView();
1496        $objSiteInfo = new SC_SiteInfo();
1497        $arrInfo = $objSiteInfo->data;
1498        // メール本文の取得
1499        $objPage->tpl_shopname=$arrInfo['shop_name'];
1500        $objPage->tpl_infoemail = $arrInfo['email02'];
1501        $objMailView->assignobj($objPage);
1502        $body = $objMailView->fetch($tplpath);
1503        // メール送信処理
1504        $objSendMail = new GC_SendMail();
1505        $to = mb_encode_mimeheader($to);
1506        $bcc = $arrInfo['email01'];
1507        $from = $arrInfo['email03'];
1508        $error = $arrInfo['email04'];
1509        $objSendMail->setItem($to, $subject, $body, $from, $arrInfo['shop_name'], $from, $error, $error, $bcc);
1510        $objSendMail->sendMail();
1511    }
1512
1513    // 通常のメール送信
1514    function sfSendMail($to, $subject, $body) {
1515        $objSiteInfo = new SC_SiteInfo();
1516        $arrInfo = $objSiteInfo->data;
1517        // メール送信処理
1518        $objSendMail = new GC_SendMail();
1519        $bcc = $arrInfo['email01'];
1520        $from = $arrInfo['email03'];
1521        $error = $arrInfo['email04'];
1522        $objSendMail->setItem($to, $subject, $body, $from, $arrInfo['shop_name'], $from, $error, $error, $bcc);
1523        $objSendMail->sendMail();
1524    }
1525
1526    //件名にテンプレートを用いる
1527    function sfMakeSubject($subject){
1528
1529        $objQuery = new SC_Query();
1530        $objMailView = new SC_SiteView();
1531        $objPage = new LC_Page();
1532
1533        $arrInfo = $objQuery->select("*","dtb_baseinfo");
1534        $arrInfo = $arrInfo[0];
1535        $objPage->tpl_shopname=$arrInfo['shop_name'];
1536        $objPage->tpl_infoemail=$subject;
1537        $objMailView->assignobj($objPage);
1538        $mailtitle = $objMailView->fetch('mail_templates/mail_title.tpl');
1539        $ret = $mailtitle.$subject;
1540        return $ret;
1541    }
1542
1543    // メール配信履歴への登録
1544    function sfSaveMailHistory($order_id, $template_id, $subject, $body) {
1545        $sqlval['subject'] = $subject;
1546        $sqlval['order_id'] = $order_id;
1547        $sqlval['template_id'] = $template_id;
1548        $sqlval['send_date'] = "Now()";
1549        if($_SESSION['member_id'] != "") {
1550            $sqlval['creator_id'] = $_SESSION['member_id'];
1551        } else {
1552            $sqlval['creator_id'] = '0';
1553        }
1554        $sqlval['mail_body'] = $body;
1555
1556        $objQuery = new SC_Query();
1557        $objQuery->insert("dtb_mail_history", $sqlval);
1558    }
1559
1560    /* 会員のメルマガ登録があるかどうかのチェック(仮会員を含まない) */
1561    function sfCheckCustomerMailMaga($email) {
1562        $col = "email, mailmaga_flg, customer_id";
1563        $from = "dtb_customer";
1564        $where = "email = ? AND status = 2";
1565        $objQuery = new SC_Query();
1566        $arrRet = $objQuery->select($col, $from, $where, array($email));
1567        // 会員のメールアドレスが登録されている
1568        if($arrRet[0]['customer_id'] != "") {
1569            return true;
1570        }
1571        return false;
1572    }
1573
1574    // カードの処理結果を返す
1575    function sfGetAuthonlyResult($dir, $file_name, $name01, $name02, $card_no, $card_exp, $amount, $order_id, $jpo_info = "10"){
1576
1577        $path = $dir .$file_name;       // cgiファイルのフルパス生成
1578        $now_dir = getcwd();            // requireがうまくいかないので、cgi実行ディレクトリに移動する
1579        chdir($dir);
1580
1581        // パイプ渡しでコマンドラインからcgi起動
1582        $cmd = "$path card_no=$card_no name01=$name01 name02=$name02 card_exp=$card_exp amount=$amount order_id=$order_id jpo_info=$jpo_info";
1583
1584        $tmpResult = popen($cmd, "r");
1585
1586        // 結果取得
1587        while( ! FEOF ( $tmpResult ) ) {
1588            $result .= FGETS($tmpResult);
1589        }
1590        pclose($tmpResult);             //  パイプを閉じる
1591        chdir($now_dir);                // 元にいたディレクトリに帰る
1592
1593        // 結果を連想配列へ格納
1594        $result = ereg_replace("&$", "", $result);
1595        foreach (explode("&",$result) as $data) {
1596            list($key, $val) = explode("=", $data, 2);
1597            $return[$key] = $val;
1598        }
1599
1600        return $return;
1601    }
1602
1603    // カテゴリID取得判定用のグローバル変数(一度取得されていたら再取得しないようにする)
1604    //$g_category_on = false;
1605    //$g_category_id = "";
1606
1607    /* 選択中のカテゴリを取得する */
1608    function sfGetCategoryId($product_id, $category_id) {
1609        global $g_category_on;
1610        global $g_category_id;
1611        if(!$g_category_on) {
1612            $g_category_on = true;
1613            $category_id = (int) $category_id;
1614            $product_id = (int) $product_id;
1615            if(SC_Utils_Ex::sfIsInt($category_id) && SC_Utils_Ex::sfIsRecord("dtb_category","category_id", $category_id)) {
1616                $g_category_id = $category_id;
1617            } else if (SC_Utils_Ex::sfIsInt($product_id) && SC_Utils_Ex::sfIsRecord("dtb_products","product_id", $product_id, "status = 1")) {
1618                $objQuery = new SC_Query();
1619                $where = "product_id = ?";
1620                $category_id = $objQuery->get("dtb_products", "category_id", $where, array($product_id));
1621                $g_category_id = $category_id;
1622            } else {
1623                // 不正な場合は、0を返す。
1624                $g_category_id = 0;
1625            }
1626        }
1627        return $g_category_id;
1628    }
1629
1630    // ROOTID取得判定用のグローバル変数(一度取得されていたら再取得しないようにする)
1631    //$g_root_on = false;
1632    //$g_root_id = "";
1633
1634    /* 選択中のアイテムのルートカテゴリIDを取得する */
1635    function sfGetRootId() {
1636        global $g_root_on;
1637        global $g_root_id;
1638        if(!$g_root_on) {
1639            $g_root_on = true;
1640            $objQuery = new SC_Query();
1641            if($_GET['product_id'] != "" || $_GET['category_id'] != "") {
1642                // 選択中のカテゴリIDを判定する
1643                $category_id = SC_Utils::sfGetCategoryId($_GET['product_id'], $_GET['category_id']);
1644                // ROOTカテゴリIDの取得
1645                 $arrRet = SC_Utils::sfGetParents($objQuery, 'dtb_category', 'parent_category_id', 'category_id', $category_id);
1646                 $root_id = $arrRet[0];
1647            } else {
1648                // ROOTカテゴリIDをなしに設定する
1649                $root_id = "";
1650            }
1651            $g_root_id = $root_id;
1652        }
1653        return $g_root_id;
1654    }
1655
1656    /* カテゴリから商品を検索する場合のWHERE文と値を返す */
1657    function sfGetCatWhere($category_id) {
1658        // 子カテゴリIDの取得
1659        $arrRet = SC_Utils::sfGetChildsID("dtb_category", "parent_category_id", "category_id", $category_id);
1660        $tmp_where = "";
1661        foreach ($arrRet as $val) {
1662            if($tmp_where == "") {
1663                $tmp_where.= " category_id IN ( ?";
1664            } else {
1665                $tmp_where.= ",? ";
1666            }
1667            $arrval[] = $val;
1668        }
1669        $tmp_where.= " ) ";
1670        return array($tmp_where, $arrval);
1671    }
1672
1673    /* 加算ポイントの計算式 */
1674    function sfGetAddPoint($totalpoint, $use_point, $arrInfo) {
1675        // 購入商品の合計ポイントから利用したポイントのポイント換算価値を引く方式
1676        $add_point = $totalpoint - intval($use_point * ($arrInfo['point_rate'] / 100));
1677
1678        if($add_point < 0) {
1679            $add_point = '0';
1680        }
1681        return $add_point;
1682    }
1683
1684    /* 一意かつ予測されにくいID */
1685    function sfGetUniqRandomId($head = "") {
1686        // 予測されないようにランダム文字列を付与する。
1687        $random = GC_Utils_Ex::gfMakePassword(8);
1688        // 同一ホスト内で一意なIDを生成
1689        $id = uniqid($head);
1690        return ($id . $random);
1691    }
1692
1693    // カテゴリ別オススメ品の取得
1694    function sfGetBestProducts( $conn, $category_id = 0){
1695        // 既に登録されている内容を取得する
1696        $sql = "SELECT name, main_image, main_list_image, price01_min, price01_max, price02_min, price02_max, point_rate,
1697                 A.product_id, A.comment FROM dtb_best_products as A LEFT JOIN vw_products_allclass AS allcls
1698                USING (product_id) WHERE A.category_id = ? AND A.del_flg = 0 AND status = 1 ORDER BY A.rank";
1699        $arrItems = $conn->getAll($sql, array($category_id));
1700
1701        return $arrItems;
1702    }
1703
1704    // 特殊制御文字の手動エスケープ
1705    function sfManualEscape($data) {
1706        // 配列でない場合
1707        if(!is_array($data)) {
1708            if (DB_TYPE == "pgsql") {
1709                $ret = pg_escape_string($data);
1710            }else if(DB_TYPE == "mysql"){
1711                $ret = mysql_real_escape_string($data);
1712            }
1713            $ret = ereg_replace("%", "\\%", $ret);
1714            $ret = ereg_replace("_", "\\_", $ret);
1715            return $ret;
1716        }
1717
1718        // 配列の場合
1719        foreach($data as $val) {
1720            if (DB_TYPE == "pgsql") {
1721                $ret = pg_escape_string($val);
1722            }else if(DB_TYPE == "mysql"){
1723                $ret = mysql_real_escape_string($val);
1724            }
1725
1726            $ret = ereg_replace("%", "\\%", $ret);
1727            $ret = ereg_replace("_", "\\_", $ret);
1728            $arrRet[] = $ret;
1729        }
1730
1731        return $arrRet;
1732    }
1733
1734    // 受注番号、利用ポイント、加算ポイントから最終ポイントを取得
1735    function sfGetCustomerPoint($order_id, $use_point, $add_point) {
1736        $objQuery = new SC_Query();
1737        $arrRet = $objQuery->select("customer_id", "dtb_order", "order_id = ?", array($order_id));
1738        $customer_id = $arrRet[0]['customer_id'];
1739        if($customer_id != "" && $customer_id >= 1) {
1740            $arrRet = $objQuery->select("point", "dtb_customer", "customer_id = ?", array($customer_id));
1741            $point = $arrRet[0]['point'];
1742            $total_point = $arrRet[0]['point'] - $use_point + $add_point;
1743        } else {
1744            $total_point = "";
1745            $point = "";
1746        }
1747        return array($point, $total_point);
1748    }
1749
1750    /* ドメイン間で有効なセッションのスタート */
1751    function sfDomainSessionStart() {
1752        $ret = session_id();
1753    /*
1754        ヘッダーを送信していてもsession_start()が必要なページがあるので
1755        コメントアウトしておく
1756        if($ret == "" && !headers_sent()) {
1757    */
1758        if($ret == "") {
1759            /* セッションパラメータの指定
1760             ・ブラウザを閉じるまで有効
1761             ・すべてのパスで有効
1762             ・同じドメイン間で共有 */
1763            session_set_cookie_params (0, "/", DOMAIN_NAME);
1764
1765            if(!ini_get("session.auto_start")){
1766                // セッション開始
1767                session_start();
1768            }
1769        }
1770    }
1771
1772    /* 文字列に強制的に改行を入れる */
1773    function sfPutBR($str, $size) {
1774        $i = 0;
1775        $cnt = 0;
1776        $line = array();
1777        $ret = "";
1778
1779        while($str[$i] != "") {
1780            $line[$cnt].=$str[$i];
1781            $i++;
1782            if(strlen($line[$cnt]) > $size) {
1783                $line[$cnt].="<br />";
1784                $cnt++;
1785            }
1786        }
1787
1788        foreach($line as $val) {
1789            $ret.=$val;
1790        }
1791        return $ret;
1792    }
1793
1794    // 二回以上繰り返されているスラッシュ[/]を一つに変換する。
1795    function sfRmDupSlash($istr){
1796        if(ereg("^http://", $istr)) {
1797            $str = substr($istr, 7);
1798            $head = "http://";
1799        } else if(ereg("^https://", $istr)) {
1800            $str = substr($istr, 8);
1801            $head = "https://";
1802        } else {
1803            $str = $istr;
1804        }
1805        $str = ereg_replace("[/]+", "/", $str);
1806        $ret = $head . $str;
1807        return $ret;
1808    }
1809
1810    function sfEncodeFile($filepath, $enc_type, $out_dir) {
1811        $ifp = fopen($filepath, "r");
1812
1813        $basename = basename($filepath);
1814        $outpath = $out_dir . "enc_" . $basename;
1815
1816        $ofp = fopen($outpath, "w+");
1817
1818        while(!feof($ifp)) {
1819            $line = fgets($ifp);
1820            $line = mb_convert_encoding($line, $enc_type, "auto");
1821            fwrite($ofp,  $line);
1822        }
1823
1824        fclose($ofp);
1825        fclose($ifp);
1826
1827        return  $outpath;
1828    }
1829
1830    function sfCutString($str, $len, $byte = true, $commadisp = true) {
1831        if($byte) {
1832            if(strlen($str) > ($len + 2)) {
1833                $ret =substr($str, 0, $len);
1834                $cut = substr($str, $len);
1835            } else {
1836                $ret = $str;
1837                $commadisp = false;
1838            }
1839        } else {
1840            if(mb_strlen($str) > ($len + 1)) {
1841                $ret = mb_substr($str, 0, $len);
1842                $cut = mb_substr($str, $len);
1843            } else {
1844                $ret = $str;
1845                $commadisp = false;
1846            }
1847        }
1848
1849        // 絵文字タグの途中で分断されないようにする。
1850        if (isset($cut)) {
1851            // 分割位置より前の最後の [ 以降を取得する。
1852            $head = strrchr($ret, '[');
1853
1854            // 分割位置より後の最初の ] 以前を取得する。
1855            $tail_pos = strpos($cut, ']');
1856            if ($tail_pos !== false) {
1857                $tail = substr($cut, 0, $tail_pos + 1);
1858            }
1859
1860            // 分割位置より前に [、後に ] が見つかった場合は、[ から ] までを
1861            // 接続して絵文字タグ1個分になるかどうかをチェックする。
1862            if ($head !== false && $tail_pos !== false) {
1863                $subject = $head . $tail;
1864                if (preg_match('/^\[emoji:e?\d+\]$/', $subject)) {
1865                    // 絵文字タグが見つかったので削除する。
1866                    $ret = substr($ret, 0, -strlen($head));
1867                }
1868            }
1869        }
1870
1871        if($commadisp){
1872            $ret = $ret . "...";
1873        }
1874        return $ret;
1875    }
1876
1877    // 年、月、締め日から、先月の締め日+1、今月の締め日を求める。
1878    function sfTermMonth($year, $month, $close_day) {
1879        $end_year = $year;
1880        $end_month = $month;
1881
1882        // 開始月が終了月と同じか否か
1883        $same_month = false;
1884
1885        // 該当月の末日を求める。
1886        $end_last_day = date("d", mktime(0, 0, 0, $month + 1, 0, $year));
1887
1888        // 月の末日が締め日より少ない場合
1889        if($end_last_day < $close_day) {
1890            // 締め日を月末日に合わせる
1891            $end_day = $end_last_day;
1892        } else {
1893            $end_day = $close_day;
1894        }
1895
1896        // 前月の取得
1897        $tmp_year = date("Y", mktime(0, 0, 0, $month, 0, $year));
1898        $tmp_month = date("m", mktime(0, 0, 0, $month, 0, $year));
1899        // 前月の末日を求める。
1900        $start_last_day = date("d", mktime(0, 0, 0, $month, 0, $year));
1901
1902        // 前月の末日が締め日より少ない場合
1903        if ($start_last_day < $close_day) {
1904            // 月末日に合わせる
1905            $tmp_day = $start_last_day;
1906        } else {
1907            $tmp_day = $close_day;
1908        }
1909
1910        // 先月の末日の翌日を取得する
1911        $start_year = date("Y", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1912        $start_month = date("m", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1913        $start_day = date("d", mktime(0, 0, 0, $tmp_month, $tmp_day + 1, $tmp_year));
1914
1915        // 日付の作成
1916        $start_date = sprintf("%d/%d/%d 00:00:00", $start_year, $start_month, $start_day);
1917        $end_date = sprintf("%d/%d/%d 23:59:59", $end_year, $end_month, $end_day);
1918
1919        return array($start_date, $end_date);
1920    }
1921
1922    // PDF用のRGBカラーを返す
1923    function sfGetPdfRgb($hexrgb) {
1924        $hex = substr($hexrgb, 0, 2);
1925        $r = hexdec($hex) / 255;
1926
1927        $hex = substr($hexrgb, 2, 2);
1928        $g = hexdec($hex) / 255;
1929
1930        $hex = substr($hexrgb, 4, 2);
1931        $b = hexdec($hex) / 255;
1932
1933        return array($r, $g, $b);
1934    }
1935
1936    //メルマガ仮登録とメール配信
1937    function sfRegistTmpMailData($mail_flag, $email){
1938        $objQuery = new SC_Query();
1939        $objConn = new SC_DBConn();
1940        $objPage = new LC_Page();
1941
1942        $random_id = sfGetUniqRandomId();
1943        $arrRegistMailMagazine["mail_flag"] = $mail_flag;
1944        $arrRegistMailMagazine["email"] = $email;
1945        $arrRegistMailMagazine["temp_id"] =$random_id;
1946        $arrRegistMailMagazine["end_flag"]='0';
1947        $arrRegistMailMagazine["update_date"] = 'now()';
1948
1949        //メルマガ仮登録用フラグ
1950        $flag = $objQuery->count("dtb_customer_mail_temp", "email=?", array($email));
1951        $objConn->query("BEGIN");
1952        switch ($flag){
1953            case '0':
1954            $objConn->autoExecute("dtb_customer_mail_temp",$arrRegistMailMagazine);
1955            break;
1956
1957            case '1':
1958            $objConn->autoExecute("dtb_customer_mail_temp",$arrRegistMailMagazine, "email = '" .addslashes($email). "'");
1959            break;
1960        }
1961        $objConn->query("COMMIT");
1962        $subject = sfMakeSubject('メルマガ仮登録が完了しました。');
1963        $objPage->tpl_url = SSL_URL."mailmagazine/regist.php?temp_id=".$arrRegistMailMagazine['temp_id'];
1964        switch ($mail_flag){
1965            case '1':
1966            $objPage->tpl_name = "登録";
1967            $objPage->tpl_kindname = "HTML";
1968            break;
1969
1970            case '2':
1971            $objPage->tpl_name = "登録";
1972            $objPage->tpl_kindname = "テキスト";
1973            break;
1974
1975            case '3':
1976            $objPage->tpl_name = "解除";
1977            break;
1978        }
1979            $objPage->tpl_email = $email;
1980        sfSendTplMail($email, $subject, 'mail_templates/mailmagazine_temp.tpl', $objPage);
1981    }
1982
1983    // 再帰的に多段配列を検索して一次元配列(Hidden引渡し用配列)に変換する。
1984    function sfMakeHiddenArray($arrSrc, $arrDst = array(), $parent_key = "") {
1985        if(is_array($arrSrc)) {
1986            foreach($arrSrc as $key => $val) {
1987                if($parent_key != "") {
1988                    $keyname = $parent_key . "[". $key . "]";
1989                } else {
1990                    $keyname = $key;
1991                }
1992                if(is_array($val)) {
1993                    $arrDst = sfMakeHiddenArray($val, $arrDst, $keyname);
1994                } else {
1995                    $arrDst[$keyname] = $val;
1996                }
1997            }
1998        }
1999        return $arrDst;
2000    }
2001
2002    // DB取得日時をタイムに変換
2003    function sfDBDatetoTime($db_date) {
2004        $date = ereg_replace("\..*$","",$db_date);
2005        $time = strtotime($date);
2006        return $time;
2007    }
2008
2009    // 出力の際にテンプレートを切り替えられる
2010    /*
2011        index.php?tpl=test.tpl
2012    */
2013    function sfCustomDisplay($objPage, $is_mobile = false) {
2014        $basename = basename($_SERVER["REQUEST_URI"]);
2015
2016        if($basename == "") {
2017            $path = $_SERVER["REQUEST_URI"] . "index.php";
2018        } else {
2019            $path = $_SERVER["REQUEST_URI"];
2020        }
2021
2022        if($_GET['tpl'] != "") {
2023            $tpl_name = $_GET['tpl'];
2024        } else {
2025            $tpl_name = ereg_replace("^/", "", $path);
2026            $tpl_name = ereg_replace("/", "_", $tpl_name);
2027            $tpl_name = ereg_replace("(\.php$|\.html$)", ".tpl", $tpl_name);
2028        }
2029
2030        $template_path = TEMPLATE_FTP_DIR . $tpl_name;
2031
2032        if($is_mobile === true) {
2033            $objView = new SC_MobileView();
2034            $objView->assignobj($objPage);
2035            $objView->display(SITE_FRAME);
2036        } else if(file_exists($template_path)) {
2037            $objView = new SC_UserView(TEMPLATE_FTP_DIR, COMPILE_FTP_DIR);
2038            $objView->assignobj($objPage);
2039            $objView->display($tpl_name);
2040        } else {
2041            $objView = new SC_SiteView();
2042            $objView->assignobj($objPage);
2043            $objView->display(SITE_FRAME);
2044        }
2045    }
2046
2047    //会員編集登録処理
2048    function sfEditCustomerData($array, $arrRegistColumn) {
2049        $objQuery = new SC_Query();
2050
2051        foreach ($arrRegistColumn as $data) {
2052            if ($data["column"] != "password") {
2053                if($array[ $data['column'] ] != "") {
2054                    $arrRegist[ $data["column"] ] = $array[ $data["column"] ];
2055                } else {
2056                    $arrRegist[ $data['column'] ] = NULL;
2057                }
2058            }
2059        }
2060        if (strlen($array["year"]) > 0 && strlen($array["month"]) > 0 && strlen($array["day"]) > 0) {
2061            $arrRegist["birth"] = $array["year"] ."/". $array["month"] ."/". $array["day"] ." 00:00:00";
2062        } else {
2063            $arrRegist["birth"] = NULL;
2064        }
2065
2066        //-- パスワードの更新がある場合は暗号化。(更新がない場合はUPDATE文を構成しない)
2067        if ($array["password"] != DEFAULT_PASSWORD) $arrRegist["password"] = sha1($array["password"] . ":" . AUTH_MAGIC);
2068        $arrRegist["update_date"] = "NOW()";
2069
2070        //-- 編集登録実行
2071        if (defined('MOBILE_SITE')) {
2072            $arrRegist['email_mobile'] = $arrRegist['email'];
2073            unset($arrRegist['email']);
2074        }
2075        $objQuery->begin();
2076        $objQuery->update("dtb_customer", $arrRegist, "customer_id = ? ", array($array['customer_id']));
2077        $objQuery->commit();
2078    }
2079
2080    // PHPのmb_convert_encoding関数をSmartyでも使えるようにする
2081    function sf_mb_convert_encoding($str, $encode = 'CHAR_CODE') {
2082        return  mb_convert_encoding($str, $encode);
2083    }
2084
2085    // PHPのmktime関数をSmartyでも使えるようにする
2086    function sf_mktime($format, $hour=0, $minute=0, $second=0, $month=1, $day=1, $year=1999) {
2087        return  date($format,mktime($hour, $minute, $second, $month, $day, $year));
2088    }
2089
2090    // PHPのdate関数をSmartyでも使えるようにする
2091    function sf_date($format, $timestamp = '') {
2092        return  date( $format, $timestamp);
2093    }
2094
2095    // チェックボックスの型を変換する
2096    function sfChangeCheckBox($data , $tpl = false){
2097        if ($tpl) {
2098            if ($data == 1){
2099                return 'checked';
2100            }else{
2101                return "";
2102            }
2103        }else{
2104            if ($data == "on"){
2105                return 1;
2106            }else{
2107                return 2;
2108            }
2109        }
2110    }
2111
2112    function sfCategory_Count($objQuery){
2113        $sql = "";
2114
2115        //テーブル内容の削除
2116        $objQuery->query("DELETE FROM dtb_category_count");
2117        $objQuery->query("DELETE FROM dtb_category_total_count");
2118
2119        //各カテゴリ内の商品数を数えて格納
2120        $sql = " INSERT INTO dtb_category_count(category_id, product_count, create_date) ";
2121        $sql .= " SELECT T1.category_id, count(T2.category_id), now() FROM dtb_category AS T1 LEFT JOIN dtb_products AS T2 ";
2122        $sql .= " ON T1.category_id = T2.category_id  ";
2123        $sql .= " WHERE T2.del_flg = 0 AND T2.status = 1 ";
2124        $sql .= " GROUP BY T1.category_id, T2.category_id ";
2125        $objQuery->query($sql);
2126
2127        //子カテゴリ内の商品数を集計する
2128        $arrCat = $objQuery->getAll("SELECT * FROM dtb_category");
2129
2130        $sql = "";
2131        foreach($arrCat as $key => $val){
2132
2133            // 子ID一覧を取得
2134            $arrRet = sfGetChildrenArray('dtb_category', 'parent_category_id', 'category_id', $val['category_id']);
2135            $line = sfGetCommaList($arrRet);
2136
2137            $sql = " INSERT INTO dtb_category_total_count(category_id, product_count, create_date) ";
2138            $sql .= " SELECT ?, SUM(product_count), now() FROM dtb_category_count ";
2139            $sql .= " WHERE category_id IN (" . $line . ")";
2140
2141            $objQuery->query($sql, array($val['category_id']));
2142        }
2143    }
2144
2145    // 2つの配列を用いて連想配列を作成する
2146    function sfarrCombine($arrKeys, $arrValues) {
2147
2148        if(count($arrKeys) <= 0 and count($arrValues) <= 0) return array();
2149
2150        $keys = array_values($arrKeys);
2151        $vals = array_values($arrValues);
2152
2153        $max = max( count( $keys ), count( $vals ) );
2154        $combine_ary = array();
2155        for($i=0; $i<$max; $i++) {
2156            $combine_ary[$keys[$i]] = $vals[$i];
2157        }
2158        if(is_array($combine_ary)) return $combine_ary;
2159
2160        return false;
2161    }
2162
2163    /* 階層構造のテーブルから子ID配列を取得する */
2164    function sfGetChildrenArray($table, $pid_name, $id_name, $id) {
2165        $objQuery = new SC_Query();
2166        $col = $pid_name . "," . $id_name;
2167         $arrData = $objQuery->select($col, $table);
2168
2169        $arrPID = array();
2170        $arrPID[] = $id;
2171        $arrChildren = array();
2172        $arrChildren[] = $id;
2173
2174        $arrRet = SC_Utils::sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrPID);
2175
2176        while(count($arrRet) > 0) {
2177            $arrChildren = array_merge($arrChildren, $arrRet);
2178            $arrRet = SC_Utils::sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrRet);
2179        }
2180
2181        return $arrChildren;
2182    }
2183
2184    /* 親ID直下の子IDをすべて取得する */
2185    function sfGetChildrenArraySub($arrData, $pid_name, $id_name, $arrPID) {
2186        $arrChildren = array();
2187        $max = count($arrData);
2188
2189        for($i = 0; $i < $max; $i++) {
2190            foreach($arrPID as $val) {
2191                if($arrData[$i][$pid_name] == $val) {
2192                    $arrChildren[] = $arrData[$i][$id_name];
2193                }
2194            }
2195        }
2196        return $arrChildren;
2197    }
2198
2199
2200    /* 階層構造のテーブルから親ID配列を取得する */
2201    function sfGetParentsArray($table, $pid_name, $id_name, $id) {
2202        $objQuery = new SC_Query();
2203        $col = $pid_name . "," . $id_name;
2204         $arrData = $objQuery->select($col, $table);
2205
2206        $arrParents = array();
2207        $arrParents[] = $id;
2208        $child = $id;
2209
2210        $ret = SC_Utils::sfGetParentsArraySub($arrData, $pid_name, $id_name, $child);
2211
2212        while($ret != "") {
2213            $arrParents[] = $ret;
2214            $ret = SC_Utils::sfGetParentsArraySub($arrData, $pid_name, $id_name, $ret);
2215        }
2216
2217        $arrParents = array_reverse($arrParents);
2218
2219        return $arrParents;
2220    }
2221
2222    /* 子ID所属する親IDを取得する */
2223    function sfGetParentsArraySub($arrData, $pid_name, $id_name, $child) {
2224        $max = count($arrData);
2225        $parent = "";
2226        for($i = 0; $i < $max; $i++) {
2227            if($arrData[$i][$id_name] == $child) {
2228                $parent = $arrData[$i][$pid_name];
2229                break;
2230            }
2231        }
2232        return $parent;
2233    }
2234
2235    /* 階層構造のテーブルから与えられたIDの兄弟を取得する */
2236    function sfGetBrothersArray($arrData, $pid_name, $id_name, $arrPID) {
2237        $max = count($arrData);
2238
2239        $arrBrothers = array();
2240        foreach($arrPID as $id) {
2241            // 親IDを検索する
2242            for($i = 0; $i < $max; $i++) {
2243                if($arrData[$i][$id_name] == $id) {
2244                    $parent = $arrData[$i][$pid_name];
2245                    break;
2246                }
2247            }
2248            // 兄弟IDを検索する
2249            for($i = 0; $i < $max; $i++) {
2250                if($arrData[$i][$pid_name] == $parent) {
2251                    $arrBrothers[] = $arrData[$i][$id_name];
2252                }
2253            }
2254        }
2255        return $arrBrothers;
2256    }
2257
2258    /* 階層構造のテーブルから与えられたIDの直属の子を取得する */
2259    function sfGetUnderChildrenArray($arrData, $pid_name, $id_name, $parent) {
2260        $max = count($arrData);
2261
2262        $arrChildren = array();
2263        // 子IDを検索する
2264        for($i = 0; $i < $max; $i++) {
2265            if($arrData[$i][$pid_name] == $parent) {
2266                $arrChildren[] = $arrData[$i][$id_name];
2267            }
2268        }
2269        return $arrChildren;
2270    }
2271
2272
2273    // カテゴリツリーの取得
2274    function sfGetCatTree($parent_category_id, $count_check = false) {
2275        $objQuery = new SC_Query();
2276        $col = "";
2277        $col .= " cat.category_id,";
2278        $col .= " cat.category_name,";
2279        $col .= " cat.parent_category_id,";
2280        $col .= " cat.level,";
2281        $col .= " cat.rank,";
2282        $col .= " cat.creator_id,";
2283        $col .= " cat.create_date,";
2284        $col .= " cat.update_date,";
2285        $col .= " cat.del_flg, ";
2286        $col .= " ttl.product_count";
2287        $from = "dtb_category as cat left join dtb_category_total_count as ttl on ttl.category_id = cat.category_id";
2288        // 登録商品数のチェック
2289        if($count_check) {
2290            $where = "del_flg = 0 AND product_count > 0";
2291        } else {
2292            $where = "del_flg = 0";
2293        }
2294        $objQuery->setoption("ORDER BY rank DESC");
2295        $arrRet = $objQuery->select($col, $from, $where);
2296
2297        $arrParentID = sfGetParents($objQuery, 'dtb_category', 'parent_category_id', 'category_id', $parent_category_id);
2298
2299        foreach($arrRet as $key => $array) {
2300            foreach($arrParentID as $val) {
2301                if($array['category_id'] == $val) {
2302                    $arrRet[$key]['display'] = 1;
2303                    break;
2304                }
2305            }
2306        }
2307
2308        return $arrRet;
2309    }
2310
2311    // 親カテゴリーを連結した文字列を取得する
2312    function sfGetCatCombName($category_id){
2313        // 商品が属するカテゴリIDを縦に取得
2314        $objQuery = new SC_Query();
2315        $arrCatID = sfGetParents($objQuery, "dtb_category", "parent_category_id", "category_id", $category_id);
2316        $ConbName = "";
2317
2318        // カテゴリー名称を取得する
2319        foreach($arrCatID as $key => $val){
2320            $sql = "SELECT category_name FROM dtb_category WHERE category_id = ?";
2321            $arrVal = array($val);
2322            $CatName = $objQuery->getOne($sql,$arrVal);
2323            $ConbName .= $CatName . ' | ';
2324        }
2325        // 最後の | をカットする
2326        $ConbName = substr_replace($ConbName, "", strlen($ConbName) - 2, 2);
2327
2328        return $ConbName;
2329    }
2330
2331    // 指定したカテゴリーIDの大カテゴリーを取得する
2332    function sfGetFirstCat($category_id){
2333        // 商品が属するカテゴリIDを縦に取得
2334        $objQuery = new SC_Query();
2335        $arrRet = array();
2336        $arrCatID = SC_Utils_Ex::sfGetParents($objQuery, "dtb_category", "parent_category_id", "category_id", $category_id);
2337        $arrRet['id'] = $arrCatID[0];
2338
2339        // カテゴリー名称を取得する
2340        $sql = "SELECT category_name FROM dtb_category WHERE category_id = ?";
2341        $arrVal = array($arrRet['id']);
2342        $arrRet['name'] = $objQuery->getOne($sql,$arrVal);
2343
2344        return $arrRet;
2345    }
2346
2347    // SQLシングルクォート対応
2348    function sfQuoteSmart($in){
2349
2350        if (is_int($in) || is_double($in)) {
2351            return $in;
2352        } elseif (is_bool($in)) {
2353            return $in ? 1 : 0;
2354        } elseif (is_null($in)) {
2355            return 'NULL';
2356        } else {
2357            return "'" . str_replace("'", "''", $in) . "'";
2358        }
2359    }
2360
2361    // ディレクトリ以下のファイルを再帰的にコピー
2362    function sfCopyDir($src, $des, $mess, $override = false){
2363        if(!is_dir($src)){
2364            return false;
2365        }
2366
2367        $oldmask = umask(0);
2368        $mod= stat($src);
2369
2370        // ディレクトリがなければ作成する
2371        if(!file_exists($des)) {
2372            if(!mkdir($des, $mod[2])) {
2373                print("path:" . $des);
2374            }
2375        }
2376
2377        $fileArray=glob( $src."*" );
2378        foreach( $fileArray as $key => $data_ ){
2379            // CVS管理ファイルはコピーしない
2380            if(ereg("/CVS/Entries", $data_)) {
2381                break;
2382            }
2383            if(ereg("/CVS/Repository", $data_)) {
2384                break;
2385            }
2386            if(ereg("/CVS/Root", $data_)) {
2387                break;
2388            }
2389
2390            mb_ereg("^(.*[\/])(.*)",$data_, $matches);
2391            $data=$matches[2];
2392            if( is_dir( $data_ ) ){
2393                $mess = sfCopyDir( $data_.'/', $des.$data.'/', $mess);
2394            }else{
2395                if(!$override && file_exists($des.$data)) {
2396                    $mess.= $des.$data . ":ファイルが存在します\n";
2397                } else {
2398                    if(@copy( $data_, $des.$data)) {
2399                        $mess.= $des.$data . ":コピー成功\n";
2400                    } else {
2401                        $mess.= $des.$data . ":コピー失敗\n";
2402                    }
2403                }
2404                $mod=stat($data_ );
2405            }
2406        }
2407        umask($oldmask);
2408        return $mess;
2409    }
2410
2411    // 指定したフォルダ内のファイルを全て削除する
2412    function sfDelFile($dir){
2413        $dh = opendir($dir);
2414        // フォルダ内のファイルを削除
2415        while($file = readdir($dh)){
2416            if ($file == "." or $file == "..") continue;
2417            $del_file = $dir . "/" . $file;
2418            if(is_file($del_file)){
2419                $ret = unlink($dir . "/" . $file);
2420            }else if (is_dir($del_file)){
2421                $ret = sfDelFile($del_file);
2422            }
2423
2424            if(!$ret){
2425                return $ret;
2426            }
2427        }
2428
2429        // 閉じる
2430        closedir($dh);
2431
2432        // フォルダを削除
2433        return rmdir($dir);
2434    }
2435
2436    /*
2437     * 関数名:sfWriteFile
2438     * 引数1 :書き込むデータ
2439     * 引数2 :ファイルパス
2440     * 引数3 :書き込みタイプ
2441     * 引数4 :パーミッション
2442     * 戻り値:結果フラグ 成功なら true 失敗なら false
2443     * 説明 :ファイル書き出し
2444     */
2445    function sfWriteFile($str, $path, $type, $permission = "") {
2446        //ファイルを開く
2447        if (!($file = fopen ($path, $type))) {
2448            return false;
2449        }
2450
2451        //ファイルロック
2452        flock ($file, LOCK_EX);
2453        //ファイルの書き込み
2454        fputs ($file, $str);
2455        //ファイルロックの解除
2456        flock ($file, LOCK_UN);
2457        //ファイルを閉じる
2458        fclose ($file);
2459        // 権限を指定
2460        if($permission != "") {
2461            chmod($path, $permission);
2462        }
2463
2464        return true;
2465    }
2466
2467    function sfFlush($output = " ", $sleep = 0){
2468        // 実行時間を制限しない
2469        set_time_limit(0);
2470        // 出力をバッファリングしない(==日本語自動変換もしない)
2471        ob_end_clean();
2472
2473        // IEのために256バイト空文字出力
2474        echo str_pad('',256);
2475
2476        // 出力はブランクだけでもいいと思う
2477        echo $output;
2478        // 出力をフラッシュする
2479        flush();
2480
2481        ob_end_flush();
2482        ob_start();
2483
2484        // 時間のかかる処理
2485        sleep($sleep);
2486    }
2487
2488    // @versionの記載があるファイルからバージョンを取得する。
2489    function sfGetFileVersion($path) {
2490        if(file_exists($path)) {
2491            $src_fp = fopen($path, "rb");
2492            if($src_fp) {
2493                while (!feof($src_fp)) {
2494                    $line = fgets($src_fp);
2495                    if(ereg("@version", $line)) {
2496                        $arrLine = split(" ", $line);
2497                        $version = $arrLine[5];
2498                    }
2499                }
2500                fclose($src_fp);
2501            }
2502        }
2503        return $version;
2504    }
2505
2506    // 指定したURLに対してPOSTでデータを送信する
2507    function sfSendPostData($url, $arrData, $arrOkCode = array()){
2508        require_once(DATA_PATH . "module/Request.php");
2509
2510        // 送信インスタンス生成
2511        $req = new HTTP_Request($url);
2512
2513        $req->addHeader('User-Agent', 'DoCoMo/2.0 P2101V(c100)');
2514        $req->setMethod(HTTP_REQUEST_METHOD_POST);
2515
2516        // POSTデータ送信
2517        $req->addPostDataArray($arrData);
2518
2519        // エラーが無ければ、応答情報を取得する
2520        if (!PEAR::isError($req->sendRequest())) {
2521
2522            // レスポンスコードがエラー判定なら、空を返す
2523            $res_code = $req->getResponseCode();
2524
2525            if(!in_array($res_code, $arrOkCode)){
2526                $response = "";
2527            }else{
2528                $response = $req->getResponseBody();
2529            }
2530
2531        } else {
2532            $response = "";
2533        }
2534
2535        // POSTデータクリア
2536        $req->clearPostData();
2537
2538        return $response;
2539    }
2540
2541    /* デバッグ用 ------------------------------------------------------------------------------------------------*/
2542    function sfPrintR($obj) {
2543        print("<div style='font-size: 12px;color: #00FF00;'>\n");
2544        print("<strong>**デバッグ中**</strong><br />\n");
2545        print("<pre>\n");
2546        print_r($obj);
2547        print("</pre>\n");
2548        print("<strong>**デバッグ中**</strong></div>\n");
2549    }
2550}
2551?>
Note: See TracBrowser for help on using the repository browser.