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

Revision 23020, 21.6 KB checked in by kimoto, 11 years ago (diff)

#2320 カテゴリ登録CSVでFatal error
#2043 typo修正・ソース整形・ソースコメントの改善

  • 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 * LC_Page_Admin_Products_UploadCSV をカスタマイズする場合はこのクラスを編集する.
30 *
31 * @package Page
32 * @author LOCKON CO.,LTD.
33 * @version $$Id$$
34 */
35class LC_Page_Admin_Products_UploadCSVCategory extends LC_Page_Admin_Ex
36{
37    /** エラー情報 **/
38    public $arrErr;
39
40    /** 表示用項目 **/
41    public $arrTitle;
42
43    /** 結果行情報 **/
44    public $arrRowResult;
45
46    /** エラー行情報 **/
47    public $arrRowErr;
48
49    /** TAGエラーチェックフィールド情報 */
50    public $arrTagCheckItem;
51
52    /** テーブルカラム情報 (登録処理用) **/
53    public $arrRegistColumn;
54
55    /** 登録フォームカラム情報 **/
56    public $arrFormKeyList;
57
58    /**
59     * Page を初期化する.
60     *
61     * @return void
62     */
63    public function init()
64    {
65        parent::init();
66        $this->tpl_mainpage = 'products/upload_csv_category.tpl';
67        $this->tpl_mainno   = 'products';
68        $this->tpl_subno    = 'upload_csv_category';
69        $this->tpl_maintitle = '商品管理';
70        $this->tpl_subtitle = 'カテゴリ登録CSV';
71        $this->csv_id = '5';
72
73        $masterData = new SC_DB_MasterData_Ex();
74        $this->arrAllowedTag = $masterData->getMasterData('mtb_allowed_tag');
75        $this->arrTagCheckItem = array();
76    }
77
78    /**
79     * Page のプロセス.
80     *
81     * @return void
82     */
83    public function process()
84    {
85        $this->action();
86        $this->sendResponse();
87    }
88
89    /**
90     * Page のアクション.
91     *
92     * @return void
93     */
94    public function action()
95    {
96        // CSV管理ヘルパー
97        $objCSV = new SC_Helper_CSV_Ex();
98        // CSV構造読み込み
99        $arrCSVFrame = $objCSV->sfGetCsvOutput($this->csv_id);
100
101        // CSV構造がインポート可能かのチェック
102        if (!$objCSV->sfIsImportCSVFrame($arrCSVFrame)) {
103            // 無効なフォーマットなので初期状態に強制変更
104            $arrCSVFrame = $objCSV->sfGetCsvOutput($this->csv_id, '', array(), 'no');
105            $this->tpl_is_format_default = true;
106        }
107        // CSV構造は更新可能なフォーマットかのフラグ取得
108        $this->tpl_is_update = $objCSV->sfIsUpdateCSVFrame($arrCSVFrame);
109
110        // CSVファイルアップロード情報の初期化
111        $objUpFile = new SC_UploadFile_Ex(IMAGE_TEMP_REALDIR, IMAGE_SAVE_REALDIR);
112        $this->lfInitFile($objUpFile);
113
114        // パラメーター情報の初期化
115        $objFormParam = new SC_FormParam_Ex();
116        $this->lfInitParam($objFormParam, $arrCSVFrame);
117
118        $this->max_upload_csv_size = SC_Utils_Ex::getUnitDataSize(CSV_SIZE);
119
120        $objFormParam->setHtmlDispNameArray();
121        $this->arrTitle = $objFormParam->getHtmlDispNameArray();
122
123        switch ($this->getMode()) {
124            case 'csv_upload':
125                $this->doUploadCsv($objFormParam, $objUpFile);
126                break;
127            default:
128                break;
129        }
130
131    }
132
133    /**
134     * 登録/編集結果のメッセージをプロパティへ追加する
135     *
136     * @param  integer $line_count 行数
137     * @param  stirng  $message    メッセージ
138     * @return void
139     */
140    public function addRowResult($line_count, $message)
141    {
142        $this->arrRowResult[] = $line_count . '行目:' . $message;
143    }
144
145    /**
146     * 登録/編集結果のエラーメッセージをプロパティへ追加する
147     *
148     * @param  integer $line_count 行数
149     * @param  stirng  $message    メッセージ
150     * @return void
151     */
152    public function addRowErr($line_count, $message)
153    {
154        $this->arrRowErr[] = $line_count . '行目:' . $message;
155    }
156
157    /**
158     * CSVアップロードを実行する
159     *
160     * @param  SC_FormParam  $objFormParam
161     * @param  SC_UploadFile $objUpFile
162     * @return void
163     */
164    public function doUploadCsv(&$objFormParam, &$objUpFile)
165    {
166        // ファイルアップロードのチェック
167        $objUpFile->makeTempFile('csv_file');
168        $arrErr = $objUpFile->checkExists();
169        if (count($arrErr) > 0) {
170            $this->arrErr = $arrErr;
171
172            return;
173        }
174        // 一時ファイル名の取得
175        $filepath = $objUpFile->getTempFilePath('csv_file');
176        // CSVファイルの文字コード変換
177        $enc_filepath = SC_Utils_Ex::sfEncodeFile($filepath, CHAR_CODE, CSV_TEMP_REALDIR);
178        // CSVファイルのオープン
179        $fp = fopen($enc_filepath, 'r');
180        // 失敗した場合はエラー表示
181        if (!$fp) {
182            SC_Utils_Ex::sfDispError('');
183        }
184
185        // 登録先テーブル カラム情報の初期化
186        $this->lfInitTableInfo();
187
188        // 登録フォーム カラム情報
189        $this->arrFormKeyList = $objFormParam->getKeyList();
190
191        // 登録対象の列数
192        $col_max_count = $objFormParam->getCount();
193        // 行数
194        $line_count = 0;
195
196        $objQuery =& SC_Query_Ex::getSingletonInstance();
197        $objQuery->begin();
198
199        $errFlag = false;
200
201        while (!feof($fp)) {
202            $arrCSV = fgetcsv($fp, CSV_LINE_MAX);
203            // 行カウント
204            $line_count++;
205            // ヘッダ行はスキップ
206            if ($line_count == 1) {
207                continue;
208            }
209            // 空行はスキップ
210            if (empty($arrCSV)) {
211                continue;
212            }
213            // 列数が異なる場合はエラー
214            $col_count = count($arrCSV);
215            if ($col_max_count != $col_count) {
216                $this->addRowErr($line_count, '※ 項目数が' . $col_count . '個検出されました。項目数は' . $col_max_count . '個になります。');
217                $errFlag = true;
218                break;
219            }
220            // シーケンス配列を格納する。
221            $objFormParam->setParam($arrCSV, true);
222            // 入力値の変換
223            $objFormParam->convParam();
224            // <br>なしでエラー取得する。
225            $arrCSVErr = $this->lfCheckError($objFormParam);
226
227            // 入力エラーチェック
228            if (count($arrCSVErr) > 0) {
229                foreach ($arrCSVErr as $err) {
230                    $this->addRowErr($line_count, $err);
231                }
232                $errFlag = true;
233                break;
234            }
235
236            $category_id = $this->lfRegistCategory($objQuery, $line_count, $objFormParam);
237            $this->addRowResult($line_count, 'カテゴリID:'.$category_id . ' / カテゴリ名:' . $objFormParam->getValue('category_name'));
238        }
239
240        // 実行結果画面を表示
241        $this->tpl_mainpage = 'products/upload_csv_category_complete.tpl';
242
243        fclose($fp);
244
245        if ($errFlag) {
246            $objQuery->rollback();
247
248            return;
249        }
250
251        $objQuery->commit();
252
253        // カテゴリ件数を更新
254        $objDb = new SC_Helper_DB_Ex();
255        $objDb->sfCountCategory($objQuery);
256
257        return;
258    }
259
260    /**
261     * ファイル情報の初期化を行う.
262     *
263     * @return void
264     */
265    public function lfInitFile(&$objUpFile)
266    {
267        $objUpFile->addFile('CSVファイル', 'csv_file', array('csv'), CSV_SIZE, true, 0, 0, false);
268    }
269
270    /**
271     * 入力情報の初期化を行う.
272     *
273     * @param array CSV構造設定配列
274     * @return void
275     */
276    public function lfInitParam(&$objFormParam, &$arrCSVFrame)
277    {
278        // 固有の初期値調整
279        $arrCSVFrame = $this->lfSetParamDefaultValue($arrCSVFrame);
280        // CSV項目毎の処理
281        foreach ($arrCSVFrame as $item) {
282            if ($item['status'] == CSV_COLUMN_STATUS_FLG_DISABLE) continue;
283            //サブクエリ構造の場合は AS名 を使用
284            if (preg_match_all('/\(.+\) as (.+)$/i', $item['col'], $match, PREG_SET_ORDER)) {
285                $col = $match[0][1];
286            } else {
287                $col = $item['col'];
288            }
289            // HTML_TAG_CHECKは別途実行なので除去し、別保存しておく
290            if (strpos(strtoupper($item['error_check_types']), 'HTML_TAG_CHECK') !== FALSE) {
291                $this->arrTagCheckItem[] = $item;
292                $error_check_types = str_replace('HTML_TAG_CHECK', '', $item['error_check_types']);
293            } else {
294                $error_check_types = $item['error_check_types'];
295            }
296            $arrErrorCheckTypes = explode(',', $error_check_types);
297            foreach ($arrErrorCheckTypes as $key => $val) {
298                if (trim($val) == '') {
299                    unset($arrErrorCheckTypes[$key]);
300                } else {
301                    $arrErrorCheckTypes[$key] = trim($val);
302                }
303            }
304            // パラメーター登録
305            $objFormParam->addParam(
306                    $item['disp_name']
307                    , $col
308                    , constant($item['size_const_type'])
309                    , $item['mb_convert_kana_option']
310                    , $arrErrorCheckTypes
311                    , $item['default']
312                    , ($item['rw_flg'] != CSV_COLUMN_RW_FLG_READ_ONLY) ? true : false
313                    );
314        }
315    }
316
317    /**
318     * 入力チェックを行う.
319     *
320     * @return void
321     */
322    public function lfCheckError(&$objFormParam)
323    {
324        // 入力データを渡す。
325        $arrRet =  $objFormParam->getHashArray();
326        $objErr = new SC_CheckError_Ex($arrRet);
327        $objErr->arrErr = $objFormParam->checkError(false);
328        // HTMLタグチェックの実行
329        foreach ($this->arrTagCheckItem as $item) {
330            $objErr->doFunc(array($item['disp_name'], $item['col'], $this->arrAllowedTag), array('HTML_TAG_CHECK'));
331        }
332        // このフォーム特有の複雑系のエラーチェックを行う
333        if (count($objErr->arrErr) == 0) {
334            $objErr->arrErr = $this->lfCheckErrorDetail($arrRet, $objErr->arrErr);
335        }
336
337        return $objErr->arrErr;
338    }
339
340    /**
341     * 保存先テーブル情報の初期化を行う.
342     *
343     * @return void
344     */
345    public function lfInitTableInfo()
346    {
347        $objQuery =& SC_Query_Ex::getSingletonInstance();
348        $this->arrRegistColumn = $objQuery->listTableFields('dtb_category');
349    }
350
351    /**
352     * カテゴリ登録を行う.
353     *
354     * FIXME: 登録の実処理自体は、LC_Page_Admin_Products_Categoryと共通化して欲しい。
355     *
356     * @param  SC_Query       $objQuery SC_Queryインスタンス
357     * @param  string|integer $line     処理中の行数
358     * @return integer        カテゴリID
359     */
360    public function lfRegistCategory($objQuery, $line, &$objFormParam)
361    {
362        // 登録データ対象取得
363        $arrList = $objFormParam->getHashArray();
364        // 登録時間を生成(DBのCURRENT_TIMESTAMPだとcommitした際、全て同一の時間になってしまう)
365        $arrList['update_date'] = $this->lfGetDbFormatTimeWithLine($line);
366
367        // 登録情報を生成する。
368        // テーブルのカラムに存在しているもののうち、Form投入設定されていないデータは上書きしない。
369        $sqlval = SC_Utils_Ex::sfArrayIntersectKeys($arrList, $this->arrRegistColumn);
370
371        // 必須入力では無い項目だが、空文字では問題のある特殊なカラム値の初期値設定
372        $sqlval = $this->lfSetCategoryDefaultData($sqlval);
373
374        if ($sqlval['category_id'] != '') {
375            // 同じidが存在すればupdate存在しなければinsert
376            $where = 'category_id = ?';
377            $category_exists = $objQuery->exists('dtb_category', $where, array($sqlval['category_id']));
378            if ($category_exists) {
379                // UPDATEの実行
380                $where = 'category_id = ?';
381                $objQuery->update('dtb_category', $sqlval, $where, array($sqlval['category_id']));
382            } else {
383                $sqlval['create_date'] = $arrList['update_date'];
384                // 新規登録
385                $category_id = $this->registerCategory($sqlval['parent_category_id'],
386                                        $sqlval['category_name'],
387                                        $_SESSION['member_id'],
388                                        $sqlval['category_id']);
389            }
390            $category_id = $sqlval['category_id'];
391            // TODO: 削除時処理
392        } else {
393            // 新規登録
394            $category_id = $this->registerCategory($sqlval['parent_category_id'],
395                                        $sqlval['category_name'],
396                                        $_SESSION['member_id']);
397        }
398
399        return $category_id;
400    }
401
402    /**
403     * 初期値の設定
404     *
405     * @param  array $arrCSVFrame CSV構造配列
406     * @return array $arrCSVFrame CSV構造配列
407     */
408    public function lfSetParamDefaultValue(&$arrCSVFrame)
409    {
410        foreach ($arrCSVFrame as $key => $val) {
411            switch ($val['col']) {
412                case 'parent_category_id':
413                    $arrCSVFrame[$key]['default'] = '0';
414                    break;
415                case 'del_flg':
416                    $arrCSVFrame[$key]['default'] = '0';
417                    break;
418                default:
419                    break;
420            }
421        }
422
423        return $arrCSVFrame;
424    }
425
426    /**
427     * データ登録前に特殊な値の持ち方をする部分のデータ部分の初期値補正を行う
428     *
429     * @param array $sqlval 商品登録情報配列
430     * @return $sqlval 登録情報配列
431     */
432    public function lfSetCategoryDefaultData(&$sqlval)
433    {
434        if ($sqlval['del_flg'] == '') {
435            $sqlval['del_flg'] = '0'; //有効
436        }
437        if ($sqlval['creator_id'] == '') {
438            $sqlval['creator_id'] = $_SESSION['member_id'];
439        }
440        if ($sqlval['parent_category_id'] == '') {
441            $sqlval['parent_category_id'] = (string) '0';
442        }
443
444        return $sqlval;
445    }
446
447    /**
448     * このフォーム特有の複雑な入力チェックを行う.
449     *
450     * @param array 確認対象データ
451     * @param array エラー配列
452     * @return array エラー配列
453     */
454    public function lfCheckErrorDetail($item, $arrErr)
455    {
456        $objQuery =& SC_Query_Ex::getSingletonInstance();
457        /*
458        // カテゴリIDの存在チェック
459        if (!$this->lfIsDbRecord('dtb_category', 'category_id', $item)) {
460            $arrErr['category_id'] = '※ 指定のカテゴリIDは、登録されていません。';
461        }
462        */
463        // 親カテゴリIDの存在チェック
464        if (array_search('parent_category_id', $this->arrFormKeyList) !== FALSE
465            && $item['parent_category_id'] != ''
466            && $item['parent_category_id'] != '0'
467            && !SC_Helper_DB_Ex::sfIsRecord('dtb_category', 'category_id', array($item['parent_category_id']))
468        ) {
469            $arrErr['parent_category_id'] = '※ 指定の親カテゴリID(' . $item['parent_category_id'] . ')は、存在しません。';
470        }
471        // 削除フラグのチェック
472        if (array_search('del_flg', $this->arrFormKeyList) !== FALSE
473            && $item['del_flg'] != ''
474        ) {
475            if (!($item['del_flg'] == '0' or $item['del_flg'] == '1')) {
476                $arrErr['del_flg'] = '※ 削除フラグは「0」(有効)、「1」(削除)のみが有効な値です。';
477            }
478        }
479        // 重複チェック 同じカテゴリ内に同名の存在は許可されない
480        if (array_search('category_name', $this->arrFormKeyList) !== FALSE
481            && $item['category_name'] != ''
482        ) {
483            $parent_category_id = $item['parent_category_id'];
484            if ($parent_category_id == '') {
485                $parent_category_id = (string) '0';
486            }
487            $where = 'parent_category_id = ? AND category_id <> ? AND category_name = ?';
488            $exists = $objQuery->exists('dtb_category',
489                        $where,
490                        array($parent_category_id,
491                                $item['category_id'],
492                                $item['category_name']));
493            if ($exists) {
494                $arrErr['category_name'] = '※ 既に同名のカテゴリが存在します。';
495            }
496        }
497        // 登録数上限チェック
498        $where = 'del_flg = 0';
499        $count = $objQuery->count('dtb_category', $where);
500        if ($count >= CATEGORY_MAX) {
501            $item['category_name'] = '※ カテゴリの登録最大数を超えました。';
502        }
503        // 階層上限チェック
504        if (array_search('parent_category_id', $this->arrFormKeyList) !== FALSE
505                and $item['parent_category_id'] != '') {
506            $level = $objQuery->get('level', 'dtb_category', 'category_id = ?', array($parent_category_id));
507            if ($level >= LEVEL_MAX) {
508                $arrErr['parent_category_id'] = '※ ' . LEVEL_MAX . '階層以上の登録はできません。';
509            }
510        }
511
512        return $arrErr;
513    }
514
515    /**
516     * カテゴリを登録する
517     *
518     * @param integer 親カテゴリID
519     * @param string カテゴリ名
520     * @param integer 作成者のID
521     * @param integer 指定カテゴリID
522     * @return integer カテゴリID
523     */
524    public function registerCategory($parent_category_id, $category_name, $creator_id, $category_id = null)
525    {
526        $objQuery =& SC_Query_Ex::getSingletonInstance();
527
528        $rank = null;
529        if ($parent_category_id == 0) {
530            // ROOT階層で最大のランクを取得する。
531            $where = 'parent_category_id = ?';
532            $rank = $objQuery->max('rank', 'dtb_category', $where, array($parent_category_id)) + 1;
533        } else {
534            // 親のランクを自分のランクとする。
535            $where = 'category_id = ?';
536            $rank = $objQuery->get('rank', 'dtb_category', $where, array($parent_category_id));
537            // 追加レコードのランク以上のレコードを一つあげる。
538            $where = 'rank >= ?';
539            $arrRawSql = array(
540                'rank' => '(rank + 1)',
541            );
542            $objQuery->update('dtb_category', array(), $where, array($rank), $arrRawSql);
543        }
544
545        $where = 'category_id = ?';
546        // 自分のレベルを取得する(親のレベル + 1)
547        $level = $objQuery->get('level', 'dtb_category', $where, array($parent_category_id)) + 1;
548
549        $arrCategory = array();
550        $arrCategory['category_name'] = $category_name;
551        $arrCategory['parent_category_id'] = $parent_category_id;
552        $arrCategory['create_date'] = 'CURRENT_TIMESTAMP';
553        $arrCategory['update_date'] = 'CURRENT_TIMESTAMP';
554        $arrCategory['creator_id']  = $creator_id;
555        $arrCategory['rank']        = $rank;
556        $arrCategory['level']       = $level;
557        //カテゴリIDが指定されていればそれを利用する
558        if (isset($category_id)) {
559            $arrCategory['category_id'] = $category_id;
560            // シーケンスの調整
561            $seq_count = $objQuery->currVal('dtb_category_category_id');
562            if ($seq_count < $arrCategory['category_id']) {
563                $objQuery->setVal('dtb_category_category_id', $arrCategory['category_id'] + 1);
564            }
565        } else {
566            $arrCategory['category_id'] = $objQuery->nextVal('dtb_category_category_id');
567        }
568        $objQuery->insert('dtb_category', $arrCategory);
569
570        return $arrCategory['category_id'];
571    }
572
573    /**
574     * 指定された行番号をmicrotimeに付与してDB保存用の時間を生成する。
575     * トランザクション内のCURRENT_TIMESTAMPは全てcommit()時の時間に統一されてしまう為。
576     *
577     * @param  string $line_no 行番号
578     * @return string $time DB保存用の時間文字列
579     */
580    public function lfGetDbFormatTimeWithLine($line_no = '')
581    {
582        $time = date('Y-m-d H:i:s');
583        // 秒以下を生成
584        if ($line_no != '') {
585            $microtime = sprintf('%06d', $line_no);
586            $time .= ".$microtime";
587        }
588
589        return $time;
590    }
591
592    /**
593     * 指定されたキーと値の有効性のDB確認
594     *
595     * @param  string  $table   テーブル名
596     * @param  string  $keyname キー名
597     * @param  array   $item    入力データ配列
598     * @return boolean true:有効なデータがある false:有効ではない
599     */
600    public function lfIsDbRecord($table, $keyname, $item)
601    {
602        if (array_search($keyname, $this->arrFormKeyList) !== FALSE  //入力対象である
603            && $item[$keyname] != ''   // 空ではない
604            && !SC_Helper_DB_Ex::sfIsRecord($table, $keyname, (array) $item[$keyname]) //DBに存在するか
605        ) {
606            return false;
607        }
608
609        return true;
610    }
611}
Note: See TracBrowser for help on using the repository browser.