Response.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  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. setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
  387. }
  388. }
  389. /**
  390. * Sends the response content to the client.
  391. */
  392. protected function sendContent()
  393. {
  394. if ($this->getStatusCode() === 204) {
  395. return;
  396. }
  397. if ($this->stream === null) {
  398. echo $this->content;
  399. return;
  400. }
  401. set_time_limit(0); // Reset time limit for big files
  402. $chunkSize = 8 * 1024 * 1024; // 8MB per chunk
  403. if (is_array($this->stream)) {
  404. list($handle, $begin, $end) = $this->stream;
  405. fseek($handle, $begin);
  406. while (!feof($handle) && ($pos = ftell($handle)) <= $end) {
  407. if ($pos + $chunkSize > $end) {
  408. $chunkSize = $end - $pos + 1;
  409. }
  410. echo fread($handle, $chunkSize);
  411. flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
  412. }
  413. fclose($handle);
  414. } else {
  415. while (!feof($this->stream)) {
  416. echo fread($this->stream, $chunkSize);
  417. flush();
  418. }
  419. fclose($this->stream);
  420. }
  421. }
  422. /**
  423. * Sends a file to the browser.
  424. *
  425. * Note that this method only prepares the response for file sending. The file is not sent
  426. * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
  427. *
  428. * The following is an example implementation of a controller action that allows requesting files from a directory
  429. * that is not accessible from web:
  430. *
  431. * ```php
  432. * public function actionFile($filename)
  433. * {
  434. * $storagePath = Yii::getAlias('@app/files');
  435. *
  436. * // check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
  437. * if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
  438. * throw new \yii\web\NotFoundHttpException('The file does not exists.');
  439. * }
  440. * return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
  441. * }
  442. * ```
  443. *
  444. * @param string $filePath the path of the file to be sent.
  445. * @param string $attachmentName the file name shown to the user. If null, it will be determined from `$filePath`.
  446. * @param array $options additional options for sending the file. The following options are supported:
  447. *
  448. * - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
  449. * - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
  450. * meaning a download dialog will pop up.
  451. *
  452. * @return $this the response object itself
  453. * @see sendContentAsFile()
  454. * @see sendStreamAsFile()
  455. * @see xSendFile()
  456. */
  457. public function sendFile($filePath, $attachmentName = null, $options = [])
  458. {
  459. if (!isset($options['mimeType'])) {
  460. $options['mimeType'] = FileHelper::getMimeTypeByExtension($filePath);
  461. }
  462. if ($attachmentName === null) {
  463. $attachmentName = basename($filePath);
  464. }
  465. $handle = fopen($filePath, 'rb');
  466. $this->sendStreamAsFile($handle, $attachmentName, $options);
  467. return $this;
  468. }
  469. /**
  470. * Sends the specified content as a file to the browser.
  471. *
  472. * Note that this method only prepares the response for file sending. The file is not sent
  473. * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
  474. *
  475. * @param string $content the content to be sent. The existing [[content]] will be discarded.
  476. * @param string $attachmentName the file name shown to the user.
  477. * @param array $options additional options for sending the file. The following options are supported:
  478. *
  479. * - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
  480. * - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
  481. * meaning a download dialog will pop up.
  482. *
  483. * @return $this the response object itself
  484. * @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable
  485. * @see sendFile() for an example implementation.
  486. */
  487. public function sendContentAsFile($content, $attachmentName, $options = [])
  488. {
  489. $headers = $this->getHeaders();
  490. $contentLength = StringHelper::byteLength($content);
  491. $range = $this->getHttpRange($contentLength);
  492. if ($range === false) {
  493. $headers->set('Content-Range', "bytes */$contentLength");
  494. throw new RangeNotSatisfiableHttpException();
  495. }
  496. list($begin, $end) = $range;
  497. if ($begin != 0 || $end != $contentLength - 1) {
  498. $this->setStatusCode(206);
  499. $headers->set('Content-Range', "bytes $begin-$end/$contentLength");
  500. $this->content = StringHelper::byteSubstr($content, $begin, $end - $begin + 1);
  501. } else {
  502. $this->setStatusCode(200);
  503. $this->content = $content;
  504. }
  505. $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
  506. $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
  507. $this->format = self::FORMAT_RAW;
  508. return $this;
  509. }
  510. /**
  511. * Sends the specified stream as a file to the browser.
  512. *
  513. * Note that this method only prepares the response for file sending. The file is not sent
  514. * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
  515. *
  516. * @param resource $handle the handle of the stream to be sent.
  517. * @param string $attachmentName the file name shown to the user.
  518. * @param array $options additional options for sending the file. The following options are supported:
  519. *
  520. * - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
  521. * - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
  522. * meaning a download dialog will pop up.
  523. * - `fileSize`: the size of the content to stream this is useful when size of the content is known
  524. * and the content is not seekable. Defaults to content size using `ftell()`.
  525. * This option is available since version 2.0.4.
  526. *
  527. * @return $this the response object itself
  528. * @throws RangeNotSatisfiableHttpException if the requested range is not satisfiable
  529. * @see sendFile() for an example implementation.
  530. */
  531. public function sendStreamAsFile($handle, $attachmentName, $options = [])
  532. {
  533. $headers = $this->getHeaders();
  534. if (isset($options['fileSize'])) {
  535. $fileSize = $options['fileSize'];
  536. } else {
  537. fseek($handle, 0, SEEK_END);
  538. $fileSize = ftell($handle);
  539. }
  540. $range = $this->getHttpRange($fileSize);
  541. if ($range === false) {
  542. $headers->set('Content-Range', "bytes */$fileSize");
  543. throw new RangeNotSatisfiableHttpException();
  544. }
  545. list($begin, $end) = $range;
  546. if ($begin != 0 || $end != $fileSize - 1) {
  547. $this->setStatusCode(206);
  548. $headers->set('Content-Range', "bytes $begin-$end/$fileSize");
  549. } else {
  550. $this->setStatusCode(200);
  551. }
  552. $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
  553. $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
  554. $this->format = self::FORMAT_RAW;
  555. $this->stream = [$handle, $begin, $end];
  556. return $this;
  557. }
  558. /**
  559. * Sets a default set of HTTP headers for file downloading purpose.
  560. * @param string $attachmentName the attachment file name
  561. * @param string $mimeType the MIME type for the response. If null, `Content-Type` header will NOT be set.
  562. * @param bool $inline whether the browser should open the file within the browser window. Defaults to false,
  563. * meaning a download dialog will pop up.
  564. * @param int $contentLength the byte length of the file being downloaded. If null, `Content-Length` header will NOT be set.
  565. * @return $this the response object itself
  566. */
  567. public function setDownloadHeaders($attachmentName, $mimeType = null, $inline = false, $contentLength = null)
  568. {
  569. $headers = $this->getHeaders();
  570. $disposition = $inline ? 'inline' : 'attachment';
  571. $headers->setDefault('Pragma', 'public')
  572. ->setDefault('Accept-Ranges', 'bytes')
  573. ->setDefault('Expires', '0')
  574. ->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
  575. ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
  576. if ($mimeType !== null) {
  577. $headers->setDefault('Content-Type', $mimeType);
  578. }
  579. if ($contentLength !== null) {
  580. $headers->setDefault('Content-Length', $contentLength);
  581. }
  582. return $this;
  583. }
  584. /**
  585. * Determines the HTTP range given in the request.
  586. * @param int $fileSize the size of the file that will be used to validate the requested HTTP range.
  587. * @return array|bool the range (begin, end), or false if the range request is invalid.
  588. */
  589. protected function getHttpRange($fileSize)
  590. {
  591. $rangeHeader = Yii::$app->getRequest()->getHeaders()->get('Range', '-');
  592. if ($rangeHeader === '-') {
  593. return [0, $fileSize - 1];
  594. }
  595. if (!preg_match('/^bytes=(\d*)-(\d*)$/', $rangeHeader, $matches)) {
  596. return false;
  597. }
  598. if ($matches[1] === '') {
  599. $start = $fileSize - $matches[2];
  600. $end = $fileSize - 1;
  601. } elseif ($matches[2] !== '') {
  602. $start = $matches[1];
  603. $end = $matches[2];
  604. if ($end >= $fileSize) {
  605. $end = $fileSize - 1;
  606. }
  607. } else {
  608. $start = $matches[1];
  609. $end = $fileSize - 1;
  610. }
  611. if ($start < 0 || $start > $end) {
  612. return false;
  613. }
  614. return [$start, $end];
  615. }
  616. /**
  617. * Sends existing file to a browser as a download using x-sendfile.
  618. *
  619. * X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
  620. * that in turn processes the request, this way eliminating the need to perform tasks like reading the file
  621. * and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
  622. * increase in performance as the web application is allowed to terminate earlier while the webserver is
  623. * handling the request.
  624. *
  625. * The request is sent to the server through a special non-standard HTTP-header.
  626. * When the web server encounters the presence of such header it will discard all output and send the file
  627. * specified by that header using web server internals including all optimizations like caching-headers.
  628. *
  629. * As this header directive is non-standard different directives exists for different web servers applications:
  630. *
  631. * - Apache: [X-Sendfile](http://tn123.org/mod_xsendfile)
  632. * - Lighttpd v1.4: [X-LIGHTTPD-send-file](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
  633. * - Lighttpd v1.5: [X-Sendfile](http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file)
  634. * - Nginx: [X-Accel-Redirect](http://wiki.nginx.org/XSendfile)
  635. * - Cherokee: [X-Sendfile and X-Accel-Redirect](http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile)
  636. *
  637. * So for this method to work the X-SENDFILE option/module should be enabled by the web server and
  638. * a proper xHeader should be sent.
  639. *
  640. * **Note**
  641. *
  642. * This option allows to download files that are not under web folders, and even files that are otherwise protected
  643. * (deny from all) like `.htaccess`.
  644. *
  645. * **Side effects**
  646. *
  647. * If this option is disabled by the web server, when this method is called a download configuration dialog
  648. * will open but the downloaded file will have 0 bytes.
  649. *
  650. * **Known issues**
  651. *
  652. * There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
  653. * an error message like this: "Internet Explorer was not able to open this Internet site. The requested site
  654. * is either unavailable or cannot be found.". You can work around this problem by removing the `Pragma`-header.
  655. *
  656. * **Example**
  657. *
  658. * ```php
  659. * Yii::$app->response->xSendFile('/home/user/Pictures/picture1.jpg');
  660. * ```
  661. *
  662. * @param string $filePath file name with full path
  663. * @param string $attachmentName file name shown to the user. If null, it will be determined from `$filePath`.
  664. * @param array $options additional options for sending the file. The following options are supported:
  665. *
  666. * - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath`
  667. * - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
  668. * meaning a download dialog will pop up.
  669. * - xHeader: string, the name of the x-sendfile header. Defaults to "X-Sendfile".
  670. *
  671. * @return $this the response object itself
  672. * @see sendFile()
  673. */
  674. public function xSendFile($filePath, $attachmentName = null, $options = [])
  675. {
  676. if ($attachmentName === null) {
  677. $attachmentName = basename($filePath);
  678. }
  679. if (isset($options['mimeType'])) {
  680. $mimeType = $options['mimeType'];
  681. } elseif (($mimeType = FileHelper::getMimeTypeByExtension($filePath)) === null) {
  682. $mimeType = 'application/octet-stream';
  683. }
  684. if (isset($options['xHeader'])) {
  685. $xHeader = $options['xHeader'];
  686. } else {
  687. $xHeader = 'X-Sendfile';
  688. }
  689. $disposition = empty($options['inline']) ? 'attachment' : 'inline';
  690. $this->getHeaders()
  691. ->setDefault($xHeader, $filePath)
  692. ->setDefault('Content-Type', $mimeType)
  693. ->setDefault('Content-Disposition', $this->getDispositionHeaderValue($disposition, $attachmentName));
  694. $this->format = self::FORMAT_RAW;
  695. return $this;
  696. }
  697. /**
  698. * Returns Content-Disposition header value that is safe to use with both old and new browsers.
  699. *
  700. * Fallback name:
  701. *
  702. * - Causes issues if contains non-ASCII characters with codes less than 32 or more than 126.
  703. * - Causes issues if contains urlencoded characters (starting with `%`) or `%` character. Some browsers interpret
  704. * `filename="X"` as urlencoded name, some don't.
  705. * - Causes issues if contains path separator characters such as `\` or `/`.
  706. * - Since value is wrapped with `"`, it should be escaped as `\"`.
  707. * - Since input could contain non-ASCII characters, fallback is obtained by transliteration.
  708. *
  709. * UTF name:
  710. *
  711. * - Causes issues if contains path separator characters such as `\` or `/`.
  712. * - Should be urlencoded since headers are ASCII-only.
  713. * - Could be omitted if it exactly matches fallback name.
  714. *
  715. * @param string $disposition
  716. * @param string $attachmentName
  717. * @return string
  718. *
  719. * @since 2.0.10
  720. */
  721. protected function getDispositionHeaderValue($disposition, $attachmentName)
  722. {
  723. $fallbackName = str_replace(
  724. ['%', '/', '\\', '"'],
  725. ['_', '_', '_', '\\"'],
  726. Inflector::transliterate($attachmentName, Inflector::TRANSLITERATE_LOOSE)
  727. );
  728. $utfName = rawurlencode(str_replace(['%', '/', '\\'], '', $attachmentName));
  729. $dispositionHeader = "{$disposition}; filename=\"{$fallbackName}\"";
  730. if ($utfName !== $fallbackName) {
  731. $dispositionHeader .= "; filename*=utf-8''{$utfName}";
  732. }
  733. return $dispositionHeader;
  734. }
  735. /**
  736. * Redirects the browser to the specified URL.
  737. *
  738. * This method adds a "Location" header to the current response. Note that it does not send out
  739. * the header until [[send()]] is called. In a controller action you may use this method as follows:
  740. *
  741. * ```php
  742. * return Yii::$app->getResponse()->redirect($url);
  743. * ```
  744. *
  745. * In other places, if you want to send out the "Location" header immediately, you should use
  746. * the following code:
  747. *
  748. * ```php
  749. * Yii::$app->getResponse()->redirect($url)->send();
  750. * return;
  751. * ```
  752. *
  753. * In AJAX mode, this normally will not work as expected unless there are some
  754. * client-side JavaScript code handling the redirection. To help achieve this goal,
  755. * this method will send out a "X-Redirect" header instead of "Location".
  756. *
  757. * If you use the "yii" JavaScript module, it will handle the AJAX redirection as
  758. * described above. Otherwise, you should write the following JavaScript code to
  759. * handle the redirection:
  760. *
  761. * ```javascript
  762. * $document.ajaxComplete(function (event, xhr, settings) {
  763. * var url = xhr && xhr.getResponseHeader('X-Redirect');
  764. * if (url) {
  765. * window.location = url;
  766. * }
  767. * });
  768. * ```
  769. *
  770. * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
  771. *
  772. * - a string representing a URL (e.g. "http://example.com")
  773. * - a string representing a URL alias (e.g. "@example.com")
  774. * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`).
  775. * Note that the route is with respect to the whole application, instead of relative to a controller or module.
  776. * [[Url::to()]] will be used to convert the array into a URL.
  777. *
  778. * Any relative URL that starts with a single forward slash "/" will be converted
  779. * into an absolute one by prepending it with the host info of the current request.
  780. *
  781. * @param int $statusCode the HTTP status code. Defaults to 302.
  782. * See <https://tools.ietf.org/html/rfc2616#section-10>
  783. * for details about HTTP status code
  784. * @param bool $checkAjax whether to specially handle AJAX (and PJAX) requests. Defaults to true,
  785. * meaning if the current request is an AJAX or PJAX request, then calling this method will cause the browser
  786. * to redirect to the given URL. If this is false, a `Location` header will be sent, which when received as
  787. * an AJAX/PJAX response, may NOT cause browser redirection.
  788. * Takes effect only when request header `X-Ie-Redirect-Compatibility` is absent.
  789. * @return $this the response object itself
  790. */
  791. public function redirect($url, $statusCode = 302, $checkAjax = true)
  792. {
  793. if (is_array($url) && isset($url[0])) {
  794. // ensure the route is absolute
  795. $url[0] = '/' . ltrim($url[0], '/');
  796. }
  797. $url = Url::to($url);
  798. if (strncmp($url, '/', 1) === 0 && strncmp($url, '//', 2) !== 0) {
  799. $url = Yii::$app->getRequest()->getHostInfo() . $url;
  800. }
  801. if ($checkAjax) {
  802. if (Yii::$app->getRequest()->getIsAjax()) {
  803. if (Yii::$app->getRequest()->getHeaders()->get('X-Ie-Redirect-Compatibility') !== null && $statusCode === 302) {
  804. // Ajax 302 redirect in IE does not work. Change status code to 200. See https://github.com/yiisoft/yii2/issues/9670
  805. $statusCode = 200;
  806. }
  807. if (Yii::$app->getRequest()->getIsPjax()) {
  808. $this->getHeaders()->set('X-Pjax-Url', $url);
  809. } else {
  810. $this->getHeaders()->set('X-Redirect', $url);
  811. }
  812. } else {
  813. $this->getHeaders()->set('Location', $url);
  814. }
  815. } else {
  816. $this->getHeaders()->set('Location', $url);
  817. }
  818. $this->setStatusCode($statusCode);
  819. return $this;
  820. }
  821. /**
  822. * Refreshes the current page.
  823. * The effect of this method call is the same as the user pressing the refresh button of his browser
  824. * (without re-posting data).
  825. *
  826. * In a controller action you may use this method like this:
  827. *
  828. * ```php
  829. * return Yii::$app->getResponse()->refresh();
  830. * ```
  831. *
  832. * @param string $anchor the anchor that should be appended to the redirection URL.
  833. * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
  834. * @return Response the response object itself
  835. */
  836. public function refresh($anchor = '')
  837. {
  838. return $this->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
  839. }
  840. private $_cookies;
  841. /**
  842. * Returns the cookie collection.
  843. *
  844. * Through the returned cookie collection, you add or remove cookies as follows,
  845. *
  846. * ```php
  847. * // add a cookie
  848. * $response->cookies->add(new Cookie([
  849. * 'name' => $name,
  850. * 'value' => $value,
  851. * ]);
  852. *
  853. * // remove a cookie
  854. * $response->cookies->remove('name');
  855. * // alternatively
  856. * unset($response->cookies['name']);
  857. * ```
  858. *
  859. * @return CookieCollection the cookie collection.
  860. */
  861. public function getCookies()
  862. {
  863. if ($this->_cookies === null) {
  864. $this->_cookies = new CookieCollection();
  865. }
  866. return $this->_cookies;
  867. }
  868. /**
  869. * @return bool whether this response has a valid [[statusCode]].
  870. */
  871. public function getIsInvalid()
  872. {
  873. return $this->getStatusCode() < 100 || $this->getStatusCode() >= 600;
  874. }
  875. /**
  876. * @return bool whether this response is informational
  877. */
  878. public function getIsInformational()
  879. {
  880. return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200;
  881. }
  882. /**
  883. * @return bool whether this response is successful
  884. */
  885. public function getIsSuccessful()
  886. {
  887. return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300;
  888. }
  889. /**
  890. * @return bool whether this response is a redirection
  891. */
  892. public function getIsRedirection()
  893. {
  894. return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400;
  895. }
  896. /**
  897. * @return bool whether this response indicates a client error
  898. */
  899. public function getIsClientError()
  900. {
  901. return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500;
  902. }
  903. /**
  904. * @return bool whether this response indicates a server error
  905. */
  906. public function getIsServerError()
  907. {
  908. return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600;
  909. }
  910. /**
  911. * @return bool whether this response is OK
  912. */
  913. public function getIsOk()
  914. {
  915. return $this->getStatusCode() == 200;
  916. }
  917. /**
  918. * @return bool whether this response indicates the current request is forbidden
  919. */
  920. public function getIsForbidden()
  921. {
  922. return $this->getStatusCode() == 403;
  923. }
  924. /**
  925. * @return bool whether this response indicates the currently requested resource is not found
  926. */
  927. public function getIsNotFound()
  928. {
  929. return $this->getStatusCode() == 404;
  930. }
  931. /**
  932. * @return bool whether this response is empty
  933. */
  934. public function getIsEmpty()
  935. {
  936. return in_array($this->getStatusCode(), [201, 204, 304]);
  937. }
  938. /**
  939. * @return array the formatters that are supported by default
  940. */
  941. protected function defaultFormatters()
  942. {
  943. return [
  944. self::FORMAT_HTML => [
  945. 'class' => 'yii\web\HtmlResponseFormatter',
  946. ],
  947. self::FORMAT_XML => [
  948. 'class' => 'yii\web\XmlResponseFormatter',
  949. ],
  950. self::FORMAT_JSON => [
  951. 'class' => 'yii\web\JsonResponseFormatter',
  952. ],
  953. self::FORMAT_JSONP => [
  954. 'class' => 'yii\web\JsonResponseFormatter',
  955. 'useJsonp' => true,
  956. ],
  957. ];
  958. }
  959. /**
  960. * Prepares for sending the response.
  961. * The default implementation will convert [[data]] into [[content]] and set headers accordingly.
  962. * @throws InvalidConfigException if the formatter for the specified format is invalid or [[format]] is not supported
  963. */
  964. protected function prepare()
  965. {
  966. if ($this->stream !== null) {
  967. return;
  968. }
  969. if (isset($this->formatters[$this->format])) {
  970. $formatter = $this->formatters[$this->format];
  971. if (!is_object($formatter)) {
  972. $this->formatters[$this->format] = $formatter = Yii::createObject($formatter);
  973. }
  974. if ($formatter instanceof ResponseFormatterInterface) {
  975. $formatter->format($this);
  976. } else {
  977. throw new InvalidConfigException("The '{$this->format}' response formatter is invalid. It must implement the ResponseFormatterInterface.");
  978. }
  979. } elseif ($this->format === self::FORMAT_RAW) {
  980. if ($this->data !== null) {
  981. $this->content = $this->data;
  982. }
  983. } else {
  984. throw new InvalidConfigException("Unsupported response format: {$this->format}");
  985. }
  986. if (is_array($this->content)) {
  987. throw new InvalidArgumentException('Response content must not be an array.');
  988. } elseif (is_object($this->content)) {
  989. if (method_exists($this->content, '__toString')) {
  990. $this->content = $this->content->__toString();
  991. } else {
  992. throw new InvalidArgumentException('Response content must be a string or an object implementing __toString().');
  993. }
  994. }
  995. }
  996. }