]> git.mxchange.org Git - friendica-addons.git/commitdiff
Merge pull request #159 from annando/master
authortobiasd <tobias.diekershoff@gmx.net>
Mon, 28 Oct 2013 06:50:54 +0000 (23:50 -0700)
committertobiasd <tobias.diekershoff@gmx.net>
Mon, 28 Oct 2013 06:50:54 +0000 (23:50 -0700)
Facebook sync

fbpost/fbpost.php
fbsync/fbsync.css [new file with mode: 0755]
fbsync/fbsync.php [new file with mode: 0644]
pumpio/oauth/http.php

index 6a0eb1973dabaeadd8bf66fb5fe7ab1cf3c3c2fa..fb6ebcda2f33f0566d11171ff324890baac43d7d 100644 (file)
@@ -184,7 +184,7 @@ function fbpost_content(&$a) {
        }
 
        $o = '';
-       
+
        $fb_installed = false;
        if (get_pconfig(local_user(),'facebook','post')) {
                $access_token = get_pconfig(local_user(),'facebook','access_token');
@@ -196,7 +196,7 @@ function fbpost_content(&$a) {
                        }
                }
        }
-       
+
        $appid = get_config('facebook','appid');
 
        if(! $appid) {
@@ -212,8 +212,10 @@ function fbpost_content(&$a) {
        if(! $fb_installed) { 
                $o .= '<div id="fbpost-enable-wrapper">';
 
+               //read_stream,publish_stream,manage_pages,photo_upload,user_groups,offline_access
+
                $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri=' 
-                       . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=read_stream,publish_stream,manage_pages,photo_upload,user_groups,offline_access">' . t('Install Facebook Post connector for this account.') . '</a>';
+                       . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=export_stream,read_stream,publish_stream,manage_pages,photo_upload,user_groups,publish_actions,user_friends,create_note,share_item,video_upload,status_update">' . t('Install Facebook Post connector for this account.') . '</a>';
                $o .= '</div>';
        }
 
@@ -225,7 +227,7 @@ function fbpost_content(&$a) {
                $o .= '<div id="fbpost-enable-wrapper">';
 
                $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri=' 
-                       . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=read_stream,publish_stream,manage_pages,photo_upload,user_groups,offline_access">' . t('Re-authenticate [This is necessary whenever your Facebook password is changed.]') . '</a>';
+                       . $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=export_stream,read_stream,publish_stream,manage_pages,photo_upload,user_groups,publish_actions,user_friends,create_note,share_item,video_upload,status_update">' . t('Re-authenticate [This is necessary whenever your Facebook password is changed.]') . '</a>';
                $o .= '</div>';
 
                $o .= '<div id="fbpost-post-default-form">';
@@ -291,7 +293,7 @@ function fbpost_content(&$a) {
 function fbpost_plugin_settings(&$a,&$b) {
 
        $b .= '<div class="settings-block">';
-       $b .= '<h3>' . t('Facebook') . '</h3>';
+       $b .= '<h3>' . t('Facebook Post Settings') . '</h3>';
        $b .= '<a href="fbpost">' . t('Facebook Post Settings') . '</a><br />';
        $b .= '</div>';
 
@@ -306,21 +308,21 @@ function fbpost_plugin_admin(&$a, &$o){
 
 
        $o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("fbsave") . '">';
-       
+
        $o .= '<h4>' . t('Facebook API Key') . '</h4>';
-       
+
        $appid  = get_config('facebook', 'appid'  );
        $appsecret = get_config('facebook', 'appsecret' );
-       
+
        $ret1 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appid' LIMIT 1");
        $ret2 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appsecret' LIMIT 1");
        if ((count($ret1) > 0 && $ret1[0]['v'] != $appid) || (count($ret2) > 0 && $ret2[0]['v'] != $appsecret)) $o .= t('Error: it appears that you have specified the App-ID and -Secret in your .htconfig.php file. As long as they are specified there, they cannot be set using this form.<br><br>');
-       
+
        $o .= '<label for="fb_appid">' . t('App-ID / API-Key') . '</label><input id="fb_appid" name="appid" type="text" value="' . escape_tags($appid ? $appid : "") . '"><br style="clear: both;">';
        $o .= '<label for="fb_appsecret">' . t('Application secret') . '</label><input id="fb_appsecret" name="appsecret" type="text" value="' . escape_tags($appsecret ? $appsecret : "") . '"><br style="clear: both;">';
 
        $o .= '<input type="submit" name="fb_save_keys" value="' . t('Save') . '">';
-       
+
 }
 
 /**
@@ -329,7 +331,7 @@ function fbpost_plugin_admin(&$a, &$o){
 
 function fbpost_plugin_admin_post(&$a){
        check_form_security_token_redirectOnErr('/admin/plugins/fbpost', 'fbsave');
-       
+
        if (x($_REQUEST,'fb_save_keys')) {
                set_config('facebook', 'appid', $_REQUEST['appid']);
                set_config('facebook', 'appsecret', $_REQUEST['appsecret']);
@@ -357,6 +359,131 @@ function fbpost_jot_nets(&$a,&$b) {
        }
 }
 
+function fbpost_createmsg($b) {
+       require_once("include/bbcode.php");
+       require_once("include/html2plain.php");
+
+       // Looking for the first image
+       $image = '';
+       if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
+               $image = $matches[3];
+
+       if ($image == '')
+               if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
+                       $image = $matches[1];
+
+       $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
+
+       // When saved into the database the content is sent through htmlspecialchars
+       // That means that we have to decode all image-urls
+       $image = htmlspecialchars_decode($image);
+
+       $body = $b["body"];
+       if ($b["title"] != "")
+               $body = $b["title"]."\n\n".$body;
+
+       if (strpos($body, "[bookmark") !== false) {
+               // splitting the text in two parts:
+               // before and after the bookmark
+               $pos = strpos($body, "[bookmark");
+               $body1 = substr($body, 0, $pos);
+               $body2 = substr($body, $pos);
+
+               // Removing all quotes after the bookmark
+               // they are mostly only the content after the bookmark.
+               $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
+               $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
+
+               $pos2 = strpos($body2, "[/bookmark]");
+               if ($pos2)
+                       $body2 = substr($body2, $pos2 + 11);
+
+               $body = $body1.$body2;
+       }
+
+       // Add some newlines so that the message could be cut better
+       $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
+                               array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
+
+       // remove the recycle signs and the names since they aren't helpful on twitter
+       // $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
+       // $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
+
+       // At first convert the text to html
+       $html = bbcode($body, false, false, 2);
+
+       // Then convert it to plain text
+       //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
+       $msg = trim(html2plain($html, 0, true));
+       $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
+
+       // Removing multiple newlines
+       while (strpos($msg, "\n\n\n") !== false)
+               $msg = str_replace("\n\n\n", "\n\n", $msg);
+
+       // Removing multiple spaces
+       while (strpos($msg, "  ") !== false)
+               $msg = str_replace("  ", " ", $msg);
+
+       // Removing URLs
+       $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
+
+       $msg = trim($msg);
+
+       $link = '';
+       $linkname = '';
+       // look for bookmark-bbcode and handle it with priority
+       if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches)) {
+               $link = $matches[1];
+               $linkname = $matches[2];
+       }
+
+       $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
+
+       if ($multiplelinks)
+               $linkname = '';
+
+       // If there is no bookmark element then take the first link
+       if ($link == '') {
+               $links = collecturls($html);
+               if (sizeof($links) > 0) {
+                       reset($links);
+                       $link = current($links);
+               }
+               $multiplelinks = (sizeof($links) > 1);
+       }
+
+       $msglink = "";
+       if ($multiplelinks)
+               $msglink = $b["plink"];
+       else if ($link != "")
+               $msglink = $link;
+       else if ($multipleimages)
+               $msglink = $b["plink"];
+       else if ($image != "")
+               $msglink = $image;
+
+       // Removing multiple spaces - again
+       while (strpos($msg, "  ") !== false)
+               $msg = str_replace("  ", " ", $msg);
+
+       if ($msglink != "") {
+               // Looking if the link points to an image
+               $img_str = fetch_url($msglink);
+
+               $tempfile = tempnam(get_config("system","temppath"), "cache");
+               file_put_contents($tempfile, $img_str);
+               $mime = image_type_to_mime_type(exif_imagetype($tempfile));
+               unlink($tempfile);
+       } else
+               $mime = "";
+
+       if (($image == $msglink) OR (substr($mime, 0, 6) == "image/"))
+               return(array("msg"=>trim($msg), "link"=>"", "linkname"=>$linkname, "image"=>$msglink));
+       else
+               return(array("msg"=>trim($msg), "link"=>$msglink, "linkname"=>$linkname,"image"=>$image));
+}
+
 /**
  * @param App $a
  * @param object $b
@@ -364,18 +491,19 @@ function fbpost_jot_nets(&$a,&$b) {
  */
 function fbpost_post_hook(&$a,&$b) {
 
+       logger('fbpost_post_hook: Facebook post invoked', LOGGER_DEBUG);
 
        if($b['deleted'] || ($b['created'] !== $b['edited']))
                return;
 
-       // Don't transmit answers (have to be cleaned up in the following code)
-       if($b['parent'] != $b['id'])
-               return;
+       logger('fbpost_post_hook: Facebook post first check successful', LOGGER_DEBUG);
 
        // if post comes from facebook don't send it back
-       if($b['app'] == "Facebook")
+       if(($b['app'] == "Facebook") AND ($b['verb'] != ACTIVITY_LIKE))
                return;
 
+       logger('fbpost_post_hook: Facebook post accepted', LOGGER_DEBUG);
+
        /**
         * Post to Facebook stream
         */
@@ -383,7 +511,6 @@ function fbpost_post_hook(&$a,&$b) {
        require_once('include/group.php');
        require_once('include/html2plain.php');
 
-       logger('Facebook post');
 
        $reply = false;
        $likes = false;
@@ -396,14 +523,21 @@ function fbpost_post_hook(&$a,&$b) {
 
        $linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
 
-       if((! $toplevel) && ($linking)) {
+       if((!$toplevel) && ($linking)) {
                $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
                        intval($b['parent']),
                        intval($b['uid'])
                );
+               //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+               //      dbesc($b['parent-uri']),
+               //      intval($b['uid'])
+               //);
+
+               // is it a reply to a facebook post?
+               // A reply to a toplevel post is only allowed for "real" facebook posts
                if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
                        $reply = substr($r[0]['uri'],4);
-               elseif(count($r) && substr($r[0]['extid'],0,4) === 'fb::')
+               elseif(count($r) && (substr($r[0]['extid'],0,4) === 'fb::') AND ($r[0]['id'] != $r[0]['parent']))
                        $reply = substr($r[0]['extid'],4);
                else
                        return;
@@ -420,7 +554,7 @@ function fbpost_post_hook(&$a,&$b) {
                        return;
 
 
-               logger('facebook reply id=' . $reply);
+               logger('fbpost_post_hook: facebook reply id=' . $reply);
        }
 
        if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
@@ -469,8 +603,10 @@ function fbpost_post_hook(&$a,&$b) {
                                return;
                }
 
-               if($b['verb'] == ACTIVITY_LIKE)
+               if($b['verb'] == ACTIVITY_LIKE) {
                        $likes = true;
+                       logger('fbpost_post_hook: liking '.print_r($b, true), LOGGER_DEBUG);
+               }
 
 
                $appid  = get_config('facebook', 'appid'  );
@@ -478,7 +614,7 @@ function fbpost_post_hook(&$a,&$b) {
 
                if($appid && $secret) {
 
-                       logger('facebook: have appid+secret');
+                       logger('fbpost_post_hook: have appid+secret');
 
                        $fb_token  = get_pconfig($b['uid'],'facebook','access_token');
 
@@ -488,110 +624,19 @@ function fbpost_post_hook(&$a,&$b) {
                        // or it's a reply or likes action to an existing facebook post
 
                        if($fb_token && ($toplevel || $b['private'] || $reply)) {
-                               logger('facebook: able to post');
+                               logger('fbpost_post_hook: able to post');
                                require_once('library/facebook.php');
                                require_once('include/bbcode.php');
 
                                $msg = $b['body'];
 
-                               logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
-
-                               // make links readable before we strip the code
-
-                               // unless it's a dislike - just send the text as a comment
-
-                               // if($b['verb'] == ACTIVITY_DISLIKE)
-                               //      $msg = trim(strip_tags(bbcode($msg)));
-
-                               // Looking for the first image
-                               $image = '';
-                               if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
-                                       $image = $matches[3];
-
-                               if ($image == '')
-                                       if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
-                                               $image = $matches[1];
-
-                               // When saved into the database the content is sent through htmlspecialchars
-                               // That means that we have to decode all image-urls
-                               $image = htmlspecialchars_decode($image);
-
-                               // Checking for a bookmark element
-                               $body = $b['body'];
-                               if (strpos($body, "[bookmark") !== false) {
-                                       // splitting the text in two parts:
-                                       // before and after the bookmark
-                                       $pos = strpos($body, "[bookmark");
-                                       $body1 = substr($body, 0, $pos);
-                                       $body2 = substr($body, $pos);
-
-                                       // Removing the bookmark and all quotes after the bookmark
-                                       // they are mostly only the content after the bookmark.
-                                       $body2 = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",'',$body2);
-                                       $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
-                                       $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
-
-                                       $body = $body1.$body2;
-                               }
-
-                               // Convert recycle signs
-                               $body = str_replace("\t", " ", $body);
-                               // recycle 1
-                               //$recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
-                               //$body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n\t$2:\t", $body);
-
-                               $body = str_replace("\t", "", $body);
-
-                               // At first convert the text to html
-                               $html = bbcode($body, false, false, 2);
-
-                               // Then convert it to plain text
-                               $msg = trim($b['title']." \n\n".html2plain($html, 0, true));
-
-                               // Removing useless spaces
-                               if (substr($msg, -2) == "«")
-                                       $msg = trim(substr($msg, 0, -2))."«";
-
-                               $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
-
-                               // Removing multiple newlines
-                               while (strpos($msg, "\n\n\n") !== false)
-                                       $msg = str_replace("\n\n\n", "\n\n", $msg);
-
-                               // add any attachments as text urls
-                               $arr = explode(',',$b['attach']);
-
-                               if(count($arr)) {
-                                       $msg .= "\n";
-                                       foreach($arr as $r) {
-                                               $matches = false;
-                                               $cnt = preg_match('|\[attach\]href=\"(.*?)\" size=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
-                                               if($cnt) {
-                                                       $msg .= "\n".$matches[1];
-                                               }
-                                       }
-                               }
-
-                               $link = '';
-                               $linkname = '';
-                               // look for bookmark-bbcode and handle it with priority
-                               if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches)) {
-                                       $link = $matches[1];
-                                       $linkname = $matches[2];
-                               }
-
-                               // If there is no bookmark element then take the first link
-                               if ($link == '') {
-                                       $links = collecturls($html);
-                                       if (sizeof($links) > 0) {
-                                               reset($links);
-                                               $link = current($links);
-                                       }
-                               }
-
-                               // Remove trailing and leading spaces
-                               $msg = trim($msg);
+                               logger('fbpost_post_hook: original msg=' . $msg, LOGGER_DATA);
 
+                               $msgarr = fbpost_createmsg($b);
+                               $msg = $msgarr["msg"];
+                               $link = $msgarr["link"];
+                               $image = $msgarr["image"];
+                               $linkname = $msgarr["linkname"];
 
                                // Fallback - if message is empty
                                if(!strlen($msg))
@@ -607,7 +652,7 @@ function fbpost_post_hook(&$a,&$b) {
                                if(!strlen($msg))
                                        return;
 
-                               logger('Facebook post: msg=' . $msg, LOGGER_DATA);
+                               logger('fbpost_post_hook: msg=' . $msg, LOGGER_DATA);
 
                                $video = "";
 
@@ -615,11 +660,11 @@ function fbpost_post_hook(&$a,&$b) {
                                        $postvars = array('access_token' => $fb_token);
                                } else {
                                        // message, picture, link, name, caption, description, source, place, tags
-                                       if(trim($link) != "")
-                                               if (@exif_imagetype($link) != 0) {
-                                                       $image = $link;
-                                                       $link = "";
-                                               }
+                                       //if(trim($link) != "")
+                                       //      if (@exif_imagetype($link) != 0) {
+                                       //              $image = $link;
+                                       //              $link = "";
+                                       //      }
 
                                        $postvars = array(
                                                'access_token' => $fb_token,
@@ -699,20 +744,22 @@ function fbpost_post_hook(&$a,&$b) {
                                if (!$reply and ($target != "me") and $page_access_token)
                                        $postvars['access_token'] = $page_access_token;
 
-                               logger('facebook: post to ' . $url);
-                               logger('facebook: postvars: ' . print_r($postvars,true));
+                               logger('fbpost_post_hook: post to ' . $url);
+                               logger('fbpost_post_hook: postvars: ' . print_r($postvars,true));
 
                                // "test_mode" prevents anything from actually being posted.
                                // Otherwise, let's do it.
 
-                               if(! get_config('facebook','test_mode')) {
+                               if(!get_config('facebook','test_mode')) {
                                        $x = post_url($url, $postvars);
-                                       logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
+                                       logger('fbpost_post_hook: post returns: ' . $x, LOGGER_DEBUG);
 
                                        $retj = json_decode($x);
                                        if($retj->id) {
-                                               q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
+                                               // Only set the extid when it isn't the toplevel post
+                                               q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
                                                        dbesc('fb::' . $retj->id),
+                                                       intval($b['id']),
                                                        intval($b['id'])
                                                );
                                        }
@@ -721,17 +768,18 @@ function fbpost_post_hook(&$a,&$b) {
                                                        $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
                                                        require_once('include/queue_fn.php');
                                                        add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
+                                                       logger('fbpost_post_hook: Post failed, requeued.', LOGGER_DEBUG);
                                                        notice( t('Facebook post failed. Queued for retry.') . EOL);
                                                }
 
                                                if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
-                                                       logger('Facebook session has expired due to changed password.', LOGGER_DEBUG);
+                                                       logger('fbpost_post_hook: Facebook session has expired due to changed password.', LOGGER_DEBUG);
 
                                                        $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
                                                        if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
                                                                require_once('include/enotify.php');
 
-                                                               $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']) );
+                                                               $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']));
                                                                notification(array(
                                                                        'uid' => $b['uid'],
                                                                        'type' => NOTIFY_SYSTEM,
@@ -745,7 +793,7 @@ function fbpost_post_hook(&$a,&$b) {
                                                                ));
 
                                                                set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
-                                                       } else logger('Facebook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
+                                                       } else logger('fbpost_post_hook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
                                                }
                                        }
                                }
@@ -838,7 +886,7 @@ function fbpost_queue_hook(&$a,&$b) {
                        $fb_token  = get_pconfig($user['uid'],'facebook','access_token');
 
                        if($fb_post && $fb_token) {
-                               logger('facebook_queue: able to post');
+                               logger('fbpost_queue_hook: able to post');
                                require_once('library/facebook.php');
 
                                $z = unserialize($x['content']);
@@ -847,15 +895,17 @@ function fbpost_queue_hook(&$a,&$b) {
 
                                $retj = json_decode($j);
                                if($retj->id) {
-                                       q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
+                                       // Only set the extid when it isn't the toplevel post
+                                       q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d AND `parent` != %d",
                                                dbesc('fb::' . $retj->id),
+                                               intval($item),
                                                intval($item)
                                        );
-                                       logger('facebook_queue: success: ' . $j); 
+                                       logger('fbpost_queue_hook: success: ' . $j);
                                        remove_queue_item($x['id']);
                                }
                                else {
-                                       logger('facebook_queue: failed: ' . $j);
+                                       logger('fbpost_queue_hook: failed: ' . $j);
                                        update_queue_time($x['id']);
                                }
                        }
@@ -970,6 +1020,9 @@ function fbpost_fetchwall($a, $uid) {
                if (($post_to_page != $item->from->id) AND ((int)$post_to_page != 0))
                        continue;
 
+               if (!strstr($item->id, $item->from->id."_") AND isset($item->to) AND ((int)$post_to_page == 0))
+                       continue;
+
                $_SESSION["authenticated"] = true;
                $_SESSION["uid"] = $uid;
 
diff --git a/fbsync/fbsync.css b/fbsync/fbsync.css
new file mode 100755 (executable)
index 0000000..9b577ab
--- /dev/null
@@ -0,0 +1,15 @@
+
+#fbsync-enable-label, #fbsync-create_user-label {
+       float: left;
+       width: 200px;
+       margin-top: 10px;
+}
+
+#fbsync-checkbox, #fbsync-create_user {
+       float: left;
+       margin-top: 10px;
+}
+
+#fbsync-submit {
+       margin-top: 15px;
+}
diff --git a/fbsync/fbsync.php b/fbsync/fbsync.php
new file mode 100644 (file)
index 0000000..76e82e7
--- /dev/null
@@ -0,0 +1,782 @@
+<?php
+/**
+ * Name: Facebook Sync
+ * Description: Synchronizes the Facebook Newsfeed
+ * Version: 0.0.1 alpha
+ * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
+ */
+
+/* To-Do
+FBSync:
+- A: Make shared posts look like shared posts
+- B: Threading for incoming comments
+- C: Receiving likes for comments
+
+FBPost:
+- A: Posts to pages currently have the page as sender - not the user
+- B: Sending likes for comments
+- C: Threading for sent comments
+*/
+
+require_once("addon/fbpost/fbpost.php");
+
+define('FBSYNC_DEFAULT_POLL_INTERVAL', 5); // given in minutes
+
+function fbsync_install() {
+       register_hook('connector_settings',      'addon/fbsync/fbsync.php', 'fbsync_settings');
+       register_hook('connector_settings_post', 'addon/fbsync/fbsync.php', 'fbsync_settings_post');
+       register_hook('cron', 'addon/fbsync/fbsync.php', 'fbsync_cron');
+}
+
+function fbsync_uninstall() {
+       unregister_hook('connector_settings',      'addon/fbsync/fbsync.php', 'fbsync_settings');
+       unregister_hook('connector_settings_post', 'addon/fbsync/fbsync.php', 'fbsync_settings_post');
+       unregister_hook('cron', 'addon/fbsync/fbsync.php', 'fbsync_cron');
+}
+
+function fbsync_settings(&$a,&$s) {
+
+       if(! local_user())
+               return;
+
+       /* Add our stylesheet to the page so we can make our settings look nice */
+
+       $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/fbsync/fbsync.css' . '" media="all" />' . "\r\n";
+
+       /* Get the current state of our config variables */
+
+       $enabled = get_pconfig(local_user(),'fbsync','sync');
+
+       $checked = (($enabled) ? ' checked="checked" ' : '');
+
+       $def_enabled = get_pconfig(local_user(),'fbsync','create_user');
+
+       $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
+
+       /* Add some HTML to the existing form */
+
+       $s .= '<div class="settings-block">';
+       $s .= '<h3>' . t('Facebook Import Settings') . '</h3>';
+
+       $s .= '<div id="fbsync-enable-wrapper">';
+       $s .= '<label id="fbsync-enable-label" for="fbsync-checkbox">' . t('Import Facebook newsfeed') . '</label>';
+       $s .= '<input id="fbsync-checkbox" type="checkbox" name="fbsync" value="1" ' . $checked . '/>';
+       $s .= '</div><div class="clear"></div>';
+
+       $s .= '<div id="fbsync-create_user-wrapper">';
+       $s .= '<label id="fbsync-create_user-label" for="fbsync-create_user">' . t('Automatically create contacts') . '</label>';
+       $s .= '<input id="fbsync-create_user" type="checkbox" name="create_user" value="1" ' . $def_checked . '/>';
+       $s .= '</div><div class="clear"></div>';
+
+       /* provide a submit button */
+
+       $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fbsync-submit" name="fbsync-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
+
+}
+
+function fbsync_settings_post(&$a,&$b) {
+
+       if(x($_POST,'fbsync-submit')) {
+               set_pconfig(local_user(),'fbsync','sync',intval($_POST['fbsync']));
+               set_pconfig(local_user(),'fbsync','create_user',intval($_POST['create_user']));
+       }
+}
+
+function fbsync_cron($a,$b) {
+       $last = get_config('fbsync','last_poll');
+
+       $poll_interval = intval(get_config('fbsync','poll_interval'));
+       if(! $poll_interval)
+               $poll_interval = FBSYNC_DEFAULT_POLL_INTERVAL;
+
+       if($last) {
+               $next = $last + ($poll_interval * 60);
+               if($next > time()) {
+                       logger('fbsync_cron: poll intervall not reached');
+                       return;
+               }
+       }
+       logger('fbsync_cron: cron_start');
+
+       $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fbsync' AND `k` = 'sync' AND `v` = '1' ORDER BY RAND()");
+       if(count($r)) {
+               foreach($r as $rr) {
+                       fbsync_get_self($rr['uid']);
+
+                       logger('fbsync_cron: importing timeline from user '.$rr['uid']);
+                       fbsync_fetchfeed($a, $rr['uid']);
+               }
+       }
+
+       logger('fbsync: cron_end');
+
+       set_config('fbsync','last_poll', time());
+}
+
+function fbsync_createpost($a, $uid, $self, $contacts, $applications, $post, $create_user) {
+
+       // check if it was already imported
+       $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
+               intval($uid),
+               dbesc('fb::'.$post->post_id)
+       );
+       if(count($r))
+               return;
+
+       $postarray = array();
+       $postarray['gravity'] = 0;
+       $postarray['uid'] = $uid;
+       $postarray['wall'] = 0;
+
+       $postarray['verb'] = ACTIVITY_POST;
+
+       $postarray['uri'] = "fb::".$post->post_id;
+       $postarray['thr-parent'] = $postarray['uri'];
+       $postarray['parent-uri'] = $postarray['uri'];
+       $postarray['plink'] = $post->permalink;
+
+       $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
+
+       if ($contact_id < 0)
+               return;
+       elseif ($contact_id == 0)
+               $contact_id = $self[0]["id"];
+
+       $postarray['contact-id'] = $contact_id;
+
+       $postarray['owner-name'] = $contacts[$post->source_id]->name;
+       $postarray['owner-link'] = $contacts[$post->source_id]->url;
+       $postarray['owner-avatar'] = $contacts[$post->source_id]->pic_square;
+
+       $postarray['author-name'] = $contacts[$post->actor_id]->name;
+       $postarray['author-link'] = $contacts[$post->actor_id]->url;
+       $postarray['author-avatar'] = $contacts[$post->actor_id]->pic_square;
+
+       $postarray["body"] = (isset($post->message) ? escape_tags($post->message) : '');
+
+       $msgdata = fbsync_convertmsg($a, $postarray["body"]);
+
+       $postarray["body"] = $msgdata["body"];
+       $postarray["tag"] = $msgdata["tags"];
+
+       if(isset($post->attachment->name) and isset($post->attachment->href))
+               $postarray["body"] .= "\n\n[bookmark=".$post->attachment->href."]".$post->attachment->name."[/bookmark]";
+       elseif (isset($post->attachment->name) AND ($post->attachment->name != ""))
+               $postarray["body"] .= "\n\n[b]" . $post->attachment->name."[/b]";
+
+       $quote = "";
+       if(isset($post->attachment->description) and ($post->attachment->fb_object_type != "photo"))
+               $quote = $post->attachment->description;
+
+       if(isset($post->attachment->caption) and ($post->attachment->fb_object_type == "photo"))
+               $quote = $post->attachment->caption;
+
+       if ($quote.$post->attachment->href.$postarray["body"] == "")
+               return;
+
+       if (isset($post->attachment->media) AND !strstr($post->attachment->href, "://www.youtube.com/")
+               AND !strstr($post->attachment->href, "://youtu.be/")
+               AND !strstr($post->attachment->href, ".vimeo.com/")) {
+               foreach ($post->attachment->media AS $media) {
+                       //$media->photo->owner = number_format($media->photo->owner, 0, '', '');
+                       //if ($media->photo->owner != '') {
+                       //      $postarray['author-name'] = $contacts[$media->photo->owner]->name;
+                       //      $postarray['author-link'] = $contacts[$media->photo->owner]->url;
+                       //      $postarray['author-avatar'] = $contacts[$media->photo->owner]->pic_square;
+                       //}
+
+                       if(isset($media->src) && isset($media->href) AND ($media->src != "") AND ($media->href != ""))
+                               $postarray["body"] .= "\n".'[url='.$media->href.'][img]'.fpost_cleanpicture($media->src).'[/img][/url]';
+                       else {
+                               if (isset($media->src) AND ($media->src != ""))
+                                       $postarray["body"] .= "\n".'[img]'.fpost_cleanpicture($media->src).'[/img]';
+
+                               // if just a link, it may be a wall photo - check
+                               if(isset($post->link))
+                                       $postarray["body"] .= fbpost_get_photo($media->href);
+                       }
+               }
+       }
+
+       if ($quote)
+               $postarray["body"] .= "\n[quote]".$quote."[/quote]";
+
+       $postarray["body"] = trim($postarray["body"]);
+
+       if (trim($postarray["body"]) == "")
+               return;
+
+       $postarray['created'] = datetime_convert('UTC','UTC',date("c", $post->created_time));
+       $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $post->updated_time));
+
+       $postarray['app'] = $applications[$post->app_id]->display_name;
+
+       if ($postarray['app'] == "")
+               $postarray['app'] = "Facebook";
+
+       if(isset($post->privacy) && $post->privacy->value !== '') {
+               $postarray['private'] = 1;
+               $postarray['allow_cid'] = '<' . $self[0]['id'] . '>';
+       }
+
+       /*
+       $postarray["location"] = $post->place->name;
+       postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
+       */
+
+       //$types = array(46, 80, 237, 247, 308);
+       //if (!in_array($post->type, $types))
+       //      $postarray["body"] = "Type: ".$post->type."\n".$postarray["body"];
+       //print_r($postarray);
+       $item = item_store($postarray);
+       logger('fbsync_createpost: User '.$self[0]["nick"].' posted feed item '.$item, LOGGER_DEBUG);
+}
+
+function fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $applications, $comment) {
+
+       // check if it was already imported
+       $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
+               intval($uid),
+               dbesc('fb::'.$comment->id)
+       );
+       if(count($r))
+               return;
+
+       // check if it was an own post (separate posting for performance reasons)
+       $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
+               intval($uid),
+               dbesc('fb::'.$comment->id)
+       );
+       if(count($r))
+               return;
+
+       $parent_uri = "";
+
+       // Fetch the parent uri (Checking if the parent exists)
+       $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
+               intval($uid),
+               dbesc('fb::'.$comment->post_id)
+       );
+       if(count($r))
+               $parent_uri = $r[0]["uri"];
+
+       // check if it is a reply to an own post (separate posting for performance reasons)
+       $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
+               intval($uid),
+               dbesc('fb::'.$comment->post_id)
+       );
+       if(count($r))
+               $parent_uri = $r[0]["uri"];
+
+       // No parent? Then quit
+       if ($parent_uri == "")
+               return;
+
+       $postarray = array();
+       $postarray['gravity'] = 0;
+       $postarray['uid'] = $uid;
+       $postarray['wall'] = 0;
+
+       $postarray['verb'] = ACTIVITY_POST;
+
+       $postarray['uri'] = "fb::".$comment->id;
+       $postarray['thr-parent'] = $parent_uri;
+       $postarray['parent-uri'] = $parent_uri;
+       //$postarray['plink'] = $comment->permalink;
+
+       $contact_id = fbsync_fetch_contact($uid, $contacts[$comment->fromid], array(), false);
+
+       if ($contact_id <= 0)
+               $contact_id = $self[0]["id"];
+
+       if ($comment->fromid != $self_id) {
+               $postarray['contact-id'] = $contact_id;
+               $postarray['owner-name'] = $contacts[$comment->fromid]->name;
+               $postarray['owner-link'] = $contacts[$comment->fromid]->url;
+               $postarray['owner-avatar'] = $contacts[$comment->fromid]->pic_square;
+       } else {
+               $postarray['contact-id'] = $self[0]["id"];
+               $postarray['owner-name'] = $self[0]["name"];
+               $postarray['owner-link'] = $self[0]["url"];
+               $postarray['owner-avatar'] = $self[0]["photo"];
+       }
+
+       $postarray['author-name'] = $postarray['owner-name'];
+       $postarray['author-link'] = $postarray['owner-link'];
+       $postarray['author-avatar'] = $postarray['owner-avatar'];
+
+       $msgdata = fbsync_convertmsg($a, $comment->text);
+
+       $postarray["body"] = $msgdata["body"];
+       $postarray["tag"] = $msgdata["tags"];
+
+       $postarray['created'] = datetime_convert('UTC','UTC',date("c", $comment->time));
+       $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $comment->time));
+
+       $postarray['app'] = $applications[$comment->app_id]->display_name;
+
+       if ($postarray['app'] == "")
+               $postarray['app'] = "Facebook";
+
+       if (trim($postarray["body"]) == "")
+               return;
+
+       $item = item_store($postarray);
+       logger('fbsync_createcomment: User '.$self[0]["nick"].' posted comment '.$item, LOGGER_DEBUG);
+
+       if ($item == 0)
+               return;
+
+       $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
+               dbesc($postarray['parent-uri']),
+               intval($uid)
+       );
+
+       if(count($myconv)) {
+               $importer_url = $a->get_baseurl() . '/profile/' . $user[0]['nickname'];
+
+               $own_contact = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
+                       intval($uid), dbesc("facebook::".$self_id));
+
+               if (!count($own_contact))
+                       return;
+
+               foreach($myconv as $conv) {
+
+                       // now if we find a match, it means we're in this conversation
+                       if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_contact[0]["url"]))
+                               continue;
+
+                       require_once('include/enotify.php');
+
+                       $conv_parent = $conv['parent'];
+
+                       $notifyarr = array(
+                                       'type'         => NOTIFY_COMMENT,
+                                       'notify_flags' => $user[0]['notify-flags'],
+                                       'language'     => $user[0]['language'],
+                                       'to_name'      => $user[0]['username'],
+                                       'to_email'     => $user[0]['email'],
+                                       'uid'          => $user[0]['uid'],
+                                       'item'         => $postarray,
+                                       'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $item,
+                                       'source_name'  => $postarray['author-name'],
+                                       'source_link'  => $postarray['author-link'],
+                                       'source_photo' => $postarray['author-avatar'],
+                                       'verb'         => ACTIVITY_POST,
+                                       'otype'        => 'item',
+                                       'parent'       => $conv_parent,
+                       );
+
+                       notification($notifyarr);
+
+                       // only send one notification
+                       break;
+               }
+       }
+}
+
+function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
+
+       $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                               dbesc("fb::".$like->post_id),
+                               intval($uid)
+               );
+
+        if (count($r))
+                $orig_post = $r[0];
+       else
+               return;
+
+       // If we posted the like locally, it will be found with our url, not the FB url.
+
+       $second_url = (($like->user_id == $self_id) ? $self[0]["url"] : $contacts[$like->user_id]->url);
+
+       $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s'
+               AND (`author-link` = '%s' OR `author-link` = '%s') LIMIT 1",
+               dbesc($orig_post["uri"]),
+               intval($uid),
+               dbesc(ACTIVITY_LIKE),
+               dbesc($contacts[$like->user_id]->url),
+               dbesc($second_url)
+       );
+
+       if (count($r))
+               return;
+
+       $contact_id = fbsync_fetch_contact($uid, $contacts[$like->user_id], array(), false);
+
+       if ($contact_id <= 0)
+               $contact_id = $self[0]["id"];
+
+       $likedata = array();
+        $likedata['parent'] = $orig_post['id'];
+        $likedata['verb'] = ACTIVITY_LIKE;
+        $likedata['gravity'] = 3;
+        $likedata['uid'] = $uid;
+        $likedata['wall'] = 0;
+        $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
+        $likedata['parent-uri'] = $orig_post["uri"];
+        $likedata['app'] = "Facebook";
+        $likedata['verb'] = ACTIVITY_LIKE;
+
+       if ($like->user_id != $self_id) {
+               $likedata['contact-id'] = $contact_id;
+               $likedata['author-name'] = $contacts[$like->user_id]->name;
+               $likedata['author-link'] = $contacts[$like->user_id]->url;
+               $likedata['author-avatar'] = $contacts[$like->user_id]->pic_square;
+       } else {
+               $likedata['contact-id'] = $self[0]["id"];
+               $likedata['author-name'] = $self[0]["name"];
+               $likedata['author-link'] = $self[0]["url"];
+               $likedata['author-avatar'] = $self[0]["photo"];
+       }
+
+       $author  = '[url=' . $likedata['author-link'] . ']' . $likedata['author-name'] . '[/url]';
+
+       $objauthor =  '[url=' . $orig_post['author-link'] . ']' . $orig_post['author-name'] . '[/url]';
+       $post_type = t('status');
+
+       $plink = '[url=' . $orig_post['plink'] . ']' . $post_type . '[/url]';
+        $likedata['object-type'] = ACTIVITY_OBJ_NOTE;
+
+        $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink);
+
+        $likedata['object'] = '<object><type>' . ACTIVITY_OBJ_NOTE . '</type><local>1</local>' .
+                '<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>';
+
+
+       $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `author-link` = '%s' AND `verb` = '%s' AND `uid` = %d LIMIT 1",
+                               dbesc($likedata['parent-uri']),
+                               dbesc($likedata['author-link']),
+                               dbesc(ACTIVITY_LIKE),
+                               intval($uid)
+               );
+
+        if (count($r))
+               return;
+
+       $item = item_store($likedata);
+       logger('fbsync_createlike: liked item '.$item.'. User '.$self[0]["nick"], LOGGER_DEBUG);
+}
+
+function fbsync_fetch_contact($uid, $contact, $create_user) {
+
+        $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
+                intval($uid), dbesc("facebook::".$contact->id));
+
+        if(!count($r) AND !$create_user)
+                return(0);
+
+        if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
+                logger("fbsync_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
+                return(-1);
+        }
+
+       $avatarpicture = $contact->pic_square;
+
+        if(!count($r)) {
+                // create contact record
+                q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
+                                        `name`, `nick`, `photo`, `network`, `rel`, `priority`,
+                                        `writable`, `blocked`, `readonly`, `pending`)
+                                        VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0)",
+                        intval($uid),
+                        dbesc(datetime_convert()),
+                        dbesc($contact->url),
+                        dbesc(normalise_link($contact->url)),
+                        dbesc($contact->username."@facebook.com"),
+                        dbesc("facebook::".$contact->id),
+                        dbesc(''),
+                        dbesc("facebook::".$contact->id),
+                        dbesc($contact->name),
+                        dbesc($contact->username),
+                        dbesc($avatarpicture),
+                        dbesc(NETWORK_FACEBOOK),
+                        intval(CONTACT_IS_FRIEND),
+                        intval(1),
+                        intval(1)
+                );
+
+                $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
+                        dbesc("facebook::".$contact->id),
+                        intval($uid)
+                        );
+
+                if(! count($r))
+                        return(false);
+
+                $contact_id  = $r[0]['id'];
+
+                $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
+                        intval($uid)
+                );
+
+                if($g && intval($g[0]['def_gid'])) {
+                        require_once('include/group.php');
+                        group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
+                }
+
+                require_once("Photo.php");
+
+                $photos = import_profile_photo($avatarpicture,$uid,$contact_id);
+
+                q("UPDATE `contact` SET `photo` = '%s',
+                                        `thumb` = '%s',
+                                        `micro` = '%s',
+                                        `name-date` = '%s',
+                                        `uri-date` = '%s',
+                                        `avatar-date` = '%s'
+                                WHERE `id` = %d",
+                        dbesc($photos[0]),
+                        dbesc($photos[1]),
+                        dbesc($photos[2]),
+                        dbesc(datetime_convert()),
+                        dbesc(datetime_convert()),
+                        dbesc(datetime_convert()),
+                        intval($contact_id)
+                );
+        } else {
+                // update profile photos once every 12 hours as we have no notification of when they change.
+                $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
+
+                // check that we have all the photos, this has been known to fail on occasion
+                if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
+
+                        logger("fbsync_fetch_contact: Updating contact ".$contact->username, LOGGER_DEBUG);
+
+                        require_once("Photo.php");
+
+                        $photos = import_profile_photo($avatarpicture, $uid, $r[0]['id']);
+
+                        q("UPDATE `contact` SET `photo` = '%s',
+                                                `thumb` = '%s',
+                                                `micro` = '%s',
+                                                `name-date` = '%s',
+                                                `uri-date` = '%s',
+                                                `avatar-date` = '%s',
+                                                `url` = '%s',
+                                                `nurl` = '%s',
+                                                `addr` = '%s',
+                                                `name` = '%s',
+                                                `nick` = '%s'
+                                        WHERE `id` = %d",
+                                dbesc($photos[0]),
+                                dbesc($photos[1]),
+                                dbesc($photos[2]),
+                                dbesc(datetime_convert()),
+                                dbesc(datetime_convert()),
+                                dbesc(datetime_convert()),
+                                dbesc($contact->url),
+                                dbesc(normalise_link($contact->url)),
+                                dbesc($contact->username."@facebook.com"),
+                                dbesc($contact->name),
+                                dbesc($contact->username),
+                                intval($r[0]['id'])
+                        );
+                }
+        }
+        return($r[0]["id"]);
+}
+
+function fbsync_get_self($uid) {
+       $access_token = get_pconfig($uid,'facebook','access_token');
+       if(! $access_token)
+               return;
+       $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
+       if($s) {
+               $j = json_decode($s);
+               set_pconfig($uid,'fbsync','self_id',(string) $j->id);
+       }
+}
+
+function fbsync_convertmsg($a, $body) {
+       $str_tags = '';
+
+       $tags = get_tags($body);
+
+       if(count($tags)) {
+               foreach($tags as $tag) {
+                       if (strstr(trim($tag), " "))
+                               continue;
+
+                       if(strpos($tag,'#') === 0) {
+                               if(strpos($tag,'[url='))
+                                       continue;
+
+                               // don't link tags that are already embedded in links
+
+                               if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
+                                       continue;
+                               if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
+                                       continue;
+
+                               $basetag = str_replace('_',' ',substr($tag,1));
+                               $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
+                               if(strlen($str_tags))
+                                       $str_tags .= ',';
+                               $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
+                               continue;
+                       } elseif(strpos($tag,'@') === 0) {
+                               $basetag = substr($tag,1);
+                               $body = str_replace($tag,'@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
+                       }
+
+               }
+       }
+
+       $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
+       if($cnt) {
+               foreach($matches as $mtch) {
+                       if(strlen($str_tags))
+                               $str_tags .= ',';
+                       $str_tags .= '@[url=' . $mtch[1] . '[/url]';
+               }
+       }
+
+       return(array("body"=>$body, "tags"=>$str_tags));
+
+}
+
+function fbsync_fetchfeed($a, $uid) {
+       $access_token = get_pconfig($uid,'facebook','access_token');
+       $last_updated = get_pconfig($uid,'fbsync','last_updated');
+       $self_id = get_pconfig($uid,'fbsync','self_id');
+
+       $create_user = get_pconfig($uid, 'fbsybc', 'create_user');
+       $do_likes = get_config('fbsync', 'do_likes');
+
+       $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
+               intval($uid)
+       );
+
+       $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
+               intval($uid)
+       );
+       if(! count($user))
+               return;
+
+       require_once('include/items.php');
+
+       if ($last_updated == "")
+               $last_updated = 0;
+
+       logger("fbsync_fetchfeed: fetching content for user ".$self_id);
+
+       $fql = array(
+               "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",
+               "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",
+               "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",
+               "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",
+               "avatars" => "SELECT id, real_size, size, url FROM square_profile_pic WHERE id IN (SELECT id FROM #profiles) AND size = 256 LIMIT 500");
+
+       if ($do_likes) {
+               $fql["likes"] = "SELECT post_id, user_id FROM like WHERE post_id IN (SELECT post_id FROM #posts)";
+               $fql["profiles"] .= " OR id IN (SELECT user_id FROM #likes)";
+       }
+
+       $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
+
+       $feed = fetch_url($url);
+
+       $data = json_decode($feed);
+
+       $posts = array();
+       $comments = array();
+       $likes = array();
+       $profiles = array();
+       $applications = array();
+       $avatars = array();
+
+       foreach($data->data AS $query) {
+               switch ($query->name) {
+                       case "posts":
+                               $posts = array_reverse($query->fql_result_set);
+                               break;
+                       case "comments":
+                               $comments = $query->fql_result_set;
+                               break;
+                       case "likes":
+                               $likes = $query->fql_result_set;
+                               break;
+                       case "profiles":
+                               $profiles = $query->fql_result_set;
+                               break;
+                       case "applications":
+                               $applications = $query->fql_result_set;
+                               break;
+                       case "avatars":
+                               $avatars = $query->fql_result_set;
+                               break;
+               }
+       }
+
+       $square_avatars = array();
+       $contacts = array();
+       $application_data = array();
+       $post_data = array();
+       $comment_data = array();
+
+       foreach ($avatars AS $avatar) {
+               $avatar->id = number_format($avatar->id, 0, '', '');
+               $square_avatars[$avatar->id] = $avatar;
+       }
+       unset($avatars);
+
+       foreach ($profiles AS $profile) {
+               $profile->id = number_format($profile->id, 0, '', '');
+
+               if ($square_avatars[$profile->id]->url != "")
+                       $profile->pic_square = $square_avatars[$profile->id]->url;
+
+               $contacts[$profile->id] = $profile;
+       }
+       unset($profiles);
+       unset($square_avatars);
+
+       foreach ($applications AS $application) {
+               $application->app_id = number_format($application->app_id, 0, '', '');
+               $application_data[$application->app_id] = $application;
+       }
+       unset($applications);
+
+       foreach ($posts AS $post) {
+               $post->actor_id = number_format($post->actor_id, 0, '', '');
+               $post->source_id = number_format($post->source_id, 0, '', '');
+               $post->app_id = number_format($post->app_id, 0, '', '');
+               $post_data[$post->post_id] = $post;
+       }
+       unset($posts);
+
+       foreach($comments AS $comment) {
+               $comment->fromid = number_format($comment->fromid, 0, '', '');
+               $comment_data[$comment->id] = $comment;
+       }
+       unset($comments);
+
+       foreach ($post_data AS $post) {
+               if ($post->updated_time > $last_updated)
+                       $last_updated = $post->updated_time;
+
+               //print_r($post);
+
+               // parent_post_id - Erkennen von geteilten Posts?
+
+               fbsync_createpost($a, $uid, $self, $contacts, $application_data, $post, $create_user);
+       }
+
+       foreach ($comment_data AS $comment) {
+               fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $application_data, $comment);
+       }
+
+       foreach($likes AS $like) {
+               $like->user_id = number_format($like->user_id, 0, '', '');
+
+               fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like);
+
+       }
+
+       set_pconfig($uid,'fbsync','last_updated', $last_updated);
+
+}
+?>
index cb336fcfabea86dd20d7674ac2ac3d883c45efc5..5d5e23f08936fb4497c8d21cd1f9a423de51828b 100644 (file)
@@ -2089,4 +2089,4 @@ class http_class
        }
 };
 
-?>
\ No newline at end of file
+?>