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

Revision 21689, 13.8 KB checked in by h_yoshimoto, 12 years ago (diff)

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