Skip to content

Commit

Permalink
add shortlink chaining up to 5 levels
Browse files Browse the repository at this point in the history
  • Loading branch information
kvibber committed Jun 24, 2022
1 parent 702032a commit 051cd1e
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
9 changes: 9 additions & 0 deletions linkchain.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
https://hyperborea.org/journal/2022/04/corrupted-gnome/
https://hyperborea.org/journal/?p=81451
https://wp.me/p4vcr-lbJ
https://tinyurl.com/33y4khfs
https://bit.ly/3HMdji2
http://ow.ly/Vcq050JGjmM
https://bit.ly/3xT4SwX
https://t.co/kTzFTX65HT

1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Automatically expands URLs at the following known link shorteners when you save
* dlvr.it
* fb.me
* qr.ae
* aka.ms

## Installation

Expand Down
15 changes: 11 additions & 4 deletions unwrap-shortlinks.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
function ktv_unwrap_shortlinks($content) {
preg_match_all('/\b(https?:\/\/(?:t\.co|bit\.ly|j\.mp|ow\.ly|is\.gd|trib\.al|buff\.ly|tmblr\.co|wp\.me|tinyurl\.com|goo\.gl|dlvr\.it|fb\.me|qr\.ae|aka\.ms)\/[^\s"\'<>]+)\b/', $content, $matches, PREG_PATTERN_ORDER);
foreach ($matches[1] as $link) {
$getlink = ktv_unwrap_shortlinks_replace($link);
$getlink = ktv_unwrap_shortlinks_replace($link, 5);
if ($getlink != "")
$content = str_replace($link, $getlink, $content);
}
Expand All @@ -24,15 +24,22 @@ function ktv_unwrap_shortlinks($content) {



function ktv_unwrap_shortlinks_replace($url) {
function ktv_unwrap_shortlinks_replace($url, $countdown) {
// make a head request and don't follow redirection, just look at the response.
$response = wp_remote_head( $url ); //, array( 'redirection' => 0 ) );
$status = wp_remote_retrieve_response_code( $response );
$finalURL = wp_remote_retrieve_header( $response, 'location' );

// If it was a redirect, return the next URL.
// If it was a redirect, get the next URL
if ($status == 301 || $status == 302 || $status == 307 || $status == 308) {
return esc_url($finalURL);
// TODO Is it also a redirector? Do we have iterations left?
// If so, try to follow that one!
if( $countdown > 0 && preg_match('/\b(https?:\/\/(?:t\.co|bit\.ly|j\.mp|ow\.ly|is\.gd|trib\.al|buff\.ly|tmblr\.co|wp\.me|tinyurl\.com|goo\.gl|dlvr\.it|fb\.me|qr\.ae|aka\.ms)\/[^\s"\'<>]+)\b/', $finalURL) ) {
return ktv_unwrap_shortlinks_replace($finalURL, $countdown - 1);
} else {
// Otherwise, send it back up the chain!
return esc_url($finalURL);
}
}
// We didn't get anything, or it didn't redirect, so let's return a blank.
return "";
Expand Down

0 comments on commit 051cd1e

Please sign in to comment.