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