Passed
Branch develop (d6f62e)
by Tito
06:29
created
extensions/libraries/redcore/api/oauth2/Response.php 2 patches
Indentation   +351 added lines, -351 removed lines patch added patch discarded remove patch
@@ -13,357 +13,357 @@
 block discarded – undo
13 13
  */
14 14
 class Response implements ResponseInterface
15 15
 {
16
-    public $version;
17
-    protected $statusCode = 200;
18
-    protected $statusText;
19
-    protected $parameters = array();
20
-    protected $httpHeaders = array();
21
-
22
-    public static $statusTexts = array(
23
-        100 => 'Continue',
24
-        101 => 'Switching Protocols',
25
-        200 => 'OK',
26
-        201 => 'Created',
27
-        202 => 'Accepted',
28
-        203 => 'Non-Authoritative Information',
29
-        204 => 'No Content',
30
-        205 => 'Reset Content',
31
-        206 => 'Partial Content',
32
-        300 => 'Multiple Choices',
33
-        301 => 'Moved Permanently',
34
-        302 => 'Found',
35
-        303 => 'See Other',
36
-        304 => 'Not Modified',
37
-        305 => 'Use Proxy',
38
-        307 => 'Temporary Redirect',
39
-        400 => 'Bad Request',
40
-        401 => 'Unauthorized',
41
-        402 => 'Payment Required',
42
-        403 => 'Forbidden',
43
-        404 => 'Not Found',
44
-        405 => 'Method Not Allowed',
45
-        406 => 'Not Acceptable',
46
-        407 => 'Proxy Authentication Required',
47
-        408 => 'Request Timeout',
48
-        409 => 'Conflict',
49
-        410 => 'Gone',
50
-        411 => 'Length Required',
51
-        412 => 'Precondition Failed',
52
-        413 => 'Request Entity Too Large',
53
-        414 => 'Request-URI Too Long',
54
-        415 => 'Unsupported Media Type',
55
-        416 => 'Requested Range Not Satisfiable',
56
-        417 => 'Expectation Failed',
57
-        418 => 'I\'m a teapot',
58
-        500 => 'Internal Server Error',
59
-        501 => 'Not Implemented',
60
-        502 => 'Bad Gateway',
61
-        503 => 'Service Unavailable',
62
-        504 => 'Gateway Timeout',
63
-        505 => 'HTTP Version Not Supported',
64
-    );
65
-
66
-    public function __construct($parameters = array(), $statusCode = 200, $headers = array())
67
-    {
68
-        $this->setParameters($parameters);
69
-        $this->setStatusCode($statusCode);
70
-        $this->setHttpHeaders($headers);
71
-        $this->version = '1.1';
72
-    }
73
-
74
-    /**
75
-     * Converts the response object to string containing all headers and the response content.
76
-     *
77
-     * @return string The response with headers and content
78
-     */
79
-    public function __toString()
80
-    {
81
-        $headers = array();
82
-        foreach ($this->httpHeaders as $name => $value) {
83
-            $headers[$name] = (array) $value;
84
-        }
85
-
86
-        return
87
-            sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
88
-            $this->getHttpHeadersAsString($headers)."\r\n".
89
-            $this->getResponseBody();
90
-    }
91
-
92
-    /**
93
-     * Returns the build header line.
94
-     *
95
-     * @param string $name  The header name
96
-     * @param string $value The header value
97
-     *
98
-     * @return string The built header line
99
-     */
100
-    protected function buildHeader($name, $value)
101
-    {
102
-        return sprintf("%s: %s\n", $name, $value);
103
-    }
104
-
105
-    public function getStatusCode()
106
-    {
107
-        return $this->statusCode;
108
-    }
109
-
110
-    public function setStatusCode($statusCode, $text = null)
111
-    {
112
-        $this->statusCode = (int) $statusCode;
113
-        if ($this->isInvalid()) {
114
-            throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $statusCode));
115
-        }
116
-
117
-        $this->statusText = false === $text ? '' : (null === $text ? self::$statusTexts[$this->statusCode] : $text);
118
-    }
119
-
120
-    public function getStatusText()
121
-    {
122
-        return $this->statusText;
123
-    }
124
-
125
-    public function getParameters()
126
-    {
127
-        return $this->parameters;
128
-    }
129
-
130
-    public function setParameters(array $parameters)
131
-    {
132
-        $this->parameters = $parameters;
133
-    }
134
-
135
-    public function addParameters(array $parameters)
136
-    {
137
-        $this->parameters = array_merge($this->parameters, $parameters);
138
-    }
139
-
140
-    public function getParameter($name, $default = null)
141
-    {
142
-        return isset($this->parameters[$name]) ? $this->parameters[$name] : $default;
143
-    }
144
-
145
-    public function setParameter($name, $value)
146
-    {
147
-        $this->parameters[$name] = $value;
148
-    }
149
-
150
-    public function setHttpHeaders(array $httpHeaders)
151
-    {
152
-        $this->httpHeaders = $httpHeaders;
153
-    }
154
-
155
-    public function setHttpHeader($name, $value)
156
-    {
157
-        $this->httpHeaders[$name] = $value;
158
-    }
159
-
160
-    public function addHttpHeaders(array $httpHeaders)
161
-    {
162
-        $this->httpHeaders = array_merge($this->httpHeaders, $httpHeaders);
163
-    }
164
-
165
-    public function getHttpHeaders()
166
-    {
167
-        return $this->httpHeaders;
168
-    }
169
-
170
-    public function getHttpHeader($name, $default = null)
171
-    {
172
-        return isset($this->httpHeaders[$name]) ? $this->httpHeaders[$name] : $default;
173
-    }
174
-
175
-    public function getResponseBody($format = 'json')
176
-    {
177
-        switch ($format) {
178
-            case 'json':
179
-                return json_encode($this->parameters);
180
-            case 'xml':
181
-                // this only works for single-level arrays
182
-                $xml = new \SimpleXMLElement('<response/>');
183
-                foreach ($this->parameters as $key => $param) {
184
-                    $xml->addChild($key, $param);
185
-                }
186
-
187
-                return $xml->asXML();
188
-        }
189
-
190
-        throw new \InvalidArgumentException(sprintf('The format %s is not supported', $format));
191
-
192
-    }
193
-
194
-    public function send($format = 'json')
195
-    {
196
-        // headers have already been sent by the developer
197
-        if (headers_sent()) {
198
-            return;
199
-        }
200
-
201
-        switch ($format) {
202
-            case 'json':
203
-                $this->setHttpHeader('Content-Type', 'application/json');
204
-                break;
205
-            case 'xml':
206
-                $this->setHttpHeader('Content-Type', 'text/xml');
207
-                break;
208
-        }
209
-        // status
210
-        header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText));
211
-
212
-        foreach ($this->getHttpHeaders() as $name => $header) {
213
-            header(sprintf('%s: %s', $name, $header));
214
-        }
215
-        echo $this->getResponseBody($format);
216
-    }
217
-
218
-    public function setError($statusCode, $error, $errorDescription = null, $errorUri = null)
219
-    {
220
-        $parameters = array(
221
-            'error' => $error,
222
-            'error_description' => $errorDescription,
223
-        );
224
-
225
-        if (!is_null($errorUri)) {
226
-            if (strlen($errorUri) > 0 && $errorUri[0] == '#') {
227
-                // we are referencing an oauth bookmark (for brevity)
228
-                $errorUri = 'http://tools.ietf.org/html/rfc6749' . $errorUri;
229
-            }
230
-            $parameters['error_uri'] = $errorUri;
231
-        }
232
-
233
-        $httpHeaders = array(
234
-            'Cache-Control' => 'no-store'
235
-        );
236
-
237
-        $this->setStatusCode($statusCode);
238
-        $this->addParameters($parameters);
239
-        $this->addHttpHeaders($httpHeaders);
240
-
241
-        if (!$this->isClientError() && !$this->isServerError()) {
242
-            throw new \InvalidArgumentException(sprintf('The HTTP status code is not an error ("%s" given).', $statusCode));
243
-        }
244
-    }
245
-
246
-    public function setRedirect($statusCode, $url, $state = null, $error = null, $errorDescription = null, $errorUri = null)
247
-    {
248
-        if (empty($url)) {
249
-            throw new \InvalidArgumentException('Cannot redirect to an empty URL.');
250
-        }
251
-
252
-        $parameters = array();
253
-
254
-        if (!is_null($state)) {
255
-            $parameters['state'] = $state;
256
-        }
257
-
258
-        if (!is_null($error)) {
259
-            $this->setError(400, $error, $errorDescription, $errorUri);
260
-        }
261
-        $this->setStatusCode($statusCode);
262
-        $this->addParameters($parameters);
263
-
264
-        if (count($this->parameters) > 0) {
265
-            // add parameters to URL redirection
266
-            $parts = parse_url($url);
267
-            $sep = isset($parts['query']) && count($parts['query']) > 0 ? '&' : '?';
268
-            $url .= $sep . http_build_query($this->parameters);
269
-        }
270
-
271
-        $this->addHttpHeaders(array('Location' =>  $url));
272
-
273
-        if (!$this->isRedirection()) {
274
-            throw new \InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $statusCode));
275
-        }
276
-    }
277
-
278
-    // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
279
-    /**
280
-     * @return Boolean
281
-     *
282
-     * @api
283
-     */
284
-    public function isInvalid()
285
-    {
286
-        return $this->statusCode < 100 || $this->statusCode >= 600;
287
-    }
288
-
289
-    /**
290
-     * @return Boolean
291
-     *
292
-     * @api
293
-     */
294
-    public function isInformational()
295
-    {
296
-        return $this->statusCode >= 100 && $this->statusCode < 200;
297
-    }
298
-
299
-    /**
300
-     * @return Boolean
301
-     *
302
-     * @api
303
-     */
304
-    public function isSuccessful()
305
-    {
306
-        return $this->statusCode >= 200 && $this->statusCode < 300;
307
-    }
308
-
309
-    /**
310
-     * @return Boolean
311
-     *
312
-     * @api
313
-     */
314
-    public function isRedirection()
315
-    {
316
-        return $this->statusCode >= 300 && $this->statusCode < 400;
317
-    }
318
-
319
-    /**
320
-     * @return Boolean
321
-     *
322
-     * @api
323
-     */
324
-    public function isClientError()
325
-    {
326
-        return $this->statusCode >= 400 && $this->statusCode < 500;
327
-    }
328
-
329
-    /**
330
-     * @return Boolean
331
-     *
332
-     * @api
333
-     */
334
-    public function isServerError()
335
-    {
336
-        return $this->statusCode >= 500 && $this->statusCode < 600;
337
-    }
338
-
339
-    /*
16
+	public $version;
17
+	protected $statusCode = 200;
18
+	protected $statusText;
19
+	protected $parameters = array();
20
+	protected $httpHeaders = array();
21
+
22
+	public static $statusTexts = array(
23
+		100 => 'Continue',
24
+		101 => 'Switching Protocols',
25
+		200 => 'OK',
26
+		201 => 'Created',
27
+		202 => 'Accepted',
28
+		203 => 'Non-Authoritative Information',
29
+		204 => 'No Content',
30
+		205 => 'Reset Content',
31
+		206 => 'Partial Content',
32
+		300 => 'Multiple Choices',
33
+		301 => 'Moved Permanently',
34
+		302 => 'Found',
35
+		303 => 'See Other',
36
+		304 => 'Not Modified',
37
+		305 => 'Use Proxy',
38
+		307 => 'Temporary Redirect',
39
+		400 => 'Bad Request',
40
+		401 => 'Unauthorized',
41
+		402 => 'Payment Required',
42
+		403 => 'Forbidden',
43
+		404 => 'Not Found',
44
+		405 => 'Method Not Allowed',
45
+		406 => 'Not Acceptable',
46
+		407 => 'Proxy Authentication Required',
47
+		408 => 'Request Timeout',
48
+		409 => 'Conflict',
49
+		410 => 'Gone',
50
+		411 => 'Length Required',
51
+		412 => 'Precondition Failed',
52
+		413 => 'Request Entity Too Large',
53
+		414 => 'Request-URI Too Long',
54
+		415 => 'Unsupported Media Type',
55
+		416 => 'Requested Range Not Satisfiable',
56
+		417 => 'Expectation Failed',
57
+		418 => 'I\'m a teapot',
58
+		500 => 'Internal Server Error',
59
+		501 => 'Not Implemented',
60
+		502 => 'Bad Gateway',
61
+		503 => 'Service Unavailable',
62
+		504 => 'Gateway Timeout',
63
+		505 => 'HTTP Version Not Supported',
64
+	);
65
+
66
+	public function __construct($parameters = array(), $statusCode = 200, $headers = array())
67
+	{
68
+		$this->setParameters($parameters);
69
+		$this->setStatusCode($statusCode);
70
+		$this->setHttpHeaders($headers);
71
+		$this->version = '1.1';
72
+	}
73
+
74
+	/**
75
+	 * Converts the response object to string containing all headers and the response content.
76
+	 *
77
+	 * @return string The response with headers and content
78
+	 */
79
+	public function __toString()
80
+	{
81
+		$headers = array();
82
+		foreach ($this->httpHeaders as $name => $value) {
83
+			$headers[$name] = (array) $value;
84
+		}
85
+
86
+		return
87
+			sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
88
+			$this->getHttpHeadersAsString($headers)."\r\n".
89
+			$this->getResponseBody();
90
+	}
91
+
92
+	/**
93
+	 * Returns the build header line.
94
+	 *
95
+	 * @param string $name  The header name
96
+	 * @param string $value The header value
97
+	 *
98
+	 * @return string The built header line
99
+	 */
100
+	protected function buildHeader($name, $value)
101
+	{
102
+		return sprintf("%s: %s\n", $name, $value);
103
+	}
104
+
105
+	public function getStatusCode()
106
+	{
107
+		return $this->statusCode;
108
+	}
109
+
110
+	public function setStatusCode($statusCode, $text = null)
111
+	{
112
+		$this->statusCode = (int) $statusCode;
113
+		if ($this->isInvalid()) {
114
+			throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $statusCode));
115
+		}
116
+
117
+		$this->statusText = false === $text ? '' : (null === $text ? self::$statusTexts[$this->statusCode] : $text);
118
+	}
119
+
120
+	public function getStatusText()
121
+	{
122
+		return $this->statusText;
123
+	}
124
+
125
+	public function getParameters()
126
+	{
127
+		return $this->parameters;
128
+	}
129
+
130
+	public function setParameters(array $parameters)
131
+	{
132
+		$this->parameters = $parameters;
133
+	}
134
+
135
+	public function addParameters(array $parameters)
136
+	{
137
+		$this->parameters = array_merge($this->parameters, $parameters);
138
+	}
139
+
140
+	public function getParameter($name, $default = null)
141
+	{
142
+		return isset($this->parameters[$name]) ? $this->parameters[$name] : $default;
143
+	}
144
+
145
+	public function setParameter($name, $value)
146
+	{
147
+		$this->parameters[$name] = $value;
148
+	}
149
+
150
+	public function setHttpHeaders(array $httpHeaders)
151
+	{
152
+		$this->httpHeaders = $httpHeaders;
153
+	}
154
+
155
+	public function setHttpHeader($name, $value)
156
+	{
157
+		$this->httpHeaders[$name] = $value;
158
+	}
159
+
160
+	public function addHttpHeaders(array $httpHeaders)
161
+	{
162
+		$this->httpHeaders = array_merge($this->httpHeaders, $httpHeaders);
163
+	}
164
+
165
+	public function getHttpHeaders()
166
+	{
167
+		return $this->httpHeaders;
168
+	}
169
+
170
+	public function getHttpHeader($name, $default = null)
171
+	{
172
+		return isset($this->httpHeaders[$name]) ? $this->httpHeaders[$name] : $default;
173
+	}
174
+
175
+	public function getResponseBody($format = 'json')
176
+	{
177
+		switch ($format) {
178
+			case 'json':
179
+				return json_encode($this->parameters);
180
+			case 'xml':
181
+				// this only works for single-level arrays
182
+				$xml = new \SimpleXMLElement('<response/>');
183
+				foreach ($this->parameters as $key => $param) {
184
+					$xml->addChild($key, $param);
185
+				}
186
+
187
+				return $xml->asXML();
188
+		}
189
+
190
+		throw new \InvalidArgumentException(sprintf('The format %s is not supported', $format));
191
+
192
+	}
193
+
194
+	public function send($format = 'json')
195
+	{
196
+		// headers have already been sent by the developer
197
+		if (headers_sent()) {
198
+			return;
199
+		}
200
+
201
+		switch ($format) {
202
+			case 'json':
203
+				$this->setHttpHeader('Content-Type', 'application/json');
204
+				break;
205
+			case 'xml':
206
+				$this->setHttpHeader('Content-Type', 'text/xml');
207
+				break;
208
+		}
209
+		// status
210
+		header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText));
211
+
212
+		foreach ($this->getHttpHeaders() as $name => $header) {
213
+			header(sprintf('%s: %s', $name, $header));
214
+		}
215
+		echo $this->getResponseBody($format);
216
+	}
217
+
218
+	public function setError($statusCode, $error, $errorDescription = null, $errorUri = null)
219
+	{
220
+		$parameters = array(
221
+			'error' => $error,
222
+			'error_description' => $errorDescription,
223
+		);
224
+
225
+		if (!is_null($errorUri)) {
226
+			if (strlen($errorUri) > 0 && $errorUri[0] == '#') {
227
+				// we are referencing an oauth bookmark (for brevity)
228
+				$errorUri = 'http://tools.ietf.org/html/rfc6749' . $errorUri;
229
+			}
230
+			$parameters['error_uri'] = $errorUri;
231
+		}
232
+
233
+		$httpHeaders = array(
234
+			'Cache-Control' => 'no-store'
235
+		);
236
+
237
+		$this->setStatusCode($statusCode);
238
+		$this->addParameters($parameters);
239
+		$this->addHttpHeaders($httpHeaders);
240
+
241
+		if (!$this->isClientError() && !$this->isServerError()) {
242
+			throw new \InvalidArgumentException(sprintf('The HTTP status code is not an error ("%s" given).', $statusCode));
243
+		}
244
+	}
245
+
246
+	public function setRedirect($statusCode, $url, $state = null, $error = null, $errorDescription = null, $errorUri = null)
247
+	{
248
+		if (empty($url)) {
249
+			throw new \InvalidArgumentException('Cannot redirect to an empty URL.');
250
+		}
251
+
252
+		$parameters = array();
253
+
254
+		if (!is_null($state)) {
255
+			$parameters['state'] = $state;
256
+		}
257
+
258
+		if (!is_null($error)) {
259
+			$this->setError(400, $error, $errorDescription, $errorUri);
260
+		}
261
+		$this->setStatusCode($statusCode);
262
+		$this->addParameters($parameters);
263
+
264
+		if (count($this->parameters) > 0) {
265
+			// add parameters to URL redirection
266
+			$parts = parse_url($url);
267
+			$sep = isset($parts['query']) && count($parts['query']) > 0 ? '&' : '?';
268
+			$url .= $sep . http_build_query($this->parameters);
269
+		}
270
+
271
+		$this->addHttpHeaders(array('Location' =>  $url));
272
+
273
+		if (!$this->isRedirection()) {
274
+			throw new \InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $statusCode));
275
+		}
276
+	}
277
+
278
+	// http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
279
+	/**
280
+	 * @return Boolean
281
+	 *
282
+	 * @api
283
+	 */
284
+	public function isInvalid()
285
+	{
286
+		return $this->statusCode < 100 || $this->statusCode >= 600;
287
+	}
288
+
289
+	/**
290
+	 * @return Boolean
291
+	 *
292
+	 * @api
293
+	 */
294
+	public function isInformational()
295
+	{
296
+		return $this->statusCode >= 100 && $this->statusCode < 200;
297
+	}
298
+
299
+	/**
300
+	 * @return Boolean
301
+	 *
302
+	 * @api
303
+	 */
304
+	public function isSuccessful()
305
+	{
306
+		return $this->statusCode >= 200 && $this->statusCode < 300;
307
+	}
308
+
309
+	/**
310
+	 * @return Boolean
311
+	 *
312
+	 * @api
313
+	 */
314
+	public function isRedirection()
315
+	{
316
+		return $this->statusCode >= 300 && $this->statusCode < 400;
317
+	}
318
+
319
+	/**
320
+	 * @return Boolean
321
+	 *
322
+	 * @api
323
+	 */
324
+	public function isClientError()
325
+	{
326
+		return $this->statusCode >= 400 && $this->statusCode < 500;
327
+	}
328
+
329
+	/**
330
+	 * @return Boolean
331
+	 *
332
+	 * @api
333
+	 */
334
+	public function isServerError()
335
+	{
336
+		return $this->statusCode >= 500 && $this->statusCode < 600;
337
+	}
338
+
339
+	/*
340 340
      * Functions from Symfony2 HttpFoundation - output pretty header
341 341
      */
