00001 <?php
00002
00003
00004
00005
00006 define("OAUTH2_DEFAULT_EXPIRES_IN", 3600);
00007
00008
00009
00010
00011 define("OAUTH2_DEFAULT_BASE_DOMAIN", '');
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 abstract class OAuth2Client {
00022
00023
00024
00025
00026 protected $conf = array();
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041 public function getVariable($name, $default = NULL) {
00042 return isset($this->conf[$name]) ? $this->conf[$name] : $default;
00043 }
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053
00054
00055 public function setVariable($name, $value) {
00056 $this->conf[$name] = $value;
00057 return $this;
00058 }
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084
00085 public function __construct($config = array()) {
00086
00087 $this->setVariable('base_uri', $config['base_uri']);
00088 unset($config['base_uri']);
00089
00090
00091 foreach (array('code', 'username', 'password') as $name) {
00092 if (isset($config[$name]))
00093 $this->setVariable($name, $config[$name]);
00094 else if (isset($_REQUEST[$name]) && !empty($_REQUEST[$name]))
00095 $this->setVariable($name, $_REQUEST[$name]);
00096 unset($config[$name]);
00097 }
00098
00099
00100 foreach (array('authorize_uri', 'access_token_uri', 'services_uri') as $name) {
00101 if (isset($config[$name]))
00102 if (substr($config[$name], 0, 4) == "http")
00103 $this->setVariable($name, $config[$name]);
00104 else
00105 $this->setVariable($name, $this->getVariable('base_uri') . $config[$name]);
00106 unset($config[$name]);
00107 }
00108
00109
00110 foreach ($config as $name => $value) {
00111 $this->setVariable($name, $value);
00112 }
00113 }
00114
00115
00116
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137
00138
00139
00140
00141
00142
00143
00144
00145 protected function getSessionObject($access_token = NULL) {
00146 $session = NULL;
00147
00148
00149 if (!empty($access_token) && isset($access_token['access_token'])) {
00150 $session['access_token'] = $access_token['access_token'];
00151 $session['base_domain'] = $this->getVariable('base_domain', OAUTH2_DEFAULT_BASE_DOMAIN);
00152 $session['expirse'] = isset($access_token['expires_in']) ? time() + $access_token['expires_in'] : time() + $this->getVariable('expires_in', OAUTH2_DEFAULT_EXPIRES_IN);
00153 $session['refresh_token'] = isset($access_token['refresh_token']) ? $access_token['refresh_token'] : '';
00154 $session['scope'] = isset($access_token['scope']) ? $access_token['scope'] : '';
00155 $session['secret'] = md5(base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), uniqid())));
00156
00157
00158 $sig = self::generateSignature(
00159 $session,
00160 $this->getVariable('client_secret')
00161 );
00162 $session['sig'] = $sig;
00163 }
00164
00165
00166 if (!$session && isset($_REQUEST['session'])) {
00167 $session = json_decode(
00168 get_magic_quotes_gpc()
00169 ? stripslashes($_REQUEST['session'])
00170 : $_REQUEST['session'],
00171 TRUE
00172 );
00173 }
00174
00175 return $session;
00176 }
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188
00189
00190
00191
00192
00193
00194
00195
00196
00197
00198
00199
00200
00201
00202
00203 public function api($path, $method = 'GET', $params = array()) {
00204 if (is_array($method) && empty($params)) {
00205 $params = $method;
00206 $method = 'GET';
00207 }
00208
00209
00210 foreach ($params as $key => $value) {
00211 if (!is_string($value)) {
00212 $params[$key] = json_encode($value);
00213 }
00214 }
00215
00216 $result = json_decode($this->makeOAuth2Request(
00217 $this->getUri($path),
00218 $method,
00219 $params
00220 ), TRUE);
00221
00222
00223 if (is_array($result) && isset($result['error'])) {
00224 $e = new OAuth2Exception($result);
00225 switch ($e->getType()) {
00226
00227 case 'invalid_token':
00228 $this->setSession(NULL);
00229 default:
00230 $this->setSession(NULL);
00231 }
00232 throw $e;
00233 }
00234 return $result;
00235 }
00236
00237
00238
00239
00240
00241
00242 public static $CURL_OPTS = array(
00243 CURLOPT_CONNECTTIMEOUT => 10,
00244 CURLOPT_RETURNTRANSFER => TRUE,
00245 CURLOPT_HEADER => TRUE,
00246 CURLOPT_TIMEOUT => 60,
00247 CURLOPT_USERAGENT => 'oauth2-draft-v10',
00248 CURLOPT_HTTPHEADER => array("Accept: application/json"),
00249 );
00250
00251
00252
00253
00254
00255
00256
00257
00258
00259
00260
00261
00262
00263
00264 public function setSession($session = NULL, $write_cookie = TRUE) {
00265 $this->setVariable('_session', $this->validateSessionObject($session));
00266 $this->setVariable('_session_loaded', TRUE);
00267 if ($write_cookie) {
00268 $this->setCookieFromSession($this->getVariable('_session'));
00269 }
00270 return $this;
00271 }
00272
00273
00274
00275
00276
00277
00278
00279
00280
00281
00282
00283
00284 public function getSession() {
00285 if (!$this->getVariable('_session_loaded')) {
00286 $session = NULL;
00287 $write_cookie = TRUE;
00288
00289
00290 $session = $this->getSessionObject(NULL);
00291 $session = $this->validateSessionObject($session);
00292
00293
00294 if (!$session && $this->getVariable('code')) {
00295 $access_token = $this->getAccessTokenFromAuthorizationCode($this->getVariable('code'));
00296 $session = $this->getSessionObject($access_token);
00297 $session = $this->validateSessionObject($session);
00298 }
00299
00300
00301 if (!$session && $this->getVariable('username') && $this->getVariable('password')) {
00302 $access_token = $this->getAccessTokenFromPassword($this->getVariable('username'), $this->getVariable('password'));
00303 $session = $this->getSessionObject($access_token);
00304 $session = $this->validateSessionObject($session);
00305 }
00306
00307
00308 if (!$session && $this->getVariable('cookie_support')) {
00309 $cookie_name = $this->getSessionCookieName();
00310 if (isset($_COOKIE[$cookie_name])) {
00311 $session = array();
00312 parse_str(trim(
00313 get_magic_quotes_gpc()
00314 ? stripslashes($_COOKIE[$cookie_name])
00315 : $_COOKIE[$cookie_name],
00316 '"'
00317 ), $session);
00318 $session = $this->validateSessionObject($session);
00319
00320 $write_cookie = empty($session);
00321 }
00322 }
00323
00324 $this->setSession($session, $write_cookie);
00325 }
00326
00327 return $this->getVariable('_session');
00328 }
00329
00330
00331
00332
00333
00334
00335
00336
00337
00338
00339 public function getAccessToken() {
00340 $session = $this->getSession();
00341 return isset($session['access_token']) ? $session['access_token'] : NULL;
00342 }
00343
00344
00345
00346
00347
00348
00349
00350
00351
00352
00353
00354
00355
00356
00357
00358 private function getAccessTokenFromAuthorizationCode($code) {
00359 if ($this->getVariable('access_token_uri') && $this->getVariable('client_id') && $this->getVariable('client_secret')) {
00360 return json_decode($this->makeRequest(
00361 $this->getVariable('access_token_uri'),
00362 'POST',
00363 array(
00364 'grant_type' => 'authorization_code',
00365 'client_id' => $this->getVariable('client_id'),
00366 'client_secret' => $this->getVariable('client_secret'),
00367 'code' => $code,
00368 'redirect_uri' => $this->getCurrentUri(),
00369 )
00370 ), TRUE);
00371 }
00372 return NULL;
00373 }
00374
00375
00376
00377
00378
00379
00380
00381
00382
00383
00384
00385
00386
00387
00388
00389
00390
00391 private function getAccessTokenFromPassword($username, $password) {
00392 if ($this->getVariable('access_token_uri') && $this->getVariable('client_id') && $this->getVariable('client_secret')) {
00393 return json_decode($this->makeRequest(
00394 $this->getVariable('access_token_uri'),
00395 'POST',
00396 array(
00397 'grant_type' => 'password',
00398 'client_id' => $this->getVariable('client_id'),
00399 'client_secret' => $this->getVariable('client_secret'),
00400 'username' => $username,
00401 'password' => $password,
00402 )
00403 ), TRUE);
00404 }
00405 return NULL;
00406 }
00407
00408
00409
00410
00411
00412
00413
00414
00415
00416
00417
00418
00419
00420
00421
00422
00423
00424
00425
00426
00427
00428 protected function makeOAuth2Request($path, $method = 'GET', $params = array()) {
00429 if ((!isset($params['oauth_token']) || empty($params['oauth_token'])) && $oauth_token = $this->getAccessToken()) {
00430 $params['oauth_token'] = $oauth_token;
00431 }
00432 return $this->makeRequest($path, $method, $params);
00433 }
00434
00435
00436
00437
00438
00439
00440
00441
00442
00443
00444
00445
00446
00447
00448
00449
00450
00451
00452
00453 protected function makeRequest($path, $method = 'GET', $params = array(), $ch = NULL) {
00454 if (!$ch)
00455 $ch = curl_init();
00456
00457 $opts = self::$CURL_OPTS;
00458 if ($params) {
00459 switch ($method) {
00460 case 'GET':
00461 $path .= '?' . http_build_query($params, NULL, '&');
00462 break;
00463
00464 default:
00465 if ($this->getVariable('file_upload_support')) {
00466 $opts[CURLOPT_POSTFIELDS] = $params;
00467 }
00468 else {
00469 $opts[CURLOPT_POSTFIELDS] = http_build_query($params, NULL, '&');
00470 }
00471 }
00472 }
00473 $opts[CURLOPT_URL] = $path;
00474
00475
00476
00477 if (isset($opts[CURLOPT_HTTPHEADER])) {
00478 $existing_headers = $opts[CURLOPT_HTTPHEADER];
00479 $existing_headers[] = 'Expect:';
00480 $opts[CURLOPT_HTTPHEADER] = $existing_headers;
00481 }
00482 else {
00483 $opts[CURLOPT_HTTPHEADER] = array('Expect:');
00484 }
00485
00486 curl_setopt_array($ch, $opts);
00487 $result = curl_exec($ch);
00488
00489 if (curl_errno($ch) == 60) {
00490 error_log('Invalid or no certificate authority found, using bundled information');
00491 curl_setopt($ch, CURLOPT_CAINFO,
00492 dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
00493 $result = curl_exec($ch);
00494 }
00495
00496 if ($result === FALSE) {
00497 $e = new OAuth2Exception(array(
00498 'code' => curl_errno($ch),
00499 'message' => curl_error($ch),
00500 ));
00501 curl_close($ch);
00502 throw $e;
00503 }
00504 curl_close($ch);
00505
00506
00507 list($headers, $body) = explode("\r\n\r\n", $result);
00508 $headers = explode("\r\n", $headers);
00509
00510
00511 if (strpos($headers[0], 'HTTP/1.1 4') !== FALSE || strpos($headers[0], 'HTTP/1.1 5') !== FALSE) {
00512 $result = array(
00513 'code' => 0,
00514 'message' => '',
00515 );
00516
00517 if (preg_match('/^HTTP\/1.1 ([0-9]{3,3}) (.*)$/', $headers[0], $matches)) {
00518 $result['code'] = $matches[1];
00519 $result['message'] = $matches[2];
00520 }
00521
00522
00523 foreach ($headers as $header) {
00524 if (preg_match("/^WWW-Authenticate:.*error='(.*)'/", $header, $matches)) {
00525 $result['error'] = $matches[1];
00526 }
00527 }
00528
00529 return json_encode($result);
00530 }
00531
00532 return $body;
00533 }
00534
00535
00536
00537
00538
00539
00540
00541 private function getSessionCookieName() {
00542 return 'oauth2_' . $this->getVariable('client_id');
00543 }
00544
00545
00546
00547
00548
00549
00550
00551
00552
00553
00554 protected function setCookieFromSession($session = NULL) {
00555 if (!$this->getVariable('cookie_support'))
00556 return;
00557
00558 $cookie_name = $this->getSessionCookieName();
00559 $value = 'deleted';
00560 $expires = time() - 3600;
00561 $base_domain = $this->getVariable('base_domain', OAUTH2_DEFAULT_BASE_DOMAIN);
00562 if ($session) {
00563 $value = '"' . http_build_query($session, NULL, '&') . '"';
00564 $base_domain = isset($session['base_domain']) ? $session['base_domain'] : $base_domain;
00565 $expires = isset($session['expires']) ? $session['expires'] : time() + $this->getVariable('expires_in', OAUTH2_DEFAULT_EXPIRES_IN);
00566 }
00567
00568
00569 if ($base_domain)
00570 $base_domain = '.' . $base_domain;
00571
00572
00573 if ($value == 'deleted' && empty($_COOKIE[$cookie_name]))
00574 return;
00575
00576 if (headers_sent())
00577 error_log('Could not set cookie. Headers already sent.');
00578 else
00579 setcookie($cookie_name, $value, $expires, '/', $base_domain);
00580 }
00581
00582
00583
00584
00585
00586
00587
00588
00589
00590
00591 protected function validateSessionObject($session) {
00592
00593 if (is_array($session) && isset($session['access_token']) && isset($session['sig'])) {
00594
00595 $session_without_sig = $session;
00596 unset($session_without_sig['sig']);
00597
00598 $expected_sig = self::generateSignature(
00599 $session_without_sig,
00600 $this->getVariable('client_secret')
00601 );
00602
00603 if ($session['sig'] != $expected_sig) {
00604 error_log('Got invalid session signature in cookie.');
00605 $session = NULL;
00606 }
00607 }
00608 else {
00609 $session = NULL;
00610 }
00611 return $session;
00612 }
00613
00614
00615
00616
00617
00618 function getRequestUri() {
00619 if (isset($_SERVER['REQUEST_URI'])) {
00620 $uri = $_SERVER['REQUEST_URI'];
00621 }
00622 else {
00623 if (isset($_SERVER['argv'])) {
00624 $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
00625 }
00626 elseif (isset($_SERVER['QUERY_STRING'])) {
00627 $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
00628 }
00629 else {
00630 $uri = $_SERVER['SCRIPT_NAME'];
00631 }
00632 }
00633
00634 $uri = '/' . ltrim($uri, '/');
00635
00636 return $uri;
00637 }
00638
00639
00640
00641
00642
00643
00644
00645 protected function getCurrentUri() {
00646 $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'
00647 ? 'https://'
00648 : 'http://';
00649 $current_uri = $protocol . $_SERVER['HTTP_HOST'] . $this->getRequestUri();
00650 $parts = parse_url($current_uri);
00651
00652 $query = '';
00653 if (!empty($parts['query'])) {
00654 $params = array();
00655 parse_str($parts['query'], $params);
00656 $params = array_filter($params);
00657 if (!empty($params)) {
00658 $query = '?' . http_build_query($params, NULL, '&');
00659 }
00660 }
00661
00662
00663 $port = isset($parts['port']) &&
00664 (($protocol === 'http://' && $parts['port'] !== 80) || ($protocol === 'https://' && $parts['port'] !== 443))
00665 ? ':' . $parts['port'] : '';
00666
00667
00668 return $protocol . $parts['host'] . $port . $parts['path'] . $query;
00669 }
00670
00671
00672
00673
00674
00675
00676
00677
00678
00679
00680
00681
00682 protected function getUri($path = '', $params = array()) {
00683 $url = $this->getVariable('services_uri') ? $this->getVariable('services_uri') : $this->getVariable('base_uri');
00684
00685 if (!empty($path))
00686 if (substr($path, 0, 4) == "http")
00687 $url = $path;
00688 else
00689 $url = rtrim($url, '/') . '/' . ltrim($path, '/');
00690
00691 if (!empty($params))
00692 $url .= '?' . http_build_query($params, NULL, '&');
00693
00694 return $url;
00695 }
00696
00697
00698
00699
00700
00701
00702
00703
00704
00705
00706
00707
00708 protected function generateSignature($params, $secret) {
00709
00710 ksort($params);
00711
00712
00713 $base_string = '';
00714 foreach ($params as $key => $value) {
00715 $base_string .= $key . '=' . $value;
00716 }
00717 $base_string .= $secret;
00718
00719 return md5($base_string);
00720 }
00721 }