Language.pm 28.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# -*- indent-tabs-mode: nil; -*-
# vim:ft=perl:et:sw=4
# $Id$
#
# Sympa - SYsteme de Multi-Postage Automatique
#
# Copyright (c) 1997, 1998, 1999 Institut Pasteur & Christophe Wolfhugel
# Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
# 2006, 2007, 2008, 2009, 2010, 2011 Comite Reseau des Universites
# Copyright (c) 2011, 2012, 2013, 2014 GIP RENATER
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

package Sympa::Language;

use strict;
use warnings;
sikeda's avatar
sikeda committed
29
30
use base qw(Class::Singleton);

31
32
33
34
35
36
37
38
39
40
41
42
43
44
use Locale::Messages '1.22';    # virtually same as 1.23.
use POSIX qw();

use Sympa::Constants;

BEGIN {
    ## Using the Pure Perl implementation of gettext
    ## This is required on Solaris : native implementation of gettext does not
    ## map ll_RR with ll.
    ## libintl-perl 1.23 or later is required to use 'gettext_dumb' package
    ## which is independent from POSIX locale.
    Locale::Messages->select_package('gettext_dumb');
    ## Workaround: Prevent from searching catalogs in /usr/share/locale.
    undef $Locale::gettext_pp::__gettext_pp_default_dir;
sikeda's avatar
sikeda committed
45
46
47
48
49
50
51
52

    ## Define what catalogs are used
    Locale::Messages::bindtextdomain(sympa    => Sympa::Constants::LOCALEDIR);
    Locale::Messages::bindtextdomain(web_help => Sympa::Constants::LOCALEDIR);
    Locale::Messages::textdomain('sympa');
    ## Get translations by internal encoding.
    Locale::Messages::bind_textdomain_codeset(sympa    => 'utf-8');
    Locale::Messages::bind_textdomain_codeset(web_help => 'utf-8');
53
54
}

sikeda's avatar
sikeda committed
55
56
57
58
sub _new_instance {
    my $class = shift;
    my $self  = $class->SUPER::_new_instance();

59
    ## Initialize lang/locale.
sikeda's avatar
sikeda committed
60
61
    $self->set_lang('en');
    return $self;
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
}

## The map to get language tag from older non-POSIX locale naming.
my %language_equiv = (
    'cn' => 'zh-CN',
    'tw' => 'zh-TW',
    'cz' => 'cs',
    'us' => 'en-US',
);

## The map to get appropriate POSIX locale name from language code.
## Why this is required is that on many systems locales often have canonic
## "ll_RR.ENCODING" names only.  n.b. This format can not express all
## languages in proper way, e.g. Common Arabic ("ar"), Esperanto ("eo").
##
## This map is also used to convert old-style Sympa "locales" to language
sikeda's avatar
sikeda committed
78
79
## tags ('en' is special case. cf. set_lang()).
my %lang2oldlocale = (
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    'af' => 'af_ZA',
    'ar' => 'ar_SY',
    'br' => 'br_FR',
    'bg' => 'bg_BG',
    'ca' => 'ca_ES',
    'cs' => 'cs_CZ',
    'de' => 'de_DE',
    'el' => 'el_GR',
    'es' => 'es_ES',
    'et' => 'et_EE',
    'eu' => 'eu_ES',
    'fi' => 'fi_FI',
    'fr' => 'fr_FR',
    'gl' => 'gl_ES',
    'hu' => 'hu_HU',
    'id' => 'id_ID',
    'it' => 'it_IT',
    'ja' => 'ja_JP',
    'ko' => 'ko_KR',
    'la' => 'la_VA',    # from OpenOffice.org
    'ml' => 'ml_IN',
    'nb' => 'nb_NO',
    'nn' => 'nn_NO',
    'nl' => 'nl_NL',
    'oc' => 'oc_FR',
    'pl' => 'pl_PL',
    'pt' => 'pt_PT',
    'rm' => 'rm_CH',    # CLDR
    'ro' => 'ro_RO',
    'ru' => 'ru_RU',
    'sv' => 'sv_SE',
    'tr' => 'tr_TR',
    'vi' => 'vi_VN',
);

sikeda's avatar
sikeda committed
115
116
## Regexp for old style canonical locale used by Sympa-6.2a or earlier.
my $oldlocale_re = qr/^([a-z]{2})_([A-Z]{2})(?![A-Z])/i;
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

