PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 5.0.7
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v5.0.7
5.11.1 5.11.0 5.10.2 5.10.1 trunk 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.1.0 1.1.1 1.1.2 1.1.3 1.2.0 1.3.0 1.3.1 1.3.2 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.1.0 4.1.1 4.1.2 4.1.3 4.10.0 4.11.0 4.12.0 4.13.0 4.13.2 4.13.3 4.13.4 4.13.5 4.14.0 4.14.1 4.14.2 4.15.0 4.15.1 4.15.2 4.15.3 4.2.0 4.3.0 4.3.1 4.4.1 4.4.2 4.5.0 4.6.0 5.0.1 5.0.2 5.0.3 5.0.4 5.0.5 5.0.6 5.0.7 5.0.8 5.1.0 5.1.1 5.1.2 5.1.3 5.1.4 5.1.5 5.1.6 5.1.7 5.10.0 5.2.0 5.2.1 5.2.2 5.3.0 5.3.1 5.3.2 5.3.3 5.6.0 5.6.1 5.7.0 5.7.1 5.8.0 5.8.1 5.8.2
matomo / app / core / UrlHelper.php
matomo / app / core Last commit date
API 2 years ago Access 2 years ago Application 2 years ago Archive 2 years ago ArchiveProcessor 2 years ago Archiver 2 years ago AssetManager 2 years ago Auth 2 years ago Category 2 years ago Changes 2 years ago CliMulti 2 years ago Columns 2 years ago Concurrency 2 years ago Config 2 years ago Container 2 years ago CronArchive 2 years ago DataAccess 2 years ago DataFiles 2 years ago DataTable 2 years ago Db 2 years ago DeviceDetector 2 years ago Email 2 years ago Exception 2 years ago Http 2 years ago Intl 2 years ago Log 2 years ago Mail 2 years ago Measurable 2 years ago Menu 2 years ago Metrics 2 years ago Notification 2 years ago Period 2 years ago Plugin 2 years ago ProfessionalServices 2 years ago Report 2 years ago ReportRenderer 2 years ago Scheduler 2 years ago Segment 2 years ago Session 2 years ago Settings 2 years ago Tracker 2 years ago Translation 2 years ago Twig 2 years ago UpdateCheck 2 years ago Updater 2 years ago Updates 2 years ago Validators 2 years ago View 2 years ago ViewDataTable 2 years ago Visualization 2 years ago Widget 2 years ago .htaccess 2 years ago Access.php 2 years ago Archive.php 2 years ago ArchiveProcessor.php 2 years ago AssetManager.php 2 years ago Auth.php 2 years ago AuthResult.php 2 years ago BaseFactory.php 2 years ago Cache.php 2 years ago CacheId.php 2 years ago CliMulti.php 2 years ago Common.php 2 years ago Config.php 2 years ago Console.php 2 years ago Context.php 2 years ago Cookie.php 2 years ago CronArchive.php 2 years ago DI.php 2 years ago DataArray.php 2 years ago DataTable.php 2 years ago Date.php 2 years ago Db.php 2 years ago DbHelper.php 2 years ago Development.php 2 years ago ErrorHandler.php 2 years ago EventDispatcher.php 2 years ago ExceptionHandler.php 2 years ago FileIntegrity.php 2 years ago Filechecks.php 2 years ago Filesystem.php 2 years ago FrontController.php 2 years ago Http.php 2 years ago IP.php 2 years ago Log.php 2 years ago LogDeleter.php 2 years ago Mail.php 2 years ago Metrics.php 2 years ago NoAccessException.php 2 years ago Nonce.php 2 years ago Notification.php 2 years ago NumberFormatter.php 2 years ago Option.php 2 years ago Period.php 2 years ago Piwik.php 2 years ago Plugin.php 2 years ago Profiler.php 2 years ago ProxyHeaders.php 2 years ago ProxyHttp.php 2 years ago QuickForm2.php 2 years ago RankingQuery.php 2 years ago ReportRenderer.php 2 years ago Request.php 2 years ago Segment.php 2 years ago Sequence.php 2 years ago Session.php 2 years ago SettingsPiwik.php 2 years ago SettingsServer.php 2 years ago Singleton.php 2 years ago Site.php 2 years ago SiteContentDetector.php 2 years ago SupportedBrowser.php 2 years ago TCPDF.php 2 years ago Theme.php 2 years ago Timer.php 2 years ago Tracker.php 2 years ago Twig.php 2 years ago Unzip.php 2 years ago UpdateCheck.php 2 years ago Updater.php 2 years ago UpdaterErrorException.php 2 years ago Updates.php 2 years ago Url.php 2 years ago UrlHelper.php 2 years ago Version.php 2 years ago View.php 2 years ago bootstrap.php 2 years ago dispatch.php 2 years ago testMinimumPhpVersion.php 2 years ago
UrlHelper.php
315 lines
1 <?php
2
3 /**
4 * Matomo - free/libre analytics platform
5 *
6 * @link https://matomo.org
7 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8 *
9 */
10 namespace Piwik;
11
12 use Piwik\Container\StaticContainer;
13 use Piwik\Intl\Data\Provider\RegionDataProvider;
14 /**
15 * Contains less commonly needed URL helper methods.
16 *
17 */
18 class UrlHelper
19 {
20 private static $validLinkProtocols = ['http', 'https', 'tel', 'sms', 'mailto', 'callto'];
21 /**
22 * Checks if a string matches/is equal to one of the patterns/strings.
23 *
24 * @static
25 * @param $test String to test.
26 * @param $patterns Array of strings or regexs.
27 *
28 * @return bool true if $test matches or is equal to one of the regex/string in $patterns, false otherwise.
29 */
30 protected static function inArrayMatchesRegex($test, $patterns) : bool
31 {
32 foreach ($patterns as $val) {
33 if (@preg_match($val, null) === false) {
34 if (strcasecmp($val, $test) === 0) {
35 return true;
36 }
37 } else {
38 if (preg_match($val, $test) === 1) {
39 return true;
40 }
41 }
42 }
43 return false;
44 }
45 /**
46 * Converts an array of query parameter name/value mappings into a query string.
47 * Parameters that are in `$parametersToExclude` will not appear in the result.
48 *
49 * @static
50 * @param $queryParameters Array of query parameters, eg, `array('site' => '0', 'date' => '2012-01-01')`.
51 * @param $parametersToExclude Array of query parameter names that shouldn't be
52 * in the result query string, eg, `array('date', 'period')`.
53 * @return string A query string, eg, `"?site=0"`.
54 * @api
55 */
56 public static function getQueryStringWithExcludedParameters($queryParameters, $parametersToExclude)
57 {
58 $validQuery = '';
59 $separator = '&';
60 foreach ($queryParameters as $name => $value) {
61 // decode encoded square brackets
62 $name = str_replace(array('%5B', '%5D'), array('[', ']'), $name);
63 if (!self::inArrayMatchesRegex(strtolower($name), $parametersToExclude)) {
64 if (is_array($value)) {
65 foreach ($value as $param) {
66 if ($param === false) {
67 $validQuery .= $name . '[]' . $separator;
68 } else {
69 $validQuery .= $name . '[]=' . $param . $separator;
70 }
71 }
72 } elseif ($value === false) {
73 $validQuery .= $name . $separator;
74 } else {
75 $validQuery .= $name . '=' . $value . $separator;
76 }
77 }
78 }
79 $validQuery = substr($validQuery, 0, -strlen($separator));
80 return $validQuery;
81 }
82 /**
83 * Reduce URL to more minimal form. 2 letter country codes are
84 * replaced by '{}', while other parts are simply removed.
85 *
86 * Examples:
87 * www.example.com -> example.com
88 * search.example.com -> example.com
89 * m.example.com -> example.com
90 * de.example.com -> {}.example.com
91 * example.de -> example.{}
92 * example.co.uk -> example.{}
93 *
94 * @param string $url
95 * @return string
96 */
97 public static function getLossyUrl($url)
98 {
99 static $countries;
100 if (!isset($countries)) {
101 /** @var RegionDataProvider $regionDataProvider */
102 $regionDataProvider = StaticContainer::get('Piwik\\Intl\\Data\\Provider\\RegionDataProvider');
103 $countries = implode('|', array_keys($regionDataProvider->getCountryList(true)));
104 }
105 return preg_replace(array('/^(w+[0-9]*|search)\\./', '/(^|\\.)m\\./', '/(\\.(com|org|net|co|it|edu))?\\.(' . $countries . ')(\\/|$)/', '/(^|\\.)(' . $countries . ')\\./'), array('', '$1', '.{}$4', '$1{}.'), $url);
106 }
107 /**
108 * Returns true if the string passed may be a URL ie. it starts with protocol://.
109 * We don't need a precise test here because the value comes from the website
110 * tracked source code and the URLs may look very strange.
111 *
112 * @api
113 * @param string $url
114 * @return bool
115 */
116 public static function isLookLikeUrl($url)
117 {
118 return $url && preg_match('~^(([[:alpha:]][[:alnum:]+.-]*)?:)?//(.*)$~D', $url, $matches) !== 0 && strlen($matches[3]) > 0 && !preg_match('/^(javascript:|vbscript:|data:)/i', $matches[1]);
119 }
120 public static function isLookLikeSafeUrl($url)
121 {
122 if (preg_match('/[\\x00-\\x1F\\x7F]/', $url)) {
123 return false;
124 }
125 if (strpos($url, ':') === false) {
126 return true;
127 }
128 $protocol = explode(':', $url, 2)[0];
129 return preg_match('/^(' . implode('|', self::$validLinkProtocols) . ')$/i', $protocol);
130 }
131 /**
132 * Returns a URL created from the result of the [parse_url](http://php.net/manual/en/function.parse-url.php)
133 * function.
134 *
135 * Copied from the PHP comments at [http://php.net/parse_url](http://php.net/parse_url).
136 *
137 * @param array $parsed Result of [parse_url](http://php.net/manual/en/function.parse-url.php).
138 * @return false|string The URL or `false` if `$parsed` isn't an array.
139 * @api
140 */
141 public static function getParseUrlReverse($parsed)
142 {
143 if (!is_array($parsed)) {
144 return false;
145 }
146 $uri = !empty($parsed['scheme']) ? $parsed['scheme'] . ':' . (!strcasecmp($parsed['scheme'], 'mailto') ? '' : '//') : '';
147 $uri .= !empty($parsed['user']) ? $parsed['user'] . (!empty($parsed['pass']) ? ':' . $parsed['pass'] : '') . '@' : '';
148 $uri .= !empty($parsed['host']) ? $parsed['host'] : '';
149 $uri .= !empty($parsed['port']) ? ':' . $parsed['port'] : '';
150 if (!empty($parsed['path'])) {
151 $uri .= !strncmp($parsed['path'], '/', 1) ? $parsed['path'] : (!empty($uri) ? '/' : '') . $parsed['path'];
152 }
153 $uri .= !empty($parsed['query']) ? '?' . $parsed['query'] : '';
154 $uri .= !empty($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
155 return $uri;
156 }
157 /**
158 * Returns a URL query string as an array.
159 *
160 * @param string $urlQuery The query string, eg, `'?param1=value1&param2=value2'`.
161 * @return array eg, `array('param1' => 'value1', 'param2' => 'value2')`
162 * @api
163 */
164 public static function getArrayFromQueryString($urlQuery)
165 {
166 if (empty($urlQuery)) {
167 return array();
168 }
169 // TODO: this method should not use a cache. callers should instead have their own cache, configured through DI.
170 // one undesirable side effect of using a cache here, is that this method can now init the StaticContainer, which makes setting
171 // test environment for RequestCommand more complicated.
172 $cache = \Piwik\Cache::getTransientCache();
173 $cacheKey = 'arrayFromQuery' . $urlQuery;
174 if ($cache->contains($cacheKey)) {
175 return $cache->fetch($cacheKey);
176 }
177 if ($urlQuery[0] == '?') {
178 $urlQuery = substr($urlQuery, 1);
179 }
180 $separator = '&';
181 $urlQuery = $separator . $urlQuery;
182 // $urlQuery = str_replace(array('%20'), ' ', $urlQuery);
183 $referrerQuery = trim($urlQuery);
184 $values = explode($separator, $referrerQuery);
185 $nameToValue = array();
186 foreach ($values as $value) {
187 $pos = strpos($value, '=');
188 if ($pos !== false) {
189 $name = substr($value, 0, $pos);
190 $value = substr($value, $pos + 1);
191 if ($value === false) {
192 $value = '';
193 }
194 } else {
195 $name = $value;
196 $value = false;
197 }
198 if (!empty($name)) {
199 $name = \Piwik\Common::sanitizeInputValue($name);
200 }
201 if (!empty($value)) {
202 $value = \Piwik\Common::sanitizeInputValue($value);
203 }
204 // if array without indexes
205 $count = 0;
206 $tmp = preg_replace('/(\\[|%5b)(]|%5d)$/i', '', $name, -1, $count);
207 if (!empty($tmp) && $count) {
208 $name = $tmp;
209 if (isset($nameToValue[$name]) == false || is_array($nameToValue[$name]) == false) {
210 $nameToValue[$name] = array();
211 }
212 array_push($nameToValue[$name], $value);
213 } elseif (!empty($name)) {
214 $nameToValue[$name] = $value;
215 }
216 }
217 $cache->save($cacheKey, $nameToValue);
218 return $nameToValue;
219 }
220 /**
221 * Returns the value of a single query parameter from the supplied query string.
222 *
223 * @param string $urlQuery The query string.
224 * @param string $parameter The query parameter name to return.
225 * @return string|null Parameter value if found (can be the empty string!), null if not found.
226 * @api
227 */
228 public static function getParameterFromQueryString($urlQuery, $parameter)
229 {
230 $nameToValue = self::getArrayFromQueryString($urlQuery);
231 if (isset($nameToValue[$parameter])) {
232 return $nameToValue[$parameter];
233 }
234 return null;
235 }
236 /**
237 * Returns the path and query string of a URL.
238 *
239 * @param string $url The URL.
240 * @param array $additionalParamsToAdd If not empty the given parameters will be added to the query.
241 * @param bool $preserveAnchor If true then do not remove any #anchor from the url, default false
242 * @return string eg, `/test/index.php?module=CoreHome` if `$url` is `http://piwik.org/test/index.php?module=CoreHome`.
243 * @api
244 */
245 public static function getPathAndQueryFromUrl($url, array $additionalParamsToAdd = [], bool $preserveAnchor = false)
246 {
247 $parsedUrl = parse_url($url);
248 // If an anchor is included in the URL parse_url() will not split the anchor and query, so we do that there
249 if (isset($parsedUrl['fragment']) && strpos($parsedUrl['fragment'], '?') !== false) {
250 $parsedUrl['query'] = substr($parsedUrl['fragment'], strpos($parsedUrl['fragment'], '?') + 1);
251 $parsedUrl['fragment'] = substr($parsedUrl['fragment'], 0, strpos($parsedUrl['fragment'], '?'));
252 }
253 $result = '';
254 if (isset($parsedUrl['path'])) {
255 if (substr($parsedUrl['path'], 0, 1) == '/') {
256 $parsedUrl['path'] = substr($parsedUrl['path'], 1);
257 }
258 $result .= $parsedUrl['path'];
259 }
260 if ($preserveAnchor && isset($parsedUrl['fragment'])) {
261 $result .= '#' . $parsedUrl['fragment'];
262 }
263 if (isset($parsedUrl['query']) || count($additionalParamsToAdd)) {
264 $query = isset($parsedUrl['query']) ? $parsedUrl['query'] : '';
265 $query = self::addAdditionalParameters($query, $additionalParamsToAdd);
266 $result .= '?' . $query;
267 }
268 return $result;
269 }
270 /**
271 * Returns the query part from any valid url and adds additional parameters to the query part if needed.
272 *
273 * @param string $url Any url eg `"http://example.com/piwik/?foo=bar"`
274 * @param array $additionalParamsToAdd If not empty the given parameters will be added to the query.
275 *
276 * @return string eg. `"foo=bar&foo2=bar2"`
277 * @api
278 */
279 public static function getQueryFromUrl($url, array $additionalParamsToAdd = [])
280 {
281 $url = @parse_url($url);
282 $query = '';
283 if (!empty($url['query'])) {
284 $query .= $url['query'];
285 }
286 $query = self::addAdditionalParameters($query, $additionalParamsToAdd);
287 return $query;
288 }
289 /**
290 * Add an array of additional parameters to a query string
291 *
292 * @param string $query
293 * @param array $additionalParamsToAdd
294 *
295 * @return string
296 */
297 private static function addAdditionalParameters(string $query, array $additionalParamsToAdd) : string
298 {
299 if (!empty($additionalParamsToAdd)) {
300 if (!empty($query)) {
301 $query .= '&';
302 }
303 $query .= \Piwik\Url::getQueryStringFromParameters($additionalParamsToAdd);
304 }
305 return $query;
306 }
307 public static function getHostFromUrl($url)
308 {
309 if (!\Piwik\UrlHelper::isLookLikeUrl($url)) {
310 $url = "http://" . $url;
311 }
312 return parse_url($url, PHP_URL_HOST);
313 }
314 }
315