Passed
Push — master ( cd7372...773ce9 )
by Roeland
08:46
created

Response   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 358
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 74
dl 0
loc 358
rs 10
c 0
b 0
f 0
wmc 30

24 Methods

Rating   Name   Duplication   Size   Complexity  
A getStatus() 0 2 1
A addHeader() 0 12 2
A setFeaturePolicy() 0 4 1
A getETag() 0 2 1
A getContentSecurityPolicy() 0 2 1
A cacheFor() 0 20 2
A throttle() 0 3 1
A addCookie() 0 3 1
A render() 0 2 1
A getThrottleMetadata() 0 2 1
A setLastModified() 0 4 1
A setETag() 0 4 1
A invalidateCookies() 0 5 2
A getFeaturePolicy() 0 2 1
A setContentSecurityPolicy() 0 3 1
A invalidateCookie() 0 3 1
A getCookies() 0 2 1
A setHeaders() 0 4 1
A setStatus() 0 4 1
A getHeaders() 0 20 4
A setCookies() 0 3 1
A getLastModified() 0 2 1
A __construct() 0 3 1
A isThrottled() 0 2 1
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Bernhard Posselt <[email protected]>
6
 * @author Christoph Wurst <[email protected]>
7
 * @author Jörn Friedrich Dreyer <[email protected]>
8
 * @author Lukas Reschke <[email protected]>
9
 * @author Morris Jobke <[email protected]>
10
 * @author Roeland Jago Douma <[email protected]>
11
 * @author Thomas Müller <[email protected]>
12
 * @author Thomas Tanghus <[email protected]>
13
 *
14
 * @license AGPL-3.0
15
 *
16
 * This code is free software: you can redistribute it and/or modify
17
 * it under the terms of the GNU Affero General Public License, version 3,
18
 * as published by the Free Software Foundation.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23
 * GNU Affero General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU Affero General Public License, version 3,
26
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
27
 *
28
 */
29
30
/**
31
 * Public interface of ownCloud for apps to use.
32
 * AppFramework\HTTP\Response class
33
 */
34
35
namespace OCP\AppFramework\Http;
36
37
use OCP\AppFramework\Http;
38
use OCP\AppFramework\Utility\ITimeFactory;
39
40
/**
41
 * Base class for responses. Also used to just send headers.
42
 *
43
 * It handles headers, HTTP status code, last modified and ETag.
44
 * @since 6.0.0
45
 */
