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