Facebook Events by Cron Job Struggle - facebook

I finally have a working script to submit Facebook Events remotely, and have finished tackling the problem of converting my site's events RSS feed to the FB Events data. Utilizing RSS2HTML, I have added in a template-based call to send each event over two days before the event. Here's the code:
// Post Today's Game
if (strstr($template, "~~~TwitterToday~~~"))
{
//Build Arrays for games (when there are more than one per day...
$name = array( 'name' );
$desc = array( 'description' );
$venue = array( 'location' );
$s_time = array( 'start_time' );
$e_time = array( 'end_time' );
$pic = array( 'picture' );
$priv = array( 'privacy' );
//Build Main Facebook Array for All games to draw from
$fbook = array(
$name,
$desc,
$venue,
$s_time,
$e_time,
$pic,
$priv,
);
$template = str_replace("~~~TwitterToday~~~", "", $template);
$mycount = 1;
for ($y = 1; $y < count($rss_parser->Items)+1; $y++) //come back through events
{
//find each event's information to look for today's
$gamedate = date('n/j/Y', $rss_parser->Items[$y]->pubDate_t);
$todaysdate = date('n/j/Y');
$tomorrowsdate = date('n/j/Y',mktime(0,0,0,date('m'), date('d')+1, date('Y')));
$gametime = date('Y-m-d H:i:s',$rss_parser->Items[$y]->pubDate_t);
$title = $rss_parser->Items[$y]->title;
$description = $rss_parser->Items[$y]->description;
if ($gamedate == $tomorrowsdate) //found it
{
$mycount++;
//Fill the arrays
$name[] = $title;
$desc[] = $description;
$venue[] = "Home";
$s_time[] = $gametime;
$e_time[] = "";
$pic[] = "";
$priv[] = "OPEN";
}
} // end $y loop
//Populate Main Facebook Array
$fbook[0] = $name;
$fbook[1] = $desc;
$fbook[2] = $venue;
$fbook[3] = $s_time;
$fbook[4] = $e_time;
$fbook[5] = $pic;
$fbook[6] = $priv;
// Let's run with it
if (strpos($title,"Special Event") === false)
{
$page_id = "xxxxxxxxxxxxxx"; //First Page Id
}
else
{
$page_id = "xxxxxxxxxxxxxxxxxxx"; //Special Event Page Id
}
$app_id = "xxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
$my_url = "http://mydomain.com/feeds/rss2html.php"; // URL to THIS script
//Going to get the PAGE access code
//First to get USER Access Code
session_start();
$code = $_REQUEST["code"];
if (empty($code))
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=" . $_SESSION['state'] . "&scope=create_event&scope=manage_pages";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if ($_REQUEST['state'] == $_SESSION['state'])
{
$token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code;
$access_token = #file_get_contents($token_url);
$params = null;
parse_str($access_token, $params);
$graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
}
else
{
echo("The state does not match. You may be a victim of CSRF.");
}
//Now, getting the PAGE Access token, using the user access token
$page_token_url = "https://graph.facebook.com/" . $page_id . "?fields=access_token&" . $access_token;
$response = file_get_contents($page_token_url);
// Parse the return value and get the Page access token
$resp_obj = json_decode($response,true);
$page_access_token = $resp_obj['access_token'];
for ($s = 1; $s < $mycount+1; $s++)
{
//Let's go post it up!
$url = "https://graph.facebook.com/" . $page_id . "/events?access_token=" . $page_access_token;
$params = array();
// Prepare Event fields
$params = array(
'name' => $fbook[0][$s],
'description' => $fbook[1][$s],
'location' => $fbook[2][$s],
'start_time' => $fbook[3][$s],
// 'end_time' => $fbook[4][$s], //These need to be excluded if they are empty
// 'picture' => $fbook[5][$s],
'privacy' => $fbook[6][$s],
);
// Start the Graph API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
$decoded = json_decode($result, true);
curl_close($ch);
if (is_array($decoded) && isset($decoded['id']))
{
$msg = "Event created successfully: {$decoded['id']}";
}
echo '<hr />' . $msg;
}
/* End FaceBook Code */
}
This script works wonders when I call it from my browser, but when calling it from the cron job, I get an "Unable to open template" error in the rss2html script. In the past, I have always been able to solve this by making a separate script for the cron job, essentially using cURL to call the feed, and it works wonders.
Unfortunately, this technique won't work with a FaceBook Auth script, because it then returns the "The state does not match. You may be a victim of CSRF."
So, I'm between a rock and a hard place. Can't run the rss2html script without the cURL call, and the cURL call impedes the Facebook login. Here's a text version of the rss2html script as it stands, in case anyone wants to see it.
Can anyone think of a good workaround one way or t'other?
Thanks to DCMS, solution went thusly:
Using Facebook's Authentication Docs at https://developers.facebook.com/docs/authentication/ and adding '&scope=offline_access" to my call, I was able to grab some offline access tokens, and altered my above code thusly:
//Going to get the PAGE access code
//First to get USER Access Code
session_start();
for ($s = 1; $s < $mycount+1; $s++)
{
//Let's go post it up!
$url = "https://graph.facebook.com/" . $page_id . "/events?access_token=" . $page_access_token;
$params = array();
// Prepare Event fields
$params = array(
'name' => $fbook[0][$s],
'description' => $fbook[1][$s],
'location' => $fbook[2][$s],
'start_time' => $fbook[3][$s],
// 'end_time' => $fbook[4][$s], //These need to be excluded if they are empty
// 'picture' => $fbook[5][$s],
'privacy' => $fbook[6][$s],
);
// Start the Graph API call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
$decoded = json_decode($result, true);
curl_close($ch);
if (is_array($decoded) && isset($decoded['id']))
{
$msg = "Event created successfully: {$decoded['id']}";
}
echo '<hr />' . $msg;
}
/* End FaceBook Code */
}
Thanks for the help, and I hope this helps anyone to come along with the same issue in the future!

