Response.php 43 KB

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