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) {
103 // Settings are done inside the fbpost addon
109 /* Add our stylesheet to the page so we can make our settings look nice */
111 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/fbsync/fbsync.css' . '" media="all" />' . "\r\n";
113 /* Get the current state of our config variables */
115 $enabled = get_pconfig(local_user(),'fbsync','sync');
117 $checked = (($enabled) ? ' checked="checked" ' : '');
119 $def_enabled = get_pconfig(local_user(),'fbsync','create_user');
121 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
123 /* Add some HTML to the existing form */
125 $s .= '<span id="settings_fbsync_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_fbsync_expanded\'); openClose(\'settings_fbsync_inflated\');">';
126 $s .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'. t('Facebook Import').'</h3>';
128 $s .= '<div id="settings_fbsync_expanded" class="settings-block" style="display: none;">';
129 $s .= '<span class="fakelink" onclick="openClose(\'settings_fbsync_expanded\'); openClose(\'settings_fbsync_inflated\');">';
130 $s .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'. t('Facebook Import').'</h3>';
133 $s .= '<div id="fbsync-enable-wrapper">';
134 $s .= '<label id="fbsync-enable-label" for="fbsync-checkbox">' . t('Import Facebook newsfeed') . '</label>';
135 $s .= '<input id="fbsync-checkbox" type="checkbox" name="fbsync" value="1" ' . $checked . '/>';
136 $s .= '</div><div class="clear"></div>';
138 $s .= '<div id="fbsync-create_user-wrapper">';
139 $s .= '<label id="fbsync-create_user-label" for="fbsync-create_user">' . t('Automatically create contacts') . '</label>';
140 $s .= '<input id="fbsync-create_user" type="checkbox" name="create_user" value="1" ' . $def_checked . '/>';
141 $s .= '</div><div class="clear"></div>';
143 /* provide a submit button */
145 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fbsync-submit" name="fbsync-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
149 function fbsync_settings_post(&$a,&$b) {
151 if(x($_POST,'fbsync-submit')) {
152 set_pconfig(local_user(),'fbsync','sync',intval($_POST['fbsync']));
153 set_pconfig(local_user(),'fbsync','create_user',intval($_POST['create_user']));
157 function fbsync_cron($a,$b) {
158 $last = get_config('fbsync','last_poll');
160 $poll_interval = intval(get_config('fbsync','poll_interval'));
162 $poll_interval = FBSYNC_DEFAULT_POLL_INTERVAL;
165 $next = $last + ($poll_interval * 60);
167 logger('fbsync_cron: poll intervall not reached');
171 logger('fbsync_cron: cron_start');
173 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fbsync' AND `k` = 'sync' AND `v` = '1' ORDER BY RAND()");
176 fbsync_get_self($rr['uid']);
178 logger('fbsync_cron: importing timeline from user '.$rr['uid']);
179 fbsync_fetchfeed($a, $rr['uid']);
183 logger('fbsync_cron: cron_end');
185 set_config('fbsync','last_poll', time());
188 function fbsync_createpost($a, $uid, $self, $contacts, $applications, $post, $create_user) {
190 require_once("include/oembed.php");
192 // check if it was already imported
193 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
195 dbesc('fb::'.$post->post_id)
200 $postarray = array();
201 $postarray['gravity'] = 0;
202 $postarray['uid'] = $uid;
203 $postarray['wall'] = 0;
205 $postarray['verb'] = ACTIVITY_POST;
206 $postarray['network'] = dbesc(NETWORK_FACEBOOK);
208 $postarray['uri'] = "fb::".$post->post_id;
209 $postarray['thr-parent'] = $postarray['uri'];
210 $postarray['parent-uri'] = $postarray['uri'];
211 $postarray['plink'] = $post->permalink;
213 $postarray['author-name'] = $contacts[$post->actor_id]->name;
214 $postarray['author-link'] = $contacts[$post->actor_id]->url;
215 $postarray['author-avatar'] = $contacts[$post->actor_id]->pic_square;
217 $postarray['owner-name'] = $contacts[$post->source_id]->name;
218 $postarray['owner-link'] = $contacts[$post->source_id]->url;
219 $postarray['owner-avatar'] = $contacts[$post->source_id]->pic_square;
223 if (($post->parent_post_id != "") AND ($post->actor_id == $post->source_id)) {
224 $pos = strpos($post->parent_post_id, "_");
227 $user_id = substr($post->parent_post_id, 0, $pos);
229 $userdata = fbsync_fetchuser($a, $uid, $user_id);
231 $contact_id = $userdata["contact-id"];
233 $postarray['contact-id'] = $contact_id;
235 if (array_key_exists("name", $userdata) AND ($userdata["name"] != "") AND !link_compare($userdata["link"], $postarray['author-link'])) {
236 $postarray['owner-name'] = $userdata["name"];
237 $postarray['owner-link'] = $userdata["link"];
238 $postarray['owner-avatar'] = $userdata["avatar"];
240 if (!intval(get_config('system','wall-to-wall_share'))) {
242 $prebody = "[share author='".$postarray['author-name'].
243 "' profile='".$postarray['author-link'].
244 "' avatar='".$postarray['author-avatar']."']";
246 $postarray['author-name'] = $postarray['owner-name'];
247 $postarray['author-link'] = $postarray['owner-link'];
248 $postarray['author-avatar'] = $postarray['owner-avatar'];
254 if ($contact_id <= 0) {
255 $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
257 if ($contact_id == -1) {
258 logger('fbsync_createpost: Contact is blocked. Post not imported '.print_r($post, true), LOGGER_DEBUG);
260 } elseif (($contact_id <= 0) AND !$create_user) {
261 logger('fbsync_createpost: No matching contact found. Post not imported '.print_r($post, true), LOGGER_DEBUG);
263 } elseif ($contact_id == 0) {
264 // This case should never happen
265 logger('fbsync_createpost: No matching contact found. Using own id. (Should never happen) '.print_r($post, true), LOGGER_DEBUG);
266 $contact_id = $self[0]["id"];
269 $postarray['contact-id'] = $contact_id;
272 $postarray["body"] = (isset($post->message) ? escape_tags($post->message) : '');
274 $msgdata = fbsync_convertmsg($a, $postarray["body"]);
276 $postarray["body"] = $msgdata["body"];
277 $postarray["tag"] = $msgdata["tags"];
282 if (isset($post->attachment->name) and isset($post->attachment->href)) {
283 $oembed_data = oembed_fetch_url($post->attachment->href);
284 $type = $oembed_data->type;
285 $content = "[bookmark=".$post->attachment->href."]".$post->attachment->name."[/bookmark]";
286 } elseif (isset($post->attachment->name) AND ($post->attachment->name != ""))
287 $content = "[b]" . $post->attachment->name."[/b]";
290 if(isset($post->attachment->description) and ($post->attachment->fb_object_type != "photo"))
291 $quote = $post->attachment->description;
293 if(isset($post->attachment->caption) and ($post->attachment->fb_object_type == "photo"))
294 $quote = $post->attachment->caption;
296 if ($quote.$post->attachment->href.$content.$postarray["body"] == "")
299 if (isset($post->attachment->media) // AND !strstr($post->attachment->href, "://www.youtube.com/")
300 //AND !strstr($post->attachment->href, "://youtu.be/")
301 //AND !strstr($post->attachment->href, ".vimeo.com/"))
302 AND (($type == "") OR ($type == "link"))) {
303 foreach ($post->attachment->media AS $media) {
304 //$media->photo->owner = number_format($media->photo->owner, 0, '', '');
305 //if ($media->photo->owner != '') {
306 // $postarray['author-name'] = $contacts[$media->photo->owner]->name;
307 // $postarray['author-link'] = $contacts[$media->photo->owner]->url;
308 // $postarray['author-avatar'] = $contacts[$media->photo->owner]->pic_square;
311 if (isset($media->type))
312 $type = $media->type;
314 if(isset($media->src) && isset($media->href) AND ($media->src != "") AND ($media->href != ""))
315 $content .= "\n".'[url='.$media->href.'][img]'.fpost_cleanpicture($media->src).'[/img][/url]';
317 if (isset($media->src) AND ($media->src != ""))
318 $content .= "\n".'[img]'.fpost_cleanpicture($media->src).'[/img]';
320 // if just a link, it may be a wall photo - check
321 if(isset($post->link))
322 $content .= fbpost_get_photo($media->href);
328 $postarray["body"] .= "\n";
331 $postarray["body"] .= "[class=type-".$type."]";
334 $postarray["body"] .= trim($content);
337 $postarray["body"] .= "\n[quote]".trim($quote)."[/quote]";
340 $postarray["body"] .= "[/class]";
342 $postarray["body"] = trim($postarray["body"]);
344 if (trim($postarray["body"]) == "")
348 $postarray["body"] = $prebody.$postarray["body"]."[/share]";
350 $postarray['created'] = datetime_convert('UTC','UTC',date("c", $post->created_time));
351 $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $post->updated_time));
353 $postarray['app'] = $applications[$post->app_id]->display_name;
355 if ($postarray['app'] == "")
356 $postarray['app'] = "Facebook";
358 if(isset($post->privacy) && $post->privacy->value !== '') {
359 $postarray['private'] = 1;
360 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
364 $postarray["location"] = $post->place->name;
365 postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
368 //$types = array(46, 80, 237, 247, 308);
369 //if (!in_array($post->type, $types))
370 // $postarray["body"] = "Type: ".$post->type."\n".$postarray["body"];
372 //print_r($postarray);
374 $item = item_store($postarray);
375 logger('fbsync_createpost: User '.$self[0]["nick"].' posted feed item '.$item, LOGGER_DEBUG);
378 function fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $applications, $comment) {
380 // check if it was already imported
381 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
383 dbesc('fb::'.$comment->id)
388 // check if it was an own post (separate posting for performance reasons)
389 $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
391 dbesc('fb::'.$comment->id)
400 // Fetch the parent uri (Checking if the parent exists)
401 $r = q("SELECT `uri`, `contact-id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
403 dbesc('fb::'.$comment->post_id)
406 $parent_uri = $r[0]["uri"];
407 $parent_contact = $r[0]["contact-id"];
410 // check if it is a reply to an own post (separate posting for performance reasons)
411 $r = q("SELECT `uri`, `contact-id` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
413 dbesc('fb::'.$comment->post_id)
416 $parent_uri = $r[0]["uri"];
417 $parent_contact = $r[0]["contact-id"];
420 // No parent? Then quit
421 if ($parent_uri == "")
424 //logger("fbsync_createcomment: Checking if parent contact is blocked: ".$parent_contact." - ".$parent_uri, LOGGER_DEBUG);
426 // Check if the contact id was blocked
427 if ($parent_contact > 0) {
428 $r = q("SELECT `blocked`, `readonly`, `nick` FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
429 intval($uid), intval($parent_contact));
431 // Should only happen if someone deleted the contact manually
433 logger("fbsync_createcomment: UID ".$uid." - Contact ".$parent_contact." doesn't seem to exist.", LOGGER_DEBUG);
437 // Is blocked? Then return
438 if ($r[0]["readonly"] OR $r[0]["blocked"]) {
439 logger("fbsync_createcomment: UID ".$uid." - Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
443 $parent_nick = $r[0]["nick"];
444 logger("fbsync_createcomment: UID ".$uid." - Contact '".$r[0]["nick"]."' isn't blocked. ".print_r($r, true), LOGGER_DEBUG);
447 $postarray = array();
448 $postarray['gravity'] = 0;
449 $postarray['uid'] = $uid;
450 $postarray['wall'] = 0;
452 $postarray['verb'] = ACTIVITY_POST;
453 $postarray['network'] = dbesc(NETWORK_FACEBOOK);
455 $postarray['uri'] = "fb::".$comment->id;
456 $postarray['thr-parent'] = $parent_uri;
457 $postarray['parent-uri'] = $parent_uri;
458 //$postarray['plink'] = $comment->permalink;
460 $contact_id = fbsync_fetch_contact($uid, $contacts[$comment->fromid], array(), false);
462 $contact_nick = $contacts[$comment->fromid]->name;
464 if ($contact_id == -1) {
465 logger('fbsync_createcomment: Contact was blocked. Comment not imported '.print_r($comment, true), LOGGER_DEBUG);
469 // If no contact was found, take it from the thread owner
470 if ($contact_id <= 0) {
471 $contact_id = $parent_contact;
472 $contact_nick = $parent_nick;
475 // This case here should never happen
476 if ($contact_id <= 0) {
477 $contact_id = $self[0]["id"];
478 $contact_nick = $self[0]["nick"];
481 if ($comment->fromid != $self_id) {
482 $postarray['contact-id'] = $contact_id;
483 $postarray['owner-name'] = $contacts[$comment->fromid]->name;
484 $postarray['owner-link'] = $contacts[$comment->fromid]->url;
485 $postarray['owner-avatar'] = $contacts[$comment->fromid]->pic_square;
487 $postarray['contact-id'] = $self[0]["id"];
488 $postarray['owner-name'] = $self[0]["name"];
489 $postarray['owner-link'] = $self[0]["url"];
490 $postarray['owner-avatar'] = $self[0]["photo"];
491 $contact_nick = $self[0]["nick"];
494 $postarray['author-name'] = $postarray['owner-name'];
495 $postarray['author-link'] = $postarray['owner-link'];
496 $postarray['author-avatar'] = $postarray['owner-avatar'];
498 $msgdata = fbsync_convertmsg($a, $comment->text);
500 $postarray["body"] = $msgdata["body"];
501 $postarray["tag"] = $msgdata["tags"];
503 $postarray['created'] = datetime_convert('UTC','UTC',date("c", $comment->time));
504 $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $comment->time));
506 $postarray['app'] = $applications[$comment->app_id]->display_name;
508 if ($postarray['app'] == "")
509 $postarray['app'] = "Facebook";
511 if (trim($postarray["body"]) == "")
514 $item = item_store($postarray);
515 logger('fbsync_createcomment: UID '.$uid.' - CID '.$postarray['contact-id'].' - Nick '.$contact_nick.' posted comment '.$item, LOGGER_DEBUG);
520 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
521 dbesc($postarray['parent-uri']),
526 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
528 $own_contact = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
529 intval($uid), dbesc("facebook::".$self_id));
531 if (!count($own_contact))
534 foreach($myconv as $conv) {
536 // now if we find a match, it means we're in this conversation
537 if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_contact[0]["url"]))
540 require_once('include/enotify.php');
542 $conv_parent = $conv['parent'];
545 'type' => NOTIFY_COMMENT,
546 'notify_flags' => $user[0]['notify-flags'],
547 'language' => $user[0]['language'],
548 'to_name' => $user[0]['username'],
549 'to_email' => $user[0]['email'],
550 'uid' => $user[0]['uid'],
551 'item' => $postarray,
552 'link' => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $item,
553 'source_name' => $postarray['author-name'],
554 'source_link' => $postarray['author-link'],
555 'source_photo' => $postarray['author-avatar'],
556 'verb' => ACTIVITY_POST,
558 'parent' => $conv_parent,
561 notification($notifyarr);
563 // only send one notification
569 function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
571 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
572 dbesc("fb::".$like->post_id),
581 // If we posted the like locally, it will be found with our url, not the FB url.
583 $second_url = (($like->user_id == $self_id) ? $self[0]["url"] : $contacts[$like->user_id]->url);
585 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
586 AND (`author-link` = '%s' OR `author-link` = '%s') LIMIT 1",
587 dbesc($orig_post["uri"]),
589 dbesc(ACTIVITY_LIKE),
590 dbesc($contacts[$like->user_id]->url),
597 $contact_id = fbsync_fetch_contact($uid, $contacts[$like->user_id], array(), false);
599 if ($contact_id <= 0)
600 $contact_id = $self[0]["id"];
603 $likedata['parent'] = $orig_post['id'];
604 $likedata['verb'] = ACTIVITY_LIKE;
605 $likedate['network'] = dbesc(NETWORK_FACEBOOK);
606 $likedata['gravity'] = 3;
607 $likedata['uid'] = $uid;
608 $likedata['wall'] = 0;
609 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
610 $likedata['parent-uri'] = $orig_post["uri"];
611 $likedata['app'] = "Facebook";
613 if ($like->user_id != $self_id) {
614 $likedata['contact-id'] = $contact_id;
615 $likedata['author-name'] = $contacts[$like->user_id]->name;
616 $likedata['author-link'] = $contacts[$like->user_id]->url;
617 $likedata['author-avatar'] = $contacts[$like->user_id]->pic_square;
619 $likedata['contact-id'] = $self[0]["id"];
620 $likedata['author-name'] = $self[0]["name"];
621 $likedata['author-link'] = $self[0]["url"];
622 $likedata['author-avatar'] = $self[0]["photo"];
625 $author = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
627 $objauthor = '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
628 $post_type = t('status');
630 $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
631 $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
633 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
635 $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
636 '<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>';
639 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `author-link` = '%s' AND `verb` = '%s' AND `uid` = %d LIMIT 1",
640 dbesc($likedata['parent-uri']),
641 dbesc($likedata['author-link']),
642 dbesc(ACTIVITY_LIKE),
649 $item = item_store($likedata);
650 logger('fbsync_createlike: liked item '.$item.'. User '.$self[0]["nick"], LOGGER_DEBUG);
653 function fbsync_fetch_contact($uid, $contact, $create_user) {
655 // Check if the unique contact is existing
656 // To-Do: only update once a while
657 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
658 dbesc(normalise_link($contact->url)));
661 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
662 dbesc(normalise_link($contact->url)),
663 dbesc($contact->name),
664 dbesc($contact->username),
665 dbesc($contact->pic_square));
667 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
668 dbesc($contact->name),
669 dbesc($contact->username),
670 dbesc($contact->pic_square),
671 dbesc(normalise_link($contact->url)));
673 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
674 intval($uid), dbesc("facebook::".$contact->id));
676 if(!count($r) AND !$create_user)
679 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
680 logger("fbsync_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
684 $avatarpicture = $contact->pic_square;
687 // create contact record
688 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
689 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
690 `writable`, `blocked`, `readonly`, `pending`)
691 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0)",
693 dbesc(datetime_convert()),
694 dbesc($contact->url),
695 dbesc(normalise_link($contact->url)),
696 dbesc($contact->username."@facebook.com"),
697 dbesc("facebook::".$contact->id),
699 dbesc("facebook::".$contact->id),
700 dbesc($contact->name),
701 dbesc($contact->username),
702 dbesc($avatarpicture),
703 dbesc(NETWORK_FACEBOOK),
704 intval(CONTACT_IS_FRIEND),
709 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
710 dbesc("facebook::".$contact->id),
717 $contact_id = $r[0]['id'];
719 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
723 if($g && intval($g[0]['def_gid'])) {
724 require_once('include/group.php');
725 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
728 require_once("Photo.php");
730 $photos = import_profile_photo($avatarpicture,$uid,$contact_id);
732 q("UPDATE `contact` SET `photo` = '%s',
742 dbesc(datetime_convert()),
743 dbesc(datetime_convert()),
744 dbesc(datetime_convert()),
748 // update profile photos once every 12 hours as we have no notification of when they change.
749 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
751 // check that we have all the photos, this has been known to fail on occasion
752 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
754 logger("fbsync_fetch_contact: Updating contact ".$contact->username, LOGGER_DEBUG);
756 require_once("Photo.php");
758 $photos = import_profile_photo($avatarpicture, $uid, $r[0]['id']);
760 q("UPDATE `contact` SET `photo` = '%s',
765 `avatar-date` = '%s',
776 dbesc(datetime_convert()),
777 dbesc(datetime_convert()),
778 dbesc(datetime_convert()),
779 dbesc($contact->url),
780 dbesc(normalise_link($contact->url)),
781 dbesc($contact->username."@facebook.com"),
782 dbesc($contact->name),
783 dbesc($contact->username),
792 function fbsync_get_self($uid) {
793 $access_token = get_pconfig($uid,'facebook','access_token');
796 $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
798 $j = json_decode($s);
799 set_pconfig($uid,'fbsync','self_id',(string) $j->id);
803 function fbsync_convertmsg($a, $body) {
806 $tags = get_tags($body);
809 foreach($tags as $tag) {
810 if (strstr(trim($tag), " "))
813 if(strpos($tag,'#') === 0) {
814 if(strpos($tag,'[url='))
817 // don't link tags that are already embedded in links
819 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
821 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
824 $basetag = str_replace('_',' ',substr($tag,1));
825 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
826 if(strlen($str_tags))
828 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
830 } elseif(strpos($tag,'@') === 0) {
831 $basetag = substr($tag,1);
832 $body = str_replace($tag,'@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
838 $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
840 foreach($matches as $mtch) {
841 if(strlen($str_tags))
843 $str_tags .= '@[url=' . $mtch[1] . '[/url]';
847 return(array("body"=>$body, "tags"=>$str_tags));
851 function fbsync_fetchuser($a, $uid, $id) {
852 $access_token = get_pconfig($uid,'facebook','access_token');
853 $self_id = get_pconfig($uid,'fbsync','self_id');
857 $contact = q("SELECT `id`, `name`, `url`, `photo` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
858 intval($uid), dbesc("facebook::".$id));
860 if (count($contact)) {
861 if (($contact[0]["readonly"] OR $contact[0]["blocked"])) {
862 logger("fbsync_fetchuser: Contact '".$contact[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
863 $user["contact-id"] = -1;
865 $user["contact-id"] = $contact[0]["id"];
867 $user["name"] = $contact[0]["name"];
868 $user["link"] = $contact[0]["url"];
869 $user["avatar"] = $contact[0]["photo"];
874 $own_contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
875 intval($uid), dbesc("facebook::".$self_id));
877 if (!count($own_contact))
880 $fql = "SELECT name, url, pic_square FROM profile WHERE id = ".$id;
882 $url = "https://graph.facebook.com/fql?q=".urlencode($fql)."&access_token=".$access_token;
884 $feed = fetch_url($url);
885 $data = json_decode($feed);
887 if (is_array($data->data)) {
888 $user["contact-id"] = $own_contact[0]["id"];
889 $user["name"] = $data->data[0]->name;
890 $user["link"] = $data->data[0]->url;
891 $user["avatar"] = $data->data[0]->pic_square;
896 function fbsync_fetchfeed($a, $uid) {
897 $access_token = get_pconfig($uid,'facebook','access_token');
898 $last_updated = get_pconfig($uid,'fbsync','last_updated');
899 $self_id = get_pconfig($uid,'fbsync','self_id');
901 $create_user = get_pconfig($uid, 'fbsync', 'create_user');
902 $do_likes = get_config('fbsync', 'do_likes');
904 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
908 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
914 require_once('include/items.php');
916 //if ($last_updated == "")
919 logger("fbsync_fetchfeed: fetching content for user ".$self_id);
922 "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",
923 "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",
924 "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",
925 "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",
926 "avatars" => "SELECT id, real_size, size, url FROM square_profile_pic WHERE id IN (SELECT id FROM #profiles) AND size = 256 LIMIT 500");
929 $fql["likes"] = "SELECT post_id, user_id FROM like WHERE post_id IN (SELECT post_id FROM #posts)";
930 $fql["profiles"] .= " OR id IN (SELECT user_id FROM #likes)";
933 $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
935 $feed = fetch_url($url);
936 //file_put_contents("/home/ike/pirati.ca/htdocs/fb.".$uid, $feed);
937 $data = json_decode($feed);
939 if (!is_array($data->data)) {
940 logger("fbsync_fetchfeed: Error fetching data for user ".$uid.": ".print_r($data, true));
948 $applications = array();
951 foreach($data->data AS $query) {
952 switch ($query->name) {
954 $posts = array_reverse($query->fql_result_set);
957 $comments = $query->fql_result_set;
960 $likes = $query->fql_result_set;
963 $profiles = $query->fql_result_set;
966 $applications = $query->fql_result_set;
969 $avatars = $query->fql_result_set;
974 $square_avatars = array();
976 $application_data = array();
977 $post_data = array();
978 $comment_data = array();
980 foreach ($avatars AS $avatar) {
981 $avatar->id = number_format($avatar->id, 0, '', '');
982 $square_avatars[$avatar->id] = $avatar;
986 foreach ($profiles AS $profile) {
987 $profile->id = number_format($profile->id, 0, '', '');
989 if ($square_avatars[$profile->id]->url != "")
990 $profile->pic_square = $square_avatars[$profile->id]->url;
992 $contacts[$profile->id] = $profile;
995 unset($square_avatars);
997 foreach ($applications AS $application) {
998 $application->app_id = number_format($application->app_id, 0, '', '');
999 $application_data[$application->app_id] = $application;
1001 unset($applications);
1003 foreach ($posts AS $post) {
1004 $post->actor_id = number_format($post->actor_id, 0, '', '');
1005 $post->source_id = number_format($post->source_id, 0, '', '');
1006 $post->app_id = number_format($post->app_id, 0, '', '');
1007 $post_data[$post->post_id] = $post;
1011 foreach($comments AS $comment) {
1012 $comment->fromid = number_format($comment->fromid, 0, '', '');
1013 $comment_data[$comment->id] = $comment;
1017 foreach ($post_data AS $post) {
1018 if ($post->updated_time > $last_updated)
1019 $last_updated = $post->updated_time;
1021 fbsync_createpost($a, $uid, $self, $contacts, $application_data, $post, $create_user);
1024 foreach ($comment_data AS $comment) {
1025 fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $application_data, $comment);
1028 foreach($likes AS $like) {
1029 $like->user_id = number_format($like->user_id, 0, '', '');
1031 fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like);
1034 set_pconfig($uid,'fbsync','last_updated', $last_updated);