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