source: branches/version-2_13-dev/data/class/SC_Response.php @ 22811

Revision 22811, 14.5 KB checked in by Seasoft, 11 years ago (diff)

#2241 (プラグイン機構の自殺を阻止)

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