/
UrlHelper.php
304 lines (253 loc) · 8.61 KB
/
UrlHelper.php
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
<?php
/*
* @copyright 2014 Mautic Contributors. All rights reserved
* @author Mautic
*
* @link http://mautic.org
*
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\CoreBundle\Helper;
use Joomla\Http\Http;
use Monolog\Logger;
/**
* Class UrlHelper.
*/
class UrlHelper
{
/**
* @var Http
*/
protected $http;
/**
* @var string
*/
protected $shortnerServiceUrl;
/**
* @var Logger
*/
protected $logger;
/**
* UrlHelper constructor.
*
* @param Http|null $http
* @param null $shortnerServiceUrl
* @param Logger|null $logger
*/
public function __construct(Http $http = null, $shortnerServiceUrl = null, Logger $logger = null)
{
$this->http = $http;
$this->shortnerServiceUrl = $shortnerServiceUrl;
}
/**
* Shorten a URL.
*
* @param $url
*
* @return mixed
*/
public function buildShortUrl($url)
{
if (!$this->shortnerServiceUrl) {
return $url;
}
try {
$response = $this->http->get($this->shortnerServiceUrl.urlencode($url));
if ($response->code === 200) {
return rtrim($response->body);
} elseif ($this->logger) {
$this->logger->addWarning("Url shortner failed with code {$response->code}: {$response->body}");
}
} catch (\Exception $exception) {
if ($this->logger) {
$this->logger->addError(
$exception->getMessage(),
['exception' => $exception]
);
}
}
return $url;
}
/**
* @param $rel
*
* @return string
*/
public static function rel2abs($rel)
{
$path = $host = $scheme = '';
$ssl = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
$scheme = strtolower($_SERVER['SERVER_PROTOCOL']);
$scheme = substr($scheme, 0, strpos($scheme, '/')).($ssl ? 's' : '');
$port = $_SERVER['SERVER_PORT'];
$port = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ":$port";
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
$host = isset($host) ? $host : $_SERVER['SERVER_NAME'].$port;
$base = "$scheme://$host".$_SERVER['REQUEST_URI'];
$base = str_replace('/index_dev.php', '', $base);
$base = str_replace('/index.php', '', $base);
/* return if already absolute URL */
if (parse_url($rel, PHP_URL_SCHEME) != '') {
return $rel;
}
/* queries and anchors */
if ($rel[0] == '#' || $rel[0] == '?') {
return $base.$rel;
}
/* after parse base URL and convert to local variables:
$scheme, $host, $path */
$urlPartsArray = parse_url($base);
// We should have a valid URL by this point. If not, just return the original value
if ($urlPartsArray === false) {
return $rel;
}
extract($urlPartsArray);
/* remove non-directory element from path */
$path = preg_replace('#/[^/]*$#', '', $path);
/* destroy path if relative url points to root */
if ($rel[0] == '/') {
$path = '';
}
/* dirty absolute URL // with port number if exists */
if (parse_url($base, PHP_URL_PORT) != '') {
$abs = "$host:".parse_url($base, PHP_URL_PORT)."$path/$rel";
} else {
$abs = "$host$path/$rel";
}
/* replace '//' or '/./' or '/foo/../' with '/' */
$re = ['#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#'];
for ($n = 1; $n > 0; $abs = preg_replace($re, '/', $abs, -1, $n)) {
}
/* absolute URL is ready! */
return $scheme.'://'.$abs;
}
/**
* Takes a plaintext, finds all URLs in it and return the array of those URLs.
* With exception of URLs used as a token default values.
*
* @param string $text
* @param array $contactUrlFields
*
* @return array
*/
public static function getUrlsFromPlaintext($text, array $contactUrlFields = [])
{
$urls = [];
// Check if there are any tokens that URL based fields
foreach ($contactUrlFields as $field) {
if (strpos($text, "{contactfield=$field}") !== false) {
$urls[] = "{contactfield=$field}";
}
}
$regex = '_(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?_ius';
if (!preg_match_all($regex, $text, $matches)) {
return $urls;
}
$urls = array_merge($urls, $matches[0]);
foreach ($urls as $key => $url) {
// Remove dangling punctuation
$urls[$key] = $url = self::removeTrailingNonAlphaNumeric($url);
// We don't want to match URLs in token default values
// like {contactfield=website|http://ignore.this.url}
if (preg_match_all("/{(.*?)\|".preg_quote($url, '/').'}/', $text, $matches)) {
unset($urls[$key]);
// We know this is a URL due to the default so let's include it as a trackable
foreach ($matches[1] as $tokenKey => $tokenContent) {
$urls[] = $matches[0][$tokenKey];
}
}
}
return $urls;
}
/**
* Sanitize parts of the URL to make sure the URL query values are HTTP encoded.
*
* @param string $url
*
* @return string
*/
public static function sanitizeAbsoluteUrl($url)
{
if (!$url) {
return $url;
}
$url = self::sanitizeUrlScheme($url);
$url = self::sanitizeUrlQuery($url);
return $url;
}
/**
* Make sure the URL has a scheme. Defaults to HTTP if not provided.
*
* @param string $url
*
* @return string
*/
private static function sanitizeUrlScheme($url)
{
$isRelative = strpos($url, '//') === 0;
if ($isRelative) {
return $url;
}
$containSlashes = strpos($url, '://') !== false;
if (!$containSlashes) {
$url = sprintf('://%s', $url);
}
$scheme = parse_url($url, PHP_URL_SCHEME);
// Set default scheme to http if missing
if (empty($scheme)) {
$url = sprintf('http%s', $url);
}
return $url;
}
/**
* @param string $url
*
* @return string
*/
private static function sanitizeUrlQuery($url)
{
$query = parse_url($url, PHP_URL_QUERY);
if (!empty($query)) {
parse_str($query, $parsedQuery);
if ($parsedQuery) {
$encodedQuery = http_build_query($parsedQuery);
$url = str_replace($query, $encodedQuery, $url);
}
}
return $url;
}
/**
* @param string $string
*
* @return string
*/
private static function removeTrailingNonAlphaNumeric($string)
{
// Special handling of closing bracket
if (substr($string, -1) === '}' && preg_match('/^[^{\r\n]*\}.*?$/', $string)) {
$string = substr($string, 0, -1);
return self::removeTrailingNonAlphaNumeric($string);
}
// Ensure only alphanumeric allowed
if (!preg_match("/^.*?[a-zA-Z0-9}\/]$/i", $string)) {
$string = substr($string, 0, -1);
return self::removeTrailingNonAlphaNumeric($string);
}
return $string;
}
/**
* This method return true with special characters in URL, for example https://domain.tld/é.pdf
* filter_var($url, FILTER_VALIDATE_URL) allow only alphanumerics [0-9a-zA-Z], the special characters "$-_.+!*'()," [not including the quotes - ed].
*
* @param string $url
*
* @return bool
*/
public static function isValidUrl($url)
{
$path = parse_url($url, PHP_URL_PATH);
$encodedPath = array_map('urlencode', explode('/', $path));
$url = str_replace($path, implode('/', $encodedPath), $url);
return (bool) filter_var($url, FILTER_VALIDATE_URL);
}
}