]> git.mxchange.org Git - friendica-addons.git/blobdiff - twitter/twitter.php
Merge pull request #172 from annando/master
[friendica-addons.git] / twitter / twitter.php
index 42a373b874bd9ece94ad1c9641c34314dfc7188b..0043a3a9bd989de8ec90b2f63af130a1097f4944 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,8 +230,13 @@ function twitter_settings(&$a,&$s) {
         $create_userenabled = get_pconfig(local_user(),'twitter','create_user');
         $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
 
-       $s .= '<div class="settings-block">';
-       $s .= '<h3>'. t('Twitter Posting Settings') .'</h3>';
+       $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 .= '</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 .= '</span>';
 
        if ( (!$ckey) && (!$csecret) ) {
                /***
@@ -627,8 +633,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 {
@@ -675,9 +685,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) {
@@ -762,6 +777,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);
@@ -787,16 +803,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) . '"');
@@ -937,6 +943,8 @@ function twitter_fetchtimeline($a, $uid) {
        if ($application_name == "")
                $application_name = $a->get_hostname();
 
+       $has_picture = false;
+
        require_once('mod/item.php');
 
        require_once('library/twitteroauth.php');
@@ -988,12 +996,13 @@ function twitter_fetchtimeline($a, $uid) {
                                                switch($media->type) {
                                                        case 'photo':
                                                                $_REQUEST['body'] = str_replace($media->url, "\n\n[img]".$media->media_url_https."[/img]\n", $_REQUEST['body']);
+                                                               $has_picture = true;
                                                                break;
                                                }
                                        }
                                }
 
-                               $converted = twitter_convertmsg($a, $_REQUEST['body'], true);
+                               $converted = twitter_convertmsg($a, $_REQUEST['body'], true, $has_picture);
                                $_REQUEST['body'] = $converted["body"];
 
                                $_REQUEST['body'] = "[share author='".$post->retweeted_status->user->name.
@@ -1010,12 +1019,13 @@ function twitter_fetchtimeline($a, $uid) {
                                                switch($media->type) {
                                                        case 'photo':
                                                                $_REQUEST['body'] = str_replace($media->url, "\n\n[img]".$media->media_url_https."[/img]\n", $_REQUEST['body']);
+                                                               $has_picture = true;
                                                                break;
                                                }
                                        }
                                }
 
-                               $converted = twitter_convertmsg($a, $_REQUEST["body"], true);
+                               $converted = twitter_convertmsg($a, $_REQUEST["body"], true, $has_picture);
                                $_REQUEST['body'] = $converted["body"];
                        }
 
@@ -1110,6 +1120,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));
 
@@ -1182,6 +1210,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.
 
@@ -1269,7 +1298,11 @@ function twitter_fetchuser($a, $uid, $screen_name = "", $user_id = "") {
 }
 
 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;
@@ -1364,6 +1397,7 @@ function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing
                        switch($media->type) {
                                case 'photo':
                                        $postarray['body'] = str_replace($media->url, "\n\n[img]".$media->media_url_https."[/img]\n", $postarray['body']);
+                                       $has_picture = true;
                                        break;
                                default:
                                        $postarray['body'] .= print_r($media, true);
@@ -1371,7 +1405,7 @@ function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing
                }
        }
 
-       $converted = twitter_convertmsg($a, $postarray['body']);
+       $converted = twitter_convertmsg($a, $postarray['body'], false, $has_picture);
        $postarray['body'] = $converted["body"];
        $postarray['tag'] = $converted["tags"];
 
@@ -1400,6 +1434,7 @@ function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing
                                switch($media->type) {
                                        case 'photo':
                                                $postarray['body'] = str_replace($media->url, "\n\n[img]".$media->media_url_https."[/img]\n", $postarray['body']);
+                                               $has_picture = true;
                                                break;
                                        default:
                                                $postarray['body'] .= print_r($media, true);
@@ -1407,10 +1442,11 @@ function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing
                        }
                }
 
-               $converted = twitter_convertmsg($a, $postarray['body']);
+               $converted = twitter_convertmsg($a, $postarray['body'], 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'))) {
@@ -1425,6 +1461,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;
+                       //}
                }
 
        }
@@ -1722,10 +1762,14 @@ function twitter_original_url($url, $depth=1, $fetchbody = false) {
         return($url);
 }
 
-function twitter_siteinfo($url) {
+function twitter_siteinfo($url, $dontincludemedia) {
        require_once("mod/parse_url.php");
 
-       $data = parseurl_getsiteinfo($url);
+       // 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("");
@@ -1733,36 +1777,46 @@ function twitter_siteinfo($url) {
        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";
+               //$text .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
+               $text .= '[img]'.$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) {
+function twitter_convertmsg($a, $body, $no_tags = false, $dontincludemedia) {
+
+       require_once("include/oembed.php");
 
        $links = preg_match_all("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", $body,$matches,PREG_SET_ORDER);
 
        $footer = "";
+       $footerurl = "";
+       $type = "";
 
        if ($links) {
                foreach ($matches AS $match) {
                        $expanded_url = twitter_original_url($match[2]);
 
-                       // To-Do:
-                       // Twitlonger
+                       $oembed_data = oembed_fetch_url($expanded_url);
 
-                       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, "//instagram.com"))
+                       if ($type == "")
+                               $type = $oembed_data->type;
+
+                       if ($oembed_data->type != "link")
                                $body = str_replace($match[2], "\n[url]".$expanded_url."[/url]\n", $body);
                        else {
                                $img_str = fetch_url($expanded_url, true, $redirects, 4);
@@ -1772,12 +1826,13 @@ function twitter_convertmsg($a, $body, $no_tags = false) {
                                $mime = image_type_to_mime_type(exif_imagetype($tempfile));
                                unlink($tempfile);
 
-                               if (substr($mime, 0, 6) == "image/")
+                               if (substr($mime, 0, 6) == "image/") {
+                                       $type = "photo";
                                        $body = str_replace($match[2], "[img]".$expanded_url."[/img]", $body);
-                               else {
-
-                                       //if ($footer == "")
-                                       $footer = "\n\n".twitter_siteinfo($expanded_url);
+                                       $dontincludemedia = true;
+                               } else {
+                                       $type = $oembed_data->type;
+                                       $footerurl = $expanded_url;
                                        $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
 
                                        $body = str_replace($match[2], $footerlink, $body);
@@ -1785,13 +1840,16 @@ function twitter_convertmsg($a, $body, $no_tags = false) {
                        }
                }
 
+               if ($footerurl != "")
+                       $footer = twitter_siteinfo($footerurl, $dontincludemedia);
+
                if (($footerlink != "") AND (trim($footer) != "")) {
                        $removedlink = trim(str_replace($footerlink, "", $body));
 
                        if (strstr($body, $removedlink))
                                $body = $removedlink;
 
-                       $body .= $footer;
+                       $body .= "\n\n[class=type-".$type."]".$footer."[/class]";
                }
        }
 
@@ -1872,8 +1930,57 @@ 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);
+
+       return(!isset($result->errors));
+}
+
 ?>