From 51753e403fa69c0ce124ede27d300477e3e799ca Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Mon, 3 Dec 2018 00:34:53 +0100 Subject: namespacing: move HTTP utilities along \Shaarli\Http\ classes Signed-off-by: VirtualTam --- application/http/UrlUtils.php | 88 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 application/http/UrlUtils.php (limited to 'application/http/UrlUtils.php') diff --git a/application/http/UrlUtils.php b/application/http/UrlUtils.php new file mode 100644 index 00000000..4bc84b82 --- /dev/null +++ b/application/http/UrlUtils.php @@ -0,0 +1,88 @@ +cleanup(); +} + +/** + * Get URL scheme. + * + * @param string url UrlUtils for which the scheme is requested + * + * @return mixed the URL scheme or false if none is provided. + */ +function get_url_scheme($url) +{ + $obj_url = new \Shaarli\Http\Url($url); + return $obj_url->getScheme(); +} + +/** + * Adds a trailing slash at the end of URL if necessary. + * + * @param string $url URL to check/edit. + * + * @return string $url URL with a end trailing slash. + */ +function add_trailing_slash($url) +{ + return $url . (!endsWith($url, '/') ? '/' : ''); +} + +/** + * Replace not whitelisted protocols by 'http://' from given URL. + * + * @param string $url URL to clean + * @param array $protocols List of allowed protocols (aside from http(s)). + * + * @return string URL with allowed protocol + */ +function whitelist_protocols($url, $protocols) +{ + if (startsWith($url, '?') || startsWith($url, '/')) { + return $url; + } + $protocols = array_merge(['http', 'https'], $protocols); + $protocol = preg_match('#^(\w+):/?/?#', $url, $match); + // Protocol not allowed: we remove it and replace it with http + if ($protocol === 1 && ! in_array($match[1], $protocols)) { + $url = str_replace($match[0], 'http://', $url); + } elseif ($protocol !== 1) { + $url = 'http://' . $url; + } + return $url; +} -- cgit v1.2.3