Merge branch 'master' of vc.linet-services.de:public/lx-office-erp
[kivitendo-erp.git] / SL / Locale.pm
1 #====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 # Contributors: Thomas Bayen <bayen@gmx.de>
16 #               Antti Kaihola <akaihola@siba.fi>
17 #               Moritz Bunkus (tex code)
18 #
19 # This program is free software; you can redistribute it and/or modify
20 # it under the terms of the GNU General Public License as published by
21 # the Free Software Foundation; either version 2 of the License, or
22 # (at your option) any later version.
23 #
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27 # GNU General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #======================================================================
32 #
33 # Translations and number/date formatting
34 #
35 #======================================================================
36
37 package Locale;
38
39 use DateTime;
40 use Encode;
41 use List::Util qw(first);
42 use List::MoreUtils qw(any);
43
44 use SL::LXDebug;
45 use SL::Common;
46 use SL::Iconv;
47 use SL::Inifile;
48
49 use strict;
50
51 my %locales_by_country;
52
53 sub new {
54   $main::lxdebug->enter_sub();
55
56   my ($type, $country) = @_;
57
58   $country ||= $::lx_office_conf{system}->{language};
59   $country   =~ s|.*/||;
60   $country   =~ s|\.||g;
61
62   if (!$locales_by_country{$country}) {
63     my $self = {};
64     bless $self, $type;
65
66     $self->_init($country);
67
68     $locales_by_country{$country} = $self;
69   }
70
71   $main::lxdebug->leave_sub();
72
73   return $locales_by_country{$country}
74 }
75
76 sub _init {
77   my $self     = shift;
78   my $country  = shift;
79
80   $self->{charset}     = Common::DEFAULT_CHARSET;
81   $self->{countrycode} = $country;
82
83   if ($country && -d "locale/$country") {
84     local *IN;
85     if (open(IN, "<", "locale/$country/all")) {
86       my $code = join("", <IN>);
87       eval($code);
88       close(IN);
89     }
90
91     if (open IN, "<", "locale/$country/charset") {
92       $self->{charset} = <IN>;
93       close IN;
94
95       chomp $self->{charset};
96     }
97   }
98
99   my $db_charset            = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
100   $self->{is_utf8}          = (any { lc($::lx_office_conf{system}->{dbcharset} || '') eq $_ } qw(utf8 utf-8 unicode)) ? 1 : 0;
101
102   if ($self->{is_utf8}) {
103     binmode STDOUT, ":utf8";
104     binmode STDERR, ":utf8";
105   }
106
107   $self->{iconv}            = SL::Iconv->new($self->{charset}, $db_charset);
108   $self->{iconv_reverse}    = SL::Iconv->new($db_charset,      $self->{charset});
109   $self->{iconv_english}    = SL::Iconv->new('ASCII',          $db_charset);
110   $self->{iconv_iso8859}    = SL::Iconv->new('ISO-8859-15',    $db_charset);
111   $self->{iconv_to_iso8859} = SL::Iconv->new($db_charset,      'ISO-8859-15');
112   $self->{iconv_utf8}       = SL::Iconv->new('UTF-8',          $db_charset);
113
114   $self->_read_special_chars_file($country);
115
116   push @{ $self->{LONG_MONTH} },
117     ("January",   "February", "March",    "April",
118      "May ",      "June",     "July",     "August",
119      "September", "October",  "November", "December");
120   push @{ $self->{SHORT_MONTH} },
121     (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
122 }
123
124 sub is_utf8 {
125   my $self   = shift;
126   my $handle = shift;
127   return $self->{is_utf8} && (!$handle || $handle->is_utf8);
128 }
129
130 sub _handle_markup {
131   my $self    = shift;
132   my $str     = shift;
133
134   my $escaped = 0;
135   my $new_str = '';
136
137   for (my $i = 0; $i < length $str; $i++) {
138     my $char = substr $str, $i, 1;
139
140     if ($escaped) {
141       if ($char eq 'n') {
142         $new_str .= "\n";
143
144       } elsif ($char eq 'r') {
145         $new_str .= "\r";
146
147       } elsif ($char eq 's') {
148         $new_str .= ' ';
149
150       } elsif ($char eq 'x') {
151         $new_str .= chr(hex(substr($str, $i + 1, 2)));
152         $i       += 2;
153
154       } else {
155         $new_str .= $char;
156       }
157
158       $escaped  = 0;
159
160     } elsif ($char eq '\\') {
161       $escaped  = 1;
162
163     } else {
164       $new_str .= $char;
165     }
166   }
167
168   return $new_str;
169 }
170
171 sub _read_special_chars_file {
172   my $self    = shift;
173   my $country = shift;
174
175   if (! -f "locale/$country/special_chars") {
176     $self->{special_chars_map} = {};
177     return;
178   }
179
180   $self->{special_chars_map} = Inifile->new("locale/$country/special_chars", 'verbatim' => 1);
181
182   foreach my $format (keys %{ $self->{special_chars_map} }) {
183     next if (($format eq 'FILE') || ($format eq 'ORDER') || (ref $self->{special_chars_map}->{$format} ne 'HASH'));
184
185     if ($format ne lc $format) {
186       $self->{special_chars_map}->{lc $format} = $self->{special_chars_map}->{$format};
187       delete $self->{special_chars_map}->{$format};
188       $format = lc $format;
189     }
190
191     my $scmap = $self->{special_chars_map}->{$format};
192     my $order = $self->{iconv}->convert($scmap->{order});
193     delete $scmap->{order};
194
195     foreach my $key (keys %{ $scmap }) {
196       $scmap->{$key} = $self->_handle_markup($self->{iconv}->convert($scmap->{$key}));
197
198       my $new_key    = $self->_handle_markup($self->{iconv}->convert($key));
199
200       if ($key ne $new_key) {
201         $scmap->{$new_key} = $scmap->{$key};
202         delete $scmap->{$key};
203       }
204     }
205
206     $self->{special_chars_map}->{"${format}-reverse"}          = { reverse %{ $scmap } };
207
208     $scmap->{order}                                            = [ map { $self->_handle_markup($_) } split m/\s+/, $order ];
209     $self->{special_chars_map}->{"${format}-reverse"}->{order} = [ grep { $_ } map { $scmap->{$_} } reverse @{ $scmap->{order} } ];
210   }
211 }
212
213 sub text {
214   my $self = shift;
215   my $text = shift;
216
217   return $text->translated if (ref($text) || '') eq 'SL::Locale::String';
218
219   if ($self->{texts}->{$text}) {
220     $text = $self->{iconv}->convert($self->{texts}->{$text});
221   } else {
222     $text = $self->{iconv_english}->convert($text);
223   }
224
225   if (@_) {
226     $text = Form->format_string($text, @_);
227   }
228
229   return $text;
230 }
231
232 sub lang_to_locale {
233   my ($self, $requested_lang) = @_;
234
235   my $requested_locale;
236   $requested_locale = 'de' if $requested_lang =~ m/^_(de|deu|ger)/i;
237   $requested_locale = 'en' if $requested_lang =~ m/^_(en|uk|us|gr)/i;
238   $requested_locale = 'fr' if $requested_lang =~ m/^_fr/i;
239   $requested_locale ||= 'de';
240
241   return $requested_locale;
242 }
243
244 sub findsub {
245   $main::lxdebug->enter_sub();
246
247   my ($self, $text) = @_;
248   my $text_rev      = lc $self->{iconv_reverse}->convert($text);
249   $text_rev         =~ s/[\s\-]+/_/g;
250
251   if (!$self->{texts_reverse}) {
252     $self->{texts_reverse} = { };
253     while (my ($original, $translation) = each %{ $self->{texts} }) {
254       $original    =  lc $original;
255       $original    =~ s/[^a-z0-9]/_/g;
256       $original    =~ s/_+/_/g;
257
258       $translation =  lc $translation;
259       $translation =~ s/[\s\-]+/_/g;
260
261       $self->{texts_reverse}->{$translation} ||= [ ];
262       push @{ $self->{texts_reverse}->{$translation} }, $original;
263     }
264   }
265
266   my $sub_name;
267   $sub_name   = first { defined(&{ "::${_}" }) } @{ $self->{texts_reverse}->{$text_rev} } if $self->{texts_reverse}->{$text_rev};
268   $sub_name ||= $text_rev if ($text_rev =~ m/^[a-z][a-z0-9_]+$/) && defined &{ "::${text_rev}" };
269
270   $main::form->error("$text not defined in locale/$self->{countrycode}/all") if !$sub_name;
271
272   $main::lxdebug->leave_sub();
273
274   return $sub_name;
275 }
276
277 sub date {
278   $main::lxdebug->enter_sub();
279
280   my ($self, $myconfig, $date, $longformat) = @_;
281
282   if (!$date) {
283     $main::lxdebug->leave_sub();
284     return '';
285   }
286
287   my $longdate  = "";
288   my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
289
290   my ($spc, $yy, $mm, $dd);
291
292     # get separator
293   $spc = $myconfig->{dateformat};
294   $spc =~ s/\w//g;
295   $spc = substr($spc, 1, 1);
296
297   if ($date =~ /\D/) {
298     if ($myconfig->{dateformat} =~ /^yy/) {
299       ($yy, $mm, $dd) = split /\D/, $date;
300     }
301     if ($myconfig->{dateformat} =~ /^mm/) {
302       ($mm, $dd, $yy) = split /\D/, $date;
303     }
304     if ($myconfig->{dateformat} =~ /^dd/) {
305       ($dd, $mm, $yy) = split /\D/, $date;
306     }
307   } else {
308     $date = substr($date, 2);
309     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
310   }
311
312   $dd *= 1;
313   $mm--;
314   $yy = ($yy < 70) ? $yy + 2000 : $yy;
315   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
316
317   if ($myconfig->{dateformat} =~ /^dd/) {
318     if (defined $longformat && $longformat == 0) {
319       $mm++;
320       $dd = "0$dd" if ($dd < 10);
321       $mm = "0$mm" if ($mm < 10);
322       $longdate = "$dd$spc$mm$spc$yy";
323     } else {
324       $longdate = "$dd";
325       $longdate .= ($spc eq '.') ? ". " : " ";
326       $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
327     }
328   } elsif ($myconfig->{dateformat} eq "yyyy-mm-dd") {
329
330     # Use German syntax with the ISO date style "yyyy-mm-dd" because
331     # Lx-Office is mainly used in Germany or German speaking countries.
332     if (defined $longformat && $longformat == 0) {
333       $mm++;
334       $dd = "0$dd" if ($dd < 10);
335       $mm = "0$mm" if ($mm < 10);
336       $longdate = "$yy-$mm-$dd";
337     } else {
338       $longdate = "$dd. ";
339       $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
340     }
341   } else {
342     if (defined $longformat && $longformat == 0) {
343       $mm++;
344       $dd = "0$dd" if ($dd < 10);
345       $mm = "0$mm" if ($mm < 10);
346       $longdate = "$mm$spc$dd$spc$yy";
347     } else {
348       $longdate = &text($self, $self->{$longmonth}[$mm]) . " $dd, $yy";
349     }
350   }
351
352   $main::lxdebug->leave_sub();
353
354   return $longdate;
355 }
356
357 sub parse_date {
358   $main::lxdebug->enter_sub(2);
359
360   my ($self, $myconfig, $date, $longformat) = @_;
361   my ($spc, $yy, $mm, $dd);
362
363   unless ($date) {
364     $main::lxdebug->leave_sub(2);
365     return ();
366   }
367
368   # get separator
369   $spc = $myconfig->{dateformat};
370   $spc =~ s/\w//g;
371   $spc = substr($spc, 1, 1);
372
373   if ($date =~ /\D/) {
374     if ($myconfig->{dateformat} =~ /^yy/) {
375       ($yy, $mm, $dd) = split /\D/, $date;
376     } elsif ($myconfig->{dateformat} =~ /^mm/) {
377       ($mm, $dd, $yy) = split /\D/, $date;
378     } elsif ($myconfig->{dateformat} =~ /^dd/) {
379       ($dd, $mm, $yy) = split /\D/, $date;
380     }
381   } else {
382     $date = substr($date, 2);
383     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
384   }
385
386   $dd *= 1;
387   $mm *= 1;
388   $yy = ($yy < 70) ? $yy + 2000 : $yy;
389   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
390
391   $main::lxdebug->leave_sub(2);
392   return ($yy, $mm, $dd);
393 }
394
395 sub parse_date_to_object {
396   my $self           = shift;
397   my ($yy, $mm, $dd) = $self->parse_date(@_);
398
399   return $yy && $mm && $dd ? DateTime->new(year => $yy, month => $mm, day => $dd) : undef;
400 }
401
402 sub format_date_object {
403   my ($self, $datetime, %params)    = @_;
404
405   my $format             =  $::myconfig{dateformat} || 'yyyy-mm-dd';
406   $format                =~ s/yyyy/\%Y/;
407   $format                =~ s/yy/\%y/;
408   $format                =~ s/mm/\%m/;
409   $format                =~ s/dd/\%d/;
410
411   my $precision          =  $params{precision} || 'day';
412   $precision             =~ s/s$//;
413   my %precision_spec_map = (
414     second => '%H:%M:%S',
415     minute => '%H:%M',
416     hour   => '%H',
417   );
418
419   $format .= ' ' . $precision_spec_map{$precision} if $precision_spec_map{$precision};
420
421   return $datetime->strftime($format);
422 }
423
424 sub reformat_date {
425   $main::lxdebug->enter_sub(2);
426
427   my ($self, $myconfig, $date, $output_format, $longformat) = @_;
428
429   $main::lxdebug->leave_sub(2) and return "" unless ($date);
430
431   my ($yy, $mm, $dd) = $self->parse_date($myconfig, $date);
432
433   $output_format =~ /d+/;
434   substr($output_format, $-[0], $+[0] - $-[0]) =
435     sprintf("%0" . (length($&)) . "d", $dd);
436
437   $output_format =~ /m+/;
438   substr($output_format, $-[0], $+[0] - $-[0]) =
439     sprintf("%0" . (length($&)) . "d", $mm);
440
441   $output_format =~ /y+/;
442   substr($output_format, $-[0], $+[0] - $-[0]) = $yy;
443
444   $main::lxdebug->leave_sub(2);
445
446   return $output_format;
447 }
448
449 sub format_date {
450   $main::lxdebug->enter_sub();
451
452   my $self     = shift;
453   my $myconfig = shift;
454   my $yy       = shift;
455   my $mm       = shift;
456   my $dd       = shift;
457   my $yy_len   = shift || 4;
458
459   ($yy, $mm, $dd) = ($yy->year, $yy->month, $yy->day) if ref $yy eq 'DateTime';
460
461   $main::lxdebug->leave_sub() and return "" unless $yy && $mm && $dd;
462
463   $yy = $yy % 100 if 2 == $yy_len;
464
465   my $format = ref $myconfig eq '' ? "$myconfig" : $myconfig->{dateformat};
466   $format =~ s{ d+ }{ sprintf("%0" . (length($&)) . "d", $dd) }gex;
467   $format =~ s{ m+ }{ sprintf("%0" . (length($&)) . "d", $mm) }gex;
468   $format =~ s{ y+ }{ sprintf("%0${yy_len}d",            $yy) }gex;
469
470   $main::lxdebug->leave_sub();
471
472   return $format;
473 }
474
475 sub quote_special_chars {
476   my $self   = shift;
477   my $format = lc shift;
478   my $string = shift;
479
480   if ($self->{special_chars_map} && $self->{special_chars_map}->{$format} && $self->{special_chars_map}->{$format}->{order}) {
481     my $scmap = $self->{special_chars_map}->{$format};
482
483     map { $string =~ s/\Q${_}\E/$scmap->{$_}/g } @{ $scmap->{order} };
484   }
485
486   return $string;
487 }
488
489 sub unquote_special_chars {
490   my $self    = shift;
491   my $format  = shift;
492
493   return $self->quote_special_chars("${format}-reverse", shift);
494 }
495
496 sub remap_special_chars {
497   my $self       = shift;
498   my $src_format = shift;
499   my $dst_format = shift;
500
501   return $self->quote_special_chars($dst_format, $self->quote_special_chars("${src_format}-reverse", shift));
502 }
503
504 sub raw_io_active {
505   my $self = shift;
506
507   return !!$self->{raw_io_active};
508 }
509
510 sub with_raw_io {
511   my $self = shift;
512   my $fh   = shift;
513   my $code = shift;
514
515   $self->{raw_io_active} = 1;
516   binmode $fh, ":raw";
517   $code->();
518   binmode $fh, ":utf8" if $self->is_utf8;
519   $self->{raw_io_active} = 0;
520 }
521
522 sub set_numberformat_wo_thousands_separator {
523   my $self     = shift;
524   my $myconfig = shift || \%::myconfig;
525
526   $self->{saved_numberformat} = $myconfig->{numberformat};
527   $myconfig->{numberformat}   =~ s/^1[,\.]/1/;
528 }
529
530 sub restore_numberformat {
531   my $self     = shift;
532   my $myconfig = shift || \%::myconfig;
533
534   $myconfig->{numberformat} = $self->{saved_numberformat} if $self->{saved_numberformat};
535 }
536
537 sub get_local_time_zone {
538   my $self = shift;
539   $self->{local_time_zone} ||= DateTime::TimeZone->new(name => 'local');
540   return $self->{local_time_zone};
541 }
542
543 1;
544 __END__
545
546 =pod
547
548 =encoding utf8
549
550 =head1 NAME
551
552 Locale - Functions for dealing with locale-dependent information
553
554 =head1 SYNOPSIS
555
556   use Locale;
557   use DateTime;
558
559   my $locale = Locale->new('de');
560   my $now    = DateTime->now_local;
561   print "Current date and time: ", $::locale->format_date_object($now, precision => 'second'), "\n";
562
563 =head1 OVERVIEW
564
565 TODO: write overview
566
567 =head1 FUNCTIONS
568
569 =over 4
570
571 =item C<date>
572
573 TODO: Describe date
574
575 =item C<findsub>
576
577 TODO: Describe findsub
578
579 =item C<format_date>
580
581 TODO: Describe format_date
582
583 =item C<format_date_object $datetime, %params>
584
585 Formats the C<$datetime> object accoring to the user's locale setting.
586
587 The parameter C<precision> can control whether or not the time
588 component is formatted as well:
589
590 =over 4
591
592 =item * C<day>
593
594 Only format the year, month and day. This is also the default.
595
596 =item * C<hour>
597
598 Add the hour to the date.
599
600 =item * C<minute>
601
602 Add hour:minute to the date.
603
604 =item * C<second>
605
606 Add hour:minute:second to the date.
607
608 =back
609
610 =item C<get_local_time_zone>
611
612 TODO: Describe get_local_time_zone
613
614 =item C<is_utf8>
615
616 TODO: Describe is_utf8
617
618 =item C<lang_to_locale>
619
620 TODO: Describe lang_to_locale
621
622 =item C<new>
623
624 TODO: Describe new
625
626 =item C<parse_date>
627
628 TODO: Describe parse_date
629
630 =item C<parse_date_to_object>
631
632 TODO: Describe parse_date_to_object
633
634 =item C<quote_special_chars>
635
636 TODO: Describe quote_special_chars
637
638 =item C<raw_io_active>
639
640 TODO: Describe raw_io_active
641
642 =item C<reformat_date>
643
644 TODO: Describe reformat_date
645
646 =item C<remap_special_chars>
647
648 TODO: Describe remap_special_chars
649
650 =item C<restore_numberformat>
651
652 TODO: Describe restore_numberformat
653
654 =item C<set_numberformat_wo_thousands_separator>
655
656 TODO: Describe set_numberformat_wo_thousands_separator
657
658 =item C<text>
659
660 TODO: Describe text
661
662 =item C<unquote_special_chars>
663
664 TODO: Describe unquote_special_chars
665
666 =item C<with_raw_io>
667
668 TODO: Describe with_raw_io
669
670 =back
671
672 =head1 BUGS
673
674 Nothing here yet.
675
676 =head1 AUTHOR
677
678 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
679
680 =cut