]> git.mxchange.org Git - friendica-addons.git/blobdiff - twitter/twitter.php
The connector settings are now with logo.
[friendica-addons.git] / twitter / twitter.php
index 1a7243595ce6136016fed79b9b3b4419eab18ae8..c14841f4c493d85dde62292f1001ad2eb777e663 100755 (executable)
@@ -169,6 +169,7 @@ function twitter_settings_post ($a,$post) {
                del_pconfig(local_user(), 'twitter', 'intelligent_shortening');
                del_pconfig(local_user(), 'twitter', 'import');
                del_pconfig(local_user(), 'twitter', 'create_user');
+               del_pconfig(local_user(), 'twitter', 'own_id');
        } else {
        if (isset($_POST['twitter-pin'])) {
                //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
@@ -229,12 +230,14 @@ function twitter_settings(&$a,&$s) {
         $create_userenabled = get_pconfig(local_user(),'twitter','create_user');
         $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
 
+       $globalshortening = get_config('twitter','intelligent_shortening');
+
        $s .= '<span id="settings_twitter_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
-       $s .= '<h3>'. t('Twitter Settings') .'</h3>';
+       $s .= '<img class="connector" src="images/twitter.png" /><h3 class="connector">'. t('Twitter Import/Export/Mirror').'</h3>';
        $s .= '</span>';
        $s .= '<div id="settings_twitter_expanded" class="settings-block" style="display: none;">';
        $s .= '<span class="fakelink" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
-       $s .= '<h3>'. t('Twitter Settings') .'</h3>';
+       $s .= '<img class="connector" src="images/twitter.png" /><h3 class="connector">'. t('Twitter Import/Export/Mirror').'</h3>';
        $s .= '</span>';
 
        if ( (!$ckey) && (!$csecret) ) {
@@ -269,7 +272,7 @@ function twitter_settings(&$a,&$s) {
                        $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="'.$token.'" />';
                        $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="'.$request_token['oauth_token_secret'].'" />';
             $s .= '</div><div class="clear"></div>';
-            $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
+            $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
                } else {
                        /***
                         *  we have an OAuth key / secret pair for the user
@@ -295,13 +298,16 @@ function twitter_settings(&$a,&$s) {
                         $s .= '<input id="twitter-mirror" type="checkbox" name="twitter-mirror" value="1" '. $mirrorchecked . '/>';
                        $s .= '<div class="clear"></div>';
 
-                        $s .= '<label id="twitter-shortening-label" for="twitter-shortening">'.t('Shortening method that optimizes the tweet').'</label>';
-                        $s .= '<input id="twitter-shortening" type="checkbox" name="twitter-shortening" value="1" '. $shorteningchecked . '/>';
-                       $s .= '<div class="clear"></div>';
+                       if (!$globalshortening) {
+                               $s .= '<label id="twitter-shortening-label" for="twitter-shortening">'.t('Shortening method that optimizes the tweet').'</label>';
+                               $s .= '<input id="twitter-shortening" type="checkbox" name="twitter-shortening" value="1" '. $shorteningchecked . '/>';
+                               $s .= '<div class="clear"></div>';
 
-                        $s .= '<label id="twitter-sendtaglinks-label" for="twitter-sendtaglinks">'.t('Send linked #-tags and @-names to Twitter').'</label>';
-                        $s .= '<input id="twitter-sendtaglinks" type="checkbox" name="twitter-sendtaglinks" value="1" '. $linkschecked . '/>';
-                       $s .= '</div><div class="clear"></div>';
+                               $s .= '<label id="twitter-sendtaglinks-label" for="twitter-sendtaglinks">'.t('Send linked #-tags and @-names to Twitter').'</label>';
+                               $s .= '<input id="twitter-sendtaglinks" type="checkbox" name="twitter-sendtaglinks" value="1" '. $linkschecked . '/>';
+                               $s .= '<div class="clear"></div>';
+                       }
+                       $s .= '</div>';
 
                         $s .= '<label id="twitter-import-label" for="twitter-import">'.t('Import the remote timeline').'</label>';
                         $s .= '<input id="twitter-import" type="checkbox" name="twitter-import" value="1" '. $importchecked . '/>';
@@ -315,7 +321,7 @@ function twitter_settings(&$a,&$s) {
                         $s .= '<label id="twitter-disconnect-label" for="twitter-disconnect">'. t('Clear OAuth configuration') .'</label>';
                         $s .= '<input id="twitter-disconnect" type="checkbox" name="twitter-disconnect" value="1" />';
                        $s .= '</div><div class="clear"></div>';
-                       $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
+                       $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>'; 
                }
        }
         $s .= '</div><div class="clear"></div>';
@@ -371,21 +377,25 @@ function short_link ($url) {
 } };
 
 function twitter_shortenmsg($b, $shortlink = false) {
+       require_once("include/api.php");
        require_once("include/bbcode.php");
        require_once("include/html2plain.php");
 
        $max_char = 140;
 
+       $b['body'] = bb_CleanPictureLinks($b['body']);
+
        // Looking for the first image
+       $cleaned_body = api_clean_plain_items($b['body']);
        $image = '';
-       if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
+       if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$cleaned_body,$matches))
                $image = $matches[3];
 
        if ($image == '')
-               if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
+               if(preg_match("/\[img\](.*?)\[\/img\]/is",$cleaned_body,$matches))
                        $image = $matches[1];
 
-       $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
+       $multipleimages = (strpos($cleaned_body, "[img") != strrpos($cleaned_body, "[img"));
 
        // When saved into the database the content is sent through htmlspecialchars
        // That means that we have to decode all image-urls
@@ -425,7 +435,7 @@ function twitter_shortenmsg($b, $shortlink = false) {
        //$body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
 
        // At first convert the text to html
-       $html = bbcode($body, false, false, 2);
+       $html = bbcode(api_clean_plain_items($body), false, false, 2);
 
        // Then convert it to plain text
        $msg = trim(html2plain($html, 0, true));
@@ -632,8 +642,12 @@ function twitter_post_hook(&$a,&$b) {
                         $orig_post = $r[0];
                 }
 
-               // To-Do: Ab dem letzten / nehmen
-               $b["body"] = "@".substr($orig_post["author-link"], 20)." ".$b["body"];
+               $nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
+               $nickname = "@[url=".$orig_post["author-link"]."]".$nickname."[/url]";
+
+               logger("twitter_post_hook: comparing ".$nickname." with ".$b["body"], LOGGER_DEBUG);
+               if (strpos($b["body"], $nickname) === false)
+                       $b["body"] = $nickname." ".$b["body"];
 
                logger("twitter_post_hook: parent found ".print_r($orig_post, true), LOGGER_DATA);
        } else {
@@ -680,9 +694,14 @@ function twitter_post_hook(&$a,&$b) {
        if($ckey && $csecret && $otoken && $osecret) {
                logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
 
+               // If it's a repeated message from twitter then do a native retweet and exit
+               if (twitter_is_retweet($a, $b['uid'], $b['body']))
+                       return;
+
                require_once('library/twitteroauth.php');
                require_once('include/bbcode.php');
                $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
+
                 // in theory max char is 140 but T. uses t.co to make links 
                 // longer so we give them 10 characters extra
                if (!$intelligent_shortening) {
@@ -767,6 +786,7 @@ function twitter_post_hook(&$a,&$b) {
                         $msg = $msgarr["msg"];
                         $image = $msgarr["image"];
                }
+
                // and now tweet it :-)
                if(strlen($msg) and ($image != "")) {
                        $img_str = fetch_url($image);
@@ -792,16 +812,6 @@ function twitter_post_hook(&$a,&$b) {
                        $result = $cb->statuses_updateWithMedia($post);
                        unlink($tempfile);
 
-                       /*
-                       // Old Code
-                       $mime = image_type_to_mime_type(exif_imagetype($tempfile));
-                       unlink($tempfile);
-
-                       $filename = "upload";
-
-                       $result = $tweet->post('statuses/update_with_media', array('media[]' => "{$img_str};type=".$mime.";filename={$filename}" , 'status' => $msg));
-                       */
-
                        logger('twitter_post_with_media send, result: ' . print_r($result, true), LOGGER_DEBUG);
                        if ($result->errors OR $result->error) {
                                logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
@@ -868,7 +878,7 @@ function twitter_plugin_admin(&$a, &$o){
        $t = get_markup_template( "admin.tpl", "addon/twitter/" );
 
        $o = replace_macros($t, array(
-               '$submit' => t('Submit'),
+               '$submit' => t('Save Settings'),
                                                                // name, label, value, help, [extra values]
                '$consumerkey' => array('consumerkey', t('Consumer key'),  get_config('twitter', 'consumerkey' ), ''),
                 '$consumersecret' => array('consumersecret', t('Consumer secret'),  get_config('twitter', 'consumersecret' ), ''),
@@ -945,6 +955,7 @@ function twitter_fetchtimeline($a, $uid) {
        $has_picture = false;
 
        require_once('mod/item.php');
+       require_once('include/items.php');
 
        require_once('library/twitteroauth.php');
        $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
@@ -1001,7 +1012,7 @@ function twitter_fetchtimeline($a, $uid) {
                                        }
                                }
 
-                               $converted = twitter_convertmsg($a, $_REQUEST['body'], true, $has_picture);
+                               $converted = twitter_expand_entities($a, $_REQUEST['body'], $post->retweeted_status, true, $has_picture);
                                $_REQUEST['body'] = $converted["body"];
 
                                $_REQUEST['body'] = "[share author='".$post->retweeted_status->user->name.
@@ -1024,7 +1035,7 @@ function twitter_fetchtimeline($a, $uid) {
                                        }
                                }
 
-                               $converted = twitter_convertmsg($a, $_REQUEST["body"], true, $has_picture);
+                               $converted = twitter_expand_entities($a, $_REQUEST["body"], $post, true, $has_picture);
                                $_REQUEST['body'] = $converted["body"];
                        }
 
@@ -1119,6 +1130,24 @@ function twitter_queue_hook(&$a,&$b) {
 
 function twitter_fetch_contact($uid, $contact, $create_user) {
 
+       // Check if the unique contact is existing
+       // To-Do: only update once a while
+        $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
+                       dbesc(normalise_link("https://twitter.com/".$contact->screen_name)));
+
+       if (count($r) == 0)
+               q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
+                       dbesc(normalise_link("https://twitter.com/".$contact->screen_name)),
+                       dbesc($contact->name),
+                       dbesc($contact->screen_name),
+                       dbesc($contact->profile_image_url_https));
+       else
+               q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
+                       dbesc($contact->name),
+                       dbesc($contact->screen_name),
+                       dbesc($contact->profile_image_url_https),
+                       dbesc(normalise_link("https://twitter.com/".$contact->screen_name)));
+
        $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
                intval($uid), dbesc("twitter::".$contact->id_str));
 
@@ -1191,6 +1220,7 @@ function twitter_fetch_contact($uid, $contact, $create_user) {
                        dbesc(datetime_convert()),
                        intval($contact_id)
                );
+
        } else {
                // update profile photos once every two weeks as we have no notification of when they change.
 
@@ -1277,11 +1307,146 @@ function twitter_fetchuser($a, $uid, $screen_name = "", $user_id = "") {
        return $contact_id;
 }
 
+function twitter_expand_entities($a, $body, $item, $no_tags = false, $dontincludemedia) {
+       require_once("include/oembed.php");
+       require_once("include/network.php");
+
+       $tags = "";
+
+       if (isset($item->entities->urls)) {
+               $type = "";
+               $footerurl = "";
+               $footerlink = "";
+               $footer = "";
+
+               foreach ($item->entities->urls AS $url) {
+                       if ($url->url AND $url->expanded_url AND $url->display_url) {
+
+                               $expanded_url = original_url($url->expanded_url);
+
+                               $oembed_data = oembed_fetch_url($expanded_url);
+
+                               // Quickfix: Workaround for URL with "[" and "]" in it
+                               if (strpos($expanded_url, "[") OR strpos($expanded_url, "]"))
+                                       $expanded_url = $url->url;
+
+                               if ($type == "")
+                                       $type = $oembed_data->type;
+
+                               if ($oembed_data->type == "video") {
+                                       $body = str_replace($url->url,
+                                                       "[video]".$expanded_url."[/video]", $body);
+                                       $dontincludemedia = true;
+                               } elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia) {
+                                       $body = str_replace($url->url,
+                                                       "[url=".$expanded_url."][img]".$oembed_data->url."[/img][/url]",
+                                                       $body);
+                                       $dontincludemedia = true;
+                               } elseif ($oembed_data->type != "link")
+                                       $body = str_replace($url->url,
+                                                       "[url=".$expanded_url."]".$expanded_url."[/url]",
+                                                       $body);
+                               else {
+                                       $img_str = fetch_url($expanded_url, true, $redirects, 4);
+
+                                       $tempfile = tempnam(get_config("system","temppath"), "cache");
+                                       file_put_contents($tempfile, $img_str);
+                                       $mime = image_type_to_mime_type(exif_imagetype($tempfile));
+                                       unlink($tempfile);
+
+                                       if (substr($mime, 0, 6) == "image/") {
+                                               $type = "photo";
+                                               $body = str_replace($url->url, "[img]".$expanded_url."[/img]", $body);
+                                               $dontincludemedia = true;
+                                       } else {
+                                               $type = $oembed_data->type;
+                                               $footerurl = $expanded_url;
+                                               $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
+
+                                               $body = str_replace($url->url, $footerlink, $body);
+                                       }
+                               }
+                       }
+               }
+
+               if ($footerurl != "")
+                       $footer = add_page_info($footerurl);
+
+               if (($footerlink != "") AND (trim($footer) != "")) {
+                       $removedlink = trim(str_replace($footerlink, "", $body));
+
+                       if (strstr($body, $removedlink))
+                               $body = $removedlink;
+
+                       $body .= $footer;
+               }
+
+               if ($no_tags)
+                       return(array("body" => $body, "tags" => ""));
+
+               $tags_arr = array();
+
+               foreach ($item->entities->hashtags AS $hashtag) {
+                       $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag->text)."]".$hashtag->text."[/url]";
+                       $tags_arr["#".$hashtag->text] = $url;
+                       $body = str_replace("#".$hashtag->text, $url, $body);
+               }
+
+               foreach ($item->entities->user_mentions AS $mention) {
+                       $url = "@[url=https://twitter.com/".rawurlencode($mention->screen_name)."]".$mention->screen_name."[/url]";
+                       $tags_arr["@".$mention->screen_name] = $url;
+                       $body = str_replace("@".$mention->screen_name, $url, $body);
+               }
+
+               // it seems as if the entities aren't always covering all mentions. So the rest will be checked here
+               $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));
+                                       $url = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($basetag).']'.$basetag.'[/url]';
+                                       $body = str_replace($tag,$url,$body);
+                                       $tags_arr["#".$basetag] = $url;
+                                       continue;
+                               } elseif(strpos($tag,'@') === 0) {
+                                       if(strpos($tag,'[url='))
+                                               continue;
+
+                                       $basetag = substr($tag,1);
+                                       $url = '@[url=https://twitter.com/'.rawurlencode($basetag).']'.$basetag.'[/url]';
+                                       $body = str_replace($tag,$url,$body);
+                                       $tags_arr["@".$basetag] = $url;
+                               }
+                       }
+               }
+
+
+               $tags = implode($tags_arr, ",");
+
+       }
+       return(array("body" => $body, "tags" => $tags));
+}
+
 function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing_contact) {
 
        $has_picture = false;
 
        $postarray = array();
+       $postarray['network'] = NETWORK_TWITTER;
        $postarray['gravity'] = 0;
        $postarray['uid'] = $uid;
        $postarray['wall'] = 0;
@@ -1384,7 +1549,7 @@ function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing
                }
        }
 
