Debian Codegraph @

html2wml.cgi

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