/
Search.pm
1222 lines (1003 loc) · 40.2 KB
/
Search.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
package Foswiki::Search;
=begin TML
---+ package Foswiki::Search
This module implements all the search functionality.
=cut
use strict;
use Assert;
use Error qw( :try );
use Foswiki ();
use Foswiki::Sandbox ();
use Foswiki::Search::InfoCache ();
use Foswiki::ListIterator ();
use Foswiki::Iterator::FilterIterator ();
use Foswiki::WebFilter ();
#TODO: move these into a more appropriate place - they are function objects so can persist for a _long_ time
my $queryParser;
my $searchParser;
BEGIN {
# 'Use locale' for internationalisation of Perl sorting and searching -
# main locale settings are done in Foswiki::setupLocale
# Do a dynamic 'use locale' for this module
if ( $Foswiki::cfg{UseLocale} ) {
require locale;
import locale();
}
}
=begin TML
---++ ClassMethod new ($session)
Constructor for the singleton Search engine object.
=cut
sub new {
my ( $class, $session ) = @_;
my $this = bless( { session => $session }, $class );
return $this;
}
=begin TML
---++ ObjectMethod finish()
Break circular references.
=cut
# Note to developers; please undef *all* fields in the object explicitly,
# whether they are references or not. That way this method is "golden
# documentation" of the live fields in the object.
sub finish {
my $this = shift;
undef $this->{session};
}
sub _extractPattern {
my ( $text, $pattern ) = @_;
# Pattern comes from topic, therefore tainted
$pattern =
Foswiki::Sandbox::untaint( $pattern, \&Foswiki::validatePattern );
my $ok = 0;
eval {
# The eval acts as a try block in case there is anything evil in
# the pattern.
$ok = 1 if ( $text =~ s/$pattern/$1/is );
};
$text = '' unless $ok;
return $text;
}
# With the same argument as $pattern, returns a number which is the count of
# occurences of the pattern argument.
sub _countPattern {
my ( $text, $pattern ) = @_;
$pattern =
Foswiki::Sandbox::untaint( $pattern, \&Foswiki::validatePattern );
my $count;
try {
# see: perldoc -q count
$count = () = $text =~ /$pattern/g;
}
catch Error::Simple with {
$count = 0;
};
return $count;
}
# get a list of topics to search in the web, filtered by the $topic
# spec
sub _getTopicList {
my ( $this, $webObject, $options ) = @_;
# E.g. "Web*, FooBar" ==> "^(Web.*|FooBar)$"
$options->{excludeTopics} = _makeTopicPattern( $options->{excludeTopics} )
if ( $options->{excludeTopics} );
my $topicFilter;
my $it;
if ( $options->{includeTopics} ) {
# E.g. "Bug*, *Patch" ==> "^(Bug.*|.*Patch)$"
$options->{includeTopics} =
_makeTopicPattern( $options->{includeTopics} );
# limit search to topic list
if ( $options->{includeTopics} =~
/^\^\([\_\-\+$Foswiki::regex{mixedAlphaNum}\|]+\)\$$/ )
{
# topic list without wildcards
# for speed, do not get all topics in web
# but convert topic pattern into topic list
my $topics = $options->{includeTopics};
$topics =~ s/^\^\(//o;
$topics =~ s/\)\$//o;
# build list from topic pattern
#TODO: erm, what about non-case senstive?
my @list =
grep( $this->{session}->topicExists( $webObject->web, $_ ),
split( /\|/, $topics ) );
$it = new Foswiki::ListIterator( \@list );
}
elsif ( !$options->{casesensitive} ) {
$topicFilter = qr/$options->{includeTopics}/i;
}
else {
$topicFilter = qr/$options->{includeTopics}/;
}
}
$it = $webObject->eachTopic() unless ( defined($it) );
my $filterIter = new Foswiki::Iterator::FilterIterator(
$it,
sub {
my $item = shift;
#my $data = shift;
return unless !$topicFilter || $item =~ /$topicFilter/;
# exclude topics, Codev.ExcludeWebTopicsFromSearch
if ( $options->{casesensitive} && $options->{excludeTopics} ) {
return if $item =~ /$options->{excludeTopics}/i;
}
elsif ( $options->{excludeTopics} ) {
return if $item =~ /$options->{excludeTopics}/;
}
return 1;
}
);
return $filterIter;
}
#convert a comma separated list of webs into the list we'll process
sub _getListOfWebs {
my ( $this, $webName, $recurse, $searchAllFlag ) = @_;
my $session = $this->{session};
my %excludeWeb;
my @tmpWebs;
if ($webName) {
foreach my $web ( split( /[\,\s]+/, $webName ) ) {
$web =~ s#\.#/#go;
# the web processing loop filters for valid web names,
# so don't do it here.
if ( $web =~ s/^-// ) {
$excludeWeb{$web} = 1;
}
else {
if ( $web =~ /^(all|on)$/i
|| $Foswiki::cfg{EnableHierarchicalWebs}
&& Foswiki::isTrue($recurse) )
{
require Foswiki::WebFilter;
my $webObject;
if ( $web =~ /^(all|on)$/i ) {
$webObject = Foswiki::Meta->new($session);
}
else {
push( @tmpWebs, $web );
$webObject = Foswiki::Meta->new( $session, $web );
}
my $it = $webObject->eachWeb(1);
while ( $it->hasNext() ) {
my $w = $web.'/'.$it->next();
next
unless $Foswiki::WebFilter::user_allowed->ok(
$session, $w );
push( @tmpWebs, $w );
}
}
else {
push( @tmpWebs, $web );
}
}
}
}
else {
# default to current web
push( @tmpWebs, $session->{webName} );
if ( Foswiki::isTrue($recurse) ) {
my $webObject = Foswiki::Meta->new( $session, $session->{webName} );
my $it =
$webObject->eachWeb( $Foswiki::cfg{EnableHierarchicalWebs} );
while ( $it->hasNext() ) {
my $w = $session->{webName}.'/'.$it->next();
next
unless $Foswiki::WebFilter::user_allowed->ok( $session, $w );
push( @tmpWebs, $w );
}
}
}
my @webs;
foreach my $web (@tmpWebs) {
push( @webs, $web ) unless $excludeWeb{$web};
$excludeWeb{$web} = 1; # eliminate duplicates
}
return @webs;
}
sub _makeTopicPattern {
my ($topic) = @_;
return '' unless ($topic);
# 'Web*, FooBar' ==> ( 'Web*', 'FooBar' ) ==> ( 'Web.*', "FooBar" )
my @arr =
map { s/[^\*\_\-\+$Foswiki::regex{mixedAlphaNum}]//go; s/\*/\.\*/go; $_ }
split( /,\s*/, $topic );
return '' unless (@arr);
# ( 'Web.*', 'FooBar' ) ==> "^(Web.*|FooBar)$"
return '^(' . join( '|', @arr ) . ')$';
}
=begin TML
---++ ObjectMethod searchWeb (...)
Search one or more webs according to the parameters.
If =_callback= is set, that means the caller wants results as
soon as they are ready. =_callback_ should be set to a reference
to a function which takes =_cbdata= as the first parameter and
remaining parameters the same as 'print'.
If =_callback= is set, the result is always undef. Otherwise the
result is a string containing the rendered search results.
If =inline= is set, then the results are *not* decorated with
the search template head and tail blocks.
The function will throw Error::Simple if it encounters any problems with the
syntax of the search string.
Note: If =format= is set, =template= will be ignored.
Note: For legacy, if =regex= is defined, it will force type='regex'
If =type="word"= it will be changed to =type="keyword"= with =wordboundaries=1=. This will be used for searching with scope="text" only, because scope="topic" will do a Perl search on topic names.
SMELL: If =template= is defined =bookview= will not work
SMELL: it seems that if you define =_callback= or =inline= then you are
responsible for converting the TML to HTML yourself!
FIXME: =callback= cannot work with format parameter (consider format='| $topic |'
=cut
sub searchWeb {
my $this = shift;
my $session = $this->{session};
ASSERT( defined $session->{webName} ) if DEBUG;
my %params = @_;
my $callback = $params{_callback};
my $cbdata = $params{_cbdata};
my $baseTopic = $params{basetopic} || $session->{topicName};
my $baseWeb = $params{baseweb} || $session->{webName};
$params{casesensitive} = Foswiki::isTrue( $params{casesensitive} );
$params{excludeTopics} = $params{excludetopic} || '';
my $formatDefined = $params{formatdefined} = defined $params{format};
my $format = $params{format};
my $inline = $params{inline};
$params{multiple} = Foswiki::isTrue( $params{multiple} );
$params{nonoise} = Foswiki::isTrue( $params{nonoise} );
$params{noempty} = Foswiki::isTrue( $params{noempty}, $params{nonoise} );
$params{zeroresults} =
1 - Foswiki::isTrue( ( $params{zeroresults} || 'on' ), $params{nonoise} );
#paging - this code should be hidden in the InfoCache iterator, but atm, that won't let me do multi-web
my $pagesize = $params{pagesize} || $Foswiki::cfg{Search}{DefaultPageSize} || 25;
my $showpage = $params{showpage} || undef; # 1-based system; 0 is not a valid page number
if (defined($showpage)) {
$params{pager_skip_results_from} = $pagesize * ($showpage-1);
$params{pager_show_results_to} = $pagesize;
}
#TODO: refactorme
my $header = $params{header};
my $footer = $params{footer};
my $noTotal = Foswiki::isTrue( $params{nototal}, $params{nonoise} );
my $noEmpty = Foswiki::isTrue( $params{noempty}, $params{nonoise} );
# Note: a defined header/footer overrides noheader/nofooter
# To maintain Cairo compatibility we ommit default header/footer if the
# now deprecated option 'inline' is used combined with 'format'
my $noHeader =
!defined($header)
&& Foswiki::isTrue( $params{noheader}, $params{nonoise} )
|| ( !$header && $formatDefined && $inline );
my $noFooter =
!defined($footer)
&& Foswiki::isTrue( $params{nofooter}, $params{nonoise} )
|| ( !$footer && $formatDefined && $inline );
my $noSummary = Foswiki::isTrue( $params{nosummary}, $params{nonoise} );
my $zeroResults =
1 - Foswiki::isTrue( ( $params{zeroresults} || 'on' ), $params{nonoise} );
#END TODO
my $sortOrder = $params{order} || '';
my $revSort = Foswiki::isTrue( $params{reverse} );
$params{scope} = $params{scope} || '';
my $searchString = defined $params{search} ? $params{search} : '';
$params{includeTopics} = $params{topic} || '';
$params{type} = $params{type} || '';
$params{wordboundaries} = 0;
if ( $params{type} eq 'word' ) {
# 'word' is exactly the same as 'keyword', except we will be searching
# with word boundaries
$params{type} = 'keyword';
$params{wordboundaries} = 1;
}
my $webName = $params{web} || '';
my $date = $params{date} || '';
my $recurse = $params{'recurse'} || '';
my $finalTerm = $inline ? ( $params{nofinalnewline} || 0 ) : 0;
$baseWeb =~ s/\./\//go;
$params{type} = 'regex' if ( $params{regex} );
my $mixedAlpha = $Foswiki::regex{mixedAlpha};
my $separator = $params{separator};
if ( defined($separator) ) {
$separator =~ s/\$n\(\)/\n/gos; # expand "$n()" to new line
$separator =~ s/\$n([^$mixedAlpha]|$)/\n$1/gos;
}
$params{separator} = $separator;
my $newLine = $params{newline} || '';
if ($newLine) {
$newLine =~ s/\$n\(\)/\n/gos; # expand "$n()" to new line
$newLine =~ s/\$n([^$mixedAlpha]|$)/\n$1/gos;
}
my $searchResult = '';
# A value of 'all' or 'on' by itself gets all webs,
# otherwise ignored (unless there is a web called 'All'.)
my $searchAllFlag = ( $webName =~ /(^|[\,\s])(all|on)([\,\s]|$)/i );
my @webs = $this->_getListOfWebs( $webName, $recurse, $searchAllFlag );
#to help later processing (formatResults)
$params{numberOfWebs} = scalar(@webs);
my $output = '';
# Write log entry
# FIXME: Move log entry further down to log actual webs searched
if ( !$inline ) {
my $t = join( ' ', @webs );
$session->logEvent( 'search', $t, $searchString );
}
my $query;
if ( length($searchString) == 0 ) {
#default search should return no results
$searchString = '1 = 2';
#shortcircuit the search
#FIXME: this breaks the per-web summary output that is hidden in the foreach
@webs = ();
}
my $theParser;
if ( $params{type} eq 'query' ) {
unless ( defined($queryParser) ) {
require Foswiki::Query::Parser;
$queryParser = new Foswiki::Query::Parser();
}
$theParser = $queryParser;
}
else {
unless ( defined($searchParser) ) {
require Foswiki::Search::Parser;
$searchParser = new Foswiki::Search::Parser($session);
}
$theParser = $searchParser;
}
my $error = '';
try {
$query = $theParser->parse( $searchString, \%params );
}
catch Foswiki::Infix::Error with {
# Pass the error on to the caller
throw Error::Simple( shift->stringify() );
};
return $error unless $query;
#TODO: redo with a $query->isEmpty() or something generic, and then push into the foreach?
unless ( $params{type} eq 'query' ) {
#shorcircuit the search foreach below for a zero result search
#FIXME: this breaks the per-web summary output that is hidden in the foreach
@webs = () unless scalar( @{ $query->{tokens} } ); #default
}
########### SEARCH specific Template
my $doBookView = Foswiki::isTrue( $params{bookview} );
my $nonoise = Foswiki::isTrue( $params{nonoise} );
my $noSearch = Foswiki::isTrue( $params{nosearch}, $nonoise );
#tmpl loading code.
my $tmpl = '';
my $originalSearch = $searchString;
my $spacedTopic;
my $template = $params{template} || '';
if ($formatDefined) {
$template = 'searchformat';
}
elsif ($template) {
# template definition overrides book and rename views
}
elsif ($doBookView) {
$template = 'searchbookview';
}
else {
$template = 'search';
}
$tmpl = $session->templates->readTemplate($template);
# SMELL: the only META tags in a template will be METASEARCH
# Why the heck are they being filtered????
$tmpl =~ s/\%META{.*?}\%//go; # remove %META{'parent'}%
# Split template into 5 sections
my ( $tmplHead, $tmplSearch, $tmplTable, $tmplNumber, $tmplTail ) =
split( /%SPLIT%/, $tmpl );
# Invalid template?
if ( !$tmplTail ) {
my $mess =
CGI::h1('Foswiki Installation Error')
. 'Incorrect format of '
. $template
. ' template (missing sections? There should be 4 %SPLIT% tags)';
if ( defined $callback ) {
&$callback( $cbdata, $mess );
return;
}
else {
return $mess;
}
}
# Expand tags in template sections
my $baseWebObject = Foswiki::Meta->new( $session, $session->{webName} );
$tmplSearch = $baseWebObject->expandMacros($tmplSearch);
#TODO: huh? why here?
$tmplNumber = $baseWebObject->expandMacros($tmplNumber);
{
# header and footer of $web
my ( $beforeText, $repeatText, $afterText ) =
split( /%REPEAT%/, $tmplTable );
unless ($noHeader) {
$params{header} = $beforeText unless defined $params{header};
}
#nosummary="on" nosearch="on" noheader="on" nototal="on"
if ($noSummary) {
$repeatText =~ s/%TEXTHEAD%//go;
$repeatText =~ s/ //go;
}
else {
$repeatText =~ s/%TEXTHEAD%/\$summary/go;
}
$params{format} |= $repeatText;
unless ($noFooter) {
$params{footer} |= $afterText;
}
unless ($noTotal) {
$params{footercounter} |= $tmplNumber;
$params{footer} .= $params{footercounter};
}
else {
#print STDERR "}}}".$params{format}."{{{";
}
}
# If not inline search, also expand tags in head and tail sections
unless ($inline) {
$tmplHead = $baseWebObject->expandMacros($tmplHead);
if ( defined $callback ) {
$tmplHead = $baseWebObject->renderTML($tmplHead);
$tmplHead =~ s|</*nop/*>||goi; # remove <nop> tags
&$callback( $cbdata, $tmplHead );
}
else {
# don't render; this will be done by a single
# call at the end.
$searchResult .= $tmplHead;
}
}
# Generate 'Search:' part showing actual search string used
unless ($noSearch) {
my $searchStr = $searchString;
$searchStr =~ s/&/&/go;
$searchStr =~ s/</</go;
$searchStr =~ s/>/>/go;
$searchStr =~ s/^\.\*$/Index/go;
$tmplSearch =~ s/%SEARCHSTRING%/$searchStr/go;
if ( defined $callback ) {
$tmplSearch = $baseWebObject->renderTML($tmplSearch);
$tmplSearch =~ s|</*nop/*>||goi; # remove <nop> tag
&$callback( $cbdata, $tmplSearch );
}
else {
# don't render; will be done later
$searchResult .= $tmplSearch;
}
}
########### END SEARCH specific Template
# Loop through webs
my $isAdmin = $session->{users}->isAdmin( $session->{user} );
my $ttopics = 0;
my $prefs = $session->{prefs};
foreach my $web (@webs) {
$web = Foswiki::Sandbox::untaint( $web,
\&Foswiki::Sandbox::validateWebName );
# can't process what ain't thar
next unless $session->webExists($web);
my $webObject = Foswiki::Meta->new( $session, $web );
my $thisWebNoSearchAll = $webObject->getPreference('NOSEARCHALL') || '';
# make sure we can report this web on an 'all' search
# DON'T filter out unless it's part of an 'all' search.
next
if ( $searchAllFlag
&& !$isAdmin
&& ( $thisWebNoSearchAll =~ /on/i || $web =~ /^[\.\_]/ )
&& $web ne $session->{webName} );
# Run the search on topics in this web
my $inputTopicSet = _getTopicList( $this, $webObject, \%params );
next
if ( $params{noempty} && !$inputTopicSet->hasNext() )
; # Nothing to show for this web
my $infoCache = $webObject->query( $query, $inputTopicSet, \%params );
$infoCache->sortResults( $web, \%params );
# add dependencies
my $cache = $session->{cache};
if ($cache) {
#TODO: ouch - this forces pre-evaluation of results,
# and assumes we need or care to evaluate all of them :/
# I wonder if this makes paging head processing heavy
foreach my $topic ( $infoCache->{list} ) {
$cache->addDependency( $web, $topic );
}
}
my ( $web_ttopics, $web_searchResult );
( $web_ttopics, $web_searchResult ) =
$this->formatResults( $webObject, $query, $searchString, $infoCache,
\%params );
$ttopics += $web_ttopics;
# add legacy SEARCH separator - see Item1773 (TODO: find a better approach)
$web_searchResult .= $separator if (($web_ttopics>0) and $noFooter and $noSummary and $separator);
$searchResult .= $web_searchResult;
#paging
if (defined($showpage) and $params{pager_show_results_to} > 0) {
$params{pager_show_results_to} -= $web_ttopics;
last if ($params{pager_show_results_to} <= 0);
}
} # end of: foreach my $web ( @webs )
return '' if ( $ttopics == 0 && $params{zeroresults} );
if ( $formatDefined && !$finalTerm ) {
if ($separator) {
$separator = quotemeta($separator);
$searchResult =~ s/$separator$//s; # remove separator at end
}
else {
$searchResult =~ s/\n$//os; # remove trailing new line
}
}
unless ($inline) {
$tmplTail = $baseWebObject->expandMacros($tmplTail);
if ( defined $callback ) {
$tmplTail = $baseWebObject->renderTML($tmplTail);
$tmplTail =~ s|</*nop/*>||goi; # remove <nop> tag
&$callback( $cbdata, $tmplTail );
}
else {
$searchResult .= $tmplTail;
}
}
return if ( defined $callback );
return $searchResult if $inline;
$searchResult = $baseWebObject->expandMacros($searchResult);
$searchResult = $baseWebObject->renderTML($searchResult);
return $searchResult;
}
=begin TML
---++ formatResults
the implementation of %FORMAT{}%
TODO: rewrite to take a resultset, a set of params? and a hash of sub's to
enable evaluations of things like '$include(blah)' in format strings.
have a default set of replacements like $lt, $nop, $percnt, $dollar etc, and then
the hash of subs can take care of %MACRO{}% specific complex to evaluate replacements..
(that way we don't pre-evaluate and then subst)
=cut
sub formatResults {
my ( $this, $webObject, $query, $searchString, $infoCache, $params ) = @_;
my $session = $this->{session};
my $users = $session->{users};
my $web = $webObject->web;
my $thisWebNoSearchAll = $webObject->getPreference('NOSEARCHALL') || '';
my $callback = $params->{_callback};
my $cbdata = $params->{_cbdata};
my $baseTopic = $params->{basetopic} || $session->{topicName};
my $baseWeb = $params->{baseweb} || $session->{webName};
my $doBookView = Foswiki::isTrue( $params->{bookview} );
my $caseSensitive = Foswiki::isTrue( $params->{casesensitive} );
my $doExpandVars = Foswiki::isTrue( $params->{expandvariables} );
my $nonoise = Foswiki::isTrue( $params->{nonoise} );
my $noSearch = Foswiki::isTrue( $params->{nosearch}, $nonoise );
my $formatDefined = defined $params->{format};
my $format = $params->{format} || '';
my $header = $params->{header} || '';
my $footer = $params->{footer} || '';
my $inline = $params->{inline};
my $limit = $params->{limit} || '';
# Limit search results
if ( $limit =~ /(^\d+$)/o ) {
# only digits, all else is the same as
# an empty string. "+10" won't work.
$limit = $1;
}
else {
# change 'all' to 0, then to big number
$limit = 0;
}
$limit = 32000 unless ($limit);
if (defined($params->{pager_show_results_to}) and
$params->{pager_show_results_to} > 0) {
$limit = $params->{pager_show_results_to};
}
#TODO: multiple is an attribute of the ResultSet
my $doMultiple = Foswiki::isTrue( $params->{multiple} );
my $noEmpty = Foswiki::isTrue( $params->{noempty}, $nonoise );
# Note: a defined header/footer overrides noheader/nofooter
# To maintain Cairo compatibility we ommit default header/footer if the
# now deprecated option 'inline' is used combined with 'format'
my $noHeader =
!defined($header) && Foswiki::isTrue( $params->{noheader}, $nonoise )
|| ( !$header && $formatDefined && $inline );
my $noFooter =
!defined($footer) && Foswiki::isTrue( $params->{nofooter}, $nonoise )
|| ( !$footer && $formatDefined && $inline );
my $noSummary = Foswiki::isTrue( $params->{nosummary}, $nonoise );
my $zeroResults =
1 - Foswiki::isTrue( ( $params->{zeroresults} || 'on' ), $nonoise );
my $noTotal = Foswiki::isTrue( $params->{nototal}, $nonoise );
my $newLine = $params->{newline} || '';
my $separator = $params->{separator};
my $type = $params->{type} || '';
if ( defined $header ) {
$header = Foswiki::expandStandardEscapes($header);
$header =~ s/\$web/$web/gos; # expand name of web
$header =~ s/([^\n])$/$1\n/os; # add new line at end
}
if ( defined $footer ) {
$footer = Foswiki::expandStandardEscapes($footer);
$footer =~ s/\$web/$web/gos; # expand name of web
$footer =~ s/([^\n])$/$1\n/os; # add new line at end
}
# output the list of topics in $web
my $ntopics = 0; # number of topics in current web
my $nhits = 0; # number of hits (if multiple=on) in current web
my $headerDone = $noHeader;
my @searchResults;
while ( $infoCache->hasNext() ) {
my $topic = $infoCache->next();
#pager..
if (defined($params->{pager_skip_results_from}) and
$params->{pager_skip_results_from} > 0) {
$params->{pager_skip_results_from}--;
next;
}
my $info = $infoCache->get($topic);
my $text; #current hits' text
# Check security (don't show topics the current user does not have permission to view)
next unless $info->{allowView};
# Special handling for format='...'
if ($formatDefined) {
$text = $info->{tom}->text();
if ($doExpandVars) {
if ( $web eq $baseWeb && $topic eq $baseTopic ) {
# primitive way to prevent recursion
$text =~ s/%SEARCH/%<nop>SEARCH/g;
}
$text = $info->{tom}->expandMacros($text);
}
}
#TODO: should extract this somehow
my @multipleHitLines = ();
if ( $doMultiple && $query->{tokens} ) {
#TODO: i wonder if this shoudl be a HoistRE..
my @tokens = @{ $query->{tokens} };
my $pattern = $tokens[$#tokens]; # last token in an AND search
$pattern = quotemeta($pattern) if ( $type ne 'regex' );
unless ($text) {
$text = $info->{tom}->text();
}
if ($caseSensitive) {
@multipleHitLines =
reverse grep { /$pattern/ } split( /[\n\r]+/, $text );
}
else {
@multipleHitLines =
reverse grep { /$pattern/i } split( /[\n\r]+/, $text );
}
}
my $epochSecs = $info->{modified};
require Foswiki::Time;
my $revDate = Foswiki::Time::formatTime($epochSecs);
my $isoDate = Foswiki::Time::formatTime( $epochSecs, '$iso', 'gmtime' );
my $ru = $info->{editby} || 'UnknownUser';
my $revNum = $info->{revNum} || 0;
my $cUID = $users->getCanonicalUserID($ru);
if ( !$cUID ) {
# Not a login name or a wiki name. Is it a valid cUID?
my $ln = $users->getLoginName($ru);
$cUID = $ru if defined $ln && $ln ne 'unknown';
}
$ntopics += 1;
do { # multiple=on loop
$nhits += 1;
my $out = '';
$text = pop(@multipleHitLines) if ( scalar(@multipleHitLines) );
my $wikiusername = $users->webDotWikiName($cUID);
$wikiusername = "$Foswiki::cfg{UsersWebName}.UnknownUser"
unless defined $wikiusername;
if ($formatDefined) {
$out = $format;
$out =~ s/\$web/$web/gs;
$out =~ s/\$topic\(([^\)]*)\)/
Foswiki::Render::breakName( $topic, $1 )/ges;
$out =~ s/\$topic/$topic/gs;
$out =~ s/\$date/$revDate/gs;
$out =~ s/\$isodate/$isoDate/gs;
$out =~ s/\$rev/$revNum/gs;
$out =~ s/\$wikiusername/$wikiusername/ges;
$out =~ s/\$ntopics/$ntopics/gs;
$out =~ s/\$nhits/$nhits/gs;
my $wikiname = $users->getWikiName($cUID);
$wikiname = 'UnknownUser' unless defined $wikiname;
$out =~ s/\$wikiname/$wikiname/ges;
my $username = $users->getLoginName($cUID);
$username = 'unknown' unless defined $username;
$out =~ s/\$username/$username/ges;
$out =~ s/\$create(date|username|wikiname|wikiusername)/
$infoCache->getRev1Info( $topic, "create$1" )/ges;
if ( $out =~ m/\$text/ ) {
unless ($text) {
$text = $info->{tom}->text();
}
if ( $topic eq $session->{topicName} ) {
# defuse SEARCH in current topic to prevent loop
$text =~ s/%SEARCH{.*?}%/SEARCH{...}/go;
}
$out =~ s/\$text/$text/gos;
}
}
else {
die "no such thing? ($format)";
#$out = $repeatText;
}
$out =~ s/%WEB%/$web/go;
$out =~ s/%TOPICNAME%/$topic/go;
$out =~ s/%TIME%/$revDate/o;
my $srev = 'r' . $revNum;
if ( $revNum eq '0' || $revNum eq '1' ) {
$srev = CGI::span( { class => 'foswikiNew' },
( $session->i18n->maketext('NEW') ) );
}
$out =~ s/%REVISION%/$srev/o;
$out =~ s/%AUTHOR%/$wikiusername/e;
if ($doBookView) {
# BookView
unless ($text) {
$text = $info->{tom}->text();
}
if ( $web eq $baseWeb && $topic eq $baseTopic ) {
# primitive way to prevent recursion
$text =~ s/%SEARCH/%<nop>SEARCH/g;
}
$text = $info->{tom}->expandMacros($text);
$text = $info->{tom}->renderTML($text);
$out =~ s/%TEXTHEAD%/$text/go;
}
elsif ($formatDefined) {
$out =~ s/\$summary(?:\(([^\)]*)\))?/
$info->{tom}->summariseText( $1, $text )/ges;
$out =~ s/\$changes(?:\(([^\)]*)\))?/
$info->{tom}->summariseChanges($1, $revNum)/ges;
$out =~ s/\$formfield\(\s*([^\)]*)\s*\)/
displayFormField( $info->{tom}, $1 )/ges;
$out =~ s/\$parent\(([^\)]*)\)/
Foswiki::Render::breakName(
$info->{tom}->getParent(), $1 )/ges;
$out =~ s/\$parent/$info->{tom}->getParent()/ges;
$out =~ s/\$formname/$info->{tom}->getFormName()/ges;
$out =~
s/\$count\((.*?\s*\.\*)\)/_countPattern( $text, $1 )/ges;
# FIXME: Allow all regex characters but escape them
# Note: The RE requires a .* at the end of a pattern to avoid false positives
# in pattern matching
$out =~
s/\$pattern\((.*?\s*\.\*)\)/_extractPattern( $text, $1 )/ges;
$out =~ s/\r?\n/$newLine/gos if ($newLine);
if ( !defined($separator) ) {
# add new line at end if needed
# SMELL: why?
#TODO: god, this needs to be made SEARCH legacy somehow (it has impact when format="asdf$n", rather than format="asdf\n")
#SMELL: I wonder if this can't be wrapped into the summarizeText code
unless ( $noTotal && !$params->{formatdefined} ) {
$out =~ s/([^\n])$/$1\n/s;
}
}
$out = Foswiki::expandStandardEscapes($out);
}
elsif ($noSummary) {
die "no such thing? (noSummary)";
$out =~ s/%TEXTHEAD%//go;
$out =~ s/ //go;
}
else {
die "no such thing? (ke)";
# regular search view
$text = $info->{tom}->summariseText( '', $text );
$out =~ s/%TEXTHEAD%/$text/go;
}
# lazy output of header (only if needed for the first time)
unless ($headerDone) {
$headerDone = 1;
my $thisWebBGColor = $webObject->getPreference('WEBBGCOLOR')
|| '\#FF00FF';
$header =~ s/%WEBBGCOLOR%/$thisWebBGColor/go;
$header =~ s/%WEB%/$web/go;
$header =~ s/\$ntopics/0/gs;
$header =~ s/\$nhits/0/gs;
$header = $webObject->expandMacros($header);
if ( defined $callback ) {
$header = $webObject->renderTML($header);
$header =~ s|</*nop/*>||goi; # remove <nop> tag
&$callback( $cbdata, $header );
}
}
# don't expand if a format is specified - it breaks tables and stuff
unless ($formatDefined) {
$out = $webObject->renderTML($out);
}
# output topic (or line if multiple=on)
if ( defined $callback ) {
$out =~ s|</*nop/*>||goi; # remove <nop> tag
&$callback( $cbdata, $out );
}
else {
push( @searchResults, $out );
}
} while (@multipleHitLines); # multiple=on loop