Yii2 Bootstrap 3
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

735 lines
23 KiB

12 years ago
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
12 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\web;
12 years ago
use Yii;
use yii\base\InvalidConfigException;
12 years ago
use yii\base\InvalidParamException;
use yii\helpers\FileHelper;
12 years ago
use yii\helpers\Html;
12 years ago
use yii\helpers\Json;
12 years ago
use yii\helpers\SecurityHelper;
use yii\helpers\StringHelper;
12 years ago
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Carsten Brandt <mail@cebe.cc>
12 years ago
* @since 2.0
*/
class Response extends \yii\base\Response
{
const FORMAT_RAW = 'raw';
const FORMAT_HTML = 'html';
const FORMAT_JSON = 'json';
const FORMAT_JSONP = 'jsonp';
const FORMAT_XML = 'xml';
/**
* @var string the response format.
*/
public $format = self::FORMAT_HTML;
/**
* @var array the formatters for converting data into the response content of the specified [[format]].
* The array keys are the format names, and the array values are the corresponding configurations
* for creating the formatter objects.
*/
public $formatters;
/**
* @var string the charset of the text response. If not set, it will use
* the value of [[Application::charset]].
*/
public $charset;
12 years ago
/**
12 years ago
* @var integer the HTTP status code that should be used when redirecting in AJAX mode.
* This is used by [[redirect()]]. A 2xx code should normally be used for this purpose
* so that the AJAX handler will treat the response as a success.
* @see redirect
*/
public $ajaxRedirectCode = 278;
12 years ago
/**
* @var string
*/
12 years ago
public $statusText;
/**
* @var string the version of the HTTP protocol to use. If not set, it will be determined via `$_SERVER['SERVER_PROTOCOL']`,
* or '1.1' if that is not available.
12 years ago
*/
public $version;
12 years ago
/**
* @var array list of HTTP status codes and the corresponding texts
*/
public static $httpStatuses = array(
12 years ago
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
118 => 'Connection timed out',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
208 => 'Already Reported',
210 => 'Content Different',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Reserved',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',
310 => 'Too many Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested range unsatisfiable',
417 => 'Expectation failed',
418 => 'I\'m a teapot',
12 years ago
422 => 'Unprocessable entity',
423 => 'Locked',
424 => 'Method failure',
425 => 'Unordered Collection',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
449 => 'Retry With',
450 => 'Blocked by Windows Parental Controls',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway ou Proxy Error',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
507 => 'Insufficient storage',
508 => 'Loop Detected',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended',
511 => 'Network Authentication Required',
);
/**
* @var integer the HTTP status code to send with the response.
*/
12 years ago
private $_statusCode;
12 years ago
/**
12 years ago
* @var HeaderCollection
*/
12 years ago
private $_headers;
/**
* Initializes this component.
*/
12 years ago
public function init()
{
if ($this->version === null) {
if (isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL'] === '1.0') {
$this->version = '1.0';
} else {
$this->version = '1.1';
}
12 years ago
}
if ($this->charset === null) {
$this->charset = Yii::$app->charset;
}
12 years ago
}
/**
* @return integer the HTTP status code to send with the response.
*/
12 years ago
public function getStatusCode()
{
return $this->_statusCode;
}
/**
* Sets the response status code.
* This method will set the corresponding status text if `$text` is null.
* @param integer $value the status code
* @param string $text the status text. If not set, it will be set automatically based on the status code.
* @throws InvalidParamException if the status code is invalid.
*/
12 years ago
public function setStatusCode($value, $text = null)
12 years ago
{
$this->_statusCode = (int)$value;
if ($this->getIsInvalid()) {
12 years ago
throw new InvalidParamException("The HTTP status code is invalid: $value");
}
12 years ago
if ($text === null) {
$this->statusText = isset(self::$httpStatuses[$this->_statusCode]) ? self::$httpStatuses[$this->_statusCode] : '';
12 years ago
} else {
$this->statusText = $text;
}
12 years ago
}
12 years ago
/**
* Returns the header collection.
* The header collection contains the currently registered HTTP headers.
* @return HeaderCollection the header collection
*/
public function getHeaders()
{
if ($this->_headers === null) {
$this->_headers = new HeaderCollection;
}
return $this->_headers;
}
12 years ago
/**
* Sends the response to the client.
*/
public function send()
{
parent::send();
12 years ago
$this->sendHeaders();
$this->sendContent();
$this->clear();
12 years ago
}
/**
* Clears the headers, cookies, content, status code of the response.
*/
public function clear()
12 years ago
{
$this->_headers = null;
$this->_cookies = null;
12 years ago
$this->_statusCode = null;
$this->_content = null;
12 years ago
$this->statusText = null;
}
12 years ago
/**
* Sends the response headers to the client
*/
protected function sendHeaders()
{
12 years ago
if (headers_sent()) {
return;
}
12 years ago
$statusCode = $this->getStatusCode();
if ($statusCode !== null) {
header("HTTP/{$this->version} $statusCode {$this->statusText}");
}
12 years ago
if ($this->_headers) {
$headers = $this->getHeaders();
foreach ($headers as $name => $values) {
foreach ($values as $value) {
header("$name: $value", false);
}
}
}
$this->sendCookies();
}
/**
* Sends the cookies to the client.
*/
protected function sendCookies()
{
if ($this->_cookies === null) {
return;
}
$request = Yii::$app->getRequest();
if ($request->enableCookieValidation) {
$validationKey = $request->getCookieValidationKey();
}
foreach ($this->getCookies() as $cookie) {
$value = $cookie->value;
if ($cookie->expire != 1 && isset($validationKey)) {
$value = SecurityHelper::hashData(serialize($value), $validationKey);
12 years ago
}
12 years ago
setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
12 years ago
}
12 years ago
$this->getCookies()->removeAll();
12 years ago
}
/**
* Sends the response content to the client
*/
protected function sendContent()
{
echo $this->getContent();
12 years ago
}
/**
* Sends a file to the browser.
* @param string $filePath the path of the file to be sent.
* @param string $attachmentName the file name shown to the user. If null, it will be determined from `$filePath`.
* @param string $mimeType the MIME type of the content. If null, it will be guessed based on `$filePath`
12 years ago
*/
public function sendFile($filePath, $attachmentName = null, $mimeType = null)
12 years ago
{
if ($mimeType === null && ($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
$mimeType = 'application/octet-stream';
12 years ago
}
if ($attachmentName === null) {
$attachmentName = basename($filePath);
}
$handle = fopen($filePath, 'rb');
$this->sendStreamAsFile($handle, $attachmentName, $mimeType);
}
/**
* Sends the specified content as a file to the browser.
* @param string $content the content to be sent. The existing [[content]] will be discarded.
* @param string $attachmentName the file name shown to the user.
* @param string $mimeType the MIME type of the content.
* @throws HttpException if the requested range is not satisfiable
*/
public function sendContentAsFile($content, $attachmentName, $mimeType = 'application/octet-stream')
{
$headers = $this->getHeaders();
$contentLength = StringHelper::strlen($content);
$range = $this->getHttpRange($contentLength);
if ($range === false) {
$headers->set('Content-Range', "bytes */$contentLength");
throw new HttpException(416, Yii::t('yii', 'Requested range not satisfiable'));
}
$headers->setDefault('Pragma', 'public')
->setDefault('Accept-Ranges', 'bytes')
->setDefault('Expires', '0')
->setDefault('Content-Type', $mimeType)
->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
->setDefault('Content-Transfer-Encoding', 'binary')
->setDefault('Content-Length', StringHelper::strlen($content))
->setDefault('Content-Disposition', "attachment; filename=\"$attachmentName\"");
list($begin, $end) = $range;
if ($begin !=0 || $end != $contentLength - 1) {
$this->setStatusCode(206);
$headers->set('Content-Range', "bytes $begin-$end/$contentLength");
$this->setContent(StringHelper::substr($content, $begin, $end - $begin + 1), self::FORMAT_RAW);
} else {
$this->setStatusCode(200);
$this->setContent($content, self::FORMAT_RAW);
}
$this->send();
12 years ago
}
/**
* Sends the specified stream as a file to the browser.
* @param resource $handle the handle of the stream to be sent.
* @param string $attachmentName the file name shown to the user.
* @param string $mimeType the MIME type of the stream content.
* @throws HttpException if the requested range cannot be satisfied.
*/
public function sendStreamAsFile($handle, $attachmentName, $mimeType = 'application/octet-stream')
{
$headers = $this->getHeaders();
fseek($handle, 0, SEEK_END);
$fileSize = ftell($handle);
$range = $this->getHttpRange($fileSize);
if ($range === false) {
$headers->set('Content-Range', "bytes */$fileSize");
throw new HttpException(416, Yii::t('yii', 'Requested range not satisfiable'));
}
list($begin, $end) = $range;
if ($begin !=0 || $end != $fileSize - 1) {
$this->setStatusCode(206);
$headers->set('Content-Range', "bytes $begin-$end/$fileSize");
} else {
$this->setStatusCode(200);
}
$length = $end - $begin + 1;
$headers->setDefault('Pragma', 'public')
->setDefault('Accept-Ranges', 'bytes')
->setDefault('Expires', '0')
->setDefault('Content-Type', $mimeType)
->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
->setDefault('Content-Transfer-Encoding', 'binary')
->setDefault('Content-Length', $length)
->setDefault('Content-Disposition', "attachment; filename=\"$attachmentName\"");
$this->send();
fseek($handle, $begin);
set_time_limit(0); // Reset time limit for big files
$chunkSize = 8 * 1024 * 1024; // 8MB per chunk
while (!feof($handle) && ($pos = ftell($handle)) <= $end) {
if ($pos + $chunkSize > $end) {
$chunkSize = $end - $pos + 1;
}
echo fread($handle, $chunkSize);
flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
}
fclose($handle);
}
12 years ago
/**
* Determines the HTTP range given in the request.
* @param integer $fileSize the size of the file that will be used to validate the requested HTTP range.
* @return array|boolean the range (begin, end), or false if the range request is invalid.
*/
protected function getHttpRange($fileSize)
{
if (!isset($_SERVER['HTTP_RANGE']) || $_SERVER['HTTP_RANGE'] === '-') {
return array(0, $fileSize - 1);
}
if (!preg_match('/^bytes=(\d*)-(\d*)$/', $_SERVER['HTTP_RANGE'], $matches)) {
return false;
}
if ($matches[1] === '') {
$start = $fileSize - $matches[2];
$end = $fileSize - 1;
} elseif ($matches[2] !== '') {
$start = $matches[1];
$end = $matches[2];
if ($end >= $fileSize) {
$end = $fileSize - 1;
}
} else {
$start = $matches[1];
$end = $fileSize - 1;
}
if ($start < 0 || $start > $end) {
return false;
} else {
return array($start, $end);
}
}
/**
12 years ago
* Sends existing file to a browser as a download using x-sendfile.
*
* X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
* that in turn processes the request, this way eliminating the need to perform tasks like reading the file
* and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
* increase in performance as the web application is allowed to terminate earlier while the webserver is
* handling the request.
*
* The request is sent to the server through a special non-standard HTTP-header.
* When the web server encounters the presence of such header it will discard all output and send the file
* specified by that header using web server internals including all optimizations like caching-headers.
*
* As this header directive is non-standard different directives exists for different web servers applications:
12 years ago
*
* - Apache: [X-Sendfile](http://tn123.org/mod_xsendfile)
* - Lighttpd v1.4: [X-LIGHTTPD-send-file](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
* - Lighttpd v1.5: [X-Sendfile](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
* - Nginx: [X-Accel-Redirect](http://wiki.nginx.org/XSendfile)
* - Cherokee: [X-Sendfile and X-Accel-Redirect](http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile)
*
12 years ago
* So for this method to work the X-SENDFILE option/module should be enabled by the web server and
* a proper xHeader should be sent.
*
12 years ago
* **Note**
*
* This option allows to download files that are not under web folders, and even files that are otherwise protected
* (deny from all) like `.htaccess`.
12 years ago
*
12 years ago
* **Side effects**
*
12 years ago
* If this option is disabled by the web server, when this method is called a download configuration dialog
* will open but the downloaded file will have 0 bytes.
*
12 years ago
* **Known issues**
*
12 years ago
* There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
12 years ago
* an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
* is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header.
*
* **Example**
*
* ~~~
* Yii::app()->request->xSendFile('/home/user/Pictures/picture1.jpg');
* ~~~
12 years ago
*
12 years ago
* @param string $filePath file name with full path
* @param string $mimeType the MIME type of the file. If null, it will be determined based on `$filePath`.
* @param string $attachmentName file name shown to the user. If null, it will be determined from `$filePath`.
* @param string $xHeader the name of the x-sendfile header.
12 years ago
*/
public function xSendFile($filePath, $attachmentName = null, $mimeType = null, $xHeader = 'X-Sendfile')
12 years ago
{
if ($mimeType === null && ($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
$mimeType = 'application/octet-stream';
12 years ago
}
if ($attachmentName === null) {
$attachmentName = basename($filePath);
12 years ago
}
$this->getHeaders()
->setDefault($xHeader, $filePath)
->setDefault('Content-Type', $mimeType)
->setDefault('Content-Disposition', "attachment; filename=\"$attachmentName\"");
12 years ago
$this->send();
12 years ago
}
/**
* Redirects the browser to the specified URL.
12 years ago
* This method will send out a "Location" header to achieve the redirection.
* In AJAX mode, this normally will not work as expected unless there are some
* client-side JavaScript code handling the redirection. To help achieve this goal,
* this method will use [[ajaxRedirectCode]] as the HTTP status code when performing
* redirection in AJAX mode. The following JavaScript code may be used on the client
* side to handle the redirection response:
*
* ~~~
* $(document).ajaxSuccess(function(event, xhr, settings) {
* if (xhr.status == 278) {
* window.location = xhr.getResponseHeader('Location');
* }
* });
* ~~~
*
* @param array|string $url the URL to be redirected to. [[\yii\helpers\Html::url()]]
* will be used to normalize the URL. If the resulting URL is still a relative URL
* (one without host info), the current request host info will be used.
* @param integer $statusCode the HTTP status code. If null, it will use 302
* for normal requests, and [[ajaxRedirectCode]] for AJAX requests.
12 years ago
* See [[http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html]]
* for details about HTTP status code
* @return Response the response object itself
*/
public function redirect($url, $statusCode = null)
{
12 years ago
$url = Html::url($url);
12 years ago
if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) {
$url = Yii::$app->getRequest()->getHostInfo() . $url;
}
if ($statusCode === null) {
$statusCode = Yii::$app->getRequest()->getIsAjax() ? $this->ajaxRedirectCode : 302;
12 years ago
}
12 years ago
$this->getHeaders()->set('Location', $url);
$this->setStatusCode($statusCode);
return $this;
}
/**
* Refreshes the current page.
* The effect of this method call is the same as the user pressing the refresh button of his browser
* (without re-posting data).
* @param string $anchor the anchor that should be appended to the redirection URL.
* Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
* @return Response the response object itself
*/
public function refresh($anchor = '')
{
return $this->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
}
12 years ago
private $_cookies;
/**
* Returns the cookie collection.
* Through the returned cookie collection, you add or remove cookies as follows,
*
* ~~~
* // add a cookie
* $response->cookies->add(new Cookie(array(
* 'name' => $name,
* 'value' => $value,
* ));
*
* // remove a cookie
* $response->cookies->remove('name');
* // alternatively
* unset($response->cookies['name']);
* ~~~
*
* @return CookieCollection the cookie collection.
*/
public function getCookies()
{
12 years ago
if ($this->_cookies === null) {
$this->_cookies = new CookieCollection;
}
return $this->_cookies;
}
12 years ago
/**
* @return boolean whether this response has a valid [[statusCode]].
*/
public function getIsInvalid()
12 years ago
{
return $this->getStatusCode() < 100 || $this->getStatusCode() >= 600;
}
/**
* @return boolean whether this response is informational
*/
public function getIsInformational()
12 years ago
{
return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200;
}
/**
* @return boolean whether this response is successful
12 years ago
*/
public function getIsSuccessful()
12 years ago
{
return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300;
}
/**
* @return boolean whether this response is a redirection
*/
public function getIsRedirection()
12 years ago
{
return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400;
}
/**
* @return boolean whether this response indicates a client error
*/
public function getIsClientError()
12 years ago
{
return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500;
}
/**
* @return boolean whether this response indicates a server error
*/
public function getIsServerError()
12 years ago
{
return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600;
}
/**
* @return boolean whether this response is OK
*/
public function getIsOk()
12 years ago
{
return $this->getStatusCode() == 200;
12 years ago
}
/**
* @return boolean whether this response indicates the current request is forbidden
*/
public function getIsForbidden()
12 years ago
{
return $this->getStatusCode() == 403;
12 years ago
}
/**
* @return boolean whether this response indicates the currently requested resource is not found
*/
public function getIsNotFound()
12 years ago
{
return $this->getStatusCode() == 404;
12 years ago
}
/**
* @return boolean whether this response is empty
*/
public function getIsEmpty()
12 years ago
{
return in_array($this->getStatusCode(), array(201, 204, 304));
}
private $_content;
12 years ago
/**
* @return string the content of this response
*/
public function getContent()
{
return $this->_content;
}
12 years ago
/**
* Sets the content of this response.
* The existing content will be overwritten.
* Depending on the value of [[format]], the data will be properly formatted.
* @param mixed $data the data that needs to be converted into the response content.
* @param string $format the format of the response. The [[formatters]] property specifies
* the supported formats and the corresponding formatters. Additionally, the following formats are
* supported if they are not found in [[formatters]]:
12 years ago
*
* - [[FORMAT_RAW]]: the data will be treated as the response content without any conversion.
* No extra HTTP header will be added.
* - [[FORMAT_HTML]]: the data will be treated as the response content without any conversion.
* The "Content-Type" header will set as "text/html" if it is not set previously.
* - [[FORMAT_JSON]]: the data will be converted into JSON format, and the "Content-Type"
* header will be set as "application/json".
* - [[FORMAT_JSONP]]: the data will be converted into JSONP format, and the "Content-Type"
* header will be set as "text/javascript". Note that in this case `$data` must be an array
* with "data" and "callback" elements. The former refers to the actual data to be sent,
* while the latter refers to the name of the JavaScript callback.
* - [[FORMAT_XML]]: the data will be converted into XML format. Please refer to [[XmlResponseFormatter]]
* for more details.
12 years ago
*/
public function setContent($data, $format = null)
{
if ($format !== null) {
$this->format = $format;
}
12 years ago
$this->_content = $this->formatContent($data, $format);
}
/**
* Formats the given data as the specified format.
* @param mixed $data the data to be formatted.
* @param string $format the format to use.
* @return string the formatting result.
* @throws InvalidParamException if `$format` is not supported
* @throws InvalidConfigException if the formatter for the specified format is invalid
*/
protected function formatContent($data, $format)
{
if (isset($this->formatters[$format])) {
$formatter = $this->formatters[$format];
if (!is_object($formatter)) {
$formatter = Yii::createObject($formatter);
}
if ($formatter instanceof ResponseFormatter) {
return $formatter->format($this, $data);
} else {
throw new InvalidConfigException("The '$format' response formatter is invalid. It must implement the ResponseFormatter interface.");
}
}
switch ($this->format) {
case self::FORMAT_RAW:
return $data;
case self::FORMAT_HTML:
$this->getHeaders()->setDefault('Content-Type', 'text/html; charset=' . $this->charset);
return $data;
case self::FORMAT_JSON:
$this->getHeaders()->set('Content-Type', 'application/json');
return Json::encode($data);
case self::FORMAT_JSONP:
12 years ago
$this->getHeaders()->set('Content-Type', 'text/javascript; charset=' . $this->charset);
if (is_array($data) && isset($data['data'], $data['callback'])) {
return sprintf('%s(%s);', $data['callback'], Json::encode($data['data']));
} else {
throw new InvalidParamException("The 'jsonp' response requires that the data be an array consisting of both 'data' and 'callback' elements.");
}
case self::FORMAT_XML:
return Yii::createObject('yii\web\XmlResponseFormatter')->format($this, $data);
default:
throw new InvalidConfigException("Unsupported response format: $format");
}
}
12 years ago
}