Skip to content

Commit

Permalink
upgrade to FB API v2; use Composer for dependencies (finally..jeez it…
Browse files Browse the repository at this point in the history
…'s 2015)
  • Loading branch information
andyjy committed Jun 1, 2015
1 parent b7bad99 commit 1dc77ce
Show file tree
Hide file tree
Showing 74 changed files with 294 additions and 13,488 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -0,0 +1 @@
vendor
23 changes: 7 additions & 16 deletions app/BaseApp.php
Expand Up @@ -14,7 +14,11 @@
ini_set('error_log', LOG_DIR . 'selectivestatus.log');
}
require_once $lib_dir . 'DB/MySQL.php';
require_once $lib_dir . 'facebook/facebook.php';
require $lib_dir . '../vendor/autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;

/**
* Controller-esque stuff for the Selective Tweets app
Expand All @@ -30,7 +34,7 @@ abstract class SelectiveTweets_BaseApp
/** @var DB DB Connection **/
protected $db;

/** @var Facebook Facebook SDK **/
/** @var Facebook FacebookSession **/
protected $fb;

/**
Expand All @@ -54,10 +58,7 @@ protected function __construct() { }
protected function init()
{
$this->db = MySQL::factory(DB_HOST, DB_NAME, DB_USER, DB_PASS);
$this->fb = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
));
FacebookSession::setDefaultApplication(FB_APP_ID, FB_APP_SECRET);
}

/**
Expand All @@ -70,16 +71,6 @@ public function getDB()
return $this->db;
}

/**
* Accessor for the Facebook SDK
*
* @return Facebook
*/
public function getFacebook()
{
return $this->fb;
}

/**
* Detects whether the tracker for the Twitter feed is returning tweets a-ok
*
Expand Down
28 changes: 22 additions & 6 deletions app/CLIApp.php
Expand Up @@ -13,6 +13,9 @@
require_once $app_dir . 'FilterTrack.php';
require_once $app_dir . '../lib/Process.php';

use Facebook\FacebookSession;
use Facebook\FacebookRequest;

/**
* Controller for CLI scripts for the Selective Tweets app
* Workhorse - handles collecting tweets and sending to FB
Expand All @@ -26,7 +29,19 @@ protected function init()
{
// security - ensure we only run these scripts under CLI
$this->requireCLI();

parent::init();

$this->fb = FacebookSession::newAppSession();
try {
$this->fb->validate();
} catch (FacebookRequestException $ex) {
// Session not valid, Graph API returned an exception with the reason.
error_log($ex->getMessage());
} catch (\Exception $ex) {
// Graph API returned info, but it may mismatch the current app or have expired.
error_log($ex->getMessage());
}
}

/**
Expand Down Expand Up @@ -153,7 +168,7 @@ protected function processTweets($tweets)
$body = http_build_query($body);
$body = urldecode($body);
$request = array(
'method' => 'post',
'method' => 'POST',
'body' => $body,
);
if ($row['fb_oauth_access_token']) {
Expand All @@ -167,10 +182,11 @@ protected function processTweets($tweets)
}
$this->log('BATCH', 'queue');
$this->log('batch: ' . count($batch), 'queue');

try {
$request = array('batch' => json_encode($batch));
// batch call
$results = $this->fb->api('/', 'post', $request);
$response = (new FacebookRequest($this->fb, 'POST', '?batch='.urlencode(json_encode($batch))))->execute();
$results = $response->getGraphObject()->asArray();

// process results
$this->log('results: ' . count($results), 'queue');
foreach ($results as $key => $result) {
Expand All @@ -180,7 +196,7 @@ protected function processTweets($tweets)
$id = $status['id'];
$timestamp = $this->getStatusTimestamp($status);
$now = date('D, j M H:i:s');
if (!empty($result['code']) && $result['code'] == 200) {
if (!empty($result->code) && $result->code == 200) {
// HTTP 200 - success!
$this->db->exec("update tweet_queue set sent = 1 where id = " . $this->db->quote($id));
$this->log("update tweet_queue set sent = 1 where id = " . $this->db->quote($id), 'queue');
Expand All @@ -193,7 +209,7 @@ protected function processTweets($tweets)
if ($timestamp > max($row['last_update_attempt'], $row['updated'])) {
$this->db->exec("UPDATE selective_status_users SET last_update_attempt = " . $this->db->quote($timestamp) . ", exception_count = 0 WHERE twitterid = " . $this->db->quote($user) . " AND fbuid = " . $this->db->quote($fbuid) . " LIMIT 1");
}
$this->log(': ' . $timestamp . ' ERROR ' . $result['code'] . ' - ' . $result['body'] . ' / ' . $user . ' - ' . $fbuid . ': ' . $msg, 'queue');
$this->log(': ' . $timestamp . ' ERROR ' . $result->code . ' - ' . $result->body . ' / ' . $user . ' - ' . $fbuid . ': ' . $msg, 'queue');
}
}
$this->log('batch done', 'queue');
Expand Down
2 changes: 0 additions & 2 deletions app/FilterTrack.php
Expand Up @@ -7,8 +7,6 @@
* @author Andy Young <andy@apexa.co.uk>
* @license MIT
*/
require_once dirname(dirname(__FILE__)) . '/lib/phirehose/lib/Phirehose.php';
require_once dirname(dirname(__FILE__)) . '/lib/phirehose/lib/OauthPhirehose.php';
/**
* Phirehose library consumer class to receive a stream of tweets and stick them into our TweetQueue
*/
Expand Down
139 changes: 121 additions & 18 deletions app/WebApp.php
Expand Up @@ -10,6 +10,13 @@
require_once 'BaseApp.php';
ini_set('error_log', '/var/log/php/selectivestatus_webapp.log');

