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

Revision 22960, 35.9 KB checked in by Seasoft, 11 years ago (diff)

#2043 (typo修正・ソース整形・ソースコメントの改善 for 2.13.0)

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