source: branches/version-2_12-multilang/data/class/pages/admin/products/LC_Page_Admin_Products_UploadCSVCategory.php @ 22058

Revision 22058, 21.5 KB checked in by h_yoshimoto, 11 years ago (diff)

#1955 r21998~r22057間のコミットをmerge

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