Your solution might be to store the access token. Request offline_access and grab that token and hold onto it. Then use that token for your Graph API calls.

Related

Consume a REST API in codeigniter controller

I have create a REST API and want to consume my own created API in codeigniter controller.
My created REST API
controller(example.php)
class Example extends REST_Controller {
public function __construct() {
parent::__construct();
$this->load->model('user');
}
public function user_fetch_post() {
//returns all rows if the id parameter doesn't exist,
//otherwise single row will be returned
$id = $this->input->post('id');
$users = $this->user->getRows($id);
//check if the user data exists
if(!empty($users)){
//set the response and exit
$this->response($users, REST_Controller::HTTP_OK);
}else{
//set the response and exit
$this->response([
'status' => FALSE,
'message' => 'No user were found.'
], REST_Controller::HTTP_NOT_FOUND);
}
}
model(user.php)
function getRows($id = ""){
if(!empty($id)){
$query = $this->db->get_where('users', array('id' => $id));
return $query->row_array();
}else{
$query = $this->db->get('users');
return $query->result_array();
}
}
Here i want to call my created api(from example.php)for fetch record in welcome.php controller with basic authentication(uname-admin,pwd-1234)
my controller welcome.php
public function index()
{
}
Can anybody help to me that how to call my api in controller welcome.php with basic authentication.
Using CURL you can consume any API/network call.
<?php
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode("user:password") // place your auth details here
);
$payload = array(
'id' => 1,
);
$process = curl_init($host); //your API url
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $payload);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
curl_close($process);
//finally print your API response
print_r($return);
?>
But why are you calling your own API this way? You can simply call your API model and perform your operations
Add below to your curl options
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'APIKEY: admin#123',
'Content-Type: application/json',
));
also update
$config['rest_key_name'] = 'APIKEY';
in rest.php file inside config folder of your codeigniter settings. By default it is 'X-API-KEY'
This may help to somebody else looking for a solution, if OP has resolved it himself/herself.

facebook publish action but without redirect

The flow of action on my site is:
a user finds something they want on any website
they click a browser button which opens an iframe with content from my site and allows the user to add the item they were looking at to a list
(at this point my system does the work to add details to the db)
the user then clicks to close the iframe and carries on doing what they were
When a user chooses to add something i want to also publish the action to facebook timeline
I use the following code which works as it should, but, once it has completed the task it redirects to a predetermined url - named $my_url
The problem is I want this action posting to happen seamlessly as my user has an iframe pop up open which at this point is saying "* has been added successfully to your list"
So can I stop it redirecting and make it just a background operation? I can't redirect to what the user is already looking at either which was one idea as you have to own the url inside the fb app
This is the code I'm using
$app_id = "_APP_ID_";
$app_secret = "_SECRET";
$my_url = "http://*******.com/pages/add.html";
$og_url = "http://*******.com/pages/view?id=$new_id";
$code = $_REQUEST["code"];
if(empty($code)) {
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. &scope=email,user_birthday,friends_birthday,user_likes,friends_likes,publish_stream";
echo("<script>top.location.href='" . $dialog_url . "'</script>");
}
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$access_token = file_get_contents($token_url);
// remove the #expires
$params = null;
parse_str($access_token, $params);
$access_token_updated = $params['access_token'];
$post_data = "wish=" . $og_url . "&access_token=" . $access_token_updated;
// setup the curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/me/*******:add');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute the curl
$result = curl_exec ($ch);
if(curl_error($ch))
{
//echo 'error:' . curl_error($ch) . "<br/>";
}
curl_close ($ch);
Is there another way around this?
Here's what I did...
Change all code in OP and replace with this and all ok:
include 'path_to/facebook.php';
$facebook = new Facebook(array(
'appId'=>'__APPID__',
'secret'=>'__SECRET__',
'cookie'=>true
));
if(!$facebook->getUser())
{
$url = $facebook->getLoginUrl(array('scope'=>'email,publish_actions'));
echo "<script> top.location=\"".$url."\"; </script>";
exit(0);
}
$params = array("OBJECT_NAME"=>"http://*****.com/view?id=$new_id","access_token"=>$facebook->getAccessToken());
$out = $facebook->api('/me/NAMESPACE:ACTION_NAME','post',$params);

