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