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