Facebook API upload photo from URL

I have a website with photo gallery and I'd like to upload each photo (one by one) to my facebook page (not wall). I managed to post a message but now I want to upload a photo to a FB Page Wall by uploading an existing image from the server - specific URL (I don't want to upload again locally). Is this possible?
Yes you can do it
Example
In Graph Api Explorer
Make the call post, set url to https://graph.facebook.com/me/photos,
Add field with key message and value "any custom message"
Add another field with key url and value https://appharbor.com/assets/images/stackoverflow-logo.png
click submit
You need to know the album id and make call POST to:
https://graph.facebook.com/albumid/photos?access_token=$access_token
You will find the album id entering into the album and looking at the URL. Will be something like https://www.facebook.com/media/set/?set=a.XXXXXXXXXXX.YYYY.ZZZZZZZZZZ&type=3
Your album id are the XXXX.
this is what I use:
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true,
'fileUpload' => true,
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
$facebook->setFileUploadSupport(true);
if($user == 0) {
// If the user is not connected to your application, redirect the user to authentication page
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*/
$login_url = $facebook->getLoginUrl($params = array('redirect_uri' => REDIRECT_URI,'scope' => PERMISSIONS_REQUIRED));
echo ("<script> top.location.href='".$login_url."'</script>");
} else {
// if the user is already connected, then fetch access_token and user's information or show some content to logged in user.
try
{
$access_token = $facebook->getAccessToken(); // Gives you current user's access_token
$user = $facebook->api('/me'); // Gets User's information based on permissions the user has granted to your application.
} catch(FacebookApiException $e){
$results = $e->getResult();
// Print results if you want to debug.
}
}
$img = './upload/'.$image_path;
$args = array(
'message' => 'Some Message',
'access_token'=>urlencode($access_token),
);
$args[basename($img)] = '#'.realpath($img);
$ch = curl_init();
$url = 'https://graph.facebook.com/me/photos';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
$response = json_decode($data,true);
$config = array('appId' => $config['App_ID'],'secret' => $config['App_Secret']);
$facebook = new Facebook($config);
// sets our access token as the access token when we call
// something using the SDK, which we are going to do now.
$facebook->setAccessToken($access_token);
$page_id = "XXXXXXXXXXXXXXX";
$page_access_token = "";
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
$facebook->setFileUploadSupport(true);
$photo = "http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png";
$args = array(
'access_token' => $page_access_token,
'message' => "message here",
'url' => $photo,
);
$post = $facebook->api("/$page_id/photos","post",$args);

facebook api returning "Got EOF while waiting for outstanding responses" error message

