diff --git a/library/facebook.php b/library/facebook.php new file mode 100644 index 0000000000..eebe3b4640 --- /dev/null +++ b/library/facebook.php @@ -0,0 +1,955 @@ + + */ +class FacebookApiException extends Exception +{ + /** + * The result from the API server that represents the exception information. + */ + protected $result; + + /** + * Make a new API Exception with the given result. + * + * @param Array $result the result from the API server + */ + public function __construct($result) { + $this->result = $result; + + $code = isset($result['error_code']) ? $result['error_code'] : 0; + + if (isset($result['error_description'])) { + // OAuth 2.0 Draft 10 style + $msg = $result['error_description']; + } else if (isset($result['error']) && is_array($result['error'])) { + // OAuth 2.0 Draft 00 style + $msg = $result['error']['message']; + } else if (isset($result['error_msg'])) { + // Rest server style + $msg = $result['error_msg']; + } else { + $msg = 'Unknown Error. Check getResult()'; + } + + parent::__construct($msg, $code); + } + + /** + * Return the associated result object returned by the API server. + * + * @returns Array the result from the API server + */ + public function getResult() { + return $this->result; + } + + /** + * Returns the associated type for the error. This will default to + * 'Exception' when a type is not available. + * + * @return String + */ + public function getType() { + if (isset($this->result['error'])) { + $error = $this->result['error']; + if (is_string($error)) { + // OAuth 2.0 Draft 10 style + return $error; + } else if (is_array($error)) { + // OAuth 2.0 Draft 00 style + if (isset($error['type'])) { + return $error['type']; + } + } + } + return 'Exception'; + } + + /** + * To make debugging easier. + * + * @returns String the string representation of the error + */ + public function __toString() { + $str = $this->getType() . ': '; + if ($this->code != 0) { + $str .= $this->code . ': '; + } + return $str . $this->message; + } +} + +/** + * Provides access to the Facebook Platform. + * + * @author Naitik Shah + */ +class Facebook +{ + /** + * Version. + */ + const VERSION = '2.1.2'; + + /** + * Default options for curl. + */ + public static $CURL_OPTS = array( + CURLOPT_CONNECTTIMEOUT => 10, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => 60, + CURLOPT_USERAGENT => 'facebook-php-2.0', + ); + + /** + * List of query parameters that get automatically dropped when rebuilding + * the current URL. + */ + protected static $DROP_QUERY_PARAMS = array( + 'session', + 'signed_request', + ); + + /** + * Maps aliases to Facebook domains. + */ + public static $DOMAIN_MAP = array( + 'api' => 'https://api.facebook.com/', + 'api_read' => 'https://api-read.facebook.com/', + 'graph' => 'https://graph.facebook.com/', + 'www' => 'https://www.facebook.com/', + ); + + /** + * The Application ID. + */ + protected $appId; + + /** + * The Application API Secret. + */ + protected $apiSecret; + + /** + * The active user session, if one is available. + */ + protected $session; + + /** + * The data from the signed_request token. + */ + protected $signedRequest; + + /** + * Indicates that we already loaded the session as best as we could. + */ + protected $sessionLoaded = false; + + /** + * Indicates if Cookie support should be enabled. + */ + protected $cookieSupport = false; + + /** + * Base domain for the Cookie. + */ + protected $baseDomain = ''; + + /** + * Indicates if the CURL based @ syntax for file uploads is enabled. + */ + protected $fileUploadSupport = false; + + /** + * Initialize a Facebook Application. + * + * The configuration: + * - appId: the application ID + * - secret: the application secret + * - cookie: (optional) boolean true to enable cookie support + * - domain: (optional) domain for the cookie + * - fileUpload: (optional) boolean indicating if file uploads are enabled + * + * @param Array $config the application configuration + */ + public function __construct($config) { + $this->setAppId($config['appId']); + $this->setApiSecret($config['secret']); + if (isset($config['cookie'])) { + $this->setCookieSupport($config['cookie']); + } + if (isset($config['domain'])) { + $this->setBaseDomain($config['domain']); + } + if (isset($config['fileUpload'])) { + $this->setFileUploadSupport($config['fileUpload']); + } + } + + /** + * Set the Application ID. + * + * @param String $appId the Application ID + */ + public function setAppId($appId) { + $this->appId = $appId; + return $this; + } + + /** + * Get the Application ID. + * + * @return String the Application ID + */ + public function getAppId() { + return $this->appId; + } + + /** + * Set the API Secret. + * + * @param String $appId the API Secret + */ + public function setApiSecret($apiSecret) { + $this->apiSecret = $apiSecret; + return $this; + } + + /** + * Get the API Secret. + * + * @return String the API Secret + */ + public function getApiSecret() { + return $this->apiSecret; + } + + /** + * Set the Cookie Support status. + * + * @param Boolean $cookieSupport the Cookie Support status + */ + public function setCookieSupport($cookieSupport) { + $this->cookieSupport = $cookieSupport; + return $this; + } + + /** + * Get the Cookie Support status. + * + * @return Boolean the Cookie Support status + */ + public function useCookieSupport() { + return $this->cookieSupport; + } + + /** + * Set the base domain for the Cookie. + * + * @param String $domain the base domain + */ + public function setBaseDomain($domain) { + $this->baseDomain = $domain; + return $this; + } + + /** + * Get the base domain for the Cookie. + * + * @return String the base domain + */ + public function getBaseDomain() { + return $this->baseDomain; + } + + /** + * Set the file upload support status. + * + * @param String $domain the base domain + */ + public function setFileUploadSupport($fileUploadSupport) { + $this->fileUploadSupport = $fileUploadSupport; + return $this; + } + + /** + * Get the file upload support status. + * + * @return String the base domain + */ + public function useFileUploadSupport() { + return $this->fileUploadSupport; + } + + /** + * Get the data from a signed_request token + * + * @return String the base domain + */ + public function getSignedRequest() { + if (!$this->signedRequest) { + if (isset($_REQUEST['signed_request'])) { + $this->signedRequest = $this->parseSignedRequest( + $_REQUEST['signed_request']); + } + } + return $this->signedRequest; + } + + /** + * Set the Session. + * + * @param Array $session the session + * @param Boolean $write_cookie indicate if a cookie should be written. this + * value is ignored if cookie support has been disabled. + */ + public function setSession($session=null, $write_cookie=true) { + $session = $this->validateSessionObject($session); + $this->sessionLoaded = true; + $this->session = $session; + if ($write_cookie) { + $this->setCookieFromSession($session); + } + return $this; + } + + /** + * Get the session object. This will automatically look for a signed session + * sent via the signed_request, Cookie or Query Parameters if needed. + * + * @return Array the session + */ + public function getSession() { + if (!$this->sessionLoaded) { + $session = null; + $write_cookie = true; + + // try loading session from signed_request in $_REQUEST + $signedRequest = $this->getSignedRequest(); + if ($signedRequest) { + // sig is good, use the signedRequest + $session = $this->createSessionFromSignedRequest($signedRequest); + } + + // try loading session from $_REQUEST + if (!$session && isset($_REQUEST['session'])) { + $session = json_decode( + get_magic_quotes_gpc() + ? stripslashes($_REQUEST['session']) + : $_REQUEST['session'], + true + ); + $session = $this->validateSessionObject($session); + } + + // try loading session from cookie if necessary + if (!$session && $this->useCookieSupport()) { + $cookieName = $this->getSessionCookieName(); + if (isset($_COOKIE[$cookieName])) { + $session = array(); + parse_str(trim( + get_magic_quotes_gpc() + ? stripslashes($_COOKIE[$cookieName]) + : $_COOKIE[$cookieName], + '"' + ), $session); + $session = $this->validateSessionObject($session); + // write only if we need to delete a invalid session cookie + $write_cookie = empty($session); + } + } + + $this->setSession($session, $write_cookie); + } + + return $this->session; + } + + /** + * Get the UID from the session. + * + * @return String the UID if available + */ + public function getUser() { + $session = $this->getSession(); + return $session ? $session['uid'] : null; + } + + /** + * Gets a OAuth access token. + * + * @return String the access token + */ + public function getAccessToken() { + $session = $this->getSession(); + // either user session signed, or app signed + if ($session) { + return $session['access_token']; + } else { + return $this->getAppId() .'|'. $this->getApiSecret(); + } + } + + /** + * Get a Login URL for use with redirects. By default, full page redirect is + * assumed. If you are using the generated URL with a window.open() call in + * JavaScript, you can pass in display=popup as part of the $params. + * + * The parameters: + * - next: the url to go to after a successful login + * - cancel_url: the url to go to after the user cancels + * - req_perms: comma separated list of requested extended perms + * - display: can be "page" (default, full page) or "popup" + * + * @param Array $params provide custom parameters + * @return String the URL for the login flow + */ + public function getLoginUrl($params=array()) { + $currentUrl = $this->getCurrentUrl(); + return $this->getUrl( + 'www', + 'login.php', + array_merge(array( + 'api_key' => $this->getAppId(), + 'cancel_url' => $currentUrl, + 'display' => 'page', + 'fbconnect' => 1, + 'next' => $currentUrl, + 'return_session' => 1, + 'session_version' => 3, + 'v' => '1.0', + ), $params) + ); + } + + /** + * Get a Logout URL suitable for use with redirects. + * + * The parameters: + * - next: the url to go to after a successful logout + * + * @param Array $params provide custom parameters + * @return String the URL for the logout flow + */ + public function getLogoutUrl($params=array()) { + return $this->getUrl( + 'www', + 'logout.php', + array_merge(array( + 'next' => $this->getCurrentUrl(), + 'access_token' => $this->getAccessToken(), + ), $params) + ); + } + + /** + * Get a login status URL to fetch the status from facebook. + * + * The parameters: + * - ok_session: the URL to go to if a session is found + * - no_session: the URL to go to if the user is not connected + * - no_user: the URL to go to if the user is not signed into facebook + * + * @param Array $params provide custom parameters + * @return String the URL for the logout flow + */ + public function getLoginStatusUrl($params=array()) { + return $this->getUrl( + 'www', + 'extern/login_status.php', + array_merge(array( + 'api_key' => $this->getAppId(), + 'no_session' => $this->getCurrentUrl(), + 'no_user' => $this->getCurrentUrl(), + 'ok_session' => $this->getCurrentUrl(), + 'session_version' => 3, + ), $params) + ); + } + + /** + * Make an API call. + * + * @param Array $params the API call parameters + * @return the decoded response + */ + public function api(/* polymorphic */) { + $args = func_get_args(); + if (is_array($args[0])) { + return $this->_restserver($args[0]); + } else { + return call_user_func_array(array($this, '_graph'), $args); + } + } + + /** + * Invoke the old restserver.php endpoint. + * + * @param Array $params method call object + * @return the decoded response object + * @throws FacebookApiException + */ + protected function _restserver($params) { + // generic application level parameters + $params['api_key'] = $this->getAppId(); + $params['format'] = 'json-strings'; + + $result = json_decode($this->_oauthRequest( + $this->getApiUrl($params['method']), + $params + ), true); + + // results are returned, errors are thrown + if (is_array($result) && isset($result['error_code'])) { + throw new FacebookApiException($result); + } + return $result; + } + + /** + * Invoke the Graph API. + * + * @param String $path the path (required) + * @param String $method the http method (default 'GET') + * @param Array $params the query/post data + * @return the decoded response object + * @throws FacebookApiException + */ + protected function _graph($path, $method='GET', $params=array()) { + if (is_array($method) && empty($params)) { + $params = $method; + $method = 'GET'; + } + $params['method'] = $method; // method override as we always do a POST + + $result = json_decode($this->_oauthRequest( + $this->getUrl('graph', $path), + $params + ), true); + + // results are returned, errors are thrown + if (is_array($result) && isset($result['error'])) { + $e = new FacebookApiException($result); + switch ($e->getType()) { + // OAuth 2.0 Draft 00 style + case 'OAuthException': + // OAuth 2.0 Draft 10 style + case 'invalid_token': + $this->setSession(null); + } + throw $e; + } + return $result; + } + + /** + * Make a OAuth Request + * + * @param String $path the path (required) + * @param Array $params the query/post data + * @return the decoded response object + * @throws FacebookApiException + */ + protected function _oauthRequest($url, $params) { + if (!isset($params['access_token'])) { + $params['access_token'] = $this->getAccessToken(); + } + + // json_encode all params values that are not strings + foreach ($params as $key => $value) { + if (!is_string($value)) { + $params[$key] = json_encode($value); + } + } + return $this->makeRequest($url, $params); + } + + /** + * Makes an HTTP request. This method can be overriden by subclasses if + * developers want to do fancier things or use something other than curl to + * make the request. + * + * @param String $url the URL to make the request to + * @param Array $params the parameters to use for the POST body + * @param CurlHandler $ch optional initialized curl handle + * @return String the response text + */ + protected function makeRequest($url, $params, $ch=null) { + if (!$ch) { + $ch = curl_init(); + } + + $opts = self::$CURL_OPTS; + if ($this->useFileUploadSupport()) { + $opts[CURLOPT_POSTFIELDS] = $params; + } else { + $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&'); + } + $opts[CURLOPT_URL] = $url; + + // disable the 'Expect: 100-continue' behaviour. This causes CURL to wait + // for 2 seconds if the server does not support this header. + if (isset($opts[CURLOPT_HTTPHEADER])) { + $existing_headers = $opts[CURLOPT_HTTPHEADER]; + $existing_headers[] = 'Expect:'; + $opts[CURLOPT_HTTPHEADER] = $existing_headers; + } else { + $opts[CURLOPT_HTTPHEADER] = array('Expect:'); + } + + curl_setopt_array($ch, $opts); + $result = curl_exec($ch); + if ($result === false) { + $e = new FacebookApiException(array( + 'error_code' => curl_errno($ch), + 'error' => array( + 'message' => curl_error($ch), + 'type' => 'CurlException', + ), + )); + curl_close($ch); + throw $e; + } + curl_close($ch); + return $result; + } + + /** + * The name of the Cookie that contains the session. + * + * @return String the cookie name + */ + protected function getSessionCookieName() { + return 'fbs_' . $this->getAppId(); + } + + /** + * Set a JS Cookie based on the _passed in_ session. It does not use the + * currently stored session -- you need to explicitly pass it in. + * + * @param Array $session the session to use for setting the cookie + */ + protected function setCookieFromSession($session=null) { + if (!$this->useCookieSupport()) { + return; + } + + $cookieName = $this->getSessionCookieName(); + $value = 'deleted'; + $expires = time() - 3600; + $domain = $this->getBaseDomain(); + if ($session) { + $value = '"' . http_build_query($session, null, '&') . '"'; + if (isset($session['base_domain'])) { + $domain = $session['base_domain']; + } + $expires = $session['expires']; + } + + // prepend dot if a domain is found + if ($domain) { + $domain = '.' . $domain; + } + + // if an existing cookie is not set, we dont need to delete it + if ($value == 'deleted' && empty($_COOKIE[$cookieName])) { + return; + } + + if (headers_sent()) { + self::errorLog('Could not set cookie. Headers already sent.'); + + // ignore for code coverage as we will never be able to setcookie in a CLI + // environment + // @codeCoverageIgnoreStart + } else { + setcookie($cookieName, $value, $expires, '/', $domain); + } + // @codeCoverageIgnoreEnd + } + + /** + * Validates a session_version=3 style session object. + * + * @param Array $session the session object + * @return Array the session object if it validates, null otherwise + */ + protected function validateSessionObject($session) { + // make sure some essential fields exist + if (is_array($session) && + isset($session['uid']) && + isset($session['access_token']) && + isset($session['sig'])) { + // validate the signature + $session_without_sig = $session; + unset($session_without_sig['sig']); + $expected_sig = self::generateSignature( + $session_without_sig, + $this->getApiSecret() + ); + if ($session['sig'] != $expected_sig) { + self::errorLog('Got invalid session signature in cookie.'); + $session = null; + } + // check expiry time + } else { + $session = null; + } + return $session; + } + + /** + * Returns something that looks like our JS session object from the + * signed token's data + * + * TODO: Nuke this once the login flow uses OAuth2 + * + * @param Array the output of getSignedRequest + * @return Array Something that will work as a session + */ + protected function createSessionFromSignedRequest($data) { + if (!isset($data['oauth_token'])) { + return null; + } + + $session = array( + 'uid' => $data['user_id'], + 'access_token' => $data['oauth_token'], + 'expires' => $data['expires'], + ); + + // put a real sig, so that validateSignature works + $session['sig'] = self::generateSignature( + $session, + $this->getApiSecret() + ); + + return $session; + } + + /** + * Parses a signed_request and validates the signature. + * Then saves it in $this->signed_data + * + * @param String A signed token + * @param Boolean Should we remove the parts of the payload that + * are used by the algorithm? + * @return Array the payload inside it or null if the sig is wrong + */ + protected function parseSignedRequest($signed_request) { + list($encoded_sig, $payload) = explode('.', $signed_request, 2); + + // decode the data + $sig = self::base64UrlDecode($encoded_sig); + $data = json_decode(self::base64UrlDecode($payload), true); + + if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') { + self::errorLog('Unknown algorithm. Expected HMAC-SHA256'); + return null; + } + + // check sig + $expected_sig = hash_hmac('sha256', $payload, + $this->getApiSecret(), $raw = true); + if ($sig !== $expected_sig) { + self::errorLog('Bad Signed JSON signature!'); + return null; + } + + return $data; + } + + /** + * Build the URL for api given parameters. + * + * @param $method String the method name. + * @return String the URL for the given parameters + */ + protected function getApiUrl($method) { + static $READ_ONLY_CALLS = + array('admin.getallocation' => 1, + 'admin.getappproperties' => 1, + 'admin.getbannedusers' => 1, + 'admin.getlivestreamvialink' => 1, + 'admin.getmetrics' => 1, + 'admin.getrestrictioninfo' => 1, + 'application.getpublicinfo' => 1, + 'auth.getapppublickey' => 1, + 'auth.getsession' => 1, + 'auth.getsignedpublicsessiondata' => 1, + 'comments.get' => 1, + 'connect.getunconnectedfriendscount' => 1, + 'dashboard.getactivity' => 1, + 'dashboard.getcount' => 1, + 'dashboard.getglobalnews' => 1, + 'dashboard.getnews' => 1, + 'dashboard.multigetcount' => 1, + 'dashboard.multigetnews' => 1, + 'data.getcookies' => 1, + 'events.get' => 1, + 'events.getmembers' => 1, + 'fbml.getcustomtags' => 1, + 'feed.getappfriendstories' => 1, + 'feed.getregisteredtemplatebundlebyid' => 1, + 'feed.getregisteredtemplatebundles' => 1, + 'fql.multiquery' => 1, + 'fql.query' => 1, + 'friends.arefriends' => 1, + 'friends.get' => 1, + 'friends.getappusers' => 1, + 'friends.getlists' => 1, + 'friends.getmutualfriends' => 1, + 'gifts.get' => 1, + 'groups.get' => 1, + 'groups.getmembers' => 1, + 'intl.gettranslations' => 1, + 'links.get' => 1, + 'notes.get' => 1, + 'notifications.get' => 1, + 'pages.getinfo' => 1, + 'pages.isadmin' => 1, + 'pages.isappadded' => 1, + 'pages.isfan' => 1, + 'permissions.checkavailableapiaccess' => 1, + 'permissions.checkgrantedapiaccess' => 1, + 'photos.get' => 1, + 'photos.getalbums' => 1, + 'photos.gettags' => 1, + 'profile.getinfo' => 1, + 'profile.getinfooptions' => 1, + 'stream.get' => 1, + 'stream.getcomments' => 1, + 'stream.getfilters' => 1, + 'users.getinfo' => 1, + 'users.getloggedinuser' => 1, + 'users.getstandardinfo' => 1, + 'users.hasapppermission' => 1, + 'users.isappuser' => 1, + 'users.isverified' => 1, + 'video.getuploadlimits' => 1); + $name = 'api'; + if (isset($READ_ONLY_CALLS[strtolower($method)])) { + $name = 'api_read'; + } + return self::getUrl($name, 'restserver.php'); + } + + /** + * Build the URL for given domain alias, path and parameters. + * + * @param $name String the name of the domain + * @param $path String optional path (without a leading slash) + * @param $params Array optional query parameters + * @return String the URL for the given parameters + */ + protected function getUrl($name, $path='', $params=array()) { + $url = self::$DOMAIN_MAP[$name]; + if ($path) { + if ($path[0] === '/') { + $path = substr($path, 1); + } + $url .= $path; + } + if ($params) { + $url .= '?' . http_build_query($params, null, '&'); + } + return $url; + } + + /** + * Returns the Current URL, stripping it of known FB parameters that should + * not persist. + * + * @return String the current URL + */ + protected function getCurrentUrl() { + $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' + ? 'https://' + : 'http://'; + $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; + $parts = parse_url($currentUrl); + + // drop known fb params + $query = ''; + if (!empty($parts['query'])) { + $params = array(); + parse_str($parts['query'], $params); + foreach(self::$DROP_QUERY_PARAMS as $key) { + unset($params[$key]); + } + if (!empty($params)) { + $query = '?' . http_build_query($params, null, '&'); + } + } + + // use port if non default + $port = + isset($parts['port']) && + (($protocol === 'http://' && $parts['port'] !== 80) || + ($protocol === 'https://' && $parts['port'] !== 443)) + ? ':' . $parts['port'] : ''; + + // rebuild + return $protocol . $parts['host'] . $port . $parts['path'] . $query; + } + + /** + * Generate a signature for the given params and secret. + * + * @param Array $params the parameters to sign + * @param String $secret the secret to sign with + * @return String the generated signature + */ + protected static function generateSignature($params, $secret) { + // work with sorted data + ksort($params); + + // generate the base string + $base_string = ''; + foreach($params as $key => $value) { + $base_string .= $key . '=' . $value; + } + $base_string .= $secret; + + return md5($base_string); + } + + /** + * Prints to the error log if you aren't in command line mode. + * + * @param String log message + */ + protected static function errorLog($msg) { + // disable error log if we are running in a CLI environment + // @codeCoverageIgnoreStart + if (php_sapi_name() != 'cli') { + error_log($msg); + } + // uncomment this if you want to see the errors on the page + // print 'error_log: '.$msg."\n"; + // @codeCoverageIgnoreEnd + } + + /** + * Base64 encoding that doesn't need to be urlencode()ed. + * Exactly the same as base64_encode except it uses + * - instead of + + * _ instead of / + * + * @param String base64UrlEncodeded string + */ + protected static function base64UrlDecode($input) { + return base64_decode(strtr($input, '-_', '+/')); + } +} diff --git a/library/oauth.php b/library/oauth.php new file mode 100644 index 0000000000..caf1a08395 --- /dev/null +++ b/library/oauth.php @@ -0,0 +1,728 @@ + , + // "expires" => , + // "scope" => , + // "redirect_uri" => , + // "expires" => , + // "scope" => + // ) + // + // Return null if the code is invalid. + + return null; + } + + // Take the provided authorization code values and store them somewhere (db, etc.) + // Required for AUTH_CODE_GRANT_TYPE + protected function store_auth_code($code, $client_id, $redirect_uri, $expires, $scope) { + // This function should be the storage counterpart to get_stored_auth_code + + // If storage fails for some reason, we're not currently checking + // for any sort of success/failure, so you should bail out of the + // script and provide a descriptive fail message + } + + // Grant access tokens for basic user credentials + // IETF Draft 4.1.2: http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-4.1.2 + // Required for USER_CREDENTIALS_GRANT_TYPE + protected function check_user_credentials($client_id, $username, $password) { + // Check the supplied username and password for validity + // You can also use the $client_id param to do any checks required + // based on a client, if you need that + // If the username and password are invalid, return false + + // If the username and password are valid, and you want to verify the scope of + // a user's access, return an array with the scope values, like so: + // + // array ( + // "scope" => + // ) + // + // We'll check the scope you provide against the requested scope before + // providing an access token. + // + // Otherwise, just return true. + + return false; + } + + // Grant access tokens for assertions + // IETF Draft 4.1.3: http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-4.1.3 + // Required for ASSERTION_GRANT_TYPE + protected function check_assertion($client_id, $assertion_type, $assertion) { + // Check the supplied assertion for validity + // You can also use the $client_id param to do any checks required + // based on a client, if you need that + // If the assertion is invalid, return false + + // If the assertion is valid, and you want to verify the scope of + // an access request, return an array with the scope values, like so: + // + // array ( + // "scope" => + // ) + // + // We'll check the scope you provide against the requested scope before + // providing an access token. + // + // Otherwise, just return true. + + return false; + } + + // Grant refresh access tokens + // IETF Draft 4.1.4: http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-4.1.4 + // Required for REFRESH_TOKEN_GRANT_TYPE + protected function get_refresh_token($refresh_token) { + // Retrieve the stored data for the given refresh token + // Should return: + // + // array ( + // "client_id" => , + // "expires" => , + // "scope" => + // ) + // + // Return null if the token id is invalid. + + return null; + } + + // Store refresh access tokens + // Required for REFRESH_TOKEN_GRANT_TYPE + protected function store_refresh_token($token, $client_id, $expires, $scope = null) { + // If storage fails for some reason, we're not currently checking + // for any sort of success/failure, so you should bail out of the + // script and provide a descriptive fail message + + return; + } + + // Grant access tokens for the "none" grant type + // Not really described in the IETF Draft, so I just left a method stub...do whatever you want! + // Required for NONE_GRANT_TYPE + protected function check_none_access($client_id) { + return false; + } + + protected function get_default_authentication_realm() { + // Change this to whatever authentication realm you want to send in a WWW-Authenticate header + return "Service"; + } + + /* End stuff that should get overridden */ + + private $access_token_lifetime = 3600; + private $auth_code_lifetime = 30; + private $refresh_token_lifetime = 1209600; // Two weeks + + public function __construct($access_token_lifetime = 3600, $auth_code_lifetime = 30, $refresh_token_lifetime = 1209600) { + $this->access_token_lifetime = $access_token_lifetime; + $this->auth_code_lifetime = $auth_code_lifetime; + $this->refresh_token_lifetime = $refresh_token_lifetime; + } + + /* Resource protecting (Section 5) */ + + // Check that a valid access token has been provided + // + // The scope parameter defines any required scope that the token must have + // If a scope param is provided and the token does not have the required scope, + // we bounce the request + // + // Some implementations may choose to return a subset of the protected resource + // (i.e. "public" data) if the user has not provided an access token + // or if the access token is invalid or expired + // + // The IETF spec says that we should send a 401 Unauthorized header and bail immediately + // so that's what the defaults are set to + // + // Here's what each parameter does: + // $scope = A space-separated string of required scope(s), if you want to check for scope + // $exit_not_present = If true and no access token is provided, send a 401 header and exit, otherwise return false + // $exit_invalid = If true and the implementation of get_access_token returns null, exit, otherwise return false + // $exit_expired = If true and the access token has expired, exit, otherwise return false + // $exit_scope = If true the access token does not have the required scope(s), exit, otherwise return false + // $realm = If you want to specify a particular realm for the WWW-Authenticate header, supply it here + public function verify_access_token($scope = null, $exit_not_present = true, $exit_invalid = true, $exit_expired = true, $exit_scope = true, $realm = null) { + $token_param = $this->get_access_token_param(); + if ($token_param === false) // Access token was not provided + return $exit_not_present ? $this->send_401_unauthorized($realm, $scope) : false; + + // Get the stored token data (from the implementing subclass) + $token = $this->get_access_token($token_param); + if ($token === null) + return $exit_invalid ? $this->send_401_unauthorized($realm, $scope, ERROR_INVALID_TOKEN) : false; + + // Check token expiration (I'm leaving this check separated, later we'll fill in better error messages) + if (isset($token["expires"]) && time() > $token["expires"]) + return $exit_expired ? $this->send_401_unauthorized($realm, $scope, ERROR_EXPIRED_TOKEN) : false; + + // Check scope, if provided + // If token doesn't have a scope, it's null/empty, or it's insufficient, then throw an error + if ($scope && + (!isset($token["scope"]) || !$token["scope"] || !$this->check_scope($scope, $token["scope"]))) + return $exit_scope ? $this->send_401_unauthorized($realm, $scope, ERROR_INSUFFICIENT_SCOPE) : false; + + return true; + } + + + // Returns true if everything in required scope is contained in available scope + // False if something in required scope is not in available scope + private function check_scope($required_scope, $available_scope) { + // The required scope should match or be a subset of the available scope + if (!is_array($required_scope)) + $required_scope = explode(" ", $required_scope); + + if (!is_array($available_scope)) + $available_scope = explode(" ", $available_scope); + + return (count(array_diff($required_scope, $available_scope)) == 0); + } + + // Send a 401 unauthorized header with the given realm + // and an error, if provided + private function send_401_unauthorized($realm, $scope, $error = null) { + $realm = $realm === null ? $this->get_default_authentication_realm() : $realm; + + $auth_header = "WWW-Authenticate: Token realm='".$realm."'"; + + if ($scope) + $auth_header .= ", scope='".$scope."'"; + + if ($error !== null) + $auth_header .= ", error='".$error."'"; + + header("HTTP/1.1 401 Unauthorized"); + header($auth_header); + + exit; + } + + // Pulls the access token out of the HTTP request + // Either from the Authorization header or GET/POST/etc. + // Returns false if no token is present + // TODO: Support POST or DELETE + private function get_access_token_param() { + $auth_header = $this->get_authorization_header(); + + if ($auth_header !== false) { + // Make sure only the auth header is set + if (isset($_GET[OAUTH_TOKEN_PARAM_NAME]) || isset($_POST[OAUTH_TOKEN_PARAM_NAME])) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); + + $auth_header = trim($auth_header); + + // Make sure it's Token authorization + if (strcmp(substr($auth_header, 0, 6),"Token ") !== 0) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); + + // Parse the rest of the header + if (preg_match('/\s*token\s*="(.+)"/', substr($auth_header, 6), $matches) == 0 || count($matches) < 2) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); + + return $matches[1]; + } + + if (isset($_GET[OAUTH_TOKEN_PARAM_NAME])) { + if (isset($_POST[OAUTH_TOKEN_PARAM_NAME])) // Both GET and POST are not allowed + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); + + return $_GET[OAUTH_TOKEN_PARAM_NAME]; + } + + if (isset($_POST[OAUTH_TOKEN_PARAM_NAME])) + return $_POST[OAUTH_TOKEN_PARAM_NAME]; + + return false; + } + + /* Access token granting (Section 4) */ + + // Grant or deny a requested access token + // This would be called from the "/token" endpoint as defined in the spec + // Obviously, you can call your endpoint whatever you want + public function grant_access_token() { + $filters = array( + "grant_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => REGEX_TOKEN_GRANT_TYPE), "flags" => FILTER_REQUIRE_SCALAR), + "scope" => array("flags" => FILTER_REQUIRE_SCALAR), + "code" => array("flags" => FILTER_REQUIRE_SCALAR), + "redirect_uri" => array("filter" => FILTER_VALIDATE_URL, "flags" => array(FILTER_FLAG_SCHEME_REQUIRED, FILTER_REQUIRE_SCALAR)), + "username" => array("flags" => FILTER_REQUIRE_SCALAR), + "password" => array("flags" => FILTER_REQUIRE_SCALAR), + "assertion_type" => array("flags" => FILTER_REQUIRE_SCALAR), + "assertion" => array("flags" => FILTER_REQUIRE_SCALAR), + "refresh_token" => array("flags" => FILTER_REQUIRE_SCALAR), + ); + + $input = filter_input_array(INPUT_POST, $filters); + + // Grant Type must be specified. + if (!$input["grant_type"]) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); + + // Make sure we've implemented the requested grant type + if (!in_array($input["grant_type"], $this->get_supported_grant_types())) + $this->error(ERROR_BAD_REQUEST, ERROR_UNSUPPORTED_GRANT_TYPE); + + // Authorize the client + $client = $this->get_client_credentials(); + + if ($this->auth_client_credentials($client[0], $client[1]) === false) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_CREDENTIALS); + + if (!$this->authorize_client($client[0], $input["grant_type"])) + $this->error(ERROR_BAD_REQUEST, ERROR_UNAUTHORIZED_CLIENT); + + // Do the granting + switch ($input["grant_type"]) { + case AUTH_CODE_GRANT_TYPE: + if (!$input["code"] || !$input["redirect_uri"]) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); + + $stored = $this->get_stored_auth_code($input["code"]); + + if ($stored === null || $input["redirect_uri"] != $stored["redirect_uri"] || $client[0] != $stored["client_id"]) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); + + if ($stored["expires"] > time()) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); + + break; + case USER_CREDENTIALS_GRANT_TYPE: + if (!$input["username"] || !$input["password"]) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); + + $stored = $this->check_user_credentials($client[0], $input["username"], $input["password"]); + + if ($stored === false) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); + + break; + case ASSERTION_GRANT_TYPE: + if (!$input["assertion_type"] || !$input["assertion"]) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); + + $stored = $this->check_assertion($client[0], $input["assertion_type"], $input["assertion"]); + + if ($stored === false) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); + + break; + case REFRESH_TOKEN_GRANT_TYPE: + if (!$input["refresh_token"]) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); + + $stored = $this->get_refresh_token($input["refresh_token"]); + + if ($stored === null || $client[0] != $stored["client_id"]) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); + + if ($stored["expires"] > time()) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_GRANT); + + break; + case NONE_GRANT_TYPE: + $stored = $this->check_none_access($client[0]); + + if ($stored === false) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); + } + + // Check scope, if provided + if ($input["scope"] && (!is_array($stored) || !isset($stored["scope"]) || !$this->check_scope($input["scope"], $stored["scope"]))) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_SCOPE); + + if (!$input["scope"]) + $input["scope"] = null; + + $token = $this->create_access_token($client[0], $input["scope"]); + + $this->send_json_headers(); + echo json_encode($token); + } + + // Internal function used to get the client credentials from HTTP basic auth or POST data + // See http://tools.ietf.org/html/draft-ietf-oauth-v2-08#section-2 + private function get_client_credentials() { + if (isset($_SERVER["PHP_AUTH_USER"]) && $_POST && isset($_POST["client_id"])) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_CREDENTIALS); + + // Try basic auth + if (isset($_SERVER["PHP_AUTH_USER"])) + return array($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"]); + + // Try POST + if ($_POST && isset($_POST["client_id"])) { + if (isset($_POST["client_secret"])) + return array($_POST["client_id"], $_POST["client_secret"]); + + return array($_POST["client_id"], NULL); + } + + // No credentials were specified + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_CREDENTIALS); + } + + /* End-user/client Authorization (Section 3 of IETF Draft) */ + + // Pull the authorization request data out of the HTTP request + // and return it so the authorization server can prompt the user + // for approval + public function get_authorize_params() { + $filters = array( + "client_id" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => REGEX_CLIENT_ID), "flags" => FILTER_REQUIRE_SCALAR), + "response_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => REGEX_AUTH_RESPONSE_TYPE), "flags" => FILTER_REQUIRE_SCALAR), + "redirect_uri" => array("filter" => FILTER_VALIDATE_URL, "flags" => array(FILTER_FLAG_SCHEME_REQUIRED, FILTER_REQUIRE_SCALAR)), + "state" => array("flags" => FILTER_REQUIRE_SCALAR), + "scope" => array("flags" => FILTER_REQUIRE_SCALAR), + ); + + $input = filter_input_array(INPUT_GET, $filters); + + // Make sure a valid client id was supplied + if (!$input["client_id"]) { + if ($input["redirect_uri"]) + $this->callback_error($input["redirect_uri"], ERROR_INVALID_CLIENT_ID, $input["state"]); + + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_CLIENT_ID); // We don't have a good URI to use + } + + // redirect_uri is not required if already established via other channels + // check an existing redirect URI against the one supplied + $redirect_uri = $this->get_redirect_uri($input["client_id"]); + + // At least one of: existing redirect URI or input redirect URI must be specified + if (!$redirect_uri && !$input["redirect_uri"]) + $this->error(ERROR_BAD_REQUEST, ERROR_INVALID_REQUEST); + + // get_redirect_uri should return false if the given client ID is invalid + // this probably saves us from making a separate db call, and simplifies the method set + if ($redirect_uri === false) + $this->callback_error($input["redirect_uri"], ERROR_INVALID_CLIENT_ID, $input["state"]); + + // If there's an existing uri and one from input, verify that they match + if ($redirect_uri && $input["redirect_uri"]) { + // Ensure that the input uri starts with the stored uri + if (strcasecmp(substr($input["redirect_uri"], 0, strlen($redirect_uri)),$redirect_uri) !== 0) + $this->callback_error($input["redirect_uri"], ERROR_REDIRECT_URI_MISMATCH, $input["state"]); + } elseif ($redirect_uri) { // They did not provide a uri from input, so use the stored one + $input["redirect_uri"] = $redirect_uri; + } + + // type and client_id are required + if (!$input["response_type"]) + $this->callback_error($input["redirect_uri"], ERROR_INVALID_REQUEST, $input["state"], ERROR_INVALID_RESPONSE_TYPE); + + // Check requested auth response type against the list of supported types + if (array_search($input["response_type"], $this->get_supported_auth_response_types()) === false) + $this->callback_error($input["redirect_uri"], ERROR_UNSUPPORTED_RESPONSE_TYPE, $input["state"]); + + // Validate that the requested scope is supported + if ($input["scope"] && !$this->check_scope($input["scope"], $this->get_supported_scopes())) + $this->callback_error($input["redirect_uri"], ERROR_INVALID_SCOPE, $input["state"]); + + return $input; + } + + // After the user has approved or denied the access request + // the authorization server should call this function to redirect + // the user appropriately + + // The params all come from the results of get_authorize_params + // except for $is_authorized -- this is true or false depending on whether + // the user authorized the access + public function finish_client_authorization($is_authorized, $type, $client_id, $redirect_uri, $state, $scope = null) { + if ($state !== null) + $result["query"]["state"] = $state; + + if ($is_authorized === false) { + $result["query"]["error"] = ERROR_USER_DENIED; + } else { + if ($type == AUTH_CODE_AUTH_RESPONSE_TYPE || $type == CODE_AND_TOKEN_AUTH_RESPONSE_TYPE) + $result["query"]["code"] = $this->create_auth_code($client_id, $redirect_uri, $scope); + + if ($type == ACCESS_TOKEN_AUTH_RESPONSE_TYPE || $type == CODE_AND_TOKEN_AUTH_RESPONSE_TYPE) + $result["fragment"] = $this->create_access_token($client_id, $scope); + } + + $this->do_redirect_uri_callback($redirect_uri, $result); + } + + /* Other/utility functions */ + + private function do_redirect_uri_callback($redirect_uri, $result) { + header("HTTP/1.1 302 Found"); + header("Location: " . $this->build_uri($redirect_uri, $result)); + exit; + } + + private function build_uri($uri, $data) { + $parse_url = parse_url($uri); + + // Add our data to the parsed uri + foreach ($data as $k => $v) { + if (isset($parse_url[$k])) + $parse_url[$k] .= "&" . http_build_query($v); + else + $parse_url[$k] = http_build_query($v); + } + + // Put humpty dumpty back together + return + ((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "") + .((isset($parse_url["user"])) ? $parse_url["user"] . ((isset($parse_url["pass"])) ? ":" . $parse_url["pass"] : "") ."@" : "") + .((isset($parse_url["host"])) ? $parse_url["host"] : "") + .((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "") + .((isset($parse_url["path"])) ? $parse_url["path"] : "") + .((isset($parse_url["query"])) ? "?" . $parse_url["query"] : "") + .((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : ""); + } + + // This belongs in a separate factory, but to keep it simple, I'm just keeping it here. + private function create_access_token($client_id, $scope) { + $token = array( + "access_token" => $this->gen_access_token(), + "expires_in" => $this->access_token_lifetime, + "scope" => $scope + ); + + $this->store_access_token($token["access_token"], $client_id, time() + $this->access_token_lifetime, $scope); + + // Issue a refresh token also, if we support them + if (in_array(REFRESH_TOKEN_GRANT_TYPE, $this->get_supported_grant_types())) { + $token["refresh_token"] = $this->gen_access_token(); + $this->store_refresh_token($token["refresh_token"], $client_id, time() + $this->refresh_token_lifetime, $scope); + } + + return $token; + } + + private function create_auth_code($client_id, $redirect_uri, $scope) { + $code = $this->gen_auth_code(); + $this->store_auth_code($code, $client_id, $redirect_uri, time() + $this->auth_code_lifetime, $scope); + return $code; + } + + // Implementing classes may want to override these two functions + // to implement other access token or auth code generation schemes + private function gen_access_token() { + return base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand())); + } + + private function gen_auth_code() { + return base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand())); + } + + // Implementing classes may need to override this function for use on non-Apache web servers + // Just pull out the Authorization HTTP header and return it + // Return false if the Authorization header does not exist + private function get_authorization_header() { + if (array_key_exists("HTTP_AUTHORIZATION", $_SERVER)) + return $_SERVER["HTTP_AUTHORIZATION"]; + + if (function_exists("apache_request_headers")) { + $headers = apache_request_headers(); + + if (array_key_exists("Authorization", $headers)) + return $headers["Authorization"]; + } + + return false; + } + + private function send_json_headers() { + header("Content-Type: application/json"); + header("Cache-Control: no-store"); + } + + public function error($code, $message = null) { + header("HTTP/1.1 " . $code); + + if ($message) { + $this->send_json_headers(); + echo json_encode(array("error" => $message)); + } + + exit; + } + + public function callback_error($redirect_uri, $error, $state, $message = null, $error_uri = null) { + $result["query"]["error"] = $error; + + if ($state) + $result["query"]["state"] = $state; + + if ($message) + $result["query"]["error_description"] = $message; + + if ($error_uri) + $result["query"]["error_uri"] = $error_uri; + + $this->do_redirect_uri_callback($redirect_uri, $result); + } +} \ No newline at end of file