diff --git a/core/polyfills.php b/core/polyfills.php index 26231298..332f3112 100644 --- a/core/polyfills.php +++ b/core/polyfills.php @@ -406,6 +406,22 @@ function get_base_href(): string return $dir; } +/** + * The opposite of the standard library's parse_url + */ +function unparse_url($parsed_url) { + $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : ''; + $host = isset($parsed_url['host']) ? $parsed_url['host'] : ''; + $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''; + $user = isset($parsed_url['user']) ? $parsed_url['user'] : ''; + $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : ''; + $pass = ($user || $pass) ? "$pass@" : ''; + $path = isset($parsed_url['path']) ? $parsed_url['path'] : ''; + $query = !empty($parsed_url['query']) ? '?' . $parsed_url['query'] : ''; + $fragment = !empty($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : ''; + return "$scheme$user$pass$host$port$path$query$fragment"; +} + function startsWith(string $haystack, string $needle): bool { $length = strlen($needle); diff --git a/core/tests/urls.test.php b/core/tests/urls.test.php index cec18284..0915bdcb 100644 --- a/core/tests/urls.test.php +++ b/core/tests/urls.test.php @@ -39,4 +39,22 @@ class UrlsTest extends TestCase make_http("https://foo.com") ); } + + public function test_modify_url() + { + $this->assertEquals( + "/foo/bar?a=3&b=2", + modify_url("/foo/bar?a=1&b=2", ["a"=>"3"]) + ); + + $this->assertEquals( + "https://blah.com/foo/bar?b=2", + modify_url("https://blah.com/foo/bar?a=1&b=2", ["a"=>null]) + ); + + $this->assertEquals( + "/foo/bar", + modify_url("/foo/bar?a=1&b=2", ["a"=>null, "b"=>null]) + ); + } } diff --git a/core/urls.php b/core/urls.php index a774b940..f4b1b721 100644 --- a/core/urls.php +++ b/core/urls.php @@ -1,7 +1,4 @@ $v) { if (is_null($v) and isset($params[$k])) { unset($params[$k]); } $params[$k] = $v; } + $parts['query'] = http_build_query($params); - return make_link($base, http_build_query($params)); + return unparse_url($parts); } @@ -117,6 +98,10 @@ function make_http(string $link): string return $link; } +/** + * If HTTP_REFERER is set, and not blacklisted, then return it + * Else return a default $dest + */ function referer_or(string $dest, ?array $blacklist=null): string { if(empty($_SERVER['HTTP_REFERER'])) return $dest; diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 9d8dc0ce..8d3dfed2 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -112,6 +112,7 @@ abstract class ShimmiePHPUnitTestCase extends TestCase if (!$args) { $args = []; } + $_SERVER['REQUEST_URI'] = make_link($page_name, http_build_query($args)); $_GET = $args; $_POST = []; $page = new Page(); @@ -129,6 +130,7 @@ abstract class ShimmiePHPUnitTestCase extends TestCase if (!$args) { $args = []; } + $_SERVER['REQUEST_URI'] = make_link($page_name); foreach ($args as $k=>$v) { if(is_array($v)) { $args[$k] = $v;