DeDOSified newlines, ugh.
[MyWeb.git] / Web.pm
1 # $Id$
2 # Common functions for HTML/XHTML output generation
3 # Copyright (C) 2003 Jan Kratochvil <project-www.jankratochvil.net@jankratochvil.net>
4
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; exactly version 2 of June 1991 is required
8
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
18
19 package My::Web;
20 require 5.6.0;  # at least 'use warnings;' but we need some 5.6.0+ modules anyway
21 our $VERSION=do { my @r=(q$Revision$=~/\d+/g); sprintf "%d.".("%03d"x$#r),@r; };
22 our $CVS_ID=q$Id$;
23 use strict;
24 use warnings;
25
26 use Exporter;
27 sub Wrequire ($);
28 sub Wuse ($@);
29 our $W;
30 our @EXPORT=qw(&Wrequire &Wuse &a_href &a_href_cz &vskip &img &centerimg &rightimg $W &top_dir &top_dir_disk &Wprint &input_hidden_persistents);
31 our @ISA=qw(Exporter Tie::Handle);
32
33 BEGIN
34 {
35         $W->{"__My::Web_init"}=1;
36
37         sub Wrequire ($)
38         {
39         my($file)=@_;
40
41 #               print STDERR "Wrequire $file\n";
42                 $file=~s#/#::#g;
43                 $file=~s/[.]pm$//;
44                 my $class=$file;
45                 $file=~s#::#/#g;
46                 $file.=".pm";
47                 my $who=$W->{"__PACKAGE__"};
48                 $who||="__My::Web" if $W->{"__My::Web_init"};
49                 if ($who) {
50                         my $aref=($W->{"packages_used"}{$who}||=[]);
51                         push @$aref,$class
52                                         if !{ map(($_=>1),@$aref) }->{$class};  # Prevent duplicated entries.
53                         }
54                 CORE::require $file;
55                 1;      # Otherwise 'require' would already file above.
56         }
57
58         sub Wuse ($@)
59         {
60         my($file,@list)=@_;
61
62 #               print STDERR "Wuse $file\n";
63                 Wrequire $file;
64                 local $Exporter::ExportLevel=$Exporter::ExportLevel+1;
65                 $file->import(@list);
66                 1;
67         }
68 }
69
70 BEGIN { Wuse 'WebConfig'; }     # for %WebConfig
71 require CGI;    # for &escapeHTML
72 require Image::Size;    # for &imgsize
73 use File::Basename;     # &basename
74 use Carp qw(cluck confess);
75 use URI::Escape;
76 require HTTP::BrowserDetect;
77 require HTTP::Negotiate;
78 my $have_Geo_IP; BEGIN { $have_Geo_IP=eval { require Geo::IP; 1; }; }
79 use ModPerl::Util qw(exit);
80 use POSIX qw(strftime);
81 use Tie::Handle;
82 use Apache::Const qw(HTTP_MOVED_TEMPORARILY);
83 use URI;
84 use URI::QueryParam;
85
86
87 #our $W;
88                 # $W->{"title"}
89                 # $W->{"head"}
90                 # $W->{"force_charset"}
91                 # $W->{"heading_done"}
92                 # $W->{"footer_passed"}
93                 # %{$W->{"headers"}}
94                 # %{$W->{"headers_lc"}} # maps lc($headers_key)=>$headers_key
95                 # @{$W->{"packages_used"}{$W->{"__PACKAGE__"}}}
96                 # @{$W->{"packages_used"}{"__My::Web"}}
97                 # %{$W->{"args"}}
98
99 sub init ($%)
100 {
101 my($class,%args)=@_;
102
103         print STDERR "$class->init ".Apache->request()->unparsed_uri()."\n";
104
105         my $packages_used_save=$W->{"packages_used"};
106         $W={ %WebConfig,%args };        # override %WebConfig settings
107         $W->{"packages_used"}=$packages_used_save;
108
109         # {"__PACKAGE__"} is mandatory for mod_perl-2.0;
110         # $Apache::Registry::curstash is no longer supported.
111         do { cluck "No $_" if !$W->{$_}; } for "__PACKAGE__";
112
113         $W->{"top_dir"}||=eval '$'.$W->{"__PACKAGE__"}.'::top_dir';
114
115         do { $W->{$_}=0  if !defined $W->{$_}; } for ("detect_ent");
116         do { $W->{$_}=0  if !defined $W->{$_}; } for ("detect_js");
117         do { $W->{$_}=1  if !defined $W->{$_}; } for ("have_css");      # AFAIK it does not hurt anyone.
118         do { $W->{$_}=1  if !defined $W->{$_}; } for ("footer");
119         do { $W->{$_}=1  if !defined $W->{$_}; } for ("footer_delimit");
120         do { $W->{$_}=1  if !defined $W->{$_}; } for ("footer_mailme");
121         do { $W->{$_}=1  if !defined $W->{$_}; } for ("footer_ids");
122         do { $W->{$_}=1  if !defined $W->{$_}; } for ("indexme");
123         do { $W->{$_}="" if !defined $W->{$_}; } for ("head");
124         do { $W->{$_}="" if !defined $W->{$_}; } for ("body_attr");
125         do { $W->{$_}="en-US" if !defined $W->{$_}; } for ("language");
126
127         my $footer_any=0;
128         for (qw(footer_mailme footer_ids)) {
129                 $W->{$_}=0 if !$W->{"footer"};
130                 $footer_any=1 if $W->{$_};
131                 }
132         $W->{"footer"}=0 if !$footer_any;
133         $W->{"footer_delimit"}=0 if !$W->{"footer"};
134
135         $W->{"r"}=Apache->request();
136
137         $W->{"QUERY_STRING"}=$W->{"r"}->args() || "";
138         if ($W->{"detect_ent"}) {
139                          if ($W->{"QUERY_STRING"}=~/[&]amp;have_ent/)
140                         { $W->{"have_ent"}=0; }
141                 elsif ($W->{"QUERY_STRING"}=~    /[&]have_ent/)
142                         { $W->{"have_ent"}=1; }
143                 else
144                         { delete $W->{"have_ent"}; }
145                 if (!defined $W->{"have_ent"} && $W->{"r"}->method() eq "GET") {
146                         $W->{"head"}.='<meta http-equiv="Refresh" content="0; URL='
147                                         .CGI::escapeHTML("http://".&{$W->{"web_hostname_sub"}}()."/".($W->{"r"}->uri()=~m#^/*(.*)$#)[0]
148                                                         ."?".($W->{"QUERY_STRING"} || "detect_ent_glue=1").'&have_ent=detect')
149                                         .'" />'."\n";
150                         }
151                 }
152         $W->{"QUERY_STRING"}=~s/([&])amp;/$1/g;
153         $W->{"r"}->args($W->{"QUERY_STRING"});
154         # Workaround: &CGI::Vars behaves weird if strings passed both as POST data and in: $QUERY_STRING
155         do { $W->{"r"}->args(""); delete $ENV{"QUERY_STRING"}; } if $W->{"r"}->method() eq "POST";
156         # Do not: $W->{"r"}->args()
157         # as it parses only QUERY_STRING (not POST data).
158         $W->{"args"}={ CGI->new($W->{"r"})->Vars() };
159         for my $name (keys(%{$W->{"args"}})) {
160                 my @vals=split /\x00/,$W->{"args"}{$name};
161                 next if @vals<=1;
162                 $W->{"args"}{$name}=[@vals];
163                 }
164
165         do { $W->{$_}=$W->{"r"}->headers_in()->{"Accept"}     if !defined $W->{$_}; } for ("accept");
166         do { $W->{$_}=$W->{"r"}->headers_in()->{"User-Agent"} if !defined $W->{$_}; } for ("user_agent");
167
168         $W->{"browser"}=HTTP::BrowserDetect->new($W->{"user_agent"});
169
170         if (!defined $W->{"have_style"}) {
171                 $W->{"have_style"}=(!$W->{"browser"}->netscape() || ($W->{"browser"}->major() && $W->{"browser"}->major()>4) ? 1 : 0);
172                 }
173
174         $W->{"have_js"}=($W->{"args"}{"have_js"} ? 1 : 0);
175         if ($W->{"detect_js"} && !$W->{"have_js"}) {
176                 $W->{"head"}.='<script type="text/javascript" src="'.top_dir('/have_js.js.pl').'"></script>'."\n";
177                 }
178
179         do { args_check(%$_) if $_; } for ($W->{"args_check"});
180
181         $ENV{"HOSTNAME"}||=&{$W->{"web_hostname_sub"}}();
182
183         return bless $W,$class;
184 }
185
186 sub Wprint($)
187 {
188 my($text)=@_;
189
190         $W->{"r"}->puts($text);
191 }
192
193 # local *FH;
194 # tie *FH,ref($W),$W;
195 sub TIEHANDLE($)
196 {
197 my($class,$W)=@_;
198
199         my $self={};
200         $self->{"W"}=$W or confess "Missing W";
201         return bless $self,$class;
202 }
203
204 sub WRITE
205 {
206 my($self,$scalar,$length,$offset)=@_;
207
208         Wprint substr($scalar,0,$length);
209 }
210
211 sub top_dir_disk ()
212 {
213         do { return $_ if $_; } for ($W->{"top_dir"});
214         return $INC[0]; # fallback
215 }
216
217 # $args{"abs"}
218 sub top_dir (;$%)
219 {
220 my($in,%args)=@_;
221
222         if (my $uri=$W->{"r"}->unparsed_uri()) {
223                 if ($W->{"args"}{"Wabs"} || $args{"abs"}) {
224                         # FIXME: $in may not be defined here!
225                         # to prevent: Use of uninitialized value in ...
226                         if ($in=~m#^/#) {
227                                 $in=~s#^/*##;
228                                 }
229                         else {
230                                 $in=$uri."/".$in;
231                                 $in=~tr#/#/#s;
232                                 1 while $in=~s#/(?:[^/]+)/\Q..\E/#/#g
233                                 }
234                         return "http://".&{$W->{"web_hostname_sub"}}()."/".(defined $in ? $in : "");
235                         }
236                 $uri.="Index" if $uri=~m#/$#;
237                 if (defined $in) {
238                         my($inpath,$inquery)=split /[?]/,$in,2;
239                         $inpath=~tr///cs;
240                         $uri=~tr///cs;
241                         for (;;) {
242                                 my($in1 ,$in2 )=($in =~m#^(/[^/]+)(/.*)$#);
243                                 my($uri1,$uri2)=($uri=~m#^(/[^/]+)(/.*)$#);
244                                 last if !defined $in1 || !defined $uri1 || $in1 ne $uri1;
245                                 $in=$in2;
246                                 $uri=$uri2;
247                                 }
248                         }
249                 $uri=~s#^/*##;
250                 $uri=~s#[^/]+#..#g;
251                 $uri=File::Basename::dirname($uri);
252                 my $r=$uri.(defined $in ? $in : "");
253 #               1 while $r=~s#^[.]/##;
254 #               $r="./$r" if $r=~m#^(?:?.*)$#;  # empty pathname?
255                 return $r;
256                 }
257         return top_dir_disk().$in;
258 }
259
260 sub fatal (;$);
261
262 sub args_check (%)
263 {
264 my(%tmpl)=@_;
265
266         while (my($name,$regex)=each(%tmpl)) {
267                 my $name_html="Parameter <span class=\"quote\">".CGI::escapeHTML($name)."</span>";
268                 $W->{"args"}{$name}="" if !defined $W->{"args"}{$name};
269                 $W->{"args"}{$name}=[ $W->{"args"}{$name} ] if !ref $W->{"args"}{$name} && ref $regex;
270                 fatal "$name_html passed as multivar although singlevar expected"
271                                 if ref $W->{"args"}{$name} && !ref $regex;
272                 $regex=$regex->[0] if ref $regex;
273                 for my $val (!ref $W->{"args"}{$name} ? $W->{"args"}{$name} : @{$W->{"args"}{$name}}) {
274                         $val="" if !defined $val;
275                         fatal "$name_html <span class=\"quote\">".CGI::escapeHTML($val)."</span>"
276                                                         ." does not match the required regex <span class=\"quote\">".CGI::escapeHTML($regex)."</span> "
277                                         if $regex ne "" && $val!~/$regex/;
278                         }
279                 }
280 }
281
282 sub vskip (;$)
283 {
284 my($height)=@_;
285
286         return '<p'.(!defined $height ? "" : ' style="height: '.$height.';"').'>&nbsp;</p>'."\n";
287 }
288
289 sub fatal (;$)
290 {
291 my($msg)=@_;
292
293         $msg="UNKNOWN" if !$msg;
294         cluck "FATAL: $msg";
295
296         $W->{"indexme"}=0;      # For the case no heading was sent yet.
297         $W->{"heading_done"}=0; # for the case of already sent {"header_only"}==1
298         $W->{"header_only"}=0;  # assurance for &heading
299         My::Web->heading();
300         Wprint "\n".vskip("3ex")."<hr /><h1 class=\"error\">FATAL ERROR: $msg!</h1>\n"
301                         ."<p>You can report this problem's details to"
302                         ." ".a_href("mailto:".$W->{"admin_mail"},"admin of this website").".</p>\n";
303         footer();
304 }
305
306 sub footer (;$)
307 {
308         exit 1 if $W->{"footer_passed"}++;      # deadlock prevention:
309
310         Wprint vskip if $W->{"footer_delimit"};
311
312         do { &{$_}() if $_; } for ($W->{"footing_delimit"});
313
314         Wprint "<hr />\n" if $W->{"footer"};
315
316         if ($W->{"footer_mailme"}) {
317                 Wprint '<form action="'.top_dir('/SendMsg.pl').'" method="post" onsubmit="'
318                                 ."this.elements['msgscript'].value=this.elements['msghtml'].value;"
319                                 ."this.elements['msghtml'].value='';"
320                                 ."this.submit();"
321                                 .'">'."\n";
322                         Wprint input_hidden_persistents()."\n";
323                         Wprint '<p align="right">'."\n";
324                                 Wprint '<input name="msgscript" type="hidden" />'."\n";
325                                 Wprint '<input name="msghtml" type="text" size="32" alt="Message" />'."\n";
326                                 Wprint '<input name="submit" type="submit" value="Quick Note" />'."\n";
327                         Wprint '</p>'."\n";
328                 Wprint '</form>'."\n";
329                 }
330
331         my @packages_used=(
332                         $W->{"__PACKAGE__"},
333                         __PACKAGE__,
334                         @{$W->{"packages_used"}{"__My::Web"}},
335                         map((!$_ ? () : @$_),$W->{"packages_used"}{$W->{"__PACKAGE__"}}),
336                         );
337         my %packages_used;
338         @packages_used=grep((!$packages_used{$_}++),@packages_used);
339         if ($W->{"footer_ids"}) {
340                 Wprint '<p class="cvs-id">';
341                 Wprint join("<br />\n",map({ my $package=$_;
342                         my $cvs_id=(eval('$'.$package."::CVS_ID")
343 #                                       || $package     # debug
344                                         );
345                         if (!$cvs_id) {
346                                 ();
347                                 }
348                         else {
349                                 $cvs_id='$'.$cvs_id.'$';        # Eaten by 'q' operator.
350                                 my @cvs_id_split=split / +/,$cvs_id;
351                                 if (@cvs_id_split==8) {
352                                         my $file=$package;
353                                         $file=~s#::#/#g;
354                                         my $ext;
355                                         my @tried;
356                                         for (qw(.html.pl .pl .pm),"") {
357                                                 $ext=$_;
358                                                 my $pathname=top_dir_disk()."/$file$ext";
359                                                 push @tried,$pathname;
360                                                 last if -r $pathname;
361                                                 cluck "Class file $file not found; tried: ".join(" ",@tried) if !$ext;
362                                                 }
363                                         $file.=$ext;
364                                         $cvs_id_split[2]=""
365                                                         .a_href((map({ my $s=$_; $s=~s#/viewcvs/#$&~checkout~/#; $s; } $W->{"viewcvs"}))[0]."$file?rev=".$cvs_id_split[2],
366                                                                         $cvs_id_split[2]);
367                                         $cvs_id_split[1]=a_href($W->{"viewcvs"}.$file,
368                                                         ($package!~/^Apache::/ ? $package : $cvs_id_split[1]));
369                                         $cvs_id_split[5]=&{$W->{"cvs_id_author"}}($cvs_id_split[5]);
370                                         }
371                                 join " ",@cvs_id_split;
372                                 }
373                         } @packages_used));
374                 Wprint "</p>\n";
375                 }
376
377         for my $package (@packages_used) {
378                 my $cvs_id=(eval('$'.$package."::CVS_ID")
379 #                               || $package     # debug
380                                 );
381                 Wprint '<!-- '.$package.' - $'.$cvs_id.'$ -->'."\n" if $cvs_id;
382                 }
383
384         do { &{$_}() if $_; } for ($W->{"footing"});
385
386         Wprint "</body></html>\n";
387         exit(0);
388 }
389
390 sub header (%)
391 {
392 my(%pairs)=@_;
393
394         while (my($key,$val)=each(%pairs)) {
395                 do { cluck "Headers already sent"; next; } if $W->{"heading_done"};
396                 for ($W->{"headers_lc"}{lc $key} || ()) {
397                         delete $W->{"headers"}{$_};
398                         }
399                 $W->{"headers_lc"}{lc $key}=$key;
400                 $W->{"headers"}{$key}=$val;
401                 }
402 }
403
404 sub size_display ($)
405 {
406 my($size)=@_;
407
408            if ($size<4096)
409                 {}
410         elsif ($size<1024*1024)
411                 { $size=sprintf "%.1fK",$size/1024; }
412         else
413                 { $size=sprintf "%.1fM",$size/1024/1024; }
414         $size.="B";
415         return $size;
416 }
417
418 sub url_is_local ($)
419 {
420 my($url)=@_;
421
422         return $url!~m#^[a-z]+://#;
423 }
424
425 sub url_out($%)
426 {
427 my($url,%args)=@_;
428
429         return $url if !url_is_local $url;
430         $url=top_dir($url,%args) if $url=~m#^/# || $args{"abs"};
431
432         my $uri=URI->new($url);
433         # Prefer the $uri values over "args_persistent" values.
434         $uri->query_form_hash({
435                         map({
436                                 my $key=$_;
437                                 my $val=$W->{"args"}{$key};
438                                 (!defined $val ? () : ($key=>$val));
439                                 } keys(%{$W->{"args_persistent"}})),
440                         %{$uri->query_form_hash()},
441                         });
442         $url="".$uri;
443
444         return $url;
445 }
446
447 sub a_href ($;$%)
448 {
449 my($url,$contents,%args)=@_;
450
451         do { $$_=1 if !defined $$_; } for (\$args{"size"});
452         if (!defined $contents) {
453                 $contents=$url;
454                 $contents=File::Basename::basename($contents) if $args{"basename"};
455                 $contents=CGI::escapeHTML($contents);
456                 }
457         $contents=~s#<a\b[^>]*>##gi;
458         $contents=~s#</a>##gi;
459
460         $url=url_out($url,%args);
461
462         my $r='<a href="';
463         my $urlent=CGI::escapeHTML($url);
464            if ($url eq $urlent)
465                 { $r.=$url; }
466         elsif (url_is_local $url)
467                 { $r.=$urlent; }
468         elsif (defined $W->{"have_ent"} && !$W->{"have_ent"})   # non-ent client
469                 { $r.=$url; }
470         elsif ($W->{"have_ent"})        # ent client
471                 { $r.=$urlent; }
472         else    # unknown client, &CGI::escapeHTML should not be needed here
473                 { $r.=CGI::escapeHTML(top_dir('/Redirect.pl?location='.uri_escape($url))); }
474         $r.='"';
475         do { $r.=" $_" if $_; } for ($args{"attr"});
476         $r.='>'.$contents.'</a>';
477         if ($args{"size"} && url_is_local($url) && ($args{"size"}>=2 || $url=~/[.](?:gz|Z|rpm|zip|deb|lha)/)) { # Downloadable?
478                 $url=top_dir_disk().$url if $url=~m#^/#;
479                 if (!-r $url)
480                         { cluck "File not readable: $url"; }
481                 else {
482                         $r.='&nbsp;('.size_display((stat($url))[7]).')';
483                         }
484                 }
485         return $r;
486 }
487
488 sub input_hidden_persistents()
489 {
490         return join("",map({
491                 my $key=$_;
492                 my $val=$W->{"args"}{$key};
493                 (!defined $val ? () : '<input type="hidden"'
494                                 .' name="'.CGI::escapeHTML($key).'"'
495                                 .' value="'.CGI::escapeHTML($val).'"'
496                                 .' />'."\n");
497                 } (keys(%{$W->{"args_persistent"}}))));
498 }
499
500 sub http_moved($$;$)
501 {
502 my($self,$url,$status)=@_;
503
504         $url=url_out($url,"abs"=>1);
505         $status||=Apache::HTTP_MOVED_TEMPORARILY;
506         $W->{"r"}->status($status);
507         $W->{"r"}->header_out("Location"=>$url);
508         $W->{"header_only"}=1;
509         My::Web->heading();
510         exit;
511         die "NOTREACHED";
512 }
513
514 sub remote_ip ()
515 {
516         # Do not: PerlModule                 Apache::ForwardedFor
517         #         PerlPostReadRequestHandler Apache::ForwardedFor
518         # As 'Apache::ForwardedFor' takes the first of $ENV{"HTTP_X_FORWARDED_FOR"}
519         # while the contents is '127.0.0.1, 213.220.195.171' if client has its own proxy.
520         # We must take the last item ourselves.
521         my $r=$W->{"r"}->headers_in()->{"X-Forwarded-For"} || $W->{"r"}->get_remote_host();
522         $r=~s/^.*,\s*//;
523         return $r;
524 }
525
526 sub is_cz ()
527 {
528         return 0 if !$have_Geo_IP;
529         return "CZ" eq Geo::IP->new()->country_code_by_addr(remote_ip());
530 }
531
532 sub a_href_cz ($$;%)
533 {
534 my($url,$contents,%args)=@_;
535
536         return a_href $url,$contents,%args if is_cz();
537         return $contents;
538 }
539
540 sub make ($)
541 {
542 my($cmd)=@_;
543
544         system {'flock'} 'flock','-x',top_dir_disk(),$cmd.' >&2';
545 }
546
547 sub img_size ($$)
548 {
549 my($width,$height)=@_;
550
551         return ($W->{"have_style"} ? "style=\"border:0;width:${width}px;height:${height}px\"" : "border=\"0\"")
552                         ." width=\"$width\" height=\"$height\"";
553 }
554
555 sub negotiate_variant (%)
556 {
557 my(%args)=@_;
558
559         my @fields=("id","qs","content-type","encoding","charset","lang","size");
560         return [ map(($args{$_}),@fields) ];
561 }
562
563 # Input: $self is required!
564 # Input: Put the fallback variant as the first one.
565 # Returns: always only scalar!
566 sub Negotiate_choose($$)
567 {
568 my($self,$variants)=@_;
569
570         my $best=HTTP::Negotiate::choose($variants,
571                         # Do not: $W->{"r"}
572                         # to prevent: Can't locate object method "scan" via package "Apache::RequestRec" at HTTP/Negotiate.pm line 84.
573                         # Do not: $W->{"r"}->headers_in()
574                         # to prevent: Can't locate object method "scan" via package "APR::Table" at HTTP/Negotiate.pm line 84.
575                         # Do not: HTTP::Headers->new($W->{"r"}->headers_in());
576                         # to prevent empty result or even: Odd number of elements in anonymous hash
577                         HTTP::Headers->new(%{$W->{"r"}->headers_in()}));
578         $best||=$variants->[0]{"id"};   # &HTTP::Negotiate::choose failed?
579         return $best;
580 }
581
582 my @img_variants=(
583                 { "id"=>"png","qs"=>0.9,"content-type"=>"image/png" },
584                 { "id"=>"gif","qs"=>0.7,"content-type"=>"image/gif" },
585                 );
586 my $img_variants_re='[.](?:'.join('|',"jpeg",map(($_->{"id"}),@img_variants)).')$';
587
588 sub img_src ($)
589 {
590 my($file_base)=@_;
591
592         if (!url_is_local($file_base)) {
593                 return $file_base if !wantarray();
594                 return ($file_base,$file_base);
595                 }
596         # Known image extension?
597         if ($file_base=~m#$img_variants_re#o) {
598                 return $file_base if !wantarray();
599                 return ($file_base,$file_base) if $file_base!~m#^/#;
600                 return (top_dir($file_base),top_dir_disk().$file_base);
601                 }
602
603         my $file_base_disk;
604         my $file_base_uri;
605         if ($file_base!~m#^/#) {
606                 $file_base_disk=$file_base_uri=$file_base;
607                 }
608         else {
609                 $file_base_disk=top_dir_disk().$file_base;
610                 $file_base_uri=top_dir($file_base);
611                 }
612
613         my @nego_variants;
614         for my $var (@img_variants) {
615                 my $file=$file_base_disk.".".$var->{"id"};
616                 # TODO: Somehow quickly check dependencies?
617                 make('make -s --no-print-directory'
618                                                 .' -C '."'".File::Basename::dirname($file)."' '".File::Basename::basename($file)."'")
619                                 if !-f $file;
620                 push @nego_variants,negotiate_variant(
621                                 %$var,
622                                 "size"=>(stat $file)[7],
623                                 );
624                 }
625         my $ext=__PACKAGE__->Negotiate_choose(\@nego_variants);
626
627         return $file_base_uri.".".$ext if !wantarray();
628         return ($file_base_uri.".".$ext,$file_base_disk.".".$ext);
629 }
630
631 sub img ($$;%)
632 {
633 my($file_base,$alt,%attr)=@_;
634
635         my($file_uri,$file_disk)=img_src $file_base;
636         my($width,$height)=Image::Size::imgsize($file_disk);
637         $alt=~s/<[^>]*>//g;
638         $alt=CGI::escapeHTML($alt);
639         my $content="<img src=\"$file_uri\" alt=\"$alt\" title=\"$alt\" ".img_size($width,$height)
640                         .(!$attr{"attr"} ? "" : " ".$attr{"attr"})." />";
641         return a_href img_src($attr{"a_href_img"}),$content if $attr{"a_href_img"};
642         return a_href $attr{"a_href"},$content if $attr{"a_href"};
643         return $content;
644 }
645
646 sub centerimg
647 {
648         my $r.="";
649         $r.='<table border="0" width="100%"><tr>'."\n";
650         @_=( [@_] ) if !ref $_[0];
651         for (@_) {
652                 $r.="\t".'<td align="center">'.&{\&img}(@$_).'</td>'."\n";
653                 }
654         $r.='</tr></table>'."\n";
655         return $r;
656 }
657
658 sub rightimg
659 {
660 my($text,@args_img)=@_;
661
662         # Workaround bug of 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)':
663         return <<"HERE";
664 <table border="0" width="100%">
665         <col width="@{[ (!$W->{"browser"}->ie() ? "1*" : "90%" ) ]}" />
666         <col width="@{[ (!$W->{"browser"}->ie() ? "0*" : "10%" ) ]}" />
667         <tr>
668                 <td align="left">
669                         @{[ $text ]}
670                 </td>
671                 <td align="right">
672                         @{[ &{\&img}(@args_img) ]}
673                 </td>
674         </tr>
675 </table>
676 HERE
677 }
678
679 sub readfile ($$)
680 {
681 my($class,$filename)=@_;
682
683         local *F;
684         open F,$filename or die "Cannot open \"$filename\": $!";
685         local $/=undef();
686         my $data=<F>;
687         close F;
688         return $data;
689 }
690
691 sub arr_keys (@)
692 {
693 my(@arr)=@_;
694
695         my @r=();
696         while (@arr) {
697                 push @r,shift @arr;     # key
698                 shift @arr;     # val
699                 }
700         return @r;
701 }
702
703 sub no_cache($)
704 {
705 my($self)=@_;
706
707         header("Expires"=>"Mon, 26 Jul 1997 05:00:00 GMT");     # date in the past
708         header("Last-Modified"=>strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime()));        # always modified
709         header("Cache-Control"=>"no-cache, must-revalidate");   # HTTP/1.1
710         header("Pragma"=>"no-cache");   # HTTP/1.0
711 }
712
713 sub heading ()
714 {
715 my($class)=@_;
716
717         # $ENV{"CLIENT_CHARSET"} ignored (mod_czech support dropped!)
718         my $client_charset=$W->{"force_charset"} || "us-ascii";
719         header("Content-Style-Type"=>"text/css");
720         header("Content-Script-Type"=>"text/javascript");
721         do { header("Content-Language"=>$_) if $_; } for $W->{"language"};
722         $class->no_cache() if $W->{"no_cache"};
723
724         while (my($key,$val)=each(%{$W->{"headers"}})) {
725                 $W->{"r"}->header_out($key,$val);
726                 }
727         exit if $W->{"r"}->header_only();
728         return if $W->{"header_only"};
729         # We still can append headers before we put out some text.
730         # FIXME: It is not clean to still append them without overwriting.
731         return if $W->{"heading_done"}++;
732
733         my $lang=($W->{"language"}||"en-US");
734         # Workaround bug
735         #   https://bugzilla.mozilla.org/show_bug.cgi?id=120556
736         # of at least
737         #   Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8b) Gecko/20050217
738         my $mime=$class->Negotiate_choose([
739                         # Put the fallback variant as the first one.
740                         # Rate both variants the same to prefer "text/html" for undecided clients.
741                         # At least
742                         #   Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8b) Gecko/20050217
743                         # prefers "application/xhtml+xml" over "text/html" itself:
744                         #   text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
745                         negotiate_variant(
746                                         "id"=>"text/html",
747                                         "content-type"=>"text/html",
748                                         "qs"=>0.6,
749                                         "charset"=>$client_charset,
750                                         "lang"=>$lang,
751                                         ),
752                         negotiate_variant(
753                                         "id"=>"application/xhtml+xml",
754                                         "content-type"=>"application/xhtml+xml",
755                                         "qs"=>0.6,
756                                         "charset"=>$client_charset,
757                                         "lang"=>$lang,
758                                         ),
759                         # application/xml ?
760                         # text/xml ?
761                         ]);
762         $W->{"r"}->send_http_header("$mime; charset=$client_charset");  # "Content-type"; do not use header()
763         if (1) { # || !$msie_major || $msie_major>=4) # TODO:dyn
764                 Wprint '<?xml version="1.0" encoding="'.$client_charset.'"?>'."\n";
765                 }
766         Wprint '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'."\n";
767         Wprint '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.$lang.'">'."\n";
768         my $title=$W->{"title_prefix"}.join("",map({ ': '.$_; } ($W->{"title"} || ())));
769         $title=~s#<[^>]*>##g;
770         Wprint "<head>";
771         Wprint "<title>$title</title>\n";
772         if ($W->{"have_css"}) {
773                 # Everything can get overriden later.
774                 Wprint <<"HERE";
775 <link rel="stylesheet" type="text/css" href="@{[ url_out("/My/Web.css") ]}" />
776 HERE
777                 }
778         Wprint '<meta name="robots" content="'.($W->{"indexme"} ? "" : "no" ).'index,follow" />'."\n";
779         Wprint $W->{"head"};
780         for my $type (qw(prev next index contents start up)) {
781                 do { Wprint '<link rel="'.$type.'" href="'.$_.'" />'."\n" if $_; } for ($W->{"rel_$type"});
782                 }
783         Wprint "</head><body";
784 #       Wprint ' bgcolor="black" text="white" link="aqua" vlink="teal"'
785 #                       if $W->{"browser"}->netscape() && (!$W->{"browser"}->major() || $W->{"browser"}->major()<=4);
786         Wprint $W->{"body_attr"};
787         Wprint ">\n";
788
789         do { &{$_}() if $_; } for ($W->{"heading"});
790 }
791
792 BEGIN {
793         delete $W->{"__My::Web_init"};
794         }
795
796 1;