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