Skip to content

Commit 05a962f

Browse files
committed
Translate REGEXP patterns from ICU to PCRE
MySQL uses ICU for regular expressions, and the REGEXP functions passed a pattern to PCRE almost as it was. PCRE reads some of the syntax in another way, so a query could return a wrong result without an error. The functions now use WP_ICU_Regex_Translator. A pattern either gets a correct translation, or it raises an error that names its syntax. This replaces the pattern escaping and the "(*ANY)" line end setting, and fixes these results: - "[^a-z]cat" didn't match "dog\r\ncat". - "[^s]" matched a part of a character on PHP 7.3 to 8.1. - A code point escape, "\w" with marks, and the POSIX classes now work like in ICU. Regular expression errors now carry their MySQL error number, like 3685 for an empty pattern and 3690 for syntax that isn't supported. In the REGEXP suites, "unsupported.json" lists the cases with syntax that isn't supported. They must raise error 3690, so they can't return a wrong result. The known failures of each function shrink to about 60 cases, each with its cause, and they depend on the PCRE version in three places only.
1 parent 99b87ad commit 05a962f

9 files changed

Lines changed: 443 additions & 3945 deletions

‎packages/mysql-on-sqlite/src/sqlite/class-wp-mysql-on-sqlite.php‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1231,6 +1231,13 @@ public function query( string $query, ?int $fetch_mode = null, ...$fetch_mode_ar
12311231
}
12321232
if ( $e instanceof WP_MySQL_On_SQLite_Exception ) {
12331233
$driver_exception = $e;
1234+
} elseif ( $e instanceof WP_ICU_Regex_Exception ) {
1235+
$driver_exception = $this->new_driver_exception(
1236+
sprintf( 'SQLSTATE[HY000]: General error: %d %s', $e->getCode(), $e->getMessage() ),
1237+
'HY000',
1238+
$e,
1239+
array( 'HY000', $e->getCode(), $e->getMessage() )
1240+
);
12341241
} elseif ( $e instanceof PDOException ) {
12351242
$driver_exception = $this->convert_sqlite_exception( $e );
12361243
} else {

‎packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-pdo-user-defined-functions.php‎

Lines changed: 28 additions & 163 deletions
Original file line numberDiff line numberDiff line change
@@ -1232,24 +1232,13 @@ private function regexp_check_match_type( $function_name, $match_type ) {
12321232
}
12331233

12341234
/**
1235-
* Compile a MySQL-style regex into a PCRE pattern string.
1236-
*
1237-
* Translates MySQL match_type flags (c/i/m/n/u) to PCRE modifiers. The u
1238-
* (UTF-8) modifier is applied unless byte-oriented matching is requested.
1239-
* Case-insensitive is the default.
1240-
*
1241-
* MySQL uses ICU, which differs from PCRE in some syntax, like ICU-only escapes
1242-
* and nested sets. The known failures of the REGEXP test suites list these
1243-
* cases. Other known differences:
1244-
*
1245-
* - Text matching ignores case unless the `c` flag is passed, as the column
1246-
* collation isn't known here.
1247-
* - PCRE doesn't match "ß" with "ss" when ignoring case, `$` also matches
1248-
* between CR and LF, and `(?P<name>...)` is valid.
1249-
* - `\G` in a lookbehind doesn't always match where it does in ICU.
1250-
* - Data that isn't valid UTF-8 is matched byte by byte and case-sensitively,
1251-
* like MySQL binary strings. Other binary values match as text, so case
1252-
* sensitivity, and whether positions count bytes, can differ between rows.
1235+
* Compile and cache a MySQL regex. WP_ICU_Regex_Translator documents the supported syntax.
1236+
*
1237+
* The SQL functions also have these limits:
1238+
*
1239+
* - Column collations are unavailable here, so text matching ignores case by default.
1240+
* - Invalid UTF-8 triggers byte matching, which defaults to case-sensitive. Other
1241+
* binary strings can match as text, so positions may count characters or bytes.
12531242
* - SQLite converts numbers to text in its own format, so `20e0` reads "20.0"
12541243
* (MySQL: "20"), and `0.000001` reads "1.0e-06".
12551244
* - `pos`, `occurrence`, and `return_option` use PHP's integer conversion, so
@@ -1260,17 +1249,16 @@ private function regexp_check_match_type( $function_name, $match_type ) {
12601249
* @param string $pattern The MySQL regex pattern.
12611250
* @param string $match_type MySQL match_type flag string.
12621251
* @param bool $binary_mode Whether to match bytes instead of UTF-8 characters.
1263-
* @param bool $without_g Whether "\G" never matches, for a search that doesn't
1264-
* start where the previous match ended.
1252+
* @param bool $without_g Disable \G when the search starts past the previous match or at a nonzero initial offset.
12651253
*
1266-
* @throws Exception If the pattern is empty or invalid.
1254+
* @throws WP_ICU_Regex_Exception If the pattern is empty, invalid, unsupported, or exceeds a translation limit.
12671255
* @return string PCRE-ready pattern with delimiter and modifiers.
12681256
*/
12691257
private function regexp_compile( $pattern, $match_type, $binary_mode = false, $without_g = false ) {
12701258
$match_type = (string) $match_type;
12711259
$pattern = (string) $pattern;
12721260
if ( '' === $pattern ) {
1273-
throw new Exception( 'Illegal argument to a regular expression.' );
1261+
throw new WP_ICU_Regex_Exception( 'Illegal argument to a regular expression.', 3685 );
12741262
}
12751263

12761264
// Without "\G" in the pattern, both versions are the same.
@@ -1280,61 +1268,13 @@ private function regexp_compile( $pattern, $match_type, $binary_mode = false, $w
12801268
return $this->regexp_cache[ $cache_key ];
12811269
}
12821270

1283-
$case_sensitive = false;
1284-
$multiline = false;
1285-
$dotall = false;
1286-
$unix_lines = false;
1287-
$len = strlen( $match_type );
1288-
for ( $i = 0; $i < $len; $i++ ) {
1289-
$flag = $match_type[ $i ];
1290-
if ( 'c' === $flag ) {
1291-
$case_sensitive = true;
1292-
} elseif ( 'i' === $flag ) {
1293-
$case_sensitive = false;
1294-
} elseif ( 'm' === $flag ) {
1295-
$multiline = true;
1296-
} elseif ( 'n' === $flag ) {
1297-
$dotall = true;
1298-
} elseif ( 'u' === $flag ) {
1299-
$unix_lines = true;
1300-
}
1301-
}
1302-
1303-
/*
1304-
* PHP 7 can read an unknown escape as literal text. For "\y", that matches ICU,
1305-
* but "\u0041" matches "u0041", where ICU matches "A". The "X" modifier makes
1306-
* all of them errors, like in PHP 8.
1307-
*/
1308-
$modifiers = $binary_mode ? 'X' : 'uX';
1309-
if ( ! $case_sensitive ) {
1310-
$modifiers .= 'i';
1311-
}
1312-
if ( $multiline ) {
1313-
$modifiers .= 'm';
1314-
}
1315-
if ( $dotall ) {
1316-
$modifiers .= 's';
1317-
}
1318-
1319-
/*
1320-
* In binary data, MySQL ends lines at CR, LF, VT and FF. No PCRE setting
1321-
* matches that. (*ANY) also ends lines at the byte 0x85, which is a part of
1322-
* characters like "ą" (0xC4 0x85). (*ANYCRLF) misses only the rare VT and FF.
1323-
*/
1324-
if ( $unix_lines ) {
1325-
$newline = '(*LF)';
1326-
} elseif ( $binary_mode ) {
1327-
$newline = '(*ANYCRLF)';
1328-
} else {
1329-
$newline = '(*ANY)';
1330-
}
1331-
$compiled = '/' . $newline . $this->regexp_escape_pattern( $pattern, $without_g ) . '/' . $modifiers;
1271+
// The last "c" or "i" sets case sensitivity. MySQL's "n" and "u" mean ICU's dotall and Unix-lines modes.
1272+
$flags = 'c' === substr( rtrim( $match_type, 'mnu' ), -1 ) ? '' : 'i';
1273+
$flags .= strtr( str_replace( array( 'c', 'i' ), '', $match_type ), 'nu', 'sd' );
1274+
$compiled = WP_ICU_Regex_Translator::translate( $pattern, $flags, $without_g, $binary_mode );
13321275

1333-
/*
1334-
* Compile the pattern by matching it against an empty string. Only a compile
1335-
* error emits a PHP warning, so silence it and report a MySQL error instead.
1336-
* A limit error concerns only the empty string, so the pattern is valid.
1337-
*/
1276+
// Probe the compiled pattern before caching it. A match limit on the empty subject
1277+
// can occur even when the pattern compiled successfully.
13381278
set_error_handler( static function () {} );
13391279
try {
13401280
$valid = false !== preg_match( $compiled, '' ) || PREG_INTERNAL_ERROR !== preg_last_error();
@@ -1352,71 +1292,6 @@ private function regexp_compile( $pattern, $match_type, $binary_mode = false, $w
13521292
return $compiled;
13531293
}
13541294

1355-
/**
1356-
* Escape pattern delimiters and NUL bytes that are not already escaped, read
1357-
* "\K" as "K", and, if asked, make "\G" never match.
1358-
*
1359-
* PHP before 8.2 rejects NUL bytes in patterns, so they become "\x00".
1360-
*
1361-
* @param string $pattern The regex pattern.
1362-
* @param bool $without_g Optional. Whether "\G" never matches.
1363-
*
1364-
* @return string Pattern safe to wrap in slash delimiters.
1365-
*/
1366-
private function regexp_escape_pattern( $pattern, $without_g = false ) {
1367-
$special = array(
1368-
'/' => '\\/',
1369-
"\0" => '\\x00',
1370-
);
1371-
1372-
/*
1373-
* ICU reads "\K" as "K". In PCRE, "\K" moves the start of the match, even to
1374-
* before the place where the search started, like in "(?<=\Ka)".
1375-
*/
1376-
$escapes = $special + array( 'K' => 'K' );
1377-
if ( $without_g ) {
1378-
// A position can't be both a word boundary and not one, so "\b\B" never
1379-
// matches. Unlike "(?!)", it has no ")" to end a "(?#...)" comment.
1380-
$escapes['G'] = '\\b\\B';
1381-
}
1382-
1383-
$escaped = '';
1384-
$quoted = false;
1385-
$length = strlen( $pattern );
1386-
for ( $i = 0; $i < $length; ++$i ) {
1387-
$character = $pattern[ $i ];
1388-
if ( $quoted ) {
1389-
if ( '\\' === $character && $i + 1 < $length && 'E' === $pattern[ $i + 1 ] ) {
1390-
$escaped .= '\\E';
1391-
$quoted = false;
1392-
++$i;
1393-
} elseif ( isset( $special[ $character ] ) ) {
1394-
$escaped .= '\\E' . $special[ $character ] . '\\Q';
1395-
} else {
1396-
$escaped .= $character;
1397-
}
1398-
continue;
1399-
}
1400-
if ( '\\' === $character && $i + 1 < $length ) {
1401-
$next = $pattern[ $i + 1 ];
1402-
$escaped .= isset( $escapes[ $next ] ) ? $escapes[ $next ] : $character . $next;
1403-
$quoted = 'Q' === $next;
1404-
++$i;
1405-
} elseif ( isset( $special[ $character ] ) ) {
1406-
$escaped .= $special[ $character ];
1407-
} else {
1408-
$escaped .= $character;
1409-
}
1410-
}
1411-
1412-
// Close quoted text that runs to the end, so that a trailing backslash
1413-
// can't escape the delimiter.
1414-
if ( $quoted ) {
1415-
$escaped .= '\\E';
1416-
}
1417-
return $escaped;
1418-
}
1419-
14201295
/**
14211296
* Check whether a string is valid UTF-8.
14221297
*
@@ -1436,7 +1311,7 @@ private function regexp_is_utf8( $value ) {
14361311
* @param bool $allow_past_end Whether the position may be one past the last character.
14371312
* @param bool $byte_mode Whether every byte is a character.
14381313
*
1439-
* @throws Exception If the position is out of range.
1314+
* @throws WP_ICU_Regex_Exception If the position is out of range.
14401315
* @return int The byte offset.
14411316
*/
14421317
private function regexp_char_to_byte_offset( $subject, $position, $allow_past_end, $byte_mode ) {
@@ -1453,7 +1328,7 @@ private function regexp_char_to_byte_offset( $subject, $position, $allow_past_en
14531328
if ( $allow_past_end && $chars + 1 === $position ) {
14541329
return $length;
14551330
}
1456-
throw new Exception( 'Index out of bounds in regular expression search.' );
1331+
throw new WP_ICU_Regex_Exception( 'Index out of bounds in regular expression search.', 3686 );
14571332
}
14581333

14591334
/**
@@ -1472,7 +1347,7 @@ private function regexp_char_to_byte_offset( $subject, $position, $allow_past_en
14721347
* @param array $match_data The match, with offsets.
14731348
* @param array $group_keys The pattern's group numbers and names, as array keys.
14741349
*
1475-
* @throws Exception On an invalid group reference.
1350+
* @throws WP_ICU_Regex_Exception On an invalid group reference.
14761351
* @return string The expanded replacement.
14771352
*/
14781353
private function regexp_expand_replacement( $replacement, $match_data, $group_keys ) {
@@ -1492,15 +1367,15 @@ static function ( $parts ) use ( $match_data, $group_keys ) {
14921367
return $match_data[ $name ][0] ?? '';
14931368
}
14941369
if ( '' === $digits ) {
1495-
throw new Exception( 'A capture group has an invalid name.' );
1370+
throw new WP_ICU_Regex_Exception( 'A capture group has an invalid name.', 3887 );
14961371
}
14971372
for ( $length = strlen( $digits ); $length > 0; --$length ) {
14981373
$group = (int) substr( $digits, 0, $length );
14991374
if ( isset( $group_keys[ $group ] ) ) {
15001375
return ( $match_data[ $group ][0] ?? '' ) . substr( $digits, $length );
15011376
}
15021377
}
1503-
throw new Exception( 'Index out of bounds in regular expression search.' );
1378+
throw new WP_ICU_Regex_Exception( 'Index out of bounds in regular expression search.', 3686 );
15041379
},
15051380
$replacement
15061381
);
@@ -1555,15 +1430,6 @@ private function regexp_matches( $pattern, $match_type, $byte_mode, $subject, $o
15551430
if ( ! $this->regexp_match( $search, $pattern, $subject, $match, PREG_OFFSET_CAPTURE, $offset ) ) {
15561431
return;
15571432
}
1558-
1559-
/*
1560-
* Only PCRE's "\K" can start a match before the search, and then the next
1561-
* search would find the same match forever. The escaper reads "\K" as "K",
1562-
* but not after a "\Q" in a comment, which it reads as quoted text.
1563-
*/
1564-
if ( $match[0][1] < $offset ) {
1565-
throw new Exception( 'Invalid regular expression: ' . $pattern . '.' );
1566-
}
15671433
yield $match;
15681434

15691435
$offset = $match[0][1] + strlen( $match[0][0] );
@@ -1589,7 +1455,7 @@ private function regexp_matches( $pattern, $match_type, $byte_mode, $subject, $o
15891455
* @param int $flags Optional. The preg_match() flags.
15901456
* @param int $offset Optional. The byte offset to start at.
15911457
*
1592-
* @throws Exception On a preg failure.
1458+
* @throws WP_ICU_Regex_Exception If PCRE cannot complete the match.
15931459
* @return int 1 on match, 0 on no match.
15941460
*/
15951461
private function regexp_match( $compiled, $pattern, $subject, &$matches = null, $flags = 0, $offset = 0 ) {
@@ -1610,14 +1476,11 @@ private function regexp_match( $compiled, $pattern, $subject, &$matches = null,
16101476
}
16111477

16121478
/**
1613-
* Translate a preg_* failure into a caller-friendly exception message.
1614-
*
1615-
* Uses preg_last_error() to distinguish invalid patterns from runtime
1616-
* limit failures.
1479+
* Map a PCRE failure to the corresponding driver error.
16171480
*
16181481
* @param string $pattern The original MySQL regex pattern.
16191482
*
1620-
* @throws Exception Always.
1483+
* @throws WP_ICU_Regex_Exception Always.
16211484
* @return void
16221485
*/
16231486
private function regexp_fail( $pattern ) {
@@ -1627,8 +1490,10 @@ private function regexp_fail( $pattern ) {
16271490
|| PREG_RECURSION_LIMIT_ERROR === $err
16281491
|| PREG_JIT_STACKLIMIT_ERROR === $err
16291492
) {
1630-
throw new Exception( 'Regular expression evaluation exceeded internal limits.' );
1493+
// Report backtracking as a MySQL timeout and recursion or JIT stack exhaustion as a stack overflow.
1494+
$code = PREG_BACKTRACK_LIMIT_ERROR === $err ? 3699 : 3698;
1495+
throw new WP_ICU_Regex_Exception( 'Regular expression evaluation exceeded internal limits.', $code );
16311496
}
1632-
throw new Exception( 'Invalid regular expression: ' . $pattern . '.' );
1497+
throw new WP_ICU_Regex_Exception( 'Invalid regular expression: ' . $pattern . '.', 3688 );
16331498
}
16341499
}

0 commit comments

Comments
 (0)