&a_href_cc: Stabilize 'headers_in' hits at the expense of CPU burden.
[MyWeb.git] / Web.pm
1 # $Id$
2 # Common functions for HTML/XHTML output generation
3 # Copyright (C) 2003-2005 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(
31                 &Wrequire &Wuse
32                 &path_web &path_abs_disk
33                 &uri_escaped
34                 &a_href &a_href_cc
35                 &vskip
36                 &img &centerimg &rightimg
37                 $W
38                 &input_hidden_persistents
39                 &escapeHTML
40                 );
41 our @ISA=qw(Tie::Handle Exporter);
42
43 my %packages_used_hash; # $packages_used_hash{$W->{"__PACKAGE__"}}{"_done"}=1;
44 my %packages_used_array;
45
46 BEGIN
47 {
48         use Carp qw(cluck confess);
49         $W->{"__My::Web_init"}=1;
50
51         sub Wrequire ($)
52         {
53         my($file)=@_;
54
55 #               print STDERR "Wrequire $file\n";
56                 $file=~s#/#::#g;
57                 $file=~s/[.]pm$//;
58                 my $class=$file;
59                 $file=~s#::#/#g;
60                 $file.=".pm";
61                 my %callers;
62                 for (my $depth=0;defined caller($depth);$depth++) {
63                         $callers{caller($depth)}=1;
64                         }
65                 my $selfpkg=__PACKAGE__;
66                 $callers{$selfpkg}=1;
67                 for my $target ($class,__PACKAGE__) {
68                         for my $caller (keys(%callers)) {
69                                 next if $caller eq $target;
70                                 next if $packages_used_hash{$caller}{$target}++;
71                                 push @{$packages_used_array{$caller}},$target;
72                                 }
73                         }
74                 eval { CORE::require "$file"; } or confess $@;
75                 1;      # Otherwise 'require' would already file above.
76         }
77
78         sub Wuse ($@)
79         {
80         my($file,@list)=@_;
81
82 #               print STDERR "Wuse $file\n";
83                 Wrequire $file;
84                 local $Exporter::ExportLevel=$Exporter::ExportLevel+1;
85                 $file->import(@list);
86                 1;
87         }
88
89         sub import
90         {
91         my($class,@rest)=@_;
92
93                 local $Exporter::ExportLevel=$Exporter::ExportLevel+1;
94                 Wrequire("$class");
95                 return $class->SUPER::import(@rest);
96         }
97 }
98
99 use WebConfig;  # see also below: Wuse 'WebConfig';
100 require CGI;
101 require Image::Size;    # for &imgsize
102 use File::Basename;     # &basename
103 use Carp qw(cluck confess);
104 use URI::Escape;
105 require HTTP::BrowserDetect;
106 require HTTP::Negotiate;
107 our $have_Geo_IP; BEGIN { $have_Geo_IP=eval { require Geo::IP; 1; }; }
108 # Do not: use ModPerl::Util qw(exit);
109 # to prevent in mod_perl2: "exit" is not exported by the ModPerl::Util module
110 # I do not know why.
111 use POSIX qw(strftime);
112 use Tie::Handle;
113 use Apache2::Const qw(HTTP_MOVED_TEMPORARILY OK HTTP_OK);
114 use URI;
115 use URI::QueryParam;
116 use Cwd;
117 require HTTP::Date;
118 require Storable;
119 require Digest::MD5;
120 require Data::Compare;
121 use Data::Dumper;
122 require Encode;
123 use Apache2::Filter;
124 use Apache2::Connection;
125
126
127 #our $W;
128
129 sub cleanup($)
130 {
131 my($apache_request)=@_;
132
133         $packages_used_hash{$W->{"__PACKAGE__"}}{"_done"}=1;
134         cache_finish();
135         # Sanity protection.
136         $W=undef();
137         return OK;
138 }
139
140 sub request_check(;$)
141 {
142 my($self)=@_;
143
144         # Use &eval to prevent: Global $r object is not available. Set:\n\tPerlOptions +GlobalRequest\nin ...
145         # CGI requires valid "r": check it beforehand here.
146         confess "Calling sensitive dynamic code from a static code" if !eval { Apache2::RequestUtil->request(); };
147         # Do not: confess "Calling sensitive dynamic code without My::Web::init" if !$W->{"__PACKAGE__"};
148         # as it is valid at least while preparing arguments to call: &project::Lib::init
149 }
150
151 sub init ($%)
152 {
153 my($class,%args)=@_;
154
155         print STDERR "$class->init ".Apache2::RequestUtil->request()->unparsed_uri()."\n";
156
157         # We need to track package dependencies, so we need to call it from &init.
158         # We cannot do it in BEGIN { } block
159         # as it would not be tracked for each of the toplevel users later.
160         Wuse 'WebConfig';
161         Wrequire 'My::Hash';
162
163         $W=My::Hash->new({
164                 "__PACKAGE__"=>scalar(caller()),
165                 %WebConfig,
166                 %args,  # override %WebConfig settings
167                 },"My::Hash::Sub","My::Hash::Push");
168
169         # {"__PACKAGE__"} is mandatory for mod_perl-2.0;
170         # $Apache2::Registry::curstash is no longer supported.
171         do { cluck "No $_" if !$W->{$_}; } for "__PACKAGE__";
172
173         # See: &escapeHTML
174         do { cluck "charset==$_, expecting ISO-8859-1" if $_ ne "ISO-8859-1"; } for CGI::charset();
175         CGI::charset("utf-8");
176
177         do { $W->{$_}=0  if !defined $W->{$_}; } for "detect_ent";
178         do { $W->{$_}=0  if !defined $W->{$_}; } for "detect_js";
179         do { $W->{$_}=1  if !defined $W->{$_}; } for "have_css";        # AFAIK it does not hurt anyone.
180         do { $W->{$_}=0  if !defined $W->{$_}; } for "css_inherit";
181         do { $W->{$_}=1  if !defined $W->{$_}; } for "footer";
182         do { $W->{$_}=1  if !defined $W->{$_}; } for "footer_delimit";
183         do { $W->{$_}=1  if !defined $W->{$_}; } for "footer_ids";
184         do { $W->{$_}=1  if !defined $W->{$_}; } for "indexme";
185         do { $W->{$_}="" if !defined $W->{$_}; } for "head";
186         do { $W->{$_}="" if !defined $W->{$_}; } for "body_attr";
187         do { $W->{$_}="en-US" if !defined $W->{$_}; } for "language";
188
189         my $footer_any=0;
190         for (qw(footer_ids)) {
191                 $W->{$_}=0 if !$W->{"footer"};
192                 $footer_any=1 if $W->{$_};
193                 }
194         $W->{"footer"}=0 if !$footer_any;
195         $W->{"footer_delimit"}=0 if !$W->{"footer"};
196
197         $W->{"r"}=Apache2::RequestUtil->request();
198
199         $W->{"r"}->push_handlers("PerlCleanupHandler"=>\&cleanup);
200
201         $W->{"web_hostname"}||=$W->{"r"}->hostname();
202
203         tie *STDOUT,$W->{"r"};
204         select *STDOUT;
205         $|=1;
206
207         $W->{"QUERY_STRING"}=$W->{"r"}->args() || "";
208         if ($W->{"detect_ent"}) {
209                          if ($W->{"QUERY_STRING"}=~/[&]amp;have_ent/)
210                         { $W->{"have_ent"}=0; }
211                 elsif ($W->{"QUERY_STRING"}=~    /[&]have_ent/)
212                         { $W->{"have_ent"}=1; }
213                 else
214                         { delete $W->{"have_ent"}; }
215                 if (!defined $W->{"have_ent"} && $W->{"r"}->method() eq "GET") {
216                         $W->{"head"}.='<meta http-equiv="Refresh" content="0; URL='
217                                         .escapeHTML("http://".$W->{"web_hostname"}."/".($W->{"r"}->uri()=~m#^/*(.*)$#)[0]
218                                                         ."?".($W->{"QUERY_STRING"} || "detect_ent_glue=1").'&have_ent=detect')
219                                         .'" />'."\n";
220                         }
221                 }
222         $W->{"QUERY_STRING"}=~s/([&])amp;/$1/g;
223         $W->{"r"}->args($W->{"QUERY_STRING"});
224         # Workaround: &CGI::Vars behaves weird if strings passed both as POST data and in: $QUERY_STRING
225         do { $W->{"r"}->args(""); delete $ENV{"QUERY_STRING"}; } if $W->{"r"}->method() eq "POST";
226         # Do not: $W->{"r"}->args()
227         # as it parses only QUERY_STRING (not POST data).
228         $W->{"args_orig_array"}=[ CGI->new($W->{"r"})->Vars() ];
229         $W->{"args"}={ @{$W->{"args_orig_array"}} };
230         for my $name (keys(%{$W->{"args"}})) {
231                 my @vals=split /\x00/,$W->{"args"}{$name};
232                 next if @vals<=1;
233                 $W->{"args"}{$name}=[@vals];
234                 }
235
236         $W->{"headers_in"}=$W->{"r"}->headers_in();
237         Wrequire 'My::Hash::Merge';
238         $W->{"headers_in"}=My::Hash::Merge->new(
239                         $W->{"headers_in"},
240                         My::Hash::Sub->new({
241                                 "_remote_ip"=>sub { return $W->{"r"}->connection()->remote_ip(); },
242                                 }),
243                         );
244         $W->{"headers_in"}=My::Hash::Readonly->new($W->{"headers_in"});
245         
246         if ($W->{"r"}->method() eq "GET" || $W->{"r"}->method() eq "HEAD") {
247                 for (\$W->{"http_safe"}) {
248                         # Extend the current ETag system instead if you would need it:
249                         cluck "Explicitely NOT HTTP-Safe for method \"".$W->{"r"}->method()."\"?!?"
250                                         if defined($$_) && !$$_;
251                         $$_=1 if !defined $$_;
252                         }
253                 }
254         else {
255                 for (\$W->{"http_safe"}) {
256                         cluck "Undefined HTTP-Safe-ty for method \"".$W->{"r"}->method()."\"!"
257                                         if !defined($$_);
258                         $$_=0 if !defined $$_;
259                         }
260                 }
261         if ($W->{"http_safe"}) {
262                 Wrequire 'My::Hash::RecordKeys';
263                 $W->{"headers_in_RecordKeys"}=My::Hash::RecordKeys->new($W->{"headers_in"});
264                 $W->{"headers_in"}=$W->{"headers_in_RecordKeys"};
265                 }
266
267         $W->{"browser"}=HTTP::BrowserDetect->new($W->{"headers_in"}{"User-Agent"});
268
269         if (!defined $W->{"have_style"}) {
270                 $W->{"have_style"}=(!$W->{"browser"}->netscape() || ($W->{"browser"}->major() && $W->{"browser"}->major()>4) ? 1 : 0);
271                 }
272
273         $W->{"have_js"}=($W->{"args"}{"have_js"} ? 1 : 0);
274         if ($W->{"detect_js"} && !$W->{"have_js"}) {
275                 $W->{"head"}.='<script type="text/javascript" src="'.uri_escaped(path_web('/My/HaveJS.pm')).'"></script>'."\n";
276                 }
277
278         do { _args_check(%$_) if $_; } for ($W->{"args_check"});
279
280         return bless $W,$class;
281 }
282
283 # Be aware other parts of code (non-My::Web) will NOT use this function!
284 # Do not: Wprint $W->{"heading"},"undef"=>1;
285 # as we would need to undef() it to turn it off and it would get defaulted in such case.
286 # Do not: exists $W->{"heading"}
287 # as we use a lot of 'for $W->{"heading"}' which instantiates it with the value: undef()
288 sub Wprint($%)
289 {
290 my($text,%args)=@_;
291
292         cluck "undef Wprint" if !defined $text && !$args{"undef"};
293         delete $args{"undef"};
294         cluck join(" ","Invalid arguments:",keys(%args)) if keys(%args);
295         return if !defined $text;
296         cluck "utf-8 untested" if Encode::is_utf8($text);
297         $W->{"r"}->puts($text);
298 }
299
300 sub escapeHTML($)
301 {
302 my($text)=@_;
303
304         # Prevent &CGI::escapeHTML breaking utf-8 strings like: \xC4\x9B eq \x{11B}
305         # Prevent case if we run under mod_perl but still just initializing:
306         request_check() if $ENV{"MOD_PERL"};
307         # Generally we are initialized from &init but we may be used without it without mod_perl
308         # and in such case check the change on all non-first invocations.
309         our $init;
310         if (!$ENV{"MOD_PERL"} && $init++) {
311                 do { cluck "charset==$_" if $_ ne "utf-8"; } for CGI::charset();
312                 }
313         CGI::charset("utf-8");
314
315         return CGI::escapeHTML($text);
316 }
317
318 # /home/user/www/webdir
319 sub dir_top_abs_disk()
320 {
321         our $dir_top_abs_disk;
322         if (!$dir_top_abs_disk) {
323                 my $selfpkg_relpath=__PACKAGE__;
324                 $selfpkg_relpath=~s{::}{/}g;
325                 $selfpkg_relpath.=".pm";
326                 my $selfpkg_abspath=$INC{$selfpkg_relpath} or do {
327                         cluck "Unable to find self package $selfpkg_relpath";
328                         return;
329                         };
330                 $selfpkg_abspath=~s{/*\Q$selfpkg_relpath\E$}{} or do {
331                         cluck "Unable to strip myself \"$selfpkg_relpath\" from the abspath: $selfpkg_abspath";
332                         return;
333                         };
334                 cluck "INC{myself} is relative?: $selfpkg_abspath" if $selfpkg_abspath!~m{^/};
335                 $dir_top_abs_disk=$selfpkg_abspath;
336                 }
337         return $dir_top_abs_disk;
338 }
339
340 sub unparsed_uri()
341 {
342         request_check();
343         if (!$W->{"unparsed_uri"}) {
344                 # Do not: $W->{"r"}
345                 # as we may be called before &init from: &My::Project::init
346                 my $r=Apache2::RequestUtil->request();
347                 cluck "Calling ".'&unparsed_uri'." from a static code, going to fail" if !$r;
348                 my $uri_string=$r->unparsed_uri() or cluck "Valid 'r' missing unparsed_uri()?";
349                 my $uri=URI->new_abs($uri_string,"http://".$W->{"web_hostname"}."/");
350                 $W->{"unparsed_uri"}=$uri;
351                 }
352         return $W->{"unparsed_uri"};
353 }
354
355 sub in_to_uri_abs($)
356 {
357 my($in)=@_;
358
359         # Otherwise we may have been already processed and thus legally relativized.
360         # FIXME data: Currently disabled, all the data are too violating such rule.
361         if (0 && !ref $in) {
362                 my $uri_check=URI->new($in);
363                 $uri_check->scheme() || $in=~m{^\Q./\E} || $in=~m{^/}
364                                 or cluck "Use './' or '/' prefix for all the local references: $in";
365                 }
366         my $uri=URI->new_abs($in,unparsed_uri());
367         $uri=$uri->canonical();
368         return $uri;
369 }
370
371 # $args{"uri_as_in"}=1 to permit passing URI objects as: $in
372 # $args{"abs"}=1;
373 sub path_web($%)
374 {
375 my($in,%args)=@_;
376
377         cluck if !$args{"uri_as_in"} && ref $in;
378         my $uri=in_to_uri_abs($in);
379         if (uri_is_local($uri)) {
380                 # Prefer the $uri values over "args_persistent" values.
381                 $uri->query_form_hash({
382                                 map({
383                                         my $key=$_;
384                                         my $val=$W->{"args"}{$key};
385                                         (!defined $val ? () : ($key=>$val));
386                                         } keys(%{$W->{"args_persistent"}})),
387                                 %{$uri->query_form_hash()},
388                                 });
389                 }
390         return $uri->abs(unparsed_uri()) if $W->{"args"}{"Wabs"} || $args{"abs"};
391         return $uri->rel(unparsed_uri());
392 }
393
394 sub path_abs_disk_register($)
395 {
396 my($path_abs_disk)=@_;
397
398         $W->{"path_abs_disk_register"}{$path_abs_disk}=1;
399 }
400
401 # $args{"uri_as_in"}=1 to permit passing URI objects as: $in
402 sub path_abs_disk($%)
403 {
404 my($in,%args)=@_;
405
406         cluck if !$args{"uri_as_in"} && ref $in;
407         my $uri=in_to_uri_abs($in);
408         cluck if !uri_is_local($uri);
409         my $path=$uri->path();
410         cluck "URI compatibility: ->path() not w/leading slash of URI \"$uri\"; path: $path" if $path!~m{^/};
411         my $r=dir_top_abs_disk().$path;
412         path_abs_disk_register $r if !defined $args{"register"} || $args{"register"};
413         return $r;
414 }
415
416 sub fatal (;$);
417
418 sub _args_check (%)
419 {
420 my(%tmpl)=@_;
421
422         while (my($name,$regex)=each(%tmpl)) {
423                 my $name_html="Parameter <span class=\"quote\">".escapeHTML($name)."</span>";
424                 $W->{"args"}{$name}="" if !defined $W->{"args"}{$name};
425                 $W->{"args"}{$name}=[ $W->{"args"}{$name} ] if !ref $W->{"args"}{$name} && ref $regex;
426                 fatal "$name_html passed as multivar although singlevar expected"
427                                 if ref $W->{"args"}{$name} && !ref $regex;
428                 $regex=$regex->[0] if ref $regex;
429                 for my $val (!ref $W->{"args"}{$name} ? $W->{"args"}{$name} : @{$W->{"args"}{$name}}) {
430                         $val="" if !defined $val;
431                         fatal "$name_html <span class=\"quote\">".escapeHTML($val)."</span>"
432                                                         ." does not match the required regex <span class=\"quote\">".escapeHTML($regex)."</span> "
433                                         if $regex ne "" && $val!~/$regex/;
434                         }
435                 }
436 }
437
438 sub vskip (;$)
439 {
440 my($height)=@_;
441
442         return '<p'.(!defined $height ? "" : ' style="height: '.$height.';"').'>&nbsp;</p>'."\n";
443 }
444
445 sub fatal (;$)
446 {
447 my($msg)=@_;
448
449         $msg="UNKNOWN" if !$msg;
450         cluck "FATAL: $msg";
451
452         # Do not send it unconditionally.
453         # The intial duplicated '<?xml...' crashes Gecko parser.
454         $W->{"heading_done"}=0 if $W->{"header_only"};
455         # Do not send it unconditionally.
456         # Prevents warn: Headers already sent
457         if (!$W->{"heading_done"}) {
458                 $W->{"indexme"}=0;      # For the case no heading was sent yet.
459                 $W->{"header_only"}=0;  # assurance for &heading
460                 My::Web->heading();
461                 }
462         Wprint "\n".vskip("3ex")."<hr /><h1 class=\"error\">FATAL ERROR: $msg!</h1>\n"
463                         ."<p>You can report this problem's details to"
464                         ." ".a_href("mailto:".$W->{"admin_mail"},"admin of this website").".</p>\n";
465         footer();
466 }
467
468 sub footer (;$)
469 {
470         exit 1 if $W->{"footer_passed"}++;      # deadlock prevention:
471
472         Wprint vskip if $W->{"footer_delimit"};
473
474         do { Wprint $_ if $_; } for $W->{"footing_delimit"};
475
476         Wprint "<hr />\n" if $W->{"footer"};
477
478         my $packages_used=$packages_used_array{$W->{"__PACKAGE__"}};
479
480         if ($W->{"footer_ids"}) {
481                 Wprint '<p class="cvs-id">';
482                 Wprint join("<br />\n",map({ my $package=$_;
483                         my $cvs_id=(eval('$'.$package."::CVS_ID")
484 #                                       || $package     # debug
485                                         );
486                         if (!$cvs_id) {
487                                 ();
488                                 }
489                         else {
490                                 $cvs_id='$'.$cvs_id.'$';        # Eaten by 'q' operator.
491                                 my @cvs_id_split=split / +/,$cvs_id;
492                                 if (@cvs_id_split==8) {
493                                         my $file=$package;
494                                         $file=~s#::#/#g;
495                                         my $ext;
496                                         my @tried;
497                                         for (qw(.pm)) {
498                                                 $ext=$_;
499                                                 my $path_abs_disk=path_abs_disk("/$file$ext");
500                                                 push @tried,$path_abs_disk;
501                                                 last if -r $path_abs_disk;
502                                                 cluck "Class file $file not found; tried: ".join(" ",@tried) if !$ext;
503                                                 }
504                                         $file.=$ext;
505                                         $cvs_id_split[2]=""
506                                                         .a_href((map({ my $s=$_; $s=~s#/viewcvs/#$&~checkout~/#; $s; } $W->{"viewcvs"}))[0]."$file?rev=".$cvs_id_split[2],
507                                                                         $cvs_id_split[2]);
508                                         $cvs_id_split[1]=a_href($W->{"viewcvs"}.$file,
509                                                         ($package!~/^Apache2::/ ? $package : $cvs_id_split[1]));
510                                         $cvs_id_split[5]=&{$W->{"cvs_id_author_sub"}}($cvs_id_split[5]);
511                                         }
512                                 join " ",@cvs_id_split;
513                                 }
514                         } @$packages_used));
515                 Wprint "</p>\n";
516                 }
517
518         for my $package (@$packages_used) {
519                 my $cvs_id=(eval('$'.$package."::CVS_ID")
520 #                               || $package     # debug
521                                 );
522                 Wprint '<!-- '.$package.' - $'.$cvs_id.'$ -->'."\n" if $cvs_id;
523                 }
524
525         do { Wprint $_ if $_; } for $W->{"footing"};
526
527         Wprint "</body></html>\n";
528         exit 0;
529 }
530
531 # Existing entries are overwritten.
532 sub header(%)
533 {
534 my(%pairs)=@_;
535
536         while (my($key,$val)=each(%pairs)) {
537                 do { cluck "Headers already sent"; next; } if $W->{"heading_done"};
538                 $W->{"r"}->headers_out()->set($key,$val);
539                 }
540 }
541
542 sub size_display ($)
543 {
544 my($size)=@_;
545
546            if ($size<4096)
547                 {}
548         elsif ($size<1024*1024)
549                 { $size=sprintf "%.1fK",$size/1024; }
550         else
551                 { $size=sprintf "%.1fM",$size/1024/1024; }
552         $size.="B";
553         return $size;
554 }
555
556 sub uri_is_local($)
557 {
558 my($in)=@_;
559
560         my $uri_rel=in_to_uri_abs($in)->rel(unparsed_uri());
561         # Do not: defined $uri_rel->("userinfo"|"host"|"port")();
562         # as they fail to be called for schemes not supporting them.
563         return 0 if $uri_rel->scheme();
564         return 0 if $uri_rel->authority();
565         return 1;
566 }
567
568 # &path_web still may be required for &uri_escaped !
569 sub uri_escaped($)
570 {
571 my($uri)=@_;
572
573         cluck if !ref $uri;
574         my $urient=escapeHTML($uri);
575         return $uri    if $uri eq $urient;
576         request_check();
577         return $urient if uri_is_local $uri;
578         return $uri    if defined $W->{"have_ent"} && !$W->{"have_ent"};        # non-ent client
579         return $urient if $W->{"have_ent"};     # ent client
580         # Unknown client, &escapeHTML should not be needed here:
581         return escapeHTML(path_web('/My/Redirect.pm?location='.uri_escape($uri->abs(unparsed_uri()))));
582 }
583
584 our $a_href_inhibited;
585 sub a_href($;$%)
586 {
587 my($in,$contents,%args)=@_;
588
589         request_check();
590         do { $$_=1 if !defined $$_; } for (\$args{"size"});
591         if (!defined $contents) {
592                 $contents=$in;
593                 $contents=File::Basename::basename($contents) if $args{"basename"};
594                 $contents=escapeHTML($contents);
595                 }
596         $contents=~s#<a\b[^>]*>##gi;
597         $contents=~s#</a>##gi;
598         return $contents if $a_href_inhibited;
599
600         my $path_web=path_web $in,%args;
601         my $r="";
602         $r.='<a href="';
603         $r.=uri_escaped $path_web;
604         $r.='"';
605         do { $r.=" $_" if $_; } for ($args{"attr"});
606         $r.='>'.$contents.'</a>';
607         if ($args{"size"} && uri_is_local($in) && ($args{"size"}>=2 || $in=~/[.](?:gz|Z|rpm|zip|deb|lha)/)) {   # Downloadable?
608                 my $path_abs_disk=path_abs_disk $in,%args;
609                 cluck "File not readable: $path_abs_disk" if !-r $path_abs_disk;
610                 $r.='&nbsp;('.size_display((stat($path_abs_disk))[7]).')';
611                 }
612         return $r;
613 }
614
615 sub a_href_inhibit($$;@)
616 {
617 my($self,$sub,@sub_args)=@_;
618
619         local $a_href_inhibited=1;
620         return &{$sub}(@sub_args);
621 }
622
623 sub input_hidden_persistents()
624 {
625         request_check();
626         return join("",map({
627                 my $key=$_;
628                 my $val=$W->{"args"}{$key};
629                 (!defined $val ? () : '<input type="hidden"'
630                                 .' name="'.escapeHTML($key).'"'
631                                 .' value="'.escapeHTML($val).'"'
632                                 .' />'."\n");
633                 } (keys(%{$W->{"args_persistent"}}))));
634 }
635
636 sub http_moved($$;$)
637 {
638 my($self,$url,$status)=@_;
639
640         $url=path_web($url,"abs"=>1);
641         $status||=HTTP_MOVED_TEMPORARILY;
642         $W->{"r"}->status($status);
643         $W->{"r"}->headers_out()->{"Location"}=$url;
644         $W->{"header_only"}=1;
645         My::Web->heading();
646         exit;
647         die "NOTREACHED";
648 }
649
650 sub remote_ip ()
651 {
652         # Do not: PerlModule                 Apache2::ForwardedFor
653         #         PerlPostReadRequestHandler Apache2::ForwardedFor
654         # As 'Apache2::ForwardedFor' takes the first of $ENV{"HTTP_X_FORWARDED_FOR"}
655         # while the contents is '127.0.0.1, 213.220.195.171' if client has its own proxy.
656         # We must take the last item ourselves.
657         # Be VERY sure you always retrieve all the headers unconditionally to hit: My::Hash::RecordKeys
658         my $x_forwarded_for=$W->{"headers_in"}{"X-Forwarded-For"};
659         $x_forwarded_for=~s/^.*,\s*// if $x_forwarded_for;
660         my $remote_ip=$W->{"headers_in"}{"_remote_ip"};
661         my $r;
662         $r||=$x_forwarded_for;
663         $r||=$remote_ip;
664         return $r;
665 }
666
667 # $url={"JP"=>"http://specific",...};
668 # $url={""=>"http://default",...};
669 sub a_href_cc($$;%)
670 {
671 my($url,$contents,%args)=@_;
672
673         # A bit ineffective but we must process all the possibilities to get stable 'headers_in' hits!
674         my %map=map(($_=>a_href($url->{$_},$contents,%args)),keys(%$url));
675         my $cc;
676         $cc||=Geo::IP->new()->country_code_by_addr(remote_ip()) if $have_Geo_IP;
677         $cc||="";
678         my $r=$map{$cc};
679         return $r if $r;
680         return $contents;
681 }
682
683 sub make ($)
684 {
685 my($cmd)=@_;
686
687         # FIXME: &alarm, --timeout is now infinite.
688         # FIXME: Try to remove bash(1).
689         # FIXME: Use: @PATH_FLOCK@
690         my @argv=('flock',dir_top_abs_disk(),'bash','-c',$cmd.' >&2');
691         print STDERR join(" ","SPAWN:",@argv)."\n";
692         system @argv;
693 }
694
695 sub make_file($$)
696 {
697 my($self,$file)=@_;
698
699         cluck "Pathname not absolute: $file" if $file!~m{^/};
700         return if -f $file;
701         # TODO: Somehow quickly check dependencies?
702         return make('make -s --no-print-directory'
703                                         .' -C '."'".File::Basename::dirname($file)."' '".File::Basename::basename($file)."'");
704 }
705
706 sub img_size ($$)
707 {
708 my($width,$height)=@_;
709
710         cluck if !defined $width || !defined $height;
711         return ($W->{"have_style"} ? "style=\"border:0;width:${width}px;height:${height}px\"" : "border=\"0\"")
712                         ." width=\"$width\" height=\"$height\"";
713 }
714
715 sub negotiate_variant (%)
716 {
717 my(%args)=@_;
718
719         my @fields=("id","qs","content-type","encoding","charset","lang","size");
720         return [ map(($args{$_}),@fields) ];
721 }
722
723 # Input: $self is required!
724 # Input: Put the fallback variant as the first one.
725 # Returns: always only scalar!
726 sub Negotiate_choose($$)
727 {
728 my($self,$variants)=@_;
729
730         # Limit these entries to generate proper 'Vary' header.
731         my %hash=(map(($_=>$W->{"headers_in"}{$_}),qw(
732                         Accept
733                         Accept-Charset
734                         Accept-Encoding
735                         Accept-Language
736                         )));
737         my $best=HTTP::Negotiate::choose($variants,
738                         # Do not: $W->{"r"}
739                         # to prevent: Can't locate object method "scan" via package "Apache2::RequestRec" at HTTP/Negotiate.pm line 84.
740                         # Do not: $W->{"r"}->headers_in()
741                         # to prevent: Can't locate object method "scan" via package "APR::Table" at HTTP/Negotiate.pm line 84.
742                         # Do not: HTTP::Headers->new($W->{"r"}->headers_in());
743                         # to prevent empty result or even: Odd number of elements in anonymous hash
744                         HTTP::Headers->new(%hash));
745         $best||=$variants->[0][0];      # $variants->[0]{"id"}; &HTTP::Negotiate::choose failed?
746         return $best;
747 }
748
749 my @img_variants=(
750                 { "id"=>"png","qs"=>0.9,"content-type"=>"image/png" },
751                 { "id"=>"gif","qs"=>0.7,"content-type"=>"image/gif" },
752                 );
753 my $img_variants_re='[.](?:'.join('|',"jpeg",map(($_->{"id"}),@img_variants)).')$';
754
755 # Returns: ($path_web,$path_abs_disk)
756 # URI path segments support ignored here. Where it is used? (';' path segment options)
757 sub _img_src($%)
758 {
759 my($in,%args)=@_;
760
761         cluck if !uri_is_local $in;
762         my $uri=in_to_uri_abs $in;
763         my $path_abs_disk=path_abs_disk $uri,%args,"uri_as_in"=>1,"register"=>0;
764
765         # Known image extension?
766         return path_web($uri,%args,"uri_as_in"=>1),$path_abs_disk if $uri->path()=~m#$img_variants_re#o;
767
768         my @nego_variants;
769         for my $var (@img_variants) {
770                 my $path_abs_disk_variant=$path_abs_disk.".".$var->{"id"};
771                 path_abs_disk_register($path_abs_disk_variant);
772                 __PACKAGE__->make_file($path_abs_disk_variant);
773                 push @nego_variants,negotiate_variant(
774                                 %$var,
775                                 "size"=>(stat $path_abs_disk_variant)[7],
776                                 );
777                 }
778         my $ext=__PACKAGE__->Negotiate_choose(\@nego_variants);
779
780         $uri->path($uri->path().".$ext");
781         return path_web($uri,%args,"uri_as_in"=>1),path_abs_disk($uri,%args,"uri_as_in"=>1);
782 }
783
784 # $args{"attr"}
785 sub img ($$%)
786 {
787 my($in,$alt,%args)=@_;
788
789         request_check();
790         my($path_web,$path_abs_disk)=_img_src($in,%args);
791         my($width,$height)=Image::Size::imgsize($path_abs_disk);
792         $alt=~s/<[^>]*>//g;
793         $alt=escapeHTML($alt);
794         my $content="<img src=\"".uri_escaped($path_web)."\" alt=\"$alt\" title=\"$alt\" ".img_size($width,$height)
795                         .(!$args{"attr"} ? "" : " ".$args{"attr"})." />";
796         do { return a_href((_img_src($_))[0],$content,"uri_as_in"=>1) if $_; } for $args{"a_href_img"};
797         do { return a_href $_,$content if $_; } for $args{"a_href"};
798         return $content;
799 }
800
801 sub centerimg
802 {
803         my $r="";
804         $r.='<table border="0" width="100%"><tr>'."\n";
805         @_=( [@_] ) if !ref $_[0];
806         for (@_) {
807                 $r.="\t".'<td align="center">'.&{\&img}(@$_).'</td>'."\n";
808                 }
809         $r.='</tr></table>'."\n";
810         return $r;
811 }
812
813 sub rightimg
814 {
815 my($text,@args_img)=@_;
816
817         # FIXME: Workaround bug of 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)':
818         #        <col width="@{[ (!$W->{"browser"}->ie() ? "1*" : "90%" ) ]}" />
819         #        <col width="@{[ (!$W->{"browser"}->ie() ? "0*" : "10%" ) ]}" />
820         # causes whole invisible projects in: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.10) Gecko/20050719 Galeon/1.3.21
821         return <<"HERE";
822 <table border="0" width="100%">
823         <tr>
824                 <td align="left">
825                         @{[ $text ]}
826                 </td>
827                 <td align="right">
828                         @{[ &{\&img}(@args_img) ]}
829                 </td>
830         </tr>
831 </table>
832 HERE
833 }
834
835 sub readfile($$)
836 {
837 my($class,$filename)=@_;
838
839         local *F;
840         open F,$filename or cluck "Cannot open \"$filename\": $!";
841         my $F=do { local $/=undef(); <F>; };
842         close F or cluck "Cannot close \"$filename\": $!";
843         return $F;
844 }
845
846 sub _no_cache($)
847 {
848 my($self)=@_;
849
850         header("Expires"=>HTTP::Date::time2str(1000000000));    # date in the past
851         header("Last-Modified"=>HTTP::Date::time2str());        # always modified
852         header("Cache-Control"=>join(", ",
853                         "no-cache",
854                         "no-store",
855                         "must-revalidate",
856                         "max-age=0",
857                         "pre-check=0",  # MSIE
858                         "post-check=0", # MSIE
859                         ));     # HTTP/1.1
860         header("Pragma"=>"no-cache");   # HTTP/1.0
861         header("Vary"=>"*");    # content may ba based on unpredictable sources
862 }
863
864 sub headers_in_filtered(@)
865 {
866 my(@keys)=@_;
867
868         return map(($_=>$W->{"headers_in"}{$_}),@keys);
869 }
870
871 our %uri_args_frozen_to_headers_in_keys;
872 our %uri_args_headers_in_frozen_to_headers_out;
873
874 sub uri_args_headers_in_frozen_get($)
875 {
876 my($headers_in_keys_arrayref)=@_;
877
878         my %uri_args_headers_in_hash=(
879                 "uri_args_frozen"=>$W->{"uri_args_frozen"},
880                 "headers_in"=>{ headers_in_filtered(@$headers_in_keys_arrayref) },
881                 );
882         return do { local $Storable::canonical=1; Storable::freeze(\%uri_args_headers_in_hash); };
883 }
884
885 sub cache_output_filter($)
886 {
887 my($f)=@_;
888
889         while ($f->read(my $text,0x400)) {
890                 cluck "utf-8 untested" if Encode::is_utf8($text);       # Possible here at all?
891                 $f->print($text);
892                 $W->{"digest-md5"}->add($text);
893                 }
894         return OK;
895 }
896
897 sub cache_start()
898 {
899         if (!$W->{"http_safe"}) {
900                 __PACKAGE__->_no_cache();
901                 return;
902                 }
903
904         {
905                 # &Wrequire it here even if it will not be later used; to be stable!
906                 Wrequire 'My::Hash::RestrictTo';
907                 my %uri_args_hash=(
908                         "uri"=>"http://".$W->{"web_hostname"}."/".$W->{"r"}->uri(),
909                         "args"=>$W->{"args_orig_array"},
910                         );
911                 $W->{"uri_args_frozen"}=do { local $Storable::canonical=1; Storable::freeze(\%uri_args_hash); };
912                 last if !(my $headers_in_keys_arrayref=$uri_args_frozen_to_headers_in_keys{$W->{"uri_args_frozen"}});
913
914                 # Protection to be sure we are stable:
915                 $W->{"headers_in"}=My::Hash::RestrictTo->new($W->{"headers_in"},@$headers_in_keys_arrayref);
916
917                 $W->{"uri_args_headers_in_frozen"}=uri_args_headers_in_frozen_get($headers_in_keys_arrayref);
918                 last if !(my $headers_out_hashref=$uri_args_headers_in_frozen_to_headers_out{$W->{"uri_args_headers_in_frozen"}});
919                 header(%$headers_out_hashref);
920                 my $status;
921                 {
922                         # &meets_conditions will always deny the attempt if !2xx status().
923                         # At least ap_read_request() sets: r->status=HTTP_REQUEST_TIME_OUT;     /* Until we get a request */
924                         my $status_old=$W->{"r"}->status();
925                         $W->{"r"}->status(HTTP_OK);
926                         # Update httpd's 'r->mtime' as the header "Last-Modified" is just not enough for ap_meets_conditions():
927                         # &update_mtime() argument is really in _secs_, not in _msecs_ as the docs claim.
928                         # Be aware '*1000000' would overflow Perl integer anyway.
929                         # &set_last_modified would also override the "Last-Modified" headers_out!
930                         # &mtime may exist but somehow does not work.
931                         $W->{"r"}->update_mtime(HTTP::Date::str2time($headers_out_hashref->{"Last-Modified"}));
932                         $status=$W->{"r"}->meets_conditions();
933                         $W->{"r"}->status($status_old);
934                         }
935                 last if OK==$status;
936                 $W->{"r"}->status($status);
937                 exit 0;
938                 die "NOTREACHED";
939                 }
940
941         $W->{"digest-md5"}=Digest::MD5->new();
942         $W->{"cache_active"}=1;
943         $W->{"r"}->add_output_filter(\&cache_output_filter);
944 }
945
946 sub cache_finish_last_modified()
947 {
948         cluck "Not yet done now? W __PACKAGE__: ".$W->{"__PACKAGE__"}
949                         if !$packages_used_hash{$W->{"__PACKAGE__"}}{"_done"};
950         for my $package_orig (@{$packages_used_array{$W->{"__PACKAGE__"}}}) {
951                 local $_=$package_orig.".pm";
952                 s{::}{/}g;
953                 path_abs_disk "/$_","register"=>1;
954                 }
955         my $mtime_newest;
956         for my $path_abs_disk (keys(%{$W->{"path_abs_disk_register"}})) {
957                 my $mtime=(stat $path_abs_disk)[9];
958                 do { cluck "No mtime for: $path_abs_disk"; next; } if !$mtime;
959                 $mtime_newest=$mtime if !$mtime_newest || $mtime_newest<$mtime;
960                 }
961         cluck "No mtime_newest found for the current W __PACKAGE__: ".$W->{"__PACKAGE__"}
962                         if !$mtime_newest;
963         return HTTP::Date::time2str($mtime_newest);
964 }
965
966
967 sub cache_finish()
968 {
969         # Do not: return if !$W->{"uri_args_frozen"};
970         # as we may have just gave 304 and 'exit 0;' without starting the caching.
971         return if !$W->{"cache_active"};
972
973         # Fill-in/check: %uri_args_frozen_to_headers_in_keys
974         my $headers_in_keys_stored_arrayref_ref=\$uri_args_frozen_to_headers_in_keys{$W->{"uri_args_frozen"}};
975         my @headers_in_keys=tied(%{$W->{"headers_in_RecordKeys"}})->accessed();
976         if (!$$headers_in_keys_stored_arrayref_ref
977                         || !Data::Compare::Compare(\@headers_in_keys,$$headers_in_keys_stored_arrayref_ref)) {
978                 cluck "Non-matching generated 'headers_in_keys' per 'uri_args_frozen' key:\n"
979                                                 .Dumper(\@headers_in_keys,$$headers_in_keys_stored_arrayref_ref)
980                                 if $$headers_in_keys_stored_arrayref_ref;
981                 # Build or possibly prevent such further warn dupes:
982                 $$headers_in_keys_stored_arrayref_ref=\@headers_in_keys;
983                 # Build or regenerate as obsoleted now:
984                 $W->{"uri_args_headers_in_frozen"}=uri_args_headers_in_frozen_get(\@headers_in_keys);
985                 }
986
987         # Prepare 'headers_out' for the future reusal:
988         my %headers_out;
989         $headers_out{"Content-MD5"}=$W->{"digest-md5"}->b64digest();
990         # In fact we could also use MD5 for ETag as if we know ETag we also know MD5.
991         # But this way we do not need to calculate MD5 and we still can provide such ETag. So.
992         # $W->{"r"}->set_etag() ?
993         $headers_out{"ETag"}='"'.Digest::MD5::md5_base64($W->{"uri_args_headers_in_frozen"}).'"';
994         # $W->{"r"}->set_content_length() ?
995         $headers_out{"Content-Length"}=$W->{"r"}->bytes_sent();
996         my %Vary=map(($_=>1),(@headers_in_keys));
997         for (keys(%Vary)) {
998                 next if !/^_/;
999                 $Vary{"*"}=1;
1000                 delete $Vary{$_};
1001                 }
1002         %Vary=("*"=>1) if $Vary{"*"};
1003         $headers_out{"Vary"}=join(", ",sort keys(%Vary));
1004         # $W->{"r"}->set_last_modified() ?
1005         $headers_out{"Last-Modified"}=cache_finish_last_modified();
1006
1007         # Fill-in/check: %uri_args_headers_in_frozen_to_headers_out
1008         my $headers_out_stored_hashref_ref=\$uri_args_headers_in_frozen_to_headers_out{$W->{"uri_args_headers_in_frozen"}};
1009         if (!$$headers_out_stored_hashref_ref
1010                         || !Data::Compare::Compare(\%headers_out,$$headers_out_stored_hashref_ref)) {
1011                 cluck "Non-matching generated 'headers_out' per 'uri_args_headers_in_frozen' key:\n"
1012                                                 .Dumper(\%headers_out,$$headers_out_stored_hashref_ref)
1013                                 if $$headers_out_stored_hashref_ref;
1014                 # Build or possibly prevent such further warn dupes:
1015                 $$headers_out_stored_hashref_ref=\%headers_out;
1016                 }
1017
1018 ###print STDERR Dumper(\%uri_args_frozen_to_headers_in_keys,\%uri_args_headers_in_frozen_to_headers_out);
1019 }
1020
1021 sub heading()
1022 {
1023 my($class)=@_;
1024
1025         if (!$W->{"header_only"}) {
1026                 header("Content-Style-Type"=>"text/css");
1027                 header("Content-Script-Type"=>"text/javascript");
1028                 # $W->{"r"}->content_languages() ?
1029                 do { header("Content-Language"=>$_) if $_; } for $W->{"language"};
1030                 }
1031         # TODO: Support also: private
1032         header("Cache-Control"=>"public");      # HTTP/1.1
1033
1034         # $ENV{"CLIENT_CHARSET"} ignored (mod_czech support dropped!)
1035         my $client_charset=$W->{"force_charset"} || "us-ascii";
1036
1037         # Workaround bug
1038         #   https://bugzilla.mozilla.org/show_bug.cgi?id=120556
1039         # of at least
1040         #   Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8b) Gecko/20050217
1041         my $mime;
1042         # http://validator.w3.org/ does not send ANY "Accept" headers!
1043         $mime||="application/xhtml+xml" if 1
1044                         && !$W->{"headers_in"}{"Accept"}
1045                         && ($W->{"headers_in"}{"User-Agent"}||"")=~m{^W3C_Validator/}i;
1046         $mime||=$class->Negotiate_choose([
1047                         # Put the fallback variant as the first one.
1048                         # Rate both variants the same to prefer "text/html" for undecided clients.
1049                         # At least
1050                         #   Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8b) Gecko/20050217
1051                         # prefers "application/xhtml+xml" over "text/html" itself:
1052                         #   text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
1053                         negotiate_variant(
1054                                         "id"=>"text/html",
1055                                         "content-type"=>"text/html",
1056                                         "qs"=>0.6,
1057                                         "charset"=>$client_charset,
1058                                         "lang"=>$W->{"language"},
1059                                         ),
1060                         negotiate_variant(
1061                                         "id"=>"application/xhtml+xml",
1062                                         "content-type"=>"application/xhtml+xml",
1063                                         "qs"=>0.6,
1064                                         "charset"=>$client_charset,
1065                                         "lang"=>$W->{"language"},
1066                                         ),
1067                         # application/xml ?
1068                         # text/xml ?
1069                         ]);
1070         # mod_perl doc: If you set this header via the headers_out table directly, it
1071         #               will be ignored by Apache. So do not do that.
1072         $W->{"r"}->content_type("$mime; charset=$client_charset");
1073
1074         cache_start();
1075         return if $W->{"header_only"};
1076         # We still can append headers before we put out some text.
1077         # FIXME: It is not clean to still append them without overwriting.
1078         return if $W->{"heading_done"}++;
1079
1080         Wprint '<?xml version="1.0" encoding="'.$client_charset.'"?>'."\n" if $mime=~m{^application/\w+[+]xml$};
1081         return if $W->{"xml_header_only"};
1082         Wprint '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'."\n";
1083         Wprint '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.$W->{"language"}.'">'."\n";
1084         my $title=$W->{"title_prefix"}.join("",map({ ': '.$_; } ($W->{"title"} || ())));
1085         # Do not: cluck if $title=~/[<>]/;
1086         # as it is not solved just by: &a_href_inhibit
1087         # as sometimes titles use also: <i>...</i>
1088         $title=~s#<[^>]*>##g;
1089         Wprint "<head>";
1090         Wprint "<title>$title</title>\n";
1091         if ($W->{"have_css"}) {
1092                 # Everything can get overriden later.
1093                 for my $css ("/My/Web.css",map((!$_ ? () : ("ARRAY" ne ref($_) ? $_ : @$_)),$W->{"css_push"})) {
1094                         Wprint <<"HERE";
1095 <link rel="stylesheet" type="text/css" href="@{[ uri_escaped(path_web $css) ]}" />
1096 HERE
1097                         }
1098                 if ($W->{"css_inherit"}) {
1099                         Wprint <<"HERE";
1100 <script type="text/javascript" src="@{[ uri_escaped(path_web('/My/css_inherit.js')) ]}" />
1101 HERE
1102                         }
1103                 }
1104         Wprint '<meta name="robots" content="'.($W->{"indexme"} ? "" : "no" ).'index,follow" />'."\n";
1105         Wprint $W->{"head"};
1106         for my $type (qw(prev next index contents start up)) {
1107                 do { Wprint '<link rel="'.$type.'" href="'.uri_escaped(path_web $_).'" />'."\n" if $_; }
1108                                 for ($W->{"rel_$type"});
1109                 }
1110         Wprint "</head><body";
1111 #       Wprint ' bgcolor="black" text="white" link="aqua" vlink="teal"'
1112 #                       if $W->{"browser"}->netscape() && (!$W->{"browser"}->major() || $W->{"browser"}->major()<=4);
1113         Wprint $W->{"body_attr"};
1114         Wprint ">\n";
1115
1116         do { Wprint $_ if $_; } for $W->{"heading"};
1117 }
1118
1119 BEGIN {
1120         delete $W->{"__My::Web_init"};
1121         }
1122
1123 1;