4 * See docs/magicword.txt.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
25 use MediaWiki\Logger\LoggerFactory
;
26 use MediaWiki\MediaWikiServices
;
29 * Class for handling an array of magic words
32 class MagicWordArray
{
36 /** @var MagicWordFactory */
48 * @param MagicWordFactory|null $factory
50 public function __construct( $names = [], MagicWordFactory
$factory = null ) {
51 $this->names
= $names;
52 $this->factory
= $factory ?
: MediaWikiServices
::getInstance()->getMagicWordFactory();
56 * Add a magic word by name
60 public function add( $name ) {
61 $this->names
[] = $name;
62 $this->hash
= $this->baseRegex
= $this->regex
= null;
66 * Add a number of magic words by name
70 public function addArray( $names ) {
71 $this->names
= array_merge( $this->names
, array_values( $names ) );
72 $this->hash
= $this->baseRegex
= $this->regex
= null;
76 * Get a 2-d hashtable for this array
79 public function getHash() {
80 if ( is_null( $this->hash
) ) {
81 $this->hash
= [ 0 => [], 1 => [] ];
82 foreach ( $this->names
as $name ) {
83 $magic = $this->factory
->get( $name );
84 $case = intval( $magic->isCaseSensitive() );
85 foreach ( $magic->getSynonyms() as $syn ) {
87 $syn = $this->factory
->getContentLanguage()->lc( $syn );
89 $this->hash
[$case][$syn] = $name;
100 public function getBaseRegex() {
101 if ( is_null( $this->baseRegex
) ) {
102 $this->baseRegex
= [ 0 => '', 1 => '' ];
104 foreach ( $this->names
as $name ) {
105 $magic = $this->factory
->get( $name );
106 $case = intval( $magic->isCaseSensitive() );
107 foreach ( $magic->getSynonyms() as $i => $syn ) {
108 // Group name must start with a non-digit in PCRE 8.34+
109 $it = strtr( $i, '0123456789', 'abcdefghij' );
110 $groupName = $it . '_' . $name;
111 $group = '(?P<' . $groupName . '>' . preg_quote( $syn, '/' ) . ')';
112 // look for same group names to avoid same named subpatterns in the regex
113 if ( isset( $allGroups[$groupName] ) ) {
114 throw new MWException(
115 __METHOD__
. ': duplicate internal name in magic word array: ' . $name
118 $allGroups[$groupName] = true;
119 if ( $this->baseRegex
[$case] === '' ) {
120 $this->baseRegex
[$case] = $group;
122 $this->baseRegex
[$case] .= '|' . $group;
127 return $this->baseRegex
;
131 * Get an unanchored regex that does not match parameters
134 public function getRegex() {
135 if ( is_null( $this->regex
) ) {
136 $base = $this->getBaseRegex();
137 $this->regex
= [ '', '' ];
138 if ( $this->baseRegex
[0] !== '' ) {
139 $this->regex
[0] = "/{$base[0]}/iuS";
141 if ( $this->baseRegex
[1] !== '' ) {
142 $this->regex
[1] = "/{$base[1]}/S";
149 * Get a regex for matching variables with parameters
153 public function getVariableRegex() {
154 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
158 * Get a regex anchored to the start of the string that does not match parameters
162 public function getRegexStart() {
163 $base = $this->getBaseRegex();
164 $newRegex = [ '', '' ];
165 if ( $base[0] !== '' ) {
166 $newRegex[0] = "/^(?:{$base[0]})/iuS";
168 if ( $base[1] !== '' ) {
169 $newRegex[1] = "/^(?:{$base[1]})/S";
175 * Get an anchored regex for matching variables with parameters
179 public function getVariableStartToEndRegex() {
180 $base = $this->getBaseRegex();
181 $newRegex = [ '', '' ];
182 if ( $base[0] !== '' ) {
183 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
185 if ( $base[1] !== '' ) {
186 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
195 public function getNames() {
200 * Parse a match array from preg_match
201 * Returns array(magic word ID, parameter value)
202 * If there is no parameter value, that element will be false.
206 * @throws MWException
209 public function parseMatch( $m ) {
211 while ( ( $key = key( $m ) ) !== null ) {
212 $value = current( $m );
214 if ( $key === 0 ||
$value === '' ) {
217 $parts = explode( '_', $key, 2 );
218 if ( count( $parts ) != 2 ) {
219 // This shouldn't happen
221 throw new MWException( __METHOD__
. ': bad parameter name' );
223 list( /* $synIndex */, $magicName ) = $parts;
224 $paramValue = next( $m );
225 return [ $magicName, $paramValue ];
227 // This shouldn't happen either
228 throw new MWException( __METHOD__
. ': parameter not found' );
232 * Match some text, with parameter capture
233 * Returns an array with the magic word name in the first element and the
234 * parameter in the second element.
235 * Both elements are false if there was no match.
237 * @param string $text
241 public function matchVariableStartToEnd( $text ) {
242 $regexes = $this->getVariableStartToEndRegex();
243 foreach ( $regexes as $regex ) {
244 if ( $regex !== '' ) {
246 if ( preg_match( $regex, $text, $m ) ) {
247 return $this->parseMatch( $m );
251 return [ false, false ];
255 * Match some text, without parameter capture
256 * Returns the magic word name, or false if there was no capture
258 * @param string $text
260 * @return string|bool False on failure
262 public function matchStartToEnd( $text ) {
263 $hash = $this->getHash();
264 if ( isset( $hash[1][$text] ) ) {
265 return $hash[1][$text];
267 $lc = $this->factory
->getContentLanguage()->lc( $text );
268 return $hash[0][$lc] ??
false;
272 * Returns an associative array, ID => param value, for all items that match
273 * Removes the matched items from the input string (passed by reference)
275 * @param string &$text
279 public function matchAndRemove( &$text ) {
281 $regexes = $this->getRegex();
282 foreach ( $regexes as $regex ) {
283 if ( $regex === '' ) {
287 $res = preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
288 if ( $res === false ) {
289 LoggerFactory
::getInstance( 'parser' )->warning( 'preg_match_all returned false', [
290 'code' => preg_last_error(),
295 foreach ( $matches as $m ) {
296 list( $name, $param ) = $this->parseMatch( $m );
297 $found[$name] = $param;
300 $res = preg_replace( $regex, '', $text );
301 if ( $res === null ) {
302 LoggerFactory
::getInstance( 'parser' )->warning( 'preg_replace returned null', [
303 'code' => preg_last_error(),
314 * Return the ID of the magic word at the start of $text, and remove
315 * the prefix from $text.
316 * Return false if no match found and $text is not modified.
317 * Does not match parameters.
319 * @param string &$text
321 * @return int|bool False on failure
323 public function matchStartAndRemove( &$text ) {
324 $regexes = $this->getRegexStart();
325 foreach ( $regexes as $regex ) {
326 if ( $regex === '' ) {
329 if ( preg_match( $regex, $text, $m ) ) {
330 list( $id, ) = $this->parseMatch( $m );
331 if ( strlen( $m[0] ) >= strlen( $text ) ) {
334 $text = substr( $text, strlen( $m[0] ) );