PageRenderTime 57ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/libraries/Facebook_oauth.php

https://github.com/socialigniter/facebook
PHP | 329 lines | 241 code | 49 blank | 39 comment | 30 complexity | 1664c7a33499acbe0cbf2d1dae27c612 MD5 | raw file
  1. <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
  2. /*
  3. * Ezra Pool (ezra@servicecut.nl) http://servicecut.nl
  4. *
  5. * @author Ezra Pool
  6. * @version 0.0.4
  7. *
  8. * Adapted Abraham Williams TwitterOAuth class for use with FacebookOAuth
  9. */
  10. /**
  11. * Facebook OAuth 2 class
  12. */
  13. class Facebook_oauth
  14. {
  15. public $verifypeer = FALSE; // Verify SSL Cert
  16. public $decode_JSON = TRUE; // Decode returned json data
  17. public $connecttimeout = 30; // Set connect timeout
  18. public $timeout = 30; // Set timeout default.
  19. /* Set the useragent. */
  20. public $useragent = "FacebookOAuth v0.0.4 | http://github.com/Zae/FacebookOAuth";
  21. /* HTTP Proxy settings (will only take effect if you set 'behind_proxy' to true) */
  22. public $proxy_settings = array(
  23. 'behind_proxy' => false,
  24. 'host' => '',
  25. 'port' => '',
  26. 'user' => '',
  27. 'pass' => '',
  28. 'type' => CURLPROXY_HTTP,
  29. 'auth' => CURLAUTH_BASIC
  30. );
  31. public $http_code; // Contains the last HTTP status code returned.
  32. public $http_info = array(); // Contains the last HTTP headers returned.
  33. public $url; // Contains the last API call.
  34. public $http_header = array(); // Contains last http_headers
  35. /* Variables used internally by the class and subclasses */
  36. protected $client_id, $client_secret, $access_token;
  37. protected $callback_url;
  38. protected static $METHOD_GET = "GET";
  39. protected static $METHOD_POST = "POST";
  40. protected static $METHOD_DELETE = "DELETE";
  41. /* Set API URLS */
  42. const AuthorizeUrl = 'https://graph.facebook.com/oauth/authorize';
  43. const AccessTokenUrl = 'https://graph.facebook.com/oauth/access_token';
  44. const GraphUrl = 'https://graph.facebook.com/';
  45. /* construct FacebookOAuth object */
  46. function __construct($facebook_config)
  47. {
  48. $this->client_id = $facebook_config['client_id'];
  49. $this->client_secret = $facebook_config['client_secret'];
  50. $this->callback_url = $facebook_config['callback_url'];
  51. $this->access_token = $facebook_config['access_token'];
  52. }
  53. /* Get the authorize URL @returns a string */
  54. public function getAuthorizeUrl($scope=NULL)
  55. {
  56. $params = array();
  57. $params["client_id"] = $this->client_id;
  58. if (!empty($this->callback_url))
  59. {
  60. $params["redirect_uri"] = $this->callback_url;
  61. }
  62. if (is_array($scope))
  63. {
  64. $params["scope"] = implode(",", $scope);
  65. }
  66. elseif ($scope != NULL)
  67. {
  68. $params["scope"] = $scope;
  69. }
  70. return self::AuthorizeUrl."?".OAuthUtils::build_http_query($params);
  71. }
  72. /* Exchange verify code for an access token @returns string access token */
  73. public function getAccessToken($code)
  74. {
  75. $params = array();
  76. $params["client_id"] = $this->client_id;
  77. $params["client_secret"] = $this->client_secret;
  78. $params["code"] = $code;
  79. if (!empty($this->callback_url))
  80. {
  81. $params["redirect_uri"] = $this->callback_url;
  82. }
  83. $url = self::AccessTokenUrl."?".OAuthUtils::build_http_query($params);
  84. $contents = $this->http($url, self::$METHOD_GET);
  85. parse_str($contents, $output);
  86. if (array_key_exists('access_token', $output))
  87. {
  88. $this->access_token = $output['access_token'];
  89. }
  90. return $this->access_token;
  91. }
  92. public function getProfilePictureUrl($facebook_user_id)
  93. {
  94. $result = FALSE;
  95. // Makes sure server supports cURL request
  96. if ((ini_get('open_basedir') == '') && (ini_get('safe_mode') == 'Off' || !ini_get('safe_mode')))
  97. {
  98. $url = 'http://graph.facebook.com/'.$facebook_user_id.'/picture?type=large';
  99. $options = array(
  100. CURLOPT_RETURNTRANSFER => 1,
  101. CURLOPT_FOLLOWLOCATION => 1
  102. );
  103. $ch = curl_init($url);
  104. curl_setopt_array($ch, $options);
  105. $output = curl_exec($ch);
  106. $download = curl_getinfo($ch);
  107. if (preg_match('/static-ak/i', $download['url']))
  108. {
  109. $result = FALSE;
  110. }
  111. else
  112. {
  113. $result = $download['url'];
  114. }
  115. }
  116. return $result;
  117. }
  118. /* GET wrapper for http. */
  119. public function get($location, $fields=NULL, $introspection=FALSE)
  120. {
  121. $params = array();
  122. if (!empty($this->access_token))
  123. {
  124. $params["access_token"] = $this->access_token;
  125. }
  126. if(!empty($fields))
  127. {
  128. $params["fields"] = $fields;
  129. }
  130. if($introspection)
  131. {
  132. $params["metadata"] = 1;
  133. }
  134. $url = self::GraphUrl.OAuthUtils::urlencode_rfc3986($location)."?".OAuthUtils::build_http_query($params);
  135. $response = $this->http($url, self::$METHOD_GET);
  136. return $this->decode_JSON ? json_decode($response) : $response;
  137. }
  138. /* GET IDS wrapper for http. @ids comma separated list of ids */
  139. public function get_ids($ids)
  140. {
  141. $params = array();
  142. if(is_array($ids))
  143. {
  144. $params["ids"] = implode(",", $ids);
  145. }
  146. else
  147. {
  148. $params["ids"] = $ids;
  149. }
  150. if(!empty($this->access_token))
  151. {
  152. $params["access_token"] = $this->access_token;
  153. }
  154. $url = self::GraphUrl."?".OAuthUtils::build_http_query($params);
  155. $response = $this->http($url, self::$METHOD_GET);
  156. return $this->decode_JSON ? json_decode($response) : $response;
  157. }
  158. /* POST wrapper for http.*/
  159. public function post($location, $postfields = array())
  160. {
  161. $url = self::GraphUrl.OAuthUtils::urlencode_rfc3986($location);
  162. if(!empty($this->access_token))
  163. {
  164. $postfields["access_token"] = $this->access_token;
  165. }
  166. $response = $this->http($url, self::$METHOD_POST, $postfields);
  167. return $this->decode_JSON ? json_decode($response) : $response;
  168. }
  169. /* DELETE wrapper for http. */
  170. public function delete($location, $postfields = array())
  171. {
  172. $url = self::GraphUrl.OAuthUtils::urlencode_rfc3986($location);
  173. $postfields = array();
  174. if(!empty($this->access_token))
  175. {
  176. $postfields["access_token"] = $this->access_token;
  177. }
  178. $response = $this->http($url, self::$METHOD_DELETE, $postfields);
  179. return $this->decode_JSON ? json_decode($response) : $response;
  180. }
  181. /**
  182. * Make an HTTP request
  183. *
  184. * @return API results
  185. */
  186. private function http($url, $method="GET", $postfields=NULL)
  187. {
  188. log_message('debug', 'the $url: '.$url);
  189. $this->http_info = array();
  190. $handle = curl_init();
  191. /* Curl settings */
  192. curl_setopt($handle, CURLOPT_HEADER, FALSE);
  193. curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
  194. curl_setopt($handle, CURLOPT_HTTPHEADER, array('Expect:'));
  195. curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
  196. curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
  197. curl_setopt($handle, CURLOPT_TIMEOUT, $this->timeout);
  198. curl_setopt($handle, CURLOPT_USERAGENT, $this->useragent);
  199. curl_setopt($handle, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
  200. if ($this->proxy_settings['behind_proxy']){
  201. curl_setopt($ci, CURLOPT_PROXY, $this->proxy_settings['host']);
  202. curl_setopt($ci, CURLOPT_PROXYPORT, $this->proxy_settings['port']);
  203. curl_setopt($ci, CURLOPT_PROXYUSERPWD, "{$this->proxy_settings['user']}:{$this->proxy_settings['pass']}");
  204. curl_setopt($ci, CURLOPT_PROXYTYPE, $this->proxy_settings['type']);
  205. curl_setopt($ci, CURLOPT_PROXYAUTH, $this->proxy_settings['auth']);
  206. }
  207. switch($method){
  208. case self::$METHOD_POST:
  209. curl_setopt($handle, CURLOPT_POST, TRUE);
  210. if (!empty($postfields)) {
  211. curl_setopt($handle, CURLOPT_POSTFIELDS, $postfields);
  212. }
  213. break;
  214. case self::$METHOD_DELETE:
  215. curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
  216. if (!empty($postfields)){
  217. $url .= "?".OAuthUtils::build_http_query($postfields);
  218. }
  219. break;
  220. }
  221. curl_setopt($handle, CURLOPT_URL, $url);
  222. $response = curl_exec($handle);
  223. $this->http_code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
  224. $this->http_info = array_merge($this->http_info, curl_getinfo($handle));
  225. $this->url = $url;
  226. curl_close($handle);
  227. return $response;
  228. }
  229. /**
  230. * Get the header info to store.
  231. */
  232. function getHeader($ch, $header) {
  233. $i = strpos($header, ':');
  234. if (!empty($i)) {
  235. $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
  236. $value = trim(substr($header, $i + 2));
  237. $this->http_header[$key] = $value;
  238. }
  239. return strlen($header);
  240. }
  241. }
  242. /**
  243. * OAuthUtils
  244. * Copied and adapted from http://oauth.googlecode.com/svn/code/php/
  245. */
  246. class OAuthUtils {
  247. public static function urlencode_rfc3986($input) {
  248. if (is_array($input)) {
  249. return array_map(array('OAuthUtils', 'urlencode_rfc3986'), $input);
  250. } else if (is_scalar($input)) {
  251. return str_replace(
  252. '+',
  253. ' ',
  254. str_replace('%7E', '~', rawurlencode($input))
  255. );
  256. } else {
  257. return '';
  258. }
  259. }
  260. public static function build_http_query($params) {
  261. if (!$params) return '';
  262. // Urlencode both keys and values
  263. $keys = OAuthUtils::urlencode_rfc3986(array_keys($params));
  264. $values = OAuthUtils::urlencode_rfc3986(array_values($params));
  265. $params = array_combine($keys, $values);
  266. $pairs = array();
  267. foreach ($params as $parameter => $value) {
  268. if (is_array($value)) {
  269. foreach ($value as $duplicate_value) {
  270. $pairs[] = $parameter . '=' . $duplicate_value;
  271. }
  272. } else {
  273. $pairs[] = $parameter . '=' . $value;
  274. }
  275. }
  276. // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
  277. // Each name-value pair is separated by an '&' character (ASCII code 38)
  278. return implode('&', $pairs);
  279. }
  280. }