source: branches/version-2_5-dev/data/class/helper/SC_Helper_Mobile.php @ 20562

Revision 20562, 16.6 KB checked in by Seasoft, 13 years ago (diff)

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

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