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

Revision 21514, 21.5 KB checked in by Seasoft, 12 years ago (diff)

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