-       $converted = twitter_convertmsg($a, $postarray['body'], false, $has_picture);
+       $converted = twitter_expand_entities($a, $postarray['body'], $post, false, $has_picture);
        $postarray['body'] = $converted["body"];
        $postarray['tag'] = $converted["tags"];
 
@@ -1421,10 +1586,11 @@ function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing
                        }
                }
 
-               $converted = twitter_convertmsg($a, $postarray['body'], false, $has_picture);
+               $converted = twitter_expand_entities($a, $postarray['body'], $post->retweeted_status, false, $has_picture);
                $postarray['body'] = $converted["body"];
                $postarray['tag'] = $converted["tags"];
 
+               twitter_fetch_contact($uid, $post->retweeted_status->user, false);
 
                // Deactivated at the moment, since there are problems with answers to retweets
                if (false AND !intval(get_config('system','wall-to-wall_share'))) {
@@ -1439,6 +1605,10 @@ function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing
                        $postarray['author-name'] = $post->retweeted_status->user->name;
                        $postarray['author-link'] = "https://twitter.com/".$post->retweeted_status->user->screen_name;
                        $postarray['author-avatar'] = $post->retweeted_status->user->profile_image_url_https;
+                       //if (($post->retweeted_status->user->screen_name != "") AND ($post->retweeted_status->id_str != "")) {
+                       //      $postarray['plink'] = "https://twitter.com/".$post->retweeted_status->user->screen_name."/status/".$post->retweeted_status->id_str;
+                       //      $postarray['uri'] = "twitter::".$post->retweeted_status->id_str;
+                       //}
                }
 
        }
