How can I get facebook albums with images from users - facebook-graph-api

I am creating a facebook app and i want to display the users albums with the cover image, i have tried with code #1 but it is really really slow as i make a facebook api call in the foreach which makes my app take forever, so I am looking for another way to make the api call just once and get all the info, so i tried with FQL multi query (code#2) but now i have a problem because if the album has no image it won´t return nothing, so please check my codes and if you have any idea how i can do this i will greatly appreciate it
code#1
$albums = $facebook->api('/me/albums?limit=0&fields=id,name,count,cover_photo');
foreach($albums['data'] as $album)
{
// get all photos for album
$photos = $facebook->api("/{$album['id']}/?fields=picture,name,count");
$foto = $photos['picture'];
$nombre = $album['name'];
$id = $album['id'];
$count = $album['count'];
$cover_photo = $album['cover_photo'];
$nombre = $nombre." (".$count.")";
echo "<li> <img src=\"https://graph.facebook.com/{$cover_photo}/\" alt=\"$nombre\" /> </li>";
}
code#2
$multiQuery = '{
"albumes":"SELECT name,cover_pid,object_id,size FROM album WHERE owner=me()",
"portadas":"SELECT src_big FROM photo WHERE pid IN (SELECT cover_pid FROM #albumes)"
}';
$param = array(
'method' => 'fql.multiquery',
'queries' => $multiQuery,
'callback' => '');
$queryresults = $facebook->api($param);
foreach($queryresults[0]['fql_result_set'] as $album)
{
$nombre = $album['name'];
$id = $album['object_id'];
$count = $album['size'];
$nombre = $nombre." (".$count.")";
echo "<li> <img src=\"https://graph.facebook.com/{$cover_photo}/\" alt=\"$nombre\" /> </li>";
}

