If you want to develop a Facebook tab application or want to use the Facebook API for users of your website, this library will help you get there quickly and without hassle.
This library consists of a PHP-part for server-side processing and a JavaScript-part to manage your application in the browser, such as chaining your own events to Facebook-API calls.
A look at the demo site is worth it!
Feature list:
1. Unzipping
Unzip the zip-file under your document root folder (be careful when overwriting files!). In case you already have a .htaccess file in your document root, merge your existing one with the .htaccess file included in the package.
2. Install the MySQL table
Copy the content of install.sql to your MySQL console or phpMyAdmin to run the mysql install. One table will be created.
If you want to use the wall-reader feature, install the required tables for this by calling fbHelperWallReader::installTables() after the Installation-Procedure.
3. Edit the config.inc.php
Set your database connection for saving the user tokens from Facebook. If you added a prefix to the created table from step 2, add the same prefix to the API_DB_PREFIX-constant.
4. Edit the config.ini.php
[dad]-section
In this section are the settings for the debugging tool included in the package. At the very least, set your E-Mail-address so that you can be informed by the PHP scripts in case an error occurs. The logpath is relative from the root where the index.php is running.
[facebook]-section
For this section you need a Facebook developer account and an existing Facebook application. If you don't have one of those, create it at this point. Add your application ID and application secret to the configuration. For your first app use the general.* settings to set up your app.
If you want to use your application in a Facebook Tab, fill in the page.id and the page.name . Those are needed to force a redirect to the correct Facebook page or to create deep links in your App.
The options restricted.pages and restricted.redirect are used to store the URL which the user will be redirected when the iFrame is not loaded by the correct Facebook page.
5. Download FirePHP / Facebook SDK
Those 2 packages are needed to run the fbHelper:
FirePhp
/lib folder into our /lib/classes/firephp/ folderFacebook SDK
/src folder into our /lib/facebook/ folder6. Ready to test
Have a look at the example.php to get some usage suggestions and read the HowTo Section below for more information.
If you want to use logging/debugging please check the right configuration for DAD.
Check the DAD (debugging) configuration
To check which debugging configuration is loaded, use the following code-snippet:
echo "DAD configuration:";
echo "";
var_dump(dad_cfg::inst()-getConfiguration());
echo "";
Check if logfile is writeable
echo "DAD Logfile writeable:";
echo "";
var_dump(dad::test(0));
echo "";
This method outputs an array with the target filename and a key success to tell you whether the file is writeable or not.
Check if the MySQL-Table is installed
echo "SQL Table installed:";
echo "";
echo fbUsers::sqlInstalled() ? 'Yes' : 'No';
echo "";
If all is ok, you can start developing your facebook application!!! Start a session and include the boot.inc.php
session_start();
require_once('lib/boot.inc.php');
$iniHandler = iniHandler::getInstance('main');
$appScope = 'general'; // use the scope here from the [facebook]-section in config.ini.php
Because you are able to manage several applications you have to set a scope for each application. The default application will have the scope "general".
Read your appId from the configuration file, set the app namespace (scope) and assign the appId and secret to your facebook helper:
$appId = $iniHandler-getIniSetting('facebook.'.$appScope.'.appId');
$appSecret = $iniHandler-getIniSetting('facebook.'.$appScope.'.secret')
$tmpFbHelper = fbHelper::getInstance($appId); // init the fbHelper
$tmpFbHelper-setSecret($appSecret);
You can get the facebook helper each time by calling it by the appId:
$tmpFbHelper = fbHelper::getInstance($appId);
... or call it by the namespace (after set once by setAppNamespace()):
fbHelper::setAppNamespace($appScope, $appId);
$tmpFbHelper = fbHelper::getInstanceByNamespace();
If you want redirect the page to your facebook tab when opened out of facebook, type following. But be sure that you set up the page.id and page.name options in config.ini.php!
$tmpFbHelper
-setPageName($iniHandler-getIniSetting('facebook.'.$appScope.'.page.name'))
-setPageId($iniHandler-getIniSetting('facebook.'.$appScope.'.page.id'));
$tmpFbHelper-forceRedirectToTab();
Open Graph
Before your is finished you can set open graph options:
// set some open graph options we can display later in our html section
$tmpFbHelper-setOgOptions(array(
'title' = 'My OpenGraph Title',
'type' = 'article',
'url' = 'http://example.net/',
'image' = 'url-to-my-open-graph-image.jpg',
'site_name' = 'The target Site Name',
'description' = 'The open Graph description...'
));
...and check if any are set and output them in the head:
// if we set some opengraph-tags (ogIsSet()) we can output them by use getOgSetting()
if(is_a ($tmpFbHelper = fbHelper::getInstanceByNamespace(), 'fbHelper') && $tmpFbHelper-ogIsSet()){
?
getOgSetting('title', 'escaped'); ?"/
getOgSetting('type', 'escaped')?"/
getOgSetting('url', 'escaped'); ?"/
getOgSetting('image', 'escaped'); ?"/
getOgSetting('site_name', 'escaped'); ?"/
getOgSetting('description', 'escaped'); ?"/
isPageFan() ? 'Yes' : 'No') . "";
Check if facebook user is connected to the app (when in facebook)
echo "Is Connected: ". ((bool)$tmpFbHelper-isConnected() ? 'Yes' : 'No') . "";
Deeplinking into your page tab
If any app_data are set by $_GET you can force your application to deeplink to the originally requested page. The method performDeeplink() will look for those data and perform the deep link:
$tmpFbHelper-performDeeplink();
If you want to have some Javascript functions called after the Facebook JSDK is loaded, you can add function-names to or fbHelper:
$tmpFbHelper-addJsInitMethod('funcNameToCallAfterInit'); // add a function name
$tmpFbHelper-getJsInits(); // returns a string in JS format with the functions to call
Read and save wall/stream of user or page
If you want to read the content of a uses/page stream/wall you have to save the access_token of a user in your database. After saved an access_token you can add a wall-entry:
fbHelperWallReader::saveWall($wall_id, $user_id, $appId);
Once a wallReader is registered in your database you can fetch the wall and save the posts:
fbHelperWallReader::refreshWall($fb_source);
The $fb_source is equal to the $wall_id we have saved in the step before. After calling this the latest 500 posts are saved to our database. Those items can now be retrieved any time:
$objWall = new fbHelperWall($fb_source);
$posts = $objWall-retrieveItems()-getItems();
Several filters can be set to define which posts exactly to search and return.
Init the Javascript fbHelper:
<script type="text/javascript" charset="utf-8">
// <![CDATA[
jQuery(window).load(function () {
fbHelper.setFBAllowed(true);
fbHelper.setOption({ 'fbLang' : 'en_US',
'canvasResizeInterval' : 1000
});
fbHelper.initFB({ appId: '<?=$appId?>' }, <?=fbHelper::getInstance($appId)->getJsInits()?>);
fbHelper.checkResizable();
});
// ]]>
</script>
This code may output something like:
<script type="text/javascript" charset="utf-8">
// <![CDATA[
jQuery(window).load(function () {
fbHelper.setFBAllowed(true);
fbHelper.setOption({ 'fbLang' : 'us_US',
'canvasResizeInterval' : 1000
});
fbHelper.initFB({ appId: '1234567890' }, Array("funcNameToCallAfterInit()"));
fbHelper.checkResizable();
});
// ]]>
</script>
Use case "Connect for commenting"
If you want to let a user connect to your app before commenting something in your app or if you want to make a stream publish to his stream/chronic the following code might help you with this:
$tmpFbHelper->addJsInitMethod('bindCommentSubmit');
<div id="comment">Click here to comment!</div>
<script type="text/javascript" charset="utf-8">
// <![CDATA[
var isConnected = function(someParams) {
console.log('The User is connected to our App...');
console.log(arguments);
// do some ajax for commenting and perform a stream publish
}
var isNotConnected = function(someParams) {
console.log('The User is NOT connected to our App...');
console.log(arguments);
}
function bindCommentSubmit() {
jQuery('#connect').click(function() {
var appScope = 'general';
fbHelper.loginAndSave('publish_stream', appScope,
{ func : isConnected,
params : ['xx'],
cufa : true
} ,
{ func : isNotConnected,
params : ['yy'],
cufa : true
}
);
}
// ]]>
</script>
What does this code do?
Once the Facebook Framework is loaded, it will call bindCommentSubmit() to bind a click-event to our button. When the user clicks the button the fbHelper will look if the user is already connected to the app and has provided the permission to "publish_stream". If we have the permission the isConnected method is called with the params-array ['xx'] (or whatever you want). If not the browser will display the facebook connect window for requesting the permissions. If the user granted the permission the script will perform an ajax call to the php fbHelper to store the accessToken from the user. After that the isConnected method is called. If the user deny the prompt the isNotConnected method is called.
Further Usecases
Feel free to comment and request custom use-cases. I will be glad to help you!
Questions & Comments