4 * Description: Synchronizes the Facebook Newsfeed
6 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
11 - B: Threading for incoming comments
12 - C: Receiving likes for comments
15 - A: Posts to pages currently have the page as sender - not the user
16 - B: Sending likes for comments
17 - C: Threading for sent comments
20 require_once("addon/fbpost/fbpost.php");
22 define('FBSYNC_DEFAULT_POLL_INTERVAL', 5); // given in minutes
24 function fbsync_install() {
25 register_hook('connector_settings', 'addon/fbsync/fbsync.php', 'fbsync_settings');
26 register_hook('connector_settings_post', 'addon/fbsync/fbsync.php', 'fbsync_settings_post');
27 register_hook('cron', 'addon/fbsync/fbsync.php', 'fbsync_cron');
30 function fbsync_uninstall() {
31 unregister_hook('connector_settings', 'addon/fbsync/fbsync.php', 'fbsync_settings');
32 unregister_hook('connector_settings_post', 'addon/fbsync/fbsync.php', 'fbsync_settings_post');
33 unregister_hook('cron', 'addon/fbsync/fbsync.php', 'fbsync_cron');
36 function fbsync_settings(&$a,&$s) {
41 /* Add our stylesheet to the page so we can make our settings look nice */
43 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/fbsync/fbsync.css' . '" media="all" />' . "\r\n";
45 /* Get the current state of our config variables */
47 $enabled = get_pconfig(local_user(),'fbsync','sync');
49 $checked = (($enabled) ? ' checked="checked" ' : '');
51 $def_enabled = get_pconfig(local_user(),'fbsync','create_user');
53 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
55 /* Add some HTML to the existing form */
57 $s .= '<div class="settings-block">';
58 $s .= '<h3>' . t('Facebook Import Settings') . '</h3>';
60 $s .= '<div id="fbsync-enable-wrapper">';
61 $s .= '<label id="fbsync-enable-label" for="fbsync-checkbox">' . t('Import Facebook newsfeed') . '</label>';
62 $s .= '<input id="fbsync-checkbox" type="checkbox" name="fbsync" value="1" ' . $checked . '/>';
63 $s .= '</div><div class="clear"></div>';
65 $s .= '<div id="fbsync-create_user-wrapper">';
66 $s .= '<label id="fbsync-create_user-label" for="fbsync-create_user">' . t('Automatically create contacts') . '</label>';
67 $s .= '<input id="fbsync-create_user" type="checkbox" name="create_user" value="1" ' . $def_checked . '/>';
68 $s .= '</div><div class="clear"></div>';
70 /* provide a submit button */
72 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fbsync-submit" name="fbsync-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
76 function fbsync_settings_post(&$a,&$b) {
78 if(x($_POST,'fbsync-submit')) {
79 set_pconfig(local_user(),'fbsync','sync',intval($_POST['fbsync']));
80 //set_pconfig(local_user(),'fbsync','create_user',intval($_POST['create_user']));
84 function fbsync_cron($a,$b) {
85 $last = get_config('fbsync','last_poll');
87 $poll_interval = intval(get_config('fbsync','poll_interval'));
89 $poll_interval = FBSYNC_DEFAULT_POLL_INTERVAL;
92 $next = $last + ($poll_interval * 60);
94 logger('fbsync_cron: poll intervall not reached');
98 logger('fbsync_cron: cron_start');
100 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fbsync' AND `k` = 'sync' AND `v` = '1' ORDER BY RAND()");
103 fbsync_get_self($rr['uid']);
105 logger('fbsync_cron: importing timeline from user '.$rr['uid']);
106 fbsync_fetchfeed($a, $rr['uid']);
110 logger('fbsync: cron_end');
112 set_config('fbsync','last_poll', time());
115 function fbsync_createpost($a, $uid, $self, $contacts, $applications, $post, $create_user) {
117 // check if it was already imported
118 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
120 dbesc('fb::'.$post->post_id)
125 $postarray = array();
126 $postarray['gravity'] = 0;
127 $postarray['uid'] = $uid;
128 $postarray['wall'] = 0;
130 $postarray['verb'] = ACTIVITY_POST;
132 $postarray['uri'] = "fb::".$post->post_id;
133 $postarray['thr-parent'] = $postarray['uri'];
134 $postarray['parent-uri'] = $postarray['uri'];
135 $postarray['plink'] = $post->permalink;
137 $postarray['author-name'] = $contacts[$post->actor_id]->name;
138 $postarray['author-link'] = $contacts[$post->actor_id]->url;
139 $postarray['author-avatar'] = $contacts[$post->actor_id]->pic_square;
141 $postarray['owner-name'] = $contacts[$post->source_id]->name;
142 $postarray['owner-link'] = $contacts[$post->source_id]->url;
143 $postarray['owner-avatar'] = $contacts[$post->source_id]->pic_square;
147 //if (($post->parent_post_id != "") AND ($post->source_id != $post->source_id)) {
148 if ($post->parent_post_id != "") {
149 $pos = strpos($post->parent_post_id, "_");
152 $user_id = substr($post->parent_post_id, 0, $pos);
154 $userdata = fbsync_fetchuser($a, $uid, $user_id);
156 $contact_id = $userdata["contact-id"];
158 $postarray['contact-id'] = $contact_id;
160 $postarray['owner-name'] = $userdata["name"];
161 $postarray['owner-link'] = $userdata["link"];
162 $postarray['owner-avatar'] = $userdata["avatar"];
164 if (!intval(get_config('system','wall-to-wall_share'))) {
166 $prebody = "[share author='".$postarray['author-name'].
167 "' profile='".$postarray['author-link'].
168 "' avatar='".$postarray['author-avatar']."']".
170 $postarray['author-name'] = $postarray['owner-name'];
171 $postarray['author-link'] = $postarray['owner-link'];
172 $postarray['author-avatar'] = $postarray['owner-avatar'];
177 if ($contact_id == 0) {
178 $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
182 elseif ($contact_id == 0)
183 $contact_id = $self[0]["id"];
185 $postarray['contact-id'] = $contact_id;
188 $postarray["body"] = (isset($post->message) ? escape_tags($post->message) : '');
190 $msgdata = fbsync_convertmsg($a, $postarray["body"]);
192 $postarray["body"] = $msgdata["body"];
193 $postarray["tag"] = $msgdata["tags"];
195 if(isset($post->attachment->name) and isset($post->attachment->href))
196 $postarray["body"] .= "\n\n[bookmark=".$post->attachment->href."]".$post->attachment->name."[/bookmark]";
197 elseif (isset($post->attachment->name) AND ($post->attachment->name != ""))
198 $postarray["body"] .= "\n\n[b]" . $post->attachment->name."[/b]";
201 if(isset($post->attachment->description) and ($post->attachment->fb_object_type != "photo"))
202 $quote = $post->attachment->description;
204 if(isset($post->attachment->caption) and ($post->attachment->fb_object_type == "photo"))
205 $quote = $post->attachment->caption;
207 if ($quote.$post->attachment->href.$postarray["body"] == "")
210 if (isset($post->attachment->media) AND !strstr($post->attachment->href, "://www.youtube.com/")
211 AND !strstr($post->attachment->href, "://youtu.be/")
212 AND !strstr($post->attachment->href, ".vimeo.com/")) {
213 foreach ($post->attachment->media AS $media) {
214 //$media->photo->owner = number_format($media->photo->owner, 0, '', '');
215 //if ($media->photo->owner != '') {
216 // $postarray['author-name'] = $contacts[$media->photo->owner]->name;
217 // $postarray['author-link'] = $contacts[$media->photo->owner]->url;
218 // $postarray['author-avatar'] = $contacts[$media->photo->owner]->pic_square;
221 if(isset($media->src) && isset($media->href) AND ($media->src != "") AND ($media->href != ""))
222 $postarray["body"] .= "\n".'[url='.$media->href.'][img]'.fpost_cleanpicture($media->src).'[/img][/url]';
224 if (isset($media->src) AND ($media->src != ""))
225 $postarray["body"] .= "\n".'[img]'.fpost_cleanpicture($media->src).'[/img]';
227 // if just a link, it may be a wall photo - check
228 if(isset($post->link))
229 $postarray["body"] .= fbpost_get_photo($media->href);
235 $postarray["body"] .= "\n[quote]".$quote."[/quote]";
237 $postarray["body"] = trim($postarray["body"]);
239 if (trim($postarray["body"]) == "")
243 $postarray["body"] = $prebody.$postarray["body"]."[/share]";
245 $postarray['created'] = datetime_convert('UTC','UTC',date("c", $post->created_time));
246 $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $post->updated_time));
248 $postarray['app'] = $applications[$post->app_id]->display_name;
250 if ($postarray['app'] == "")
251 $postarray['app'] = "Facebook";
253 if(isset($post->privacy) && $post->privacy->value !== '') {
254 $postarray['private'] = 1;
255 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
259 $postarray["location"] = $post->place->name;
260 postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
263 //$types = array(46, 80, 237, 247, 308);
264 //if (!in_array($post->type, $types))
265 // $postarray["body"] = "Type: ".$post->type."\n".$postarray["body"];
267 //print_r($postarray);
269 $item = item_store($postarray);
270 logger('fbsync_createpost: User '.$self[0]["nick"].' posted feed item '.$item, LOGGER_DEBUG);
273 function fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $applications, $comment) {
275 // check if it was already imported
276 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
278 dbesc('fb::'.$comment->id)
283 // check if it was an own post (separate posting for performance reasons)
284 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
286 dbesc('fb::'.$comment->id)
293 // Fetch the parent uri (Checking if the parent exists)
294 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
296 dbesc('fb::'.$comment->post_id)
299 $parent_uri = $r[0]["uri"];
301 // check if it is a reply to an own post (separate posting for performance reasons)
302 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
304 dbesc('fb::'.$comment->post_id)
307 $parent_uri = $r[0]["uri"];
309 // No parent? Then quit
310 if ($parent_uri == "")
313 $postarray = array();
314 $postarray['gravity'] = 0;
315 $postarray['uid'] = $uid;
316 $postarray['wall'] = 0;
318 $postarray['verb'] = ACTIVITY_POST;
320 $postarray['uri'] = "fb::".$comment->id;
321 $postarray['thr-parent'] = $parent_uri;
322 $postarray['parent-uri'] = $parent_uri;
323 //$postarray['plink'] = $comment->permalink;
325 $contact_id = fbsync_fetch_contact($uid, $contacts[$comment->fromid], array(), false);
327 if ($contact_id <= 0)
328 $contact_id = $self[0]["id"];
330 if ($comment->fromid != $self_id) {
331 $postarray['contact-id'] = $contact_id;
332 $postarray['owner-name'] = $contacts[$comment->fromid]->name;
333 $postarray['owner-link'] = $contacts[$comment->fromid]->url;
334 $postarray['owner-avatar'] = $contacts[$comment->fromid]->pic_square;
336 $postarray['contact-id'] = $self[0]["id"];
337 $postarray['owner-name'] = $self[0]["name"];
338 $postarray['owner-link'] = $self[0]["url"];
339 $postarray['owner-avatar'] = $self[0]["photo"];
342 $postarray['author-name'] = $postarray['owner-name'];
343 $postarray['author-link'] = $postarray['owner-link'];
344 $postarray['author-avatar'] = $postarray['owner-avatar'];
346 $msgdata = fbsync_convertmsg($a, $comment->text);
348 $postarray["body"] = $msgdata["body"];
349 $postarray["tag"] = $msgdata["tags"];
351 $postarray['created'] = datetime_convert('UTC','UTC',date("c", $comment->time));
352 $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $comment->time));
354 $postarray['app'] = $applications[$comment->app_id]->display_name;
356 if ($postarray['app'] == "")
357 $postarray['app'] = "Facebook";
359 if (trim($postarray["body"]) == "")
362 $item = item_store($postarray);
363 logger('fbsync_createcomment: User '.$self[0]["nick"].' posted comment '.$item, LOGGER_DEBUG);
368 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
369 dbesc($postarray['parent-uri']),
374 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
376 $own_contact = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
377 intval($uid), dbesc("facebook::".$self_id));
379 if (!count($own_contact))
382 foreach($myconv as $conv) {
384 // now if we find a match, it means we're in this conversation
385 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_contact[0]["url"]))
388 require_once('include/enotify.php');
390 $conv_parent = $conv['parent'];
393 'type' => NOTIFY_COMMENT,
394 'notify_flags' => $user[0]['notify-flags'],
395 'language' => $user[0]['language'],
396 'to_name' => $user[0]['username'],
397 'to_email' => $user[0]['email'],
398 'uid' => $user[0]['uid'],
399 'item' => $postarray,
400 'link' => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $item,
401 'source_name' => $postarray['author-name'],
402 'source_link' => $postarray['author-link'],
403 'source_photo' => $postarray['author-avatar'],
404 'verb' => ACTIVITY_POST,
406 'parent' => $conv_parent,
409 notification($notifyarr);
411 // only send one notification
417 function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
419 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
420 dbesc("fb::".$like->post_id),
429 // If we posted the like locally, it will be found with our url, not the FB url.
431 $second_url = (($like->user_id == $self_id) ? $self[0]["url"] : $contacts[$like->user_id]->url);
433 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
434 AND (`author-link` = '%s' OR `author-link` = '%s') LIMIT 1",
435 dbesc($orig_post["uri"]),
437 dbesc(ACTIVITY_LIKE),
438 dbesc($contacts[$like->user_id]->url),
445 $contact_id = fbsync_fetch_contact($uid, $contacts[$like->user_id], array(), false);
447 if ($contact_id <= 0)
448 $contact_id = $self[0]["id"];
451 $likedata['parent'] = $orig_post['id'];
452 $likedata['verb'] = ACTIVITY_LIKE;
453 $likedata['gravity'] = 3;
454 $likedata['uid'] = $uid;
455 $likedata['wall'] = 0;
456 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
457 $likedata['parent-uri'] = $orig_post["uri"];
458 $likedata['app'] = "Facebook";
459 $likedata['verb'] = ACTIVITY_LIKE;
461 if ($like->user_id != $self_id) {
462 $likedata['contact-id'] = $contact_id;
463 $likedata['author-name'] = $contacts[$like->user_id]->name;
464 $likedata['author-link'] = $contacts[$like->user_id]->url;
465 $likedata['author-avatar'] = $contacts[$like->user_id]->pic_square;
467 $likedata['contact-id'] = $self[0]["id"];
468 $likedata['author-name'] = $self[0]["name"];
469 $likedata['author-link'] = $self[0]["url"];
470 $likedata['author-avatar'] = $self[0]["photo"];
473 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
475 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
476 $post_type = t('status');
478 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
479 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
481 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
483 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
484 '<id>' . $orig_post['uri'] . '</id><link>' . xmlify('<link rel="alternate" type="text/html" href="' . xmlify($orig_post['plink']) . '" />') . '</link><title>' . $orig_post['title'] . '</title><content>' . $orig_post['body'] . '</content></object>';
487 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `author-link` = '%s' AND `verb` = '%s' AND `uid` = %d LIMIT 1",
488 dbesc($likedata['parent-uri']),
489 dbesc($likedata['author-link']),
490 dbesc(ACTIVITY_LIKE),
497 $item = item_store($likedata);
498 logger('fbsync_createlike: liked item '.$item.'. User '.$self[0]["nick"], LOGGER_DEBUG);
501 function fbsync_fetch_contact($uid, $contact, $create_user) {
503 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
504 intval($uid), dbesc("facebook::".$contact->id));
506 if(!count($r) AND !$create_user)
509 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
510 logger("fbsync_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
514 $avatarpicture = $contact->pic_square;
517 // create contact record
518 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
519 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
520 `writable`, `blocked`, `readonly`, `pending`)
521 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0)",
523 dbesc(datetime_convert()),
524 dbesc($contact->url),
525 dbesc(normalise_link($contact->url)),
526 dbesc($contact->username."@facebook.com"),
527 dbesc("facebook::".$contact->id),
529 dbesc("facebook::".$contact->id),
530 dbesc($contact->name),
531 dbesc($contact->username),
532 dbesc($avatarpicture),
533 dbesc(NETWORK_FACEBOOK),
534 intval(CONTACT_IS_FRIEND),
539 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
540 dbesc("facebook::".$contact->id),
547 $contact_id = $r[0]['id'];
549 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
553 if($g && intval($g[0]['def_gid'])) {
554 require_once('include/group.php');
555 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
558 require_once("Photo.php");
560 $photos = import_profile_photo($avatarpicture,$uid,$contact_id);
562 q("UPDATE `contact` SET `photo` = '%s',
572 dbesc(datetime_convert()),
573 dbesc(datetime_convert()),
574 dbesc(datetime_convert()),
578 // update profile photos once every 12 hours as we have no notification of when they change.
579 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
581 // check that we have all the photos, this has been known to fail on occasion
582 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
584 logger("fbsync_fetch_contact: Updating contact ".$contact->username, LOGGER_DEBUG);
586 require_once("Photo.php");
588 $photos = import_profile_photo($avatarpicture, $uid, $r[0]['id']);
590 q("UPDATE `contact` SET `photo` = '%s',
595 `avatar-date` = '%s',
605 dbesc(datetime_convert()),
606 dbesc(datetime_convert()),
607 dbesc(datetime_convert()),
608 dbesc($contact->url),
609 dbesc(normalise_link($contact->url)),
610 dbesc($contact->username."@facebook.com"),
611 dbesc($contact->name),
612 dbesc($contact->username),
620 function fbsync_get_self($uid) {
621 $access_token = get_pconfig($uid,'facebook','access_token');
624 $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
626 $j = json_decode($s);
627 set_pconfig($uid,'fbsync','self_id',(string) $j->id);
631 function fbsync_convertmsg($a, $body) {
634 $tags = get_tags($body);
637 foreach($tags as $tag) {
638 if (strstr(trim($tag), " "))
641 if(strpos($tag,'#') === 0) {
642 if(strpos($tag,'[url='))
645 // don't link tags that are already embedded in links
647 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
649 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
652 $basetag = str_replace('_',' ',substr($tag,1));
653 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
654 if(strlen($str_tags))
656 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
658 } elseif(strpos($tag,'@') === 0) {
659 $basetag = substr($tag,1);
660 $body = str_replace($tag,'@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
666 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
668 foreach($matches as $mtch) {
669 if(strlen($str_tags))
671 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
675 return(array("body"=>$body, "tags"=>$str_tags));
679 function fbsync_fetchuser($a, $uid, $id) {
680 $access_token = get_pconfig($uid,'facebook','access_token');
681 $self_id = get_pconfig($uid,'fbsync','self_id');
685 $contact = q("SELECT `id`, `name`, `url`, `photo` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
686 intval($uid), dbesc("facebook::".$id));
688 if (count($contact)) {
689 $user["contact-id"] = $contact[0]["id"];
690 $user["name"] = $contact[0]["name"];
691 $user["link"] = $contact[0]["url"];
692 $user["avatar"] = $contact[0]["photo"];
697 $own_contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
698 intval($uid), dbesc("facebook::".$self_id));
700 if (!count($own_contact))
703 $fql = "SELECT name, url, pic_square FROM profile WHERE id = ".$id;
705 $url = "https://graph.facebook.com/fql?q=".urlencode($fql)."&access_token=".$access_token;
707 $feed = fetch_url($url);
708 $data = json_decode($feed);
710 if (is_array($data->data)) {
711 $user["contact-id"] = $own_contact[0]["id"];
712 $user["name"] = $data->data[0]->name;
713 $user["link"] = $data->data[0]->url;
714 $user["avatar"] = $data->data[0]->pic_square;
719 function fbsync_fetchfeed($a, $uid) {
720 $access_token = get_pconfig($uid,'facebook','access_token');
721 $last_updated = get_pconfig($uid,'fbsync','last_updated');
722 $self_id = get_pconfig($uid,'fbsync','self_id');
724 //$create_user = get_pconfig($uid, 'fbsybc', 'create_user');
726 $do_likes = get_config('fbsync', 'do_likes');
728 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
732 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
738 require_once('include/items.php');
740 if ($last_updated == "")
743 logger("fbsync_fetchfeed: fetching content for user ".$self_id);
746 "posts" => "SELECT action_links, actor_id, app_data, app_id, attachment, attribution, comment_info, created_time, filter_key, like_info, message, message_tags, parent_post_id, permalink, place, post_id, privacy, share_count, share_info, source_id, subscribed, tagged_ids, type, updated_time, with_tags FROM stream where filter_key in (SELECT filter_key FROM stream_filter WHERE uid=me() AND type='newsfeed') AND updated_time > $last_updated ORDER BY updated_time DESC LIMIT 500",
747 "comments" => "SELECT app_id, attachment, post_id, id, likes, fromid, time, text, text_tags, user_likes, likes FROM comment WHERE post_id IN (SELECT post_id FROM #posts) ORDER BY time DESC LIMIT 500",
748 "profiles" => "SELECT id, name, username, url, pic_square FROM profile WHERE id IN (SELECT actor_id FROM #posts) OR id IN (SELECT fromid FROM #comments) OR id IN (SELECT source_id FROM #posts) LIMIT 500",
749 "applications" => "SELECT app_id, display_name FROM application WHERE app_id IN (SELECT app_id FROM #posts) OR app_id IN (SELECT app_id FROM #comments) LIMIT 500",
750 "avatars" => "SELECT id, real_size, size, url FROM square_profile_pic WHERE id IN (SELECT id FROM #profiles) AND size = 256 LIMIT 500");
753 $fql["likes"] = "SELECT post_id, user_id FROM like WHERE post_id IN (SELECT post_id FROM #posts)";
754 $fql["profiles"] .= " OR id IN (SELECT user_id FROM #likes)";
757 $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
759 $feed = fetch_url($url);
761 $data = json_decode($feed);
763 if (!is_array($data->data)) {
764 logger("fbsync_fetchfeed: Error fetching data for user ".$uid.": ".print_r($data, true));
772 $applications = array();
775 foreach($data->data AS $query) {
776 switch ($query->name) {
778 $posts = array_reverse($query->fql_result_set);
781 $comments = $query->fql_result_set;
784 $likes = $query->fql_result_set;
787 $profiles = $query->fql_result_set;
790 $applications = $query->fql_result_set;
793 $avatars = $query->fql_result_set;
798 $square_avatars = array();
800 $application_data = array();
801 $post_data = array();
802 $comment_data = array();
804 foreach ($avatars AS $avatar) {
805 $avatar->id = number_format($avatar->id, 0, '', '');
806 $square_avatars[$avatar->id] = $avatar;
810 foreach ($profiles AS $profile) {
811 $profile->id = number_format($profile->id, 0, '', '');
813 if ($square_avatars[$profile->id]->url != "")
814 $profile->pic_square = $square_avatars[$profile->id]->url;
816 $contacts[$profile->id] = $profile;
819 unset($square_avatars);
821 foreach ($applications AS $application) {
822 $application->app_id = number_format($application->app_id, 0, '', '');
823 $application_data[$application->app_id] = $application;
825 unset($applications);
827 foreach ($posts AS $post) {
828 $post->actor_id = number_format($post->actor_id, 0, '', '');
829 $post->source_id = number_format($post->source_id, 0, '', '');
830 $post->app_id = number_format($post->app_id, 0, '', '');
831 $post_data[$post->post_id] = $post;
835 foreach($comments AS $comment) {
836 $comment->fromid = number_format($comment->fromid, 0, '', '');
837 $comment_data[$comment->id] = $comment;
841 foreach ($post_data AS $post) {
842 if ($post->updated_time > $last_updated)
843 $last_updated = $post->updated_time;
845 fbsync_createpost($a, $uid, $self, $contacts, $application_data, $post, $create_user);
848 foreach ($comment_data AS $comment) {
849 fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $application_data, $comment);
852 foreach($likes AS $like) {
853 $like->user_id = number_format($like->user_id, 0, '', '');
855 fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like);
858 set_pconfig($uid,'fbsync','last_updated', $last_updated);