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

Revision 21420, 14.0 KB checked in by Seasoft, 12 years ago (diff)

#1613 (ソース整形・ソースコメントの改善)

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