]> git.mxchange.org Git - friendica-addons.git/blob - fbsync/fbsync.php
Merge pull request #225 from annando/1411-leistungsschutzrecht
[friendica-addons.git] / fbsync / fbsync.php
1 <?php
2 /**
3  * Name: Facebook Sync
4  * Description: Synchronizes the Facebook Newsfeed
5  * Version: 1.0
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         register_hook('follow', 'addon/fbsync/fbsync.php', 'fbsync_follow');
29         register_hook('expire', 'addon/fbsync/fbsync.php', 'fbsync_expire');
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         unregister_hook('follow', 'addon/fbsync/fbsync.php', 'fbsync_follow');
37         unregister_hook('expire', 'addon/fbsync/fbsync.php', 'fbsync_expire');
38 }
39
40 function fbsync_follow($a, &$contact) {
41
42         logger("fbsync_follow: Check if contact is facebook contact. ".$contact["url"], LOGGER_DEBUG);
43
44         if (!strstr($contact["url"], "://www.facebook.com") AND !strstr($contact["url"], "://facebook.com") AND !strstr($contact["url"], "@facebook.com"))
45                 return;
46
47         // contact seems to be a facebook contact, so continue
48         $nickname = preg_replace("=https?://.*facebook.com/([\w.]*).*=ism", "$1", $contact["url"]);
49         $nickname = str_replace("@facebook.com", "", $nickname);
50
51         $uid = $a->user["uid"];
52
53         $access_token = get_pconfig($uid,'facebook','access_token');
54
55         $fql = array(
56                         "profile" => "SELECT id, pic_square, url, username, name FROM profile WHERE username = '$nickname'",
57                         "avatar" => "SELECT url FROM square_profile_pic WHERE id IN (SELECT id FROM #profile) AND size = 256");
58
59         $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
60
61         $feed = fetch_url($url);
62         $data = json_decode($feed);
63
64         $id = 0;
65
66         logger("fbsync_follow: Query id for nickname ".$nickname, LOGGER_DEBUG);
67
68         if (!is_array($data->data))
69                 return;
70
71         $contactdata = new stdClass;
72
73         foreach($data->data AS $query) {
74                 switch ($query->name) {
75                         case "profile":
76                                 $contactdata->id =  number_format($query->fql_result_set[0]->id, 0, '', '');
77                                 $contactdata->pic_square = $query->fql_result_set[0]->pic_square;
78                                 $contactdata->url = $query->fql_result_set[0]->url;
79                                 $contactdata->username = $query->fql_result_set[0]->username;
80                                 $contactdata->name = $query->fql_result_set[0]->name;
81                                 break;
82
83                         case "avatar":
84                                 $contactdata->pic_square = $query->fql_result_set[0]->url;
85                                 break;
86                 }
87         }
88
89         logger("fbsync_follow: Got contact for nickname ".$nickname." ".print_r($contactdata, true), LOGGER_DEBUG);
90
91         // Create contact
92         fbsync_fetch_contact($uid, $contactdata, true);
93
94         $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
95                 FROM `contact` WHERE `uid` = %d AND `alias` = '%s'",
96                                 intval($uid),
97                                 dbesc("facebook::".$contactdata->id));
98         if (count($r))
99                 $contact["contact"] = $r[0];
100 }
101
102
103 function fbsync_settings(&$a,&$s) {
104
105         // Settings are done inside the fbpost addon
106         return;
107
108         if(! local_user())
109                 return;
110
111         /* Add our stylesheet to the page so we can make our settings look nice */
112
113         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/fbsync/fbsync.css' . '" media="all" />' . "\r\n";
114
115         /* Get the current state of our config variables */
116
117         $enabled = get_pconfig(local_user(),'fbsync','sync');
118
119         $checked = (($enabled) ? ' checked="checked" ' : '');
120
121         $def_enabled = get_pconfig(local_user(),'fbsync','create_user');
122
123         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
124
125         /* Add some HTML to the existing form */
126
127         $s .= '<span id="settings_fbsync_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_fbsync_expanded\'); openClose(\'settings_fbsync_inflated\');">';
128         $s .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'. t('Facebook Import').'</h3>';
129         $s .= '</span>';
130         $s .= '<div id="settings_fbsync_expanded" class="settings-block" style="display: none;">';
131         $s .= '<span class="fakelink" onclick="openClose(\'settings_fbsync_expanded\'); openClose(\'settings_fbsync_inflated\');">';
132         $s .= '<img class="connector" src="images/facebook.png" /><h3 class="connector">'. t('Facebook Import').'</h3>';
133         $s .= '</span>';
134
135         $s .= '<div id="fbsync-enable-wrapper">';
136         $s .= '<label id="fbsync-enable-label" for="fbsync-checkbox">' . t('Import Facebook newsfeed') . '</label>';
137         $s .= '<input id="fbsync-checkbox" type="checkbox" name="fbsync" value="1" ' . $checked . '/>';
138         $s .= '</div><div class="clear"></div>';
139
140         $s .= '<div id="fbsync-create_user-wrapper">';
141         $s .= '<label id="fbsync-create_user-label" for="fbsync-create_user">' . t('Automatically create contacts') . '</label>';
142         $s .= '<input id="fbsync-create_user" type="checkbox" name="create_user" value="1" ' . $def_checked . '/>';
143         $s .= '</div><div class="clear"></div>';
144
145         /* provide a submit button */
146
147         $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fbsync-submit" name="fbsync-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
148
149 }
150
151 function fbsync_settings_post(&$a,&$b) {
152
153         if(x($_POST,'fbsync-submit')) {
154                 set_pconfig(local_user(),'fbsync','sync',intval($_POST['fbsync']));
155                 set_pconfig(local_user(),'fbsync','create_user',intval($_POST['create_user']));
156         }
157 }
158
159 function fbsync_cron($a,$b) {
160         $last = get_config('fbsync','last_poll');
161
162         $poll_interval = intval(get_config('fbsync','poll_interval'));
163         if(! $poll_interval)
164                 $poll_interval = FBSYNC_DEFAULT_POLL_INTERVAL;
165
166         if($last) {
167                 $next = $last + ($poll_interval * 60);
168                 if($next > time()) {
169                         logger('fbsync_cron: poll intervall not reached');
170                         return;
171                 }
172         }
173         logger('fbsync_cron: cron_start');
174
175         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fbsync' AND `k` = 'sync' AND `v` = '1' ORDER BY RAND()");
176         if(count($r)) {
177                 foreach($r as $rr) {
178                         fbsync_get_self($rr['uid']);
179
180                         logger('fbsync_cron: importing timeline from user '.$rr['uid']);
181                         fbsync_fetchfeed($a, $rr['uid']);
182                 }
183         }
184
185         logger('fbsync_cron: cron_end');
186
187         set_config('fbsync','last_poll', time());
188 }
189
190 function fbsync_expire($a,$b) {
191
192         $days = get_config('fbsync', 'expire');
193
194         if ($days == 0)
195                 return;
196
197         $r = q("DELETE FROM `item` WHERE `deleted` AND `network` = '%s'", dbesc(NETWORK_FACEBOOK));
198
199         require_once("include/items.php");
200
201         logger('fbsync_expire: expire_start');
202
203         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fbsync' AND `k` = 'sync' AND `v` = '1' ORDER BY RAND()");
204         if(count($r)) {
205                 foreach($r as $rr) {
206                         logger('fbsync_expire: user '.$rr['uid']);
207                         item_expire($rr['uid'], $days, NETWORK_FACEBOOK, true);
208                 }
209         }
210
211         logger('fbsync_expire: expire_end');
212 }
213
214 function fbsync_createpost($a, $uid, $self, $contacts, $applications, $post, $create_user) {
215
216         $access_token = get_pconfig($uid,'facebook','access_token');
217
218         require_once("include/oembed.php");
219         require_once("include/network.php");
220         require_once("include/items.php");
221
222         // check if it was already imported
223         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
224                 intval($uid),
225                 dbesc('fb::'.$post->post_id)
226         );
227         if(count($r))
228                 return;
229
230         $postarray = array();
231         $postarray['gravity'] = 0;
232         $postarray['uid'] = $uid;
233         $postarray['wall'] = 0;
234
235         $postarray['verb'] = ACTIVITY_POST;
236         $postarray['object-type'] = ACTIVITY_OBJ_NOTE; // default value - is maybe changed later when media is attached
237         $postarray['network'] =  dbesc(NETWORK_FACEBOOK);
238
239         $postarray['uri'] = "fb::".$post->post_id;
240         $postarray['thr-parent'] = $postarray['uri'];
241         $postarray['parent-uri'] = $postarray['uri'];
242         $postarray['plink'] = $post->permalink;
243
244         $postarray['author-name'] = $contacts[$post->actor_id]->name;
245         $postarray['author-link'] = $contacts[$post->actor_id]->url;
246         $postarray['author-avatar'] = $contacts[$post->actor_id]->pic_square;
247
248         $postarray['owner-name'] = $contacts[$post->source_id]->name;
249         $postarray['owner-link'] = $contacts[$post->source_id]->url;
250         $postarray['owner-avatar'] = $contacts[$post->source_id]->pic_square;
251
252         $contact_id = 0;
253
254         if (($post->parent_post_id != "") AND ($post->actor_id == $post->source_id)) {
255                 $pos = strpos($post->parent_post_id, "_");
256
257                 if ($pos != 0) {
258                         $user_id = substr($post->parent_post_id, 0, $pos);
259
260                         $userdata = fbsync_fetchuser($a, $uid, $user_id);
261
262                         $contact_id = $userdata["contact-id"];
263
264                         $postarray['contact-id'] = $contact_id;
265
266                         if (array_key_exists("name", $userdata) AND ($userdata["name"] != "") AND !link_compare($userdata["link"], $postarray['author-link'])) {
267                                 $postarray['owner-name'] = $userdata["name"];
268                                 $postarray['owner-link'] = $userdata["link"];
269                                 $postarray['owner-avatar'] = $userdata["avatar"];
270
271                                 if (!intval(get_config('system','wall-to-wall_share'))) {
272
273                                         $prebody = "[share author='".$postarray['author-name'].
274                                                 "' profile='".$postarray['author-link'].
275                                                 "' avatar='".$postarray['author-avatar']."']";
276
277                                         $postarray['author-name'] = $postarray['owner-name'];
278                                         $postarray['author-link'] = $postarray['owner-link'];
279                                         $postarray['author-avatar'] = $postarray['owner-avatar'];
280                                 }
281                         }
282                 }
283         }
284
285         if ($contact_id <= 0) {
286                 if ($post->actor_id != $post->source_id) {
287                         // Testing if we know the source or the actor
288                         $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], false);
289
290                         if (($contact_id == 0) and array_key_exists($post->actor_id, $contacts))
291                                 $contact_id = fbsync_fetch_contact($uid, $contacts[$post->actor_id], false);
292
293                         // If we don't know anyone, we guess we should know the source. Could be the wrong decision
294                         if ($contact_id == 0)
295                                 $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
296                 } else
297                         $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
298
299
300                 if ($contact_id == -1) {
301                         logger('fbsync_createpost: Contact is blocked. Post not imported '.print_r($post, true), LOGGER_DEBUG);
302                         return;
303                 } elseif (($contact_id <= 0) AND !$create_user) {
304                         logger('fbsync_createpost: No matching contact found. Post not imported '.print_r($post, true), LOGGER_DEBUG);
305                         return;
306                 } elseif ($contact_id == 0) {
307                         // This case should never happen
308                         logger('fbsync_createpost: No matching contact found. Using own id. (Should never happen) '.print_r($post, true), LOGGER_DEBUG);
309                         $contact_id = $self[0]["id"];
310                 }
311
312                 $postarray['contact-id'] = $contact_id;
313         }
314
315         $postarray["body"] = (isset($post->message) ? escape_tags($post->message) : '');
316
317         $msgdata = fbsync_convertmsg($a, $postarray["body"]);
318
319         $postarray["body"] = $msgdata["body"];
320         $postarray["tag"] = $msgdata["tags"];
321
322         // Change the object type when an attachment is present
323         if (isset($post->attachment->fb_object_type))
324                 logger('fb_object_type: '.$post->attachment->fb_object_type." ".print_r($post->attachment, true), LOGGER_DEBUG);
325                 switch ($post->attachment->fb_object_type) {
326                         case 'photo':
327                                 $postarray['object-type'] = ACTIVITY_OBJ_IMAGE; // photo is deprecated: http://activitystrea.ms/head/activity-schema.html#image
328                                 break;
329                         case 'video':
330                                 $postarray['object-type'] = ACTIVITY_OBJ_VIDEO;
331                                 break;
332                         case '':
333                                 //$postarray['object-type'] = ACTIVITY_OBJ_BOOKMARK;
334                                 break;
335                         default:
336                                 logger('Unknown object type '.$post->attachment->fb_object_type, LOGGER_DEBUG);
337                                 break;
338                 }
339
340         $pagedata = array();
341         $content = "";
342         $pagedata["type"] = "";
343
344         if (isset($post->attachment->name) and isset($post->attachment->href)) {
345                 $post->attachment->href = original_url($post->attachment->href);
346                 $oembed_data = oembed_fetch_url($post->attachment->href);
347                 $pagedata["type"] = $oembed_data->type;
348                 if ($pagedata["type"] == "rich")
349                         $pagedata["type"] = "link";
350
351                 $pagedata["url"] = $post->attachment->href;
352                 $pagedata["title"] = $post->attachment->name;
353                 $content = "[bookmark=".$post->attachment->href."]".$post->attachment->name."[/bookmark]";
354
355                 // If a link is not only attached but also added in the body, look if it can be removed in the body.
356                 $removedlink = trim(str_replace($post->attachment->href, "", $postarray["body"]));
357
358                 if (($removedlink == "") OR strstr($postarray["body"], $removedlink))
359                         $postarray["body"] = $removedlink;
360
361         } elseif (isset($post->attachment->name) AND ($post->attachment->name != ""))
362                 $content = "[b]" . $post->attachment->name."[/b]";
363
364         $pagedata["text"] = "";
365         if (isset($post->attachment->description) and ($post->attachment->fb_object_type != "photo"))
366                 $pagedata["text"] = $post->attachment->description;
367
368         if (isset($post->attachment->caption) and ($post->attachment->fb_object_type == "photo"))
369                 $pagedata["text"] = $post->attachment->caption;
370
371         if ($pagedata["text"].$post->attachment->href.$content.$postarray["body"] == "")
372                 return;
373
374         if (isset($post->attachment->media) AND (($pagedata["type"] == "") OR ($pagedata["type"] == "link"))) {
375                 foreach ($post->attachment->media AS $media) {
376
377                         if (isset($media->type))
378                                 $pagedata["type"] = $media->type;
379
380                         if (isset($media->src))
381                                 $pagedata["images"][0]["src"] = $media->src;
382
383                         if (isset($media->photo)) {
384                                 if (isset($media->photo->images) AND (count($media->photo->images) > 1))
385                                         $pagedata["images"][0]["src"] = $media->photo->images[1]->src;
386
387                                 if (isset($media->photo->fbid)) {
388                                         logger('fbsync_createpost: fetching fbid '.$media->photo->fbid, LOGGER_DEBUG);
389                                         $url = "https://graph.facebook.com/".$media->photo->fbid."?access_token=".$access_token;
390                                         $feed = fetch_url($url);
391                                         $data = json_decode($feed);
392                                         if (isset($data->images)) {
393                                                 $pagedata["images"][0]["src"] = $data->images[0]->source;
394                                                 logger('fbsync_createpost: got fbid '.$media->photo->fbid.' image '.$pagedata["images"][0]["src"], LOGGER_DEBUG);
395                                         } else
396                                                 logger('fbsync_createpost: error fetching fbid '.$media->photo->fbid.' '.print_r($data, true), LOGGER_DEBUG);
397                                 }
398                         }
399
400                         $pagedata["images"][0]["src"] = fbpost_cleanpicture($pagedata["images"][0]["src"]);
401
402                         if (isset($media->href) AND ($pagedata["images"][0]["src"] != "") AND ($media->href != "")) {
403                                 $media->href = original_url($media->href);
404                                 $pagedata["url"] = $media->href;
405                                 $content .= "\n".'[url='.$media->href.'][img]'.$pagedata["images"][0]["src"].'[/img][/url]';
406                         } else {
407                                 if ($pagedata["images"][0]["src"] != "")
408                                         $content .= "\n".'[img]'.$pagedata["images"][0]["src"].'[/img]';
409
410                                 // if just a link, it may be a wall photo - check
411                                 if (isset($post->link))
412                                         $content .= fbpost_get_photo($media->href);
413                         }
414                 }
415         }
416
417         if ($pagedata["type"] != "") {
418                 if ($pagedata["type"] == "link")
419                         $postarray["object-type"] = ACTIVITY_OBJ_BOOKMARK;
420
421                 $postarray["body"] .= add_page_info_data($pagedata);
422         } else {
423                 if ($content)
424                         $postarray["body"] .= "\n".trim($content);
425
426                 if ($pagedata["text"])
427                         $postarray["body"] .= "\n[quote]".trim($pagedata["text"])."[/quote]";
428
429                 $postarray["body"] = trim($postarray["body"]);
430         }
431
432         if (trim($postarray["body"]) == "")
433                 return;
434
435         if ($prebody != "")
436                 $postarray["body"] = $prebody.$postarray["body"]."[/share]";
437
438         $postarray['created'] = datetime_convert('UTC','UTC',date("c", $post->created_time));
439         $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $post->updated_time));
440
441         $postarray['app'] = $applications[$post->app_id]->display_name;
442
443         if ($postarray['app'] == "")
444                 $postarray['app'] = "Facebook";
445
446         if(isset($post->privacy) && $post->privacy->value !== '') {
447                 $postarray['private'] = 1;
448                 $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
449         }
450
451         /*
452         $postarray["location"] = $post->place->name;
453         postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
454         */
455
456         //$types = array(46, 80, 237, 247, 308);
457         //if (!in_array($post->type, $types))
458         //      $postarray["body"] = "Type: ".$post->type."\n".$postarray["body"];
459         //print_r($post);
460         //print_r($postarray);
461         $item = item_store($postarray);
462         logger('fbsync_createpost: User '.$self[0]["nick"].' posted feed item '.$item, LOGGER_DEBUG);
463 }
464
465 function fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $applications, $comment) {
466
467         // check if it was already imported
468         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
469                 intval($uid),
470                 dbesc('fb::'.$comment->id)
471         );
472         if(count($r))
473                 return;
474
475         // check if it was an own post (separate posting for performance reasons)
476         $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
477                 intval($uid),
478                 dbesc('fb::'.$comment->id)
479         );
480         if(count($r))
481                 return;
482
483         $parent_uri = "";
484         $parent_contact = 0;
485         $parent_nick = "";
486
487         // Fetch the parent uri (Checking if the parent exists)
488         $r = q("SELECT `uri`, `contact-id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
489                 intval($uid),
490                 dbesc('fb::'.$comment->post_id)
491         );
492         if(count($r)) {
493                 $parent_uri = $r[0]["uri"];
494                 $parent_contact = $r[0]["contact-id"];
495         }
496
497         // check if it is a reply to an own post (separate posting for performance reasons)
498         $r = q("SELECT `uri`, `contact-id` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
499                 intval($uid),
500                 dbesc('fb::'.$comment->post_id)
501         );
502         if(count($r)) {
503                 $parent_uri = $r[0]["uri"];
504                 $parent_contact = $r[0]["contact-id"];
505         }
506
507         // No parent? Then quit
508         if ($parent_uri == "")
509                 return;
510
511         //logger("fbsync_createcomment: Checking if parent contact is blocked: ".$parent_contact." - ".$parent_uri, LOGGER_DEBUG);
512
513         // Check if the contact id was blocked
514         if ($parent_contact > 0) {
515                 $r = q("SELECT `blocked`, `readonly`, `nick` FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
516                         intval($uid), intval($parent_contact));
517
518                 // Should only happen if someone deleted the contact manually
519                 if(!count($r)) {
520                         logger("fbsync_createcomment: UID ".$uid." - Contact ".$parent_contact." doesn't seem to exist.", LOGGER_DEBUG);
521                         return;
522                 }
523
524                 // Is blocked? Then return
525                 if ($r[0]["readonly"] OR $r[0]["blocked"]) {
526                         logger("fbsync_createcomment: UID ".$uid." - Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
527                         return;
528                 }
529
530                 $parent_nick = $r[0]["nick"];
531                 logger("fbsync_createcomment: UID ".$uid." - Contact '".$r[0]["nick"]."' isn't blocked. ".print_r($r, true), LOGGER_DEBUG);
532         }
533
534         $postarray = array();
535         $postarray['gravity'] = 0;
536         $postarray['uid'] = $uid;
537         $postarray['wall'] = 0;
538
539         $postarray['verb'] = ACTIVITY_POST;
540         $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
541         $postarray['network'] =  dbesc(NETWORK_FACEBOOK);
542
543         $postarray['uri'] = "fb::".$comment->id;
544         $postarray['thr-parent'] = $parent_uri;
545         $postarray['parent-uri'] = $parent_uri;
546         //$postarray['plink'] = $comment->permalink;
547
548         $contact_id = fbsync_fetch_contact($uid, $contacts[$comment->fromid], array(), false);
549
550         $contact_nick = $contacts[$comment->fromid]->name;
551
552         if ($contact_id == -1) {
553                 logger('fbsync_createcomment: Contact was blocked. Comment not imported '.print_r($comment, true), LOGGER_DEBUG);
554                 return;
555         }
556
557         // If no contact was found, take it from the thread owner
558         if ($contact_id <= 0) {
559                 $contact_id = $parent_contact;
560                 $contact_nick = $parent_nick;
561         }
562
563         // This case here should never happen
564         if ($contact_id <= 0) {
565                 $contact_id = $self[0]["id"];
566                 $contact_nick = $self[0]["nick"];
567         }
568
569         if ($comment->fromid != $self_id) {
570                 $postarray['contact-id'] = $contact_id;
571                 $postarray['owner-name'] = $contacts[$comment->fromid]->name;
572                 $postarray['owner-link'] = $contacts[$comment->fromid]->url;
573                 $postarray['owner-avatar'] = $contacts[$comment->fromid]->pic_square;
574         } else {
575                 $postarray['contact-id'] = $self[0]["id"];
576                 $postarray['owner-name'] = $self[0]["name"];
577                 $postarray['owner-link'] = $self[0]["url"];
578                 $postarray['owner-avatar'] = $self[0]["photo"];
579                 $contact_nick = $self[0]["nick"];
580         }
581
582         $postarray['author-name'] = $postarray['owner-name'];
583         $postarray['author-link'] = $postarray['owner-link'];
584         $postarray['author-avatar'] = $postarray['owner-avatar'];
585
586         $msgdata = fbsync_convertmsg($a, $comment->text);
587
588         $postarray["body"] = $msgdata["body"];
589         $postarray["tag"] = $msgdata["tags"];
590
591         $postarray['created'] = datetime_convert('UTC','UTC',date("c", $comment->time));
592         $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $comment->time));
593
594         $postarray['app'] = $applications[$comment->app_id]->display_name;
595
596         if ($postarray['app'] == "")
597                 $postarray['app'] = "Facebook";
598
599         if (trim($postarray["body"]) == "")
600                 return;
601
602         $item = item_store($postarray);
603         logger('fbsync_createcomment: UID '.$uid.' - CID '.$postarray['contact-id'].' - Nick '.$contact_nick.' posted comment '.$item, LOGGER_DEBUG);
604
605         if ($item == 0)
606                 return;
607
608         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
609                 dbesc($postarray['parent-uri']),
610                 intval($uid)
611         );
612
613         if(count($myconv)) {
614                 $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
615
616                 $own_contact = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
617                         intval($uid), dbesc("facebook::".$self_id));
618
619                 if (!count($own_contact))
620                         return;
621
622                 foreach($myconv as $conv) {
623
624                         // now if we find a match, it means we're in this conversation
625                         if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_contact[0]["url"]))
626                                 continue;
627
628                         require_once('include/enotify.php');
629
630                         $conv_parent = $conv['parent'];
631
632                         $notifyarr = array(
633                                         'type'         => NOTIFY_COMMENT,
634                                         'notify_flags' => $user[0]['notify-flags'],
635                                         'language'     => $user[0]['language'],
636                                         'to_name'      => $user[0]['username'],
637                                         'to_email'     => $user[0]['email'],
638                                         'uid'          => $user[0]['uid'],
639                                         'item'         => $postarray,
640                                         'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
641                                         'source_name'  => $postarray['author-name'],
642                                         'source_link'  => $postarray['author-link'],
643                                         'source_photo' => $postarray['author-avatar'],
644                                         'verb'         => ACTIVITY_POST,
645                                         'otype'        => 'item',
646                                         'parent'       => $conv_parent,
647                         );
648
649                         notification($notifyarr);
650
651                         // only send one notification
652                         break;
653                 }
654         }
655 }
656
657 function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
658
659         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
660                                 dbesc("fb::".$like->post_id),
661                                 intval($uid)
662                 );
663
664         if (count($r))
665                 $orig_post = $r[0];
666         else
667                 return;
668
669         // If we posted the like locally, it will be found with our url, not the FB url.
670
671         $second_url = (($like->user_id == $self_id) ? $self[0]["url"] : $contacts[$like->user_id]->url);
672
673         $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
674                 AND (`author-link` = '%s' OR `author-link` = '%s') LIMIT 1",
675                 dbesc($orig_post["uri"]),
676                 intval($uid),
677                 dbesc(ACTIVITY_LIKE),
678                 dbesc($contacts[$like->user_id]->url),
679                 dbesc($second_url)
680         );
681
682         if (count($r))
683                 return;
684
685         $contact_id = fbsync_fetch_contact($uid, $contacts[$like->user_id], array(), false);
686
687         if ($contact_id <= 0)
688                 $contact_id = $self[0]["id"];
689
690         $likedata = array();
691         $likedata['parent'] = $orig_post['id'];
692
693         $likedata['verb'] = ACTIVITY_LIKE;
694         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
695         $likedate['network'] =  dbesc(NETWORK_FACEBOOK);
696
697         $likedata['gravity'] = 3;
698         $likedata['uid'] = $uid;
699         $likedata['wall'] = 0;
700         $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
701         $likedata['parent-uri'] = $orig_post["uri"];
702         $likedata['app'] = "Facebook";
703
704         if ($like->user_id != $self_id) {
705                 $likedata['contact-id'] = $contact_id;
706                 $likedata['author-name'] = $contacts[$like->user_id]->name;
707                 $likedata['author-link'] = $contacts[$like->user_id]->url;
708                 $likedata['author-avatar'] = $contacts[$like->user_id]->pic_square;
709         } else {
710                 $likedata['contact-id'] = $self[0]["id"];
711                 $likedata['author-name'] = $self[0]["name"];
712                 $likedata['author-link'] = $self[0]["url"];
713                 $likedata['author-avatar'] = $self[0]["photo"];
714         }
715
716         $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
717
718         $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
719         $post_type = t('status');
720
721         $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
722         $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
723
724         $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
725
726         $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
727                 '<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>';
728
729
730         $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `author-link` = '%s' AND `verb` = '%s' AND `uid` = %d LIMIT 1",
731                                 dbesc($likedata['parent-uri']),
732                                 dbesc($likedata['author-link']),
733                                 dbesc(ACTIVITY_LIKE),
734                                 intval($uid)
735                 );
736
737         if (count($r))
738                 return;
739
740         $item = item_store($likedata);
741         logger('fbsync_createlike: liked item '.$item.'. User '.$self[0]["nick"], LOGGER_DEBUG);
742 }
743
744 function fbsync_fetch_contact($uid, $contact, $create_user) {
745
746         if($contact->url == "")
747                 return(0);
748
749         // Check if the unique contact is existing
750         // To-Do: only update once a while
751         $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
752                 dbesc(normalise_link($contact->url)));
753
754         if (count($r) == 0)
755                 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
756                         dbesc(normalise_link($contact->url)),
757                         dbesc($contact->name),
758                         dbesc($contact->username),
759                         dbesc($contact->pic_square));
760         else
761                 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
762                         dbesc($contact->name),
763                         dbesc($contact->username),
764                         dbesc($contact->pic_square),
765                         dbesc(normalise_link($contact->url)));
766
767         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
768                 intval($uid), dbesc("facebook::".$contact->id));
769
770         if(!count($r) AND !$create_user)
771                 return(0);
772
773         if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
774                 logger("fbsync_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
775                 return(-1);
776         }
777
778         $avatarpicture = $contact->pic_square;
779
780         if(!count($r)) {
781                 // create contact record
782                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
783                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
784                                         `writable`, `blocked`, `readonly`, `pending`)
785                                         VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0)",
786                         intval($uid),
787                         dbesc(datetime_convert()),
788                         dbesc($contact->url),
789                         dbesc(normalise_link($contact->url)),
790                         dbesc($contact->username."@facebook.com"),
791                         dbesc("facebook::".$contact->id),
792                         dbesc($contact->id),
793                         dbesc("facebook::".$contact->id),
794                         dbesc($contact->name),
795                         dbesc($contact->username),
796                         dbesc($avatarpicture),
797                         dbesc(NETWORK_FACEBOOK),
798                         intval(CONTACT_IS_FRIEND),
799                         intval(1),
800                         intval(1)
801                 );
802
803                 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
804                         dbesc("facebook::".$contact->id),
805                         intval($uid)
806                         );
807
808                 if(! count($r))
809                         return(false);
810
811                 $contact_id  = $r[0]['id'];
812
813                 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
814                         intval($uid)
815                 );
816
817                 if($g && intval($g[0]['def_gid'])) {
818                         require_once('include/group.php');
819                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
820                 }
821
822                 require_once("Photo.php");
823
824                 $photos = import_profile_photo($avatarpicture,$uid,$contact_id);
825
826                 q("UPDATE `contact` SET `photo` = '%s',
827                                         `thumb` = '%s',
828                                         `micro` = '%s',
829                                         `name-date` = '%s',
830                                         `uri-date` = '%s',
831                                         `avatar-date` = '%s'
832                                 WHERE `id` = %d",
833                         dbesc($photos[0]),
834                         dbesc($photos[1]),
835                         dbesc($photos[2]),
836                         dbesc(datetime_convert()),
837                         dbesc(datetime_convert()),
838                         dbesc(datetime_convert()),
839                         intval($contact_id)
840                 );
841         } else {
842                 // update profile photos once every 12 hours as we have no notification of when they change.
843                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
844
845                 // check that we have all the photos, this has been known to fail on occasion
846                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
847
848                         logger("fbsync_fetch_contact: Updating contact ".$contact->username, LOGGER_DEBUG);
849
850                         require_once("Photo.php");
851
852                         $photos = import_profile_photo($avatarpicture, $uid, $r[0]['id']);
853
854                         q("UPDATE `contact` SET `photo` = '%s',
855                                                 `thumb` = '%s',
856                                                 `micro` = '%s',
857                                                 `name-date` = '%s',
858                                                 `uri-date` = '%s',
859                                                 `avatar-date` = '%s',
860                                                 `url` = '%s',
861                                                 `nurl` = '%s',
862                                                 `addr` = '%s',
863                                                 `name` = '%s',
864                                                 `nick` = '%s',
865                                                 `notify` = '%s'
866                                         WHERE `id` = %d",
867                                 dbesc($photos[0]),
868                                 dbesc($photos[1]),
869                                 dbesc($photos[2]),
870                                 dbesc(datetime_convert()),
871                                 dbesc(datetime_convert()),
872                                 dbesc(datetime_convert()),
873                                 dbesc($contact->url),
874                                 dbesc(normalise_link($contact->url)),
875                                 dbesc($contact->username."@facebook.com"),
876                                 dbesc($contact->name),
877                                 dbesc($contact->username),
878                                 dbesc($contact->id),
879                                 intval($r[0]['id'])
880                         );
881                 }
882         }
883         return($r[0]["id"]);
884 }
885
886 function fbsync_get_self($uid) {
887         $access_token = get_pconfig($uid,'facebook','access_token');
888         if(! $access_token)
889                 return;
890         $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
891         if($s) {
892                 $j = json_decode($s);
893                 set_pconfig($uid,'fbsync','self_id',(string) $j->id);
894         }
895 }
896
897 function fbsync_convertmsg($a, $body) {
898         $str_tags = '';
899
900         $tags = get_tags($body);
901
902         if(count($tags)) {
903                 foreach($tags as $tag) {
904                         if (strstr(trim($tag), " "))
905                                 continue;
906
907                         if(strpos($tag,'#') === 0) {
908                                 if(strpos($tag,'[url='))
909                                         continue;
910
911                                 // don't link tags that are already embedded in links
912
913                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
914                                         continue;
915                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
916                                         continue;
917
918                                 $basetag = str_replace('_',' ',substr($tag,1));
919                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
920                                 if(strlen($str_tags))
921                                         $str_tags .= ',';
922                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
923                                 continue;
924                         } elseif(strpos($tag,'@') === 0) {
925                                 $basetag = substr($tag,1);
926                                 $body = str_replace($tag,'@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
927                         }
928
929                 }
930         }
931
932         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
933         if($cnt) {
934                 foreach($matches as $mtch) {
935                         if(strlen($str_tags))
936                                 $str_tags .= ',';
937                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';
938                 }
939         }
940
941         return(array("body"=>$body, "tags"=>$str_tags));
942
943 }
944
945 function fbsync_fetchuser($a, $uid, $id) {
946         $access_token = get_pconfig($uid,'facebook','access_token');
947         $self_id = get_pconfig($uid,'fbsync','self_id');
948
949         $user = array();
950
951         $contact = q("SELECT `id`, `name`, `url`, `photo`  FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
952                 intval($uid), dbesc("facebook::".$id));
953
954         if (count($contact)) {
955                 if (($contact[0]["readonly"] OR $contact[0]["blocked"])) {
956                         logger("fbsync_fetchuser: Contact '".$contact[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
957                         $user["contact-id"] = -1;
958                 } else
959                         $user["contact-id"] = $contact[0]["id"];
960
961                 $user["name"] = $contact[0]["name"];
962                 $user["link"] = $contact[0]["url"];
963                 $user["avatar"] = $contact[0]["photo"];
964
965                 return($user);
966         }
967
968         $own_contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
969                 intval($uid), dbesc("facebook::".$self_id));
970
971         if (!count($own_contact))
972                 return($user);
973
974         $fql = "SELECT name, url, pic_square FROM profile WHERE id = ".$id;
975
976         $url = "https://graph.facebook.com/fql?q=".urlencode($fql)."&access_token=".$access_token;
977
978         $feed = fetch_url($url);
979         $data = json_decode($feed);
980
981         if (is_array($data->data)) {
982                 $user["contact-id"] = $own_contact[0]["id"];
983                 $user["name"] = $data->data[0]->name;
984                 $user["link"] = $data->data[0]->url;
985                 $user["avatar"] = $data->data[0]->pic_square;
986         }
987         return($user);
988 }
989
990 function fbsync_fetchfeed($a, $uid) {
991         $access_token = get_pconfig($uid,'facebook','access_token');
992         $last_updated = get_pconfig($uid,'fbsync','last_updated');
993         $self_id = get_pconfig($uid,'fbsync','self_id');
994
995         $create_user = get_pconfig($uid, 'fbsync', 'create_user');
996         $do_likes = get_config('fbsync', 'do_likes');
997
998         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
999                 intval($uid)
1000         );
1001
1002         $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
1003                 intval($uid)
1004         );
1005         if(! count($user))
1006                 return;
1007
1008         require_once('include/items.php');
1009
1010         //if ($last_updated == "")
1011                 $last_updated = 0;
1012
1013         logger("fbsync_fetchfeed: fetching content for user ".$self_id);
1014
1015         $fql = array(
1016                 "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",
1017                 "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",
1018                 "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",
1019                 "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",
1020                 "avatars" => "SELECT id, real_size, size, url FROM square_profile_pic WHERE id IN (SELECT id FROM #profiles) AND size = 256 LIMIT 500");
1021
1022         if ($do_likes) {
1023                 $fql["likes"] = "SELECT post_id, user_id FROM like WHERE post_id IN (SELECT post_id FROM #posts)";
1024                 $fql["profiles"] .= " OR id IN (SELECT user_id FROM #likes)";
1025         }
1026
1027         $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
1028
1029         $feed = fetch_url($url);
1030         $data = json_decode($feed);
1031
1032         if (!is_array($data->data)) {
1033                 logger("fbsync_fetchfeed: Error fetching data for user ".$uid.": ".print_r($data, true));
1034                 return;
1035         }
1036
1037         $posts = array();
1038         $comments = array();
1039         $likes = array();
1040         $profiles = array();
1041         $applications = array();
1042         $avatars = array();
1043
1044         foreach($data->data AS $query) {
1045                 switch ($query->name) {
1046                         case "posts":
1047                                 $posts = array_reverse($query->fql_result_set);
1048                                 break;
1049                         case "comments":
1050                                 $comments = $query->fql_result_set;
1051                                 break;
1052                         case "likes":
1053                                 $likes = $query->fql_result_set;
1054                                 break;
1055                         case "profiles":
1056                                 $profiles = $query->fql_result_set;
1057                                 break;
1058                         case "applications":
1059                                 $applications = $query->fql_result_set;
1060                                 break;
1061                         case "avatars":
1062                                 $avatars = $query->fql_result_set;
1063                                 break;
1064                 }
1065         }
1066
1067         $square_avatars = array();
1068         $contacts = array();
1069         $application_data = array();
1070         $post_data = array();
1071         $comment_data = array();
1072
1073         foreach ($avatars AS $avatar) {
1074                 $avatar->id = number_format($avatar->id, 0, '', '');
1075                 $square_avatars[$avatar->id] = $avatar;
1076         }
1077         unset($avatars);
1078
1079         foreach ($profiles AS $profile) {
1080                 $profile->id = number_format($profile->id, 0, '', '');
1081
1082                 if ($square_avatars[$profile->id]->url != "")
1083                         $profile->pic_square = $square_avatars[$profile->id]->url;
1084
1085                 $contacts[$profile->id] = $profile;
1086         }
1087         unset($profiles);
1088         unset($square_avatars);
1089
1090         foreach ($applications AS $application) {
1091                 $application->app_id = number_format($application->app_id, 0, '', '');
1092                 $application_data[$application->app_id] = $application;
1093         }
1094         unset($applications);
1095
1096         foreach ($posts AS $post) {
1097                 $post->actor_id = number_format($post->actor_id, 0, '', '');
1098                 $post->source_id = number_format($post->source_id, 0, '', '');
1099                 $post->app_id = number_format($post->app_id, 0, '', '');
1100                 $post_data[$post->post_id] = $post;
1101         }
1102         unset($posts);
1103
1104         foreach($comments AS $comment) {
1105                 $comment->fromid = number_format($comment->fromid, 0, '', '');
1106                 $comment_data[$comment->id] = $comment;
1107         }
1108         unset($comments);
1109
1110         foreach ($post_data AS $post) {
1111                 if ($post->updated_time > $last_updated)
1112                         $last_updated = $post->updated_time;
1113                 fbsync_createpost($a, $uid, $self, $contacts, $application_data, $post, $create_user);
1114         }
1115
1116         foreach ($comment_data AS $comment) {
1117                 fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $application_data, $comment);
1118         }
1119
1120         foreach($likes AS $like) {
1121                 $like->user_id = number_format($like->user_id, 0, '', '');
1122
1123                 fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like);
1124         }
1125
1126         set_pconfig($uid,'fbsync','last_updated', $last_updated);
1127 }
1128 ?>