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