Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

953 lines
36KB

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