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