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