342
-    private function getHttpHeadersAsString($headers)
343
-    {
344
-        if (count($headers) == 0) {
345
-            return '';
346
-        }
347
-
348
-        $max = max(array_map('strlen', array_keys($headers))) + 1;
349
-        $content = '';
350
-        ksort($headers);
351
-        foreach ($headers as $name => $values) {
352
-            foreach ($values as $value) {
353
-                $content .= sprintf("%-{$max}s %s\r\n", $this->beautifyHeaderName($name).':', $value);
354
-            }
355
-        }
356
-
357
-        return $content;
358
-    }
359
-
360
-    private function beautifyHeaderName($name)
361
-    {
362
-        return preg_replace_callback('/\-(.)/', array($this, 'beautifyCallback'), ucfirst($name));
363
-    }
364
-
365
-    private function beautifyCallback($match)
366
-    {
367
-        return '-'.strtoupper($match[1]);
368
-    }
342
+	private function getHttpHeadersAsString($headers)
343
+	{
344
+		if (count($headers) == 0) {
345
+			return '';
346
+		}
347
+
348
+		$max = max(array_map('strlen', array_keys($headers))) + 1;
349
+		$content = '';
350
+		ksort($headers);
351
+		foreach ($headers as $name => $values) {
352
+			foreach ($values as $value) {
353
+				$content .= sprintf("%-{$max}s %s\r\n", $this->beautifyHeaderName($name).':', $value);
354
+			}
355
+		}
356
+
357
+		return $content;
358
+	}
359
+
360
+	private function beautifyHeaderName($name)
361
+	{
362
+		return preg_replace_callback('/\-(.)/', array($this, 'beautifyCallback'), ucfirst($name));
363
+	}
364
+
365
+	private function beautifyCallback($match)
366
+	{
367
+		return '-'.strtoupper($match[1]);
368
+	}
369 369
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -84,8 +84,8 @@  discard block
 block discarded – undo
