source: branches/version-2_13_3/data/class/pages/admin/products/LC_Page_Admin_Products_UploadCSVCategory.php @ 23667

Revision 23667, 21.7 KB checked in by shinichi_takahashi, 9 years ago (diff)

#2028 r23498をリバート

  • 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-2014 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(CSV_TEMP_REALDIR, CSV_TEMP_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  string  $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  string  $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     * @param SC_UploadFile $objUpFile
264     * @return void
265     */
266    public function lfInitFile(SC_UploadFile &$objUpFile)
267    {
268        $objUpFile->addFile('CSVファイル', 'csv_file', array('csv'), CSV_SIZE, true, 0, 0, false);
269    }
270
271    /**
272     * 入力情報の初期化を行う.
273     *
274     * @param SC_FormParam $objFormParam
275     * @param array $arrCSVFrame CSV構造設定配列
276     * @return void
277     */
278    public function lfInitParam(SC_FormParam &$objFormParam, &$arrCSVFrame)
279    {
280        // 固有の初期値調整
281        $arrCSVFrame = $this->lfSetParamDefaultValue($arrCSVFrame);
282        // CSV項目毎の処理
283        foreach ($arrCSVFrame as $item) {
284            if ($item['status'] == CSV_COLUMN_STATUS_FLG_DISABLE) continue;
285            //サブクエリ構造の場合は AS名 を使用
286            if (preg_match_all('/\(.+\) as (.+)$/i', $item['col'], $match, PREG_SET_ORDER)) {
287                $col = $match[0][1];
288            } else {
289                $col = $item['col'];
290            }
291            // HTML_TAG_CHECKは別途実行なので除去し、別保存しておく
292            if (strpos(strtoupper($item['error_check_types']), 'HTML_TAG_CHECK') !== FALSE) {
293                $this->arrTagCheckItem[] = $item;
294                $error_check_types = str_replace('HTML_TAG_CHECK', '', $item['error_check_types']);
295            } else {
296                $error_check_types = $item['error_check_types'];
297            }
298            $arrErrorCheckTypes = explode(',', $error_check_types);
299            foreach ($arrErrorCheckTypes as $key => $val) {
300                if (trim($val) == '') {
301                    unset($arrErrorCheckTypes[$key]);
302                } else {
303                    $arrErrorCheckTypes[$key] = trim($val);
304                }
305            }
306            // パラメーター登録
307            $objFormParam->addParam(
308                    $item['disp_name'],
309                    $col,
310                    constant($item['size_const_type']),
311                    $item['mb_convert_kana_option'],
312                    $arrErrorCheckTypes,
313                    $item['default'],
314                    $item['rw_flg'] != CSV_COLUMN_RW_FLG_READ_ONLY
315                    );
316        }
317    }
318
319    /**
320     * 入力チェックを行う.
321     *
322     * @param SC_FormParam $objFormParam
323     * @return array
324     */
325    public function lfCheckError(SC_FormParam &$objFormParam)
326    {
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
340        return $objErr->arrErr;
341    }
342
343    /**
344     * 保存先テーブル情報の初期化を行う.
345     *
346     * @return void
347     */
348    public function lfInitTableInfo()
349    {
350        $objQuery =& SC_Query_Ex::getSingletonInstance();
351        $this->arrRegistColumn = $objQuery->listTableFields('dtb_category');
352    }
353
354    /**
355     * カテゴリ登録を行う.
356     *
357     * FIXME: 登録の実処理自体は、LC_Page_Admin_Products_Categoryと共通化して欲しい。
358     *
359     * @param  SC_Query       $objQuery SC_Queryインスタンス
360     * @param  string|integer $line     処理中の行数
361     * @return integer        カテゴリID
362     */
363    public function lfRegistCategory($objQuery, $line, &$objFormParam)
364    {
365        // 登録データ対象取得
366        $arrList = $objFormParam->getDbArray();
367        // 登録時間を生成(DBのCURRENT_TIMESTAMPだとcommitした際、全て同一の時間になってしまう)
368        $arrList['update_date'] = $this->lfGetDbFormatTimeWithLine($line);
369
370        // 登録情報を生成する。
371        // テーブルのカラムに存在しているもののうち、Form投入設定されていないデータは上書きしない。
372        $sqlval = SC_Utils_Ex::sfArrayIntersectKeys($arrList, $this->arrRegistColumn);
373
374        // 必須入力では無い項目だが、空文字では問題のある特殊なカラム値の初期値設定
375        $sqlval = $this->lfSetCategoryDefaultData($sqlval);
376
377        if ($sqlval['category_id'] != '') {
378            // 同じidが存在すればupdate存在しなければinsert
379            $where = 'category_id = ?';
380            $category_exists = $objQuery->exists('dtb_category', $where, array($sqlval['category_id']));
381            if ($category_exists) {
382                // UPDATEの実行
383                $where = 'category_id = ?';
384                $objQuery->update('dtb_category', $sqlval, $where, array($sqlval['category_id']));
385            } else {
386                $sqlval['create_date'] = $arrList['update_date'];
387                // 新規登録
388                $category_id = $this->registerCategory($sqlval['parent_category_id'],
389                                        $sqlval['category_name'],
390                                        $_SESSION['member_id'],
391                                        $sqlval['category_id']);
392            }
393            $category_id = $sqlval['category_id'];
394            // TODO: 削除時処理
395        } else {
396            // 新規登録
397            $category_id = $this->registerCategory($sqlval['parent_category_id'],
398                                        $sqlval['category_name'],
399                                        $_SESSION['member_id']);
400        }
401
402        return $category_id;
403    }
404
405    /**
406     * 初期値の設定
407     *
408     * @param  array $arrCSVFrame CSV構造配列
409     * @return array $arrCSVFrame CSV構造配列
410     */
411    public function lfSetParamDefaultValue(&$arrCSVFrame)
412    {
413        foreach ($arrCSVFrame as $key => $val) {
414            switch ($val['col']) {
415                case 'parent_category_id':
416                    $arrCSVFrame[$key]['default'] = '0';
417                    break;
418                case 'del_flg':
419                    $arrCSVFrame[$key]['default'] = '0';
420                    break;
421                default:
422                    break;
423            }
424        }
425
426        return $arrCSVFrame;
427    }
428
429    /**
430     * データ登録前に特殊な値の持ち方をする部分のデータ部分の初期値補正を行う
431     *
432     * @param array $sqlval 商品登録情報配列
433     * @return array $sqlval 登録情報配列
434     */
435    public function lfSetCategoryDefaultData(&$sqlval)
436    {
437        if ($sqlval['del_flg'] == '') {
438            $sqlval['del_flg'] = '0'; //有効
439        }
440        if ($sqlval['creator_id'] == '') {
441            $sqlval['creator_id'] = $_SESSION['member_id'];
442        }
443        if ($sqlval['parent_category_id'] == '') {
444            $sqlval['parent_category_id'] = (string) '0';
445        }
446
447        return $sqlval;
448    }
449
450    /**
451     * このフォーム特有の複雑な入力チェックを行う.
452     *
453     * @param array $item 確認対象データ
454     * @param array $arrErr エラー配列
455     * @return array エラー配列
456     */
457    public function lfCheckErrorDetail($item, $arrErr)
458    {
459        $objQuery =& SC_Query_Ex::getSingletonInstance();
460        /*
461        // カテゴリIDの存在チェック
462        if (!$this->lfIsDbRecord('dtb_category', 'category_id', $item)) {
463            $arrErr['category_id'] = '※ 指定のカテゴリIDは、登録されていません。';
464        }
465        */
466        // 親カテゴリIDの存在チェック
467        if (array_search('parent_category_id', $this->arrFormKeyList) !== FALSE
468            && $item['parent_category_id'] != ''
469            && $item['parent_category_id'] != '0'
470            && !SC_Helper_DB_Ex::sfIsRecord('dtb_category', 'category_id', array($item['parent_category_id']))
471        ) {
472            $arrErr['parent_category_id'] = '※ 指定の親カテゴリID(' . $item['parent_category_id'] . ')は、存在しません。';
473        }
474        // 削除フラグのチェック
475        if (array_search('del_flg', $this->arrFormKeyList) !== FALSE
476            && $item['del_flg'] != ''
477        ) {
478            if (!($item['del_flg'] == '0' or $item['del_flg'] == '1')) {
479                $arrErr['del_flg'] = '※ 削除フラグは「0」(有効)、「1」(削除)のみが有効な値です。';
480            }
481        }
482        // 重複チェック 同じカテゴリ内に同名の存在は許可されない
483        if (array_search('category_name', $this->arrFormKeyList) !== FALSE
484            && $item['category_name'] != ''
485        ) {
486            $parent_category_id = $item['parent_category_id'];
487            if ($parent_category_id == '') {
488                $parent_category_id = (string) '0';
489            }
490            $where = 'parent_category_id = ? AND category_id <> ? AND category_name = ?';
491            $exists = $objQuery->exists('dtb_category',
492                        $where,
493                        array($parent_category_id,
494                                $item['category_id'],
495                                $item['category_name']));
496            if ($exists) {
497                $arrErr['category_name'] = '※ 既に同名のカテゴリが存在します。';
498            }
499        }
500        // 登録数上限チェック
501        $where = 'del_flg = 0';
502        $count = $objQuery->count('dtb_category', $where);
503        if ($count >= CATEGORY_MAX) {
504            $item['category_name'] = '※ カテゴリの登録最大数を超えました。';
505        }
506
507        if (array_search('parent_category_id', $this->arrFormKeyList) !== FALSE
508                and $item['parent_category_id'] != '') {
509            $level = $objQuery->get('level', 'dtb_category', 'category_id = ?', array($parent_category_id));
510            if ($level >= LEVEL_MAX) {
511                $arrErr['parent_category_id'] = '※ ' . LEVEL_MAX . '階層以上の登録はできません。';
512            }
513        }
514
515
516        return $arrErr;
517    }
518
519    /**
520     * カテゴリを登録する
521     *
522     * @param integer 親カテゴリID
523     * @param string カテゴリ名
524     * @param integer 作成者のID
525     * @param integer 指定カテゴリID
526     * @return integer カテゴリID
527     */
528    public function registerCategory($parent_category_id, $category_name, $creator_id, $category_id = null)
529    {
530        $objQuery =& SC_Query_Ex::getSingletonInstance();
531
532        $rank = null;
533        if ($parent_category_id == 0) {
534            // ROOT階層で最大のランクを取得する。
535            $where = 'parent_category_id = ?';
536            $rank = $objQuery->max('rank', 'dtb_category', $where, array($parent_category_id)) + 1;
537        } else {
538            // 親のランクを自分のランクとする。
539            $where = 'category_id = ?';
540            $rank = $objQuery->get('rank', 'dtb_category', $where, array($parent_category_id));
541            // 追加レコードのランク以上のレコードを一つあげる。
542            $where = 'rank >= ?';
543            $arrRawSql = array(
544                'rank' => '(rank + 1)',
545            );
546            $objQuery->update('dtb_category', array(), $where, array($rank), $arrRawSql);
547        }
548
549        $where = 'category_id = ?';
550        // 自分のレベルを取得する(親のレベル + 1)
551        $level = $objQuery->get('level', 'dtb_category', $where, array($parent_category_id)) + 1;
552
553        $arrCategory = array();
554        $arrCategory['category_name'] = $category_name;
555        $arrCategory['parent_category_id'] = $parent_category_id;
556        $arrCategory['create_date'] = 'CURRENT_TIMESTAMP';
557        $arrCategory['update_date'] = 'CURRENT_TIMESTAMP';
558        $arrCategory['creator_id']  = $creator_id;
559        $arrCategory['rank']        = $rank;
560        $arrCategory['level']       = $level;
561        //カテゴリIDが指定されていればそれを利用する
562        if (isset($category_id)) {
563            $arrCategory['category_id'] = $category_id;
564            // シーケンスの調整
565            $seq_count = $objQuery->currVal('dtb_category_category_id');
566            if ($seq_count < $arrCategory['category_id']) {
567                $objQuery->setVal('dtb_category_category_id', $arrCategory['category_id'] + 1);
568            }
569        } else {
570            $arrCategory['category_id'] = $objQuery->nextVal('dtb_category_category_id');
571        }
572        $objQuery->insert('dtb_category', $arrCategory);
573
574        return $arrCategory['category_id'];
575    }
576
577    /**
578     * 指定された行番号をmicrotimeに付与してDB保存用の時間を生成する。
579     * トランザクション内のCURRENT_TIMESTAMPは全てcommit()時の時間に統一されてしまう為。
580     *
581     * @param  string $line_no 行番号
582     * @return string $time DB保存用の時間文字列
583     */
584    public function lfGetDbFormatTimeWithLine($line_no = '')
585    {
586        $time = date('Y-m-d H:i:s');
587        // 秒以下を生成
588        if ($line_no != '') {
589            $microtime = sprintf('%06d', $line_no);
590            $time .= ".$microtime";
591        }
592
593        return $time;
594    }
595
596    /**
597     * 指定されたキーと値の有効性のDB確認
598     *
599     * @param  string  $table   テーブル名
600     * @param  string  $keyname キー名
601     * @param  array   $item    入力データ配列
602     * @return boolean true:有効なデータがある false:有効ではない
603     */
604    public function lfIsDbRecord($table, $keyname, $item)
605    {
606        if (array_search($keyname, $this->arrFormKeyList) !== FALSE  //入力対象である
607            && $item[$keyname] != ''   // 空ではない
608            && !SC_Helper_DB_Ex::sfIsRecord($table, $keyname, (array) $item[$keyname]) //DBに存在するか
609        ) {
610            return false;
611        }
612
613        return true;
614    }
615}
Note: See TracBrowser for help on using the repository browser.