Paul's problem #1 is now fixed: Bug in regular expression $re_directive.
[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
27 ###############################################################################
28
29 # Hideous stuff
30 use vars qw( $re_directive );
31 BEGIN {
32     # $re_directive must not do any backreferences
33     $re_directive = q{<(?:(?i)(?:!--\s*)?\/?TMPL_(?:VAR|LOOP|INCLUDE|IF|ELSE|UNLESS)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
34 }
35
36 # Hideous stuff from subst.pl, slightly modified to use the above hideous stuff
37 # Note: The $re_tag's set $1 (<tag), $2 (>), and $3 (rest of string)
38 use vars qw( $re_comment $re_entity_name $re_end_entity $re_etag );
39 use vars qw( $re_tag_strict $re_tag_compat @re_tag );
40 sub re_tag ($) {
41    my($compat) = @_;
42    my $etag = $compat? '>': '<>\/';
43    # See the file "subst.pl.test1" for how the following mess is derived
44    # Unfortunately, inserting $re_directive's has made this even messier
45    # FIXME: The following is somehow wrong. Paul's 1st report shouldn't happen.
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 $val =~ /[^-\.A-Za-z0-9]/s && $val_orig !~ /^['"]/;
85     }
86     if ($s =~ /\S/s) { # should never happen
87         warn "Warning: Strange attribute syntax"
88                 . (defined $lc? " in line $lc": '') . ": $s\n";
89     }
90     return \%attr;
91 }
92
93 sub next_token_internal (*) {
94     my($h) = @_;
95     my($it, $kind);
96     my $eof_p = 0;
97     if (!defined $readahead || !length $readahead) {
98         my $next = scalar <$h>;
99         $eof_p = !defined $next;
100         if (!$eof_p) {
101             $lc += 1;
102             $readahead .= $next;
103         }
104     }
105     $lc_0 = $lc;                        # remember line number of first line
106     if ($eof_p && !length $readahead) { # nothing left to do
107         ;
108     } elsif ($readahead =~ /^\s+/s) {   # whitespace
109         ($kind, $it, $readahead) = (KIND_TEXT, $&, $');
110     # FIXME the following (the [<\s] part) is an unreliable HACK :-(
111     } elsif ($readahead =~ /^(?:[^<]|<[<\s])+/s) {      # non-space normal text
112         ($kind, $it, $readahead) = (KIND_TEXT, $&, $');
113         warn "Warning: Unescaped < in line $lc: $it\n" if $it =~ /</s;
114     } else {                            # tag/declaration/processing instruction
115         my $ok_p = 0;
116         for (;;) {
117             if ($cdata_mode_p) {
118                 if ($readahead =~ /^$cdata_close/) {
119                     ($kind, $it, $readahead) = (KIND_TAG, $&, $');
120                     $ok_p = 1;
121                 } else {
122                     ($kind, $it, $readahead) = (KIND_TEXT, $readahead, undef);
123                     $ok_p = 1;
124                 }
125             } elsif ($readahead =~ /^$re_tag_compat/os) {
126                 ($kind, $it, $readahead) = (KIND_TAG, "$1$2", $3);
127                 $ok_p = 1;
128             } elsif ($readahead =~ /^<!--(?:(?!-->).)*-->/s) {
129                 ($kind, $it, $readahead) = (KIND_COMMENT, $&, $');
130                 $ok_p = 1;
131                 warn "Warning: Syntax error in comment at line $lc_0: $&\n";
132                 $syntaxerror_p = 1;
133             }
134         last if $ok_p;
135             my $next = scalar <$h>;
136             $eof_p = !defined $next;
137         last if $eof_p;
138             $lc += 1;
139             $readahead .= $next;
140         }
141         if ($kind ne KIND_TAG) {
142             ;
143         } elsif ($it =~ /^<!/) {
144             $kind = KIND_DECL;
145             $kind = KIND_COMMENT if $it =~ /^<!--(?:(?!-->).)*-->/;
146         } elsif ($it =~ /^<\?/) {
147             $kind = KIND_PI;
148         }
149         if ($it =~ /^$re_directive/ios && !$cdata_mode_p) {
150             $kind = KIND_DIRECTIVE;
151         }
152         if (!$ok_p && $eof_p) {
153             ($kind, $it, $readahead) = (KIND_UNKNOWN, $readahead, undef);
154             $syntaxerror_p = 1;
155         }
156     }
157     warn "Warning: Unrecognizable token found in line $lc_0: $it\n"
158             if $kind eq KIND_UNKNOWN;
159     return defined $it? (wantarray? ($kind, $it):
160                                     [$kind, $it]): undef;
161 }
162
163 sub next_token (*) {
164     my($h) = @_;
165     my $it;
166     if (!$cdata_mode_p) {
167         $it = next_token_internal($h);
168         if (defined $it && $it->[0] eq KIND_TAG) { # FIXME
169             ($cdata_mode_p, $cdata_close) = (1, "</$1\\s*>")
170                     if $it->[1] =~ /^<(script|style|textarea)\b/i; #FIXME
171             push @$it, extract_attributes($it->[1], $lc); #FIXME
172         }
173     } else {
174         for (;;) {
175             my $lc_prev = $lc;
176             my $next = next_token_internal($h);
177         last if !defined $next;
178             if (defined $next && $next->[1] =~ /$cdata_close/i) { #FIXME
179                 ($lc, $readahead) = ($lc_prev, $next->[1] . $readahead); #FIXME
180                 $cdata_mode_p = 0;
181             }
182         last unless $cdata_mode_p;
183             $it .= $next->[1]; #FIXME
184         }
185         $it = [KIND_CDATA, $it] if defined $it; #FIXME
186         $cdata_close = undef;
187     }
188     return defined $it? (wantarray? @$it: $it): undef;
189 }
190
191 ###############################################################################
192
193 sub debug_dump (*) { # for testing only
194     my($h) = @_;
195     print "re_tag_compat is /$re_tag_compat/\n";
196     for (;;) {
197         my $s = next_token $h;
198     last unless defined $s;
199         printf "%s\n", ('-' x 79);
200         my($kind, $t, $attr) = @$s; # FIXME
201         printf "%s:\n", $kind;
202         printf "%4dH%s\n", length($t),
203                 join('', map {/[\0-\37]/? $_: "$_\b$_"} split(//, $t));
204         if ($kind eq KIND_TAG && %$attr) {
205             printf "Attributes:\n";
206             for my $a (keys %$attr) {
207                 my($key, $val, $val_orig, $order) = @{$attr->{$a}};
208                 printf "%s = %dH%s -- %s\n", $a, length $val,
209                 join('', map {/[\0-\37]/? $_: "$_\b$_"} split(//, $val)),
210                 $val_orig;
211             }
212         }
213     }
214 }
215
216 ###############################################################################
217
218 sub text_extract (*) {
219     my($h) = @_;
220     my %text = ();
221     for (;;) {
222         my $s = next_token $h;
223     last unless defined $s;
224         my($kind, $t, $attr) = @$s; # FIXME
225         if ($kind eq KIND_TEXT) {
226             $t =~ s/\s+$//s;
227             $text{$t} = 1 if $t =~ /\S/s;
228         } elsif ($kind eq KIND_TAG && %$attr) {
229             # value [tag=input], meta
230             my $tag = lc($1) if $t =~ /^<(\S+)/s;
231             for my $a ('alt', 'content', 'title', 'value') {
232                 if ($attr->{$a}) {
233                     next if $a eq 'content' && $tag ne 'meta';
234                     next if $a eq 'value' && ($tag ne 'input'
235                         || (ref $attr->{'type'} && $attr->{'type'}->[1] eq 'hidden')); # FIXME
236                     my($key, $val, $val_orig, $order) = @{$attr->{$a}}; #FIXME
237                     $val =~ s/\s+$//s;
238                     $text{$val} = 1 if $val =~ /\S/s;
239                 }
240             }
241         }
242     }
243     # Emit all extracted strings. Don't emit pure whitespace or pure numbers.
244     for my $t (keys %text) {
245         printf "%s\n", $t unless $t =~ /^(?:\s|\&nbsp;)*$/s || $t =~ /^\d+$/;
246     }
247 }
248
249 ###############################################################################
250
251 GetOptions(
252     'f|file=s' => \$input,
253     'debug-dump-only-p' => \$debug_dump_only_p,
254 ) || exit(-1);
255
256 open(INPUT, "<$input") || die "$0: $input: $!\n";
257 if ($debug_dump_only_p) {
258     debug_dump(*INPUT);
259 } else {
260     text_extract(*INPUT);
261 }
262
263 warn "Warning: This input will not work with Mozilla standards-compliant mode\n"
264         if $syntaxerror_p;
265
266 close INPUT;
267