I'm trying to issue a Facebook Graphp API search call for groups with a specific search term. The important fact is to search for groups not only beginning with the term but also to search for the term within the group name. So something like that.
FQL => SELECT * FROM groups WHERE groupname LIKE '%term%'
As far as i know this isn't possible in FQL. Therefore I have to use the Graph API search.
http://developers.facebook.com/docs/api#search
But I have to issue th call even if the user isn't logged in. Is this possible
or is there a possibility to log in a default user with some curl calls without user interaction (without displaying a form)?
If there is a simplier solution (for instance with FQL) please tell me.
I work with the graph API and not with the FQL so I'm not 100% sure on the differences etc etc... however a way I'd try is using the cURL script at http://developers.facebook.com/docs/authentication/#authenticating-users-in-a-web-application to get an auth token, then you must add the received auth token to the graph parameters as you can see on the site (a good way to test in the graph api is to click on the example likes or queries given while logged into facebook then copying the api code and breaking up the process like that [testing that you can get results you want from the query, testing that you can get your auth token then combining] so that you know what parts are 'problem' parts).
If that fails, scroll down to the "single sign-on with java-script" and have a look at the code they use to get the auth token from the facebook cookie, I notced you may be able to access that cookie from FQL.
I hope this was of some help! Please tell me if those ideas didn't work.
Jon
Using PHP-SDK 3.1.1, no auth or access_token needed. This sample assumes you have PHP-SDK installed on the page.
Use a form post the question to the page, arguments for get and post
are included. This will return the array from search https://graph.facebook.com/search?q=facebook&type=group
<?php
$q = urlencode($_GET['qs']);
if(!$_GET['qs']){
$q = urlencode($_POST['qs']);
if(!$_POST['qs']){
$q = "facebook";
}
}
$MEsearch = $facebook->api('/search?q='.$q.'&type=group');
foreach ($MEsearch as $key=>$value) {
$i=1;
foreach ($value as $fkey=>$fvalue) {
$i++;
if($fvalue[id]=="h"){
}else{
$groupname = $fvalue[name];
$groupid = $fvalue[id];
$groupversion = $fvalue[version];
echo $groupname. '<br />';
echo $groupid. '<br />';
echo $groupversion. '<br /><hr />';
}
};
};
?>
Sample Usage http://shawnsspace.com/plugins/photofeed.php Click Get Plugin at the bottom and use the search box to see this sample in action.
Related
I've already got a database set up with a table that is successfully populated with the final (permanent?) OAuth User Token and OAuth User Secret. The thing I don't understand is how I'm supposed to know what the current user's ID is, especially when it's been 2 weeks since their last login. My app is authorized by all of its users, so theoretically Twitter can look at the list of authorized apps for the current user and share the Twitter User ID, right? Isn't there some good way of requesting (on behalf of the current user) what his ID is? I feel like the temporary tokens should be able to facilitate this somehow... If it helps, every user in my app is just a Twitter account with some extra info. I'm just looking for the best way to utilize the tokens and secrets that are in my database...
I'm using PHP (libraries: Codebird-PHP & tmhOAuth) so if you could show an example in PHP that'd be nice, but really I just want to know how I'm supposed to use this information that I'm storing.
Thanks!
I'm assuming you store the data together with some username or user id that identifies the users of your website and links them to their proper twitter id. In order to get the basic info of your user, after authorization, you have to use the endpoint https://api.twitter.com/1.1/account/verify_credentials.json with a GET.
The documentation for the 1.1 API can be found here.
This returns an array. You find the username uder "screen_name" and the user id under "id" or "id_string".
The question is a possible duplicate of Get current user's info from Twitter API, but I've added an answer because that discussion points to the deprecated API. The code you find there, nevertheless, is still useful (it appears to use Abraham William's library, but the steps are basically the same). Replace the classes and functions with those you have in Matt Harris' library. I don't know codebird, sorry!
EDIT: I am also providing a code sample (tested and working, although I have issues with tmhOAuth, so I use it occasionally only for myself. I have noticed that, when I try to post, it sometimes returns some weird error codes and I can't figure out why):
// Authentication page, with button. You have already connected to your database
$mywebsiteuser = $_SESSION['website_user_id'];
$query= "SELECT * FROM `table_where_you_store_twitter` WHERE website_user_id ='$mywebsiteuser'";
$sql= $mysqli->query($query) or die($mysqli->error.__LINE__); // or whatever else to check is the query fails.
if ($sql->num_rows != 0){
//etc. retrieve data and set the sessions.
// already got some credentials stored?
if ( isset($_SESSION['access_token']) ) {
$tmhOAuth->config['user_token'] = $_SESSION['access_token']['oauth_token'];
$tmhOAuth->config['user_secret'] = $_SESSION['access_token']['oauth_token_secret'];
$code = $tmhOAuth->request('GET', $tmhOAuth->url('1/account/verify_credentials'));
if ($code == 200) {
$resp = json_decode($tmhOAuth->response['response']);
echo $resp->screen_name;
echo $resp->id;
//Etc. Instead of printing them you it's a good idea to store them in the db.
} else {
outputError($tmhOAuth);
}
// we're being called back by Twitter
} elseif (isset($_REQUEST['oauth_verifier'])) {
$tmhOAuth->config['user_token'] = $_SESSION['oauth']['oauth_token'];
$tmhOAuth->config['user_secret'] = $_SESSION['oauth']['oauth_token_secret'];
$code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/access_token', ''), array(
'oauth_verifier' => $_REQUEST['oauth_verifier']
));
if ($code == 200) {
//etc.
Anyhow, all in all, in order to get the info of a user you need them to authorize your app first. I check if I have something from my user with the user's session variables on my website, not through twitter. If I have nothing stored, I ask them to authorize the app. I hope this helps.
Access Token : 1274865264-QiVY50RGnmJz6AU9IPRxxiXfv4DYqo0nj6wg8hS
Access Token Secret : fZQnHSuSpwARicIdLqkqQLy1JeG9LxrbNIRKypWcGR
First part of Access Token is user id
I'm trying to get the data of my users venues (the details about the venues from the users checkins information).
I'm using the user access token to get the data. This is the code I'm using:
if($_GET['code']){
$authkey = file_get_contents("https://foursquare.com/oauth2/access_token? client_id=".$client_id."&client_secret=".$secret."&grant_type=authorization_code&redirect_uri=".$redirect."&code=".$_GET['code']);
$decoded_auth = json_decode($authkey,true);
$venueinfo = file_get_contents("https://api.foursquare.com/v2/users/self/checkins?oauth_token=$access_token&v=$version");
$decoded_venueinfo = json_decode($venueinfo, true);
foreach ($decoded_venueinfo->response->checkins->items->venue as $result){
echo $result->name;
echo $result->id;
echo $result->location->address;
echo $result->location->city;
echo $result->location->country;
}
}
I get a blank page. I've tried to add "else" to the end of the first "if" with echo "error", and I got it displayed, so I guess my "if" statement condition is false.
I'm fairly new to PHP and I learn as I go. Any help will be deeply appreciated.
The _GET['code'] refers to the "&code=" GET parameter in the URL of the request. This parameter will be present in requests that foursquare makes to your app to authenticate users. It sounds like you are manually making requests in order to test your app, in which case you will need to supply the code parameter in the URL.
I would like show the "select friends" dialog before publish to a friend wall, like that:
I am not sure if it is possible with the PHP SDK, I didn't find anything about it on the Fb documentation.
Could I also use a kind of Facebook URL, such as :
$link=https://www.facebook.com/dialog/feed?app_id=<your appid>&redirect_uri=<your redirecting link>&link=<link u are posting>&message=<message>.&picture=<picture URL you want to show>&caption=<title>&description=<description>&name=<title>
(this on is use to post to our own wall)
UPDATE:
After I have selected the selected friends uids, I want add them to the Graph API link and then publish to their wall.
if (isset($_GET['request_ids'])) {
$i = 0;
$n = count(request_ids);
while($n!=$i){
$link = ($link + "&to=" + $request_ids[$i]);
$i = $i +1;
}
echo "<script language=javascript>parent.location=''</script>";
}
Is something wrong with my php code?
Any help would be appreciated. Thank you.
Here it is the doc:
https://developers.facebook.com/docs/reference/dialogs/
https://developers.facebook.com/docs/reference/dialogs/requests/
You can either do that by using the JavaScript SDK, or the Graph API.
To use the graph api, you can build an URL like this:
https://www.facebook.com/dialog/apprequests
?app_id=<your-app-id>
&redirect_uri=http://www.example.com/response/
&message=Your%20message%20here
&display=popup
By specifying different values for "display", you can choose how to display the selector. Can be page, popup, iframe, touch, or wap.
When the user clicks the "send request" button, gets redirected to "redirect_uri" with shome get appended (I wasn't able to find the exact name for the get parameter, but it would be easy to find out).
UPDATE:
After the user clicks on "Send request", he gets redirected to:
<redirect_uri>?request_ids[0]=XXXX&request_ids[1]=YYYY&request_ids[2]=ZZZZ#_=_
So, in PHP, you'll find a list of ids of selected friends in $_GET['request_ids']. You can use that list to publish something on friends wall, by using the Graph API.
Side note: must have the same domain you specified as your site URL in the app configuration page.
UPDATE:
An improvement to your PHP code:
if (isset($_GET['request_ids'])) {
for ($i=0; $i<count(request_ids); $i++){
$link = ($link + "&to=" + $request_ids[$i]);
}
echo "<script language=javascript>parent.location=''</script>";
}
Then, what's inside $link?
To publish on one's wall, you should use the appropriate Graph API request, directly from the script you specified in redirect_uri.
I have been implementing a Google/Facebook authentication system on my site. I use their respective service to authenticate the user, then use the results to instantiate sessions on my end. The Google one is running no problem, but for the Facebook one I have hit a snag.
I can authenticate users with no problem, but when trying to authenticate a company or other Facebook page type, it fails.
For instance, using the GraphAPI, I am able to retrieve the values shown in one of their examples https://graph.facebook.com/btaylor and store it properly.
But when I try to use the same system to authenticate a company ( https://graph.facebook.com/nike for instance), it fails since the objects are not part of the user results returned by the GraphAPI.
Normal stuff setting up the call:
$FBcookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);
$user = json_decode(file_get_contents_curl('https://graph.facebook.com/me?access_token='.$FBcookie['access_token']));
And when storing results, it works fine as a user:
$_Fname =$user->first_name;
$_Lname =$user->last_name;
But trying to access the expected attributes seen at the Nike example above, nothing gets returned.
I even tried echoing out the object to see whats there:
print('<pre>');
print_r($user);
print('</pre>');
For the user, I see everything, for non-user (company, event or other page type), I see nothing.
Question is, has anyone seen what other objects we may need to query via the GraphAPI? The Facebook developer pages are all over the place and have no real concise tutorials on this.
Any help would be much appreciated ;)
Company/Page info on facebook is as follows:
$user->id;
$user->name;
$user->picture;
$user->link;
$user->likes;
$user->category;
$user->website;
$user->username;
$user->description;
$user->public_transit;
So $user->first_name; and $user->last_name; don't exist.
You could try something like this :
if(empty($user->first_name)&&empty($user->last_name)){
//probably company set $user->username;
}
I'm looking for a good, simple PHP function to get my latest Facebook status updates. Anyone know of one?
Thanks!
EDIT: I've added a half-solution below.
Or if anyone knows a good way to read in the RSS feed and spit out the recent status update?
A quick check on PEAR found Services_Facebook
This is an incomplete answer, but this is what I've gotten so far:
First: add the developer application on FB. Then create a new application. Call it whatever you want.
Second: Download the PHP client. Dump it somewhere on your webhost, i.e. /facebook/
Third: Copy the following beginner code to get yourself started into a php file:
<?php
require_once('facebook/php/facebook.php');
$facebook = new Facebook("YOUR_API_KEY","YOUR_SECRET_KEY");
$result = $facebook->api_client->fql_query("SELECT status FROM user WHERE uid = YOURIDNUMBER");
// OR --- they both get the same data
$result = $facebook->api_client->users_getInfo(YOURIDNUMBER,'status');
print_r($result);
echo "<pre>Debug:" . print_r($facebook,true) . "</pre>"; // debug info
?>
Other info:
You must be logged in and have the
application added. OR you give the
application offline_access
permissions and have the
aapplication added.
You can add offline_access by typing
in the following url:
http://www.facebook.com/authorize.php?api_key=YOUR_API_KEY&v=1.0&ext_perm=offline_access
more info on permissions found here: http://wiki.developers.facebook.com/index.php/Extended_permissions
I'm at a stopping point: anything my
program calls the fql query or
users_getInfo, my page stops
executing the php? I'm guessing
there are a limited amount of calls
for new applications? I've never
done any FB development so I'm
completely new to it. Maybe make
the call and save your recent status
(or most recent statuses) in your
own DB to prevent excessive calls to
the API?
I hope this helps someone get started!
EDIT: It seems that FB won't let you access someones status, even if the offline_access is on, unless you are that person or their friend (depending on their privacy settings).
I did however, finally manage to find the RSS feed in the new profile version: http://www.new.facebook.com/minifeed.php?filter=11
I have found a way to fetch your latest facebook status. This is how you do it:
1) Create a facebook app, and copy your application secret and application id.
2) Grant the app read_stream and offline_access to your profile. (http://developers.facebook.com/docs/authentication/permissions) To fetch your latest status the app needs an access_token. With offline_access granted the access_token should "never" expire. The easiest way to do this is to click the button generated by this code: (be sure to fill in 'your app id' and set cookie to true!)
<fb:login-button perms="read_stream,offline_access"></fb:login-button>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});</script>
3) Now try to find out what access_token it is using. The access_token is saved in the fbs_appId cookie. Locate it using your browser or using $_COOKIE['fbs_appId']. Look for access_token=....
4) Now that you have a (hopefully) never expiring access_token you can use the following code:
$access_token='xxxxxxxxxxxxxxxxxxxx';
$appId='123456789132456789';
$appSecret='xxxxxxxxxxxxxxxxxxxx';
$profileId='123456789';
//http://github.com/facebook/php-sdk/blob/master/src/facebook.php
require 'facebook.php';
$facebook = new Facebook(array('appId' => $appId,'secret' => $appSecret));
$response = $facebook->api('/'.$profileId.'/feed?limit=1&access_token='.$access_token);
5) The message part should be located: $response['data'][0]['message']
I don't know HOW long the access token is valid. Facebook says:
Enables your application to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.
Here is a REALLY simple function if you just want to get the latest status. It doesn't depend on the Facebook SDK or anything. You just need CURL and JSON support.
Simple PHP function to get facebook status
I never seem to get along with PEAR, but if you have better luck than I, then the PEAR solution seems the best route long term.
Another idea is to explore the Facebook Developer API library and see if that might give you anything you are looking for.
Lastly, there used to be a way to get an RSS feed... but I can't seem to find any instructions that work anymore, but you might poke around Facebook help if that interests you. Mine ends up looking something like this:
http://www.new.facebook.com/feeds/status.php?id=[idnumber]&viewer=[viewer]&key=[key]&format=rss20
I got it working using Jens' post to retrieve a valid access_token. Then, I extracted the status messages and the time of posting from the xml file using the following code (you can change $limit to display more or less status messages, or use a form to change it).
Be sure to put in your Facebook ID and the access token you got from the app you created (see Jens' post). You can check the output of this script here.
Have fun!
<?php
if(isset($_POST['limit'])) {
$limit = $_POST['limit'];
}
else {
$limit = 3; // number of status messages to display
}
$f = fopen ("https://api.facebook.com/method/status.get?uid=YOUR_FACEBOOK_ID&limit=".$limit."&access_token=YOUR_ACCESS_TOKEN", "r");
while ($line= htmlentities(fgets($f))) {
if ($line===FALSE) print ("FALSE\n");
else
{
$content = $content." ".$line;
}
}
fclose ($f);
$message = explode("<message>", $content); // search for the <message> tag
$message_cnt = count($message);
$msg_index = 0;
$time = explode("<time>", $content); // search for the <time> tag
for($i=1; $i<$message_cnt; $i++)
{
$tmp = explode("</message>", $message[$i]);
$msg[$msg_index] = $tmp[0]; // status message
$tmp2 = explode("</time>", $time[$i]);
$t[$msg_index++] = $tmp2[0]; // time of posting
}
for($i=0; $i<$msg_index; $i++)
{
echo("<span class=\"status\">".preg_replace('!\015\012|\015|\012!','<br>',$msg[$i])."</span><br>\n
<span class=\"date\">on ".date("d.m.Y", $t[$i])." at ".date("H:i",$t[$i])."</span><br><br>\n");
}
?>
I have tried loads of tutorials over the last few days and none of them have worked. I think it may be due to facebook changing their api requirements. This is the only one I found that works at the moment:
http://www.deanblog.co.uk/article/13/adding-a-facebook-status-feed-to-your-website-with-php
Just use PHPforFB framework (www.phpforfb.com/en/) for the fastest way.
The code looks like this:
require_once('phpforfb_framework.php');
$structInit = array('app_id' => APP_ID,'app_name' => APP_NAME,'sec_key' => APP_SECKEY);
$FacebookAPP = new PHPforFB($structInit);
if($FacebookAPP->lastErrorCode>0){
//Creation failed => Display error message and exit
echo "PHPforFB Error: ".$FacebookAPP->lastErrorCode." -> ".$FacebookAPP->lastError;
}else{
//PHPforFB framework established
if($FacebookAPP->userLoggedIn === TRUE){
//If the user is logged in at Facebook:
//Here you can determine if the user has at least once before
//granted basic permissions to your application.
if($FacebookAPP->userAuthenticated === FALSE){
//The user has not yet granted permissions
//**your code here**
}else{
//The user has already granted permissions, therefore his Facebook ID
//is known to us. It is always available in $FacebookAPP->userID:
$userID = $FacebookAPP->userID;
//**your code here**
}
}
}
Since I couldn't use the API route, I went with the RSS found at: http://www.new.facebook.com/minifeed.php?filter=11
And used the following PHP function, called StatusPress, with some of my own modifications, to parse the RSS feed for my Facebook status. Works great!
<?php
// see http://github.com/facebook/php-sdk/blob/master/facebook.php
require './facebook.php';
// Create our Application instance.
// see http://www.youtube.com/watch?v=jYqx-RtmkeU for how to get these numbers
$facebook = new Facebook(array('appId' => 'XXX','secret' => 'XXX'));
// This call will always work since we are fetching public data.
// this could be /username or /username/friends etc...
// see developer api for FQL for examples
$status = $facebook->api('/haanmc/feed?limit=1');
?>
<p><?php print $status['data'][0]['message']; ?></p>
<p>Likes: <?php print $status['data'][0]['likes']; ?> | Comments: <?php print count($status['data'][0]['comments']['data']); ?></p>
<textarea style="width: 95%; height: 600px;"><?php print_r($status); ?></textarea>