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