source: branches/version-2_12-dev/data/class/pages/admin/products/LC_Page_Admin_Products_UploadCSV.php @ 22243

Revision 22243, 33.8 KB checked in by undertree, 11 years ago (diff)

#1734 (商品登録CSV 入力必須でないカラムが末尾にあると、当該カラムを省略した CSV の読み込みがエラーとなる)

・項目が多すぎる場合にエラーを、少ない場合に空欄を読み込んだものとして扱うように変更

  • 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 * This file is part of EC-CUBE
4 *
5 * Copyright(c) 2000-2013 LOCKON CO.,LTD. All Rights Reserved.
6 *
7 * http://www.lockon.co.jp/
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22 */
23
24// {{{ requires
25require_once CLASS_EX_REALDIR . 'page_extends/admin/LC_Page_Admin_Ex.php';
26
27/**
28 * 商品登録CSVのページクラス.
29 *
30 * @package Page
31 * @author LOCKON CO.,LTD.
32 * @version $Id:LC_Page_Admin_Products_UploadCSV.php 15532 2007-08-31 14:39:46Z nanasess $
33 *
34 * FIXME 同一商品IDで商品規格違いを登録できない。(更新は可能)
35 */
36class LC_Page_Admin_Products_UploadCSV extends LC_Page_Admin_Ex {
37
38    // }}}
39    // {{{ functions
40
41    /** TAGエラーチェックフィールド情報 */
42    var $arrTagCheckItem;
43
44    /** 商品テーブルカラム情報 (登録処理用) **/
45    var $arrProductColumn;
46
47    /** 商品規格テーブルカラム情報 (登録処理用) **/
48    var $arrProductClassColumn;
49
50    /** 登録フォームカラム情報 **/
51    var $arrFormKeyList;
52
53    var $arrRowErr;
54
55    var $arrRowResult;
56
57    /**
58     * Page を初期化する.
59     *
60     * @return void
61     */
62    function init() {
63        parent::init();
64        $this->tpl_mainpage = 'products/upload_csv.tpl';
65        $this->tpl_mainno = 'products';
66        $this->tpl_subno = 'upload_csv';
67        $this->tpl_maintitle = '商品管理';
68        $this->tpl_subtitle = '商品登録CSV';
69        $this->csv_id = '1';
70
71        $masterData = new SC_DB_MasterData_Ex();
72        $this->arrDISP = $masterData->getMasterData('mtb_disp');
73        $this->arrSTATUS = $masterData->getMasterData('mtb_status');
74        $this->arrDELIVERYDATE = $masterData->getMasterData('mtb_delivery_date');
75        $this->arrProductType = $masterData->getMasterData('mtb_product_type');
76        $this->arrMaker = SC_Helper_DB_Ex::sfGetIDValueList('dtb_maker', 'maker_id', 'name');
77        $this->arrPayments = SC_Helper_DB_Ex::sfGetIDValueList('dtb_payment', 'payment_id', 'payment_method');
78        $this->arrInfo = SC_Helper_DB_Ex::sfGetBasisData();
79        $this->arrAllowedTag = $masterData->getMasterData('mtb_allowed_tag');
80        $this->arrTagCheckItem = array();
81    }
82
83    /**
84     * Page のプロセス.
85     *
86     * @return void
87     */
88    function process() {
89        $this->action();
90        $this->sendResponse();
91    }
92
93    /**
94     * Page のアクション.
95     *
96     * @return void
97     */
98    function action() {
99
100        $this->objDb = new SC_Helper_DB_Ex();
101
102        // CSV管理ヘルパー
103        $objCSV = new SC_Helper_CSV_Ex();
104        // CSV構造読み込み
105        $arrCSVFrame = $objCSV->sfGetCsvOutput($this->csv_id);
106
107        // CSV構造がインポート可能かのチェック
108        if (!$objCSV->sfIsImportCSVFrame($arrCSVFrame)) {
109            // 無効なフォーマットなので初期状態に強制変更
110            $arrCSVFrame = $objCSV->sfGetCsvOutput($this->csv_id, '', array(), 'no');
111            $this->tpl_is_format_default = true;
112        }
113        // CSV構造は更新可能なフォーマットかのフラグ取得
114        $this->tpl_is_update = $objCSV->sfIsUpdateCSVFrame($arrCSVFrame);
115
116        // CSVファイルアップロード情報の初期化
117        $objUpFile = new SC_UploadFile_Ex(IMAGE_TEMP_REALDIR, IMAGE_SAVE_REALDIR);
118        $this->lfInitFile($objUpFile);
119
120        // パラメーター情報の初期化
121        $objFormParam = new SC_FormParam_Ex();
122        $this->lfInitParam($objFormParam, $arrCSVFrame);
123
124        $objFormParam->setHtmlDispNameArray();
125        $this->arrTitle = $objFormParam->getHtmlDispNameArray();
126
127        switch ($this->getMode()) {
128            case 'csv_upload':
129                $this->doUploadCsv($objFormParam, $objUpFile);
130                break;
131            default:
132                break;
133        }
134
135    }
136
137    /**
138     * 登録/編集結果のメッセージをプロパティへ追加する
139     *
140     * @param integer $line_count 行数
141     * @param stirng $message メッセージ
142     * @return void
143     */
144    function addRowResult($line_count, $message) {
145        $this->arrRowResult[] = $line_count . '行目:' . $message;
146    }
147
148    /**
149     * 登録/編集結果のエラーメッセージをプロパティへ追加する
150     *
151     * @param integer $line_count 行数
152     * @param stirng $message メッセージ
153     * @return void
154     */
155    function addRowErr($line_count, $message) {
156        $this->arrRowErr[] = $line_count . '行目:' . $message;
157    }
158
159    /**
160     * CSVアップロードを実行します.
161     *
162     * @return void
163     */
164    function doUploadCsv(&$objFormParam, &$objUpFile) {
165        // ファイルアップロードのチェック
166        $this->arrErr['csv_file'] = $objUpFile->makeTempFile('csv_file');
167        if (strlen($this->arrErr['csv_file']) >= 1) {
168            return;
169        }
170        $arrErr = $objUpFile->checkExists();
171        if (count($arrErr) > 0) {
172            $this->arrErr = $arrErr;
173            return;
174        }
175        // 一時ファイル名の取得
176        $filepath = $objUpFile->getTempFilePath('csv_file');
177        // CSVファイルの文字コード変換
178        $enc_filepath = SC_Utils_Ex::sfEncodeFile($filepath, CHAR_CODE, CSV_TEMP_REALDIR);
179        // CSVファイルのオープン
180        $fp = fopen($enc_filepath, 'r');
181        // 失敗した場合はエラー表示
182        if (!$fp) {
183            SC_Utils_Ex::sfDispError('');
184        }
185
186        // 登録先テーブル カラム情報の初期化
187        $this->lfInitTableInfo();
188
189        // 登録フォーム カラム情報
190        $this->arrFormKeyList = $objFormParam->getKeyList();
191
192        // 登録対象の列数
193        $col_max_count = $objFormParam->getCount();
194        // 行数
195        $line_count = 0;
196
197        $objQuery =& SC_Query_Ex::getSingletonInstance();
198        $objQuery->begin();
199
200        $errFlag = false;
201        $all_line_checked = false;
202
203        while (!feof($fp)) {
204            $arrCSV = fgetcsv($fp, CSV_LINE_MAX);
205
206            // 全行入力チェック後に、ファイルポインターを先頭に戻す
207            if (feof($fp) && !$all_line_checked) {
208                rewind($fp);
209                $line_count = 0;
210                $all_line_checked = true;
211                continue;
212            }
213
214            // 行カウント
215            $line_count++;
216            // ヘッダ行はスキップ
217            if ($line_count == 1) {
218                continue;
219            }
220            // 空行はスキップ
221            if (empty($arrCSV)) {
222                continue;
223            }
224            // 列数が多すぎる場合はエラー、列数が少ない場合は未設定として配列を補う
225            $col_count = count($arrCSV);
226            if ($col_count > $col_max_count) {
227                $this->addRowErr($line_count, '※ 項目数が' . $col_count . '個検出されました。項目数は' . $col_max_count . '個になります。');
228                $errFlag = true;
229                break;
230            } elseif ($col_count < $col_max_count) {
231                $arrCSV = array_pad($arrCSV, $col_max_count, "");
232                $this->addRowResult($line_count, ($col_count + 1) . "項目以降を空欄として読み込みました");
233            }
234            // シーケンス配列を格納する。
235            $objFormParam->setParam($arrCSV, true);
236            $arrRet = $objFormParam->getHashArray();
237            $objFormParam->setParam($arrRet);
238            // 入力値の変換
239            $objFormParam->convParam();
240            // <br>なしでエラー取得する。
241            $arrCSVErr = $this->lfCheckError($objFormParam);
242
243            // 入力エラーチェック
244            if (count($arrCSVErr) > 0) {
245                foreach ($arrCSVErr as $err) {
246                    $this->addRowErr($line_count, $err);
247                }
248                $errFlag = true;
249                break;
250            }
251
252            if ($all_line_checked) {
253                $this->lfRegistProduct($objQuery, $line_count, $objFormParam);
254                $arrParam = $objFormParam->getHashArray();
255
256                $this->addRowResult($line_count, '商品ID:'.$arrParam['product_id'] . ' / 商品名:' . $arrParam['name']);
257            }
258            SC_Utils_Ex::extendTimeOut();
259        }
260
261        // 実行結果画面を表示
262        $this->tpl_mainpage = 'products/upload_csv_complete.tpl';
263
264        fclose($fp);
265
266        if ($errFlag) {
267            $objQuery->rollback();
268            return;
269        }
270
271        $objQuery->commit();
272
273        // 商品件数カウント関数の実行
274        $this->objDb->sfCountCategory($objQuery);
275        $this->objDb->sfCountMaker($objQuery);
276    }
277
278    /**
279     * デストラクタ.
280     *
281     * @return void
282     */
283    function destroy() {
284        parent::destroy();
285    }
286
287    /**
288     * ファイル情報の初期化を行う.
289     *
290     * @return void
291     */
292    function lfInitFile(&$objUpFile) {
293        $objUpFile->addFile('CSVファイル', 'csv_file', array('csv'), CSV_SIZE, true, 0, 0, false);
294    }
295
296    /**
297     * 入力情報の初期化を行う.
298     *
299     * @param array CSV構造設定配列
300     * @return void
301     */
302    function lfInitParam(&$objFormParam, &$arrCSVFrame) {
303        // 固有の初期値調整
304        $arrCSVFrame = $this->lfSetParamDefaultValue($arrCSVFrame);
305        // CSV項目毎の処理
306        foreach ($arrCSVFrame as $item) {
307            if ($item['status'] == CSV_COLUMN_STATUS_FLG_DISABLE) continue;
308            //サブクエリ構造の場合は AS名 を使用
309            if (preg_match_all('/\(.+\)\s+as\s+(.+)$/i', $item['col'], $match, PREG_SET_ORDER)) {
310                $col = $match[0][1];
311            } else {
312                $col = $item['col'];
313            }
314            // HTML_TAG_CHECKは別途実行なので除去し、別保存しておく
315            if (strpos(strtoupper($item['error_check_types']), 'HTML_TAG_CHECK') !== FALSE) {
316                $this->arrTagCheckItem[] = $item;
317                $error_check_types = str_replace('HTML_TAG_CHECK', '', $item['error_check_types']);
318            } else {
319                $error_check_types = $item['error_check_types'];
320            }
321            $arrErrorCheckTypes = explode(',', $error_check_types);
322            foreach ($arrErrorCheckTypes as $key => $val) {
323                if (trim($val) == '') {
324                    unset($arrErrorCheckTypes[$key]);
325                } else {
326                    $arrErrorCheckTypes[$key] = trim($val);
327                }
328            }
329            // パラメーター登録
330            $objFormParam->addParam(
331                    $item['disp_name']
332                    , $col
333                    , constant($item['size_const_type'])
334                    , $item['mb_convert_kana_option']
335                    , $arrErrorCheckTypes
336                    , $item['default']
337                    , ($item['rw_flg'] != CSV_COLUMN_RW_FLG_READ_ONLY) ? true : false
338                    );
339        }
340    }
341
342    /**
343     * 入力チェックを行う.
344     *
345     * @return void
346     */
347    function lfCheckError(&$objFormParam) {
348        // 入力データを渡す。
349        $arrRet =  $objFormParam->getHashArray();
350        $objErr = new SC_CheckError_Ex($arrRet);
351        $objErr->arrErr = $objFormParam->checkError(false);
352        // HTMLタグチェックの実行
353        foreach ($this->arrTagCheckItem as $item) {
354            $objErr->doFunc(array($item['disp_name'], $item['col'], $this->arrAllowedTag), array('HTML_TAG_CHECK'));
355        }
356        // このフォーム特有の複雑系のエラーチェックを行う
357        if (count($objErr->arrErr) == 0) {
358            $objErr->arrErr = $this->lfCheckErrorDetail($arrRet, $objErr->arrErr);
359        }
360        return $objErr->arrErr;
361    }
362
363    /**
364     * 保存先テーブル情報の初期化を行う.
365     *
366     * @return void
367     */
368    function lfInitTableInfo() {
369        $objQuery =& SC_Query_Ex::getSingletonInstance();
370        $this->arrProductColumn = $objQuery->listTableFields('dtb_products');
371        $this->arrProductClassColumn = $objQuery->listTableFields('dtb_products_class');
372    }
373
374    /**
375     * 商品登録を行う.
376     *
377     * FIXME: 商品登録の実処理自体は、LC_Page_Admin_Products_Productと共通化して欲しい。
378     *
379     * @param SC_Query $objQuery SC_Queryインスタンス
380     * @param string|integer $line 処理中の行数
381     * @return void
382     */
383    function lfRegistProduct($objQuery, $line = '', &$objFormParam) {
384        $objProduct = new SC_Product_Ex();
385        // 登録データ対象取得
386        $arrList = $objFormParam->getHashArray();
387        // 登録時間を生成(DBのCURRENT_TIMESTAMPだとcommitした際、すべて同一の時間になってしまう)
388        $arrList['update_date'] = $this->lfGetDbFormatTimeWithLine($line);
389
390        // 商品登録情報を生成する。
391        // 商品テーブルのカラムに存在しているもののうち、Form投入設定されていないデータは上書きしない。
392        $sqlval = SC_Utils_Ex::sfArrayIntersectKeys($arrList, $this->arrProductColumn);
393
394        // 必須入力では無い項目だが、空文字では問題のある特殊なカラム値の初期値設定
395        $sqlval = $this->lfSetProductDefaultData($sqlval);
396
397        if ($sqlval['product_id'] != '') {
398            // 同じidが存在すればupdate存在しなければinsert
399            $where = 'product_id = ?';
400            $product_exists = $objQuery->exists('dtb_products', $where, array($sqlval['product_id']));
401            if ($product_exists) {
402                $objQuery->update('dtb_products', $sqlval, $where, array($sqlval['product_id']));
403            } else {
404                $sqlval['create_date'] = $arrList['update_date'];
405                // INSERTの実行
406                $objQuery->insert('dtb_products', $sqlval);
407                // シーケンスの調整
408                $seq_count = $objQuery->currVal('dtb_products_product_id');
409                if ($seq_count < $sqlval['product_id']) {
410                    $objQuery->setVal('dtb_products_product_id', $sqlval['product_id'] + 1);
411                }
412            }
413            $product_id = $sqlval['product_id'];
414        } else {
415            // 新規登録
416            $sqlval['product_id'] = $objQuery->nextVal('dtb_products_product_id');
417            $product_id = $sqlval['product_id'];
418            $sqlval['create_date'] = $arrList['update_date'];
419            // INSERTの実行
420            $objQuery->insert('dtb_products', $sqlval);
421        }
422
423        // カテゴリ登録
424        if (isset($arrList['category_ids'])) {
425            $arrCategory_id = explode(',', $arrList['category_ids']);
426            $this->objDb->updateProductCategories($arrCategory_id, $product_id);
427        }
428        // 商品ステータス登録
429        if (isset($arrList['product_statuses'])) {
430            $arrStatus_id = explode(',', $arrList['product_statuses']);
431            $objProduct->setProductStatus($product_id, $arrStatus_id);
432        }
433
434        // 商品規格情報を登録する
435        $this->lfRegistProductClass($objQuery, $arrList, $product_id, $arrList['product_class_id']);
436
437        // 関連商品登録
438        $this->lfRegistReccomendProducts($objQuery, $arrList, $product_id);
439    }
440
441    /**
442     * 商品規格登録を行う.
443     *
444     * FIXME: 商品規格登録の実処理自体は、LC_Page_Admin_Products_Productと共通化して欲しい。
445     *
446     * @param SC_Query $objQuery SC_Queryインスタンス
447     * @param array $arrList 商品規格情報配列
448     * @param integer $product_id 商品ID
449     * @param integer $product_class_id 商品規格ID
450     * @return void
451     */
452    function lfRegistProductClass($objQuery, $arrList, $product_id, $product_class_id) {
453        $objProduct = new SC_Product_Ex();
454        // 商品規格登録情報を生成する。
455        // 商品規格テーブルのカラムに存在しているもののうち、Form投入設定されていないデータは上書きしない。
456        $sqlval = SC_Utils_Ex::sfArrayIntersectKeys($arrList, $this->arrProductClassColumn);
457
458        if ($product_class_id == '') {
459            // 新規登録
460            // 必須入力では無い項目だが、空文字では問題のある特殊なカラム値の初期値設定
461            $sqlval = $this->lfSetProductClassDefaultData($sqlval);
462            $sqlval['product_id'] = $product_id;
463            $sqlval['product_class_id'] = $objQuery->nextVal('dtb_products_class_product_class_id');
464            $sqlval['create_date'] = $arrList['update_date'];
465            // INSERTの実行
466            $objQuery->insert('dtb_products_class', $sqlval);
467            $product_class_id = $sqlval['product_class_id'];
468        } else {
469            // UPDATEの実行
470            // 必須入力では無い項目だが、空文字では問題のある特殊なカラム値の初期値設定
471            $sqlval = $this->lfSetProductClassDefaultData($sqlval, true);
472            $where = 'product_class_id = ?';
473            $objQuery->update('dtb_products_class', $sqlval, $where, array($product_class_id));
474        }
475    }
476
477    /**
478     * 関連商品登録を行う.
479     *
480     * FIXME: 商品規格登録の実処理自体は、LC_Page_Admin_Products_Productと共通化して欲しい。
481     *        DELETE/INSERT ではなく UPDATEへの変更も・・・
482     *
483     * @param SC_Query $objQuery SC_Queryインスタンス
484     * @param array $arrList 商品規格情報配列
485     * @param integer $product_id 商品ID
486     * @return void
487     */
488    function lfRegistReccomendProducts($objQuery, $arrList, $product_id) {
489        $objQuery->delete('dtb_recommend_products', 'product_id = ?', array($product_id));
490        for ($i = 1; $i <= RECOMMEND_PRODUCT_MAX; $i++) {
491            $keyname = 'recommend_product_id' . $i;
492            $comment_key = 'recommend_comment' . $i;
493            if ($arrList[$keyname] != '') {
494                $arrProduct = $objQuery->select('product_id', 'dtb_products', 'product_id = ?', array($arrList[$keyname]));
495                if ($arrProduct[0]['product_id'] != '') {
496                    $arrWhereVal = array();
497                    $arrWhereVal['product_id'] = $product_id;
498                    $arrWhereVal['recommend_product_id'] = $arrProduct[0]['product_id'];
499                    $arrWhereVal['comment'] = $arrList[$comment_key];
500                    $arrWhereVal['update_date'] = $arrList['update_date'];
501                    $arrWhereVal['create_date'] = $arrList['update_date'];
502                    $arrWhereVal['creator_id'] = $_SESSION['member_id'];
503                    $arrWhereVal['rank'] = RECOMMEND_PRODUCT_MAX - $i + 1;
504                    $objQuery->insert('dtb_recommend_products', $arrWhereVal);
505                }
506            }
507        }
508    }
509
510    /**
511     * 初期値の設定
512     *
513     * @param array $arrCSVFrame CSV構造配列
514     * @return array $arrCSVFrame CSV構造配列
515     */
516    function lfSetParamDefaultValue(&$arrCSVFrame) {
517        foreach ($arrCSVFrame as $key => $val) {
518            switch ($val['col']) {
519                case 'status':
520                    $arrCSVFrame[$key]['default'] = DEFAULT_PRODUCT_DISP;
521                    break;
522                case 'del_flg':
523                    $arrCSVFrame[$key]['default'] = '0';
524                    break;
525                case 'point_rate':
526                    $arrCSVFrame[$key]['default'] = $this->arrInfo['point_rate'];
527                    break;
528                case 'product_type_id':
529                    $arrCSVFrame[$key]['default'] = DEFAULT_PRODUCT_DOWN;
530                    break;
531                case 'stock_unlimited':
532                    $arrCSVFrame[$key]['default'] = UNLIMITED_FLG_LIMITED;
533                default:
534                    break;
535            }
536        }
537        return $arrCSVFrame;
538    }
539
540    /**
541     * 商品データ登録前に特殊な値の持ち方をする部分のデータ部分の初期値補正を行う
542     *
543     * @param array $sqlval 商品登録情報配列
544     * @return $sqlval 登録情報配列
545     */
546    function lfSetProductDefaultData(&$sqlval) {
547        //新規登録時のみ設定する項目
548        if ($sqlval['product_id'] == '') {
549            if ($sqlval['status'] == '') {
550                $sqlval['status'] = DEFAULT_PRODUCT_DISP;
551            }
552        }
553        //共通で空欄時に上書きする項目
554        if ($sqlval['del_flg'] == '') {
555            $sqlval['del_flg'] = '0'; //有効
556        }
557        if ($sqlval['creator_id'] == '') {
558            $sqlval['creator_id'] = $_SESSION['member_id'];
559        }
560        return $sqlval;
561    }
562
563    /**
564     * 商品規格データ登録前に特殊な値の持ち方をする部分のデータ部分の初期値補正を行う
565     *
566     * @param array $sqlval 商品登録情報配列
567     * @param boolean $upload_flg 更新フラグ(更新の場合true)
568     * @return $sqlval 登録情報配列
569     */
570    function lfSetProductClassDefaultData(&$sqlval, $upload_flg) {
571        //新規登録時のみ設定する項目
572        if ($sqlval['product_class_id'] == '') {
573            if ($sqlval['point_rate'] == '') {
574                $sqlval['point_rate'] = $this->arrInfo['point_rate'];
575            }
576            if ($sqlval['product_type_id'] == '') {
577                $sqlval['product_type_id'] = DEFAULT_PRODUCT_DOWN;
578            }
579        }
580        //共通で設定する項目
581        if ($sqlval['del_flg'] == '') {
582            $sqlval['del_flg'] = '0'; //有効
583        }
584        if ($sqlval['creator_id'] == '') {
585            $sqlval['creator_id'] = $_SESSION['member_id'];
586        }
587
588        // 在庫無制限フラグ列を利用する場合、
589        if (array_key_exists('stock_unlimited', $sqlval) and $sqlval['stock_unlimited'] != '') {
590            // 在庫無制限フラグ = 無制限の場合、
591            if ($sqlval['stock_unlimited'] == UNLIMITED_FLG_UNLIMITED) {
592                $sqlval['stock'] = null;
593            }
594        } else {
595            // 初期登録の場合は、在庫数設定がされていない場合、在庫無制限フラグ = 無制限。
596            if (strlen($sqlval['stock']) === 0){
597                //更新の場合は、sqlvalのキーにstockがある場合のみ対象
598                if (!$upload_flg or ($upload_flg and array_key_exists('stock', $sqlval))) {
599                    $sqlval['stock_unlimited'] = UNLIMITED_FLG_UNLIMITED;
600                }
601            }
602            // 在庫数を入力している場合、在庫無制限フラグ = 制限有り
603            elseif (strlen($sqlval['stock']) >= 1) {
604                $sqlval['stock_unlimited'] = UNLIMITED_FLG_LIMITED;
605            }
606            // いずれにも該当しない場合、例外エラー
607            else {
608                trigger_error('', E_USER_ERROR);
609            }
610        }
611        return $sqlval;
612    }
613
614    /**
615     * このフォーム特有の複雑な入力チェックを行う.
616     *
617     * @param array 確認対象データ
618     * @param array エラー配列
619     * @return array エラー配列
620     */
621    function lfCheckErrorDetail($item, $arrErr) {
622        // 規格IDの存在チェック
623        // FIXME 規格分類ID自体のが有効かを主眼においたチェックをすべきと感じる。
624        if (!$this->lfIsDbRecord('dtb_products_class', 'product_class_id', $item)) {
625            $arrErr['product_class_id'] = '※ 指定の商品規格IDは、登録されていません。';
626        }
627        // 商品ID、規格IDの組合せチェック
628        if (array_search('product_class_id', $this->arrFormKeyList) !== FALSE
629            && $item['product_class_id'] != ''
630        ) {
631            if ($item['product_id'] == '') {
632                $arrErr['product_class_id'] = '※ 商品規格ID指定時には商品IDの指定が必須です。';
633            } else {
634                if (!$this->objDb->sfIsRecord('dtb_products_class', 'product_id, product_class_id'
635                        , array($item['product_id'], $item['product_class_id']))
636                ) {
637                    $arrErr['product_class_id'] = '※ 指定の商品IDと商品規格IDの組合せは正しくありません。';
638                }
639            }
640        }
641        // 表示ステータスの存在チェック
642        if (!$this->lfIsArrayRecord($this->arrDISP, 'status', $item)) {
643            $arrErr['status'] = '※ 指定の表示ステータスは、登録されていません。';
644        }
645        // メーカーIDの存在チェック
646        if (!$this->lfIsArrayRecord($this->arrMaker, 'maker_id', $item)) {
647            $arrErr['maker_id'] = '※ 指定のメーカーIDは、登録されていません。';
648        }
649        // 発送日目安IDの存在チェック
650        if (!$this->lfIsArrayRecord($this->arrDELIVERYDATE, 'deliv_date_id', $item)) {
651            $arrErr['deliv_date_id'] = '※ 指定の発送日目安IDは、登録されていません。';
652        }
653        // 発送日目安IDの存在チェック
654        if (!$this->lfIsArrayRecord($this->arrProductType, 'product_type_id', $item)) {
655            $arrErr['product_type_id'] = '※ 指定の商品種別IDは、登録されていません。';
656        }
657        // 関連商品IDのチェック
658        $arrRecommendProductUnique = array();
659        for ($i = 1; $i <= RECOMMEND_PRODUCT_MAX; $i++) {
660            $recommend_product_id_key = 'recommend_product_id' . $i;
661            if ((array_search($recommend_product_id_key, $this->arrFormKeyList) !== FALSE)
662             && ($item[$recommend_product_id_key] != '')) {
663
664                // 商品IDの存在チェック
665                if (!$this->objDb->sfIsRecord('dtb_products', 'product_id', (array)$item[$recommend_product_id_key])) {
666                    $arrErr[$recommend_product_id_key] = "※ 指定の関連商品ID($i)は、登録されていません。";
667                    continue;
668                }
669                // 商品IDの重複チェック
670                $recommend_product_id = $item[$recommend_product_id_key];
671                if (isset($arrRecommendProductUnique[$recommend_product_id])) {
672                    $arrErr[$recommend_product_id_key] = "※ 指定の関連商品ID($i)は、すでに登録されています。";
673                } else {
674                    $arrRecommendProductUnique[$recommend_product_id] = true;
675                }
676            }
677        }
678        // カテゴリIDの存在チェック
679        if (!$this->lfIsDbRecordMulti('dtb_category', 'category_id', 'category_ids', $item, ',')) {
680            $arrErr['category_ids'] = '※ 指定のカテゴリIDは、登録されていません。';
681        }
682        // 商品ステータスIDの存在チェック
683        if (!$this->lfIsArrayRecordMulti($this->arrSTATUS, 'product_statuses', $item, ',')) {
684            $arrErr['product_statuses'] = '※ 指定の商品ステータスIDは、登録されていません。';
685        }
686        // 削除フラグのチェック
687        if (array_search('del_flg', $this->arrFormKeyList) !== FALSE
688            && $item['del_flg'] != ''
689        ) {
690            if (!($item['del_flg'] == '0' or $item['del_flg'] == '1')) {
691                $arrErr['del_flg'] = '※ 削除フラグは「0」(有効)、「1」(削除)のみが有効な値です。';
692            }
693        }
694/*
695    TODO: 在庫数の扱いが2.4仕様ではぶれているのでどうするか・・
696        // 在庫数/在庫無制限フラグの有効性に関するチェック
697        if ($item['stock'] == '') {
698            if (array_search('stock_unlimited', $this->arrFormKeyList) === FALSE) {
699                $arrErr['stock'] = '※ 在庫数は必須です(無制限フラグ項目がある場合のみ空欄許可)。';
700            } else if ($item['stock_unlimited'] != UNLIMITED_FLG_UNLIMITED) {
701                $arrErr['stock'] = '※ 在庫数または在庫無制限フラグのいずれかの入力が必須です。';
702            }
703        }
704*/
705        // ダウンロード商品チェック
706        if (array_search('product_type_id', $this->arrFormKeyList) !== FALSE
707            && $item['product_type_id'] == PRODUCT_TYPE_NORMAL
708        ) {
709            //実商品の場合
710            if ($item['down_filename'] != '') {
711                $arrErr['down_filename'] = '※ 実商品の場合はダウンロードファイル名は入力できません。';
712            }
713            if ($item['down_realfilename'] != '') {
714                $arrErr['down_realfilename'] = '※ 実商品の場合はダウンロード商品用ファイルアップロードは入力できません。';
715            }
716        } elseif (array_search('product_type_id', $this->arrFormKeyList) !== FALSE
717                  && $item['product_type_id'] == PRODUCT_TYPE_DOWNLOAD
718        ) {
719            //ダウンロード商品の場合
720            if ($item['down_filename'] == '') {
721                $arrErr['down_filename'] = '※ ダウンロード商品の場合はダウンロードファイル名は必須です。';
722            }
723            if ($item['down_realfilename'] == '') {
724                $arrErr['down_realfilename'] = '※ ダウンロード商品の場合はダウンロード商品用ファイルアップロードは必須です。';
725            }
726        }
727        return $arrErr;
728    }
729
730    // TODO: ここから下のルーチンは汎用ルーチンとして移動が望ましい
731
732    /**
733     * 指定された行番号をmicrotimeに付与してDB保存用の時間を生成する。
734     * トランザクション内のCURRENT_TIMESTAMPは全てcommit()時の時間に統一されてしまう為。
735     *
736     * @param string $line_no 行番号
737     * @return string $time DB保存用の時間文字列
738     */
739    function lfGetDbFormatTimeWithLine($line_no = '') {
740        $time = date('Y-m-d H:i:s');
741        // 秒以下を生成
742        if ($line_no != '') {
743            $microtime = sprintf('%06d', $line_no);
744            $time .= ".$microtime";
745        }
746        return $time;
747    }
748
749    /**
750     * 指定されたキーと複数値の有効性の配列内確認
751     *
752     * @param string $arr チェック対象配列
753     * @param string $keyname フォームキー名
754     * @param array  $item 入力データ配列
755     * @param string $delimiter 分割文字
756     * @return boolean true:有効なデータがある false:有効ではない
757     */
758    function lfIsArrayRecordMulti($arr, $keyname, $item, $delimiter = ',') {
759        if (array_search($keyname, $this->arrFormKeyList) === FALSE) {
760            return true;
761        }
762        if ($item[$keyname] == '') {
763            return true;
764        }
765        $arrItems = explode($delimiter, $item[$keyname]);
766        //空項目のチェック 1つでも空指定があったら不正とする。
767        if (array_search('', $arrItems) !== FALSE) {
768            return false;
769        }
770        //キー項目への存在チェック
771        foreach ($arrItems as $item) {
772            if (!array_key_exists($item, $arr)) {
773                return false;
774            }
775        }
776        return true;
777    }
778
779    /**
780     * 指定されたキーと複数値の有効性のDB確認
781     *
782     * @param string $table テーブル名
783     * @param string $tblkey テーブルキー名
784     * @param string $keyname フォームキー名
785     * @param array  $item 入力データ配列
786     * @param string $delimiter 分割文字
787     * @return boolean true:有効なデータがある false:有効ではない
788     */
789    function lfIsDbRecordMulti($table, $tblkey, $keyname, $item, $delimiter = ',') {
790        if (array_search($keyname, $this->arrFormKeyList) === FALSE) {
791            return true;
792        }
793        if ($item[$keyname] == '') {
794            return true;
795        }
796        $arrItems = explode($delimiter, $item[$keyname]);
797        //空項目のチェック 1つでも空指定があったら不正とする。
798        if (array_search('', $arrItems) !== FALSE) {
799            return false;
800        }
801        $count = count($arrItems);
802        $where = $tblkey .' IN (' . SC_Utils_Ex::repeatStrWithSeparator('?', $count) . ')';
803
804        $objQuery =& SC_Query_Ex::getSingletonInstance();
805        $db_count = $objQuery->count($table, $where, $arrItems);
806        if ($count != $db_count) {
807            return false;
808        }
809        return true;
810    }
811
812    /**
813     * 指定されたキーと値の有効性のDB確認
814     *
815     * @param string $table テーブル名
816     * @param string $keyname キー名
817     * @param array  $item 入力データ配列
818     * @return boolean true:有効なデータがある false:有効ではない
819     */
820    function lfIsDbRecord($table, $keyname, $item) {
821        if (array_search($keyname, $this->arrFormKeyList) !== FALSE  //入力対象である
822            && $item[$keyname] != ''   // 空ではない
823            && !$this->objDb->sfIsRecord($table, $keyname, (array)$item[$keyname]) //DBに存在するか
824        ) {
825            return false;
826        }
827        return true;
828    }
829
830    /**
831     * 指定されたキーと値の有効性の配列内確認
832     *
833     * @param string $arr チェック対象配列
834     * @param string $keyname キー名
835     * @param array  $item 入力データ配列
836     * @return boolean true:有効なデータがある false:有効ではない
837     */
838    function lfIsArrayRecord($arr, $keyname, $item) {
839        if (array_search($keyname, $this->arrFormKeyList) !== FALSE //入力対象である
840            && $item[$keyname] != '' // 空ではない
841            && !array_key_exists($item[$keyname], $arr) //配列に存在するか
842        ) {
843            return false;
844        }
845        return true;
846    }
847}
Note: See TracBrowser for help on using the repository browser.