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