]> git.deb.at Git - deb/packages.git/blob - lib/Packages/Dispatcher.pm
Add L10N support for Template Toolkit output
[deb/packages.git] / lib / Packages / Dispatcher.pm
1 #!/usr/bin/perl -T
2 # Packages::Dispatcher -- CGI interface for packages.debian.org
3 #
4 # Copyright (C) 2004-2007 Frank Lichtenheld
5 #
6 #    This program is free software; you can redistribute it and/or modify
7 #    it under the terms of the GNU General Public License as published by
8 #    the Free Software Foundation; either version 1 of the License, or
9 #    (at your option) any later version.
10 #
11 #    This program is distributed in the hope that it will be useful,
12 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #    GNU General Public License for more details.
15 #
16 #    You should have received a copy of the GNU General Public License
17 #    along with this program; if not, write to the Free Software
18 #    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 package Packages::Dispatcher;
21
22 use strict;
23 use warnings;
24
25 use CGI;
26 use POSIX;
27 use File::Basename;
28 use URI;
29 use URI::Escape;
30 use HTML::Entities;
31 use Template;
32 use DB_File;
33 use Benchmark ':hireswallclock';
34 use I18N::AcceptLanguage;
35 use Locale::gettext;
36
37 use Deb::Versions;
38 use Packages::Config qw( $DBDIR $ROOT $TEMPLATEDIR $CACHEDIR
39                          @SUITES @SECTIONS @ARCHIVES @ARCHITECTURES @PRIORITIES
40                          @LANGUAGES @DDTP_LANGUAGES $LOCALES );
41 use Packages::CGI qw( :DEFAULT error get_all_messages );
42 use Packages::DB;
43 use Packages::Search qw( :all );
44 use Packages::Template ();
45 use Packages::Sections;
46 use Packages::I18N::Locale;
47
48 use Packages::DoSearch;
49 use Packages::DoSearchContents;
50 use Packages::DoShow;
51 use Packages::DoIndex;
52 use Packages::DoNewPkg;
53 use Packages::DoDownload;
54 use Packages::DoFilelist;
55
56
57 sub do_dispatch {
58
59     &Packages::CGI::reset;
60     $Packages::Search::too_many_hits = 0;
61
62     # clean up env
63     $ENV{PATH} = "/bin:/usr/bin";
64     delete $ENV{'LANGUAGE'};
65     delete $ENV{'LANG'};
66     delete $ENV{'LC_ALL'};
67     delete $ENV{'LC_MESSAGES'};
68
69     my %SUITES_ALIAS = ( oldstable => 'sarge',
70                          stable => 'etch',
71                          testing => 'lenny',
72                          unstable => 'sid',
73                          '3.1' => 'sarge',
74                          '4.0' => 'etch' );
75
76     # Read in all the variables set by the form
77     my $input;
78     if ($ARGV[0] && ($ARGV[0] eq 'php')) {
79         $input = new CGI(\*STDIN);
80     } else {
81         $input = new CGI;
82     }
83     my $cgi_error = $input->cgi_error;
84     if ($cgi_error) {
85         fatal_error( "Error parsing the request", $cgi_error );
86     }
87
88     my $pet0 = new Benchmark;
89     my $tet0 = new Benchmark;
90     my $debug = DEBUG && $input->param("debug");
91     $debug = 0 if !defined($debug) || $debug !~ /^\d+$/o;
92     $Packages::CGI::debug = $debug;
93
94     my $homedir = dirname($ENV{SCRIPT_FILENAME}).'/../';
95     &Packages::Config::init( $homedir );
96     &Packages::DB::init();
97
98     my $acc = I18N::AcceptLanguage->new();
99     my %all_langs = map { $_ => 1 } (@LANGUAGES, @DDTP_LANGUAGES);
100     my @all_langs = sort keys %all_langs;
101     my $http_lang = $acc->accepts( $input->http("Accept-Language"),
102                                    \@all_langs ) || 'en';
103     debug( "LANGUAGES=@all_langs header=".
104            ($input->http("Accept-Language")||'').
105            " http_lang=$http_lang", 1 ) if DEBUG;
106     bindtextdomain ( 'pdo', $LOCALES );
107     bindtextdomain ( 'templates', $LOCALES );
108     textdomain( 'pdo' );
109
110     # backwards compatibility stuff
111     debug( "SCRIPT_URL=$ENV{SCRIPT_URL} SCRIPT_URI=$ENV{SCRIPT_URI}" ) if DEBUG;
112
113     if ($ENV{SCRIPT_URL} =~ m|^/cgi-bin/search_|) {
114         error( "You reached this site over an old URL. ".
115                "Depending on the exact parameters your search might work or not." );
116         # contents search changed a lot
117         if ($ENV{SCRIPT_URL} =~ m|^/cgi-bin/search_contents|) {
118             $input->param('keywords',$input->param('word')) if $input->param('word');
119             $input->param('searchon','contents');
120             for ($input->param('searchmode')) {
121                 /^searchfiles/ && do {
122                     $input->param('mode','filename');
123                     last;
124                 };
125                 /^filelist/ && do {
126                     $ENV{PATH_INFO} = '/'.join('/',($input->param('version')||'stable',
127                                                     $input->param('keywords'),
128                                                     $input->param('arch')||'i386',
129                                                     'filelist' ));
130                     $input->delete('searchon','version','keywords','arch');
131                     last;
132                 };
133             }
134         }
135     }
136     if ($ENV{is_reportbug}) {
137         $input->param('exact', 1);
138         debug( "reportbug detected, set paramater exact to '1'" ) if DEBUG;
139     }
140
141     my $what_to_do = 'show';
142     my $source = 0;
143     if (my $path = $input->path_info() || $input->param('PATH_INFO')) {
144         my @components = grep { $_ } map { lc $_ } split /\/+/, $path;
145
146         debug( "PATH_INFO=$path components=@components", 3) if DEBUG;
147
148         push @components, 'index' if @components && $path =~ m,/$,;
149
150         my %LANGUAGES = map { $_ => 1 } @all_langs;
151         if (@components > 0 and $LANGUAGES{$components[0]}
152             and !$input->param('lang')) {
153             $input->param( 'lang', shift(@components) );
154         }
155         if (@components > 0 and $components[0] eq 'source') {
156             shift @components;
157             $input->param( 'source', 1 );
158         }
159         if (@components > 0 and $components[0] eq 'search') {
160             shift @components;
161             $what_to_do = 'search';
162             # Done
163             fatal_error( _g( "search doesn't take any more path elements" ) )
164                 if @components;
165         } elsif (@components == 0) {
166             fatal_error( _g( "We're supposed to display the homepage here, instead of getting dispatch.pl" ) );
167         } elsif (@components == 1) {
168             $what_to_do = 'search';
169         } else {
170
171             for ($components[-1]) {
172                 /^(index|allpackages|newpkg|changelog|copyright|download|filelist)$/ && do {
173                     pop @components;
174                     $what_to_do = $1;
175                     last;
176                 };
177             }
178
179             my %SUITES = map { $_ => 1 } @SUITES;
180             my %SECTIONS = map { $_ => 1 } @SECTIONS;
181             my %ARCHIVES = map { $_ => 1 } @ARCHIVES;
182             my %ARCHITECTURES = map { $_ => 1 } (@ARCHITECTURES, 'all', 'any');
183             my %PRIORITIES = map { $_ => 1 } @PRIORITIES;
184             my %params_set;
185             sub set_param_once {
186                 my ($cgi, $params_set, $key, $val) = @_;
187                 debug("set_param_once key=$key val=$val",4) if DEBUG;
188                 if ($params_set->{$key}++) {
189                     fatal_error( sprintf( _g( "%s set more than once in path" ), $key ) );
190                 } else {
191                     $cgi->param( $key, $val );
192                 }
193             }
194
195             my (@pkg, $need_pkg);
196             foreach (reverse @components) {
197                 $need_pkg = !@pkg
198                     && ($what_to_do !~ /^(index|allpackages|newpkg)$/);
199                 debug("need_pkg=$need_pkg component=$_",4) if DEBUG;
200                 if (!$need_pkg && $SUITES{$_}) {
201                     set_param_once( $input, \%params_set, 'suite', $_);
202                 } elsif (!$need_pkg && (my $s = $SUITES_ALIAS{$_})) {
203                     set_param_once( $input, \%params_set, 'suite', $s);
204                 } elsif (!$need_pkg && $SECTIONS{$_}) {
205                     set_param_once( $input, \%params_set, 'section', $_);
206                 } elsif (!$need_pkg && $ARCHIVES{$_}) {
207                     set_param_once( $input, \%params_set, 'archive', $_);
208                 } elsif (!$need_pkg && $sections_descs{$_}) {
209                     set_param_once( $input, \%params_set, 'subsection', $_);
210                 } elsif (!$need_pkg && ($_ eq 'source')) {
211                     set_param_once( $input, \%params_set, 'source', 1);
212                 } elsif ($ARCHITECTURES{$_}) {
213                     set_param_once( $input, \%params_set, 'arch', $_)
214                         unless $_ eq 'any';
215                 } elsif ($PRIORITIES{$_}) {
216                     set_param_once( $input, \%params_set, 'priority', $_);
217                 } else {
218                     push @pkg, $_;
219                 }
220             }
221             @components = @pkg;
222
223             if (@components > 1) {
224                 fatal_error( sprintf( _g( "two or more packages specified (%s)" ), "@components" ) );
225             }
226         } # else if (@components == 1)
227
228         if (@components) {
229             my $c = uri_unescape($components[0]);
230             $input->param( 'keywords', $c );
231             $input->param( 'package', $c );
232         }
233     }
234
235     my ( $pkg, @suites, @sections, @subsections, @archives, @archs );
236
237     my %params_def = ( keywords => { default => undef,
238                                      array => '\s+',
239                                      match => '^([-+\@\w\/.:]+)$',
240                                  },
241                        'package' => { default => undef,
242                                       match => '^([\w.+-]+)$',
243                                       var => \$pkg },
244                        suite => { default => 'default', match => '^([\w-]+)$',
245                                   array => ',', var => \@suites,
246                                   replace => { all => \@SUITES,
247                                                default => \@SUITES,
248                                                %SUITES_ALIAS } },
249                        archive => { default => ($what_to_do eq 'search') ?
250                                         'all' : 'default',
251                                         match => '^([\w-]+)$',
252                                         array => ',', var => \@archives,
253                                         replace => { all => \@ARCHIVES,
254                                                      default => \@ARCHIVES} },
255                        exact => { default => 0, match => '^(\w+)$',  },
256                        lang => { default => $http_lang, match => '^(\w+)$',  },
257                        source => { default => 0, match => '^(\d+)$',  },
258                        debug => { default => 0, match => '^(\d+)$',  },
259                        searchon => { default => 'names', match => '^(\w+)$', },
260                        section => { default => 'all', match => '^([\w-]+)$',
261                                     alias => 'release', array => ',',
262                                     var => \@sections,
263                                     replace => { all => \@SECTIONS } },
264                        subsection => { default => 'default', match => '^([\w-]+)$',
265                                        array => ',', var => \@subsections,
266                                        replace => { default => [] } },
267                        priority => { default => 'default', match => '^([\w-]+)$',
268                                      array => ',',
269                                      replace => { default => [] } },
270                        arch => { default => 'any', match => '^([\w-]+)$',
271                                  array => ',', var => \@archs, replace =>
272                                  { any => \@ARCHITECTURES } },
273                        'format' => { default => 'html', match => '^([\w.]+)$',  },
274                        mode => { default => '', match => '^(\w+)$',  },
275                        sort_by => { default => 'file', match => '^(\w+)$', },
276                        );
277     my %opts;
278     my %params = Packages::CGI::parse_params( $input, \%params_def, \%opts );
279     Packages::CGI::init_url( $input, \%params, \%opts );
280
281     my $locale = get_locale($opts{lang});
282     my $charset = get_charset($opts{lang});
283     setlocale ( LC_ALL, $locale )
284         or do { debug( "couldn't set locale $locale, using default" ) if DEBUG;
285                 setlocale( LC_ALL, get_locale() )
286                     or do {
287                         debug( "couldn't set default locale either" ) if DEBUG;
288                         setlocale( LC_ALL, "C" );
289                     };
290             };
291     debug( "locale=$locale charset=$charset", 1 ) if DEBUG;
292
293     $opts{h_suites} = { map { $_ => 1 } @suites };
294     $opts{h_sections} = { map { $_ => 1 } @sections };
295     $opts{h_archives} = { map { $_ => 1 } @archives };
296     $opts{h_archs} = { map { $_ => 1 } @archs };
297
298     if ((($opts{searchon} eq 'names') && $opts{source}) ||
299         ($opts{searchon} eq 'sourcenames')) {
300         $opts{source} = 1;
301         $opts{searchon} = 'names',
302         $opts{searchon_form} = 'sourcenames';
303     } else {
304         $opts{searchon_form} = $opts{searchon};
305     }
306     if ($opts{searchon} eq 'contents' or $opts{searchon} eq 'filenames') {
307         $what_to_do = 'search_contents';
308     }
309
310     my $pet1 = new Benchmark;
311     my $petd = timediff($pet1, $pet0);
312     debug( "Parameter evaluation took ".timestr($petd) ) if DEBUG;
313
314     my $template = new Packages::Template( $TEMPLATEDIR, $opts{format},
315                                            { lang => $opts{lang}, charset => $charset,
316                                              debug => ( DEBUG ? $opts{debug} : 0 ) },
317                                            ( $CACHEDIR ? { COMPILE_DIR => $CACHEDIR } : {} ) );
318
319     #FIXME: ugly hack
320     unless (($what_to_do eq 'allpackages' and $opts{format} =~ /^(html|txt\.gz)/)
321             || -e "$TEMPLATEDIR/$opts{format}/${what_to_do}.tmpl") {
322         fatal_error( _g("requested format not available for this document"),
323                      "406 requested format not available");
324     }
325
326     my (%page_content);
327     unless (@Packages::CGI::fatal_errors) {
328         no strict 'refs';
329         &{"do_$what_to_do"}( \%params, \%opts, \%page_content );
330     }
331
332     $page_content{opts} = \%opts;
333     $page_content{params} = \%params;
334
335     $page_content{make_search_url} = sub { return &Packages::CGI::make_search_url(@_) };
336     $page_content{make_url} = sub { return &Packages::CGI::make_url(@_) };
337     $page_content{extract_host} = sub { my $uri = URI->new($_[0]);
338                                         my $host = $uri->host;
339                                         $host .= ':'.$uri->port if $uri->port != $uri->default_port;
340                                         return $host;
341                                     };
342     $page_content{g} = sub { return &Packages::I18N::Locale::tt_gettext(@_) };
343     # needed to work around the limitations of the the FILTER syntax
344     $page_content{html_encode} = sub { return HTML::Entities::encode_entities(@_,'<>&"') };
345     $page_content{uri_escape} = sub { return URI::Escape::uri_escape(@_) };
346     $page_content{quotemeta} = sub { return quotemeta($_[0]) };
347     $page_content{string2id} = sub { return &Packages::CGI::string2id(@_) };
348
349     unless (@Packages::CGI::fatal_errors) {
350         print $input->header(-charset => $charset, -type => get_mime($opts{format}) );
351         #use Data::Dumper;
352         #print '<pre>'.Dumper(\%ENV, \%page_content, get_all_messages()).'</pre>';
353         print $template->page( $what_to_do, { %page_content, %{ get_all_messages() } } );
354     } elsif ($Packages::CGI::http_code && $Packages::CGI::http_code !~ /^2\d\d/) {
355         print $input->header( -charset => $charset, -status => $Packages::CGI::http_code );
356     } else {
357         # We currently have only an error page in html
358         # so no format support here
359         print $input->header( -charset => $charset );
360         print $template->error_page( get_all_messages() );
361     }
362 }
363
364 1;
365 # vim: ts=8 sw=4