Response.php 41 KB

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