84 84
         }
85 85
 
86 86
         return
87
-            sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
88
-            $this->getHttpHeadersAsString($headers)."\r\n".
87
+            sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText) . "\r\n" .
88
+            $this->getHttpHeadersAsString($headers) . "\r\n" .
89 89
             $this->getResponseBody();
90 90
     }
91 91
 
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
         ksort($headers);
351 351
         foreach ($headers as $name => $values) {
352 352
             foreach ($values as $value) {
353
-                $content .= sprintf("%-{$max}s %s\r\n", $this->beautifyHeaderName($name).':', $value);
353
+                $content .= sprintf("%-{$max}s %s\r\n", $this->beautifyHeaderName($name) . ':', $value);
354 354
             }
355 355
         }
356 356
 
@@ -364,6 +364,6 @@  discard block
 block discarded – undo
364 364
 
365 365
     private function beautifyCallback($match)
366 366
     {
367
-        return '-'.strtoupper($match[1]);
367
+        return '-' . strtoupper($match[1]);
368 368
     }
369 369
 }
Please login to merge, or discard this patch.
libraries/redcore/api/oauth2/ResponseType/ResponseTypeInterface.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -4,5 +4,5 @@
 block discarded – undo
4 4
 
5 5
 interface ResponseTypeInterface
6 6
 {
7
-    public function getAuthorizeResponse($params, $user_id = null);
7
+	public function getAuthorizeResponse($params, $user_id = null);
8 8
 }
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/ResponseType/AuthorizationCode.php 1 patch
Indentation   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -10,91 +10,91 @@
 block discarded – undo
