File: UrlHelper.php

package info (click to toggle)
matomo 5.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 95,068 kB
  • sloc: php: 289,425; xml: 127,249; javascript: 112,130; python: 202; sh: 178; makefile: 20; sql: 10
file content (395 lines) | stat: -rw-r--r-- 13,680 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
<?php

/**
 * Matomo - free/libre analytics platform
 *
 * @link    https://matomo.org
 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik;

use Piwik\Container\StaticContainer;
use Piwik\Intl\Data\Provider\RegionDataProvider;

/**
 * Contains less commonly needed URL helper methods.
 *
 */
class UrlHelper
{
    /**
     * @var string[]
     */
    private static $validLinkProtocols = [
        'http',
        'https',
        'tel',
        'sms',
        'mailto',
        'callto',
    ];

    /**
     * Checks if a string matches/is equal to one of the patterns/strings.
     *
     * @static
     * @param string $test String to test.
     * @param string[] $patterns Array of strings or regexs.
     *
     * @return bool true if $test matches or is equal to one of the regex/string in $patterns, false otherwise.
     */
    protected static function inArrayMatchesRegex($test, $patterns): bool
    {
        foreach ($patterns as $val) {
            if (@preg_match($val, '') === false) {
                if (strcasecmp($val, $test) === 0) {
                    return true;
                }
            } else {
                if (preg_match($val, $test) === 1) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Converts an array of query parameter name/value mappings into a query string.
     * Parameters that are in `$parametersToExclude` will not appear in the result.
     *
     * @static
     * @param array<string, string|false|array<string|false>> $queryParameters Array of query parameters, eg, `array('site' => '0', 'date' => '2012-01-01')`.
     * @param string[] $parametersToExclude Array of query parameter names that shouldn't be
     *                             in the result query string, eg, `array('date', 'period')`.
     * @return string A query string, eg, `"?site=0"`.
     * @api
     */
    public static function getQueryStringWithExcludedParameters($queryParameters, $parametersToExclude)
    {
        $validQuery = '';
        $separator = '&';
        foreach ($queryParameters as $name => $value) {
            // decode encoded square brackets
            $name = str_replace(array('%5B', '%5D'), array('[', ']'), $name);

            if (!self::inArrayMatchesRegex(strtolower($name), $parametersToExclude)) {
                if (is_array($value)) {
                    foreach ($value as $param) {
                        if ($param === false) {
                            $validQuery .= $name . '[]' . $separator;
                        } else {
                            $validQuery .= $name . '[]=' . $param . $separator;
                        }
                    }
                } elseif ($value === false) {
                    $validQuery .= $name . $separator;
                } else {
                    $validQuery .= $name . '=' . $value . $separator;
                }
            }
        }
        $validQuery = substr($validQuery, 0, -strlen($separator));
        return $validQuery;
    }

    /**
     * Reduce URL to more minimal form.  2 letter country codes are
     * replaced by '{}', while other parts are simply removed.
     *
     * Examples:
     *   www.example.com -> example.com
     *   search.example.com -> example.com
     *   m.example.com -> example.com
     *   de.example.com -> {}.example.com
     *   example.de -> example.{}
     *   example.co.uk -> example.{}
     *
     * @param string $url
     * @return string
     */
    public static function getLossyUrl($url)
    {
        static $countries;
        if (!isset($countries)) {
            /** @var RegionDataProvider $regionDataProvider */
            $regionDataProvider = StaticContainer::get('Piwik\Intl\Data\Provider\RegionDataProvider');
            $countries = implode('|', array_keys($regionDataProvider->getCountryList(true)));
        }

        return preg_replace(
            array(
                 '/^(w+[0-9]*|search)\./',
                 '/(^|\.)m\./',
                 '/(\.(com|org|net|co|it|edu))?\.(' . $countries . ')(\/|$)/',
                 '/(^|\.)(' . $countries . ')\./',
            ),
            array(
                 '',
                 '$1',
                 '.{}$4',
                 '$1{}.',
            ),
            $url
        );
    }

    /**
     * Returns true if the string passed may be a URL ie. it starts with protocol://.
     * We don't need a precise test here because the value comes from the website
     * tracked source code and the URLs may look very strange.
     *
     * @api
     * @param string $url
     * @return bool
     */
    public static function isLookLikeUrl($url)
    {
        return $url && preg_match('~^(([[:alpha:]][[:alnum:]+.-]*)?:)?//(.*)$~D', $url, $matches) !== 0
            && strlen($matches[3]) > 0
            && !preg_match('/^(javascript:|vbscript:|data:)/i', $matches[1])
            ;
    }

    /**
     * @param string $url
     * @return bool
     */
    public static function isLookLikeSafeUrl($url)
    {
        if (preg_match('/[\x00-\x1F\x7F]/', $url)) {
            return false;
        }

        if (strpos($url, ':') === false) {
            return true;
        }

        $protocol = explode(':', $url, 2)[0];
        return (bool)preg_match('/^(' . implode('|', self::$validLinkProtocols) . ')$/i', $protocol);
    }

    /**
     * Returns a URL created from the result of the [parse_url](https://php.net/manual/en/function.parse-url.php)
     * function.
     *
     * Copied from the PHP comments at [https://php.net/parse_url](https://php.net/parse_url).
     *
     * @param array $parsed Result of [parse_url](https://php.net/manual/en/function.parse-url.php).
     * @return false|string The URL or `false` if `$parsed` isn't an array.
     * @api
     */
    public static function getParseUrlReverse($parsed)
    {
        if (!is_array($parsed)) {
            return false;
        }

        // According to RFC 1738, the chars ':', '@' and '/' need to be encoded in username or password part of an url
        // We also encode '\' as a username or password containing that char, might be handled incorrectly by browsers
        $escapeSpecialChars = function ($value) {
            return str_replace([':', '@', '/', '\\'], [urlencode(':'), urlencode('@'), urlencode('/'), urlencode('\\')], $value);
        };

        $uri = !empty($parsed['scheme']) ? $parsed['scheme'] . ':' . (!strcasecmp($parsed['scheme'], 'mailto') ? '' : '//') : '';
        $uri .= !empty($parsed['user']) ? $escapeSpecialChars($parsed['user']) . (!empty($parsed['pass']) ? ':' . $escapeSpecialChars($parsed['pass']) : '') . '@' : '';
        $uri .= !empty($parsed['host']) ? $parsed['host'] : '';
        $uri .= !empty($parsed['port']) ? ':' . $parsed['port'] : '';

        if (!empty($parsed['path'])) {
            $uri .= (!strncmp($parsed['path'], '/', 1))
                ? $parsed['path']
                : ((!empty($uri) ? '/' : '') . $parsed['path']);
        }

        $uri .= !empty($parsed['query']) ? '?' . $parsed['query'] : '';
        $uri .= !empty($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
        return $uri;
    }

    /**
     * Returns a URL query string as an array.
     *
     * @param string $urlQuery The query string, eg, `'?param1=value1&param2=value2'`.
     * @return array eg, `array('param1' => 'value1', 'param2' => 'value2')`
     * @api
     */
    public static function getArrayFromQueryString($urlQuery)
    {
        if (empty($urlQuery)) {
            return array();
        }

        // TODO: this method should not use a cache. callers should instead have their own cache, configured through DI.
        //       one undesirable side effect of using a cache here, is that this method can now init the StaticContainer, which makes setting
        //       test environment for RequestCommand more complicated.
        $cache    = Cache::getTransientCache();
        $cacheKey = 'arrayFromQuery' . $urlQuery;

        if ($cache->contains($cacheKey)) {
            return $cache->fetch($cacheKey);
        }

        if ($urlQuery[0] == '?') {
            $urlQuery = substr($urlQuery, 1);
        }
        $separator = '&';

        $urlQuery = $separator . $urlQuery;
        //        $urlQuery = str_replace(array('%20'), ' ', $urlQuery);
        $referrerQuery = trim($urlQuery);

        $values = explode($separator, $referrerQuery);

        $nameToValue = array();

        foreach ($values as $value) {
            $pos = strpos($value, '=');
            if ($pos !== false) {
                $name = substr($value, 0, $pos);
                $value = substr($value, $pos + 1);
                if ($value === false) {
                    $value = '';
                }
            } else {
                $name = $value;
                $value = false;
            }
            if (!empty($name)) {
                $name = Common::sanitizeInputValue($name);
            }
            if (!empty($value)) {
                $value = Common::sanitizeInputValue($value);
            }

            // if array without indexes
            $count = 0;
            $tmp = preg_replace('/(\[|%5b)(]|%5d)$/i', '', $name, -1, $count);
            if (!empty($tmp) && $count) {
                $name = $tmp;
                if (isset($nameToValue[$name]) == false || is_array($nameToValue[$name]) == false) {
                    $nameToValue[$name] = array();
                }
                array_push($nameToValue[$name], $value);
            } elseif (!empty($name)) {
                $nameToValue[$name] = $value;
            }
        }

        $cache->save($cacheKey, $nameToValue);

        return $nameToValue;
    }

    /**
     * Returns the value of a single query parameter from the supplied query string.
     *
     * @param string $urlQuery The query string.
     * @param string $parameter The query parameter name to return.
     * @return string|null Parameter value if found (can be the empty string!), null if not found.
     * @api
     */
    public static function getParameterFromQueryString($urlQuery, $parameter)
    {
        $nameToValue = self::getArrayFromQueryString($urlQuery);

        if (isset($nameToValue[$parameter])) {
            return $nameToValue[$parameter];
        }
        return null;
    }

    /**
     * Returns the path and query string of a URL.
     *
     * @param string    $url                    The URL.
     * @param array     $additionalParamsToAdd  If not empty the given parameters will be added to the query.
     * @param bool      $preserveAnchor         If true then do not remove any #anchor from the url, default false
     * @return string eg, `/test/index.php?module=CoreHome` if `$url` is `https://piwik.org/test/index.php?module=CoreHome`.
     * @api
     */
    public static function getPathAndQueryFromUrl($url, array $additionalParamsToAdd = [], bool $preserveAnchor = false)
    {
        $parsedUrl = parse_url($url);

        // If an anchor is included in the URL parse_url() will not split the anchor and query, so we do that there
        if (isset($parsedUrl['fragment']) && strpos($parsedUrl['fragment'], '?') !== false) {
            $parsedUrl['query'] = substr($parsedUrl['fragment'], strpos($parsedUrl['fragment'], '?') + 1);
            $parsedUrl['fragment'] = substr($parsedUrl['fragment'], 0, strpos($parsedUrl['fragment'], '?'));
        }

        $result = '';

        if (isset($parsedUrl['path'])) {
            if (substr($parsedUrl['path'], 0, 1) == '/') {
                $parsedUrl['path'] = substr($parsedUrl['path'], 1);
            }
            $result .= $parsedUrl['path'];
        }

        if ($preserveAnchor && isset($parsedUrl['fragment'])) {
            $result .= '#' . $parsedUrl['fragment'];
        }

        if (isset($parsedUrl['query']) || count($additionalParamsToAdd)) {
            $query = (isset($parsedUrl['query']) ? $parsedUrl['query'] : '');
            $query = self::addAdditionalParameters($query, $additionalParamsToAdd);
            $result .= '?' . $query;
        }
        return $result;
    }

    /**
     * Returns the query part from any valid url and adds additional parameters to the query part if needed.
     *
     * @param string $url    Any url eg `"https://example.com/piwik/?foo=bar"`
     * @param array $additionalParamsToAdd    If not empty the given parameters will be added to the query.
     *
     * @return string eg. `"foo=bar&foo2=bar2"`
     * @api
     */
    public static function getQueryFromUrl($url, array $additionalParamsToAdd = [])
    {
        $url = @parse_url($url);
        $query = '';

        if (!empty($url['query'])) {
            $query .= $url['query'];
        }

        $query = self::addAdditionalParameters($query, $additionalParamsToAdd);

        return $query;
    }

    /**
     * Add an array of additional parameters to a query string
     *
     * @param array  $additionalParamsToAdd
     *
     */
    private static function addAdditionalParameters(string $query, array $additionalParamsToAdd): string
    {
        if (!empty($additionalParamsToAdd)) {
            if (!empty($query)) {
                $query .= '&';
            }
            $query .= Url::getQueryStringFromParameters($additionalParamsToAdd);
        }

        return $query;
    }

    /**
     * @param string $url
     * @return string|false|null
     */
    public static function getHostFromUrl($url)
    {
        if (!UrlHelper::isLookLikeUrl($url)) {
            $url = "http://" . $url;
        }
        return parse_url($url, PHP_URL_HOST);
    }
}