]> git.deb.at Git - deb/packages.git/blob - cgi-bin/search_packages.pl
0723387264e48fabdf3bb59506f924192542c423
[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 if ($params{errors}{keywords}) {
128     print "Error: keyword not valid or missing" if $format eq 'html';
129     exit 0;
130 }
131
132 my $case_bool = ( $case !~ /insensitive/ );
133 $exact = !$subword unless defined $exact;
134 $opts{h_suites} = { map { $_ => 1 } @suites };
135 $opts{h_sections} = { map { $_ => 1 } @sections };
136 $opts{h_archs} = { map { $_ => 1 } @archs };
137
138 # for URL construction
139 my $suites_param = join ',', @{$params{values}{suite}{no_replace}};
140 my $sections_param = join ',', @{$params{values}{section}{no_replace}};
141 my $archs_param = join ',', @{$params{values}{arch}{no_replace}};
142
143 # for output
144 my $keyword_enc = encode_entities $keyword;
145 my $searchon_enc = encode_entities $searchon;
146 my $suites_enc = encode_entities join ', ', @{$params{values}{suite}{no_replace}};
147 my $sections_enc = encode_entities join ', ', @{$params{values}{section}{no_replace}};
148 my $archs_enc = encode_entities join ', ',  @{$params{values}{arch}{no_replace}};
149 my $pet1 = new Benchmark;
150 my $petd = timediff($pet1, $pet0);
151 print "DEBUG: Parameter evaluation took ".timestr($petd)."<br>" if $debug;
152
153 if ($format eq 'html') {
154 print Packages::HTML::header( title => 'Package Search Results' ,
155                               lang => 'en',
156                               title_tag => 'Debian Package Search Results',
157                               print_title_above => 1,
158                               print_search_field => 'packages',
159                               search_field_values => { 
160                                   keywords => $keyword_enc,
161                                   searchon => $searchon,
162                                   arch => $archs_enc,
163                                   suite => $suites_enc,
164                                   section => $sections_enc,
165                                   subword => $subword,
166                                   exact => $exact,
167                                   case => $case,
168                                   },
169                               );
170 }
171
172 # read the configuration
173 my $topdir;
174 if (!open (C, "../config.sh")) {
175     print "\nInternal Error: Cannot open configuration file.\n\n"
176 if $format eq 'html';
177     exit 0;
178 }
179 while (<C>) {
180     $topdir = $1 if (/^\s*topdir="?(.*)"?\s*$/);
181 }
182 close (C);
183
184 my $DBDIR = $topdir . "/files/db";
185 my $search_on_sources = 0;
186
187 my $st0 = new Benchmark;
188 my @results;
189 my $too_many_hits;
190 if ($searchon eq 'sourcenames') {
191     $search_on_sources = 1;
192 }
193
194 sub read_entry {
195     my ($hash, $key, $results, $opts) = @_;
196     my $result = $hash->{$key} || '';
197     foreach (split /\000/, $result) {
198         my @data = split ( /\s/, $_, 7 );
199         print "DEBUG: Considering entry ".join( ':', @data)."<br>" if $debug > 2;
200         if ($opts->{h_suites}{$data[0]}
201             && ($opts->{h_archs}{$data[1]} || $data[1] eq 'all')
202             && $opts->{h_sections}{$data[2]}) {
203             print "DEBUG: Using entry ".join( ':', @data)."<br>" if $debug > 2;
204             push @$results, [ $key, @data ];
205         }
206     }
207 }
208 sub read_src_entry {
209     my ($hash, $key, $results, $opts) = @_;
210     my $result = $hash->{$key} || '';
211     foreach (split /\000/, $result) {
212         my @data = split ( /\s/, $_, 5 );
213         print "DEBUG: Considering entry ".join( ':', @data)."<br>" if $debug > 2;
214         if ($opts->{h_suites}{$data[0]} && $opts->{h_sections}{$data[1]}) {
215             print "DEBUG: Using entry ".join( ':', @data)."<br>" if $debug > 2;
216             push @$results, [ $key, @data ];
217         }
218     }
219 }
220 sub do_names_search {
221     my ($keyword, $file, $postfix_file, $read_entry, $opts) = @_;
222     my @results;
223
224     $keyword = lc $keyword unless $opts->{case_bool};
225     
226     my $obj = tie my %packages, 'DB_File', "$DBDIR/$file", O_RDONLY, 0666, $DB_BTREE
227         or die "couldn't tie DB $DBDIR/$file: $!";
228     
229     if ($opts->{exact}) {
230         &$read_entry( \%packages, $keyword, \@results, $opts );
231     } else {
232         my ($key, $prefixes) = ($keyword, '');
233         my %pkgs;
234         my $p_obj = tie my %pref, 'DB_File', "$DBDIR/$postfix_file", O_RDONLY, 0666, $DB_BTREE
235             or die "couldn't tie postfix db $DBDIR/$postfix_file: $!";
236         $p_obj->seq( $key, $prefixes, R_CURSOR );
237         while (index($key, $keyword) >= 0) {
238             if ($prefixes =~ /^\001(\d+)/o) {
239                 $too_many_hits += $1;
240             } else {
241                 foreach (split /\000/o, $prefixes) {
242                     $_ = '' if $_ eq '^';
243                     print "DEBUG: add word $_$key<br>" if $debug > 2;
244                     $pkgs{$_.$key}++;
245                 }
246             }
247             last if $p_obj->seq( $key, $prefixes, R_NEXT ) != 0;
248             last if $too_many_hits or keys %pkgs >= 100;
249         }
250         
251         my $no_results = keys %pkgs;
252         if ($too_many_hits || ($no_results >= 100)) {
253             $too_many_hits += $no_results;
254             %pkgs = ( $keyword => 1 );
255         }
256         foreach my $pkg (sort keys %pkgs) {
257             &$read_entry( \%packages, $pkg, \@results, $opts );
258         }
259     }
260     return \@results;
261 }
262 sub do_fulltext_search {
263     my ($keword, $file, $mapping, $lookup, $read_entry, $opts) = @_;
264     my @results;
265
266     my @lines;
267     my $regex;
268     if ($opts->{case_bool}) {
269         if ($opts->{exact}) {
270             $regex = qr/\b\Q$keyword\E\b/o;
271         } else {
272             $regex = qr/\Q$keyword\E/o;
273         }
274     } else {
275         if ($exact) {
276             $regex = qr/\b\Q$keyword\E\b/io;
277         } else {
278             $regex = qr/\Q$keyword\E/io;
279         }
280     }
281
282     open DESC, '<', "$DBDIR/$file"
283         or die "couldn't open $DBDIR/$file: $!";
284     while (<DESC>) {
285         $_ =~ $regex or next;
286         print "DEBUG: Matched line $.<br>" if $debug > 2;
287         push @lines, $.;
288     }
289     close DESC;
290
291     tie my %packages, 'DB_File', "$DBDIR/$lookup", O_RDONLY, 0666, $DB_BTREE
292         or die "couldn't tie DB $DBDIR/$lookup: $!";
293     tie my %did2pkg, 'DB_File', "$DBDIR/$mapping", O_RDONLY, 0666, $DB_BTREE
294         or die "couldn't tie DB $DBDIR/$mapping: $!";
295
296     my %tmp_results;
297     foreach my $l (@lines) {
298         my $result = $did2pkg{$l};
299         foreach (split /\000/o, $result) {
300             my @data = split /\s/, $_, 3;
301             next unless $opts->{h_archs}{$data[2]};
302             $tmp_results{$data[0]}++;
303         }
304     }
305     foreach my $pkg (keys %tmp_results) {
306         &$read_entry( \%packages, $pkg, \@results, $opts );
307     }
308     return \@results;
309 }
310
311 sub find_binaries {
312     my ($pkg, $suite) = @_;
313
314     tie my %src2bin, 'DB_File', "$DBDIR/sources_packages.db", O_RDONLY, 0666, $DB_BTREE
315         or die "couldn't open $DBDIR/sources_packages.db: $!";
316
317     my $bins = $src2bin{$pkg} || '';
318     my %bins;
319     foreach (split /\000/o, $bins) {
320         my @data = split /\s/, $_, 4;
321
322         if ($data[0] eq $suite) {
323             $bins{$data[1]}++;
324         }
325     }
326
327     return [ keys %bins ];
328 }
329
330 if ($searchon eq 'names') {
331     push @results, @{ do_names_search( $keyword, 'packages_small.db',
332                                        'package_postfixes.db',
333                                        \&read_entry, \%opts ) };
334 } elsif ($searchon eq 'sourcenames') {
335     push @results, @{ do_names_search( $keyword, 'sources_small.db',
336                                        'source_postfixes.db',
337                                        \&read_src_entry, \%opts ) };
338 } else {
339     push @results, @{ do_names_search( $keyword, 'packages_small.db',
340                                        'package_postfixes.db',
341                                        \&read_entry, \%opts ) };
342     push @results, @{ do_fulltext_search( $keyword, 'descriptions.txt',
343                                           'descriptions_packages.db',
344                                           'packages_small.db',
345                                           \&read_entry, \%opts ) };
346 }
347
348 my $st1 = new Benchmark;
349 my $std = timediff($st1, $st0);
350 print "DEBUG: Search took ".timestr($std)."<br>" if $debug;
351
352 if ($format eq 'html') {
353     my $suite_wording = $suites_enc eq "all" ? "all suites"
354         : "suite(s) <em>$suites_enc</em>";
355     my $section_wording = $sections_enc eq 'all' ? "all sections"
356         : "section(s) <em>$sections_enc</em>";
357     my $arch_wording = $archs_enc eq 'any' ? "all architectures"
358         : "architecture(s) <em>$archs_enc</em>";
359     if (($searchon eq "names") || ($searchon eq 'sourcenames')) {
360         my $source_wording = $search_on_sources ? "source " : "";
361         my $exact_wording = $exact ? "named" : "that names contain";
362         print "<p>You have searched for ${source_wording}packages $exact_wording <em>$keyword_enc</em> in $suite_wording, $section_wording, and $arch_wording.</p>";
363     } else {
364         my $exact_wording = $exact ? "" : " (including subword matching)";
365         print "<p>You have searched for <em>$keyword_enc</em> in packages names and descriptions in $suite_wording, $section_wording, and $arch_wording$exact_wording.</p>";
366     }
367 }
368
369 if ($too_many_hits) {
370     print "<p><strong>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.</strong></p>";
371 }
372
373 if (!@results) {
374     if ($format eq 'html') {
375         my $keyword_esc = uri_escape( $keyword );
376         my $printed = 0;
377         if (($searchon eq "names") || ($searchon eq 'sourcenames')) {
378             if (($suites_enc eq 'all')
379                 && ($archs_enc eq 'any')
380                 && ($sections_enc eq 'all')) {
381                 print "<p><strong>Can't find that package.</strong></p>\n";
382             } else {
383                 print "<p><strong>Can't find that package, at least not in that suite ".
384                     ( $search_on_sources ? "" : " and on that architecture" ).
385                     ".</strong></p>\n";
386             }
387             
388             if ($exact) {
389                 $printed = 1;
390                 print "<p>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>.</p>";
391             }
392         } else {
393             if (($suites_enc eq 'all')
394                 && ($archs_enc eq 'any')
395                 && ($sections_enc eq 'all')) {
396                 print "<p><strong>Can't find that string.</strong></p>\n";
397             } else {
398                 print "<p><strong>Can't find that string, at least not in that suite ($suites_enc, section $sections_enc) and on that architecture ($archs_enc).</strong></p>\n";
399             }
400             
401             unless ($subword) {
402                 $printed = 1;
403                 print "<p>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>.</p>";
404             }
405         }
406         print "<p>".( $printed ? "Or you" : "You" )." can try a different search on the <a href=\"$SEARCHPAGE#search_packages\">Packages search page</a>.</p>";
407         
408         &printfooter;
409     }
410     exit;
411 }
412
413 my (%pkgs, %sect, %part, %desc, %binaries);
414
415 unless ($search_on_sources) {
416     foreach (@results) {
417         my ($pkg_t, $suite, $arch, $section, $subsection,
418             $priority, $version, $desc) = @$_;
419         
420         my ($package) = $pkg_t =~ m/^(.+)/; # untaint
421         $pkgs{$package}{$suite}{$version}{$arch} = 1;
422         $sect{$package}{$suite}{$version} = $subsection;
423         $part{$package}{$suite}{$version} = $section unless $section eq 'main';
424         
425         $desc{$package}{$suite}{$version} = $desc;
426     }
427
428     if ($format eq 'html') {
429         my ($start, $end) = multipageheader( scalar keys %pkgs );
430         my $count = 0;
431         
432         foreach my $pkg (sort keys %pkgs) {
433             $count++;
434             next if $count < $start or $count > $end;
435             printf "<h3>Package %s</h3>\n", $pkg;
436             print "<ul>\n";
437             foreach my $ver (@SUITES) {
438                 if (exists $pkgs{$pkg}{$ver}) {
439                     my @versions = version_sort keys %{$pkgs{$pkg}{$ver}};
440                     my $part_str = "";
441                     if ($part{$pkg}{$ver}{$versions[0]}) {
442                         $part_str = "[<span style=\"color:red\">$part{$pkg}{$ver}{$versions[0]}</span>]";
443                     }
444                     printf "<li><a href=\"$ROOT/%s/%s/%s\">%s</a> (%s): %s   %s\n",
445                     $ver, $sect{$pkg}{$ver}{$versions[0]}, $pkg, $ver, $sect{$pkg}{$ver}{$versions[0]}, $desc{$pkg}{$ver}{$versions[0]}, $part_str;
446                     
447                     foreach my $v (@versions) {
448                         printf "<br>%s: %s\n",
449                         $v, join (" ", (sort keys %{$pkgs{$pkg}{$ver}{$v}}) );
450                     }
451                     print "</li>\n";
452                 }
453             }
454             print "</ul>\n";
455         }
456     }
457 } else {
458     foreach (@results) {
459         my ($package, $suite, $section, $subsection, $priority,
460             $version) = @$_;
461         
462         $pkgs{$package}{$suite} = $version;
463         $sect{$package}{$suite}{source} = $subsection;
464         $part{$package}{$suite}{source} = $section unless $section eq 'main';
465
466         $binaries{$package}{$suite} = find_binaries( $package, $suite );
467     }
468
469     if ($format eq 'html') {
470         my ($start, $end) = multipageheader( scalar keys %pkgs );
471         my $count = 0;
472         
473         foreach my $pkg (sort keys %pkgs) {
474             $count++;
475             next if ($count < $start) or ($count > $end);
476             printf "<h3>Source package %s</h3>\n", $pkg;
477             print "<ul>\n";
478             foreach my $ver (@SUITES) {
479                 if (exists $pkgs{$pkg}{$ver}) {
480                     my $part_str = "";
481                     if ($part{$pkg}{$ver}{source}) {
482                         $part_str = "[<span style=\"color:red\">$part{$pkg}{$ver}{source}</span>]";
483                     }
484                     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;
485                     
486                     print "<br>Binary packages: ";
487                     my @bp_links;
488                     foreach my $bp (@{$binaries{$pkg}{$ver}}) {
489                         my $bp_link = sprintf( "<a href=\"$ROOT/%s/%s\">%s</a>",
490                                                $ver, uri_escape( $bp ),  $bp );
491                         push @bp_links, $bp_link;
492                     }
493                     print join( ", ", @bp_links );
494                     print "</li>\n";
495                 }
496             }
497             print "</ul>\n";
498         }
499     }
500 }
501
502 if ($format eq 'html') {
503     &printindexline( scalar keys %pkgs );
504     &printfooter;
505 }
506
507 exit;
508
509 sub printindexline {
510     my $no_results = shift;
511
512     my $index_line;
513     if ($no_results > $opts{number}) {
514         
515         $index_line = prevlink($input,\%params)." | ".
516             indexline( $input, \%params, $no_results)." | ".
517             nextlink($input,\%params, $no_results);
518         
519         print "<p style=\"text-align:center\">$index_line</p>";
520     }
521 }
522
523 sub multipageheader {
524     my $no_results = shift;
525
526     my ($start, $end);
527     if ($opts{number} =~ /^all$/i) {
528         $start = 1;
529         $end = $no_results;
530         $opts{number} = $no_results;
531     } else {
532         $start = Packages::Search::start( \%params );
533         $end = Packages::Search::end( \%params );
534         if ($end > $no_results) { $end = $no_results; }
535     }
536
537     print "<p>Found <em>$no_results</em> matching packages,";
538     if ($end == $start) {
539         print " displaying package $end.</p>";
540     } else {
541         print " displaying packages $start to $end.</p>";
542     }
543
544     printindexline( $no_results );
545
546     if ($no_results > 100) {
547         print "<p>Results per page: ";
548         my @resperpagelinks;
549         for (50, 100, 200) {
550             if ($opts{number} == $_) {
551                 push @resperpagelinks, $_;
552             } else {
553                 push @resperpagelinks, resperpagelink($input,\%params,$_);
554             }
555         }
556         if ($params{values}{number}{final} =~ /^all$/i) {
557             push @resperpagelinks, "all";
558         } else {
559             push @resperpagelinks, resperpagelink($input, \%params,"all");
560         }
561         print join( " | ", @resperpagelinks )."</p>";
562     }
563     return ( $start, $end );
564 }
565
566 sub printfooter {
567 print <<END;
568 </div>
569
570 <hr class="hidecss">
571 <p style="text-align:right;font-size:small;font-stlye:italic"><a href="$SEARCHPAGE">Packages search page</a></p>
572
573 </div>
574 END
575
576 my $pete = new Benchmark;
577 my $petd = timediff($pete, $pet0);
578 print "Total page evaluation took ".timestr($petd)."<br>"
579     if $debug_allowed;
580 print $input->end_html;
581 }
582
583 # vim: ts=8 sw=4