Response.php 43 KB

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