How To Fetch Facebook Activity Feed of A Particular User - php

Do any one know how to fetch activity feed of an user who is associated with an app id ?
I am able to fetch the list of users who are associated with an app id by using this code
<?php
require "facebook.php";
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
));
$user = $facebook->getUser();
if ($user) {
try {
$result = $facebook->api(array(
"method" => "fql.query",
"query" => "SELECT uid, name, pic_square, activities FROM user
WHERE uid IN (SELECT uid1 FROM friend WHERE uid2 = me()) and is_app_user"
));
echo "<pre>";
print_r($result);
?>
Output
Array
(
[0] => Array
(
[uid] => 14529121124
[name] => Saurabh
[pic_square] => http://profile.ak.fbcdn.net/hprofile-ak-ash4/187195_1452918224_6692287_q.jpg
[activities] =>
)
[1] => Array
(
[uid] => 100000565666371
[name] => Abhijeet
[pic_square] => http://profile.ak.fbcdn.net/hprofile-ak-prn1/157718_100000289210371_1409561577_q.jpg
[activities] =>
)
)
Now i just want to fetch activity feed of these 2 users (User Id: 14529121124 , 100000565666371) individually who are associated with this (54975723243503) app_id.

Use graph API : https://developers.facebook.com/docs/reference/api/user/
Search for "feed" in that page

You need to query the FQL stream table or the Graph API feed object:
Since you're working with FQL, I'll give an example using FQL. I did some quick testing, and the stream table doesn't allow you to use the IN keyword to select streams from multiple sources, so you'll need to make two separate calls, first to get the user_ids, second to get the stream.
Try this:
$queries = array();
$i = 0;
foreach ($result as $item) {
$queries['user_stream'.$i] =>
"SELECT source_id, created_time, message, attachment FROM stream
WHERE source_id = " . $item['uid'];
$i++;
}
$result2 = $facebook->api(array(
"method" => "fql.multiquery",
"queries" => json_encode($queries)
));

Related

Laravel DB::select() does not return "correct" data

I am using Laravel 8.12
I am doing a DB::select() call with DB::raw() method filtering. But for convenience I will post full statement with values as well.
Here is the PHP code for query
$sql = "SELECT `medium_info`.* , `postings`.`posting_timestamp` FROM `postings` INNER JOIN `medium_info` ON `postings`.`medium_info_id` = `medium_info`.`id` INNER JOIN `accounts` ON `accounts`.`id` = `postings`.`account_id` INNER JOIN `merchants` ON `merchants`.`account_holder_id` = `accounts`.`account_holder_id` INNER JOIN `medium_types` ON `medium_types`.`id` = `accounts`.`medium_type_id` WHERE `merchants`.`account_holder_id` = :merchant_account_holder_id AND `medium_info`.`id` = :medium_info_id AND `medium_types`.`id` = :medium_types_id";
$result = DB::select ( DB::raw($sql), ['merchant_account_holder_id'=>230124, 'medium_info_id'=>551678, 'medium_types_id'=>1] );
When I print $result it gives me data like this:
[0] => stdClass Object
(
[id] => 230124
[purchase_date] => 2020-11-22
[redemption_date] =>
[expiration_date] =>
[hold_until] => 2021-05-07 02:30:08
...more medium_info data here
[posting_timestamp] => 2020-11-25 23:27:13
...merchants table data which I did not request
[account_holder_id] => 230124
[name] => Best Buy
[logo] => /cdn/merchants/230124/logo.png
If I do the following, results are still same:
$sql = "SELECT `medium_info`.* , `postings`.`posting_timestamp` FROM `postings` INNER JOIN `medium_info` ON `postings`.`medium_info_id` = `medium_info`.`id` INNER JOIN `accounts` ON `accounts`.`id` = `postings`.`account_id` INNER JOIN `merchants` ON `merchants`.`account_holder_id` = `accounts`.`account_holder_id` INNER JOIN `medium_types` ON `medium_types`.`id` = `accounts`.`medium_type_id` WHERE `merchants`.`account_holder_id` = 230124 AND `medium_info`.`id` = 551678 AND `medium_types`.`id` = 1";
$result = DB::select ( $sql));
However when I run this query in phpMyAdmin it gives me 'correct' results with "id" from medium_info table. Here is a screenshot:
I want to add here that results received via DB::select() query has "merchants" row attached which I did not request in my query. Even if I just do SELECT `postings`.`posting_timestamp` FROM... request it would give me this result:
Array
(
[0] => stdClass Object
(
[posting_timestamp] => 2020-11-25 23:27:13
[account_holder_id] => 230124
[id] => 230124
[name] => Best Buy
[logo] => /cdn/merchants/230124/logo.png
[description] => <p>When technology meets life, they come together at Best Buy®. Best Buy has the technology that’s fun and functional, from tablets and videogames, to appliances and big screen TVs. Use your gift card at BestBuy.com® or at any US Best Buy store.</p>
[website] => http://www.bestbuy.com
[merchant_code] => BES
[is_premium] => 1
[large_icon] => /cdn/merchants/230124/large_icon.png
[status] => 1
[get_gift_codes_from_root] => 0
[website_is_redemption_url] => 0
[cost_to_program] => 0
[toa_name] =>
)
)
So obviously it is attaching "merchants" row no matter what I "SELECT". Also, notice that there is [id] => 230124 which is coming from "nowhere", there is no field id in merchants table. There is an id field in medium_info table but it should have returned 551678 not 230124 which is merchant id with field name account_holder_id in merchants table.
Edit: Just want to add that it does not attach merchants data when I run it in phpMyAdmin.
I am still trying to figure this out. If you need more info I am ready to provide. This must be something to do with Laravel DB::select conventions which I am not understanding, since it works in phpMyAdmin? Any help is appreciated.
Try this mate, using query builder :
\DB::table('postings')
->join('medium_info', 'postings.medium_info_id', '=', 'medium_info.id')
->join('accounts', 'postings.account_id', '=', 'accounts.id')
->join('merchants', 'merchants.account_holder_id', '=', 'accounts.account_holder_id')
->join('medium_types', 'medium_types.id', '=', 'accounts.medium_type_id')
->where('merchants.account_holder_id', 230124)
->where('medium_info.id', 551678)
->where('medium_types.id', 1)
->select('medium_info.*', 'postings.posting_timestamp')
->get();
It may help to check which SQL Laravel is actually running on your database.
The snippet bellow allows you to see just that.
<?php
DB::listen(function ($query) {
var_dump($query->sql);
});
Route::get('/', function () {
DB::select('SELECT * FROM users');
});
Also check barryvdh/laravel-debugbar extension.

How to encode an array of data and save to a pivot table laravel

All I want here is to be able to save all the ID's of services into the pivot table associated with the given keywords/tags but at the moment all it does is that it takes the last ID of the created object and saves into the pivot table with different keywords. let's say for example I enter [id1 => service1, id2 => service2] and [id1 = > keyword1, id2 => keyword2, id3 => keyword3] instead of it saving only id2 of service2 and all the keywords I want it to save all the Ids of all of the services and the keywords. I hope it makes sense
foreach($params['service'] as $key => $value){
$service = Service::firstOrNew(['service' => $value, 'price' => $params['price'][$key], 'business_id' => $params['business_id']]);
$service->service = $value;
$service->price = $params['price'][$key];
$service->business_id = $params['business_id'];
$service->save();
}
foreach($params['keywords'] as $keyword){
$cleaned_keyword = self::cleanKeywords($keyword);
$newKeyword = Keyword::firstOrNew(['keyword' => $cleaned_keyword]);
$newKeyword->keyword = $cleaned_keyword;
$newKeyword->save();
$service->keywords()->syncWithoutDetaching([$newKeyword->id => ['business_id' => $params['business_id']]]);
}
This is something I would expect but it is tricky because a single or 2 services for example can have multiple keywords. NOTE: I had manually changed these values in the database
These are the results from a dd($params)
Based on the dd($params).attached is the result,only
"service" => array:2[
1 => "Mobile development"
]
was saved in the pivot table and got assigned all the keywords
Please correct me if this is a good approach, I managed to solve this by having an inner loop.
foreach($params['service'] as $key => $value) {
$service = Service::firstOrNew(['service' => $value, 'price' => $params['price'][$key], 'business_id' => $params['business_id']]);
$service->service = $value;
$service->price = $params['price'][$key];
$service->business_id = $params['business_id'];
$service->save();
foreach($params['keywords'] as $keyword) {
$cleaned_keyword = self::cleanKeywords($keyword);
$newKeyword = Keyword::firstOrNew(['keyword' => $cleaned_keyword]);
$newKeyword->keyword = $cleaned_keyword;
$newKeyword->save();
$service->keywords()->syncWithoutDetaching([$newKeyword->id => ['business_id' => $params['business_id']]]);
}
}

how to select all news entries and all comments to him in one query

Reply question*
Fetch all news and all comments
You really think this best way?
I`am also needed get all news for current user [authorId]=>99
example
$news = array(
[0] = array(
[id]=>1,[authorId]=>99,[data]=>"Lorem Ipsum"
),
[1] = array(
[id]=>2,[authorId]=>99,[data]=>"Lorem Ipsum"
)
);
and get all comments for this user
example
$comments = array(
[0] = array(
[comId]=>1,[newsid]=>1,[authorId]=>99,[data]=>"bla bla bla bla"
),
[1] = array(
[comId]=>2,[newsid]=>1,[authorId]=>99,[data]=>"bla bla"
)
);
other table users
$users = array(
[0] = array(
[userId]=>99,
[userName]=>"User99"
)
);
and after
select * from news n left join users u on n.authorId = u.userId where n.authorId = 99
into this select push select for get comments
array(
[0] => array(
[id] => 1 // news' id
[userId] => 99,
[data]=>"Lorem Ipsum",
[comments] => array(
[0] => arra(
[comId] => 1 // comment's id
[userId] => 99
[data]=>"bla bla"
),
...
)
),
...
)
in question***(top)
The first query gets all of the news articles and puts them in an array. The second query gets the comments, and accumulates a separate array within each news article's structure.
But if this queries and foreach two array be run 10000 times while
example
10000 refresh page ?
You must use a logical caching
1) If you get many records and limit considered paged query result
2) Separate information for each table in different arrangements
$user = array();
$comments = array();
3) Combines both arrays using foreach and array_merge
$merge = array();
$i=0;
foreach ($comments as $row) {
extract($row);
if(in_array($iduser, $user)):
$merge[$i] = $comments + $user;
endif;
$i++;
}
This is a pseudo code have not tried it maybe should do some adjustments. I hope you serve

Getting Facebook event venue latitude & longitude

Hello I use the following code in order to retrieve an events infoormation from facebook based on the url provided.
The code is this:
function importEvent($url)
{
$facebook = new Facebook(array(
'appId' => 'someAppId',
'secret' => 'someSecret',
'cookie' => true, // enable optional cookie support
));
if(checkLogin()==true)
{
//get rid of hash if exists
$hash = explode('#',$url);
if(!empty($hash[1]))
$array = parse_url($hash[1]);
else
$array = parse_url($hash[0]);
parse_str($array['query'],$output);
$eid = $output['eid'];
if(empty($eid))//new url think http://www.facebook.com/events/2323423423423/
{
$url = str_replace('http://www.facebook.com/events/','',$url);
$url = str_replace('https://www.facebook.com/events/','',$url);
$hash = explode('/?',$url);
if(!empty($hash[1]))
$url = $hash[0];
$eid = str_replace('?','',$url);
$eid = str_replace('/','',$url);
//print_r($eid);
}
//Calling users.getinfo legacy api call example
try{
$param = array(
'method' => 'events.get',
'eids' => $eid,
'access_token' => $_SESSION['access_token']
);
$events = $facebook->api($param);
}
catch(Exception $o){
error_log($o);
echo $o;
}
print_r($events);
return $events;
}
}
The output I'm getting is this:
Array
(
[0] => Array
(
[eid] => 410474065693887
[name] => Sunday Night Fever Vol.4 Disco Special #Legacy Rock Area
[pic_small] => http://profile.ak.fbcdn.net/hprofile-ak-snc6/276862_410474065693887_714884848_t.jpg
[pic_big] => http://profile.ak.fbcdn.net/hprofile-ak-snc6/276862_410474065693887_714884848_n.jpg
[pic] => http://profile.ak.fbcdn.net/hprofile-ak-snc6/276862_410474065693887_714884848_s.jpg
[pic_square] => http://profile.ak.fbcdn.net/hprofile-ak-snc6/276862_410474065693887_714884848_q.jpg
[has_profile_pic] => 1
[host] => Legacy Rock Area
[version] => 2
[description] => Αφου μας το ζητησατε "παρτε" το..!!!
Μετα το τελευταιο απιστευτο killer Disco Party εχουμε την ευκαιρια να κανουμε προθερμανση για τον Super Αποκριατικο Φεβρουαριο που θα ακολουθησει στο Legacy Rock Area μεμια βραδυα γεματη Disco,Dance,Pop και οπου μας βγαλει...!!
Κυριακη 20 Ιανουαριου λοιπον..Sunday Night Fever Disco Special!!!
That night the DJ saves our lives...!!!
[start_time] => 2013-01-20
[end_time] =>
[timezone] =>
[is_date_only] => 1
[creator] => 1732432279
[update_time] => 1357737066
[location] => Legacy Rock Area
[hide_guest_list] =>
[can_invite_friends] =>
[privacy] => OPEN
[venue] => Array
(
[id] => 244479685665743
)
[all_members_count] => 7175
[attending_count] => 74
[unsure_count] => 144
[declined_count] => 509
[not_replied_count] => 6957
)
)
However on the api documentation it mentions that venue contains the following:
The location of this event
generic access_token, user_events or friends_events
object containing one or more of the following fields: id, street, city, state, zip, country, latitude, and longitude fields.
But all I'm getting is the venue id.
I couldn't locate a specific piece of information on how to retrieve lat + lng of a venue place and I assume that this code is ok if I'm not mistaken.
Do I need to execute another query just for the venue info and if so could you please provide any reference or code examples? Or is there a way for this piece of code to return the lat + lng also, so I wont have to do 2 queries for 1 event?
After some research I've found that that this could be doen with fql.multiquery and it seems to work fine now. Here is the source code.
function importEventFQL($url)
{
$facebook = new Facebook(array(
'appId' => 'someApddID',
'secret' => 'someSecret',
'cookie' => true, // enable optional cookie support
));
if(checkLogin()==true)
{
list($url_static,$url_URI) = explode('/events',$url);
$url_URI = ltrim($url_URI,'/');
list($eid, $trash) = explode('/?',$url_URI);
$fql = '{';
$fql .= '"event_info":"SELECT name, description, pic_small, pic_big, eid, venue, location, start_time, end_time, host from event WHERE eid=\'' . $eid . '\'",';
$fql .= '"event_venue":"SELECT name, username, page_id, location FROM page WHERE page_id IN (SELECT venue.id FROM #event_info)"';
$fql .= '}';
$param = array(
'method' => 'fql.multiquery',
'queries' => $fql,
'callback' => ''
);
$result = $facebook->api($param);
print_r($result);
}
}
If you want just the FQL to do this:
{
"events" : "SELECT privacy, name, description, start_time, venue.id, pic_cover FROM event WHERE eid IN (SELECT eid FROM event_member WHERE uid = me())",
"venues" : "SELECT latitude, longitude, name, page_id FROM place WHERE page_id IN (SELECT venue.id FROM #events)"
}

SQL Syntax and Columns using PHP

(This is called via PHP) I have the following:
"SELECT name FROM user WHERE uid IN (SELECT uid1 FROM friend WHERE uid2={$user})"
The SQL executes perfectly fine, however, the result is an array where the key is "name". I would like each result's key to be the respective uid in user that was searched to pull that name.
Example:
How it is right now
If the name was "Bob" and his uid was "12345", I would like the return array to be - [name] => Bob.
How I would like it to be
If the name was "Bob" and his uid was "12345", I would like the return array to be - [12345] => Bob.
EDIT (as per the comment request):
$fql = "SELECT pic FROM user WHERE uid IN (SELECT uid1 FROM friend WHERE uid2={$user})";
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$result = $facebook->api($param);
$newResult = array();
foreach ($result as $entry)
{
$newResult[$entry['uid']] = $entry['name'];
}

Categories