Getting Facebooks' Cover Photo via PHP SDK & Graph API - facebook

I'd like to know if there is a simple way of retrieving the Cover photo from a user in my application, via the Facebook php sdk.
I managed to retrieve the cover photo id of the album of the cover photo album, but my solution only works partially. (As you can see, it's not efficient, and If more albums will be added, and moved to other pages, thus this will not work).
$albums = $facebook->api('/me/albums','GET');
for($i = 0;$i<count($albums['data']);$i++){
for($j = 0;$j<count($albums['data'][$i]);$j++){
if($albums['data'][$i]['name'] == "Cover Photos"){
echo $facebook->api('/me/albums/'.$albums['data'][$i]['cover_photo'],'GET');
}
}
}

Facebook seems to have added the Cover field to User Object recently
https://graph.facebook.com/facebookuserid?fields=cover will give you the user cover pic Details
Facebook Doc Link : http://developers.facebook.com/docs/reference/api/user/

I think the easiest is to use the graph api:
http://graph.facebook.com/{user_id or page_id}?fields=cover
and parse the returned JSON.
{
"cover": {
"id": "XXX",
"source": "https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-ash4/311205_989690200741_1231438675_n.jpg",
"offset_y": 66
},
"id": "XXXXXX"
}

Facebook has a really poor and outdated documentation...
At the moment there isn't a proper way to do this via Graph API, but with FQL it is possible.
SELECT pic_cover FROM user WHERE uid='yourUserId'
The field pic_cover isn't documented but available.
The response should look like this:
[
{
"pic_cover": {
"cover_id": someId,
"source": "someUrl",
"offset_y": someOffset
}
}
]

The latest versions of Graph API (2.4 is current at the time of writing) support 'picture' field that returns user's profile picture. It's worth checking.
/<user-id>?fields=id,name,picture

I think it is better to ask type of album then name.
$albums = $facebook->api("/me/albums");
$album_id = "";
foreach($albums["data"] as $item){
//echo $item["id"]." - ".$item["name"]." - ".$item["type"]." - ".$item["cover_photo"]."<br/>";
if($item["type"] == "profile"){
$album_id = $item["id"];
$profile_picture_id = $item["cover_photo"];
break;
}
}

Looks like at this stage, pending updated documentation from facebook, that your method is the only "sure fire" way to retrieve the cover of a users timeline.
If you find this method to be slow or inefficient - maybe you could try running it as a cron job and having a minimal update delay.. eg. run the cron twice a day (maybe even more), maybe handle two or three users at a time and have the cron running every 2 minutes...
Not a solution per-say; more of a suggestion.

I use: http://graph.facebook.com/{user_id or page_id}?fields=cover
Return on browser:
{
"cover": {
"id": "XXX",
"source": "https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-ash4/311205_989690200741_1231438675_n.jpg",
"offset_y": 66
},
"id": "XXXXXX"
}
How can I get field 'source' to a php varible?
Sr, I can't reply so i post here. :(

it tries to automatically recover from the image through php
$json = file_get_contents("https://graph.facebook.com/PROFILE_ID?fields=cover");
$obj = json_decode($json);
echo $obj->cover ->source;

I use username instead of id and it works:
http://graph.facebook.com/{username}?fields=cover
Parse the JSON accordingly.

I have used https://graph.facebook.com/facebookuserid?fields=cover link but it did not work. When I search Facebook SDK documentation, I see the answer that works.
I hope this will be helpful for you.
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"/%#?fields=cover", [user objectForKey:#"id"]]
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
NSLog(#"%#",[[result objectForKey:#"cover"]objectForKey:#"source"]);
/* handle the result */
}];
Result is a type of a Dictionary. You can see the link of user's cover photo under "cover" tag and its "source" tag also.

This is how I extracted my cover pic using Jackson and the Graph API.
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode actualObj = mapper.readTree(String.valueOf(object));
JsonNode cover = actualObj.get("cover");
Map<String,String> myMap = mapper.readValue(cover.toString(), HashMap.class);
Log.e("Cover link", myMap.get("source"));
coverpic = myMap.get("source");
} catch (IOException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "cover");
request.setParameters(parameters);
request.executeAsync();

function getCover() {
FB.api('/me?fields=cover', function(response) {
document.getElementById('cover').innerHTML =
"<img src='" + response.cover['source'] + "' alt='' />"
});
}

Related

How to get the post of the user using javascript sdk