10 10
  */
11 11
 class AuthorizationCode implements AuthorizationCodeInterface
12 12
 {
13
-    protected $storage;
14
-    protected $config;
13
+	protected $storage;
14
+	protected $config;
15 15
 
16
-    public function __construct(AuthorizationCodeStorageInterface $storage, array $config = array())
17
-    {
18
-        $this->storage = $storage;
19
-        $this->config = array_merge(array(
20
-            'enforce_redirect' => false,
21
-            'auth_code_lifetime' => 30,
22
-        ), $config);
23
-    }
16
+	public function __construct(AuthorizationCodeStorageInterface $storage, array $config = array())
17
+	{
18
+		$this->storage = $storage;
19
+		$this->config = array_merge(array(
20
+			'enforce_redirect' => false,
21
+			'auth_code_lifetime' => 30,
22
+		), $config);
23
+	}
24 24
 
25
-    public function getAuthorizeResponse($params, $user_id = null)
26
-    {
27
-        // build the URL to redirect to
28
-        $result = array('query' => array());
25
+	public function getAuthorizeResponse($params, $user_id = null)
26
+	{
27
+		// build the URL to redirect to
28
+		$result = array('query' => array());
29 29
 
30
-        $params += array('scope' => null, 'state' => null);
30
+		$params += array('scope' => null, 'state' => null);
31 31
 
32
-        $result['query']['code'] = $this->createAuthorizationCode($params['client_id'], $user_id, $params['redirect_uri'], $params['scope']);
32
+		$result['query']['code'] = $this->createAuthorizationCode($params['client_id'], $user_id, $params['redirect_uri'], $params['scope']);
33 33
 
34
-        if (isset($params['state'])) {
35
-            $result['query']['state'] = $params['state'];
36
-        }
34
+		if (isset($params['state'])) {
35
+			$result['query']['state'] = $params['state'];
36
+		}
37 37
 
38
-        return array($params['redirect_uri'], $result);
39
-    }
38
+		return array($params['redirect_uri'], $result);
39
+	}
40 40
 
41
-    /**
42
-     * Handle the creation of the authorization code.
43
-     *
44
-     * @param $client_id
45
-     * Client identifier related to the authorization code
46
-     * @param $user_id
47
-     * User ID associated with the authorization code
48
-     * @param $redirect_uri
49
-     * An absolute URI to which the authorization server will redirect the
50
-     * user-agent to when the end-user authorization step is completed.
51
-     * @param $scope
52
-     * (optional) Scopes to be stored in space-separated string.
53
-     *
54
-     * @see http://tools.ietf.org/html/rfc6749#section-4
55
-     * @ingroup oauth2_section_4
56
-     */
57
-    public function createAuthorizationCode($client_id, $user_id, $redirect_uri, $scope = null)
58
-    {
59
-        $code = $this->generateAuthorizationCode();
60
-        $this->storage->setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, time() + $this->config['auth_code_lifetime'], $scope);
41
+	/**
42
+	 * Handle the creation of the authorization code.
43
+	 *
44
+	 * @param $client_id
45
+	 * Client identifier related to the authorization code
46
+	 * @param $user_id
47
+	 * User ID associated with the authorization code
48
+	 * @param $redirect_uri
49
+	 * An absolute URI to which the authorization server will redirect the
50
+	 * user-agent to when the end-user authorization step is completed.
51
+	 * @param $scope
52
+	 * (optional) Scopes to be stored in space-separated string.
53
+	 *
54
+	 * @see http://tools.ietf.org/html/rfc6749#section-4
55
+	 * @ingroup oauth2_section_4
56
+	 */
57
+	public function createAuthorizationCode($client_id, $user_id, $redirect_uri, $scope = null)
58
+	{
59
+		$code = $this->generateAuthorizationCode();
60
+		$this->storage->setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, time() + $this->config['auth_code_lifetime'], $scope);
61 61
 
62
-        return $code;
63
-    }
62
+		return $code;
63
+	}
64 64
 
65
-    /**
66
-     * @return
67
-     * TRUE if the grant type requires a redirect_uri, FALSE if not
68
-     */
69
-    public function enforceRedirect()
70
-    {
71
-        return $this->config['enforce_redirect'];
72
-    }
65
+	/**
66
+	 * @return
67
+	 * TRUE if the grant type requires a redirect_uri, FALSE if not
68
+	 */
69
+	public function enforceRedirect()
70
+	{
71
+		return $this->config['enforce_redirect'];
72
+	}
73 73
 
74
-    /**
75
-     * Generates an unique auth code.
76
-     *
77
-     * Implementing classes may want to override this function to implement
78
-     * other auth code generation schemes.
79
-     *
80
-     * @return
81
-     * An unique auth code.
82
-     *
83
-     * @ingroup oauth2_section_4
84
-     */
85
-    protected function generateAuthorizationCode()
86
-    {
87
-        $tokenLen = 40;
88
-        if (function_exists('mcrypt_create_iv')) {
89
-            $randomData = mcrypt_create_iv(100, MCRYPT_DEV_URANDOM);
90
-        } elseif (function_exists('openssl_random_pseudo_bytes')) {
91
-            $randomData = openssl_random_pseudo_bytes(100);
92
-        } elseif (@file_exists('/dev/urandom')) { // Get 100 bytes of random data
93
-            $randomData = file_get_contents('/dev/urandom', false, null, 0, 100) . uniqid(mt_rand(), true);
94
-        } else {
95
-            $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
96
-        }
74
+	/**
75
+	 * Generates an unique auth code.
76
+	 *
77
+	 * Implementing classes may want to override this function to implement
78
+	 * other auth code generation schemes.
79
+	 *
80
+	 * @return
81
+	 * An unique auth code.
82
+	 *
83
+	 * @ingroup oauth2_section_4
84
+	 */
85
+	protected function generateAuthorizationCode()
86
+	{
87
+		$tokenLen = 40;
88
+		if (function_exists('mcrypt_create_iv')) {
89
+			$randomData = mcrypt_create_iv(100, MCRYPT_DEV_URANDOM);
90
+		} elseif (function_exists('openssl_random_pseudo_bytes')) {
91
+			$randomData = openssl_random_pseudo_bytes(100);
92
+		} elseif (@file_exists('/dev/urandom')) { // Get 100 bytes of random data
93
+			$randomData = file_get_contents('/dev/urandom', false, null, 0, 100) . uniqid(mt_rand(), true);
94
+		} else {
95
+			$randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
96
+		}
97 97
 
98
-        return substr(hash('sha512', $randomData), 0, $tokenLen);
99
-    }
98
+		return substr(hash('sha512', $randomData), 0, $tokenLen);
99
+	}
100 100
 }
Please login to merge, or discard this patch.
libraries/redcore/api/oauth2/ResponseType/AccessTokenInterface.php 1 patch
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -8,27 +8,27 @@
 block discarded – undo
8 8
  */
