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