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