@@ -1670,211 +1840,6 @@ function twitter_fetchhometimeline($a, $uid) {
        set_pconfig($uid, 'twitter', 'lastmentionid', $lastid);
 }
 
-function twitter_original_url($url, $depth=1, $fetchbody = false) {
-        if ($depth > 10)
-                return($url);
-
-        $siteinfo = array();
-        $ch = curl_init();
-        curl_setopt($ch, CURLOPT_URL, $url);
-        curl_setopt($ch, CURLOPT_HEADER, 1);
-
-       if ($fetchbody)
-               curl_setopt($ch, CURLOPT_NOBODY, 0);
-       else
-               curl_setopt($ch, CURLOPT_NOBODY, 1);
-
-        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
-        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-        curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0');
-
-        $header = curl_exec($ch);
-        $curl_info = @curl_getinfo($ch);
-        $http_code = $curl_info['http_code'];
-        curl_close($ch);
-
-        if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
-                AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
-                if ($curl_info['redirect_url'] != "")
-                        return(twitter_original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
-                else
-                        return(twitter_original_url($curl_info['location'], ++$depth, $fetchbody));
-        }
-
-        $pos = strpos($header, "\r\n\r\n");
-
-        if ($pos)
-                $body = trim(substr($header, $pos));
-        else
-                $body = $header;
-
-       if (trim($body) == "")
-               return(twitter_original_url($url, ++$depth, true));
-
-        $doc = new DOMDocument();
-        @$doc->loadHTML($body);
-
-        $xpath = new DomXPath($doc);
-
-        $list = $xpath->query("//meta[@content]");
-        foreach ($list as $node) {
-                $attr = array();
-                if ($node->attributes->length)
-                        foreach ($node->attributes as $attribute)
-                                $attr[$attribute->name] = $attribute->value;
-
-                if (@$attr["http-equiv"] == 'refresh') {
-                        $path = $attr["content"];
-                        $pathinfo = explode(";", $path);
-                        $content = "";
-                        foreach ($pathinfo AS $value)
-                                if (substr(strtolower($value), 0, 4) == "url=")
-                                        return(twitter_original_url(substr($value, 4), ++$depth));
-                }
-        }
-
-        return($url);
-}
-
-function twitter_siteinfo($url, $dontincludemedia) {
-       require_once("mod/parse_url.php");
-
-       // Fetch site infos - but only from the meta data
-       $data = parseurl_getsiteinfo($url, true);
-
-       if ($dontincludemedia)
-               unset($data["images"]);
-
-       if (!is_string($data["text"]) AND (sizeof($data["images"]) == 0) AND ($data["title"] == $url))
-               return("");
-
-       if (is_string($data["title"]))
-               $text .= "[bookmark=".$url."]".trim($data["title"])."[/bookmark]\n";
-
-       // Add a spoiler to the extra information
-       //if ((sizeof($data["images"]) > 0) OR is_string($data["text"]))
-       //      $text .= "[spoiler]";
-
-       if (sizeof($data["images"]) > 0) {
-               $imagedata = $data["images"][0];
-               $text .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
-       }
-
-       if (is_string($data["text"]))
-               $text .= "[quote]".$data["text"]."[/quote]";
-
-       //if ((sizeof($data["images"]) > 0) OR is_string($data["text"]))
-       //      $text .= "[/spoiler]";
-
-       return($text);
-
-}
-
-function twitter_convertmsg($a, $body, $no_tags = false, $dontincludemedia) {
-
-       $links = preg_match_all("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", $body,$matches,PREG_SET_ORDER);
-
-       $footer = "";
-       $footerurl = "";
-
-       if ($links) {
-               foreach ($matches AS $match) {
-                       $expanded_url = twitter_original_url($match[2]);
-
-                       // To-Do:
-                       // Twitlonger
-
-                       if (strstr($expanded_url, "//www.youtube.com/"))
-                               $body = str_replace($match[2], "\n[youtube]".$expanded_url."[/youtube]\n", $body);
-                       elseif (strstr($expanded_url, "//player.vimeo.com/"))
-                               $body = str_replace($match[2], "\n[vimeo]".$expanded_url."[/vimeo]\n", $body);
-                       elseif (strstr($expanded_url, "//twitpic.com/")) // Test
-                               $body = str_replace($match[2], "\n[url]".$expanded_url."[/url]\n", $body);
-                       elseif (strstr($expanded_url, "//instagram.com/"))
-                               $body = str_replace($match[2], "\n[url]".$expanded_url."[/url]\n", $body);
-                       else {
-                               $img_str = fetch_url($expanded_url, true, $redirects, 4);
-
-                               $tempfile = tempnam(get_config("system","temppath"), "cache");
-                               file_put_contents($tempfile, $img_str);
-                               $mime = image_type_to_mime_type(exif_imagetype($tempfile));
-                               unlink($tempfile);
-
-                               if (substr($mime, 0, 6) == "image/") {
-                                       $body = str_replace($match[2], "[img]".$expanded_url."[/img]", $body);
-                                       $dontincludemedia = true;
-                               } else {
-                                       $footerurl = $expanded_url;
-                                       $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
-
-                                       $body = str_replace($match[2], $footerlink, $body);
-                               }
-                       }
-               }
-
-               if ($footerurl != "")
-                       $footer = "\n\n".twitter_siteinfo($footerurl, $dontincludemedia);
-
-               if (($footerlink != "") AND (trim($footer) != "")) {
-                       $removedlink = trim(str_replace($footerlink, "", $body));
-
-                       if (strstr($body, $removedlink))
-                               $body = $removedlink;
-
-                       $body .= $footer;
-               }
-       }
-
-       if ($no_tags)
-               return(array("body" => $body, $tags => ""));
-
-       $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 twitter_fetch_own_contact($a, $uid) {
        $ckey    = get_config('twitter', 'consumerkey');
        $csecret = get_config('twitter', 'consumersecret');
@@ -1902,8 +1867,59 @@ function twitter_fetch_own_contact($a, $uid) {
                        intval($uid), dbesc("twitter::".$own_id));
                if(count($r))
                        $contact_id = $r[0]["id"];
+               else
+                       del_pconfig($uid, 'twitter', 'own_id');
+
        }
 
        return($contact_id);
 }