## Regexp for IETF language tag described in RFC 5646 (BCP 47), modified.
my $language_tag_re = qr/^
    ([a-z]{2}(?:-[a-z]{3}){,3} | [a-z]{2,3})        # language (and ext.)
    (?:-([a-z]{4}))?                                # script
    (?:-([a-z]{2}))?                                # region (no UN M.49)
    (?:-(                                           # variant
	(?:[a-z0-9]{5,} | [0-9][a-z0-9]{3,})
	(?:-[a-z0-9]{5,} | -[0-9][a-z0-9]{3,})*
    ))?
$/ix;

## A tiny subset of script codes and gettext modifier names.
## Keys are ISO 15924 script codes (Titlecased).
## Values are property value aliases standardised by Unicode Consortium
## (lowercased).  cf. <http://www.unicode.org/iso15924/iso15924-codes.html>.
my %script2modifier = (
    'Arab' => 'arabic',
    'Cyrl' => 'cyrillic',
    'Deva' => 'devanagari',
    'Dsrt' => 'deseret',
    'Glag' => 'glagolitic',
sikeda's avatar
sikeda committed
139
    'Grek' => 'greek',
140
    'Guru' => 'gurmukhi',
sikeda's avatar
sikeda committed
141
    'Hebr' => 'hebrew',
142
143
144
145
146
147
    'Latn' => 'latin',
    'Mong' => 'mongolian',
    'Shaw' => 'shaw',         # found in Debian "en@shaw" locale.
    'Tfng' => 'tifinagh',
);

sikeda's avatar
sikeda committed
148
sub canonic_lang {
149
150
151
152
153
154
155
    my $lang = shift;
    return unless $lang;

    ## Compatibility: older non-POSIX locale names.
    if ($language_equiv{$lang}) {
        $lang = $language_equiv{$lang};
    }
sikeda's avatar
sikeda committed
156
157
    ## Compatibility: names used as "lang" or "locale" by Sympa <= 6.2a.
    elsif ($lang =~ $oldlocale_re) {
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
        $lang = _oldlocale2lang(lc($1) . '_' . uc($2));
    }

    my @subtags;

    # unknown format.
    return unless @subtags = ($lang =~ $language_tag_re);

    ## Canonicalize cases of subtags: ll-ext-Scri-RR-variant-...
    $subtags[0] = lc $subtags[0];
    $subtags[1] =~ s/^(\w)(\w+)/uc($1) . lc($2)/e if $subtags[1];
    $subtags[2] = uc $subtags[2] if $subtags[2];
    $subtags[3] = lc $subtags[3] if $subtags[3];

    ##XXX Maybe more canonicalizations here.

    ## Check subtags,
    # won't support language extension subtags.
    return unless $subtags[0] =~ /^[a-z]{2,3}$/;

    # won't allow multiple variant subtags.
    $subtags[3] =~ s/-.+// if $subtags[3];

    ##XXX Maybe more checks here.

    return @subtags if wantarray;
    return join '-', grep {$_} @subtags;
}

