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