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

Revision 15279, 86.1 KB checked in by nanasess, 17 years ago (diff)

リファクタリング

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