2323 * - Property names other than general categories, like "Lu", scripts, like "Greek",
2424 * and POSIX classes, like "alpha".
2525 * - An escaped letter without a meaning, which ICU reads as the letter, like "\y".
26+ * - A look-behind that holds more than characters, sets, and "|", like "(?<=a+)". PCRE
27+ * supports the other ones only in its newer versions.
2628 * - A backreference to group 10 or higher, a repeated "^" or "$", and an empty "\Q\E".
2729 *
2830 * Accepted, although ICU rejects it, because MySQL 5.7 and MariaDB accept it, and
4143 * flag "m", "^" never matches between them.
4244 * - "\X" uses PCRE's rules for character clusters.
4345 * - Before PCRE 10.40, "[:alpha:]" and "[:alnum:]" miss combining vowel signs.
44- * - PCRE compiles a backreference in a look-behind, and a "\k<name>" before its group.
45- * - PCRE's own limits apply: no look-behind of variable length before PCRE 10.43, a
46- * group name of up to 32 characters before PCRE 10.44, and a "{n}" of up to 65535.
46+ * - PCRE compiles a "\k<name>" before its group.
47+ * - PCRE's own limits apply: a group name of up to 32 characters before PCRE 10.44, and
48+ * a "{n}" of up to 65535.
4749 */
4850class WP_ICU_Regex_Translator {
49- // The characters that end a line in ICU.
50- private const LINE_ENDS = '\n\x0B\f\r\x85\x{2028}\x{2029} ' ;
51+ // The characters that end a line in ICU, and the ones among them that are bytes.
52+ private const BYTE_LINE_ENDS = '\n\x0B\f\r ' ;
53+ private const LINE_ENDS = self ::BYTE_LINE_ENDS . '\x85\x{2028}\x{2029} ' ;
5154
5255 // ICU's word characters. PCRE's "\w" misses marks, and it matches numbers like "²".
5356 private const WORD = '\p{L}\p{M}\p{Nd}\p{Nl}\p{Pc}\x{200C}\x{200D}\x{24B6}-\x{24E9}\x{1F130}-\x{1F149}\x{1F150}-\x{1F169}\x{1F170}-\x{1F189} ' ;
@@ -109,7 +112,7 @@ class WP_ICU_Regex_Translator {
109112 /*
110113 * The tokens of a pattern. An item may have a quantifier, and a position may not.
111114 * TOKEN captures the quantifier (1), the flags that an inline flag group turns on (2)
112- * and off (3) with its end (4), and a literal brace (5).
115+ * and off (3) with its end (4), and text that is no supported token (5).
113116 */
114117 private const QUOTE = '\\\\Q(?! \\\\E)(?:[^ \\\\]++| \\\\(?!E))*+ ' ;
115118 private const ESCAPE = '\\\\(?:[pP]\{[^}]*\}|x\{[0-9A-Fa-f]{1,6}\}|x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}|0[0-3][0-7]{2}|0[0-7]{1,2}|c[\x00-\x7F]|k<[A-Za-z][A-Za-z0-9]*>|[1-9](?!\d)|[^Q0-9]) ' ;
@@ -118,13 +121,25 @@ class WP_ICU_Regex_Translator {
118121 private const SET = '(?!\[:[^:]*:\])\[\^?+\]?+(?: ' . self ::SET_ITEM . ')*+\] ' ;
119122 private const INTERVAL = '\{\d+(?:,\d*)?\} ' ;
120123 private const QUANTIFIER = '((?:[*+?]| ' . self ::INTERVAL . ')[+?]?)? ' ;
121- private const GROUP = '\((?:\?(?:[:=!>]|<[=!]|<[A-Za-z][A-Za-z0-9]*>|#[^) \\\\]*\)|(?=[imsdu-])([imsdu]*)-?([imsdu]*)([:)])))? ' ;
122- private const BRACE = '(\}|(?! ' . self ::INTERVAL . ')\{) ' ;
123- private const TOKEN = '/(?:[^ \\\\\[(){}|^$.*+?\/\x00]++| ' . self ::QUOTE . '(?: \\\\E|\z)| ' . self ::ESCAPE . '| ' . self ::POSIX . '| ' . self ::SET . '|[.)\/\x00]) ' . self ::QUANTIFIER . '| ' . self ::GROUP . '| ' . self ::BRACE . '|\[\[:[<>]:\]\]|[\s\S]/ ' ;
124+ private const GROUP = '\((?:(?!\?)|\?(?:[:=!>]|<[A-Za-z][A-Za-z0-9]*>|#[^) \\\\]*\)|(?=[imsdu-])([imsdu]*)-?([imsdu]*)([:)]))) ' ;
125+ private const BRACE = '\}|(?! ' . self ::INTERVAL . ')\{ ' ;
126+
127+ /*
128+ * A look-behind is one token. It can hold single characters, sets, and "|" only, as
129+ * every PCRE version supports that, where older ones reject other look-behinds.
130+ */
131+ private const LOOK_BEHIND = '\(\?<[=!](?: ' . self ::SET . '|(?! \\\\[AbBGkRXzZ1-9]) ' . self ::ESCAPE . '|[^ \\\\\[(){}^$.*+?]++|\.)*+\) ' ;
132+
133+ // Text that is no supported token: the start of an escape or a group, or a character.
134+ private const OTHER = '\\\\(?:Q \\\\E|\d+)?|\(\?(?:<[=!]|\w+|[^)])?|[\s\S] ' ;
135+ private const TOKEN = '/(?:[^ \\\\\[(){}|^$.*+?\/\x00]++| ' . self ::QUOTE . '(?: \\\\E|\z)| ' . self ::ESCAPE . '| ' . self ::POSIX . '| ' . self ::SET . '|[.)\/\x00]) ' . self ::QUANTIFIER . '| ' . self ::LOOK_BEHIND . '| ' . self ::GROUP . '| ' . self ::BRACE . '|\[\[:[<>]:\]\]|[|^$]|( ' . self ::OTHER . ')/ ' ;
124136
125137 // PCRE can't compile a longer pattern.
126138 private const MAX_LENGTH = 65535 ;
127139
140+ // The MySQL error for a regular expression feature that isn't implemented.
141+ private const UNSUPPORTED = 3690 ;
142+
128143 // The flags in effect, as ICU's flag letters.
129144 private $ flags ;
130145
@@ -134,28 +149,34 @@ class WP_ICU_Regex_Translator {
134149 // Whether "\G" never matches.
135150 private $ without_g ;
136151
152+ // Whether the pattern matches bytes instead of UTF-8 characters.
153+ private $ bytes ;
154+
137155 /**
138156 * Translate an ICU regular expression to a PCRE pattern.
139157 *
140158 * @param string $pattern The ICU regular expression.
141159 * @param string $flags ICU's flag letters: "i", "m", "s", and "d" (UNIX_LINES).
142160 * @param bool $without_g Whether "\G" never matches, for a search that doesn't start
143161 * where the previous match ended.
162+ * @param bool $bytes Whether to match bytes instead of UTF-8 characters. Then
163+ * classes, "\b", and line ends cover ASCII, like in PCRE.
144164 *
145- * @throws DomainException If the pattern uses syntax that isn't supported.
165+ * @throws WP_ICU_Regex_Exception If the pattern uses syntax that isn't supported.
146166 * @return string A pattern for the preg_*() functions. It can still fail to compile.
147167 */
148- public static function translate ( $ pattern , $ flags = '' , $ without_g = false ) {
168+ public static function translate ( $ pattern , $ flags = '' , $ without_g = false , $ bytes = false ) {
149169 if ( strlen ( $ pattern ) > self ::MAX_LENGTH || strspn ( $ flags , 'imsd ' ) !== strlen ( $ flags ) ) {
150- throw new DomainException ( 'Unsupported regular expression length or flags. ' );
170+ throw new WP_ICU_Regex_Exception ( 'Unsupported regular expression length or flags. ' , self :: UNSUPPORTED );
151171 }
152172 $ translator = new self ();
153173 $ translator ->flags = $ flags ;
154174 $ translator ->without_g = $ without_g ;
175+ $ translator ->bytes = $ bytes ;
155176 $ translated = self ::replace ( self ::TOKEN , array ( $ translator , 'translate_token ' ), $ pattern );
156177
157178 // "X" stops PHP 7.3 and 7.4 from reading an unknown property as literal text.
158- return '/ ' . $ translated . ' / uX ' . ( false !== strpos ( $ flags , 'i ' ) ? 'i ' : '' );
179+ return '/ ' . $ translated . ( $ bytes ? ' /X ' : ' / uX ' ) . ( false !== strpos ( $ flags , 'i ' ) ? 'i ' : '' );
159180 }
160181
161182 /**
@@ -168,26 +189,26 @@ private function translate_token( $parts ) {
168189 $ token = $ parts [0 ];
169190 $ quantifier = $ parts [1 ] ?? '' ;
170191 $ item = substr ( $ token , 0 , strlen ( $ token ) - strlen ( $ quantifier ) );
192+ if ( isset ( $ parts [5 ] ) ) {
193+ throw new WP_ICU_Regex_Exception ( "Unsupported regular expression syntax: $ token " , self ::UNSUPPORTED );
194+ }
171195
172196 switch ( $ item [0 ] ) {
173197 case '\\' :
174198 // A position, like "\b", can't be repeated.
175- if ( isset ( $ item [ 1 ] ) && ( '' === $ quantifier || false === strpos ( 'AbBGzZ ' , $ item [1 ] ) ) ) {
199+ if ( '' === $ quantifier || false === strpos ( 'AbBGzZ ' , $ item [1 ] ) ) {
176200 return $ this ->translate_escape ( substr ( $ item , 1 ), false ) . $ quantifier ;
177201 }
178202 break ;
179203 case '[ ' :
180204 if ( isset ( self ::ESCAPES [ $ item ] ) ) {
181- return self ::ESCAPES [ $ item ];
205+ return $ this -> bytes ? $ item : self ::ESCAPES [ $ item ];
182206 }
183207 // Like in ICU, "[:name:]" is a property, also outside of a set.
184208 if ( preg_match ( '/^\[:[^:]*:\]$/ ' , $ item ) ) {
185209 return $ this ->translate_property ( trim ( $ item , '[:^] ' ), '^ ' === $ item [2 ], false ) . $ quantifier ;
186210 }
187- if ( isset ( $ item [1 ] ) ) {
188- return $ this ->translate_set ( $ item ) . $ quantifier ;
189- }
190- break ;
211+ return $ this ->translate_set ( $ item ) . $ quantifier ;
191212 case '( ' :
192213 if ( '' !== ( $ parts [4 ] ?? '' ) ) {
193214 // Inline flags. PCRE gets the case flag, and the others change the translation.
@@ -198,12 +219,16 @@ private function translate_token( $parts ) {
198219 }
199220 return '(? ' . ( false !== strpos ( $ this ->flags , 'i ' ) ? 'i ' : '-i ' ) . $ parts [4 ];
200221 }
201- if ( '(?# ' === substr ( $ item , 0 , 3 ) ) {
202- return '(?#) ' ;
222+ if ( ') ' === substr ( $ item , -1 ) ) {
223+ if ( '# ' === $ item [2 ] ) {
224+ return '(?#) ' ;
225+ }
226+ // A look-behind has no groups, so its tokens are translated in place.
227+ return substr ( $ item , 0 , 4 ) . self ::replace ( self ::TOKEN , array ( $ this , 'translate_token ' ), substr ( $ item , 4 , -1 ) ) . ') ' ;
203228 }
204- // A look-around can't be repeated.
205- $ is_look_around = false !== strpbrk ( $ item , '=! ' );
206- $ this ->groups [] = array ( $ this ->flags , ! $ is_look_around );
229+ // A look-ahead can't be repeated.
230+ $ is_look_ahead = false !== strpbrk ( $ item , '=! ' );
231+ $ this ->groups [] = array ( $ this ->flags , ! $ is_look_ahead );
207232 return $ item ;
208233 case ') ' :
209234 if ( $ this ->groups ) {
@@ -214,31 +239,23 @@ private function translate_token( $parts ) {
214239 }
215240 break ;
216241 case '. ' :
217- return self ::LINES [ $ this ->with_flags ( '. ' , 'sd ' ) ] . $ quantifier ;
242+ return $ this -> with_line_ends ( self ::LINES [ $ this ->with_flags ( '. ' , 'sd ' ) ] ) . $ quantifier ;
218243 case '^ ' :
219244 case '$ ' :
220- return self ::LINES [ $ this ->with_flags ( $ item , 'md ' ) ];
245+ return $ this -> with_line_ends ( self ::LINES [ $ this ->with_flags ( $ item , 'md ' ) ] ) ;
221246 case '{ ' :
222247 case '} ' :
223- // An interval with nothing to repeat is an error.
224- if ( '' !== ( $ parts [5 ] ?? '' ) ) {
225- return '\\' . $ item ;
226- }
227- break ;
248+ return '\\' . $ item ;
228249 case '/ ' :
229250 return '\/ ' . $ quantifier ;
230251 case "\0" :
231252 return '\x00 ' . $ quantifier ;
232253 case '| ' :
233254 return '| ' ;
234- case '* ' :
235- case '+ ' :
236- case '? ' :
237- break ;
238255 default :
239256 return $ token ;
240257 }
241- throw new DomainException ( "Unsupported regular expression syntax: $ token " );
258+ throw new WP_ICU_Regex_Exception ( "Unsupported regular expression syntax: $ token " , self :: UNSUPPORTED );
242259 }
243260
244261 /**
@@ -270,25 +287,34 @@ private function translate_escape( $escape, $in_set ) {
270287 return sprintf ( '\x{%X} ' , $ code );
271288 }
272289
290+ // PHP before 8.2 rejects a NUL byte in a pattern.
291+ if ( "\0" === $ letter ) {
292+ return '\x00 ' ;
293+ }
294+
273295 // A character that is no ASCII letter or digit is literal.
274296 if ( ! preg_match ( '/^[A-Za-z0-9]/ ' , $ letter ) || false !== strpos ( 'aefnrt ' , $ letter ) ) {
275297 return '\\' . $ letter ;
276298 }
277- if ( isset ( self ::CLASSES [ strtolower ( $ letter ) ] ) ) {
278- return $ this ->class_body ( self ::CLASSES [ strtolower ( $ letter ) ], strtolower ( $ letter ) !== $ letter , $ in_set );
299+ $ lower = strtolower ( $ letter );
300+ if ( isset ( self ::CLASSES [ $ lower ] ) ) {
301+ return $ this ->class_body ( $ this ->bytes ? '\\' . $ lower : self ::CLASSES [ $ lower ], $ lower !== $ letter , $ in_set );
279302 }
280303 if ( ! $ in_set ) {
281304 if ( 'G ' === $ letter && $ this ->without_g ) {
282305 return '(?!) ' ;
283306 }
307+ if ( 'b ' === $ lower && $ this ->bytes ) {
308+ return '\\' . $ letter ;
309+ }
284310 if ( isset ( self ::ESCAPES [ $ letter ] ) ) {
285- return self ::ESCAPES [ $ letter ];
311+ return $ this -> with_line_ends ( self ::ESCAPES [ $ letter ] ) ;
286312 }
287313 if ( false !== strpos ( '123456789 ' , $ letter ) ) {
288314 return '\g{ ' . $ letter . '} ' ;
289315 }
290316 }
291- throw new DomainException ( "Unsupported regular expression syntax: \\$ escape " );
317+ throw new WP_ICU_Regex_Exception ( "Unsupported regular expression syntax: \\$ escape " , self :: UNSUPPORTED );
292318 }
293319
294320 /**
@@ -326,7 +352,7 @@ function ( $parts ) use ( &$previous ) {
326352 $ is_ends_class = '- ' === $ item && isset ( $ next [1 ] ) && ( 'character ' === $ last || '& ' === $ last );
327353 $ is_after_amp = '- ' === $ item && null === $ next && '& ' === $ last ;
328354 if ( $ is_operator || $ is_ends_class || $ is_after_amp ) {
329- throw new DomainException ( "Unsupported regular expression syntax: $ item in a set " );
355+ throw new WP_ICU_Regex_Exception ( "Unsupported regular expression syntax: $ item in a set " , self :: UNSUPPORTED );
330356 }
331357 return '\\' . $ item ;
332358 }
@@ -374,7 +400,9 @@ function ( $parts ) use ( &$previous ) {
374400 */
375401 private function translate_property ( $ name , $ negated , $ in_set ) {
376402 $ key = strtolower ( $ name );
377- if ( false !== strpos ( $ this ->flags , 'i ' ) && in_array ( $ key , array ( 'lu ' , 'll ' , 'lt ' , 'upper ' , 'lower ' ), true ) ) {
403+ if ( $ this ->bytes && isset ( $ key [2 ], self ::CLASSES [ $ key ] ) ) {
404+ $ body = '[: ' . $ key . ':] ' ;
405+ } elseif ( false !== strpos ( $ this ->flags , 'i ' ) && in_array ( $ key , array ( 'lu ' , 'll ' , 'lt ' , 'upper ' , 'lower ' ), true ) ) {
378406 // When ignoring case, ICU matches the other case too. PCRE does so from 10.45.
379407 $ body = '\p{L&} ' ;
380408 } elseif ( isset ( $ key [2 ], self ::CLASSES [ $ key ] ) ) {
@@ -387,7 +415,7 @@ private function translate_property( $name, $negated, $in_set ) {
387415 // bare name as Script_Extensions.
388416 $ body = '\p{ ' . ( self ::has_pcre_10_40 () ? 'sc: ' : '' ) . $ name . '} ' ;
389417 } else {
390- throw new DomainException ( "Unsupported regular expression property: $ name " );
418+ throw new WP_ICU_Regex_Exception ( "Unsupported regular expression property: $ name " , self :: UNSUPPORTED );
391419 }
392420 return $ this ->class_body ( $ body , $ negated , $ in_set );
393421 }
@@ -411,10 +439,14 @@ private function class_body( $body, $negated, $in_set ) {
411439 return $ body ;
412440 }
413441
414- // In a set, PCRE can only negate a single item, like "\d" or "\p{L}". "\p{Alphabetic}"
415- // is a single item only from PCRE 10.40, so it is left out for every version.
416- if ( ! preg_match ( '/^ \\\\(?:[dhsv]|p\{(?!Alphabetic)[^}]*\})$/ ' , $ body ) ) {
417- throw new DomainException ( 'Unsupported regular expression syntax: a negated class in a set ' );
442+ // In a set, PCRE can only negate a single item, like "\d", "\p{L}", or "[:alpha:]".
443+ // "\p{Alphabetic}" is a single item only from PCRE 10.40, so it is left out for
444+ // every version.
445+ if ( '[ ' === $ body [0 ] ) {
446+ return '[:^ ' . substr ( $ body , 2 );
447+ }
448+ if ( ! preg_match ( '/^ \\\\(?:[dhsvw]|p\{(?!Alphabetic)[^}]*\})$/ ' , $ body ) ) {
449+ throw new WP_ICU_Regex_Exception ( 'Unsupported regular expression syntax: a negated class in a set ' , self ::UNSUPPORTED );
418450 }
419451 $ body [1 ] = strtoupper ( $ body [1 ] );
420452 return $ body ;
@@ -431,6 +463,16 @@ private function with_flags( $character, $flags ) {
431463 return $ character . implode ( '' , array_intersect ( str_split ( $ flags ), str_split ( $ this ->flags ) ) );
432464 }
433465
466+ /**
467+ * Limit the line ends of a translation to bytes, when matching bytes.
468+ *
469+ * @param string $fragment The PCRE text of ".", "^", "$", or an escape.
470+ * @return string The PCRE text for the current mode.
471+ */
472+ private function with_line_ends ( $ fragment ) {
473+ return $ this ->bytes ? str_replace ( self ::LINE_ENDS , self ::BYTE_LINE_ENDS , $ fragment ) : $ fragment ;
474+ }
475+
434476 /**
435477 * Replace the tokens of a text, and fail when the regex hits a PCRE limit.
436478 *
@@ -444,7 +486,7 @@ private function with_flags( $character, $flags ) {
444486 private static function replace ( $ regex , $ callback , $ text ) {
445487 $ replaced = preg_replace_callback ( $ regex , $ callback , $ text );
446488 if ( null === $ replaced ) {
447- throw new DomainException ( 'Unsupported regular expression: it is too complex. ' );
489+ throw new WP_ICU_Regex_Exception ( 'Unsupported regular expression: it is too complex. ' , self :: UNSUPPORTED );
448490 }
449491 return $ replaced ;
450492 }
0 commit comments