-
Notifications
You must be signed in to change notification settings - Fork 38
/
Calc.pm
2283 lines (2004 loc) · 63 KB
/
Calc.pm
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
# See bottom of file for license and copyright information
#
# This is part of Foswiki's Spreadsheet Plugin.
#
# The code below is kept out of the main plugin module for
# performance reasons, so it doesn't get compiled until it
# is actually used.
package Foswiki::Plugins::SpreadSheetPlugin::Calc;
use strict;
use warnings;
use HTML::Entities;
use Time::Local;
use Time::Local qw( timegm_nocheck timelocal_nocheck ); # Necessary for DOY
# =========================
my $web;
my $topic;
my $debug;
my @tableMatrix;
my $cPos;
my $rPos;
my $escToken = "\0";
my $escComma =
"\1"; # Single char escapes so that size functions work as expected
my $escOpenP = "\2";
my $escCloseP = "\3";
my $escNewLn = "\4";
my %varStore = ();
my $dontSpaceRE = "";
# SMELL: I18N
my @monArr = (
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
);
my @wdayArr = (
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
);
my %mon2num;
{
my $count = 0;
%mon2num = map { $_ => $count++ } @monArr;
}
my $recurseFunc = \&_recurseFunc;
my $allowHTML;
# =========================
sub init {
( $web, $topic, $debug ) = @_;
# initialize variables, once per page view
%varStore = ();
$dontSpaceRE = "";
$allowHTML =
Foswiki::Func::getPreferencesFlag("SPREADSHEETPLUGIN_ALLOWHTML");
# Module initialized
Foswiki::Func::writeDebug(
"- Foswiki::Plugins::SpreadSheetPlugin::Calc::init( $web.$topic )")
if $debug;
return 1;
}
# =========================
sub CALC {
### my ( $text, $topic, $web ) = @_; # do not uncomment, use $_[0], $_[1]... instead
Foswiki::Func::writeDebug("- SpreadSheetPlugin::Calc::CALC( $_[2].$_[1] )")
if $debug;
@tableMatrix = ();
$cPos = -1;
$rPos = -1;
$web = $_[2];
my @result = ();
my $insidePRE = 0;
my $insideTABLE = 0;
my $line = "";
my $before = "";
my $cell = "";
my @row = ();
$_[0] =~ s/\r//g;
$_[0] =~ s/\\\n//g; # Join lines ending in "\"
foreach ( split( /\n/, $_[0] ) ) {
# change state:
m|<pre>|i && ( $insidePRE = 1 );
m|<verbatim>|i && ( $insidePRE = 1 );
m|</pre>|i && ( $insidePRE = 0 );
m|</verbatim>|i && ( $insidePRE = 0 );
if ( !($insidePRE) ) {
if (/^\s*\|.*\|\s*$/) {
# inside | table |
if ( !$insideTABLE ) {
$insideTABLE = 1;
@tableMatrix = (); # reset table matrix
$cPos = -1;
$rPos = -1;
}
$line = $_;
$line =~ s/^(\s*\|)(.*)\|\s*$/$2/;
$before = $1;
@row = split( /\|/, $line, -1 );
$row[0] = '' unless @row; # See Item5163
push( @tableMatrix, [@row] );
$rPos++;
$line = "$before";
for ( $cPos = 0 ; $cPos < @row ; $cPos++ ) {
$cell = $row[$cPos];
$cell =~ s/%CALC\{(.*?)\}%/_doCalc($1)/ge;
$line .= "$cell|";
}
s/.*/$line/;
}
else {
# outside | table |
if ($insideTABLE) {
$insideTABLE = 0;
}
s/%CALC\{(.*?)\}%/_doCalc($1)/ge;
}
}
push( @result, $_ );
}
$_[0] = join( "\n", @result );
return $_[0];
}
# =========================
sub _doCalc {
my ($theAttributes) = @_;
my $text = &Foswiki::Func::extractNameValuePair($theAttributes);
# Escape commas, parenthesis and newlines in tripple quoted strings
$text =~ s/'''(.*?)'''/_escapeString($1)/ges;
# For better performance, use a function reference when calling the recurse
# functions, instead of an "if" statement within the &$recurseFunc function
if ( $text =~ /\n/ ) {
# recursively evaluate functions, and remove white space around functions and parameters
$recurseFunc = \&_recurseFuncCutWhitespace;
}
else {
# recursively evaluate functions without removing white space (compatible with old spec)
$recurseFunc = \&_recurseFunc;
}
# Add nesting level to parenthesis,
# e.g. "A(B())" gets "A-esc-1(B-esc-2(-esc-2)-esc-1)"
my $level = 0;
$text =~ s/([\(\)])/_addNestingLevel($1, \$level)/ge;
$text = _doFunc( "MAIN", $text );
if ( defined($rPos) && defined($cPos) && $rPos >= 0 && $cPos >= 0 ) {
# update cell in table matrix
$tableMatrix[$rPos][$cPos] = $text;
}
# Restore escaped strings
$text =~ s/$escComma/,/g;
$text =~ s/$escOpenP/\(/g;
$text =~ s/$escCloseP/\)/g;
$text =~ s/$escNewLn/\n/g;
unless ($allowHTML) {
# encode < > to prevent html insertion
# SMELL: what about '"%
$text =~ s/([<>])/HTML::Entities::encode_entities($1)/ge;
}
return $text;
}
# =========================
sub _escapeString {
my ($text) = @_;
$text =~ s/,/$escComma/g;
$text =~ s/\(/$escOpenP/g;
$text =~ s/\)/$escCloseP/g;
$text =~ s/\n/$escNewLn/g;
return $text;
}
# =========================
sub _addNestingLevel {
my ( $theParen, $theLevelRef ) = @_;
my $result = "";
if ( $theParen eq "(" ) {
$$theLevelRef++;
$result = "$escToken$$theLevelRef$theParen";
}
else {
$result = "$escToken$$theLevelRef$theParen";
$$theLevelRef--;
}
return $result;
}
# =========================
sub _recurseFunc {
# Handle functions recursively
no warnings 'uninitialized';
$_[0] =~
s/\$([A-Z]+[A-Z0-9]*)$escToken([0-9]+)\((.*?)$escToken\2\)/_doFunc($1,$3)/geos;
use warnings 'uninitialized';
# Clean up unbalanced mess
$_[0] =~ s/$escToken\-*[0-9]+([\(\)])/$1/go;
}
# =========================
sub _recurseFuncCutWhitespace {
# Handle functions recursively
$_[0] =~
s/\s*\$([A-Z]+[A-Z0-9]*)$escToken([0-9]+)\(\s*(.*?)\s*$escToken\2\)\s*/_doFunc($1,$3)/geos;
# Clean up unbalanced mess
$_[0] =~ s/$escToken\-*[0-9]+([\(\)])/$1/go;
}
#<<< do not let perltidy touch this
# Commented functions new in TWiki
my $Function = {
ABOVE => sub { my $i = $cPos + 1; return "R1:C$i..R$rPos:C$i" },
ABS => sub { abs( _getNumber($_[0]) ) },
# ADDLIST
AND => \&_AND,
AVERAGE => \&_AVERAGE,
BIN2DEC => \&_BIN2DEC,
BITXOR => \&_BITXOR,
CEILING => \&_CEILING,
CHAR => \&_CHAR,
CODE => sub { ord($_[0]) },
COLUMN => sub { $cPos + ( $_[0] || 0 ) + 1 },
COUNTITEMS => \&_COUNTITEMS,
COUNTSTR => \&_COUNTSTR,
DEC2BIN => \&_DEC2BIN,
DEC2HEX => \&_DEC2HEX,
DEC2OCT => \&_DEC2OCT,
DEF => \&_DEF,
EMPTY => sub { ( length($_[0]) ) ? 0 : 1 },
EVAL => sub { _safeEvalPerl($_[0]) },
EVEN => sub { ( _getNumber($_[0]) + 1 ) % 2 },
EXACT => \&_EXACT,
EXEC => \&_EXEC,
EXISTS => sub { ( Foswiki::Func::topicExists( $web, $_[0] ) ) ? 1 : 0 },
EXP => sub { exp( _getNumber($_[0]) ) },
FILTER => \&_FILTER,
FIND => \&_FIND,
FLOOR => \&_FLOOR,
FORMAT => \&_FORMAT,
FORMATGMTIME => \&_FORMATGMTIME,
FORMATTIME => \&_FORMATTIME,
FORMATTIMEDIFF => \&_FORMATTIMEDIFF,
GET => \&_GET,
# GETHASH
# GETLIST - Get a saved list
# HASH2LIST - Convert hash to list
# HASHCOPY - Copy a hash
# HASHEACH - Evaluate & update each element
# HASHEXISTS - Test if hash exists
# HASHREVERSE - Swap keys and values
HEX2DEC => \&_HEX2DEC,
HEXDECODE => \&_HEXDECODE,
HEXENCODE => sub { uc( unpack( "H*", $_[0] ) ) },
IF => \&_IF,
INSERTSTRING => \&_INSERTSTRING,
INT => sub {
my $rslt = _safeEvalPerl($_[0]);
return ( $rslt =~ /^ERROR/ ) ? $rslt : int( _getNumber($rslt) );
},
ISDIGIT => sub { ($_[0] =~ m/^[[:digit:]]+$/ ) ? 1 : 0 },
ISLOWER => sub { ($_[0] =~ m/^[[:lower:]]+$/ ) ? 1 : 0 },
ISUPPER => sub { ($_[0] =~ m/^[[:upper:]]+$/ ) ? 1 : 0 },
ISWIKIWORD => sub { (Foswiki::isValidWikiWord( $_[0] ) ) ? 1 : 0 },
LEFT => sub { my $i = $rPos + 1; return "R$i:C1..R$i:C$cPos" },
LEFTSTRING => \&_LEFTSTRING,
LENGTH => sub { length( $_[0] ) },
LIST => sub { _listToDelimitedString(_getList($_[0])) },
# LIST2HASH
LISTEACH => \&_LISTMAP,
LISTIF => \&_LISTIF,
LISTITEM => \&_LISTITEM,
LISTJOIN => \&_LISTJOIN,
LISTMAP => \&_LISTMAP,
LISTNONEMPTY => sub { _listToDelimitedString( grep { /./ } _getList($_[0]) ) },
LISTRAND => \&_LISTRAND,
LISTREVERSE => sub { _listToDelimitedString(reverse _getList($_[0])) },
LISTSHUFFLE => \&_LISTSHUFFLE,
LISTSIZE => sub { scalar( _getList($_[0])) },
LISTSORT => \&_LISTSORT,
LISTTRUNCATE => \&_LISTTRUNCATE,
LISTUNIQUE => \&_LISTUNIQUE,
LN => sub { log( _getNumber($_[0]) ) },
LOG => \&_LOG,
LOWER => sub { lc( $_[0] ) },
MAIN => sub { $_[0] },
MAX => \&_MAX,
MEDIAN => \&_MEDIAN,
MIN => \&_MIN,
MOD => \&_MOD,
NOEXEC => sub { $_[0] },
NOP => \&_NOP,
NOT => sub { ( _getNumber( $_[0] )) ? 0 : 1 },
OCT2DEC => \&_OCT2DEC,
ODD => sub { _getNumber( $_[0] ) % 2 },
OR => \&_OR,
PERCENTILE => \&_PERCENTILE,
PI => sub { 3.1415926535897932384 },
PRODUCT => \&_PRODUCT,
PROPER => sub {
$_[0] =~ s/(\w+)/\u\L$1/g;
return $_[0];
},
PROPERSPACE => sub { _properSpace($_[0]) },
RAND => sub {
my $max = _getNumber($_[0]);
$max = 1 if ( $max <= 0 );
rand($max);
},
RANDSTRING => \&_RANDSTRING,
REPEAT => \&_REPEAT,
REPLACE => \&_REPLACE,
RIGHT => sub {
my $i = $rPos + 1;
my $c = $cPos + 2;
return "R$i:C$c..R$i:C32000";
},
RIGHTSTRING => \&_RIGHTSTRING,
ROUND => \&_ROUND,
ROW => sub { $rPos + ( $_[0] || 0 ) + 1 },
SEARCH => \&_SEARCH,
SET => \&_SET,
# SETHASH - Set a hash for later use
SETIFEMPTY => \&_SETIFEMPTY,
# SETLIST - Save a list for later use
SETM => \&_SETM,
# SETMHASH - Modify a hash
SIGN => sub {
my $i = _getNumber($_[0]);
return ( $i > 0 ) ? 1
: ( $i < 0 ) ? -1
: 0;
},
SPLIT => \&_SPLIT,
SQRT => sub { sqrt( _getNumber( $_[0] ) ) },
# STDEV - Std. Deviation
# STDEVP - Std. Deviation population
SUBSTITUTE => \&_SUBSTITUTE,
SUBSTRING => \&_SUBSTRING,
SUM => \&_SUM,
SUMDAYS => \&_SUMDAYS,,
SUMPRODUCT => \&_SUMPRODUCT,
T => \&_T,
TIME => \&_TIME,
TIMEADD => \&_TIMEADD,
TIMEDIFF => \&_TIMEDIFF,
TODAY => sub { _date2serial( _serial2date( time(), '$year/$month/$day GMT', 1 ) ) },
TRANSLATE => \&_TRANSLATE,
TRIM => sub {
$_[0] =~ s/^\s*//;
$_[0] =~ s/\s*$//;
$_[0] =~ s/\s+/ /g;
return $_[0];
},
UPPER => sub { uc( $_[0] ) },
VALUE => sub { _getNumber( $_[0] ) },
# VAR - Variance sample
# VARP - Variance population
WHILE => \&_WHILE,
WORKINGDAYS => sub {
my ($stime, $etime) = split( /,\s*/, $_[0], 2);
_workingDays( _getNumber($stime), _getNumber($etime));
},
XOR => \&_XOR,
};
#>>>
$Function->{MIDSTRING} = $Function->{SUBSTRING}; # MIDSTRING Undocumented
$Function->{DURATION} = $Function->{SUMDAYS}; # DURATION undocumented, for Sven
$Function->{MULT} = $Function->{PRODUCT}; # MULT deprecated
$Function->{MEAN} = $Function->{AVERAGE}; # # Both documented & supported
sub _doFunc {
my ( $theFunc, $theAttr ) = @_;
$theAttr = "" unless ( defined $theAttr );
Foswiki::Func::writeDebug(
"- SpreadSheetPlugin::Calc::_doFunc: $theFunc( $theAttr ) start")
if $debug;
unless ( $theFunc =~ /^(IF|LISTEACH|LISTIF|LISTMAP|NOEXEC|WHILE)$/ ) {
&$recurseFunc($theAttr);
}
# else: delay the function handler to after parsing the parameters,
# in which case handling functions and cleaning up needs to be done later
my $result = "";
my $i = 0;
# Execute functions defined in the above $Function hash
if ( defined $Function->{$theFunc} ) {
my $f = $Function->{$theFunc};
$result = &$f($theAttr);
}
Foswiki::Func::writeDebug(
"- SpreadSheetPlugin::Calc::_doFunc: $theFunc( $theAttr ) returns: $result"
) if $debug;
return $result;
}
#########################
# Spreadsheet Cells
#########################
# ======================
sub _T {
my @arr = _getTableRange("$_[0]..$_[0]");
return (@arr) ? $arr[0] : '';
}
# ======================
sub _DEF {
# Format DEF(list) returns first defined cell
# Added by MF 26/3/2002, fixed by PeterThoeny
my $result = '';
my @arr = _getList( $_[0] );
foreach my $cell (@arr) {
if ($cell) {
$cell =~ s/^\s*(.*?)\s*$/$1/;
if ($cell) {
$result = $cell;
last;
}
}
}
return $result;
}
#########################
# Conditional and Looping
#########################
# ======================
sub _EXEC {
# add nesting level escapes
my $level = 0;
$_[0] =~ s/([\(\)])/_addNestingLevel($1, \$level)/ge;
# execute functions in attribute recursively and clean up unbalanced parenthesis
&$recurseFunc( $_[0] );
return $_[0];
}
# =======================
sub _IF {
# IF(condition, value if true, value if false)
my ( $condition, $str1, $str2 ) = _properSplit( $_[0], 3 );
# with delay, handle functions in condition recursively and clean up unbalanced parenthesis
&$recurseFunc($condition);
$condition =~ s/^\s*(.*?)\s*$/$1/;
my $result = _safeEvalPerl($condition);
unless ( $result =~ /^ERROR/ ) {
if ($result) {
$result = $str1;
}
else {
$result = $str2;
}
$result = "" unless ( defined($result) );
# with delay, handle functions in result recursively and clean up unbalanced parenthesis
&$recurseFunc($result);
} # else return error message
return $result;
}
# =========================
sub _NOP {
# pass everything through, this will allow plugins to defy plugin order
# for example the %SEARCH{}% variable
$_[0] =~ s/\$per(cnt)?/%/g;
$_[0] =~ s/\$quot/"/g;
return $_[0];
}
# ===========================
sub _WHILE {
# WHILE(condition, do something)
my ( $condition, $str ) = _properSplit( $_[0], 2 );
return '' unless defined $condition;
my $result;
my $i = 0;
while (1) {
if ( $i++ >= 32767 ) {
$result .= 'ERROR: Infinite loop (32767 cycles)';
last; # prevent infinite loop
}
# with delay, handle functions in condition recursively and clean up unbalanced parenthesis
my $cond = $condition;
$cond =~ s/\$counter/$i/g;
&$recurseFunc($cond);
$cond =~ s/^\s*(.*?)\s*$/$1/;
my $res = _safeEvalPerl($cond);
if ( $res =~ /^ERROR/ ) {
$result .= $res;
last; # exit loop and return error
}
last unless ($res); # proper loop exit
$res = $str;
$res = "" unless ( defined($res) );
# with delay, handle functions in result recursively and clean up unbalanced parenthesis
$res =~ s/\$counter/$i/g;
&$recurseFunc($res);
$result .= $res;
}
return $result;
}
#######################
# Numeric Functions
#######################
# =========================
sub _AVERAGE {
my $result = 0;
my $items = 0;
my @arr = _getListAsFloat( $_[0] );
foreach my $i (@arr) {
if ( defined $i ) {
$result += $i;
$items++;
}
}
if ( $items > 0 ) {
$result = $result / $items;
}
return $result;
}
# =========================
sub _CEILING {
my $i = _getNumber( $_[0] );
my $result = int($i);
if ( $i > 0 && $i != $result ) {
$result += 1;
}
return $result;
}
# =========================
sub _BIN2DEC {
$_[0] =~ s/[^0-1]//g; # only binary digits
$_[0] ||= 0;
return oct( '0b' . $_[0] );
}
# =========================
sub _DEC2BIN {
my ( $num, $size ) = _getListAsInteger( $_[0] );
$num ||= 0;
my $format = '%';
$format .= '0' . $size if ($size);
$format .= 'b';
return sprintf( $format, $num );
}
# =========================
sub _HEX2DEC {
$_[0] =~ s/[^0-9A-Fa-f]//g; # only hex numbers
$_[0] ||= 0;
return hex( $_[0] );
}
# =========================
sub _DEC2HEX {
my ( $num, $size ) = _getListAsInteger( $_[0] );
$num ||= 0;
my $format = '%';
$format .= '0' . $size if ($size);
$format .= 'X';
return sprintf( $format, $num );
}
# =========================
sub _OCT2DEC {
$_[0] =~ s/[^0-7]//g; # only octal digits
$_[0] ||= 0;
return oct( $_[0] );
}
# =========================
sub _DEC2OCT {
my ( $num, $size ) = _getListAsInteger( $_[0] );
$num ||= 0;
my $format = '%';
$format .= '0' . $size if ($size);
$format .= 'o';
return sprintf( $format, $num );
}
# =========================
sub _FLOOR {
my $i = _getNumber( $_[0] );
my $result = int($i);
if ( $i < 0 && $i != $result ) {
$result -= 1;
}
return $result;
}
# =====================
sub _FORMAT {
# Format FORMAT(TYPE, precision, value) returns formatted value -- JimStraus - 05 Jan 2003
my ( $format, $res, $value ) = split( /,\s*/, $_[0] );
$format =~ s/^\s*(.*?)\s*$/$1/; #Strip leading and trailing spaces
$res =~ s/^\s*(.*?)\s*$/$1/;
$value =~ s/^\s*(.*?)\s*$/$1/;
$res =~ m/^(.*)$/; # SMELL why do we need to untaint
$res = $1;
my $result = '';
if ( $format eq "DOLLAR" ) {
my $neg = 0;
$neg = 1 if $value < 0;
$value = abs($value);
$result = sprintf( "%0.${res}f", $value );
my $temp = reverse $result;
$temp =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
$result = "\$" . ( scalar( reverse($temp) ) );
$result = "(" . $result . ")" if $neg;
}
# TWIKI: Added CURRENCY format
elsif ( $format eq "COMMA" ) {
$result = sprintf( "%0.${res}f", $value );
my $temp = reverse $result;
$temp =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
$result = scalar( reverse($temp) );
}
elsif ( $format eq "PERCENT" ) {
$result = sprintf( "%0.${res}f%%", $value * 100 );
}
elsif ( $format eq "NUMBER" ) {
$result = sprintf( "%0.${res}f", $value );
}
elsif ( $format eq "K" ) {
$result = sprintf( "%0.${res}f K", $value / 1024 );
}
elsif ( $format eq "KB" ) {
$result = sprintf( "%0.${res}f KB", $value / 1024 );
}
elsif ( $format eq "MB" ) {
$result = sprintf( "%0.${res}f MB", $value / ( 1024 * 1024 ) );
}
elsif ( $format =~ /^KBMB/ ) {
$value /= 1024;
my @lbls = ( "MB", "GB", "TB", "PB", "EB", "ZB" );
my $lbl = "KB";
while ( $value >= 1024 && @lbls ) {
$value /= 1024;
$lbl = shift @lbls;
}
$result = sprintf( "%0.${res}f", $value ) . " $lbl";
}
else {
# FORMAT not recognized, just return value
$result = $value;
}
return $result;
}
# =========================
sub _HEXDECODE {
my $theAttr = shift;
$theAttr =~ s/[^0-9A-Fa-f]//g; # only hex numbers
$theAttr =~ s/.$// if ( length($theAttr) % 2 ); # must be set of two
return pack( "H*", $theAttr );
}
# =======================
sub _LOG {
my ( $num, $base ) = split( /,\s*/, $_[0], 2 );
$num = _getNumber($num);
$base = _getNumber($base);
$base = 10 if ( $base <= 0 );
return log($num) / log($base);
}
# =========================
sub _MAX {
my @arr = sort { $a <=> $b }
grep { /./ }
grep { defined $_ } _getListAsFloat( $_[0] );
return $arr[-1];
}
# =========================
sub _MEDIAN {
my @arr =
sort { $a <=> $b } grep { defined $_ } _getListAsFloat( $_[0] );
my $i = @arr;
my $result = '';
if ( ( $i % 2 ) > 0 ) {
$result = $arr[ $i / 2 ];
}
elsif ($i) {
$i /= 2;
$result = ( $arr[$i] + $arr[ $i - 1 ] ) / 2;
}
return $result;
}
# =========================
sub _MIN {
my @arr = sort { $a <=> $b }
grep { /./ }
grep { defined $_ } _getListAsFloat( $_[0] );
return $arr[0];
}
# =======================
sub _MOD {
my $result = 0;
my ( $num1, $num2 ) = split( /,\s*/, $_[0], 2 );
$num1 = _getNumber($num1);
$num2 = _getNumber($num2);
if ( $num1 && $num2 ) {
$result = $num1 % $num2;
}
return $result;
}
# =========================
sub _PERCENTILE {
my ( $percentile, $set ) = split( /,\s*/, $_[0], 2 );
my $i;
my @arr = sort { $a <=> $b } grep { defined $_ } _getListAsFloat($set);
my $result = 0;
my $size = scalar(@arr);
if ( $size > 0 ) {
$i = $percentile / 100 * ( $size + 1 );
my $iInt = int($i);
if ( $i <= 1 ) {
$result = $arr[0];
}
elsif ( $i >= $size ) {
$result = $arr[ $size - 1 ];
}
elsif ( $i == $iInt ) {
$result = $arr[ $i - 1 ];
}
else {
# interpolate beween neighbors # Example: $i = 7.25
my $r1 = $iInt + 1 - $i; # 0.75 = 7 + 1 - 7.25
my $r2 = 1 - $r1; # 0.25 = 1 - 0.75
my $x1 = $arr[ $iInt - 1 ];
my $x2 = $arr[$iInt];
$result = ( $r1 * $x1 ) + ( $r2 * $x2 );
}
}
return $result;
}
# =========================
sub _PRODUCT {
my $result = 0;
my @arr = _getListAsFloat( $_[0] );
# no arguments, return 0.
return 0 unless scalar @arr;
$result = 1;
foreach my $i (@arr) {
$result *= $i if defined $i;
}
return $result;
}
# =========================
sub _ROUND {
# ROUND(num, digits)
my ( $num, $digits ) = split( /,\s*/, $_[0], 2 );
my $result = _safeEvalPerl($num);
unless ( $result =~ /^ERROR/ ) {
$result = _getNumber($result);
if ( ($digits)
&& ( $digits =~ s/^.*?(\-?[0-9]+).*$/$1/ )
&& ($digits) )
{
my $factor = 10**$digits;
$result *= $factor;
( $result >= 0 ) ? ( $result += 0.5 ) : ( $result -= 0.5 );
$result = int($result);
$result /= $factor;
}
else {
( $result >= 0 ) ? ( $result += 0.5 ) : ( $result -= 0.5 );
$result = int($result);
}
}
return $result;
}
# =========================
sub _SUM {
my $result = 0;
my @arr = _getListAsFloat( $_[0] );
foreach my $i (@arr) {
$result += $i if defined $i;
}
return $result;
}
# =========================
sub _SUMPRODUCT {
my $result = 0;
my @arr;
my @lol = split( /,\s*/, $_[0] );
my $size = 32000;
for my $i ( 0 .. $#lol ) {
@arr = _getListAsFloat( $lol[$i] );
$lol[$i] = [@arr]; # store reference to array
$size = @arr if ( @arr < $size ); # remember smallest array
}
if ( ( $size > 0 ) && ( $size < 32000 ) ) {
my $y;
my $prod;
my $val;
$size--;
for my $y ( 0 .. $size ) {
$prod = 1;
for my $i ( 0 .. $#lol ) {
$val = $lol[$i][$y];
if ( defined $val ) {
$prod *= $val;
}
else {
$prod = 0; # don't count empty cells
}
}
$result += $prod;
}
}
return $result;
}
#######################
# GET / SET Functions
#######################
# =========================
sub _GET {
my $name = $_[0];
$name =~ s/[^a-zA-Z0-9\_]//g;
my $result = $varStore{$name} if ($name);
$result = "" unless ( defined($result) );
return $result;
}
# =========================
sub _SET {
my ( $name, $value ) = split( /,\s*/, $_[0], 2 );
return '' unless defined $name;
$name =~ s/[^a-zA-Z0-9\_]//g;
if ( $name && defined($value) ) {
$value =~ s/\s*$//;
$varStore{$name} = $value;
}
return '';
}
# =========================
sub _SETIFEMPTY {
my ( $name, $value ) = split( /,\s*/, $_[0], 2 );
return '' unless defined $name;
$name =~ s/[^a-zA-Z0-9\_]//g;
if ( $name && defined($value) && !$varStore{$name} ) {
$value =~ s/\s*$//;
$varStore{$name} = $value;
}
return '';
}
# =========================
sub _SETM {
my ( $name, $value ) = split( /,\s*/, $_[0], 2 );
return '' unless defined $name;
$name =~ s/[^a-zA-Z0-9\_]//g;
if ($name) {
my $old = $varStore{$name};
$old = "" unless ( defined($old) );
$value = "" unless ( defined($value) );
$value = _safeEvalPerl("$old $value");
$varStore{$name} = $value;
}
return '';
}
#######################
# LIST Functions
#######################
# =====================
sub _COUNTITEMS {
my $result = '';
my @arr = _getList( $_[0] );
my %items = ();
foreach my $key (@arr) {
$key =~ s/^\s*(.*?)\s*$/$1/ if ($key);
if ($key) {
if ( exists( $items{$key} ) ) {
$items{$key}++;
}
else {
$items{$key} = 1;
}
}
}
foreach my $key ( sort keys %items ) {
$result .= "$key: $items{ $key }%BR% ";
}
$result =~ s|%BR% $||;
return $result;
}
# =========================
# LISTIF(cmd, item 1, item 2, ...)
#
sub _LISTIF {
my ( $cmd, $str ) = _properSplit( $_[0], 2 );
$cmd = "" unless ( defined($cmd) );
$cmd =~ s/^\s*(.*?)\s*$/$1/;
$str = "" unless ( defined($str) );
# with delay, handle functions in result $str and clean up unbalanced parenthesis
&$recurseFunc($str);
my $item = qw{};
my $eval = qw{};
my $i = 0;
my @arr =
grep { !/^FOSWIKI_GREP_REMOVE$/ }
map {
$item = $_;
$_ = $cmd;
$i++;
s/\$index/$i/g;
s/\$item/$item/g;
&$recurseFunc($_);
$eval = _safeEvalPerl($_);
if ( $eval =~ /^ERROR/ ) {
$_ = $eval;
}
elsif ($eval) {
$_ = $item;
}
else {