Response.php 29 KB

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