]> git.mxchange.org Git - friendica-addons.git/blob - fbsync/fbsync.php
Some more debug information for twitter-sync and facebook-sync
[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         $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
139
140         if ($contact_id < 0)
141                 return;
142         elseif ($contact_id == 0)
143                 $contact_id = $self[0]["id"];
144
145         $postarray['contact-id'] = $contact_id;
146
147         $postarray['owner-name'] = $contacts[$post->source_id]->name;
148         $postarray['owner-link'] = $contacts[$post->source_id]->url;
149         $postarray['owner-avatar'] = $contacts[$post->source_id]->pic_square;
150
151         $postarray['author-name'] = $contacts[$post->actor_id]->name;
152         $postarray['author-link'] = $contacts[$post->actor_id]->url;
153         $postarray['author-avatar'] = $contacts[$post->actor_id]->pic_square;
154
155         $postarray["body"] = (isset($post->message) ? escape_tags($post->message) : '');
156
157         $msgdata = fbsync_convertmsg($a, $postarray["body"]);
158
159         $postarray["body"] = $msgdata["body"];
160         $postarray["tag"] = $msgdata["tags"];
161
162         if(isset($post->attachment->name) and isset($post->attachment->href))
163                 $postarray["body"] .= "\n\n[bookmark=".$post->attachment->href."]".$post->attachment->name."[/bookmark]";
164         elseif (isset($post->attachment->name) AND ($post->attachment->name != ""))
165                 $postarray["body"] .= "\n\n[b]" . $post->attachment->name."[/b]";
166
167         $quote = "";
168         if(isset($post->attachment->description) and ($post->attachment->fb_object_type != "photo"))
169                 $quote = $post->attachment->description;
170
171         if(isset($post->attachment->caption) and ($post->attachment->fb_object_type == "photo"))
172                 $quote = $post->attachment->caption;
173
174         if ($quote.$post->attachment->href.$postarray["body"] == "")
175                 return;
176
177         if (isset($post->attachment->media) AND !strstr($post->attachment->href, "://www.youtube.com/")
178                 AND !strstr($post->attachment->href, "://youtu.be/")
179                 AND !strstr($post->attachment->href, ".vimeo.com/")) {
180                 foreach ($post->attachment->media AS $media) {
181                         //$media->photo->owner = number_format($media->photo->owner, 0, '', '');
182                         //if ($media->photo->owner != '') {
183                         //      $postarray['author-name'] = $contacts[$media->photo->owner]->name;
184                         //      $postarray['author-link'] = $contacts[$media->photo->owner]->url;
185                         //      $postarray['author-avatar'] = $contacts[$media->photo->owner]->pic_square;
186                         //}
187
188                         if(isset($media->src) && isset($media->href) AND ($media->src != "") AND ($media->href != ""))
189                                 $postarray["body"] .= "\n".'[url='.$media->href.'][img]'.fpost_cleanpicture($media->src).'[/img][/url]';
190                         else {
191                                 if (isset($media->src) AND ($media->src != ""))
192                                         $postarray["body"] .= "\n".'[img]'.fpost_cleanpicture($media->src).'[/img]';
193
194                                 // if just a link, it may be a wall photo - check
195                                 if(isset($post->link))
196                                         $postarray["body"] .= fbpost_get_photo($media->href);
197                         }
198                 }
199         }
200
201         if ($quote)
202                 $postarray["body"] .= "\n[quote]".$quote."[/quote]";
203
204         $postarray["body"] = trim($postarray["body"]);
205
206         if (trim($postarray["body"]) == "")
207                 return;
208
209         $postarray['created'] = datetime_convert('UTC','UTC',date("c", $post->created_time));
210         $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $post->updated_time));
211
212         $postarray['app'] = $applications[$post->app_id]->display_name;
213
214         if ($postarray['app'] == "")
215                 $postarray['app'] = "Facebook";
216
217         if(isset($post->privacy) && $post->privacy->value !== '') {
218                 $postarray['private'] = 1;
219                 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
220         }
221
222         /*
223         $postarray["location"] = $post->place->name;
224         postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
225         */
226
227         //$types = array(46, 80, 237, 247, 308);
228         //if (!in_array($post->type, $types))
229         //      $postarray["body"] = "Type: ".$post->type."\n".$postarray["body"];
230         //print_r($postarray);
231         $item = item_store($postarray);
232         logger('fbsync_createpost: User '.$self[0]["nick"].' posted feed item '.$item, LOGGER_DEBUG);
233 }
234
235 function fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $applications, $comment) {
236
237         // check if it was already imported
238         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
239                 intval($uid),
240                 dbesc('fb::'.$comment->id)
241         );
242         if(count($r))
243                 return;
244
245         // check if it was an own post (separate posting for performance reasons)
246         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
247                 intval($uid),
248                 dbesc('fb::'.$comment->id)
249         );
250         if(count($r))
251                 return;
252
253         $parent_uri = "";
254
255         // Fetch the parent uri (Checking if the parent exists)
256         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
257                 intval($uid),
258                 dbesc('fb::'.$comment->post_id)
259         );
260         if(count($r))
261                 $parent_uri = $r[0]["uri"];
262
263         // check if it is a reply to an own post (separate posting for performance reasons)
264         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
265                 intval($uid),
266                 dbesc('fb::'.$comment->post_id)
267         );
268         if(count($r))
269                 $parent_uri = $r[0]["uri"];
270
271         // No parent? Then quit
272         if ($parent_uri == "")
273                 return;
274
275         $postarray = array();
276         $postarray['gravity'] = 0;
277         $postarray['uid'] = $uid;
278         $postarray['wall'] = 0;
279
280         $postarray['verb'] = ACTIVITY_POST;
281
282         $postarray['uri'] = "fb::".$comment->id;
283         $postarray['thr-parent'] = $parent_uri;
284         $postarray['parent-uri'] = $parent_uri;
285         //$postarray['plink'] = $comment->permalink;
286
287         $contact_id = fbsync_fetch_contact($uid, $contacts[$comment->fromid], array(), false);
288
289         if ($contact_id <= 0)
290                 $contact_id = $self[0]["id"];
291
292         if ($comment->fromid != $self_id) {
293                 $postarray['contact-id'] = $contact_id;
294                 $postarray['owner-name'] = $contacts[$comment->fromid]->name;
295                 $postarray['owner-link'] = $contacts[$comment->fromid]->url;
296                 $postarray['owner-avatar'] = $contacts[$comment->fromid]->pic_square;
297         } else {
298                 $postarray['contact-id'] = $self[0]["id"];
299                 $postarray['owner-name'] = $self[0]["name"];
300                 $postarray['owner-link'] = $self[0]["url"];
301                 $postarray['owner-avatar'] = $self[0]["photo"];
302         }
303
304         $postarray['author-name'] = $postarray['owner-name'];
305         $postarray['author-link'] = $postarray['owner-link'];
306         $postarray['author-avatar'] = $postarray['owner-avatar'];
307
308         $msgdata = fbsync_convertmsg($a, $comment->text);
309
310         $postarray["body"] = $msgdata["body"];
311         $postarray["tag"] = $msgdata["tags"];
312
313         $postarray['created'] = datetime_convert('UTC','UTC',date("c", $comment->time));
314         $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $comment->time));
315
316         $postarray['app'] = $applications[$comment->app_id]->display_name;
317
318         if ($postarray['app'] == "")
319                 $postarray['app'] = "Facebook";
320
321         if (trim($postarray["body"]) == "")
322                 return;
323
324         $item = item_store($postarray);
325         logger('fbsync_createcomment: User '.$self[0]["nick"].' posted comment '.$item, LOGGER_DEBUG);
326
327         if ($item == 0)
328                 return;
329
330         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
331                 dbesc($postarray['parent-uri']),
332                 intval($uid)
333         );
334
335         if(count($myconv)) {
336                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
337
338                 $own_contact = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
339                         intval($uid), dbesc("facebook::".$self_id));
340
341                 if (!count($own_contact))
342                         return;
343
344                 foreach($myconv as $conv) {
345
346                         // now if we find a match, it means we're in this conversation
347                         if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_contact[0]["url"]))
348                                 continue;
349
350                         require_once('include/enotify.php');
351
352                         $conv_parent = $conv['parent'];
353
354                         $notifyarr = array(
355                                         'type'         => NOTIFY_COMMENT,
356                                         'notify_flags' => $user[0]['notify-flags'],
357                                         'language'     => $user[0]['language'],
358                                         'to_name'      => $user[0]['username'],
359                                         'to_email'     => $user[0]['email'],
360                                         'uid'          => $user[0]['uid'],
361                                         'item'         => $postarray,
362                                         'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $item,
363                                         'source_name'  => $postarray['author-name'],
364                                         'source_link'  => $postarray['author-link'],
365                                         'source_photo' => $postarray['author-avatar'],
366                                         'verb'         => ACTIVITY_POST,
367                                         'otype'        => 'item',
368                                         'parent'       => $conv_parent,
369                         );
370
371                         notification($notifyarr);
372
373                         // only send one notification
374                         break;
375                 }
376         }
377 }
378
379 function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
380
381         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
382                                 dbesc("fb::".$like->post_id),
383                                 intval($uid)
384                 );
385
386         if (count($r))
387                 $orig_post = $r[0];
388         else
389                 return;
390
391         // If we posted the like locally, it will be found with our url, not the FB url.
392
393         $second_url = (($like->user_id == $self_id) ? $self[0]["url"] : $contacts[$like->user_id]->url);
394
395         $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
396                 AND (`author-link` = '%s' OR `author-link` = '%s') LIMIT 1",
397                 dbesc($orig_post["uri"]),
398                 intval($uid),
399                 dbesc(ACTIVITY_LIKE),
400                 dbesc($contacts[$like->user_id]->url),
401                 dbesc($second_url)
402         );
403
404         if (count($r))
405                 return;
406
407         $contact_id = fbsync_fetch_contact($uid, $contacts[$like->user_id], array(), false);
408
409         if ($contact_id <= 0)
410                 $contact_id = $self[0]["id"];
411
412         $likedata = array();
413         $likedata['parent'] = $orig_post['id'];
414         $likedata['verb'] = ACTIVITY_LIKE;
415         $likedata['gravity'] = 3;
416         $likedata['uid'] = $uid;
417         $likedata['wall'] = 0;
418         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
419         $likedata['parent-uri'] = $orig_post["uri"];
420         $likedata['app'] = "Facebook";
421         $likedata['verb'] = ACTIVITY_LIKE;
422
423         if ($like->user_id != $self_id) {
424                 $likedata['contact-id'] = $contact_id;
425                 $likedata['author-name'] = $contacts[$like->user_id]->name;
426                 $likedata['author-link'] = $contacts[$like->user_id]->url;
427                 $likedata['author-avatar'] = $contacts[$like->user_id]->pic_square;
428         } else {
429                 $likedata['contact-id'] = $self[0]["id"];
430                 $likedata['author-name'] = $self[0]["name"];
431                 $likedata['author-link'] = $self[0]["url"];
432                 $likedata['author-avatar'] = $self[0]["photo"];
433         }
434
435         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
436
437         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
438         $post_type = t('status');
439
440         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
441         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
442
443         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
444
445         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
446                 '<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>';
447
448
449         $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `author-link` = '%s' AND `verb` = '%s' AND `uid` = %d LIMIT 1",
450                                 dbesc($likedata['parent-uri']),
451                                 dbesc($likedata['author-link']),
452                                 dbesc(ACTIVITY_LIKE),
453                                 intval($uid)
454                 );
455
456         if (count($r))
457                 return;
458
459         $item = item_store($likedata);
460         logger('fbsync_createlike: liked item '.$item.'. User '.$self[0]["nick"], LOGGER_DEBUG);
461 }
462
463 function fbsync_fetch_contact($uid, $contact, $create_user) {
464
465         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
466                 intval($uid), dbesc("facebook::".$contact->id));
467
468         if(!count($r) AND !$create_user)
469                 return(0);
470
471         if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
472                 logger("fbsync_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
473                 return(-1);
474         }
475
476         $avatarpicture = $contact->pic_square;
477
478         if(!count($r)) {
479                 // create contact record
480                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
481                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
482                                         `writable`, `blocked`, `readonly`, `pending`)
483                                         VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0)",
484                         intval($uid),
485                         dbesc(datetime_convert()),
486                         dbesc($contact->url),
487                         dbesc(normalise_link($contact->url)),
488                         dbesc($contact->username."@facebook.com"),
489                         dbesc("facebook::".$contact->id),
490                         dbesc(''),
491                         dbesc("facebook::".$contact->id),
492                         dbesc($contact->name),
493                         dbesc($contact->username),
494                         dbesc($avatarpicture),
495                         dbesc(NETWORK_FACEBOOK),
496                         intval(CONTACT_IS_FRIEND),
497                         intval(1),
498                         intval(1)
499                 );
500
501                 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
502                         dbesc("facebook::".$contact->id),
503                         intval($uid)
504                         );
505
506                 if(! count($r))
507                         return(false);
508
509                 $contact_id  = $r[0]['id'];
510
511                 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
512                         intval($uid)
513                 );
514
515                 if($g && intval($g[0]['def_gid'])) {
516                         require_once('include/group.php');
517                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
518                 }
519
520                 require_once("Photo.php");
521
522                 $photos = import_profile_photo($avatarpicture,$uid,$contact_id);
523
524                 q("UPDATE `contact` SET `photo` = '%s',
525                                         `thumb` = '%s',
526                                         `micro` = '%s',
527                                         `name-date` = '%s',
528                                         `uri-date` = '%s',
529                                         `avatar-date` = '%s'
530                                 WHERE `id` = %d",
531                         dbesc($photos[0]),
532                         dbesc($photos[1]),
533                         dbesc($photos[2]),
534                         dbesc(datetime_convert()),
535                         dbesc(datetime_convert()),
536                         dbesc(datetime_convert()),
537                         intval($contact_id)
538                 );
539         } else {
540                 // update profile photos once every 12 hours as we have no notification of when they change.
541                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
542
543                 // check that we have all the photos, this has been known to fail on occasion
544                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
545
546                         logger("fbsync_fetch_contact: Updating contact ".$contact->username, LOGGER_DEBUG);
547
548                         require_once("Photo.php");
549
550                         $photos = import_profile_photo($avatarpicture, $uid, $r[0]['id']);
551
552                         q("UPDATE `contact` SET `photo` = '%s',
553                                                 `thumb` = '%s',
554                                                 `micro` = '%s',
555                                                 `name-date` = '%s',
556                                                 `uri-date` = '%s',
557                                                 `avatar-date` = '%s',
558                                                 `url` = '%s',
559                                                 `nurl` = '%s',
560                                                 `addr` = '%s',
561                                                 `name` = '%s',
562                                                 `nick` = '%s'
563                                         WHERE `id` = %d",
564                                 dbesc($photos[0]),
565                                 dbesc($photos[1]),
566                                 dbesc($photos[2]),
567                                 dbesc(datetime_convert()),
568                                 dbesc(datetime_convert()),
569                                 dbesc(datetime_convert()),
570                                 dbesc($contact->url),
571                                 dbesc(normalise_link($contact->url)),
572                                 dbesc($contact->username."@facebook.com"),
573                                 dbesc($contact->name),
574                                 dbesc($contact->username),
575                                 intval($r[0]['id'])
576                         );
577                 }
578         }
579         return($r[0]["id"]);
580 }
581
582 function fbsync_get_self($uid) {
583         $access_token = get_pconfig($uid,'facebook','access_token');
584         if(! $access_token)
585                 return;
586         $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
587         if($s) {
588                 $j = json_decode($s);
589                 set_pconfig($uid,'fbsync','self_id',(string) $j->id);
590         }
591 }
592
593 function fbsync_convertmsg($a, $body) {
594         $str_tags = '';
595
596         $tags = get_tags($body);
597
598         if(count($tags)) {
599                 foreach($tags as $tag) {
600                         if (strstr(trim($tag), " "))
601                                 continue;
602
603                         if(strpos($tag,'#') === 0) {
604                                 if(strpos($tag,'[url='))
605                                         continue;
606
607                                 // don't link tags that are already embedded in links
608
609                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
610                                         continue;
611                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
612                                         continue;
613
614                                 $basetag = str_replace('_',' ',substr($tag,1));
615                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
616                                 if(strlen($str_tags))
617                                         $str_tags .= ',';
618                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
619                                 continue;
620                         } elseif(strpos($tag,'@') === 0) {
621                                 $basetag = substr($tag,1);
622                                 $body = str_replace($tag,'@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
623                         }
624
625                 }
626         }
627
628         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
629         if($cnt) {
630                 foreach($matches as $mtch) {
631                         if(strlen($str_tags))
632                                 $str_tags .= ',';
633                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';
634                 }
635         }
636
637         return(array("body"=>$body, "tags"=>$str_tags));
638
639 }
640
641 function fbsync_fetchfeed($a, $uid) {
642         $access_token = get_pconfig($uid,'facebook','access_token');
643         $last_updated = get_pconfig($uid,'fbsync','last_updated');
644         $self_id = get_pconfig($uid,'fbsync','self_id');
645
646         $create_user = get_pconfig($uid, 'fbsybc', 'create_user');
647         $do_likes = get_config('fbsync', 'do_likes');
648
649         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
650                 intval($uid)
651         );
652
653         $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
654                 intval($uid)
655         );
656         if(! count($user))
657                 return;
658
659         require_once('include/items.php');
660
661         if ($last_updated == "")
662                 $last_updated = 0;
663
664         logger("fbsync_fetchfeed: fetching content for user ".$self_id);
665
666         $fql = array(
667                 "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",
668                 "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",
669                 "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",
670                 "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",
671                 "avatars" => "SELECT id, real_size, size, url FROM square_profile_pic WHERE id IN (SELECT id FROM #profiles) AND size = 256 LIMIT 500");
672
673         if ($do_likes) {
674                 $fql["likes"] = "SELECT post_id, user_id FROM like WHERE post_id IN (SELECT post_id FROM #posts)";
675                 $fql["profiles"] .= " OR id IN (SELECT user_id FROM #likes)";
676         }
677
678         $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
679
680         $feed = fetch_url($url);
681
682         $data = json_decode($feed);
683
684         if (!is_array($data->data)) {
685                 logger("fbsync_fetchfeed: Error fetching data for user ".$uid.": ".print_r($data, true));
686                 return;
687         }
688
689         $posts = array();
690         $comments = array();
691         $likes = array();
692         $profiles = array();
693         $applications = array();
694         $avatars = array();
695
696         foreach($data->data AS $query) {
697                 switch ($query->name) {
698                         case "posts":
699                                 $posts = array_reverse($query->fql_result_set);
700                                 break;
701                         case "comments":
702                                 $comments = $query->fql_result_set;
703                                 break;
704                         case "likes":
705                                 $likes = $query->fql_result_set;
706                                 break;
707                         case "profiles":
708                                 $profiles = $query->fql_result_set;
709                                 break;
710                         case "applications":
711                                 $applications = $query->fql_result_set;
712                                 break;
713                         case "avatars":
714                                 $avatars = $query->fql_result_set;
715                                 break;
716                 }
717         }
718
719         $square_avatars = array();
720         $contacts = array();
721         $application_data = array();
722         $post_data = array();
723         $comment_data = array();
724
725         foreach ($avatars AS $avatar) {
726                 $avatar->id = number_format($avatar->id, 0, '', '');
727                 $square_avatars[$avatar->id] = $avatar;
728         }
729         unset($avatars);
730
731         foreach ($profiles AS $profile) {
732                 $profile->id = number_format($profile->id, 0, '', '');
733
734                 if ($square_avatars[$profile->id]->url != "")
735                         $profile->pic_square = $square_avatars[$profile->id]->url;
736
737                 $contacts[$profile->id] = $profile;
738         }
739         unset($profiles);
740         unset($square_avatars);
741
742         foreach ($applications AS $application) {
743                 $application->app_id = number_format($application->app_id, 0, '', '');
744                 $application_data[$application->app_id] = $application;
745         }
746         unset($applications);
747
748         foreach ($posts AS $post) {
749                 $post->actor_id = number_format($post->actor_id, 0, '', '');
750                 $post->source_id = number_format($post->source_id, 0, '', '');
751                 $post->app_id = number_format($post->app_id, 0, '', '');
752                 $post_data[$post->post_id] = $post;
753         }
754         unset($posts);
755
756         foreach($comments AS $comment) {
757                 $comment->fromid = number_format($comment->fromid, 0, '', '');
758                 $comment_data[$comment->id] = $comment;
759         }
760         unset($comments);
761
762         foreach ($post_data AS $post) {
763                 if ($post->updated_time > $last_updated)
764                         $last_updated = $post->updated_time;
765
766                 //print_r($post);
767
768                 // parent_post_id - Erkennen von geteilten Posts?
769
770                 fbsync_createpost($a, $uid, $self, $contacts, $application_data, $post, $create_user);
771         }
772
773         foreach ($comment_data AS $comment) {
774                 fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $application_data, $comment);
775         }
776
777         foreach($likes AS $like) {
778                 $like->user_id = number_format($like->user_id, 0, '', '');
779
780                 fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like);
781
782         }
783
784         set_pconfig($uid,'fbsync','last_updated', $last_updated);
785
786 }
787 ?>