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

Revision 22567, 14.3 KB checked in by shutta, 13 years ago (diff)

#2043 (typo修正・ソース整形・ソースコメントの改善 for 2.12.4)
Zend Framework PHP 標準コーディング規約のコーディングスタイルへ準拠。
classおよびfunctionの開始波括弧「{」のスタイルを修正。

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