Fixed remote IP detection.
[MyWeb.git] / Web.pm
1 # $Id$
2 # Common functions for HTML/XHTML output generation
3 # Copyright (C) 2003 Jan Kratochvil <project-www.jankratochvil.net@jankratochvil.net>
4
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; exactly version 2 of June 1991 is required
8
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
18
19 package My::Web;
20 require 5.6.0;  # at least 'use warnings;' but we need some 5.6.0+ modules anyway
21 our $VERSION=do { my @r=(q$Revision$=~/\d+/g); sprintf "%d.".("%03d"x$#r),@r; };
22 our $CVS_ID=q$Id$;
23 use strict;
24 use warnings;
25
26 use lib qw(/home/short/lib/perl5/site_perl/5.6.0/i386-linux /home/short/lib/perl5/site_perl/5.6.0 /home/short/lib/perl5/site_perl/i386-linux /home/short/lib/perl5/site_perl /home/short/lib/perl5/5.6.0/i386-linux /home/short/lib/perl5/5.6.0 /home/short/lib/perl5/i386-linux /home/short/lib/perl5);
27
28 use Exporter;
29 our @EXPORT=qw(&require &a_href &a_href_cz &vskip &img $W);
30 our @ISA=qw(Exporter);
31
32 use WebConfig;  # for %WebConfig
33 require CGI;    # for &escapeHTML
34 require Image::Size;    # for &imgsize
35 use File::Basename;     # &basename
36 use Carp qw(cluck confess);
37 use URI::Escape;
38 require HTTP::BrowserDetect;
39 require HTTP::Negotiate;
40 require Geo::IP;
41
42
43 # Undo 'www/engine/httpd-restart' as it may use obsolete Perl for 'mod_perl'
44 delete $ENV{"PERLLIB"};
45 delete $ENV{"LD_LIBRARY_PATH"};
46
47
48 our $W;
49                 # $W->{"title"}
50                 # $W->{"head"}
51                 # $W->{"head_css"}
52                 # $W->{"force_charset"}
53                 # %{$W->{"packages_used"}
54                 # $W->{"heading_done"}
55                 # $W->{"footer_passed"}
56                 # %{$W->{"headers"}}
57                 # %{$W->{"headers_lc"}} # maps lc($headers_key)=>$headers_key
58                 # @{$W->{"packages_used"}{$Apache::Registry::curstash}}}
59                 # %{$W->{"args"}}
60
61 sub init ($%)
62 {
63 my($class,%args)=@_;
64
65         $W={ %WebConfig,%args };        # override %WebConfig settings
66
67         $W->{"__PACKAGE__"}||="Apache::ROOT".$Apache::Registry::curstash;
68
69         $W->{"top_dir"}||=eval '$'.$W->{"__PACKAGE__"}.'::top_dir';
70
71         do { $W->{$_}=0  if !defined $W->{$_}; } for ("detect_ent");
72         do { $W->{$_}=0  if !defined $W->{$_}; } for ("detect_js");
73         do { $W->{$_}=1  if !defined $W->{$_}; } for ("have_css");      # AFAIK it does not hurt anyone.
74         do { $W->{$_}=1  if !defined $W->{$_}; } for ("footer_delimit");
75         do { $W->{$_}=1  if !defined $W->{$_}; } for ("footer_ids");
76         do { $W->{$_}=1  if !defined $W->{$_}; } for ("indexme");
77         do { $W->{$_}="" if !defined $W->{$_}; } for ("head");
78         do { $W->{$_}="" if !defined $W->{$_}; } for ("head_css");
79
80         $W->{"r"}=Apache->request();
81
82         $W->{"QUERY_STRING"}=$W->{"r"}->args() || "";
83            if ($W->{"QUERY_STRING"}=~/[&]amp;have_ent/)
84                 { $W->{"have_ent"}=0; }
85         elsif ($W->{"QUERY_STRING"}=~    /[&]have_ent/)
86                 { $W->{"have_ent"}=1; }
87         else
88                 { delete $W->{"have_ent"}; }
89         if ($W->{"detect_ent"} && !defined $W->{"have_ent"} && $W->{"r"}->method() eq "GET") {
90                 $W->{"head"}.='<meta http-equiv="Refresh" content="0; URL='
91                                 .CGI::escapeHTML("http://".$W->{"r"}->hostname()."/".($W->{"r"}->uri()=~m#^/*(.*)$#)[0]
92                                                 ."?".($W->{"QUERY_STRING"} || "detect_ent_glue=1").'&have_ent=detect')
93                                 .'" />'."\n";
94                 }
95         $W->{"QUERY_STRING"}=~s/([&])amp;/$1/g;
96         $W->{"r"}->args($W->{"QUERY_STRING"});
97         $W->{"args"}={ $W->{"r"}->args() };
98
99         do { $W->{$_}=$ENV{"HTTP_ACCEPT"} if !defined $W->{$_}; } for ("accept");
100         do { $W->{$_}=$ENV{"HTTP_USER_AGENT"} if !defined $W->{$_}; } for ("user_agent");
101
102         $W->{"browser"}=HTTP::BrowserDetect->new($W->{"user_agent"});
103
104         if (!defined $W->{"have_style"}) {
105                 $W->{"have_style"}=(!$W->{"browser"}->netscape() || $W->{"browser"}->major>4 ? 1 : 0);
106                 }
107
108         $W->{"have_js"}=($W->{"args"}{"have_js"} ? 1 : 0);
109         if ($W->{"detect_js"} && !$W->{"have_js"}) {
110                 $W->{"head"}.='<script type="text/javascript" src="'.$W->{"top_dir"}.'/have_js.js.pl"></script>'."\n";
111                 }
112
113         do { args_check(%$_) if $_; } for ($W->{"args_check"});
114
115         return $W;
116 }
117
118 sub require ($)
119 {
120 my($file)=@_;
121
122         $file=~s#/#::#g;
123         $file=~s/[.]pm$//;
124         my $class=$file;
125         $file=~s#::#/#g;
126         $file.=".pm";
127         my $aref=($W->{"packages_used"}{$Apache::Registry::curstash}||=[]);
128         push @$aref,$class
129                         if !{ map(($_=>1),@$aref) }->{$class};  # Prevent duplicated entries.
130         CORE::require $file;
131         1;      # Otherwise 'require' would already file above.
132 }
133
134 sub fatal (;$);
135
136 sub args_check (%)
137 {
138 my(%tmpl)=@_;
139
140         while (my($name,$regex)=each(%tmpl)) {
141                 my $name_html="Parametr <span class=\"quote\">".CGI::escapeHTML($name)."</span>";
142                 my $val=$W->{"args"}{$name};
143                 fatal "$name_html does not match required regex <span class=\"quote\">".CGI::escapeHTML($regex)."</span>"
144                                 if defined $val && $val!~/$regex/;
145                 fatal "$name_html is required"
146                                 if !defined $val;
147                 }
148 }
149
150 sub vskip (;$)
151 {
152 my($height)=@_;
153
154         return '<p'.(!defined $height ? "" : ' style="height: '.$height.';"').'>&nbsp;</p>'."\n";
155 }
156
157 sub fatal (;$)
158 {
159 my($msg)=@_;
160
161         $msg="UNKNOWN" if !$msg;
162
163 #       heading(false/*title*/,false/*indexme*/);       # notitle is always safe, don't index the error message
164         print "\n".vskip("3ex")."<hr /><h1 class=\"error\">FATAL ERROR: $msg!</h1>\n"
165                         ."<p>You can report this problem's details to"
166                         ." ".a_href("mailto:".$W->{"admin_mail"},"admin of this website").".</p>\n";
167         footer();
168 }
169
170 sub footer (;$)
171 {
172         exit 1 if $W->{"footer_passed"}++;      # deadlock prevention:
173
174         if ($W->{"footer_ids"}) {
175                 print vskip if $W->{"footer_delimit"};
176                 print '<hr /><p class="cvs-id">';
177
178                 print join("<br />\n",map({ my $package=$_;
179                         my $cvs_id=(eval('$'.$package."::CVS_ID")
180 #                                       || $package     # debug
181                                         );
182                         if (!$cvs_id) {
183                                 ();
184                                 }
185                         else {
186                                 $cvs_id='$'.$cvs_id.'$';        # Eaten by 'q' operator.
187                                 my @cvs_id_split=split / +/,$cvs_id;
188                                 if (@cvs_id_split==8) {
189                                         my $file=$package;
190                                         $file=~s#::#/#g;
191                                         my $ext;
192                                         for (qw(.html.pl .pl .pm),"") {
193                                                 $ext=$_;
194                                                 last if -r $W->{"top_dir"}."/$file$ext";
195                                                 cluck "Class file $file not found" if !$ext;
196                                                 }
197                                         $file.=$ext;
198                                         $cvs_id_split[2]=""
199                                                         .a_href((map({ my $s=$_; $s=~s#/viewcvs/#$&~checkout~/#; $s; } $W->{"viewcvs"}))[0]."$file?rev=".$cvs_id_split[2],
200                                                                         $cvs_id_split[2]);
201                                         $cvs_id_split[1]=a_href($W->{"viewcvs"}.$file,
202                                                         ($package!~/^Apache::/ ? $package : $cvs_id_split[1]));
203                                         $cvs_id_split[5]=&{$W->{"cvs_id_author"}}($cvs_id_split[5]);
204                                         }
205                                 join " ",@cvs_id_split;
206                                 }
207                         } (
208                                         $W->{"__PACKAGE__"},
209                                         __PACKAGE__,
210                                         @{$W->{"packages_used"}{$Apache::Registry::curstash}},
211                                         )));
212                 print "</p>\n";
213                 }
214         print "</body></html>\n";
215         exit(0);
216 }
217
218 sub header (%)
219 {
220 my(%pairs)=@_;
221
222         while (my($key,$val)=each(%pairs)) {
223                 do { cluck "Headers already sent"; next; } if $W->{"heading_done"};
224                 for ($W->{"headers_lc"}{lc $key} || ()) {
225                         delete $W->{"headers"}{$_};
226                         }
227                 $W->{"headers_lc"}{lc $key}=$key;
228                 $W->{"headers"}{$key}=$val;
229                 }
230 }
231
232 sub size_display ($)
233 {
234 my($size)=@_;
235
236            if ($size<4096)
237                 {}
238         elsif ($size<1024*1024)
239                 { $size=sprintf "%.1fK",$size/1024; }
240         else
241                 { $size=sprintf "%.1fM",$size/1024/1024; }
242         $size.="B";
243         return $size;
244 }
245
246 sub url_is_local ($)
247 {
248 my($url)=@_;
249
250         return $url!~m#^[a-z]+://#;
251 }
252
253 sub a_href ($;$%)
254 {
255 my($url,$contents,%args)=@_;
256
257         do { $$_=1 if !defined $$_; } for ($args{"size"});
258         $contents=CGI::escapeHTML($url) if !defined $contents;
259
260         my $r='<a href="';
261         my $urlent=CGI::escapeHTML($url);
262            if ($url eq $urlent)
263                 { $r.=$url; }
264         elsif (url_is_local $url)
265                 { $r.=$urlent; }
266         elsif (defined $W->{"have_ent"} && !$W->{"have_ent"})   # non-ent client
267                 { $r.=$url; }
268         elsif ($W->{"have_ent"})        # ent client
269                 { $r.=$urlent; }
270         else    # unknown client, &CGI::escapeHTML should not be needed here
271                 { $r.=CGI::escapeHTML("http://".$W->{"r"}->hostname()."/redirect.pl?location=".uri_escape($url)); }
272         $r.='">'.$contents.'</a>';
273         if ($args{"size"} && url_is_local($url) && $url=~/[.](?:gz|rpm|zip|deb)/) {     # Downloadable?
274                 if (!-r $url)
275                         { cluck "File not readable: $url"; }
276                 else {
277                         $r.='&nbsp;('.size_display((stat($url))[7]).')';
278                         }
279                 }
280         return $r;
281 }
282
283 sub remote_ip ()
284 {
285         # Do not: PerlModule                 Apache::ForwardedFor
286         #         PerlPostReadRequestHandler Apache::ForwardedFor
287         # As 'Apache::ForwardedFor' takes the first of $ENV{"HTTP_X_FORWARDED_FOR"}
288         # while the contents is '127.0.0.1, 213.220.195.171' if client has its own proxy.
289         # We must take the last item ourselves.
290         my $r=$ENV{"HTTP_X_FORWARDED_FOR"};
291         $r=~s/^.*,\s*//;
292         return $r;
293 }
294
295 sub is_cz ()
296 {
297 print STDERR "IP=".remote_ip()."\n";
298         return "CZ" eq Geo::IP->new()->country_code_by_addr(remote_ip());
299 }
300
301 sub a_href_cz ($$;%)
302 {
303 my($url,$contents,%args)=@_;
304
305         return a_href $url,$contents,%args if is_cz();
306         return $contents;
307 }
308
309 sub img_size ($$)
310 {
311 my($width,$height)=@_;
312
313         return ($W->{"have_style"} ? "style=\"border:0;width:${width}px;height:${height}px\"" : "border=\"0\"")
314                         ." width=\"$width\" height=\"$height\"";
315 }
316
317 sub negotiate_variant (%)
318 {
319 my(%args)=@_;
320
321         my @fields=("id","qs","content-type","encoding","charset","lang","size");
322         return [ map(($args{$_}),@fields) ];
323 }
324
325 my @img_variants=(
326                 { "id"=>"png","qs"=>1.0,"content-type"=>"image/png" },
327                 { "id"=>"gif","qs"=>0.9,"content-type"=>"image/gif" },
328                 );
329 my $img_variants_re='[.](?:'.join('|',map(($_->{"id"}),@img_variants)).')$';
330
331 sub img ($$;$)
332 {
333 my($file_base,$alt,$attrs)=@_;
334
335         my $file;
336         if (url_is_local($file_base)
337                         # No known image extension?
338                         && $file_base!~m#$img_variants_re#o) {
339                 my @nego_variants;
340                 for my $var (@img_variants) {
341                         $file=$file_base.".".$var->{"id"};
342                         # TODO: Somehow quickly check dependencies?
343                         system 'make >&2 -s --no-print-directory'
344                                                         .' -C '."'".File::Basename::dirname($file)."' '".File::Basename::basename($file)."'"
345                                         if !-f $file;
346                         push @nego_variants,negotiate_variant(
347                                         %$var,
348                                         "size"=>(stat $file)[7],
349                                         );
350                         }
351                 # Do not: ,$W->{"r"});
352                 # but should we provide somehow either 'HTTP::Headers' or 'HTTP::Request' ?
353                 my $ext=HTTP::Negotiate::choose(\@nego_variants);
354                 $ext||=$img_variants[0]->{"id"};        # &HTTP::Negotiate::choose failed?
355                 $file=$file_base.".".$ext;
356                 }
357         else
358                 { $file=$file_base; }
359         my($width,$height)=Image::Size::imgsize($file);
360         $alt=CGI::escapeHTML($alt);
361         return "<img src=\"$file\" alt=\"$alt\" title=\"$alt\" ".img_size($width,$height)
362                         .(!$attrs ? "" : " ".$attrs)." />";
363 }
364
365 sub readfile ($$)
366 {
367 my($class,$filename)=@_;
368
369         local *F;
370         open F,$filename or die "Cannot open \"$filename\": $!";
371         local $/=undef();
372         my $data=<F>;
373         close F;
374         return $data;
375 }
376
377 sub arr_keys (@)
378 {
379 my(@arr)=@_;
380
381         my @r=();
382         while (@arr) {
383                 push @r,shift @arr;     # key
384                 shift @arr;     # val
385                 }
386         return @r;
387 }
388
389 sub heading ()
390 {
391 my($class)=@_;
392
393         # $ENV{"CLIENT_CHARSET"} ignored (mod_czech support dropped!)
394         my $client_charset=$W->{"force_charset"} || "us-ascii";
395         header("Content-Style-Type"=>"text/css");
396
397         while (my($key,$val)=each(%{$W->{"headers"}})) {
398                 $W->{"r"}->header_out($key,$val);
399                 }
400         $W->{"r"}->send_http_header("text/html; charset=$client_charset");      # "Content-type"; do not use header()
401
402         return if $W->{"heading_done"}++;
403         exit if $W->{"r"}->header_only();
404
405         if (1) { # || !$msie_major || $msie_major>=4) # TODO:dyn
406                 print '<?xml version="1.0" encoding="'.$client_charset.'"?>'."\n";
407                 }
408         print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'."\n";
409         print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">'."\n";
410         print '<head><title>'.CGI::escapeHTML($W->{"title_prefix"})
411                         .join("",map({ ': '.CGI::escapeHTML($_); } ($W->{"title"} || ())))
412                         .'</title>'."\n";
413
414         if ($W->{"have_css"}) {
415                 print <<'HERE';
416 <style type="text/css"><!--
417 .cvs-id   { font-family: monospace; }
418 .error    { color: red;   background-color: transparent; }
419 .quote    { font-family: monospace; }
420 .nowrap   { white-space: nowrap; }
421 .centered { text-align: center; }
422 .tab-bold { font-weight: bold; }
423 .tab-head { font-weight: bold; color: yellow; background-color: transparent; }
424 body {
425                 background-color: black;
426                 color: white;
427                 }
428 :link    { color: aqua;   background-color: transparent; }
429 :visited { color: teal;   background-color: transparent; }
430 h1,h2    { color: yellow; background-color: transparent; }
431 td       { padding: 2px; }
432 .footer img { vertical-align: middle; }
433 HERE
434                 print $W->{"head_css"}."\n";
435                 print "--></style>\n";
436                 }
437
438         print '<meta name="robots" content="'.($W->{"indexme"} ? "" : "no" ).'index,follow" />'."\n";
439         print $W->{"head"};
440         print "</head><body";
441         print ' bgcolor="black" text="white" link="aqua" vlink="teal"'
442                         if $W->{"browser"}->netscape() && $W->{"browser"}->major<=4;
443         print ">\n";
444 }
445
446 1;