2 # Common functions for HTML/XHTML output generation
3 # Copyright (C) 2003 Jan Kratochvil <project-www.jankratochvil.net@jankratochvil.net>
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
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.
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
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; };
30 our @EXPORT=qw(&Wrequire &Wuse &a_href &a_href_cz &vskip &img ¢erimg &rightimg $W &top_dir &top_dir_disk &Wprint &input_hidden_persistents);
31 our @ISA=qw(Exporter Tie::Handle);
35 $W->{"__My::Web_init"}=1;
41 # print STDERR "Wrequire $file\n";
47 my $who=$W->{"__PACKAGE__"};
48 $who||="__My::Web" if $W->{"__My::Web_init"};
50 my $aref=($W->{"packages_used"}{$who}||=[]);
52 if !{ map(($_=>1),@$aref) }->{$class}; # Prevent duplicated entries.
55 1; # Otherwise 'require' would already file above.
62 # print STDERR "Wuse $file\n";
64 local $Exporter::ExportLevel=$Exporter::ExportLevel+1;
70 BEGIN { Wuse 'WebConfig'; } # for %WebConfig
71 require CGI; # for &escapeHTML
72 require Image::Size; # for &imgsize
73 use File::Basename; # &basename
74 use Carp qw(cluck confess);
76 require HTTP::BrowserDetect;
77 require HTTP::Negotiate;
78 my $have_Geo_IP; BEGIN { $have_Geo_IP=eval { require Geo::IP; 1; }; }
79 use ModPerl::Util qw(exit);
80 use POSIX qw(strftime);
82 use Apache::Const qw(HTTP_MOVED_TEMPORARILY);
90 # $W->{"force_charset"}
91 # $W->{"heading_done"}
92 # $W->{"footer_passed"}
94 # %{$W->{"headers_lc"}} # maps lc($headers_key)=>$headers_key
95 # @{$W->{"packages_used"}{$W->{"__PACKAGE__"}}}
96 # @{$W->{"packages_used"}{"__My::Web"}}
103 print STDERR "$class->init ".Apache->request()->unparsed_uri()."\n";
105 my $packages_used_save=$W->{"packages_used"};
106 $W={ %WebConfig,%args }; # override %WebConfig settings
107 $W->{"packages_used"}=$packages_used_save;
109 # {"__PACKAGE__"} is mandatory for mod_perl-2.0;
110 # $Apache::Registry::curstash is no longer supported.
111 do { cluck "No $_" if !$W->{$_}; } for "__PACKAGE__";
113 $W->{"top_dir"}||=eval '$'.$W->{"__PACKAGE__"}.'::top_dir';
115 do { $W->{$_}=0 if !defined $W->{$_}; } for ("detect_ent");
116 do { $W->{$_}=0 if !defined $W->{$_}; } for ("detect_js");
117 do { $W->{$_}=1 if !defined $W->{$_}; } for ("have_css"); # AFAIK it does not hurt anyone.
118 do { $W->{$_}=1 if !defined $W->{$_}; } for ("footer");
119 do { $W->{$_}=1 if !defined $W->{$_}; } for ("footer_delimit");
120 do { $W->{$_}=1 if !defined $W->{$_}; } for ("footer_mailme");
121 do { $W->{$_}=1 if !defined $W->{$_}; } for ("footer_ids");
122 do { $W->{$_}=1 if !defined $W->{$_}; } for ("indexme");
123 do { $W->{$_}="" if !defined $W->{$_}; } for ("head");
124 do { $W->{$_}="" if !defined $W->{$_}; } for ("body_attr");
125 do { $W->{$_}="en-US" if !defined $W->{$_}; } for ("language");
128 for (qw(footer_mailme footer_ids)) {
129 $W->{$_}=0 if !$W->{"footer"};
130 $footer_any=1 if $W->{$_};
132 $W->{"footer"}=0 if !$footer_any;
133 $W->{"footer_delimit"}=0 if !$W->{"footer"};
135 $W->{"r"}=Apache->request();
137 $W->{"QUERY_STRING"}=$W->{"r"}->args() || "";
138 if ($W->{"detect_ent"}) {
139 if ($W->{"QUERY_STRING"}=~/[&]amp;have_ent/)
140 { $W->{"have_ent"}=0; }
141 elsif ($W->{"QUERY_STRING"}=~ /[&]have_ent/)
142 { $W->{"have_ent"}=1; }
144 { delete $W->{"have_ent"}; }
145 if (!defined $W->{"have_ent"} && $W->{"r"}->method() eq "GET") {
146 $W->{"head"}.='<meta http-equiv="Refresh" content="0; URL='
147 .CGI::escapeHTML("http://".&{$W->{"web_hostname_sub"}}()."/".($W->{"r"}->uri()=~m#^/*(.*)$#)[0]
148 ."?".($W->{"QUERY_STRING"} || "detect_ent_glue=1").'&have_ent=detect')
152 $W->{"QUERY_STRING"}=~s/([&])amp;/$1/g;
153 $W->{"r"}->args($W->{"QUERY_STRING"});
154 # Workaround: &CGI::Vars behaves weird if strings passed both as POST data and in: $QUERY_STRING
155 do { $W->{"r"}->args(""); delete $ENV{"QUERY_STRING"}; } if $W->{"r"}->method() eq "POST";
156 # Do not: $W->{"r"}->args()
157 # as it parses only QUERY_STRING (not POST data).
158 $W->{"args"}={ CGI->new($W->{"r"})->Vars() };
159 for my $name (keys(%{$W->{"args"}})) {
160 my @vals=split /\x00/,$W->{"args"}{$name};
162 $W->{"args"}{$name}=[@vals];
165 do { $W->{$_}=$W->{"r"}->headers_in()->{"Accept"} if !defined $W->{$_}; } for ("accept");
166 do { $W->{$_}=$W->{"r"}->headers_in()->{"User-Agent"} if !defined $W->{$_}; } for ("user_agent");
168 $W->{"browser"}=HTTP::BrowserDetect->new($W->{"user_agent"});
170 if (!defined $W->{"have_style"}) {
171 $W->{"have_style"}=(!$W->{"browser"}->netscape() || ($W->{"browser"}->major() && $W->{"browser"}->major()>4) ? 1 : 0);
174 $W->{"have_js"}=($W->{"args"}{"have_js"} ? 1 : 0);
175 if ($W->{"detect_js"} && !$W->{"have_js"}) {
176 $W->{"head"}.='<script type="text/javascript" src="'.top_dir('/have_js.js.pl').'"></script>'."\n";
179 do { args_check(%$_) if $_; } for ($W->{"args_check"});
181 $ENV{"HOSTNAME"}||=&{$W->{"web_hostname_sub"}}();
183 return bless $W,$class;
190 $W->{"r"}->puts($text);
194 # tie *FH,ref($W),$W;
200 $self->{"W"}=$W or confess "Missing W";
201 return bless $self,$class;
206 my($self,$scalar,$length,$offset)=@_;
208 Wprint substr($scalar,0,$length);
213 do { return $_ if $_; } for ($W->{"top_dir"});
214 return $INC[0]; # fallback
222 if (my $uri=$W->{"r"}->unparsed_uri()) {
223 if ($W->{"args"}{"Wabs"} || $args{"abs"}) {
224 # FIXME: $in may not be defined here!
225 # to prevent: Use of uninitialized value in ...
232 1 while $in=~s#/(?:[^/]+)/\Q..\E/#/#g
234 return "http://".&{$W->{"web_hostname_sub"}}()."/".(defined $in ? $in : "");
236 $uri.="Index" if $uri=~m#/$#;
238 my($inpath,$inquery)=split /[?]/,$in,2;
242 my($in1 ,$in2 )=($in =~m#^(/[^/]+)(/.*)$#);
243 my($uri1,$uri2)=($uri=~m#^(/[^/]+)(/.*)$#);
244 last if !defined $in1 || !defined $uri1 || $in1 ne $uri1;
251 $uri=File::Basename::dirname($uri);
252 my $r=$uri.(defined $in ? $in : "");
253 # 1 while $r=~s#^[.]/##;
254 # $r="./$r" if $r=~m#^(?:?.*)$#; # empty pathname?
257 return top_dir_disk().$in;
266 while (my($name,$regex)=each(%tmpl)) {
267 my $name_html="Parameter <span class=\"quote\">".CGI::escapeHTML($name)."</span>";
268 $W->{"args"}{$name}="" if !defined $W->{"args"}{$name};
269 $W->{"args"}{$name}=[ $W->{"args"}{$name} ] if !ref $W->{"args"}{$name} && ref $regex;
270 fatal "$name_html passed as multivar although singlevar expected"
271 if ref $W->{"args"}{$name} && !ref $regex;
272 $regex=$regex->[0] if ref $regex;
273 for my $val (!ref $W->{"args"}{$name} ? $W->{"args"}{$name} : @{$W->{"args"}{$name}}) {
274 $val="" if !defined $val;
275 fatal "$name_html <span class=\"quote\">".CGI::escapeHTML($val)."</span>"
276 ." does not match the required regex <span class=\"quote\">".CGI::escapeHTML($regex)."</span> "
277 if $regex ne "" && $val!~/$regex/;
286 return '<p'.(!defined $height ? "" : ' style="height: '.$height.';"').'> </p>'."\n";
293 $msg="UNKNOWN" if !$msg;
296 $W->{"indexme"}=0; # For the case no heading was sent yet.
297 $W->{"heading_done"}=0; # for the case of already sent {"header_only"}==1
298 $W->{"header_only"}=0; # assurance for &heading
300 Wprint "\n".vskip("3ex")."<hr /><h1 class=\"error\">FATAL ERROR: $msg!</h1>\n"
301 ."<p>You can report this problem's details to"
302 ." ".a_href("mailto:".$W->{"admin_mail"},"admin of this website").".</p>\n";
308 exit 1 if $W->{"footer_passed"}++; # deadlock prevention:
310 Wprint vskip if $W->{"footer_delimit"};
312 do { &{$_}() if $_; } for ($W->{"footing_delimit"});
314 Wprint "<hr />\n" if $W->{"footer"};
316 if ($W->{"footer_mailme"}) {
317 Wprint '<form action="'.top_dir('/SendMsg.pl').'" method="post" onsubmit="'
318 ."this.elements['msgscript'].value=this.elements['msghtml'].value;"
319 ."this.elements['msghtml'].value='';"
322 Wprint input_hidden_persistents()."\n";
323 Wprint '<p align="right">'."\n";
324 Wprint '<input name="msgscript" type="hidden" />'."\n";
325 Wprint '<input name="msghtml" type="text" size="32" alt="Message" />'."\n";
326 Wprint '<input name="submit" type="submit" value="Quick Note" />'."\n";
328 Wprint '</form>'."\n";
334 @{$W->{"packages_used"}{"__My::Web"}},
335 map((!$_ ? () : @$_),$W->{"packages_used"}{$W->{"__PACKAGE__"}}),
338 @packages_used=grep((!$packages_used{$_}++),@packages_used);
339 if ($W->{"footer_ids"}) {
340 Wprint '<p class="cvs-id">';
341 Wprint join("<br />\n",map({ my $package=$_;
342 my $cvs_id=(eval('$'.$package."::CVS_ID")
343 # || $package # debug
349 $cvs_id='$'.$cvs_id.'$'; # Eaten by 'q' operator.
350 my @cvs_id_split=split / +/,$cvs_id;
351 if (@cvs_id_split==8) {
356 for (qw(.html.pl .pl .pm),"") {
358 my $pathname=top_dir_disk()."/$file$ext";
359 push @tried,$pathname;
360 last if -r $pathname;
361 cluck "Class file $file not found; tried: ".join(" ",@tried) if !$ext;
365 .a_href((map({ my $s=$_; $s=~s#/viewcvs/#$&~checkout~/#; $s; } $W->{"viewcvs"}))[0]."$file?rev=".$cvs_id_split[2],
367 $cvs_id_split[1]=a_href($W->{"viewcvs"}.$file,
368 ($package!~/^Apache::/ ? $package : $cvs_id_split[1]));
369 $cvs_id_split[5]=&{$W->{"cvs_id_author"}}($cvs_id_split[5]);
371 join " ",@cvs_id_split;
377 for my $package (@packages_used) {
378 my $cvs_id=(eval('$'.$package."::CVS_ID")
379 # || $package # debug
381 Wprint '<!-- '.$package.' - $'.$cvs_id.'$ -->'."\n" if $cvs_id;
384 do { &{$_}() if $_; } for ($W->{"footing"});
386 Wprint "</body></html>\n";
394 while (my($key,$val)=each(%pairs)) {
395 do { cluck "Headers already sent"; next; } if $W->{"heading_done"};
396 for ($W->{"headers_lc"}{lc $key} || ()) {
397 delete $W->{"headers"}{$_};
399 $W->{"headers_lc"}{lc $key}=$key;
400 $W->{"headers"}{$key}=$val;
410 elsif ($size<1024*1024)
411 { $size=sprintf "%.1fK",$size/1024; }
413 { $size=sprintf "%.1fM",$size/1024/1024; }
422 return $url!~m#^[a-z]+://#;
429 return $url if !url_is_local $url;
430 $url=top_dir($url,%args) if $url=~m#^/# || $args{"abs"};
432 my $uri=URI->new($url);
433 # Prefer the $uri values over "args_persistent" values.
434 $uri->query_form_hash({
437 my $val=$W->{"args"}{$key};
438 (!defined $val ? () : ($key=>$val));
439 } keys(%{$W->{"args_persistent"}})),
440 %{$uri->query_form_hash()},
449 my($url,$contents,%args)=@_;
451 do { $$_=1 if !defined $$_; } for (\$args{"size"});
452 if (!defined $contents) {
454 $contents=File::Basename::basename($contents) if $args{"basename"};
455 $contents=CGI::escapeHTML($contents);
457 $contents=~s#<a\b[^>]*>##gi;
458 $contents=~s#</a>##gi;
460 $url=url_out($url,%args);
463 my $urlent=CGI::escapeHTML($url);
466 elsif (url_is_local $url)
468 elsif (defined $W->{"have_ent"} && !$W->{"have_ent"}) # non-ent client
470 elsif ($W->{"have_ent"}) # ent client
472 else # unknown client, &CGI::escapeHTML should not be needed here
473 { $r.=CGI::escapeHTML(top_dir('/Redirect.pl?location='.uri_escape($url))); }
475 do { $r.=" $_" if $_; } for ($args{"attr"});
476 $r.='>'.$contents.'</a>';
477 if ($args{"size"} && url_is_local($url) && ($args{"size"}>=2 || $url=~/[.](?:gz|Z|rpm|zip|deb|lha)/)) { # Downloadable?
478 $url=top_dir_disk().$url if $url=~m#^/#;
480 { cluck "File not readable: $url"; }
482 $r.=' ('.size_display((stat($url))[7]).')';
488 sub input_hidden_persistents()
492 my $val=$W->{"args"}{$key};
493 (!defined $val ? () : '<input type="hidden"'
494 .' name="'.CGI::escapeHTML($key).'"'
495 .' value="'.CGI::escapeHTML($val).'"'
497 } (keys(%{$W->{"args_persistent"}}))));
502 my($self,$url,$status)=@_;
504 $url=url_out($url,"abs"=>1);
505 $status||=Apache::HTTP_MOVED_TEMPORARILY;
506 $W->{"r"}->status($status);
507 $W->{"r"}->header_out("Location"=>$url);
508 $W->{"header_only"}=1;
516 # Do not: PerlModule Apache::ForwardedFor
517 # PerlPostReadRequestHandler Apache::ForwardedFor
518 # As 'Apache::ForwardedFor' takes the first of $ENV{"HTTP_X_FORWARDED_FOR"}
519 # while the contents is '127.0.0.1, 213.220.195.171' if client has its own proxy.
520 # We must take the last item ourselves.
521 my $r=$W->{"r"}->headers_in()->{"X-Forwarded-For"} || $W->{"r"}->get_remote_host();
528 return 0 if !$have_Geo_IP;
529 return "CZ" eq Geo::IP->new()->country_code_by_addr(remote_ip());
534 my($url,$contents,%args)=@_;
536 return a_href $url,$contents,%args if is_cz();
544 system {'flock'} 'flock','-x',top_dir_disk(),$cmd.' >&2';
549 my($width,$height)=@_;
551 return ($W->{"have_style"} ? "style=\"border:0;width:${width}px;height:${height}px\"" : "border=\"0\"")
552 ." width=\"$width\" height=\"$height\"";
555 sub negotiate_variant (%)
559 my @fields=("id","qs","content-type","encoding","charset","lang","size");
560 return [ map(($args{$_}),@fields) ];
564 { "id"=>"png","qs"=>1.0,"content-type"=>"image/png" },
565 { "id"=>"gif","qs"=>0.9,"content-type"=>"image/gif" },
567 my $img_variants_re='[.](?:'.join('|',"jpeg",map(($_->{"id"}),@img_variants)).')$';
573 if (!url_is_local($file_base)) {
574 return $file_base if !wantarray();
575 return ($file_base,$file_base);
577 # Known image extension?
578 if ($file_base=~m#$img_variants_re#o) {
579 return $file_base if !wantarray();
580 return ($file_base,$file_base) if $file_base!~m#^/#;
581 return (top_dir($file_base),top_dir_disk().$file_base);
586 if ($file_base!~m#^/#) {
587 $file_base_disk=$file_base_uri=$file_base;
590 $file_base_disk=top_dir_disk().$file_base;
591 $file_base_uri=top_dir($file_base);
595 for my $var (@img_variants) {
596 my $file=$file_base_disk.".".$var->{"id"};
597 # TODO: Somehow quickly check dependencies?
598 make('make -s --no-print-directory'
599 .' -C '."'".File::Basename::dirname($file)."' '".File::Basename::basename($file)."'")
601 push @nego_variants,negotiate_variant(
603 "size"=>(stat $file)[7],
606 # Do not: ,$W->{"r"});
607 # but should we provide somehow either 'HTTP::Headers' or 'HTTP::Request' ?
608 my $ext=HTTP::Negotiate::choose(\@nego_variants);
609 $ext||=$img_variants[0]->{"id"}; # &HTTP::Negotiate::choose failed?
611 return $file_base_uri.".".$ext if !wantarray();
612 return ($file_base_uri.".".$ext,$file_base_disk.".".$ext);
617 my($file_base,$alt,%attr)=@_;
619 my($file_uri,$file_disk)=img_src $file_base;
620 my($width,$height)=Image::Size::imgsize($file_disk);
622 $alt=CGI::escapeHTML($alt);
623 my $content="<img src=\"$file_uri\" alt=\"$alt\" title=\"$alt\" ".img_size($width,$height)
624 .(!$attr{"attr"} ? "" : " ".$attr{"attr"})." />";
625 return a_href img_src($attr{"a_href_img"}),$content if $attr{"a_href_img"};
626 return a_href $attr{"a_href"},$content if $attr{"a_href"};
633 $r.='<table border="0" width="100%"><tr>'."\n";
634 @_=( [@_] ) if !ref $_[0];
636 $r.="\t".'<td align="center">'.&{\&img}(@$_).'</td>'."\n";
638 $r.='</tr></table>'."\n";
644 my($text,@args_img)=@_;
646 # Workaround bug of 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)':
648 <table border="0" width="100%">
649 <col width="@{[ (!$W->{"browser"}->ie() ? "1*" : "90%" ) ]}" />
650 <col width="@{[ (!$W->{"browser"}->ie() ? "0*" : "10%" ) ]}" />
656 @{[ &{\&img}(@args_img) ]}
665 my($class,$filename)=@_;
668 open F,$filename or die "Cannot open \"$filename\": $!";
681 push @r,shift @arr; # key
691 header("Expires"=>"Mon, 26 Jul 1997 05:00:00 GMT"); # date in the past
692 header("Last-Modified"=>strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime())); # always modified
693 header("Cache-Control"=>"no-cache, must-revalidate"); # HTTP/1.1
694 header("Pragma"=>"no-cache"); # HTTP/1.0
701 # $ENV{"CLIENT_CHARSET"} ignored (mod_czech support dropped!)
702 my $client_charset=$W->{"force_charset"} || "us-ascii";
703 header("Content-Style-Type"=>"text/css");
704 header("Content-Script-Type"=>"text/javascript");
705 do { header("Content-Language"=>$_) if $_; } for $W->{"language"};
706 $class->no_cache() if $W->{"no_cache"};
708 while (my($key,$val)=each(%{$W->{"headers"}})) {
709 $W->{"r"}->header_out($key,$val);
711 if (!$W->{"header_only"}) {
712 $W->{"r"}->send_http_header("text/html; charset=$client_charset"); # "Content-type"; do not use header()
715 exit if $W->{"r"}->header_only();
716 return if $W->{"header_only"};
717 # We still can append headers before we put out some text.
718 # FIXME: It is not clean to still append them without overwriting.
719 return if $W->{"heading_done"}++;
721 if (1) { # || !$msie_major || $msie_major>=4) # TODO:dyn
722 Wprint '<?xml version="1.0" encoding="'.$client_charset.'"?>'."\n";
724 Wprint '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'."\n";
725 Wprint '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'
726 .($W->{"language"}||"en-US").'">'."\n";
727 my $title=$W->{"title_prefix"}.join("",map({ ': '.$_; } ($W->{"title"} || ())));
728 $title=~s#<[^>]*>##g;
730 Wprint "<title>$title</title>\n";
731 if ($W->{"have_css"}) {
732 # Everything can get overriden later.
734 <link rel="stylesheet" type="text/css" href="@{[ url_out("/My/Web.css") ]}" />
737 Wprint '<meta name="robots" content="'.($W->{"indexme"} ? "" : "no" ).'index,follow" />'."\n";
739 for my $type (qw(prev next index contents start up)) {
740 do { Wprint '<link rel="'.$type.'" href="'.$_.'" />'."\n" if $_; } for ($W->{"rel_$type"});
742 Wprint "</head><body";
743 # Wprint ' bgcolor="black" text="white" link="aqua" vlink="teal"'
744 # if $W->{"browser"}->netscape() && (!$W->{"browser"}->major() || $W->{"browser"}->major()<=4);
745 Wprint $W->{"body_attr"};
748 do { &{$_}() if $_; } for ($W->{"heading"});
752 delete $W->{"__My::Web_init"};