upload photos got by fql query on my server - facebook

Hello guys i'm trying to understand how to upload the image from facebook.
function for do fql query. Is useful for future occasions.
<?php
// connection facebook api key...
function fb_fql($fql) {
$this->ci =& get_instance();
// Get User Details
$this->ci->load->model('facebook_model');
$this->ci->load->library('user');
// $fb_id = $this->ci->user->get_facebook_id($this->ci->session->userdata('user_id'));
// User is found
// Get Facebook User profile
$user_profile = $this->ci->facebook->getUser();
$result = false;
if ($user_profile) { // if profile exist
try{
$accessToken = $this->ci->facebook->getAccessToken();
$fb_id = $this->ci->facebook->api('/me?access_token='.$accessToken);
if( isset($user_profile) )
{
$fql_run = array(
'method' => 'fql.query',
'query' => $fql,
);
$result = $this->ci->facebook->api($fql_run); // run fql
} else { $result = false; }
}catch(FacebookApiException $e){
$result = null;
}
}
return $result;
}
?>
Here i get the photos by this query and the result of the array show correctly 10 photos of facebook. Now i have to upload it on my server but how can i do that?
<?php
// fql query
$fql = "SELECT pid
FROM photo
WHERE aid IN (
SELECT aid
FROM album
WHERE owner=me() LIMIT 10
) ";
// run query
$photos = $this->facebook_action->fb_fql($fql);
if ($photos != false) {
foreach ($photos as $photo) {
echo print_r($photos); // show the array with the data taken
// here i would like upload the photos got from the query.
}
} else {
echo "no photo";
}
?>

You will need to get the src or src_big field from the photo table and then download this using CURL, file_put_contents or similar. There are quite a few StackOverflow answers for grabbing an image and saving it to a file - e.g Saving image from PHP URL
SELECT src_big FROM photo
WHERE aid IN (SELECT aid FROM album WHERE owner=me() LIMIT 10)
Since you will be downloading user's data to your own server, I would advise you to check that your application does not violate the Facebook Platform Policy.

Related

how can I get a facebook Page access token from a users access token using php?

