MediaWiki master
LinkFilter.php
Go to the documentation of this file.
1<?php
22
27use StringUtils;
28use Wikimedia\IPUtils;
32
54 public static function matchEntry( Content $content, $filterEntry, $protocol = 'http://' ) {
55 if ( !( $content instanceof TextContent ) ) {
56 // TODO: handle other types of content too.
57 // Maybe create ContentHandler::matchFilter( LinkFilter ).
58 // Think about a common base class for LinkFilter and MagicWord.
59 return 0;
60 }
61
62 $text = $content->getText();
63 $regex = self::makeRegex( $filterEntry, $protocol );
64 return preg_match( $regex, $text );
65 }
66
76 private static function makeRegex( $filterEntry, $protocol ) {
77 $regex = '!' . preg_quote( $protocol, '!' );
78 if ( substr( $filterEntry, 0, 2 ) == '*.' ) {
79 $regex .= '(?:[A-Za-z0-9.-]+\.|)';
80 $filterEntry = substr( $filterEntry, 2 );
81 }
82 $regex .= preg_quote( $filterEntry, '!' ) . '!Si';
83 return $regex;
84 }
85
93 private static function indexifyHost( $host, $reverse = true ) {
94 // Canonicalize.
95 $host = rawurldecode( $host );
96 if ( $host !== '' ) {
97 $tmp = idn_to_utf8( $host );
98 if ( $tmp !== false ) {
99 $host = $tmp;
100 }
101 }
102 $okChars = 'a-zA-Z0-9\\-._~!$&\'()*+,;=';
103 if ( StringUtils::isUtf8( $host ) ) {
104 // Save a little space by not percent-encoding valid UTF-8 bytes
105 $okChars .= '\x80-\xf4';
106 }
107 $host = preg_replace_callback(
108 '<[^' . $okChars . ']+>',
109 static fn ( $m ) => rawurlencode( $m[0] ),
110 strtolower( $host )
111 );
112
113 // IPv6? RFC 3986 syntax.
114 if ( preg_match( '/^\[([0-9a-f:*]+)\]$/', rawurldecode( $host ), $m ) ) {
115 $ip = $m[1];
116 if ( IPUtils::isValid( $ip ) ) {
117 if ( !$reverse ) {
118 return '[' . IPUtils::sanitizeIP( $ip ) . ']';
119 }
120 return 'V6.' . implode( '.', explode( ':', IPUtils::sanitizeIP( $ip ) ) ) . '.';
121 }
122 if ( substr( $ip, -2 ) === ':*' ) {
123 $cutIp = substr( $ip, 0, -2 );
124 if ( IPUtils::isValid( "{$cutIp}::" ) ) {
125 // Wildcard IP doesn't contain "::", so multiple parts can be wild
126 $ct = count( explode( ':', $ip ) ) - 1;
127 if ( !$reverse ) {
128 return '[' . IPUtils::sanitizeIP( "{$cutIp}::" ) . ']';
129 }
130 return 'V6.' .
131 implode( '.', array_slice( explode( ':', IPUtils::sanitizeIP( "{$cutIp}::" ) ), 0, $ct ) ) .
132 '.*.';
133 }
134 if ( IPUtils::isValid( "{$cutIp}:1" ) ) {
135 // Wildcard IP does contain "::", so only the last part is wild
136 if ( !$reverse ) {
137 return '[' . IPUtils::sanitizeIP( "{$cutIp}:1" ) . ']';
138 }
139 return 'V6.' .
140 substr( implode( '.', explode( ':', IPUtils::sanitizeIP( "{$cutIp}:1" ) ) ), 0, -1 ) .
141 '*.';
142 }
143 }
144 }
145
146 // Regularize explicit specification of the DNS root.
147 // Browsers seem to do this for IPv4 literals too.
148 if ( substr( $host, -1 ) === '.' ) {
149 $host = substr( $host, 0, -1 );
150 }
151
152 // IPv4?
153 $b = '(?:0*25[0-5]|0*2[0-4][0-9]|0*1[0-9][0-9]|0*[0-9]?[0-9])';
154 if ( preg_match( "/^(?:{$b}\.){3}{$b}$|^(?:{$b}\.){1,3}\*$/", $host ) ) {
155 if ( !$reverse ) {
156 return $host;
157 }
158 return 'V4.' . implode( '.', array_map( static function ( $v ) {
159 return $v === '*' ? $v : (int)$v;
160 }, explode( '.', $host ) ) ) . '.';
161 }
162
163 // Must be a host name.
164 if ( $reverse ) {
165 return implode( '.', array_reverse( explode( '.', $host ) ) ) . '.';
166 } else {
167 return $host;
168 }
169 }
170
180 public static function makeIndexes( $url, $reverseDomain = true ) {
181 // NOTE: refreshExternallinksIndex.php assumes that only protocol-relative URLs return more
182 // than one index, and that the indexes for protocol-relative URLs only vary in the "http://"
183 // versus "https://" prefix. If you change that, you'll likely need to update
184 // refreshExternallinksIndex.php accordingly.
185
186 $bits = MediaWikiServices::getInstance()->getUrlUtils()->parse( $url );
187 if ( !$bits ) {
188 return [];
189 }
190
191 // URI RFC identifies the email/server part of mailto or news protocol as 'path',
192 // while we want to match the email's domain or news server the same way we are
193 // matching hosts for other URLs.
194 if ( in_array( $bits['scheme'], [ 'mailto', 'news' ] ) ) {
195 // (T347574) Only set host if it's not already set (if // is used)
196 if ( array_key_exists( 'path', $bits ) ) {
197 $bits['host'] = $bits['path'];
198 }
199 $bits['path'] = '';
200 }
201
202 // Reverse the labels in the hostname, convert to lower case, unless it's an IP.
203 // For emails turn it into "domain.reversed@localpart"
204 if ( $bits['scheme'] == 'mailto' ) {
205 $mailparts = explode( '@', $bits['host'], 2 );
206 if ( count( $mailparts ) === 2 ) {
207 $domainpart = self::indexifyHost( $mailparts[1], $reverseDomain );
208 } else {
209 // No @, assume it's a local part with no domain
210 $domainpart = '';
211 }
212 if ( $reverseDomain ) {
213 $bits['host'] = $domainpart . '@' . $mailparts[0];
214 } else {
215 $bits['host'] = $mailparts[0] . '@' . $domainpart;
216 }
217 } else {
218 $bits['host'] = self::indexifyHost( $bits['host'], $reverseDomain );
219 }
220
221 // Reconstruct the pseudo-URL
222 $index = $bits['scheme'] . $bits['delimiter'] . $bits['host'];
223 // Leave out user and password. Add the port, path, query and fragment
224 if ( isset( $bits['port'] ) ) {
225 $index .= ':' . $bits['port'];
226 }
227 $index2 = $bits['path'] ?? '/';
228 if ( isset( $bits['query'] ) ) {
229 $index2 .= '?' . $bits['query'];
230 }
231 if ( isset( $bits['fragment'] ) ) {
232 $index2 .= '#' . $bits['fragment'];
233 }
234
235 if ( $bits['scheme'] == '' ) {
236 return [ [ "https:$index", $index2 ] ];
237 } else {
238 return [ [ $index, $index2 ] ];
239 }
240 }
241
248 public static function getIndexedUrlsNonReversed( $urls ) {
249 $newLinks = [];
250 foreach ( $urls as $url ) {
251 $indexes = self::makeIndexes( $url, false );
252 if ( !$indexes ) {
253 continue;
254 }
255 foreach ( $indexes as $index ) {
256 $newLinks[] = $index[0] . $index[1];
257 }
258 }
259 return $newLinks;
260 }
261
262 public static function reverseIndexes( $domainIndex ) {
263 $bits = MediaWikiServices::getInstance()->getUrlUtils()->parse( $domainIndex );
264 if ( !$bits ) {
265 return '';
266 }
267
268 // Reverse the labels in the hostname, convert to lower case, unless it's an IP.
269 // For emails turn it into "domain.reversed@localpart"
270 if ( $bits['scheme'] == 'mailto' ) {
271 $mailparts = explode( '@', $bits['path'], 2 );
272 if ( count( $mailparts ) === 2 ) {
273 $domainpart = rtrim( self::reverseDomain( $mailparts[0] ), '.' );
274 } else {
275 // No @, assume it's a local part with no domain
276 $domainpart = '';
277 }
278 $bits['host'] = $mailparts[1] . '@' . $domainpart;
279 } else {
280 $bits['host'] = rtrim( self::reverseDomain( $bits['host'] ), '.' );
281 }
282
283 $index = $bits['scheme'] . $bits['delimiter'] . $bits['host'];
284 if ( isset( $bits['port'] ) && $bits['port'] ) {
285 $index .= ':' . $bits['port'];
286 }
287 return $index;
288 }
289
290 private static function reverseDomain( $domain ) {
291 if ( substr( $domain, 0, 3 ) === 'V6.' ) {
292 $ipv6 = str_replace( '.', ':', trim( substr( $domain, 3 ), '.' ) );
293 if ( IPUtils::isValid( $ipv6 ) ) {
294 return '[' . $ipv6 . ']';
295 }
296 } elseif ( substr( $domain, 0, 3 ) === 'V4.' ) {
297 $ipv4 = trim( substr( $domain, 3 ), '.' );
298 if ( IPUtils::isValid( $ipv4 ) ) {
299 return $ipv4;
300 }
301 }
302 return self::indexifyHost( $domain );
303 }
304
332 public static function getQueryConditions( $filterEntry, array $options = [] ) {
333 $options += [
334 'protocol' => [ 'http://', 'https://' ],
335 'oneWildcard' => false,
336 'db' => null,
337 ];
338 $domainGaps = MediaWikiServices::getInstance()->getMainConfig()->get(
340 );
341
342 if ( is_string( $options['protocol'] ) ) {
343 $options['protocol'] = [ $options['protocol'] ];
344 } elseif ( $options['protocol'] === null ) {
345 $options['protocol'] = [ 'http://', 'https://' ];
346 }
347
348 $domainConditions = [];
349 $db = $options['db'] ?: MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
350 foreach ( $options['protocol'] as $protocol ) {
351 $like = self::makeLikeArray( $filterEntry, $protocol );
352 if ( $like === false ) {
353 continue;
354 }
355 [ $likeDomain, $likePath ] = $like;
356 $trimmedlikeDomain = self::keepOneWildcard( $likeDomain );
357 if ( $trimmedlikeDomain[count( $trimmedlikeDomain ) - 1] instanceof LikeMatch ) {
358 array_pop( $trimmedlikeDomain );
359 }
360 $index1 = implode( '', $trimmedlikeDomain );
361 if ( $options['oneWildcard'] && $likePath[0] != '/' ) {
362 $thisDomainExpr = $db->expr( 'el_to_domain_index', '=', $index1 );
363 } else {
364 $thisDomainExpr = $db->expr(
365 'el_to_domain_index',
366 IExpression::LIKE,
367 new LikeValue( $index1, $db->anyString() )
368 );
369 }
370 foreach ( $domainGaps[$index1] ?? [] as $from => $to ) {
371 $thisDomainExpr = $thisDomainExpr->andExpr( $db->expr( 'el_id', '<', $from )->or( 'el_id', '>', $to ) );
372 }
373 $domainConditions[] = $thisDomainExpr;
374 }
375 if ( !$domainConditions ) {
376 return false;
377 }
378 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable
379 $trimmedlikePath = self::keepOneWildcard( $likePath );
380 if ( $trimmedlikePath[count( $trimmedlikePath ) - 1] instanceof LikeMatch ) {
381 array_pop( $trimmedlikePath );
382 }
383 $index2 = implode( '', $trimmedlikePath );
384
385 return [
386 $db->orExpr( $domainConditions ),
387 $db->expr( 'el_to_path', IExpression::LIKE, new LikeValue( $index2, $db->anyString() ) ),
388 ];
389 }
390
391 public static function getProtocolPrefix( $protocol ) {
392 // Find the right prefix
393 $urlProtocols = MediaWikiServices::getInstance()->getMainConfig()
395 if ( $protocol && !in_array( $protocol, $urlProtocols ) ) {
396 foreach ( $urlProtocols as $p ) {
397 if ( str_starts_with( $p, $protocol ) ) {
398 $protocol = $p;
399 break;
400 }
401 }
402
403 return $protocol;
404 } else {
405 return null;
406 }
407 }
408
409 public static function prepareProtocols() {
410 $urlProtocols = MediaWikiServices::getInstance()->getMainConfig()
412 $protocols = [ '' ];
413 foreach ( $urlProtocols as $p ) {
414 if ( $p !== '//' ) {
415 $protocols[] = substr( $p, 0, strpos( $p, ':' ) );
416 }
417 }
418
419 return $protocols;
420 }
421
434 public static function makeLikeArray( $filterEntry, $protocol = 'http://' ) {
435 $services = MediaWikiServices::getInstance();
436 $db = $services->getConnectionProvider()->getReplicaDatabase();
437 $likeDomain = [];
438 $likePath = [];
439
440 $target = $protocol . $filterEntry;
441 $bits = $services->getUrlUtils()->parse( $target );
442 if ( !$bits ) {
443 return false;
444 }
445
446 // URI RFC identifies the email/server part of mailto or news protocol as 'path',
447 // while we want to match the email's domain or news server the same way we are
448 // matching hosts for other URLs.
449 if ( in_array( $bits['scheme'], [ 'mailto', 'news' ] ) ) {
450 // (T364743) Only set host if it's not already set (if // is used)
451 if ( array_key_exists( 'path', $bits ) ) {
452 $bits['host'] = $bits['path'];
453 }
454 $bits['path'] = '';
455 }
456
457 $subdomains = false;
458 if ( $bits['scheme'] === 'mailto' && strpos( $bits['host'], '@' ) ) {
459 // Email address with domain and non-empty local part
460 $mailparts = explode( '@', $bits['host'], 2 );
461 $domainpart = self::indexifyHost( $mailparts[1] );
462 if ( $mailparts[0] === '*' ) {
463 $subdomains = true;
464 $bits['host'] = $domainpart . '@';
465 } else {
466 $bits['host'] = $domainpart . '@' . $mailparts[0];
467 }
468 } else {
469 // Non-email, or email with only a domain part.
470 $bits['host'] = self::indexifyHost( $bits['host'] );
471 if ( substr( $bits['host'], -3 ) === '.*.' ) {
472 $subdomains = true;
473 $bits['host'] = substr( $bits['host'], 0, -2 );
474 }
475 }
476
477 $likeDomain[] = $bits['scheme'] . $bits['delimiter'] . $bits['host'];
478
479 if ( $subdomains ) {
480 $likeDomain[] = $db->anyString();
481 }
482
483 if ( isset( $bits['port'] ) ) {
484 $likeDomain[] = ':' . $bits['port'];
485 }
486 if ( isset( $bits['path'] ) ) {
487 $likePath[] = $bits['path'];
488 } else {
489 $likePath[] = '/';
490 }
491 if ( isset( $bits['query'] ) ) {
492 $likePath[] = '?' . $bits['query'];
493 }
494 if ( isset( $bits['fragment'] ) ) {
495 $likePath[] = '#' . $bits['fragment'];
496 }
497 $likePath[] = $db->anyString();
498
499 // Check for stray asterisks: asterisk only allowed at the start of the domain
500 foreach ( array_merge( $likeDomain, $likePath ) as $likepart ) {
501 if ( !( $likepart instanceof LikeMatch ) && strpos( $likepart, '*' ) !== false ) {
502 return false;
503 }
504 }
505
506 return [ $likeDomain, $likePath ];
507 }
508
517 public static function keepOneWildcard( $arr ) {
518 if ( !is_array( $arr ) ) {
519 return $arr;
520 }
521
522 foreach ( $arr as $key => $value ) {
523 if ( $value instanceof LikeMatch ) {
524 return array_slice( $arr, 0, $key + 1 );
525 }
526 }
527
528 return $arr;
529 }
530}
531
533class_alias( LinkFilter::class, 'LinkFilter' );
Content object implementation for representing flat text.
A class containing constants representing the names of configuration variables.
const ExternalLinksDomainGaps
Name constant for the ExternalLinksDomainGaps setting, for use with Config::get()
const UrlProtocols
Name constant for the UrlProtocols setting, for use with Config::get()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
A collection of static methods to play with strings.
Used by Database::buildLike() to represent characters that have special meaning in SQL LIKE clauses a...
Definition LikeMatch.php:10
Content of like value.
Definition LikeValue.php:14
Base interface for representing page content.
Definition Content.php:39