9 9
 interface AccessTokenInterface extends ResponseTypeInterface
10 10
 {
11
-    /**
12
-     * Handle the creation of access token, also issue refresh token if supported / desirable.
13
-     *
14
-     * @param $client_id                client identifier related to the access token.
15
-     * @param $user_id                  user ID associated with the access token
16
-     * @param $scope                    OPTONAL scopes to be stored in space-separated string.
17
-     * @param bool $includeRefreshToken if true, a new refresh_token will be added to the response
18
-     *
19
-     * @see http://tools.ietf.org/html/rfc6749#section-5
20
-     * @ingroup oauth2_section_5
21
-     */
22
-    public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true);
11
+	/**
12
+	 * Handle the creation of access token, also issue refresh token if supported / desirable.
13
+	 *
14
+	 * @param $client_id                client identifier related to the access token.
15
+	 * @param $user_id                  user ID associated with the access token
16
+	 * @param $scope                    OPTONAL scopes to be stored in space-separated string.
17
+	 * @param bool $includeRefreshToken if true, a new refresh_token will be added to the response
18
+	 *
19
+	 * @see http://tools.ietf.org/html/rfc6749#section-5
20
+	 * @ingroup oauth2_section_5
21
+	 */
22
+	public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true);
23 23
 
24
-    /**
25
-     * Handle the revoking of refresh tokens, and access tokens if supported / desirable
26
-     *
27
-     * @param $token
28
-     * @param $tokenTypeHint
29
-     * @return mixed
30
-     *
31
-     * @todo v2.0 include this method in interface. Omitted to maintain BC in v1.x
32
-     */
33
-    //public function revokeToken($token, $tokenTypeHint);
24
+	/**
25
+	 * Handle the revoking of refresh tokens, and access tokens if supported / desirable
26
+	 *
27
+	 * @param $token
28
+	 * @param $tokenTypeHint
29
+	 * @return mixed
30
+	 *
31
+	 * @todo v2.0 include this method in interface. Omitted to maintain BC in v1.x
32
+	 */
33
+	//public function revokeToken($token, $tokenTypeHint);
34 34
 }
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/ResponseType/JwtAccessToken.php 1 patch
Indentation   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -15,110 +15,110 @@
 block discarded – undo
15 15
  */
16 16
 class JwtAccessToken extends AccessToken
17 17
 {
18
-    protected $publicKeyStorage;
19
-    protected $encryptionUtil;
18
+	protected $publicKeyStorage;
19
+	protected $encryptionUtil;
20 20
 
21
-    /**
22
-     * @param $config
23
-     *  - store_encrypted_token_string (bool true)
24
-     *       whether the entire encrypted string is stored,
25
-     *       or just the token ID is stored
26
-     */
27
-    public function __construct(PublicKeyInterface $publicKeyStorage = null, AccessTokenStorageInterface $tokenStorage = null, RefreshTokenInterface $refreshStorage = null, array $config = array(), EncryptionInterface $encryptionUtil = null)
28
-    {
29
-        $this->publicKeyStorage = $publicKeyStorage;
30
-        $config = array_merge(array(
31
-            'store_encrypted_token_string' => true,
32
-            'issuer' => ''
33
-        ), $config);
34
-        if (is_null($tokenStorage)) {
35
-            // a pass-thru, so we can call the parent constructor
36
-            $tokenStorage = new Memory();
37
-        }
38
-        if (is_null($encryptionUtil)) {
39
-            $encryptionUtil = new Jwt();
40
-        }
41
-        $this->encryptionUtil = $encryptionUtil;
42
-        parent::__construct($tokenStorage, $refreshStorage, $config);
43
-    }
21
+	/**
22
+	 * @param $config
23
+	 *  - store_encrypted_token_string (bool true)
24
+	 *       whether the entire encrypted string is stored,
25
+	 *       or just the token ID is stored
26
+	 */
27
+	public function __construct(PublicKeyInterface $publicKeyStorage = null, AccessTokenStorageInterface $tokenStorage = null, RefreshTokenInterface $refreshStorage = null, array $config = array(), EncryptionInterface $encryptionUtil = null)
28
+	{
29
+		$this->publicKeyStorage = $publicKeyStorage;
30
+		$config = array_merge(array(
31
+			'store_encrypted_token_string' => true,
32
+			'issuer' => ''
33
+		), $config);
34
+		if (is_null($tokenStorage)) {
35
+			// a pass-thru, so we can call the parent constructor
36
+			$tokenStorage = new Memory();
37
+		}
38
+		if (is_null($encryptionUtil)) {
39
+			$encryptionUtil = new Jwt();
40
+		}
41
+		$this->encryptionUtil = $encryptionUtil;
42
+		parent::__construct($tokenStorage, $refreshStorage, $config);
43
+	}
44 44
 
45
-    /**
46
-     * Handle the creation of access token, also issue refresh token if supported / desirable.
47
-     *
48
-     * @param $client_id
49
-     * Client identifier related to the access token.
50
-     * @param $user_id
51
-     * User ID associated with the access token
52
-     * @param $scope
53
-     * (optional) Scopes to be stored in space-separated string.
54
-     * @param bool $includeRefreshToken
55
-     *                                  If true, a new refresh_token will be added to the response
56
-     *
57
-     * @see http://tools.ietf.org/html/rfc6749#section-5
58
-     * @ingroup oauth2_section_5
59
-     */
60
-    public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true)
61
-    {
62
-        // token to encrypt
63
-        $expires = time() + $this->config['access_lifetime'];
64
-        $id = $this->generateAccessToken();
65
-        $jwtAccessToken = array(
66
-            'id'         => $id, // for BC (see #591)
67
-            'jti'        => $id,
68
-            'iss'        => $this->config['issuer'],
69
-            'aud'        => $client_id,
70
-            'sub'        => $user_id,
71
-            'exp'        => $expires,
72
-            'iat'        => time(),
73
-            'token_type' => $this->config['token_type'],
74
-            'scope'      => $scope
75
-        );
45
+	/**
46
+	 * Handle the creation of access token, also issue refresh token if supported / desirable.
47
+	 *
48
+	 * @param $client_id
49
+	 * Client identifier related to the access token.
50
+	 * @param $user_id
51
+	 * User ID associated with the access token
52
+	 * @param $scope
53
+	 * (optional) Scopes to be stored in space-separated string.
54
+	 * @param bool $includeRefreshToken
55
+	 *                                  If true, a new refresh_token will be added to the response
56
+	 *
57
+	 * @see http://tools.ietf.org/html/rfc6749#section-5
58
+	 * @ingroup oauth2_section_5
59
+	 */
60
+	public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true)
61
+	{
62
+		// token to encrypt
63
+		$expires = time() + $this->config['access_lifetime'];
64
+		$id = $this->generateAccessToken();
65
+		$jwtAccessToken = array(
66
+			'id'         => $id, // for BC (see #591)
67
+			'jti'        => $id,
68
+			'iss'        => $this->config['issuer'],
69
+			'aud'        => $client_id,
70
+			'sub'        => $user_id,
71
+			'exp'        => $expires,
72
+			'iat'        => time(),
73
+			'token_type' => $this->config['token_type'],
74
+			'scope'      => $scope
75
+		);
76 76
 
77
-        /*
77
+		/*
78 78
          * Encode the token data into a single access_token string
79 79
          */
80
-        $access_token = $this->encodeToken($jwtAccessToken, $client_id);
80
+		$access_token = $this->encodeToken($jwtAccessToken, $client_id);
81 81
 
82
-        /*
82
+		/*
83 83
          * Save the token to a secondary storage.  This is implemented on the
84 84
          * OAuth2\Storage\JwtAccessToken side, and will not actually store anything,
85 85
          * if no secondary storage has been supplied
86 86
          */
87
-        $token_to_store = $this->config['store_encrypted_token_string'] ? $access_token : $jwtAccessToken['id'];
88
-        $this->tokenStorage->setAccessToken($token_to_store, $client_id, $user_id, $this->config['access_lifetime'] ? time() + $this->config['access_lifetime'] : null, $scope);
87
+		$token_to_store = $this->config['store_encrypted_token_string'] ? $access_token : $jwtAccessToken['id'];
88
+		$this->tokenStorage->setAccessToken($token_to_store, $client_id, $user_id, $this->config['access_lifetime'] ? time() + $this->config['access_lifetime'] : null, $scope);
89 89
 
90
-        // token to return to the client
91
-        $token = array(
92
-            'access_token' => $access_token,
93
-            'expires_in' => $this->config['access_lifetime'],
94
-            'token_type' => $this->config['token_type'],
95
-            'scope' => $scope
96
-        );
90
+		// token to return to the client
91
+		$token = array(
92
+			'access_token' => $access_token,
93
+			'expires_in' => $this->config['access_lifetime'],
94
+			'token_type' => $this->config['token_type'],
95
+			'scope' => $scope
96
+		);
97 97
 
98
-        /*
98
+		/*
99 99
          * Issue a refresh token also, if we support them
100 100
          *
101 101
          * Refresh Tokens are considered supported if an instance of OAuth2\Storage\RefreshTokenInterface
102 102
          * is supplied in the constructor
103 103
          */
104
-        if ($includeRefreshToken && $this->refreshStorage) {
105
-            $refresh_token = $this->generateRefreshToken();
106
-            $expires = 0;
107
-            if ($this->config['refresh_token_lifetime'] > 0) {
108
-                $expires = time() + $this->config['refresh_token_lifetime'];
109
-            }
110
-            $this->refreshStorage->setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope);
111
-            $token['refresh_token'] = $refresh_token;
112
-        }
104
+		if ($includeRefreshToken && $this->refreshStorage) {
105
+			$refresh_token = $this->generateRefreshToken();
106
+			$expires = 0;
107
+			if ($this->config['refresh_token_lifetime'] > 0) {
108
+				$expires = time() + $this->config['refresh_token_lifetime'];
109
+			}
110
+			$this->refreshStorage->setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope);
111
+			$token['refresh_token'] = $refresh_token;
112
+		}
113 113
 