I am trying to get a page access token starting out with just a users access token stored in my database and a page id. So far I have not been using the facebook.php instead just using php's curl_* functions. So far I can send posts to the page (with a hard coded page id) but I want to impersonate the page when doing so.
Can I do this easily without facebook.php, that would be nice as it might save me from feeling like I should rewrite what I've done so far. If not, then how would I get the page access token from the facebook object - remember so far at least I don't store user ids or page ids in my db, just user access tokens and of course my app id and secret.
I've been looking at the example for getting page access tokens but I find it not quite what I need as it gets a user object and in so doing seems to force the user to login to facebook each time, but I stored the user access token to avoid exactly that from happening.
Do I need more permissions than manage_page and publish_stream? I tried adding offline_access but it doesn't seem available anymore (roadmap mentions this).
here is some of my code from my most recent attempt which uses the facebook.php file:
// try using facebook.php
require_once 'src/facebook.php';
// Create our Application instance
$facebook = new Facebook(array(
'appId' => $FB_APP_ID, // $FB_APP_ID hardcoded earlier
'secret' => $FB_APP_SECRET, // $FB_APP_SECRET hardcoded earlier
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//got user access token $FB_ACCESS_TOKEN from database
// Get User ID -- why?
$user = $facebook->getUser();
//------ get PAGE access token
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {// $page_id hardcoded earlier
$page_access_token = $page["access_token"];
break;
}
}
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result); //this prints: array(1) { ["data"]=> array(0) { } }
$facebook->setAccessToken($page_access_token );
// Get User ID, why - re-init with new token maybe?
$user = $facebook->getUser();
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result);
} catch(Exception $e) {
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $e= ' ;
var_dump($e); /*this gives : "An active access token must
be used to query information about the
current user." */
}
die;
Thanks
PS: I hardcoded the user id and started calling
$result = $facebook->api("/$user_id/accounts", $attachment_1);
and I still get an empty result.
PPS: The Graph API Explorer does not show my fan pages either even though my account is set as the Manager. My attempts to post work but show as being from my account rather than from the page.
PPPS: made a little progress by adding permissions on the graph explorer page to get an access token that way but that doesn't help as I need to the the access token programmatically. When a user with many fan pages logs in to my site I want to show them the list of their facebook fan pages to choose from. In practice aren't the permissions just granted on the app?
PPPPS: the list of permissions on my app now stands at : email, user_about_me, publish_actions
and
Extended Permissions:
manage_pages, publish_stream, create_note, status_update, share_item
do I need more? when I try now I still fail to get anything from the call to:
$facebook->api("/$user_id/accounts", $attachment_1);
Px5S: DOH!!! I see now that I was neglecting to add the manage_pages permissions to my call for a user access token when my scripts first get one and store it in the DB. But when I reuse that new access token I still get the error : "An active access token must be used to query information about the current user." So, can't such tokens be reused? Aren't they long term? will read more stuff...
Here is my functioning code, still messy but seems to work, note the scopes on the first $dialog_url, and please feel free to mock my code or even suggest improvements :
function doWallPost($postName='',$postMessage='',$postLink='',$postCaption='',$postDescription=''){
global $FB_APP_ID, $FB_APP_SECRET;
$APP_RETURN_URL=((substr($_SERVER['SERVER_PROTOCOL'],0,4)=="HTTP")?"http://":"https://").$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'?returnurl=1';
$code = $_REQUEST["code"];
$FB_ACCESS_TOKEN = getFaceBookAccessToken( );
$FB_ACCESS_TOKEN_OLD = $FB_ACCESS_TOKEN;
//if no code ot facebook access token get one
if( empty($code) && empty($FB_ACCESS_TOKEN) && $_REQUEST["returnurl"] != '1')
{
// if( $_REQUEST["returnurl"] == '1') die;
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=".$FB_APP_ID."&redirect_uri=".$APP_RETURN_URL."&scope=publish_stream,manage_pages";
header("Location:$dialog_url");
}
if( empty($FB_ACCESS_TOKEN) ){
if($_REQUEST['error_code'] == '200'){
return null;
}else if (!empty($code)){
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$FB_APP_ID."&redirect_uri=".urlencode($APP_RETURN_URL)."&client_secret=".$FB_APP_SECRET."&code=".$code;
$access_token = file_get_contents($token_url);
$param1=explode("&",$access_token);
$param2=explode("=",$param1[0]);
$FB_ACCESS_TOKEN=$param2[1];
}else{
return null;
}
}
if(!empty($FB_ACCESS_TOKEN) && $FB_ACCESS_TOKEN_OLD != $FB_ACCESS_TOKEN) {
setFaceBookAccessToken( $FB_ACCESS_TOKEN);
}
$_SESSION['FB_ACCESS_TOKEN'] = $FB_ACCESS_TOKEN;
$page_name = '';
$page_id = getFaceBookPageId(); //from db
if(empty($page_id ) ) return null;
//in case there are multiple page_ids separated by commas
if(stripos($page_id, ',') !== false ){
$page_ids = explode(',', $page_id) ;// = substr($page_id, 0, stripos($page_id, ','));
}
$result = null;
foreach($page_ids as $page_id){
$page_id = trim($page_id);
if( !empty($FB_ACCESS_TOKEN)){
//get page_id
require_once 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $FB_APP_ID,
'secret' => $FB_APP_SECRET
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//------ get PAGE access token
$page_access_token ='';
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
if(count($result["data"])==0) {
return null;
}
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
} catch(Exception $e) {
return null;
}
} //end if( !empty($FB_ACCESS_TOKEN))
}//end foreach
return $result; }
Now, I wonder if I can send the same message to several pages at once ...
Yup, just by looping over the ids, see above, it now supports multiple page ids.
And unless someone wants to contribute to the code - there's lots of ways it can be improved - I'm done.

