Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

971 line
37KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\base\InvalidParamException;
  11. use yii\helpers\Url;
  12. use yii\helpers\FileHelper;
  13. use yii\helpers\StringHelper;
  14. /**
  15. * The web Response class represents an HTTP response
  16. *
  17. * It holds the [[headers]], [[cookies]] and [[content]] that is to be sent to the client.
  18. * It also controls the HTTP [[statusCode|status code]].
  19. *
  20. * Response is configured as an application component in [[\yii\web\Application]] by default.
  21. * You can access that instance via `Yii::$app->response`.
  22. *
  23. * You can modify its configuration by adding an array to your application config under `components`
  24. * as it is shown in the following example:
  25. *
  26. * ```php
  27. * 'response' => [
  28. * 'format' => yii\web\Response::FORMAT_JSON,
  29. * 'charset' => 'UTF-8',
  30. * // ...
  31. * ]
  32. * ```
  33. *
  34. * @property CookieCollection $cookies The cookie collection. This property is read-only.
  35. * @property string $downloadHeaders The attachment file name. This property is write-only.
  36. * @property HeaderCollection $headers The header collection. This property is read-only.
  37. * @property boolean $isClientError Whether this response indicates a client error. This property is
  38. * read-only.
  39. * @property boolean $isEmpty Whether this response is empty. This property is read-only.
  40. * @property boolean $isForbidden Whether this response indicates the current request is forbidden. This
  41. * property is read-only.
  42. * @property boolean $isInformational Whether this response is informational. This property is read-only.
  43. * @property boolean $isInvalid Whether this response has a valid [[statusCode]]. This property is read-only.
  44. * @property boolean $isNotFound Whether this response indicates the currently requested resource is not
  45. * found. This property is read-only.
  46. * @property boolean $isOk Whether this response is OK. This property is read-only.
  47. * @property boolean $isRedirection Whether this response is a redirection. This property is read-only.
  48. * @property boolean $isServerError Whether this response indicates a server error. This property is
  49. * read-only.
  50. * @property boolean $isSuccessful Whether this response is successful. This property is read-only.
  51. * @property integer $statusCode The HTTP status code to send with the response.
  52. *
  53. * @author Qiang Xue <qiang.xue@gmail.com>
  54. * @author Carsten Brandt <mail@cebe.cc>
  55. * @since 2.0
  56. */
  57. class Response extends \yii\base\Response
  58. {
  59. /**
  60. * @event ResponseEvent an event that is triggered at the beginning of [[send()]].
  61. */
  62. const EVENT_BEFORE_SEND = 'beforeSend';
  63. /**
  64. * @event ResponseEvent an event that is triggered at the end of [[send()]].
  65. */
  66. const EVENT_AFTER_SEND = 'afterSend';
  67. /**
  68. * @event ResponseEvent an event that is triggered right after [[prepare()]] is called in [[send()]].
  69. * You may respond to this event to filter the response content before it is sent to the client.
  70. */
  71. const EVENT_AFTER_PREPARE = 'afterPrepare';
  72. const FORMAT_RAW = 'raw';
  73. const FORMAT_HTML = 'html';
  74. const FORMAT_JSON = 'json';
  75. const FORMAT_JSONP = 'jsonp';
  76. const FORMAT_XML = 'xml';
  77. /**
  78. * @var string the response format. This determines how to convert [[data]] into [[content]]
  79. * when the latter is not set. The value of this property must be one of the keys declared in the [[formatters] array.
  80. * By default, the following formats are supported:
  81. *
  82. * - [[FORMAT_RAW]]: the data will be treated as the response content without any conversion.
  83. * No extra HTTP header will be added.
  84. * - [[FORMAT_HTML]]: the data will be treated as the response content without any conversion.
  85. * The "Content-Type" header will set as "text/html".
  86. * - [[FORMAT_JSON]]: the data will be converted into JSON format, and the "Content-Type"
  87. * header will be set as "application/json".
  88. * - [[FORMAT_JSONP]]: the data will be converted into JSONP format, and the "Content-Type"
  89. * header will be set as "text/javascript". Note that in this case `$data` must be an array
  90. * with "data" and "callback" elements. The former refers to the actual data to be sent,
  91. * while the latter refers to the name of the JavaScript callback.
  92. * - [[FORMAT_XML]]: the data will be converted into XML format. Please refer to [[XmlResponseFormatter]]
  93. * for more details.
  94. *
  95. * You may customize the formatting process or support additional formats by configuring [[formatters]].
  96. * @see formatters
  97. */
  98. public $format = self::FORMAT_HTML;
  99. /**
  100. * @var string the MIME type (e.g. `application/json`) from the request ACCEPT header chosen for this response.
  101. * This property is mainly set by [[\yii\filters\ContentNegotiator]].
  102. */
  103. public $acceptMimeType;
  104. /**
  105. * @var array the parameters (e.g. `['q' => 1, 'version' => '1.0']`) associated with the [[acceptMimeType|chosen MIME type]].
  106. * This is a list of name-value pairs associated with [[acceptMimeType]] from the ACCEPT HTTP header.
  107. * This property is mainly set by [[\yii\filters\ContentNegotiator]].
  108. */
  109. public $acceptParams = [];
  110. /**
  111. * @var array the formatters for converting data into the response content of the specified [[format]].
  112. * The array keys are the format names, and the array values are the corresponding configurations
  113. * for creating the formatter objects.
  114. * @see format
  115. * @see defaultFormatters
  116. */
  117. public $formatters = [];
  118. /**
  119. * @var mixed the original response data. When this is not null, it will be converted into [[content]]
  120. * according to [[format]] when the response is being sent out.
  121. * @see content
  122. */
  123. public $data;
  124. /**
  125. * @var string the response content. When [[data]] is not null, it will be converted into [[content]]
  126. * according to [[format]] when the response is being sent out.
  127. * @see data
  128. */
  129. public $content;
  130. /**
  131. * @var resource|array the stream to be sent. This can be a stream handle or an array of stream handle,
  132. * the begin position and the end position. Note that when this property is set, the [[data]] and [[content]]
  133. * properties will be ignored by [[send()]].
  134. */
  135. public $stream;
  136. /**
  137. * @var string the charset of the text response. If not set, it will use
  138. * the value of [[Application::charset]].
  139. */
  140. public $charset;
  141. /**
  142. * @var string the HTTP status description that comes together with the status code.
  143. * @see httpStatuses
  144. */
  145. public $statusText = 'OK';
  146. /**
  147. * @var string the version of the HTTP protocol to use. If not set, it will be determined via `$_SERVER['SERVER_PROTOCOL']`,
  148. * or '1.1' if that is not available.
  149. */
  150. public $version;
  151. /**
  152. * @var boolean whether the response has been sent. If this is true, calling [[send()]] will do nothing.
  153. */
  154. public $isSent = false;
  155. /**
  156. * @var array list of HTTP status codes and the corresponding texts
  157. */
  158. public static $httpStatuses = [
  159. 100 => 'Continue',
  160. 101 => 'Switching Protocols',
  161. 102 => 'Processing',
  162. 118 => 'Connection timed out',
  163. 200 => 'OK',
  164. 201 => 'Created',
  165. 202 => 'Accepted',
  166. 203 => 'Non-Authoritative',
  167. 204 => 'No Content',
  168. 205 => 'Reset Content',
  169. 206 => 'Partial Content',
  170. 207 => 'Multi-Status',
  171. 208 => 'Already Reported',
  172. 210 => 'Content Different',
  173. 226 => 'IM Used',
  174. 300 => 'Multiple Choices',
  175. 301 => 'Moved Permanently',
  176. 302 => 'Found',
  177. 303 => 'See Other',
  178. 304 => 'Not Modified',
  179. 305 => 'Use Proxy',
  180. 306 => 'Reserved',
  181. 307 => 'Temporary Redirect',
  182. 308 => 'Permanent Redirect',
  183. 310 => 'Too many Redirect',
  184. 400 => 'Bad Request',
  185. 401 => 'Unauthorized',
  186. 402 => 'Payment Required',
  187. 403 => 'Forbidden',
  188. 404 => 'Not Found',
  189. 405 => 'Method Not Allowed',
  190. 406 => 'Not Acceptable',
  191. 407 => 'Proxy Authentication Required',
  192. 408 => 'Request Time-out',
  193. 409 => 'Conflict',
  194. 410 => 'Gone',
  195. 411 => 'Length Required',
  196. 412 => 'Precondition Failed',
  197. 413 => 'Request Entity Too Large',
  198. 414 => 'Request-URI Too Long',
  199. 415 => 'Unsupported Media Type',
  200. 416 => 'Requested range unsatisfiable',
  201. 417 => 'Expectation failed',
  202. 418 => 'I\'m a teapot',
  203. 421 => 'Misdirected Request',
  204. 422 => 'Unprocessable entity',
  205. 423 => 'Locked',
  206. 424 => 'Method failure',
  207. 425 => 'Unordered Collection',
  208. 426 => 'Upgrade Required',
  209. 428 => 'Precondition Required',
  210. 429 => 'Too Many Requests',
  211. 431 => 'Request Header Fields Too Large',
  212. 449 => 'Retry With',
  213. 450 => 'Blocked by Windows Parental Controls',
  214. 500 => 'Internal Server Error',
  215. 501 => 'Not Implemented',
  216. 502 => 'Bad Gateway or Proxy Error',
  217. 503 => 'Service Unavailable',
  218. 504 => 'Gateway Time-out',
  219. 505 => 'HTTP Version not supported',
  220. 507 => 'Insufficient storage',
  221. 508 => 'Loop Detected',
  222. 509 => 'Bandwidth Limit Exceeded',
  223. 510 => 'Not Extended',
  224. 511 => 'Network Authentication Required',
  225. ];
  226. /**
  227. * @var integer the HTTP status code to send with the response.
  228. */
  229. private $_statusCode = 200;
  230. /**
  231. * @var HeaderCollection
  232. */
  233. private $_headers;
  234. /**
  235. * Initializes this component.
  236. */
  237. public function init()
  238. {
  239. if ($this->version === null) {
  240. if (isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.0') {
  241. $this->version = '1.0';
  242. } else {
  243. $this->version = '1.1';
  244. }
  245. }
  246. if ($this->charset === null) {
  247. $this->charset = Yii::$app->charset;
  248. }
  249. $this->formatters = array_merge($this->defaultFormatters(), $this->formatters);
  250. }
  251. /**
  252. * @return integer the HTTP status code to send with the response.
  253. */
  254. public function getStatusCode()
  255. {
  256. return $this->_statusCode;
  257. }
  258. /**
  259. * Sets the response status code.
  260. * This method will set the corresponding status text if `$text` is null.
  261. * @param integer $value the status code
  262. * @param string $text the status text. If not set, it will be set automatically based on the status code.
  263. * @throws InvalidParamException if the status code is invalid.
  264. */
  265. public function setStatusCode($value, $text = null)
  266. {
  267. if ($value === null) {
  268. $value = 200;
  269. }
  270. $this->_statusCode = (int) $value;
  271. if ($this->getIsInvalid()) {
  272. throw new InvalidParamException("The HTTP status code is invalid: $value");
  273. }
  274. if ($text === null) {
  275. $this->statusText = isset(static::$httpStatuses[$this->_statusCode]) ? static::$httpStatuses[$this->_statusCode] : '';
  276. } else {
  277. $this->statusText = $text;
  278. }
  279. }
  280. /**
  281. * Returns the header collection.
  282. * The header collection contains the currently registered HTTP headers.
  283. * @return HeaderCollection the header collection
  284. */
  285. public function getHeaders()
  286. {
  287. if ($this->_headers === null) {
  288. $this->_headers = new HeaderCollection;
  289. }
  290. return $this->_headers;
  291. }
  292. /**
  293. * Sends the response to the client.
  294. */
  295. public function send()
  296. {
  297. if ($this->isSent) {
  298. return;
  299. }
  300. $this->trigger(self::EVENT_BEFORE_SEND);
  301. $this->prepare();
  302. $this->trigger(self::EVENT_AFTER_PREPARE);
  303. $this->sendHeaders();
  304. $this->sendContent();
  305. $this->trigger(self::EVENT_AFTER_SEND);
  306. $this->isSent = true;
  307. }
  308. /**
  309. * Clears the headers, cookies, content, status code of the response.
  310. */
  311. public function clear()
  312. {
  313. $this->_headers = null;
  314. $this->_cookies = null;
  315. $this->_statusCode = 200;
  316. $this->statusText = 'OK';
  317. $this->data = null;
  318. $this->stream = null;
  319. $this->content = null;
  320. $this->isSent = false;
  321. }
  322. /**
  323. * Sends the response headers to the client
  324. */
  325. protected function sendHeaders()
  326. {
  327. if (headers_sent()) {
  328. return;
  329. }
  330. if ($this->_headers) {
  331. $headers = $this->getHeaders();
  332. foreach ($headers as $name => $values) {
  333. $name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $name)));
  334. // set replace for first occurrence of header but false afterwards to allow multiple
  335. $replace = true;
  336. foreach ($values as $value) {
  337. header("$name: $value", $replace);
  338. $replace = false;
  339. }
  340. }
  341. }
  342. $statusCode = $this->getStatusCode();
  343. header("HTTP/{$this->version} {$statusCode} {$this->statusText}");
  344. $this->sendCookies();
  345. }
  346. /**
  347. * Sends the cookies to the client.
  348. */
  349. protected function sendCookies()
  350. {
  351. if ($this->_cookies === null) {
  352. return;
  353. }
  354. $request = Yii::$app->getRequest();
  355. if ($request->enableCookieValidation) {
  356. if ($request->cookieValidationKey == '') {
  357. throw new InvalidConfigException(get_class($request) . '::cookieValidationKey must be configured with a secret key.');
  358. }
  359. $validationKey = $request->cookieValidationKey;
  360. }
  361. foreach ($this->getCookies() as $cookie) {
  362. $value = $cookie->value;
  363. if ($cookie->expire != 1 && isset($validationKey)) {
  364. $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey);
  365. }
  366. setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
  367. }
  368. }
  369. /**
  370. * Sends the response content to the client
  371. */
  372. protected function sendContent()
  373. {
  374. if ($this->stream === null) {
  375. echo $this->content;
  376. return;
  377. }
  378. set_time_limit(0); // Reset time limit for big files
  379. $chunkSize = 8 * 1024 * 1024; // 8MB per chunk
  380. if (is_array($this->stream)) {
  381. list ($handle, $begin, $end) = $this->stream;
  382. fseek($handle, $begin);
  383. while (!feof($handle) && ($pos = ftell($handle)) <= $end) {
  384. if ($pos + $chunkSize > $end) {
  385. $chunkSize = $end - $pos + 1;
  386. }
  387. echo fread($handle, $chunkSize);
  388. flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
  389. }
  390. fclose($handle);
  391. } else {
  392. while (!feof($this->stream)) {
  393. echo fread($this->stream, $chunkSize);
  394. flush();
  395. }
  396. fclose($this->stream);
  397. }
  398. }
  399. /**
  400. * Sends a file to the browser.
  401. *
  402. * Note that this method only prepares the response for file sending. The file is not sent
  403. * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
  404. *
  405. * @param string $filePath the path of the file to be sent.
  406. * @param string $attachmentName the file name shown to the user. If null, it will be determined from `$filePath`.
  407. * @param array $options additional options for sending the file. The following options are supported:
  408. *
  409. * - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
  410. * - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
  411. * meaning a download dialog will pop up.
  412. *
  413. * @return $this the response object itself
  414. */
  415. public function sendFile($filePath, $attachmentName = null, $options = [])
  416. {
  417. if (!isset($options['mimeType'])) {
  418. $options['mimeType'] = FileHelper::getMimeTypeByExtension($filePath);
  419. }
  420. if ($attachmentName === null) {
  421. $attachmentName = basename($filePath);
  422. }
  423. $handle = fopen($filePath, 'rb');
  424. $this->sendStreamAsFile($handle, $attachmentName, $options);
  425. return $this;
  426. }
  427. /**
  428. * Sends the specified content as a file to the browser.
  429. *
  430. * Note that this method only prepares the response for file sending. The file is not sent
  431. * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
  432. *
  433. * @param string $content the content to be sent. The existing [[content]] will be discarded.
  434. * @param string $attachmentName the file name shown to the user.
  435. * @param array $options additional options for sending the file. The following options are supported:
  436. *
  437. * - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
  438. * - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
  439. * meaning a download dialog will pop up.
  440. *
  441. * @return $this the response object itself
  442. * @throws HttpException if the requested range is not satisfiable
  443. */
  444. public function sendContentAsFile($content, $attachmentName, $options = [])
  445. {
  446. $headers = $this->getHeaders();
  447. $contentLength = StringHelper::byteLength($content);
  448. $range = $this->getHttpRange($contentLength);
  449. if ($range === false) {
  450. $headers->set('Content-Range', "bytes */$contentLength");
  451. throw new HttpException(416, 'Requested range not satisfiable');
  452. }
  453. list($begin, $end) = $range;
  454. if ($begin != 0 || $end != $contentLength - 1) {
  455. $this->setStatusCode(206);
  456. $headers->set('Content-Range', "bytes $begin-$end/$contentLength");
  457. $this->content = StringHelper::byteSubstr($content, $begin, $end - $begin + 1);
  458. } else {
  459. $this->setStatusCode(200);
  460. $this->content = $content;
  461. }
  462. $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
  463. $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
  464. $this->format = self::FORMAT_RAW;
  465. return $this;
  466. }
  467. /**
  468. * Sends the specified stream as a file to the browser.
  469. *
  470. * Note that this method only prepares the response for file sending. The file is not sent
  471. * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
  472. *
  473. * @param resource $handle the handle of the stream to be sent.
  474. * @param string $attachmentName the file name shown to the user.
  475. * @param array $options additional options for sending the file. The following options are supported:
  476. *
  477. * - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
  478. * - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
  479. * meaning a download dialog will pop up.
  480. * - `fileSize`: the size of the content to stream this is useful when size of the content is known
  481. * and the content is not seekable. Defaults to content size using `ftell()`.
  482. * This option is available since version 2.0.4.
  483. *
  484. * @return $this the response object itself
  485. * @throws HttpException if the requested range cannot be satisfied.
  486. */
  487. public function sendStreamAsFile($handle, $attachmentName, $options = [])
  488. {
  489. $headers = $this->getHeaders();
  490. if (isset($options['fileSize'])) {
  491. $fileSize = $options['fileSize'];
  492. } else {
  493. fseek($handle, 0, SEEK_END);
  494. $fileSize = ftell($handle);
  495. }
  496. $range = $this->getHttpRange($fileSize);
  497. if ($range === false) {
  498. $headers->set('Content-Range', "bytes */$fileSize");
  499. throw new HttpException(416, 'Requested range not satisfiable');
  500. }
  501. list($begin, $end) = $range;
  502. if ($begin != 0 || $end != $fileSize - 1) {
  503. $this->setStatusCode(206);
  504. $headers->set('Content-Range', "bytes $begin-$end/$fileSize");
  505. } else {
  506. $this->setStatusCode(200);
  507. }
  508. $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
  509. $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
  510. $this->format = self::FORMAT_RAW;
  511. $this->stream = [$handle, $begin, $end];
  512. return $this;
  513. }
  514. /**
  515. * Sets a default set of HTTP headers for file downloading purpose.
  516. * @param string $attachmentName the attachment file name
  517. * @param string $mimeType the MIME type for the response. If null, `Content-Type` header will NOT be set.
  518. * @param boolean $inline whether the browser should open the file within the browser window. Defaults to false,
  519. * meaning a download dialog will pop up.
  520. * @param integer $contentLength the byte length of the file being downloaded. If null, `Content-Length` header will NOT be set.
  521. * @return $this the response object itself
  522. */
  523. public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = false, $contentLength = null)
  524. {
  525. $headers = $this->getHeaders();
  526. $disposition = $inline ? 'inline' : 'attachment';
  527. $headers->setDefault('Pragma', 'public')
  528. ->setDefault('Accept-Ranges', 'bytes')
  529. ->setDefault('Expires', '0')
  530. ->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
  531. ->setDefault('Content-Disposition', "$disposition; filename=\"$attachmentName\"");
  532. if ($mimeType !== null) {
  533. $headers->setDefault('Content-Type', $mimeType);
  534. }
  535. if ($contentLength !== null) {
  536. $headers->setDefault('Content-Length', $contentLength);
  537. }
  538. return $this;
  539. }
  540. /**
  541. * Determines the HTTP range given in the request.
  542. * @param integer $fileSize the size of the file that will be used to validate the requested HTTP range.
  543. * @return array|boolean the range (begin, end), or false if the range request is invalid.
  544. */
  545. protected function getHttpRange($fileSize)
  546. {
  547. if (!isset($_SERVER['HTTP_RANGE']) || $_SERVER['HTTP_RANGE'] === '-') {
  548. return [0, $fileSize - 1];
  549. }
  550. if (!preg_match('/^bytes=(\d*)-(\d*)$/', $_SERVER['HTTP_RANGE'], $matches)) {
  551. return false;
  552. }
  553. if ($matches[1] === '') {
  554. $start = $fileSize - $matches[2];
  555. $end = $fileSize - 1;
  556. } elseif ($matches[2] !== '') {
  557. $start = $matches[1];
  558. $end = $matches[2];
  559. if ($end >= $fileSize) {
  560. $end = $fileSize - 1;
  561. }
  562. } else {
  563. $start = $matches[1];
  564. $end = $fileSize - 1;
  565. }
  566. if ($start < 0 || $start > $end) {
  567. return false;
  568. } else {
  569. return [$start, $end];
  570. }
  571. }
  572. /**
  573. * Sends existing file to a browser as a download using x-sendfile.
  574. *
  575. * X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
  576. * that in turn processes the request, this way eliminating the need to perform tasks like reading the file
  577. * and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
  578. * increase in performance as the web application is allowed to terminate earlier while the webserver is
  579. * handling the request.
  580. *
  581. * The request is sent to the server through a special non-standard HTTP-header.
  582. * When the web server encounters the presence of such header it will discard all output and send the file
  583. * specified by that header using web server internals including all optimizations like caching-headers.
  584. *
  585. * As this header directive is non-standard different directives exists for different web servers applications:
  586. *
  587. * - Apache: [X-Sendfile](http://tn123.org/mod_xsendfile)
  588. * - Lighttpd v1.4: [X-LIGHTTPD-send-file](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
  589. * - Lighttpd v1.5: [X-Sendfile](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
  590. * - Nginx: [X-Accel-Redirect](http://wiki.nginx.org/XSendfile)
  591. * - Cherokee: [X-Sendfile and X-Accel-Redirect](http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile)
  592. *
  593. * So for this method to work the X-SENDFILE option/module should be enabled by the web server and
  594. * a proper xHeader should be sent.
  595. *
  596. * **Note**
  597. *
  598. * This option allows to download files that are not under web folders, and even files that are otherwise protected
  599. * (deny from all) like `.htaccess`.
  600. *
  601. * **Side effects**
  602. *
  603. * If this option is disabled by the web server, when this method is called a download configuration dialog
  604. * will open but the downloaded file will have 0 bytes.
  605. *
  606. * **Known issues**
  607. *
  608. * There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
  609. * an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
  610. * is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header.
  611. *
  612. * **Example**
  613. *
  614. * ```php
  615. * Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
  616. * ```
  617. *
  618. * @param string $filePath file name with full path
  619. * @param string $attachmentName file name shown to the user. If null, it will be determined from `$filePath`.
  620. * @param array $options additional options for sending the file. The following options are supported:
  621. *
  622. * - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
  623. * - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
  624. * meaning a download dialog will pop up.
  625. * - xHeader: string, the name of the x-sendfile header. Defaults to "X-Sendfile".
  626. *
  627. * @return $this the response object itself
  628. */
  629. public function xSendFile($filePath, $attachmentName = null, $options = [])
  630. {
  631. if ($attachmentName === null) {
  632. $attachmentName = basename($filePath);
  633. }
  634. if (isset($options['mimeType'])) {
  635. $mimeType = $options['mimeType'];
  636. } elseif (($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
  637. $mimeType = 'application/octet-stream';
  638. }
  639. if (isset($options['xHeader'])) {
  640. $xHeader = $options['xHeader'];
  641. } else {
  642. $xHeader = 'X-Sendfile';
  643. }
  644. $disposition = empty($options['inline']) ? 'attachment' : 'inline';
  645. $this->getHeaders()
  646. ->setDefault($xHeader, $filePath)
  647. ->setDefault('Content-Type', $mimeType)
  648. ->setDefault('Content-Disposition', "{$disposition}; filename=\"{$attachmentName}\"");
  649. $this->format = self::FORMAT_RAW;
  650. return $this;
  651. }
  652. /**
  653. * Redirects the browser to the specified URL.
  654. *
  655. * This method adds a "Location" header to the current response. Note that it does not send out
  656. * the header until [[send()]] is called. In a controller action you may use this method as follows:
  657. *
  658. * ```php
  659. * return Yii::$app->getResponse()->redirect($url);
  660. * ```
  661. *
  662. * In other places, if you want to send out the "Location" header immediately, you should use
  663. * the following code:
  664. *
  665. * ```php
  666. * Yii::$app->getResponse()->redirect($url)->send();
  667. * return;
  668. * ```
  669. *
  670. * In AJAX mode, this normally will not work as expected unless there are some
  671. * client-side JavaScript code handling the redirection. To help achieve this goal,
  672. * this method will send out a "X-Redirect" header instead of "Location".
  673. *
  674. * If you use the "yii" JavaScript module, it will handle the AJAX redirection as
  675. * described above. Otherwise, you should write the following JavaScript code to
  676. * handle the redirection:
  677. *
  678. * ```javascript
  679. * $document.ajaxComplete(function (event, xhr, settings) {
  680. * var url = xhr.getResponseHeader('X-Redirect');
  681. * if (url) {
  682. * window.location = url;
  683. * }
  684. * });
  685. * ```
  686. *
  687. * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
  688. *
  689. * - a string representing a URL (e.g. "http://example.com")
  690. * - a string representing a URL alias (e.g. "@example.com")
  691. * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`).
  692. * Note that the route is with respect to the whole application, instead of relative to a controller or module.
  693. * [[Url::to()]] will be used to convert the array into a URL.
  694. *
  695. * Any relative URL will be converted into an absolute one by prepending it with the host info
  696. * of the current request.
  697. *
  698. * @param integer $statusCode the HTTP status code. Defaults to 302.
  699. * See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html>
  700. * for details about HTTP status code
  701. * @param boolean $checkAjax whether to specially handle AJAX (and PJAX) requests. Defaults to true,
  702. * meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser
  703. * to redirect to the given URL. If this is false, a `Location` header will be sent, which when received as
  704. * an AJAX/PJAX response, may NOT cause browser redirection.
  705. * Takes effect only when request header `X-Ie-Redirect-Compatibility` is absent.
  706. * @return $this the response object itself
  707. */
  708. public function redirect($url, $statusCode = 302, $checkAjax = true)
  709. {
  710. if (is_array($url) && isset($url[0])) {
  711. // ensure the route is absolute
  712. $url[0] = '/' . ltrim($url[0], '/');
  713. }
  714. $url = Url::to($url);
  715. if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) {
  716. $url = Yii::$app->getRequest()->getHostInfo() . $url;
  717. }
  718. if ($checkAjax) {
  719. if (Yii::$app->getRequest()->getIsAjax()) {
  720. if (Yii::$app->getRequest()->getHeaders()->get('X-Ie-Redirect-Compatibility') !== null && $statusCode === 302) {
  721. // Ajax 302 redirect in IE does not work. Change status code to 200. See https://github.com/yiisoft/yii2/issues/9670
  722. $statusCode = 200;
  723. }
  724. if (Yii::$app->getRequest()->getIsPjax()) {
  725. $this->getHeaders()->set('X-Pjax-Url', $url);
  726. } else {
  727. $this->getHeaders()->set('X-Redirect', $url);
  728. }
  729. } else {
  730. $this->getHeaders()->set('Location', $url);
  731. }
  732. } else {
  733. $this->getHeaders()->set('Location', $url);
  734. }
  735. $this->setStatusCode($statusCode);
  736. return $this;
  737. }
  738. /**
  739. * Refreshes the current page.
  740. * The effect of this method call is the same as the user pressing the refresh button of his browser
  741. * (without re-posting data).
  742. *
  743. * In a controller action you may use this method like this:
  744. *
  745. * ```php
  746. * return Yii::$app->getResponse()->refresh();
  747. * ```
  748. *
  749. * @param string $anchor the anchor that should be appended to the redirection URL.
  750. * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
  751. * @return Response the response object itself
  752. */
  753. public function refresh($anchor = '')
  754. {
  755. return $this->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
  756. }
  757. private $_cookies;
  758. /**
  759. * Returns the cookie collection.
  760. * Through the returned cookie collection, you add or remove cookies as follows,
  761. *
  762. * ```php
  763. * // add a cookie
  764. * $response->cookies->add(new Cookie([
  765. * 'name' => $name,
  766. * 'value' => $value,
  767. * ]);
  768. *
  769. * // remove a cookie
  770. * $response->cookies->remove('name');
  771. * // alternatively
  772. * unset($response->cookies['name']);
  773. * ```
  774. *
  775. * @return CookieCollection the cookie collection.
  776. */
  777. public function getCookies()
  778. {
  779. if ($this->_cookies === null) {
  780. $this->_cookies = new CookieCollection;
  781. }
  782. return $this->_cookies;
  783. }
  784. /**
  785. * @return boolean whether this response has a valid [[statusCode]].
  786. */
  787. public function getIsInvalid()
  788. {
  789. return $this->getStatusCode() < 100 || $this->getStatusCode() >= 600;
  790. }
  791. /**
  792. * @return boolean whether this response is informational
  793. */
  794. public function getIsInformational()
  795. {
  796. return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200;
  797. }
  798. /**
  799. * @return boolean whether this response is successful
  800. */
  801. public function getIsSuccessful()
  802. {
  803. return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300;
  804. }
  805. /**
  806. * @return boolean whether this response is a redirection
  807. */
  808. public function getIsRedirection()
  809. {
  810. return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400;
  811. }
  812. /**
  813. * @return boolean whether this response indicates a client error
  814. */
  815. public function getIsClientError()
  816. {
  817. return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500;
  818. }
  819. /**
  820. * @return boolean whether this response indicates a server error
  821. */
  822. public function getIsServerError()
  823. {
  824. return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600;
  825. }
  826. /**
  827. * @return boolean whether this response is OK
  828. */
  829. public function getIsOk()
  830. {
  831. return $this->getStatusCode() == 200;
  832. }
  833. /**
  834. * @return boolean whether this response indicates the current request is forbidden
  835. */
  836. public function getIsForbidden()
  837. {
  838. return $this->getStatusCode() == 403;
  839. }
  840. /**
  841. * @return boolean whether this response indicates the currently requested resource is not found
  842. */
  843. public function getIsNotFound()
  844. {
  845. return $this->getStatusCode() == 404;
  846. }
  847. /**
  848. * @return boolean whether this response is empty
  849. */
  850. public function getIsEmpty()
  851. {
  852. return in_array($this->getStatusCode(), [201, 204, 304]);
  853. }
  854. /**
  855. * @return array the formatters that are supported by default
  856. */
  857. protected function defaultFormatters()
  858. {
  859. return [
  860. self::FORMAT_HTML => 'yii\web\HtmlResponseFormatter',
  861. self::FORMAT_XML => 'yii\web\XmlResponseFormatter',
  862. self::FORMAT_JSON => 'yii\web\JsonResponseFormatter',
  863. self::FORMAT_JSONP => [
  864. 'class' => 'yii\web\JsonResponseFormatter',
  865. 'useJsonp' => true,
  866. ],
  867. ];
  868. }
  869. /**
  870. * Prepares for sending the response.
  871. * The default implementation will convert [[data]] into [[content]] and set headers accordingly.
  872. * @throws InvalidConfigException if the formatter for the specified format is invalid or [[format]] is not supported
  873. */
  874. protected function prepare()
  875. {
  876. if ($this->stream !== null) {
  877. return;
  878. }
  879. if (isset($this->formatters[$this->format])) {
  880. $formatter = $this->formatters[$this->format];
  881. if (!is_object($formatter)) {
  882. $this->formatters[$this->format] = $formatter = Yii::createObject($formatter);
  883. }
  884. if ($formatter instanceof ResponseFormatterInterface) {
  885. $formatter->format($this);
  886. } else {
  887. throw new InvalidConfigException("The '{$this->format}' response formatter is invalid. It must implement the ResponseFormatterInterface.");
  888. }
  889. } elseif ($this->format === self::FORMAT_RAW) {
  890. if ($this->data !== null) {
  891. $this->content = $this->data;
  892. }
  893. } else {
  894. throw new InvalidConfigException("Unsupported response format: {$this->format}");
  895. }
  896. if (is_array($this->content)) {
  897. throw new InvalidParamException('Response content must not be an array.');
  898. } elseif (is_object($this->content)) {
  899. if (method_exists($this->content, '__toString')) {
  900. $this->content = $this->content->__toString();
  901. } else {
  902. throw new InvalidParamException('Response content must be a string or an object implementing __toString().');
  903. }
  904. }
  905. }
  906. }