I am posting images through my app to users wall on their behalf (they step in front of a camera at events). MY app was working successfully last week now its not working and reporting "Got EOF while waiting for outstanding responses".
There is a related bug report but its for an iphone app while mine is a web based php.
Can anyone shed light on this error message? my code is below but its broken down a lot for pic processing and db calls..
//initial calling code
$data = array('title' => $station_info->title,
'message' => $station_info->message,
'token' => $result['access_token'],
'item' => $item,
'pic_source' => $image,
'fb_id' => $result['fb_id'],
'album_id' => $station_info->pic_station_album_id,
'user_id' => $user_id_data['id'],
);
//$result = $this->__do_facebook_image_post($data);
$feedback = "FACEBOOKIMG: " . $this->__do_facebook_image_post($data, 'x');
///processing code
private function __do_facebook_image_post($data,$type = "normal"){
$attachment = array(
'title' => $data['title'],
'message' => $data['message'],
'token' => $data['token']
);
if($type =="normal"){
$folder = "webcam";
}else if($type="x"){
$folder = "x";
}
$upload_path = FCPATH . "/pic_uploads/".$folder."/".$data['item'];
echo $upload_path;
if(is_file($upload_path))
{
$attachment['source'] = '#' . realpath(FCPATH . "/img_uploads/".$folder."/". $upload_path);
}
else
{
$attachment['source'] = '#' . realpath(FCPATH . "/img_uploads/".$folder."/". $data['pic_source']);
}
return $this->facebook_img_post($data['fb_id'],$attachment,$this->__get_facebook_album_id($data['album_id'],$data['user_id'],$data['token']),$data['token']);
}
private function __do_facebook_image_post($data,$type = "normal"){
$attachment = array(
'title' => $data['title'],
'message' => $data['message'],
'token' => $data['token']
);
if($type =="normal"){
$folder = "webcam";
}else if($type="x"){
$folder = "x";
}
$upload_path = FCPATH . "/pic_uploads/".$folder."/".$data['item'];
echo $upload_path;
if(is_file($upload_path))
{
$attachment['source'] = '#' . realpath(FCPATH . "/img_uploads/".$folder."/". $upload_path);
}
else
{
$attachment['source'] = '#' . realpath(FCPATH . "/img_uploads/".$folder."/". $data['pic_source']);
}
return $this->facebook_img_post($data['fb_id'],$attachment,$this->__get_facebook_album_id($data['album_id'],$data['user_id'],$data['token']),$data['token']);
}
private function __post_to_facebook($url,$attachment)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // This i added as the URL is https
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // This i added as the URL is https
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, true); // Do I need this ?
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
$result= curl_exec($ch);
curl_close ($ch);
return $result;
}
function facebook_img_post($fb_id,$data,$album_id ='')
{
if(!empty($album_id)){
$url = "https://graph.facebook.com/".$album_id."/photos";
}else{
$url = "https://graph.facebook.com/".$fb_id."/photos";
}
$attachment = array(
'access_token' => $data['token'],
'message'=> $data['message'],
'source' => $data['source'] . ";type=".get_mime_by_extension($data['source'])
);
return $this->__post_to_facebook($url,$attachment);
}
The error message that got returned didn't really match the problem.
I fixed this error as I was trying to upload a photo but was not passing the correct file path.

facebook web app, getting error 'The state does not match. You may be a victim of CSRF'