use Facebook\FacebookCanvasLoginHelper;
use Facebook\FacebookJavaScriptLoginHelper;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookSession;
use Facebook\GraphUser;

/**
* html-safe shorthand function
*/
Expand All @@ -23,6 +30,78 @@ function _h($str)
*/
class SelectiveTweets_WebApp extends SelectiveTweets_BaseApp
{
protected $fb_uid;

protected function init()
{
session_start();
parent::init();
$this->initFacebookSession();
}

protected function initFacebookSession()
{
// first try from redirect
try {
$helper = new FacebookRedirectLoginHelper(ROOT_URL);
$this->fb = $helper->getSessionFromRedirect();
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if (!$this->fb) {
// next try from canvas
try {
$helper = new FacebookCanvasLoginHelper();
$this->fb = $helper->getSession();
} catch(\Exception $ex) {
// When validation fails or other local issues
}
}
if (!$this->fb) {
// next try from JS
try {
$helper = new FacebookJavaScriptLoginHelper();
$this->fb = $helper->getSession();
} catch(\Exception $ex) {
// When validation fails or other local issues
}
}
// finally fall back to an existing session, if we have one
if (!$this->fb && !empty($_SESSION['fb_token'])) {
try {
$this->fb = new FacebookSession($_SESSION['fb_token']);
$this->fb->validate();
} catch(\Exception $ex) {
// When validation fails or other local issues
}
}
if ($this->fb) {
// Logged in
try {
$_SESSION['fb_token'] = $this->fb->getToken();
$user_profile = (new FacebookRequest(
$this->fb, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
$this->fb_uid = $user_profile->getId();
} catch (\Exception $e) {
$this->fb = null;
}
}
if (!$this->fb) {
session_destroy();
}
}

/**
* Accessor for the Facebook SDK
*
* @return Facebook
*/
public function getFacebook()
{
return $this->fb;
}

/**
* Returns the twitter ID we've associated with the curent Facebook user
*
Expand All @@ -42,11 +121,7 @@ public function getTwitterName()
*/
public function getFBUID()
{
try {
return $this->fb->getUser();
} catch (Exception $e) {
// may not be logged in
}
return $this->fb_uid;
}

/**
Expand All @@ -57,8 +132,19 @@ public function getFBUID()
public function getCanPublishStream()
{
try {
$permissions = $this->fb->api('/me/permissions');
return !empty($permissions['data'][0]['publish_stream']);
if (!$this->fb) {
return false;
}
$permissions = (new FacebookRequest(
$this->fb, 'GET', '/me/permissions'
))->execute()->getGraphObject();
foreach($permissions->asArray() as $permission) {
if ($permission->permission == 'publish_actions' && $permission->status == 'granted') {
return true;
}
}
// else
return false;
} catch (Exception $e) {
// may not be logged in
}
Expand All @@ -72,8 +158,19 @@ public function getCanPublishStream()
public function getCanPostToPages()
{
try {
$permissions = $this->fb->api('/me/permissions');
return !(empty($permissions['data'][0]['manage_pages']) || empty($permissions['data'][0]['publish_stream']));
if (!$this->fb) {
return false;
}
$permissions = (new FacebookRequest(
$this->fb, 'GET', '/me/permissions'
))->execute()->getGraphObject();
foreach($permissions->asArray() as $permission) {
if (($permission->permission == 'publish_actions' || $permission->permission == 'manage_pages') && $permission->status == 'granted') {
return true;
}
}
// else
return false;
} catch (Exception $e) {
// may not be logged in
}
Expand All @@ -97,7 +194,8 @@ public function redirect($url)
*/
public function redirectToLogin()
{
$this->redirect($this->fb->getLoginUrl());
$helper = new FacebookRedirectLoginHelper(ROOT_URL);
$this->redirect($helper->getLoginUrl());
}

/**
Expand Down Expand Up @@ -140,21 +238,26 @@ public function getUserData()
public function getUserPages()
{
$users_pages = array();
$accounts = $this->fb->api('/me/accounts');
if (!empty($accounts['data'])) {
if (!$this->fb) {
return array();
}
$accounts = (new FacebookRequest(
$this->fb, 'GET', '/me/accounts'
))->execute()->getGraphObject(GraphUser::className());
if ($accounts = $accounts->asArray()) {
foreach ($accounts['data'] as $account) {
if ($account['category'] != 'Application') {
if (!empty($account['id']) && !empty($account['name'])) {
$account['twitterid'] = '';
$users_pages[$account['id']] = $account;
if ($account->category != 'Application') {
if (!empty($account->id) && !empty($account->name)) {
$account->twitterid = '';
$users_pages[$account->id] = $account;
} else {
$this->log('invalid account: ' . print_r($account, true), 'badaccounts');
}
}
}
$rs = $this->db->query("SELECT * from selective_status_users where fbuid IN ('" . implode("', '", array_keys($users_pages)) . "')");
while ($rs && $row = $rs->fetch()) {
$users_pages[$row['fbuid']]['twitterid'] = $row['twitterid'];
$users_pages[$row['fbuid']]->twitterid = $row['twitterid'];
}
}
return $users_pages;
Expand Down Expand Up @@ -189,7 +292,7 @@ public function savePages(&$pages)
foreach ($_POST as $key => $value) {
if (substr($key, 0, 8) == 'username') {
$the_page_id = trim(substr($key, 8));
$access_token = !empty($pages[$the_page_id]) ? $pages[$the_page_id]['access_token'] : '';
$access_token = !empty($pages[$the_page_id]) ? $pages[$the_page_id]->access_token : '';
$result = $this->db->exec("INSERT IGNORE INTO selective_status_users (fbuid, twitterid, is_page, fb_oauth_access_token) VALUES ("
. $this->db->quote($the_page_id) . ", " . $this->db->quote($value) . ", 1, " . $this->db->quote($access_token) . ")"
. " ON DUPLICATE KEY UPDATE twitterid = " . $this->db->quote($value) . ", is_page = 1, fb_oauth_access_token = " . $this->db->quote($access_token));
Expand Down
6 changes: 6 additions & 0 deletions composer.json
@@ -0,0 +1,6 @@
{
"require" : {
"facebook/php-sdk-v4" : "4.0.*",
"fennb/phirehose": "1.0.*"
}
}

0 comments on commit 1dc77ce

Please sign in to comment.