Make sure that if an attribute contains < or >, a warning is given; these
[koha.git] / misc / translator / text-extract2.pl
1 #!/usr/bin/perl
2
3 # Test filter partially based on Ambrose's hideous subst.pl code
4 # The idea is that the .tmpl files are not valid HTML, and as a result
5 # HTML::Parse would be completely confused by these templates.
6 # This is just a simple scanner (not a parser) & should give better results.
7
8 # This script is meant to be a drop-in replacement of text-extract.pl
9
10 # FIXME: Strings like "<< Prev" or "Next >>" may confuse *this* filter
11 # TODO: Need to detect unclosed tags, empty tags, and other such stuff.
12 # (Why? Because Mozilla apparently knows what SGML unclosed tags are :-/ )
13
14 # A grander plan: Code could be written to detect template variables and
15 # construct gettext-c-format-string-like meta-strings (e.g., "Results %s
16 # through %s of %s records" that will be more likely to be translatable
17 # to languages where word order is very unlike English word order.
18 # --> This will be relatively major rework, and requires corresponding
19 # rework in tmpl_process.pl
20
21 use Getopt::Long;
22 use strict;
23
24 use vars qw( $input );
25 use vars qw( $debug_dump_only_p );
26 use vars qw( $pedantic_p );
27 use vars qw( $fatal_p );
28
29 ###############################################################################
30
31 # Hideous stuff
32 use vars qw( $re_directive );
33 BEGIN {
34     # $re_directive must not do any backreferences
35     $re_directive = q{<(?:(?i)(?:!--\s*)?\/?TMPL_(?:VAR|LOOP|INCLUDE|IF|ELSE|UNLESS)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
36 }
37
38 # Hideous stuff from subst.pl, slightly modified to use the above hideous stuff
39 # Note: The $re_tag's set $1 (<tag), $2 (>), and $3 (rest of string)
40 use vars qw( $re_comment $re_entity_name $re_end_entity $re_etag );
41 use vars qw( $re_tag_strict $re_tag_compat @re_tag );
42 sub re_tag ($) {
43    my($compat) = @_;
44    my $etag = $compat? '>': '<>\/';
45    # See the file "subst.pl.test1" for how the following mess is derived
46    # Unfortunately, inserting $re_directive's has made this even messier
47    q{(<\/?(?:|(?:"(?:} . $re_directive . q{|[^"])*"|'(?:} . $re_directive . q{|[^'])*'|--(?:[^-]|-[^-])*--|(?:} . $re_directive . q{|[^-"'} . $etag . q{]|-[^-]))+))([} . $etag . q{])(.*)};
48 }
49 BEGIN {
50     $re_comment = '(?:--(?:[^-]|-[^-])*--)';
51     $re_entity_name = '(?:[^&%#;<>\s]+)'; # NOTE: not really correct SGML
52     $re_end_entity = '(?:;|$|(?=\s))'; # semicolon or before-whitespace
53     $re_etag = q{(?:<\/?(?:"[^"]*"|'[^']*'|[^"'>\/])*[>\/])}; # end-tag
54     @re_tag = ($re_tag_strict, $re_tag_compat) = (re_tag(0), re_tag(1));
55 }
56
57 # End of the hideous stuff
58
59 sub KIND_TEXT      () { 'TEXT' }
60 sub KIND_CDATA     () { 'CDATA' }
61 sub KIND_TAG       () { 'TAG' }
62 sub KIND_DECL      () { 'DECL' }
63 sub KIND_PI        () { 'PI' }
64 sub KIND_DIRECTIVE () { 'HTML::Template' }
65 sub KIND_COMMENT   () { 'COMMENT' }   # empty DECL with exactly one SGML comment
66 sub KIND_UNKNOWN   () { 'ERROR' }
67
68 use vars qw( $readahead $lc_0 $lc $syntaxerror_p );
69 use vars qw( $cdata_mode_p $cdata_close );
70
71 sub extract_attributes ($;$) {
72     my($s, $lc) = @_;
73     my %attr;
74     $s = $1 if $s =~ /^<\S+(.*)\/\S$/s  # XML-style self-closing tags
75             || $s =~ /^<\S+(.*)\S$/s;   # SGML-style tags
76
77     for (my $i = 0; $s =~ /^\s+(?:([a-zA-Z][-a-zA-Z0-9]*)\s*=\s*)?('((?:$re_directive|[^'])*)'|"((?:$re_directive|[^"])*)"|(($re_directive|[^\s<>])+))/os;) {
78         my($key, $val, $val_orig, $rest)
79                 = ($1, (defined $3? $3: defined $4? $4: $5), $2, $');
80         $i += 1;
81         $attr{+lc($key)} = [$key, $val, $val_orig, $i];
82         $s = $rest;
83         warn "Warning: Attribute should be quoted"
84                 . (defined $lc? " near line $lc": '') . ": $val_orig\n"
85                 if $val_orig !~ /^['"]/ && (
86                         ($pedantic_p && $val =~ /[^-\.A-Za-z0-9]/s)
87                         || $val =~ /[<>]/s      # this covers $re_directive, too
88                     )
89     }
90     if ($s =~ /\S/s) { # should never happen
91         if ($s =~ /^([^\n]*)\n/s) { # this is even worse
92             warn "Error: Completely confused while extracting attributes"
93                     . (defined $lc? " near line $lc": '') . ": $1\n";
94             warn "Error: " . (scalar split(/\n/, $s) - 1) . " more line(s) not shown.\n";
95             $fatal_p = 1;
96         } else {
97             warn "Warning: Strange attribute syntax"
98                     . (defined $lc? " near line $lc": '') . ": $s\n";
99         }
100     }
101     return \%attr;
102 }
103
104 sub next_token_internal (*) {
105     my($h) = @_;
106     my($it, $kind);
107     my $eof_p = 0;
108     if (!defined $readahead || !length $readahead) {
109         my $next = scalar <$h>;
110         $eof_p = !defined $next;
111         if (!$eof_p) {
112             $lc += 1;
113             $readahead .= $next;
114         }
115     }
116     $lc_0 = $lc;                        # remember line number of first line
117     if ($eof_p && !length $readahead) { # nothing left to do
118         ;
119     } elsif ($readahead =~ /^\s+/s) {   # whitespace
120         ($kind, $it, $readahead) = (KIND_TEXT, $&, $');
121     # FIXME the following (the [<\s] part) is an unreliable HACK :-(
122     } elsif ($readahead =~ /^(?:[^<]|<[<\s])+/s) {      # non-space normal text
123         ($kind, $it, $readahead) = (KIND_TEXT, $&, $');
124         warn "Warning: Unescaped < near line $lc_0: $it\n" if $it =~ /</s;
125     } else {                            # tag/declaration/processing instruction
126         my $ok_p = 0;
127         for (;;) {
128             if ($cdata_mode_p) {
129                 if ($readahead =~ /^$cdata_close/) {
130                     ($kind, $it, $readahead) = (KIND_TAG, $&, $');
131                     $ok_p = 1;
132                 } else {
133                     ($kind, $it, $readahead) = (KIND_TEXT, $readahead, undef);
134                     $ok_p = 1;
135                 }
136             } elsif ($readahead =~ /^$re_tag_compat/os) {
137                 ($kind, $it, $readahead) = (KIND_TAG, "$1$2", $3);
138                 $ok_p = 1;
139             } elsif ($readahead =~ /^<!--(?:(?!-->).)*-->/s) {
140                 ($kind, $it, $readahead) = (KIND_COMMENT, $&, $');
141                 $ok_p = 1;
142                 warn "Warning: Syntax error in comment at line $lc_0: $&\n";
143                 $syntaxerror_p = 1;
144             }
145         last if $ok_p;
146             my $next = scalar <$h>;
147             $eof_p = !defined $next;
148         last if $eof_p;
149             $lc += 1;
150             $readahead .= $next;
151         }
152         if ($kind ne KIND_TAG) {
153             ;
154         } elsif ($it =~ /^<!/) {
155             $kind = KIND_DECL;
156             $kind = KIND_COMMENT if $it =~ /^<!--(?:(?!-->).)*-->/;
157         } elsif ($it =~ /^<\?/) {
158             $kind = KIND_PI;
159         }
160         if ($it =~ /^$re_directive/ios && !$cdata_mode_p) {
161             $kind = KIND_DIRECTIVE;
162         }
163         if (!$ok_p && $eof_p) {
164             ($kind, $it, $readahead) = (KIND_UNKNOWN, $readahead, undef);
165             $syntaxerror_p = 1;
166         }
167     }
168     warn "Warning: Unrecognizable token found near line $lc_0: $it\n"
169             if $kind eq KIND_UNKNOWN;
170     return defined $it? (wantarray? ($kind, $it):
171                                     [$kind, $it]): undef;
172 }
173
174 sub next_token (*) {
175     my($h) = @_;
176     my $it;
177     if (!$cdata_mode_p) {
178         $it = next_token_internal($h);
179         if (defined $it && $it->[0] eq KIND_TAG) { # FIXME
180             ($cdata_mode_p, $cdata_close) = (1, "</$1\\s*>")
181                     if $it->[1] =~ /^<(script|style|textarea)\b/i; #FIXME
182             push @$it, extract_attributes($it->[1], $lc_0); #FIXME
183         }
184     } else {
185         for ($it = '';;) {
186             my $lc_prev = $lc;
187             my $next = next_token_internal($h);
188         last if !defined $next;
189             if (defined $next && $next->[1] =~ /$cdata_close/i) { #FIXME
190                 ($lc, $readahead) = ($lc_prev, $next->[1] . $readahead); #FIXME
191                 $cdata_mode_p = 0;
192             }
193         last unless $cdata_mode_p;
194             $it .= $next->[1]; #FIXME
195         }
196         $it = [KIND_CDATA, $it]; #FIXME
197         $cdata_close = undef;
198     }
199     return defined $it? (wantarray? @$it: $it): undef;
200 }
201
202 ###############################################################################
203
204 sub debug_dump (*) { # for testing only
205     my($h) = @_;
206     print "re_tag_compat is /$re_tag_compat/\n";
207     for (;;) {
208         my $s = next_token $h;
209     last unless defined $s;
210         printf "%s\n", ('-' x 79);
211         my($kind, $t, $attr) = @$s; # FIXME
212         printf "%s:\n", $kind;
213         printf "%4dH%s\n", length($t),
214                 join('', map {/[\0-\37]/? $_: "$_\b$_"} split(//, $t));
215         if ($kind eq KIND_TAG && %$attr) {
216             printf "Attributes:\n";
217             for my $a (keys %$attr) {
218                 my($key, $val, $val_orig, $order) = @{$attr->{$a}};
219                 printf "%s = %dH%s -- %s\n", $a, length $val,
220                 join('', map {/[\0-\37]/? $_: "$_\b$_"} split(//, $val)),
221                 $val_orig;
222             }
223         }
224     }
225 }
226
227 ###############################################################################
228
229 sub trim ($) {
230     my($s) = @_;
231     $s =~ s/^(?:\s|\&nbsp$re_end_entity)+//os;
232     $s =~ s/(?:\s|\&nbsp$re_end_entity)+$//os;
233     return $s;
234 }
235
236 ###############################################################################
237
238 sub text_extract (*) {
239     my($h) = @_;
240     my %text = ();
241     for (;;) {
242         my $s = next_token $h;
243     last unless defined $s;
244         my($kind, $t, $attr) = @$s; # FIXME
245         if ($kind eq KIND_TEXT) {
246             $t = trim $t;
247             $text{$t} = 1 if $t =~ /\S/s;
248         } elsif ($kind eq KIND_TAG && %$attr) {
249             # value [tag=input], meta
250             my $tag = lc($1) if $t =~ /^<(\S+)/s;
251             for my $a ('alt', 'content', 'title', 'value') {
252                 if ($attr->{$a}) {
253                     next if $a eq 'content' && $tag ne 'meta';
254                     next if $a eq 'value' && ($tag ne 'input'
255                         || (ref $attr->{'type'} && $attr->{'type'}->[1] eq 'hidden')); # FIXME
256                     my($key, $val, $val_orig, $order) = @{$attr->{$a}}; #FIXME
257                     $val = trim $val;
258                     $text{$val} = 1 if $val =~ /\S/s;
259                 }
260             }
261         }
262     }
263     # Emit all extracted strings. Don't emit pure whitespace or pure numbers.
264     for my $t (keys %text) {
265         printf "%s\n", $t
266             unless $t =~ /^(?:\s|\&nbsp$re_end_entity)*$/os || $t =~ /^\d+$/;
267     }
268 }
269
270 ###############################################################################
271
272 sub usage ($) {
273     my($exitcode) = @_;
274     my $h = $exitcode? *STDERR: *STDOUT;
275     print $h <<EOF;
276 Usage: $0 [OPTIONS]
277 Extract strings from HTML file.
278
279       --debug-dump-only     Do not extract strings; but display scanned tokens
280   -f, --file=FILE           Extract from the specified FILE
281       --pedantic-warnings   Issue warnings even for detected problems which
282                             are likely to be harmless
283       --help                Display this help and exit
284 EOF
285     exit($exitcode);
286 }
287
288 ###############################################################################
289
290 sub usage_error (;$) {
291     print STDERR "$_[0]\n" if @_;
292     print STDERR "Try `$0 --help' for more information.\n";
293     exit(-1);
294 }
295
296 ###############################################################################
297
298 GetOptions(
299     'f|file=s'          => \$input,
300     'debug-dump-only'   => \$debug_dump_only_p,
301     'pedantic-warnings' => sub { $pedantic_p = 1 },
302     'help'              => sub { usage(0) },
303 ) || usage_error;
304 usage_error('Missing mandatory option -f') unless defined $input;
305
306 open(INPUT, "<$input") || die "$0: $input: $!\n";
307 if ($debug_dump_only_p) {
308     debug_dump(*INPUT);
309 } else {
310     text_extract(*INPUT);
311 }
312
313 warn "Warning: This input will not work with Mozilla standards-compliant mode\n"
314         if $syntaxerror_p;
315
316 close INPUT;
317
318 exit(-1) if $fatal_p;