Facebook API taggin photos work only in sandbox mode

I'm having a problem with the function of tagging the facebook API, I'll do a summary of the application that I am creating for you to have a better idea of what I need.
I am creating an application where the user selects his friends and the software produces an image with all his friends names plus each ones tags.
I succeed in all of the functions: listing friends, selecting them, generating the image and posting to the timeline. But I can not tag the people, which is an important function to the viral effect of the app.
A strange thing has happened, if I enable Sandbox Mode and select only the ADMINS or TESTERS, the code works. But if I turn off Sandbox mode and select any other friends, nothing happens with the tags.
Below I leave the code I've used.
I used the array_push function to add the IDs to the Facebook 'tags' array.
Facebook Conection:
// INSERE O HEADER
include('includes/header.php');
// CONNECT // CONFIGURAÇÕES
require('facebook_sdk/src/facebook.php');
// CONEXÃO COM O FACEBOOK
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXX,
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
));
// PEGA SEU ID
$user = $facebook->getUser();
// FUNÇÕES QUE PEGA AS INFOS DO FACEBOOK
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me?fields=id,name,email,friends,photos,friends.fields(photos)');
$input = $facebook->api('/me?fields=id,name,email,friends,photos,friends.fields(photos)');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// LINK PARA LOGOUT E REDIRECT SE FOR USUARIO
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
header('Location: passo1.php');
}
?> <div class="bt-face"><img name="bt_face" id="bt_face" onMouseOver="formbaixo_ON('face');" onMouseOut="formbaixo_OFF('face');" src="images/bt-face.png" alt="Conectar no Facebook" /></div>
</div>
<!---------------- PHP / JAVA BUTTON FACEBOOK (SCOPE = PERMISSÕES) ----------------->
<div id="fb-root"></div>
<script type="text/javascript">
function fbLogin() {
FB.login(function(response) {
if (response.session) {
//user is logged in, reload page
window.location.reload(true);
} else {
// user is not logged in
}
}, { perms:'email,manage_friendlists,publish_stream,user_photos,friends_photos'} );
}
</script>
Tagging code:
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$access_token = $facebook->getAccessToken();
$timeline = $facebook->api('/me?link');
$timeline_link = $timeline['link'];
$input = $facebook->api('/me?fields=id,name,email,friends,photos,friends.fields(photos)');
//At the time of writing it is necessary to enable upload support in the Facebook SDK, you do this with the line:
$facebook->setFileUploadSupport(true);
$album = $facebook->api(array(
'query' => "SELECT object_id FROM album WHERE owner=me() AND name='Album name' AND can_upload=1",
'method' => 'fql.query',
));
if (isset($album[0]['object_id'])) $album_uid = $album[0]['object_id'];
else
{
foreach ($albums[data] as $album) {
//Test if the current album name is already in facebook
if($album[name] == 'Album name'){
$album_uid = $album[id];
}
}
if(!$album_uid){
}
}
//Upload a photo to album of ID...
$photo_details = array(
'message'=> 'Eu criei um time...'
);
$file = $url_image; //'images/teste2.gif'; //Example image file
$args_tags = array();
// RETIRA BARRAS DOS ARRAYS
$parte = explode("//", $convocados);
$conta = count($parte);
// EXIBE
$espacamento_linha = 20;
$x_convocados = 0;
$y_convocados = 0;
$array_facebook_tag = '';
for($i=0; $i < ($conta-1); $i++) {
$explode_parte = explode("-", $parte[$i]);
$nome = str_replace("_"," ", $explode_parte[0]);
$id = $explode_parte[1];
$x_jogador = $x_convocados;
$y_jogador = $y_convocados + ($i * $espacamento_linha);
array_push($args_tags, array('tag_uid' => $explode_parte[1], 'x' => $x_jogador, 'y' => $y_jogador));
}
$args = array(
'message' => 'Esse é o meu time dos sonhos. Crie o seu time ',
'image' => '#' . realpath($file),
'tags' => $args_tags,
);
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $args);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
Any help will be welcome, Thanks!

