summaryrefslogtreecommitdiffstats
path: root/includes/OAuth/Oauth.php
blob: 0ca721d1442b425767857b763ba66727fad0b70d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
<?php

class Oauth {
	
	protected $_client_id;
	protected $_client_secret;
	protected $_callback;
	
	protected $_access_token;
	protected $_access_token_secret;
	protected $_expires;
	
	protected $_scope;
	
	protected $_prefix;
	protected $_authorize_url;
	protected $_access_token_url;
	protected $_request_token_url;
	
	public function __construct($client_id, $client_secret, $callback){
		$this->_client_id = $client_id;
		$this->_client_secret = $client_secret;
		$this->_callback = $callback;
	}
	
	public function setAccessToken($access_token, $access_token_secret = null, $expires = null){
		$this->_access_token = $access_token;
		$this->_access_token_secret = $access_token_secret;
		$this->_expires = $expires;
	}
	
	public function setScope(Array $scope){
		$this->_scope = $scope;
	}
	
	public function makeRequest($url, $method = 'GET', Array $parameters = array(), $returnType = 'json', $includeCallback = false, $includeVerifier = false){
		// set oauth headers for oauth 1.0
		if(isset($this->_request_token_url) && strlen($this->_request_token_url) > 0){
			$headers = $this->getOauthHeaders($includeCallback);
			if($includeVerifier && isset($_GET['oauth_verifier'])){
				$headers['oauth_verifier'] = $_GET['oauth_verifier'];
			}
			$base_info = $this->buildBaseString($url, $method, $headers);
			$composite_key = $this->getCompositeKey();
			$headers['oauth_signature'] = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
			$header = array($this->buildAuthorizationHeader($headers), 'Expect:');
		}
		// add access token to parameter list for oauth 2.0 requests
		else {
			if(isset($_SESSION[$this->_prefix]['access_token'])){
				$parameters['access_token'] = $_SESSION[$this->_prefix]['access_token'];
			}
		}
		
		// create a querystring for GET requests
		if(count($parameters) > 0 && $method == 'GET' && strpos($url, '?') === false){
			$p = array();
			foreach($parameters as $k => $v){
				$p[] = $k . '=' . $v;
			}
			$querystring = implode('&', $p);
			$url = $url . '?' . $querystring;
		}
		
		// set default CURL options
		$options = array(
			CURLOPT_URL => $url,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_SSL_VERIFYPEER => false
		);
		
		// set CURL headers for oauth 1.0 requests
		if(isset($this->_request_token_url) && strlen($this->_request_token_url) > 0){
			$options[CURLOPT_HTTPHEADER] = $header;
			$options[CURLOPT_HEADER] = false;
		}
		
		// set post fields for POST requests
		if($method == 'POST'){
			$options[CURLOPT_POST] = true;
			$options[CURLOPT_POSTFIELDS] = $parameters;
		}
		
		// make CURL request
		$curl = curl_init();
		curl_setopt_array($curl, $options);
		$response = curl_exec($curl);
		$info = curl_getinfo($curl);
		curl_close($curl);
		
		// show error when http_code is not 200
		if($info['http_code'] != 200){
			// mostly errors are thrown when a user has denied access
			unset($_SESSION[$this->_prefix]);
			throw new Exception($response);
		}
		
		// return json decoded array or plain response
		if($returnType == 'json'){
			return json_decode($response, true);
		} else {
			return $response;
		}
	}
	
	public function validateAccessToken(){
		// check if current token has expired
		if(isset($_SESSION[$this->_prefix]['expires']) && $_SESSION[$this->_prefix]['expires'] < time()){
			unset($_SESSION[$this->_prefix]);
			$this->authorize($this->_scope);
			return false;
		}
		// return true if access token is found
		if(isset($_SESSION[$this->_prefix]['access_token']) || (isset($this->_access_token) && strlen($this->_access_token) > 0)){
			$this->_access_token = $_SESSION[$this->_prefix]['access_token'];
			if(isset($_SESSION[$this->_prefix]['access_token_secret'])){
				$this->_access_token_secret = $_SESSION[$this->_prefix]['access_token_secret'];
			}
			if(isset($_SESSION[$this->_prefix]['expires'])){
				$this->_expires = $_SESSION[$this->_prefix]['expires'];
			}
			return true;
		}
		// authorize app if no token is found
		if(!isset($this->_access_token) || strlen($this->_access_token) == 0){
			// handle oauth 1.0 flow
			if(isset($this->_request_token_url) && strlen($this->_request_token_url) > 0){
				// request token and authorize app
				if(!isset($_GET['oauth_token']) && !isset($_GET['oauth_verifier'])){
					$this->requestToken();
					$this->authorize();
					return false;
				}
				// request access token
				else {
					if($_GET['oauth_token'] != $_SESSION[$this->_prefix]['token']){
						unset($_SESSION[$this->_prefix]['token'], $_SESSION[$this->_prefix]['token_secret']);
						return false;
					} else {
						$this->requestAccessToken();
						unset($_SESSION[$this->_prefix]['token'], $_SESSION[$this->_prefix]['token_secret']);
						return true;
					}
				}
			}
			// handle oauth 2.0 flow
			else {
				// authorize app
				if(!isset($_GET['state']) && !isset($_GET['code'])){
					$this->authorize($this->_scope);
					return false;
				}
				// request access token
				else {
					if($_GET['state'] != $_SESSION[$this->_prefix]['state']){
						unset($_SESSION[$this->_prefix]['state']);
						return false;
					} else {
						unset($_SESSION[$this->_prefix]['state']);
						$this->requestAccessToken();
						return true;
					}
				}
			}
		}
	}
	
