]> git.deb.at Git - deb/packages.git/blob - cgi-bin/search_packages.pl
* Move all the debug/error/message output to functions so that
[deb/packages.git] / cgi-bin / search_packages.pl
1 #!/usr/bin/perl -wT
2 #
3 # search_packages.pl -- CGI interface to the Packages files on packages.debian.org
4 #
5 # Copyright (C) 1998 James Treacy
6 # Copyright (C) 2000, 2001 Josip Rodin
7 # Copyright (C) 2001 Adam Heath
8 # Copyright (C) 2004 Martin Schulze
9 # Copyright (C) 2004-2006 Frank Lichtenheld
10 #
11 # use is allowed under the terms of the GNU Public License (GPL)                              
12 # see http://www.fsf.org/copyleft/gpl.html for a copy of the license
13
14 use strict;
15 use CGI qw( -oldstyle_urls );
16 use CGI::Carp qw( fatalsToBrowser );
17 use POSIX;
18 use URI::Escape;
19 use HTML::Entities;
20 use DB_File;
21 use Benchmark;
22
23 use lib "../lib";
24
25 use Deb::Versions;
26 use Packages::Search qw( :all );
27 use Packages::HTML ();
28
29 my $thisscript = $Packages::HTML::SEARCH_CGI;
30 my $HOME = "http://www.debian.org";
31 my $ROOT = "";
32 my $SEARCHPAGE = "http://packages.debian.org/";
33 my @SUITES = qw( oldstable stable testing unstable experimental );
34 my @SECTIONS = qw( main contrib non-free );
35 my @ARCHIVES = qw( us security installer );
36 my @ARCHITECTURES = qw( alpha amd64 arm hppa hurd-i386 i386 ia64
37                         kfreebsd-i386 mips mipsel powerpc s390 sparc );
38 my %SUITES = map { $_ => 1 } @SUITES;
39 my %SECTIONS = map { $_ => 1 } @SECTIONS;
40 my %ARCHIVES = map { $_ => 1 } @ARCHIVES;
41 my %ARCHITECTURES = map { $_ => 1 } @ARCHITECTURES;
42
43 $ENV{PATH} = "/bin:/usr/bin";
44
45 # Read in all the variables set by the form
46 my $input;
47 if ($ARGV[0] && ($ARGV[0] eq 'php')) {
48         $input = new CGI(\*STDIN);
49 } else {
50         $input = new CGI;
51 }
52
53 my $pet0 = new Benchmark;
54 # use this to disable debugging in production mode completly
55 my $debug_allowed = 1;
56 my $debug = $debug_allowed && $input->param("debug");
57 $debug = 0 if not defined($debug);
58 #$Packages::Search::debug = 1 if $debug > 1;
59
60 # If you want, just print out a list of all of the variables and exit.
61 #print $input->header if $debug;
62 # print $input->dump;
63 # exit;
64
65 if (my $path = $input->param('path')) {
66     my @components = map { lc $_ } split /\//, $path;
67
68     foreach (@components) {
69         if ($SUITES{$_}) {
70             $input->param('suite', $_);
71         } elsif ($SECTIONS{$_}) {
72             $input->param('section', $_);
73         } elsif ($ARCHIVES{$_}) {
74             $input->param('archive', $_);
75         }elsif ($ARCHITECTURES{$_}) {
76             $input->param('arch', $_);
77         }
78     }
79 }
80
81 my ( $format, $keyword, $case, $subword, $exact, $searchon,
82      @suites, @sections, @archs );
83
84 my %params_def = ( keywords => { default => undef,
85                                  match => '^\s*([-+\@\w\/.:]+)\s*$',
86                                  var => \$keyword },
87                    suite => { default => 'stable', match => '^(\w+)$',
88                               alias => 'version', array => ',',
89                               var => \@suites,
90                               replace => { all => \@SUITES } },
91                    case => { default => 'insensitive', match => '^(\w+)$',
92                              var => \$case },
93 #                  official => { default => 0, match => '^(\w+)$' },
94 #                  use_cache => { default => 1, match => '^(\w+)$' },
95                    subword => { default => 0, match => '^(\w+)$',
96                                 var => \$subword },
97                    exact => { default => undef, match => '^(\w+)$',
98                               var => \$exact },
99                    searchon => { default => 'all', match => '^(\w+)$',
100                                  var => \$searchon },
101                    section => { default => 'all', match => '^([\w-]+)$',
102                                 alias => 'release', array => ',',
103                                 var => \@sections,
104                                 replace => { all => \@SECTIONS } },
105                    arch => { default => 'any', match => '^(\w+)$',
106                              array => ',', var => \@archs, replace =>
107                              { any => \@ARCHITECTURES } },
108                    archive => { default => 'all', match => '^(\w+)$',
109                                 array => ',', replace =>
110                                 { all => \@ARCHIVES } },
111                    format => { default => 'html', match => '^(\w+)$',
112                                var => \$format },
113                    );
114 my %opts;
115 my %params = Packages::Search::parse_params( $input, \%params_def, \%opts );
116
117 #XXX: Don't use alternative output formats yet
118 $format = 'html';
119
120 if ($format eq 'html') {
121     print $input->header;
122 } elsif ($format eq 'xml') {
123 #    print $input->header( -type=>'application/rdf+xml' );
124     print $input->header( -type=>'text/plain' );
125 }
126
127 my (@errors, @debug, @msgs, @hints);
128 sub error {
129     push @errors, $_[0];
130 }
131 sub hint {
132     push @hints, $_[0];
133 }
134 sub debug {
135     my $lvl = $_[1] || 0;
136     push(@debug, $_[0]) if $debug > $lvl;
137 }
138 sub msg {
139     push @msgs, $_[0];
140 }
141 sub print_errors {
142     return unless @errors;
143     print '<div>';
144     foreach (@errors) {
145         print "<p style=\"background-color:#F99;font-weight:bold;padding:0.5em;margin:0;\">$_</p>";
146     }
147     print '</div>';
148 }
149 sub print_debug {
150     return unless $debug && @debug;
151     print '<div style="font-size:80%";border:solid thin grey">';
152     print '<h2>Debugging:</h2><pre>';
153     foreach (@debug) {
154         print "$_\n";
155     }
156     print '</pre></div>';
157
158 }
159 sub print_hints {
160     return unless @hints;
161     print '<div>';
162     foreach (@hints) {
163         print "<p style=\"background-color:#FF9;padding:0.5em;margin:0\">$_</p>";
164     }
165     print '</div>';
166 }
167 sub print_msgs {
168     foreach (@msgs) {
169         print "<p>$_</p>";
170     }
171 }
172
173 if ($params{errors}{keywords}) {
174     error( "Error: keyword not valid or missing" );
175 }
176
177 my $case_bool = ( $case !~ /insensitive/ );
178 $exact = !$subword unless defined $exact;
179 $opts{h_suites} = { map { $_ => 1 } @suites };
180 $opts{h_sections} = { map { $_ => 1 } @sections };
181 $opts{h_archs} = { map { $_ => 1 } @archs };
182
183 # for URL construction
184 my $suites_param = join ',', @{$params{values}{suite}{no_replace}};
185 my $sections_param = join ',', @{$params{values}{section}{no_replace}};
186 my $archs_param = join ',', @{$params{values}{arch}{no_replace}};
187
188 # for output
189 my $keyword_enc = encode_entities $keyword;
190 my $searchon_enc = encode_entities $searchon;
191 my $suites_enc = encode_entities join ', ', @{$params{values}{suite}{no_replace}};
192 my $sections_enc = encode_entities join ', ', @{$params{values}{section}{no_replace}};
193 my $archs_enc = encode_entities join ', ',  @{$params{values}{arch}{no_replace}};
194 my $pet1 = new Benchmark;
195 my $petd = timediff($pet1, $pet0);
196 debug( "Parameter evaluation took ".timestr($petd) );
197
198 # read the configuration
199 my $topdir;
200 if (!open (C, "../config.sh")) {
201     error( "Internal Error: Cannot open configuration file." );
202 }
203 while (<C>) {
204     $topdir = $1 if /^\s*topdir="?(.*)"?\s*$/;
205     $ROOT = $1 if /^\s*root="?(.*)"?\s*$/;
206 }
207 close (C);
208
209 my $DBDIR = $topdir . "/files/db";
210 my $search_on_sources = 0;
211
212 my $st0 = new Benchmark;
213 my @results;
214 my $too_many_hits;
215 if ($searchon eq 'sourcenames') {
216     $search_on_sources = 1;
217 }
218
219 sub print_header {
220     print Packages::HTML::header( title => 'Package Search Results' ,
221                                   lang => 'en',
222                                   title_tag => 'Debian Package Search Results',
223                                   print_title_above => 1,
224                                   print_search_field => 'packages',
225                                   search_field_values => { 
226                                       keywords => $keyword_enc,
227                                       searchon => $searchon,
228                                       arch => $archs_enc,
229                                       suite => $suites_enc,
230                                       section => $sections_enc,
231                                       subword => $subword,
232                                       exact => $exact,
233                                       case => $case,
234                                   },
235                                   );
236 }
237
238 sub read_entry {
239     my ($hash, $key, $results, $opts) = @_;
240     my $result = $hash->{$key} || '';
241     foreach (split /\000/, $result) {
242         my @data = split ( /\s/, $_, 7 );
243         debug( "Considering entry ".join( ':', @data), 2);
244         if ($opts->{h_suites}{$data[0]}
245             && ($opts->{h_archs}{$data[1]} || $data[1] eq 'all')
246             && $opts->{h_sections}{$data[2]}) {
247             debug( "Using entry ".join( ':', @data), 2);
248             push @$results, [ $key, @data ];
249         }
250     }
251 }
252 sub read_src_entry {
253     my ($hash, $key, $results, $opts) = @_;
254     my $result = $hash->{$key} || '';
255     foreach (split /\000/, $result) {
256         my @data = split ( /\s/, $_, 5 );
257         debug( "Considering entry ".join( ':', @data), 2);
258         if ($opts->{h_suites}{$data[0]} && $opts->{h_sections}{$data[1]}) {
259             debug( "Using entry ".join( ':', @data), 2);
260             push @$results, [ $key, @data ];
261         }
262     }
263 }
264 sub do_names_search {
265     my ($keyword, $file, $postfix_file, $read_entry, $opts) = @_;
266     my @results;
267
268     $keyword = lc $keyword unless $opts->{case_bool};
269     
270     my $obj = tie my %packages, 'DB_File', "$DBDIR/$file", O_RDONLY, 0666, $DB_BTREE
271         or die "couldn't tie DB $DBDIR/$file: $!";
272     
273     if ($opts->{exact}) {
274         &$read_entry( \%packages, $keyword, \@results, $opts );
275     } else {
276         my ($key, $prefixes) = ($keyword, '');
277         my %pkgs;
278         my $p_obj = tie my %pref, 'DB_File', "$DBDIR/$postfix_file", O_RDONLY, 0666, $DB_BTREE
279             or die "couldn't tie postfix db $DBDIR/$postfix_file: $!";
280         $p_obj->seq( $key, $prefixes, R_CURSOR );
281         while (index($key, $keyword) >= 0) {
282             if ($prefixes =~ /^\001(\d+)/o) {
283                 $too_many_hits += $1;
284             } else {
285                 foreach (split /\000/o, $prefixes) {
286                     $_ = '' if $_ eq '^';
287                     debug( "add word $_$key", 2);
288                     $pkgs{$_.$key}++;
289                 }
290             }
291             last if $p_obj->seq( $key, $prefixes, R_NEXT ) != 0;
292             last if $too_many_hits or keys %pkgs >= 100;
293         }
294         
295         my $no_results = keys %pkgs;
296         if ($too_many_hits || ($no_results >= 100)) {
297             $too_many_hits += $no_results;
298             %pkgs = ( $keyword => 1 );
299         }
300         foreach my $pkg (sort keys %pkgs) {
301             &$read_entry( \%packages, $pkg, \@results, $opts );
302         }
303     }
304     return \@results;
305 }
306 sub do_fulltext_search {
307     my ($keword, $file, $mapping, $lookup, $read_entry, $opts) = @_;
308     my @results;
309
310     my @lines;
311     my $regex;
312     if ($opts->{case_bool}) {
313         if ($opts->{exact}) {
314             $regex = qr/\b\Q$keyword\E\b/o;
315         } else {
316             $regex = qr/\Q$keyword\E/o;
317         }
318     } else {
319         if ($opts->{exact}) {
320             $regex = qr/\b\Q$keyword\E\b/io;
321         } else {
322             $regex = qr/\Q$keyword\E/io;
323         }
324     }
325
326     open DESC, '<', "$DBDIR/$file"
327         or die "couldn't open $DBDIR/$file: $!";
328     while (<DESC>) {
329         $_ =~ $regex or next;
330         debug( "Matched line $.", 2);
331         push @lines, $.;
332     }
333     close DESC;
334
335     tie my %packages, 'DB_File', "$DBDIR/$lookup", O_RDONLY, 0666, $DB_BTREE
336         or die "couldn't tie DB $DBDIR/$lookup: $!";
337     tie my %did2pkg, 'DB_File', "$DBDIR/$mapping", O_RDONLY, 0666, $DB_BTREE
338         or die "couldn't tie DB $DBDIR/$mapping: $!";
339
340     my %tmp_results;
341     foreach my $l (@lines) {
342         my $result = $did2pkg{$l};
343         foreach (split /\000/o, $result) {
344             my @data = split /\s/, $_, 3;
345             next unless $opts->{h_archs}{$data[2]};
346             $tmp_results{$data[0]}++;
347         }
348     }
349     foreach my $pkg (keys %tmp_results) {
350         &$read_entry( \%packages, $pkg, \@results, $opts );
351     }
352     return \@results;
353 }
354
355 sub find_binaries {
356     my ($pkg, $suite) = @_;
357
358     tie my %src2bin, 'DB_File', "$DBDIR/sources_packages.db", O_RDONLY, 0666, $DB_BTREE
359         or die "couldn't open $DBDIR/sources_packages.db: $!";
360
361     my $bins = $src2bin{$pkg} || '';
362     my %bins;
363     foreach (split /\000/o, $bins) {
364         my @data = split /\s/, $_, 4;
365
366         if ($data[0] eq $suite) {
367             $bins{$data[1]}++;
368         }
369     }
370
371     return [ keys %bins ];
372 }
373
374 if ($searchon eq 'names') {
375     push @results, @{ do_names_search( $keyword, 'packages_small.db',
376                                        'package_postfixes.db',
377                                        \&read_entry, \%opts ) };
378 } elsif ($searchon eq 'sourcenames') {
379     push @results, @{ do_names_search( $keyword, 'sources_small.db',
380                                        'source_postfixes.db',
381                                        \&read_src_entry, \%opts ) };
382 } else {
383     push @results, @{ do_names_search( $keyword, 'packages_small.db',
384                                        'package_postfixes.db',
385                                        \&read_entry, \%opts ) };
386     push @results, @{ do_fulltext_search( $keyword, 'descriptions.txt',
387                                           'descriptions_packages.db',
388                                           'packages_small.db',
389                                           \&read_entry, \%opts ) };
390 }
391
392 my $st1 = new Benchmark;
393 my $std = timediff($st1, $st0);
394 debug( "Search took ".timestr($std) );
395
396 if ($format eq 'html') {
397     my $suite_wording = $suites_enc eq "all" ? "all suites"
398         : "suite(s) <em>$suites_enc</em>";
399     my $section_wording = $sections_enc eq 'all' ? "all sections"
400         : "section(s) <em>$sections_enc</em>";
401     my $arch_wording = $archs_enc eq 'any' ? "all architectures"
402         : "architecture(s) <em>$archs_enc</em>";
403     if (($searchon eq "names") || ($searchon eq 'sourcenames')) {
404         my $source_wording = $search_on_sources ? "source " : "";
405         my $exact_wording = $exact ? "named" : "that names contain";
406         msg( "You have searched for ${source_wording}packages $exact_wording <em>$keyword_enc</em> in $suite_wording, $section_wording, and $arch_wording." );
407     } else {
408         my $exact_wording = $exact ? "" : " (including subword matching)";
409         msg( "You have searched for <em>$keyword_enc</em> in packages names and descriptions in $suite_wording, $section_wording, and $arch_wording$exact_wording." );
410     }
411 }
412
413 if ($too_many_hits) {
414     error( "Your search was too wide so we will only display exact matches. At least <em>$too_many_hits</em> results have been omitted and will not be displayed. Please consider using a longer keyword or more keywords." );
415 }
416
417 if (!@results) {
418     if ($format eq 'html') {
419         my $keyword_esc = uri_escape( $keyword );
420         my $printed = 0;
421         if (($searchon eq "names") || ($searchon eq 'sourcenames')) {
422             if (($suites_enc eq 'all')
423                 && ($archs_enc eq 'any')
424                 && ($sections_enc eq 'all')) {
425                 error( "Can't find that package." );
426             } else {
427                 error( "Can't find that package, at least not in that suite ".
428                     ( $search_on_sources ? "" : " and on that architecture" ) )
429             }
430             
431             if ($exact) {
432                 hint( "You have searched only for exact matches of the package name. You can try to search for <a href=\"$thisscript?exact=0&amp;searchon=$searchon&amp;suite=$suites_param&amp;case=$case&amp;section=$sections_param&amp;keywords=$keyword_esc&amp;arch=$archs_param\">package names that contain your search string</a>." );
433             }
434         } else {
435             if (($suites_enc eq 'all')
436                 && ($archs_enc eq 'any')
437                 && ($sections_enc eq 'all')) {
438                 error( "Can't find that string." );
439             } else {
440                 error( "Can't find that string, at least not in that suite ($suites_enc, section $sections_enc) and on that architecture ($archs_enc)." );
441             }
442             
443             unless ($subword) {
444                 hint( "You have searched only for words exactly matching your keywords. You can try to search <a href=\"$thisscript?subword=1&amp;searchon=$searchon&amp;suite=$suites_param&amp;case=$case&amp;section=$sections_param&amp;keywords=$keyword_esc&amp;arch=$archs_param\">allowing subword matching</a>." );
445             }
446         }
447         hint( ( @hints ? "Or you" : "You" )." can try a different search on the <a href=\"$SEARCHPAGE#search_packages\">Packages search page</a>." );
448             
449     }
450 }
451
452 print_header;    
453 print_msgs;
454 print_errors;
455 print_hints;
456 print_debug;
457
458 my (%pkgs, %sect, %part, %desc, %binaries);
459
460 unless ($search_on_sources) {
461     foreach (@results) {
462         my ($pkg_t, $suite, $arch, $section, $subsection,
463             $priority, $version, $desc) = @$_;
464         
465         my ($package) = $pkg_t =~ m/^(.+)/; # untaint
466         $pkgs{$package}{$suite}{$version}{$arch} = 1;
467         $sect{$package}{$suite}{$version} = $subsection;
468         $part{$package}{$suite}{$version} = $section unless $section eq 'main';
469         
470         $desc{$package}{$suite}{$version} = $desc;
471     }
472
473     if ($format eq 'html') {
474         my ($start, $end) = multipageheader( scalar keys %pkgs );
475         my $count = 0;
476         
477         foreach my $pkg (sort keys %pkgs) {
478             $count++;
479             next if $count < $start or $count > $end;
480             printf "<h3>Package %s</h3>\n", $pkg;
481             print "<ul>\n";
482             foreach my $ver (@SUITES) {
483                 if (exists $pkgs{$pkg}{$ver}) {
484                     my @versions = version_sort keys %{$pkgs{$pkg}{$ver}};
485                     my $part_str = "";
486                     if ($part{$pkg}{$ver}{$versions[0]}) {
487                         $part_str = "[<span style=\"color:red\">$part{$pkg}{$ver}{$versions[0]}</span>]";
488                     }
489                     printf "<li><a href=\"$ROOT/%s/%s/%s\">%s</a> (%s): %s   %s\n",
490                     $ver, $sect{$pkg}{$ver}{$versions[0]}, $pkg, $ver, $sect{$pkg}{$ver}{$versions[0]}, $desc{$pkg}{$ver}{$versions[0]}, $part_str;
491                     
492                     foreach my $v (@versions) {
493                         printf "<br>%s: %s\n",
494                         $v, join (" ", (sort keys %{$pkgs{$pkg}{$ver}{$v}}) );
495                     }
496                     print "</li>\n";
497                 }
498             }
499             print "</ul>\n";
500         }
501     }
502 } else {
503     foreach (@results) {
504         my ($package, $suite, $section, $subsection, $priority,
505             $version) = @$_;
506         
507         $pkgs{$package}{$suite} = $version;
508         $sect{$package}{$suite}{source} = $subsection;
509         $part{$package}{$suite}{source} = $section unless $section eq 'main';
510
511         $binaries{$package}{$suite} = find_binaries( $package, $suite );
512     }
513
514     if ($format eq 'html') {
515         my ($start, $end) = multipageheader( scalar keys %pkgs );
516         my $count = 0;
517         
518         foreach my $pkg (sort keys %pkgs) {
519             $count++;
520             next if ($count < $start) or ($count > $end);
521             printf "<h3>Source package %s</h3>\n", $pkg;
522             print "<ul>\n";
523             foreach my $ver (@SUITES) {
524                 if (exists $pkgs{$pkg}{$ver}) {
525                     my $part_str = "";
526                     if ($part{$pkg}{$ver}{source}) {
527                         $part_str = "[<span style=\"color:red\">$part{$pkg}{$ver}{source}</span>]";
528                     }
529                     printf "<li><a href=\"$ROOT/%s/source/%s\">%s</a> (%s): %s   %s", $ver, $pkg, $ver, $sect{$pkg}{$ver}{source}, $pkgs{$pkg}{$ver}, $part_str;
530                     
531                     print "<br>Binary packages: ";
532                     my @bp_links;
533                     foreach my $bp (@{$binaries{$pkg}{$ver}}) {
534                         my $bp_link = sprintf( "<a href=\"$ROOT/%s/%s\">%s</a>",
535                                                $ver, uri_escape( $bp ),  $bp );
536                         push @bp_links, $bp_link;
537                     }
538                     print join( ", ", @bp_links );
539                     print "</li>\n";
540                 }
541             }
542             print "</ul>\n";
543         }
544     }
545 }
546
547 if ($format eq 'html') {
548     &printindexline( scalar keys %pkgs );
549     &printfooter;
550 }
551
552 exit;
553
554 sub printindexline {
555     my $no_results = shift;
556
557     my $index_line;
558     if ($no_results > $opts{number}) {
559         
560         $index_line = prevlink($input,\%params)." | ".
561             indexline( $input, \%params, $no_results)." | ".
562             nextlink($input,\%params, $no_results);
563         
564         print "<p style=\"text-align:center\">$index_line</p>";
565     }
566 }
567
568 sub multipageheader {
569     my $no_results = shift;
570
571     my ($start, $end);
572     if ($opts{number} =~ /^all$/i) {
573         $start = 1;
574         $end = $no_results;
575         $opts{number} = $no_results;
576     } else {
577         $start = Packages::Search::start( \%params );
578         $end = Packages::Search::end( \%params );
579         if ($end > $no_results) { $end = $no_results; }
580     }
581
582     print "<p>Found <em>$no_results</em> matching packages,";
583     if ($end == $start) {
584         print " displaying package $end.</p>";
585     } else {
586         print " displaying packages $start to $end.</p>";
587     }
588
589     printindexline( $no_results );
590
591     if ($no_results > 100) {
592         print "<p>Results per page: ";
593         my @resperpagelinks;
594         for (50, 100, 200) {
595             if ($opts{number} == $_) {
596                 push @resperpagelinks, $_;
597             } else {
598                 push @resperpagelinks, resperpagelink($input,\%params,$_);
599             }
600         }
601         if ($params{values}{number}{final} =~ /^all$/i) {
602             push @resperpagelinks, "all";
603         } else {
604             push @resperpagelinks, resperpagelink($input, \%params,"all");
605         }
606         print join( " | ", @resperpagelinks )."</p>";
607     }
608     return ( $start, $end );
609 }
610
611 sub printfooter {
612 print <<END;
613 </div>
614
615 <hr class="hidecss">
616 <p style="text-align:right;font-size:small;font-stlye:italic"><a href="$SEARCHPAGE">Packages search page</a></p>
617
618 </div>
619 END
620
621 my $pete = new Benchmark;
622 my $petd = timediff($pete, $pet0);
623 print "Total page evaluation took ".timestr($petd)."<br>"
624     if $debug_allowed;
625 print $input->end_html;
626 }
627
628 # vim: ts=8 sw=4