Debian Codegraph @

html2chtml.cgi

raw
1 #!/usr/bin/perl
2
3 # ########################################################################### #
4 # Html2cHtml #
5 # ========== #
6 # Author: Sebastien Aperghis-Tramoni <[email protected]> #
7 # #
8 # This program converts HTML pages to compactHTML pages. #
9 # See the documentation for more informations. #
10 # #
11 # This program is available under the GNU General Public License. #
12 # #
13 # You can find the original archive of this program on the author's web site #
14 # http://www.maddingue.org/softwares/ #
15 # #
16 # and on the web site of Html2Wml on SourceForge #
17 # http://www.html2wml.org/ #
18 # #
19 # Copyright (c)2000, 2001, 2002 Sebastien Aperghis-Tramoni #
20 # ########################################################################### #
21
22 use strict;
23 use CGI;
24 use File::Basename;
25 use Getopt::Long;
26 use HTML::Parser;
27 use LWP::UserAgent;
28 use POSIX qw(isatty);
29 use Text::Template;
30 use URI;
31 use URI::URL;
32
33 use vars qw($program $version);
34 $program = 'Html2cHtml';
35 $version = '0.4.11-chtml.03';
36
37
38 # --------------------------------------------------------------------------- #
39 # Static configuration #
40 # #
41 # If you want to hard-code some parameters of Html2cHtml, this is the #
42 # place to edit. Please check the documentation for more information. #
43 # #
44 my %defaults = (
45 ## proxy settings
46 'proxy-server' => '', ## proxy server
47
48 ## cHTML version and identifier
49 'wmlvers' => q|<!DOCTYPE HTML PUBLIC "-//W3C//DTD Compact HTML 1.0 Draft//EN">|,
50
51 ## characters encoding
52 'encoding' => 'iso-8859-1',
53
54 ## links reconstruction default options
55 'hreftmpl' => '{FILEPATH}{FILENAME}{$FILETYPE =~ s/s?html?/wml/o; $FILETYPE}',
56 'srctmpl' => '{FILEPATH}{FILENAME}{$FILETYPE =~ s/gif|png|jpe?g/wbmp/o; $FILETYPE}',
57
58 ## links reconstruction in CGI mode
59 'relative-url' => 1, ## use relative self path ?
60 );
61
62 my %options = (
63 'help' => 0, ## show the usage and exit
64 'version' => 0, ## show the program name and version and exit
65
66 ## conversion options
67 'ascii' => 0, ## convert named entities to US-ASCII
68 'collapse' => 1, ## collapse white space characters
69 'compile' => 0, ## compile WML to binary tokenized data
70 'ignore-images' => 0, ## completly ignore image links
71 'img-alt-text' => 1, ## replace IMG tags with their ALT attribute
72 'linearize' => 1, ## suppress the tables tags
73 'nopre' => 0, ## don't use PRE tag
74 'numeric-non-ascii' => 0, ## convert non-ASCII characters to numeric entities
75
76 ## links reconstruction options
77 'hreftmpl' => $defaults{hreftmpl},
78 'srctmpl' => $defaults{srctmpl},
79
80 ## card splitting options
81 'split-card' => 1, ## slice the document by cards
82 'split-deck' => 0, ## slice the document by decks
83 'max-card-size' => 4_096, ## maximum size of data per card
84 'card-split-threshold' => 50, ## card split threshold
85 'next-card-label' => '[&gt;&gt;]', ## label of the link to go to the next card
86 'prev-card-label' => '[&lt;&lt;]', ## label of the link to go to the previous card
87
88 ## HTTP authentication
89 'http-user' => '', ## HTTP user
90 'http-passwd' => '', ## HTTP password
91
92 ## proxy support
93 'proxy' => 1, ## turn proxy support on/off
94
95 ## debugging options
96 'debug' => undef,## activate the debug mode
97 'xmlcheck' => 0, ## perform a well-formedness check (using XML::Parser)
98 );
99
100 # You should not edit below this line unless you know what you are doing. #
101 # --------------------------------------------------------------------------- #
102
103 #
104 # globals
105 #
106 sub debug;
107 sub warning;
108 sub fatal;
109
110 use vars qw($cgi);
111 $cgi = 0;
112 my $agent; ## LWP user agent
113 my $result; ## WML deck in text format
114 my $binary; ## WML deck in binary format
115 my $xmlckres = '';
116 my $complres = '';
117
118 my %optname = (
119 'a' => 'ascii',
120 'c' => 'xmlcheck',
121 'd' => 'debug',
122 'i' => 'ignore-images',
123 #'h' => 'help', ## shell only
124 'k' => 'compile',
125 'n' => 'numeric-non-ascii',
126 #'o' => 'output', ## shell only
127 'p' => 'nopre',
128 'P' => 'http-passwd',
129 's' => 'max-card-size',
130 't' => 'card-split-threshold',
131 'U' => 'http-user',
132 #'v' => 'version', ## shell only
133 );
134 my %optchar = ();
135
136 ## used by the html parser
137 use vars qw(%state);
138 %state = (
139 doc_uri => '', ## document absolute URI
140 doc_name => '', ## document file name
141 self_url => '', ## the CGI's URL for self-referencing
142 self_srv => '', ## the CGI's server
143 output => '', ## buffer for storing output
144 type => 'chtml', ## type of the output
145 decks => {}, ## hash that contains the decks, indexed by their id
146 skip => 0, ## skip switch (on/off)
147 stack => [], ## tag stack
148 cardsize => 0, ## size of the current card/deck
149 cardid => 'wdf000', ## ID of the current card/deck (stands for "WML Document - Fragment 000")
150 title => '', ## title of the WML deck
151 encoding => '', ## encoding of the document
152 );
153
154 my %entities = (); ## named entities conversion table
155 my %num2ascii = (); ## non-ASCII characters to ASCII equivalent conversion table
156
157 #
158 # The following two hashes are based on the WML DTD. They are the hardcoded
159 # conversion tables which describe the legal syntax of WML tags.
160 #
161 my %dtdent = ();
162 ## parameter entities
163 $dtdent{heading} = 'h1,h2,h3,h4,h5,h6';
164 $dtdent{list} = 'ul,ol,dir,menu';
165 ## text markup
166 $dtdent{phrase} = 'dfn';
167 $dtdent{special} = 'a,img,br';
168 $dtdent{form} = 'input,select,textarea';
169 $dtdent{text} = "$dtdent{phrase},$dtdent{special},$dtdent{form}";
170 ## HTML content model
171 $dtdent{block} = "p,$dtdent{list},pre,dl,div,center,blockquote,form,hr";
172 $dtdent{flow} = "$dtdent{text},$dtdent{block}";
173
174 $dtdent{emph} = 'em,strong,b,i,u,big,small';
175 $dtdent{layout} = 'br';
176 $dtdent{fields} = "$dtdent{flow},input,select,fieldset";
177 $dtdent{body} = "$dtdent{heading},$dtdent{text},$dtdent{block}";
178
179 my %with = (
180 html => { action => 'keep', nest => 'head,body', unique => 1 },
181
182 ## header tags
183 head => { action => 'keep', nest => 'meta,title,base', unique => 1 },
184 meta => { action => 'keep', nest => 'EMPTY', attributes => 'http-equiv' },
185 title => { action => 'keep', nest => '' },
186 base => { action => 'keep', nest => 'EMPTY', atrributes => 'href' },
187 style => { action => 'skip' },
188 script => { action => 'skip' },
189
190 ## structural tags
191 body => { action => 'keep', nest => $dtdent{body}, unique => 1 },
192 div => { action => 'keep', nest => $dtdent{body}, attributes => 'align' },
193 center => { action => 'keep', nest => $dtdent{body} },
194 h1 => { action => 'keep', nest => "$dtdent{text}", attributes => 'align' },
195 h2 => { action => 'keep', nest => "$dtdent{text}", attributes => 'align' },
196 h1 => { action => 'keep', nest => "$dtdent{text}", attributes => 'align' },
197 h4 => { action => 'keep', nest => "$dtdent{text}", attributes => 'align' },
198 h5 => { action => 'keep', nest => "$dtdent{text}", attributes => 'align' },
199 h6 => { action => 'keep', nest => "$dtdent{text}", attributes => 'align' },
200 p => { action => 'keep', nest => "$dtdent{text}", attributes => 'align' },
201 pre => { action => 'keep', nest => "$dtdent{text}", attributes => 'align' },
202 plaintext => { action => 'keep', nest => "$dtdent{text}", attributes => 'align' },
203 blockquote => { action => 'keep', nest => $dtdent{body} },
204 br => { action => 'keep', nest => 'EMPTY' },
205 hr => { action => 'keep', nest => 'EMPTY', attributes => 'align,' },
206
207 ## lists
208 dl => { action => 'keep', nest => 'dt,dd' },
209 dt => { action => 'keep', nest => $dtdent{text} },
210 dd => { action => 'keep', nest => $dtdent{flow} },
211 ol => { action => 'keep', nest => 'li' },
212 ul => { action => 'keep', nest => 'li' },
213 dir => { action => 'keep', nest => "li,$dtdent{block}" },
214 menu => { action => 'keep', nest => "li,$dtdent{block}" },
215 li => { action => 'keep', nest => $dtdent{flow} },
216
217 ## tables
218 caption => { action => 'replace', new_value => 'p', render => 'b' },
219 'tr' => { action => 'replace', new_value => 'p' },
220 th => { action => 'replace', new_value => 'p', render => 'b' },
221 #td => { action => 'keep', nest => "$dtdent{emph},$dtdent{layout},img,a,anchor" },
222
223 ## link tags
224 a => { action => 'keep', nest => "$dtdent{text}", attributes => 'name,href,accesskey' },
225 img => { action => 'keep', nest => 'EMPTY', attributes => 'src,align,width,height,hspace,vspace,alt,border' },
226 frame => { action => 'replace', new_value => 'p' },
227 area => { action => 'replace', new_value => 'p' },
228
229 ## style tags
230 em => { action => 'keep', nest => $dtdent{flow} },
231 strong => { action => 'keep', nest => $dtdent{flow} },
232 b => { action => 'keep', nest => $dtdent{flow} },
233 i => { action => 'keep', nest => $dtdent{flow} },
234 u => { action => 'keep', nest => $dtdent{flow} },
235 big => { action => 'keep', nest => $dtdent{flow} },
236 small => { action => 'keep', nest => $dtdent{flow} },
237
238 ## form tags
239 form => { action => 'keep', nest => $dtdent{body}, attributes => 'action,method,enctype' },
240 input => { action => 'keep', nest => 'EMPTY', attributes => 'type,name,value,checked,size,maxlength,src,align'},
241 'select' => { action => 'keep', nest => 'option', attributes => 'name,size,multiple' },
242 option => { action => 'keep', nest => 'EMPTY', attributes => 'selected,value' },
243 textarea => { action => 'keep', nest => 'EMPTY', attributes => 'name,rows,cols' },
244 );
245
246
247 #
248 # The following hash hardcodes the parent-lookup for each element
249 # of the WML syntax, i.e. for each element, it gives the prefered
250 # parent element.
251 #
252 my %reverse = (
253 html => '',
254
255 ## header tags
256 head => 'html', meta => 'head',
257 title => 'head', base => 'head',
258
259 ## structural tags
260 body => 'html', div => 'body', center => 'body', p => 'body',
261 h1 => 'body', h2 => 'body', h3 => 'body', h4 => 'body',
262 h5 => 'body', h6 => 'body', pre => 'body', plaintext => 'body',
263 br => 'p', hr => 'p',
264
265 ## lists tags
266 dl => 'p', dt => 'dl', dd => 'dl',
267 ol => 'p', ul => 'p', dir => 'p', menu => 'p',
268 li => 'ul',
269
270 ## link tags
271 a => 'p', img => 'p',
272
273 ## style tags
274 b => 'p', i => 'p', u => 'p',
275 strong => 'p', em => 'p',
276 big => 'p', small => 'p',
277
278 ## form tags
279 form => 'body', input => 'form', 'select' => 'form', option => 'select',
280 textarea => 'form',
281 );
282
283
284
285 #
286 # main
287 #
288 $| = 1;
289 my $time = time;
290
291 Getopt::Long::Configure(qw(no_auto_abbrev));
292
293 fileparse_set_fstype('Unix'); ## this is because I use fileparse() to
294 ## split the URL fragments
295
296 ## CGI security options
297 $CGI::POST_MAX = 1024 * 1; # max 1K posts
298 $CGI::DISABLE_UPLOADS = 1; # no uploads
299
300 load_entities();
301
302 ## create the user agent
303 $agent = new LWP::UserAgent protocols_forbidden => ['file'];
304 $agent->agent("[$program/$version ".$agent->agent.']');
305
306 for my $opt (keys %optname) {
307 $optchar{$optname{$opt}} = $opt
308 }
309
310 ## constructing %num2ascii using data from %entities
311 for my $ent (keys %entities) {
312 $num2ascii{$entities{$ent}[0]} = $entities{$ent}[1]
313 }
314
315 if(@ARGV or isatty(\*STDOUT)) {
316 ## launched from shell
317
318 my @opts = (
319 ## usage options
320 qw(help|h|H version|v|V),
321
322 ## conversion options
323 qw(ascii|a! collapse! ignore-images|i img-alt-text!
324 linearize! nopre|p numeric-non-ascii|n),
325
326 ## links reconstructions options
327 qw(hreftmpl=s srctmpl=s),
328
329 ## card splitting options
330 qw(split-card split-deck
331 max-card-size|s=i card-split-threshold|t=i
332 next-card-label=s prev-card-label=s),
333
334 ## HTTP authentication
335 qw(http-user|U=s http-passwd|P=s),
336
337 ## proxy support
338 qw(proxy|Y!),
339
340 ## output options
341 qw(compile|k output|o=s),
342
343 ## debugging options
344 qw(debug|d:i xmlcheck|c!)
345 );
346
347 ## getting options
348 GetOptions(\%options, @opts);
349 version() if $options{version};
350 usage() if $options{help};
351 usage() unless @ARGV;
352 apply_options();
353
354 ## converting the file
355 $result = html2wml(shift);
356
357 } else {
358 ## launched from web
359 $cgi = new CGI;
360 $agent->agent($cgi->user_agent . ' ' . $agent->agent);
361 $cgi->compile(qw(param url header));
362
363 ## get the options
364 for my $param ($cgi->param) {
365 my $option = length($param) == 1 ? $optname{$param} : $param;
366 next unless exists $options{$option};
367 $options{$option} = $cgi->param($param)
368 }
369
370 apply_options();
371
372 $state{doc_name} = 'output';
373
374 ## creating static part of the self url
375 my $cgi_options = '';
376 for my $param ($cgi->param) {
377 next if 'url,id' =~ /\b$param\b/;
378 my $value = $cgi->param($param);
379 next unless $value;
380 next unless exists $options{$param} or exists $options{$optname{$param}};
381 my $opt = exists $optchar{$param} ? $optchar{$param} : $param;
382 $cgi_options .= "$param=$value;"
383 }
384
385 $state{self_url} = $cgi->url(-relative => $defaults{'relative-url'}) . "?$cgi_options";
386
387 ## send debug header if needed
388 print $cgi->header if $options{'debug'};
389
390 ## execute main part
391 $result = html2wml($cgi->param('url') || '/');
392 }
393
394
395 ## special case: splitting by decks
396 if($cgi and $options{'split-deck'}) {
397 ## return the desired deck (as specified by the id parameter)
398 ## or the first deck if none has been specified
399 $result = $state{decks}{ $cgi->param('id') || (sort keys %{$state{decks}})[0] }
400 }
401
402
403 ## XML check
404 if($options{xmlcheck}) {
405
406 eval {
407 require XML::Parser;
408 my $parser = new XML::Parser Style => 'Tree', ErrorContext => 2;
409 $parser->parse($result);
410 };
411 $@ =~ /Can't locate/ and $@ = '(XML::Parser not available)';
412 $xmlckres = $@ ? "\nExpat errors\n$@" : "Expat: well-formed";
413
414 eval {
415 require XML::LibXML;
416 my $parser = new XML::LibXML;
417 $parser->validation(1);
418 $parser->expand_entities(1);
419 $parser->load_ext_dtd(1);
420 my $dom = $parser->parse_string($result);
421 #die "document isn't valid" unless $dom->is_valid;
422 };
423 $@ =~ /Can't locate/ and $@ = ', (XML::LibXML not available)';
424 $xmlckres .= $@ ? "\nGnome-XML errors\n$@" : ", Gnome-XML: valid";
425
426 eval {
427 require XML::Checker::Parser;
428 #XML::Checker::Parser::map_uri(
429 # "-//WAPFORUM//DTD WML 1.2//EN" => "file:///Users/madingue/Documents/Softwares/Html2Wml/devel/t/wml12.dtd"
430 #);
431 my $parser = new XML::Checker::Parser Style => 'Tree',
432 ErrorContext => 2, ParseParamEnt => 1, #NoLWP => 1,
433 SkipExternalDTD => 1, KeepCDATA => 1;
434 $parser->parse($result);
435 };
436 $@ =~ /Can't locate/ and $@ = ', (XML::Checker not available)';
437 $xmlckres .= $@ ? "\nXML-Checker errors\n$@" : ", XML-Checker: valid";
438 }
439
440
441 ## WML tokenization
442 if($options{compile}) {
443 $binary = '';
444 my $buf;
445
446 eval {
447 require IPC::Open2;
448 require IO::Handle;
449 my $in = new IO::Handle;
450 my $out = new IO::Handle;
451
452 my $pid = IPC::Open2::open2($out, $in, $defaults{wmlc}, '-', '-');
453
454 print $in $result;
455 close($in);
456 $binary = join '', <$out>;
457 close($out);
458 waitpid($pid, 0);
459 };
460
461 $complres = $@
462 }
463
464
465 if($options{'debug'}) { ## debug output
466 $time = time - $time;
467 my @times = times;
468 $times[0] += $times[2]; ## total user time
469 $times[1] += $times[3]; ## total system time
470 $times[2] = $times[0] + $times[1]; ## total time
471
472 my $i = 1;
473 $result .= "\n";
474 $result =~ s/^/@{[sprintf '%3d', $i++]}: /gm; ## add lines number
475 $result = simple_wrap($result);
476
477 if($cgi) {
478 print qq|<html>\n<head>\n<title>$program -- Debug Mode</title>\n|,
479 qq|<style type="text/css">\n BODY { background-color: #ffffff}\n|,
480 qq| .tag { color: #8811BB }\n .attr { color: #553399 }\n </style>\n|,
481 qq|</head>\n<body>\n<h1>$program -- Debug Mode</h1>\n|,
482 qq|<p>This is the result of the conversion of the document |,
483 qq|<a href="$state{doc_uri}">$state{doc_uri}</a> by $program v$version.</p>\n|,
484 qq|<hr />\n|,
485 htmlize($result),
486 qq|<hr />\n<p>Result of XML check:</p>\n|,
487 htmlize($xmlckres);
488
489 print qq|<hr />\n<p>Result of WML compilation:</p>\n<pre>|,
490 ($complres ? "$complres\n" : hextype($binary)), "</pre>\n"
491 if $options{compile};
492
493 printf "<hr />\n<p>Time: $time wallclock secs (%.2f usr + %.2f sys = %.2f cpu)</p>\n",
494 @times[0..2];
495
496 print qq|\n</body>\n</html>|
497
498 } else {
499 my $s = "$program -- Debug Mode\n";
500 print $s, '-'x length($s), "\n",
501 $result, "\n", ' -'x5, "\n",
502 $xmlckres, "\n";
503 print ' -'x5, "\nCompiled WML\n", ' -'x5, "\n",
504 ($complres ? "$complres\n" : hextype($binary))
505 if $options{compile};
506 print ' -'x5, "\n";
507 printf "Time: $time wallclock secs (%.2f usr + %.2f sys = %.2f cpu)\n", @times[0..2];
508 }
509
510 } else { ## normal output
511 my $out = \*STDOUT;
512
513 if($options{'output'}) {
514 open(OUT, ">$options{output}") or fatal "cannot write to '$options{output}': $!\n";
515 $out = \*OUT;
516 }
517
518 if($options{'compile'}) {
519 print $out $cgi->header(
520 -type => 'application/vnd.wap.wmlc',
521 -content_length => length $result
522 ) if $cgi;
523 print $out $binary;
524
525 } else {
526 print $out $cgi->header(
527 -type => "text/vnd.wap.wml; charset=$state{encoding}",
528 -content_length => length $result
529 ) if $cgi;
530 print $out $result;
531 }
532 }
533
534
535
536 #
537 # apply_options()
538 # -------------
539 sub apply_options {
540 if($options{'linearize'}) {
541 delete @with{qw(table tr td th)};
542 $with{'caption'} = { action => 'replace', new_value => 'p', render => 'b' };
543 $with{'tr'} = { action => 'replace', new_value => 'p' };
544 delete @reverse{qw(table tr td)};
545 }
546
547 if($options{'ignore-images'}) {
548 delete $with{'img'};
549 }
550
551 if(not defined $options{'debug'}) {
552 $options{'debug'} = 0;
553 } elsif($options{'debug'} == 0) {
554 $options{'debug'} = 1;
555 }
556
557 if($options{'debug'}) {
558 $options{'xmlcheck'} = 1;
559 }
560
561 if($options{'nopre'}) {
562 delete $with{'pre'};
563 $with{'pre'} = { action => 'replace', new_value => 'p' };
564 $with{'plaintext'} = { action => 'replace', new_value => 'p' };
565 }
566
567 if($cgi) {
568 $options{'split-card'} = 0;
569 $options{'split-deck'} = 1;
570
571 ## security: don't allow to modify the templates
572 ## when called as a CGI
573 $options{'hreftmpl'} = $defaults{'hreftmpl'};
574 $options{'srctmpl'} = $defaults{'srctmpl'};
575 }
576
577 ## security: check if the templates contains suspicious code
578 ## if the templates have changed
579 if($options{hreftmpl} ne $defaults{hreftmpl} or $options{srctmpl} ne $defaults{srctmpl}) {
580 my $forbidden = join '|', '[``]', map {"\\b$_\\b"}
581 qw(eval exec system unlink kill fork open sysopen pipe socket);
582
583 $options{hreftmpl} = $defaults{hreftmpl} if $options{hreftmpl} =~ /$forbidden/;
584 $options{srctmpl} = $defaults{hreftmpl} if $options{srctmpl} =~ /$forbidden/;
585 }
586
587 $options{'cardsize-limit'} = $options{'max-card-size'} - $options{'card-split-threshold'};
588
589 if($^O eq 'MacOS') {
590 $options{'compile'} = 0;
591 }
592
593 if($options{'compile'}) {
594 $options{'prev-card-label'} = '[&#38;lt;&#38lt;]';
595 }
596
597 ## proxy support
598 if($options{'proxy'}) {
599 if($defaults{'proxy-server'}) {
600 ## use hardcoded settings
601 $agent->proxy([qw(http ftp gopher)] => $defaults{'proxy-server'});
602
603 } else {
604 ## load from environment
605 $agent->env_proxy();
606 }
607 }
608
609 ## cHTML: there is no "multi-body" in cHTML as there is the
610 ## multi-card mechanism in WML, so we always activate the
611 ## document slicing (split-deck option)
612 $options{'split-card'} = 0;
613 $options{'split-deck'} = 1;
614 }
615
616
617 #
618 # html2wml()
619 # --------
620 sub html2wml {
621 my $url = shift;
622 my $file = '';
623 my $type = '';
624 my $enc = '';
625 my $converter = new HTML::Parser api_version => 3;
626
627 return unless $url;
628
629 ## read the file
630 if($url =~ m{https?://}) { ## absolute uri
631 ($file,$type,$enc) = get_url($url)
632
633 } elsif(not $cgi) { ## local file
634 $file = read_file($url)
635
636 } else { ## absolute url relative to the server
637 ($file,$type,$enc) = get_url( $url = URI::URL->new($url, $cgi->url)->abs )
638 }
639
640 $enc ||= '';
641 $enc =~ s/charset=//i;
642 url_encode($url);
643 $state{doc_uri} = $url;
644 ($state{self_srv}) = ($state{self_url} =~ m|^(https?://[\w.-]+(?::\d+)?)/|);
645
646 ## strip the DOCTYPE
647 $file =~ s/<!DOCTYPE[^>]+>//go;
648
649 ## try to get the document charset encoding
650 if(not $enc and $file =~ m|meta +http-equiv.+charset=["']?([a-zA-Z0-9_-]+)['"]?|i) {
651 $enc = lc $1
652 }
653
654 $state{encoding} = $enc || $defaults{'encoding'};
655
656 $type ||= '';
657
658 ## if it's an image, call send_image()
659 if(index($type, 'image') >= 0 or $url =~ /\.(?:gif|jpg|png)$/i) {
660 @_ = ($file, $url);
661 goto &send_image
662 }
663
664 ## get the document title
665 if($file =~ m|<title>([^<]+)</title>|i) {
666 $state{title} = $1;
667 convert_entities($state{title});
668 clean_spaces($state{title});
669 }
670
671 ## WML header
672 $state{skip} = 0;
673 $state{output} = "$defaults{wmlvers}\n";
674
675 ## affectation of the HTML::Parser handlers
676 $converter->unbroken_text(1);
677 $converter->handler(start => \&start_tag, 'tagname, attr');
678 $converter->handler(end => \&end_tag, 'tagname');
679 $converter->handler(text => \&text_tag, 'text, is_cdata');
680 $converter->handler(comment => \&comment_tag, 'tokens');
681 #$converter->handler(declaration => \&default_handler, 'text');
682 #$converter->handler(process => \&default_handler, 'text');
683 #$converter->handler(default => \&default_handler, 'text');
684
685 ## begin the conversion
686 $converter->parse($file);
687 $converter->eof;
688
689 ## flush the stack
690 while(my $tag = pop @{$state{stack}}) {
691 $state{output} .= "</$tag>"
692 }
693
694 post_conversion_cleanup();
695
696 $state{decks}{$state{cardid}} = $state{output};
697
698 return $state{output}
699 }
700
701
702 #
703 # post_conversion_cleanup()
704 # -----------------------
705 #
706 sub post_conversion_cleanup {
707 ## convert alone ampersand characters to entities
708 $state{output} =~ s/\&\s/\&#38; /go;
709
710 ## correct unclosed numeric entities
711 $state{output} =~ s/(\&#\d+)([^\d;])/$1;$2/go;
712
713 ## convert the named HTML entities to numeric entities
714 convert_entities($state{output});
715
716 ## convert non-ASCII characters to numeric entities
717 if($options{'numeric-non-ascii'}) {
718 $state{output} =~ s/([\x80-\xFF])/'&#'.ord($1).';'/eg;
719 }
720
721 ## escape $ chars
722 #$state{output} =~ s/\$/\$\$/go; ## not needed in cHTML
723
724 collapse($state{output}) if $options{'collapse'};
725
726 ## set the title of the card
727 if(length $state{title}) {
728 my $title = $state{title};
729 $title =~ s/"/\&#34;/go;
730 $title =~ s/\$/\$\$/go;
731 $title =~ s/(\&#\d+)([^\d;])/$1;$2/go;
732 $state{output} =~ s/<card/<card title="$title"/g;
733 }
734 }
735
736
737 #
738 # collapse()
739 # --------
740 # Collapse empty spaces and paragraphes from the given parameter
741 #
742 sub collapse{
743 $_[0] =~ s/\015\012|\012|\015/\n/go; ## converts CR/LF to native eol
744 $_[0] =~ s|\s+>|>|go; ## collapse spaces inside tags
745 $_[0] =~ s|\s+/>|/>|go; ## collapse spaces inside empty tags
746 $_[0] =~ s|<(\w+) +|<$1 |g; ## collapse spaces between tag and attributes
747 $_[0] =~ s|<p>\s+|<p>|go; ## collapse spaces at the begining of a paragraph
748 $_[0] =~ s|\s+</p>|</p>|go; ## collapse spaces at the end of a paragraph
749
750 ## collapse empty paragraphs
751 $_[0] =~ s|<p[^>]*>\s*</p>||go;
752 $_[0] =~ s|<p[^>]*>\s*(?:<br/>)+\s*</p>||go;
753 $_[0] =~ s|<p[^>]*>\s*(?:\&nbsp;\s*)+</p>||go;
754 $_[0] =~ s|<p[^>]*>\s*(?:\&#32;\s*)+</p>||go;
755 $_[0] =~ s|<p[^>]*>\s*(?:\[IMG\]\s*)+</p>||go;
756 $_[0] =~ s|<(\w+)>\s*</\1>||go;
757
758 ## collapse multiple lines
759 $_[0] =~ s/\n+/\n/go;
760 $_[0] =~ s/(?: +\n)+/\n/go;
761 }
762
763
764 #
765 # get_url()
766 # -------
767 # This function gets and returns the file from the given URI.
768 # If called in a array context, returns the file content and the associated
769 # MIME type (as given by the server).
770 #
771 sub get_url {
772 my $uri = shift;
773 my $quiet = shift || 0;
774
775 if($cgi and index($uri, 'file:') == 0) {
776 cgi_error(q|For security reasons, the file: scheme is not allowed.|)
777 }
778
779 my $request = new HTTP::Request GET => $uri;
780 my $response = $agent->request($request);
781
782 if($response->is_error) {
783 if($response->status_line == 401) {
784 ## Authorization required
785 my($realm) = ($response->header('WWW-Authenticate') =~ /realm=(.+)/);
786 my $self = "$state{self_url}url=$state{doc_uri}";
787
788 if($options{'http-user'} and $options{'http-passwd'}) {
789 $request->www_authenticate($response->header('WWW-Authenticate'));
790 $request->authorization_basic($options{'http-user'}, $options{'http-passwd'});
791 $response = $agent->request($request);
792
793 } else {
794 if($cgi) {
795 print $cgi->header(-type => 'text/vnd.wap.wml'), <<"PASSFORM"; exit
796 <?xml version="1.0"?>
797 $defaults{wmlvers}
798 <wml><card title="Authentication">
799 <p>Please enter your user name and password for $realm. </p>
800 <p>User: <input name="U" type="text" emptyok="false"/><br/>
801 Password: <input name="P" type="password" emptyok="false"/></p>
802 <do type="accept"><go href="$self;U=\$(U);P=\$(P)"/></do>
803 </card></wml>
804 PASSFORM
805 } else {
806 fatal <<"PASSASK"
807 website requires authentication
808
809 The web site requires you to authenticate in order to process your request.
810 Please enter your user name and password for $realm.
811 Use the --http-user and --http-passwd options (or their short counterparts
812 -U and -P). Check the documentation for more information.
813 PASSASK
814 }
815 }
816
817 } else {
818 my $err = <<"ERR";
819 The following error occured while trying to access the following URL
820 -- $uri --
821 Error @{[ $response->status_line ]}
822 ERR
823 if($cgi) {
824 if($quiet) {
825 warning "can't fetch file:\n", $err;
826 return '';
827 } else {
828 cgi_error($err)
829 }
830 } else {
831 fatal "fetch error\n\n", $err
832 }
833 }
834 }
835
836 return wantarray ? ($response->content, $response->content_type,
837 $response->content_encoding) : $response->content
838 }
839
840
841 #
842 # read_file()
843 # ---------
844 # This function reads and returns the file from the local disk.
845 #
846 sub read_file {
847 my $filepath = shift;
848 my $quiet = shift || 0;
849
850 my $dir = dirname($filepath);
851 my $file = basename($filepath);
852 chdir($dir) if $dir;
853
854 open(FILE, $file) or my $failed = 1;
855
856 if($failed) {
857 if($quiet) {
858 warning("can't read file '$file': $!\n") and return ''
859 } else {
860 fatal("can't read file '$file': $!\n")
861 }
862 }
863
864 local $/ = undef;
865 $file = <FILE>;
866 close(FILE);
867 return $file
868 }
869
870
871 #
872 # send_image()
873 # ----------
874 # This function allow Html2Wml to send WBMP images to the client.
875 # Currently, it send an empty hardcoded image, but support for
876 # conversion from common formats (GIF, JPEG, PNG) will be added soon.
877 #
878 sub send_image {
879 my $data = shift;
880 my $path = shift;
881
882 my $pixel = pack 'C*', 0, 0, 1, 1, 0xFF; ## this is one white pixel
883
884 ## TODO: add the code to allow conversion using an external program
885
886 print $cgi->header(-type => 'image/wbmp', -content_length => length $pixel), $pixel;
887 exit
888 }
889
890
891 #
892 # convert_entities()
893 # ----------------
894 # This function converts the named HTML entities into numeric entities.
895 #
896 sub convert_entities {
897 my $ascii = $options{ascii};
898
899 ## try to correct unclosed named entities
900 $_[0] =~ s/(&\w{2,6})\b([^;])/$1;$2/go;
901
902 ## convert numeric entities and non-ASCII characters
903 ## to ASCII equivalent if requested
904 if($ascii) {
905 $_[0] =~ s/&#(\d+);/$num2ascii{$1}/g;
906 $_[0] =~ s/([\x80-\xFF])/$num2ascii{ord($1)}/g;
907 }
908
909 my $code = q| while($_[0] =~ /&(\w+);/g) { |
910 . q| my $ent = $1; |
911 . q| if(exists $entities{$ent}) { |
912 .($ascii ? q| my $chr = $entities{$ent}[1]; |
913 : q| my $chr = '&#'.$entities{$ent}[0].';'; | )
914 . q| $_[0] =~ s/&$ent;/$chr/g |
915 . q| } |
916 . q| } |;
917
918 eval $code;
919
920 if($_[0] =~ /&(\w{2,6});?/) {
921 ## there are some residual unknown or incorrect named entities
922 while($_[0] =~ /&(\w{2,6});?/g) {
923 my $ent = $1;
924
925 ## check if $ent is a known entity
926 if(exists $entities{$ent}) {
927 warning "unclosed entity: $ent, corrected\n";
928 my $chr = $ascii ? $entities{$ent}[1] : '&#'.$entities{$ent}[0].';';
929 $_[0] =~ s//$chr/;
930 next
931 }
932
933 my($e1,$e2) = ('','');
934
935 ## split the entity in two parts and check if the first part
936 ## is a valid entity name
937 ## entities names are between 2 and 6 characters long, so this
938 ## loop won't be executed more than 4 times
939 for my $i (2..length($ent)) {
940 $e1 = substr($ent, 0, $i);
941 $e2 = substr($ent, $i);
942 last if exists $entities{$e1}
943 }
944
945 if(exists $entities{$e1}) {
946 warning "unknown entity: $ent, replaced with $e1\n";
947 my $chr = $ascii ? $entities{$e1}[1] : '&#'.$entities{$e1}[0].';';
948 $_[0] =~ s//$chr$e2/;
949 } else {
950 warning "unknown entity: $ent\n";
951 $_[0] =~ s//&#38;$ent/;
952 }
953 }
954 }
955
956 ## escape the remaining ampersands
957 $_[0] =~ s/&(\w+[^;])/&#38;$1/g;
958 }
959
960
961 #
962 # clean_spaces()
963 # ------------
964 sub clean_spaces {
965 $_[0] =~ s/\t+/ /go;
966 $_[0] =~ s/^\s+/ /go;
967 $_[0] =~ s/ +/ /go;
968 }
969
970
971 #
972 # HTML::Parser start tag handler
973 #
974 sub start_tag {
975 my($tag, $attr) = @_;
976 local $_;
977 return unless exists $with{$tag};
978
979 return if $state{skip};
980
981 my $curr_tag = ($with{$tag}{action} eq 'replace' ? $with{$tag}{new_value} : $tag);
982 my $prev_tag = scalar @{$state{stack}} ? ${$state{stack}}[-1] : 0;
983
984 ## prevent incorrect auto-nesting
985 return if $curr_tag eq $prev_tag and $with{$curr_tag}{unique} and $with{$curr_tag}{nest} !~ /\b$curr_tag\b/;
986
987 ## special case: replacing image with its alternative text when necessary
988 if($curr_tag eq 'img' and $options{'img-alt-text'}) {
989 my $alt = $attr->{alt} || $attr->{title} || $attr->{id} || $attr->{name} || '[IMG]';
990 text_tag($alt) and return
991 }
992
993 ## special case: <frame> tag
994 if($tag eq 'frame') {
995 if($prev_tag eq 'p') { pop @{$state{stack}}; $state{output} .= '</p>' }
996 if($prev_tag eq 'wml') { push @{$state{stack}}, 'card'; $state{output} .= '<card>' }
997 my $link = xlate_url($$attr{src}, 'href');
998 $state{output} .= qq|<p><small>Frame: <a href="$link">$$attr{name}</a></small></p>|;
999 }
1000
1001 ## special case: <area> image map tag
1002 if($tag eq 'area') {
1003 if($prev_tag eq 'p') { pop @{$state{stack}}; $state{output} .= '</p>' }
1004 if($prev_tag eq 'wml') { push @{$state{stack}}, 'card'; $state{output} .= '<card>' }
1005 my $link = xlate_url($$attr{href}, 'href');
1006 $state{output} .= qq|<p><small>Image map: <a href="$link">$$attr{href}</a></small></p>|;
1007 }
1008
1009 ## special case: when inside a <a> don't allow opening tags
1010 if($prev_tag eq 'a' and $with{a}{nest} !~ /\b$curr_tag\b/) {
1011 return
1012 }
1013
1014 ## special case: <a name=".."> is replaced by <anchor id="..">
1015 if($curr_tag eq 'a' and not exists $attr->{href}) {
1016 $curr_tag = $tag = 'anchor';
1017 $attr->{id} = exists $attr->{id} ? $attr->{id} : $attr->{name};
1018 delete $attr->{name};
1019 }
1020
1021 ## special case: <base> element that defines a base URL
1022 if($tag eq 'base') {
1023 $state{doc_uri} = URI::URL->new($attr->{href}, $state{doc_uri})->abs;
1024 }
1025
1026 ## reconstruct well-formed attributes list with only the allowed ones
1027 if(exists $with{$curr_tag}{attributes} and scalar keys %$attr) {
1028 my @attrs = ();
1029
1030 for my $param (keys %$attr) {
1031 if(index($with{$curr_tag}{attributes}, $param) >= 0) {
1032 $param = $with{$tag}{attrconv}{$param} if exists $with{$tag}{attrconv}{$param};
1033 my $value = $attr->{$param};
1034
1035 if($param eq 'align' or $param eq 'type') {
1036 $value = lc $value
1037 } elsif($param eq 'href' or $param eq 'src') {
1038 $value = xlate_url($value, $param);
1039 }
1040 convert_entities($value);
1041 push @attrs, qq|$param="$value"|;
1042 }
1043 }
1044
1045 $attr = join ' ', '', @attrs;
1046
1047 } else {
1048 $attr = ''
1049 }
1050
1051 ## set the skip mode state
1052 $state{skip} = 1 if $with{$curr_tag}{action} eq 'skip';
1053
1054 debug [2], "\n(start tag) <$tag> => action: ", ($with{$tag}{action} ? $with{$tag}{action} : 'clear'), ($curr_tag ne $tag ? " with $curr_tag " : ''), ($attr? ", attributes:$attr" : ''), "\n";
1055
1056
1057 if($with{$curr_tag}{action} eq 'keep') {
1058 # TODO: this part of the syntax repairing engine will have to be
1059 # re-written. Maybe a loop on the stack to check whether the
1060 # tree is correct, and in case not, insert the missing ones
1061
1062 if(scalar @{$state{stack}}) {
1063 debug [2], " -> syntax repair: closing tags ";
1064 ## syntax repair: close the tags that were left opened
1065 while($prev_tag = pop @{$state{stack}}) {
1066 if($with{$prev_tag}{nest} =~ /\b$curr_tag\b/
1067 or $with{$prev_tag}{nest} =~ /\b$reverse{$curr_tag}\b/) {
1068 push @{$state{stack}}, $prev_tag;
1069 last
1070 }
1071 debug [2], "</$prev_tag> ";
1072 $state{output} .= "</$prev_tag>";
1073 }
1074 debug [2], "\n";
1075 }
1076
1077 ## syntax repair: open the tags that should have been opened
1078 if($with{$prev_tag}{nest} !~ /\b$curr_tag\b/) {
1079 debug [2], " -> syntax repair: opening tags ";
1080
1081 my($inner_tag,$outter_tag) = ($curr_tag,$prev_tag);
1082 my @nesting_tags = ();
1083
1084 while($reverse{$inner_tag} and $reverse{$inner_tag} ne $outter_tag) {
1085 $inner_tag = $reverse{$inner_tag};
1086 debug [2], "<$inner_tag> ";
1087 unshift @nesting_tags, $inner_tag;
1088 }
1089
1090 push @{$state{stack}}, @nesting_tags;
1091 for my $t (@nesting_tags) { $state{output} .= "<$t>" }
1092 debug [2], "\n";
1093 debug [2], " new stack: (@{$state{stack}})\n";
1094 }
1095 }
1096
1097 ## clean up a little
1098 collapse($state{output}) if $options{'collapse'};
1099
1100 ## split the card if needed ## disabled for cHTML
1101 #if($state{cardsize} > $options{'cardsize-limit'}
1102 # and exists $with{$tag}{special} and $with{$tag}{special} =~ /nowidow/) {
1103 # split_card()
1104 #}
1105
1106 ## simple tag translation
1107 if($with{$curr_tag}{action} eq 'keep') {
1108 if($with{$curr_tag}{nest} eq 'EMPTY') {
1109 $state{cardsize} += length($curr_tag) + length($attr);
1110 $state{output} .= "<$curr_tag$attr/>"
1111 } else {
1112 $state{cardsize} += length($curr_tag) + length($attr);
1113 $state{output} .= "<$curr_tag$attr>";
1114 push @{$state{stack}}, $curr_tag;
1115 }
1116
1117 } else {
1118 ## do nothing
1119 }
1120
1121 ## additional rendering effects
1122 if(defined $with{$tag}{render}) { ## note that it's $tag, not $curr_tag
1123 for my $t (split ',', $with{$tag}{render}) {
1124 $state{cardsize} += length $t;
1125 $state{output} .= "<$t>"
1126 }
1127 }
1128 }
1129
1130
1131 #
1132 # HTML::Parser end tag handler
1133 #
1134 sub end_tag {
1135 my($tag) = @_;
1136 return unless exists $with{$tag};
1137 my $curr_tag = ($with{$tag}{action} eq 'replace' ? $with{$tag}{new_value} : $tag);
1138
1139 ## special case: anchors
1140 if($tag eq 'a' and ${$state{stack}}[-1] eq 'anchor') { $curr_tag = $tag = 'anchor'}
1141
1142 debug [2], "( end tag ) </$curr_tag> stack = (@{$state{stack}})\n\n";
1143
1144 $state{skip} = 0 if $with{$tag}{action} eq 'skip';
1145 return if $state{skip};
1146 return if exists $with{$tag}{nest} and $with{$tag}{nest} eq 'EMPTY';
1147
1148 ## additional rendering effects
1149 if(defined $with{$tag}{render}) { ## note that it's $tag, not $curr_tag
1150 for my $t (reverse split ',', $with{$tag}{render}) {
1151 $state{cardsize} += length $t;
1152 $state{output} .= "</$t>"
1153 }
1154 }
1155
1156 ## special case: /card cleans up the stack
1157 if($curr_tag eq 'card') {
1158 while(${$state{stack}}[-1] ne $curr_tag) {
1159 my $t = pop @{$state{stack}};
1160 $state{cardsize} += length $t;
1161 $state{output} .= "</$t>";
1162 }
1163
1164 my $s = qq|\n<p align="right"><do type="prev" | .
1165 qq|label="$options{'prev-card-label'}"><prev/></do></p>|;
1166 $state{cardsize} += length $s ;#- 25;
1167 $state{output} .= $s;
1168 }
1169
1170 ## closing element
1171 if(${$state{stack}}[-1] eq $curr_tag and $with{$curr_tag}{action} eq 'keep') {
1172 $state{cardsize} += length $curr_tag;
1173 $state{output} .= "</$curr_tag> ";
1174 pop @{$state{stack}};
1175
1176 } else {
1177 ## do nothing
1178 }
1179
1180 ## clean up a little
1181 collapse($state{output}) if $options{'collapse'};
1182
1183 ## check current card size ## disabled for cHTML
1184 #if($curr_tag ne 'card' and $curr_tag ne 'wml' and $state{cardsize} > $options{'cardsize-limit'}) {
1185 # split_card()
1186 #}
1187 }
1188
1189
1190 #
1191 # HTML::Parser text handler
1192 #
1193 sub text_tag {
1194 my($text) = @_;
1195 my $curr_tag = ${$state{stack}}[-1] || '';
1196
1197 debug [3], "(text node) stack = (@{$state{stack}})\n- - - - -\n$text\n- - - - -\n";
1198
1199 return if $state{skip};
1200
1201 return if $text =~ /^\s*$/s; ## skip empty lines
1202
1203 ## add a para tag if we're on the card node
1204 if($curr_tag eq 'card') {
1205 $state{cardsize} += 4;
1206 $state{output} .= "\n<p>";
1207 push @{$state{stack}}, 'p';
1208 }
1209
1210 clean_spaces($text) if $options{'collapse'} and $curr_tag ne 'pre';
1211 #
1212 # TODO: add the code that split too long chunks of text
1213 #
1214 $state{output} .= $text;
1215 $state{cardsize} += length $text;
1216 }
1217
1218
1219 #
1220 # HTML::Parser comment tag handler
1221 #
1222 sub comment_tag {
1223 my($comment) = @_;
1224 local $_;
1225
1226 $comment = join '', @$comment;
1227
1228 debug [3], "( comment ) stack = (@{$state{stack}})\n $comment\n";
1229
1230 ## Actions engine
1231 if($comment =~ /^\s*\[(\w+)\s*(.*)\]\s*$/) {
1232 my $action = $1;
1233 my %attributes = map { /\G(\w+)=["']([^"']+)["']/g } split /\s+/, $2;
1234
1235 for my $attr (keys %attributes) {
1236 if($attr eq 'for') {
1237 return if $attributes{$attr} ne $state{type};
1238 }
1239 if($attr eq 'virtual' and $attributes{virtual} !~ /^http:/) {
1240 $attributes{virtual} = URI::URL->new( $attributes{virtual}, $state{doc_uri} )->abs
1241 }
1242 }
1243
1244 for($action) {
1245 /include/ and do {
1246 my $buf;
1247 if($attributes{virtual}) {
1248 $buf = get_url($attributes{virtual}, 1);
1249 } elsif($attributes{file}) {
1250 $buf = read_file($attributes{file}, 1)
1251 }
1252 $state{output} .= $buf;
1253 $state{cardsize} = length $buf;
1254 };
1255
1256 /skip/ and do {
1257 $state{skip} = 1;
1258 };
1259
1260 /end_skip/ and do {
1261 $state{skip} = 0;
1262 };
1263
1264 /fsize/ and do {
1265 my $buf;
1266 if($attributes{virtual}) {
1267 $buf = length get_url($attributes{virtual}, 1);
1268 } elsif($attributes{file}) {
1269 $buf = length read_file($attributes{file}, 1)
1270 }
1271 $state{output} .= $buf;
1272 $state{cardsize} = length $buf;
1273 };
1274 }
1275 }
1276 }
1277
1278
1279 #
1280 # HTML::Parser default handler
1281 #
1282 sub default_handler {
1283 my($text) = @_;
1284 debug [2], "( default ) [$text]\n\n";
1285 }
1286
1287
1288 #
1289 # split_card()
1290 # ----------
1291 # This function closes the current card and creates a new one.
1292 #
1293 sub split_card {
1294 my @stack = @{$state{stack}};
1295 shift @stack; ## shift the <wml> tag
1296 shift @stack; ## shift the <card> tag
1297
1298 my $id = $state{cardid}++;
1299 $state{cardsize} = 0;
1300 debug [2], "(splitcard) stack = (@{$state{stack}})\n\n";
1301
1302 for my $tag (reverse @stack) { $state{output} .= "</$tag>" }
1303
1304 my $doc_uri = $state{doc_uri};
1305
1306 # strip the server part if the document and this CGI are on the same server
1307 $doc_uri =~ s/^$state{self_srv}//o if $cgi;
1308
1309 my $link_to_next = $options{'split-deck'} ?
1310 "$state{self_url}url=$doc_uri;id=$state{cardid}" : "#$state{cardid}";
1311
1312 $state{output} .= join '', qq|\n<p align="right">|,
1313 qq|<a href="$link_to_next"/>$options{'next-card-label'}</a>|,
1314 qq|</p>\n</body>\n|;
1315
1316 if($options{'split-deck'}) {
1317 post_conversion_cleanup();
1318 $state{output} .= '</html>';
1319 $state{decks}{$id} = $state{output};
1320 $state{output} = "$defaults{wmlvers}\n<html>";
1321 }
1322
1323 $state{output} .= qq|<card id="$state{cardid}">\n|;
1324
1325 for my $tag (@stack) { $state{output} .= "<$tag>" }
1326 }
1327
1328
1329 #
1330 # xlate_url()
1331 # ---------
1332 # This function translates the given url so that the pointed document will
1333 # pass through this CGI for conversion when in CGI mode, or construct a url
1334 # that fits the needs of the webmaster using the given template, if present.
1335 #
1336 sub xlate_url {
1337 my $url = shift; ## $url is the url from a href or a src attribute
1338 my $type = shift; ## $type is 'src' or 'href'
1339
1340 ## URL encode special characters
1341 url_encode($url);
1342
1343 ## we only treat http URLs
1344 return $url if $url =~ /^(\w+):/ and index($1, 'http') != 0;
1345
1346 if($cgi) {
1347 ## CGI mode
1348
1349 # create the absolute URL relative to the document
1350 my $link = URI::URL->new($url, $state{doc_uri})->abs;
1351
1352 # strip the server part if the URL and this CGI are on the same server
1353 $link =~ s/^$state{self_srv}//o;
1354
1355 return "$state{self_url}url=$link"
1356
1357 } else {
1358 ## shell mode
1359
1360 ## we don't touch URLs other than http(s):
1361 return $url if $url =~ m|^(\w+):| and index($1, 'http') < 0;
1362
1363 ## This is where the link reconstruction engine lives... (waah... :)
1364
1365 if($options{"${type}tmpl"} and $url !~ m|^https?://|) {
1366 ## we don't touch absolute urls
1367
1368 my $tmpl = $options{"${type}tmpl"};
1369 my $uri = new URI $url, 'http';
1370
1371 if($uri->path) {
1372 my($filename,$filepath,$filetype) = fileparse($uri->path, '((?:\.\w+)+)');
1373
1374 my $init_vars = qq|{
1375 sub FILEPATH { q<$filepath> }
1376 sub FILENAME { q<$filename> }
1377 sub FILETYPE { q<$filetype> }
1378 sub URL { q<$url> }
1379 }|;
1380
1381 my $new_url = new Text::Template TYPE => 'STRING', SOURCE => $init_vars.$tmpl
1382 or fatal("can't construct template: $Text::Template::ERROR\n");
1383
1384 return $new_url->fill_in(HASH => {
1385 'FILEPATH' => $filepath,
1386 'FILENAME' => $filename,
1387 'FILETYPE' => $filetype,
1388 'URL' => $url
1389 }) or fatal("$Text::Template::ERROR\n")
1390
1391 } else {
1392 return $url
1393 }
1394
1395 } else {
1396 return $url
1397 }
1398 }
1399 }
1400
1401
1402 #
1403 # url_encode()
1404 #
1405 sub url_encode {
1406 $_[0] =~ s'[$]'%24'go;
1407 $_[0] =~ s'&'%26'go;
1408 $_[0] =~ s';'%3b'go;
1409 $_[0] =~ s'='%3d'go;
1410 $_[0] =~ s'[?]'%3f'go;
1411 }
1412
1413
1414 #
1415 # htmlize()
1416 # -------
1417 # This function translate the given text into HTML
1418 #
1419 sub htmlize {
1420 my $str = shift;
1421
1422 ## convert special chars to entities
1423 $str =~ s/&/\&amp;/go;
1424 $str =~ s/</\&lt;/go;
1425 $str =~ s/>/\&gt;/go;
1426
1427 ## add a small syntax highlighting
1428 $str =~ s{(\&lt;[!?/]?)(\w+)(.*?)([!?/]?\&gt;)}
1429 {<b>$1<span class="tag">$2</span></b><span class="attr">$3</span><b>$4</b>}gs;
1430 $str =~ s{\&lt;!--(.*?)--\&gt;}{\&lt;!--<i>$1</i>--\&gt;}gs;
1431 $str =~ s{href="([^\"]+)"}{href="<a href="$1">$1</a>"}gs;
1432
1433 return "<pre>$str</pre>"
1434 }
1435
1436
1437 #
1438 # hextype()
1439 # -------
1440 # This function generates a human readable representation of binary data
1441 #
1442 sub hextype {
1443 my $data = shift; ## data to print
1444 my $colwidth = shift || 16; ## width of ASCII column
1445
1446 my $half = $colwidth/2;
1447 my $line = 1;
1448 my $out = '';
1449
1450 while(length $data) {
1451 my @hex = unpack 'C'x$colwidth, substr($data, 0, $colwidth);
1452 substr($data, 0, $colwidth) = '';
1453 $out .= sprintf '%3d: '. ((('%02x 'x$half).' ')x2) .' ', $line++, @hex;
1454 $out .= sprintf ''.('%s'x$half)x2 . "\n", map { $_ > 32 ? chr : '.' } @hex;
1455 }
1456
1457 return $out
1458 }
1459
1460
1461 #
1462 # simple_wrap()
1463 # -----------
1464 # This function wraps the text given in parameter.
1465 #
1466 sub simple_wrap {
1467 my $orig = ref $_[0] ? $_[0] : \$_[0];
1468 my $text = '';
1469 my $curlen = 0;
1470 my $beg = ' 'x5;
1471 my $cols = 75;
1472
1473 while($$orig =~ m/(\s*\S+\s+)/gm) {
1474 if($curlen + length($1) > $cols) {
1475 $text .= "\n$beg$1";
1476 $curlen = 1 + length($beg) + length($1)
1477 } else {
1478 $text .= $1;
1479 $curlen += length $1;
1480 }
1481 $curlen = 0 if index($1, "\n") >= 0;
1482 }
1483
1484 return $text
1485 }
1486
1487
1488 #
1489 # load_entities()
1490 # -------------
1491 #
1492 sub load_entities {
1493 %entities = (
1494 ## Special entities
1495 quot => [ 34, '&#34;'],## double quote
1496 quote => [ 34, '&#34;'],## double quote
1497 amp => [ 38, '&#38;'],## ampersand
1498 apos => [ 39, '&#39;'],## single quote
1499 lt => [ 60, '&#60;'],## less than sign
1500 gt => [ 62, '&#62;'],## greater than sign
1501
1502 ## Spacing characters
1503 nbsp => [ 32, ' '], ## non-breaking space (real value #160)
1504 ensp => [ 32, ' '], ## en space (real value: #8194, U+2002)
1505 emsp => [ 32, ' '], ## em space (real value: #8195, U+2003)
1506 thinsp => [ 32, ' '], ## thin space (real value: #8201, U+2009)
1507 zwnj => [ 0, '' ], ## zero width non-joiner (real value: #8204, U+200C)
1508 zwj => [ 0, '' ], ## zero width joiner (real value: #8205, U+200D)
1509
1510 ## Latin Extended-A entities + Mathematical symbols
1511 sbquo => [130, ','], ## single low-9 quotation mark
1512 fnof => [131, 'f'], ## latin small f with hook = florin
1513 bdquo => [132, ',,'], ## double low-9 quotation mark
1514 hellip => [133, '...'], ## horizontal ellipsis
1515 dagger => [134, ' '], ## dagger
1516 Dagger => [135, ' '], ## double dagger
1517 circ => [136, '^'], ## modifier letter circumflex accent
1518 permil => [137, 'o/oo'], ## per mille sign
1519 Scaron => [138, 'S'], ## latin capital letter S with caron
1520 lsaquo => [139, '&#60;'],## single left-pointing angle quotation mark
1521 OElig => [140, 'OE'], ## latin capital ligature OE
1522 lsquo => [145, "'"], ## left single quotation mark
1523 rsquo => [146, "'"], ## right single quotation mark
1524 ldquo => [147, '"'], ## left double quotation mark
1525 rdquo => [148, '"'], ## right double quotation mark
1526 bull => [149, 'o'], ## bullet
1527 ndash => [150, '-'], ## en dash
1528 mdash => [151, '--'], ## em dash
1529 tilde => [152, '~'], ## small tilde
1530 trade => [153, '(tm)'], ## trademark sign
1531 scaron => [154, 's'], ## latin small letter s with caron
1532 rsaquo => [155, '&#62;'],## single right-pointing angle quotation mark
1533 oelig => [156, 'oe'], ## latin small ligature oe
1534 Yuml => [159, 'Y'], ## latin capital letter Y with diaeresis
1535
1536 ## ISO-Latin-1 entities
1537 iexcl => [161, '!'],
1538 cent => [162, '-c-'],
1539 pound => [163, '-L-'],
1540 curren => [164, 'CUR'],
1541 yen => [165, 'YEN'],
1542 brvbar => [166, '|'],
1543 sect => [167, 'S:'],
1544 uml => [168, '"'],
1545 copy => [169, '(c)'],
1546 ordf => [170, '-a'],
1547 laquo => [171, '&#60;&#60;'],
1548 'not' => [172, 'NOT'],
1549 shy => [173, '-'],
1550 reg => [174, '(R)'],
1551 macr => [175, '-'],
1552 deg => [176, 'DEG'],
1553 plusmn => [177, '+/-'],
1554 sup2 => [178, '^2'],
1555 sup3 => [179, '^3'],
1556 acute => [180, "'"],
1557 micro => [181, 'u'],
1558 para => [182, 'P:'],
1559 middot => [183, '.'],
1560 cedil => [184, ','],
1561 sup1 => [185, '^1'],
1562 ordm => [186, '-o'],
1563 raquo => [187, '&#62;&#62;'],
1564 frac14 => [188, ' 1/4'],
1565 frac12 => [189, ' 1/2'],
1566 frac34 => [190, ' 3/4'],
1567 iquest => [191, '?'],
1568 Agrave => [192, 'A'],
1569 Aacute => [193, 'A'],
1570 Acirc => [194, 'A'],
1571 Atilde => [195, 'A'],
1572 Auml => [196, 'Ae'],
1573 Aring => [197, 'A'],
1574 AElig => [198, 'AE'],
1575 Ccedil => [199, 'C'],
1576 Egrave => [200, 'E'],
1577 Eacute => [201, 'E'],
1578 Ecirc => [202, 'E'],
1579 Euml => [203, 'E'],
1580 Igrave => [204, 'I'],
1581 Iacute => [205, 'I'],
1582 Icirc => [206, 'I'],
1583 Iuml => [207, 'I'],
1584 ETH => [208, 'DH'],
1585 Ntilde => [209, 'N'],
1586 Ograve => [210, 'O'],
1587 Oacute => [211, 'O'],
1588 Ocirc => [212, 'O'],
1589 Otilde => [213, 'O'],
1590 Ouml => [214, 'Oe'],
1591 'times' => [215, '*'],
1592 Oslash => [216, 'O'],
1593 Ugrave => [217, 'U'],
1594 Uacute => [218, 'U'],
1595 Ucirc => [219, 'U'],
1596 Uuml => [220, 'Ue'],
1597 Yacute => [221, 'Y'],
1598 THORN => [222, 'P'],
1599 szlig => [223, 'ss'],
1600 agrave => [224, 'a'],
1601 aacute => [225, 'a'],
1602 acirc => [226, 'a'],
1603 atilde => [227, 'a'],
1604 auml => [228, 'ae'],
1605 aring => [229, 'a'],
1606 aelig => [230, 'ae'],
1607 ccedil => [231, 'c'],
1608 egrave => [232, 'e'],
1609 eacute => [233, 'e'],
1610 ecirc => [234, 'e'],
1611 euml => [235, 'e'],
1612 igrave => [236, 'i'],
1613 iacute => [237, 'i'],
1614 icirc => [238, 'i'],
1615 iuml => [239, 'i'],
1616 eth => [240, 'e'],
1617 ntilde => [241, 'n'],
1618 ograve => [242, 'o'],
1619 oacute => [243, 'o'],
1620 ocirc => [244, 'o'],
1621 otilde => [245, 'o'],
1622 ouml => [246, 'o'],
1623 divide => [247, '/'],
1624 oslash => [248, 'o'],
1625 ugrave => [249, 'u'],
1626 uacute => [250, 'u'],
1627 ucirc => [251, 'u'],
1628 uuml => [252, 'u'],
1629 yacute => [253, 'y'],
1630 thorn => [254, 'p'],
1631 yuml => [255, 'y'],
1632 );
1633 }
1634
1635
1636 #
1637 # warning()
1638 # -------
1639 sub warning {
1640 print STDERR 'html2wml: warning: ', @_
1641 }
1642
1643
1644 #
1645 # fatal()
1646 # -----
1647 sub fatal {
1648 print STDERR 'html2wml: fatal: ', @_;
1649 exit -1;
1650 }
1651
1652
1653 #
1654 # debug()
1655 # -----
1656 sub debug {
1657 if($options{'debug'}) {
1658 my $level = ref $_[0] ? shift->[0] : 1;
1659 print STDERR @_ if $level <= $options{'debug'}
1660 }
1661 }
1662
1663
1664 #
1665 # version()
1666 # -------
1667 sub version {
1668 print "$program/$version\n"; exit
1669 }
1670
1671
1672 #
1673 # usage()
1674 # -----
1675 sub usage {
1676 print STDERR <<"USAGE"; exit
1677 usage: $0 [options] file [-o output]
1678
1679 options:
1680 -a, --ascii use 7 bits ASCII emulation to convert named entities
1681 --nocollapse don't collapse spaces and empty paragraphs
1682 --hreftmpl=template set the template for the links reconstruction engine
1683 -i, --ignore-images completly ignore image links
1684 --noimg-alt-text don't replace the images by their alternative text
1685 --nolinearize don't linearize the tables
1686 -n, --numeric-non-ascii convert non-ASCII characters to numeric entities
1687 -p, --nopre don't use the <pre> tag
1688
1689 --split-card slice the document by cards (default)
1690 --split-deck slice the document by decks
1691 -s, --max-card-size=size set the card size upper limit
1692 -t, --card-split-threshold=size set the card splitting threshold
1693 --next-card-label=label set the label of the link to the next card
1694 --prev-card-label=label set the label of the link to the previous card
1695
1696 -U, --http-user set the HTTP user
1697 -P, --http-passwd set the HTTP password
1698
1699 -Y, --proxy use proxy settings provided by environnement
1700 --noproxy don't use proxy
1701
1702 -k, --compile compile the result in binary form
1703 -o, --output=outfile select the outpout (stdout if none specified)
1704
1705 -d, --debug=n activate the debug mode (always prints to stdout)
1706 -c, --xmlcheck activate the XML well-formedness and validity check
1707
1708 -h, --help show this help screen and exit
1709 -v, --version show the program name and version and exit
1710
1711 Read the documentation for more information.
1712 USAGE
1713 }
1714
1715
1716 #
1717 # cgi_error()
1718 # ---------
1719 sub cgi_error {
1720 if($options{'debug'}) {
1721 print <<"OUTPUT"; exit
1722 <html>
1723 <head>
1724 <title>Html2Wml - Error</title>
1725 </head>
1726 <body>
1727 <h1>Html2Wml - Error</h1>
1728 <p>This program was called with incorrect parameters or an error occured
1729 when processing the request. Please check your request and try again. </p>
1730 <p>@_</p>
1731 <hr />
1732 <p>$program v$version</p>
1733 </body>
1734 </html>
1735 OUTPUT
1736 } else {
1737 print $cgi->header(-type => 'text/vnd.wap.wml'), <<"OUTPUT"; exit
1738 <?xml version="1.0"?>
1739 $defaults{wmlvers}
1740 <wml><card title="Html2Wml - Error">
1741 <p>This program was called with incorrect parameters or an error occured
1742 when processing the request. Please check your request and try again. </p>
1743 <p>@_</p>
1744 <p>_____<br/>$program v$version</p>
1745 </card></wml>
1746 OUTPUT
1747 }
1748 }
1749
1750
1751 1;