I am creating my first facebook app using javascript sdk. In that i can able to post to the user's wall using(FB.api('me/feed', 'post', )).
Now what I need is, when the user accessing my app, it has to show (or list) the post of that user. The code is
FB.api('/me/posts', function(response) {
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
alert('The value of post is:'+post);
if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
But it is not working. If I remove l=response.length and change the condition as i<5 it is going inside the loop but it gives the value of post is undefined.
I didn't get why it is returning as undefined. It returns same for post.message also.
I am getting the access_token of the user also.
If I want to get the post of my user what code i have to use. Can anyone help me in this.
Thanks in advance
You can use the Facebook Graph API Explorer to better understand what data you will be receiving. https://developers.facebook.com/tools/explorer/
You should have l=response.data.length and var post = response.data[i];. Also, some posts will not have a "message", but will have a "story" instead (mainly posts like "Joe Smith and Tom Someone are now friends."). Make sure you also have the appropriate permissions (e.g. user_status) for the information you're trying to receive.

Facebook profile picture doesnt show up, it shows an icon of a question mark

Do you have any idea? I am developing an app using Unity IDE and C#. Also, I'm using the social networking prime31 for my plugin with Facebook. I was able to get all the graphs and display it in my screen app, but since last week it didn't show the profile picture and my friend's picture, it just shows a plain question mark. Do you have any idea with regard to that?
But I was able to show the username and my friend's username. My app token is working, and I am using JSON data to get the data from the Facebook URL.
void Start()
{
getFB_ID();
}
void getFB_ID()
{
Facebook.instance.graphRequest( "me/", HTTPVerb.GET, ( error, obj ) =>
{
var ht = obj as Hashtable;
userId = ht["id"].ToString();
Debug.Log( "USER ID: " + userId);
string url = "http://graph.facebook.com/"+userId+"?fields=id,name,picture";
StartCoroutine(getURL(url));
});
}
IEnumerator getURL(string url)
{
WWW www = new WWW(url);
yield return www;
Debug.Log ("Heres the URL you are accessing: " + url);
ProfilePicDisplay(www.text);
public void ProfilePicDisplay(string jsonString)
{
JsonData jsonProfilePic = JsonMapper.ToObject(jsonString);
ConverterScript fbprofilepic;
MyPicture = new ArrayList();
{
fbprofilepic = new ConverterScript();
fbprofilepic.name = jsonProfilePic["name"].ToString();
fbprofilepic.picture = jsonProfilePic["picture"].ToString();
LoadProfilePic(fbprofilepic);
MyPicture.Add(fbprofilepic.name);
}
}
private void LoadProfilePic(ConverterScript profile)
{
string ProfilePic = "userAvatar";
GameObject profile_pic_holder = GameObject.Find(ProfilePic);
profile_pic_holder.SendMessage("LoadImage", profile);
}
was able to get the data in my logs, but the problem is it didnt load the image, it says:
You are trying to load data from a www stream which had the following error when downloading.
Could not resolve host: JsonData object (Domain name not found)
As of last week, October 3rd and detailed here: https://developers.facebook.com/blog/post/2012/10/03/platform-updates--operation-developer-love/
The picture endpoint no longer returns the picture URL in the string. It returns a dictionary and you have to change your parsing to get to it. So the data returned will look more like this:
{
"id": "1234567",
"name": "Your Name",
"picture": {
"data": {
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn1/your_picture.jpg",
"is_silhouette": false
}
}
}
In the latest LeanLoader, there is an automatic fix for the newly implimented Facebook endpoint abernathy mentioned, which allows you to load the image directly (with all the parsing of the json and other data handled by the engine). You can easily load profile images like this:
function Start () {
LeanLoader.load("https://graph.facebook.com/DentedPixel/picture?type=large&redirect=false", LLOptions().setOnLoad(onImageLoaded));
}
private function onImageLoaded( tex:Texture2D ){
Debug.Log("Your image texture ready to use! :"+tex);
}
There is also many other features that I think people will find helpful with LeanLoader (including caching of images/text/sound and a built-in JSON parser).
try this- fb sdk version-9.1.0
FB.API ("/me/picture?type=large", HttpMethod.GET, DisplayProfilePic);// API call
void DisplayProfilePic(IGraphResult result)
{
Image profilePic;
if (result.Texture != null)
{
profilePic = image1; // diplaying image
profilePic.sprite = Sprite.Create(result.Texture, new Rect(0, 0, result.Texture.width, result.Texture.height), new Vector2());
}
}

Can't send a link to my own wall

I am developing a multi protocol client (currently Twitter, Facebook and Google Reader) for Windows using C# and wanted to extend its functions to send links to Facebook (currently I "only" have text status messages, comments and likes).
So I wrote this quite small method here:
public void PostLink(string text, string url)
{
if (string.IsNullOrEmpty(url))
{
PostTextStatus(text);
return;
}
dynamic parameters = new ExpandoObject();
parameters.message = text;
parameters.link = System.Web.HttpUtility.UrlEncode(url);
dynamic result = facebookClient.Post("me/links", parameters);
UpdateNewsFeed();
}
But I get the following error message back from Facebook: "(OAuthException) (#1500) The url you supplied is invalid"
But at least as I read the API docs this should be the right url and I tried it also with my user ID instead of "me" and without the UrlEncode - no luck so far.
Any help appreciated :)
(Using latest stable version für Facebook C# SDK)
The used client is initiated by
facebookClient = new FacebookClient(AccessToken);
dynamic result = (IDictionary<string, object>)facebookClient.Get("me");
if (result != null)
{
LoginSuccessfull = true;
}
}
and the AccesToken and its permissions were retrieved using
IDictionary<string, object> loginParameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "appId", appId},
{ "secret", appSecret }
};
Uri redirectUri = new Uri("http://www.li-ghun.de/Nymphicus/");
loginUri = FacebookOAuthClient.GetLoginUrl(appId, null, _extendedPermissions, loginParameters);
with I think quite more than enough permissons:
private string[] _extendedPermissions = new[] {
"user_activities",
"user_birthday",
"user_checkins",
"user_education_history",
"user_events",
"user_games_activity",
"user_groups",
"user_hometown",
"user_interests",
"user_likes",
"user_location",
"user_notes",
"user_online_presence",
"user_photo_video_tags",
"user_photos",
"user_questions",
"user_relationship_details",
"user_relationships",
"user_religion_politics",
"user_status",
"user_subscriptions",
"user_videos",
"user_website",
"user_work_history",
"friends_about_me",
"friends_activities",
"friends_birthday",
"friends_checkins",
"friends_education_history",
"friends_events",
"friends_games_activity",
"friends_groups",
"friends_hometown",
"friends_interests",
"friends_likes",
"friends_location",
"friends_notes",
"friends_online_presence",
"friends_photo_video_tags",
"friends_photos",
"friends_questions",
"friends_relationship_details",
"friends_relationships",
"friends_religion_politics",
"friends_status",
"friends_subscriptions",
"friends_videos",
"friends_website",
"friends_work_history",
"create_event",
"create_note",
"email",
"export_stream",
"manage_friendlists",
"manage_notifications",
"manage_pages",
"offline_access",
"photo_upload",
"publish_actions",
"publish_checkins",
"publish_stream",
"read_friendlists",
"read_insights",
"read_mailbox",
"read_requests",
"read_stream",
"rsvp_event",
"share_item",
"status_update",
"video_upload",
};
Problem has been all the time at myself being stupid - I accidently exchanged the parameters when calling my method so the text of the entry was in the link property and vica versa.
Stupid me :(
I think your issue lies in the URL being posted as the link. Be sure that URL is visible to the linter (https://developers.facebook.com/tools/lint).
Another thing is to try playing with the Graph API Explorer tool and see if you can use it to post a link. If so, then try changing the application drop down to the app you're having issues with and try posting the link again.
In my case i was posting "http://localhost:3000" and facebook reject it. I tried with "www.google.com" and it works
The error I was getting was, even though the URL itself was valid, the og:image was being set to //example.com/example.jpg and missing http: or https:. I blame Facebook for this one, for not accepting a valid URL that any browser will accept, but the Debugger definitely helped identify this and solved the issue.
https://developers.facebook.com/tools/lint

How to post image on facebook fan page using C# facebook sdk on codeplex

Currently I'm working on my HTML 5 ASP.Net Application,
Which has requirement of Graffiti Wall, When user draw something on my Wall(means on my HTML 5 Canvas element), and Press Share Button on my Page, at that time the whole picture should need to be post on one of the Facebook Page.
Now my question is that is this thing possible using C# facebook sdk by codeplex ?
if its possible, than how to post image on facebook fan page using this SDK??
Where can I get the good resource the implement this kind of functionality or similar code.
I've check the all examples given by them, there is no any example which post on the facebook fan page.
Or even other library that can implement this kind of functionality.
I've check this library, and see that it has FacebookClient,ExpandoObject, FacebookMediaObject kind of classes, but how to and where to use this classes,where are the description and sample code.
Thanks,
Jigar Shah
you can post to others wall using "{id}/feed"
if you want to post image/video on wall. Try downloading the samples from nuget.
Install-Package Facebook.Sample
Here is how to do using the graph api.
public static string UploadPictureToWall(string id, string accessToken, string filePath)
{
var mediaObject = new FacebookMediaObject
{
FileName = System.IO.Path.GetFileName(filePath),
ContentType = "image/jpeg"
};
mediaObject.SetValue(System.IO.File.ReadAllBytes(filePath));
try
{
var fb = new FacebookClient(accessToken);
var result = (IDictionary<string, object>)fb.Post(id + "/photos", new Dictionary<string, object>
{
{ "source", mediaObject },
{ "message","photo" }
});
var postId = (string)result["id"];
Console.WriteLine("Post Id: {0}", postId);
// Note: This json result is not the orginal json string as returned by Facebook.
Console.WriteLine("Json: {0}", result.ToString());
return postId;
}
catch (FacebookApiException ex)
{
// Note: make sure to handle this exception.
throw;
}
}

Retrieve Facebook Post Comments Using Graph API

I tried to get Facebook comments using:
http://graph.facebook.com/[post_id]/comments
It results only 2 of 15 comments, and without count info.
{
"data": [
{
"id": "[post_id]",
"from": {
"name": "[name]",
"id": "[id]"
},
"message": "[message]",
"created_time": "2011-01-23T02:36:23+0000"
},
{
"id": "[id]",
"from": {
"name": "[name]",
"id": "[id]"
},
"message": "[message]",
"created_time": "2011-01-23T05:16:56+0000"
}
]
}
Anyone know why only 2 comments?
Also, I want to retrieve comments (default number) or retrieve comments with my limit number, and get its comments count. Any idea? (Please use Graph API).
You need to call it from a secure request https and provide an access_token:
https://graph.facebook.com/19292868552_118464504835613/comments?access_token=XXX
EDIT:
Added the object from the post document. try clicking the comments connection and then remove the access_token and try and see the difference.
In order to get the Like count and the comment count then you need to use a combination of the PostOwnerID and PostID not just the PostID
So for your example it would be:
https://graph.facebook.com/153125724720582_184234384932460/comments
Again, as mentioned in some of the other answers you need to use the https method along with an auth_token
I experienced the same problem with comments. The issue was that I was using an access token for a test user. Because test users don't have access to other FB users information, only the comments from pages were shown.
There is a word JUGAAR in Urdu that means, finding a way out, just to get the job done. So for like purpose I made this JUGAAR, I hope it helps.
$contents = file_get_contents("http://graph.facebook.com/" . $_GET['id'] . "/likes");
if (substr_count($contents, 'name')>0) {
echo substr_count($contents, 'name') . " people like this album";
}
By the way I am also new to this Fb stuff, I am looking for help to post comments. When I try to use graph.api./id/comments?access_token=sdfsfsdf&message="D" it still returns comments for the id instead of posting.
As a sanity check, do you have "read_stream" permission? I can see the full comments with my access token that uses "read_stream". As mentioned by other people, you have to use https and access token as well...
Try to authenticate via App Login (http://developers.facebook.com/docs/authentication) and then to call GraphAPI with access_token prarameter.
You can do something like this to avoid the whole count of comments issues:
Get the object's (a post is considered an object in the Graph API) ID-as I understand from your question, you already have it?
Create a Comments Social Plugin with this ID, and get the code for it.
Embed the code in your site.
This will result in all the comments for this object.
To get the count of comments per object, you can execute an fql query, something like this:
SELECT comments FROM stream WHERE post_id = [yourpostid]
This will return in the comments array under the count parameter the number of counts for this object.
SELECT comments FROM stream WHERE post_id = [yourpostid] shall not work in this case ..
the id which is returned after making a graph call successfully to post on a user's wall (using access_token of an application ) is of the form abcdef_qwerty ( underscore seperated id )
where as the post id which is mapped in the post_id of the comments table is of the form "lmnop" ..
to get the counts of like and comments on this post id of form "abcdef_qwerty" making a graph call withh app generated access token seems to be the only solution ..
something like:
https://graph.facebook.com/100002619172565_117323155031656?access_token=xxxxxxxxxxxxx
After Successfully Login call this method facebookComments()
parameters.putString("fields", "message"); .............// Its Important
AccessToken accessToken = AccessToken.getCurrentAccessToken();
public void facebookComments() {
try {
getFriends(accessToken, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("keshav", "one" + response);
CommonMethod.showAlert("res --> " + response, MainActivity.this);
}
}
);
} catch (Exception e) {
CommonMethod.showAlert("Exception is -> " + e, MainActivity.this);
}
}
public void getFriends(AccessToken token, GraphRequest.Callback callback)
{
// TODO Comments Working but id return only
GraphRequest requestt = new GraphRequest(token, "744511125731315_751199848395776/comments",
null, HttpMethod.GET, callback);
Bundle parameters = new Bundle();
parameters.putString("fields", "id"); // todo in use imp
parameters.putString("fields", "name"); // todo in use imp
parameters.putString("fields", "from"); // todo in use imp
parameters.putString("fields", "message"); // todo in use imp
requestt.setParameters(parameters);
requestt.executeAsync();
}
It results only 2 of 15 comments
Add a limit parameter to the URL:
http://graph.facebook.com/[post_id]/comments?limit=1000&access_token=XXX
This should show all the comments.