so i tried with FQL multi query (code#2) but now i have a problem because if the album has no image it won´t return nothing
Can’t really see your problem there. If I try your queries using the Graph API explorer, it gives me all my albums, and a cover photo for each one that has one. (So that’s 4 albums and 3 photos for me.)
If you’re having trouble to tell which photo is from which album – then just include the aid field in both queries.
it is really really slow as i make a facebook api call in the foreach which makes my app take forever
Of course it does, because each API call means another HTTP request, and those are slow.
If the FQL method doesn’t give you what you want, then make your API requests into batch requests – that reduces the number of HTTP requests, and therefor should speed things up quite well.

Related

Photos in album returning empty

I've been having a recurring issue today. I'm trying to display the photos from an album. For some reason everything works fine on the Graph Explorer using graph and fql (https://developers.facebook.com/tools/explorer/ ) but when I pull it into the app I always get an empty array returned.
I do have the correct permissions for this request too all permissions on this app are email, user_about_me, publish_actions, user_photos
The call's I have tried that are doing this are below and they all give me the same results.
$photos = $facebook->api('/'.$album_id.'/photos/');
// or
$photos = file_get_contents('https://graph.facebook.com/'.$album_id.'/photos/?access_token=' . $access_token);
// or
$params = array(
'method' => 'fql.query',
'query' => "SELECT images, src FROM photo WHERE album_object_id = " . $album_id,
);
$photos = $facebook->api($params);
It has returned the album contents once or twice, but out of the hundreds of times i've tested this 99.99% of the time its a blank array/json coming back.
Anyone know of a similar issue with this at all.

Display name & picture knowing ID

I was looking to find an answer to my question, but so far I got this:
https://graph.facebook.com/the_user_id?fields=name,picture
I need to be able to display/print first,last name and picture of a set list of users for which I know their ID. What code is required to get this data and then to publish it on a php/html page? Of course, this will means that if I want to show 10 users, I will input 10 different IDs (read smtg about an array list?). Notice that I DO NOT require for this to work for the current user.
Thanks in advance for your replies.
You need to use file_get_contents ( http://uk3.php.net/file_get_contents ) or curl in php and issue a request to the url such as follows:
https://graph.facebook.com/?ids=id1,id2,id3&fields=name,picture
(replacing id1,id2 with your ids)
this will then return you a json object. You then need to decode ( http://uk3.php.net/json_decode ) and loop through this and access the information
this should get you started
// people array uses the users id as the key and the dessert as the value. The id is then used in the query to facebook to select the corresponding value from this array
$people = array("id1"=>"favourite "dessert", "id2"=>"favourite dessert", "id3"=>"apple pie");
$json = file_get_contents('https://graph.facebook.com/?ids=id1,id2,id3&fields=id,name,picture');
$json = json_decode($json);
foreach($json as $key=>$person){
echo '<p><img src="'.$person->picture.'" alt="'.$person->name.'" />';
echo $person->name.'\'s favourite dessert is '.$people[$person->id'];
echo '</p>';
}
I've batched the requests here, alternatively you could perform 10 separate queries for each user, but that would be a bit pointless and inefficient
The easiest way is with an FQL query:
SELECT first_name, last_name, pic, uid FROM user WHERE uid IN
(Known_ID_1, Known_ID_2, ... Known_ID_n)
The easiest, if you're using PHP is to install the PHP SDK, though you can also make a call directly to https://graph.facebook.com/fql?q=URL_ENCODED_QUERY

How to "Spawn" a Wall album in a new page

I am trying to post pictures to customers' pages. There may or may not be a "Wall Photos" album in the page.
In scenarios where there is not a pre-existing "Wall Photos" album how would I create / request the creation of a wall photo album?
I am using Koala and I can create albums, but I cannot create albums with type = "wall".
here is the code I am using to create / find albums:
def get_photo_album(facebook_id)
# Looking for a pre-existing WALL PHOTO album
p "============= Getting Wall Photos album for fbid #{facebook_id}"
album = get_album facebook_id, 'Wall Photos'
unless album
p ' ======= Album FAIL 1 - getting Photos '
album = get_album facebook_id, FALLBACK_ALBUM_NAME
unless album
p ' ========== Album FAIL 2 - MAKING Phtoos '
#graph_client.put_object facebook_id, 'albums', 'name' => FALLBACK_ALBUM_NAME
sleep 3 # wait 3 seconds to let facebook make and fiddle with new album
album = get_album facebook_id, FALLBACK_ALBUM_NAME
unless album
p ' ##################### UTTER ALBUM FAIL '
raise "Cannot use alternative photo album"
end
end
end
if album && album.length > 0
album
else
# ensure that there is an album.
raise "Cannot use alternative photo album"
end
end
def get_album(facebook_id, name)
params = {'name' => name};
albums = #graph_client.get_connections(facebook_id, "albums", params)
p "Found #{albums ? albums.length : 0} albums named #{name} for fbid #{facebook_id}"
albums = albums.reject do |a|
a['name'] != name
end
p "Found #{albums ? albums.length : 0} albums named #{name} for fbid #{facebook_id} AFTER filtering for name"
pp albums
albums.length >0 ? albums[0] : nil
end
end
And here is the Koala code I am using to put the picture itself
def put_image(facebook_id, params)
params = sanitize_params(params)
params = encode_necessary_params(params)
picture = URI.decode(params['picture'])
photo_album = get_photo_album(facebook_id)
photo_album_id = photo_album['id']
params = params.reject do |key, value|
key == 'metadata_type'
end
p ' -------------------------------------- PUT PICTURE ----------------------------'
p "fbid:#{facebook_id}, message: #{params['message']}, picture: #{picture}"
p ' -------------------------------------- PUT PICTURE ----------------------------'
out = #graph_client.put_picture picture, {:message => params['message']}, photo_album_id
Statsd.increment("posts")
out
rescue Exception => ex
handle_error(ex)
end
I have tried several variations including:
putting 'type' => 'wall' in the #graph_client.put_object parameters: doesn't post the image at all
creating an album named 'Wall Photos' - the album appears, but the posts don't look like wall posts.
To be clear: *The ultimate goal is for all posts to this album to have "big" previews - full column width, not tiled 1" previews. *
Any help would be appreciated.
What you're trying to do isn't going to be possible - the Wall Photos album is a special album which is generated from photos posted to feed, and there is no API available to post photos that way - if you post to /photos they go into an album specifically for the app.
However, all is not lost. If you're willing to embrace newer functionality, you'll both be able to meet your goal of having large photos in feed whilst also achieving greater viral potential for your app. The answer is Open Graph Actions. Specifically User Generated Photos in Open Graph
The process for this is relatively simple:
Create an Open Graph action and object for your app (do this from the Developer App Dashboard for that particular app), this can be anything depending on what your app does, but, for example, Instagram uses 'took' as their OG action and 'a photo' as their OG object. This means that posts from that app look like "Matthew took a photo with Instagram" and show the photo below. Which action you want to use is up to you.
Request publish_actions permission from your app users, if you haven't been already.
Make API calls to:
https://graph.facebook.com/me/YOURAPPNAMESPACE:YOURACTION?
YOUROBJECTTYPE=URLWHEREYOUROGOBJECTISLOCATED&
image[0][url]=URLOFPHOTOYOUWANTTOADD&
image[0][user_generated]=true
You'll also need to sign this API call with the access token for that user, or I believe, if you have publish_actions for that user, you can make the above call to /USERID instead of /me and use your app's access token and it will work.
As you can see from the documentation this will give you the full sized photo that you're after and having it be created by an Open Graph action allows for a whole host of extra virality if you incorporate extras such as OG action links, authenticated referrals etc.

Upload photo to an album AND to wall in facebook through php. So we get a big picture on wall

I manage to sent a photo from my server to a users album on facebook.
But this photo is not automaticly seen on his wall. And specifically it is not seen as a big photo, like how photos from albums are shown on a wall.
So I suppose I have to do a second request to tell facebook to put the photo on the wall.
I have these 2 requests:
$ret_obj = $facebook->api('/me/photos', 'POST',
array(
'source' => '#/var/www/cover/test.jpg',
'message' => $_POST['msg']
)
);
This returns for example:
[id] => 358313274248558 [post_id] => 100001736648729_358281023575116
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'message' => $_POST['msg'],
'object_attachment' => $ret_obj['id']
)
);
I have tried for the 'object_attachment' 358313274238558, 100001796648729_358281027575116 and 358281027575116. But facebook tells me that those are not correct.
So how on earth can we add a photo to a wall, which we just put in an album, and which we want to show in a large format (not as a little thumbnail).
If there is another way, without using albums, that is fine with me.
Please help. I know there have been a few questions already about photo uploads to facebook here on stackoverflow, I think I have read them all about 10 times already. It seems there is no answer yet. Somebody said we could post to /me/links but facebook doesn't seem to be able to handle links like http(s)://www.facebook.com/photo.php?fbid=358309510905631 anymore.
I have changed the ids in this post so they are not linked to actual stuff, they are here as examples.
Thanks
edit:
Ok, it seems a post of an image to an album is also a post of a big image to the wall IF the user allows the app to do public stuff. Because I was developing, I told the app to not do public stuff and only show stuff to me personally.
So there is no need to do 2 requests, just adding a photo to the album is enough to have it appear big on the users wall IF the user allows app activity to be public.
It is still somewhat confusing that a second request seems unable to also add the foto in a large size to the wall.

Graph API: Can I make multi-calls at a same time?

In fact, I want to get the cover photo for each user's albums.
So, first I get the albums data:
$albums = $GLOBALS["facebook"]->api("/me/albums",'GET');
Then I retrieve the cover_photo id and ask API to get details about this photo (such as the source)
foreach($albums as $album) {
$data = $GLOBALS["facebook"]->api("/". $album["cover_photo"], 'GET');
}
But this make a lot of calls to the API (one per album) and it's seems that she doesn't like.. Because my application return a timeout error.
Is there another way to do what I want?
Thanks.
You can always use the Batch API, or just use FQL. Something like the below would retrieve the src of all the album covers of the current user:
SELECT src
FROM photo
WHERE pid IN (
SELECT cover_pid
FROM album
WHERE owner = me()
)
You can try it here. Obviously you can choose any field to retrieve from the photo table.