I am using the code from the facebook app developer site. I tried it and I am getting the following error :
"The state does not match. You may be a victim of CSRF"
The code used is as follows :
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_URL";
session_start();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
?>
From the code its obv that for some reason, $_REQUEST['state'] != $_SESSION['state']. Can somebody please explain why this is happening. I am also a PHP amateur.
Thank u :)
Use SDK, much easier.
This code gets the user data and serializes it, and throws to the database, i know its not perfect but have a look. I'm going to edit this when i get some free time, then i recommend encoding the users data as JSON, not as base64 serialized, because it will be easier to do query searches in the future.
<?php
require 'facebook.php'; // USE FACEBOOK PHP SDK
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'APPSECRET',
));
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// Get User ID
$user = $facebook->getUser();
/* We may or may not have this data based on whether the user is logged in.
If we have a $user id here, it means we know the user is logged into
Facebook, but we don't know if the access token is valid. An access
token is invalid if the user logged out of Facebook. */
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
// these are the graph calls
$dt = $facebook->api('/me');
$lk = $facebook->api('/me/likes');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// Handler for Login Status
// With the LoginURL, user the 'scope' to ask for permissions
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array("scope" => "email,user_birthday,user_likes,user_work_history,user_location,user_education_history"));
}
// ----------------------------------------------------------------------------------------
?>
<?php if (!$user): header ('Location:'.$loginUrl.''); //CHECKS IF USER IS LOGGED IN
else:
// Do Something here. This next bit of code shows what comes out of those calls.
echo "<pre>";
print_r($dt);
echo"</pre>";
echo"<br/><br/>";
echo "<pre>";
print_r($lk);
echo"</pre>";
endif
?>
I do realize that this problem is already 2 months old but I have a similar issue using the Heroku code. I'm not fully done debugging it yet but I've noticed that the output of
session_id();
changes in IE after a refresh but remains the same in Chrome suggesting that the session gets lost in IE. Obviously, the state of the session will be blank in IE and you receive the CSRF error while it works fine under Chrome.
If someone can shed more light on this I would be grateful. I'll keep updating this answer as I find out more as to what specifically is causing the issue in IE and how to solve it.
[edit]Duh. It's a cookie issue. My IE had blocked coockies (including session cookies) while Chrome didn't. I got the idea after reading http://www.daniweb.com/web-development/php/threads/294235. I'm unsure of the workaround though. I'll keep this updated as I find out more. Any input from others is welcome![/edit]
[edit-2]Alright, as promised here's the solution. You need to activate P3P like so:
header('P3P: CP="CAO PSA OUR"');
Add this to the top of your code where you're using your session(s). I found the solution at Session Lost on IE Facebook App iFrame
For the sake of completeness, here's the code I'm using (look at the login method)-
<?php
/**
* This class provides Facebook specfic utility functions that you may use
* to build your app.
*/
require_once('AppInfo.php');
require_once('utils.php');
class FBUtils {
/*****************************************************************************
*
* The content below provides some helper functions that you may wish to use as
* you develop your app.
*
****************************************************************************/
/**
* GETs graph.facebook.com/$target, and returns it as decoded JSON
* To learn more about the Graph API, visit:
* 'https://developers.facebook.com/docs/refererence/api'
*
* #return graph api content of $target
*/
public static function fetchFromFBGraph($target) {
return self::curl('https://graph.facebook.com/' . $target);
}
/**
* Uses FQL (Facebook Query Language) to return the result of $query with the
* access-token $token. FQL is used to process more complex requests that the
* graph API does not directly expose. For more information, visit
'https://developers.facebook.com/docs/reference/fql'
*
* #return Facebook Query result for $query
*/
public static function fql($query, $token) {
$query = urlencode($query);
return self::curl("https://api.facebook.com/method/fql.query?query=$query&format=json&access_token=$token");
}
/**
* Helper function
* #return the JSON decoded results of curling $url
*/
public static function curl($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
return json_decode(curl_exec($ch), true);
}
/**
* Authenticates the current viewer of the app, prompting them to login and
* grant permissions if necessary. For more information, check the
* 'https://developers.facebook.com/docs/authentication/'
*
* #return app access token if login is successful
*/
public static function login($redirect) {
$app_id = AppInfo::appID();
//echo "app id: $app_id <br>";
$app_secret = AppInfo::appSecret();
//echo "app secret: $app_secret <br>";
$home = AppInfo::getHome();
//echo "home: $home <br>";
// Scope defines what permissions that we are asking the user to grant.
// In this example, we are asking for the ability to publish stories
// about using the app, access to what the user likes, and to be able
// to use their pictures. You should rewrite this scope with whatever
// permissions your app needs.
// See https://developers.facebook.com/docs/reference/api/permissions/
// for a full list of permissions
$scope = 'user_likes,user_photos,user_photo_video_tags,publish_stream';
//session_start();
$code = $_REQUEST["code"];
// If we don't have a code returned from Facebook, the first step is to get
// that code
if (empty($code)) {
//echo "test"; exit();
// CSRF protection - for more information, look at 'Security Considerations'
// at 'https://developers.facebook.com/docs/authentication/'
$state = md5(uniqid(rand(), TRUE));
setcookie(
AppInfo::appID() . '-fb-app',
$state,
$expires = time()+3600,
$path = "",
$domain = "",
$secure = "",
$httponly = true);
$_SESSION[AppInfo::appID() . '-fb-app'] = $state;
echo session_id(); exit(); // debugging output
// Now form the login URL that you will use to authorize your app
$authorize_url = "https://www.facebook.com/dialog/oauth?client_id=$app_id" .
"&redirect_uri=$home&state=" . $state . "&scope=$scope";
// Now we redirect the user to the login page
echo("<script> window.location.href='" . $authorize_url . "'</script>");
return false;
// Once we have that code, we can now request an access-token. We check to
// ensure that the state has remained the same.
} else
{
echo $_REQUEST['state']."|"; echo $_SESSION[AppInfo::appID() . '-fb-app']; exit(); // debugging output
if ($_REQUEST['state'] === $_COOKIE[AppInfo::appID() . '-fb-app']) {
$ch = curl_init("https://graph.facebook.com/oauth/access_token");
curl_setopt($ch, CURLOPT_POSTFIELDS,
"client_id=$app_id&redirect_uri=$home&client_secret=$app_secret" .
"&code=$code&scope=$scope");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
// Once we get a response, we then parse it to extract the access token
parse_str($response, $params);
$token = $params['access_token'];
return $token;
// In the event that the two states do not match, we return false to signify
// that something has gone wrong during authentication
}}
//else {
// echo("States do not match. CSRF?");
// return false;
//}
}
}