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

Revision 20961, 14.6 KB checked in by Seasoft, 13 years ago (diff)

#144 (郵便番号DB のアップデート)

  • 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';
26require_once DATA_REALDIR . 'module/Request.php';
27
28/** CSV ファイルの最大行数 */
29define("ZIP_CSV_LINE_MAX", 8192);
30
31/** 画像の表示数量 */
32define("IMAGE_MAX", 680);
33
34/** 郵便番号CSV ファイルのパス */
35define("ZIP_CSV_REALFILE", DATA_REALDIR . "downloads/KEN_ALL.CSV");
36
37/** UTF-8 変換済みの郵便番号CSV ファイルのパス */
38define("ZIP_CSV_UTF8_REALFILE", DATA_REALDIR . "downloads/KEN_ALL_utf-8.CSV");
39
40/**
41 * 郵便番号DB登録 のページクラス.
42 *
43 * @package Page
44 * @author LOCKON CO.,LTD.
45 * @version $Id:LC_Page_Admin_Basis_ZipInstall.php 16741 2007-11-08 00:43:24Z adachi $
46 */
47class LC_Page_Admin_Basis_ZipInstall extends LC_Page_Admin_Ex {
48
49    /** CSVの行数 */
50    var $tpl_line = 0;
51    var $tpl_mode;
52    var $exec;
53    var $tpl_count_mtb_zip;
54
55    /** CSV の更新日時 */
56    var $tpl_csv_datetime;
57
58    /** 日本郵便から取得した ZIP アーカイブファイルの保管パス */
59    var $zip_csv_temp_realfile;
60
61    // }}}
62    // {{{ functions
63
64    /**
65     * Page を初期化する.
66     *
67     * @return void
68     */
69    function init() {
70        parent::init();
71        $this->tpl_mainpage = 'basis/zip_install.tpl';
72        $this->tpl_subno = 'zip_install';
73        $this->tpl_maintitle = '基本情報管理';
74        $this->tpl_subtitle = '郵便番号DB登録';
75        $this->tpl_mainno = 'basis';
76
77        $this->tpl_mode = $this->getMode();
78        $this->exec = (boolean)$_GET['exec'];
79        $this->zip_csv_temp_realfile = DATA_REALDIR . 'downloads/tmp/ken_all.zip';
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        // パラメータ管理クラス
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                SC_Utils_Ex::sfDispException();
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            exit;
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     * @return void
156     */
157    function destroy() {
158        parent::destroy();
159    }
160
161    function lfAutoCommitZip() {
162        $objQuery =& SC_Query_Ex::getSingletonInstance();
163
164        if (!$this->tpl_skip_update_csv) {
165            $this->lfDownloadZipFileFromJp();
166            $this->lfExtractZipFile();
167        }
168
169        $objQuery->begin();
170        $this->lfDeleteZip();
171        $this->insertMtbZip();
172        $objQuery->commit();
173    }
174
175    /**
176     * テーブルデータと UTF-8 変換済みの郵便番号 CSV を削除
177     *
178     * @return void
179     */
180    function lfDeleteZip() {
181        $objQuery =& SC_Query_Ex::getSingletonInstance();
182
183        // DB
184        $objQuery->delete('mtb_zip');
185
186        // UTF-8 変換済みの郵便番号 CSV
187        unlink(ZIP_CSV_UTF8_REALFILE);
188    }
189
190    /**
191     * パラメータ情報の初期化
192     *
193     * @return void
194     */
195    function lfInitParam($tpl_mode, &$objFormParam) {
196        if ($tpl_mode == 'manual') {
197            $objFormParam->addParam("開始行", 'startRowNum', INT_LEN, 'n', array("EXIST_CHECK", "MAX_LENGTH_CHECK", "NUM_CHECK"));
198        }
199    }
200
201    /**
202     * DB登録
203     *
204     * @return void
205     */
206    function insertMtbZip($start = 1) {
207        $objQuery =& SC_Query_Ex::getSingletonInstance();
208
209        $img_path = USER_URL . USER_PACKAGE_DIR . "admin/img/basis/"; // 画像パスは admin 固定
210
211        ?>
212        <html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
213        <head>
214            <meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHAR_CODE ?>" />
215        </head>
216        <body>
217        <p>DB 登録進捗状況</p>
218        <div style="background-color: #494E5F;">
219        <?php
220        // 一部のIEは256バイト以上受け取ってから表示を開始する。
221        SC_Utils_Ex::sfFlush(true);
222
223        echo '<img src="' . $img_path . 'zip_install_progress.gif"><br />';
224        echo '<img src="' . $img_path . 'space_w.gif">';
225        SC_Utils_Ex::sfFlush();
226
227        // 画像を一個表示する件数を求める。
228        $line_all = $this->countZipCsv();
229        $disp_line = intval($line_all / IMAGE_MAX);
230
231        /** 現在行(CSV形式。空行は除く。) */
232        $cntCurrentLine = 0;
233        /** 挿入した行数 */
234        $cntInsert = 0;
235        $img_cnt = 0;
236        $safe_mode = (boolean)ini_get('safe_mode');
237        $max_execution_time
238            = is_numeric(ini_get('max_execution_time'))
239            ? intval(ini_get('max_execution_time'))
240            : intval(get_cfg_var('max_execution_time'))
241        ;
242
243        $fp = $this->openZipCsv();
244        while (!feof($fp)) {
245            $arrCSV = fgetcsv($fp, ZIP_CSV_LINE_MAX);
246            if (empty($arrCSV)) continue;
247            $cntCurrentLine++;
248            if ($cntCurrentLine >= $start) {
249                $sqlval = array();
250                // $sqlval['code'] = $arrCSV[0];
251                // $sqlval['old_zipcode'] = $arrCSV[1];
252                $sqlval['zipcode'] = $arrCSV[2];
253                // $sqlval['state_kana'] = $arrCSV[3];
254                // $sqlval['city_kana'] = $arrCSV[4];
255                // $sqlval['town_kana'] = $arrCSV[5];
256                $sqlval['state'] = $arrCSV[6];
257                $sqlval['city'] = $arrCSV[7];
258                $sqlval['town'] = $arrCSV[8];
259                // $sqlval['flg1'] = $arrCSV[9];
260                // $sqlval['flg2'] = $arrCSV[10];
261                // $sqlval['flg3'] = $arrCSV[11];
262                // $sqlval['flg4'] = $arrCSV[12];
263                // $sqlval['flg5'] = $arrCSV[13];
264                // $sqlval['flg6'] = $arrCSV[14];
265                $objQuery->insert("mtb_zip", $sqlval);
266                $cntInsert++;
267            }
268
269            // $disp_line件ごとに進捗表示する
270            if($cntCurrentLine % $disp_line == 0 && $img_cnt < IMAGE_MAX) {
271                echo '<img src="' . $img_path . 'graph_1_w.gif">';
272                SC_Utils_Ex::sfFlush();
273                $img_cnt++;
274            }
275            // 暴走スレッドが残留する確率を軽減したタイムアウト防止のロジック
276            // TODO 動作が安定していれば、SC_Utils 辺りに移動したい。
277            if (!$safe_mode) {
278                // タイムアウトをリセット
279                set_time_limit($max_execution_time);
280            }
281        }
282        fclose($fp);
283
284        echo '<img src="' . $img_path . 'space_w.gif">';
285        echo '</div>' . "\n";
286
287        ?>
288        <script type="text/javascript" language="javascript">
289            <!--
290                // 完了画面
291                function complete() {
292                    document.open("text/html","replace");
293                    document.clear();
294                    document.write("<p>完了しました。<br />");
295                    document.write("<?php echo $cntInsert ?> 件を追加しました。</p>");
296                    document.write("<p><a href='?' target='_top'>戻る</a></p>");
297                    document.close();
298                }
299                // コンテンツを削除するため、タイムアウトで呼び出し。
300                setTimeout("complete()", 0);
301            // -->
302        </script>
303        </body>
304        </html>
305        <?php
306    }
307
308    function openZipCsv() {
309        $this->convertZipCsv();
310        $fp = fopen(ZIP_CSV_UTF8_REALFILE, 'r');
311        if (!$fp) {
312            SC_Utils_Ex::sfDispException(ZIP_CSV_UTF8_REALFILE . ' の読み込みに失敗しました。');
313        }
314        return $fp;
315    }
316
317    function convertZipCsv() {
318        if (file_exists(ZIP_CSV_UTF8_REALFILE)) return;
319
320        $fpr = fopen(ZIP_CSV_REALFILE, 'r');
321        if (!$fpr) {
322            SC_Utils_Ex::sfDispException(ZIP_CSV_REALFILE . ' の読み込みに失敗しました。');
323        }
324
325        $fpw = fopen(ZIP_CSV_UTF8_REALFILE, 'w');
326        if (!$fpw) {
327            SC_Utils_Ex::sfDispException(ZIP_CSV_UTF8_REALFILE . ' を開けません。');
328        }
329
330        while (!feof($fpr)) {
331            fwrite($fpw, mb_convert_encoding(fgets($fpr, ZIP_CSV_LINE_MAX), CHAR_CODE, 'sjis-win'));
332        }
333
334        fclose($fpw);
335        fclose($fpr);
336    }
337
338    function countMtbZip() {
339        $objQuery =& SC_Query_Ex::getSingletonInstance();
340        return $objQuery->count('mtb_zip');
341    }
342
343    function countZipCsv() {
344        $line = 0;
345        $fp = $this->openZipCsv();
346
347        // CSVの行数を数える
348        while (!feof($fp)) {
349            /*
350            // 正確にカウントする
351            $tmp = fgetcsv($fp, ZIP_CSV_LINE_MAX);
352            */
353            // 推測でカウントする
354            $tmp = fgets($fp, ZIP_CSV_LINE_MAX);
355            if (empty($tmp)) continue;
356            $line++;
357        }
358        fclose($fp);
359
360        return $line;
361    }
362
363    /**
364     * 日本郵便から郵便番号 CSV の ZIP アーカイブファイルを取得
365     *
366     * @return void
367     */
368   function lfDownloadZipFileFromJp() {
369        // Proxy経由を可能とする。
370        // TODO Proxyの設定は「DATA_REALDIR . 'module/Request.php'」内の「function HTTP_Request」へ記述する。いずれは、外部設定としたい。
371        $req = new HTTP_Request();
372
373        $req->setURL(ZIP_DOWNLOAD_URL);
374
375        // 郵便番号CSVをdownloadする。
376        $res = $req->sendRequest();
377        if (!$res) {
378            SC_Utils_Ex::sfDispException(ZIP_DOWNLOAD_URL . ' の取得に失敗しました。');
379        }
380
381        // 郵便番号CSV(zip file)を保存する。
382        $fp = fopen($this->zip_csv_temp_realfile, 'w');
383        if (!$fp) {
384            SC_Utils_Ex::sfDispException($this->zip_csv_temp_realfile . ' を開けません。');
385        }
386        $res = fwrite($fp, $req->getResponseBody());
387        if (!$res) {
388            SC_Utils_Ex::sfDispException($this->zip_csv_temp_realfile . ' への書き込みに失敗しました。');
389        }
390    }
391
392    /**
393     * ZIP アーカイブファイルを展開して、郵便番号 CSV を上書き
394     *
395     * @return void
396     */
397    function lfExtractZipFile() {
398        $zip = zip_open($this->zip_csv_temp_realfile);
399        if (!is_resource($zip)) {
400            SC_Utils_Ex::sfDispException($this->zip_csv_temp_realfile . ' をオープンできません。');
401        }
402
403        do {
404            $entry = zip_read($zip);
405        } while ($entry && zip_entry_name($entry) != 'KEN_ALL.CSV');
406
407        if (!$entry) {
408            SC_Utils_Ex::sfDispException($this->zip_csv_temp_realfile . ' に対象ファイルが見つかりません。');
409        }
410
411        // 展開時の破損を考慮し、別名で一旦展開する。
412        $tmp_csv_realfile = ZIP_CSV_REALFILE . '.tmp';
413
414        $res = zip_entry_open($zip, $entry, 'rb');
415        if (!$res) {
416            SC_Utils_Ex::sfDispException($this->zip_csv_temp_realfile . ' の展開に失敗しました。');
417        }
418
419        $fp = fopen($tmp_csv_realfile, 'w');
420        if (!$fp) {
421            SC_Utils_Ex::sfDispException($tmp_csv_realfile . ' を開けません。');
422        }
423
424        $res = fwrite($fp, zip_entry_read($entry, zip_entry_filesize($entry)));
425        if ($res === FALSE) {
426            SC_Utils_Ex::sfDispException($tmp_csv_realfile . ' の書き込みに失敗しました。');
427        }
428
429        fclose($fp);
430        zip_close($zip);
431
432        // CSV 削除
433        $res = unlink(ZIP_CSV_REALFILE);
434        if (!$res) {
435            SC_Utils_Ex::sfDispException(ZIP_CSV_REALFILE . ' を削除できません。');
436        }
437
438        // CSV ファイル名変更
439        $res = rename($tmp_csv_realfile, ZIP_CSV_REALFILE);
440        if (!$res) {
441            SC_Utils_Ex::sfDispException('ファイル名を変更できません。: ' . $tmp_csv_realfile . ' -> ' . ZIP_CSV_REALFILE);
442        }
443    }
444
445    /**
446     * CSV の更新日時を取得
447     *
448     * @return string CSV の更新日時 (整形済みテキスト)
449     */
450    function lfGetCsvDatetime() {
451        return date('Y/m/d H:i:s', filemtime(ZIP_CSV_REALFILE));
452    }
453}
454?>
Note: See TracBrowser for help on using the repository browser.