46
class Response {
47
48
	/**
49
	 * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate']
50
	 * @var array
51
	 */
52
	private $headers = array(
53
		'Cache-Control' => 'no-cache, no-store, must-revalidate'
54
	);
55
56
57
	/**
58
	 * Cookies that will be need to be constructed as header
59
	 * @var array
60
	 */
61
	private $cookies = array();
62
63
64
	/**
65
	 * HTTP status code - defaults to STATUS OK
66
	 * @var int
67
	 */
68
	private $status = Http::STATUS_OK;
69
70
71
	/**
72
	 * Last modified date
73
	 * @var \DateTime
74
	 */
75
	private $lastModified;
76
77
78
	/**
79
	 * ETag
80
	 * @var string
81
	 */
82
	private $ETag;
83
84
	/** @var ContentSecurityPolicy|null Used Content-Security-Policy */
85
	private $contentSecurityPolicy = null;
86
87
	/** @var FeaturePolicy */
88
	private $featurePolicy;
89
90
	/** @var bool */
91
	private $throttled = false;
92
	/** @var array */
93
	private $throttleMetadata = [];
94
95
	/**
96
	 * Response constructor.
97
	 *
98
	 * @since 17.0.0
99
	 */
100
	public function __construct() {
101
		$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
102
		$this->setFeaturePolicy(new EmptyFeaturePolicy());
103
	}
104
105
	/**
106
	 * Caches the response
107
	 * @param int $cacheSeconds the amount of seconds that should be cached
108
	 * if 0 then caching will be disabled
109
	 * @return $this
110
	 * @since 6.0.0 - return value was added in 7.0.0
111
	 */
112
	public function cacheFor(int $cacheSeconds) {
113
		if($cacheSeconds > 0) {
114
			$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
115
116
			// Old scool prama caching
117
			$this->addHeader('Pragma', 'public');
118
119
			// Set expires header
120
			$expires = new \DateTime();
121
			/** @var ITimeFactory $time */
122
			$time = \OC::$server->query(ITimeFactory::class);
123
			$expires->setTimestamp($time->getTime());
124
			$expires->add(new \DateInterval('PT'.$cacheSeconds.'S'));
125
			$this->addHeader('Expires', $expires->format(\DateTime::RFC2822));
126
		} else {
127
			$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
128
			unset($this->headers['Expires'], $this->headers['Pragma']);
129
		}
130
131
		return $this;
132
	}
133
134
	/**
135
	 * Adds a new cookie to the response
136
	 * @param string $name The name of the cookie
137
	 * @param string $value The value of the cookie
138
	 * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
139
	 * 									to null cookie will be considered as session
140
	 * 									cookie.
141
	 * @return $this
142
	 * @since 8.0.0
143
	 */
144
	public function addCookie($name, $value, \DateTime $expireDate = null) {
145
		$this->cookies[$name] = array('value' => $value, 'expireDate' => $expireDate);
146
		return $this;
147
	}
148
149
150
	/**
151
	 * Set the specified cookies
152
	 * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
153
	 * @return $this
154
	 * @since 8.0.0
155
	 */
156
	public function setCookies(array $cookies) {
157
		$this->cookies = $cookies;
158
		return $this;
159
	}
160
161
162
	/**
163
	 * Invalidates the specified cookie
164
	 * @param string $name
165
	 * @return $this
166
	 * @since 8.0.0
167
	 */
168
	public function invalidateCookie($name) {
169
		$this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
170
		return $this;
171
	}
172
173
	/**
174
	 * Invalidates the specified cookies
175
	 * @param array $cookieNames array('foo', 'bar')
176
	 * @return $this
177
	 * @since 8.0.0
178
	 */
179
	public function invalidateCookies(array $cookieNames) {
180
		foreach($cookieNames as $cookieName) {
181
			$this->invalidateCookie($cookieName);
182
		}
183
		return $this;
184
	}
185
186
	/**
187
	 * Returns the cookies
188
	 * @return array
189
	 * @since 8.0.0
190
	 */
191
	public function getCookies() {
192
		return $this->cookies;
193
	}
194
195
	/**
196
	 * Adds a new header to the response that will be called before the render
197
	 * function
198
	 * @param string $name The name of the HTTP header
199
	 * @param string $value The value, null will delete it
200
	 * @return $this
201
	 * @since 6.0.0 - return value was added in 7.0.0
202
	 */
203
	public function addHeader($name, $value) {
204
		$name = trim($name);  // always remove leading and trailing whitespace
205
		                      // to be able to reliably check for security
206
		                      // headers
207
208
		if(is_null($value)) {
0 ignored issues
show
introduced by
The condition is_null($value) is always false.
Loading history...
209
			unset($this->headers[$name]);
210
		} else {
211
			$this->headers[$name] = $value;
212
		}
213
214
		return $this;
215
	}
216
217
218
	/**
219
	 * Set the headers
220
	 * @param array $headers value header pairs
221
	 * @return $this
222
	 * @since 8.0.0
223
	 */
224
	public function setHeaders(array $headers) {
225
		$this->headers = $headers;
226
227
		return $this;
228
	}
229
230
231
	/**
232
	 * Returns the set headers
233
	 * @return array the headers
234
	 * @since 6.0.0
235
	 */
236
	public function getHeaders() {
237
		$mergeWith = [];
238
239
		if($this->lastModified) {
240
			$mergeWith['Last-Modified'] =
241
				$this->lastModified->format(\DateTime::RFC2822);
242
		}
243
244
		// Build Content-Security-Policy and use default if none has been specified
245
		if(is_null($this->contentSecurityPolicy)) {
246
			$this->setContentSecurityPolicy(new ContentSecurityPolicy());
247
		}
248
		$this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
249
		$this->headers['Feature-Policy'] = $this->featurePolicy->buildPolicy();
250
251
		if($this->ETag) {
252
			$mergeWith['ETag'] = '"' . $this->ETag . '"';
253
		}
254
255
		return array_merge($mergeWith, $this->headers);
256
	}
257
258
259
	/**
260
	 * By default renders no output
261
	 * @return string
262
	 * @since 6.0.0
263
	 */
264
	public function render() {
265
		return '';
266
	}
267
268
269
	/**
270
	 * Set response status
271
	 * @param int $status a HTTP status code, see also the STATUS constants
272
	 * @return Response Reference to this object
273
	 * @since 6.0.0 - return value was added in 7.0.0
274
	 */
275
	public function setStatus($status) {
276
		$this->status = $status;
277
278
		return $this;
279
	}
280
281
	/**
282
	 * Set a Content-Security-Policy
283
	 * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
284
	 * @return $this
285
	 * @since 8.1.0
286
	 */
287
	public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
288
		$this->contentSecurityPolicy = $csp;
0 ignored issues
show
Documentation Bug introduced by
$csp is of type OCP\AppFramework\Http\EmptyContentSecurityPolicy, but the property $contentSecurityPolicy was declared to be of type OCP\AppFramework\Http\ContentSecurityPolicy|null. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
289
		return $this;
290
	}
