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

Revision 22742, 36.1 KB checked in by shutta, 11 years ago (diff)

#2044 (無駄な処理を改善する for 2.13.0)
冗長なsetParam処理を削除。

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