From 6ccd564d566e9d00465ab887f4ab2814737ec52d Mon Sep 17 00:00:00 2001 From: Jonny Barnes Date: Fri, 12 Jan 2018 12:20:36 +0000 Subject: [PATCH] Remove unwanted query parameters from normalized URLs --- helpers.php | 29 +++++++++++++++++++++-------- tests/Unit/HelpersTest.php | 21 +++++++++++++-------- 2 files changed, 34 insertions(+), 16 deletions(-) diff --git a/helpers.php b/helpers.php index 7e5a0852..230c6317 100644 --- a/helpers.php +++ b/helpers.php @@ -126,20 +126,33 @@ if (! function_exists('normalize_url')) { // Sort GET params alphabetically, not because the RFC requires it but because it's cool! if (isset($url['query'])) { - if (preg_match('/&/', $url['query'])) { - $s = explode('&', $url['query']); - $url['query'] = ''; - sort($s); - foreach ($s as $z) { - $url['query'] .= "{$z}&"; + $queries = explode('&', $url['query']); + $url['query'] = ''; + sort($queries); + foreach ($queries as $query) { + //lets drop query params we don’t want + $key = stristr($query, '=', true); + if (queryKeyIsBanned($key) === false) { + $url['query'] .= "{$query}&"; } - $url['query'] = preg_replace('/&\Z/', '', $url['query']); } - $newUrl .= "?{$url['query']}"; + $url['query'] = preg_replace('/&\Z/', '', $url['query']); + if ($url['query'] !== '') { + $newUrl .= "?{$url['query']}"; + } } return $newUrl; } + + function queryKeyIsBanned(string $key): bool + { + $bannedKeys = [ + 'ref_src', + ]; + + return in_array($key, $bannedKeys); + } } // sourced from https://stackoverflow.com/a/9776726 diff --git a/tests/Unit/HelpersTest.php b/tests/Unit/HelpersTest.php index d1d78298..a9b32150 100644 --- a/tests/Unit/HelpersTest.php +++ b/tests/Unit/HelpersTest.php @@ -12,14 +12,6 @@ class HelpersTest extends TestCase $this->assertEquals(normalize_url(normalize_url($input)), normalize_url($input)); } - /** - * @dataProvider urlProvider - */ - public function test_normalize_url($input, $output) - { - $this->assertEquals($output, normalize_url($input)); - } - public function urlProvider() { return [ @@ -27,9 +19,22 @@ class HelpersTest extends TestCase ['https://example.org:443/', 'https://example.org'], ['http://www.foo.bar/index.php/', 'http://www.foo.bar'], ['https://example.org/?foo=bar&baz=true', 'https://example.org?baz=true&foo=bar'], + [ + 'http://example.org/?ref_src=twcamp^share|twsrc^ios|twgr^software.studioh.Indigenous.share-micropub', + 'http://example.org', + ], ]; } + /** + * @dataProvider urlProvider + * @group temp + */ + public function test_normalize_url($input, $output) + { + $this->assertEquals($output, normalize_url($input)); + } + public function test_pretty_print_json() { $json = <<