291
292
	/**
293
	 * Get the currently used Content-Security-Policy
294
	 * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
295
	 *                                    none specified.
296
	 * @since 8.1.0
297
	 */
298
	public function getContentSecurityPolicy() {
299
		return $this->contentSecurityPolicy;
300
	}
301
302
303
	/**
304
	 * @since 17.0.0
305
	 */
306
	public function getFeaturePolicy(): EmptyFeaturePolicy {
307
		return $this->featurePolicy;
308
	}
309
310
	/**
311
	 * @since 17.0.0
312
	 */
313
	public function setFeaturePolicy(EmptyFeaturePolicy $featurePolicy): self {
314
		$this->featurePolicy = $featurePolicy;
0 ignored issues
show
Documentation Bug introduced by
$featurePolicy is of type OCP\AppFramework\Http\EmptyFeaturePolicy, but the property $featurePolicy was declared to be of type OCP\AppFramework\Http\FeaturePolicy. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
315
316
		return $this;
317
	}
318
319
320
321
	/**
322
	 * Get response status
323
	 * @since 6.0.0
324
	 */
325
	public function getStatus() {
326
		return $this->status;
327
	}
328
329
330
	/**
331
	 * Get the ETag
332
	 * @return string the etag
333
	 * @since 6.0.0
334
	 */
335
	public function getETag() {
336
		return $this->ETag;
337
	}
338
339
340
	/**
341
	 * Get "last modified" date
342
	 * @return \DateTime RFC2822 formatted last modified date
343
	 * @since 6.0.0
344
	 */
345
	public function getLastModified() {
346
		return $this->lastModified;
347
	}
348
349
350
	/**
351
	 * Set the ETag
352
	 * @param string $ETag
353
	 * @return Response Reference to this object
354
	 * @since 6.0.0 - return value was added in 7.0.0
355
	 */
356
	public function setETag($ETag) {
357
		$this->ETag = $ETag;
358
359
		return $this;
360
	}
361
362
363
	/**
364
	 * Set "last modified" date
365
	 * @param \DateTime $lastModified
366
	 * @return Response Reference to this object
367
	 * @since 6.0.0 - return value was added in 7.0.0
368
	 */
369
	public function setLastModified($lastModified) {
370
		$this->lastModified = $lastModified;
371
372
		return $this;
373
	}
374
375
	/**
376
	 * Marks the response as to throttle. Will be throttled when the
377
	 * @BruteForceProtection annotation is added.
378
	 *
379
	 * @param array $metadata
380
	 * @since 12.0.0
381
	 */
382
	public function throttle(array $metadata = []) {
383
		$this->throttled = true;
384
		$this->throttleMetadata = $metadata;
385
	}
386
387
	/**
388
	 * Returns the throttle metadata, defaults to empty array
389
	 *
390
	 * @return array
391
	 * @since 13.0.0
392
	 */
393
	public function getThrottleMetadata() {
394
		return $this->throttleMetadata;
395
	}
396
397
	/**
398
	 * Whether the current response is throttled.
399
	 *
400
	 * @since 12.0.0
401
	 */
402
	public function isThrottled() {
403
		return $this->throttled;
404
	}
405
}
406