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

Revision 21867, 13.5 KB checked in by nakanishi, 12 years ago (diff)

#1831 Copyright Update

  • 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/** 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['zip_id'] = $cntInsert;
246                $sqlval['zipcode'] = $arrCSV[2];
247                $sqlval['state'] = $arrCSV[6];
248                $sqlval['city'] = $arrCSV[7];
249                $sqlval['town'] = $arrCSV[8];
250                $objQuery->insert('mtb_zip', $sqlval);
251                $cntInsert++;
252            }
253
254            // $disp_line件ごとに進捗表示する
255            if ($cntCurrentLine % $disp_line == 0 && $img_cnt < IMAGE_MAX) {
256                echo '<img src="' . $img_path . 'graph_1_w.gif">';
257                SC_Utils_Ex::sfFlush();
258                $img_cnt++;
259            }
260            SC_Utils_Ex::extendTimeOut();
261        }
262        fclose($fp);
263
264        echo '<img src="' . $img_path . 'space_w.gif">';
265
266        ?>
267        </div>
268        <script type='text/javascript' language='javascript'>
269            <!--
270                // 完了画面
271                function complete() {
272                    document.open('text/html','replace');
273                    document.clear();
274                    document.write('<p>完了しました。<br />');
275                    document.write("<?php echo $cntInsert ?> 件を追加しました。</p>");
276                    document.write("<p><a href='?' target='_top'>戻る</a></p>");
277                    document.close();
278                }
279                // コンテンツを削除するため、タイムアウトで呼び出し。
280                setTimeout('complete()', 0);
281            // -->
282        </script>
283        </body>
284        </html>
285        <?php
286    }
287
288    function openZipCsv() {
289        $this->convertZipCsv();
290        $fp = fopen(ZIP_CSV_UTF8_REALFILE, 'r');
291        if (!$fp) {
292            trigger_error(ZIP_CSV_UTF8_REALFILE . ' の読み込みに失敗しました。', E_USER_ERROR);
293        }
294        return $fp;
295    }
296
297    function convertZipCsv() {
298        if (file_exists(ZIP_CSV_UTF8_REALFILE)) return;
299
300        $fpr = fopen(ZIP_CSV_REALFILE, 'r');
301        if (!$fpr) {
302            trigger_error(ZIP_CSV_REALFILE . ' の読み込みに失敗しました。', E_USER_ERROR);
303        }
304
305        $fpw = fopen(ZIP_CSV_UTF8_REALFILE, 'w');
306        if (!$fpw) {
307            trigger_error(ZIP_CSV_UTF8_REALFILE . ' を開けません。', E_USER_ERROR);
308        }
309
310        while (!feof($fpr)) {
311            fwrite($fpw, mb_convert_encoding(fgets($fpr, ZIP_CSV_LINE_MAX), CHAR_CODE, 'sjis-win'));
312        }
313
314        fclose($fpw);
315        fclose($fpr);
316    }
317
318    function countMtbZip() {
319        $objQuery =& SC_Query_Ex::getSingletonInstance();
320        return $objQuery->count('mtb_zip');
321    }
322
323    function countZipCsv() {
324        $line = 0;
325        $fp = $this->openZipCsv();
326
327        // CSVの行数を数える
328        while (!feof($fp)) {
329            /*
330            // 正確にカウントする
331            $tmp = fgetcsv($fp, ZIP_CSV_LINE_MAX);
332            */
333            // 推測でカウントする
334            $tmp = fgets($fp, ZIP_CSV_LINE_MAX);
335            if (empty($tmp)) continue;
336            $line++;
337        }
338        fclose($fp);
339
340        return $line;
341    }
342
343    /**
344     * 日本郵便から郵便番号 CSV の ZIP アーカイブファイルを取得
345     *
346     * @return void
347     */
348    function lfDownloadZipFileFromJp() {
349        // Proxy経由を可能とする。
350        // TODO Proxyの設定は「data/module/HTTP/Request.php」内の「function HTTP_Request」へ記述する。いずれは、外部設定としたい。
351        $req = new HTTP_Request();
352
353        $req->setURL(ZIP_DOWNLOAD_URL);
354
355        // 郵便番号CSVをdownloadする。
356        $res = $req->sendRequest();
357        if (!$res) {
358            trigger_error(ZIP_DOWNLOAD_URL . ' の取得に失敗しました。', E_USER_ERROR);
359        }
360
361        // 郵便番号CSV(zip file)を保存する。
362        $fp = fopen($this->zip_csv_temp_realfile, 'w');
363        if (!$fp) {
364            trigger_error($this->zip_csv_temp_realfile . ' を開けません。', E_USER_ERROR);
365        }
366        $res = fwrite($fp, $req->getResponseBody());
367        if (!$res) {
368            trigger_error($this->zip_csv_temp_realfile . ' への書き込みに失敗しました。', E_USER_ERROR);
369        }
370    }
371
372    /**
373     * ZIP アーカイブファイルを展開して、郵便番号 CSV を上書き
374     *
375     * @return void
376     */
377    function lfExtractZipFile() {
378        $zip = zip_open($this->zip_csv_temp_realfile);
379        if (!is_resource($zip)) {
380            trigger_error($this->zip_csv_temp_realfile . ' をオープンできません。', E_USER_ERROR);
381        }
382
383        do {
384            $entry = zip_read($zip);
385        } while ($entry && zip_entry_name($entry) != 'KEN_ALL.CSV');
386
387        if (!$entry) {
388            trigger_error($this->zip_csv_temp_realfile . ' に対象ファイルが見つかりません。', E_USER_ERROR);
389        }
390
391        // 展開時の破損を考慮し、別名で一旦展開する。
392        $tmp_csv_realfile = ZIP_CSV_REALFILE . '.tmp';
393
394        $res = zip_entry_open($zip, $entry, 'rb');
395        if (!$res) {
396            trigger_error($this->zip_csv_temp_realfile . ' の展開に失敗しました。', E_USER_ERROR);
397        }
398
399        $fp = fopen($tmp_csv_realfile, 'w');
400        if (!$fp) {
401            trigger_error($tmp_csv_realfile . ' を開けません。', E_USER_ERROR);
402        }
403
404        $res = fwrite($fp, zip_entry_read($entry, zip_entry_filesize($entry)));
405        if ($res === FALSE) {
406            trigger_error($tmp_csv_realfile . ' の書き込みに失敗しました。', E_USER_ERROR);
407        }
408
409        fclose($fp);
410        zip_close($zip);
411
412        // CSV 削除
413        $res = unlink(ZIP_CSV_REALFILE);
414        if (!$res) {
415            trigger_error(ZIP_CSV_REALFILE . ' を削除できません。', E_USER_ERROR);
416        }
417
418        // CSV ファイル名変更
419        $res = rename($tmp_csv_realfile, ZIP_CSV_REALFILE);
420        if (!$res) {
421            trigger_error('ファイル名を変更できません。: ' . $tmp_csv_realfile . ' -> ' . ZIP_CSV_REALFILE, E_USER_ERROR);
422        }
423    }
424
425    /**
426     * CSV の更新日時を取得
427     *
428     * @return string CSV の更新日時 (整形済みテキスト)
429     */
430    function lfGetCsvDatetime() {
431        return date('Y/m/d H:i:s', filemtime(ZIP_CSV_REALFILE));
432    }
433}
Note: See TracBrowser for help on using the repository browser.