sikeda's avatar
sikeda committed
187
sub implicated_langs {
188
    my @langs = @_;
sikeda's avatar
sikeda committed
189
    die 'missing langs parameter' unless @langs;
190
191
192
193

    my @implicated_langs = ();

    foreach my $lang (@langs) {
sikeda's avatar
sikeda committed
194
        my @subtags = canonic_lang($lang);
195
196
        while (@subtags) {
            my $l = join '-', grep {$_} @subtags;
197
            @implicated_langs = ((grep { $_ ne $l } @implicated_langs), $l);
198
199
200
201
202
203
204

            ## Workaround:
            ## - "zh-Hans-CN", "zh-Hant-TW", ... may occasionally be
            ##   identified with "zh-CN", "zh-TW" etc.  Add them to
            ##   implication list.
            if ($l =~ /^zh-(Hans|Hant)-[A-Z]{2}\b/) {
                $l = join '-', grep {$_} @subtags[0, 2 .. $#subtags];
205
206
                @implicated_langs =
                    ((grep { $_ ne $l } @implicated_langs), $l);
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
            }

            1 until pop @subtags;
        }
    }

    return @implicated_langs;
}

## Parses content of HTTP 1.1 Accept-Charset, Accept-Encoding or
## Accept-Language request header field.
## Returns an array of arrayrefs [ITEM, WEIGHT].
##
## NOTE: This might be moved to utility package such as tools.pm.
sub parse_http_accept_string {
    my $accept_string = shift || '';

    $accept_string =~ s/^\s+//;
    $accept_string =~ s/\s+$//;
    $accept_string ||= '*';
    my @pairs = split /\s*,\s*/, $accept_string;

    my @ret = ();
    foreach my $pair (@pairs) {
        my ($item, $weight) = split /\s*;\s*/, $pair, 2;
        if (    defined $weight
            and $weight =~ s/^q\s*=\s*//i
            and $weight =~ /^(\d+(\.\d*)?|\.\d+)$/) {
            $weight += 0.0;
        } else {
            $weight = 1.0;
        }
        push @ret, [$item => $weight];
    }
    return @ret;
}

sikeda's avatar
sikeda committed
244
sub negotiate_lang {
245
    my $accept_string = shift || '*';
sikeda's avatar
sikeda committed
246
    my @supported_languages = grep {$_} map { split /[\s,]+/, $_ } @_;
247
248
249
250

    ## parse Accept-Language: header field.
    ## unknown languages are ignored.
    my @accept_languages =
sikeda's avatar
sikeda committed
251
        grep { $_->[0] eq '*' or $_->[0] = canonic_lang($_->[0]) }
252
253
254
255
256
257
258
        parse_http_accept_string($accept_string);
    return unless @accept_languages;

    ## try to find the best language.
    my $best_lang   = undef;
    my $best_weight = 0.0;
    foreach my $supported_lang (@supported_languages) {
sikeda's avatar
sikeda committed
259
        my @supported_pfxs = implicated_langs($supported_lang);
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
        foreach my $pair (@accept_languages) {
            my ($accept_lang, $weight) = @$pair;
            if ($accept_lang eq '*'
                or grep { $accept_lang eq $_ } @supported_pfxs) {
                unless ($best_lang and $weight <= $best_weight) {
                    $best_lang   = $supported_pfxs[0];    # canonic form
                    $best_weight = $weight;
                }
            }
        }
    }

    return $best_lang;
}

##sub GetSupportedLanguages {
##DEPRECATED: use tools::get_supported_languages().
## Supported languages are defined by 'supported_lang' sympa.conf parameter.

sikeda's avatar
sikeda committed
279
280
281
282
## Old name: PushLang()
sub push_lang {
    my $self  = shift;
    my @langs = @_;
283

sikeda's avatar
sikeda committed
284
285
    push @{$self->{previous_lang}}, $self->get_lang;
    $self->set_lang(@langs);
286
287
288
289

    return 1;
}

sikeda's avatar
sikeda committed
290
291
292
293
294
295
296
297
## Old name: PopLang()
sub pop_lang {
    my $self = shift;

    die 'calling pop_lang() without push_lang()'
        unless @{$self->{previous_lang}};
    my $lang = pop @{$self->{previous_lang}};
    $self->set_lang($lang);
298
299
300
301

    return 1;
}

sikeda's avatar
sikeda committed
302
303
304
305
## Old name: SetLang()
sub set_lang {
    my $self  = shift;
    my @langs = @_;
306
307
    my $locale;

sikeda's avatar
sikeda committed
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
    foreach my $lang (@langs) {
        # Canonicalize lang.
        # Note: 'en' is always allowed.  Use 'en-US' and so on to provide NLS
        # for English.
        next unless $lang = canonic_lang($lang);

        # Try to set POSIX locale and gettext locale, and get lang actually
        # set.
        # Note: Macrolanguage 'zh', 'zh-Hans' or 'zh-Hant' may fallback to
        # lang with available region.
        if ($locale = _resolve_gettext_locale(lang2locale($lang))) {
            ($lang) =
                grep { lang2locale($_) eq $locale } implicated_langs($lang);
        } elsif ($lang =~ /^zh\b/) {
            my @rr;
            if ($lang =~ /^zh-Hans\b/) {
                @rr = qw(CN SG  HK MO TW);    # try simp. first
            } elsif ($lang =~ /^zh-Hant\b/) {
                @rr = qw(HK MO TW  CN SG);    # try trad. first
            } else {
                @rr = qw(CN HK MO SG TW);
            }
            foreach my $rr (@rr) {
                $lang = "zh-$rr";
                last if $locale = _resolve_gettext_locale(lang2locale($lang));
            }
334
335
        }

sikeda's avatar
sikeda committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
        next unless $locale and $lang;

        # The locale is the gettext catalog name; lang is the IETF language
        # tag.  Ex: locale = pt_BR ; lang = pt-BR
        # locale_numeric and locale_time are POSIX locales for LC_NUMERIC and
        # LC_TIME catogories, respectively.  As of 6.2b, they became optional:
        # If setting each of them failed, 'C' locale will be set.
        $self->{lang}   = $lang;
        $self->{locale} = $locale;
        $self->{locale_numeric} =
            _find_posix_locale(POSIX::LC_NUMERIC(), $locale)
            || 'C';
        $self->{locale_time} = _find_posix_locale(POSIX::LC_TIME(), $locale)
            || 'C';

        return $lang;
    }
353

sikeda's avatar
sikeda committed
354
    return;
355
356
}

sikeda's avatar
sikeda committed
357
## Trys to set gettext locale and returns actually set locale.
358
## Mandatory parameter is gettext locale name.
sikeda's avatar
sikeda committed
359
sub _resolve_gettext_locale {
360
361
    my $locale = shift or die 'missing locale parameter';

sikeda's avatar
sikeda committed
362
363
    # 'en' is always allowed.
    return $locale if $locale eq 'en';
364
365
366
367
368
369
370
371

    # Workaround:
    # - "nb" and "nn" are recommended not to have "_NO" region suffix:
    #   Both of them are official languages in Norway.  However, current Sympa
    #   provides "nb_NO" NLS catalog.
    $locale =~ s/^(nb|nn)\b/${1}_NO/;

    ## Check if catalog is loaded.
sikeda's avatar
sikeda committed
372
373
374
375
376
377
378
379
380
381
382
    local %ENV;
    $ENV{'LANGUAGE'} = $locale;
    my $metadata = Locale::Messages::gettext('');    # get header

    unless ($metadata) {
        ## If a sub-locale of 'en' (en-CA, en@shaw, ...) failed, fallback to
        ## 'en'.  Otherwise fails.
        if ($locale =~ /^en(?![a-z])/) {
            $locale = 'en';
        } else {
            return;
383
        }
sikeda's avatar
sikeda committed
384
385
386
    } elsif ($metadata =~ /(?:\A|\n)Language:\s*([\@\w]+)/i) {
        ## Get precise name of gettext locale if possible.
        $locale = $1;
387
388
389
390
391
392
393
394
    }

    ## Workaround for "nb" and "nn": See above.
    $locale =~ s/^(nb|nn)_NO\b/$1/;

    return $locale;
}

sikeda's avatar
sikeda committed
395
396
397
398
# Trys to set POSIX locale which affects to strftime, sprintf etc.
sub _find_posix_locale {
    my $type   = shift;
    my $locale = shift;
399

sikeda's avatar
sikeda committed
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
    # Special case: 'en' is an alias of 'C' locale.  Use 'en_US' and so on for
    # real English.
    return 'C' if $locale eq 'en';

    my $orig_locale = POSIX::setlocale($type);

    ## From "ll@modifier", gets "ll", "ll_RR" and "@modifier".
    my ($loc, $mod) = split /(?=\@)/, $locale, 2;
    my $machloc = $loc;
    $machloc =~ s/^([a-z]{2,3})(?!_)/$lang2oldlocale{$1} || $1/e;
    $mod ||= '';

    ## Set POSIX locale
    my $posix_locale;
    my @try;

    ## Add codeset.
    ## UpperCase required for FreeBSD; dashless required on HP-UX;
    ## null codeset is last resort.
    foreach my $cs ('.utf-8', '.UTF-8', '.utf8', '') {
        ## Truncate locale similarly in gettext: full locale, and omit
        ## region then modifier.
        push @try,
            map { sprintf $_, $cs }
            ("$machloc%s$mod", "$loc%s$mod", "$loc%s");
    }
    foreach my $try (@try) {
        if (POSIX::setlocale($type, $try)) {
            $posix_locale = $try;
            last;
        }
    }

    POSIX::setlocale($type, $orig_locale);

    return $posix_locale;
}
437

sikeda's avatar
sikeda committed
438
439
440
441
442
443
444
445
## Old name: GetLangName()
## Note: Optional $lang argument was deprecated.
sub native_name {
    my $self = shift;
    die 'extra argument(s)' if @_;
    my $name;

    unless ($self->{lang} and $self->{lang} ne 'en') {
446
447
        $name = 'English';
    } else {
sikeda's avatar
sikeda committed
448
449
450
451
        ## Workaround for nb/nn.
        my $locale = $self->{locale};
        $locale =~ s/^(nb|nn)\b/${1}_NO/;

452
        local %ENV;
sikeda's avatar
sikeda committed
453
        $ENV{'LANGUAGE'} = $locale;
454
455
        my $metadata = Locale::Messages::gettext('');    # get header

sikeda's avatar
sikeda committed
456
        if ($metadata =~ /(?:\A|\n)Language-Team:\s*(.+)/i) {
457
458
459
460
461
462
463
464
            $name = $1;
            $name =~ s/\s*\<\S+\>//;
        }
    }

    return (defined $name and $name =~ /\S/) ? $name : '';
}

sikeda's avatar
sikeda committed
465
466
467
468
## Old name: GetLang()
sub get_lang {
    my $self = shift;
    return $self->{lang} || 'en';    # the last resort
469
470
}

sikeda's avatar
sikeda committed
471
472
# DEPRECATED: use tools::lang2charset().
# sub GetCharset;
473

sikeda's avatar
sikeda committed
474
## DEPRECATED: Use canonic_lang().
475
476
477
478
## sub Locale2Lang;

# Internal function.
# Convert language tag to gettext locale name.
sikeda's avatar
sikeda committed
479
sub lang2locale {
480
481
482
483
484
    my $lang = shift;
    my $locale;
    my @subtags;

    ## unknown format.
sikeda's avatar
sikeda committed
485
    return unless @subtags = canonic_lang($lang);
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503

    ## convert from "ll-Scri-RR" to "ll_RR@scriptname", or
    ## from "ll-RR-variant" to "ll_RR@variant".
    $locale = $subtags[0];
    if ($subtags[2]) {
        $locale .= '_' . $subtags[2];
    }
    if ($subtags[1]) {
        $locale .= '@' . ($script2modifier{$subtags[1]} || $subtags[1]);
    } elsif ($subtags[3]) {
        $locale .= '@' . $subtags[3];
    }

    return $locale;
}

# Internal function.
# Get language tag from old-style "locale".
sikeda's avatar
sikeda committed
504
505
# Note: Old name is Locale2Lang().
# Note: Use canonic_lang().
506
sub _oldlocale2lang {
sikeda's avatar
sikeda committed
507
508
    my $oldlocale = shift;
    my @parts = split /[\W_]/, $oldlocale;
509
510
    my $lang;

sikeda's avatar
sikeda committed
511
    if ($lang = {reverse %lang2oldlocale}->{$oldlocale}) {
512
513
514
515
516
517
518
519
        return $lang;
    } elsif (scalar @parts > 1 and length $parts[1]) {
        return join '-', lc $parts[0], uc $parts[1];
    } else {
        return lc $parts[0];
    }
}

sikeda's avatar
sikeda committed
520
521
522
# Convert language tag to old style "locale".
# Note: This function in earlier releases was named Lang2Locale().
sub lang2oldlocale {
523
    my $lang = shift;
sikeda's avatar
sikeda committed
524
    my $oldlocale;
525
526
527
    my @subtags;

    ## unknown format.
sikeda's avatar
sikeda committed
528
    return unless @subtags = canonic_lang($lang);
529
530
531
532
533
534
535
536
537
538
539
540
541

    ## 'zh-Hans' and 'zh-Hant' cannot map to useful POSIX locale.  Map them to
    ## 'zh_CN' and 'zh_TW'.
    ## 'zh' cannot map.
    if ($subtags[0] eq 'zh' and $subtags[1] and not $subtags[2]) {
        if ($subtags[1] eq 'Hans') {
            $subtags[2] = 'CN';
        } elsif ($subtags[1] eq 'Hant') {
            $subtags[2] = 'TW';
        }
    }

    unless ($subtags[2]) {
sikeda's avatar
sikeda committed
542
543
        if ($lang2oldlocale{$subtags[0]}) {
            return $lang2oldlocale{$subtags[0]};
544
545
546
547
548
549
550
551
        }
    } else {
        return join '_', $subtags[0], $subtags[2];
    }
    ## unconvertible locale name
    return;
}

sikeda's avatar
sikeda committed
552
553
# DEPRECATED: merged to tt2::maketext().
# sub maketext;
554
555
556

# Note: older name is sympa_dgettext().
sub dgettext {
sikeda's avatar
sikeda committed
557
    my $self       = shift;
558
    my $textdomain = shift;
sikeda's avatar
sikeda committed
559
    my $msgid      = shift;
560

sikeda's avatar
sikeda committed
561
562
563
    # Returns meta information on the catalog.
    # Note: currently, charset is always 'utf-8'; encoding won't be used.
    unless (defined $msgid) {
564
        return;
sikeda's avatar
sikeda committed
565
    } elsif ($msgid eq '') {    # prevents meta information to be returned
566
        return '';
sikeda's avatar
sikeda committed
567
    } elsif ($msgid eq '_language_') {
sikeda's avatar
sikeda committed
568
        return $self->native_name;
sikeda's avatar
sikeda committed
569
570
571
572
    } elsif ($msgid eq '_charset_') {
        return 'UTF-8';
    } elsif ($msgid eq '_encoding_') {
        return '8bit';
573
574
    }

sikeda's avatar
sikeda committed
575
576
577
578
579
580
    return $msgid unless $self->{lang} and $self->{lang} ne 'en';

    ## Workaround for nb/nn.
    my $locale = $self->{locale};
    $locale =~ s/^(nb|nn)\b/${1}_NO/;

sikeda's avatar
sikeda committed
581
    local %ENV;
sikeda's avatar
sikeda committed
582
    $ENV{'LANGUAGE'} = $locale;
sikeda's avatar
sikeda committed
583
    return Locale::Messages::dgettext($textdomain, $msgid);
584
585
586
}

sub gettext {
sikeda's avatar
sikeda committed
587
    my $self  = shift;
sikeda's avatar
sikeda committed
588
    my $msgid = shift;
589

sikeda's avatar
sikeda committed
590
591
592
    # Returns meta information on the catalog.
    # Note: currently, charset is always 'utf-8'; encoding won't be used.
    unless (defined $msgid) {
593
        return;
sikeda's avatar
sikeda committed
594
    } elsif ($msgid eq '') {    # prevents meta information to be returned
595
        return '';
sikeda's avatar
sikeda committed
596
    } elsif ($msgid eq '_language_') {
sikeda's avatar
sikeda committed
597
        return $self->native_name;
sikeda's avatar
sikeda committed
598
599
600
601
    } elsif ($msgid eq '_charset_') {
        return 'UTF-8';
    } elsif ($msgid eq '_encoding_') {
        return '8bit';
602
603
    }

sikeda's avatar
sikeda committed
604
605
606
607
608
609
    return $msgid unless $self->{lang} and $self->{lang} ne 'en';

    ## Workaround for nb/nn.
    my $locale = $self->{locale};
    $locale =~ s/^(nb|nn)\b/${1}_NO/;

sikeda's avatar
sikeda committed
610
    local %ENV;
sikeda's avatar
sikeda committed
611
    $ENV{'LANGUAGE'} = $locale;
sikeda's avatar
sikeda committed
612
    return Locale::Messages::gettext($msgid);
613
614
}

sikeda's avatar
sikeda committed
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
sub gettext_sprintf {
    my $self   = shift;
    my $format = shift;
    my @args   = @_;

    my $orig_locale = POSIX::setlocale(POSIX::LC_NUMERIC());

    ## if lang has not been set or 'en' is set, fallback to native sprintf().
    unless ($self->{lang} and $self->{lang} ne 'en') {
        POSIX::setlocale(POSIX::LC_NUMERIC(), 'C');
        my $ret = sprintf($format, @args);
        POSIX::setlocale(POSIX::LC_NUMERIC(), $orig_locale);
        return $ret;
    }

    $format = $self->gettext($format);

    POSIX::setlocale(POSIX::LC_NUMERIC(), $self->{locale_numeric});
    my $ret = sprintf($format, @args);
    POSIX::setlocale(POSIX::LC_NUMERIC(), $orig_locale);
    return $ret;
}

638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
my %date_part_names = (
    '%a' => {
        'index'      => 6,
        'gettext_id' => 'Sun:Mon:Tue:Wed:Thu:Fri:Sat'
    },
    '%A' => {
        'index' => 6,
        'gettext_id' =>
            'Sunday:Monday:Tuesday:Wednesday:Thursday:Friday:Saturday'
    },
    '%b' => {
        'index'      => 4,
        'gettext_id' => 'Jan:Feb:Mar:Apr:May:Jun:Jul:Aug:Sep:Oct:Nov:Dec'
    },
    '%B' => {
        'index' => 4,
        'gettext_id' =>
            'January:February:March:April:May:June:July:August:September:October:November:December'
    },
    '%p' => {
        'index'      => 2,
        'gettext_id' => 'AM:PM'
    },
);

sub gettext_strftime {
sikeda's avatar
sikeda committed
664
    my $self   = shift;
665
666
667
    my $format = shift;
    my @args   = @_;

sikeda's avatar
sikeda committed
668
    my $orig_locale = POSIX::setlocale(POSIX::LC_TIME());
669
670

    ## if lang has not been set or 'en' is set, fallback to native strftime().
sikeda's avatar
sikeda committed
671
    unless ($self->{lang} and $self->{lang} ne 'en') {
672
        POSIX::setlocale(POSIX::LC_TIME(), 'C');
sikeda's avatar
sikeda committed
673
674
675
        my $ret = POSIX::strftime($format, @args);
        POSIX::setlocale(POSIX::LC_TIME(), $orig_locale);
        return $ret;
676
677
    }

sikeda's avatar
sikeda committed
678
    $format = $self->gettext($format);
679
680

    ## If POSIX locale was not set, emulate format strings.
sikeda's avatar
sikeda committed
681
682
683
    unless ($self->{locale_time}
        and $self->{locale_time} ne 'C'
        and $self->{locale_time} ne 'POSIX') {
684
685
        my %names;
        foreach my $k (keys %date_part_names) {
sikeda's avatar
sikeda committed
686
687
688
689
            $names{$k} = [
                split /:/,
                $self->gettext($date_part_names{$k}->{'gettext_id'})
            ];
690
691
692
693
694
695
696
697
698
699
700
701
702
703
        }
        $format =~ s{(\%[EO]?.)}{
	    my $index;
	    if ($names{$1} and
		defined($index = $args[$date_part_names{$1}->{'index'}])) {
		$index = ($index < 12) ? 0 : 1
		    if $1 eq '%p';
		$names{$1}->[$index];
	    } else {
		$1;
	    }
	}eg;
    }

sikeda's avatar
sikeda committed
704
705
706
707
    POSIX::setlocale(POSIX::LC_TIME(), $self->{locale_time});
    my $ret = POSIX::strftime($format, @args);
    POSIX::setlocale(POSIX::LC_TIME(), $orig_locale);
    return $ret;
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
}

1;
__END__

=encoding utf-8

=head1 NAME

Sympa::Language - Handling languages and locales

=head1 DESCRIPTION

This package provides interfaces for i18n (internationalization) of Sympa.

The language tags are used to determine each language.
A language tag consists of one or more subtags: language, script, region and
variant.  Below are some examples.

=over 4

=item *

C<ar> - Arabic language

=item *

C<ain> - Ainu language

=item *

C<pt-BR> - Portuguese language in Brazil

=item *

C<be-Latn> - Belarusian language in Latin script

=item *

C<ca-ES-valencia> - Valencian variant of Catalan

=back

Other two sorts of identifiers are derived from language tags:
gettext locales and POSIX locales.

The gettext locales determine each translation catalog.
It consists of one to three parts: language, territory and modifier.
For example, their equivalents of language tags above are C<ar>, C<ain>,
C<pt_BR>, C<be@latin> and C<ca_ES@valencia>, respectively.

The POSIX locales determine each I<locale>.  They have similar forms to
gettext locales and are used by this package internally.

=head2 Functions

=head3 Manipulating language tags

=over 4

sikeda's avatar
sikeda committed
768
=item canonic_lang ( $lang )
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793

I<Function>.
Canonicalizes language tag according to RFC 5646 (BCP 47) and returns it.

Parameter:

=over

=item $lang

Language tag or similar thing.
Old style "locale" by Sympa (see also L</Compatibility>) will also be
accepted.

=back

Returns:

Canonicalized language tag.
In array context, returns an array
C<(I<language>, I<script>, I<region>, I<variant>)>.
For malformed inputs, returns C<undef> or empty array.

See L</CAVEATS> about details on format.

sikeda's avatar
sikeda committed
794
=item implicated_langs ( $lang, ... )
795
796
797
798
799
800
801
802
803
804
805
806
807
808

I<Function>.
Gets a list of each language $lang itself and its "super" languages.
For example:
If C<'tyv-Latn-MN'> is given, this function returns
C<('tyv-Latn-MN', 'tyv-Latn', 'tyv')>.

Parameters:

=over

=item $lang, ...

Language tags or similar things.
sikeda's avatar
sikeda committed
809
They will be canonicalized by L</canonic_lang>()
810
811
812
813
814
815
816
and malformed inputs will be ignored.

=back

Returns:

A list of implicated languages, if any.
sikeda's avatar
sikeda committed
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
If no $lang arguments were given, this function will die.

=item lang2locale ( $lang )

I<Function>, I<internal use>.
Convert language tag to gettext locale name
(see also L</"Native language support (NLS)">).
This function may be useful if you want to know internal information such as
name of catalog file.

Parameter:

=over

=item $lang

Language tag or similar thing.

=back

Returns:

The gettext locale name.
For malformed inputs returns C<undef>.
841

sikeda's avatar
sikeda committed
842
=item negotiate_lang ( $string, $lang, ... )
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867

I<Function>.
Get the best language according to the content of C<Accept-Language:> HTTP
request header field.

Parameters:

=over

=item $string

Content of the header.  If it is false value, C<'*'> is assumed.

=item $lang, ...

Acceptable languages.

=back

Returns:

The best language or, if negotiation failed, C<undef>.

=back

sikeda's avatar
sikeda committed
868
869
870
871
872
873
874
=head3 Compatibility

As of Sympa 6.2b, language tags are used to specify languages along with
locales.  Earlier releases used POSIX locale names.

These functions are used to migrate data structures and configurations of
earlier versions.
875
876
877

=over 4

sikeda's avatar
sikeda committed
878
=item lang2oldlocale ( $lang )
879
880

I<Function>.
sikeda's avatar
sikeda committed
881
Convert language tag to old-style "locale".
882
883
884
885
886
887
888
889
890
891
892
893
894

Parameter:

=over

=item $lang

Language tag or similar thing.

=back

Returns:

sikeda's avatar
sikeda committed
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
Old-style "locale".
If corresponding locale could not be determined, returns C<undef>.

Note:
In earlier releases this function was named Lang2Locale()
(don't confuse with L</lang2locale>()).

=back

=head2 Methods

=over 4

=item instance ( )

I<Constructor>.
Gets the singleton instance of L<Sympa::Language> class.

=back

=head3 Getting/setting language context

=over 4

=item push_lang ( $lang, ... )

I<Instance method>.
Set current language by L</set_lang>() keeping the previous one;
it can be restored with L</pop_lang>().

Parameter:

=over

=item $lang, ...

Language tags or similar things.

=back

Returns:

937
938
Always C<1>.

sikeda's avatar
sikeda committed
939
=item pop_lang
940

sikeda's avatar
sikeda committed
941
I<Instance method>.
942
943
944
945
946
947
948
949
950
951
Restores previous language.

Parameters:

None.

Returns:

Always C<1>.

sikeda's avatar
sikeda committed
952
=item set_lang ( $lang, ... )
953

sikeda's avatar
sikeda committed
954
I<Instance method>.
955
956
957
958
959
960
961
Sets current language along with translation catalog,
and POSIX locale if possible.

Parameter:

=over

sikeda's avatar
sikeda committed
962
=item $lang, ...
963

sikeda's avatar
sikeda committed
964
Language tags or similer things.
965
966
Old style "locale" by Sympa (see also L</Compatibility>) will also be
accepted.
sikeda's avatar
sikeda committed
967
968
969
970
If multiple tags are specified, this function trys each of them in order.

Note that C<'en'> will always succeed.  Thus, it may be useful to put it at
the end of argument list.
971
972
973
974
975

=back

Returns:

sikeda's avatar
sikeda committed
976
Canonic language tag actually set or, if no usable catalogs were found,
977
978
979
980
981
982
983
984
985
C<undef>.

Note that the language actually set may not be identical to the parameter
$lang, even when latter has been canonicalized.

The language tag C<'en'> is special:
it is used to set C<'C'> locale and will succeed always.

Note:
sikeda's avatar
sikeda committed
986
This function of Sympa 6.2a or earlier returned old style "locale" names.
987

sikeda's avatar
sikeda committed
988
=item native_name ( )
989

sikeda's avatar
sikeda committed
990
I<Instance method>.
991
992
Get the name of the language, ie the one defined in the catalog.

sikeda's avatar
sikeda committed
993
Parameters:
994

sikeda's avatar
sikeda committed
995
None.
996
997
998
999
1000

Returns:

Name of the language in native notation.
If it was not found, returns an empty string C<''>.
For faster browsing, not all history is shown. View entire blame