3 # -n do not include custom_ scripts
 
   4 # -v verbose mode, shows progress stuff
 
   6 # this version of locles processes not only all required .pl files
 
   7 # but also all parse_html_templated files.
 
  13   unshift(@INC, 'modules/override'); # Use our own versions of various modules (e.g. YAML).
 
  14   push   (@INC, 'modules/fallback'); # Only use our own versions of modules if there's no system version.
 
  21 use File::Slurp qw(slurp);
 
  25 use List::MoreUtils qw(apply);
 
  26 use List::Util qw(first);
 
  29 $OUTPUT_AUTOFLUSH = 1;
 
  40 my $basedir      = "../..";
 
  41 my $locales_dir  = ".";
 
  42 my $bindir       = "$basedir/bin/mozilla";
 
  43 my @progdirs     = ( "$basedir/SL" );
 
  44 my @menufiles    = <${basedir}/menus/*.ini>;
 
  45 my @javascript_dirs = ($basedir .'/js', $basedir .'/templates/webpages');
 
  46 my $javascript_output_dir = $basedir .'/js';
 
  47 my $submitsearch = qr/type\s*=\s*[\"\']?submit/i;
 
  52 my %ignore_unused_templates = (
 
  53   map { $_ => 1 } qw(ct/testpage.html generic/autocomplete.html oe/periodic_invoices_email.txt part/testpage.html t/render.html t/render.js task_server/failure_notification_email.txt
 
  54                      failed_background_jobs_report/email.txt)
 
  57 my (%referenced_html_files, %locale, %htmllocale, %alllocales, %cached, %submit, %jslocale);
 
  58 my ($ALL_HEADER, $MISSING_HEADER, $LOST_HEADER);
 
  63   my ($top_dir_name) = @_;
 
  70     tie my %dir_h, 'IO::Dir', $dir_name;
 
  72     push @files,   grep { -f } map { "${dir_name}/${_}" }                       keys %dir_h;
 
  73     my @sub_dirs = grep { -d } map { "${dir_name}/${_}" } grep { ! m/^\.\.?$/ } keys %dir_h;
 
  75     $finder->($_) for @sub_dirs;
 
  78   $finder->($top_dir_name);
 
  84 # overwrite existing entries with the ones from 'missing'
 
  85   $self->{texts}->{$_} = $missing->{$_} for grep { $missing->{$_} } keys %alllocales;
 
  87   # try to set missing entries from lost ones
 
  88   my %lost_by_text = map { ($_->{text} => $_->{translation}) } @lost;
 
  89   $self->{texts}->{$_} = $lost_by_text{$_} for grep { !$self->{texts}{$_} } keys %alllocales;
 
  92 my @bindir_files = find_files($bindir);
 
  93 my @progfiles    = map { m:^(.+)/([^/]+)$:; [ $2, $1 ]  } grep { /\.pl$/ && !/_custom/ } @bindir_files;
 
  94 my @customfiles  = grep /_custom/, @bindir_files;
 
  96 push @progfiles, map { m:^(.+)/([^/]+)$:; [ $2, $1 ] } grep { /\.pm$/ } map { find_files($_) } @progdirs;
 
  98 # put customized files into @customfiles
 
 104   tie %dir_h, 'IO::Dir', $basedir;
 
 105   push @menufiles, map { "$basedir/$_" } grep { /.*_menu.ini$/ } keys %dir_h;
 
 109 foreach my $sub_dir ("Pg-upgrade2", "Pg-upgrade2-auth") {
 
 110   my $dir = "$basedir/sql/$sub_dir";
 
 111   tie %dir_h, 'IO::Dir', $dir;
 
 112   push @dbplfiles, map { [ $_, $dir ] } grep { /\.pl$/ } keys %dir_h;
 
 115 # slurp the translations in
 
 116 if (-f "$locales_dir/all") {
 
 117   require "$locales_dir/all";
 
 119 if (-f "$locales_dir/missing") {
 
 120   require "$locales_dir/missing" ;
 
 121   unlink "$locales_dir/missing";
 
 123 if (-f "$locales_dir/lost") {
 
 124   require "$locales_dir/lost";
 
 125   unlink "$locales_dir/lost";
 
 128 my %old_texts = %{ $self->{texts} || {} };
 
 130 handle_file(@{ $_ })       for @progfiles;
 
 131 handle_file(@{ $_ })       for @dbplfiles;
 
 132 scanmenu($_)               for @menufiles;
 
 134 for my $file_name (grep { /\.(?:js|html)$/i } map({find_files($_)} @javascript_dirs)) {
 
 135   scan_javascript_file($file_name);
 
 138 # merge entries to translate with entries from files 'missing' and 'lost'
 
 143   file      => "$locales_dir/all",
 
 144   header    => $ALL_HEADER,
 
 145   data_name => '$self->{texts}',
 
 146   data_sub  => sub { _print_line($_, $self->{texts}{$_}, @_) for sort keys %alllocales },
 
 149 open(my $js_file, '>:encoding(utf8)', $javascript_output_dir .'/locale/'. $locale .'.js') || die;
 
 150 print $js_file 'namespace("kivi").setupLocale({';
 
 152 for my $key (sort(keys(%jslocale))) {
 
 153   print $js_file ((!$first_entry ? ',' : '') ."\n". _double_quote($key) .':'. _double_quote($self->{texts}{$key}));
 
 156 print $js_file ("\n");
 
 157 print $js_file ('});'."\n");
 
 160   foreach my $text (keys %$missing) {
 
 161     if ($locale{$text} || $htmllocale{$text}) {
 
 162       unless ($self->{texts}{$text}) {
 
 163         $self->{texts}{$text} = $missing->{$text};
 
 169 # calc and generate missing
 
 170 my @new_missing = grep { !$self->{texts}{$_} } sort keys %alllocales;
 
 174     my %existing_lc = map { (lc $_ => $_) } grep { $self->{texts}->{$_} } keys %{ $self->{texts} };
 
 175     foreach my $entry (@new_missing) {
 
 176       my $other = $existing_lc{lc $entry};
 
 177       print "W: No entry for '${entry}' exists, but there is one with different case: '${other}'\n" if $other;
 
 182     for my $string (@new_missing) {
 
 183       print "new string '$string' in files:\n";
 
 186         apply { s{^(?:\.\./)+}{}          }
 
 187         grep  { $cached{$_}{all}{$string} }
 
 193     file      => "$locales_dir/missing",
 
 194     header    => $MISSING_HEADER,
 
 195     data_name => '$missing',
 
 196     data_sub  => sub { _print_line($_, '', @_) for @new_missing },
 
 200 # calc and generate lost
 
 201 while (my ($text, $translation) = each %old_texts) {
 
 202   next if ($alllocales{$text});
 
 203   push @lost, { 'text' => $text, 'translation' => $translation };
 
 207   splice @lost, 0, (scalar @lost - 50) if (scalar @lost > 50);
 
 209     file      => "$locales_dir/lost",
 
 210     header    => $LOST_HEADER,
 
 212     data_name => '@lost',
 
 214       _print_line($_->{text}, $_->{translation}, @_, template => "  { 'text' => %s, 'translation' => %s },\n") for @lost;
 
 219 my $trlanguage = slurp("$locales_dir/LANGUAGE");
 
 222 search_unused_htmlfiles() if $opt_c;
 
 224 my $count  = scalar keys %alllocales;
 
 225 my $notext = scalar @new_missing;
 
 226 my $per    = sprintf("%.1f", ($count - $notext) / $count * 100);
 
 227 print "\n$trlanguage - ${per}%";
 
 228 print " - $notext/$count missing" if $notext;
 
 237 # These are all the texts to build the translations files.
 
 238 # The file has the form of 'english text'  => 'foreign text',
 
 239 # you can add the translation in this file or in the 'missing' file
 
 240 # run locales.pl from this directory to rebuild the translation files
 
 242   $MISSING_HEADER = <<EOL;
 
 243 # add the missing texts and run locales.pl to rebuild
 
 245   $LOST_HEADER  = <<EOL;
 
 246 # The last 50 text strings, that have been removed.
 
 247 # This file has been auto-generated by locales.pl. Please don't edit!
 
 254   my ($opt_no_c, $ignore_for_compatiblity);
 
 257     'no-custom-files' => \$opt_n,
 
 258     'check-files'     => \$ignore_for_compatiblity,
 
 259     'no-check-files'  => \$opt_no_c,
 
 260     'verbose'         => \$opt_v,
 
 261     'filenames'       => \$opt_f,
 
 275     pod2usage(-exitstatus => 0, -verbose => 2);
 
 280     my $arg = shift @ARGV;
 
 282     foreach my $dir ("../locale/$arg", "locale/$arg", "../$arg", $arg) {
 
 283       next unless -d $dir && -f "$dir/all" && -f "$dir/LANGUAGE";
 
 292       print "The locale directory '$arg' could not be found.\n";
 
 296   } elsif (!-f 'all' || !-f 'LANGUAGE') {
 
 297     print "locales.pl was not called from a locale/* subdirectory,\n"
 
 298       .   "and no locale directory name was given.\n";
 
 302   $locale ||=  (grep { $_ } split m:/:, getcwd())[-1];
 
 307   my ($file, $dir) = @_;
 
 308   print "\n$file" if $opt_v;
 
 312   &scanfile("$dir/$file");
 
 314   # scan custom_{module}.pl or {login}_{module}.pl files
 
 315   foreach my $customfile (@customfiles) {
 
 316     if ($customfile =~ /_$file/) {
 
 317       if (-f "$dir/$customfile") {
 
 318         &scanfile("$dir/$customfile");
 
 326 sub extract_text_between_parenthesis {
 
 327   my ($fh, $line) = @_;
 
 328   my ($inside_string, $pos, $text, $quote_next) = (undef, 0, "", 0);
 
 331     if (length($line) <= $pos) {
 
 333       return ($text, "") unless ($line);
 
 337     my $cur_char = substr($line, $pos, 1);
 
 339     if (!$inside_string) {
 
 340       if ((length($line) >= ($pos + 3)) && (substr($line, $pos, 2)) eq "qq") {
 
 341         $inside_string = substr($line, $pos + 2, 1);
 
 344       } elsif ((length($line) >= ($pos + 2)) &&
 
 345                (substr($line, $pos, 1) eq "q")) {
 
 346         $inside_string = substr($line, $pos + 1, 1);
 
 349       } elsif (($cur_char eq '"') || ($cur_char eq '\'')) {
 
 350         $inside_string = $cur_char;
 
 352       } elsif (($cur_char eq ")") || ($cur_char eq ',')) {
 
 353         return ($text, substr($line, $pos + 1));
 
 358         $text .= '\\' unless $cur_char eq "'";
 
 362       } elsif ($cur_char eq '\\') {
 
 365       } elsif ($cur_char eq $inside_string) {
 
 366         undef($inside_string);
 
 379   my $dont_include_subs = shift;
 
 380   my $scanned_files = shift;
 
 385   $scanned_files = {} unless ($scanned_files);
 
 386   return if ($scanned_files->{$file});
 
 387   $scanned_files->{$file} = 1;
 
 389   if (!defined $cached{$file}) {
 
 391     return unless (-f "$file");
 
 393     my $fh = new FileHandle;
 
 394     open $fh, '<:encoding(utf8)', $file or die "$! : $file";
 
 396     my ($is_submit, $line_no, $sub_line_no) = (0, 0, 0);
 
 399       last if /^\s*__END__/;
 
 403       # is this another file
 
 404       if (/require\s+\W.*\.pl/) {
 
 406         $newfile =~ s/require\s+\W//;
 
 407         $newfile =~ s|bin/mozilla||;
 
 408          $cached{$file}{scan}{"$bindir/$newfile"} = 1;
 
 409       } elsif (/use\s+SL::([\w:]*)/) {
 
 412         $cached{$file}{scannosubs}{"../../SL/${module}.pm"} = 1;
 
 415       # Some calls to render() are split over multiple lines. Deal
 
 417       while (/(?:parse_html_template2?|render)\s*\( *$/) {
 
 422       # is this a template call?
 
 423       if (/(?:parse_html_template2?|render)\s*\(\s*[\"\']([\w\/]+)\s*[\"\']/) {
 
 424         my $new_file_base = "$basedir/templates/webpages/$1.";
 
 425         if (/parse_html_template2/) {
 
 426           print "E: " . strip_base($file) . " is still using 'parse_html_template2' for " . strip_base("${new_file_base}html") . ".\n";
 
 430         foreach my $ext (qw(html js json)) {
 
 431           my $new_file = "${new_file_base}${ext}";
 
 433             $cached{$file}{scanh}{$new_file} = 1;
 
 439         if ($opt_c && !$found_one) {
 
 440           print "W: missing HTML template: " . strip_base($new_file_base) . "{html,json,js} (referenced from " . strip_base($file) . ")\n";
 
 449             my ($null, $country) = split(/,/);
 
 450             $country =~ s/^ +[\"\']//;
 
 451             $country =~ s/[\"\'].*//;
 
 457         # is it a submit button before $locale->
 
 458         if (/$submitsearch/) {
 
 460           if ($` !~ /locale->text/) {
 
 462             $sub_line_no = $line_no;
 
 467         if (/ (?: locale->text | \b t8 ) \b .*? \(/x) {
 
 474           ($string, $_) = extract_text_between_parenthesis($fh, $postmatch);
 
 477           # if there is no $ in the string record it
 
 478           unless (($string =~ /\$\D.*/) || ("" eq $string)) {
 
 480             # this guarantees one instance of string
 
 481             $cached{$file}{locale}{$string} = 1;
 
 483             # this one is for all the locales
 
 484             $cached{$file}{all}{$string} = 1;
 
 486             # is it a submit button before $locale->
 
 488               $cached{$file}{submit}{$string} = 1;
 
 491         } elsif ($postmatch =~ />/) {
 
 495         # exit loop if there are no more locales on this line
 
 496         ($rc) = ($postmatch =~ /locale->text | \b t8/x);
 
 498         if (   ($postmatch =~ />/)
 
 499             || (!$found && ($sub_line_no != $line_no) && />/)) {
 
 509   $alllocales{$_} = 1             for keys %{$cached{$file}{all}};
 
 510   $locale{$_}     = 1             for keys %{$cached{$file}{locale}};
 
 511   $submit{$_}     = 1             for keys %{$cached{$file}{submit}};
 
 513   scanfile($_, 0, $scanned_files) for keys %{$cached{$file}{scan}};
 
 514   scanfile($_, 1, $scanned_files) for keys %{$cached{$file}{scannosubs}};
 
 515   scanhtmlfile($_)                for keys %{$cached{$file}{scanh}};
 
 517   $referenced_html_files{$_} = 1  for keys %{$cached{$file}{scanh}};
 
 523   my $fh = new FileHandle;
 
 524   open $fh, '<:encoding(utf8)', $file or die "$! : $file";
 
 526   my @a = grep m/^\[/, <$fh>;
 
 530   grep { s/(\[|\])//g } @a;
 
 532   foreach my $item (@a) {
 
 533     my @b = split /--/, $item;
 
 534     foreach my $string (@b) {
 
 536       $locale{$string}     = 1;
 
 537       $alllocales{$string} = 1;
 
 543 sub unescape_template_string {
 
 554   return if defined $cached{$file};
 
 556   my %plugins = ( 'loaded' => { }, 'needed' => { } );
 
 558   if (!open(IN, '<:encoding(utf8)', $file)) {
 
 559     print "E: template file '$file' not found\n";
 
 566   while (my $line = <IN>) {
 
 569     while ($line =~ m/\[\%[^\w]*use[^\w]+(\w+)[^\w]*?\%\]/gi) {
 
 570       $plugins{loaded}->{$1} = 1;
 
 573     while ($line =~ m/\[\%[^\w]*(\w+)\.\w+\(/g) {
 
 575       $plugins{needed}->{$plugin} = 1 if (first { $_ eq $plugin } qw(HTML LxERP JavaScript JSON L P));
 
 578     $plugins{needed}->{T8} = 1 if $line =~ m/\[\%.*\|.*\$T8/;
 
 580     while ($line =~ m/(?:             # Start von Variante 1: LxERP.t8('...'); ohne darumliegende [% ... %]-Tags
 
 581                         (LxERP\.t8)\( #   LxERP.t8(                             ::Parameter $1::
 
 582                         ([\'\"])      #   Anfang des zu übersetzenden Strings   ::Parameter $2::
 
 583                         (.*?)         #   Der zu übersetzende String            ::Parameter $3::
 
 584                         (?<!\\)\2     #   Ende des zu übersetzenden Strings
 
 585                       |               # Start von Variante 2: [% '...' | $T8 %]
 
 586                         \[\%          #   Template-Start-Tag
 
 587                         [\-~#]?       #   Whitespace-Unterdrückung
 
 588                         \s*           #   Optional beliebig viele Whitespace
 
 589                         ([\'\"])      #   Anfang des zu übersetzenden Strings   ::Parameter $4::
 
 590                         (.*?)         #   Der zu übersetzende String            ::Parameter $5::
 
 591                         (?<!\\)\4     #   Ende des zu übersetzenden Strings
 
 592                         \s*\|\s*      #   Pipe-Zeichen mit optionalen Whitespace davor und danach
 
 593                         (\$T8)        #   Filteraufruf                          ::Parameter $6::
 
 594                         .*?           #   Optionale Argumente für den Filter
 
 596                         [\-~#]?       #   Whitespace-Unterdrückung
 
 597                         \%\]          #   Template-Ende-Tag
 
 600       my $module = $1 || $6;
 
 601       my $string = $3 || $5;
 
 602       print "Found filter >>>$string<<<\n" if $debug;
 
 603       substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
 
 605       $string                         = unescape_template_string($string);
 
 606       $cached{$file}{all}{$string}    = 1;
 
 607       $cached{$file}{html}{$string}   = 1;
 
 608       $cached{$file}{submit}{$string} = 1 if $PREMATCH =~ /$submitsearch/;
 
 609       $plugins{needed}->{T8}          = 1 if $module eq '$T8';
 
 610       $plugins{needed}->{LxERP}       = 1 if $module eq 'LxERP.t8';
 
 613     while ($line =~ m/\[\%          # Template-Start-Tag
 
 614                       [\-~#]?       # Whitespace-Unterdrückung
 
 615                       \s*           # Optional beliebig viele Whitespace
 
 616                       (?:           # Die erkannten Template-Direktiven
 
 621                       \s+           # Mindestens ein Whitespace
 
 622                       [\'\"]?       # Anfang des Dateinamens
 
 623                       ([^\s]+)      # Beliebig viele Nicht-Whitespaces -- Dateiname
 
 624                       \.(html|js)   # Endung ".html" oder ".js", ansonsten kann es der Name eines Blocks sein
 
 626       my $new_file_name = "$basedir/templates/webpages/$1.$2";
 
 627       $cached{$file}{scanh}{$new_file_name} = 1;
 
 628       substr $line, $LAST_MATCH_START[1], $LAST_MATCH_END[0] - $LAST_MATCH_START[0], '';
 
 634   foreach my $plugin (keys %{ $plugins{needed} }) {
 
 635     next if ($plugins{loaded}->{$plugin});
 
 636     print "E: " . strip_base($file) . " requires the Template plugin '$plugin', but is not loaded with '[\% USE $plugin \%]'.\n";
 
 639   # copy back into global arrays
 
 640   $alllocales{$_} = 1            for keys %{$cached{$file}{all}};
 
 641   $locale{$_}     = 1            for keys %{$cached{$file}{html}};
 
 642   $submit{$_}     = 1            for keys %{$cached{$file}{submit}};
 
 644   scanhtmlfile($_)               for keys %{$cached{$file}{scanh}};
 
 646   $referenced_html_files{$_} = 1 for keys %{$cached{$file}{scanh}};
 
 649 sub scan_javascript_file {
 
 652   open(my $fh, '<:encoding(utf8)', $file) || die('can not open file: '. $file);
 
 654   while( my $line = readline($fh) ) {
 
 665       my $text = unescape_template_string($2);
 
 667       $jslocale{$text} = 1;
 
 668       $alllocales{$text} = 1;
 
 674 sub search_unused_htmlfiles {
 
 675   my @unscanned_dirs = ('../../templates/webpages');
 
 677   while (scalar @unscanned_dirs) {
 
 678     my $dir = shift @unscanned_dirs;
 
 680     foreach my $entry (<$dir/*>) {
 
 682         push @unscanned_dirs, $entry;
 
 684       } elsif (!$ignore_unused_templates{strip_base($entry)} && -f $entry && !$referenced_html_files{$entry}) {
 
 685         print "W: unused HTML template: " . strip_base($entry) . "\n";
 
 693   my $s =  "$_[0]";             # Create a copy of the string.
 
 696   $s    =~ s|templates/webpages/||;
 
 703   $val =~ s/(\'|\\$)/\\$1/g;
 
 704   return  "'" . $val .  "'";
 
 709   $val =~ s/(\"|\\$)/\\$1/g;
 
 710   return  '"'. $val .'"';
 
 714   my $key      = _single_quote(shift);
 
 715   my $text     = _single_quote(shift);
 
 717   my $template = $params{template} || qq|  %-29s => %s,\n|;
 
 718   my $fh       = $params{fh}       || croak 'need filehandle in _print_line';
 
 720   print $fh sprintf $template, $key, $text;
 
 726   my $file      = $params{file}   || croak 'need filename in generate_file';
 
 727   my $header    = $params{header};
 
 728   my $lines     = $params{data_sub};
 
 729   my $data_name = $params{data_name};
 
 730   my @delim     = split //, ($params{delim} || '{}');
 
 732   open my $fh, '>:encoding(utf8)', $file or die "$! : $file";
 
 734   print $fh "#!/usr/bin/perl\n# -*- coding: utf-8; -*-\n# vim: fenc=utf-8\n\nuse utf8;\n\n";
 
 735   print $fh $header, "\n" if $header;
 
 736   print $fh "$data_name = $delim[0]\n" if $data_name;
 
 740   print $fh qq|$delim[1];\n\n1;\n|;
 
 748 locales.pl - Collect strings for translation in kivitendo
 
 752 locales.pl [options] lang_code
 
 755   -n, --no-custom-files  Do not process files whose name contains "_"
 
 756   -c, --check-files      Run extended checks on HTML files
 
 757   -f, --filenames        Show the filenames where new strings where found
 
 758   -v, --verbose          Be more verbose
 
 759   -h, --help             Show this help
 
 765 =item B<-n>, B<--no-custom-files>
 
 767 Do not process files whose name contains "_", e.g. "custom_io.pl".
 
 769 =item B<-c>, B<--check-files>
 
 771 Run extended checks on the usage of templates. This can be used to
 
 772 discover HTML templates that are never used as well as the usage of
 
 773 non-existing HTML templates.
 
 775 =item B<-v>, B<--verbose>
 
 783 This script collects strings from Perl files, the menu.ini file and
 
 784 HTML templates and puts them into the file "all" for translation.