Facebook php api in Ajax facebox - javascript

I'm trying to load some php fql calls in to an ajax facebox (its like lightbox), i include a file with the following code in, but it does not work without the redirect ($my_url), is there any way to make the code ignore the redirect? Or do i need to use the javascript sdk from facebook?
$app_id = 'APP ID';
$app_secret = 'APP SECRET';
$my_url = 'LINK HERE';
$code = $_REQUEST["code"];
$bruger = "me()";
//auth user
if(empty($code)) {
$dialog_url = 'https://www.facebook.com/dialog/oauth?client_id='
. $app_id . '&redirect_uri=' . urlencode($my_url) ;
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;
// response is of the format "access_token=AAAC..."
$access_token = substr(file_get_contents($token_url), 13);

Have you tried using the Facebook PHP SDK? I highly recommend moving away from depreciated FQL as once you get to grips with the new API it is very easy to use
Once you have set up $facebook you can then just make API calls with $facebook->api('/query');
I'm not 100% sure what information you are trying to retrieve from your question however but I have put together a Lightbox / Facebook myself, even using tag data to pick people out of the picture so feel free to provide more detail and I will try to provide a more comprehensive answer
EDIT:
In order to build queries and test data returned you can use the Graph API Explorer and construct the query you want to test against your own Facebook Application
I'm trying to fetch friendlist
After you've setup $facebook then you can retrieve your friends by using
$fb_friends = $facebook->api("/me?fields=friends");
Next:
50 latest tagged photos and likes
To retrieve the latest 50 tagged photos and likes you'll need to do:
$fb_photos = $facebook->api("/me?fields=photos.limit(50)");
$fb_likes = $facebook->api("/me?fields=likes.limit(50)");
// I should mention that each time api() is called, the server makes a HTTPS request to Facebook, so it is worth condensing api queries to reduce load time:
$fb_data = $facebook->api("/me?fields=photos.limit(50),likes.limit(50)");
$fb_photos = $fb_data['photos'];
$fb_likes = $fb_data['likes'];
If you want the latest 50 of photos and likes chronologically sorted, you can array_merge() the two arrays and use a subval sort function for created_time, then just take the first 50.
I'm going to insert all the basic info into mysql (stuff like name, facebook id, email ect.) I'm going to use the fb id inserted into myslq, to view the friendlist, likes and photos
Right then, when you user logs on you will need to request extended permissions from them to access data like photos, likes and friends. When your user logs into facebook with the link you provide to them on your website, you need to call
$loginUrl = $facebook->getLoginUrl(array( 'scope' => 'read_stream,user_likes,user_photos,friends_photos,user_friends'));`
The scope is defined by the permissions stated here
Once you have been granted access to that information by the user you can retrieve profile information with $user = $facebook->api("/me"); and store the facebook ID, name etc in your database.
To get a better look at the data you'll be handing for photos then make sure that you click Get access token at the top of the page and grant permission to access photos and likes
Any more questions feel free to ask and I will provide more detail, hope that helps mate!

Related

get query parameters from google with referrer javascript

Is it possible to get the query parameters from google searches?
I.e. if someone googled bicycles the url becomes:
https://www.google.es/search?q=bicycles......
If you then come in the search results and someone clicks to your page you cannot see the query parameters with document.referrer it will only show
https://www.google.es/
Is there a way to know what a visitor searched before coming to your site?
Late response, but I have recently been doing some research and thought that this information may be interesting to other stackoverflow visitors who end up on this page.
Prior to 2016 you could get the url parameters using PHP from the referral data when visitors came to your site via organic search by using server variables:
function get_search_query(){
$query = $_SERVER['QUERY_STRING'];
return (strlen($query)? $query: 'none');
}
or
function get_search_query() {
$query = false;
$referrer = $_SERVER['HTTP_REFERER'];
if (!empty($referrer)) {
//Parse the referrer URL
$parts_url = parse_url($referrer);
// Check if a query string exists
$query = isset($parts_url['query']) ? $parts_url['query'] : '';
return (strlen($query)? $query: false);
}
return $query;
}
However, Google and other search engines have since made it impossible to view the query parameters from organic search and any script like that above returns a blank query string. This is true whether you are logged in to Google or not.
This is unfortunate because this removes valuable information like the the keywords used to find your site. The information still can be found in Google Search Console, but this provides Googles interpretation of what you should see and it is not as direct as getting the information immediately when a visitor hits a page after an organic search.
I am not aware of there being any way to still get organic query parameters.

Facebook PHP API How to get current user profile_id?

After login with FB JavaScript API, how can I get the profile_id of that user? ('/me'), please help...I used many hours on google and facebook official dev site still no luck on this. How come this kind of simple user profile id also didn't provide in API documentation...is me noob or facebook?.
sesssion_start();
require_once 'autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
use Facebook\FacebookJavaScriptLoginHelper;
FacebookSession::setDefaultApplication( 'APP_ID','APP_SECRET' );
$helper = new FacebookJavaScriptLoginHelper();
$session = new FacebookSession($_POST['access_token']);
$request = new FacebookRequest(
$session,
'GET',
'/me'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
$profile_id = $graphObject->getProperty('profile-id'); // HOW TO GET PROFILE ID??
P.S: I want profile id not user id...
I think You have to get user_id
A user represents a person on Facebook. The /{user-id} node returns a single user.
Here is the reference of Graph Api .. Check it in detail according to your requirement
https://developers.facebook.com/docs/graph-api/reference/user
For profile-id
check that link of Graph Api
Reference:
Profile /{profile-id}
A profile can be a:
User
Page
Group
Event
Application
The profile object is used within the Graph API to refer to the generic type that includes all of these other objects.
The individual reference docs for each profile type should be used instead.
Fields
When something has a profile, Graph API returns the fields for that object.
https://developers.facebook.com/docs/graph-api/reference/v2.5/profile/

How to get your website visitors to follow twitter accounts from your website

I am new on this forum, so accept my apologies if my question is inappropriate or is not clear enough.
I have a website where Twitter users are listed having follow button against each user, but when visitor click on 'follow' button then that user get followed from my Twitter account (which have app that is being used for authentication) instead of visitors account. so basically i want these accounts to be followed by visitors twitter account not mine.
when user clicks on follow button an ajax call is made to send username to page where following code runs to get that user followed.
<?php
ini_set('display_errors', 1);
require_once('lib/TwitterAPIExchange.php');
$uname=$_REQUEST['name'];
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "XXXXXX-XXXXXXXXXX",
'oauth_access_token_secret' => "XXXXXXXXXX",
'consumer_key' => "XXXXXXXXXX",
'consumer_secret' => "XXXXXXXXXX"
);
// Choose the url you want from the docs, this is the users/show
$url = 'https://api.twitter.com/1.1/friendships/create.json';
// The request method, according to the docs, is GET, not POST
$requestMethod = 'POST';
$varl=$uname;
// Set up your get string, we're using my screen name here
//$getfield = '?screen_name='.$varl;
$postfields = array(
'screen_name' => $varl
);
// Create the object
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
TwitterAPIExchange.php is php wrapper for twitter api request should i share that too ? Thanks in advance if anyone can help.
Don't do that from the server side. It's not necessary or appropriate.
Use Twitter web intents for this. They allow users of your site to perform a variety of actions using their logged-in Twitter account, including posting statuses, retweeting statuses, and following other Twitter users.

how to fetch the current user data in phpfox

Topic: Fetch current user(some particular fields) data from the DB and display it on the Welcome Screen.
Explaination of UI : On the Registration Page, A dropdown would appear. As the user selects an option, it would trigger an event to fetch user image to show on the welcome page.
I have put following code in (pages.process) module
function getUserId($iUserId)
{
$aRows = $this->database()->select('p.image_path')->from($this->_sTable, 'p')
->Join(Phpfox::getT('user') , 'u', ' p.page_id = u.college_name') ->
where('u.college_name = p.page_id AND u.user_id = ' .
(int)$iUserId)->execute('getRows');
return $aRows;
}
The data will selected from User & Pages Table, and will be used to show the user image. Please suggest.
There is a service to get user details by is
$user_id = Phpfox::getUserId();
$aRow = Phpfox::getService('user')->getUser($user_id);
This will give you user details
For performance, check if the page you are altering already has the information you need, maybe you dont need to query the database in ajax if the page, when being created, already has that info and you can store it in javascript.
Since you mentioned an ajax situation (trigger an event on drop down to query the database), then you need to include a JS file (my suggestion since you can do this from a plugin), there are other ways but this is the best in my opinion.
Please read my article about plugins if you need help with writing one. My suggestion is to write a plugin to include your JS file in the page.
In the JS file you can call a "controller function" like this:
$.ajaxCall('mymodule.myfunction', 'param1=value1&param2=value2');
this would run the function "myfunction" in the file /module/mymodule/include/component/ajax/ajax.class.php
From this ajax file you can call "service functions" and send code to the browser, for example:
$value = Phpfox::getService('mmodule')->someOtherFunction();
$this->call('alert("' . $value . '");');
Hope it helps

Setting up Twitter API, getting the last few Tweets

I am completely new to using Twitter in general and have never embedded "latest tweets" on any project. I am simply trying to embed the 3-4 newest tweets on the site footer with no additional features of functionality. I have been researching how to do this for quite some time now and having some trouble.
I added the following code snippet to the project, which works quite well, however, I am not sure how to update the snippet so it uses my Twitter account instead of the one it is set up with.
<div id="twitter_update_list">
</div>
<script type="text/javascript" src="http://api.twitter.com/1/statuses/user_timeline.json?screen_name=stackoverflow&include_rts=true&count=4&callback=twitterCallback2">
</script>
In addition, I keep reading that the most commonly used Twitter API will stop working soon because Twitter wants people to use their own, as opposed to third party.
I am not sure how to proceed from here. I would greatly appreciate any suggestions in this regard. To recap, all I am trying to do is grab the 3-4 latest tweets from my account.
many thanks in advance!
So you REALLY don't want to do this client-side anymore. (Just went through numerous docs, and devs suggest to do all oAuth server-side)
What you need to do:
First: sign up on https://dev.twitter.com, and make a new application.
Second: NOTE: Your Consumer Key / Secret along with Access Token / Secret
Third: Download Twitter OAuth Library (In this case I used the PHP Library https://github.com/abraham/twitteroauth , additional libraries located here: https://dev.twitter.com/docs/twitter-libraries)
Fourth: (If using PHP) Make sure cURL is enabled if your running on a LAMP here's the command you need:
sudo apt-get install php5-curl
Fifth: Make a new PHP file and insert the following: Thanks to Tom Elliot http://www.webdevdoor.com/php/authenticating-twitter-feed-timeline-oauth/
<?php
session_start();
require_once("twitteroauth/twitteroauth/twitteroauth.php"); //Path to twitteroauth library you downloaded in step 3
$twitteruser = "twitterusername"; //user name you want to reference
$notweets = 30; //how many tweets you want to retrieve
$consumerkey = "12345"; //Noted keys from step 2
$consumersecret = "123456789"; //Noted keys from step 2
$accesstoken = "123456789"; //Noted keys from step 2
$accesstokensecret = "12345"; //Noted keys from step 2
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
echo json_encode($tweets);
echo $tweets; //testing remove for production
?>
And boom, you're done. I know this isn't a pure js solution but again reading through the new Twitter API 1.1 docs they REALLY don't want you to do this client-side. Hope this helps!
How to get last few tweets of user with core PHP functionality only (no CURL or Twitter oAuth library needed):
Register your app/webpage https://apps.twitter.com (You may need to verify your personal account mobile number too)
Note Consumer Key and Consumer Secret
PHP Code:
// auth parameters
$api_key = urlencode('REPLACEWITHAPPAPIKEY'); // Consumer Key (API Key)
$api_secret = urlencode('REPLACEWITHAPPAPISECRET'); // Consumer Secret (API Secret)
$auth_url = 'https://api.twitter.com/oauth2/token';
// what we want?
$data_username = 'Independent'; // username
$data_count = 10; // number of tweets
$data_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?tweet_mode=extended';
// get api access token
$api_credentials = base64_encode($api_key.':'.$api_secret);
$auth_headers = 'Authorization: Basic '.$api_credentials."\r\n".
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8'."\r\n";
$auth_context = stream_context_create(
array(
'http' => array(
'header' => $auth_headers,
'method' => 'POST',
'content'=> http_build_query(array('grant_type' => 'client_credentials', )),
)
)
);
$auth_response = json_decode(file_get_contents($auth_url, 0, $auth_context), true);
$auth_token = $auth_response['access_token'];
// get tweets
$data_context = stream_context_create( array( 'http' => array( 'header' => 'Authorization: Bearer '.$auth_token."\r\n", ) ) );
$data = json_decode(file_get_contents($data_url.'&count='.$data_count.'&screen_name='.urlencode($data_username), 0, $data_context), true);
// result - do what you want
print('<pre>');
print_r($data);
Tested with XAMPP for Windows and Centos6 default installation (PHP 5.3)
Most probable problem with this might be that openssl is not enabled in php.ini
To fix check if extension=php_openssl.dll or extension=php_openssl.so line is present and uncommented in php.ini
Actually twitter has many restrictions, as there is lot of contest from companies like Nike and others. The reading of tweet is limited in the sense that if you are reading through the latest API its actually a bit behind time.
They have also controlled the DM delay which means you cannot DM instantly even if you do, the other party will only receive after X amount of time. If you do through script, and even if you try to DM a lot from one single ip twitter will simply BLOCK you.

Categories

Resources