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