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');
29 register_hook('expire', 'addon/fbsync/fbsync.php', 'fbsync_expire');
32 function fbsync_uninstall() {
33 unregister_hook('connector_settings', 'addon/fbsync/fbsync.php', 'fbsync_settings');
34 unregister_hook('connector_settings_post', 'addon/fbsync/fbsync.php', 'fbsync_settings_post');
35 unregister_hook('cron', 'addon/fbsync/fbsync.php', 'fbsync_cron');
36 unregister_hook('follow', 'addon/fbsync/fbsync.php', 'fbsync_follow');
37 unregister_hook('expire', 'addon/fbsync/fbsync.php', 'fbsync_expire');
40 function fbsync_follow($a, &$contact) {
42 logger("fbsync_follow: Check if contact is facebook contact. ".$contact["url"], LOGGER_DEBUG);
44 if (!strstr($contact["url"], "://www.facebook.com") AND !strstr($contact["url"], "://facebook.com") AND !strstr($contact["url"], "@facebook.com"))
47 // contact seems to be a facebook contact, so continue
48 $nickname = preg_replace("=https?://.*facebook.com/([\w.]*).*=ism", "$1", $contact["url"]);
49 $nickname = str_replace("@facebook.com", "", $nickname);
51 $uid = $a->user["uid"];
53 $access_token = get_pconfig($uid,'facebook','access_token');
56 "profile" => "SELECT id, pic_square, url, username, name FROM profile WHERE username = '$nickname'",
57 "avatar" => "SELECT url FROM square_profile_pic WHERE id IN (SELECT id FROM #profile) AND size = 256");
59 $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
61 $feed = fetch_url($url);
62 $data = json_decode($feed);
66 logger("fbsync_follow: Query id for nickname ".$nickname, LOGGER_DEBUG);
68 if (!is_array($data->data))
71 $contactdata = new stdClass;
73 foreach($data->data AS $query) {
74 switch ($query->name) {
76 $contactdata->id = number_format($query->fql_result_set[0]->id, 0, '', '');
77 $contactdata->pic_square = $query->fql_result_set[0]->pic_square;
78 $contactdata->url = $query->fql_result_set[0]->url;
79 $contactdata->username = $query->fql_result_set[0]->username;
80 $contactdata->name = $query->fql_result_set[0]->name;
84 $contactdata->pic_square = $query->fql_result_set[0]->url;
89 logger("fbsync_follow: Got contact for nickname ".$nickname." ".print_r($contactdata, true), LOGGER_DEBUG);
92 fbsync_fetch_contact($uid, $contactdata, true);
94 $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
95 FROM `contact` WHERE `uid` = %d AND `alias` = '%s'",
97 dbesc("facebook::".$contactdata->id));
99 $contact["contact"] = $r[0];
103 function fbsync_settings(&$a,&$s) {
105 // Settings are done inside the fbpost addon
111 /* Add our stylesheet to the page so we can make our settings look nice */
113 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/fbsync/fbsync.css' . '" media="all" />' . "\r\n";
115 /* Get the current state of our config variables */
117 $enabled = get_pconfig(local_user(),'fbsync','sync');
119 $checked = (($enabled) ? ' checked="checked" ' : '');
121 $def_enabled = get_pconfig(local_user(),'fbsync','create_user');
123 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
125 /* Add some HTML to the existing form */
127 $s .= '<span id="settings_fbsync_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_fbsync_expanded\'); openClose(\'settings_fbsync_inflated\');">';
128 $s .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'. t('Facebook Import').'</h3>';
130 $s .= '<div id="settings_fbsync_expanded" class="settings-block" style="display: none;">';
131 $s .= '<span class="fakelink" onclick="openClose(\'settings_fbsync_expanded\'); openClose(\'settings_fbsync_inflated\');">';
132 $s .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'. t('Facebook Import').'</h3>';
135 $s .= '<div id="fbsync-enable-wrapper">';
136 $s .= '<label id="fbsync-enable-label" for="fbsync-checkbox">' . t('Import Facebook newsfeed') . '</label>';
137 $s .= '<input id="fbsync-checkbox" type="checkbox" name="fbsync" value="1" ' . $checked . '/>';
138 $s .= '</div><div class="clear"></div>';
140 $s .= '<div id="fbsync-create_user-wrapper">';
141 $s .= '<label id="fbsync-create_user-label" for="fbsync-create_user">' . t('Automatically create contacts') . '</label>';
142 $s .= '<input id="fbsync-create_user" type="checkbox" name="create_user" value="1" ' . $def_checked . '/>';
143 $s .= '</div><div class="clear"></div>';
145 /* provide a submit button */
147 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fbsync-submit" name="fbsync-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
151 function fbsync_settings_post(&$a,&$b) {
153 if(x($_POST,'fbsync-submit')) {
154 set_pconfig(local_user(),'fbsync','sync',intval($_POST['fbsync']));
155 set_pconfig(local_user(),'fbsync','create_user',intval($_POST['create_user']));
159 function fbsync_cron($a,$b) {
160 $last = get_config('fbsync','last_poll');
162 $poll_interval = intval(get_config('fbsync','poll_interval'));
164 $poll_interval = FBSYNC_DEFAULT_POLL_INTERVAL;
167 $next = $last + ($poll_interval * 60);
169 logger('fbsync_cron: poll intervall not reached');
173 logger('fbsync_cron: cron_start');
175 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fbsync' AND `k` = 'sync' AND `v` = '1' ORDER BY RAND()");
178 fbsync_get_self($rr['uid']);
180 logger('fbsync_cron: importing timeline from user '.$rr['uid']);
181 fbsync_fetchfeed($a, $rr['uid']);
185 logger('fbsync_cron: cron_end');
187 set_config('fbsync','last_poll', time());
190 function fbsync_expire($a,$b) {
192 $days = get_config('fbsync', 'expire');
197 $r = q("DELETE FROM `item` WHERE `deleted` AND `network` = '%s'", dbesc(NETWORK_FACEBOOK));
199 require_once("include/items.php");
201 logger('fbsync_expire: expire_start');
203 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fbsync' AND `k` = 'sync' AND `v` = '1' ORDER BY RAND()");
206 logger('fbsync_expire: user '.$rr['uid']);
207 item_expire($rr['uid'], $days, NETWORK_FACEBOOK, true);
211 logger('fbsync_expire: expire_end');
214 function fbsync_createpost($a, $uid, $self, $contacts, $applications, $post, $create_user) {
216 require_once("include/oembed.php");
218 // check if it was already imported
219 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
221 dbesc('fb::'.$post->post_id)
226 $postarray = array();
227 $postarray['gravity'] = 0;
228 $postarray['uid'] = $uid;
229 $postarray['wall'] = 0;
231 $postarray['verb'] = ACTIVITY_POST;
232 $postarray['network'] = dbesc(NETWORK_FACEBOOK);
234 $postarray['uri'] = "fb::".$post->post_id;
235 $postarray['thr-parent'] = $postarray['uri'];
236 $postarray['parent-uri'] = $postarray['uri'];
237 $postarray['plink'] = $post->permalink;
239 $postarray['author-name'] = $contacts[$post->actor_id]->name;
240 $postarray['author-link'] = $contacts[$post->actor_id]->url;
241 $postarray['author-avatar'] = $contacts[$post->actor_id]->pic_square;
243 $postarray['owner-name'] = $contacts[$post->source_id]->name;
244 $postarray['owner-link'] = $contacts[$post->source_id]->url;
245 $postarray['owner-avatar'] = $contacts[$post->source_id]->pic_square;
249 if (($post->parent_post_id != "") AND ($post->actor_id == $post->source_id)) {
250 $pos = strpos($post->parent_post_id, "_");
253 $user_id = substr($post->parent_post_id, 0, $pos);
255 $userdata = fbsync_fetchuser($a, $uid, $user_id);
257 $contact_id = $userdata["contact-id"];
259 $postarray['contact-id'] = $contact_id;
261 if (array_key_exists("name", $userdata) AND ($userdata["name"] != "") AND !link_compare($userdata["link"], $postarray['author-link'])) {
262 $postarray['owner-name'] = $userdata["name"];
263 $postarray['owner-link'] = $userdata["link"];
264 $postarray['owner-avatar'] = $userdata["avatar"];
266 if (!intval(get_config('system','wall-to-wall_share'))) {
268 $prebody = "[share author='".$postarray['author-name'].
269 "' profile='".$postarray['author-link'].
270 "' avatar='".$postarray['author-avatar']."']";
272 $postarray['author-name'] = $postarray['owner-name'];
273 $postarray['author-link'] = $postarray['owner-link'];
274 $postarray['author-avatar'] = $postarray['owner-avatar'];
280 if ($contact_id <= 0) {
282 // $contacts[$post->source_id] seems to be wrong by repeated posts
283 // must be changed in future
284 $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
286 if ($contact_id == -1) {
287 logger('fbsync_createpost: Contact is blocked. Post not imported '.print_r($post, true), LOGGER_DEBUG);
289 } elseif (($contact_id <= 0) AND !$create_user) {
290 logger('fbsync_createpost: No matching contact found. Post not imported '.print_r($post, true), LOGGER_DEBUG);
292 } elseif ($contact_id == 0) {
293 // This case should never happen
294 logger('fbsync_createpost: No matching contact found. Using own id. (Should never happen) '.print_r($post, true), LOGGER_DEBUG);
295 $contact_id = $self[0]["id"];
298 $postarray['contact-id'] = $contact_id;
301 $postarray["body"] = (isset($post->message) ? escape_tags($post->message) : '');
303 $msgdata = fbsync_convertmsg($a, $postarray["body"]);
305 $postarray["body"] = $msgdata["body"];
306 $postarray["tag"] = $msgdata["tags"];
311 if (isset($post->attachment->name) and isset($post->attachment->href)) {
312 $oembed_data = oembed_fetch_url($post->attachment->href);
313 $type = $oembed_data->type;
317 $content = "[bookmark=".$post->attachment->href."]".$post->attachment->name."[/bookmark]";
318 } elseif (isset($post->attachment->name) AND ($post->attachment->name != ""))
319 $content = "[b]" . $post->attachment->name."[/b]";
322 if(isset($post->attachment->description) and ($post->attachment->fb_object_type != "photo"))
323 $quote = $post->attachment->description;
325 if(isset($post->attachment->caption) and ($post->attachment->fb_object_type == "photo"))
326 $quote = $post->attachment->caption;
328 if ($quote.$post->attachment->href.$content.$postarray["body"] == "")
331 if (isset($post->attachment->media) // AND !strstr($post->attachment->href, "://www.youtube.com/")
332 //AND !strstr($post->attachment->href, "://youtu.be/")
333 //AND !strstr($post->attachment->href, ".vimeo.com/"))
334 AND (($type == "") OR ($type == "link"))) {
335 foreach ($post->attachment->media AS $media) {
336 //$media->photo->owner = number_format($media->photo->owner, 0, '', '');
337 //if ($media->photo->owner != '') {
338 // $postarray['author-name'] = $contacts[$media->photo->owner]->name;
339 // $postarray['author-link'] = $contacts[$media->photo->owner]->url;
340 // $postarray['author-avatar'] = $contacts[$media->photo->owner]->pic_square;
343 if (isset($media->type))
344 $type = $media->type;
346 if(isset($media->src) && isset($media->href) AND ($media->src != "") AND ($media->href != ""))
347 $content .= "\n".'[url='.$media->href.'][img]'.fpost_cleanpicture($media->src).'[/img][/url]';
349 if (isset($media->src) AND ($media->src != ""))
350 $content .= "\n".'[img]'.fpost_cleanpicture($media->src).'[/img]';
352 // if just a link, it may be a wall photo - check
353 if(isset($post->link))
354 $content .= fbpost_get_photo($media->href);
360 $postarray["body"] .= "\n";
363 $postarray["body"] .= "[class=type-".$type."]";
366 $postarray["body"] .= trim($content);
369 $postarray["body"] .= "\n[quote]".trim($quote)."[/quote]";
372 $postarray["body"] .= "[/class]";
374 $postarray["body"] = trim($postarray["body"]);
376 if (trim($postarray["body"]) == "")
380 $postarray["body"] = $prebody.$postarray["body"]."[/share]";
382 $postarray['created'] = datetime_convert('UTC','UTC',date("c", $post->created_time));
383 $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $post->updated_time));
385 $postarray['app'] = $applications[$post->app_id]->display_name;
387 if ($postarray['app'] == "")
388 $postarray['app'] = "Facebook";
390 if(isset($post->privacy) && $post->privacy->value !== '') {
391 $postarray['private'] = 1;
392 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
396 $postarray["location"] = $post->place->name;
397 postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
400 //$types = array(46, 80, 237, 247, 308);
401 //if (!in_array($post->type, $types))
402 // $postarray["body"] = "Type: ".$post->type."\n".$postarray["body"];
404 //print_r($postarray);
405 $item = item_store($postarray);
406 logger('fbsync_createpost: User '.$self[0]["nick"].' posted feed item '.$item, LOGGER_DEBUG);
409 function fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $applications, $comment) {
411 // check if it was already imported
412 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
414 dbesc('fb::'.$comment->id)
419 // check if it was an own post (separate posting for performance reasons)
420 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
422 dbesc('fb::'.$comment->id)
431 // Fetch the parent uri (Checking if the parent exists)
432 $r = q("SELECT `uri`, `contact-id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
434 dbesc('fb::'.$comment->post_id)
437 $parent_uri = $r[0]["uri"];
438 $parent_contact = $r[0]["contact-id"];
441 // check if it is a reply to an own post (separate posting for performance reasons)
442 $r = q("SELECT `uri`, `contact-id` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
444 dbesc('fb::'.$comment->post_id)
447 $parent_uri = $r[0]["uri"];
448 $parent_contact = $r[0]["contact-id"];
451 // No parent? Then quit
452 if ($parent_uri == "")
455 //logger("fbsync_createcomment: Checking if parent contact is blocked: ".$parent_contact." - ".$parent_uri, LOGGER_DEBUG);
457 // Check if the contact id was blocked
458 if ($parent_contact > 0) {
459 $r = q("SELECT `blocked`, `readonly`, `nick` FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
460 intval($uid), intval($parent_contact));
462 // Should only happen if someone deleted the contact manually
464 logger("fbsync_createcomment: UID ".$uid." - Contact ".$parent_contact." doesn't seem to exist.", LOGGER_DEBUG);
468 // Is blocked? Then return
469 if ($r[0]["readonly"] OR $r[0]["blocked"]) {
470 logger("fbsync_createcomment: UID ".$uid." - Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
474 $parent_nick = $r[0]["nick"];
475 logger("fbsync_createcomment: UID ".$uid." - Contact '".$r[0]["nick"]."' isn't blocked. ".print_r($r, true), LOGGER_DEBUG);
478 $postarray = array();
479 $postarray['gravity'] = 0;
480 $postarray['uid'] = $uid;
481 $postarray['wall'] = 0;
483 $postarray['verb'] = ACTIVITY_POST;
484 $postarray['network'] = dbesc(NETWORK_FACEBOOK);
486 $postarray['uri'] = "fb::".$comment->id;
487 $postarray['thr-parent'] = $parent_uri;
488 $postarray['parent-uri'] = $parent_uri;
489 //$postarray['plink'] = $comment->permalink;
491 $contact_id = fbsync_fetch_contact($uid, $contacts[$comment->fromid], array(), false);
493 $contact_nick = $contacts[$comment->fromid]->name;
495 if ($contact_id == -1) {
496 logger('fbsync_createcomment: Contact was blocked. Comment not imported '.print_r($comment, true), LOGGER_DEBUG);
500 // If no contact was found, take it from the thread owner
501 if ($contact_id <= 0) {
502 $contact_id = $parent_contact;
503 $contact_nick = $parent_nick;
506 // This case here should never happen
507 if ($contact_id <= 0) {
508 $contact_id = $self[0]["id"];
509 $contact_nick = $self[0]["nick"];
512 if ($comment->fromid != $self_id) {
513 $postarray['contact-id'] = $contact_id;
514 $postarray['owner-name'] = $contacts[$comment->fromid]->name;
515 $postarray['owner-link'] = $contacts[$comment->fromid]->url;
516 $postarray['owner-avatar'] = $contacts[$comment->fromid]->pic_square;
518 $postarray['contact-id'] = $self[0]["id"];
519 $postarray['owner-name'] = $self[0]["name"];
520 $postarray['owner-link'] = $self[0]["url"];
521 $postarray['owner-avatar'] = $self[0]["photo"];
522 $contact_nick = $self[0]["nick"];
525 $postarray['author-name'] = $postarray['owner-name'];
526 $postarray['author-link'] = $postarray['owner-link'];
527 $postarray['author-avatar'] = $postarray['owner-avatar'];
529 $msgdata = fbsync_convertmsg($a, $comment->text);
531 $postarray["body"] = $msgdata["body"];
532 $postarray["tag"] = $msgdata["tags"];
534 $postarray['created'] = datetime_convert('UTC','UTC',date("c", $comment->time));
535 $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $comment->time));
537 $postarray['app'] = $applications[$comment->app_id]->display_name;
539 if ($postarray['app'] == "")
540 $postarray['app'] = "Facebook";
542 if (trim($postarray["body"]) == "")
545 $item = item_store($postarray);
546 logger('fbsync_createcomment: UID '.$uid.' - CID '.$postarray['contact-id'].' - Nick '.$contact_nick.' posted comment '.$item, LOGGER_DEBUG);
551 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
552 dbesc($postarray['parent-uri']),
557 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
559 $own_contact = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
560 intval($uid), dbesc("facebook::".$self_id));
562 if (!count($own_contact))
565 foreach($myconv as $conv) {
567 // now if we find a match, it means we're in this conversation
568 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_contact[0]["url"]))
571 require_once('include/enotify.php');
573 $conv_parent = $conv['parent'];
576 'type' => NOTIFY_COMMENT,
577 'notify_flags' => $user[0]['notify-flags'],
578 'language' => $user[0]['language'],
579 'to_name' => $user[0]['username'],
580 'to_email' => $user[0]['email'],
581 'uid' => $user[0]['uid'],
582 'item' => $postarray,
583 'link' => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $item,
584 'source_name' => $postarray['author-name'],
585 'source_link' => $postarray['author-link'],
586 'source_photo' => $postarray['author-avatar'],
587 'verb' => ACTIVITY_POST,
589 'parent' => $conv_parent,
592 notification($notifyarr);
594 // only send one notification
600 function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
602 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
603 dbesc("fb::".$like->post_id),
612 // If we posted the like locally, it will be found with our url, not the FB url.
614 $second_url = (($like->user_id == $self_id) ? $self[0]["url"] : $contacts[$like->user_id]->url);
616 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
617 AND (`author-link` = '%s' OR `author-link` = '%s') LIMIT 1",
618 dbesc($orig_post["uri"]),
620 dbesc(ACTIVITY_LIKE),
621 dbesc($contacts[$like->user_id]->url),
628 $contact_id = fbsync_fetch_contact($uid, $contacts[$like->user_id], array(), false);
630 if ($contact_id <= 0)
631 $contact_id = $self[0]["id"];
634 $likedata['parent'] = $orig_post['id'];
635 $likedata['verb'] = ACTIVITY_LIKE;
636 $likedate['network'] = dbesc(NETWORK_FACEBOOK);
637 $likedata['gravity'] = 3;
638 $likedata['uid'] = $uid;
639 $likedata['wall'] = 0;
640 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
641 $likedata['parent-uri'] = $orig_post["uri"];
642 $likedata['app'] = "Facebook";
644 if ($like->user_id != $self_id) {
645 $likedata['contact-id'] = $contact_id;
646 $likedata['author-name'] = $contacts[$like->user_id]->name;
647 $likedata['author-link'] = $contacts[$like->user_id]->url;
648 $likedata['author-avatar'] = $contacts[$like->user_id]->pic_square;
650 $likedata['contact-id'] = $self[0]["id"];
651 $likedata['author-name'] = $self[0]["name"];
652 $likedata['author-link'] = $self[0]["url"];
653 $likedata['author-avatar'] = $self[0]["photo"];
656 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
658 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
659 $post_type = t('status');
661 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
662 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
664 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
666 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
667 '<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>';
670 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `author-link` = '%s' AND `verb` = '%s' AND `uid` = %d LIMIT 1",
671 dbesc($likedata['parent-uri']),
672 dbesc($likedata['author-link']),
673 dbesc(ACTIVITY_LIKE),
680 $item = item_store($likedata);
681 logger('fbsync_createlike: liked item '.$item.'. User '.$self[0]["nick"], LOGGER_DEBUG);
684 function fbsync_fetch_contact($uid, $contact, $create_user) {
686 // Check if the unique contact is existing
687 // To-Do: only update once a while
688 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
689 dbesc(normalise_link($contact->url)));
692 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
693 dbesc(normalise_link($contact->url)),
694 dbesc($contact->name),
695 dbesc($contact->username),
696 dbesc($contact->pic_square));
698 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
699 dbesc($contact->name),
700 dbesc($contact->username),
701 dbesc($contact->pic_square),
702 dbesc(normalise_link($contact->url)));
704 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
705 intval($uid), dbesc("facebook::".$contact->id));
707 if(!count($r) AND !$create_user)
710 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
711 logger("fbsync_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
715 $avatarpicture = $contact->pic_square;
718 // create contact record
719 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
720 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
721 `writable`, `blocked`, `readonly`, `pending`)
722 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0)",
724 dbesc(datetime_convert()),
725 dbesc($contact->url),
726 dbesc(normalise_link($contact->url)),
727 dbesc($contact->username."@facebook.com"),
728 dbesc("facebook::".$contact->id),
730 dbesc("facebook::".$contact->id),
731 dbesc($contact->name),
732 dbesc($contact->username),
733 dbesc($avatarpicture),
734 dbesc(NETWORK_FACEBOOK),
735 intval(CONTACT_IS_FRIEND),
740 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
741 dbesc("facebook::".$contact->id),
748 $contact_id = $r[0]['id'];
750 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
754 if($g && intval($g[0]['def_gid'])) {
755 require_once('include/group.php');
756 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
759 require_once("Photo.php");
761 $photos = import_profile_photo($avatarpicture,$uid,$contact_id);
763 q("UPDATE `contact` SET `photo` = '%s',
773 dbesc(datetime_convert()),
774 dbesc(datetime_convert()),
775 dbesc(datetime_convert()),
779 // update profile photos once every 12 hours as we have no notification of when they change.
780 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
782 // check that we have all the photos, this has been known to fail on occasion
783 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
785 logger("fbsync_fetch_contact: Updating contact ".$contact->username, LOGGER_DEBUG);
787 require_once("Photo.php");
789 $photos = import_profile_photo($avatarpicture, $uid, $r[0]['id']);
791 q("UPDATE `contact` SET `photo` = '%s',
796 `avatar-date` = '%s',
807 dbesc(datetime_convert()),
808 dbesc(datetime_convert()),
809 dbesc(datetime_convert()),
810 dbesc($contact->url),
811 dbesc(normalise_link($contact->url)),
812 dbesc($contact->username."@facebook.com"),
813 dbesc($contact->name),
814 dbesc($contact->username),
823 function fbsync_get_self($uid) {
824 $access_token = get_pconfig($uid,'facebook','access_token');
827 $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
829 $j = json_decode($s);
830 set_pconfig($uid,'fbsync','self_id',(string) $j->id);
834 function fbsync_convertmsg($a, $body) {
837 $tags = get_tags($body);
840 foreach($tags as $tag) {
841 if (strstr(trim($tag), " "))
844 if(strpos($tag,'#') === 0) {
845 if(strpos($tag,'[url='))
848 // don't link tags that are already embedded in links
850 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
852 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
855 $basetag = str_replace('_',' ',substr($tag,1));
856 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
857 if(strlen($str_tags))
859 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
861 } elseif(strpos($tag,'@') === 0) {
862 $basetag = substr($tag,1);
863 $body = str_replace($tag,'@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
869 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
871 foreach($matches as $mtch) {
872 if(strlen($str_tags))
874 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
878 return(array("body"=>$body, "tags"=>$str_tags));
882 function fbsync_fetchuser($a, $uid, $id) {
883 $access_token = get_pconfig($uid,'facebook','access_token');
884 $self_id = get_pconfig($uid,'fbsync','self_id');
888 $contact = q("SELECT `id`, `name`, `url`, `photo` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
889 intval($uid), dbesc("facebook::".$id));
891 if (count($contact)) {
892 if (($contact[0]["readonly"] OR $contact[0]["blocked"])) {
893 logger("fbsync_fetchuser: Contact '".$contact[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
894 $user["contact-id"] = -1;
896 $user["contact-id"] = $contact[0]["id"];
898 $user["name"] = $contact[0]["name"];
899 $user["link"] = $contact[0]["url"];
900 $user["avatar"] = $contact[0]["photo"];
905 $own_contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
906 intval($uid), dbesc("facebook::".$self_id));
908 if (!count($own_contact))
911 $fql = "SELECT name, url, pic_square FROM profile WHERE id = ".$id;
913 $url = "https://graph.facebook.com/fql?q=".urlencode($fql)."&access_token=".$access_token;
915 $feed = fetch_url($url);
916 $data = json_decode($feed);
918 if (is_array($data->data)) {
919 $user["contact-id"] = $own_contact[0]["id"];
920 $user["name"] = $data->data[0]->name;
921 $user["link"] = $data->data[0]->url;
922 $user["avatar"] = $data->data[0]->pic_square;
927 function fbsync_fetchfeed($a, $uid) {
928 $access_token = get_pconfig($uid,'facebook','access_token');
929 $last_updated = get_pconfig($uid,'fbsync','last_updated');
930 $self_id = get_pconfig($uid,'fbsync','self_id');
932 $create_user = get_pconfig($uid, 'fbsync', 'create_user');
933 $do_likes = get_config('fbsync', 'do_likes');
935 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
939 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
945 require_once('include/items.php');
947 //if ($last_updated == "")
950 logger("fbsync_fetchfeed: fetching content for user ".$self_id);
953 "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",
954 "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",
955 "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",
956 "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",
957 "avatars" => "SELECT id, real_size, size, url FROM square_profile_pic WHERE id IN (SELECT id FROM #profiles) AND size = 256 LIMIT 500");
960 $fql["likes"] = "SELECT post_id, user_id FROM like WHERE post_id IN (SELECT post_id FROM #posts)";
961 $fql["profiles"] .= " OR id IN (SELECT user_id FROM #likes)";
964 $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
966 $feed = fetch_url($url);
967 $data = json_decode($feed);
969 if (!is_array($data->data)) {
970 logger("fbsync_fetchfeed: Error fetching data for user ".$uid.": ".print_r($data, true));
978 $applications = array();
981 foreach($data->data AS $query) {
982 switch ($query->name) {
984 $posts = array_reverse($query->fql_result_set);
987 $comments = $query->fql_result_set;
990 $likes = $query->fql_result_set;
993 $profiles = $query->fql_result_set;
996 $applications = $query->fql_result_set;
999 $avatars = $query->fql_result_set;
1004 $square_avatars = array();
1005 $contacts = array();
1006 $application_data = array();
1007 $post_data = array();
1008 $comment_data = array();
1010 foreach ($avatars AS $avatar) {
1011 $avatar->id = number_format($avatar->id, 0, '', '');
1012 $square_avatars[$avatar->id] = $avatar;
1016 foreach ($profiles AS $profile) {
1017 $profile->id = number_format($profile->id, 0, '', '');
1019 if ($square_avatars[$profile->id]->url != "")
1020 $profile->pic_square = $square_avatars[$profile->id]->url;
1022 $contacts[$profile->id] = $profile;
1025 unset($square_avatars);
1027 foreach ($applications AS $application) {
1028 $application->app_id = number_format($application->app_id, 0, '', '');
1029 $application_data[$application->app_id] = $application;
1031 unset($applications);
1033 foreach ($posts AS $post) {
1034 $post->actor_id = number_format($post->actor_id, 0, '', '');
1035 $post->source_id = number_format($post->source_id, 0, '', '');
1036 $post->app_id = number_format($post->app_id, 0, '', '');
1037 $post_data[$post->post_id] = $post;
1041 foreach($comments AS $comment) {
1042 $comment->fromid = number_format($comment->fromid, 0, '', '');
1043 $comment_data[$comment->id] = $comment;
1047 foreach ($post_data AS $post) {
1048 if ($post->updated_time > $last_updated)
1049 $last_updated = $post->updated_time;
1050 fbsync_createpost($a, $uid, $self, $contacts, $application_data, $post, $create_user);
1053 foreach ($comment_data AS $comment) {
1054 fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $application_data, $comment);
1057 foreach($likes AS $like) {
1058 $like->user_id = number_format($like->user_id, 0, '', '');
1060 fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like);
1063 set_pconfig($uid,'fbsync','last_updated', $last_updated);