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

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