]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/http/UrlUtils.php
Merge pull request #1698 from ArthurHoaro/feature/plugins-search-filter
[github/shaarli/Shaarli.git] / application / http / UrlUtils.php
1 <?php
2
3 /**
4 * Converts an array-represented URL to a string
5 *
6 * Source: http://php.net/manual/en/function.parse-url.php#106731
7 *
8 * @see http://php.net/manual/en/function.parse-url.php
9 *
10 * @param array $parsedUrl an array-represented URL
11 *
12 * @return string the string representation of the URL
13 */
14 function unparse_url($parsedUrl)
15 {
16 $scheme = isset($parsedUrl['scheme']) ? $parsedUrl['scheme'] . '://' : '';
17 $host = isset($parsedUrl['host']) ? $parsedUrl['host'] : '';
18 $port = isset($parsedUrl['port']) ? ':' . $parsedUrl['port'] : '';
19 $user = isset($parsedUrl['user']) ? $parsedUrl['user'] : '';
20 $pass = isset($parsedUrl['pass']) ? ':' . $parsedUrl['pass'] : '';
21 $pass = ($user || $pass) ? "$pass@" : '';
22 $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
23 $query = isset($parsedUrl['query']) ? '?' . $parsedUrl['query'] : '';
24 $fragment = isset($parsedUrl['fragment']) ? '#' . $parsedUrl['fragment'] : '';
25
26 return "$scheme$user$pass$host$port$path$query$fragment";
27 }
28
29 /**
30 * Removes undesired query parameters and fragments
31 *
32 * @param string url UrlUtils to be cleaned
33 *
34 * @return string the string representation of this URL after cleanup
35 */
36 function cleanup_url($url)
37 {
38 $obj_url = new \Shaarli\Http\Url($url);
39 return $obj_url->cleanup();
40 }
41
42 /**
43 * Get URL scheme.
44 *
45 * @param string url UrlUtils for which the scheme is requested
46 *
47 * @return mixed the URL scheme or false if none is provided.
48 */
49 function get_url_scheme($url)
50 {
51 $obj_url = new \Shaarli\Http\Url($url);
52 return $obj_url->getScheme();
53 }
54
55 /**
56 * Adds a trailing slash at the end of URL if necessary.
57 *
58 * @param string $url URL to check/edit.
59 *
60 * @return string $url URL with a end trailing slash.
61 */
62 function add_trailing_slash($url)
63 {
64 return $url . (!endsWith($url, '/') ? '/' : '');
65 }
66
67 /**
68 * Replace not whitelisted protocols by 'http://' from given URL.
69 *
70 * @param string $url URL to clean
71 * @param array $protocols List of allowed protocols (aside from http(s)).
72 *
73 * @return string URL with allowed protocol
74 */
75 function whitelist_protocols($url, $protocols)
76 {
77 if (startsWith($url, '?') || startsWith($url, '/') || startsWith($url, '#')) {
78 return $url;
79 }
80 $protocols = array_merge(['http', 'https'], $protocols);
81 $protocol = preg_match('#^(\w+):/?/?#', $url, $match);
82 // Protocol not allowed: we remove it and replace it with http
83 if ($protocol === 1 && ! in_array($match[1], $protocols)) {
84 $url = str_replace($match[0], 'http://', $url);
85 } elseif ($protocol !== 1) {
86 $url = 'http://' . $url;
87 }
88 return $url;
89 }