Merge branch 'new/bug_4330' into kcmaster
[koha.git] / misc / translator / tmpl_process3.pl
1 #!/usr/bin/perl
2 # This file is part of Koha
3 # Parts copyright 2003-2004 Paul Poulain
4 # Parts copyright 2003-2004 Jerome Vizcaino
5 # Parts copyright 2004 Ambrose Li
6
7 =head1 NAME
8
9 tmpl_process3.pl - Alternative version of tmpl_process.pl
10 using gettext-compatible translation files
11
12 =cut
13
14 use strict;
15 #use warnings; FIXME - Bug 2505
16 use Getopt::Long;
17 use Locale::PO;
18 use File::Temp qw( :POSIX );
19 use TmplTokenizer;
20 use VerboseWarnings qw( :warn :die );
21
22 ###############################################################################
23
24 use vars qw( @in_files $in_dir $str_file $out_dir $quiet );
25 use vars qw( @excludes $exclude_regex );
26 use vars qw( $recursive_p );
27 use vars qw( $pedantic_p );
28 use vars qw( $href );
29 use vars qw( $type );   # file extension (DOS form without the dot) to match
30 use vars qw( $charset_in $charset_out );
31
32 ###############################################################################
33
34 sub find_translation ($) {
35     my($s) = @_;
36     my $key = $s;
37     if ($s =~ /\S/s) {
38     $key = TmplTokenizer::string_canon($key);
39     $key = TmplTokenizer::charset_convert($key, $charset_in, $charset_out);
40     $key = TmplTokenizer::quote_po($key);
41     }
42     return defined $href->{$key}
43         && !$href->{$key}->fuzzy
44         && length Locale::PO->dequote($href->{$key}->msgstr)?
45        Locale::PO->dequote($href->{$key}->msgstr): $s;
46 }
47
48 sub text_replace_tag ($$) {
49     my($t, $attr) = @_;
50     my $it;
51
52     # value [tag=input], meta
53     my $tag = lc($1) if $t =~ /^<(\S+)/s;
54     my $translated_p = 0;
55     for my $a ('alt', 'content', 'title', 'value','label') {
56     if ($attr->{$a}) {
57         next if $a eq 'label' && $tag ne 'optgroup';
58         next if $a eq 'content' && $tag ne 'meta';
59         next if $a eq 'value' && ($tag ne 'input' || (ref $attr->{'type'} && $attr->{'type'}->[1] =~ /^(?:checkbox|hidden|radio|text)$/)); # FIXME
60
61         my($key, $val, $val_orig, $order) = @{$attr->{$a}}; #FIXME
62         if ($val =~ /\S/s) {
63         my $s = find_translation($val);
64         if ($attr->{$a}->[1] ne $s) { #FIXME
65             $attr->{$a}->[1] = $s; # FIXME
66             $attr->{$a}->[2] = ($s =~ /"/s)? "'$s'": "\"$s\""; #FIXME
67             $translated_p = 1;
68         }
69         }
70     }
71     }
72     if ($translated_p) {
73      $it = "<$tag"
74           . join('', map { if ($_ ne '/'){
75                              sprintf(' %s="%s"', $_, $attr->{$_}->[1]);
76           }
77               else {
78                   sprintf(' %s',$_);
79                   }
80                          
81               } sort {
82                   $attr->{$a}->[3] <=> $attr->{$b}->[3] #FIXME
83               } keys %$attr);
84         $it .= '>';
85     }
86     else {
87         $it = $t;
88     }
89     return $it;
90 }
91
92 sub text_replace (**) {
93     my($h, $output) = @_;
94     for (;;) {
95     my $s = TmplTokenizer::next_token $h;
96     last unless defined $s;
97     my($kind, $t, $attr) = ($s->type, $s->string, $s->attributes);
98     if ($kind eq C4::TmplTokenType::TEXT) {
99         print $output find_translation($t);
100     } elsif ($kind eq C4::TmplTokenType::TEXT_PARAMETRIZED) {
101         my $fmt = find_translation($s->form);
102         print $output TmplTokenizer::parametrize($fmt, 1, $s, sub {
103         $_ = $_[0];
104         my($kind, $t, $attr) = ($_->type, $_->string, $_->attributes);
105         $kind == C4::TmplTokenType::TAG && %$attr?
106             text_replace_tag($t, $attr): $t });
107     } elsif ($kind eq C4::TmplTokenType::TAG && %$attr) {
108         print $output text_replace_tag($t, $attr);
109     } elsif ($s->has_js_data) {
110         for my $t (@{$s->js_data}) {
111         # FIXME for this whole block
112         if ($t->[0]) {
113             printf $output "%s%s%s", $t->[2], find_translation $t->[3],
114                 $t->[2];
115         } else {
116             print $output $t->[1];
117         }
118         }
119     } elsif (defined $t) {
120         # Quick fix to bug 4472
121         $t = "<!DOCTYPE stylesheet ["  if $t =~ /DOCTYPE stylesheet/ ;
122         print $output $t;
123     }
124     }
125 }
126
127 sub listfiles ($$$) {
128     my($dir, $type, $action) = @_;
129     my @it = ();
130     if (opendir(DIR, $dir)) {
131     my @dirent = readdir DIR;   # because DIR is shared when recursing
132     closedir DIR;
133     for my $dirent (@dirent) {
134         my $path = "$dir/$dirent";
135         if ($dirent =~ /^\./ || $dirent eq 'CVS' || $dirent eq 'RCS'
136         || (defined $exclude_regex && $dirent =~ /^(?:$exclude_regex)$/)) {
137         ;
138         } elsif (-f $path) {
139         push @it, $path if (!defined $type || $dirent =~ /\.(?:$type)$/) || $action eq 'install';
140         } elsif (-d $path && $recursive_p) {
141         push @it, listfiles($path, $type, $action);
142         }
143     }
144     } else {
145     warn_normal "$dir: $!", undef;
146     }
147     return @it;
148 }
149
150 ###############################################################################
151
152 sub mkdir_recursive ($) {
153     my($dir) = @_;
154     local($`, $&, $', $1);
155     $dir = $` if $dir ne /^\/+$/ && $dir =~ /\/+$/;
156     my ($prefix, $basename) = ($dir =~ /\/([^\/]+)$/s)? ($`, $1): ('.', $dir);
157     mkdir_recursive($prefix) if $prefix ne '.' && !-d $prefix;
158     if (!-d $dir) {
159     print STDERR "Making directory $dir..." unless $quiet;
160     # creates with rwxrwxr-x permissions
161     mkdir($dir, 0775) || warn_normal "$dir: $!", undef;
162     }
163 }
164
165 ###############################################################################
166
167 sub usage ($) {
168     my($exitcode) = @_;
169     my $h = $exitcode? *STDERR: *STDOUT;
170     print $h <<EOF;
171 Usage: $0 create [OPTION]
172   or:  $0 update [OPTION]
173   or:  $0 install [OPTION]
174   or:  $0 --help
175 Create or update PO files from templates, or install translated templates.
176
177   -i, --input=SOURCE          Get or update strings from SOURCE file.
178                               SOURCE is a directory if -r is also specified.
179   -o, --outputdir=DIRECTORY   Install translation(s) to specified DIRECTORY
180       --pedantic-warnings     Issue warnings even for detected problems
181                               which are likely to be harmless
182   -r, --recursive             SOURCE in the -i option is a directory
183   -s, --str-file=FILE         Specify FILE as the translation (po) file
184                               for input (install) or output (create, update)
185   -x, --exclude=REGEXP        Exclude files matching the given REGEXP
186       --help                  Display this help and exit
187   -q, --quiet                 no output to screen (except for errors)
188
189 The -o option is ignored for the "create" and "update" actions.
190 Try `perldoc $0 for perhaps more information.
191 EOF
192     exit($exitcode);
193 }#`
194
195 ###############################################################################
196
197 sub usage_error (;$) {
198     for my $msg (split(/\n/, $_[0])) {
199     print STDERR "$msg\n";
200     }
201     print STDERR "Try `$0 --help for more information.\n";
202     exit(-1);
203 }
204
205 ###############################################################################
206
207 GetOptions(
208     'input|i=s'             => \@in_files,
209     'outputdir|o=s'         => \$out_dir,
210     'recursive|r'           => \$recursive_p,
211     'str-file|s=s'          => \$str_file,
212     'exclude|x=s'           => \@excludes,
213     'quiet|q'               => \$quiet,
214     'pedantic-warnings|pedantic'    => sub { $pedantic_p = 1 },
215     'help'              => \&usage,
216 ) || usage_error;
217
218 VerboseWarnings::set_application_name $0;
219 VerboseWarnings::set_pedantic_mode $pedantic_p;
220
221 # keep the buggy Locale::PO quiet if it says stupid things
222 $SIG{__WARN__} = sub {
223     my($s) = @_;
224     print STDERR $s unless $s =~ /^Strange line in [^:]+: #~/s
225     };
226
227 my $action = shift or usage_error('You must specify an ACTION.');
228 usage_error('You must at least specify input and string list filenames.')
229     if !@in_files || !defined $str_file;
230
231 # Type match defaults to *.tt plus *.inc if not specified
232 $type = "tt|inc|xsl" if !defined($type);
233
234 # Check the inputs for being files or directories
235 for my $input (@in_files) {
236     usage_error("$input: Input must be a file or directory.\n"
237         . "(Symbolic links are not supported at the moment)")
238     unless -d $input || -f $input;;
239 }
240
241 # Generates the global exclude regular expression
242 $exclude_regex =  '(?:'.join('|', @excludes).')' if @excludes;
243
244 # Generate the list of input files if a directory is specified
245 if (-d $in_files[0]) {
246     die "If you specify a directory as input, you must specify only it.\n"
247         if @in_files > 1;
248
249     # input is a directory, generates list of files to process
250     $in_dir = $in_files[0];
251     $in_dir =~ s/\/$//; # strips the trailing / if any
252     @in_files = listfiles($in_dir, $type, $action);
253 } else {
254     for my $input (@in_files) {
255     die "You cannot specify input files and directories at the same time.\n"
256         unless -f $input;
257     }
258 }
259
260 # restores the string list from file
261 $href = Locale::PO->load_file_ashash($str_file);
262
263 # guess the charsets. HTML::Templates defaults to iso-8859-1
264 if (defined $href) {
265     die "$str_file: PO file is corrupted, or not a PO file\n" unless defined $href->{'""'};
266     $charset_out = TmplTokenizer::charset_canon $2 if $href->{'""'}->msgstr =~ /\bcharset=(["']?)([^;\s"'\\]+)\1/;
267     $charset_in = $charset_out;
268     warn "Charset in/out: ".$charset_out;
269 #     for my $msgid (keys %$href) {
270 #   if ($msgid =~ /\bcharset=(["']?)([^;\s"'\\]+)\1/) {
271 #       my $candidate = TmplTokenizer::charset_canon $2;
272 #       die "Conflicting charsets in msgid: $charset_in vs $candidate => $msgid\n"
273 #           if defined $charset_in && $charset_in ne $candidate;
274 #       $charset_in = $candidate;
275 #   }
276 #     }
277
278     # BUG6464: check consistency of PO messages
279     #  - count number of '%s' in msgid and msgstr
280     for my $msg ( values %$href ) {
281         my $id_count  = split(/%s/, $msg->{msgid}) - 1;
282         my $str_count = split(/%s/, $msg->{msgstr}) - 1;
283         next if $id_count == $str_count ||
284                 $msg->{msgstr} eq '""' ||
285                 grep { /fuzzy/ } @{$msg->{_flags}};
286         warn_normal
287             "unconsistent %s count: ($id_count/$str_count):\n" .
288             "  line:   " . $msg->{loaded_line_number} . "\n" .
289             "  msgid:  " . $msg->{msgid} . "\n" .
290             "  msgstr: " . $msg->{msgstr} . "\n", undef;
291     }
292 }
293
294 # set our charset in to UTF-8
295 if (!defined $charset_in) {
296     $charset_in = TmplTokenizer::charset_canon 'UTF-8';
297     warn "Warning: Can't determine original templates' charset, defaulting to $charset_in\n";
298 }
299 # set our charset out to UTF-8
300 if (!defined $charset_out) {
301     $charset_out = TmplTokenizer::charset_canon 'UTF-8';
302     warn "Warning: Charset Out defaulting to $charset_out\n";
303 }
304 my $xgettext = './xgettext.pl'; # actual text extractor script
305 my $st;
306
307 if ($action eq 'create')  {
308     # updates the list. As the list is empty, every entry will be added
309     if (!-s $str_file) {
310     warn "Removing empty file $str_file\n";
311     unlink $str_file || die "$str_file: $!\n";
312     }
313     die "$str_file: Output file already exists\n" if -f $str_file;
314     my($tmph1, $tmpfile1) = tmpnam();
315     my($tmph2, $tmpfile2) = tmpnam();
316     close $tmph2; # We just want a name
317     # Generate the temporary file that acts as <MODULE>/POTFILES.in
318     for my $input (@in_files) {
319     print $tmph1 "$input\n";
320     }
321     close $tmph1;
322     warn "I $charset_in O $charset_out";
323     # Generate the specified po file ($str_file)
324     $st = system ($xgettext, '-s', '-f', $tmpfile1, '-o', $tmpfile2,
325             (defined $charset_in? ('-I', $charset_in): ()),
326             (defined $charset_out? ('-O', $charset_out): ())
327     );
328     # Run msgmerge so that the pot file looks like a real pot file
329     # We need to help msgmerge a bit by pre-creating a dummy po file that has
330     # the headers and the "" msgid & msgstr. It will fill in the rest.
331     if ($st == 0) {
332     # Merge the temporary "pot file" with the specified po file ($str_file)
333     # FIXME: msgmerge(1) is a Unix dependency
334     # FIXME: need to check the return value
335     unless (-f $str_file) {
336         local(*INPUT, *OUTPUT);
337         open(INPUT, "<$tmpfile2");
338         open(OUTPUT, ">$str_file");
339         while (<INPUT>) {
340         print OUTPUT;
341         last if /^\n/s;
342         }
343         close INPUT;
344         close OUTPUT;
345     }
346     $st = system('msgmerge', '-U', '-s', $str_file, $tmpfile2);
347     } else {
348     error_normal "Text extraction failed: $xgettext: $!\n", undef;
349     error_additional "Will not run msgmerge\n", undef;
350     }
351 #   unlink $tmpfile1 || warn_normal "$tmpfile1: unlink failed: $!\n", undef;
352 #   unlink $tmpfile2 || warn_normal "$tmpfile2: unlink failed: $!\n", undef;
353
354 } elsif ($action eq 'update') {
355     my($tmph1, $tmpfile1) = tmpnam();
356     my($tmph2, $tmpfile2) = tmpnam();
357     close $tmph2; # We just want a name
358     # Generate the temporary file that acts as <MODULE>/POTFILES.in
359     for my $input (@in_files) {
360     print $tmph1 "$input\n";
361     }
362     close $tmph1;
363     # Generate the temporary file that acts as <MODULE>/<LANG>.pot
364     $st = system($xgettext, '-s', '-f', $tmpfile1, '-o', $tmpfile2,
365         '--po-mode',
366         (defined $charset_in? ('-I', $charset_in): ()),
367         (defined $charset_out? ('-O', $charset_out): ()));
368     if ($st == 0) {
369     # Merge the temporary "pot file" with the specified po file ($str_file)
370     # FIXME: msgmerge(1) is a Unix dependency
371     # FIXME: need to check the return value
372     $st = system('msgmerge', '-U', '-s', $str_file, $tmpfile2);
373     } else {
374     error_normal "Text extraction failed: $xgettext: $!\n", undef;
375     error_additional "Will not run msgmerge\n", undef;
376     }
377 #   unlink $tmpfile1 || warn_normal "$tmpfile1: unlink failed: $!\n", undef;
378 #   unlink $tmpfile2 || warn_normal "$tmpfile2: unlink failed: $!\n", undef;
379
380 } elsif ($action eq 'install') {
381     if(!defined($out_dir)) {
382     usage_error("You must specify an output directory when using the install method.");
383     }
384     
385     if ($in_dir eq $out_dir) {
386     warn "You must specify a different input and output directory.\n";
387     exit -1;
388     }
389
390     # Make sure the output directory exists
391     # (It will auto-create it, but for compatibility we should not)
392     -d $out_dir || die "$out_dir: The directory does not exist\n";
393
394     # Try to open the file, because Locale::PO doesn't check :-/
395     open(INPUT, "<$str_file") || die "$str_file: $!\n";
396     close INPUT;
397
398     # creates the new tmpl file using the new translation
399     for my $input (@in_files) {
400         die "Assertion failed"
401             unless substr($input, 0, length($in_dir) + 1) eq "$in_dir/";
402 #       print "$input / $type\n";
403         if (!defined $type || $input =~ /\.(?:$type)$/) {
404             my $h = TmplTokenizer->new( $input );
405             $h->set_allow_cformat( 1 );
406             VerboseWarnings::set_input_file_name $input;
407         
408             my $target = $out_dir . substr($input, length($in_dir));
409             my $targetdir = $` if $target =~ /[^\/]+$/s;
410             mkdir_recursive($targetdir) unless -d $targetdir;
411             print STDERR "Creating $target...\n" unless $quiet;
412             open( OUTPUT, ">$target" ) || die "$target: $!\n";            
413             text_replace( $h, *OUTPUT );
414             close OUTPUT;
415         } else {
416         # just copying the file
417             my $target = $out_dir . substr($input, length($in_dir));
418             my $targetdir = $` if $target =~ /[^\/]+$/s;
419             mkdir_recursive($targetdir) unless -d $targetdir;
420             system("cp -f $input $target");
421             print STDERR "Copying $input...\n" unless $quiet;
422         }
423     }
424
425 } else {
426     usage_error('Unknown action specified.');
427 }
428
429 if ($st == 0) {
430     printf "The %s seems to be successful.\n", $action unless $quiet;
431 } else {
432     printf "%s FAILED.\n", "\u$action" unless $quiet;
433 }
434 exit 0;
435
436 ###############################################################################
437
438 =head1 SYNOPSIS
439
440 ./tmpl_process3.pl [ I<tmpl_process.pl options> ]
441
442 =head1 DESCRIPTION
443
444 This is an alternative version of the tmpl_process.pl script,
445 using standard gettext-style PO files.  While there still might
446 be changes made to the way it extracts strings, at this moment
447 it should be stable enough for general use; it is already being
448 used for the Chinese and Polish translations.
449
450 Currently, the create, update, and install actions have all been
451 reimplemented and seem to work.
452
453 =head2 Features
454
455 =over
456
457 =item -
458
459 Translation files in standard Uniforum PO format.
460 All standard tools including all gettext tools,
461 plus PO file editors like kbabel(1) etc.
462 can be used.
463
464 =item -
465
466 Minor changes in whitespace in source templates
467 do not generally require strings to be re-translated.
468
469 =item -
470
471 Able to handle <TMPL_VAR> variables in the templates;
472 <TMPL_VAR> variables are usually extracted in proper context,
473 represented by a short %s placeholder.
474
475 =item -
476
477 Able to handle text input and radio button INPUT elements
478 in the templates; these INPUT elements are also usually
479 extracted in proper context,
480 represented by a short %S or %p placeholder.
481
482 =item -
483
484 Automatic comments in the generated PO files to provide
485 even more context (line numbers, and the names and types
486 of the variables).
487
488 =item -
489
490 The %I<n>$s (or %I<n>$p, etc.) notation can be used
491 for change the ordering of the variables,
492 if such a reordering is required for correct translation.
493
494 =item -
495
496 If a particular <TMPL_VAR> should not appear in the
497 translation, it can be suppressed with the %0.0s notation.
498
499 =item -
500
501 Using the PO format also means translators can add their
502 own comments in the translation files, if necessary.
503
504 =item -
505
506 Create, update, and install actions are all based on the
507 same scanner module. This ensures that update and install
508 have the same idea of what is a translatable string;
509 attribute names in tags, for example, will not be
510 accidentally translated.
511
512 =back
513
514 =head1 NOTES
515
516 Anchors are represented by an <AI<n>> notation.
517 The meaning of this non-standard notation might not be obvious.
518
519 The create action calls xgettext.pl to do the actual work;
520 the update action calls xgettext.pl and msgmerge(1) to do the
521 actual work.
522
523 =head1 BUGS
524
525 xgettext.pl must be present in the current directory; the
526 msgmerge(1) command must also be present in the search path.
527 The script currently does not check carefully whether these
528 dependent commands are present.
529
530 Locale::PO(3) has a lot of bugs. It can neither parse nor
531 generate GNU PO files properly; a couple of workarounds have
532 been written in TmplTokenizer and more is likely to be needed
533 (e.g., to get rid of the "Strange line" warning for #~).
534
535 This script may not work in Windows.
536
537 There are probably some other bugs too, since this has not been
538 tested very much.
539
540 =head1 SEE ALSO
541
542 xgettext.pl,
543 TmplTokenizer.pm,
544 msgmerge(1),
545 Locale::PO(3),
546 translator_doc.txt
547
548 http://www.saas.nsw.edu.au/koha_wiki/index.php?page=DifficultTerms
549
550 =cut