Passed
Push — master ( 34aa51...29d78e )
by Roeland
12:50 queued 10s
created

Response   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 335
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 68
dl 0
loc 335
rs 10
c 0
b 0
f 0
wmc 28

22 Methods

Rating   Name   Duplication   Size   Complexity  
A getStatus() 0 2 1
A addHeader() 0 12 2
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 getThrottleMetadata() 0 2 1
A render() 0 2 1
A setLastModified() 0 4 1
A invalidateCookies() 0 5 2
A setETag() 0 4 1
A setContentSecurityPolicy() 0 3 1
A invalidateCookie() 0 3 1
A setHeaders() 0 4 1
A getCookies() 0 2 1
A setStatus() 0 4 1
A getHeaders() 0 19 4
A getLastModified() 0 2 1
A setCookies() 0 3 1
A __construct() 0 2 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 bool */
88
	private $throttled = false;
89
	/** @var array */
90
	private $throttleMetadata = [];
91
92
	/**
93
	 * Response constructor.
94
	 *
95
	 * @since 17.0.0
96
	 */
97
	public function __construct() {
98
		$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
99
	}
100
101
	/**
102
	 * Caches the response
103
	 * @param int $cacheSeconds the amount of seconds that should be cached
104
	 * if 0 then caching will be disabled
105
	 * @return $this
106
	 * @since 6.0.0 - return value was added in 7.0.0
107
	 */
108
	public function cacheFor(int $cacheSeconds) {
109
		if($cacheSeconds > 0) {
110
			$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
111
112
			// Old scool prama caching
113
			$this->addHeader('Pragma', 'public');
114
115
			// Set expires header
116
			$expires = new \DateTime();
117
			/** @var ITimeFactory $time */
118
			$time = \OC::$server->query(ITimeFactory::class);
119
			$expires->setTimestamp($time->getTime());
120
			$expires->add(new \DateInterval('PT'.$cacheSeconds.'S'));
121
			$this->addHeader('Expires', $expires->format(\DateTime::RFC2822));
122
		} else {
123
			$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
124
			unset($this->headers['Expires'], $this->headers['Pragma']);
125
		}
126
127
		return $this;
128
	}
129
130
	/**
131
	 * Adds a new cookie to the response
132
	 * @param string $name The name of the cookie
133
	 * @param string $value The value of the cookie
134
	 * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
135
	 * 									to null cookie will be considered as session
136
	 * 									cookie.
137
	 * @return $this
138
	 * @since 8.0.0
139
	 */
140
	public function addCookie($name, $value, \DateTime $expireDate = null) {
141
		$this->cookies[$name] = array('value' => $value, 'expireDate' => $expireDate);
142
		return $this;
143
	}
144
145
146
	/**
147
	 * Set the specified cookies
148
	 * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
149
	 * @return $this
150
	 * @since 8.0.0
151
	 */
152
	public function setCookies(array $cookies) {
153
		$this->cookies = $cookies;
154
		return $this;
155
	}
156
157
158
	/**
159
	 * Invalidates the specified cookie
160
	 * @param string $name
161
	 * @return $this
162
	 * @since 8.0.0
163
	 */
164
	public function invalidateCookie($name) {
165
		$this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
166
		return $this;
167
	}
168
169
	/**
170
	 * Invalidates the specified cookies
171
	 * @param array $cookieNames array('foo', 'bar')
172
	 * @return $this
173
	 * @since 8.0.0
174
	 */
175
	public function invalidateCookies(array $cookieNames) {
176
		foreach($cookieNames as $cookieName) {
177
			$this->invalidateCookie($cookieName);
178
		}
179
		return $this;
180
	}
181
182
	/**
183
	 * Returns the cookies
184
	 * @return array
185
	 * @since 8.0.0
186
	 */
187
	public function getCookies() {
188
		return $this->cookies;
189
	}
190
191
	/**
192
	 * Adds a new header to the response that will be called before the render
193
	 * function
194
	 * @param string $name The name of the HTTP header
195
	 * @param string $value The value, null will delete it
196
	 * @return $this
197
	 * @since 6.0.0 - return value was added in 7.0.0
198
	 */
199
	public function addHeader($name, $value) {
200
		$name = trim($name);  // always remove leading and trailing whitespace
201
		                      // to be able to reliably check for security
202
		                      // headers
203
204
		if(is_null($value)) {
0 ignored issues
show
introduced by
The condition is_null($value) is always false.
Loading history...
205
			unset($this->headers[$name]);
206
		} else {
207
			$this->headers[$name] = $value;
208
		}
209
210
		return $this;
211
	}
