]> git.mxchange.org Git - friendica-addons.git/blob - fbsync/fbsync.php
fbsync: Shared posts
[friendica-addons.git] / fbsync / fbsync.php
1 <?php
2 /**
3  * Name: Facebook Sync
4  * Description: Synchronizes the Facebook Newsfeed
5  * Version: 0.0.1 alpha
6  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
7  */
8
9 /* To-Do
10 FBSync:
11 - A: Make shared posts look like shared posts
12 - B: Threading for incoming comments
13 - C: Receiving likes for comments
14
15 FBPost:
16 - A: Posts to pages currently have the page as sender - not the user
17 - B: Sending likes for comments
18 - C: Threading for sent comments
19 */
20
21 require_once("addon/fbpost/fbpost.php");
22
23 define('FBSYNC_DEFAULT_POLL_INTERVAL', 5); // given in minutes
24
25 function fbsync_install() {
26         register_hook('connector_settings',      'addon/fbsync/fbsync.php', 'fbsync_settings');
27         register_hook('connector_settings_post', 'addon/fbsync/fbsync.php', 'fbsync_settings_post');
28         register_hook('cron', 'addon/fbsync/fbsync.php', 'fbsync_cron');
29 }
30
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 }
36
37 function fbsync_settings(&$a,&$s) {
38
39         if(! local_user())
40                 return;
41
42         /* Add our stylesheet to the page so we can make our settings look nice */
43
44         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/fbsync/fbsync.css' . '" media="all" />' . "\r\n";
45
46         /* Get the current state of our config variables */
47
48         $enabled = get_pconfig(local_user(),'fbsync','sync');
49
50         $checked = (($enabled) ? ' checked="checked" ' : '');
51
52         $def_enabled = get_pconfig(local_user(),'fbsync','create_user');
53
54         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
55
56         /* Add some HTML to the existing form */
57
58         $s .= '<div class="settings-block">';
59         $s .= '<h3>' . t('Facebook Import Settings') . '</h3>';
60
61         $s .= '<div id="fbsync-enable-wrapper">';
62         $s .= '<label id="fbsync-enable-label" for="fbsync-checkbox">' . t('Import Facebook newsfeed') . '</label>';
63         $s .= '<input id="fbsync-checkbox" type="checkbox" name="fbsync" value="1" ' . $checked . '/>';
64         $s .= '</div><div class="clear"></div>';
65 /*
66         $s .= '<div id="fbsync-create_user-wrapper">';
67         $s .= '<label id="fbsync-create_user-label" for="fbsync-create_user">' . t('Automatically create contacts') . '</label>';
68         $s .= '<input id="fbsync-create_user" type="checkbox" name="create_user" value="1" ' . $def_checked . '/>';
69         $s .= '</div><div class="clear"></div>';
70 */
71         /* provide a submit button */
72
73         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fbsync-submit" name="fbsync-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
74
75 }
76
77 function fbsync_settings_post(&$a,&$b) {
78
79         if(x($_POST,'fbsync-submit')) {
80                 set_pconfig(local_user(),'fbsync','sync',intval($_POST['fbsync']));
81                 //set_pconfig(local_user(),'fbsync','create_user',intval($_POST['create_user']));
82         }
83 }
84
85 function fbsync_cron($a,$b) {
86         $last = get_config('fbsync','last_poll');
87
88         $poll_interval = intval(get_config('fbsync','poll_interval'));
89         if(! $poll_interval)
90                 $poll_interval = FBSYNC_DEFAULT_POLL_INTERVAL;
91
92         if($last) {
93                 $next = $last + ($poll_interval * 60);
94                 if($next > time()) {
95                         logger('fbsync_cron: poll intervall not reached');
96                         return;
97                 }
98         }
99         logger('fbsync_cron: cron_start');
100
101         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fbsync' AND `k` = 'sync' AND `v` = '1' ORDER BY RAND()");
102         if(count($r)) {
103                 foreach($r as $rr) {
104                         fbsync_get_self($rr['uid']);
105
106                         logger('fbsync_cron: importing timeline from user '.$rr['uid']);
107                         fbsync_fetchfeed($a, $rr['uid']);
108                 }
109         }
110
111         logger('fbsync: cron_end');
112
113         set_config('fbsync','last_poll', time());
114 }
115
116 function fbsync_createpost($a, $uid, $self, $contacts, $applications, $post, $create_user) {
117
118         // check if it was already imported
119         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
120                 intval($uid),
121                 dbesc('fb::'.$post->post_id)
122         );
123         if(count($r))
124                 return;
125
126         $postarray = array();
127         $postarray['gravity'] = 0;
128         $postarray['uid'] = $uid;
129         $postarray['wall'] = 0;
130
131         $postarray['verb'] = ACTIVITY_POST;
132
133         $postarray['uri'] = "fb::".$post->post_id;
134         $postarray['thr-parent'] = $postarray['uri'];
135         $postarray['parent-uri'] = $postarray['uri'];
136         $postarray['plink'] = $post->permalink;
137
138         $postarray['author-name'] = $contacts[$post->actor_id]->name;
139         $postarray['author-link'] = $contacts[$post->actor_id]->url;
140         $postarray['author-avatar'] = $contacts[$post->actor_id]->pic_square;
141
142         $contact_id = 0;
143
144         //if (($post->parent_post_id != "") AND ($post->source_id != $post->source_id)) {
145         if ($post->parent_post_id != "") {
146                 $pos = strpos($post->parent_post_id, "_");
147
148                 if ($pos != 0) {
149                         $user_id = substr($post->parent_post_id, 0, $pos);
150
151                         $userdata = fbsync_fetchuser($a, $uid, $user_id);
152
153                         $contact_id = $userdata["contact-id"];
154
155                         $postarray['contact-id'] = $contact_id;
156                         $postarray['owner-name'] = $userdata["name"];
157                         $postarray['owner-link'] = $userdata["link"];
158                         $postarray['owner-avatar'] = $userdata["avatar"];
159                 }
160         }
161
162         if ($contact_id == 0) {
163                 $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
164
165                 if ($contact_id < 0)
166                         return;
167                 elseif ($contact_id == 0)
168                         $contact_id = $self[0]["id"];
169
170                 $postarray['contact-id'] = $contact_id;
171                 $postarray['owner-name'] = $contacts[$post->source_id]->name;
172                 $postarray['owner-link'] = $contacts[$post->source_id]->url;
173                 $postarray['owner-avatar'] = $contacts[$post->source_id]->pic_square;
174         }
175
176         $postarray["body"] = (isset($post->message) ? escape_tags($post->message) : '');
177
178         $msgdata = fbsync_convertmsg($a, $postarray["body"]);
179
180         $postarray["body"] = $msgdata["body"];
181         $postarray["tag"] = $msgdata["tags"];
182
183         if(isset($post->attachment->name) and isset($post->attachment->href))
184                 $postarray["body"] .= "\n\n[bookmark=".$post->attachment->href."]".$post->attachment->name."[/bookmark]";
185         elseif (isset($post->attachment->name) AND ($post->attachment->name != ""))
186                 $postarray["body"] .= "\n\n[b]" . $post->attachment->name."[/b]";
187
188         $quote = "";
189         if(isset($post->attachment->description) and ($post->attachment->fb_object_type != "photo"))
190                 $quote = $post->attachment->description;
191
192         if(isset($post->attachment->caption) and ($post->attachment->fb_object_type == "photo"))
193                 $quote = $post->attachment->caption;
194
195         if ($quote.$post->attachment->href.$postarray["body"] == "")
196                 return;
197
198         if (isset($post->attachment->media) AND !strstr($post->attachment->href, "://www.youtube.com/")
199                 AND !strstr($post->attachment->href, "://youtu.be/")
200                 AND !strstr($post->attachment->href, ".vimeo.com/")) {
201                 foreach ($post->attachment->media AS $media) {
202                         //$media->photo->owner = number_format($media->photo->owner, 0, '', '');
203                         //if ($media->photo->owner != '') {
204                         //      $postarray['author-name'] = $contacts[$media->photo->owner]->name;
205                         //      $postarray['author-link'] = $contacts[$media->photo->owner]->url;
206                         //      $postarray['author-avatar'] = $contacts[$media->photo->owner]->pic_square;
207                         //}
208
209                         if(isset($media->src) && isset($media->href) AND ($media->src != "") AND ($media->href != ""))
210                                 $postarray["body"] .= "\n".'[url='.$media->href.'][img]'.fpost_cleanpicture($media->src).'[/img][/url]';
211                         else {
212                                 if (isset($media->src) AND ($media->src != ""))
213                                         $postarray["body"] .= "\n".'[img]'.fpost_cleanpicture($media->src).'[/img]';
214
215                                 // if just a link, it may be a wall photo - check
216                                 if(isset($post->link))
217                                         $postarray["body"] .= fbpost_get_photo($media->href);
218                         }
219                 }
220         }
221
222         if ($quote)
223                 $postarray["body"] .= "\n[quote]".$quote."[/quote]";
224
225         $postarray["body"] = trim($postarray["body"]);
226
227         if (trim($postarray["body"]) == "")
228                 return;
229
230         $postarray['created'] = datetime_convert('UTC','UTC',date("c", $post->created_time));
231         $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $post->updated_time));
232
233         $postarray['app'] = $applications[$post->app_id]->display_name;
234
235         if ($postarray['app'] == "")
236                 $postarray['app'] = "Facebook";
237
238         if(isset($post->privacy) && $post->privacy->value !== '') {
239                 $postarray['private'] = 1;
240                 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
241         }
242
243         /*
244         $postarray["location"] = $post->place->name;
245         postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
246         */
247
248         //$types = array(46, 80, 237, 247, 308);
249         //if (!in_array($post->type, $types))
250         //      $postarray["body"] = "Type: ".$post->type."\n".$postarray["body"];
251         //print_r($post);
252         //print_r($postarray);
253
254         $item = item_store($postarray);
255         logger('fbsync_createpost: User '.$self[0]["nick"].' posted feed item '.$item, LOGGER_DEBUG);
256 }
257
258 function fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $applications, $comment) {
259
260         // check if it was already imported
261         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
262                 intval($uid),
263                 dbesc('fb::'.$comment->id)
264         );
265         if(count($r))
266                 return;
267
268         // check if it was an own post (separate posting for performance reasons)
269         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
270                 intval($uid),
271                 dbesc('fb::'.$comment->id)
272         );
273         if(count($r))
274                 return;
275
276         $parent_uri = "";
277
278         // Fetch the parent uri (Checking if the parent exists)
279         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
280                 intval($uid),
281                 dbesc('fb::'.$comment->post_id)
282         );
283         if(count($r))
284                 $parent_uri = $r[0]["uri"];
285
286         // check if it is a reply to an own post (separate posting for performance reasons)
287         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
288                 intval($uid),
289                 dbesc('fb::'.$comment->post_id)
290         );
291         if(count($r))
292                 $parent_uri = $r[0]["uri"];
293
294         // No parent? Then quit
295         if ($parent_uri == "")
296                 return;
297
298         $postarray = array();
299         $postarray['gravity'] = 0;
300         $postarray['uid'] = $uid;
301         $postarray['wall'] = 0;
302
303         $postarray['verb'] = ACTIVITY_POST;
304
305         $postarray['uri'] = "fb::".$comment->id;
306         $postarray['thr-parent'] = $parent_uri;
307         $postarray['parent-uri'] = $parent_uri;
308         //$postarray['plink'] = $comment->permalink;
309
310         $contact_id = fbsync_fetch_contact($uid, $contacts[$comment->fromid], array(), false);
311
312         if ($contact_id <= 0)
313                 $contact_id = $self[0]["id"];
314
315         if ($comment->fromid != $self_id) {
316                 $postarray['contact-id'] = $contact_id;
317                 $postarray['owner-name'] = $contacts[$comment->fromid]->name;
318                 $postarray['owner-link'] = $contacts[$comment->fromid]->url;
319                 $postarray['owner-avatar'] = $contacts[$comment->fromid]->pic_square;
320         } else {
321                 $postarray['contact-id'] = $self[0]["id"];
322                 $postarray['owner-name'] = $self[0]["name"];
323                 $postarray['owner-link'] = $self[0]["url"];
324                 $postarray['owner-avatar'] = $self[0]["photo"];
325         }
326
327         $postarray['author-name'] = $postarray['owner-name'];
328         $postarray['author-link'] = $postarray['owner-link'];
329         $postarray['author-avatar'] = $postarray['owner-avatar'];
330
331         $msgdata = fbsync_convertmsg($a, $comment->text);
332
333         $postarray["body"] = $msgdata["body"];
334         $postarray["tag"] = $msgdata["tags"];
335
336         $postarray['created'] = datetime_convert('UTC','UTC',date("c", $comment->time));
337         $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $comment->time));
338
339         $postarray['app'] = $applications[$comment->app_id]->display_name;
340
341         if ($postarray['app'] == "")
342                 $postarray['app'] = "Facebook";
343
344         if (trim($postarray["body"]) == "")
345                 return;
346
347         $item = item_store($postarray);
348         logger('fbsync_createcomment: User '.$self[0]["nick"].' posted comment '.$item, LOGGER_DEBUG);
349
350         if ($item == 0)
351                 return;
352
353         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
354                 dbesc($postarray['parent-uri']),
355                 intval($uid)
356         );
357
358         if(count($myconv)) {
359                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
360
361                 $own_contact = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
362                         intval($uid), dbesc("facebook::".$self_id));
363
364                 if (!count($own_contact))
365                         return;
366
367                 foreach($myconv as $conv) {
368
369                         // now if we find a match, it means we're in this conversation
370                         if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_contact[0]["url"]))
371                                 continue;
372
373                         require_once('include/enotify.php');
374
375                         $conv_parent = $conv['parent'];
376
377                         $notifyarr = array(
378                                         'type'         => NOTIFY_COMMENT,
379                                         'notify_flags' => $user[0]['notify-flags'],
380                                         'language'     => $user[0]['language'],
381                                         'to_name'      => $user[0]['username'],
382                                         'to_email'     => $user[0]['email'],
383                                         'uid'          => $user[0]['uid'],
384                                         'item'         => $postarray,
385                                         'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $item,
386                                         'source_name'  => $postarray['author-name'],
387                                         'source_link'  => $postarray['author-link'],
388                                         'source_photo' => $postarray['author-avatar'],
389                                         'verb'         => ACTIVITY_POST,
390                                         'otype'        => 'item',
391                                         'parent'       => $conv_parent,
392                         );
393
394                         notification($notifyarr);
395
396                         // only send one notification
397                         break;
398                 }
399         }
400 }
401
402 function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
403
404         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
405                                 dbesc("fb::".$like->post_id),
406                                 intval($uid)
407                 );
408
409         if (count($r))
410                 $orig_post = $r[0];
411         else
412                 return;
413
414         // If we posted the like locally, it will be found with our url, not the FB url.
415
416         $second_url = (($like->user_id == $self_id) ? $self[0]["url"] : $contacts[$like->user_id]->url);
417
418         $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
419                 AND (`author-link` = '%s' OR `author-link` = '%s') LIMIT 1",
420                 dbesc($orig_post["uri"]),
421                 intval($uid),
422                 dbesc(ACTIVITY_LIKE),
423                 dbesc($contacts[$like->user_id]->url),
424                 dbesc($second_url)
425         );
426
427         if (count($r))
428                 return;
429
430         $contact_id = fbsync_fetch_contact($uid, $contacts[$like->user_id], array(), false);
431
432         if ($contact_id <= 0)
433                 $contact_id = $self[0]["id"];
434
435         $likedata = array();
436         $likedata['parent'] = $orig_post['id'];
437         $likedata['verb'] = ACTIVITY_LIKE;
438         $likedata['gravity'] = 3;
439         $likedata['uid'] = $uid;
440         $likedata['wall'] = 0;
441         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
442         $likedata['parent-uri'] = $orig_post["uri"];
443         $likedata['app'] = "Facebook";
444         $likedata['verb'] = ACTIVITY_LIKE;
445
446         if ($like->user_id != $self_id) {
447                 $likedata['contact-id'] = $contact_id;
448                 $likedata['author-name'] = $contacts[$like->user_id]->name;
449                 $likedata['author-link'] = $contacts[$like->user_id]->url;
450                 $likedata['author-avatar'] = $contacts[$like->user_id]->pic_square;
451         } else {
452                 $likedata['contact-id'] = $self[0]["id"];
453                 $likedata['author-name'] = $self[0]["name"];
454                 $likedata['author-link'] = $self[0]["url"];
455                 $likedata['author-avatar'] = $self[0]["photo"];
456         }
457
458         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
459
460         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
461         $post_type = t('status');
462
463         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
464         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
465
466         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
467
468         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
469                 '<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>';
470
471
472         $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `author-link` = '%s' AND `verb` = '%s' AND `uid` = %d LIMIT 1",
473                                 dbesc($likedata['parent-uri']),
474                                 dbesc($likedata['author-link']),
475                                 dbesc(ACTIVITY_LIKE),
476                                 intval($uid)
477                 );
478
479         if (count($r))
480                 return;
481
482         $item = item_store($likedata);
483         logger('fbsync_createlike: liked item '.$item.'. User '.$self[0]["nick"], LOGGER_DEBUG);
484 }
485
486 function fbsync_fetch_contact($uid, $contact, $create_user) {
487
488         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
489                 intval($uid), dbesc("facebook::".$contact->id));
490
491         if(!count($r) AND !$create_user)
492                 return(0);
493
494         if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
495                 logger("fbsync_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
496                 return(-1);
497         }
498
499         $avatarpicture = $contact->pic_square;
500
501         if(!count($r)) {
502                 // create contact record
503                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
504                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
505                                         `writable`, `blocked`, `readonly`, `pending`)
506                                         VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0)",
507                         intval($uid),
508                         dbesc(datetime_convert()),
509                         dbesc($contact->url),
510                         dbesc(normalise_link($contact->url)),
511                         dbesc($contact->username."@facebook.com"),
512                         dbesc("facebook::".$contact->id),
513                         dbesc(''),
514                         dbesc("facebook::".$contact->id),
515                         dbesc($contact->name),
516                         dbesc($contact->username),
517                         dbesc($avatarpicture),
518                         dbesc(NETWORK_FACEBOOK),
519                         intval(CONTACT_IS_FRIEND),
520                         intval(1),
521                         intval(1)
522                 );
523
524                 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
525                         dbesc("facebook::".$contact->id),
526                         intval($uid)
527                         );
528
529                 if(! count($r))
530                         return(false);
531
532                 $contact_id  = $r[0]['id'];
533
534                 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
535                         intval($uid)
536                 );
537
538                 if($g && intval($g[0]['def_gid'])) {
539                         require_once('include/group.php');
540                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
541                 }
542
543                 require_once("Photo.php");
544
545                 $photos = import_profile_photo($avatarpicture,$uid,$contact_id);
546
547                 q("UPDATE `contact` SET `photo` = '%s',
548                                         `thumb` = '%s',
549                                         `micro` = '%s',
550                                         `name-date` = '%s',
551                                         `uri-date` = '%s',
552                                         `avatar-date` = '%s'
553                                 WHERE `id` = %d",
554                         dbesc($photos[0]),
555                         dbesc($photos[1]),
556                         dbesc($photos[2]),
557                         dbesc(datetime_convert()),
558                         dbesc(datetime_convert()),
559                         dbesc(datetime_convert()),
560                         intval($contact_id)
561                 );
562         } else {
563                 // update profile photos once every 12 hours as we have no notification of when they change.
564                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
565
566                 // check that we have all the photos, this has been known to fail on occasion
567                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
568
569                         logger("fbsync_fetch_contact: Updating contact ".$contact->username, LOGGER_DEBUG);
570
571                         require_once("Photo.php");
572
573                         $photos = import_profile_photo($avatarpicture, $uid, $r[0]['id']);
574
575                         q("UPDATE `contact` SET `photo` = '%s',
576                                                 `thumb` = '%s',
577                                                 `micro` = '%s',
578                                                 `name-date` = '%s',
579                                                 `uri-date` = '%s',
580                                                 `avatar-date` = '%s',
581                                                 `url` = '%s',
582                                                 `nurl` = '%s',
583                                                 `addr` = '%s',
584                                                 `name` = '%s',
585                                                 `nick` = '%s'
586                                         WHERE `id` = %d",
587                                 dbesc($photos[0]),
588                                 dbesc($photos[1]),
589                                 dbesc($photos[2]),
590                                 dbesc(datetime_convert()),
591                                 dbesc(datetime_convert()),
592                                 dbesc(datetime_convert()),
593                                 dbesc($contact->url),
594                                 dbesc(normalise_link($contact->url)),
595                                 dbesc($contact->username."@facebook.com"),
596                                 dbesc($contact->name),
597                                 dbesc($contact->username),
598                                 intval($r[0]['id'])
599                         );
600                 }
601         }
602         return($r[0]["id"]);
603 }
604
605 function fbsync_get_self($uid) {
606         $access_token = get_pconfig($uid,'facebook','access_token');
607         if(! $access_token)
608                 return;
609         $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
610         if($s) {
611                 $j = json_decode($s);
612                 set_pconfig($uid,'fbsync','self_id',(string) $j->id);
613         }
614 }
615
616 function fbsync_convertmsg($a, $body) {
617         $str_tags = '';
618
619         $tags = get_tags($body);
620
621         if(count($tags)) {
622                 foreach($tags as $tag) {
623                         if (strstr(trim($tag), " "))
624                                 continue;
625
626                         if(strpos($tag,'#') === 0) {
627                                 if(strpos($tag,'[url='))
628                                         continue;
629
630                                 // don't link tags that are already embedded in links
631
632                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
633                                         continue;
634                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
635                                         continue;
636
637                                 $basetag = str_replace('_',' ',substr($tag,1));
638                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
639                                 if(strlen($str_tags))
640                                         $str_tags .= ',';
641                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
642                                 continue;
643                         } elseif(strpos($tag,'@') === 0) {
644                                 $basetag = substr($tag,1);
645                                 $body = str_replace($tag,'@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
646                         }
647
648                 }
649         }
650
651         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
652         if($cnt) {
653                 foreach($matches as $mtch) {
654                         if(strlen($str_tags))
655                                 $str_tags .= ',';
656                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';
657                 }
658         }
659
660         return(array("body"=>$body, "tags"=>$str_tags));
661
662 }
663
664 function fbsync_fetchuser($a, $uid, $id) {
665         $access_token = get_pconfig($uid,'facebook','access_token');
666         $self_id = get_pconfig($uid,'fbsync','self_id');
667
668         $user = array();
669
670         $contact = q("SELECT `id`, `name`, `url`, `photo`  FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
671                 intval($uid), dbesc("facebook::".$id));
672
673         if (count($contact)) {
674                 $user["contact-id"] = $contact[0]["id"];
675                 $user["name"] = $contact[0]["name"];
676                 $user["link"] = $contact[0]["url"];
677                 $user["avatar"] = $contact[0]["photo"];
678
679                 return($user);
680         }
681
682         $own_contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
683                 intval($uid), dbesc("facebook::".$self_id));
684
685         if (!count($own_contact))
686                 return($user);
687
688         $fql = "SELECT name, url, pic_square FROM profile WHERE id = ".$id;
689
690         $url = "https://graph.facebook.com/fql?q=".urlencode($fql)."&access_token=".$access_token;
691
692         $feed = fetch_url($url);
693         $data = json_decode($feed);
694
695         if (is_array($data->data)) {
696                 $user["contact-id"] = $own_contact[0]["id"];
697                 $user["name"] = $data->data[0]->name;
698                 $user["link"] = $data->data[0]->url;
699                 $user["avatar"] = $data->data[0]->pic_square;
700         }
701         return($user);
702 }
703
704 function fbsync_fetchfeed($a, $uid) {
705         $access_token = get_pconfig($uid,'facebook','access_token');
706         $last_updated = get_pconfig($uid,'fbsync','last_updated');
707         $self_id = get_pconfig($uid,'fbsync','self_id');
708
709         //$create_user = get_pconfig($uid, 'fbsybc', 'create_user');
710         $create_user = true;
711         $do_likes = get_config('fbsync', 'do_likes');
712
713         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
714                 intval($uid)
715         );
716
717         $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
718                 intval($uid)
719         );
720         if(! count($user))
721                 return;
722
723         require_once('include/items.php');
724
725         if ($last_updated == "")
726                 $last_updated = 0;
727
728         logger("fbsync_fetchfeed: fetching content for user ".$self_id);
729
730         $fql = array(
731                 "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",
732                 "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",
733                 "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",
734                 "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",
735                 "avatars" => "SELECT id, real_size, size, url FROM square_profile_pic WHERE id IN (SELECT id FROM #profiles) AND size = 256 LIMIT 500");
736
737         if ($do_likes) {
738                 $fql["likes"] = "SELECT post_id, user_id FROM like WHERE post_id IN (SELECT post_id FROM #posts)";
739                 $fql["profiles"] .= " OR id IN (SELECT user_id FROM #likes)";
740         }
741
742         $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
743
744         $feed = fetch_url($url);
745
746         $data = json_decode($feed);
747
748         if (!is_array($data->data)) {
749                 logger("fbsync_fetchfeed: Error fetching data for user ".$uid.": ".print_r($data, true));
750                 return;
751         }
752
753         $posts = array();
754         $comments = array();
755         $likes = array();
756         $profiles = array();
757         $applications = array();
758         $avatars = array();
759
760         foreach($data->data AS $query) {
761                 switch ($query->name) {
762                         case "posts":
763                                 $posts = array_reverse($query->fql_result_set);
764                                 break;
765                         case "comments":
766                                 $comments = $query->fql_result_set;
767                                 break;
768                         case "likes":
769                                 $likes = $query->fql_result_set;
770                                 break;
771                         case "profiles":
772                                 $profiles = $query->fql_result_set;
773                                 break;
774                         case "applications":
775                                 $applications = $query->fql_result_set;
776                                 break;
777                         case "avatars":
778                                 $avatars = $query->fql_result_set;
779                                 break;
780                 }
781         }
782
783         $square_avatars = array();
784         $contacts = array();
785         $application_data = array();
786         $post_data = array();
787         $comment_data = array();
788
789         foreach ($avatars AS $avatar) {
790                 $avatar->id = number_format($avatar->id, 0, '', '');
791                 $square_avatars[$avatar->id] = $avatar;
792         }
793         unset($avatars);
794
795         foreach ($profiles AS $profile) {
796                 $profile->id = number_format($profile->id, 0, '', '');
797
798                 if ($square_avatars[$profile->id]->url != "")
799                         $profile->pic_square = $square_avatars[$profile->id]->url;
800
801                 $contacts[$profile->id] = $profile;
802         }
803         unset($profiles);
804         unset($square_avatars);
805
806         foreach ($applications AS $application) {
807                 $application->app_id = number_format($application->app_id, 0, '', '');
808                 $application_data[$application->app_id] = $application;
809         }
810         unset($applications);
811
812         foreach ($posts AS $post) {
813                 $post->actor_id = number_format($post->actor_id, 0, '', '');
814                 $post->source_id = number_format($post->source_id, 0, '', '');
815                 $post->app_id = number_format($post->app_id, 0, '', '');
816                 $post_data[$post->post_id] = $post;
817         }
818         unset($posts);
819
820         foreach($comments AS $comment) {
821                 $comment->fromid = number_format($comment->fromid, 0, '', '');
822                 $comment_data[$comment->id] = $comment;
823         }
824         unset($comments);
825
826         foreach ($post_data AS $post) {
827                 if ($post->updated_time > $last_updated)
828                         $last_updated = $post->updated_time;
829
830                 fbsync_createpost($a, $uid, $self, $contacts, $application_data, $post, $create_user);
831         }
832
833         foreach ($comment_data AS $comment) {
834                 fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $application_data, $comment);
835         }
836
837         foreach($likes AS $like) {
838                 $like->user_id = number_format($like->user_id, 0, '', '');
839
840                 fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like);
841         }
842
843         set_pconfig($uid,'fbsync','last_updated', $last_updated);
844
845 }
846 ?>