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