source: branches/version-2_12-dev/data/class/pages/admin/basis/LC_Page_Admin_Basis_ZipInstall.php @ 21743

Revision 21743, 13.4 KB checked in by AMUAMU, 12 years ago (diff)

#1754 (exit;を個別の処理でしない) #1692 (プラグイン機能) 各ファイルでフックポイントの呼出を書かないで、自動的にフックポイントを呼び出すように修正。

  • 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/** CSV ファイルの最大行数 */
28define('ZIP_CSV_LINE_MAX', 8192);
29
30/** 画像の表示数量 */
31define('IMAGE_MAX', 680);
32
33/** 郵便番号CSV ファイルのパス */
34define('ZIP_CSV_REALFILE', DATA_REALDIR . 'downloads/KEN_ALL.CSV');
35
36/** UTF-8 変換済みの郵便番号CSV ファイルのパス */
37define('ZIP_CSV_UTF8_REALFILE', DATA_REALDIR . 'downloads/KEN_ALL_utf-8.CSV');
38
39/**
40 * 郵便番号DB登録 のページクラス.
41 *
42 * @package Page
43 * @author LOCKON CO.,LTD.
44 * @version $Id:LC_Page_Admin_Basis_ZipInstall.php 16741 2007-11-08 00:43:24Z adachi $
45 */
46class LC_Page_Admin_Basis_ZipInstall extends LC_Page_Admin_Ex {
47
48    /** CSVの行数 */
49    var $tpl_line = 0;
50    var $tpl_mode;
51    var $exec;
52    var $tpl_count_mtb_zip;
53
54    /** CSV の更新日時 */
55    var $tpl_csv_datetime;
56
57    /** 日本郵便から取得した ZIP アーカイブファイルの保管パス */
58    var $zip_csv_temp_realfile;
59
60    // }}}
61    // {{{ functions
62
63    /**
64     * Page を初期化する.
65     *
66     * @return void
67     */
68    function init() {
69        parent::init();
70        $this->tpl_mainpage = 'basis/zip_install.tpl';
71        $this->tpl_subno = 'zip_install';
72        $this->tpl_maintitle = '基本情報管理';
73        $this->tpl_subtitle = '郵便番号DB登録';
74        $this->tpl_mainno = 'basis';
75
76        $this->tpl_mode = $this->getMode();
77        $this->exec = (boolean)$_GET['exec'];
78        $this->zip_csv_temp_realfile = DATA_REALDIR . 'downloads/tmp/ken_all.zip';
79    }
80
81    /**
82     * Page のプロセス.
83     *
84     * @return void
85     */
86    function process() {
87        $this->action();
88        $this->sendResponse();
89    }
90
91    /**
92     * Page のアクション.
93     *
94     * @return void
95     */
96    function action() {
97
98        // パラメーター管理クラス
99        $objFormParam = new SC_FormParam_Ex();
100        // パラメーター情報の初期化
101        $this->lfInitParam($this->tpl_mode, $objFormParam);
102        $objFormParam->setParam($_GET);
103        $this->arrErr = $objFormParam->checkError();
104        $this->arrForm = $objFormParam->getHashArray();
105        $this->tpl_zip_download_url_empty = !defined('ZIP_DOWNLOAD_URL') || strlen(ZIP_DOWNLOAD_URL) === 0 || ZIP_DOWNLOAD_URL === false;
106        $this->tpl_zip_function_not_exists = !function_exists('zip_open');
107        $this->tpl_skip_update_csv = $this->tpl_zip_download_url_empty || $this->tpl_zip_function_not_exists;
108
109        if ($this->exec) {
110            if (!empty($this->arrErr)) {
111                trigger_error('', E_USER_ERROR);
112            }
113            switch ($this->tpl_mode) {
114                // 自動登録
115                case 'auto':
116                    $this->lfAutoCommitZip();
117                    break;
118                // DB手動登録
119                case 'manual':
120                    $this->insertMtbZip($this->arrForm['startRowNum']);
121                    break;
122            }
123            SC_Response_Ex::actionExit();
124        }
125
126        switch ($this->tpl_mode) {
127            // 削除
128            case 'delete':
129                $this->lfDeleteZip();
130
131                // 進捗・完了画面を表示しない
132                $this->tpl_mode = null;
133                break;
134
135            // 郵便番号CSV更新
136            case 'update_csv';
137                $this->lfDownloadZipFileFromJp();
138                $this->lfExtractZipFile();
139
140                // 進捗・完了画面を表示しない
141                $this->tpl_mode = null;
142                break;
143        }
144
145        $this->tpl_line = $this->countZipCsv();
146        $this->tpl_count_mtb_zip = $this->countMtbZip();
147        $this->tpl_csv_datetime = $this->lfGetCsvDatetime();
148        // XXX PHP4 を切捨てたら、ダウンロードの必要性チェックなども行いたい
149        // $arrHeader = get_headers(ZIP_DOWNLOAD_URL, 1);
150
151    }
152
153    /**
154     * デストラクタ.
155     *
156     * @return void
157     */
158    function destroy() {
159        parent::destroy();
160    }
161
162    function lfAutoCommitZip() {
163        $objQuery =& SC_Query_Ex::getSingletonInstance();
164
165        if (!$this->tpl_skip_update_csv) {
166            $this->lfDownloadZipFileFromJp();
167            $this->lfExtractZipFile();
168        }
169
170        $objQuery->begin();
171        $this->lfDeleteZip();
172        $this->insertMtbZip();
173        $objQuery->commit();
174    }
175
176    /**
177     * テーブルデータと UTF-8 変換済みの郵便番号 CSV を削除
178     *
179     * @return void
180     */
181    function lfDeleteZip() {
182        $objQuery =& SC_Query_Ex::getSingletonInstance();
183
184        // DB
185        $objQuery->delete('mtb_zip');
186
187        // UTF-8 変換済みの郵便番号 CSV
188        unlink(ZIP_CSV_UTF8_REALFILE);
189    }
190
191    /**
192     * パラメーター情報の初期化
193     *
194     * @return void
195     */
196    function lfInitParam($tpl_mode, &$objFormParam) {
197        if ($tpl_mode == 'manual') {
198            $objFormParam->addParam('開始行', 'startRowNum', INT_LEN, 'n', array('EXIST_CHECK', 'MAX_LENGTH_CHECK', 'NUM_CHECK'));
199        }
200    }
201
202    /**
203     * DB登録
204     *
205     * @return void
206     */
207    function insertMtbZip($start = 1) {
208        $objQuery =& SC_Query_Ex::getSingletonInstance();
209
210        $img_path = USER_URL . USER_PACKAGE_DIR . 'admin/img/basis/'; // 画像パスは admin 固定
211
212        ?>
213        <html xmlns='http://www.w3.org/1999/xhtml' lang='ja' xml:lang='ja'>
214        <head>
215            <meta http-equiv='Content-Type' content='text/html; charset=<?php echo CHAR_CODE ?>' />
216        </head>
217        <body>
218        <p>DB 登録進捗状況</p>
219        <div style='background-color: #494E5F;'>
220        <?php
221        // 一部のIEは256バイト以上受け取ってから表示を開始する。
222        SC_Utils_Ex::sfFlush(true);
223
224        echo '<img src="' . $img_path . 'zip_install_progress.gif"><br />';
225        echo '<img src="' . $img_path . 'space_w.gif">';
226        SC_Utils_Ex::sfFlush();
227
228        // 画像を一個表示する件数を求める。
229        $line_all = $this->countZipCsv();
230        $disp_line = intval($line_all / IMAGE_MAX);
231
232        /** 現在行(CSV形式。空行は除く。) */
233        $cntCurrentLine = 0;
234        /** 挿入した行数 */
235        $cntInsert = 0;
236        $img_cnt = 0;
237
238        $fp = $this->openZipCsv();
239        while (!feof($fp)) {
240            $arrCSV = fgetcsv($fp, ZIP_CSV_LINE_MAX);
241            if (empty($arrCSV)) continue;
242            $cntCurrentLine++;
243            if ($cntCurrentLine >= $start) {
244                $sqlval = array();
245                $sqlval['zipcode'] = $arrCSV[2];
246                $sqlval['state'] = $arrCSV[6];
247                $sqlval['city'] = $arrCSV[7];
248                $sqlval['town'] = $arrCSV[8];
249                $objQuery->insert('mtb_zip', $sqlval);
250                $cntInsert++;
251            }
252
253            // $disp_line件ごとに進捗表示する
254            if ($cntCurrentLine % $disp_line == 0 && $img_cnt < IMAGE_MAX) {
255                echo '<img src="' . $img_path . 'graph_1_w.gif">';
256                SC_Utils_Ex::sfFlush();
257                $img_cnt++;
258            }
259            SC_Utils_Ex::extendTimeOut();
260        }
261        fclose($fp);
262
263        echo '<img src="' . $img_path . 'space_w.gif">';
264
265        ?>
266        </div>
267        <script type='text/javascript' language='javascript'>
268            <!--
269                // 完了画面
270                function complete() {
271                    document.open('text/html','replace');
272                    document.clear();
273                    document.write('<p>完了しました。<br />');
274                    document.write("<?php echo $cntInsert ?> 件を追加しました。</p>");
275                    document.write("<p><a href='?' target='_top'>戻る</a></p>");
276                    document.close();
277                }
278                // コンテンツを削除するため、タイムアウトで呼び出し。
279                setTimeout('complete()', 0);
280            // -->
281        </script>
282        </body>
283        </html>
284        <?php
285    }
286
287    function openZipCsv() {
288        $this->convertZipCsv();
289        $fp = fopen(ZIP_CSV_UTF8_REALFILE, 'r');
290        if (!$fp) {
291            trigger_error(ZIP_CSV_UTF8_REALFILE . ' の読み込みに失敗しました。', E_USER_ERROR);
292        }
293        return $fp;
294    }
295
296    function convertZipCsv() {
297        if (file_exists(ZIP_CSV_UTF8_REALFILE)) return;
298
299        $fpr = fopen(ZIP_CSV_REALFILE, 'r');
300        if (!$fpr) {
301            trigger_error(ZIP_CSV_REALFILE . ' の読み込みに失敗しました。', E_USER_ERROR);
302        }
303
304        $fpw = fopen(ZIP_CSV_UTF8_REALFILE, 'w');
305        if (!$fpw) {
306            trigger_error(ZIP_CSV_UTF8_REALFILE . ' を開けません。', E_USER_ERROR);
307        }
308
309        while (!feof($fpr)) {
310            fwrite($fpw, mb_convert_encoding(fgets($fpr, ZIP_CSV_LINE_MAX), CHAR_CODE, 'sjis-win'));
311        }
312
313        fclose($fpw);
314        fclose($fpr);
315    }
316
317    function countMtbZip() {
318        $objQuery =& SC_Query_Ex::getSingletonInstance();
319        return $objQuery->count('mtb_zip');
320    }
321
322    function countZipCsv() {
323        $line = 0;
324        $fp = $this->openZipCsv();
325
326        // CSVの行数を数える
327        while (!feof($fp)) {
328            /*
329            // 正確にカウントする
330            $tmp = fgetcsv($fp, ZIP_CSV_LINE_MAX);
331            */
332            // 推測でカウントする
333            $tmp = fgets($fp, ZIP_CSV_LINE_MAX);
334            if (empty($tmp)) continue;
335            $line++;
336        }
337        fclose($fp);
338
339        return $line;
340    }
341
342    /**
343     * 日本郵便から郵便番号 CSV の ZIP アーカイブファイルを取得
344     *
345     * @return void
346     */
347    function lfDownloadZipFileFromJp() {
348        // Proxy経由を可能とする。
349        // TODO Proxyの設定は「data/module/HTTP/Request.php」内の「function HTTP_Request」へ記述する。いずれは、外部設定としたい。
350        $req = new HTTP_Request();
351
352        $req->setURL(ZIP_DOWNLOAD_URL);
353
354        // 郵便番号CSVをdownloadする。
355        $res = $req->sendRequest();
356        if (!$res) {
357            trigger_error(ZIP_DOWNLOAD_URL . ' の取得に失敗しました。', E_USER_ERROR);
358        }
359
360        // 郵便番号CSV(zip file)を保存する。
361        $fp = fopen($this->zip_csv_temp_realfile, 'w');
362        if (!$fp) {
363            trigger_error($this->zip_csv_temp_realfile . ' を開けません。', E_USER_ERROR);
364        }
365        $res = fwrite($fp, $req->getResponseBody());
366        if (!$res) {
367            trigger_error($this->zip_csv_temp_realfile . ' への書き込みに失敗しました。', E_USER_ERROR);
368        }
369    }
370
371    /**
372     * ZIP アーカイブファイルを展開して、郵便番号 CSV を上書き
373     *
374     * @return void
375     */
376    function lfExtractZipFile() {
377        $zip = zip_open($this->zip_csv_temp_realfile);
378        if (!is_resource($zip)) {
379            trigger_error($this->zip_csv_temp_realfile . ' をオープンできません。', E_USER_ERROR);
380        }
381
382        do {
383            $entry = zip_read($zip);
384        } while ($entry && zip_entry_name($entry) != 'KEN_ALL.CSV');
385
386        if (!$entry) {
387            trigger_error($this->zip_csv_temp_realfile . ' に対象ファイルが見つかりません。', E_USER_ERROR);
388        }
389
390        // 展開時の破損を考慮し、別名で一旦展開する。
391        $tmp_csv_realfile = ZIP_CSV_REALFILE . '.tmp';
392
393        $res = zip_entry_open($zip, $entry, 'rb');
394        if (!$res) {
395            trigger_error($this->zip_csv_temp_realfile . ' の展開に失敗しました。', E_USER_ERROR);
396        }
397
398        $fp = fopen($tmp_csv_realfile, 'w');
399        if (!$fp) {
400            trigger_error($tmp_csv_realfile . ' を開けません。', E_USER_ERROR);
401        }
402
403        $res = fwrite($fp, zip_entry_read($entry, zip_entry_filesize($entry)));
404        if ($res === FALSE) {
405            trigger_error($tmp_csv_realfile . ' の書き込みに失敗しました。', E_USER_ERROR);
406        }
407
408        fclose($fp);
409        zip_close($zip);
410
411        // CSV 削除
412        $res = unlink(ZIP_CSV_REALFILE);
413        if (!$res) {
414            trigger_error(ZIP_CSV_REALFILE . ' を削除できません。', E_USER_ERROR);
415        }
416
417        // CSV ファイル名変更
418        $res = rename($tmp_csv_realfile, ZIP_CSV_REALFILE);
419        if (!$res) {
420            trigger_error('ファイル名を変更できません。: ' . $tmp_csv_realfile . ' -> ' . ZIP_CSV_REALFILE, E_USER_ERROR);
421        }
422    }
423
424    /**
425     * CSV の更新日時を取得
426     *
427     * @return string CSV の更新日時 (整形済みテキスト)
428     */
429    function lfGetCsvDatetime() {
430        return date('Y/m/d H:i:s', filemtime(ZIP_CSV_REALFILE));
431    }
432}
Note: See TracBrowser for help on using the repository browser.