Response.php 39KB

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