Response.php 9.6 KB

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