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