114
-        return $token;
115
-    }
114
+		return $token;
115
+	}
116 116
 
117
-    protected function encodeToken(array $token, $client_id = null)
118
-    {
119
-        $private_key = $this->publicKeyStorage->getPrivateKey($client_id);
120
-        $algorithm   = $this->publicKeyStorage->getEncryptionAlgorithm($client_id);
117
+	protected function encodeToken(array $token, $client_id = null)
118
+	{
119
+		$private_key = $this->publicKeyStorage->getPrivateKey($client_id);
120
+		$algorithm   = $this->publicKeyStorage->getEncryptionAlgorithm($client_id);
121 121
 
122
-        return $this->encryptionUtil->encode($token, $private_key, $algorithm);
123
-    }
122
+		return $this->encryptionUtil->encode($token, $private_key, $algorithm);
123
+	}
124 124
 }
Please login to merge, or discard this patch.
libraries/redcore/api/oauth2/ResponseType/AuthorizationCodeInterface.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -8,23 +8,23 @@
 block discarded – undo
8 8
  */
9 9
 interface AuthorizationCodeInterface extends ResponseTypeInterface
10 10
 {
11
-    /**
12
-     * @return
13
-     * TRUE if the grant type requires a redirect_uri, FALSE if not
14
-     */
15
-    public function enforceRedirect();
11
+	/**
12
+	 * @return
13
+	 * TRUE if the grant type requires a redirect_uri, FALSE if not
14
+	 */
15
+	public function enforceRedirect();
16 16
 
17
-    /**
18
-     * Handle the creation of the authorization code.
19
-     *
20
-     * @param $client_id    client identifier related to the authorization code
21
-     * @param $user_id      user id associated with the authorization code
22
-     * @param $redirect_uri an absolute URI to which the authorization server will redirect the
23
-     *                      user-agent to when the end-user authorization step is completed.
24
-     * @param $scope        OPTIONAL scopes to be stored in space-separated string.
25
-     *
26
-     * @see http://tools.ietf.org/html/rfc6749#section-4
27
-     * @ingroup oauth2_section_4
28
-     */
29
-    public function createAuthorizationCode($client_id, $user_id, $redirect_uri, $scope = null);
17
+	/**
18
+	 * Handle the creation of the authorization code.
19
+	 *
20
+	 * @param $client_id    client identifier related to the authorization code
21
+	 * @param $user_id      user id associated with the authorization code
22
+	 * @param $redirect_uri an absolute URI to which the authorization server will redirect the
23
+	 *                      user-agent to when the end-user authorization step is completed.
24
+	 * @param $scope        OPTIONAL scopes to be stored in space-separated string.
25
+	 *
26
+	 * @see http://tools.ietf.org/html/rfc6749#section-4
27
+	 * @ingroup oauth2_section_4
28
+	 */
29
+	public function createAuthorizationCode($client_id, $user_id, $redirect_uri, $scope = null);
30 30
 }
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/ResponseType/AccessToken.php 1 patch
Indentation   +171 added lines, -171 removed lines patch added patch discarded remove patch
@@ -11,184 +11,184 @@
 block discarded – undo
11 11
  */
12 12
 class AccessToken implements AccessTokenInterface
