Debian Codegraph @

extensions/AbuseFilter/includes/Parser/FilterEvaluator.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\AbuseFilter\Parser;
4
5 use Exception;
6 use InvalidArgumentException;
7 use MediaWiki\Extension\AbuseFilter\KeywordsManager;
8 use MediaWiki\Extension\AbuseFilter\Parser\Exception\ConditionLimitException;
9 use MediaWiki\Extension\AbuseFilter\Parser\Exception\ExceptionBase;
10 use MediaWiki\Extension\AbuseFilter\Parser\Exception\InternalException;
11 use MediaWiki\Extension\AbuseFilter\Parser\Exception\UserVisibleException;
12 use MediaWiki\Extension\AbuseFilter\Parser\Exception\UserVisibleWarning;
13 use MediaWiki\Extension\AbuseFilter\Variables\VariableHolder;
14 use MediaWiki\Extension\AbuseFilter\Variables\VariablesManager;
15 use MediaWiki\Language\Language;
16 use MediaWiki\Parser\Sanitizer;
17 use Psr\Log\LoggerInterface;
18 use Wikimedia\Equivset\Equivset;
19 use Wikimedia\IPUtils;
20 use Wikimedia\ObjectCache\BagOStuff;
21 use Wikimedia\Stats\IBufferingStatsdDataFactory;
22
23 /**
24 * This class evaluates an AST generated by the filter parser.
25 *
26 * @todo Override checkSyntax and make it only try to build the AST. That would mean faster results,
27 * and no need to mess with DUNDEFINED and the like. However, we must first try to reduce the
28 * amount of runtime-only exceptions, and try to detect them in the AFPTreeParser instead.
29 * Otherwise, people may be able to save a broken filter without the syntax check reporting that.
30 */
31 class FilterEvaluator {
32 private const CACHE_VERSION = 1;
33
34 public const FUNCTIONS = [
35 'lcase' => 'funcLc',
36 'ucase' => 'funcUc',
37 'length' => 'funcLen',
38 'string' => 'castString',
39 'int' => 'castInt',
40 'float' => 'castFloat',
41 'bool' => 'castBool',
42 'norm' => 'funcNorm',
43 'ccnorm' => 'funcCCNorm',
44 'ccnorm_contains_any' => 'funcCCNormContainsAny',
45 'ccnorm_contains_all' => 'funcCCNormContainsAll',
46 'specialratio' => 'funcSpecialRatio',
47 'rmspecials' => 'funcRMSpecials',
48 'rmdoubles' => 'funcRMDoubles',
49 'rmwhitespace' => 'funcRMWhitespace',
50 'count' => 'funcCount',
51 'rcount' => 'funcRCount',
52 'get_matches' => 'funcGetMatches',
53 'ip_in_range' => 'funcIPInRange',
54 'ip_in_ranges' => 'funcIPInRanges',
55 'contains_any' => 'funcContainsAny',
56 'contains_all' => 'funcContainsAll',
57 'equals_to_any' => 'funcEqualsToAny',
58 'substr' => 'funcSubstr',
59 'strlen' => 'funcLen',
60 'strpos' => 'funcStrPos',
61 'str_replace' => 'funcStrReplace',
62 'str_replace_regexp' => 'funcStrReplaceRegexp',
63 'rescape' => 'funcStrRegexEscape',
64 'set' => 'funcSetVar',
65 'set_var' => 'funcSetVar',
66 'sanitize' => 'funcSanitize',
67 ];
68
69 /**
70 * The minimum and maximum amount of arguments required by each function.
71 * @var int[][]
72 */
73 public const FUNC_ARG_COUNT = [
74 'lcase' => [ 1, 1 ],
75 'ucase' => [ 1, 1 ],
76 'length' => [ 1, 1 ],
77 'string' => [ 1, 1 ],
78 'int' => [ 1, 1 ],
79 'float' => [ 1, 1 ],
80 'bool' => [ 1, 1 ],
81 'norm' => [ 1, 1 ],
82 'ccnorm' => [ 1, 1 ],
83 'ccnorm_contains_any' => [ 2, INF ],
84 'ccnorm_contains_all' => [ 2, INF ],
85 'specialratio' => [ 1, 1 ],
86 'rmspecials' => [ 1, 1 ],
87 'rmdoubles' => [ 1, 1 ],
88 'rmwhitespace' => [ 1, 1 ],
89 'count' => [ 1, 2 ],
90 'rcount' => [ 1, 2 ],
91 'get_matches' => [ 2, 2 ],
92 'ip_in_range' => [ 2, 2 ],
93 'ip_in_ranges' => [ 2, INF ],
94 'contains_any' => [ 2, INF ],
95 'contains_all' => [ 2, INF ],
96 'equals_to_any' => [ 2, INF ],
97 'substr' => [ 2, 3 ],
98 'strlen' => [ 1, 1 ],
99 'strpos' => [ 2, 3 ],
100 'str_replace' => [ 3, 3 ],
101 'str_replace_regexp' => [ 3, 3 ],
102 'rescape' => [ 1, 1 ],
103 'set' => [ 2, 2 ],
104 'set_var' => [ 2, 2 ],
105 'sanitize' => [ 1, 1 ],
106 ];
107
108 // Functions that affect parser state, and shouldn't be cached.
109 private const ACTIVE_FUNCTIONS = [
110 'funcSetVar',
111 ];
112
113 public const KEYWORDS = [
114 'in' => 'keywordIn',
115 'like' => 'keywordLike',
116 'matches' => 'keywordLike',
117 'contains' => 'keywordContains',
118 'rlike' => 'keywordRegex',
119 'irlike' => 'keywordRegexInsensitive',
120 'regex' => 'keywordRegex',
121 ];
122
123 /**
124 * @var bool Are we allowed to use short-circuit evaluation?
125 */
126 private $mAllowShort;
127
128 /**
129 * @var VariableHolder
130 */
131 private $mVariables;
132 /**
133 * @var int The current amount of conditions being consumed
134 */
135 private $mCondCount;
136 /**
137 * @var bool Whether the condition limit is enabled.
138 */
139 private $condLimitEnabled = true;
140 /**
141 * @var string|null The ID of the filter being parsed, if available. Can also be "global-$ID"
142 */
143 private $mFilter;
144 /**
145 * @var bool Whether we can allow retrieving _builtin_ variables not included in $this->mVariables
146 */
147 private $allowMissingVariables = false;
148
149 /**
150 * @var BagOStuff Used to cache the AST and the tokens
151 */
152 private $cache;
153 /**
154 * @var bool Whether the AST was retrieved from cache
155 */
156 private $fromCache = false;
157 /**
158 * @var LoggerInterface Used for debugging
159 */
160 private $logger;
161 /**
162 * @var Language Content language, used for language-dependent functions
163 */
164 private $contLang;
165 /**
166 * @var IBufferingStatsdDataFactory
167 */
168 private $statsd;
169
170 /** @var KeywordsManager */
171 private $keywordsManager;
172
173 /** @var VariablesManager */
174 private $varManager;
175
176 /** @var int */
177 private $conditionsLimit;
178
179 /** @var UserVisibleWarning[] */
180 private $warnings = [];
181
182 /**
183 * @var array Cached results of functions
184 */
185 private $funcCache = [];
186
187 /**
188 * @var Equivset
189 */
190 private $equivset;
191
192 /**
193 * @var array AFPToken::TID values found during node evaluation
194 */
195 private $usedVars = [];
196
197 /**
198 * Create a new instance
199 *
200 * @param Language $contLang Content language, used for language-dependent function
201 * @param BagOStuff $cache Used to cache the AST and the tokens
202 * @param LoggerInterface $logger Used for debugging
203 * @param KeywordsManager $keywordsManager
204 * @param VariablesManager $varManager
205 * @param IBufferingStatsdDataFactory $statsdDataFactory
206 * @param Equivset $equivset
207 * @param int $conditionsLimit
208 * @param VariableHolder|null $vars
209 */
210 public function __construct(
211 Language $contLang,
212 BagOStuff $cache,
213 LoggerInterface $logger,
214 KeywordsManager $keywordsManager,
215 VariablesManager $varManager,
216 IBufferingStatsdDataFactory $statsdDataFactory,
217 Equivset $equivset,
218 int $conditionsLimit,
219 ?VariableHolder $vars = null
220 ) {
221 $this->contLang = $contLang;
222 $this->cache = $cache;
223 $this->logger = $logger;
224 $this->statsd = $statsdDataFactory;
225 $this->keywordsManager = $keywordsManager;
226 $this->varManager = $varManager;
227 $this->equivset = $equivset;
228 $this->conditionsLimit = $conditionsLimit;
229 $this->resetState();
230 if ( $vars ) {
231 $this->mVariables = $vars;
232 }
233 }
234
235 /**
236 * For use in batch scripts and the like
237 *
238 * @param bool $enable True to enable the limit, false to disable it
239 */
240 public function toggleConditionLimit( $enable ) {
241 $this->condLimitEnabled = $enable;
242 }
243
244 /**
245 * @throws ConditionLimitException
246 */
247 private function raiseCondCount() {
248 $this->mCondCount++;
249 if ( $this->condLimitEnabled && $this->mCondCount > $this->conditionsLimit ) {
250 throw new ConditionLimitException();
251 }
252 }
253
254 /**
255 * @param VariableHolder $vars
256 */
257 public function setVariables( VariableHolder $vars ) {
258 $this->mVariables = $vars;
259 }
260
261 /**
262 * Return the generated version of the parser for cache invalidation
263 * purposes. Automatically tracks list of all functions and invalidates the
264 * cache if it is changed.
265 * @return string
266 */
267 private static function getCacheVersion() {
268 static $version = null;
269 if ( $version !== null ) {
270 return $version;
271 }
272
273 $versionKey = [
274 self::CACHE_VERSION,
275 AFPTreeParser::CACHE_VERSION,
276 AbuseFilterTokenizer::CACHE_VERSION,
277 SyntaxChecker::CACHE_VERSION,
278 array_keys( self::FUNCTIONS ),
279 array_keys( self::KEYWORDS ),
280 ];
281 $version = hash( 'sha256', serialize( $versionKey ) );
282
283 return $version;
284 }
285
286 /**
287 * Resets the state of the parser
288 */
289 private function resetState() {
290 $this->mVariables = new VariableHolder();
291 $this->mCondCount = 0;
292 $this->mAllowShort = true;
293 $this->mFilter = null;
294 $this->warnings = [];
295 $this->usedVars = [];
296 }
297
298 /**
299 * Check the syntax of $filter, throwing an exception if invalid
300 * @param string $filter
301 * @return true When successful
302 * @throws UserVisibleException
303 */
304 public function checkSyntaxThrow( string $filter ): bool {
305 $this->allowMissingVariables = true;
306 $origAS = $this->mAllowShort;
307 try {
308 $this->mAllowShort = false;
309 $this->evalTree( $this->getTree( $filter ) );
310 } finally {
311 $this->mAllowShort = $origAS;
312 $this->allowMissingVariables = false;
313 }
314
315 return true;
316 }
317
318 /**
319 * Check the syntax of $filter, without throwing
320 *
321 * @param string $filter
322 * @return ParserStatus
323 */
324 public function checkSyntax( string $filter ): ParserStatus {
325 $initialConds = $this->mCondCount;
326 try {
327 $this->checkSyntaxThrow( $filter );
328 } catch ( UserVisibleException $excep ) {
329 }
330
331 return new ParserStatus(
332 $excep ?? null,
333 $this->warnings,
334 $this->mCondCount - $initialConds
335 );
336 }
337
338 /**
339 * This is the main entry point. It checks the given conditions and returns whether
340 * they match. Parser errors are always logged.
341 *
342 * @param string $conds
343 * @param string|null $filter The ID of the filter being parsed
344 * @return RuleCheckerStatus
345 */
346 public function checkConditions( string $conds, $filter = null ): RuleCheckerStatus {
347 $this->mFilter = $filter;
348 $excep = null;
349 $initialConds = $this->mCondCount;
350 $startTime = microtime( true );
351 try {
352 $res = $this->parse( $conds );
353 } catch ( ExceptionBase $excep ) {
354 $res = false;
355 }
356 $this->statsd->timing( 'abusefilter_cachingParser_full', microtime( true ) - $startTime );
357 $result = new RuleCheckerStatus(
358 $res,
359 $this->fromCache,
360 $excep,
361 $this->warnings,
362 $this->mCondCount - $initialConds
363 );
364
365 if ( $excep !== null ) {
366 if ( $excep instanceof UserVisibleException ) {
367 $msg = $excep->getMessageForLogs();
368 } else {
369 $msg = $excep->getMessage();
370 }
371
372 $this->logger->warning(
373 "AbuseFilter parser error: {parser_error}",
374 [ 'parser_error' => $msg, 'broken_filter' => $filter ?: 'none' ]
375 );
376 }
377
378 return $result;
379 }
380
381 /**
382 * @param string $code
383 * @return bool
384 */
385 public function parse( $code ) {
386 $res = $this->evalTree( $this->getTree( $code ) );
387 return $res->getType() === AFPData::DUNDEFINED ? false : $res->toBool();
388 }
389
390 /**
391 * @param string $filter
392 * @return mixed
393 */
394 public function evaluateExpression( $filter ) {
395 return $this->evalTree( $this->getTree( $filter ) )->toNative();
396 }
397
398 /**
399 * @param string $code
400 * @return AFPSyntaxTree
401 */
402 private function getTree( $code ): AFPSyntaxTree {
403 $this->fromCache = true;
404 return $this->cache->getWithSetCallback(
405 $this->cache->makeGlobalKey(
406 __CLASS__,
407 self::getCacheVersion(),
408 hash( 'sha256', $code )
409 ),
410 BagOStuff::TTL_DAY,
411 function () use ( $code ) {
412 $this->fromCache = false;
413 $tokenizer = new AbuseFilterTokenizer( $this->cache );
414 $tokens = $tokenizer->getTokens( $code );
415 $parser = new AFPTreeParser( $this->logger, $this->statsd, $this->keywordsManager );
416 $parser->setFilter( $this->mFilter );
417 $tree = $parser->parse( $tokens );
418 $checker = new SyntaxChecker(
419 $tree,
420 $this->keywordsManager,
421 SyntaxChecker::MCONSERVATIVE,
422 false
423 );
424 $checker->start();
425 return $tree;
426 }
427 );
428 }
429
430 /**
431 * @param AFPSyntaxTree $tree
432 * @return AFPData
433 */
434 private function evalTree( AFPSyntaxTree $tree ): AFPData {
435 $startTime = microtime( true );
436 $root = $tree->getRoot();
437
438 if ( !$root ) {
439 return new AFPData( AFPData::DNULL );
440 }
441
442 $ret = $this->evalNode( $root );
443 $this->statsd->timing( 'abusefilter_cachingParser_eval', microtime( true ) - $startTime );
444 return $ret;
445 }
446
447 /**
448 * Parse a filter and return the variables used.
449 * All variables are AFPToken::TID and are found during the node stepthrough in evaluation
450 * and saved to self::usedVars to be returned to the caller in this function.
451 *
452 * @param string $filter
453 * @return string[]
454 */
455 public function getUsedVars( string $filter ): array {
456 $this->checkSyntax( $filter );
457 return array_unique( $this->usedVars );
458 }
459
460 /**
461 * Evaluate the value of the specified AST node.
462 *
463 * @param AFPTreeNode $node The node to evaluate.
464 * @return AFPData|AFPTreeNode|string
465 * @throws ExceptionBase
466 * @throws UserVisibleException
467 */
468 private function evalNode( AFPTreeNode $node ) {
469 switch ( $node->type ) {
470 case AFPTreeNode::ATOM:
471 $tok = $node->children;
472 switch ( $tok->type ) {
473 case AFPToken::TID:
474 return $this->getVarValue( strtolower( $tok->value ) );
475 case AFPToken::TSTRING:
476 return new AFPData( AFPData::DSTRING, $tok->value );
477 case AFPToken::TFLOAT:
478 return new AFPData( AFPData::DFLOAT, $tok->value );
479 case AFPToken::TINT:
480 return new AFPData( AFPData::DINT, $tok->value );
481 /** @noinspection PhpMissingBreakStatementInspection */
482 case AFPToken::TKEYWORD:
483 switch ( $tok->value ) {
484 case "true":
485 return new AFPData( AFPData::DBOOL, true );
486 case "false":
487 return new AFPData( AFPData::DBOOL, false );
488 case "null":
489 return new AFPData( AFPData::DNULL );
490 }
491 // Fallthrough intended
492 default:
493 // @codeCoverageIgnoreStart
494 throw new InternalException( "Unknown token provided in the ATOM node" );
495 // @codeCoverageIgnoreEnd
496 }
497 // Unreachable line
498 case AFPTreeNode::ARRAY_DEFINITION:
499 $items = [];
500 // Foreach is usually faster than array_map
501 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach children is array here
502 foreach ( $node->children as $el ) {
503 $items[] = $this->evalNode( $el );
504 }
505 return new AFPData( AFPData::DARRAY, $items );
506
507 case AFPTreeNode::FUNCTION_CALL:
508 $functionName = $node->children[0];
509 $args = array_slice( $node->children, 1 );
510
511 $dataArgs = [];
512 // Foreach is usually faster than array_map
513 foreach ( $args as $arg ) {
514 $dataArgs[] = $this->evalNode( $arg );
515 }
516
517 return $this->callFunc( $functionName, $dataArgs, $node->position );
518 case AFPTreeNode::ARRAY_INDEX:
519 [ $array, $offset ] = $node->children;
520
521 $array = $this->evalNode( $array );
522 // Note: we MUST evaluate the offset to ensure it is valid, regardless
523 // of $array!
524 $offset = $this->evalNode( $offset );
525 // @todo If $array has no elements we could already throw an outofbounds. We don't
526 // know what the index is, though.
527 if ( $offset->getType() === AFPData::DUNDEFINED ) {
528 return new AFPData( AFPData::DUNDEFINED );
529 }
530 $offset = $offset->toInt();
531
532 if ( $array->getType() === AFPData::DUNDEFINED ) {
533 return new AFPData( AFPData::DUNDEFINED );
534 }
535
536 if ( $array->getType() !== AFPData::DARRAY ) {
537 throw new UserVisibleException( 'notarray', $node->position, [] );
538 }
539
540 $array = $array->toArray();
541 if ( count( $array ) <= $offset ) {
542 throw new UserVisibleException( 'outofbounds', $node->position,
543 [ $offset, count( $array ) ] );
544 } elseif ( $offset < 0 ) {
545 throw new UserVisibleException( 'negativeindex', $node->position, [ $offset ] );
546 }
547
548 return $array[$offset];
549
550 case AFPTreeNode::UNARY:
551 [ $operation, $argument ] = $node->children;
552 $argument = $this->evalNode( $argument );
553 if ( $operation === '-' ) {
554 return $argument->unaryMinus();
555 }
556 return $argument;
557
558 case AFPTreeNode::KEYWORD_OPERATOR:
559 [ $keyword, $leftOperand, $rightOperand ] = $node->children;
560 $leftOperand = $this->evalNode( $leftOperand );
561 $rightOperand = $this->evalNode( $rightOperand );
562
563 return $this->callKeyword( $keyword, $leftOperand, $rightOperand, $node->position );
564 case AFPTreeNode::BOOL_INVERT:
565 [ $argument ] = $node->children;
566 $argument = $this->evalNode( $argument );
567 return $argument->boolInvert();
568
569 case AFPTreeNode::POW:
570 [ $base, $exponent ] = $node->children;
571 $base = $this->evalNode( $base );
572 $exponent = $this->evalNode( $exponent );
573 return $base->pow( $exponent );
574
575 case AFPTreeNode::MUL_REL:
576 [ $op, $leftOperand, $rightOperand ] = $node->children;
577 $leftOperand = $this->evalNode( $leftOperand );
578 $rightOperand = $this->evalNode( $rightOperand );
579 return $leftOperand->mulRel( $rightOperand, $op, $node->position );
580
581 case AFPTreeNode::SUM_REL:
582 [ $op, $leftOperand, $rightOperand ] = $node->children;
583 $leftOperand = $this->evalNode( $leftOperand );
584 $rightOperand = $this->evalNode( $rightOperand );
585 switch ( $op ) {
586 case '+':
587 return $leftOperand->sum( $rightOperand );
588 case '-':
589 return $leftOperand->sub( $rightOperand );
590 default:
591 // @codeCoverageIgnoreStart
592 throw new InternalException( "Unknown sum-related operator: {$op}" );
593 // @codeCoverageIgnoreEnd
594 }
595 // Unreachable line
596 case AFPTreeNode::COMPARE:
597 [ $op, $leftOperand, $rightOperand ] = $node->children;
598 $leftOperand = $this->evalNode( $leftOperand );
599 $rightOperand = $this->evalNode( $rightOperand );
600 $this->raiseCondCount();
601 return $leftOperand->compareOp( $rightOperand, $op );
602
603 case AFPTreeNode::LOGIC:
604 [ $op, $leftOperand, $rightOperand ] = $node->children;
605 $leftOperand = $this->evalNode( $leftOperand );
606 $value = $leftOperand->getType() === AFPData::DUNDEFINED ? false : $leftOperand->toBool();
607 // Short-circuit.
608 if ( ( !$value && $op === '&' ) || ( $value && $op === '|' ) ) {
609 if ( $rightOperand instanceof AFPTreeNode ) {
610 $this->maybeDiscardNode( $rightOperand );
611 }
612 return $leftOperand;
613 }
614 $rightOperand = $this->evalNode( $rightOperand );
615 return $leftOperand->boolOp( $rightOperand, $op );
616
617 case AFPTreeNode::CONDITIONAL:
618 [ $condition, $valueIfTrue, $valueIfFalse ] = $node->children;
619 $condition = $this->evalNode( $condition );
620 $isTrue = $condition->getType() === AFPData::DUNDEFINED ? false : $condition->toBool();
621 if ( $isTrue ) {
622 if ( $valueIfFalse !== null ) {
623 $this->maybeDiscardNode( $valueIfFalse );
624 }
625 return $this->evalNode( $valueIfTrue );
626 } else {
627 $this->maybeDiscardNode( $valueIfTrue );
628 return $valueIfFalse !== null
629 ? $this->evalNode( $valueIfFalse )
630 // We assume null as default if the else is missing
631 : new AFPData( AFPData::DNULL );
632 }
633
634 case AFPTreeNode::ASSIGNMENT:
635 [ $varName, $value ] = $node->children;
636 $value = $this->evalNode( $value );
637 $this->setUserVariable( $varName, $value );
638 return $value;
639
640 case AFPTreeNode::INDEX_ASSIGNMENT:
641 [ $varName, $offset, $value ] = $node->children;
642
643 $array = $this->getVarValue( $varName );
644
645 if ( $array->getType() !== AFPData::DARRAY && $array->getType() !== AFPData::DUNDEFINED ) {
646 throw new UserVisibleException( 'notarray', $node->position, [] );
647 }
648
649 $offset = $this->evalNode( $offset );
650 // @todo If $array has no elements we could already throw an outofbounds. We don't
651 // know what the index is, though.
652
653 if ( $array->getType() !== AFPData::DUNDEFINED ) {
654 // If it's a DUNDEFINED, leave it as is
655 if ( $offset->getType() !== AFPData::DUNDEFINED ) {
656 $offset = $offset->toInt();
657 $array = $array->toArray();
658 if ( count( $array ) <= $offset ) {
659 throw new UserVisibleException( 'outofbounds', $node->position,
660 [ $offset, count( $array ) ] );
661 } elseif ( $offset < 0 ) {
662 throw new UserVisibleException( 'negativeindex', $node->position, [ $offset ] );
663 }
664
665 $value = $this->evalNode( $value );
666 $array[$offset] = $value;
667 $array = new AFPData( AFPData::DARRAY, $array );
668 } else {
669 $value = $this->evalNode( $value );
670 $array = new AFPData( AFPData::DUNDEFINED );
671 }
672 $this->setUserVariable( $varName, $array );
673 } else {
674 $value = $this->evalNode( $value );
675 }
676
677 return $value;
678
679 case AFPTreeNode::ARRAY_APPEND:
680 [ $varName, $value ] = $node->children;
681
682 $array = $this->getVarValue( $varName );
683 $value = $this->evalNode( $value );
684 if ( $array->getType() !== AFPData::DUNDEFINED ) {
685 // If it's a DUNDEFINED, leave it as is
686 if ( $array->getType() !== AFPData::DARRAY ) {
687 throw new UserVisibleException( 'notarray', $node->position, [] );
688 }
689
690 $array = $array->toArray();
691 $array[] = $value;
692 $this->setUserVariable( $varName, new AFPData( AFPData::DARRAY, $array ) );
693 }
694 return $value;
695
696 case AFPTreeNode::SEMICOLON:
697 $lastValue = null;
698 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach children is array here
699 foreach ( $node->children as $statement ) {
700 $lastValue = $this->evalNode( $statement );
701 }
702
703 // @phan-suppress-next-next-line PhanTypeMismatchReturnNullable Can never be null because
704 // empty statements are discarded in AFPTreeParser
705 return $lastValue;
706 default:
707 // @codeCoverageIgnoreStart
708 throw new InternalException( "Unknown node type passed: {$node->type}" );
709 // @codeCoverageIgnoreEnd
710 }
711 }
712
713 /**
714 * Helper to call a built-in function.
715 *
716 * @param string $fname The name of the function as found in the filter code
717 * @param AFPData[] $args Arguments for the function
718 * @param int $position
719 * @return AFPData The return value of the function
720 * @throws InvalidArgumentException if given an invalid func
721 */
722 private function callFunc( $fname, array $args, int $position ): AFPData {
723 if ( !array_key_exists( $fname, self::FUNCTIONS ) ) {
724 // @codeCoverageIgnoreStart
725 throw new InvalidArgumentException( "$fname is not a valid function." );
726 // @codeCoverageIgnoreEnd
727 }
728
729 $funcHandler = self::FUNCTIONS[$fname];
730 $funcHash = md5( $funcHandler . serialize( $args ) );
731
732 if ( isset( $this->funcCache[$funcHash] ) &&
733 !in_array( $funcHandler, self::ACTIVE_FUNCTIONS )
734 ) {
735 $result = $this->funcCache[$funcHash];
736 } else {
737 $this->raiseCondCount();
738
739 // Any undefined argument should be special-cased by the function, but that would be too
740 // much overhead. We also cannot skip calling the handler in case it's making further
741 // validation (T234339). So temporarily replace the DUNDEFINED with a DNULL.
742 // @todo This is subpar.
743 $hasUndefinedArg = false;
744 foreach ( $args as $i => $arg ) {
745 if ( $arg->hasUndefined() ) {
746 $args[$i] = $arg->cloneAsUndefinedReplacedWithNull();
747 $hasUndefinedArg = true;
748 }
749 }
750 if ( $hasUndefinedArg ) {
751 // @phan-suppress-next-line PhanParamTooMany Not every function needs the position
752 $this->$funcHandler( $args, $position );
753 $result = new AFPData( AFPData::DUNDEFINED );
754 } else {
755 // @phan-suppress-next-line PhanParamTooMany Not every function needs the position
756 $result = $this->$funcHandler( $args, $position );
757 }
758 $this->funcCache[$funcHash] = $result;
759 }
760
761 if ( count( $this->funcCache ) > 1000 ) {
762 // @codeCoverageIgnoreStart
763 $this->funcCache = [];
764 // @codeCoverageIgnoreEnd
765 }
766 return $result;
767 }
768
769 /**
770 * Helper to invoke a built-in keyword. Note that this assumes that $kname is
771 * a valid keyword name.
772 *
773 * @param string $kname
774 * @param AFPData $lhs
775 * @param AFPData $rhs
776 * @param int $position
777 * @return AFPData
778 */
779 private function callKeyword( $kname, AFPData $lhs, AFPData $rhs, int $position ): AFPData {
780 $func = self::KEYWORDS[$kname];
781 $this->raiseCondCount();
782
783 $hasUndefinedOperand = false;
784 if ( $lhs->hasUndefined() ) {
785 $lhs = $lhs->cloneAsUndefinedReplacedWithNull();
786 $hasUndefinedOperand = true;
787 }
788 if ( $rhs->hasUndefined() ) {
789 $rhs = $rhs->cloneAsUndefinedReplacedWithNull();
790 $hasUndefinedOperand = true;
791 }
792 if ( $hasUndefinedOperand ) {
793 // We need to run the handler with bogus args, see the comment in self::callFunc (T234339)
794 // @todo Likewise, this is subpar.
795 // @phan-suppress-next-line PhanParamTooMany Not every function needs the position
796 $this->$func( $lhs, $rhs, $position );
797 $result = new AFPData( AFPData::DUNDEFINED );
798 } else {
799 // @phan-suppress-next-line PhanParamTooMany Not every function needs the position
800 $result = $this->$func( $lhs, $rhs, $position );
801 }
802 return $result;
803 }
804
805 /**
806 * Check whether a variable exists, being either built-in or user-defined. Doesn't include
807 * disabled variables.
808 *
809 * @param string $varname
810 * @return bool
811 */
812 private function varExists( $varname ) {
813 return $this->keywordsManager->isVarInUse( $varname ) ||
814 $this->mVariables->varIsSet( $varname );
815 }
816
817 /**
818 * @param string $var
819 * @return AFPData
820 * @throws UserVisibleException
821 */
822 private function getVarValue( $var ) {
823 $var = strtolower( $var );
824 $deprecatedVars = $this->keywordsManager->getDeprecatedVariables();
825
826 if ( array_key_exists( $var, $deprecatedVars ) ) {
827 $var = $deprecatedVars[ $var ];
828 }
829 // With check syntax, all unbound variables will be caught
830 // already. So we do not error unbound variables at runtime,
831 // allowing it to result in DUNDEFINED.
832 $allowMissingVariables = !$this->varExists( $var ) || $this->allowMissingVariables;
833
834 array_push( $this->usedVars, $var );
835
836 // It's a built-in, non-disabled variable (either set or unset), or a set custom variable
837 $flags = $allowMissingVariables
838 ? VariablesManager::GET_LAX
839 // TODO: This should be GET_STRICT, but that's going to be very hard (see T230256)
840 : VariablesManager::GET_BC;
841 return $this->varManager->getVar( $this->mVariables, $var, $flags );
842 }
843
844 /**
845 * @param string $name
846 * @param mixed $value
847 * @throws UserVisibleException
848 */
849 private function setUserVariable( $name, $value ) {
850 $this->mVariables->setVar( $name, $value );
851 }
852
853 // Built-in functions
854
855 /**
856 * @param array $args
857 * @return AFPData
858 */
859 private function funcLc( $args ) {
860 $s = $args[0]->toString();
861
862 return new AFPData( AFPData::DSTRING, $this->contLang->lc( $s ) );
863 }
864
865 /**
866 * @param array $args
867 * @return AFPData
868 */
869 private function funcUc( $args ) {
870 $s = $args[0]->toString();
871
872 return new AFPData( AFPData::DSTRING, $this->contLang->uc( $s ) );
873 }
874
875 /**
876 * @param array $args
877 * @return AFPData
878 */
879 private function funcLen( $args ) {
880 if ( $args[0]->type === AFPData::DARRAY ) {
881 // Don't use toString on arrays, but count
882 $val = count( $args[0]->data );
883 } else {
884 $val = mb_strlen( $args[0]->toString(), 'utf-8' );
885 }
886
887 return new AFPData( AFPData::DINT, $val );
888 }
889
890 /**
891 * @param array $args
892 * @return AFPData
893 */
894 private function funcSpecialRatio( $args ) {
895 $s = $args[0]->toString();
896
897 if ( !strlen( $s ) ) {
898 return new AFPData( AFPData::DFLOAT, 0 );
899 }
900
901 $nospecials = $this->rmspecials( $s );
902
903 $val = 1. - ( ( mb_strlen( $nospecials ) / mb_strlen( $s ) ) );
904
905 return new AFPData( AFPData::DFLOAT, $val );
906 }
907
908 /**
909 * @param array $args
910 * @return AFPData
911 */
912 private function funcCount( $args ) {
913 if ( $args[0]->type === AFPData::DARRAY && count( $args ) === 1 ) {
914 return new AFPData( AFPData::DINT, count( $args[0]->data ) );
915 }
916
917 if ( count( $args ) === 1 ) {
918 $count = count( explode( ',', $args[0]->toString() ) );
919 } else {
920 $needle = $args[0]->toString();
921 $haystack = $args[1]->toString();
922
923 // T62203: Keep empty parameters from causing PHP warnings
924 if ( $needle === '' ) {
925 $count = 0;
926 } else {
927 $count = substr_count( $haystack, $needle );
928 }
929 }
930
931 return new AFPData( AFPData::DINT, $count );
932 }
933
934 /**
935 * @param array $args
936 * @param int $position
937 * @return AFPData
938 * @throws UserVisibleException
939 */
940 private function funcRCount( $args, int $position ) {
941 if ( count( $args ) === 1 ) {
942 $count = count( explode( ',', $args[0]->toString() ) );
943 } else {
944 $needle = $args[0]->toString();
945 $haystack = $args[1]->toString();
946
947 $needle = $this->mungeRegexp( $needle );
948
949 $this->checkRegexMatchesEmpty( $args[0], $needle, $position );
950 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
951 $count = @preg_match_all( $needle, $haystack );
952
953 if ( $count === false ) {
954 throw new UserVisibleException(
955 'regexfailure',
956 $position,
957 [ $needle ]
958 );
959 }
960 }
961
962 return new AFPData( AFPData::DINT, $count );
963 }
964
965 /**
966 * Returns an array of matches of needle in the haystack, the first one for the whole regex,
967 * the other ones for every capturing group.
968 *
969 * @param array $args
970 * @param int $position
971 * @return AFPData An array of matches.
972 * @throws UserVisibleException
973 */
974 private function funcGetMatches( $args, int $position ) {
975 $needle = $args[0]->toString();
976 $haystack = $args[1]->toString();
977
978 // Count the amount of capturing groups in the submitted pattern.
979 // This way we can return a fixed-dimension array, much easier to manage.
980 // ToDo: Find a better way to do this.
981 // First, strip away escaped parentheses
982 $sanitized = preg_replace( '/((\\\\\\\\)*)\\\\\(/', '$1', $needle );
983
984 // Then strip starting parentheses of non-capturing groups, including
985 // atomics, lookaheads and so on, even if not every of them is supported.
986 // Avoid stripping named capturing groups: (?P<name>), (?<name>) and (?'name')
987 $sanitized = preg_replace( '/\(\?(?!P?<[a-zA-Z_][a-zA-Z0-9_]*>|\'[a-zA-Z_][a-zA-Z0-9_]*\')/', '', $sanitized );
988
989 // And also strip "(*", used with backtracking verbs like (*FAIL)
990 $sanitized = str_replace( '(*', '', $sanitized );
991
992 // Finally create an array of falses with dimension = # of capturing groups + 1
993 // (as there is also the 0 element, which contains the whole match)
994 $groupscount = substr_count( $sanitized, '(' ) + 1;
995 $falsy = array_fill( 0, $groupscount, false );
996
997 $needle = $this->mungeRegexp( $needle );
998
999 $this->checkRegexMatchesEmpty( $args[0], $needle, $position );
1000 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1001 $check = @preg_match( $needle, $haystack, $matches );
1002
1003 if ( $check === false ) {
1004 throw new UserVisibleException(
1005 'regexfailure',
1006 $position,
1007 [ $needle ]
1008 );
1009 }
1010
1011 // Named capturing groups add the capture twice: with a numeric key and with a string key.
1012 // AF doesn't provide associative arrays, thus we have to filter out the elements with string keys,
1013 // else AFPData::newFromPHPVar would erroneously insert them into the final array, with numeric keys.
1014 $matches = array_filter( $matches, 'is_int', ARRAY_FILTER_USE_KEY );
1015
1016 // Returned array has non-empty positions identical to the ones returned
1017 // by the third parameter of a standard preg_match call ($matches in this case).
1018 // We want an union with falsy to return a fixed-dimension array.
1019 return AFPData::newFromPHPVar( $matches + $falsy );
1020 }
1021
1022 /**
1023 * @param array $args
1024 * @param int $position
1025 * @return AFPData
1026 * @throws UserVisibleException
1027 */
1028 private function funcIPInRange( $args, int $position ) {
1029 $ip = $args[0]->toString();
1030 $range = $args[1]->toString();
1031
1032 if ( !IPUtils::isValidRange( $range ) && !IPUtils::isIPAddress( $range ) ) {
1033 throw new UserVisibleException(
1034 'invalidiprange',
1035 $position,
1036 [ $range ]
1037 );
1038 }
1039
1040 $result = IPUtils::isInRange( $ip, $range );
1041
1042 return new AFPData( AFPData::DBOOL, $result );
1043 }
1044
1045 /**
1046 * @param array $args
1047 * @param int $position
1048 * @return AFPData
1049 * @throws UserVisibleException
1050 */
1051 private function funcIPInRanges( $args, int $position ) {
1052 $ip = array_shift( $args )->toString();
1053
1054 $strRanges = [];
1055 foreach ( $args as $range ) {
1056 $range = $range->toString();
1057
1058 if ( !IPUtils::isValidRange( $range ) && !IPUtils::isIPAddress( $range ) ) {
1059 throw new UserVisibleException(
1060 'invalidiprange',
1061 $position,
1062 [ $range ]
1063 );
1064 }
1065
1066 $strRanges[] = $range;
1067 }
1068
1069 return new AFPData( AFPData::DBOOL, IPUtils::isInRanges( $ip, $strRanges ) );
1070 }
1071
1072 /**
1073 * @param array $args
1074 * @return AFPData
1075 */
1076 private function funcCCNorm( $args ) {
1077 $s = $args[0]->toString();
1078
1079 $s = html_entity_decode( $s, ENT_QUOTES, 'UTF-8' );
1080 $s = $this->ccnorm( $s );
1081
1082 return new AFPData( AFPData::DSTRING, $s );
1083 }
1084
1085 /**
1086 * @param array $args
1087 * @return AFPData
1088 */
1089 private function funcSanitize( $args ) {
1090 $s = $args[0]->toString();
1091
1092 $s = html_entity_decode( $s, ENT_QUOTES, 'UTF-8' );
1093 $s = Sanitizer::decodeCharReferences( $s );
1094
1095 return new AFPData( AFPData::DSTRING, $s );
1096 }
1097
1098 /**
1099 * @param array $args
1100 * @return AFPData
1101 */
1102 private function funcContainsAny( $args ) {
1103 $s = array_shift( $args );
1104
1105 return new AFPData( AFPData::DBOOL, $this->contains( $s, $args, true ) );
1106 }
1107
1108 /**
1109 * @param array $args
1110 * @return AFPData
1111 */
1112 private function funcContainsAll( $args ) {
1113 $s = array_shift( $args );
1114
1115 return new AFPData( AFPData::DBOOL, $this->contains( $s, $args, false, false ) );
1116 }
1117
1118 /**
1119 * Normalize and search a string for multiple substrings in OR mode
1120 *
1121 * @param array $args
1122 * @return AFPData
1123 */
1124 private function funcCCNormContainsAny( $args ) {
1125 $s = array_shift( $args );
1126
1127 return new AFPData( AFPData::DBOOL, $this->contains( $s, $args, true, true ) );
1128 }
1129
1130 /**
1131 * Normalize and search a string for multiple substrings in AND mode
1132 *
1133 * @param array $args
1134 * @return AFPData
1135 */
1136 private function funcCCNormContainsAll( $args ) {
1137 $s = array_shift( $args );
1138
1139 return new AFPData( AFPData::DBOOL, $this->contains( $s, $args, false, true ) );
1140 }
1141
1142 /**
1143 * Search for substrings in a string
1144 *
1145 * Use is_any to determine whether to use logic OR (true) or AND (false).
1146 *
1147 * Use normalize = true to make use of ccnorm and
1148 * normalize both sides of the search.
1149 *
1150 * @param AFPData $string
1151 * @param AFPData[] $values
1152 * @param bool $is_any
1153 * @param bool $normalize
1154 *
1155 * @return bool
1156 */
1157 private function contains( $string, $values, $is_any = true, $normalize = false ) {
1158 $string = $string->toString();
1159
1160 if ( $string === '' ) {
1161 return false;
1162 }
1163
1164 if ( $normalize ) {
1165 $string = $this->ccnorm( $string );
1166 }
1167
1168 foreach ( $values as $needle ) {
1169 $needle = $needle->toString();
1170 if ( $normalize ) {
1171 $needle = $this->ccnorm( $needle );
1172 }
1173 if ( $needle === '' ) {
1174 // T62203: Keep empty parameters from causing PHP warnings
1175 continue;
1176 }
1177
1178 $is_found = strpos( $string, $needle ) !== false;
1179 if ( $is_found === $is_any ) {
1180 // If I'm here and it's ANY (OR) => something is found.
1181 // If I'm here and it's ALL (AND) => nothing is found.
1182 // In both cases, we've had enough.
1183 return $is_found;
1184 }
1185 }
1186
1187 // If I'm here and it's ANY (OR) => nothing was found: return false ($is_any is true)
1188 // If I'm here and it's ALL (AND) => everything was found: return true ($is_any is false)
1189 return !$is_any;
1190 }
1191
1192 /**
1193 * @param array $args
1194 * @return AFPData
1195 */
1196 private function funcEqualsToAny( $args ) {
1197 $s = array_shift( $args );
1198
1199 return new AFPData( AFPData::DBOOL, self::equalsToAny( $s, $args ) );
1200 }
1201
1202 /**
1203 * Check if the given string is equals to any of the following strings
1204 *
1205 * @param AFPData $string
1206 * @param AFPData[] $values
1207 *
1208 * @return bool
1209 */
1210 private static function equalsToAny( $string, $values ) {
1211 foreach ( $values as $needle ) {
1212 if ( $string->equals( $needle, true ) ) {
1213 return true;
1214 }
1215 }
1216
1217 return false;
1218 }
1219
1220 /**
1221 * @param string $s
1222 * @return string
1223 */
1224 private function ccnorm( $s ): string {
1225 return $this->equivset->normalize( $s );
1226 }
1227
1228 /**
1229 * @param string $s
1230 * @return array|string
1231 */
1232 private function rmspecials( $s ) {
1233 // (T385452) Disable JIT for this call, as it breaks sometimes
1234 ini_set( 'pcre.jit', '0' );
1235 $res = preg_replace( '/[^\p{L}\p{N}\s]/u', '', $s );
1236 ini_restore( 'pcre.jit' );
1237 return $res;
1238 }
1239
1240 /**
1241 * @param string $s
1242 * @return array|string
1243 */
1244 private function rmdoubles( $s ) {
1245 // (T385452) Disable JIT for this call, as it breaks sometimes
1246 ini_set( 'pcre.jit', '0' );
1247 $res = preg_replace( '/(.)\1+/us', '\1', $s );
1248 ini_restore( 'pcre.jit' );
1249 return $res;
1250 }
1251
1252 /**
1253 * @param string $s
1254 * @return array|string
1255 */
1256 private function rmwhitespace( $s ) {
1257 return preg_replace( '/\s+/u', '', $s );
1258 }
1259
1260 /**
1261 * @param array $args
1262 * @return AFPData
1263 */
1264 private function funcRMSpecials( $args ) {
1265 $s = $args[0]->toString();
1266
1267 return new AFPData( AFPData::DSTRING, $this->rmspecials( $s ) );
1268 }
1269
1270 /**
1271 * @param array $args
1272 * @return AFPData
1273 */
1274 private function funcRMWhitespace( $args ) {
1275 $s = $args[0]->toString();
1276
1277 return new AFPData( AFPData::DSTRING, $this->rmwhitespace( $s ) );
1278 }
1279
1280 /**
1281 * @param array $args
1282 * @return AFPData
1283 */
1284 private function funcRMDoubles( $args ) {
1285 $s = $args[0]->toString();
1286
1287 return new AFPData( AFPData::DSTRING, $this->rmdoubles( $s ) );
1288 }
1289
1290 /**
1291 * @param array $args
1292 * @return AFPData
1293 */
1294 private function funcNorm( $args ) {
1295 $s = $args[0]->toString();
1296
1297 $s = $this->ccnorm( $s );
1298 $s = $this->rmdoubles( $s );
1299 $s = $this->rmspecials( $s );
1300 $s = $this->rmwhitespace( $s );
1301
1302 return new AFPData( AFPData::DSTRING, $s );
1303 }
1304
1305 /**
1306 * @param array $args
1307 * @return AFPData
1308 */
1309 private function funcSubstr( $args ) {
1310 $s = $args[0]->toString();
1311 $offset = $args[1]->toInt();
1312 $length = isset( $args[2] ) ? $args[2]->toInt() : null;
1313
1314 $result = mb_substr( $s, $offset, $length );
1315
1316 return new AFPData( AFPData::DSTRING, $result );
1317 }
1318
1319 /**
1320 * @param array $args
1321 * @return AFPData
1322 */
1323 private function funcStrPos( $args ) {
1324 $haystack = $args[0]->toString();
1325 $needle = $args[1]->toString();
1326 $offset = isset( $args[2] ) ? $args[2]->toInt() : 0;
1327
1328 // T62203: Keep empty parameters from causing PHP warnings
1329 if ( $needle === '' ) {
1330 return new AFPData( AFPData::DINT, -1 );
1331 }
1332 // Special handling for when the offset is not contained in $haystack. PHP can emit a warning
1333 // or throw an error depending on the version (T285978). TODO Should we also throw?
1334 if ( $offset > mb_strlen( $haystack ) ) {
1335 return new AFPData( AFPData::DINT, -1 );
1336 }
1337 $result = mb_strpos( $haystack, $needle, $offset );
1338
1339 if ( $result === false ) {
1340 $result = -1;
1341 }
1342
1343 return new AFPData( AFPData::DINT, $result );
1344 }
1345
1346 /**
1347 * @param array $args
1348 * @return AFPData
1349 */
1350 private function funcStrReplace( $args ) {
1351 $subject = $args[0]->toString();
1352 $search = $args[1]->toString();
1353 $replace = $args[2]->toString();
1354
1355 return new AFPData( AFPData::DSTRING, str_replace( $search, $replace, $subject ) );
1356 }
1357
1358 /**
1359 * @param array $args
1360 * @param int $position
1361 * @return AFPData
1362 */
1363 private function funcStrReplaceRegexp( $args, int $position ) {
1364 $subject = $args[0]->toString();
1365 $search = $args[1]->toString();
1366 $replace = $args[2]->toString();
1367
1368 $this->checkRegexMatchesEmpty( $args[1], $search, $position );
1369 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1370 $result = @preg_replace(
1371 $this->mungeRegexp( $search ),
1372 $replace,
1373 $subject
1374 );
1375
1376 if ( $result === null ) {
1377 throw new UserVisibleException(
1378 'regexfailure',
1379 $position,
1380 [ $search ]
1381 );
1382 }
1383
1384 return new AFPData( AFPData::DSTRING, $result );
1385 }
1386
1387 /**
1388 * @param array $args
1389 * @return AFPData
1390 */
1391 private function funcStrRegexEscape( $args ) {
1392 $string = $args[0]->toString();
1393
1394 // preg_quote does not need the second parameter, since rlike takes
1395 // care of the delimiter symbol itself
1396 return new AFPData( AFPData::DSTRING, preg_quote( $string ) );
1397 }
1398
1399 /**
1400 * @param array $args
1401 * @return mixed
1402 */
1403 private function funcSetVar( $args ) {
1404 $varName = $args[0]->toString();
1405 $value = $args[1];
1406
1407 $this->setUserVariable( $varName, $value );
1408
1409 return $value;
1410 }
1411
1412 /**
1413 * Checks if $a contains $b
1414 *
1415 * @param AFPData $a
1416 * @param AFPData $b
1417 * @return AFPData
1418 */
1419 private function containmentKeyword( AFPData $a, AFPData $b ) {
1420 $a = $a->toString();
1421 $b = $b->toString();
1422
1423 if ( $a === '' || $b === '' ) {
1424 return new AFPData( AFPData::DBOOL, false );
1425 }
1426
1427 return new AFPData( AFPData::DBOOL, strpos( $a, $b ) !== false );
1428 }
1429
1430 /**
1431 * @param AFPData $a
1432 * @param AFPData $b
1433 * @return AFPData
1434 */
1435 private function keywordIn( AFPData $a, AFPData $b ) {
1436 return $this->containmentKeyword( $b, $a );
1437 }
1438
1439 /**
1440 * @param AFPData $a
1441 * @param AFPData $b
1442 * @return AFPData
1443 */
1444 private function keywordContains( AFPData $a, AFPData $b ) {
1445 return $this->containmentKeyword( $a, $b );
1446 }
1447
1448 /**
1449 * @param AFPData $str
1450 * @param AFPData $pattern
1451 * @return AFPData
1452 */
1453 private function keywordLike( AFPData $str, AFPData $pattern ) {
1454 $str = $str->toString();
1455 $pattern = '#^' . strtr( preg_quote( $pattern->toString(), '#' ), AFPData::WILDCARD_MAP ) . '$#u';
1456 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1457 $result = @preg_match( $pattern, $str );
1458
1459 return new AFPData( AFPData::DBOOL, (bool)$result );
1460 }
1461
1462 /**
1463 * @param AFPData $str
1464 * @param AFPData $regex
1465 * @param int $pos
1466 * @param bool $insensitive
1467 * @return AFPData
1468 * @throws Exception
1469 */
1470 private function keywordRegex( AFPData $str, AFPData $regex, $pos, $insensitive = false ) {
1471 $str = $str->toString();
1472 $pattern = $regex->toString();
1473
1474 $pattern = $this->mungeRegexp( $pattern );
1475
1476 if ( $insensitive ) {
1477 $pattern .= 'i';
1478 }
1479
1480 $this->checkRegexMatchesEmpty( $regex, $pattern, $pos );
1481 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1482 $result = @preg_match( $pattern, $str );
1483 if ( $result === false ) {
1484 throw new UserVisibleException(
1485 'regexfailure',
1486 // Coverage bug
1487 // @codeCoverageIgnoreStart
1488 $pos,
1489 // @codeCoverageIgnoreEnd
1490 [ $pattern ]
1491 );
1492 }
1493
1494 return new AFPData( AFPData::DBOOL, (bool)$result );
1495 }
1496
1497 /**
1498 * @param AFPData $str
1499 * @param AFPData $regex
1500 * @param int $pos
1501 * @return AFPData
1502 */
1503 private function keywordRegexInsensitive( AFPData $str, AFPData $regex, $pos ) {
1504 return $this->keywordRegex( $str, $regex, $pos, true );
1505 }
1506
1507 /**
1508 * @param array $args
1509 * @return AFPData
1510 */
1511 private function castString( $args ) {
1512 return AFPData::castTypes( $args[0], AFPData::DSTRING );
1513 }
1514
1515 /**
1516 * @param array $args
1517 * @return AFPData
1518 */
1519 private function castInt( $args ) {
1520 return AFPData::castTypes( $args[0], AFPData::DINT );
1521 }
1522
1523 /**
1524 * @param array $args
1525 * @return AFPData
1526 */
1527 private function castFloat( $args ) {
1528 return AFPData::castTypes( $args[0], AFPData::DFLOAT );
1529 }
1530
1531 /**
1532 * @param array $args
1533 * @return AFPData
1534 */
1535 private function castBool( $args ) {
1536 return AFPData::castTypes( $args[0], AFPData::DBOOL );
1537 }
1538
1539 /**
1540 * Given a node that we don't need to evaluate, decide what to do with it.
1541 * The nodes passed in will usually be discarded by short-circuit
1542 * evaluation. If we don't allow it, we fully evaluate the node.
1543 *
1544 * @param AFPTreeNode $node
1545 */
1546 private function maybeDiscardNode( AFPTreeNode $node ) {
1547 if ( !$this->mAllowShort ) {
1548 $this->evalNode( $node );
1549 }
1550 }
1551
1552 /**
1553 * Given a regexp in the AF syntax, make it PCRE-compliant (i.e. we need to escape slashes, add
1554 * delimiters and modifiers).
1555 *
1556 * @param string $rawRegexp
1557 * @return string
1558 */
1559 private function mungeRegexp( string $rawRegexp ): string {
1560 $needle = preg_replace( '!(\\\\\\\\)*(\\\\)?/!', '$1\/', $rawRegexp );
1561 return "/$needle/u";
1562 }
1563
1564 /**
1565 * Check whether the provided regex matches the empty string.
1566 * @note This method can generate a PHP notice if the regex is invalid
1567 *
1568 * @param AFPData $regex TODO Can we avoid passing this in?
1569 * @param string $pattern Already munged
1570 * @param int $position
1571 */
1572 private function checkRegexMatchesEmpty( AFPData $regex, string $pattern, int $position ): void {
1573 if ( $regex->getType() === AFPData::DUNDEFINED ) {
1574 // We can't tell, and toString() would return the empty string (T273809)
1575 return;
1576 }
1577 // @phan-suppress-next-next-line PhanParamSuspiciousOrder
1578 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
1579 if ( @preg_match( $pattern, '' ) === 1 ) {
1580 $this->warnings[] = new UserVisibleWarning(
1581 'match-empty-regex',
1582 $position,
1583 []
1584 );
1585 }
1586 }
1587 }