/
Search.pm
1382 lines (1100 loc) · 46.1 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 warnings;
use Assert;
use Error qw( :try );
use Foswiki ();
use Foswiki::Sandbox ();
use Foswiki::Search::InfoCache ();
use Foswiki::Search::ResultSet ();
use Foswiki::ListIterator ();
use Foswiki::Iterator::FilterIterator ();
use Foswiki::WebFilter ();
use Foswiki::MetaCache ();
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.
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.
=cut
sub finish {
my $this = shift;
undef $this->{session};
# these may well be function objects, but if (a setting changes, it needs to be picked up again.
if ( defined( $this->{queryParser} ) ) {
$this->{queryParser}->finish();
undef $this->{queryParser};
}
if ( defined( $this->{searchParser} ) ) {
$this->{searchParser}->finish();
undef $this->{searchParser};
}
if ( defined( $this->{MetaCache} ) ) {
$this->{MetaCache}->finish();
undef $this->{MetaCache};
}
}
=begin TML
---++ ObjectMethod metacache
returns the metacache.
=cut
sub metacache {
my $this = shift;
# these may well be function objects, but if (a setting changes, it needs to be picked up again.
if ( !defined( $this->{MetaCache} ) ) {
$this->{MetaCache} = new Foswiki::MetaCache( $this->{session} );
}
return $this->{MetaCache};
}
=begin TML
---++ ObjectMethod parseSearch($searchString, $params) -> Foswiki::*::Node
parses the search string and builds the appropriate nodes (uses $param->{type} to work out which parser
TODO: make parser register themselves with their type, so that we could plug in anything.
=cut
sub parseSearch {
my $this = shift;
my $searchString = shift;
my $params = shift;
my $query;
my $theParser;
if ( $params->{type} eq 'query' ) {
unless ( defined( $this->{queryParser} ) ) {
require Foswiki::Query::Parser;
$this->{queryParser} = new Foswiki::Query::Parser();
}
$theParser = $this->{queryParser};
}
else {
unless ( defined( $this->{searchParser} ) ) {
require Foswiki::Search::Parser;
$this->{searchParser} =
new Foswiki::Search::Parser( $this->{session} );
}
$theParser = $this->{searchParser};
}
try {
$query = $theParser->parse( $searchString, $params );
}
catch Foswiki::Infix::Error with {
# Pass the error on to the caller
throw Error::Simple( shift->stringify() );
};
return $query;
}
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;
}
=begin TML
---++ StaticMethod _isSetTrue( $value, $default ) -> $boolean
Returns 1 if =$value= is _actually set to_ true, and 0 otherwise.
If the value is undef, then =$default= is returned. If =$default= is
not specified it is taken as 0.
=cut
sub _isSetTrue {
my ( $value, $default ) = @_;
$default ||= 0;
return $default unless defined($value);
$value =~ s/on//gi;
$value =~ s/yes//gi;
$value =~ s/true//gi;
return ($value) ? 0 : 1;
}
=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.
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= 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 $baseWebObject = Foswiki::Meta->new( $session, $session->{webName} );
my ( $callback, $cbdata ) = setup_callback( \%params, $baseWebObject );
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};
$params{multiple} = Foswiki::isTrue( $params{multiple} );
$params{nonoise} = Foswiki::isTrue( $params{nonoise} );
$params{noempty} = Foswiki::isTrue( $params{noempty}, $params{nonoise} );
### $params{zeroresults} = Foswiki::isTrue( ( $params{zeroresults} ), $params{nonoise} );
#paging - this code should be hidden in the InfoCache iterator, but atm, that won't let me do multi-web
#TODO: or... I may wrap an AggregateIterator in a PagingIterator which then is evaluated by a Formattingiterator.
my $pagesize =
$params{pagesize}
|| $Foswiki::cfg{Search}{DefaultPageSize}
|| 25;
require Digest::MD5;
my $string_id = $params{_RAW} || 'we had better not go there';
my $paging_ID = 'SEARCH' . Digest::MD5::md5_hex($string_id);
$params{pager_urlparam_id} = $paging_ID;
# 1-based system; 0 is not a valid page number
my $showpage = $session->{request}->param($paging_ID) || $params{showpage};
if ( defined( $params{pagesize} ) or defined($showpage) ) {
if ( !defined($showpage) ) {
$showpage = 1;
}
$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
my $noHeader =
!defined($header)
&& Foswiki::isTrue( $params{noheader}, $params{nonoise} )
|| ( !$header && $formatDefined );
my $noFooter =
!defined($footer)
&& Foswiki::isTrue( $params{nofooter}, $params{nonoise} )
|| ( !$footer && $formatDefined );
my $noSummary = Foswiki::isTrue( $params{nosummary}, $params{nonoise} );
my $zeroResults =
Foswiki::isTrue( $params{zeroresults}, $params{nonoise} || 1 );
#END TODO
my $doBookView = Foswiki::isTrue( $params{bookview} );
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 $webNames = $params{web} || '';
my $date = $params{date} || '';
my $recurse = $params{'recurse'} || '';
$baseWeb =~ s/\./\//go;
$params{type} = 'regex' if ( $params{regex} );
#TODO: quick hackjob - see what the feature proposal gives before it becomes public
if ( defined( $params{groupby} ) and ( $params{groupby} eq 'none' ) ) {
#_only_ allow groupby="none" - as its a secrect none public setting.
}
else {
$params{groupby} = 'web';
}
################### Perform The Search
my $query = $this->parseSearch( $searchString, \%params );
#setting the inputTopicSet to be undef allows the search/query algo to use
#the topic="" and excludetopic="" params and web Obj to get a new list of topics.
#this allows the algo's to customise and optimise the getting of this list themselves.
my $infoCache = Foswiki::Meta::query( $query, undef, \%params );
################### Do the Rendering
# If the search did not return anything, return the rendered zeroresults
# if it is defined as a string.
# (http://foswiki.org/Development/AddDefaultTopicParameterToINCLUDE)
if ( not $infoCache->hasNext() ) {
if ( not $zeroResults ) {
return '';
}
else {
if ( not _isSetTrue( $params{zeroresults}, 1 ) ) {
#foswiki 1.1 Feature Proposal: SEARCH needs an alt parameter in case of zero results
#TODO: extract & merge with extraction of footer processing code below
my $result =
Foswiki::expandStandardEscapes( $params{zeroresults} );
$result =~ s/\$web/$baseWeb/gos; # expand name of web
$result =~ s/([^\n])$/$1\n/os; # add new line at end
# output footer of $web
$result =~ s/\$ntopics/0/gs;
$result =~ s/\$nhits/0/gs;
#legacy SEARCH counter support
$result =~ s/%NTOPICS%/0/go;
#$result = $this->formatCommon( $result, \%pager_formatting );
$result =~ s/\n$//os; # remove trailing new line
return $result;
}
}
}
my $tmplSearch =
$this->loadTemplates( \%params, $baseWebObject, $formatDefined,
$doBookView, $noHeader, $noSummary, $noTotal, $noFooter );
# Generate 'Search:' part showing actual search string used
# Ommit any text before search results if either nosearch or nonoise is on
my $nonoise = Foswiki::isTrue( $params{nonoise} );
my $noSearch = Foswiki::isTrue( $params{nosearch}, $nonoise );
unless ($noSearch) {
my $searchStr = $searchString;
$searchStr =~ s/&/&/go;
$searchStr =~ s/</</go;
$searchStr =~ s/>/>/go;
$tmplSearch =~ s/%SEARCHSTRING%/$searchStr/go;
&$callback( $cbdata, $tmplSearch );
}
# We now format the results.
# All the
my ( $numberOfResults, $web_searchResult ) =
$this->formatResults( $query, $infoCache, \%params );
return if ( defined $params{_callback} );
my $searchResult = join( '', @{ $params{_cbdata} } );
# Remove trailing separator or new line if nofinalnewline parameter is set
my $noFinalNewline = Foswiki::isTrue( $params{nofinalnewline}, 1 );
if ( $formatDefined && $noFinalNewline ) {
if ($params{separator}) {
my $separator = quotemeta($params{separator});
$searchResult =~ s/$separator$//s; # remove separator at end
}
else {
$searchResult =~ s/\n$//os; # remove trailing new line
}
}
return $searchResult;
}
=begin TML
---++ ObjectMethod loadTemplates (...)
this code was extracted from searchWeb, and should probably be private.
=cut
sub loadTemplates {
my (
$this, $params, $baseWebObject,
$formatDefined, $doBookView, $noHeader,
$noSummary, $noTotal, $noFooter
) = @_;
my $session = $this->{session};
#tmpl loading code.
my $tmpl = '';
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);
#print STDERR "}}} $tmpl {{{\n";
# SMELL: the only META tags in a template will be METASEARCH
# Why the heck are they being filtered????
#TODO: write a unit test that uses topic based templates with META's in them and if ok, remove.
$tmpl =~ s/\%META{.*?}\%//go; # remove %META{'parent'}%
# Split template into 5 sections
my ( $tmplHead, $tmplSearch, $tmplTable, $tmplNumber, $tmplTail ) =
split( /%SPLIT%/, $tmpl );
my $repeatText;
if ( !defined($tmplTail) ) {
$tmplSearch = $session->templates->expandTemplate('SEARCH:searched');
$tmplNumber = $session->templates->expandTemplate('SEARCH:count');
#it'd be nice to not need this if, but it seem that the noheader setting is ignored if a header= is set. truely bizzare
#TODO: push up the 'noheader' evaluation to take not of this quirk
#TODO: um, we die when ASSERT is on with a wide char in print
unless ($noHeader) {
$params->{header} =
$session->templates->expandTemplate('SEARCH:header')
unless defined $params->{header};
}
$repeatText = $session->templates->expandTemplate('SEARCH:format');
unless ($noFooter) {
$params->{footer} =
$session->templates->expandTemplate('SEARCH:footer')
unless defined $params->{footer};
}
}
else {
#Historical legacy form of the search TMPL's
# header and footer of $web
my $beforeText;
my $afterText;
( $beforeText, $repeatText, $afterText ) =
split( /%REPEAT%/, $tmplTable );
unless ($noHeader) {
$params->{header} = $beforeText unless defined $params->{header};
}
unless ($noFooter) {
$params->{footer} |= $afterText;
}
}
#nosummary="on" nosearch="on" noheader="on" nototal="on"
if ($noSummary) {
$repeatText =~ s/%TEXTHEAD%//go;
$repeatText =~ s/ //go;
}
else {
$repeatText =~ s/%TEXTHEAD%/\$summary(searchcontext)/go;
}
$params->{format} |= $repeatText;
$params->{footercounter} |= $tmplNumber;
return $tmplSearch;
}
=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, $query, $infoCache, $params ) = @_;
my $session = $this->{session};
my $users = $session->{users};
my ( $callback, $cbdata ) = setup_callback($params);
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 $limit = $params->{limit} || '';
# Limit search results. Cannot be deprecated
# Limit will still be needed for the application types of SEARCHES
# even if pagesize is added as feature. Example for searching and listing
# text from first 5 bullets in a formatted multiple type search
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);
#pager formatting
my %pager_formatting;
if ( defined( $params->{pager_show_results_to} )
and $params->{pager_show_results_to} > 0 )
{
$limit = $params->{pager_show_results_to};
#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;
#TODO: paging only implemented for SEARCH atm :/
my $paging_ID = $params->{pager_urlparam_id};
# 1-based system; 0 is not a valid page number
my $showpage =
$session->{request}->param($paging_ID)
|| $params->{showpage}
|| 1;
#TODO: need to ask the result set
my $numberofpages = $infoCache->numberOfTopics / $params->{pagesize};
$numberofpages = int($numberofpages) + 1;
#TODO: excuse me?
my $sep = ' ';
my $nextidx = $showpage + 1;
my $previousidx = $showpage - 1;
my %new_params;
#kill me please, i can't find a way to just load up the hash :(
foreach my $key ( $session->{request}->param ) {
$new_params{$key} = $session->{request}->param($key);
}
$session->templates->readTemplate('searchformat');
my $previouspagebutton = '';
my $previouspageurl = '';
if ( $previousidx >= 1 ) {
$new_params{$paging_ID} = $previousidx;
$previouspageurl =
Foswiki::Func::getScriptUrl( $baseWeb, $baseTopic, 'view',
%new_params );
$previouspagebutton =
$session->templates->expandTemplate('SEARCH:pager_previous');
}
my $nextpagebutton = '';
my $nextpageurl = '';
if ( $nextidx <= $numberofpages ) {
$new_params{$paging_ID} = $nextidx;
$nextpageurl =
Foswiki::Func::getScriptUrl( $baseWeb, $baseTopic, 'view',
%new_params );
$nextpagebutton =
$session->templates->expandTemplate('SEARCH:pager_next');
}
%pager_formatting = (
'\$previouspage' => sub { return $previousidx },
'\$currentpage' => sub { return $showpage },
'\$nextpage' => sub { return $showpage + 1 },
'\$numberofpages' => sub { return $numberofpages },
'\$pagesize' => sub { return $pagesize },
'\$previousurl' => sub { return $previouspageurl },
'\$nexturl' => sub { return $nextpageurl },
'\$sep' => sub { return $sep; }
);
$previouspagebutton =
$this->formatCommon( $previouspagebutton, \%pager_formatting );
$pager_formatting{'\$previousbutton'} =
sub { return $previouspagebutton };
$nextpagebutton =
$this->formatCommon( $nextpagebutton, \%pager_formatting );
$pager_formatting{'\$nextbutton'} = sub { return $nextpagebutton };
my $pager_control = $params->{pagerformat}
|| $session->templates->expandTemplate('SEARCH:pager');
$pager_control =
$this->formatCommon( $pager_control, \%pager_formatting );
$pager_control = Foswiki::expandStandardEscapes($pager_control);
$pager_formatting{'\$pager'} = sub { return $pager_control; };
}
#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
my $noHeader =
!defined($header) && Foswiki::isTrue( $params->{noheader}, $nonoise )
|| ( !$header && $formatDefined );
my $noFooter =
!defined($footer) && Foswiki::isTrue( $params->{nofooter}, $nonoise )
|| ( !$footer && $formatDefined );
my $noSummary = Foswiki::isTrue( $params->{nosummary}, $nonoise );
my $zeroResults =
Foswiki::isTrue( ( $params->{zeroresults} ), $nonoise || 1 );
my $noTotal = Foswiki::isTrue( $params->{nototal}, $nonoise );
my $newLine = $params->{newline} || '';
my $separator = $params->{separator};
my $type = $params->{type} || '';
# 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 $web;
my $webObject;
my $lastWebProcessed = '';
my $ttopics = 0;
my $thits = 0;
while ( $infoCache->hasNext() ) {
my $webtopic = $infoCache->next();
ASSERT($webtopic) if DEBUG;
my $topic;
( $web, $topic ) =
Foswiki::Func::normalizeWebTopicName( '', $webtopic );
#pager..
if ( defined( $params->{pager_skip_results_from} )
and $params->{pager_skip_results_from} > 0 )
{
$params->{pager_skip_results_from}--;
next;
}
# add dependencies (TODO: unclear if this should be before the paging, or after the allowView - sadly, it can't be _in_ the infoCache)
if ( my $cache = $session->{cache} ) {
$cache->addDependency( $web, $topic );
}
my $info = $this->metacache->get( $web, $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();
$text = '' unless defined $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..
#TODO: well, um, and how does this work for query search?
my @tokens = @{ $query->{tokens} };
my $pattern = $tokens[$#tokens]; # last token in an AND search
$pattern = quotemeta($pattern) if ( $type ne 'regex' );
$text = $info->{tom}->text() unless defined $text;
$text = '' unless defined $text;
if ($caseSensitive) {
@multipleHitLines =
reverse grep { /$pattern/ } split( /[\n\r]+/, $text );
}
else {
@multipleHitLines =
reverse grep { /$pattern/i } split( /[\n\r]+/, $text );
}
}
my $ru = $info->{editby} || 'UnknownUser';
my $revNum = $info->{revNum} || 0;
$ntopics += 1;
$ttopics += 1;
do { # multiple=on loop
$nhits += 1;
$thits += 1;
$text = pop(@multipleHitLines) if ( scalar(@multipleHitLines) );
my $justdidHeaderOrFooter = 0;
if ( ( defined( $params->{groupby} ) )
and ( $params->{groupby} eq 'web' ) )
{
if ( $lastWebProcessed ne $web ) {
#output the footer for the previous webtopic
if ( $lastWebProcessed ne '' ) {
#c&p from below
#TODO: needs refactoring.
my $processedfooter = $footer;
if ( not $noTotal ) {
$processedfooter .= $params->{footercounter};
}
if ( defined($processedfooter)
and ( $processedfooter ne '' ) )
{
#footer comes before result
$ntopics--;
$nhits--;
#because $pager contains more $ntopics like format strings, it needs to be expanded first.
$processedfooter =
$this->formatCommon( $processedfooter,
\%pager_formatting );
$processedfooter =
Foswiki::expandStandardEscapes($processedfooter);
$processedfooter =~ s/\$web/$lastWebProcessed/gos
; # expand name of web
$processedfooter =~
s/([^\n])$/$1\n/os; # add new line at end
# output footer of $web
$processedfooter =~ s/\$ntopics/$ntopics/gs;
$processedfooter =~ s/\$nhits/$nhits/gs;
#legacy SEARCH counter support
$processedfooter =~ s/%NTOPICS%/$ntopics/go;
$processedfooter =
$this->formatCommon( $processedfooter,
\%pager_formatting );
$processedfooter =~
s/\n$//os; # remove trailing new line
if ( defined($separator) ) {
# $header = $header.$separator if (defined($params->{header}));
#TODO: see Item1773 for discussion (foswiki 1.0 compatibility removes the if..)
if ( defined($processedfooter)
and ( $processedfooter ne '' ) )
{
&$callback( $cbdata, $separator );
}
}
else {
#TODO: legacy from SEARCH - we want to remove this oddness
# &$callback( $cbdata, $separator ) if (defined($params->{footer}) && $processedfooter ne '<nop>');
}
$justdidHeaderOrFooter = 1;
&$callback( $cbdata, $processedfooter );
#go back to counting results
$ntopics++;
$nhits++;
}
}
#trigger a header for this new web
$headerDone = undef;
}
}
if ( $lastWebProcessed ne $web ) {
$webObject = new Foswiki::Meta( $session, $web );
$lastWebProcessed = $web;
#reset our web partitioned legacy counts
$ntopics = 1;
$nhits = 1;
}
# lazy output of header (only if needed for the first time)
if ( ( !$headerDone and ( defined($header) ) )
and ( $header ne '' ) )
{
# add legacy SEARCH separator - see Item1773 (TODO: find a better approach)
if ( ( $ttopics > 1 )
and $noFooter
and $noSummary
and $separator )
{
&$callback( $cbdata, $separator );
}
my $processedheader = $header;
#because $pager contains more $ntopics like format strings, it needs to be expanded first.
$processedheader =
$this->formatCommon( $processedheader, \%pager_formatting );
$processedheader =
Foswiki::expandStandardEscapes($processedheader);
$processedheader =~ s/\$web/$web/gos; # expand name of web
$processedheader =~ s/([^\n])$/$1\n/os; # add new line at end
$headerDone = 1;
my $thisWebBGColor = $webObject->getPreference('WEBBGCOLOR')
|| '\#FF00FF';
$processedheader =~ s/%WEBBGCOLOR%/$thisWebBGColor/go;
$processedheader =~ s/%WEB%/$web/go;
$processedheader =~ s/\$ntopics/($ntopics-1)/gse;
$processedheader =~ s/\$nhits/($nhits-1)/gse;
$processedheader =
$this->formatCommon( $processedheader, \%pager_formatting );
&$callback( $cbdata, $processedheader );
$justdidHeaderOrFooter = 1;
}
if ( defined($separator)
and ( $thits > 1 )
and ( $justdidHeaderOrFooter != 1 ) )
{
&$callback( $cbdata, $separator );
}
###################Render the result
my $out;
if ( $formatDefined and ( $format ne '' ) ) {
#TODO: hack to convert a bad SEARCH format to the one used by getRevInfo..
$format =~ s/\$createdate/\$createlongdate/gs;
#it looks like $isodate in format is equive to $iso in renderRevisionInfo
#TODO: clean these 3 hacks up
$format =~ s/\$isodate/\$iso/gs;
$format =~ s/\%TIME\%/\$date/gs;
$format =~ s/\$date/\$longdate/gs;
#other tmpl based renderings
$format =~ s/%WEB%/\$web/go;
$format =~ s/%TOPICNAME%/\$topic/go;
$format =~ s/%AUTHOR%/\$wikiusername/g;
# pass search options to summary parser
my $searchOptions = {
type => $params->{type},
wordboundaries => $params->{wordboundaries},
casesensitive => $caseSensitive,
tokens => $query->{tokens}
};
#TODO: why is this not part of the callback? at least the non-result element format strings can be common here.
#or do i need a formatCommon sub that formatResult can also call.. (which then goes into the callback?
$out = $this->formatResult(
$format,
$info->{tom},
$text,
$searchOptions,
{
'\$ntopics' => sub { return $ntopics },
'\$nhits' => sub { return $nhits },
%pager_formatting,
#rev1 info
#TODO: move the $create* formats into Render::renderRevisionInfo..
#which implies moving the infocache's pre-extracted data into the tom obj too.
# $out =~ s/\$create(longdate|username|wikiname|wikiusername)/
# $infoCache->getRev1Info( $topic, "create$1" )/ges;
'\$createlongdate' => sub {
return $this->metacache->get( $web, $topic )->{tom}
->getRev1Info("createlongdate");
},
'\$createusername' => sub {
return $this->metacache->get( $web, $topic )->{tom}
->getRev1Info("createusername");
},
'\$createwikiname' => sub {
return $this->metacache->get( $web, $topic )->{tom}
->getRev1Info("createwikiname");
},
'\$createwikiusername' => sub {
return $this->metacache->get( $web, $topic )->{tom}
->getRev1Info("createwikiusername");
},
#TODO: hacky bits that need to be moved out of formatResult()
'$revNum' => sub { return $revNum; },
'$doBookView' => sub { return $doBookView; },
'$baseWeb' => sub { return $baseWeb; },
'$baseTopic' => sub { return $baseTopic; },
'$newLine' => sub { return $newLine; },
'$separator' => sub { return $separator; },
'$noTotal' => sub { return $noTotal; },
'$paramsHash' => sub { return $params; },
}
);
}
else {
$out = '';
}
&$callback( $cbdata, $out );
} while (@multipleHitLines); # multiple=on loop
last if ( $ttopics >= $limit );
} # end topic loop
# output footer only if hits in web
if ( $ntopics == 0 ) {
if ( $zeroResults and not $noTotal ) {
$footer = $params->{footercounter};
}
else {
$footer = '';
}
$webObject = new Foswiki::Meta( $session, $baseWeb );
}