Response.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Clement Wong <git@clement.hk>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Thomas Tanghus <thomas@tanghus.net>
  15. * @author Kate Döen <kate.doeen@nextcloud.com>
  16. *
  17. * @license AGPL-3.0
  18. *
  19. * This code is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License, version 3,
  21. * as published by the Free Software Foundation.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License, version 3,
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>
  30. *
  31. */
  32. namespace OCP\AppFramework\Http;
  33. use OCP\AppFramework\Http;
  34. use OCP\AppFramework\Utility\ITimeFactory;
  35. use OCP\IConfig;
  36. use OCP\IRequest;
  37. use Psr\Log\LoggerInterface;
  38. /**
  39. * Base class for responses. Also used to just send headers.
  40. *
  41. * It handles headers, HTTP status code, last modified and ETag.
  42. * @since 6.0.0
  43. * @template S of int
  44. * @template H of array<string, mixed>
  45. */
  46. class Response {
  47. /**
  48. * Headers
  49. * @var H
  50. */
  51. private $headers;
  52. /**
  53. * Cookies that will be need to be constructed as header
  54. * @var array
  55. */
  56. private $cookies = [];
  57. /**
  58. * HTTP status code - defaults to STATUS OK
  59. * @var S
  60. */
  61. private $status;
  62. /**
  63. * Last modified date
  64. * @var \DateTime
  65. */
  66. private $lastModified;
  67. /**
  68. * ETag
  69. * @var string
  70. */
  71. private $ETag;
  72. /** @var ContentSecurityPolicy|null Used Content-Security-Policy */
  73. private $contentSecurityPolicy = null;
  74. /** @var FeaturePolicy */
  75. private $featurePolicy;
  76. /** @var bool */
  77. private $throttled = false;
  78. /** @var array */
  79. private $throttleMetadata = [];
  80. /**
  81. * @param S $status
  82. * @param H $headers
  83. * @since 17.0.0
  84. */
  85. public function __construct(int $status = Http::STATUS_OK, array $headers = []) {
  86. $this->setStatus($status);
  87. $this->setHeaders($headers);
  88. }
  89. /**
  90. * Caches the response
  91. *
  92. * @param int $cacheSeconds amount of seconds the response is fresh, 0 to disable cache.
  93. * @param bool $public whether the page should be cached by public proxy. Usually should be false, unless this is a static resources.
  94. * @param bool $immutable whether browser should treat the resource as immutable and not ask the server for each page load if the resource changed.
  95. * @return $this
  96. * @since 6.0.0 - return value was added in 7.0.0
  97. */
  98. public function cacheFor(int $cacheSeconds, bool $public = false, bool $immutable = false) {
  99. if ($cacheSeconds > 0) {
  100. $cacheStore = $public ? 'public' : 'private';
  101. $this->addHeader('Cache-Control', sprintf('%s, max-age=%s, %s', $cacheStore, $cacheSeconds, ($immutable ? 'immutable' : 'must-revalidate')));
  102. // Set expires header
  103. $expires = new \DateTime();
  104. /** @var ITimeFactory $time */
  105. $time = \OCP\Server::get(ITimeFactory::class);
  106. $expires->setTimestamp($time->getTime());
  107. $expires->add(new \DateInterval('PT'.$cacheSeconds.'S'));
  108. $this->addHeader('Expires', $expires->format(\DateTimeInterface::RFC2822));
  109. } else {
  110. $this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
  111. unset($this->headers['Expires']);
  112. }
  113. return $this;
  114. }
  115. /**
  116. * Adds a new cookie to the response
  117. * @param string $name The name of the cookie
  118. * @param string $value The value of the cookie
  119. * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
  120. * to null cookie will be considered as session
  121. * cookie.
  122. * @param string $sameSite The samesite value of the cookie. Defaults to Lax. Other possibilities are Strict or None
  123. * @return $this
  124. * @since 8.0.0
  125. */
  126. public function addCookie($name, $value, \DateTime $expireDate = null, $sameSite = 'Lax') {
  127. $this->cookies[$name] = ['value' => $value, 'expireDate' => $expireDate, 'sameSite' => $sameSite];
  128. return $this;
  129. }
  130. /**
  131. * Set the specified cookies
  132. * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
  133. * @return $this
  134. * @since 8.0.0
  135. */
  136. public function setCookies(array $cookies) {
  137. $this->cookies = $cookies;
  138. return $this;
  139. }
  140. /**
  141. * Invalidates the specified cookie
  142. * @param string $name
  143. * @return $this
  144. * @since 8.0.0
  145. */
  146. public function invalidateCookie($name) {
  147. $this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
  148. return $this;
  149. }
  150. /**
  151. * Invalidates the specified cookies
  152. * @param array $cookieNames array('foo', 'bar')
  153. * @return $this
  154. * @since 8.0.0
  155. */
  156. public function invalidateCookies(array $cookieNames) {
  157. foreach ($cookieNames as $cookieName) {
  158. $this->invalidateCookie($cookieName);
  159. }
  160. return $this;
  161. }
  162. /**
  163. * Returns the cookies
  164. * @return array
  165. * @since 8.0.0
  166. */
  167. public function getCookies() {
  168. return $this->cookies;
  169. }
  170. /**
  171. * Adds a new header to the response that will be called before the render
  172. * function
  173. * @param string $name The name of the HTTP header
  174. * @param string $value The value, null will delete it
  175. * @return $this
  176. * @since 6.0.0 - return value was added in 7.0.0
  177. */
  178. public function addHeader($name, $value) {
  179. $name = trim($name); // always remove leading and trailing whitespace
  180. // to be able to reliably check for security
  181. // headers
  182. if ($this->status === Http::STATUS_NOT_MODIFIED
  183. && stripos($name, 'x-') === 0) {
  184. /** @var IConfig $config */
  185. $config = \OC::$server->get(IConfig::class);
  186. if ($config->getSystemValueBool('debug', false)) {
  187. \OC::$server->get(LoggerInterface::class)->error('Setting custom header on a 204 or 304 is not supported (Header: {header})', [
  188. 'header' => $name,
  189. ]);
  190. }
  191. }
  192. if (is_null($value)) {
  193. unset($this->headers[$name]);
  194. } else {
  195. $this->headers[$name] = $value;
  196. }
  197. return $this;
  198. }
  199. /**
  200. * Set the headers
  201. * @template NewH as array<string, mixed>
  202. * @param NewH $headers value header pairs
  203. * @psalm-this-out static<S, NewH>
  204. * @return static
  205. * @since 8.0.0
  206. */
  207. public function setHeaders(array $headers): static {
  208. /** @psalm-suppress InvalidPropertyAssignmentValue Expected due to @psalm-this-out */
  209. $this->headers = $headers;
  210. return $this;
  211. }
  212. /**
  213. * Returns the set headers
  214. * @return array{X-Request-Id: string, Cache-Control: string, Content-Security-Policy: string, Feature-Policy: string, X-Robots-Tag: string, Last-Modified?: string, ETag?: string, ...H} the headers
  215. * @since 6.0.0
  216. */
  217. public function getHeaders() {
  218. /** @var IRequest $request */
  219. /**
  220. * @psalm-suppress UndefinedClass
  221. */
  222. $request = \OC::$server->get(IRequest::class);
  223. $mergeWith = [
  224. 'X-Request-Id' => $request->getId(),
  225. 'Cache-Control' => 'no-cache, no-store, must-revalidate',
  226. 'Content-Security-Policy' => $this->getContentSecurityPolicy()->buildPolicy(),
  227. 'Feature-Policy' => $this->getFeaturePolicy()->buildPolicy(),
  228. 'X-Robots-Tag' => 'noindex, nofollow',
  229. ];
  230. if ($this->lastModified) {
  231. $mergeWith['Last-Modified'] = $this->lastModified->format(\DateTimeInterface::RFC2822);
  232. }
  233. if ($this->ETag) {
  234. $mergeWith['ETag'] = '"' . $this->ETag . '"';
  235. }
  236. return array_merge($mergeWith, $this->headers);
  237. }
  238. /**
  239. * By default renders no output
  240. * @return string
  241. * @since 6.0.0
  242. */
  243. public function render() {
  244. return '';
  245. }
  246. /**
  247. * Set response status
  248. * @template NewS as int
  249. * @param NewS $status a HTTP status code, see also the STATUS constants
  250. * @psalm-this-out static<NewS, H>
  251. * @return static
  252. * @since 6.0.0 - return value was added in 7.0.0
  253. */
  254. public function setStatus($status): static {
  255. /** @psalm-suppress InvalidPropertyAssignmentValue Expected due to @psalm-this-out */
  256. $this->status = $status;
  257. return $this;
  258. }
  259. /**
  260. * Set a Content-Security-Policy
  261. * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
  262. * @return $this
  263. * @since 8.1.0
  264. */
  265. public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
  266. $this->contentSecurityPolicy = $csp;
  267. return $this;
  268. }
  269. /**
  270. * Get the currently used Content-Security-Policy
  271. * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
  272. * none specified.
  273. * @since 8.1.0
  274. */
  275. public function getContentSecurityPolicy() {
  276. if ($this->contentSecurityPolicy === null) {
  277. $this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
  278. }
  279. return $this->contentSecurityPolicy;
  280. }
  281. /**
  282. * @since 17.0.0
  283. */
  284. public function getFeaturePolicy(): EmptyFeaturePolicy {
  285. if ($this->featurePolicy === null) {
  286. $this->setFeaturePolicy(new EmptyFeaturePolicy());
  287. }
  288. return $this->featurePolicy;
  289. }
  290. /**
  291. * @since 17.0.0
  292. */
  293. public function setFeaturePolicy(EmptyFeaturePolicy $featurePolicy): self {
  294. $this->featurePolicy = $featurePolicy;
  295. return $this;
  296. }
  297. /**
  298. * Get response status
  299. * @since 6.0.0
  300. * @return S
  301. */
  302. public function getStatus() {
  303. return $this->status;
  304. }
  305. /**
  306. * Get the ETag
  307. * @return string the etag
  308. * @since 6.0.0
  309. */
  310. public function getETag() {
  311. return $this->ETag;
  312. }
  313. /**
  314. * Get "last modified" date
  315. * @return \DateTime RFC2822 formatted last modified date
  316. * @since 6.0.0
  317. */
  318. public function getLastModified() {
  319. return $this->lastModified;
  320. }
  321. /**
  322. * Set the ETag
  323. * @param string $ETag
  324. * @return Response Reference to this object
  325. * @since 6.0.0 - return value was added in 7.0.0
  326. */
  327. public function setETag($ETag) {
  328. $this->ETag = $ETag;
  329. return $this;
  330. }
  331. /**
  332. * Set "last modified" date
  333. * @param \DateTime $lastModified
  334. * @return Response Reference to this object
  335. * @since 6.0.0 - return value was added in 7.0.0
  336. */
  337. public function setLastModified($lastModified) {
  338. $this->lastModified = $lastModified;
  339. return $this;
  340. }
  341. /**
  342. * Marks the response as to throttle. Will be throttled when the
  343. * @BruteForceProtection annotation is added.
  344. *
  345. * @param array $metadata
  346. * @since 12.0.0
  347. */
  348. public function throttle(array $metadata = []) {
  349. $this->throttled = true;
  350. $this->throttleMetadata = $metadata;
  351. }
  352. /**
  353. * Returns the throttle metadata, defaults to empty array
  354. *
  355. * @return array
  356. * @since 13.0.0
  357. */
  358. public function getThrottleMetadata() {
  359. return $this->throttleMetadata;
  360. }
  361. /**
  362. * Whether the current response is throttled.
  363. *
  364. * @since 12.0.0
  365. */
  366. public function isThrottled() {
  367. return $this->throttled;
  368. }
  369. }