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