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