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