	protected function requestToken($returnType = 'flat', Array $values = array('oauth_token', 'oauth_token_secret')){
		// make the request
		$response = $this->makeRequest($this->_request_token_url, 'POST', array(), $returnType, true);
		
		// get the correct parameters from the response
		$params = $this->getParameters($response, $returnType);
		
		// add the token and token secret to the session
		if(isset($params[$values[0]]) && isset($params[$values[1]])){
			$_SESSION[$this->_prefix]['token'] = $params[$values[0]];
			$_SESSION[$this->_prefix]['token_secret'] = $params[$values[1]];
		}
		// throw exception if incorrect parameters were returned
		else {
			$s = '';
			foreach($params as $k => $v){$s = $k . '=' . $v;}
			throw new Exception('incorrect access token parameters returned: ' . implode('&', $s));
		}
	}
	
	protected function requestAccessToken($method = 'GET', Array $params = array(), $returnType = 'flat', Array $values = array('access_token', 'expires')){
		// add oauth verifier to parameters for oauth 1.0 request
		if(isset($this->_request_token_url) && strlen($this->_request_token_url) > 0){
			$parameters = array('oauth_verifier' => $_GET['oauth_verifier']);
			$parameters = array_merge($parameters, $params);
		}
		// set parameters for oauth 2.0 request
		else {
			$parameters = array(
				'client_id' => $this->_client_id,
				'redirect_uri' => $this->_callback,
				'client_secret' => $this->_client_secret,
				'code' => $_GET['code']
			);
			$parameters = array_merge($parameters, $params);
		}
		
		// make the request
		$response = $this->makeRequest($this->_access_token_url, $method, $parameters, $returnType, false);
		
		// get the correct parameters from the response
		$params = $this->getParameters($response, $returnType);
		
		// add the token to the session
		if(isset($params[$values[0]]) && isset($params[$values[1]])){
			if(isset($this->_request_token_url) && strlen($this->_request_token_url) > 0){
				$_SESSION[$this->_prefix]['access_token'] = $params[$values[0]];
				$_SESSION[$this->_prefix]['access_token_secret'] = $params[$values[1]];
			} else {
				$_SESSION[$this->_prefix]['access_token'] = $params[$values[0]];
				$_SESSION[$this->_prefix]['expires'] = time() + $params[$values[1]];
			}
		}
		// throw exception if incorrect parameters were returned
		else {
			$s = '';
			foreach($params as $k => $v){$s = $k . '=' . $v;}
			throw new Exception('incorrect access token parameters returned: ' . implode('&', $s));
		}
	}
	
	protected function authorize(Array $scope = array(), $scope_seperator = ',', $attach = null){
		// build authorize url for oauth 1.0 requests
		if(isset($this->_request_token_url) && strlen($this->_request_token_url) > 0){
			$this->_authorize_url .= '?oauth_token=' . $_SESSION[$this->_prefix]['token'];
		}
		// build authorize url for oauth 2.0 requests
		else {
			$this->_authorize_url .= '?client_id=' . $this->_client_id . '&redirect_uri=' . $this->_callback;
			$state = md5(time() . mt_rand());
			$_SESSION[$this->_prefix]['state'] = $state;
			$this->_authorize_url .= '&state=' . $state . '&scope=' . implode($scope_seperator, $scope) . $attach;
		}
		// redirect
		header('Location: ' . $this->_authorize_url);exit;
	}
	
	private function getParameters($response, $returnType){
		if($returnType != 'json'){
			$r = explode('&', $response);
			$params = array();
			foreach($r as $v){
				$param = explode('=', $v);
				$params[$param[0]] = $param[1];
			}
		} else {
			$params = $response;
		}
		return $params;
	}
	
	private function getCompositeKey(){
		if(isset($this->_access_token_secret) && strlen($this->_access_token_secret) > 0){
			$composite_key = rawurlencode($this->_client_secret) . '&' . rawurlencode($this->_access_token_secret);
		} else if(isset($_SESSION[$this->_prefix]['token_secret'])){
			$composite_key = rawurlencode($this->_client_secret) . '&' . rawurlencode($_SESSION[$this->_prefix]['token_secret']);
		} else {
			$composite_key = rawurlencode($this->_client_secret) . '&';
		}
		return $composite_key;
	}
	
	private function getOauthHeaders($includeCallback = false){
		$oauth = array(
			'oauth_consumer_key' => $this->_client_id,
			'oauth_nonce' => time(),
			'oauth_signature_method' => 'HMAC-SHA1',
			'oauth_timestamp' => time(),
			'oauth_version' => '1.0'
		);
		if(isset($this->_access_token)){
			$oauth['oauth_token'] = $this->_access_token;
		} else if(isset($_SESSION[$this->_prefix]['token'])){
			$oauth['oauth_token'] = $_SESSION[$this->_prefix]['token'];
		}
		if($includeCallback){
			$oauth['oauth_callback'] = $this->_callback;
		}
		return $oauth;
	}
	
	private function buildBaseString($baseURI, $method, $params){
		$r = array();
		ksort($params);
		foreach($params as $key => $value){
			$r[] = $key . '=' . rawurlencode($value);
		}
		return $method . '&' . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
	}
	
	private function buildAuthorizationHeader($oauth){
		$r = 'Authorization: OAuth ';
		$values = array();
		foreach($oauth as $key => $value){
			$values[] = $key . '="' . rawurlencode($value) . '"';
		}
		$r .= implode(', ', $values);
		return $r;
	}
	
}