Don't bother warning about TMPL_VAR if the key is onclick, onblur, etc.
[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 # A grander plan: Code could be written to detect template variables and
11 # construct gettext-c-format-string-like meta-strings (e.g., "Results %s
12 # through %s of %s records" that will be more likely to be translatable
13 # to languages where word order is very unlike English word order.
14 # --> This will be relatively major rework, and requires corresponding
15 # rework in tmpl_process.pl
16
17 use Getopt::Long;
18 use strict;
19
20 use vars qw( $input );
21 use vars qw( $debug_dump_only_p );
22 use vars qw( $pedantic_p $pedantic_tag );
23 use vars qw( $pedantic_attribute_error_in_nonpedantic_mode_p );
24 use vars qw( $pedantic_tmpl_var_use_in_nonpedantic_mode_p );
25 use vars qw( $fatal_p );
26
27 ###############################################################################
28
29 # Hideous stuff
30 use vars qw( $re_directive $re_tmpl_var $re_tmpl_var_escaped $re_tmpl_include );
31 use vars qw( $re_directive_control $re_tmpl_endif_endloop );
32 BEGIN {
33     # $re_directive must not do any backreferences
34     $re_directive = q{<(?:(?i)(?:!--\s*)?\/?TMPL_(?:VAR|LOOP|INCLUDE|IF|ELSE|UNLESS)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
35     # TMPL_VAR or TMPL_INCLUDE
36     $re_tmpl_var = q{<(?:(?i)(?:!--\s*)?TMPL_(?:VAR)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
37     $re_tmpl_include = q{<(?:(?i)(?:!--\s*)?TMPL_(?:INCLUDE)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
38     # TMPL_VAR ESCAPE=1/HTML/URL
39     $re_tmpl_var_escaped = q{<(?:(?i)(?:!--\s*)?TMPL_(?:VAR|INCLUDE)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))\s+ESCAPE=(?:1|HTML|URL)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
40     # Any control flow directive
41     $re_directive_control = q{<(?:(?i)(?:!--\s*)?\/?TMPL_(?:LOOP|IF|ELSE|UNLESS)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
42     # /LOOP or /IF or /UNLESS
43     $re_tmpl_endif_endloop = q{<(?:(?i)(?:!--\s*)?\/TMPL_(?:LOOP|IF|UNLESS)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
44 }
45
46 # Hideous stuff from subst.pl, slightly modified to use the above hideous stuff
47 # Note: The $re_tag's set $1 (<tag), $2 (>), and $3 (rest of string)
48 use vars qw( $re_comment $re_entity_name $re_end_entity $re_etag );
49 use vars qw( $re_tag_strict $re_tag_compat @re_tag );
50 sub re_tag ($) {
51    my($compat) = @_;
52    my $etag = $compat? '>': '<>\/';
53    # This is no longer similar to the original regexp in subst.pl :-(
54    # Note that we don't want <> in compat mode; Mozilla knows about <
55    q{(<\/?(?:|(?:"(?:} . $re_directive . q{|[^"])*"|'(?:} . $re_directive . q{|[^'])*'|--(?:[^-]|-[^-])*--|(?:}
56    . $re_directive
57    . q{|(?!--)[^"'<>} . $etag . q{]))+))([} . $etag . q{]|(?=<))(.*)};
58 }
59 BEGIN {
60     $re_comment = '(?:--(?:[^-]|-[^-])*--)';
61     $re_entity_name = '(?:[^&%#;<>\s]+)'; # NOTE: not really correct SGML
62     $re_end_entity = '(?:;|$|(?=\s))'; # semicolon or before-whitespace
63     $re_etag = q{(?:<\/?(?:"[^"]*"|'[^']*'|[^"'>\/])*[>\/])}; # end-tag
64     @re_tag = ($re_tag_strict, $re_tag_compat) = (re_tag(0), re_tag(1));
65 }
66
67 # End of the hideous stuff
68
69 sub KIND_TEXT      () { 'TEXT' }
70 sub KIND_CDATA     () { 'CDATA' }
71 sub KIND_TAG       () { 'TAG' }
72 sub KIND_DECL      () { 'DECL' }
73 sub KIND_PI        () { 'PI' }
74 sub KIND_DIRECTIVE () { 'HTML::Template' }
75 sub KIND_COMMENT   () { 'COMMENT' }   # empty DECL with exactly one SGML comment
76 sub KIND_UNKNOWN   () { 'ERROR' }
77
78 use vars qw( $readahead $lc_0 $lc $syntaxerror_p );
79 use vars qw( $cdata_mode_p $cdata_close );
80
81 ###############################################################################
82
83 sub warn_pedantic ($$) {
84     my($flag, $msg) = @_;
85     warn "Warning$pedantic_tag: $msg\n" if $pedantic_p || !$$flag;
86     if (!$pedantic_p) {
87         warn "Warning$pedantic_tag: Further similar negligible warnings will not be reported, use --pedantic for details\n" unless $$flag;
88         $$flag = 1;
89     }
90 }
91
92 ###############################################################################
93
94 sub extract_attributes ($;$) {
95     my($s, $lc) = @_;
96     my %attr;
97     $s = $1 if $s =~ /^<\S+(.*)\/\S$/s  # XML-style self-closing tags
98             || $s =~ /^<\S+(.*)\S$/s;   # SGML-style tags
99
100     for (my $i = 0; $s =~ /^(?:$re_directive_control)?\s+(?:$re_directive_control)?(?:([a-zA-Z][-a-zA-Z0-9]*)\s*=\s*)?('((?:$re_directive|[^'])*)'|"((?:$re_directive|[^"])*)"|((?:$re_directive|[^\s<>])+))/os;) {
101         my($key, $val, $val_orig, $rest)
102                 = ($1, (defined $3? $3: defined $4? $4: $5), $2, $');
103         $i += 1;
104         $attr{+lc($key)} = [$key, $val, $val_orig, $i];
105         $s = $rest;
106         if ($val =~ /$re_tmpl_include/os) {
107             warn "Warning: TMPL_INCLUDE in attribute"
108                 . (defined $lc? " near line $lc": '') . ": $val_orig\n";
109         } elsif ($val =~ /$re_tmpl_var/os && $val !~ /$re_tmpl_var_escaped/os) {
110             # XXX: we probably should not warn if key is "onclick" etc
111             # XXX: there's just no reasonable thing to suggest
112             my $suggest = ($key =~ /^(?:action|archive|background|cite|classid|codebase|data|datasrc|for|href|longdesc|profile|src|usemap)$/i? 'URL': 'HTML');
113             undef $suggest if $key =~ /^(?:onblur|onchange|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onload|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onreset|onselect|onsubmit|onunload)$/i;
114             warn_pedantic \$pedantic_tmpl_var_use_in_nonpedantic_mode_p,
115                     "Suggest ESCAPE=$suggest for TMPL_VAR in attribute \"$key\""
116                     . (defined $lc? " near line $lc": '') . ": $val_orig"
117                 if defined $suggest && ($pedantic_p || !$pedantic_tmpl_var_use_in_nonpedantic_mode_p);
118         } elsif ($val_orig !~ /^['"]/) {
119             my $t = $val; $t =~ s/$re_directive_control//os;
120             warn_pedantic \$pedantic_attribute_error_in_nonpedantic_mode_p,
121                 "Unquoted attribute contains character(s) that should be quoted"
122                 . (defined $lc? " near line $lc": '') . ": $val_orig"
123                 if $t =~ /[^-\.A-Za-z0-9]/s;
124         }
125     }
126     my $s2 = $s; $s2 =~ s/$re_tmpl_endif_endloop//g; # for the next check
127     if ($s2 =~ /\S/s) { # should never happen
128         if ($s =~ /^([^\n]*)\n/s) { # this is even worse
129             warn "Error: Completely confused while extracting attributes"
130                     . (defined $lc? " near line $lc": '') . ": $1\n";
131             warn "Error: " . (scalar split(/\n/, $s) - 1) . " more line(s) not shown.\n";
132             $fatal_p = 1;
133         } else {
134             warn "Warning: Strange attribute syntax"
135                     . (defined $lc? " near line $lc": '') . ": $s\n";
136         }
137     }
138     return \%attr;
139 }
140
141 sub next_token_internal (*) {
142     my($h) = @_;
143     my($it, $kind);
144     my $eof_p = 0;
145     if (!defined $readahead || !length $readahead) {
146         my $next = scalar <$h>;
147         $eof_p = !defined $next;
148         if (!$eof_p) {
149             $lc += 1;
150             $readahead .= $next;
151         }
152     }
153     $lc_0 = $lc;                        # remember line number of first line
154     if ($eof_p && !length $readahead) { # nothing left to do
155         ;
156     } elsif ($readahead =~ /^\s+/s) {   # whitespace
157         ($kind, $it, $readahead) = (KIND_TEXT, $&, $');
158     # FIXME the following (the [<\s] part) is an unreliable HACK :-(
159     } elsif ($readahead =~ /^(?:[^<]|<[<\s])+/s) {      # non-space normal text
160         ($kind, $it, $readahead) = (KIND_TEXT, $&, $');
161         warn "Warning: Unescaped < near line $lc_0: $it\n"
162                 if !$cdata_mode_p && $it =~ /</s;
163     } else {                            # tag/declaration/processing instruction
164         my $ok_p = 0;
165         for (;;) {
166             if ($cdata_mode_p) {
167                 if ($readahead =~ /^$cdata_close/) {
168                     ($kind, $it, $readahead) = (KIND_TAG, $&, $');
169                     $ok_p = 1;
170                 } else {
171                     ($kind, $it, $readahead) = (KIND_TEXT, $readahead, undef);
172                     $ok_p = 1;
173                 }
174             } elsif ($readahead =~ /^$re_tag_compat/os) {
175                 ($kind, $it, $readahead) = (KIND_TAG, "$1>", $3);
176                 $ok_p = 1;
177                 warn "Warning: SGML \"closed start tag\" notation near line $lc_0: $1<\n" if $2 eq '';
178             } elsif ($readahead =~ /^<!--(?:(?!-->).)*-->/s) {
179                 ($kind, $it, $readahead) = (KIND_COMMENT, $&, $');
180                 $ok_p = 1;
181                 warn "Warning: Syntax error in comment at line $lc_0: $&\n";
182                 $syntaxerror_p = 1;
183             }
184         last if $ok_p;
185             my $next = scalar <$h>;
186             $eof_p = !defined $next;
187         last if $eof_p;
188             $lc += 1;
189             $readahead .= $next;
190         }
191         if ($kind ne KIND_TAG) {
192             ;
193         } elsif ($it =~ /^<!/) {
194             $kind = KIND_DECL;
195             $kind = KIND_COMMENT if $it =~ /^<!--(?:(?!-->).)*-->/;
196         } elsif ($it =~ /^<\?/) {
197             $kind = KIND_PI;
198         }
199         if ($it =~ /^$re_directive/ios && !$cdata_mode_p) {
200             $kind = KIND_DIRECTIVE;
201         }
202         if (!$ok_p && $eof_p) {
203             ($kind, $it, $readahead) = (KIND_UNKNOWN, $readahead, undef);
204             $syntaxerror_p = 1;
205         }
206     }
207     warn "Warning: Unrecognizable token found near line $lc_0: $it\n"
208             if $kind eq KIND_UNKNOWN;
209     return defined $it? (wantarray? ($kind, $it):
210                                     [$kind, $it]): undef;
211 }
212
213 sub next_token (*) {
214     my($h) = @_;
215     my $it;
216     if (!$cdata_mode_p) {
217         $it = next_token_internal($h);
218         if (defined $it && $it->[0] eq KIND_TAG) { # FIXME
219             ($cdata_mode_p, $cdata_close) = (1, "</$1\\s*>")
220                     if $it->[1] =~ /^<(script|style|textarea)\b/i; #FIXME
221             push @$it, extract_attributes($it->[1], $lc_0); #FIXME
222         }
223     } else {
224         for ($it = '';;) {
225             my $lc_prev = $lc;
226             my $next = next_token_internal($h);
227         last if !defined $next;
228             if (defined $next && $next->[1] =~ /$cdata_close/i) { #FIXME
229                 ($lc, $readahead) = ($lc_prev, $next->[1] . $readahead); #FIXME
230                 $cdata_mode_p = 0;
231             }
232         last unless $cdata_mode_p;
233             $it .= $next->[1]; #FIXME
234         }
235         $it = [KIND_CDATA, $it]; #FIXME
236         $cdata_close = undef;
237     }
238     return defined $it? (wantarray? @$it: $it): undef;
239 }
240
241 ###############################################################################
242
243 sub debug_dump (*) { # for testing only
244     my($h) = @_;
245     print "re_tag_compat is /$re_tag_compat/\n";
246     for (;;) {
247         my $s = next_token $h;
248     last unless defined $s;
249         printf "%s\n", ('-' x 79);
250         my($kind, $t, $attr) = @$s; # FIXME
251         printf "%s:\n", $kind;
252         printf "%4dH%s\n", length($t),
253                 join('', map {/[\0-\37]/? $_: "$_\b$_"} split(//, $t));
254         if ($kind eq KIND_TAG && %$attr) {
255             printf "Attributes:\n";
256             for my $a (keys %$attr) {
257                 my($key, $val, $val_orig, $order) = @{$attr->{$a}};
258                 printf "%s = %dH%s -- %s\n", $a, length $val,
259                 join('', map {/[\0-\37]/? $_: "$_\b$_"} split(//, $val)),
260                 $val_orig;
261             }
262         }
263     }
264 }
265
266 ###############################################################################
267
268 sub trim ($) {
269     my($s) = @_;
270     $s =~ s/^(?:\s|\&nbsp$re_end_entity)+//os;
271     $s =~ s/(?:\s|\&nbsp$re_end_entity)+$//os;
272     return $s;
273 }
274
275 ###############################################################################
276
277 sub text_extract (*) {
278     my($h) = @_;
279     my %text = ();
280     for (;;) {
281         my $s = next_token $h;
282     last unless defined $s;
283         my($kind, $t, $attr) = @$s; # FIXME
284         if ($kind eq KIND_TEXT) {
285             $t = trim $t;
286             $text{$t} = 1 if $t =~ /\S/s;
287         } elsif ($kind eq KIND_TAG && %$attr) {
288             # value [tag=input], meta
289             my $tag = lc($1) if $t =~ /^<(\S+)/s;
290             for my $a ('alt', 'content', 'title', 'value') {
291                 if ($attr->{$a}) {
292                     next if $a eq 'content' && $tag ne 'meta';
293                     next if $a eq 'value' && ($tag ne 'input'
294                         || (ref $attr->{'type'} && $attr->{'type'}->[1] eq 'hidden')); # FIXME
295                     my($key, $val, $val_orig, $order) = @{$attr->{$a}}; #FIXME
296                     $val = trim $val;
297                     $text{$val} = 1 if $val =~ /\S/s;
298                 }
299             }
300         }
301     }
302     # Emit all extracted strings.
303     # Don't emit pure whitespace, pure numbers, or TMPL_VAR's.
304     for my $t (keys %text) {
305         printf "%s\n", $t
306             unless $t =~ /^(?:\s|\&nbsp$re_end_entity|$re_tmpl_var)*$/os || $t =~ /^\d+$/;
307     }
308 }
309
310 ###############################################################################
311
312 sub usage ($) {
313     my($exitcode) = @_;
314     my $h = $exitcode? *STDERR: *STDOUT;
315     print $h <<EOF;
316 Usage: $0 [OPTIONS]
317 Extract strings from HTML file.
318
319       --debug-dump-only     Do not extract strings; but display scanned tokens
320   -f, --file=FILE           Extract from the specified FILE
321       --pedantic-warnings   Issue warnings even for detected problems which
322                             are likely to be harmless
323       --help                Display this help and exit
324 EOF
325     exit($exitcode);
326 }
327
328 ###############################################################################
329
330 sub usage_error (;$) {
331     print STDERR "$_[0]\n" if @_;
332     print STDERR "Try `$0 --help' for more information.\n";
333     exit(-1);
334 }
335
336 ###############################################################################
337
338 GetOptions(
339     'f|file=s'          => \$input,
340     'debug-dump-only'   => \$debug_dump_only_p,
341     'pedantic-warnings' => sub { $pedantic_p = 1 },
342     'help'              => sub { usage(0) },
343 ) || usage_error;
344 $pedantic_tag = $pedantic_p? '': ' (negligible)';
345 usage_error('Missing mandatory option -f') unless defined $input;
346
347 open(INPUT, "<$input") || die "$0: $input: $!\n";
348 if ($debug_dump_only_p) {
349     debug_dump(*INPUT);
350 } else {
351     text_extract(*INPUT);
352 }
353
354 warn "Warning: This input will not work with Mozilla standards-compliant mode\n"
355         if $syntaxerror_p;
356
357 close INPUT;
358
359 exit(-1) if $fatal_p;