Inlined CSS moved out to: /My/Web.css
[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 my @img_variants=(
564                 { "id"=>"png","qs"=>1.0,"content-type"=>"image/png" },
565                 { "id"=>"gif","qs"=>0.9,"content-type"=>"image/gif" },
566                 );
567 my $img_variants_re='[.](?:'.join('|',"jpeg",map(($_->{"id"}),@img_variants)).')$';
568
569 sub img_src ($)
570 {
571 my($file_base)=@_;
572
573         if (!url_is_local($file_base)) {
574                 return $file_base if !wantarray();
575                 return ($file_base,$file_base);
576                 }
577         # Known image extension?
578         if ($file_base=~m#$img_variants_re#o) {
579                 return $file_base if !wantarray();
580                 return ($file_base,$file_base) if $file_base!~m#^/#;
581                 return (top_dir($file_base),top_dir_disk().$file_base);
582                 }
583
584         my $file_base_disk;
585         my $file_base_uri;
586         if ($file_base!~m#^/#) {
587                 $file_base_disk=$file_base_uri=$file_base;
588                 }
589         else {
590                 $file_base_disk=top_dir_disk().$file_base;
591                 $file_base_uri=top_dir($file_base);
592                 }
593
594         my @nego_variants;
595         for my $var (@img_variants) {
596                 my $file=$file_base_disk.".".$var->{"id"};
597                 # TODO: Somehow quickly check dependencies?
598                 make('make -s --no-print-directory'
599                                                 .' -C '."'".File::Basename::dirname($file)."' '".File::Basename::basename($file)."'")
600                                 if !-f $file;
601                 push @nego_variants,negotiate_variant(
602                                 %$var,
603                                 "size"=>(stat $file)[7],
604                                 );
605                 }
606         # Do not: ,$W->{"r"});
607         # but should we provide somehow either 'HTTP::Headers' or 'HTTP::Request' ?
608         my $ext=HTTP::Negotiate::choose(\@nego_variants);
609         $ext||=$img_variants[0]->{"id"};        # &HTTP::Negotiate::choose failed?
610
611         return $file_base_uri.".".$ext if !wantarray();
612         return ($file_base_uri.".".$ext,$file_base_disk.".".$ext);
613 }
614
615 sub img ($$;%)
616 {
617 my($file_base,$alt,%attr)=@_;
618
619         my($file_uri,$file_disk)=img_src $file_base;
620         my($width,$height)=Image::Size::imgsize($file_disk);
621         $alt=~s/<[^>]*>//g;
622         $alt=CGI::escapeHTML($alt);
623         my $content="<img src=\"$file_uri\" alt=\"$alt\" title=\"$alt\" ".img_size($width,$height)
624                         .(!$attr{"attr"} ? "" : " ".$attr{"attr"})." />";
625         return a_href img_src($attr{"a_href_img"}),$content if $attr{"a_href_img"};
626         return a_href $attr{"a_href"},$content if $attr{"a_href"};
627         return $content;
628 }
629
630 sub centerimg
631 {
632         my $r.="";
633         $r.='<table border="0" width="100%"><tr>'."\n";
634         @_=( [@_] ) if !ref $_[0];
635         for (@_) {
636                 $r.="\t".'<td align="center">'.&{\&img}(@$_).'</td>'."\n";
637                 }
638         $r.='</tr></table>'."\n";
639         return $r;
640 }
641
642 sub rightimg
643 {
644 my($text,@args_img)=@_;
645
646         # Workaround bug of 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)':
647         return <<"HERE";
648 <table border="0" width="100%">
649         <col width="@{[ (!$W->{"browser"}->ie() ? "1*" : "90%" ) ]}" />
650         <col width="@{[ (!$W->{"browser"}->ie() ? "0*" : "10%" ) ]}" />
651         <tr>
652                 <td align="left">
653                         @{[ $text ]}
654                 </td>
655                 <td align="right">
656                         @{[ &{\&img}(@args_img) ]}
657                 </td>
658         </tr>
659 </table>
660 HERE
661 }
662
663 sub readfile ($$)
664 {
665 my($class,$filename)=@_;
666
667         local *F;
668         open F,$filename or die "Cannot open \"$filename\": $!";
669         local $/=undef();
670         my $data=<F>;
671         close F;
672         return $data;
673 }
674
675 sub arr_keys (@)
676 {
677 my(@arr)=@_;
678
679         my @r=();
680         while (@arr) {
681                 push @r,shift @arr;     # key
682                 shift @arr;     # val
683                 }
684         return @r;
685 }
686
687 sub no_cache($)
688 {
689 my($self)=@_;
690
691         header("Expires"=>"Mon, 26 Jul 1997 05:00:00 GMT");     # date in the past
692         header("Last-Modified"=>strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime()));        # always modified
693         header("Cache-Control"=>"no-cache, must-revalidate");   # HTTP/1.1
694         header("Pragma"=>"no-cache");   # HTTP/1.0
695 }
696
697 sub heading ()
698 {
699 my($class)=@_;
700
701         # $ENV{"CLIENT_CHARSET"} ignored (mod_czech support dropped!)
702         my $client_charset=$W->{"force_charset"} || "us-ascii";
703         header("Content-Style-Type"=>"text/css");
704         header("Content-Script-Type"=>"text/javascript");
705         do { header("Content-Language"=>$_) if $_; } for $W->{"language"};
706         $class->no_cache() if $W->{"no_cache"};
707
708         while (my($key,$val)=each(%{$W->{"headers"}})) {
709                 $W->{"r"}->header_out($key,$val);
710                 }
711         if (!$W->{"header_only"}) {
712                 $W->{"r"}->send_http_header("text/html; charset=$client_charset");      # "Content-type"; do not use header()
713                 }
714
715         exit if $W->{"r"}->header_only();
716         return if $W->{"header_only"};
717         # We still can append headers before we put out some text.
718         # FIXME: It is not clean to still append them without overwriting.
719         return if $W->{"heading_done"}++;
720
721         if (1) { # || !$msie_major || $msie_major>=4) # TODO:dyn
722                 Wprint '<?xml version="1.0" encoding="'.$client_charset.'"?>'."\n";
723                 }
724         Wprint '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'."\n";
725         Wprint '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'
726                         .($W->{"language"}||"en-US").'">'."\n";
727         my $title=$W->{"title_prefix"}.join("",map({ ': '.$_; } ($W->{"title"} || ())));
728         $title=~s#<[^>]*>##g;
729         Wprint "<head>";
730         Wprint "<title>$title</title>\n";
731         if ($W->{"have_css"}) {
732                 # Everything can get overriden later.
733                 Wprint <<"HERE";
734 <link rel="stylesheet" type="text/css" href="@{[ url_out("/My/Web.css") ]}" />
735 HERE
736                 }
737         Wprint '<meta name="robots" content="'.($W->{"indexme"} ? "" : "no" ).'index,follow" />'."\n";
738         Wprint $W->{"head"};
739         for my $type (qw(prev next index contents start up)) {
740                 do { Wprint '<link rel="'.$type.'" href="'.$_.'" />'."\n" if $_; } for ($W->{"rel_$type"});
741                 }
742         Wprint "</head><body";
743 #       Wprint ' bgcolor="black" text="white" link="aqua" vlink="teal"'
744 #                       if $W->{"browser"}->netscape() && (!$W->{"browser"}->major() || $W->{"browser"}->major()<=4);
745         Wprint $W->{"body_attr"};
746         Wprint ">\n";
747
748         do { &{$_}() if $_; } for ($W->{"heading"});
749 }
750
751 BEGIN {
752         delete $W->{"__My::Web_init"};
753         }
754
755 1;