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