This is an experimental filter, based on simple scanning, that *should*
[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: Trailing spaces are not yet handled correctly
11
12 use Getopt::Long;
13 use strict;
14
15 use vars qw( $input );
16 use vars qw( $debug_dump_only_p );
17
18 ###############################################################################
19
20 # Hideous stuff from subst.pl
21 # Note: The $re_tag's set $1 (<tag), $2 (>), and $3 (rest of string)
22 use vars qw( $re_comment $re_entity_name $re_end_entity $re_etag );
23 use vars qw( $re_tag_strict $re_tag_compat @re_tag );
24 sub re_tag ($) {
25    my($compat) = @_;
26    my $etag = $compat? '>': '<>\/';
27    # See the file "subst.pl.test1" for how the following mess is derived
28    q{(<\/?(?:|(?:"[^"]*"|'[^']*'|--(?:[^-]|-[^-])*--|(?:[^-"'} . $etag . q{]|-[^-]))+))([} . $etag . q{])(.*)};
29 }
30 BEGIN {
31     $re_comment = '(?:--(?:[^-]|-[^-])*--)';
32     $re_entity_name = '(?:[^&%#;<>\s]+)'; # NOTE: not really correct SGML
33     $re_end_entity = '(?:;|$|(?=\s))'; # semicolon or before-whitespace
34     $re_etag = q{(?:<\/?(?:"[^"]*"|'[^']*'|[^"'>\/])*[>\/])}; # end-tag
35     @re_tag = ($re_tag_strict, $re_tag_compat) = (re_tag(0), re_tag(1));
36 }
37
38 # End of the hideous stuff
39
40 use vars qw( $re_directive );
41 BEGIN {
42     # $re_directive must not do any backreferences
43     $re_directive = q{<(?:!--\s*)?\/?TMPL_(?:VAR|LOOP|INCLUDE|IF|ELSE|UNLESS)\b(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))\s*(?:--)?>};
44 }
45
46 sub KIND_TEXT      () { 'TEXT' }
47 sub KIND_CDATA     () { 'CDATA' }
48 sub KIND_TAG       () { 'TAG' }
49 sub KIND_DECL      () { 'DECL' }
50 sub KIND_PI        () { 'PI' }
51 sub KIND_DIRECTIVE () { 'HTML::Template' }
52 sub KIND_COMMENT   () { 'COMMENT' }   # empty DECL with exactly one SGML comment
53 sub KIND_UNKNOWN   () { 'ERROR' }
54
55 use vars qw( $readahead $lc_0 $lc $syntaxerror_p );
56 use vars qw( $cdata_mode_p $cdata_close );
57
58 sub extract_attributes ($;$) {
59     my($s, $lc) = @_;
60     my %attr;
61     $s = $1 if $s =~ /^<\S+(.*)\S$/s; # should be always true
62     for (my $i = 0; $s =~ /^\s+(?:([a-zA-Z][-a-zA-Z0-9]*)=)?('((?:$re_directive|[^'])*)'|"((?:$re_directive|[^"])*)"|(($re_directive|[^\s<>])+))/os;) {
63         my($key, $val, $val_orig, $rest)
64                 = ($1, (defined $3? $3: defined $4? $4: $5), $2, $');
65         $i += 1;
66         $attr{+lc($key)} = [$key, $val, $val_orig, $i];
67         $s = $rest;
68     }
69     if ($s =~ /\S/s) { # should never happen
70         warn "Warning: Strange attribute syntax"
71                 . (defined $lc? " in line $lc": '') . ": $s\n";
72     } else {
73     }
74     return \%attr;
75 }
76
77 sub next_token_internal (*) {
78     my($h) = @_;
79     my($it, $kind);
80     my $eof_p = 0;
81     if (!defined $readahead || !length $readahead) {
82         my $next = scalar <$h>;
83         $eof_p = !defined $next;
84         if (!$eof_p) {
85             $lc += 1;
86             $readahead .= $next;
87         }
88     }
89     $lc_0 = $lc;                        # remember line number of first line
90     if ($eof_p && !length $readahead) { # nothing left to do
91         ;
92     } elsif ($readahead =~ /^\s+/s) {   # whitespace
93         ($kind, $it, $readahead) = (KIND_TEXT, $&, $');
94     } elsif ($readahead =~ /^[^<]+/s) { # non-whitespace normal text
95         ($kind, $it, $readahead) = (KIND_TEXT, $&, $');
96     } else {                            # tag/declaration/processing instruction
97         my $ok_p = 0;
98         for (;;) {
99             if ($cdata_mode_p) {
100                 if ($readahead =~ /^$cdata_close/) {
101                     ($kind, $it, $readahead) = (KIND_TAG, $&, $');
102                     $ok_p = 1;
103                 } else {
104                     ($kind, $it, $readahead) = (KIND_TEXT, $readahead, undef);
105                     $ok_p = 1;
106                 }
107             } elsif ($readahead =~ /^$re_tag_compat/os) {
108                 ($kind, $it, $readahead) = (KIND_TAG, "$1$2", $3);
109                 $ok_p = 1;
110             } elsif ($readahead =~ /^<!--(?:(?!-->).)*-->/s) {
111                 ($kind, $it, $readahead) = (KIND_COMMENT, $&, $');
112                 $ok_p = 1;
113                 warn "Warning: Syntax error in comment at line $lc_0: $&\n";
114                 $syntaxerror_p = 1;
115             }
116         last if $ok_p;
117             my $next = scalar <$h>;
118             $eof_p = !defined $next;
119         last if $eof_p;
120             $lc += 1;
121             $readahead .= $next;
122         }
123         if ($kind ne KIND_TAG) {
124             ;
125         } elsif ($it =~ /^<!/) {
126             $kind = KIND_DECL;
127             $kind = KIND_COMMENT if $it =~ /^<!--(?:(?!-->).)*-->/;
128         } elsif ($it =~ /^<\?/) {
129             $kind = KIND_PI;
130         }
131         if ($it =~ /^$re_directive/ios && !$cdata_mode_p) {
132             $kind = KIND_DIRECTIVE;
133         }
134         ($kind, $it) = (KIND_UNKNOWN, $readahead)
135                 if !$ok_p && $eof_p && !length $readahead;
136     }
137     return defined $it? (wantarray? ($kind, $it):
138                                     [$kind, $it]): undef;
139 }
140
141 sub next_token (*) {
142     my($h) = @_;
143     my $it;
144     if (!$cdata_mode_p) {
145         $it = next_token_internal($h);
146         if (defined $it && $it->[0] eq KIND_TAG) { # FIXME
147             ($cdata_mode_p, $cdata_close) = (1, "</$1\\s*>")
148                     if $it->[1] =~ /^<(script|style|textarea)\b/i; #FIXME
149             push @$it, extract_attributes($it->[1], $lc); #FIXME
150         }
151     } else {
152         for (;;) {
153             my $lc_prev = $lc;
154             my $next = next_token_internal($h);
155         last if !defined $next;
156             if (defined $next && $next->[1] =~ /$cdata_close/i) { #FIXME
157                 ($lc, $readahead) = ($lc_prev, $next->[1] . $readahead); #FIXME
158                 $cdata_mode_p = 0;
159             }
160         last unless $cdata_mode_p;
161             $it .= $next->[1]; #FIXME
162         }
163         $it = [KIND_CDATA, $it] if defined $it; #FIXME
164         $cdata_close = undef;
165     }
166     return defined $it? (wantarray? @$it: $it): undef;
167 }
168
169 ###############################################################################
170
171 sub debug_dump (*) { # for testing only
172     my($h) = @_;
173     print "re_tag_compat is /$re_tag_compat/\n";
174     for (;;) {
175         my $s = next_token $h;
176     last unless defined $s;
177         printf "%s\n", ('-' x 79);
178         my($kind, $t, $attr) = @$s; # FIXME
179         printf "%s:\n", $kind;
180         printf "%4dH%s\n", length($t),
181                 join('', map {/[\0-\37]/? $_: "$_\b$_"} split(//, $t));
182         if ($kind eq KIND_TAG && %$attr) {
183             printf "Attributes:\n";
184             for my $a (keys %$attr) {
185                 my($key, $val, $val_orig, $order) = @{$attr->{$a}};
186                 printf "%s = %dH%s -- %s\n", $a, length $val,
187                 join('', map {/[\0-\37]/? $_: "$_\b$_"} split(//, $val)),
188                 $val_orig;
189             }
190         }
191     }
192 }
193
194 ###############################################################################
195
196 sub text_extract (*) {
197     my($h) = @_;
198     my %text = ();
199     for (;;) {
200         my $s = next_token $h;
201     last unless defined $s;
202         my($kind, $t, $attr) = @$s; # FIXME
203         if ($kind eq KIND_TEXT) {
204             $text{$t} = 1 if $t =~ /\S/s; # FIXME... trailing whitespace
205         } elsif ($kind eq KIND_TAG && %$attr) {
206             # value [tag=input], meta
207             my $tag = lc($1) if $t =~ /^<(\S+)/s;
208             for my $a ('alt', 'content', 'title', 'value') {
209                 if ($attr->{$a}) {
210                     next if $a eq 'content' && $tag ne 'meta';
211                     next if $a eq 'value' && $tag ne 'input';
212                     my($key, $val, $val_orig, $order) = @{$attr->{$a}};
213                     $text{$val} = 1 if $val =~ /\S/s;
214                 }
215             }
216         }
217     }
218     for my $t (keys %text) {
219         printf "%s\n", $t unless $t =~ /^(?:\s|\&nbsp;)*$/;
220     }
221 }
222
223 ###############################################################################
224
225 GetOptions(
226     'f|file=s' => \$input,
227     'debug-dump-only-p' => \$debug_dump_only_p,
228 ) || exit(-1);
229
230 open(INPUT, "<$input") || die "$0: $input: $!\n";
231 if ($debug_dump_only_p) {
232     debug_dump(*INPUT);
233 } else {
234     text_extract(*INPUT);
235 }
236
237 warn "Warning: This input will not work with Mozilla standards-compliant mode\n"
238         if $syntaxerror_p;
239
240 close INPUT;
241