source: branches/version-2_12-dev/data/class/SC_Response.php @ 21745

Revision 21745, 14.3 KB checked in by AMUAMU, 12 years ago (diff)

r21743 の修正により一部の画面でreload処理が正常に動かない場合がある問題の修正

  • 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/**
25 * HttpResponse を扱うクラス.
26 *
27 * @author Ryuichi Tokugami
28 * @version $Id$
29 */
30class SC_Response{
31
32    /**
33     * コンテンツタイプ
34     * Enter description here ...
35     * @var unknown_type
36     */
37    var $contentType;
38    var $body;
39    var $statusCode;
40    var $header = array();
41
42    /**
43     *
44     * Enter description here ...
45     */
46    var $encoding;
47
48    function SC_Response() {
49    }
50
51    /**
52     * レスポンス出力を書き込む.
53     */
54    function write() {
55        $this->sendHeader();
56        echo $this->body;
57    }
58
59    function sendHeader() {
60        // HTTPのヘッダ
61        foreach ($this->header as $name => $head) {
62            header($name.': '.$head);
63        }
64        if (strlen($this->statusCode) >= 1) {
65            $this->sendHttpStatus($this->statusCode);
66        }
67    }
68
69    function setContentType($contentType) {
70        $this->header['Content-Type'] = $contentType;
71    }
72
73    function setResposeBody($body) {
74        $this->body = $body;
75    }
76
77    function addHeader($name, $value) {
78        $this->header[$name] = $value;
79    }
80
81    function containsHeader($name) {
82        return isset($this->header[$name]);
83    }
84
85    /**
86     * アプリケーションのexit処理をする。以降の出力は基本的に停止する。
87     * 各クラス内部で勝手にexitするな!
88    */
89    function actionExit() {
90        // ローカルフックポイント処理
91        $objPlugin = SC_Helper_Plugin_Ex::getSingletonInstance($this->plugin_activate_flg);
92        $arrBacktrace = debug_backtrace();
93        if (is_object($arrBacktrace[0]['object'])) {
94            $parent_class_name = get_parent_class($arrBacktrace[0]['object']);
95            $objPlugin->doAction($parent_class_name . '_action_' . $arrBacktrace[0]['object']->getMode(), array($arrBacktrace[0]['object']));
96            $class_name = get_class($arrBacktrace[0]['object']);
97            if ($class_name != $parent_class_name) {
98                $objPlugin->doAction($class_name . '_action_' . $arrBacktrace[0]['object']->getMode(), array($arrBacktrace[0]['object']));
99            }
100        }
101
102        exit;
103        // exitしてますが、実際は、LC_Page::destroy() が呼ばれるはず
104    }
105
106    /**
107     * アプリケーション内でリダイレクトする
108     *
109     * 内部で生成する URL の searchpart は、下記の順で上書きしていく。(後勝ち)
110     * 1. 引数 $inheritQueryString が true の場合、$_SERVER['QUERY_STRING']
111     * 2. $location に含まれる searchpart
112     * 3. 引数 $arrQueryString
113     * @param string $location 「url-path」「現在のURLからのパス」「URL」のいずれか。「../」の解釈は行なわない。
114     * @param array $arrQueryString URL に付加する searchpart
115     * @param bool $inheritQueryString 現在のリクエストの searchpart を継承するか
116     * @param bool|null $useSsl true:HTTPSを強制, false:HTTPを強制, null:継承
117     * @return void
118     * @static
119     */
120    function sendRedirect($location, $arrQueryString = array(), $inheritQueryString = false, $useSsl = null) {
121
122        // ローカルフックポイント処理
123        $objPlugin = SC_Helper_Plugin_Ex::getSingletonInstance($this->plugin_activate_flg);
124
125        $arrBacktrace = debug_backtrace();
126        if (is_object($arrBacktrace[0]['object']) && method_exists($arrBacktrace[0]['object'], 'getMode')) {
127            $parent_class_name = get_parent_class($arrBacktrace[0]['object']);
128            $objPlugin->doAction($parent_class_name . '_action_' . $arrBacktrace[0]['object']->getMode(), array($arrBacktrace[0]['object']));
129            $class_name = get_class($arrBacktrace[0]['object']);
130            if ($class_name != $parent_class_name) {
131                $objPlugin->doAction($class_name . '_action_' . $arrBacktrace[0]['object']->getMode(), array($this));
132            }
133        } elseif (is_object($arrBacktrace[0]['object'])) {
134            $pattern = '/^[a-zA-Z0-9_]+$/';
135            $mode = null;
136            if (isset($_GET['mode']) && preg_match($pattern, $_GET['mode'])) {
137                $mode =  $_GET['mode'];
138            } elseif (isset($_POST['mode']) && preg_match($pattern, $_POST['mode'])) {
139                $mode = $_POST['mode'];
140            }
141            $parent_class_name = get_parent_class($arrBacktrace[0]['object']);
142            $objPlugin->doAction($parent_class_name . '_action_' . $mode, array($arrBacktrace[0]['object']));
143            $class_name = get_class($arrBacktrace[0]['object']);
144            if ($class_name != $parent_class_name) {
145                $objPlugin->doAction($class_name . '_action_' . $mode, array($this));
146            }
147
148        }
149
150        // url-path → URL 変換
151        if ($location[0] === '/') {
152            $netUrl = new Net_URL($location);
153            $location = $netUrl->getUrl();
154        }
155
156        // URL の場合
157        if (preg_match('/^https?:/', $location)) {
158            $url = $location;
159            if (is_bool($useSsl)) {
160                if ($useSsl) {
161                    $pattern = '/^' . preg_quote(HTTP_URL, '/') . '(.*)/';
162                    $replacement = HTTPS_URL . '\1';
163                    $url = preg_replace($pattern, $replacement, $url);
164                } else {
165                    $pattern = '/^' . preg_quote(HTTPS_URL, '/') . '(.*)/';
166                    $replacement = HTTP_URL . '\1';
167                    $url = preg_replace($pattern, $replacement, $url);
168                }
169            }
170        }
171        // 現在のURLからのパス
172        else {
173            if (!is_bool($useSsl)) {
174                $useSsl = SC_Utils_Ex::sfIsHTTPS();
175            }
176            $netUrl = new Net_URL($useSsl ? HTTPS_URL : HTTP_URL);
177            $netUrl->path = dirname($_SERVER['SCRIPT_NAME']) . '/' . $location;
178            $url = $netUrl->getUrl();
179        }
180
181        $pattern = '/^(' . preg_quote(HTTP_URL, '/') . '|' . preg_quote(HTTPS_URL, '/') . ')/';
182
183        // アプリケーション外へのリダイレクトは扱わない
184        if (preg_match($pattern, $url) === 0) {
185            trigger_error('', E_USER_ERROR);
186        }
187
188        $netUrl = new Net_URL($url);
189
190        if ($inheritQueryString && !empty($_SERVER['QUERY_STRING'])) {
191            $arrQueryStringBackup = $netUrl->querystring;
192            // XXX メソッド名は add で始まるが、実際には置換を行う
193            $netUrl->addRawQueryString($_SERVER['QUERY_STRING']);
194            $netUrl->querystring = array_merge($netUrl->querystring, $arrQueryStringBackup);
195        }
196
197        $netUrl->querystring = array_merge($netUrl->querystring, $arrQueryString);
198
199        $session = SC_SessionFactory::getInstance();
200        if ((SC_Display_Ex::detectDevice() == DEVICE_TYPE_MOBILE)
201            || ($session->useCookie() == false)
202        ) {
203            $netUrl->addQueryString(session_name(), session_id());
204        }
205
206        $netUrl->addQueryString(TRANSACTION_ID_NAME, SC_Helper_Session_Ex::getToken());
207        $url = $netUrl->getURL();
208
209        header("Location: $url");
210        exit;
211    }
212
213    /**
214     * /html/ からのパスを指定してリダイレクトする
215     *
216     * FIXME メソッド名を分かりやすくしたい。現状だと、引数が「url-path より後」とも「url-path」とも読み取れる。(前者が意図したいところ)
217     * @param string $location /html/ からのパス。先頭に / を含むかは任意。「../」の解釈は行なわない。
218     * @return void
219     * @static
220     */
221    function sendRedirectFromUrlPath($location, $arrQueryString = array(), $inheritQueryString = false, $useSsl = null) {
222        $location = ROOT_URLPATH . ltrim($location, '/');
223        SC_Response_Ex::sendRedirect($location, $arrQueryString, $inheritQueryString, $useSsl);
224    }
225
226    /**
227     * @static
228     */
229    function reload($arrQueryString = array(), $removeQueryString = false) {
230        // 現在の URL を取得
231        $netUrl = new Net_URL($_SERVER['REQUEST_URI']);
232
233        if (!$removeQueryString) {
234            $arrQueryString = array_merge($netUrl->querystring, $arrQueryString);
235        }
236        $netUrl->querystring = array();
237
238        SC_Response_Ex::sendRedirect($netUrl->getURL(), $arrQueryString);
239    }
240
241    function setHeader($headers) {
242        $this->header = $headers;
243    }
244
245    function setStatusCode($statusCode = null) {
246        $this->statusCode = $statusCode;
247    }
248
249    /**
250     * HTTPステータスコードを送出する。
251     *
252     * @param integer $statusCode HTTPステータスコード
253     * @return void
254     * @author Seasoft (新規作成)
255     * @see Moony_Action::status() (オリジナル)
256     * @link http://moony.googlecode.com/ (オリジナル)
257     * @author YAMAOKA Hiroyuki (オリジナル)
258     * @copyright 2005-2008 YAMAOKA Hiroyuki (オリジナル)
259     * @license http://opensource.org/licenses/bsd-license.php New BSD License (オリジナル)
260     * @link http://ja.wikipedia.org/wiki/HTTP%E3%82%B9%E3%83%86%E3%83%BC%E3%82%BF%E3%82%B9%E3%82%B3%E3%83%BC%E3%83%89 (邦訳)
261     * @license http://www.gnu.org/licenses/fdl.html GFDL (邦訳)
262     * @static
263     */
264    function sendHttpStatus($statusCode) {
265        $protocol = $_SERVER['SERVER_PROTOCOL'];
266        $httpVersion = (strpos($protocol, '1.1') !== false) ? '1.1' : '1.0';
267        $messages = array(
268            // Informational 1xx                        // 【情報】
269            100 => 'Continue',                          // 継続
270            101 => 'Switching Protocols',               // プロトコル切替え
271            // Success 2xx                              // 【成功】
272            200 => 'OK',                                // OK
273            201 => 'Created',                           // 作成
274            202 => 'Accepted',                          // 受理
275            203 => 'Non-Authoritative Information',     // 信頼できない情報
276            204 => 'No Content',                        // 内容なし
277            205 => 'Reset Content',                     // 内容のリセット
278            206 => 'Partial Content',                   // 部分的内容
279            // Redirection 3xx                          // 【リダイレクション】
280            300 => 'Multiple Choices',                  // 複数の選択
281            301 => 'Moved Permanently',                 // 恒久的に移動した
282            302 => 'Found',  // 1.1                     // 発見した (リクエストしたリソースは一時的に移動されているときに返される)
283            303 => 'See Other',                         // 他を参照せよ
284            304 => 'Not Modified',                      // 未更新
285            305 => 'Use Proxy',                         // プロキシを使用せよ
286            // 306 is no longer used but still reserved // 将来のために予約されている
287            307 => 'Temporary Redirect',                // 一時的リダイレクト
288            // Client Error 4xx                         // 【クライアントエラー】
289            400 => 'Bad Request',                       // リクエストが不正である
290            401 => 'Unauthorized',                      // 認証が必要である
291            402 => 'Payment Required',                  // 支払いが必要である
292            403 => 'Forbidden',                         // 禁止されている
293            404 => 'Not Found',                         // 未検出
294            405 => 'Method Not Allowed',                // 許可されていないメソッド
295            406 => 'Not Acceptable',                    // 受理できない
296            407 => 'Proxy Authentication Required',     // プロキシ認証が必要である
297            408 => 'Request Timeout',                   // リクエストタイムアウト
298            409 => 'Conflict',                          // 矛盾
299            410 => 'Gone',                              // 消滅した
300            411 => 'Length Required',                   // 長さが必要
301            412 => 'Precondition Failed',               // 前提条件で失敗した
302            413 => 'Request Entity Too Large',          // リクエストエンティティが大きすぎる
303            414 => 'Request-URI Too Long',              // リクエストURIが大きすぎる
304            415 => 'Unsupported Media Type',            // サポートしていないメディアタイプ
305            416 => 'Requested Range Not Satisfiable',   // リクエストしたレンジは範囲外にある
306            417 => 'Expectation Failed',                // 期待するヘッダに失敗
307            // Server Error 5xx                         // 【サーバーエラー】
308            500 => 'Internal Server Error',             // サーバー内部エラー
309            501 => 'Not Implemented',                   // 実装されていない
310            502 => 'Bad Gateway',                       // 不正なゲートウェイ
311            503 => 'Service Unavailable',               // サービス利用不可
312            504 => 'Gateway Timeout',                   // ゲートウェイタイムアウト
313            505 => 'HTTP Version Not Supported',        // サポートしていないHTTPバージョン
314            509 => 'Bandwidth Limit Exceeded'           // 帯域幅制限超過
315        );
316        if (isset($messages[$statusCode])) {
317            if ($httpVersion !== '1.1') {
318                // HTTP/1.0
319                $messages[302] = 'Moved Temporarily';
320            }
321            header("HTTP/{$httpVersion} {$statusCode} {$messages[$statusCode]}");
322            header("Status: {$statusCode} {$messages[$statusCode]}", true, $statusCode);
323        }
324    }
325}
Note: See TracBrowser for help on using the repository browser.