13 13
 {
14
-    protected $tokenStorage;
15
-    protected $refreshStorage;
16
-    protected $config;
17
-
18
-    /**
19
-     * @param OAuth2\Storage\AccessTokenInterface  $tokenStorage   REQUIRED Storage class for saving access token information
20
-     * @param OAuth2\Storage\RefreshTokenInterface $refreshStorage OPTIONAL Storage class for saving refresh token information
21
-     * @param array                                $config         OPTIONAL Configuration options for the server
22
-     *                                                             <code>
23
-     *                                                             $config = array(
24
-     *                                                             'token_type' => 'bearer',              // token type identifier
25
-     *                                                             'access_lifetime' => 3600,             // time before access token expires
26
-     *                                                             'refresh_token_lifetime' => 1209600,   // time before refresh token expires
27
-     *                                                             );
28
-     *                                                             </endcode>
29
-     */
30
-    public function __construct(AccessTokenStorageInterface $tokenStorage, RefreshTokenInterface $refreshStorage = null, array $config = array())
31
-    {
32
-        $this->tokenStorage = $tokenStorage;
33
-        $this->refreshStorage = $refreshStorage;
34
-
35
-        $this->config = array_merge(array(
36
-            'token_type'             => 'bearer',
37
-            'access_lifetime'        => 3600,
38
-            'refresh_token_lifetime' => 1209600,
39
-        ), $config);
40
-    }
41
-
42
-    public function getAuthorizeResponse($params, $user_id = null)
43
-    {
44
-        // build the URL to redirect to
45
-        $result = array('query' => array());
46
-
47
-        $params += array('scope' => null, 'state' => null);
48
-
49
-        /*
14
+	protected $tokenStorage;
15
+	protected $refreshStorage;
16
+	protected $config;
17
+
18
+	/**
19
+	 * @param OAuth2\Storage\AccessTokenInterface  $tokenStorage   REQUIRED Storage class for saving access token information
20
+	 * @param OAuth2\Storage\RefreshTokenInterface $refreshStorage OPTIONAL Storage class for saving refresh token information
21
+	 * @param array                                $config         OPTIONAL Configuration options for the server
22
+	 *                                                             <code>
23
+	 *                                                             $config = array(
24
+	 *                                                             'token_type' => 'bearer',              // token type identifier
25
+	 *                                                             'access_lifetime' => 3600,             // time before access token expires
26
+	 *                                                             'refresh_token_lifetime' => 1209600,   // time before refresh token expires
27
+	 *                                                             );
28
+	 *                                                             </endcode>
29
+	 */
30
+	public function __construct(AccessTokenStorageInterface $tokenStorage, RefreshTokenInterface $refreshStorage = null, array $config = array())
31
+	{
32
+		$this->tokenStorage = $tokenStorage;
33
+		$this->refreshStorage = $refreshStorage;
34
+
35
+		$this->config = array_merge(array(
36
+			'token_type'             => 'bearer',
37
+			'access_lifetime'        => 3600,
38
+			'refresh_token_lifetime' => 1209600,
39
+		), $config);
40
+	}
41
+
42
+	public function getAuthorizeResponse($params, $user_id = null)
43
+	{
44
+		// build the URL to redirect to
45
+		$result = array('query' => array());
46
+
47
+		$params += array('scope' => null, 'state' => null);
48
+
49
+		/*
50 50
          * a refresh token MUST NOT be included in the fragment
51 51
          *
52 52
          * @see http://tools.ietf.org/html/rfc6749#section-4.2.2
53 53
          */
54
-        $includeRefreshToken = false;
55
-        $result["fragment"] = $this->createAccessToken($params['client_id'], $user_id, $params['scope'], $includeRefreshToken);
56
-
57
-        if (isset($params['state'])) {
58
-            $result["fragment"]["state"] = $params['state'];
59
-        }
60
-
61
-        return array($params['redirect_uri'], $result);
62
-    }
63
-
64
-    /**
65
-     * Handle the creation of access token, also issue refresh token if supported / desirable.
66
-     *
67
-     * @param $client_id                client identifier related to the access token.
68
-     * @param $user_id                  user ID associated with the access token
69
-     * @param $scope                    OPTIONAL scopes to be stored in space-separated string.
70
-     * @param bool $includeRefreshToken if true, a new refresh_token will be added to the response
71
-     *
72
-     * @see http://tools.ietf.org/html/rfc6749#section-5
73
-     * @ingroup oauth2_section_5
74
-     */
75
-    public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true)
76
-    {
77
-        $token = array(
78
-            "access_token" => $this->generateAccessToken(),
79
-            "expires_in" => $this->config['access_lifetime'],
80
-            "token_type" => $this->config['token_type'],
81
-            "scope" => $scope
82
-        );
83
-
84
-        $this->tokenStorage->setAccessToken($token["access_token"], $client_id, $user_id, $this->config['access_lifetime'] ? time() + $this->config['access_lifetime'] : null, $scope);
85
-
86
-        /*
54
+		$includeRefreshToken = false;
55
+		$result["fragment"] = $this->createAccessToken($params['client_id'], $user_id, $params['scope'], $includeRefreshToken);
56
+
57
+		if (isset($params['state'])) {
58
+			$result["fragment"]["state"] = $params['state'];
59
+		}
60
+
61
+		return array($params['redirect_uri'], $result);
62
+	}
63
+
64
+	/**
65
+	 * Handle the creation of access token, also issue refresh token if supported / desirable.
66
+	 *
67
+	 * @param $client_id                client identifier related to the access token.
68
+	 * @param $user_id                  user ID associated with the access token
69
+	 * @param $scope                    OPTIONAL scopes to be stored in space-separated string.
70
+	 * @param bool $includeRefreshToken if true, a new refresh_token will be added to the response
71
+	 *
72
+	 * @see http://tools.ietf.org/html/rfc6749#section-5
73
+	 * @ingroup oauth2_section_5
74
+	 */
75
+	public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true)
76
+	{
77
+		$token = array(
78
+			"access_token" => $this->generateAccessToken(),
79
+			"expires_in" => $this->config['access_lifetime'],
80
+			"token_type" => $this->config['token_type'],
81
+			"scope" => $scope
82
+		);
83
+
84
+		$this->tokenStorage->setAccessToken($token["access_token"], $client_id, $user_id, $this->config['access_lifetime'] ? time() + $this->config['access_lifetime'] : null, $scope);
85
+
86
+		/*
87 87
          * Issue a refresh token also, if we support them
88 88
          *
89 89
          * Refresh Tokens are considered supported if an instance of OAuth2\Storage\RefreshTokenInterface
90 90
          * is supplied in the constructor
91 91
          */
92
-        if ($includeRefreshToken && $this->refreshStorage) {
93
-            $token["refresh_token"] = $this->generateRefreshToken();
94
-            $expires = 0;
95
-            if ($this->config['refresh_token_lifetime'] > 0) {
96
-                $expires = time() + $this->config['refresh_token_lifetime'];
97
-            }
98
-            $this->refreshStorage->setRefreshToken($token['refresh_token'], $client_id, $user_id, $expires, $scope);
99
-        }
100
-
101
-        return $token;
102
-    }
103
-
104
-    /**
105
-     * Generates an unique access token.
106
-     *
107
-     * Implementing classes may want to override this function to implement
108
-     * other access token generation schemes.
109
-     *
110
-     * @return
111
-     * An unique access token.
112
-     *
113
-     * @ingroup oauth2_section_4
114
-     */
115
-    protected function generateAccessToken()
116
-    {
117
-        if (function_exists('mcrypt_create_iv')) {
118
-            $randomData = mcrypt_create_iv(20, MCRYPT_DEV_URANDOM);
119
-            if ($randomData !== false && strlen($randomData) === 20) {
120
-                return bin2hex($randomData);
121
-            }
122
-        }
123
-        if (function_exists('openssl_random_pseudo_bytes')) {
124
-            $randomData = openssl_random_pseudo_bytes(20);
125
-            if ($randomData !== false && strlen($randomData) === 20) {
126
-                return bin2hex($randomData);
127
-            }
128
-        }
129
-        if (@file_exists('/dev/urandom')) { // Get 100 bytes of random data
130
-            $randomData = file_get_contents('/dev/urandom', false, null, 0, 20);
131
-            if ($randomData !== false && strlen($randomData) === 20) {
132
-                return bin2hex($randomData);
133
-            }
134
-        }
135
-        // Last resort which you probably should just get rid of:
136
-        $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
137
-
138
-        return substr(hash('sha512', $randomData), 0, 40);
139
-    }
140
-
141
-    /**
142
-     * Generates an unique refresh token
143
-     *
144
-     * Implementing classes may want to override this function to implement
145
-     * other refresh token generation schemes.
146
-     *
147
-     * @return
148
-     * An unique refresh.
149
-     *
150
-     * @ingroup oauth2_section_4
151
-     * @see OAuth2::generateAccessToken()
152
-     */
153
-    protected function generateRefreshToken()
154
-    {
155
-        return $this->generateAccessToken(); // let's reuse the same scheme for token generation
156
-    }
157
-
158
-    /**
159
-     * Handle the revoking of refresh tokens, and access tokens if supported / desirable
160
-     * RFC7009 specifies that "If the server is unable to locate the token using
161
-     * the given hint, it MUST extend its search across all of its supported token types"
162
-     *
163
-     * @param $token
164
-     * @param null $tokenTypeHint
165
-     * @return boolean
166
-     */
167
-    public function revokeToken($token, $tokenTypeHint = null)
168
-    {
169
-        if ($tokenTypeHint == 'refresh_token') {
170
-            if ($this->refreshStorage && $revoked = $this->refreshStorage->unsetRefreshToken($token)) {
171
-                return true;
172
-            }
173
-        }
174
-
175
-        /** @TODO remove in v2 */
176
-        if (!method_exists($this->tokenStorage, 'unsetAccessToken')) {
177
-            throw new \RuntimeException(
178
-                sprintf('Token storage %s must implement unsetAccessToken method', get_class($this->tokenStorage)
179
-            ));
180
-        }
181
-
182
-        $revoked = $this->tokenStorage->unsetAccessToken($token);
183
-
184
-        // if a typehint is supplied and fails, try other storages 
185
-        // @see https://tools.ietf.org/html/rfc7009#section-2.1
186
-        if (!$revoked && $tokenTypeHint != 'refresh_token') {
187
-            if ($this->refreshStorage) {
188
-                $revoked = $this->refreshStorage->unsetRefreshToken($token);
189
-            }
190
-        }
191
-
192
-        return $revoked;
193
-    }
92
+		if ($includeRefreshToken && $this->refreshStorage) {
93
+			$token["refresh_token"] = $this->generateRefreshToken();
94
+			$expires = 0;
95
+			if ($this->config['refresh_token_lifetime'] > 0) {
96
+				$expires = time() + $this->config['refresh_token_lifetime'];
97
+			}
98
+			$this->refreshStorage->setRefreshToken($token['refresh_token'], $client_id, $user_id, $expires, $scope);
99
+		}
100
+
101
+		return $token;
102
+	}
103
+
104
+	/**
105
+	 * Generates an unique access token.
106
+	 *
107
+	 * Implementing classes may want to override this function to implement
108
+	 * other access token generation schemes.
109
+	 *
110
+	 * @return
111
+	 * An unique access token.
112
+	 *
113
+	 * @ingroup oauth2_section_4
114
+	 */
115
+	protected function generateAccessToken()
116
+	{
117
+		if (function_exists('mcrypt_create_iv')) {
118
+			$randomData = mcrypt_create_iv(20, MCRYPT_DEV_URANDOM);
119
+			if ($randomData !== false && strlen($randomData) === 20) {
120
+				return bin2hex($randomData);
121
+			}
122
+		}
123
+		if (function_exists('openssl_random_pseudo_bytes')) {
124
+			$randomData = openssl_random_pseudo_bytes(20);
125
+			if ($randomData !== false && strlen($randomData) === 20) {
126
+				return bin2hex($randomData);
127
+			}
128
+		}
129
+		if (@file_exists('/dev/urandom')) { // Get 100 bytes of random data
130
+			$randomData = file_get_contents('/dev/urandom', false, null, 0, 20);
131
+			if ($randomData !== false && strlen($randomData) === 20) {
132
+				return bin2hex($randomData);
133
+			}
134
+		}
135
+		// Last resort which you probably should just get rid of:
136
+		$randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
137
+
138
+		return substr(hash('sha512', $randomData), 0, 40);
139
+	}
140
+
141
+	/**
142
+	 * Generates an unique refresh token
143
+	 *
144
+	 * Implementing classes may want to override this function to implement
145
+	 * other refresh token generation schemes.
146
+	 *
147
+	 * @return
148
+	 * An unique refresh.
149
+	 *
150
+	 * @ingroup oauth2_section_4
151
+	 * @see OAuth2::generateAccessToken()
152
+	 */
153
+	protected function generateRefreshToken()
154
+	{
155
+		return $this->generateAccessToken(); // let's reuse the same scheme for token generation
156
+	}
157
+
158
+	/**
159
+	 * Handle the revoking of refresh tokens, and access tokens if supported / desirable
160
+	 * RFC7009 specifies that "If the server is unable to locate the token using
161
+	 * the given hint, it MUST extend its search across all of its supported token types"
162
+	 *
163
+	 * @param $token
164
+	 * @param null $tokenTypeHint
165
+	 * @return boolean
166
+	 */
167
+	public function revokeToken($token, $tokenTypeHint = null)
168
+	{
169
+		if ($tokenTypeHint == 'refresh_token') {
170
+			if ($this->refreshStorage && $revoked = $this->refreshStorage->unsetRefreshToken($token)) {
171
+				return true;
172
+			}
173
+		}
174
+
175
+		/** @TODO remove in v2 */
176
+		if (!method_exists($this->tokenStorage, 'unsetAccessToken')) {
177
+			throw new \RuntimeException(
178
+				sprintf('Token storage %s must implement unsetAccessToken method', get_class($this->tokenStorage)
179
+			));
180
+		}
181
+
182
+		$revoked = $this->tokenStorage->unsetAccessToken($token);
183
+
184
+		// if a typehint is supplied and fails, try other storages 
185
+		// @see https://tools.ietf.org/html/rfc7009#section-2.1
186
+		if (!$revoked && $tokenTypeHint != 'refresh_token') {
187
+			if ($this->refreshStorage) {
188
+				$revoked = $this->refreshStorage->unsetRefreshToken($token);
189
+			}
190
+		}
191
+
192
+		return $revoked;
193
+	}
194 194
 }
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/Encryption/EncryptionInterface.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -4,8 +4,8 @@
 block discarded – undo