212
213
214
	/**
215
	 * Set the headers
216
	 * @param array $headers value header pairs
217
	 * @return $this
218
	 * @since 8.0.0
219
	 */
220
	public function setHeaders(array $headers) {
221
		$this->headers = $headers;
222
223
		return $this;
224
	}
225
226
227
	/**
228
	 * Returns the set headers
229
	 * @return array the headers
230
	 * @since 6.0.0
231
	 */
232
	public function getHeaders() {
233
		$mergeWith = [];
234
235
		if($this->lastModified) {
236
			$mergeWith['Last-Modified'] =
237
				$this->lastModified->format(\DateTime::RFC2822);
238
		}
239
240
		// Build Content-Security-Policy and use default if none has been specified
241
		if(is_null($this->contentSecurityPolicy)) {
242
			$this->setContentSecurityPolicy(new ContentSecurityPolicy());
243
		}
244
		$this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
245
246
		if($this->ETag) {
247
			$mergeWith['ETag'] = '"' . $this->ETag . '"';
248
		}
249
250
		return array_merge($mergeWith, $this->headers);
251
	}
252
253
254
	/**
255
	 * By default renders no output
256
	 * @return string
257
	 * @since 6.0.0
258
	 */
259
	public function render() {
260
		return '';
261
	}
262
263
264
	/**
265
	 * Set response status
266
	 * @param int $status a HTTP status code, see also the STATUS constants
267
	 * @return Response Reference to this object
268
	 * @since 6.0.0 - return value was added in 7.0.0
269
	 */
270
	public function setStatus($status) {
271
		$this->status = $status;
272
273
		return $this;
274
	}
275
276
	/**
277
	 * Set a Content-Security-Policy
278
	 * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
279
	 * @return $this
280
	 * @since 8.1.0
281
	 */
282
	public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
283
		$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...
284
		return $this;
285
	}
286
287
	/**
288
	 * Get the currently used Content-Security-Policy
289
	 * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
290
	 *                                    none specified.
291
	 * @since 8.1.0
292
	 */
293
	public function getContentSecurityPolicy() {
294
		return $this->contentSecurityPolicy;
295
	}
296
297
298
	/**
299
	 * Get response status
300
	 * @since 6.0.0
301
	 */
302
	public function getStatus() {
303
		return $this->status;
304
	}
305
306
307
	/**
308
	 * Get the ETag
309
	 * @return string the etag
310
	 * @since 6.0.0
311
	 */
312
	public function getETag() {
313
		return $this->ETag;
314
	}
315
316
317
	/**
318
	 * Get "last modified" date
319
	 * @return \DateTime RFC2822 formatted last modified date
320
	 * @since 6.0.0
321
	 */
322
	public function getLastModified() {
323
		return $this->lastModified;
324
	}
325
326
327
	/**
328
	 * Set the ETag
329
	 * @param string $ETag
330
	 * @return Response Reference to this object
331
	 * @since 6.0.0 - return value was added in 7.0.0
332
	 */
333
	public function setETag($ETag) {
334
		$this->ETag = $ETag;
335
336
		return $this;
337
	}
338
339
340
	/**
341
	 * Set "last modified" date
342
	 * @param \DateTime $lastModified
343
	 * @return Response Reference to this object
344
	 * @since 6.0.0 - return value was added in 7.0.0
345
	 */
346
	public function setLastModified($lastModified) {
347
		$this->lastModified = $lastModified;
348
349
		return $this;
350
	}
351
352
	/**
353
	 * Marks the response as to throttle. Will be throttled when the
354
	 * @BruteForceProtection annotation is added.
355
	 *
356
	 * @param array $metadata
357
	 * @since 12.0.0
358
	 */
359
	public function throttle(array $metadata = []) {
360
		$this->throttled = true;
361
		$this->throttleMetadata = $metadata;
362
	}
363
364
	/**
365
	 * Returns the throttle metadata, defaults to empty array
366
	 *
367
	 * @return array
368
	 * @since 13.0.0
369
	 */
370
	public function getThrottleMetadata() {
371
		return $this->throttleMetadata;
372
	}
373
374
	/**
375
	 * Whether the current response is throttled.
376
	 *
377
	 * @since 12.0.0
378
	 */
379
	public function isThrottled() {
380
		return $this->throttled;
381
	}
382
}
383