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