Response.php 40 KB

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