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');
28 register_hook('follow', 'addon/fbsync/fbsync.php', 'fbsync_follow');
31 function fbsync_uninstall() {
32 unregister_hook('connector_settings', 'addon/fbsync/fbsync.php', 'fbsync_settings');
33 unregister_hook('connector_settings_post', 'addon/fbsync/fbsync.php', 'fbsync_settings_post');
34 unregister_hook('cron', 'addon/fbsync/fbsync.php', 'fbsync_cron');
35 unregister_hook('follow', 'addon/fbsync/fbsync.php', 'fbsync_follow');
38 function fbsync_follow($a, &$contact) {
40 logger("fbsync_follow: Check if contact is facebook contact. ".$contact["url"], LOGGER_DEBUG);
42 if (!strstr($contact["url"], "://www.facebook.com") AND !strstr($contact["url"], "://facebook.com") AND !strstr($contact["url"], "@facebook.com"))
45 // contact seems to be a facebook contact, so continue
46 $nickname = preg_replace("=https?://.*facebook.com/([\w.]*).*=ism", "$1", $contact["url"]);
47 $nickname = str_replace("@facebook.com", "", $nickname);
49 $uid = $a->user["uid"];
51 $access_token = get_pconfig($uid,'facebook','access_token');
54 "profile" => "SELECT id, pic_square, url, username, name FROM profile WHERE username = '$nickname'",
55 "avatar" => "SELECT url FROM square_profile_pic WHERE id IN (SELECT id FROM #profile) AND size = 256");
57 $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
59 $feed = fetch_url($url);
60 $data = json_decode($feed);
64 logger("fbsync_follow: Query id for nickname ".$nickname, LOGGER_DEBUG);
66 if (!is_array($data->data))
69 $contactdata = new stdClass;
71 foreach($data->data AS $query) {
72 switch ($query->name) {
74 $contactdata->id = number_format($query->fql_result_set[0]->id, 0, '', '');
75 $contactdata->pic_square = $query->fql_result_set[0]->pic_square;
76 $contactdata->url = $query->fql_result_set[0]->url;
77 $contactdata->username = $query->fql_result_set[0]->username;
78 $contactdata->name = $query->fql_result_set[0]->name;
82 $contactdata->pic_square = $query->fql_result_set[0]->url;
87 logger("fbsync_follow: Got contact for nickname ".$nickname." ".print_r($contactdata, true), LOGGER_DEBUG);
90 fbsync_fetch_contact($uid, $contactdata, true);
92 $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
93 FROM `contact` WHERE `uid` = %d AND `alias` = '%s'",
95 dbesc("facebook::".$contactdata->id));
97 $contact["contact"] = $r[0];
101 function fbsync_settings(&$a,&$s) {
106 /* Add our stylesheet to the page so we can make our settings look nice */
108 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/fbsync/fbsync.css' . '" media="all" />' . "\r\n";
110 /* Get the current state of our config variables */
112 $enabled = get_pconfig(local_user(),'fbsync','sync');
114 $checked = (($enabled) ? ' checked="checked" ' : '');
116 $def_enabled = get_pconfig(local_user(),'fbsync','create_user');
118 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
120 /* Add some HTML to the existing form */
122 $s .= '<div class="settings-block">';
123 $s .= '<h3>' . t('Facebook Import Settings') . '</h3>';
125 $s .= '<div id="fbsync-enable-wrapper">';
126 $s .= '<label id="fbsync-enable-label" for="fbsync-checkbox">' . t('Import Facebook newsfeed') . '</label>';
127 $s .= '<input id="fbsync-checkbox" type="checkbox" name="fbsync" value="1" ' . $checked . '/>';
128 $s .= '</div><div class="clear"></div>';
130 $s .= '<div id="fbsync-create_user-wrapper">';
131 $s .= '<label id="fbsync-create_user-label" for="fbsync-create_user">' . t('Automatically create contacts') . '</label>';
132 $s .= '<input id="fbsync-create_user" type="checkbox" name="create_user" value="1" ' . $def_checked . '/>';
133 $s .= '</div><div class="clear"></div>';
135 /* provide a submit button */
137 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fbsync-submit" name="fbsync-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
141 function fbsync_settings_post(&$a,&$b) {
143 if(x($_POST,'fbsync-submit')) {
144 set_pconfig(local_user(),'fbsync','sync',intval($_POST['fbsync']));
145 set_pconfig(local_user(),'fbsync','create_user',intval($_POST['create_user']));
149 function fbsync_cron($a,$b) {
150 $last = get_config('fbsync','last_poll');
152 $poll_interval = intval(get_config('fbsync','poll_interval'));
154 $poll_interval = FBSYNC_DEFAULT_POLL_INTERVAL;
157 $next = $last + ($poll_interval * 60);
159 logger('fbsync_cron: poll intervall not reached');
163 logger('fbsync_cron: cron_start');
165 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fbsync' AND `k` = 'sync' AND `v` = '1' ORDER BY RAND()");
168 fbsync_get_self($rr['uid']);
170 logger('fbsync_cron: importing timeline from user '.$rr['uid']);
171 fbsync_fetchfeed($a, $rr['uid']);
175 logger('fbsync: cron_end');
177 set_config('fbsync','last_poll', time());
180 function fbsync_createpost($a, $uid, $self, $contacts, $applications, $post, $create_user) {
182 // check if it was already imported
183 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
185 dbesc('fb::'.$post->post_id)
190 $postarray = array();
191 $postarray['gravity'] = 0;
192 $postarray['uid'] = $uid;
193 $postarray['wall'] = 0;
195 $postarray['verb'] = ACTIVITY_POST;
197 $postarray['uri'] = "fb::".$post->post_id;
198 $postarray['thr-parent'] = $postarray['uri'];
199 $postarray['parent-uri'] = $postarray['uri'];
200 $postarray['plink'] = $post->permalink;
202 $postarray['author-name'] = $contacts[$post->actor_id]->name;
203 $postarray['author-link'] = $contacts[$post->actor_id]->url;
204 $postarray['author-avatar'] = $contacts[$post->actor_id]->pic_square;
206 $postarray['owner-name'] = $contacts[$post->source_id]->name;
207 $postarray['owner-link'] = $contacts[$post->source_id]->url;
208 $postarray['owner-avatar'] = $contacts[$post->source_id]->pic_square;
212 //if ($post->parent_post_id != "") {
213 if (($post->parent_post_id != "") AND ($post->actor_id == $post->source_id)) {
214 $pos = strpos($post->parent_post_id, "_");
217 $user_id = substr($post->parent_post_id, 0, $pos);
219 $userdata = fbsync_fetchuser($a, $uid, $user_id);
221 $contact_id = $userdata["contact-id"];
223 $postarray['contact-id'] = $contact_id;
225 $postarray['owner-name'] = $userdata["name"];
226 $postarray['owner-link'] = $userdata["link"];
227 $postarray['owner-avatar'] = $userdata["avatar"];
229 if (!intval(get_config('system','wall-to-wall_share'))) {
231 $prebody = "[share author='".$postarray['author-name'].
232 "' profile='".$postarray['author-link'].
233 "' avatar='".$postarray['author-avatar']."']".
235 $postarray['author-name'] = $postarray['owner-name'];
236 $postarray['author-link'] = $postarray['owner-link'];
237 $postarray['author-avatar'] = $postarray['owner-avatar'];
242 if ($contact_id == 0) {
243 $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
245 if (($contact_id <= 0) AND !$create_user)
247 elseif ($contact_id == 0)
248 $contact_id = $self[0]["id"];
250 $postarray['contact-id'] = $contact_id;
253 $postarray["body"] = (isset($post->message) ? escape_tags($post->message) : '');
255 $msgdata = fbsync_convertmsg($a, $postarray["body"]);
257 $postarray["body"] = $msgdata["body"];
258 $postarray["tag"] = $msgdata["tags"];
260 if(isset($post->attachment->name) and isset($post->attachment->href))
261 $postarray["body"] .= "\n\n[bookmark=".$post->attachment->href."]".$post->attachment->name."[/bookmark]";
262 elseif (isset($post->attachment->name) AND ($post->attachment->name != ""))
263 $postarray["body"] .= "\n\n[b]" . $post->attachment->name."[/b]";
266 if(isset($post->attachment->description) and ($post->attachment->fb_object_type != "photo"))
267 $quote = $post->attachment->description;
269 if(isset($post->attachment->caption) and ($post->attachment->fb_object_type == "photo"))
270 $quote = $post->attachment->caption;
272 if ($quote.$post->attachment->href.$postarray["body"] == "")
275 if (isset($post->attachment->media) AND !strstr($post->attachment->href, "://www.youtube.com/")
276 AND !strstr($post->attachment->href, "://youtu.be/")
277 AND !strstr($post->attachment->href, ".vimeo.com/")) {
278 foreach ($post->attachment->media AS $media) {
279 //$media->photo->owner = number_format($media->photo->owner, 0, '', '');
280 //if ($media->photo->owner != '') {
281 // $postarray['author-name'] = $contacts[$media->photo->owner]->name;
282 // $postarray['author-link'] = $contacts[$media->photo->owner]->url;
283 // $postarray['author-avatar'] = $contacts[$media->photo->owner]->pic_square;
286 if(isset($media->src) && isset($media->href) AND ($media->src != "") AND ($media->href != ""))
287 $postarray["body"] .= "\n".'[url='.$media->href.'][img]'.fpost_cleanpicture($media->src).'[/img][/url]';
289 if (isset($media->src) AND ($media->src != ""))
290 $postarray["body"] .= "\n".'[img]'.fpost_cleanpicture($media->src).'[/img]';
292 // if just a link, it may be a wall photo - check
293 if(isset($post->link))
294 $postarray["body"] .= fbpost_get_photo($media->href);
300 $postarray["body"] .= "\n[quote]".$quote."[/quote]";
302 $postarray["body"] = trim($postarray["body"]);
304 if (trim($postarray["body"]) == "")
308 $postarray["body"] = $prebody.$postarray["body"]."[/share]";
310 $postarray['created'] = datetime_convert('UTC','UTC',date("c", $post->created_time));
311 $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $post->updated_time));
313 $postarray['app'] = $applications[$post->app_id]->display_name;
315 if ($postarray['app'] == "")
316 $postarray['app'] = "Facebook";
318 if(isset($post->privacy) && $post->privacy->value !== '') {
319 $postarray['private'] = 1;
320 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
324 $postarray["location"] = $post->place->name;
325 postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
328 //$types = array(46, 80, 237, 247, 308);
329 //if (!in_array($post->type, $types))
330 // $postarray["body"] = "Type: ".$post->type."\n".$postarray["body"];
332 //print_r($postarray);
334 $item = item_store($postarray);
335 logger('fbsync_createpost: User '.$self[0]["nick"].' posted feed item '.$item, LOGGER_DEBUG);
338 function fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $applications, $comment) {
340 // check if it was already imported
341 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
343 dbesc('fb::'.$comment->id)
348 // check if it was an own post (separate posting for performance reasons)
349 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
351 dbesc('fb::'.$comment->id)
358 // Fetch the parent uri (Checking if the parent exists)
359 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
361 dbesc('fb::'.$comment->post_id)
364 $parent_uri = $r[0]["uri"];
366 // check if it is a reply to an own post (separate posting for performance reasons)
367 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
369 dbesc('fb::'.$comment->post_id)
372 $parent_uri = $r[0]["uri"];
374 // No parent? Then quit
375 if ($parent_uri == "")
378 $postarray = array();
379 $postarray['gravity'] = 0;
380 $postarray['uid'] = $uid;
381 $postarray['wall'] = 0;
383 $postarray['verb'] = ACTIVITY_POST;
385 $postarray['uri'] = "fb::".$comment->id;
386 $postarray['thr-parent'] = $parent_uri;
387 $postarray['parent-uri'] = $parent_uri;
388 //$postarray['plink'] = $comment->permalink;
390 $contact_id = fbsync_fetch_contact($uid, $contacts[$comment->fromid], array(), false);
392 if ($contact_id <= 0)
393 $contact_id = $self[0]["id"];
395 if ($comment->fromid != $self_id) {
396 $postarray['contact-id'] = $contact_id;
397 $postarray['owner-name'] = $contacts[$comment->fromid]->name;
398 $postarray['owner-link'] = $contacts[$comment->fromid]->url;
399 $postarray['owner-avatar'] = $contacts[$comment->fromid]->pic_square;
401 $postarray['contact-id'] = $self[0]["id"];
402 $postarray['owner-name'] = $self[0]["name"];
403 $postarray['owner-link'] = $self[0]["url"];
404 $postarray['owner-avatar'] = $self[0]["photo"];
407 $postarray['author-name'] = $postarray['owner-name'];
408 $postarray['author-link'] = $postarray['owner-link'];
409 $postarray['author-avatar'] = $postarray['owner-avatar'];
411 $msgdata = fbsync_convertmsg($a, $comment->text);
413 $postarray["body"] = $msgdata["body"];
414 $postarray["tag"] = $msgdata["tags"];
416 $postarray['created'] = datetime_convert('UTC','UTC',date("c", $comment->time));
417 $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $comment->time));
419 $postarray['app'] = $applications[$comment->app_id]->display_name;
421 if ($postarray['app'] == "")
422 $postarray['app'] = "Facebook";
424 if (trim($postarray["body"]) == "")
427 $item = item_store($postarray);
428 logger('fbsync_createcomment: User '.$self[0]["nick"].' posted comment '.$item, LOGGER_DEBUG);
433 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
434 dbesc($postarray['parent-uri']),
439 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
441 $own_contact = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
442 intval($uid), dbesc("facebook::".$self_id));
444 if (!count($own_contact))
447 foreach($myconv as $conv) {
449 // now if we find a match, it means we're in this conversation
450 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_contact[0]["url"]))
453 require_once('include/enotify.php');
455 $conv_parent = $conv['parent'];
458 'type' => NOTIFY_COMMENT,
459 'notify_flags' => $user[0]['notify-flags'],
460 'language' => $user[0]['language'],
461 'to_name' => $user[0]['username'],
462 'to_email' => $user[0]['email'],
463 'uid' => $user[0]['uid'],
464 'item' => $postarray,
465 'link' => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $item,
466 'source_name' => $postarray['author-name'],
467 'source_link' => $postarray['author-link'],
468 'source_photo' => $postarray['author-avatar'],
469 'verb' => ACTIVITY_POST,
471 'parent' => $conv_parent,
474 notification($notifyarr);
476 // only send one notification
482 function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
484 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
485 dbesc("fb::".$like->post_id),
494 // If we posted the like locally, it will be found with our url, not the FB url.
496 $second_url = (($like->user_id == $self_id) ? $self[0]["url"] : $contacts[$like->user_id]->url);
498 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
499 AND (`author-link` = '%s' OR `author-link` = '%s') LIMIT 1",
500 dbesc($orig_post["uri"]),
502 dbesc(ACTIVITY_LIKE),
503 dbesc($contacts[$like->user_id]->url),
510 $contact_id = fbsync_fetch_contact($uid, $contacts[$like->user_id], array(), false);
512 if ($contact_id <= 0)
513 $contact_id = $self[0]["id"];
516 $likedata['parent'] = $orig_post['id'];
517 $likedata['verb'] = ACTIVITY_LIKE;
518 $likedata['gravity'] = 3;
519 $likedata['uid'] = $uid;
520 $likedata['wall'] = 0;
521 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
522 $likedata['parent-uri'] = $orig_post["uri"];
523 $likedata['app'] = "Facebook";
524 $likedata['verb'] = ACTIVITY_LIKE;
526 if ($like->user_id != $self_id) {
527 $likedata['contact-id'] = $contact_id;
528 $likedata['author-name'] = $contacts[$like->user_id]->name;
529 $likedata['author-link'] = $contacts[$like->user_id]->url;
530 $likedata['author-avatar'] = $contacts[$like->user_id]->pic_square;
532 $likedata['contact-id'] = $self[0]["id"];
533 $likedata['author-name'] = $self[0]["name"];
534 $likedata['author-link'] = $self[0]["url"];
535 $likedata['author-avatar'] = $self[0]["photo"];
538 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
540 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
541 $post_type = t('status');
543 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
544 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
546 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
548 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
549 '<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>';
552 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `author-link` = '%s' AND `verb` = '%s' AND `uid` = %d LIMIT 1",
553 dbesc($likedata['parent-uri']),
554 dbesc($likedata['author-link']),
555 dbesc(ACTIVITY_LIKE),
562 $item = item_store($likedata);
563 logger('fbsync_createlike: liked item '.$item.'. User '.$self[0]["nick"], LOGGER_DEBUG);
566 function fbsync_fetch_contact($uid, $contact, $create_user) {
568 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
569 intval($uid), dbesc("facebook::".$contact->id));
571 if(!count($r) AND !$create_user)
574 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
575 logger("fbsync_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
579 $avatarpicture = $contact->pic_square;
582 // create contact record
583 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
584 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
585 `writable`, `blocked`, `readonly`, `pending`)
586 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0)",
588 dbesc(datetime_convert()),
589 dbesc($contact->url),
590 dbesc(normalise_link($contact->url)),
591 dbesc($contact->username."@facebook.com"),
592 dbesc("facebook::".$contact->id),
594 dbesc("facebook::".$contact->id),
595 dbesc($contact->name),
596 dbesc($contact->username),
597 dbesc($avatarpicture),
598 dbesc(NETWORK_FACEBOOK),
599 intval(CONTACT_IS_FRIEND),
604 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
605 dbesc("facebook::".$contact->id),
612 $contact_id = $r[0]['id'];
614 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
618 if($g && intval($g[0]['def_gid'])) {
619 require_once('include/group.php');
620 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
623 require_once("Photo.php");
625 $photos = import_profile_photo($avatarpicture,$uid,$contact_id);
627 q("UPDATE `contact` SET `photo` = '%s',
637 dbesc(datetime_convert()),
638 dbesc(datetime_convert()),
639 dbesc(datetime_convert()),
643 // update profile photos once every 12 hours as we have no notification of when they change.
644 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
646 // check that we have all the photos, this has been known to fail on occasion
647 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
649 logger("fbsync_fetch_contact: Updating contact ".$contact->username, LOGGER_DEBUG);
651 require_once("Photo.php");
653 $photos = import_profile_photo($avatarpicture, $uid, $r[0]['id']);
655 q("UPDATE `contact` SET `photo` = '%s',
660 `avatar-date` = '%s',
670 dbesc(datetime_convert()),
671 dbesc(datetime_convert()),
672 dbesc(datetime_convert()),
673 dbesc($contact->url),
674 dbesc(normalise_link($contact->url)),
675 dbesc($contact->username."@facebook.com"),
676 dbesc($contact->name),
677 dbesc($contact->username),
685 function fbsync_get_self($uid) {
686 $access_token = get_pconfig($uid,'facebook','access_token');
689 $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
691 $j = json_decode($s);
692 set_pconfig($uid,'fbsync','self_id',(string) $j->id);
696 function fbsync_convertmsg($a, $body) {
699 $tags = get_tags($body);
702 foreach($tags as $tag) {
703 if (strstr(trim($tag), " "))
706 if(strpos($tag,'#') === 0) {
707 if(strpos($tag,'[url='))
710 // don't link tags that are already embedded in links
712 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
714 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
717 $basetag = str_replace('_',' ',substr($tag,1));
718 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
719 if(strlen($str_tags))
721 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
723 } elseif(strpos($tag,'@') === 0) {
724 $basetag = substr($tag,1);
725 $body = str_replace($tag,'@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
731 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
733 foreach($matches as $mtch) {
734 if(strlen($str_tags))
736 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
740 return(array("body"=>$body, "tags"=>$str_tags));
744 function fbsync_fetchuser($a, $uid, $id) {
745 $access_token = get_pconfig($uid,'facebook','access_token');
746 $self_id = get_pconfig($uid,'fbsync','self_id');
750 $contact = q("SELECT `id`, `name`, `url`, `photo` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
751 intval($uid), dbesc("facebook::".$id));
753 if (count($contact)) {
754 $user["contact-id"] = $contact[0]["id"];
755 $user["name"] = $contact[0]["name"];
756 $user["link"] = $contact[0]["url"];
757 $user["avatar"] = $contact[0]["photo"];
762 $own_contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
763 intval($uid), dbesc("facebook::".$self_id));
765 if (!count($own_contact))
768 $fql = "SELECT name, url, pic_square FROM profile WHERE id = ".$id;
770 $url = "https://graph.facebook.com/fql?q=".urlencode($fql)."&access_token=".$access_token;
772 $feed = fetch_url($url);
773 $data = json_decode($feed);
775 if (is_array($data->data)) {
776 $user["contact-id"] = $own_contact[0]["id"];
777 $user["name"] = $data->data[0]->name;
778 $user["link"] = $data->data[0]->url;
779 $user["avatar"] = $data->data[0]->pic_square;
784 function fbsync_fetchfeed($a, $uid) {
785 $access_token = get_pconfig($uid,'facebook','access_token');
786 $last_updated = get_pconfig($uid,'fbsync','last_updated');
787 $self_id = get_pconfig($uid,'fbsync','self_id');
789 $create_user = get_pconfig($uid, 'fbsync', 'create_user');
790 $do_likes = get_config('fbsync', 'do_likes');
792 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
796 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
802 require_once('include/items.php');
804 if ($last_updated == "")
807 logger("fbsync_fetchfeed: fetching content for user ".$self_id);
810 "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",
811 "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",
812 "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",
813 "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",
814 "avatars" => "SELECT id, real_size, size, url FROM square_profile_pic WHERE id IN (SELECT id FROM #profiles) AND size = 256 LIMIT 500");
817 $fql["likes"] = "SELECT post_id, user_id FROM like WHERE post_id IN (SELECT post_id FROM #posts)";
818 $fql["profiles"] .= " OR id IN (SELECT user_id FROM #likes)";
821 $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
823 $feed = fetch_url($url);
825 $data = json_decode($feed);
827 if (!is_array($data->data)) {
828 logger("fbsync_fetchfeed: Error fetching data for user ".$uid.": ".print_r($data, true));
836 $applications = array();
839 foreach($data->data AS $query) {
840 switch ($query->name) {
842 $posts = array_reverse($query->fql_result_set);
845 $comments = $query->fql_result_set;
848 $likes = $query->fql_result_set;
851 $profiles = $query->fql_result_set;
854 $applications = $query->fql_result_set;
857 $avatars = $query->fql_result_set;
862 $square_avatars = array();
864 $application_data = array();
865 $post_data = array();
866 $comment_data = array();
868 foreach ($avatars AS $avatar) {
869 $avatar->id = number_format($avatar->id, 0, '', '');
870 $square_avatars[$avatar->id] = $avatar;
874 foreach ($profiles AS $profile) {
875 $profile->id = number_format($profile->id, 0, '', '');
877 if ($square_avatars[$profile->id]->url != "")
878 $profile->pic_square = $square_avatars[$profile->id]->url;
880 $contacts[$profile->id] = $profile;
883 unset($square_avatars);
885 foreach ($applications AS $application) {
886 $application->app_id = number_format($application->app_id, 0, '', '');
887 $application_data[$application->app_id] = $application;
889 unset($applications);
891 foreach ($posts AS $post) {
892 $post->actor_id = number_format($post->actor_id, 0, '', '');
893 $post->source_id = number_format($post->source_id, 0, '', '');
894 $post->app_id = number_format($post->app_id, 0, '', '');
895 $post_data[$post->post_id] = $post;
899 foreach($comments AS $comment) {
900 $comment->fromid = number_format($comment->fromid, 0, '', '');
901 $comment_data[$comment->id] = $comment;
905 foreach ($post_data AS $post) {
906 if ($post->updated_time > $last_updated)
907 $last_updated = $post->updated_time;
909 fbsync_createpost($a, $uid, $self, $contacts, $application_data, $post, $create_user);
912 foreach ($comment_data AS $comment) {
913 fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $application_data, $comment);
916 foreach($likes AS $like) {
917 $like->user_id = number_format($like->user_id, 0, '', '');
919 fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like);
922 set_pconfig($uid,'fbsync','last_updated', $last_updated);