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

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