forked from wikimedia/mediawiki-extensions-AbuseFilter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbuseFilter.parser.php
2265 lines (2005 loc) · 53.8 KB
/
AbuseFilter.parser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
Abuse filter parser.
Copyright © Victor Vasiliev, 2008. Based on ideas by Andrew Garrett Distributed under GNU GPL v2 terms.
Types of token:
* T_NONE - special-purpose token
* T_BRACE - ( or )
* T_COMMA - ,
* T_OP - operator like + or ^
* T_NUMBER - number
* T_STRING - string, in "" or ''
* T_KEYWORD - keyword
* T_ID - identifier
* T_STATEMENT_SEPARATOR - ;
* T_SQUARE_BRACKETS - [ or ]
Levels of parsing:
* Entry - catches unexpected characters
* Semicolon - ;
* Set - :=
* Conditionls (IF) - if-then-else-end, cond ? a :b
* BoolOps (BO) - &, |, ^
* CompOps (CO) - ==, !=, ===, !==, >, <, >=, <=
* SumRel (SR) - +, -
* MulRel (MR) - *, /, %
* Pow (P) - **
* BoolNeg (BN) - ! operation
* SpecialOperators (SO) - in and like
* Unarys (U) - plus and minus in cases like -5 or -(2 * +2)
* ListElement (LE) - list[number]
* Braces (B) - ( and )
* Functions (F)
* Atom (A) - return value
*/
class AFPToken {
// Types of tken
const TNone = 'T_NONE';
const TID = 'T_ID';
const TKeyword = 'T_KEYWORD';
const TString = 'T_STRING';
const TInt = 'T_INT';
const TFloat = 'T_FLOAT';
const TOp = 'T_OP';
const TBrace = 'T_BRACE';
const TSquareBracket = 'T_SQUARE_BRACKET';
const TComma = 'T_COMMA';
const TStatementSeparator = 'T_STATEMENT_SEPARATOR';
public $type;
public $value;
public $pos;
public function __construct( $type = self::TNone, $value = null, $pos = 0 ) {
$this->type = $type;
$this->value = $value;
$this->pos = $pos;
}
}
class AFPData {
// Datatypes
const DInt = 'int';
const DString = 'string';
const DNull = 'null';
const DBool = 'bool';
const DFloat = 'float';
const DList = 'list';
// Translation table mapping shell-style wildcards to PCRE equivalents.
// Derived from <http://www.php.net/manual/en/function.fnmatch.php#100207>
private static $wildcardMap = array(
'\*' => '.*',
'\+' => '\+',
'\-' => '\-',
'\.' => '\.',
'\?' => '.',
'\[' => '[',
'\[\!' => '[^',
'\\' => '\\\\',
'\]' => ']',
);
public $type;
public $data;
/**
* @param string $type
* @param null $val
*/
public function __construct( $type = self::DNull, $val = null ) {
$this->type = $type;
$this->data = $val;
}
/**
* @param $var
* @return AFPData
* @throws AFPException
*/
public static function newFromPHPVar( $var ) {
if ( is_string( $var ) ) {
return new AFPData( self::DString, $var );
} elseif ( is_int( $var ) ) {
return new AFPData( self::DInt, $var );
} elseif ( is_float( $var ) ) {
return new AFPData( self::DFloat, $var );
} elseif ( is_bool( $var ) ) {
return new AFPData( self::DBool, $var );
} elseif ( is_array( $var ) ) {
$result = array();
foreach ( $var as $item ) {
$result[] = self::newFromPHPVar( $item );
}
return new AFPData( self::DList, $result );
} elseif ( is_null( $var ) ) {
return new AFPData();
} else {
throw new AFPException(
'Data type ' . gettype( $var ) . ' is not supported by AbuseFilter'
);
}
}
/**
* @return AFPData
*/
public function dup() {
return new AFPData( $this->type, $this->data );
}
/**
* @param $orig AFPData
* @param $target
* @return AFPData
*/
public static function castTypes( $orig, $target ) {
if ( $orig->type == $target ) {
return $orig->dup();
}
if ( $target == self::DNull ) {
return new AFPData();
}
if ( $orig->type == self::DList ) {
if ( $target == self::DBool ) {
return new AFPData( self::DBool, (bool)count( $orig->data ) );
}
if ( $target == self::DFloat ) {
return new AFPData( self::DFloat, floatval( count( $orig->data ) ) );
}
if ( $target == self::DInt ) {
return new AFPData( self::DInt, intval( count( $orig->data ) ) );
}
if ( $target == self::DString ) {
$s = '';
foreach ( $orig->data as $item ) {
$s .= $item->toString() . "\n";
}
return new AFPData( self::DString, $s );
}
}
if ( $target == self::DBool ) {
return new AFPData( self::DBool, (bool)$orig->data );
}
if ( $target == self::DFloat ) {
return new AFPData( self::DFloat, floatval( $orig->data ) );
}
if ( $target == self::DInt ) {
return new AFPData( self::DInt, intval( $orig->data ) );
}
if ( $target == self::DString ) {
return new AFPData( self::DString, strval( $orig->data ) );
}
if ( $target == self::DList ) {
return new AFPData( self::DList, array( $orig ) );
}
}
/**
* @param $value AFPData
* @return AFPData
*/
public static function boolInvert( $value ) {
return new AFPData( self::DBool, !$value->toBool() );
}
/**
* @param $base AFPData
* @param $exponent AFPData
* @return AFPData
*/
public static function pow( $base, $exponent ) {
return new AFPData( self::DFloat, pow( $base->toFloat(), $exponent->toFloat() ) );
}
/**
* @param $a AFPData
* @param $b AFPData
* @return AFPData
*/
public static function keywordIn( $a, $b ) {
$a = $a->toString();
$b = $b->toString();
if ( $a == '' || $b == '' ) {
return new AFPData( self::DBool, false );
}
return new AFPData( self::DBool, strpos( $b, $a ) !== false );
}
/**
* @param $a AFPData
* @param $b AFPData
* @return AFPData
*/
public static function keywordContains( $a, $b ) {
$a = $a->toString();
$b = $b->toString();
if ( $a == '' || $b == '' ) {
return new AFPData( self::DBool, false );
}
return new AFPData( self::DBool, strpos( $a, $b ) !== false );
}
/**
* @param $value
* @param $list
* @return bool
*/
public static function listContains( $value, $list ) {
// Should use built-in PHP function somehow
foreach ( $list->data as $item ) {
if ( self::equals( $value, $item ) ) {
return true;
}
}
return false;
}
/**
* @param $d1 AFPData
* @param $d2 AFPData
* @return bool
*/
public static function equals( $d1, $d2 ) {
return $d1->type != self::DList && $d2->type != self::DList &&
$d1->toString() === $d2->toString();
}
/**
* @param $str AFPData
* @param $pattern AFPData
* @return AFPData
*/
public static function keywordLike( $str, $pattern ) {
$str = $str->toString();
$pattern = '#^' . strtr( preg_quote( $pattern->toString(), '#' ), self::$wildcardMap ) . '$#u';
wfSuppressWarnings();
$result = preg_match( $pattern, $str );
wfRestoreWarnings();
return new AFPData( self::DBool, (bool)$result );
}
/**
* @param $str AFPData
* @param $regex AFPData
* @param $pos
* @param $insensitive bool
* @return AFPData
* @throws Exception
*/
public static function keywordRegex( $str, $regex, $pos, $insensitive = false ) {
$str = $str->toString();
$pattern = $regex->toString();
$pattern = preg_replace( '!(\\\\\\\\)*(\\\\)?/!', '$1\/', $pattern );
$pattern = "/$pattern/u";
if( $insensitive ) {
$pattern .= 'i';
}
$handler = new AFPRegexErrorHandler( $pattern, $pos );
try {
$handler->install();
$result = preg_match( $pattern, $str );
$handler->restore();
} catch ( Exception $e ) {
$handler->restore();
throw $e;
}
return new AFPData( self::DBool, (bool)$result );
}
/**
* @param $str
* @param $regex
* @param $pos
* @return AFPData
*/
public static function keywordRegexInsensitive( $str, $regex, $pos ) {
return self::keywordRegex( $str, $regex, $pos, true );
}
/**
* @param $data AFPData
* @return AFPData
*/
public static function unaryMinus( $data ) {
if ( $data->type == self::DInt ) {
return new AFPData( $data->type, - $data->toInt() );
} else {
return new AFPData( $data->type, - $data->toFloat() );
}
}
/**
* @param $a AFPData
* @param $b AFPData
* @param $op string
* @return AFPData
* @throws AFPException
*/
public static function boolOp( $a, $b, $op ) {
$a = $a->toBool();
$b = $b->toBool();
if ( $op == '|' ) {
return new AFPData( self::DBool, $a || $b );
}
if ( $op == '&' ) {
return new AFPData( self::DBool, $a && $b );
}
if ( $op == '^' ) {
return new AFPData( self::DBool, $a xor $b );
}
throw new AFPException( "Invalid boolean operation: {$op}" ); // Should never happen.
}
/**
* @param $a AFPData
* @param $b AFPData
* @param $op string
* @return AFPData
* @throws AFPException
*/
public static function compareOp( $a, $b, $op ) {
if ( $op == '==' || $op == '=' ) {
return new AFPData( self::DBool, self::equals( $a, $b ) );
}
if ( $op == '!=' ) {
return new AFPData( self::DBool, !self::equals( $a, $b ) );
}
if ( $op == '===' ) {
return new AFPData( self::DBool, $a->type == $b->type && self::equals( $a, $b ) );
}
if ( $op == '!==' ) {
return new AFPData( self::DBool, $a->type != $b->type || !self::equals( $a, $b ) );
}
$a = $a->toString();
$b = $b->toString();
if ( $op == '>' ) {
return new AFPData( self::DBool, $a > $b );
}
if ( $op == '<' ) {
return new AFPData( self::DBool, $a < $b );
}
if ( $op == '>=' ) {
return new AFPData( self::DBool, $a >= $b );
}
if ( $op == '<=' ) {
return new AFPData( self::DBool, $a <= $b );
}
throw new AFPException( "Invalid comparison operation: {$op}" ); // Should never happen
}
/**
* @param $a AFPData
* @param $b AFPData
* @param $op string
* @param $pos
* @return AFPData
* @throws AFPUserVisibleException
* @throws AFPException
*/
public static function mulRel( $a, $b, $op, $pos ) {
// Figure out the type.
if ( $a->type == self::DFloat || $b->type == self::DFloat ||
$a->toFloat() != $a->toString() || $b->toFloat() != $b->toString() ) {
$type = self::DFloat;
$a = $a->toFloat();
$b = $b->toFloat();
} else {
$type = self::DInt;
$a = $a->toInt();
$b = $b->toInt();
}
if ( $op != '*' && $b == 0 ) {
throw new AFPUserVisibleException( 'dividebyzero', $pos, array( $a ) );
}
if ( $op == '*' ) {
$data = $a * $b;
} elseif ( $op == '/' ) {
$data = $a / $b;
} elseif ( $op == '%' ) {
$data = $a % $b;
} else {
throw new AFPException( "Invalid multiplication-related operation: {$op}" ); // Should never happen
}
if ( $type == self::DInt ) {
$data = intval( $data );
} else {
$data = floatval( $data );
}
return new AFPData( $type, $data );
}
/**
* @param $a AFPData
* @param $b AFPData
* @return AFPData
*/
public static function sum( $a, $b ) {
if ( $a->type == self::DString || $b->type == self::DString ) {
return new AFPData( self::DString, $a->toString() . $b->toString() );
} elseif ( $a->type == self::DList && $b->type == self::DList ) {
return new AFPData( self::DList, array_merge( $a->toList(), $b->toList() ) );
} else {
return new AFPData( self::DFloat, $a->toFloat() + $b->toFloat() );
}
}
/**
* @param $a AFPData
* @param $b AFPData
* @return AFPData
*/
public static function sub( $a, $b ) {
return new AFPData( self::DFloat, $a->toFloat() - $b->toFloat() );
}
/** Convert shorteners */
/**
* @throws MWException
* @return mixed
*/
public function toNative() {
switch( $this->type ) {
case self::DBool:
return $this->toBool();
case self::DString:
return $this->toString();
case self::DFloat:
return $this->toFloat();
case self::DInt:
return $this->toInt();
case self::DList:
$input = $this->toList();
$output = array();
foreach( $input as $item ) {
$output[] = $item->toNative();
}
return $output;
case self::DNull:
return null;
default:
throw new MWException( "Unknown type" );
}
}
/**
* @return bool
*/
public function toBool() {
return self::castTypes( $this, self::DBool )->data;
}
/**
* @return string
*/
public function toString() {
return self::castTypes( $this, self::DString )->data;
}
/**
* @return float
*/
public function toFloat() {
return self::castTypes( $this, self::DFloat )->data;
}
/**
* @return int
*/
public function toInt() {
return self::castTypes( $this, self::DInt )->data;
}
public function toList() {
return self::castTypes( $this, self::DList )->data;
}
}
class AFPParserState {
public $pos, $token, $lastInput;
public function __construct( $token, $pos ) {
$this->token = $token;
$this->pos = $pos;
$this->lastInput = AbuseFilterParser::$lastHandledToken;
}
}
class AFPException extends MWException { }
// Exceptions that we might conceivably want to report to ordinary users
// (i.e. exceptions that don't represent bugs in the extension itself)
class AFPUserVisibleException extends AFPException {
/**
* @param string $exception_id
* @param int $position
* @param array $params
*/
function __construct( $exception_id, $position, $params ) {
// Give grep a chance to find the usages:
// abusefilter-exception-unexpectedatend, abusefilter-exception-expectednotfound
// abusefilter-exception-unrecognisedkeyword, abusefilter-exception-unexpectedtoken
// abusefilter-exception-unclosedstring, abusefilter-exception-invalidoperator
// abusefilter-exception-unrecognisedtoken, abusefilter-exception-noparams
// abusefilter-exception-dividebyzero, abusefilter-exception-unrecognisedvar
// abusefilter-exception-notenoughargs, abusefilter-exception-regexfailure
// abusefilter-exception-overridebuiltin, abusefilter-exception-outofbounds
// abusefilter-exception-notlist
$msg = wfMessage(
'abusefilter-exception-' . $exception_id,
array_merge( array( $position ), $params )
)->text();
parent::__construct( $msg );
$this->mExceptionID = $exception_id;
$this->mPosition = $position;
$this->mParams = $params;
}
}
class AFPRegexErrorHandler {
function __construct( $regex, $pos ) {
$this->regex = $regex;
$this->pos = $pos;
}
/**
* @param $errno
* @param $errstr
* @param $errfile
* @param $errline
* @param $context
* @return bool
* @throws AFPUserVisibleException
*/
function handleError( $errno, $errstr, $errfile, $errline, $context ) {
if ( error_reporting() == 0 ) {
return true;
}
throw new AFPUserVisibleException(
'regexfailure',
$this->pos,
array( $errstr, $this->regex )
);
}
function install() {
set_error_handler( array( $this, 'handleError' ) );
}
function restore() {
restore_error_handler();
}
}
class AbuseFilterParser {
public $mParams, $mCode, $mTokens, $mPos, $mCur, $mShortCircuit, $mAllowShort, $mLen;
/**
* @var AbuseFilterVariableHolder
*/
public $mVars;
// length,lcase,ucase,ccnorm,rmdoubles,specialratio,rmspecials,norm,count
static $mFunctions = array(
'lcase' => 'funcLc',
'ucase' => 'funcUc',
'length' => 'funcLen',
'string' => 'castString',
'int' => 'castInt',
'float' => 'castFloat',
'bool' => 'castBool',
'norm' => 'funcNorm',
'ccnorm' => 'funcCCNorm',
'specialratio' => 'funcSpecialRatio',
'rmspecials' => 'funcRMSpecials',
'rmdoubles' => 'funcRMDoubles',
'rmwhitespace' => 'funcRMWhitespace',
'count' => 'funcCount',
'rcount' => 'funcRCount',
'ip_in_range' => 'funcIPInRange',
'contains_any' => 'funcContainsAny',
'substr' => 'funcSubstr',
'strlen' => 'funcLen',
'strpos' => 'funcStrPos',
'str_replace' => 'funcStrReplace',
'rescape' => 'funcStrRegexEscape',
'set' => 'funcSetVar',
'set_var' => 'funcSetVar',
);
// Functions that affect parser state, and shouldn't be cached.
static $ActiveFunctions = array(
'funcSetVar',
);
// Order is important. The punctuation-matching regex requires that
// ** comes before *, etc. They are sorted to make it easy to spot
// such errors.
static $mOps = array(
'!==', '!=', '!', // Inequality
'**', '*', // Multiplication/exponentiation
'/', '+', '-', '%', // Other arithmetic
'&', '|', '^', // Logic
':=', // Setting
'?', ':', // Ternery
'<=', '<', // Less than
'>=', '>', // Greater than
'===', '==', '=', // Equality
);
static $mKeywords = array(
'in', 'like', 'true', 'false', 'null', 'contains', 'matches',
'rlike', 'irlike', 'regex', 'if', 'then', 'else', 'end',
);
static $parserCache = array();
static $funcCache = array();
static $lastHandledToken = array();
/**
* Create a new instance
*
* @param $vars AbuseFilterVariableHolder
*/
public function __construct( $vars = null ) {
$this->resetState();
if ( $vars instanceof AbuseFilterVariableHolder ) {
$this->mVars = $vars;
}
}
public function resetState() {
$this->mParams = array();
$this->mCode = '';
$this->mTokens = array();
$this->mVars = new AbuseFilterVariableHolder;
$this->mPos = 0;
$this->mShortCircuit = false;
$this->mAllowShort = true;
}
/**
* @param $filter
* @return array|bool
*/
public function checkSyntax( $filter ) {
try {
$origAS = $this->mAllowShort;
$this->mAllowShort = false;
$this->parse( $filter );
} catch ( AFPUserVisibleException $excep ) {
$this->mAllowShort = $origAS;
return array( $excep->getMessage(), $excep->mPosition );
}
$this->mAllowShort = $origAS;
return true;
}
/**
* @param $name
* @param $value
*/
public function setVar( $name, $value ) {
$this->mVars->setVar( $name, $value );
}
/**
* @param $vars
*/
public function setVars( $vars ) {
if ( is_array( $vars ) ) {
foreach ( $vars as $name => $var ) {
$this->setVar( $name, $var );
}
} elseif ( $vars instanceof AbuseFilterVariableHolder ) {
$this->mVars->addHolders( $vars );
}
}
/**
* @return AFPToken
*/
protected function move( ) {
wfProfileIn( __METHOD__ );
list( $val, $type, , $offset ) = self::nextToken( $this->mCode, $this->mPos );
$token = new AFPToken( $type, $val, $this->mPos );
$this->mPos = $offset;
wfProfileOut( __METHOD__ );
return $this->mCur = $token;
}
/**
* getState() function allows parser state to be rollbacked to several tokens back
* @return AFPParserState
*/
protected function getState() {
return new AFPParserState( $this->mCur, $this->mPos );
}
/**
* setState() function allows parser state to be rollbacked to several tokens back
* @param AFPParserState $state
*/
protected function setState( AFPParserState $state ) {
$this->mCur = $state->token;
$this->mPos = $state->pos;
self::$lastHandledToken = $state->lastInput;
}
/**
* @return mixed
* @throws AFPUserVisibleException
*/
protected function skipOverBraces() {
if ( !( $this->mCur->type == AFPToken::TBrace && $this->mCur->value == '(' ) || !$this->mShortCircuit ) {
return;
}
$braces = 1;
wfProfileIn( __METHOD__ );
while ( $this->mCur->type != AFPToken::TNone && $braces > 0 ) {
$this->move();
if ( $this->mCur->type == AFPToken::TBrace ) {
if ( $this->mCur->value == '(' ) {
$braces++;
} elseif ( $this->mCur->value == ')' ) {
$braces--;
}
}
}
wfProfileOut( __METHOD__ );
if ( !( $this->mCur->type == AFPToken::TBrace && $this->mCur->value == ')' ) )
throw new AFPUserVisibleException( 'expectednotfound', $this->mCur->pos, array( ')' ) );
}
/**
* @param $code
* @return bool
*/
public function parse( $code ) {
return $this->intEval( $code )->toBool();
}
/**
* @param $filter
* @return string
*/
public function evaluateExpression( $filter ) {
return $this->intEval( $filter )->toString();
}
/**
* @param $code
* @return AFPData
*/
function intEval( $code ) {
// Setup, resetting
$this->mCode = $code;
$this->mPos = 0;
$this->mLen = strlen( $code );
$this->mShortCircuit = false;
$result = new AFPData();
$this->doLevelEntry( $result );
return $result;
}
/**
* @param $a
* @param $b
* @return int
*/
static function lengthCompare( $a, $b ) {
if ( strlen( $a ) == strlen( $b ) ) {
return 0;
}
return ( strlen( $a ) < strlen( $b ) ) ? - 1 : 1;
}
/* Levels */
/**
* Handles unexpected characters after the expression
*
* @param $result AFPData
* @throws AFPUserVisibleException
*/
protected function doLevelEntry( &$result ) {
$this->doLevelSemicolon( $result );
if ( $this->mCur->type != AFPToken::TNone ) {
throw new AFPUserVisibleException( 'unexpectedatend', $this->mCur->pos, array( $this->mCur->type ) );
}
}
/**
* Handles multiple expressions
* @param $result AFPData
*/
protected function doLevelSemicolon( &$result ) {
do {
$this->move();
if ( $this->mCur->type != AFPToken::TStatementSeparator ) {
$this->doLevelSet( $result );
}
} while ( $this->mCur->type == AFPToken::TStatementSeparator );
}
/**
* Handles multiple expressions
*
* @param $result AFPData
* @throws AFPUserVisibleException
*/
protected function doLevelSet( &$result ) {
if ( $this->mCur->type == AFPToken::TID ) {
$varname = $this->mCur->value;
$prev = $this->getState();
$this->move();
if ( $this->mCur->type == AFPToken::TOp && $this->mCur->value == ':=' ) {
$this->move();
$this->doLevelSet( $result );
$this->setUserVariable( $varname, $result );
return;
} elseif ( $this->mCur->type == AFPToken::TSquareBracket && $this->mCur->value == '[' ) {
if ( !$this->mVars->varIsSet( $varname ) ) {
throw new AFPUserVisibleException( 'unrecognisedvar',
$this->mCur->pos,
array( $varname )
);
}
$list = $this->mVars->getVar( $varname );
if ( $list->type != AFPData::DList ) {
throw new AFPUserVisibleException( 'notlist', $this->mCur->pos, array() );
}
$list = $list->toList();
$this->move();
if ( $this->mCur->type == AFPToken::TSquareBracket && $this->mCur->value == ']' ) {
$idx = 'new';
} else {
$this->setState( $prev );
$this->move();
$idx = new AFPData();
$this->doLevelSemicolon( $idx );
$idx = $idx->toInt();
if ( !( $this->mCur->type == AFPToken::TSquareBracket && $this->mCur->value == ']' ) ) {
throw new AFPUserVisibleException( 'expectednotfound', $this->mCur->pos,
array( ']', $this->mCur->type, $this->mCur->value ) );
}
if ( count( $list ) <= $idx ) {
throw new AFPUserVisibleException( 'outofbounds', $this->mCur->pos,
array( $idx, count( $result->data ) ) );
}
}
$this->move();
if ( $this->mCur->type == AFPToken::TOp && $this->mCur->value == ':=' ) {
$this->move();
$this->doLevelSet( $result );
if ( $idx === 'new' ) {
$list[] = $result;
} else {
$list[$idx] = $result;
}
$this->setUserVariable( $varname, new AFPData( AFPData::DList, $list ) );
return;
} else {
$this->setState( $prev );
}
} else {
$this->setState( $prev );
}
}
$this->doLevelConditions( $result );
}
/**
* @param $result AFPData
* @throws AFPUserVisibleException
*/
protected function doLevelConditions( &$result ) {
if ( $this->mCur->type == AFPToken::TKeyword && $this->mCur->value == 'if' ) {
$this->move();
$this->doLevelBoolOps( $result );
if ( !( $this->mCur->type == AFPToken::TKeyword && $this->mCur->value == 'then' ) )
throw new AFPUserVisibleException( 'expectednotfound',
$this->mCur->pos,
array(
'then',
$this->mCur->type,
$this->mCur->value
)
);
$this->move();
$r1 = new AFPData();
$r2 = new AFPData();
$isTrue = $result->toBool();
if ( !$isTrue ) {
$scOrig = $this->mShortCircuit;
$this->mShortCircuit = $this->mAllowShort;
}
$this->doLevelConditions( $r1 );
if ( !$isTrue ) {
$this->mShortCircuit = $scOrig;
}
if ( !( $this->mCur->type == AFPToken::TKeyword && $this->mCur->value == 'else' ) )
throw new AFPUserVisibleException( 'expectednotfound',
$this->mCur->pos,
array(
'else',
$this->mCur->type,
$this->mCur->value
)
);
$this->move();
if ( $isTrue ) {
$scOrig = $this->mShortCircuit;
$this->mShortCircuit = $this->mAllowShort;
}
$this->doLevelConditions( $r2 );
if ( $isTrue ) {
$this->mShortCircuit = $scOrig;
}
if ( !( $this->mCur->type == AFPToken::TKeyword && $this->mCur->value == 'end' ) )
throw new AFPUserVisibleException( 'expectednotfound',
$this->mCur->pos,
array(
'end',
$this->mCur->type,
$this->mCur->value
)
);
$this->move();
if ( $result->toBool() ) {
$result = $r1;
} else {
$result = $r2;
}
} else {
$this->doLevelBoolOps( $result );
if ( $this->mCur->type == AFPToken::TOp && $this->mCur->value == '?' ) {
$this->move();
$r1 = new AFPData();
$r2 = new AFPData();
$isTrue = $result->toBool();
if ( !$isTrue ) {
$scOrig = $this->mShortCircuit;
$this->mShortCircuit = $this->mAllowShort;