+
+function twitter_is_retweet($a, $uid, $body) {
+       $body = trim($body);
+
+       // Skip if it isn't a pure repeated messages
+       // Does it start with a share?
+       if (strpos($body, "[share") > 0)
+               return(false);
+
+       // Does it end with a share?
+       if (strlen($body) > (strrpos($body, "[/share]") + 8))
+               return(false);
+
+       $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
+       // Skip if there is no shared message in there
+       if ($body == $attributes)
+               return(false);
+
+       $link = "";
+       preg_match("/link='(.*?)'/ism", $attributes, $matches);
+       if ($matches[1] != "")
+               $link = $matches[1];
+
+       preg_match('/link="(.*?)"/ism', $attributes, $matches);
+       if ($matches[1] != "")
+               $link = $matches[1];
+
+       $id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link);
+       if ($id == $link)
+               return(false);
+
+       logger('twitter_is_retweet: Retweeting id '.$id.' for user '.$uid, LOGGER_DEBUG);
+
+       $ckey    = get_config('twitter', 'consumerkey');
+       $csecret = get_config('twitter', 'consumersecret');
+       $otoken  = get_pconfig($uid, 'twitter', 'oauthtoken');
+       $osecret = get_pconfig($uid, 'twitter', 'oauthsecret');
+
+       require_once('library/twitteroauth.php');
+       $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
+
+       $result = $connection->post('statuses/retweet/'.$id);
+
+       logger('twitter_is_retweet: result '.print_r($result, true), LOGGER_DEBUG);
+
+       return(!isset($result->errors));
+}
+
 ?>