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