4 4
 
5 5
 interface EncryptionInterface
6 6
 {
7
-    public function encode($payload, $key, $algorithm = null);
8
-    public function decode($payload, $key, $algorithm = null);
9
-    public function urlSafeB64Encode($data);
10
-    public function urlSafeB64Decode($b64);
7
+	public function encode($payload, $key, $algorithm = null);
8
+	public function decode($payload, $key, $algorithm = null);
9
+	public function urlSafeB64Encode($data);
10
+	public function urlSafeB64Decode($b64);
11 11
 }
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/Encryption/FirebaseJwt.php 2 patches
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -8,40 +8,40 @@
 block discarded – undo
8 8
  */
9 9
 class FirebaseJwt implements EncryptionInterface
10 10
 {
11
-    public function __construct()
12
-    {
13
-        if (!class_exists('\JWT')) {
14
-            throw new \ErrorException('firebase/php-jwt must be installed to use this feature. You can do this by running "composer require firebase/php-jwt"');
15
-        }
16
-    }
17
-
18
-    public function encode($payload, $key, $alg = 'HS256', $keyId = null)
19
-    {
20
-        return \JWT::encode($payload, $key, $alg, $keyId);
21
-    }
22
-
23
-    public function decode($jwt, $key = null, $allowedAlgorithms = null)
24
-    {
25
-        try {
26
-
27
-            //Maintain BC: Do not verify if no algorithms are passed in.
28
-            if (!$allowedAlgorithms) {
29
-                $key = null;
30
-            }
31
-
32
-            return (array)\JWT::decode($jwt, $key, $allowedAlgorithms);
33
-        } catch (\Exception $e) {
34
-            return false;
35
-        }
36
-    }
37
-
38
-    public function urlSafeB64Encode($data)
39
-    {
40
-        return \JWT::urlsafeB64Encode($data);
41
-    }
42
-
43
-    public function urlSafeB64Decode($b64)
44
-    {
45
-        return \JWT::urlsafeB64Decode($b64);
46
-    }
11
+	public function __construct()
12
+	{
13
+		if (!class_exists('\JWT')) {
14
+			throw new \ErrorException('firebase/php-jwt must be installed to use this feature. You can do this by running "composer require firebase/php-jwt"');
15
+		}
16
+	}
17
+
18
+	public function encode($payload, $key, $alg = 'HS256', $keyId = null)
19
+	{
20
+		return \JWT::encode($payload, $key, $alg, $keyId);
21
+	}
22
+
23
+	public function decode($jwt, $key = null, $allowedAlgorithms = null)
24
+	{
25
+		try {
26
+
27
+			//Maintain BC: Do not verify if no algorithms are passed in.
28
+			if (!$allowedAlgorithms) {
29
+				$key = null;
30
+			}
31
+
32
+			return (array)\JWT::decode($jwt, $key, $allowedAlgorithms);
33
+		} catch (\Exception $e) {
34
+			return false;
35
+		}
36
+	}
37
+
38
+	public function urlSafeB64Encode($data)
39
+	{
40
+		return \JWT::urlsafeB64Encode($data);
41
+	}
42
+
43
+	public function urlSafeB64Decode($b64)
44
+	{
45
+		return \JWT::urlsafeB64Decode($b64);
46
+	}
47 47
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@
 block discarded – undo
29 29
                 $key = null;
30 30
             }
31 31
 
32
-            return (array)\JWT::decode($jwt, $key, $allowedAlgorithms);
32
+            return (array) \JWT::decode($jwt, $key, $allowedAlgorithms);
33 33
         } catch (\Exception $e) {
34 34
             return false;
35 35
         }
Please login to merge, or discard this patch.