source: branches/comu-utf8/data/lib/slib.php @ 16100

Revision 16100, 95.3 KB checked in by adachi, 17 years ago (diff)

set property

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