base_facebook.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. <?php
  2. /**
  3. * Copyright 2011 Facebook, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. * not use this file except in compliance with the License. You may obtain
  7. * a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. * License for the specific language governing permissions and limitations
  15. * under the License.
  16. */
  17. if (!function_exists('curl_init')) {
  18. throw new Exception('Facebook needs the CURL PHP extension.');
  19. }
  20. if (!function_exists('json_decode')) {
  21. throw new Exception('Facebook needs the JSON PHP extension.');
  22. }
  23. /**
  24. * Thrown when an API call returns an exception.
  25. *
  26. * @author Naitik Shah <naitik@facebook.com>
  27. */
  28. class FacebookApiException extends Exception
  29. {
  30. /**
  31. * The result from the API server that represents the exception information.
  32. */
  33. protected $result;
  34. /**
  35. * Make a new API Exception with the given result.
  36. *
  37. * @param array $result The result from the API server
  38. */
  39. public function __construct($result) {
  40. $this->result = $result;
  41. $code = isset($result['error_code']) ? $result['error_code'] : 0;
  42. if (isset($result['error_description'])) {
  43. // OAuth 2.0 Draft 10 style
  44. $msg = $result['error_description'];
  45. } else if (isset($result['error']) && is_array($result['error'])) {
  46. // OAuth 2.0 Draft 00 style
  47. $msg = $result['error']['message'];
  48. } else if (isset($result['error_msg'])) {
  49. // Rest server style
  50. $msg = $result['error_msg'];
  51. } else {
  52. $msg = 'Unknown Error. Check getResult()';
  53. }
  54. parent::__construct($msg, $code);
  55. }
  56. /**
  57. * Return the associated result object returned by the API server.
  58. *
  59. * @return array The result from the API server
  60. */
  61. public function getResult() {
  62. return $this->result;
  63. }
  64. /**
  65. * Returns the associated type for the error. This will default to
  66. * 'Exception' when a type is not available.
  67. *
  68. * @return string
  69. */
  70. public function getType() {
  71. if (isset($this->result['error'])) {
  72. $error = $this->result['error'];
  73. if (is_string($error)) {
  74. // OAuth 2.0 Draft 10 style
  75. return $error;
  76. } else if (is_array($error)) {
  77. // OAuth 2.0 Draft 00 style
  78. if (isset($error['type'])) {
  79. return $error['type'];
  80. }
  81. }
  82. }
  83. return 'Exception';
  84. }
  85. /**
  86. * To make debugging easier.
  87. *
  88. * @return string The string representation of the error
  89. */
  90. public function __toString() {
  91. $str = $this->getType() . ': ';
  92. if ($this->code != 0) {
  93. $str .= $this->code . ': ';
  94. }
  95. return $str . $this->message;
  96. }
  97. }
  98. /**
  99. * Provides access to the Facebook Platform. This class provides
  100. * a majority of the functionality needed, but the class is abstract
  101. * because it is designed to be sub-classed. The subclass must
  102. * implement the four abstract methods listed at the bottom of
  103. * the file.
  104. *
  105. * @author Naitik Shah <naitik@facebook.com>
  106. */
  107. abstract class BaseFacebook
  108. {
  109. /**
  110. * Version.
  111. */
  112. const VERSION = '3.1.1';
  113. /**
  114. * Default options for curl.
  115. */
  116. public static $CURL_OPTS = array(
  117. CURLOPT_CONNECTTIMEOUT => 10,
  118. CURLOPT_RETURNTRANSFER => true,
  119. CURLOPT_TIMEOUT => 60,
  120. CURLOPT_USERAGENT => 'facebook-php-3.1',
  121. );
  122. /**
  123. * List of query parameters that get automatically dropped when rebuilding
  124. * the current URL.
  125. */
  126. protected static $DROP_QUERY_PARAMS = array(
  127. 'code',
  128. 'state',
  129. 'signed_request',
  130. );
  131. /**
  132. * Maps aliases to Facebook domains.
  133. */
  134. public static $DOMAIN_MAP = array(
  135. 'api' => 'https://api.facebook.com/',
  136. 'api_video' => 'https://api-video.facebook.com/',
  137. 'api_read' => 'https://api-read.facebook.com/',
  138. 'graph' => 'https://graph.facebook.com/',
  139. 'www' => 'https://www.facebook.com/',
  140. );
  141. /**
  142. * The Application ID.
  143. *
  144. * @var string
  145. */
  146. protected $appId;
  147. /**
  148. * The Application API Secret.
  149. *
  150. * @var string
  151. */
  152. protected $apiSecret;
  153. /**
  154. * The ID of the Facebook user, or 0 if the user is logged out.
  155. *
  156. * @var integer
  157. */
  158. protected $user;
  159. /**
  160. * The data from the signed_request token.
  161. */
  162. protected $signedRequest;
  163. /**
  164. * A CSRF state variable to assist in the defense against CSRF attacks.
  165. */
  166. protected $state;
  167. /**
  168. * The OAuth access token received in exchange for a valid authorization
  169. * code. null means the access token has yet to be determined.
  170. *
  171. * @var string
  172. */
  173. protected $accessToken = null;
  174. /**
  175. * Indicates if the CURL based @ syntax for file uploads is enabled.
  176. *
  177. * @var boolean
  178. */
  179. protected $fileUploadSupport = false;
  180. /**
  181. * Initialize a Facebook Application.
  182. *
  183. * The configuration:
  184. * - appId: the application ID
  185. * - secret: the application secret
  186. * - fileUpload: (optional) boolean indicating if file uploads are enabled
  187. *
  188. * @param array $config The application configuration
  189. */
  190. public function __construct($config) {
  191. $this->setAppId($config['appId']);
  192. $this->setApiSecret($config['secret']);
  193. if (isset($config['fileUpload'])) {
  194. $this->setFileUploadSupport($config['fileUpload']);
  195. }
  196. $state = $this->getPersistentData('state');
  197. if (!empty($state)) {
  198. $this->state = $this->getPersistentData('state');
  199. }
  200. }
  201. /**
  202. * Set the Application ID.
  203. *
  204. * @param string $appId The Application ID
  205. * @return BaseFacebook
  206. */
  207. public function setAppId($appId) {
  208. $this->appId = $appId;
  209. return $this;
  210. }
  211. /**
  212. * Get the Application ID.
  213. *
  214. * @return string the Application ID
  215. */
  216. public function getAppId() {
  217. return $this->appId;
  218. }
  219. /**
  220. * Set the API Secret.
  221. *
  222. * @param string $apiSecret The API Secret
  223. * @return BaseFacebook
  224. */
  225. public function setApiSecret($apiSecret) {
  226. $this->apiSecret = $apiSecret;
  227. return $this;
  228. }
  229. /**
  230. * Get the API Secret.
  231. *
  232. * @return string the API Secret
  233. */
  234. public function getApiSecret() {
  235. return $this->apiSecret;
  236. }
  237. /**
  238. * Set the file upload support status.
  239. *
  240. * @param boolean $fileUploadSupport The file upload support status.
  241. * @return BaseFacebook
  242. */
  243. public function setFileUploadSupport($fileUploadSupport) {
  244. $this->fileUploadSupport = $fileUploadSupport;
  245. return $this;
  246. }
  247. /**
  248. * Get the file upload support status.
  249. *
  250. * @return boolean true if and only if the server supports file upload.
  251. */
  252. public function useFileUploadSupport() {
  253. return $this->fileUploadSupport;
  254. }
  255. /**
  256. * Sets the access token for api calls. Use this if you get
  257. * your access token by other means and just want the SDK
  258. * to use it.
  259. *
  260. * @param string $access_token an access token.
  261. * @return BaseFacebook
  262. */
  263. public function setAccessToken($access_token) {
  264. $this->accessToken = $access_token;
  265. return $this;
  266. }
  267. /**
  268. * Determines the access token that should be used for API calls.
  269. * The first time this is called, $this->accessToken is set equal
  270. * to either a valid user access token, or it's set to the application
  271. * access token if a valid user access token wasn't available. Subsequent
  272. * calls return whatever the first call returned.
  273. *
  274. * @return string The access token
  275. */
  276. public function getAccessToken() {
  277. if ($this->accessToken !== null) {
  278. // we've done this already and cached it. Just return.
  279. return $this->accessToken;
  280. }
  281. // first establish access token to be the application
  282. // access token, in case we navigate to the /oauth/access_token
  283. // endpoint, where SOME access token is required.
  284. $this->setAccessToken($this->getApplicationAccessToken());
  285. if ($user_access_token = $this->getUserAccessToken()) {
  286. $this->setAccessToken($user_access_token);
  287. }
  288. return $this->accessToken;
  289. }
  290. /**
  291. * Determines and returns the user access token, first using
  292. * the signed request if present, and then falling back on
  293. * the authorization code if present. The intent is to
  294. * return a valid user access token, or false if one is determined
  295. * to not be available.
  296. *
  297. * @return string A valid user access token, or false if one
  298. * could not be determined.
  299. */
  300. protected function getUserAccessToken() {
  301. // first, consider a signed request if it's supplied.
  302. // if there is a signed request, then it alone determines
  303. // the access token.
  304. $signed_request = $this->getSignedRequest();
  305. if ($signed_request) {
  306. // apps.facebook.com hands the access_token in the signed_request
  307. if (array_key_exists('oauth_token', $signed_request)) {
  308. $access_token = $signed_request['oauth_token'];
  309. $this->setPersistentData('access_token', $access_token);
  310. return $access_token;
  311. }
  312. // the JS SDK puts a code in with the redirect_uri of ''
  313. if (array_key_exists('code', $signed_request)) {
  314. $code = $signed_request['code'];
  315. $access_token = $this->getAccessTokenFromCode($code, '');
  316. if ($access_token) {
  317. $this->setPersistentData('code', $code);
  318. $this->setPersistentData('access_token', $access_token);
  319. return $access_token;
  320. }
  321. }
  322. // signed request states there's no access token, so anything
  323. // stored should be cleared.
  324. $this->clearAllPersistentData();
  325. return false; // respect the signed request's data, even
  326. // if there's an authorization code or something else
  327. }
  328. $code = $this->getCode();
  329. if ($code && $code != $this->getPersistentData('code')) {
  330. $access_token = $this->getAccessTokenFromCode($code);
  331. if ($access_token) {
  332. $this->setPersistentData('code', $code);
  333. $this->setPersistentData('access_token', $access_token);
  334. return $access_token;
  335. }
  336. // code was bogus, so everything based on it should be invalidated.
  337. $this->clearAllPersistentData();
  338. return false;
  339. }
  340. // as a fallback, just return whatever is in the persistent
  341. // store, knowing nothing explicit (signed request, authorization
  342. // code, etc.) was present to shadow it (or we saw a code in $_REQUEST,
  343. // but it's the same as what's in the persistent store)
  344. return $this->getPersistentData('access_token');
  345. }
  346. /**
  347. * Retrieve the signed request, either from a request parameter or,
  348. * if not present, from a cookie.
  349. *
  350. * @return string the signed request, if available, or null otherwise.
  351. */
  352. public function getSignedRequest() {
  353. if (!$this->signedRequest) {
  354. if (isset($_REQUEST['signed_request'])) {
  355. $this->signedRequest = $this->parseSignedRequest(
  356. $_REQUEST['signed_request']);
  357. } else if (isset($_COOKIE[$this->getSignedRequestCookieName()])) {
  358. $this->signedRequest = $this->parseSignedRequest(
  359. $_COOKIE[$this->getSignedRequestCookieName()]);
  360. }
  361. }
  362. return $this->signedRequest;
  363. }
  364. /**
  365. * Get the UID of the connected user, or 0
  366. * if the Facebook user is not connected.
  367. *
  368. * @return string the UID if available.
  369. */
  370. public function getUser() {
  371. if ($this->user !== null) {
  372. // we've already determined this and cached the value.
  373. return $this->user;
  374. }
  375. return $this->user = $this->getUserFromAvailableData();
  376. }
  377. /**
  378. * Determines the connected user by first examining any signed
  379. * requests, then considering an authorization code, and then
  380. * falling back to any persistent store storing the user.
  381. *
  382. * @return integer The id of the connected Facebook user,
  383. * or 0 if no such user exists.
  384. */
  385. protected function getUserFromAvailableData() {
  386. // if a signed request is supplied, then it solely determines
  387. // who the user is.
  388. $signed_request = $this->getSignedRequest();
  389. if ($signed_request) {
  390. if (array_key_exists('user_id', $signed_request)) {
  391. $user = $signed_request['user_id'];
  392. $this->setPersistentData('user_id', $signed_request['user_id']);
  393. return $user;
  394. }
  395. // if the signed request didn't present a user id, then invalidate
  396. // all entries in any persistent store.
  397. $this->clearAllPersistentData();
  398. return 0;
  399. }
  400. $user = $this->getPersistentData('user_id', $default = 0);
  401. $persisted_access_token = $this->getPersistentData('access_token');
  402. // use access_token to fetch user id if we have a user access_token, or if
  403. // the cached access token has changed.
  404. $access_token = $this->getAccessToken();
  405. if ($access_token &&
  406. $access_token != $this->getApplicationAccessToken() &&
  407. !($user && $persisted_access_token == $access_token)) {
  408. $user = $this->getUserFromAccessToken();
  409. if ($user) {
  410. $this->setPersistentData('user_id', $user);
  411. } else {
  412. $this->clearAllPersistentData();
  413. }
  414. }
  415. return $user;
  416. }
  417. /**
  418. * Get a Login URL for use with redirects. By default, full page redirect is
  419. * assumed. If you are using the generated URL with a window.open() call in
  420. * JavaScript, you can pass in display=popup as part of the $params.
  421. *
  422. * The parameters:
  423. * - redirect_uri: the url to go to after a successful login
  424. * - scope: comma separated list of requested extended perms
  425. *
  426. * @param array $params Provide custom parameters
  427. * @return string The URL for the login flow
  428. */
  429. public function getLoginUrl($params=array()) {
  430. $this->establishCSRFTokenState();
  431. $currentUrl = $this->getCurrentUrl();
  432. // if 'scope' is passed as an array, convert to comma separated list
  433. $scopeParams = isset($params['scope']) ? $params['scope'] : null;
  434. if ($scopeParams && is_array($scopeParams)) {
  435. $params['scope'] = implode(',', $scopeParams);
  436. }
  437. return $this->getUrl(
  438. 'www',
  439. 'dialog/oauth',
  440. array_merge(array(
  441. 'client_id' => $this->getAppId(),
  442. 'redirect_uri' => $currentUrl, // possibly overwritten
  443. 'state' => $this->state),
  444. $params));
  445. }
  446. /**
  447. * Get a Logout URL suitable for use with redirects.
  448. *
  449. * The parameters:
  450. * - next: the url to go to after a successful logout
  451. *
  452. * @param array $params Provide custom parameters
  453. * @return string The URL for the logout flow
  454. */
  455. public function getLogoutUrl($params=array()) {
  456. return $this->getUrl(
  457. 'www',
  458. 'logout.php',
  459. array_merge(array(
  460. 'next' => $this->getCurrentUrl(),
  461. 'access_token' => $this->getAccessToken(),
  462. ), $params)
  463. );
  464. }
  465. /**
  466. * Get a login status URL to fetch the status from Facebook.
  467. *
  468. * The parameters:
  469. * - ok_session: the URL to go to if a session is found
  470. * - no_session: the URL to go to if the user is not connected
  471. * - no_user: the URL to go to if the user is not signed into facebook
  472. *
  473. * @param array $params Provide custom parameters
  474. * @return string The URL for the logout flow
  475. */
  476. public function getLoginStatusUrl($params=array()) {
  477. return $this->getUrl(
  478. 'www',
  479. 'extern/login_status.php',
  480. array_merge(array(
  481. 'api_key' => $this->getAppId(),
  482. 'no_session' => $this->getCurrentUrl(),
  483. 'no_user' => $this->getCurrentUrl(),
  484. 'ok_session' => $this->getCurrentUrl(),
  485. 'session_version' => 3,
  486. ), $params)
  487. );
  488. }
  489. /**
  490. * Make an API call.
  491. *
  492. * @return mixed The decoded response
  493. */
  494. public function api(/* polymorphic */) {
  495. $args = func_get_args();
  496. if (is_array($args[0])) {
  497. return $this->_restserver($args[0]);
  498. } else {
  499. return call_user_func_array(array($this, '_graph'), $args);
  500. }
  501. }
  502. /**
  503. * Constructs and returns the name of the cookie that
  504. * potentially houses the signed request for the app user.
  505. * The cookie is not set by the BaseFacebook class, but
  506. * it may be set by the JavaScript SDK.
  507. *
  508. * @return string the name of the cookie that would house
  509. * the signed request value.
  510. */
  511. protected function getSignedRequestCookieName() {
  512. return 'fbsr_'.$this->getAppId();
  513. }
  514. /**
  515. * Get the authorization code from the query parameters, if it exists,
  516. * and otherwise return false to signal no authorization code was
  517. * discoverable.
  518. *
  519. * @return mixed The authorization code, or false if the authorization
  520. * code could not be determined.
  521. */
  522. protected function getCode() {
  523. if (isset($_REQUEST['code'])) {
  524. if ($this->state !== null &&
  525. isset($_REQUEST['state']) &&
  526. $this->state === $_REQUEST['state']) {
  527. // CSRF state has done its job, so clear it
  528. $this->state = null;
  529. $this->clearPersistentData('state');
  530. return $_REQUEST['code'];
  531. } else {
  532. self::errorLog('CSRF state token does not match one provided.');
  533. return false;
  534. }
  535. }
  536. return false;
  537. }
  538. /**
  539. * Retrieves the UID with the understanding that
  540. * $this->accessToken has already been set and is
  541. * seemingly legitimate. It relies on Facebook's Graph API
  542. * to retrieve user information and then extract
  543. * the user ID.
  544. *
  545. * @return integer Returns the UID of the Facebook user, or 0
  546. * if the Facebook user could not be determined.
  547. */
  548. protected function getUserFromAccessToken() {
  549. try {
  550. $user_info = $this->api('/me');
  551. return $user_info['id'];
  552. } catch (FacebookApiException $e) {
  553. return 0;
  554. }
  555. }
  556. /**
  557. * Returns the access token that should be used for logged out
  558. * users when no authorization code is available.
  559. *
  560. * @return string The application access token, useful for gathering
  561. * public information about users and applications.
  562. */
  563. protected function getApplicationAccessToken() {
  564. return $this->appId.'|'.$this->apiSecret;
  565. }
  566. /**
  567. * Lays down a CSRF state token for this process.
  568. *
  569. * @return void
  570. */
  571. protected function establishCSRFTokenState() {
  572. if ($this->state === null) {
  573. $this->state = md5(uniqid(mt_rand(), true));
  574. $this->setPersistentData('state', $this->state);
  575. }
  576. }
  577. /**
  578. * Retrieves an access token for the given authorization code
  579. * (previously generated from www.facebook.com on behalf of
  580. * a specific user). The authorization code is sent to graph.facebook.com
  581. * and a legitimate access token is generated provided the access token
  582. * and the user for which it was generated all match, and the user is
  583. * either logged in to Facebook or has granted an offline access permission.
  584. *
  585. * @param string $code An authorization code.
  586. * @return mixed An access token exchanged for the authorization code, or
  587. * false if an access token could not be generated.
  588. */
  589. protected function getAccessTokenFromCode($code, $redirect_uri = null) {
  590. if (empty($code)) {
  591. return false;
  592. }
  593. if ($redirect_uri === null) {
  594. $redirect_uri = $this->getCurrentUrl();
  595. }
  596. try {
  597. // need to circumvent json_decode by calling _oauthRequest
  598. // directly, since response isn't JSON format.
  599. $access_token_response =
  600. $this->_oauthRequest(
  601. $this->getUrl('graph', '/oauth/access_token'),
  602. $params = array('client_id' => $this->getAppId(),
  603. 'client_secret' => $this->getApiSecret(),
  604. 'redirect_uri' => $redirect_uri,
  605. 'code' => $code));
  606. } catch (FacebookApiException $e) {
  607. // most likely that user very recently revoked authorization.
  608. // In any event, we don't have an access token, so say so.
  609. return false;
  610. }
  611. if (empty($access_token_response)) {
  612. return false;
  613. }
  614. $response_params = array();
  615. parse_str($access_token_response, $response_params);
  616. if (!isset($response_params['access_token'])) {
  617. return false;
  618. }
  619. return $response_params['access_token'];
  620. }
  621. /**
  622. * Invoke the old restserver.php endpoint.
  623. *
  624. * @param array $params Method call object
  625. *
  626. * @return mixed The decoded response object
  627. * @throws FacebookApiException
  628. */
  629. protected function _restserver($params) {
  630. // generic application level parameters
  631. $params['api_key'] = $this->getAppId();
  632. $params['format'] = 'json-strings';
  633. $result = json_decode($this->_oauthRequest(
  634. $this->getApiUrl($params['method']),
  635. $params
  636. ), true);
  637. // results are returned, errors are thrown
  638. if (is_array($result) && isset($result['error_code'])) {
  639. throw new FacebookApiException($result);
  640. }
  641. return $result;
  642. }
  643. /**
  644. * Invoke the Graph API.
  645. *
  646. * @param string $path The path (required)
  647. * @param string $method The http method (default 'GET')
  648. * @param array $params The query/post data
  649. *
  650. * @return mixed The decoded response object
  651. * @throws FacebookApiException
  652. */
  653. protected function _graph($path, $method = 'GET', $params = array()) {
  654. if (is_array($method) && empty($params)) {
  655. $params = $method;
  656. $method = 'GET';
  657. }
  658. $params['method'] = $method; // method override as we always do a POST
  659. $result = json_decode($this->_oauthRequest(
  660. $this->getUrl('graph', $path),
  661. $params
  662. ), true);
  663. // results are returned, errors are thrown
  664. if (is_array($result) && isset($result['error'])) {
  665. $this->throwAPIException($result);
  666. }
  667. return $result;
  668. }
  669. /**
  670. * Make a OAuth Request.
  671. *
  672. * @param string $url The path (required)
  673. * @param array $params The query/post data
  674. *
  675. * @return string The decoded response object
  676. * @throws FacebookApiException
  677. */
  678. protected function _oauthRequest($url, $params) {
  679. if (!isset($params['access_token'])) {
  680. $params['access_token'] = $this->getAccessToken();
  681. }
  682. // json_encode all params values that are not strings
  683. foreach ($params as $key => $value) {
  684. if (!is_string($value)) {
  685. $params[$key] = json_encode($value);
  686. }
  687. }
  688. return $this->makeRequest($url, $params);
  689. }
  690. /**
  691. * Makes an HTTP request. This method can be overridden by subclasses if
  692. * developers want to do fancier things or use something other than curl to
  693. * make the request.
  694. *
  695. * @param string $url The URL to make the request to
  696. * @param array $params The parameters to use for the POST body
  697. * @param CurlHandler $ch Initialized curl handle
  698. *
  699. * @return string The response text
  700. */
  701. protected function makeRequest($url, $params, $ch=null) {
  702. if (!$ch) {
  703. $ch = curl_init();
  704. }
  705. $opts = self::$CURL_OPTS;
  706. if ($this->useFileUploadSupport()) {
  707. $opts[CURLOPT_POSTFIELDS] = $params;
  708. } else {
  709. $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
  710. }
  711. $opts[CURLOPT_URL] = $url;
  712. // disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
  713. // for 2 seconds if the server does not support this header.
  714. if (isset($opts[CURLOPT_HTTPHEADER])) {
  715. $existing_headers = $opts[CURLOPT_HTTPHEADER];
  716. $existing_headers[] = 'Expect:';
  717. $opts[CURLOPT_HTTPHEADER] = $existing_headers;
  718. } else {
  719. $opts[CURLOPT_HTTPHEADER] = array('Expect:');
  720. }
  721. curl_setopt_array($ch, $opts);
  722. $result = curl_exec($ch);
  723. if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
  724. self::errorLog('Invalid or no certificate authority found, '.
  725. 'using bundled information');
  726. curl_setopt($ch, CURLOPT_CAINFO,
  727. dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
  728. $result = curl_exec($ch);
  729. }
  730. if ($result === false) {
  731. $e = new FacebookApiException(array(
  732. 'error_code' => curl_errno($ch),
  733. 'error' => array(
  734. 'message' => curl_error($ch),
  735. 'type' => 'CurlException',
  736. ),
  737. ));
  738. curl_close($ch);
  739. throw $e;
  740. }
  741. curl_close($ch);
  742. return $result;
  743. }
  744. /**
  745. * Parses a signed_request and validates the signature.
  746. *
  747. * @param string $signed_request A signed token
  748. * @return array The payload inside it or null if the sig is wrong
  749. */
  750. protected function parseSignedRequest($signed_request) {
  751. list($encoded_sig, $payload) = explode('.', $signed_request, 2);
  752. // decode the data
  753. $sig = self::base64UrlDecode($encoded_sig);
  754. $data = json_decode(self::base64UrlDecode($payload), true);
  755. if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
  756. self::errorLog('Unknown algorithm. Expected HMAC-SHA256');
  757. return null;
  758. }
  759. // check sig
  760. $expected_sig = hash_hmac('sha256', $payload,
  761. $this->getApiSecret(), $raw = true);
  762. if ($sig !== $expected_sig) {
  763. self::errorLog('Bad Signed JSON signature!');
  764. return null;
  765. }
  766. return $data;
  767. }
  768. /**
  769. * Build the URL for api given parameters.
  770. *
  771. * @param $method String the method name.
  772. * @return string The URL for the given parameters
  773. */
  774. protected function getApiUrl($method) {
  775. static $READ_ONLY_CALLS =
  776. array('admin.getallocation' => 1,
  777. 'admin.getappproperties' => 1,
  778. 'admin.getbannedusers' => 1,
  779. 'admin.getlivestreamvialink' => 1,
  780. 'admin.getmetrics' => 1,
  781. 'admin.getrestrictioninfo' => 1,
  782. 'application.getpublicinfo' => 1,
  783. 'auth.getapppublickey' => 1,
  784. 'auth.getsession' => 1,
  785. 'auth.getsignedpublicsessiondata' => 1,
  786. 'comments.get' => 1,
  787. 'connect.getunconnectedfriendscount' => 1,
  788. 'dashboard.getactivity' => 1,
  789. 'dashboard.getcount' => 1,
  790. 'dashboard.getglobalnews' => 1,
  791. 'dashboard.getnews' => 1,
  792. 'dashboard.multigetcount' => 1,
  793. 'dashboard.multigetnews' => 1,
  794. 'data.getcookies' => 1,
  795. 'events.get' => 1,
  796. 'events.getmembers' => 1,
  797. 'fbml.getcustomtags' => 1,
  798. 'feed.getappfriendstories' => 1,
  799. 'feed.getregisteredtemplatebundlebyid' => 1,
  800. 'feed.getregisteredtemplatebundles' => 1,
  801. 'fql.multiquery' => 1,
  802. 'fql.query' => 1,
  803. 'friends.arefriends' => 1,
  804. 'friends.get' => 1,
  805. 'friends.getappusers' => 1,
  806. 'friends.getlists' => 1,
  807. 'friends.getmutualfriends' => 1,
  808. 'gifts.get' => 1,
  809. 'groups.get' => 1,
  810. 'groups.getmembers' => 1,
  811. 'intl.gettranslations' => 1,
  812. 'links.get' => 1,
  813. 'notes.get' => 1,
  814. 'notifications.get' => 1,
  815. 'pages.getinfo' => 1,
  816. 'pages.isadmin' => 1,
  817. 'pages.isappadded' => 1,
  818. 'pages.isfan' => 1,
  819. 'permissions.checkavailableapiaccess' => 1,
  820. 'permissions.checkgrantedapiaccess' => 1,
  821. 'photos.get' => 1,
  822. 'photos.getalbums' => 1,
  823. 'photos.gettags' => 1,
  824. 'profile.getinfo' => 1,
  825. 'profile.getinfooptions' => 1,
  826. 'stream.get' => 1,
  827. 'stream.getcomments' => 1,
  828. 'stream.getfilters' => 1,
  829. 'users.getinfo' => 1,
  830. 'users.getloggedinuser' => 1,
  831. 'users.getstandardinfo' => 1,
  832. 'users.hasapppermission' => 1,
  833. 'users.isappuser' => 1,
  834. 'users.isverified' => 1,
  835. 'video.getuploadlimits' => 1);
  836. $name = 'api';
  837. if (isset($READ_ONLY_CALLS[strtolower($method)])) {
  838. $name = 'api_read';
  839. } else if (strtolower($method) == 'video.upload') {
  840. $name = 'api_video';
  841. }
  842. return self::getUrl($name, 'restserver.php');
  843. }
  844. /**
  845. * Build the URL for given domain alias, path and parameters.
  846. *
  847. * @param $name string The name of the domain
  848. * @param $path string Optional path (without a leading slash)
  849. * @param $params array Optional query parameters
  850. *
  851. * @return string The URL for the given parameters
  852. */
  853. protected function getUrl($name, $path='', $params=array()) {
  854. $url = self::$DOMAIN_MAP[$name];
  855. if ($path) {
  856. if ($path[0] === '/') {
  857. $path = substr($path, 1);
  858. }
  859. $url .= $path;
  860. }
  861. if ($params) {
  862. $url .= '?' . http_build_query($params, null, '&');
  863. }
  864. return $url;
  865. }
  866. /**
  867. * Returns the Current URL, stripping it of known FB parameters that should
  868. * not persist.
  869. *
  870. * @return string The current URL
  871. */
  872. protected function getCurrentUrl() {
  873. if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1)
  874. || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
  875. ) {
  876. $protocol = 'https://';
  877. }
  878. else {
  879. $protocol = 'http://';
  880. }
  881. $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  882. $parts = parse_url($currentUrl);
  883. $query = '';
  884. if (!empty($parts['query'])) {
  885. // drop known fb params
  886. $params = explode('&', $parts['query']);
  887. $retained_params = array();
  888. foreach ($params as $param) {
  889. if ($this->shouldRetainParam($param)) {
  890. $retained_params[] = $param;
  891. }
  892. }
  893. if (!empty($retained_params)) {
  894. $query = '?'.implode($retained_params, '&');
  895. }
  896. }
  897. // use port if non default
  898. $port =
  899. isset($parts['port']) &&
  900. (($protocol === 'http://' && $parts['port'] !== 80) ||
  901. ($protocol === 'https://' && $parts['port'] !== 443))
  902. ? ':' . $parts['port'] : '';
  903. // rebuild
  904. return $protocol . $parts['host'] . $port . $parts['path'] . $query;
  905. }
  906. /**
  907. * Returns true if and only if the key or key/value pair should
  908. * be retained as part of the query string. This amounts to
  909. * a brute-force search of the very small list of Facebook-specific
  910. * params that should be stripped out.
  911. *
  912. * @param string $param A key or key/value pair within a URL's query (e.g.
  913. * 'foo=a', 'foo=', or 'foo'.
  914. *
  915. * @return boolean
  916. */
  917. protected function shouldRetainParam($param) {
  918. foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {
  919. if (strpos($param, $drop_query_param.'=') === 0) {
  920. return false;
  921. }
  922. }
  923. return true;
  924. }
  925. /**
  926. * Analyzes the supplied result to see if it was thrown
  927. * because the access token is no longer valid. If that is
  928. * the case, then the persistent store is cleared.
  929. *
  930. * @param $result array A record storing the error message returned
  931. * by a failed API call.
  932. */
  933. protected function throwAPIException($result) {
  934. $e = new FacebookApiException($result);
  935. switch ($e->getType()) {
  936. // OAuth 2.0 Draft 00 style
  937. case 'OAuthException':
  938. // OAuth 2.0 Draft 10 style
  939. case 'invalid_token':
  940. $message = $e->getMessage();
  941. if ((strpos($message, 'Error validating access token') !== false) ||
  942. (strpos($message, 'Invalid OAuth access token') !== false)) {
  943. $this->setAccessToken(null);
  944. $this->user = 0;
  945. $this->clearAllPersistentData();
  946. }
  947. }
  948. throw $e;
  949. }
  950. /**
  951. * Prints to the error log if you aren't in command line mode.
  952. *
  953. * @param string $msg Log message
  954. */
  955. protected static function errorLog($msg) {
  956. // disable error log if we are running in a CLI environment
  957. // @codeCoverageIgnoreStart
  958. if (php_sapi_name() != 'cli') {
  959. error_log($msg);
  960. }
  961. // uncomment this if you want to see the errors on the page
  962. // print 'error_log: '.$msg."\n";
  963. // @codeCoverageIgnoreEnd
  964. }
  965. /**
  966. * Base64 encoding that doesn't need to be urlencode()ed.
  967. * Exactly the same as base64_encode except it uses
  968. * - instead of +
  969. * _ instead of /
  970. *
  971. * @param string $input base64UrlEncoded string
  972. * @return string
  973. */
  974. protected static function base64UrlDecode($input) {
  975. return base64_decode(strtr($input, '-_', '+/'));
  976. }
  977. /**
  978. * Each of the following four methods should be overridden in
  979. * a concrete subclass, as they are in the provided Facebook class.
  980. * The Facebook class uses PHP sessions to provide a primitive
  981. * persistent store, but another subclass--one that you implement--
  982. * might use a database, memcache, or an in-memory cache.
  983. *
  984. * @see Facebook
  985. */
  986. /**
  987. * Stores the given ($key, $value) pair, so that future calls to
  988. * getPersistentData($key) return $value. This call may be in another request.
  989. *
  990. * @param string $key
  991. * @param array $value
  992. *
  993. * @return void
  994. */
  995. abstract protected function setPersistentData($key, $value);
  996. /**
  997. * Get the data for $key, persisted by BaseFacebook::setPersistentData()
  998. *
  999. * @param string $key The key of the data to retrieve
  1000. * @param boolean $default The default value to return if $key is not found
  1001. *
  1002. * @return mixed
  1003. */
  1004. abstract protected function getPersistentData($key, $default = false);
  1005. /**
  1006. * Clear the data with $key from the persistent storage
  1007. *
  1008. * @param string $key
  1009. * @return void
  1010. */
  1011. abstract protected function clearPersistentData($key);
  1012. /**
  1013. * Clear all data from the persistent storage
  1014. *
  1015. * @return void
  1016. */
  1017. abstract protected function clearAllPersistentData();
  1018. }