Don't mindlessly spew out 40 lines of text in a warning message if we get
[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]*)=)?('((?:$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 $pedantic_p
86                 && $val =~ /[^-\.A-Za-z0-9]/s && $val_orig !~ /^['"]/;
87     }
88     if ($s =~ /\S/s) { # should never happen
89         if ($s =~ /^([^\n]*)\n/s) { # this is even worse
90             warn "Error: Completely confused while extracting attributes"
91                     . (defined $lc? " near line $lc": '') . ": $1\n";
92             warn "Error: " . (scalar split(/\n/, $s) - 1) . " more line(s) not shown.\n";
93             $fatal_p = 1;
94         } else {
95             warn "Warning: Strange attribute syntax"
96                     . (defined $lc? " near line $lc": '') . ": $s\n";
97         }
98     }
99     return \%attr;
100 }
101
102 sub next_token_internal (*) {
103     my($h) = @_;
104     my($it, $kind);
105     my $eof_p = 0;
106     if (!defined $readahead || !length $readahead) {
107         my $next = scalar <$h>;
108         $eof_p = !defined $next;
109         if (!$eof_p) {
110             $lc += 1;
111             $readahead .= $next;
112         }
113     }
114     $lc_0 = $lc;                        # remember line number of first line
115     if ($eof_p && !length $readahead) { # nothing left to do
116         ;
117     } elsif ($readahead =~ /^\s+/s) {   # whitespace
118         ($kind, $it, $readahead) = (KIND_TEXT, $&, $');
119     # FIXME the following (the [<\s] part) is an unreliable HACK :-(
120     } elsif ($readahead =~ /^(?:[^<]|<[<\s])+/s) {      # non-space normal text
121         ($kind, $it, $readahead) = (KIND_TEXT, $&, $');
122         warn "Warning: Unescaped < near line $lc_0: $it\n" if $it =~ /</s;
123     } else {                            # tag/declaration/processing instruction
124         my $ok_p = 0;
125         for (;;) {
126             if ($cdata_mode_p) {
127                 if ($readahead =~ /^$cdata_close/) {
128                     ($kind, $it, $readahead) = (KIND_TAG, $&, $');
129                     $ok_p = 1;
130                 } else {
131                     ($kind, $it, $readahead) = (KIND_TEXT, $readahead, undef);
132                     $ok_p = 1;
133                 }
134             } elsif ($readahead =~ /^$re_tag_compat/os) {
135                 ($kind, $it, $readahead) = (KIND_TAG, "$1$2", $3);
136                 $ok_p = 1;
137             } elsif ($readahead =~ /^<!--(?:(?!-->).)*-->/s) {
138                 ($kind, $it, $readahead) = (KIND_COMMENT, $&, $');
139                 $ok_p = 1;
140                 warn "Warning: Syntax error in comment at line $lc_0: $&\n";
141                 $syntaxerror_p = 1;
142             }
143         last if $ok_p;
144             my $next = scalar <$h>;
145             $eof_p = !defined $next;
146         last if $eof_p;
147             $lc += 1;
148             $readahead .= $next;
149         }
150         if ($kind ne KIND_TAG) {
151             ;
152         } elsif ($it =~ /^<!/) {
153             $kind = KIND_DECL;
154             $kind = KIND_COMMENT if $it =~ /^<!--(?:(?!-->).)*-->/;
155         } elsif ($it =~ /^<\?/) {
156             $kind = KIND_PI;
157         }
158         if ($it =~ /^$re_directive/ios && !$cdata_mode_p) {
159             $kind = KIND_DIRECTIVE;
160         }
161         if (!$ok_p && $eof_p) {
162             ($kind, $it, $readahead) = (KIND_UNKNOWN, $readahead, undef);
163             $syntaxerror_p = 1;
164         }
165     }
166     warn "Warning: Unrecognizable token found near line $lc_0: $it\n"
167             if $kind eq KIND_UNKNOWN;
168     return defined $it? (wantarray? ($kind, $it):
169                                     [$kind, $it]): undef;
170 }
171
172 sub next_token (*) {
173     my($h) = @_;
174     my $it;
175     if (!$cdata_mode_p) {
176         $it = next_token_internal($h);
177         if (defined $it && $it->[0] eq KIND_TAG) { # FIXME
178             ($cdata_mode_p, $cdata_close) = (1, "</$1\\s*>")
179                     if $it->[1] =~ /^<(script|style|textarea)\b/i; #FIXME
180             push @$it, extract_attributes($it->[1], $lc_0); #FIXME
181         }
182     } else {
183         for (;;) {
184             my $lc_prev = $lc;
185             my $next = next_token_internal($h);
186         last if !defined $next;
187             if (defined $next && $next->[1] =~ /$cdata_close/i) { #FIXME
188                 ($lc, $readahead) = ($lc_prev, $next->[1] . $readahead); #FIXME
189                 $cdata_mode_p = 0;
190             }
191         last unless $cdata_mode_p;
192             $it .= $next->[1]; #FIXME
193         }
194         $it = [KIND_CDATA, $it] if defined $it; #FIXME
195         $cdata_close = undef;
196     }
197     return defined $it? (wantarray? @$it: $it): undef;
198 }
199
200 ###############################################################################
201
202 sub debug_dump (*) { # for testing only
203     my($h) = @_;
204     print "re_tag_compat is /$re_tag_compat/\n";
205     for (;;) {
206         my $s = next_token $h;
207     last unless defined $s;
208         printf "%s\n", ('-' x 79);
209         my($kind, $t, $attr) = @$s; # FIXME
210         printf "%s:\n", $kind;
211         printf "%4dH%s\n", length($t),
212                 join('', map {/[\0-\37]/? $_: "$_\b$_"} split(//, $t));
213         if ($kind eq KIND_TAG && %$attr) {
214             printf "Attributes:\n";
215             for my $a (keys %$attr) {
216                 my($key, $val, $val_orig, $order) = @{$attr->{$a}};
217                 printf "%s = %dH%s -- %s\n", $a, length $val,
218                 join('', map {/[\0-\37]/? $_: "$_\b$_"} split(//, $val)),
219                 $val_orig;
220             }
221         }
222     }
223 }
224
225 ###############################################################################
226
227 sub text_extract (*) {
228     my($h) = @_;
229     my %text = ();
230     for (;;) {
231         my $s = next_token $h;
232     last unless defined $s;
233         my($kind, $t, $attr) = @$s; # FIXME
234         if ($kind eq KIND_TEXT) {
235             $t =~ s/\s+$//s;
236             $text{$t} = 1 if $t =~ /\S/s;
237         } elsif ($kind eq KIND_TAG && %$attr) {
238             # value [tag=input], meta
239             my $tag = lc($1) if $t =~ /^<(\S+)/s;
240             for my $a ('alt', 'content', 'title', 'value') {
241                 if ($attr->{$a}) {
242                     next if $a eq 'content' && $tag ne 'meta';
243                     next if $a eq 'value' && ($tag ne 'input'
244                         || (ref $attr->{'type'} && $attr->{'type'}->[1] eq 'hidden')); # FIXME
245                     my($key, $val, $val_orig, $order) = @{$attr->{$a}}; #FIXME
246                     $val =~ s/\s+$//s;
247                     $text{$val} = 1 if $val =~ /\S/s;
248                 }
249             }
250         }
251     }
252     # Emit all extracted strings. Don't emit pure whitespace or pure numbers.
253     for my $t (keys %text) {
254         printf "%s\n", $t unless $t =~ /^(?:\s|\&nbsp;)*$/s || $t =~ /^\d+$/;
255     }
256 }
257
258 ###############################################################################
259
260 sub usage ($) {
261     my($exitcode) = @_;
262     my $h = $exitcode? *STDERR: *STDOUT;
263     print $h <<EOF;
264 Usage: $0 [OPTIONS]
265 Extract strings from HTML file.
266
267       --debug-dump-only     Do not extract strings; but display scanned tokens
268   -f, --file=FILE           Extract from the specified FILE
269       --pedantic-warnings   Issue warnings even for detected problems which
270                             are likely to be harmless
271       --help                Display this help and exit
272 EOF
273     exit($exitcode);
274 }
275
276 ###############################################################################
277
278 sub usage_error (;$) {
279     print STDERR "$_[0]\n" if @_;
280     print STDERR "Try `$0 --help' for more information.\n";
281     exit(-1);
282 }
283
284 ###############################################################################
285
286 GetOptions(
287     'f|file=s'          => \$input,
288     'debug-dump-only'   => \$debug_dump_only_p,
289     'pedantic-warnings' => sub { $pedantic_p = 1 },
290     'help'              => sub { usage(0) },
291 ) || usage_error;
292 usage_error('Missing mandatory option -f') unless defined $input;
293
294 open(INPUT, "<$input") || die "$0: $input: $!\n";
295 if ($debug_dump_only_p) {
296     debug_dump(*INPUT);
297 } else {
298     text_extract(*INPUT);
299 }
300
301 warn "Warning: This input will not work with Mozilla standards-compliant mode\n"
302         if $syntaxerror_p;
303
304 close INPUT;
305
306 exit(-1) if $fatal_p;