source: branches/version-2_12-dev/data/class/helper/SC_Helper_Mobile.php @ 21481

Revision 21481, 16.6 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_REALDIR . '../module/Net/URL.php';
26require_once CLASS_REALDIR . 'SC_Query.php';
27
28/**
29 * モバイルのヘルパークラス.
30 *
31 * @package Helper
32 * @author LOCKON CO.,LTD.
33 * @version $Id$
34 */
35class SC_Helper_Mobile {
36
37    /** 基本MimeType */
38    var $defaultMimeType = 'application/force-download';
39
40    /** 拡張MimeType配列
41     * Application/octet-streamで対応出来ないファイルタイプのみ拡張子をキーに記述する
42     * 拡張子が本配列に存在しない場合は application/force-download を利用する */
43    var $arrMimetypes = array(
44            'html'=> 'text/html',
45            'css' => 'text/css',
46            'hdml'=> 'text/x-hdml',
47            'mmf' => 'application/x-smaf',
48            'jpeg'=> 'image/jpeg',
49            'jpg' => 'image/jpeg',
50            'gif' => 'image/gif',
51            'png' => 'image/png',
52            'bmp' => 'image/x-ms-bmp',
53            'amc' => 'application/x-mpeg',
54            '3g2' => 'video/3gpp2',
55            '3gp' => 'video/3gpp',
56            'jam' => 'application/x-jam',
57            'kjx' => 'application/x-kjx',
58            'jar' => 'application/java-archive',
59            'jad' => 'text/vnd.sun.j2me.app-descriptor',
60            'swf' => 'application/x-shockwave-flash',
61            'dmt' => 'application/x-decomail-template',
62            'khm' => 'application/x-kddi-htmlmail',
63            'hmt' => 'application/x-htmlmail-template',
64            'ucm' => 'application/x-ucf-package',
65            'ucp' => 'application/x-ucf-package',
66            'pdf' => 'application/pdf',
67            'wma' => 'audio/x-ms-wma',
68            'asf' => 'video/x-ms-asf',
69            'wax' => 'audio/x-ms-wax',
70            'wvx' => 'video/x-ms-wvx',
71            'wmv' => 'video/x-ms-wmv',
72            'asx' => 'video/asx',
73            'txt' => 'text/plain',
74            'exe' => 'application/octet-stream',
75            'zip' => 'application/zip',
76            'doc' => 'application/msword',
77            'xls' => 'application/vnd.ms-excel',
78            'ppt' => 'application/vnd.ms-powerpoint'
79        );
80
81    /**
82     * EC-CUBE がサポートする携帯端末かどうかをチェックする。
83     * 非対応端末の場合は /unsupported/ へリダイレクトする。
84     *
85     * @return void
86     */
87    function lfMobileCheckCompatibility() {
88        if (!SC_MobileUserAgent_Ex::isSupported()) {
89            header('Location: ' . ROOT_URLPATH . 'unsupported/' . DIR_INDEX_PATH);
90            exit;
91        }
92    }
93
94    /**
95     * 入力データを内部エンコーディングに変換し、絵文字を除去する。
96     *
97     * @param string &$value 入力データへの参照
98     * @return void
99     */
100    function lfMobileConvertInputValue(&$value) {
101        if (is_array($value)) {
102            foreach ($value as $key => $val) {
103                $this->lfMobileConvertInputValue($value[$key]);
104            }
105        } else {
106            // Shift JIS から内部エンコーディングに変換する。
107            $value = mb_convert_encoding($value, CHAR_CODE, 'SJIS');
108            // SoftBank? 以外の絵文字は外字領域に含まれるため、この段階で除去される。
109            // SoftBank? の絵文字を除去する。
110            $value = preg_replace('/\\x1b\\$[^\\x0f]*\\x0f/', '', $value);
111        }
112    }
113
114    /**
115     * モバイルサイト用の入力の初期処理を行う。
116     *
117     * @return void
118     */
119    function lfMobileInitInput() {
120        array_walk($_GET, array($this, 'lfMobileConvertInputValue'));
121        array_walk($_POST, array($this, 'lfMobileConvertInputValue'));
122        array_walk($_REQUEST, array($this, 'lfMobileConvertInputValue'));
123    }
124
125    /**
126     * dtb_mobile_ext_session_id テーブルを検索してセッションIDを取得する。
127     *
128     * @return string|null 取得したセッションIDを返す。
129     *                     取得できなかった場合は null を返す。
130     */
131    function lfMobileGetExtSessionId() {
132        if (!preg_match('|^' . ROOT_URLPATH . '(.*)$|', $_SERVER['SCRIPT_NAME'], $matches)) {
133            return null;
134        }
135
136        $url = $matches[1];
137        $time = date('Y-m-d H:i:s', time() - MOBILE_SESSION_LIFETIME);
138        $objQuery = new SC_Query_Ex();
139
140        foreach ($_REQUEST as $key => $value) {
141            $session_id = $objQuery->get('session_id', 'dtb_mobile_ext_session_id',
142                                         'param_key = ? AND param_value = ? AND url = ? AND create_date >= ?',
143                                         array($key, $value, $url, $time));
144            if (isset($session_id)) {
145                return $session_id;
146            }
147        }
148
149        return null;
150    }
151
152    /**
153     * パラメーターから有効なセッションIDを取得する。
154     *
155     * @return string|false 取得した有効なセッションIDを返す。
156     *                      取得できなかった場合は false を返す。
157     */
158    function lfMobileGetSessionId() {
159        // パラメーターからセッションIDを取得する。
160        $sessionId = @$_POST[session_name()];
161        if (!isset($sessionId)) {
162            $sessionId = @$_GET[session_name()];
163        }
164        if (!isset($sessionId)) {
165            $sessionId = $this->lfMobileGetExtSessionId();
166        }
167        if (!isset($sessionId)) {
168            return false;
169        }
170
171        // セッションIDの存在をチェックする。
172        $objSession = new SC_Helper_Session_Ex();
173        if ($objSession->sfSessRead($sessionId) === null) {
174            GC_Utils_Ex::gfPrintLog("Non-existent session id : sid=$sessionId");
175            return false;
176        }
177        return session_id($sessionId);
178    }
179
180    /**
181     * セッションデータが有効かどうかをチェックする。
182     *
183     * FIXME "@" でエラーを抑制するのは良くない
184     *
185     * @return boolean セッションデータが有効な場合は true、無効な場合は false を返す。
186     */
187    function lfMobileValidateSession() {
188        // 配列 mobile が登録されているかどうかをチェックする。
189        if (!is_array(@$_SESSION['mobile'])) {
190            return false;
191        }
192
193        // 有効期限を過ぎていないかどうかをチェックする。
194        if (intval(@$_SESSION['mobile']['expires']) < time()) {
195            GC_Utils_Ex::gfPrintLog("Session expired at " .
196                       date('Y/m/d H:i:s', @$_SESSION['mobile']['expires']) .
197                       ' : sid=' . session_id());
198
199            return false;
200        }
201
202        // 携帯端末の機種が一致するかどうかをチェックする。
203        $model = SC_MobileUserAgent_Ex::getModel();
204        if (@$_SESSION['mobile']['model'] != $model) {
205            GC_Utils_Ex::gfPrintLog("User agent model mismatch : " .
206                       "\"$model\" != \"" . @$_SESSION['mobile']['model'] .
207                       '" (expected), sid=' . session_id());
208            return false;
209        }
210
211        return true;
212    }
213
214    /**
215     * モバイルサイト用の出力の初期処理を行う。
216     *
217     * 出力の流れ
218     * 1. ページクラスでの出力
219     * 2. 全角カタカナを半角カタカナに変換する。
220     * 3. 内部エンコーディングから Shift JIS に変換する。
221     * 4. 画像を調整する。
222     * 5. 絵文字タグを絵文字コードに変換する。(require.php で設定)
223     *
224     * @return void
225     */
226    function lfMobileInitOutput() {
227        // 出力用のエンコーディングを Shift JIS に固定する。
228        mb_http_output('SJIS-win');
229
230        // 端末に合わせて画像サイズを変換する。
231        ob_start(array('SC_MobileImage_Ex', 'handler'));
232
233        // 内部エンコーディングから Shift JIS に変換する。
234        ob_start('mb_output_handler');
235
236        //download.phpに対してカタカナ変換をするとファイルが壊れてしまうため回避する
237        if ($_SERVER['SCRIPT_FILENAME'] != HTML_REALDIR . "mypage/download.php") {
238            // 全角カタカナを半角カタカナに変換する。
239            ob_start(create_function('$buffer', 'return mb_convert_kana($buffer, "k");'));
240        }
241    }
242
243    /**
244     * モバイルサイト用の初期処理を行う。
245     *
246     * @return void
247     */
248    function sfMobileInit() {
249        $this->lfMobileInitInput();
250
251        if (basename(dirname($_SERVER['SCRIPT_NAME'])) != 'unsupported') {
252            $this->lfMobileCheckCompatibility();
253        }
254
255        $this->lfMobileInitOutput();
256    }
257
258    /**
259     * Location等でセッションIDを付加する必要があるURLにセッションIDを付加する。
260     *
261     * @return String
262     */
263    function gfAddSessionId($url = null) {
264        $objURL = new Net_URL($url);
265        $objURL->addQueryString(session_name(), session_id());
266        return $objURL->getURL();
267    }
268
269    /**
270     * セッション ID を付加した配列を返す.
271     *
272     * @param array $array 元となる配列
273     * @param array セッション ID を追加した配列
274     */
275    function sessionIdArray($array = array()) {
276        return array_merge($array, array(session_name() => session_id()));
277    }
278
279    /**
280     * 空メール用のトークンを生成する。
281     *
282     * @return string 生成したトークンを返す。
283     */
284    function lfGenerateKaraMailToken() {
285        $token_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
286        $token_chars_length = strlen($token_chars);
287        $token_length = 10;
288        $token = '';
289
290        while ($token_length > 0) {
291            $token .= $token_chars{mt_rand(0, $token_chars_length - 1)};
292            --$token_length;
293        }
294
295        return $token;
296    }
297
298    /**
299     * 空メール管理テーブルに新規エントリーを登録し、トークンを返す。
300     *
301     * @param string $next_url 空メール受け付け後に遷移させるページ (モバイルサイトトップからの相対URL)
302     * @param string $session_id セッションID (省略した場合は現在のセッションID)
303     * @return string|false トークンを返す。エラーが発生した場合はfalseを返す。
304     */
305    function gfPrepareKaraMail($next_url, $session_id = null) {
306        if (!isset($session_id)) {
307            $session_id = session_id();
308        }
309
310        $objQuery = new SC_Query_Ex();
311
312        // GC
313        $time = date('Y-m-d H:i:s', time() - MOBILE_SESSION_LIFETIME);
314        $objQuery->delete('dtb_mobile_kara_mail', 'email IS NULL AND create_date < ?', array($time));
315
316        $objQuery->delete('dtb_mobile_kara_mail', 'session_id = ?', array($session_id));
317
318        $arrValues = array('session_id' => $session_id,
319                           'next_url'   => $next_url);
320
321        $try = 10;
322
323        while ($try > 0) {
324            $arrValues['token'] = $token = $this->lfGenerateKaraMailToken();
325
326            $arrValues['kara_mail_id'] = $objQuery->nextVal('dtb_mobile_kara_mail_kara_mail_id');
327            $objQuery->insert('dtb_mobile_kara_mail', $arrValues);
328            $exists = $objQuery->exists('dtb_mobile_kara_mail', 'token = ?', array($token));
329
330            if ($exists) {
331                break;
332            }
333
334            $objQuery->delete('dtb_mobile_kara_mail', 'session_id = ?', array($session_id));
335            $token = false;
336            --$try;
337        }
338
339        return $token;
340    }
341
342    /**
343     * 空メールから取得したメールアドレスを空メール管理テーブルに登録する。
344     *
345     * @param string $token トークン
346     * @param string $email メールアドレス
347     * @return boolean 成功した場合はtrue、失敗した場合はfalseを返す。
348     */
349    function gfRegisterKaraMail($token, $email) {
350        $objQuery = new SC_Query_Ex();
351
352        // GC
353        $time = date('Y-m-d H:i:s', time() - MOBILE_SESSION_LIFETIME);
354        $objQuery->delete('dtb_mobile_kara_mail',
355                          '(email IS NULL AND create_date < ?) OR (email IS NOT NULL AND receive_date < ?)',
356                          array($time, $time));
357
358        $kara_mail_id = $objQuery->get('kara_mail_id', 'dtb_mobile_kara_mail', 'token = ?', array($token));
359        if (!isset($kara_mail_id)) {
360            return false;
361        }
362
363        $arrValues = array('email' => $email);
364        $arrRawValues = array('receive_date' => 'CURRENT_TIMESTAMP');
365        $objQuery->update('dtb_mobile_kara_mail', $arrValues, 'kara_mail_id = ?', array($kara_mail_id), $arrRawValues);
366
367        return true;
368    }
369
370    /**
371     * 空メール管理テーブルからトークンが一致する行を削除し、
372     * 次に遷移させるページのURLを返す。 
373     *
374     * メールアドレスは $_SESSION['mobile']['kara_mail_from'] に登録される。
375     *
376     * @param string $token トークン
377     * @return string|false URLを返す。エラーが発生した場合はfalseを返す。
378     */
379    function gfFinishKaraMail($token) {
380        $objQuery = new SC_Query_Ex();
381
382        $arrRow = $objQuery->getRow(
383             'session_id, next_url, email'
384            ,'dtb_mobile_kara_mail'
385            ,'token = ? AND email IS NOT NULL AND receive_date >= ?'
386            ,array($token, date('Y-m-d H:i:s', time() - MOBILE_SESSION_LIFETIME))
387            ,DB_FETCHMODE_ORDERED
388        );
389
390        if (!isset($arrRow)) {
391            return false;
392        }
393
394        $objQuery->delete('dtb_mobile_kara_mail', 'token = ?', array($token));
395
396        list($session_id, $next_url, $email) = $arrRow;
397        $objURL = new Net_URL(HTTP_URL . $next_url);
398        $objURL->addQueryString(session_name(), $session_id);
399        $url = $objURL->getURL();
400
401        session_id($session_id);
402        session_start();
403        $_SESSION['mobile']['kara_mail_from'] = $email;
404        session_write_close();
405
406        return $url;
407    }
408
409    /**
410     * 外部サイト連携用にセッションIDとパラメーターの組み合わせを保存する。
411     *
412     * @param string $param_key パラメーター名
413     * @param string $param_value パラメーター値
414     * @param string $url URL
415     * @return void
416     */
417    function sfMobileSetExtSessionId($param_key, $param_value, $url) {
418        $objQuery = new SC_Query_Ex();
419
420        // GC
421        $time = date('Y-m-d H:i:s', time() - MOBILE_SESSION_LIFETIME);
422        $objQuery->delete('dtb_mobile_ext_session_id', 'create_date < ?', array($time));
423
424        $arrValues = array('session_id'  => session_id(),
425                           'param_key'   => $param_key,
426                           'param_value' => $param_value,
427                           'url'         => $url);
428
429        $objQuery->insert('dtb_mobile_ext_session_id', $arrValues);
430    }
431
432    /**
433     * メールアドレスが携帯のものかどうかを判別する。
434     *
435     * @param string $address メールアドレス
436     * @return boolean 携帯のメールアドレスの場合はtrue、それ以外の場合はfalseを返す。
437     */
438    function gfIsMobileMailAddress($address) {
439        $masterData = new SC_DB_MasterData_Ex();
440        $arrMobileMailDomains = $masterData->getMasterData('mtb_mobile_domain');
441
442        foreach ($arrMobileMailDomains as $domain) {
443            $domain = preg_quote($domain, '/');
444            if (preg_match("/@([^@]+\\.)?$domain\$/", $address)) {
445                return true;
446            }
447        }
448
449        return false;
450    }
451
452    /**
453     * ファイルのMIMEタイプを判別する
454     *
455     * @param string $filename ファイル名
456     * @return string MIMEタイプ
457     */
458    function getMimeType($filename) {
459        //ファイルの拡張子からコンテンツタイプを決定する
460        $file_extension = strtolower(substr(strrchr($filename,"."),1));
461        $mime_type = $this->defaultMimeType;
462        if (array_key_exists($file_extension, $this->arrMimetypes)) {
463            $mime_type = $this->arrMimetypes[$file_extension];
464        }
465        return $mime_type;
466    }
467}
Note: See TracBrowser for help on using the repository browser.