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