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