PageRenderTime 45ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/inc/lib/facebook/base_facebook.php

https://bitbucket.org/yoander/mtrack
PHP | 1269 lines | 632 code | 124 blank | 513 comment | 107 complexity | 9e9556021d9375d0804ff7e80ac16e43 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  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. 'graph_video' => 'https://graph-video.facebook.com/',
  140. 'www' => 'https://www.facebook.com/',
  141. );
  142. /**
  143. * The Application ID.
  144. *
  145. * @var string
  146. */
  147. protected $appId;
  148. /**
  149. * The Application App Secret.
  150. *
  151. * @var string
  152. */
  153. protected $appSecret;
  154. /**
  155. * The ID of the Facebook user, or 0 if the user is logged out.
  156. *
  157. * @var integer
  158. */
  159. protected $user;
  160. /**
  161. * The data from the signed_request token.
  162. */
  163. protected $signedRequest;
  164. /**
  165. * A CSRF state variable to assist in the defense against CSRF attacks.
  166. */
  167. protected $state;
  168. /**
  169. * The OAuth access token received in exchange for a valid authorization
  170. * code. null means the access token has yet to be determined.
  171. *
  172. * @var string
  173. */
  174. protected $accessToken = null;
  175. /**
  176. * Indicates if the CURL based @ syntax for file uploads is enabled.
  177. *
  178. * @var boolean
  179. */
  180. protected $fileUploadSupport = false;
  181. /**
  182. * Initialize a Facebook Application.
  183. *
  184. * The configuration:
  185. * - appId: the application ID
  186. * - secret: the application secret
  187. * - fileUpload: (optional) boolean indicating if file uploads are enabled
  188. *
  189. * @param array $config The application configuration
  190. */
  191. public function __construct($config) {
  192. $this->setAppId($config['appId']);
  193. $this->setAppSecret($config['secret']);
  194. if (isset($config['fileUpload'])) {
  195. $this->setFileUploadSupport($config['fileUpload']);
  196. }
  197. $state = $this->getPersistentData('state');
  198. if (!empty($state)) {
  199. $this->state = $this->getPersistentData('state');
  200. }
  201. }
  202. /**
  203. * Set the Application ID.
  204. *
  205. * @param string $appId The Application ID
  206. * @return BaseFacebook
  207. */
  208. public function setAppId($appId) {
  209. $this->appId = $appId;
  210. return $this;
  211. }
  212. /**
  213. * Get the Application ID.
  214. *
  215. * @return string the Application ID
  216. */
  217. public function getAppId() {
  218. return $this->appId;
  219. }
  220. /**
  221. * Set the App Secret.
  222. *
  223. * @param string $apiSecret The App Secret
  224. * @return BaseFacebook
  225. * @deprecated
  226. */
  227. public function setApiSecret($apiSecret) {
  228. $this->setAppSecret($apiSecret);
  229. return $this;
  230. }
  231. /**
  232. * Set the App Secret.
  233. *
  234. * @param string $appSecret The App Secret
  235. * @return BaseFacebook
  236. */
  237. public function setAppSecret($appSecret) {
  238. $this->appSecret = $appSecret;
  239. return $this;
  240. }
  241. /**
  242. * Get the App Secret.
  243. *
  244. * @return string the App Secret
  245. * @deprecated
  246. */
  247. public function getApiSecret() {
  248. return $this->getAppSecret();
  249. }
  250. /**
  251. * Get the App Secret.
  252. *
  253. * @return string the App Secret
  254. */
  255. public function getAppSecret() {
  256. return $this->appSecret;
  257. }
  258. /**
  259. * Set the file upload support status.
  260. *
  261. * @param boolean $fileUploadSupport The file upload support status.
  262. * @return BaseFacebook
  263. */
  264. public function setFileUploadSupport($fileUploadSupport) {
  265. $this->fileUploadSupport = $fileUploadSupport;
  266. return $this;
  267. }
  268. /**
  269. * Get the file upload support status.
  270. *
  271. * @return boolean true if and only if the server supports file upload.
  272. */
  273. public function getFileUploadSupport() {
  274. return $this->fileUploadSupport;
  275. }
  276. /**
  277. * DEPRECATED! Please use getFileUploadSupport instead.
  278. *
  279. * Get the file upload support status.
  280. *
  281. * @return boolean true if and only if the server supports file upload.
  282. */
  283. public function useFileUploadSupport() {
  284. return $this->getFileUploadSupport();
  285. }
  286. /**
  287. * Sets the access token for api calls. Use this if you get
  288. * your access token by other means and just want the SDK
  289. * to use it.
  290. *
  291. * @param string $access_token an access token.
  292. * @return BaseFacebook
  293. */
  294. public function setAccessToken($access_token) {
  295. $this->accessToken = $access_token;
  296. return $this;
  297. }
  298. /**
  299. * Determines the access token that should be used for API calls.
  300. * The first time this is called, $this->accessToken is set equal
  301. * to either a valid user access token, or it's set to the application
  302. * access token if a valid user access token wasn't available. Subsequent
  303. * calls return whatever the first call returned.
  304. *
  305. * @return string The access token
  306. */
  307. public function getAccessToken() {
  308. if ($this->accessToken !== null) {
  309. // we've done this already and cached it. Just return.
  310. return $this->accessToken;
  311. }
  312. // first establish access token to be the application
  313. // access token, in case we navigate to the /oauth/access_token
  314. // endpoint, where SOME access token is required.
  315. $this->setAccessToken($this->getApplicationAccessToken());
  316. $user_access_token = $this->getUserAccessToken();
  317. if ($user_access_token) {
  318. $this->setAccessToken($user_access_token);
  319. }
  320. return $this->accessToken;
  321. }
  322. /**
  323. * Determines and returns the user access token, first using
  324. * the signed request if present, and then falling back on
  325. * the authorization code if present. The intent is to
  326. * return a valid user access token, or false if one is determined
  327. * to not be available.
  328. *
  329. * @return string A valid user access token, or false if one
  330. * could not be determined.
  331. */
  332. protected function getUserAccessToken() {
  333. // first, consider a signed request if it's supplied.
  334. // if there is a signed request, then it alone determines
  335. // the access token.
  336. $signed_request = $this->getSignedRequest();
  337. if ($signed_request) {
  338. // apps.facebook.com hands the access_token in the signed_request
  339. if (array_key_exists('oauth_token', $signed_request)) {
  340. $access_token = $signed_request['oauth_token'];
  341. $this->setPersistentData('access_token', $access_token);
  342. return $access_token;
  343. }
  344. // the JS SDK puts a code in with the redirect_uri of ''
  345. if (array_key_exists('code', $signed_request)) {
  346. $code = $signed_request['code'];
  347. $access_token = $this->getAccessTokenFromCode($code, '');
  348. if ($access_token) {
  349. $this->setPersistentData('code', $code);
  350. $this->setPersistentData('access_token', $access_token);
  351. return $access_token;
  352. }
  353. }
  354. // signed request states there's no access token, so anything
  355. // stored should be cleared.
  356. $this->clearAllPersistentData();
  357. return false; // respect the signed request's data, even
  358. // if there's an authorization code or something else
  359. }
  360. $code = $this->getCode();
  361. if ($code && $code != $this->getPersistentData('code')) {
  362. $access_token = $this->getAccessTokenFromCode($code);
  363. if ($access_token) {
  364. $this->setPersistentData('code', $code);
  365. $this->setPersistentData('access_token', $access_token);
  366. return $access_token;
  367. }
  368. // code was bogus, so everything based on it should be invalidated.
  369. $this->clearAllPersistentData();
  370. return false;
  371. }
  372. // as a fallback, just return whatever is in the persistent
  373. // store, knowing nothing explicit (signed request, authorization
  374. // code, etc.) was present to shadow it (or we saw a code in $_REQUEST,
  375. // but it's the same as what's in the persistent store)
  376. return $this->getPersistentData('access_token');
  377. }
  378. /**
  379. * Retrieve the signed request, either from a request parameter or,
  380. * if not present, from a cookie.
  381. *
  382. * @return string the signed request, if available, or null otherwise.
  383. */
  384. public function getSignedRequest() {
  385. if (!$this->signedRequest) {
  386. if (isset($_REQUEST['signed_request'])) {
  387. $this->signedRequest = $this->parseSignedRequest(
  388. $_REQUEST['signed_request']);
  389. } else if (isset($_COOKIE[$this->getSignedRequestCookieName()])) {
  390. $this->signedRequest = $this->parseSignedRequest(
  391. $_COOKIE[$this->getSignedRequestCookieName()]);
  392. }
  393. }
  394. return $this->signedRequest;
  395. }
  396. /**
  397. * Get the UID of the connected user, or 0
  398. * if the Facebook user is not connected.
  399. *
  400. * @return string the UID if available.
  401. */
  402. public function getUser() {
  403. if ($this->user !== null) {
  404. // we've already determined this and cached the value.
  405. return $this->user;
  406. }
  407. return $this->user = $this->getUserFromAvailableData();
  408. }
  409. /**
  410. * Determines the connected user by first examining any signed
  411. * requests, then considering an authorization code, and then
  412. * falling back to any persistent store storing the user.
  413. *
  414. * @return integer The id of the connected Facebook user,
  415. * or 0 if no such user exists.
  416. */
  417. protected function getUserFromAvailableData() {
  418. // if a signed request is supplied, then it solely determines
  419. // who the user is.
  420. $signed_request = $this->getSignedRequest();
  421. if ($signed_request) {
  422. if (array_key_exists('user_id', $signed_request)) {
  423. $user = $signed_request['user_id'];
  424. $this->setPersistentData('user_id', $signed_request['user_id']);
  425. return $user;
  426. }
  427. // if the signed request didn't present a user id, then invalidate
  428. // all entries in any persistent store.
  429. $this->clearAllPersistentData();
  430. return 0;
  431. }
  432. $user = $this->getPersistentData('user_id', $default = 0);
  433. $persisted_access_token = $this->getPersistentData('access_token');
  434. // use access_token to fetch user id if we have a user access_token, or if
  435. // the cached access token has changed.
  436. $access_token = $this->getAccessToken();
  437. if ($access_token &&
  438. $access_token != $this->getApplicationAccessToken() &&
  439. !($user && $persisted_access_token == $access_token)) {
  440. $user = $this->getUserFromAccessToken();
  441. if ($user) {
  442. $this->setPersistentData('user_id', $user);
  443. } else {
  444. $this->clearAllPersistentData();
  445. }
  446. }
  447. return $user;
  448. }
  449. /**
  450. * Get a Login URL for use with redirects. By default, full page redirect is
  451. * assumed. If you are using the generated URL with a window.open() call in
  452. * JavaScript, you can pass in display=popup as part of the $params.
  453. *
  454. * The parameters:
  455. * - redirect_uri: the url to go to after a successful login
  456. * - scope: comma separated list of requested extended perms
  457. *
  458. * @param array $params Provide custom parameters
  459. * @return string The URL for the login flow
  460. */
  461. public function getLoginUrl($params=array()) {
  462. $this->establishCSRFTokenState();
  463. $currentUrl = $this->getCurrentUrl();
  464. // if 'scope' is passed as an array, convert to comma separated list
  465. $scopeParams = isset($params['scope']) ? $params['scope'] : null;
  466. if ($scopeParams && is_array($scopeParams)) {
  467. $params['scope'] = implode(',', $scopeParams);
  468. }
  469. return $this->getUrl(
  470. 'www',
  471. 'dialog/oauth',
  472. array_merge(array(
  473. 'client_id' => $this->getAppId(),
  474. 'redirect_uri' => $currentUrl, // possibly overwritten
  475. 'state' => $this->state),
  476. $params));
  477. }
  478. /**
  479. * Get a Logout URL suitable for use with redirects.
  480. *
  481. * The parameters:
  482. * - next: the url to go to after a successful logout
  483. *
  484. * @param array $params Provide custom parameters
  485. * @return string The URL for the logout flow
  486. */
  487. public function getLogoutUrl($params=array()) {
  488. return $this->getUrl(
  489. 'www',
  490. 'logout.php',
  491. array_merge(array(
  492. 'next' => $this->getCurrentUrl(),
  493. 'access_token' => $this->getAccessToken(),
  494. ), $params)
  495. );
  496. }
  497. /**
  498. * Get a login status URL to fetch the status from Facebook.
  499. *
  500. * The parameters:
  501. * - ok_session: the URL to go to if a session is found
  502. * - no_session: the URL to go to if the user is not connected
  503. * - no_user: the URL to go to if the user is not signed into facebook
  504. *
  505. * @param array $params Provide custom parameters
  506. * @return string The URL for the logout flow
  507. */
  508. public function getLoginStatusUrl($params=array()) {
  509. return $this->getUrl(
  510. 'www',
  511. 'extern/login_status.php',
  512. array_merge(array(
  513. 'api_key' => $this->getAppId(),
  514. 'no_session' => $this->getCurrentUrl(),
  515. 'no_user' => $this->getCurrentUrl(),
  516. 'ok_session' => $this->getCurrentUrl(),
  517. 'session_version' => 3,
  518. ), $params)
  519. );
  520. }
  521. /**
  522. * Make an API call.
  523. *
  524. * @return mixed The decoded response
  525. */
  526. public function api(/* polymorphic */) {
  527. $args = func_get_args();
  528. if (is_array($args[0])) {
  529. return $this->_restserver($args[0]);
  530. } else {
  531. return call_user_func_array(array($this, '_graph'), $args);
  532. }
  533. }
  534. /**
  535. * Constructs and returns the name of the cookie that
  536. * potentially houses the signed request for the app user.
  537. * The cookie is not set by the BaseFacebook class, but
  538. * it may be set by the JavaScript SDK.
  539. *
  540. * @return string the name of the cookie that would house
  541. * the signed request value.
  542. */
  543. protected function getSignedRequestCookieName() {
  544. return 'fbsr_'.$this->getAppId();
  545. }
  546. /**
  547. * Constructs and returns the name of the coookie that potentially contain
  548. * metadata. The cookie is not set by the BaseFacebook class, but it may be
  549. * set by the JavaScript SDK.
  550. *
  551. * @return string the name of the cookie that would house metadata.
  552. */
  553. protected function getMetadataCookieName() {
  554. return 'fbm_'.$this->getAppId();
  555. }
  556. /**
  557. * Get the authorization code from the query parameters, if it exists,
  558. * and otherwise return false to signal no authorization code was
  559. * discoverable.
  560. *
  561. * @return mixed The authorization code, or false if the authorization
  562. * code could not be determined.
  563. */
  564. protected function getCode() {
  565. if (isset($_REQUEST['code'])) {
  566. if ($this->state !== null &&
  567. isset($_REQUEST['state']) &&
  568. $this->state === $_REQUEST['state']) {
  569. // CSRF state has done its job, so clear it
  570. $this->state = null;
  571. $this->clearPersistentData('state');
  572. return $_REQUEST['code'];
  573. } else {
  574. self::errorLog('CSRF state token does not match one provided.');
  575. return false;
  576. }
  577. }
  578. return false;
  579. }
  580. /**
  581. * Retrieves the UID with the understanding that
  582. * $this->accessToken has already been set and is
  583. * seemingly legitimate. It relies on Facebook's Graph API
  584. * to retrieve user information and then extract
  585. * the user ID.
  586. *
  587. * @return integer Returns the UID of the Facebook user, or 0
  588. * if the Facebook user could not be determined.
  589. */
  590. protected function getUserFromAccessToken() {
  591. try {
  592. $user_info = $this->api('/me');
  593. return $user_info['id'];
  594. } catch (FacebookApiException $e) {
  595. return 0;
  596. }
  597. }
  598. /**
  599. * Returns the access token that should be used for logged out
  600. * users when no authorization code is available.
  601. *
  602. * @return string The application access token, useful for gathering
  603. * public information about users and applications.
  604. */
  605. protected function getApplicationAccessToken() {
  606. return $this->appId.'|'.$this->appSecret;
  607. }
  608. /**
  609. * Lays down a CSRF state token for this process.
  610. *
  611. * @return void
  612. */
  613. protected function establishCSRFTokenState() {
  614. if ($this->state === null) {
  615. $this->state = md5(uniqid(mt_rand(), true));
  616. $this->setPersistentData('state', $this->state);
  617. }
  618. }
  619. /**
  620. * Retrieves an access token for the given authorization code
  621. * (previously generated from www.facebook.com on behalf of
  622. * a specific user). The authorization code is sent to graph.facebook.com
  623. * and a legitimate access token is generated provided the access token
  624. * and the user for which it was generated all match, and the user is
  625. * either logged in to Facebook or has granted an offline access permission.
  626. *
  627. * @param string $code An authorization code.
  628. * @return mixed An access token exchanged for the authorization code, or
  629. * false if an access token could not be generated.
  630. */
  631. protected function getAccessTokenFromCode($code, $redirect_uri = null) {
  632. if (empty($code)) {
  633. return false;
  634. }
  635. if ($redirect_uri === null) {
  636. $redirect_uri = $this->getCurrentUrl();
  637. }
  638. try {
  639. // need to circumvent json_decode by calling _oauthRequest
  640. // directly, since response isn't JSON format.
  641. $access_token_response =
  642. $this->_oauthRequest(
  643. $this->getUrl('graph', '/oauth/access_token'),
  644. $params = array('client_id' => $this->getAppId(),
  645. 'client_secret' => $this->getAppSecret(),
  646. 'redirect_uri' => $redirect_uri,
  647. 'code' => $code));
  648. } catch (FacebookApiException $e) {
  649. // most likely that user very recently revoked authorization.
  650. // In any event, we don't have an access token, so say so.
  651. return false;
  652. }
  653. if (empty($access_token_response)) {
  654. return false;
  655. }
  656. $response_params = array();
  657. parse_str($access_token_response, $response_params);
  658. if (!isset($response_params['access_token'])) {
  659. return false;
  660. }
  661. return $response_params['access_token'];
  662. }
  663. /**
  664. * Invoke the old restserver.php endpoint.
  665. *
  666. * @param array $params Method call object
  667. *
  668. * @return mixed The decoded response object
  669. * @throws FacebookApiException
  670. */
  671. protected function _restserver($params) {
  672. // generic application level parameters
  673. $params['api_key'] = $this->getAppId();
  674. $params['format'] = 'json-strings';
  675. $result = json_decode($this->_oauthRequest(
  676. $this->getApiUrl($params['method']),
  677. $params
  678. ), true);
  679. // results are returned, errors are thrown
  680. if (is_array($result) && isset($result['error_code'])) {
  681. $this->throwAPIException($result);
  682. }
  683. if ($params['method'] === 'auth.expireSession' ||
  684. $params['method'] === 'auth.revokeAuthorization') {
  685. $this->destroySession();
  686. }
  687. return $result;
  688. }
  689. /**
  690. * Return true if this is video post.
  691. *
  692. * @param string $path The path
  693. * @param string $method The http method (default 'GET')
  694. *
  695. * @return boolean true if this is video post
  696. */
  697. protected function isVideoPost($path, $method = 'GET') {
  698. if ($method == 'POST' && preg_match("/^(\/)(.+)(\/)(videos)$/", $path)) {
  699. return true;
  700. }
  701. return false;
  702. }
  703. /**
  704. * Invoke the Graph API.
  705. *
  706. * @param string $path The path (required)
  707. * @param string $method The http method (default 'GET')
  708. * @param array $params The query/post data
  709. *
  710. * @return mixed The decoded response object
  711. * @throws FacebookApiException
  712. */
  713. protected function _graph($path, $method = 'GET', $params = array()) {
  714. if (is_array($method) && empty($params)) {
  715. $params = $method;
  716. $method = 'GET';
  717. }
  718. $params['method'] = $method; // method override as we always do a POST
  719. if ($this->isVideoPost($path, $method)) {
  720. $domainKey = 'graph_video';
  721. } else {
  722. $domainKey = 'graph';
  723. }
  724. $result = json_decode($this->_oauthRequest(
  725. $this->getUrl($domainKey, $path),
  726. $params
  727. ), true);
  728. // results are returned, errors are thrown
  729. if (is_array($result) && isset($result['error'])) {
  730. $this->throwAPIException($result);
  731. }
  732. return $result;
  733. }
  734. /**
  735. * Make a OAuth Request.
  736. *
  737. * @param string $url The path (required)
  738. * @param array $params The query/post data
  739. *
  740. * @return string The decoded response object
  741. * @throws FacebookApiException
  742. */
  743. protected function _oauthRequest($url, $params) {
  744. if (!isset($params['access_token'])) {
  745. $params['access_token'] = $this->getAccessToken();
  746. }
  747. // json_encode all params values that are not strings
  748. foreach ($params as $key => $value) {
  749. if (!is_string($value)) {
  750. $params[$key] = json_encode($value);
  751. }
  752. }
  753. return $this->makeRequest($url, $params);
  754. }
  755. /**
  756. * Makes an HTTP request. This method can be overridden by subclasses if
  757. * developers want to do fancier things or use something other than curl to
  758. * make the request.
  759. *
  760. * @param string $url The URL to make the request to
  761. * @param array $params The parameters to use for the POST body
  762. * @param CurlHandler $ch Initialized curl handle
  763. *
  764. * @return string The response text
  765. */
  766. protected function makeRequest($url, $params, $ch=null) {
  767. if (!$ch) {
  768. $ch = curl_init();
  769. }
  770. $opts = self::$CURL_OPTS;
  771. if ($this->getFileUploadSupport()) {
  772. $opts[CURLOPT_POSTFIELDS] = $params;
  773. } else {
  774. $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
  775. }
  776. $opts[CURLOPT_URL] = $url;
  777. // disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
  778. // for 2 seconds if the server does not support this header.
  779. if (isset($opts[CURLOPT_HTTPHEADER])) {
  780. $existing_headers = $opts[CURLOPT_HTTPHEADER];
  781. $existing_headers[] = 'Expect:';
  782. $opts[CURLOPT_HTTPHEADER] = $existing_headers;
  783. } else {
  784. $opts[CURLOPT_HTTPHEADER] = array('Expect:');
  785. }
  786. curl_setopt_array($ch, $opts);
  787. $result = curl_exec($ch);
  788. if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
  789. self::errorLog('Invalid or no certificate authority found, '.
  790. 'using bundled information');
  791. curl_setopt($ch, CURLOPT_CAINFO,
  792. dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
  793. $result = curl_exec($ch);
  794. }
  795. if ($result === false) {
  796. $e = new FacebookApiException(array(
  797. 'error_code' => curl_errno($ch),
  798. 'error' => array(
  799. 'message' => curl_error($ch),
  800. 'type' => 'CurlException',
  801. ),
  802. ));
  803. curl_close($ch);
  804. throw $e;
  805. }
  806. curl_close($ch);
  807. return $result;
  808. }
  809. /**
  810. * Parses a signed_request and validates the signature.
  811. *
  812. * @param string $signed_request A signed token
  813. * @return array The payload inside it or null if the sig is wrong
  814. */
  815. protected function parseSignedRequest($signed_request) {
  816. list($encoded_sig, $payload) = explode('.', $signed_request, 2);
  817. // decode the data
  818. $sig = self::base64UrlDecode($encoded_sig);
  819. $data = json_decode(self::base64UrlDecode($payload), true);
  820. if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
  821. self::errorLog('Unknown algorithm. Expected HMAC-SHA256');
  822. return null;
  823. }
  824. // check sig
  825. $expected_sig = hash_hmac('sha256', $payload,
  826. $this->getAppSecret(), $raw = true);
  827. if ($sig !== $expected_sig) {
  828. self::errorLog('Bad Signed JSON signature!');
  829. return null;
  830. }
  831. return $data;
  832. }
  833. /**
  834. * Build the URL for api given parameters.
  835. *
  836. * @param $method String the method name.
  837. * @return string The URL for the given parameters
  838. */
  839. protected function getApiUrl($method) {
  840. static $READ_ONLY_CALLS =
  841. array('admin.getallocation' => 1,
  842. 'admin.getappproperties' => 1,
  843. 'admin.getbannedusers' => 1,
  844. 'admin.getlivestreamvialink' => 1,
  845. 'admin.getmetrics' => 1,
  846. 'admin.getrestrictioninfo' => 1,
  847. 'application.getpublicinfo' => 1,
  848. 'auth.getapppublickey' => 1,
  849. 'auth.getsession' => 1,
  850. 'auth.getsignedpublicsessiondata' => 1,
  851. 'comments.get' => 1,
  852. 'connect.getunconnectedfriendscount' => 1,
  853. 'dashboard.getactivity' => 1,
  854. 'dashboard.getcount' => 1,
  855. 'dashboard.getglobalnews' => 1,
  856. 'dashboard.getnews' => 1,
  857. 'dashboard.multigetcount' => 1,
  858. 'dashboard.multigetnews' => 1,
  859. 'data.getcookies' => 1,
  860. 'events.get' => 1,
  861. 'events.getmembers' => 1,
  862. 'fbml.getcustomtags' => 1,
  863. 'feed.getappfriendstories' => 1,
  864. 'feed.getregisteredtemplatebundlebyid' => 1,
  865. 'feed.getregisteredtemplatebundles' => 1,
  866. 'fql.multiquery' => 1,
  867. 'fql.query' => 1,
  868. 'friends.arefriends' => 1,
  869. 'friends.get' => 1,
  870. 'friends.getappusers' => 1,
  871. 'friends.getlists' => 1,
  872. 'friends.getmutualfriends' => 1,
  873. 'gifts.get' => 1,
  874. 'groups.get' => 1,
  875. 'groups.getmembers' => 1,
  876. 'intl.gettranslations' => 1,
  877. 'links.get' => 1,
  878. 'notes.get' => 1,
  879. 'notifications.get' => 1,
  880. 'pages.getinfo' => 1,
  881. 'pages.isadmin' => 1,
  882. 'pages.isappadded' => 1,
  883. 'pages.isfan' => 1,
  884. 'permissions.checkavailableapiaccess' => 1,
  885. 'permissions.checkgrantedapiaccess' => 1,
  886. 'photos.get' => 1,
  887. 'photos.getalbums' => 1,
  888. 'photos.gettags' => 1,
  889. 'profile.getinfo' => 1,
  890. 'profile.getinfooptions' => 1,
  891. 'stream.get' => 1,
  892. 'stream.getcomments' => 1,
  893. 'stream.getfilters' => 1,
  894. 'users.getinfo' => 1,
  895. 'users.getloggedinuser' => 1,
  896. 'users.getstandardinfo' => 1,
  897. 'users.hasapppermission' => 1,
  898. 'users.isappuser' => 1,
  899. 'users.isverified' => 1,
  900. 'video.getuploadlimits' => 1);
  901. $name = 'api';
  902. if (isset($READ_ONLY_CALLS[strtolower($method)])) {
  903. $name = 'api_read';
  904. } else if (strtolower($method) == 'video.upload') {
  905. $name = 'api_video';
  906. }
  907. return self::getUrl($name, 'restserver.php');
  908. }
  909. /**
  910. * Build the URL for given domain alias, path and parameters.
  911. *
  912. * @param $name string The name of the domain
  913. * @param $path string Optional path (without a leading slash)
  914. * @param $params array Optional query parameters
  915. *
  916. * @return string The URL for the given parameters
  917. */
  918. protected function getUrl($name, $path='', $params=array()) {
  919. $url = self::$DOMAIN_MAP[$name];
  920. if ($path) {
  921. if ($path[0] === '/') {
  922. $path = substr($path, 1);
  923. }
  924. $url .= $path;
  925. }
  926. if ($params) {
  927. $url .= '?' . http_build_query($params, null, '&');
  928. }
  929. return $url;
  930. }
  931. /**
  932. * Returns the Current URL, stripping it of known FB parameters that should
  933. * not persist.
  934. *
  935. * @return string The current URL
  936. */
  937. protected function getCurrentUrl() {
  938. if (isset($_SERVER['HTTPS']) &&
  939. ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
  940. isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
  941. $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  942. $protocol = 'https://';
  943. }
  944. else {
  945. $protocol = 'http://';
  946. }
  947. $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  948. $parts = parse_url($currentUrl);
  949. $query = '';
  950. if (!empty($parts['query'])) {
  951. // drop known fb params
  952. $params = explode('&', $parts['query']);
  953. $retained_params = array();
  954. foreach ($params as $param) {
  955. if ($this->shouldRetainParam($param)) {
  956. $retained_params[] = $param;
  957. }
  958. }
  959. if (!empty($retained_params)) {
  960. $query = '?'.implode($retained_params, '&');
  961. }
  962. }
  963. // use port if non default
  964. $port =
  965. isset($parts['port']) &&
  966. (($protocol === 'http://' && $parts['port'] !== 80) ||
  967. ($protocol === 'https://' && $parts['port'] !== 443))
  968. ? ':' . $parts['port'] : '';
  969. // rebuild
  970. return $protocol . $parts['host'] . $port . $parts['path'] . $query;
  971. }
  972. /**
  973. * Returns true if and only if the key or key/value pair should
  974. * be retained as part of the query string. This amounts to
  975. * a brute-force search of the very small list of Facebook-specific
  976. * params that should be stripped out.
  977. *
  978. * @param string $param A key or key/value pair within a URL's query (e.g.
  979. * 'foo=a', 'foo=', or 'foo'.
  980. *
  981. * @return boolean
  982. */
  983. protected function shouldRetainParam($param) {
  984. foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {
  985. if (strpos($param, $drop_query_param.'=') === 0) {
  986. return false;
  987. }
  988. }
  989. return true;
  990. }
  991. /**
  992. * Analyzes the supplied result to see if it was thrown
  993. * because the access token is no longer valid. If that is
  994. * the case, then we destroy the session.
  995. *
  996. * @param $result array A record storing the error message returned
  997. * by a failed API call.
  998. */
  999. protected function throwAPIException($result) {
  1000. $e = new FacebookApiException($result);
  1001. switch ($e->getType()) {
  1002. // OAuth 2.0 Draft 00 style
  1003. case 'OAuthException':
  1004. // OAuth 2.0 Draft 10 style
  1005. case 'invalid_token':
  1006. // REST server errors are just Exceptions
  1007. case 'Exception':
  1008. $message = $e->getMessage();
  1009. if ((strpos($message, 'Error validating access token') !== false) ||
  1010. (strpos($message, 'Invalid OAuth access token') !== false) ||
  1011. (strpos($message, 'An active access token must be used') !== false)
  1012. ) {
  1013. $this->destroySession();
  1014. }
  1015. break;
  1016. }
  1017. throw $e;
  1018. }
  1019. /**
  1020. * Prints to the error log if you aren't in command line mode.
  1021. *
  1022. * @param string $msg Log message
  1023. */
  1024. protected static function errorLog($msg) {
  1025. // disable error log if we are running in a CLI environment
  1026. // @codeCoverageIgnoreStart
  1027. if (php_sapi_name() != 'cli') {
  1028. error_log($msg);
  1029. }
  1030. // uncomment this if you want to see the errors on the page
  1031. // print 'error_log: '.$msg."\n";
  1032. // @codeCoverageIgnoreEnd
  1033. }
  1034. /**
  1035. * Base64 encoding that doesn't need to be urlencode()ed.
  1036. * Exactly the same as base64_encode except it uses
  1037. * - instead of +
  1038. * _ instead of /
  1039. *
  1040. * @param string $input base64UrlEncoded string
  1041. * @return string
  1042. */
  1043. protected static function base64UrlDecode($input) {
  1044. return base64_decode(strtr($input, '-_', '+/'));
  1045. }
  1046. /**
  1047. * Destroy the current session
  1048. */
  1049. public function destroySession() {
  1050. $this->accessToken = null;
  1051. $this->signedRequest = null;
  1052. $this->user = null;
  1053. $this->clearAllPersistentData();
  1054. // Javascript sets a cookie that will be used in getSignedRequest that we
  1055. // need to clear if we can
  1056. $cookie_name = $this->getSignedRequestCookieName();
  1057. if (array_key_exists($cookie_name, $_COOKIE)) {
  1058. unset($_COOKIE[$cookie_name]);
  1059. if (!headers_sent()) {
  1060. // The base domain is stored in the metadata cookie if not we fallback
  1061. // to the current hostname
  1062. $base_domain = '.'. $_SERVER['HTTP_HOST'];
  1063. $metadata = $this->getMetadataCookie();
  1064. if (array_key_exists('base_domain', $metadata) &&
  1065. !empty($metadata['base_domain'])) {
  1066. $base_domain = $metadata['base_domain'];
  1067. }
  1068. setcookie($cookie_name, '', 0, '/', $base_domain);
  1069. } else {
  1070. self::errorLog(
  1071. 'There exists a cookie that we wanted to clear that we couldn\'t '.
  1072. 'clear because headers was already sent. Make sure to do the first '.
  1073. 'API call before outputing anything'
  1074. );
  1075. }
  1076. }
  1077. }
  1078. /**
  1079. * Parses the metadata cookie that our Javascript API set
  1080. *
  1081. * @return an array mapping key to value
  1082. */
  1083. protected function getMetadataCookie() {
  1084. $cookie_name = $this->getMetadataCookieName();
  1085. if (!array_key_exists($cookie_name, $_COOKIE)) {
  1086. return array();
  1087. }
  1088. // The cookie value can be wrapped in "-characters so remove them
  1089. $cookie_value = trim($_COOKIE[$cookie_name], '"');
  1090. if (empty($cookie_value)) {
  1091. return array();
  1092. }
  1093. $parts = explode('&', $cookie_value);
  1094. $metadata = array();
  1095. foreach ($parts as $part) {
  1096. $pair = explode('=', $part, 2);
  1097. if (!empty($pair[0])) {
  1098. $metadata[urldecode($pair[0])] =
  1099. (count($pair) > 1) ? urldecode($pair[1]) : '';
  1100. }
  1101. }
  1102. return $metadata;
  1103. }
  1104. /**
  1105. * Each of the following four methods should be overridden in
  1106. * a concrete subclass, as they are in the provided Facebook class.
  1107. * The Facebook class uses PHP sessions to provide a primitive
  1108. * persistent store, but another subclass--one that you implement--
  1109. * might use a database, memcache, or an in-memory cache.
  1110. *
  1111. * @see Facebook
  1112. */
  1113. /**
  1114. * Stores the given ($key, $value) pair, so that future calls to
  1115. * getPersistentData($key) return $value. This call may be in another request.
  1116. *
  1117. * @param string $key
  1118. * @param array $value
  1119. *
  1120. * @return void
  1121. */
  1122. abstract protected function setPersistentData($key, $value);
  1123. /**
  1124. * Get the data for $key, persisted by BaseFacebook::setPersistentData()
  1125. *
  1126. * @param string $key The key of the data to retrieve
  1127. * @param boolean $default The default value to return if $key is not found
  1128. *
  1129. * @return mixed
  1130. */
  1131. abstract protected function getPersistentData($key, $default = false);
  1132. /**
  1133. * Clear the data with $key from the persistent storage
  1134. *
  1135. * @param string $key
  1136. * @return void
  1137. */
  1138. abstract protected function clearPersistentData($key);
  1139. /**
  1140. * Clear all data from the persistent storage
  1141. *
  1142. * @return void
  1143. */
  1144. abstract protected function clearAllPersistentData();
  1145. }