]> git.deb.at Git - deb/packages.git/blob - lib/Packages/DoSearchContents.pm
We welcome DoSearchContents.pm to the "multiple keywords" age
[deb/packages.git] / lib / Packages / DoSearchContents.pm
1 package Packages::DoSearchContents;
2
3 use strict;
4 use warnings;
5
6 use Benchmark ':hireswallclock';
7 use DB_File;
8 use URI::Escape;
9 use HTML::Entities;
10 use Exporter;
11 our @ISA = qw( Exporter );
12 our @EXPORT = qw( do_search_contents );
13
14 use Deb::Versions;
15 use Packages::I18N::Locale;
16 use Packages::Search qw( :all );
17 use Packages::CGI;
18 use Packages::DB;
19 use Packages::Config qw( $DBDIR $SEARCH_URL $SEARCH_PAGE
20                          @SUITES @ARCHIVES @ARCHITECTURES $ROOT );
21
22 sub do_search_contents {
23     my ($params, $opts, $html_header, $menu, $page_content) = @_;
24
25     if ($params->{errors}{keywords}) {
26         fatal_error( _g( "keyword not valid or missing" ) );
27     } elsif (grep { length($_) < 2 } @{$opts->{keywords}}) {
28         fatal_error( _g( "keyword too short (keywords need to have at least two characters)" ) );
29     }
30     if ($params->{errors}{suite}) {
31         fatal_error( _g( "suite not valid or not specified" ) );
32     }
33
34     #FIXME: that's extremely hacky atm
35     if ($params->{values}{suite}{no_replace}[0] eq 'default') {
36         $params->{values}{suite}{no_replace} =
37             $params->{values}{suite}{final} = $opts->{suite} = [ 'stable' ];
38     }
39
40     if (@{$opts->{suite}} > 1) {
41         fatal_error( sprintf( _g( "more than one suite specified for contents search (%s)" ), "@{$opts->{suite}}" ) );
42     }
43
44     $$menu = "";
45     
46     my @keywords = @{$opts->{keywords}};
47     my $mode = $opts->{mode} || '';
48     my $suite = $opts->{suite}[0];
49     my $archive = $opts->{archive}[0] ||'';
50     $Packages::Search::too_many_hits = 0;
51
52     # for URL construction
53     my $keyword_esc = uri_escape( "@keywords" );
54     my $suites_param = join ',', @{$params->{values}{suite}{no_replace}};
55     my $sections_param = join ',', @{$params->{values}{section}{no_replace}};
56     my $archs_param = join ',', @{$params->{values}{arch}{no_replace}};
57
58     # for output
59     my $keyword_enc = encode_entities "@keywords" || '';
60     my $suites_enc = encode_entities( join( ', ', @{$params->{values}{suite}{no_replace}} ), '&<>"' );
61     my $sections_enc = encode_entities( join( ', ', @{$params->{values}{section}{no_replace}} ), '&<>"' );
62     my $archs_enc = encode_entities( join( ', ',  @{$params->{values}{arch}{no_replace}} ), '&<>"' );
63     
64     my $st0 = new Benchmark;
65     my (@results);
66
67     unless (@Packages::CGI::fatal_errors) {
68
69         my $nres = 0;
70
71         my $first_kw = lc shift @keywords;
72         # full filename search is tricky
73         my $ffn = $mode eq 'filename';
74
75         my $reverses = tie my %reverses, 'DB_File', "$DBDIR/contents/reverse_$suite.db",
76             O_RDONLY, 0666, $DB_BTREE
77             or die "Failed opening reverse DB: $!";
78
79         if ($ffn) {
80             open FILENAMES, '-|', 'fgrep', '--', $first_kw, "$DBDIR/contents/filenames_$suite.txt"
81                 or die "Failed opening filename table: $!";
82
83           FILENAME:
84             while (<FILENAMES>) {
85                 chomp;
86                 foreach my $kw (@keywords) {
87                     next FILENAME unless /\Q$kw\E/;
88                 }
89                 &searchfile(\@results, reverse($_)."/", \$nres, $reverses);
90                 last if $Packages::Search::too_many_hits;
91             }
92             close FILENAMES or warn "fgrep error: $!\n";
93         } else {
94
95             error(_g("The search mode you selected doesn't support more than one keyword."))
96                 if @keywords;
97
98             my $kw = reverse $first_kw;
99             
100             # exact filename searching follows trivially:
101             $kw = "$kw/" if $mode eq 'exactfilename';
102
103             &searchfile(\@results, $kw, \$nres, $reverses);
104         }
105         $reverses = undef;
106         untie %reverses;
107
108     
109         my $st1 = new Benchmark;
110         my $std = timediff($st1, $st0);
111         debug( "Search took ".timestr($std) ) if DEBUG;
112     }
113     
114     my $suite_wording = sprintf(_g("suite <em>%s</em>"), $suites_enc );
115     my $section_wording = $sections_enc eq 'all' ? _g("all sections")
116         : sprintf(_g("section(s) <em>%s</em>"), $sections_enc );
117     my $arch_wording = $archs_enc eq 'any' ? _g("all architectures")
118         : sprintf(_g("architecture(s) <em>%s</em>"), $archs_enc );
119     my $wording = _g("paths that end with");
120     if ($mode eq 'filename') {
121         $wording =  _g("files named");
122     } elsif ($mode eq 'exactfilename') {
123         $wording = _g("filenames that contain");
124     }
125     msg( sprintf( _g("You have searched for %s <em>%s</em> in %s, %s, and %s." ),
126                   $wording, $keyword_enc,
127                   $suite_wording, $section_wording, $arch_wording ) );
128
129     if ($mode ne 'filename') {
130         msg( '<a href="'.make_search_url('',"keywords=$keyword_esc",{mode=>'filename'}).
131               "\">"._g("Search within filenames")."</a>");
132     }
133     if ($mode ne 'exactfilename') {
134         msg( '<a href="'.make_search_url('',"keywords=$keyword_esc",{mode=>'exactfilename'}).
135               "\">"._g("Search exact filename")."</a>");
136     }
137     if ($mode eq 'exactfilename' || $mode eq 'filename') {
138         msg( '<a href="'.make_search_url('',"keywords=$keyword_esc",{mode=>undef}).
139               "\">"._g("Search for paths ending with")."</a>");
140     }
141
142     msg( _g("Search in other suite:")." ".
143          join( ' ', map { '[<a href="'.make_search_url('',"keywords=$keyword_esc",{suite=>$_}).
144                               "\">$_</a>]" } @SUITES ) );
145
146     if ($Packages::Search::too_many_hits) {
147         error( _g( "Your search was too wide so we will only display only the first about 100 matches. Please consider using a longer keyword or more keywords." ) );
148     }
149     
150     %$html_header = ( title => _g( 'Package Contents Search Results' ),
151                       lang => $opts->{lang},
152                       title_tag => _g( 'Debian Package Contents Search Results' ),
153                       print_title => 1,
154                       print_search_field => 'packages',
155                       search_field_values => { 
156                           keywords => $keyword_enc,
157                           searchon => 'contents',
158                           arch => $archs_enc,
159                           suite => $suites_enc,
160                           section => $sections_enc,
161                           exact => $opts->{exact},
162                           debug => $opts->{debug},
163                       },
164                       );
165
166     $$page_content = '';
167     my (%results,%archs);
168     foreach my $result (sort { $a->[0] cmp $b->[0] } @results) {
169         my $file = shift @$result;
170         my %pkgs;
171         foreach (@$result) {
172             my ($pkg, $arch) = split /:/, $_;
173             next unless $opts->{h_archs}{$arch};
174             $pkgs{$pkg}{$arch}++;
175             $archs{$arch}++ unless $arch eq 'all';
176         }
177         next unless keys %pkgs;
178         $results{$file} = \%pkgs;
179     }
180     my @all_archs = keys %archs;
181     @all_archs = @ARCHITECTURES unless @all_archs;
182     debug( "all_archs = @all_archs", 1 ) if DEBUG;
183     msg(_g("Limit search to a specific architecture:")." ".
184         join( ' ', map { '[<a href="'.make_search_url('',"keywords=$keyword_esc",{arch=>$_}).
185                              "\">$_</a>]" } @all_archs ) )
186         unless (@{$opts->{arch}} == 1) || (@all_archs == 1);
187     msg(sprintf(_g('Search in <a href="%s">all architectures</a>'),
188                 make_search_url('',"keywords=$keyword_esc",{arch=>undef})))
189         if @{$opts->{arch}} == 1;
190
191     if (!@Packages::CGI::fatal_errors && !keys(%results)) {
192         error( _g( "Nothing found" ) );
193     }
194
195     if (keys %results) {
196         $$page_content .= "<p>".sprintf( _g( 'Found %s results' ),
197                                          scalar keys %results )."</p>";
198         $$page_content .= '<div
199         id="pcontentsres"><table><colgroup><col><col></colgroup><tr><th>'._g('File').'</th><th>'._g('Packages')
200             ."</th></tr>\n";
201         foreach my $file (sort keys %results) {
202                 my $file_enc = encode_entities($file);
203                 foreach my $kw (@{$opts->{keywords}}) {
204                     my $kw_enc = encode_entities($kw);
205                     $file_enc =~ s#(\Q$kw_enc\E)#<span class="keyword">$1</span>#g;
206                 }
207             $$page_content .= "<tr><td class=\"file\">/$file_enc</td><td>";
208             my @pkgs;
209             foreach my $pkg (sort keys %{$results{$file}}) {
210                 my $arch_str = '';
211                 my @archs = keys %{$results{$file}{$pkg}};
212                 unless ($results{$file}{$pkg}{all} ||
213                         (@archs == @all_archs)) {
214                     if (@archs < @all_archs/2) {
215                         $arch_str = ' ['.join(' ',sort @archs).']';
216                     } else {
217                         $arch_str = ' ['._g('not').' '.
218                             join(' ', grep { !$results{$file}{$pkg}{$_} } @all_archs).']';
219                     }
220                 }
221                 push @pkgs, "<a href=\"".make_url($pkg,'',{suite=>$suite})."\">$pkg</a>$arch_str";
222             }
223             $$page_content .= join( ", ", @pkgs);
224             $$page_content .= "</td></tr>\n";
225         }
226         $$page_content .= '<tr><th>'._g('File').'</th><th>'._g('Packages')."</th></tr>\n" if @results > 20;
227         $$page_content .= '</table></div>';
228     }
229 } # sub do_search_contents
230
231 sub searchfile
232 {
233     my ($results, $kw, $nres, $reverses) = @_;
234
235     my ($key, $value) = ($kw, "");
236     debug( "searchfile: kw=$kw", 1 ) if DEBUG;
237     for (my $status = $reverses->seq($key, $value, R_CURSOR);
238         $status == 0;
239         $status =  $reverses->seq( $key, $value, R_NEXT)) {
240
241         # FIXME: what's the most efficient "is prefix of" thingy? We only want to know
242         # whether $kw is or is not a prefix of $key
243         last unless index($key, $kw) == 0;
244         debug( "found $key", 2 ) if DEBUG;
245
246         my @hits = split /\0/o, $value;
247         push @$results, [ scalar reverse($key), @hits ];
248         last if ($$nres)++ > 100;
249     }
250
251     $Packages::Search::too_many_hits += $$nres - 100 if $$nres > 100;
252 }
253
254
255 1;