facebook.php

Go to the documentation of this file.
00001 <?php
00002 
00003 if (!function_exists('curl_init')) {
00004   throw new Exception('Facebook needs the CURL PHP extension.');
00005 }
00006 if (!function_exists('json_decode')) {
00007   throw new Exception('Facebook needs the JSON PHP extension.');
00008 }
00009 
00015 class FacebookApiException extends Exception
00016 {
00020   protected $result;
00021 
00027   public function __construct($result) {
00028     $this->result = $result;
00029 
00030     $code = isset($result['error_code']) ? $result['error_code'] : 0;
00031     $msg  = isset($result['error'])
00032               ? $result['error']['message'] : $result['error_msg'];
00033     parent::__construct($msg, $code);
00034   }
00035 
00041   public function getResult() {
00042     return $this->result;
00043   }
00044 
00051   public function getType() {
00052     return
00053       isset($this->result['error']) && isset($this->result['error']['type'])
00054       ? $this->result['error']['type']
00055       : 'Exception';
00056   }
00057 
00063   public function __toString() {
00064     $str = $this->getType() . ': ';
00065     if ($this->code != 0) {
00066       $str .= $this->code . ': ';
00067     }
00068     return $str . $this->message;
00069   }
00070 }
00071 
00077 class Facebook
00078 {
00082   const VERSION = '2.0.3';
00083 
00087   public static $CURL_OPTS = array(
00088     CURLOPT_CONNECTTIMEOUT => 10,
00089     CURLOPT_RETURNTRANSFER => true,
00090     CURLOPT_TIMEOUT        => 60,
00091     CURLOPT_USERAGENT      => 'facebook-php-2.0',
00092   );
00093 
00098   protected static $DROP_QUERY_PARAMS = array(
00099     'session',
00100   );
00101 
00105   public static $DOMAIN_MAP = array(
00106     'api'      => 'https://api.facebook.com/',
00107     'api_read' => 'https://api-read.facebook.com/',
00108     'graph'    => 'https://graph.facebook.com/',
00109     'www'      => 'https://www.facebook.com/',
00110   );
00111 
00115   protected $appId;
00116 
00120   protected $apiSecret;
00121 
00125   protected $session;
00126 
00130   protected $sessionLoaded = false;
00131 
00135   protected $cookieSupport = false;
00136 
00140   protected $baseDomain = '';
00141 
00153   public function __construct($config) {
00154     $this->setAppId($config['appId']);
00155     $this->setApiSecret($config['secret']);
00156     if (isset($config['cookie'])) {
00157       $this->setCookieSupport($config['cookie']);
00158     }
00159     if (isset($config['domain'])) {
00160       $this->setBaseDomain($config['domain']);
00161     }
00162   }
00163 
00169   public function setAppId($appId) {
00170     $this->appId = $appId;
00171     return $this;
00172   }
00173 
00179   public function getAppId() {
00180     return $this->appId;
00181   }
00182 
00188   public function setApiSecret($apiSecret) {
00189     $this->apiSecret = $apiSecret;
00190     return $this;
00191   }
00192 
00198   public function getApiSecret() {
00199     return $this->apiSecret;
00200   }
00201 
00207   public function setCookieSupport($cookieSupport) {
00208     $this->cookieSupport = $cookieSupport;
00209     return $this;
00210   }
00211 
00217   public function useCookieSupport() {
00218     return $this->cookieSupport;
00219   }
00220 
00226   public function setBaseDomain($domain) {
00227     $this->baseDomain = $domain;
00228     return $this;
00229   }
00230 
00236   public function getBaseDomain() {
00237     return $this->baseDomain;
00238   }
00239 
00247   public function setSession($session=null, $write_cookie=true) {
00248     $session = $this->validateSessionObject($session);
00249     $this->sessionLoaded = true;
00250     $this->session = $session;
00251     if ($write_cookie) {
00252       $this->setCookieFromSession($session);
00253     }
00254     return $this;
00255   }
00256 
00263   public function getSession() {
00264     if (!$this->sessionLoaded) {
00265       $session = null;
00266       $write_cookie = true;
00267 
00268       // try loading session from $_GET
00269       if (isset($_GET['session'])) {
00270         $session = json_decode(
00271           get_magic_quotes_gpc()
00272             ? stripslashes($_GET['session'])
00273             : $_GET['session'],
00274           true
00275         );
00276         $session = $this->validateSessionObject($session);
00277       }
00278 
00279       // try loading session from cookie if necessary
00280       if (!$session && $this->useCookieSupport()) {
00281         $cookieName = $this->getSessionCookieName();
00282         if (isset($_COOKIE[$cookieName])) {
00283           $session = array();
00284           parse_str(trim(
00285             get_magic_quotes_gpc()
00286               ? stripslashes($_COOKIE[$cookieName])
00287               : $_COOKIE[$cookieName],
00288             '"'
00289           ), $session);
00290           $session = $this->validateSessionObject($session);
00291           // write only if we need to delete a invalid session cookie
00292           $write_cookie = empty($session);
00293         }
00294       }
00295 
00296       $this->setSession($session, $write_cookie);
00297     }
00298 
00299     return $this->session;
00300   }
00301 
00307   public function getUser() {
00308     $session = $this->getSession();
00309     return $session ? $session['uid'] : null;
00310   }
00311 
00326   public function getLoginUrl($params=array()) {
00327     $currentUrl = $this->getCurrentUrl();
00328     return $this->getUrl(
00329       'www',
00330       'login.php',
00331       array_merge(array(
00332         'api_key'         => $this->getAppId(),
00333         'cancel_url'      => $currentUrl,
00334         'display'         => 'page',
00335         'fbconnect'       => 1,
00336         'next'            => $currentUrl,
00337         'return_session'  => 1,
00338         'session_version' => 3,
00339         'v'               => '1.0',
00340       ), $params)
00341     );
00342   }
00343 
00353   public function getLogoutUrl($params=array()) {
00354     $session = $this->getSession();
00355     return $this->getUrl(
00356       'www',
00357       'logout.php',
00358       array_merge(array(
00359         'api_key'     => $this->getAppId(),
00360         'next'        => $this->getCurrentUrl(),
00361         'session_key' => $session['session_key'],
00362       ), $params)
00363     );
00364   }
00365 
00377   public function getLoginStatusUrl($params=array()) {
00378     return $this->getUrl(
00379       'www',
00380       'extern/login_status.php',
00381       array_merge(array(
00382         'api_key'         => $this->getAppId(),
00383         'no_session'      => $this->getCurrentUrl(),
00384         'no_user'         => $this->getCurrentUrl(),
00385         'ok_session'      => $this->getCurrentUrl(),
00386         'session_version' => 3,
00387       ), $params)
00388     );
00389   }
00390 
00397   public function api(/* polymorphic */) {
00398     $args = func_get_args();
00399     if (is_array($args[0])) {
00400       return $this->_restserver($args[0]);
00401     } else {
00402       return call_user_func_array(array($this, '_graph'), $args);
00403     }
00404   }
00405 
00413   protected function _restserver($params) {
00414     // generic application level parameters
00415     $params['api_key'] = $this->getAppId();
00416     $params['format'] = 'json';
00417 
00418     $result = json_decode($this->_oauthRequest(
00419       $this->getApiUrl($params['method']),
00420       $params
00421     ), true);
00422 
00423     // results are returned, errors are thrown
00424     if (is_array($result) && isset($result['error_code'])) {
00425       throw new FacebookApiException($result);
00426     }
00427     return $result;
00428   }
00429 
00439   protected function _graph($path, $method='GET', $params=array()) {
00440     if (is_array($method) && empty($params)) {
00441       $params = $method;
00442       $method = 'GET';
00443     }
00444     $params['method'] = $method; // method override as we always do a POST
00445 
00446     $result = json_decode($this->_oauthRequest(
00447       $this->getUrl('graph', $path),
00448       $params
00449     ), true);
00450 
00451     // results are returned, errors are thrown
00452     if (is_array($result) && isset($result['error'])) {
00453       $e = new FacebookApiException($result);
00454       if ($e->getType() === 'OAuthException') {
00455         $this->setSession(null);
00456       }
00457       throw $e;
00458     }
00459     return $result;
00460   }
00461 
00470   protected function _oauthRequest($url, $params) {
00471     if (!isset($params['access_token'])) {
00472       $session = $this->getSession();
00473       // either user session signed, or app signed
00474       if ($session) {
00475         $params['access_token'] = $session['access_token'];
00476       } else {
00477         // TODO (naitik) sync with abanker
00478         //$params['access_token'] = $this->getAppId() .'|'. $this->getApiSecret();
00479       }
00480     }
00481 
00482     // json_encode all params values that are not strings
00483     foreach ($params as $key => $value) {
00484       if (!is_string($value)) {
00485         $params[$key] = json_encode($value);
00486       }
00487     }
00488     return $this->makeRequest($url, $params);
00489   }
00490 
00501   protected function makeRequest($url, $params, $ch=null) {
00502     if (!$ch) {
00503       $ch = curl_init();
00504     }
00505 
00506     $opts = self::$CURL_OPTS;
00507     $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
00508     $opts[CURLOPT_URL] = $url;
00509     curl_setopt_array($ch, $opts);
00510     $result = curl_exec($ch);
00511     curl_close($ch);
00512     return $result;
00513   }
00514 
00520   protected function getSessionCookieName() {
00521     return 'fbs_' . $this->getAppId();
00522   }
00523 
00530   protected function setCookieFromSession($session=null) {
00531     if (!$this->useCookieSupport()) {
00532       return;
00533     }
00534 
00535     $cookieName = $this->getSessionCookieName();
00536     $value = 'deleted';
00537     $expires = time() - 3600;
00538     $domain = $this->getBaseDomain();
00539     if ($session) {
00540       $value = '"' . http_build_query($session, null, '&') . '"';
00541       if (isset($session['base_domain'])) {
00542         $domain = $session['base_domain'];
00543       }
00544       $expires = $session['expires'];
00545     }
00546 
00547     // if an existing cookie is not set, we dont need to delete it
00548     if ($value == 'deleted' && empty($_COOKIE[$cookieName])) {
00549       return;
00550     }
00551 
00552     if (headers_sent()) {
00553       // disable error log if we are running in a CLI environment
00554       // @codeCoverageIgnoreStart
00555       if (php_sapi_name() != 'cli') {
00556         error_log('Could not set cookie. Headers already sent.');
00557       }
00558       // @codeCoverageIgnoreEnd
00559 
00560     // ignore for code coverage as we will never be able to setcookie in a CLI
00561     // environment
00562     // @codeCoverageIgnoreStart
00563     } else {
00564       setcookie($cookieName, $value, $expires, '/', '.' . $domain);
00565     }
00566     // @codeCoverageIgnoreEnd
00567   }
00568 
00575   protected function validateSessionObject($session) {
00576     // make sure some essential fields exist
00577     if (is_array($session) &&
00578         isset($session['uid']) &&
00579         isset($session['session_key']) &&
00580         isset($session['secret']) &&
00581         isset($session['access_token']) &&
00582         isset($session['sig'])) {
00583       // validate the signature
00584       $session_without_sig = $session;
00585       unset($session_without_sig['sig']);
00586       $expected_sig = self::generateSignature(
00587         $session_without_sig,
00588         $this->getApiSecret()
00589       );
00590       if ($session['sig'] != $expected_sig) {
00591         // disable error log if we are running in a CLI environment
00592         // @codeCoverageIgnoreStart
00593         if (php_sapi_name() != 'cli') {
00594           error_log('Got invalid session signature in cookie.');
00595         }
00596         // @codeCoverageIgnoreEnd
00597         $session = null;
00598       }
00599       // check expiry time
00600     } else {
00601       $session = null;
00602     }
00603     return $session;
00604   }
00605 
00612   protected function getApiUrl($method) {
00613     static $READ_ONLY_CALLS =
00614       array('admin.getallocation' => 1,
00615             'admin.getappproperties' => 1,
00616             'admin.getbannedusers' => 1,
00617             'admin.getlivestreamvialink' => 1,
00618             'admin.getmetrics' => 1,
00619             'admin.getrestrictioninfo' => 1,
00620             'application.getpublicinfo' => 1,
00621             'auth.getapppublickey' => 1,
00622             'auth.getsession' => 1,
00623             'auth.getsignedpublicsessiondata' => 1,
00624             'comments.get' => 1,
00625             'connect.getunconnectedfriendscount' => 1,
00626             'dashboard.getactivity' => 1,
00627             'dashboard.getcount' => 1,
00628             'dashboard.getglobalnews' => 1,
00629             'dashboard.getnews' => 1,
00630             'dashboard.multigetcount' => 1,
00631             'dashboard.multigetnews' => 1,
00632             'data.getcookies' => 1,
00633             'events.get' => 1,
00634             'events.getmembers' => 1,
00635             'fbml.getcustomtags' => 1,
00636             'feed.getappfriendstories' => 1,
00637             'feed.getregisteredtemplatebundlebyid' => 1,
00638             'feed.getregisteredtemplatebundles' => 1,
00639             'fql.multiquery' => 1,
00640             'fql.query' => 1,
00641             'friends.arefriends' => 1,
00642             'friends.get' => 1,
00643             'friends.getappusers' => 1,
00644             'friends.getlists' => 1,
00645             'friends.getmutualfriends' => 1,
00646             'gifts.get' => 1,
00647             'groups.get' => 1,
00648             'groups.getmembers' => 1,
00649             'intl.gettranslations' => 1,
00650             'links.get' => 1,
00651             'notes.get' => 1,
00652             'notifications.get' => 1,
00653             'pages.getinfo' => 1,
00654             'pages.isadmin' => 1,
00655             'pages.isappadded' => 1,
00656             'pages.isfan' => 1,
00657             'permissions.checkavailableapiaccess' => 1,
00658             'permissions.checkgrantedapiaccess' => 1,
00659             'photos.get' => 1,
00660             'photos.getalbums' => 1,
00661             'photos.gettags' => 1,
00662             'profile.getinfo' => 1,
00663             'profile.getinfooptions' => 1,
00664             'stream.get' => 1,
00665             'stream.getcomments' => 1,
00666             'stream.getfilters' => 1,
00667             'users.getinfo' => 1,
00668             'users.getloggedinuser' => 1,
00669             'users.getstandardinfo' => 1,
00670             'users.hasapppermission' => 1,
00671             'users.isappuser' => 1,
00672             'users.isverified' => 1,
00673             'video.getuploadlimits' => 1);
00674     $name = 'api';
00675     if (isset($READ_ONLY_CALLS[strtolower($method)])) {
00676       $name = 'api_read';
00677     }
00678     return self::getUrl($name, 'restserver.php');
00679   }
00680 
00689   protected function getUrl($name, $path='', $params=array()) {
00690     $url = self::$DOMAIN_MAP[$name];
00691     if ($path) {
00692       if ($path[0] === '/') {
00693         $path = substr($path, 1);
00694       }
00695       $url .= $path;
00696     }
00697     if ($params) {
00698       $url .= '?' . http_build_query($params);
00699     }
00700     return $url;
00701   }
00702 
00709   protected function getCurrentUrl() {
00710     $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'
00711       ? 'https://'
00712       : 'http://';
00713     $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
00714     $parts = parse_url($currentUrl);
00715 
00716     // drop known fb params
00717     $query = '';
00718     if (!empty($parts['query'])) {
00719       $params = array();
00720       parse_str($parts['query'], $params);
00721       foreach(self::$DROP_QUERY_PARAMS as $key) {
00722         unset($params[$key]);
00723       }
00724       if (!empty($params)) {
00725         $query = '?' . http_build_query($params);
00726       }
00727     }
00728 
00729     // use port if non default
00730     $port =
00731       isset($parts['port']) &&
00732       (($protocol === 'http://' && $parts['port'] !== 80) ||
00733        ($protocol === 'https://' && $parts['port'] !== 443))
00734       ? ':' . $parts['port'] : '';
00735 
00736     // rebuild
00737     return $protocol . $parts['host'] . $port . $parts['path'] . $query;
00738   }
00739 
00747   protected static function generateSignature($params, $secret) {
00748     // work with sorted data
00749     ksort($params);
00750 
00751     // generate the base string
00752     $base_string = '';
00753     foreach($params as $key => $value) {
00754       $base_string .= $key . '=' . $value;
00755     }
00756     $base_string .= $secret;
00757 
00758     return md5($base_string);
00759   }
00760 }