First time access after facebook authentication

Is there any way that when user authenticate my app through Enhanced Auth Dialog, and gets redirected to canvas page, my canvas page knows its his first time visit?
Your may get the user id from facebook after the user redirected to canvas page:
Here is the example:
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = false; // optional
$facebook = new Facebook($config);
$app->user_id = $facebook->getUser();
After you obtain the user_id, you may save it in your database so that you can know whether the user is first time visit.
The previous answer is correct and here is the code I use to check if they are a new user or a returning user. Then I insert them into the database if they are new.
// Get the app User ID
$user = $facebook->getUser();
$seeif = mysql_num_rows(mysql_query("SELECT id FROM users WHERE fbid='$user' LIMIT 1"));
if ( $seeif == "1" ) {
// already exists
} else {
// insert new user
mysql_query("INSERT INTO users (fbid) VALUES('$user' ) ")
or die(mysql_error());
}
While the previous answers are correct, this might be more useful to you in the long run building your application.
Remember this relies on you having an open database connection as well as the facebook php sdk
// this brings back more info print_r($user)
$user = $facebook->api('/me');
$exists = mysql_num_rows(mysql_query("SELECT id FROM users WHERE fbid='" . $user['id'] . "'));
if ( $exists > 0) {
// already exists
} else {
// insert new user
mysql_query("INSERT INTO users (fbid) VALUES('" . $user['id'] . "' ) ") or die(mysql_error());
// do something else (post to timeline?)
// look up facebook feed for more info on posting
try {
// Post Message to feed.
$facebook->api('/me/feed', 'POST', $msg);
} catch (FacebookApiException $e) {
error_log($e);
}
}

Facebook Getting picture from file server and upload it to fan page photo album

I've photos on my web server,now,i've to upload it to fan page photo album.Is there any limit for photo upload.After uploading it to fan page photo album,i've to post it to wall.
// Get the page access token
$accounts = $facebook->api('/my_account_id/accounts', 'GET', $params);
$data = $accounts['data'];
foreach($data as $account) {
if( $account['id'] == $fanpage || $account['name'] == $fanpage )
$fanpage_token = $account['access_token'];
}
// Get all albums from the page
// Must use app access token, not page token!
// You can also use a static album id to test
$fanpage_albums = $facebook->api($fanpage . '/albums', 'GET', $params);
$albums = $fanpage_albums['data'];
$sorted = array();
foreach($albums as $album) {
if( ! strpos($album['name'], 'Special') )
continue;
$sorted[] = $album;
}
$album_id = $sorted[0]['id']; // Get the first one. Shouldn't be empty!
// Upload the photo (previously uploaded by user)
$args = array(
'message' => 'Von ' . $teilnehmer_name,
'image' => '#' . realpath($path. $_FILES['media']['name']),
'aid' => $album_id,
'no_story' => 1 // Nicht auf der Wall anzeigen (Thank God for that),
'access_token' => $fanpage_token // note, we use the page token here
);
$photo = $facebook->api($album_id . '/photos', 'post', $args);
if( is_array( $photo ) && ! empty( $photo['id'] ) )
echo 'Photo uploaded. Check it on Graph API Explorer. ID: ' . $photo['id'];
I tried the above code but it is not working.
Do not use realpath(), use the folder name/file name, it will work then you need a page access token.

How to get facebook total likes for a facebook application?

I know you can get the total fan count for a facebook page via the facebook graph api. But I cannot seem to be able to get the total likes (or fan count) of a facebook application. Take for example, graph.facebook.com/castleage, notice that the fan count is missing...any clues on how to do so? Thanks.
Try luck with something like this:
$data = array();
try {
$data = $facebook->api(array(
'query' => 'SELECT uid FROM page_fan WHERE page_id=' . $fanpageId,
'method' => 'fql.query'
));
} catch(Exception $e) {
print_r($e);
}
$fanCount = count($data);
print_r($fanCount);