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