PageRenderTime 72ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/libs/facebook/base_facebook.php

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