spellcheck strikes again!
[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   if ($self->{texts}->{$text}) {
218     $text = $self->{iconv}->convert($self->{texts}->{$text});
219   } else {
220     $text = $self->{iconv_english}->convert($text);
221   }
222
223   if (@_) {
224     $text = Form->format_string($text, @_);
225   }
226
227   return $text;
228 }
229
230 sub lang_to_locale {
231   my ($self, $requested_lang) = @_;
232
233   my $requested_locale;
234   $requested_locale = 'de' if $requested_lang =~ m/^_(de|deu|ger)/i;
235   $requested_locale = 'en' if $requested_lang =~ m/^_(en|uk|us|gr)/i;
236   $requested_locale = 'fr' if $requested_lang =~ m/^_fr/i;
237   $requested_locale ||= 'de';
238
239   return $requested_locale;
240 }
241
242 sub findsub {
243   $main::lxdebug->enter_sub();
244
245   my ($self, $text) = @_;
246   my $text_rev      = lc $self->{iconv_reverse}->convert($text);
247   $text_rev         =~ s/[\s\-]+/_/g;
248
249   if (!$self->{texts_reverse}) {
250     $self->{texts_reverse} = { };
251     while (my ($original, $translation) = each %{ $self->{texts} }) {
252       $original    =  lc $original;
253       $original    =~ s/[^a-z0-9]/_/g;
254       $original    =~ s/_+/_/g;
255
256       $translation =  lc $translation;
257       $translation =~ s/[\s\-]+/_/g;
258
259       $self->{texts_reverse}->{$translation} ||= [ ];
260       push @{ $self->{texts_reverse}->{$translation} }, $original;
261     }
262   }
263
264   my $sub_name;
265   $sub_name   = first { defined(&{ "::${_}" }) } @{ $self->{texts_reverse}->{$text_rev} } if $self->{texts_reverse}->{$text_rev};
266   $sub_name ||= $text_rev if ($text_rev =~ m/^[a-z][a-z0-9_]+$/) && defined &{ "::${text_rev}" };
267
268   $main::form->error("$text not defined in locale/$self->{countrycode}/all") if !$sub_name;
269
270   $main::lxdebug->leave_sub();
271
272   return $sub_name;
273 }
274
275 sub date {
276   $main::lxdebug->enter_sub();
277
278   my ($self, $myconfig, $date, $longformat) = @_;
279
280   if (!$date) {
281     $main::lxdebug->leave_sub();
282     return '';
283   }
284
285   my $longdate  = "";
286   my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
287
288   my ($spc, $yy, $mm, $dd);
289
290     # get separator
291   $spc = $myconfig->{dateformat};
292   $spc =~ s/\w//g;
293   $spc = substr($spc, 1, 1);
294
295   if ($date =~ /\D/) {
296     if ($myconfig->{dateformat} =~ /^yy/) {
297       ($yy, $mm, $dd) = split /\D/, $date;
298     }
299     if ($myconfig->{dateformat} =~ /^mm/) {
300       ($mm, $dd, $yy) = split /\D/, $date;
301     }
302     if ($myconfig->{dateformat} =~ /^dd/) {
303       ($dd, $mm, $yy) = split /\D/, $date;
304     }
305   } else {
306     $date = substr($date, 2);
307     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
308   }
309
310   $dd *= 1;
311   $mm--;
312   $yy = ($yy < 70) ? $yy + 2000 : $yy;
313   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
314
315   if ($myconfig->{dateformat} =~ /^dd/) {
316     if (defined $longformat && $longformat == 0) {
317       $mm++;
318       $dd = "0$dd" if ($dd < 10);
319       $mm = "0$mm" if ($mm < 10);
320       $longdate = "$dd$spc$mm$spc$yy";
321     } else {
322       $longdate = "$dd";
323       $longdate .= ($spc eq '.') ? ". " : " ";
324       $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
325     }
326   } elsif ($myconfig->{dateformat} eq "yyyy-mm-dd") {
327
328     # Use German syntax with the ISO date style "yyyy-mm-dd" because
329     # Lx-Office is mainly used in Germany or German speaking countries.
330     if (defined $longformat && $longformat == 0) {
331       $mm++;
332       $dd = "0$dd" if ($dd < 10);
333       $mm = "0$mm" if ($mm < 10);
334       $longdate = "$yy-$mm-$dd";
335     } else {
336       $longdate = "$dd. ";
337       $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
338     }
339   } else {
340     if (defined $longformat && $longformat == 0) {
341       $mm++;
342       $dd = "0$dd" if ($dd < 10);
343       $mm = "0$mm" if ($mm < 10);
344       $longdate = "$mm$spc$dd$spc$yy";
345     } else {
346       $longdate = &text($self, $self->{$longmonth}[$mm]) . " $dd, $yy";
347     }
348   }
349
350   $main::lxdebug->leave_sub();
351
352   return $longdate;
353 }
354
355 sub parse_date {
356   $main::lxdebug->enter_sub(2);
357
358   my ($self, $myconfig, $date, $longformat) = @_;
359   my ($spc, $yy, $mm, $dd);
360
361   unless ($date) {
362     $main::lxdebug->leave_sub(2);
363     return ();
364   }
365
366   # get separator
367   $spc = $myconfig->{dateformat};
368   $spc =~ s/\w//g;
369   $spc = substr($spc, 1, 1);
370
371   if ($date =~ /\D/) {
372     if ($myconfig->{dateformat} =~ /^yy/) {
373       ($yy, $mm, $dd) = split /\D/, $date;
374     } elsif ($myconfig->{dateformat} =~ /^mm/) {
375       ($mm, $dd, $yy) = split /\D/, $date;
376     } elsif ($myconfig->{dateformat} =~ /^dd/) {
377       ($dd, $mm, $yy) = split /\D/, $date;
378     }
379   } else {
380     $date = substr($date, 2);
381     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
382   }
383
384   $dd *= 1;
385   $mm *= 1;
386   $yy = ($yy < 70) ? $yy + 2000 : $yy;
387   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
388
389   $main::lxdebug->leave_sub(2);
390   return ($yy, $mm, $dd);
391 }
392
393 sub parse_date_to_object {
394   my $self           = shift;
395   my ($yy, $mm, $dd) = $self->parse_date(@_);
396
397   return $yy && $mm && $dd ? DateTime->new(year => $yy, month => $mm, day => $dd) : undef;
398 }
399
400 sub format_date_object {
401   my ($self, $datetime, %params)    = @_;
402
403   my $format             =  $::myconfig{dateformat} || 'yyyy-mm-dd';
404   $format                =~ s/yyyy/\%Y/;
405   $format                =~ s/yy/\%y/;
406   $format                =~ s/mm/\%m/;
407   $format                =~ s/dd/\%d/;
408
409   my $precision          =  $params{precision} || 'day';
410   $precision             =~ s/s$//;
411   my %precision_spec_map = (
412     second => '%H:%M:%S',
413     minute => '%H:%M',
414     hour   => '%H',
415   );
416
417   $format .= ' ' . $precision_spec_map{$precision} if $precision_spec_map{$precision};
418
419   return $datetime->strftime($format);
420 }
421
422 sub reformat_date {
423   $main::lxdebug->enter_sub(2);
424
425   my ($self, $myconfig, $date, $output_format, $longformat) = @_;
426
427   $main::lxdebug->leave_sub(2) and return "" unless ($date);
428
429   my ($yy, $mm, $dd) = $self->parse_date($myconfig, $date);
430
431   $output_format =~ /d+/;
432   substr($output_format, $-[0], $+[0] - $-[0]) =
433     sprintf("%0" . (length($&)) . "d", $dd);
434
435   $output_format =~ /m+/;
436   substr($output_format, $-[0], $+[0] - $-[0]) =
437     sprintf("%0" . (length($&)) . "d", $mm);
438
439   $output_format =~ /y+/;
440   substr($output_format, $-[0], $+[0] - $-[0]) = $yy;
441
442   $main::lxdebug->leave_sub(2);
443
444   return $output_format;
445 }
446
447 sub format_date {
448   $main::lxdebug->enter_sub();
449
450   my $self     = shift;
451   my $myconfig = shift;
452   my $yy       = shift;
453   my $mm       = shift;
454   my $dd       = shift;
455   my $yy_len   = shift || 4;
456
457   ($yy, $mm, $dd) = ($yy->year, $yy->month, $yy->day) if ref $yy eq 'DateTime';
458
459   $main::lxdebug->leave_sub() and return "" unless $yy && $mm && $dd;
460
461   $yy = $yy % 100 if 2 == $yy_len;
462
463   my $format = ref $myconfig eq '' ? "$myconfig" : $myconfig->{dateformat};
464   $format =~ s{ d+ }{ sprintf("%0" . (length($&)) . "d", $dd) }gex;
465   $format =~ s{ m+ }{ sprintf("%0" . (length($&)) . "d", $mm) }gex;
466   $format =~ s{ y+ }{ sprintf("%0${yy_len}d",            $yy) }gex;
467
468   $main::lxdebug->leave_sub();
469
470   return $format;
471 }
472
473 sub quote_special_chars {
474   my $self   = shift;
475   my $format = lc shift;
476   my $string = shift;
477
478   if ($self->{special_chars_map} && $self->{special_chars_map}->{$format} && $self->{special_chars_map}->{$format}->{order}) {
479     my $scmap = $self->{special_chars_map}->{$format};
480
481     map { $string =~ s/\Q${_}\E/$scmap->{$_}/g } @{ $scmap->{order} };
482   }
483
484   return $string;
485 }
486
487 sub unquote_special_chars {
488   my $self    = shift;
489   my $format  = shift;
490
491   return $self->quote_special_chars("${format}-reverse", shift);
492 }
493
494 sub remap_special_chars {
495   my $self       = shift;
496   my $src_format = shift;
497   my $dst_format = shift;
498
499   return $self->quote_special_chars($dst_format, $self->quote_special_chars("${src_format}-reverse", shift));
500 }
501
502 sub raw_io_active {
503   my $self = shift;
504
505   return !!$self->{raw_io_active};
506 }
507
508 sub with_raw_io {
509   my $self = shift;
510   my $fh   = shift;
511   my $code = shift;
512
513   $self->{raw_io_active} = 1;
514   binmode $fh, ":raw";
515   $code->();
516   binmode $fh, ":utf8" if $self->is_utf8;
517   $self->{raw_io_active} = 0;
518 }
519
520 sub set_numberformat_wo_thousands_separator {
521   my $self     = shift;
522   my $myconfig = shift || \%::myconfig;
523
524   $self->{saved_numberformat} = $myconfig->{numberformat};
525   $myconfig->{numberformat}   =~ s/^1[,\.]/1/;
526 }
527
528 sub restore_numberformat {
529   my $self     = shift;
530   my $myconfig = shift || \%::myconfig;
531
532   $myconfig->{numberformat} = $self->{saved_numberformat} if $self->{saved_numberformat};
533 }
534
535 sub get_local_time_zone {
536   my $self = shift;
537   $self->{local_time_zone} ||= DateTime::TimeZone->new(name => 'local');
538   return $self->{local_time_zone};
539 }
540
541 1;
542 __END__
543
544 =pod
545
546 =encoding utf8
547
548 =head1 NAME
549
550 Locale - Functions for dealing with locale-dependent information
551
552 =head1 SYNOPSIS
553
554   use Locale;
555   use DateTime;
556
557   my $locale = Locale->new('de');
558   my $now    = DateTime->now_local;
559   print "Current date and time: ", $::locale->format_date_object($now, precision => 'second'), "\n";
560
561 =head1 OVERVIEW
562
563 TODO: write overview
564
565 =head1 FUNCTIONS
566
567 =over 4
568
569 =item C<date>
570
571 TODO: Describe date
572
573 =item C<findsub>
574
575 TODO: Describe findsub
576
577 =item C<format_date>
578
579 TODO: Describe format_date
580
581 =item C<format_date_object $datetime, %params>
582
583 Formats the C<$datetime> object accoring to the user's locale setting.
584
585 The parameter C<precision> can control whether or not the time
586 component is formatted as well:
587
588 =over 4
589
590 =item * C<day>
591
592 Only format the year, month and day. This is also the default.
593
594 =item * C<hour>
595
596 Add the hour to the date.
597
598 =item * C<minute>
599
600 Add hour:minute to the date.
601
602 =item * C<second>
603
604 Add hour:minute:second to the date.
605
606 =back
607
608 =item C<get_local_time_zone>
609
610 TODO: Describe get_local_time_zone
611
612 =item C<is_utf8>
613
614 TODO: Describe is_utf8
615
616 =item C<lang_to_locale>
617
618 TODO: Describe lang_to_locale
619
620 =item C<new>
621
622 TODO: Describe new
623
624 =item C<parse_date>
625
626 TODO: Describe parse_date
627
628 =item C<parse_date_to_object>
629
630 TODO: Describe parse_date_to_object
631
632 =item C<quote_special_chars>
633
634 TODO: Describe quote_special_chars
635
636 =item C<raw_io_active>
637
638 TODO: Describe raw_io_active
639
640 =item C<reformat_date>
641
642 TODO: Describe reformat_date
643
644 =item C<remap_special_chars>
645
646 TODO: Describe remap_special_chars
647
648 =item C<restore_numberformat>
649
650 TODO: Describe restore_numberformat
651
652 =item C<set_numberformat_wo_thousands_separator>
653
654 TODO: Describe set_numberformat_wo_thousands_separator
655
656 =item C<text>
657
658 TODO: Describe text
659
660 =item C<unquote_special_chars>
661
662 TODO: Describe unquote_special_chars
663
664 =item C<with_raw_io>
665
666 TODO: Describe with_raw_io
667
668 =back
669
670 =head1 BUGS
671
672 Nothing here yet.
673
674 =head1 AUTHOR
675
676 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
677
678 =cut