blib/lib/CGI/Lingua.pm untested

filter: Statementstmt 0.0% 0 / 1209 Branchbran 0.0% 0 / 712 Conditioncond 0.0% 0 / 418 MC/DCmcdc 0.0% 0 / 254 Subroutinesub 0.0% 0 / 88 Podpod 0.0% 0 / 59 totaltotal 0.0% 0 / 2740 CC 317 SCAR 63.4
CC
317
Cov
0%
country
2970.0
new
650.0
_find_language_from_ip
650.0
CRAP 564.0
1 package CGI::Lingua;
2  
3 use warnings;
4 use strict;
5  
6 use Carp (); # fully qualified calls: nothing imported into this package
7 use Object::Configure 0.25;
8 use Params::Get 0.17; # 0.15 fast-path: unblessed hashref returned directly
9 use Readonly;
10 use Scalar::Util (); # fully qualified, so $obj->blessed() is not a method
11 use JSON::PP ();
12 use Class::Autouse qw{
13 Locale::Language
14 Locale::Object::Country
15 Locale::Object::DB
16 I18N::AcceptLanguage
17 };
18  
19 our $VERSION = '0.88';
20  
21 # Post-release roadmap (from the 0.87 gap analysis).
22 #
23 # Upstream services
24 # TODO: geoplugin.net has no free tier any more, so that look-up is dead code
25 # for nearly everyone. Make the web providers configurable
26 # (geo_providers => [...]) with a built-in client for a free HTTPS
27 # service, or drop geoplugin.
28 # TODO: ip-api.com is plain HTTP and limited to 45 requests a minute; answers
29 # are validated but can be read and altered in transit. Allow an API key
30 # / HTTPS provider and add rate limiting or back-off.
31 # TODO: Add a timeout option: a slow upstream holds the request for LWP's
32 # default of 180 seconds.
33 #
34 # Features
35 # TODO: native_name() ("Francais" for French, in that language's script),
36 # plus bcp47() / lang_attribute() for the HTML lang attribute.
37 # TODO: Number, currency and date formatting helpers from the negotiated
38 # locale (CLDR via Locale::CLDR, optional).
39 # TODO: Script detection (zh-Hant / zh-Hans, sr-Latn) and RTL by script
40 # rather than by language.
41 # TODO: Proper 3-letter and UN M.49 regions (es-419, en-029); these are the
42 # remaining TODO tests (t/es_419.t, t/en_029.t).
43 # TODO: A Content-Language / Vary: Accept-Language header helper, and RFC
44 # 4647 "lookup" fallback chains.
45 # TODO: PSGI / Plack: middleware or a from_env(\%env) constructor that does
46 # not depend on %ENV, removing the "country() reads REMOTE_ADDR when
47 # called" pitfall.
48 #
49 # Technical debt
50 # TODO: Split this file into ::Negotiate, ::Geo (one class per provider) and
51 # ::Cache; most of the mocking pitfalls in the tests come from the
52 # coupling.
53 # TODO: Replace the three geo sentinels and the two package sentinels
54 # ($_locale_object_db_ok, $_have_dvip) with one capability probe, cached
55 # per process.
56 # TODO: Enforce privacy with Sub::Private once t/function.t and
57 # t/extended_tests.t stop calling _-methods directly.
58 # TODO: Structured log events (a code plus fields) instead of English
59 # strings, so applications can translate and filter them.
60 # TODO: t/integration.t takes about 15 seconds because of its ~45 child
61 # processes; run them in parallel or reuse one child per combination.
62  
63 # Gathering magic strings here makes behavioural changes one-edit operations.
64  
65 Readonly my $CACHE_TTL_LONG => '1 month';
66 Readonly my $CACHE_TTL_SHORT => '1 hour';
67 Readonly my $CACHE_NS => 'CGI::Lingua:'; # namespace prefix for every key
68 Readonly my $BROKEN_GEOIPFREE => '45.128.139.41'; # https://github.com/bricas/geo-ipfree/issues/10
69 Readonly my $BAIDU_SUBNET => '185.10.104.0/22';# RT-86809: Baidu misreports as EU
70 Readonly my $DEPRECATED_EN_UK => 'en-uk'; # some browsers still send this
71 Readonly my $CANONICAL_EN_GB => 'en-gb';
72 Readonly my $ACCEPT_LANG_MAX => 256; # max bytes we accept from the header
73 Readonly my $UA_MAX => 512; # max bytes we accept from HTTP_USER_AGENT
74 Readonly my $GEO_UNKNOWN => -1; # geo-module sentinel: not yet probed
75 Readonly my $GEO_ABSENT => 0; # geo-module sentinel: unavailable
76 Readonly my $GEO_PRESENT => 1; # geo-module sentinel: loaded OK
77  
78 # Shapes of the values CGI::Lingua keeps in the cache. Anything read back
79 # that does not match is treated as poisoned and discarded. Language and
80 # country names from Locale::Language, Locale::Codes and Locale::Object use
81 # only these characters (e.g. "Cote D'Ivoire", "Modern Greek (1453-)",
82 # "Falkland Islands (The) [Malvinas]"); none of them use < > " & ; / =.
83 Readonly my $NAME_RE => qr/^[A-Za-z][A-Za-z0-9 ,.:'()\[\]\-]{0,99}\z/a; # ":" for "English (Unknown: zz)"
84 Readonly my $NAME_CODE_RE => qr/^[A-Za-z][A-Za-z0-9 ,.'()\[\]\-]{0,99}=[a-z]{2,3}\z/a;
85 Readonly my $LANG_CODE_RE => qr/^[a-z]{2,3}\z/a;
86 Readonly my $COUNTRY_RE => qr/^(?:[a-z]{2}|Unknown)\z/a;
87  
88 # A language list from HTTP_ACCEPT_LANGUAGE or a lang= parameter: the RFC 7231
89 # characters plus "*", spaces and tabs (never CR or LF), at most
90 # $ACCEPT_LANG_MAX bytes. Captures the untainted value.
91 Readonly my $ACCEPT_LANG_RE => qr/^([A-Za-z0-9\-,;=.* \t]{1,$ACCEPT_LANG_MAX})\z/a;
92  
93 # A locale from LC_ALL, LC_MESSAGES or LANG, as POSIX names them:
94 # language[_territory][.codeset][@modifier], e.g. "en_US.UTF-8",
95 # "sr_RS@latin", "C". The characters only; captures the untainted value.
96 Readonly my $LOCALE_RE => qr/^([A-Za-z0-9_.\-@]{1,$ACCEPT_LANG_MAX})\z/a;
97  
98 # The language tag a locale stands for: its language, and its territory if it
99 # has one ("en_US.UTF-8" is en-US). A hyphen is taken too, for "LANG=en-US".
100 # "C", "POSIX" and other names that are not a language do not match.
101 Readonly my $LOCALE_TAG_RE => qr/^([A-Za-z]{2,3})(?:[_-]([A-Za-z]{2}|[0-9]{3}))?(?:\.[A-Za-z0-9_\-]+)?(?:\@[A-Za-z0-9_\-]+)?\z/a;
102  
103 # The locale variables, in the order POSIX consults them for the language of
104 # messages: the first that is set and not empty decides.
105 Readonly my @LOCALE_VARS => qw(LC_ALL LC_MESSAGES LANG);
106  
107 # A supported-list entry: a language tag such as "en", "en-gb", "es-419" or
108 # "zh-Hant" (an underscore is accepted for "en_gb"). "english" is not one.
109 Readonly my $SUPPORTED_RE => qr/^[A-Za-z]{2,3}(?:[-_][A-Za-z0-9]{2,8})*\z/a;
110  
111 # An IP address as accepted from REMOTE_ADDR, before Data::Validate::IP checks
112 # it properly: dotted quad, or IPv6 including ::ffff:a.b.c.d. Captures it.
113 Readonly my $IP_SHAPE_RE => qr/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|[0-9a-fA-F:]{2,39}|[0-9a-fA-F:]{2,30}:(?:\d{1,3}\.){3}\d{1,3})\z/a;
114  
115 # An IPv6 address has eight 16-bit groups of one to four hex digits (_is_ipv6)
116 Readonly my $IPV6_GROUPS => 8;
117 Readonly my $IPV6_GROUP_RE => qr/^[0-9A-Fa-f]{1,4}\z/;
118  
119 # Fields that DESTROY saves and new() restores, with the shape each must have
120 # time_zone(): IANA zone names (e.g. "America/New_York", "Etc/GMT+8", "UTC")
121 Readonly my $ZONE_RE => qr/^[A-Za-z][A-Za-z0-9_+\-\/]{0,50}\z/a;
122 Readonly my $ZONE_FILE_MAX => 256; # bytes read from $ZONE_FILE; a zone name is far shorter
123  
124 # File holding the system time zone, read by time_zone() when there is no
125 # REMOTE_ADDR. A package variable (not Readonly) so tests can point it at a
126 # hostile file with "local $CGI::Lingua::ZONE_FILE = ...".
127 our $ZONE_FILE = '/etc/timezone';
128  
129 # Where _load_geoip() looks for the legacy MaxMind GeoIP.dat used by Geo::IP;
130 # the first readable regular file wins. A package variable so a test or a
131 # site can point it elsewhere ("local @CGI::Lingua::GEOIP_DAT = ...").
132 our @GEOIP_DAT = (
133 (($^O eq 'MSWin32') ? ('c:/GeoIP/GeoIP.dat') : ()),
134 '/usr/share/GeoIP/GeoIP.dat',
135 '/usr/local/share/GeoIP/GeoIP.dat',
136 );
137  
138 # Where _load_mmdb() looks for a MaxMind GeoIP2 / GeoLite2 database (.mmdb).
139 # Unlike GeoIP.dat these are still updated, so country() and time_zone() try
140 # one first. City databases come first because they also hold the time zone.
141 # /var/lib/GeoIP is where geoipupdate writes on Debian and Ubuntu. A package
142 # variable so a test or a site can point it elsewhere.
143 our @GEOIP2_MMDB = map {
144 my $dir = $_;
145 map { "$dir/$_.mmdb" } qw(GeoIP2-City GeoLite2-City GeoIP2-Country GeoLite2-Country)
146 } (($^O eq 'MSWin32') ? ('c:/GeoIP') : ()), '/var/lib/GeoIP', '/usr/share/GeoIP', '/usr/local/share/GeoIP';
147  
148 # Modules that can read a .mmdb file, in order of preference. Both have
149 # new(file => ...) and record_for_address($ip), returning the same hashes.
150 # IP::Geolocation::MMDB wraps the libmaxminddb C library; MaxMind::DB::Reader
151 # is the pure-Perl reader that GeoIP2::Database::Reader is built on.
152 Readonly my @MMDB_READERS => ('IP::Geolocation::MMDB', 'MaxMind::DB::Reader');
153  
154 Readonly my %RESTORABLE => (
155 _slanguage => $NAME_RE,
156 _rlanguage => $NAME_RE,
157 _sublanguage => $NAME_RE,
158 _slanguage_code_alpha2 => $LANG_CODE_RE,
159 _sublanguage_code_alpha2 => $LANG_CODE_RE,
160 _country => $COUNTRY_RE,
161 );
162  
163 # Package-level sentinel for Locale::Object's SQLite database. undef = not yet
164 # probed; 0 = database absent (Windows installers often omit it); 1 = available.
165 # Package-level (not per-object) because the database either exists on the
166 # filesystem or it doesn't -- there is no per-request variability.
167 my $_locale_object_db_ok;
168  
169 # Package-level sentinel for Data::Validate::IP / NetAddr::IP availability.
170 # NetAddr::IP::UtilPP fails to build on Windows (mask4to6 bad-argument error),
171 # which cascades to Data::Validate::IP. undef = not yet probed; 0 = broken;
172 # 1 = available. On first country() call we try to load the module and, if it
173 # fails, install pure-Perl aliases for the four functions we use.
174 my $_have_dvip;
175  
176 # Short-name overrides used when Locale::Object's database is absent and we
177 # fall back to Locale::Codes::Country. Locale::Codes carries full ISO official
178 # names (e.g. "United Kingdom of Great Britain and Northern Ireland") while
179 # Locale::Object returns the common short form ("United Kingdom"). Only
180 # entries that differ are listed; everything else comes from Locale::Codes.
181 my %COUNTRY_SHORT_NAMES = (
182 bo => 'Bolivia',
183 cd => 'Democratic Republic of the Congo',
184 fk => 'Falkland Islands',
185 fm => 'Micronesia',
186 gb => 'United Kingdom',
187 ir => 'Iran',
188 kp => 'North Korea',
189 kr => 'South Korea',
190 md => 'Moldova',
191 nl => 'Netherlands',
192 ps => 'Palestine',
193 tw => 'Taiwan',
194 tz => 'Tanzania',
195 us => 'United States',
196 ve => 'Venezuela',
197 );
198  
199 Readonly my %RTL_LANGS => (map { $_ => 1 } # ISO 639-1 codes whose primary script is RTL
200 qw(ar dv fa he ku ps sd ug ur yi));
201  
202 =head1 NAME
203  
204 CGI::Lingua - Create a multilingual web page
205  
206 =head1 VERSION
207  
208 Version 0.88
209  
210 =cut
211  
212 =head1 SYNOPSIS
213  
214 Your website tells CGI::Lingua which languages it can show.
215 CGI::Lingua looks at what the visitor's web browser asks for,
216 and tells your website which of its languages to use.
217  
218 =head2 Pick a language for the page
219  
220 use CGI::Lingua;
221  
222 # The site has pages in English and French
223 my $l = CGI::Lingua->new(supported => ['en', 'fr']);
224  
225 my $language = $l->language(); # 'English', 'French' or 'Unknown'
226 if($language eq 'English') {
227 print "<p>Hello</p>\n";
228 } elsif($language eq 'French') {
229 print "<p>Bonjour</p>\n";
230 } else {
231 # The visitor wants a language that the site does not have
232 my $wanted = $l->requested_language(); # e.g. 'German'
233 print "<p>Sorry, this page is not available in $wanted.</p>\n";
234 }
235  
236 =head2 Use the short code to choose a file or template
237  
238 my $l = CGI::Lingua->new(supported => ['en-gb', 'en-us', 'fr']);
239  
240 my $code = $l->language_code_alpha2() // 'en'; # 'en' or 'fr'
241 my $variant = $l->sublanguage_code_alpha2(); # 'gb', 'us' or undef
242 my $template = defined($variant) ? "$code-$variant.tmpl" : "$code.tmpl";
243  
244 =head2 Show different content for different countries
245  
246 my $l = CGI::Lingua->new(supported => ['en']);
247  
248 my $country = $l->country() // ''; # e.g. 'us', 'ca', 'gb'
249 if($country eq 'us') {
250 print "Call us on 1-800-555-0100\n";
251 } elsif($country eq 'ca') {
252 print "Call us on 1-888-555-0100\n";
253 } else {
254 print "Email us at help\@example.com\n";
255 }
256  
257 =head2 Make it faster with a cache
258  
259 Finding the country of an IP address can be slow.
260 Give CGI::Lingua a L<CHI> cache so that the work is only done once
261 for each visitor.
262  
263 use CHI;
264 use CGI::Lingua;
265  
266 my $cache = CHI->new(
267 driver => 'File',
268 root_dir => '/var/cache/myapp',
269 namespace => 'CGI::Lingua',
270 );
271 my $l = CGI::Lingua->new(supported => ['en', 'fr'], cache => $cache);
272  
273 =head2 Let the visitor choose with a "lang" parameter
274  
275 If you pass a L<CGI::Info> object, a C<lang=fr> parameter in the URL
276 is used before the browser's settings.
277  
278 use CGI::Info;
279 use CGI::Lingua;
280  
281 my $info = CGI::Info->new();
282 my $l = CGI::Lingua->new(supported => ['en', 'fr', 'de'], info => $info);
283 print $l->language(); # 'German' for https://example.com/page?lang=de
284  
285 =head2 Set the HTML "lang" and "dir" attributes
286  
287 my $l = CGI::Lingua->new(supported => ['en', 'ar', 'he']);
288 my $code = $l->language_code_alpha2() // 'en';
289 printf qq{<html lang="%s" dir="%s">\n}, $code, $l->text_direction();
290 # <html lang="ar" dir="rtl"> for an Arabic-speaking visitor
291  
292 =head2 Choose the right plural form
293  
294 my $l = CGI::Lingua->new(supported => ['en', 'ru']);
295 my %messages = (
296 one => '%d file',
297 few => '%d files (few)',
298 many => '%d files (many)',
299 other => '%d files',
300 );
301 my $n = 3;
302 printf $messages{$l->plural_category($n)} . "\n", $n;
303  
304 =head2 Load a translation file
305  
306 # Looks for /var/www/i18n/en-gb.json, then /var/www/i18n/en.json
307 my $l = CGI::Lingua->new(supported => ['en-gb', 'en', 'fr']);
308 if(my $file = $l->translation_file('/var/www/i18n')) {
309 # read and use $file
310 }
311  
312 =head2 Guess the visitor's time zone and locale
313  
314 my $l = CGI::Lingua->new(supported => ['en']);
315 my $tz = $l->time_zone() // 'UTC'; # e.g. 'America/New_York'
316 if(my $locale = $l->locale()) { # a Locale::Object::Country
317 print 'Currency: ', $locale->currency()->code(), "\n";
318 }
319  
320 =head2 Do not guess from the IP address
321  
322 # Only use what the browser asks for; never look up the IP address
323 my $l = CGI::Lingua->new(supported => ['en', 'fr'], dont_use_ip => 1);
324  
325 =head1 DESCRIPTION
326  
327 This section explains, in simple steps, how CGI::Lingua finds the answer.
328  
329 =head2 Finding the language
330  
331 When you first call a language method (for example L</language>),
332 CGI::Lingua looks for the visitor's language in this order:
333  
334 =over 4
335  
336 =item 1. The C<lang> parameter of the L<CGI::Info> object, if you gave one
337 to L</new> with C<info>.
338  
339 =item 2. The C<HTTP_ACCEPT_LANGUAGE> environment variable.
340 The web server sets this from the browser's C<Accept-Language> header,
341 for example C<fr-CA,fr;q=0.9,en;q=0.8>.
342 Languages with a higher C<q> value are tried first.
343 A language with C<q=0> means "not acceptable" (RFC 7231) and is never chosen.
344 Some browsers still send the old tag C<en-uk>; it is treated as C<en-gb>
345 (the code for the United Kingdom is C<gb>), with a warning.
346  
347 =item 3. The locale: C<LC_ALL>, then C<LC_MESSAGES>, then C<LANG>.
348 This is used when you run the program on the command line,
349 for example C<LANG=fr_FR.UTF-8>.
350 As in POSIX, the first of these that is set and not empty decides, so
351 C<LC_ALL=C> means no language even when C<LANG> names one.
352 The locale is read as the language tag it stands for:
353 C<en_US.UTF-8> is C<en-US> (English, United States) and C<de_DE@euro> is
354 C<de-DE>; C<C> and C<POSIX> name no language.
355 Before 0.88 the locale was passed on as it was written, and C<en_US.UTF-8>
356 matched no language.
357  
358 =item 4. The visitor's country (see below).
359 CGI::Lingua uses the official language of that country.
360 This step is skipped when you give C<dont_use_ip> to L</new>.
361  
362 =back
363  
364 It then compares the answer with your C<supported> list.
365 If a visitor asks for C<en-us> and you only support C<en-gb>,
366 CGI::Lingua still chooses English, because the base language is the same.
367 If nothing matches, L</language> returns the string C<'Unknown'>.
368  
369 =head2 Finding the country
370  
371 L</country> tries these sources in order, and stops at the first answer:
372  
373 =over 4
374  
375 =item 1. C<GEOIP_COUNTRY_CODE> (set by Apache's mod_geoip).
376  
377 =item 2. C<HTTP_CF_IPCOUNTRY> (set by Cloudflare).
378  
379 =item 3. A local database: a MaxMind GeoIP2 or GeoLite2 database (see
380 L</@CGI::Lingua::GEOIP2_MMDB>), then L<IP::Country>, then L<Geo::IP>, then
381 L<Geo::IPfree>, if they are installed.
382  
383 =item 4. The geoplugin.net web service.
384  
385 =item 5. A Whois look-up (L<Net::Whois::IP>, then L<Net::Whois::IANA>).
386  
387 =back
388  
389 Steps 3 to 5 use the visitor's IP address from C<REMOTE_ADDR>.
390 Private addresses (such as C<192.168.1.1>) and loopback addresses
391 (such as C<127.0.0.1>) have no country, so the answer is C<undef>.
392  
393 =head2 Remembering answers
394  
395 Each object remembers its answers, so a second call to the same method is fast.
396 If you give a C<cache> to L</new>, answers are also stored in the cache when the
397 object is destroyed. The next object created for the same IP address, the same
398 requested language and the same C<supported> list starts with those answers.
399  
400 =head1 SUBROUTINES/METHODS
401  
402 =head2 new
403  
404 Creates a CGI::Lingua object.
405  
406 You must tell it which languages your website supports, with C<supported>.
407 Each language is a short code, such as C<'en'> (English),
408 C<'fr'> (French) or C<'en-gb'> (British English).
409  
410 You can give the arguments as a list, as a hash reference,
411 as a single array reference (the supported list), or as a single string
412 (one supported language):
413  
414 CGI::Lingua->new(supported => ['en', 'fr']);
415 CGI::Lingua->new({ supported => ['en', 'fr'] });
416 CGI::Lingua->new(['en', 'fr']);
417 CGI::Lingua->new('en');
418  
419 The arguments are:
420  
421 =over 4
422  
423 =item * C<supported> (required)
424  
425 The languages your website supports: one short code (a string of 2 to 5
426 characters) or a reference to an array of language tags.
427 C<supported_languages> is another name for the same argument.
428  
429 Each entry in the array must look like a language tag: two or three letters,
430 optionally followed by subtags, such as C<'en'>, C<'en-gb'>, C<'en_gb'>,
431 C<'es-419'> or C<'zh-Hant'>. Other entries (C<undef>, references, C<''>, or
432 words such as C<'english'>) could never match, so they are dropped with the
433 warning C<"Ignoring '...' in the supported list: not a language code">.
434 An empty list is allowed; L</language> then always returns C<'Unknown'>.
435  
436 =item * C<cache> (optional)
437  
438 An object with C<get()>, C<set()> and C<remove()> methods, such as a L<CHI> object.
439 CGI::Lingua stores its answers here so that later requests are faster.
440 If a call to the cache dies (for example a full disc, an unreachable server,
441 or a L<CHI> object created with C<< on_get_error =E<gt> 'die' >>), CGI::Lingua
442 warns C<"Cache get failed: ..."> (or C<set> / C<remove>) and carries on as if
443 the value was not cached. Any method that uses the cache can give this warning.
444  
445 Everything read back from the cache is checked before it is used, because a
446 cache can be shared with, or written by, other programs. A value that does not
447 have the shape CGI::Lingua stores (for example C<< gb<script> >> as a country, or
448 a hash where a language name should be) is removed and warned about with
449 C<"Discarding malformed cache entry for ...">, and the answer is worked out
450 again.
451  
452 =item * C<config_file> (optional)
453  
454 The path to a configuration file. It is read by L<Object::Configure>.
455 Values in this file B<replace> the arguments that you give to C<new()>
456 (see L</COMMON PITFALLS>).
457  
458 =item * C<logger> (optional)
459  
460 Where to send messages. This can be an object with C<warn()>, C<info()> and
461 C<error()> methods, or any value that L<Object::Configure> accepts
462 (for example an array reference, which collects the messages).
463 It is always changed into a L<Log::Abstraction> object.
464 Without a logger, warnings go to L<Carp>.
465  
466 =item * C<info> (optional)
467  
468 A L<CGI::Info> object (or any object with a C<lang()> method).
469 A C<lang> parameter in the request is then used before the browser's
470 settings. The parameter comes from the visitor, so it is checked like the
471 C<Accept-Language> header (see L</ENCODING>); a value that fails is ignored with
472 the warning C<"lang parameter contains invalid characters; ignoring">.
473  
474 =item * C<dont_use_ip> (optional, default false)
475  
476 When true, CGI::Lingua never guesses the language from the visitor's
477 IP address.
478  
479 =item * C<syslog> (optional)
480  
481 Passed on to the logging configuration.
482  
483 =item * C<debug> (optional, default false)
484  
485 When true, L<I18N::AcceptLanguage> prints debug information.
486  
487 =back
488  
489 If you call C<new()> on an existing object, you get a copy of that object.
490 The arguments you give replace the values in the copy.
491 The copy also keeps any answers that the original has already worked out
492 (see L</COMMON PITFALLS>).
493  
494 =head3 API SPECIFICATION
495  
496 =head4 Input
497  
498 {
499 supported => { type => 'string|arrayref', optional => 0 },
500 supported_languages => { type => 'string|arrayref', optional => 1 },
501 cache => { type => 'object', can => ['get', 'set'], optional => 1 },
502 config_file => { type => 'string', optional => 1 },
503 logger => { type => 'object|arrayref|hashref|string', optional => 1 },
504 info => { type => 'object', can => 'lang', optional => 1 },
505 dont_use_ip => { type => 'boolean', optional => 1 },
506 syslog => { type => 'boolean|hashref', optional => 1 },
507 debug => { type => 'boolean', optional => 1 },
508 }
509  
510 You must give C<supported> or its other name C<supported_languages>.
511 A string must be 2 to 5 characters long.
512  
513 =head4 Output
514  
515 {
516 type => 'object',
517 isa => 'CGI::Lingua',
518 }
519  
520 =head3 EXAMPLE
521  
522 # The most common form: a list of supported codes
523 my $l = CGI::Lingua->new(supported => ['en', 'fr', 'de']);
524  
525 # One supported language
526 my $l = CGI::Lingua->new(supported => 'en');
527  
528 # With a cache, a logger and a CGI::Info object
529 use CHI;
530 use CGI::Info;
531 my $l = CGI::Lingua->new({
532 supported => ['en', 'fr'],
533 cache => CHI->new(driver => 'File', root_dir => '/var/cache/myapp'),
534 logger => \my @messages,
535 info => CGI::Info->new(),
536 });
537  
538 =head3 MESSAGES
539  
540 C<new()> dies (with L<Carp/croak>) with one of these messages:
541  
542 "You must give a list of supported languages"
543 - supported is missing, undef, 0 or the empty string
544 "List of supported languages must be an array ref"
545 - supported is a reference, but not to an array
546 "Supported languages must be the short code"
547 - supported is a string shorter than 2 or longer than 5 characters
548 "Logger must be a blessed object with warn/info/error methods"
549 - logger is an object that is missing one of these methods
550 "CGI::Lingua use ->new() not ::new() to instantiate"
551 - new() was called as a function, with arguments
552 "info must be an object with a lang() method"
553 - info is not an object, or has neither lang() nor AUTOLOAD
554  
555 It warns, and carries on, with:
556  
557 "Ignoring '...' in the supported list: not a language code"
558 - an entry of the supported list is not a language tag
559 "Cache get failed: ..."
560 - the cache died while looking up saved answers
561 "Discarding malformed cache entry for ..."
562 - the saved answers were not in the shape CGI::Lingua writes
563  
564 =head3 PSEUDOCODE
565  
566 1. Read the arguments with Params::Get
567 2. If called on an object, return a copy with the new arguments on top
568 3. If logger is an object, check that it has warn, info and error
569 4. Merge in config_file and environment settings with Object::Configure
570 5. Check supported (required; string of 2-5 characters, or an arrayref)
571 6. If there is a cache and REMOTE_ADDR is set, try to load saved answers
572 from the cache (JSON); if found, return them as an object
573 7. Otherwise return a new object with no answers yet
574  
575 =cut
576  
577 sub new
578 {
579 my $class = shift;
580 my $params = Params::Get::get_params('supported', @_);
581  
582 # Handle ::new() misuse
583 if(!defined($class)) {
584 if($params) {
585 # Object::Configure has not run yet, so the logger may still be in
586 # one of its raw forms (arrayref, hashref, file name)
587 my $logger = $params->{'logger'};
588 if(Scalar::Util::blessed($logger) && $logger->can('error')) {
589 $logger->error(__PACKAGE__ . ' use ->new() not ::new() to instantiate');
590 }
591 Carp::croak(__PACKAGE__ . ' use ->new() not ::new() to instantiate');
592 }
593 $class = __PACKAGE__;
594 } elsif(ref($class)) {
595 # Clone: overlay new params onto existing object state
596 $params->{_supported} ||= $params->{supported} if defined $params->{'supported'};
597 return bless { %{$class}, %{$params} }, ref($class);
598 }
599  
600 # Validate blessed logger objects before Object::Configure runs.
601 # Non-blessed values (arrayrefs, hashrefs) are valid config forms that
602 # Object::Configure knows how to convert into a Log::Abstraction instance.
603 if(defined $params->{'logger'} && Scalar::Util::blessed($params->{'logger'})) {
604 unless(
605 $params->{'logger'}->can('warn')
606 && $params->{'logger'}->can('info')
607 && $params->{'logger'}->can('error')
608 ) {
609 Carp::croak('Logger must be a blessed object with warn/info/error methods');
610 }
611 }
612  
613 # Object::Configure runs evals and file tests; keep them off the caller's $@ and $!
614 $params = do { local ($@, $!); Object::Configure::configure($class, $params) };
615  
616 # Normalise supported / supported_languages alias
617 $params->{'supported'} ||= $params->{'supported_languages'};
618 if(defined($params->{supported})) {
619 # Validate supported type/length
620 if(ref($params->{supported})) {
621 if(ref($params->{supported}) ne 'ARRAY') {
622 Carp::croak('List of supported languages must be an array ref');
623 }
624 } elsif((length($params->{supported}) < 2) || (length($params->{supported}) > 5)) {
625 Carp::croak('Supported languages must be the short code');
626 }
627 } else {
628 if(my $logger = $params->{'logger'}) {
629 $logger->error('You must give a list of supported languages');
630 }
631 Carp::croak('You must give a list of supported languages');
632 }
633  
634 my $cache = $params->{cache};
635 my $info = $params->{info};
636  
637 # info is asked for lang() on every request. CGI::Info provides lang()
638 # through AUTOLOAD, so can('lang') alone is not enough of a test.
639 if(defined($info) && !(Scalar::Util::blessed($info) && ($info->can('lang') || $info->can('AUTOLOAD')))) {
640 Carp::croak('info must be an object with a lang() method');
641 }
642  
643 # Keep only entries that are language tags ("en", "en-gb", "es-419").
644 # undef, references (including a list that contains itself), '' and words
645 # such as "english" could never match and would make I18N::AcceptLanguage
646 # warn; say so rather than drop them silently.
647 my @supported;
648 for my $item (ref($params->{supported}) ? @{$params->{supported}} : ($params->{'supported'})) {
649 my $entry = $item; # a copy: the loop variable aliases the caller's array
650 if(defined($entry) && !ref($entry) && ($entry =~ $SUPPORTED_RE)) {
651 if(lc($entry) eq $DEPRECATED_EN_UK) {
652 # Same rule as the header: en-uk is en-gb
653 my $msg = "Resetting country code to GB for $entry";
654 if(Scalar::Util::blessed($params->{'logger'}) && $params->{'logger'}->can('warn')) {
655 $params->{'logger'}->warn($msg);
656 } else {
657 Carp::carp($msg);
658 }
659 $entry = $CANONICAL_EN_GB;
660 }
661 push @supported, $entry;
662 next;
663 }
664 my $msg = q{Ignoring '} . _printable($entry) . q{' in the supported list: not a language code};
665 if(Scalar::Util::blessed($params->{'logger'}) && $params->{'logger'}->can('warn')) {
666 $params->{'logger'}->warn($msg);
667 } else {
668 Carp::carp($msg);
669 }
670 }
671  
672 my $self = bless {
673 %{$params},
674 _supported => \@supported,
675 _cache => $cache,
676 _info => $info,
677 _syslog => $params->{syslog},
678 _dont_use_ip => $params->{dont_use_ip} || 0,
679 _have_mmdb => $GEO_UNKNOWN,
680 _have_ipcountry => $GEO_UNKNOWN,
681 _have_geoip => $GEO_UNKNOWN,
682 _have_geoipfree => $GEO_UNKNOWN,
683 _debug => $params->{debug} || 0,
684 }, $class;
685  
686 # Try to restore the answers saved by DESTROY for this visitor. Only the
687 # fields in %RESTORABLE are taken from the cache, each checked against
688 # its pattern: the cache can be written by others (world-writable /tmp,
689 # unauthenticated Redis), so a hostile entry must not set the logger,
690 # the supported list, dont_use_ip, or an HTML/path payload as a language.
691 if($cache && $ENV{'REMOTE_ADDR'}) {
692 my $key = _build_cache_key($ENV{'REMOTE_ADDR'}, $params, $class, $info);
693 # No key means REMOTE_ADDR is not a valid address: do not cache
694 if(defined($key) && (my $frozen = _cache_call($params, $cache, 'get', $key))) {
695 # JSON::PP rather than Storable::thaw: Storable can run code via
696 # STORABLE_thaw hooks in a crafted blob; JSON cannot. A blob that
697 # is not JSON (e.g. a legacy Storable entry) is quietly rebuilt.
698 my $rc = do { local $@; eval { local $SIG{__DIE__}; JSON::PP::decode_json($frozen) } };
699 if(ref($rc) eq 'HASH') {
700 my @bad = grep {
701 defined($rc->{$_}) && (ref($rc->{$_}) || ($rc->{$_} !~ $RESTORABLE{$_}))
702 } sort keys %RESTORABLE;
703 if(@bad) {
704 my $msg = "Discarding malformed cache entry for $key";
705 if(Scalar::Util::blessed($params->{'logger'}) && $params->{'logger'}->can('warn')) {
706 $params->{'logger'}->warn($msg);
707 } else {
708 Carp::carp($msg);
709 }
710 _cache_call($params, $cache, 'remove', $key);
711 } else {
712 $self->{$_} = $rc->{$_} for grep { defined $rc->{$_} } keys %RESTORABLE;
713  
714 # A lang= CGI parameter overrides the browser, so the
715 # cached language choice may be stale: work it out again
716 if(_info_lang($info)) {
717 delete @{$self}{qw(_slanguage _rlanguage _sublanguage
718 _slanguage_code_alpha2 _sublanguage_code_alpha2)};
719 }
720 }
721 }
722 }
723 }
724  
725 return $self;
726 }
727 # -- _build_cache_key ----------------------------------------------------------
728 # Purpose: Produce a deterministic string key for the per-request cache
729 # entry stored in new() and DESTROY().
730 # Entry: $addr -- IP string (not yet taint-checked; used read-only here)
731 # $params -- constructor params hashref
732 # $class -- package name
733 # $info -- optional CGI::Info object
734 # Exit: A plain string key of the form "ip/lang/lang1/lang2/..."
735 sub _build_cache_key
736 {
737 my ($addr, $params, $class, $info) = @_;
738  
739 # Every part of the key comes from the visitor or the caller, and cache
740 # backends such as Memcached treat CR, LF and spaces in a key as protocol.
741 # So the key is built only from checked values, and there is no key (and
742 # so no caching) when the address is not a valid one.
743 my $ip = _untaint_ip($addr);
744 return undef unless defined($ip);
745 my $key = "$ip/";
746  
747 # Include the requested language (if determinable) so different
748 # Accept-Language values get distinct cache slots for the same IP.
749 # Both sources are validated; spaces are not significant in the header.
750 my $l;
751 if(defined($l = _info_lang($info)) || defined($l = $class->_what_language())) {
752 $l =~ s/[ \t]+//g;
753 $key .= "$l/" if length($l);
754 }
755  
756 # Fix: was ref($params->{'supported'} eq 'ARRAY') -- eq was inside ref(),
757 # so ref() always received a boolean (1 or ''), never the arrayref itself.
758 # Only entries that new() would keep are used.
759 my @supported = ref($params->{'supported'}) eq 'ARRAY' ? @{$params->{supported}} : ($params->{'supported'});
760 $key .= join('/', grep { defined($_) && !ref($_) && ($_ =~ $SUPPORTED_RE) } @supported);
761  
762 return $key;
763 }
764  
765 # -- _untaint_ip ----------------------------------------------------------
766 # Purpose: Check that a value has the shape of an IP address and return
767 # an untainted copy. The single place REMOTE_ADDR is checked,
768 # so country(), time_zone() and the cache key always agree.
769 # Entry: $raw -- any scalar.
770 # Exit: The address, or undef. \z, not $, so "1.2.3.4\n" is refused.
771 # Notes: Shape only: country() then range-checks with is_ipv4/is_ipv6.
772 sub _untaint_ip
773 {
774 my $raw = shift;
775 return undef unless defined($raw) && !ref($raw);
776 return $raw =~ $IP_SHAPE_RE ? $1 : undef;
777 }
778  
779 # -- _cache_call ----------------------------------------------------------
780 # Purpose: Call get/set/remove on the caller-supplied cache without
781 # letting a cache failure take down the request. The cache only
782 # saves time, so a broken backend (full disc, unreachable Redis,
783 # CHI with on_get_error => 'die') must degrade to "not cached".
784 # Entry: $self -- a CGI::Lingua object, or new()'s params hashref
785 # (used only to find a logger);
786 # $cache -- the cache object; $method -- 'get', 'set' or 'remove';
787 # @args -- passed to the method unchanged.
788 # Exit: The method's scalar result, or undef if it died.
789 # Side Effects: Warns "Cache <method> failed: <error>" on failure.
790 sub _cache_call
791 {
792 my ($self, $cache, $method, @args) = @_;
793  
794 local $@;
795 my $rc;
796 return $rc if eval { local $SIG{__DIE__}; $rc = $cache->$method(@args); 1 };
797  
798 my $err = $@ || 'unknown error';
799 $err =~ s/\s+\z//;
800 my $msg = "Cache $method failed: $err";
801 if(Scalar::Util::blessed($self)) {
802 $self->_warn({ warning => $msg });
803 } elsif((ref($self) eq 'HASH') && Scalar::Util::blessed($self->{'logger'}) && $self->{'logger'}->can('warn')) {
804 $self->{'logger'}->warn($msg);
805 } else {
806 Carp::carp($msg);
807 }
808 return;
809 }
810  
811 # -- _info_lang -----------------------------------------------------------
812 # Purpose: Ask the CGI::Info-style object for the lang= parameter without
813 # letting a broken object (an AUTOLOAD that dies) end the request.
814 # Entry: $info -- the info object, or undef;
815 # $self -- optional object to warn through when the value is bad.
816 # Exit: The validated, untainted lang value, or undef if there is none,
817 # the call died, or the value is not a plausible language list.
818 sub _info_lang
819 {
820 my ($info, $self) = @_;
821  
822 return undef unless $info;
823 local $@;
824 my $lang;
825 return undef unless eval { local $SIG{__DIE__}; $lang = $info->lang(); 1 };
826 return undef unless defined($lang) && length($lang);
827  
828 # lang= comes from the query string, so it is as hostile as any header:
829 # same character set and length cap as HTTP_ACCEPT_LANGUAGE
830 return $1 if !ref($lang) && ($lang =~ $ACCEPT_LANG_RE);
831 $self->_warn({ warning => 'lang parameter contains invalid characters; ignoring' }) if ref($self);
832 return undef;
833 }
834  
835 # -- _cache_get_valid -----------------------------------------------------
836 # Purpose: Read a value from the cache and use it only if it has the
837 # shape CGI::Lingua itself stores. The cache may be shared or
838 # writable by others; a poisoned entry ("<script>", a hashref,
839 # "../../etc") must never become a language or country.
840 # Entry: $key -- full cache key; $re -- the pattern the value must match.
841 # Exit: The value, or undef on a miss or a malformed value.
842 # Side Effects: A malformed value is removed and "Discarding malformed cache
843 # entry for <key>" is warned (the value itself is not logged:
844 # it is attacker-controlled).
845 sub _cache_get_valid
846 {
847 my ($self, $key, $re) = @_;
848  
849 my $value = $self->_cache_call($self->{_cache}, 'get', $key);
850 return $value if !defined($value) || (!ref($value) && ($value =~ $re));
851  
852 $self->_warn({ warning => "Discarding malformed cache entry for $key" });
853 $self->_cache_call($self->{_cache}, 'remove', $key);
854 return;
855 }
856  
857 # Some of the information takes a long time to work out, so cache what we can
858 sub DESTROY {
859 # Destructors run at arbitrary points, e.g. while the caller is examining $@
860 local ($@, $!);
861 if(defined($^V) && ($^V ge 'v5.14.0')) {
862 return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
863 }
864 return unless $ENV{'REMOTE_ADDR'};
865  
866 my $self = shift;
867 return unless ref($self);
868  
869 my $cache = $self->{_cache};
870 return unless $cache;
871  
872 my $key = _build_cache_key(
873 $ENV{'REMOTE_ADDR'},
874 { supported => $self->{_supported} },
875 ref($self),
876 $self->{_info},
877 );
878 return unless defined($key); # REMOTE_ADDR is not a valid address
879 return if $self->_cache_call($cache, 'get', $key);
880  
881 $self->_debug("Storing self in cache as $key");
882  
883 # Serialise only the computed state -- not loggers, file handles, or
884 # geo-module objects (they are re-initialised on next construction).
885 # JSON::PP is used instead of Storable so that a compromised cache backend
886 # cannot deliver a blob that executes code via STORABLE_thaw hooks.
887 # Only the fields new() will accept back (see %RESTORABLE). _sublanguage
888 # used to be left out, so sublanguage() was undef after a restore.
889 my %state = map { $_ => $self->{$_} } keys %RESTORABLE;
890  
891 $self->_cache_call($cache, 'set', $key, JSON::PP::encode_json(\%state), $CACHE_TTL_LONG);
892 }
893  
894 =head2 language
895  
896 Returns the name of the language to show to the visitor, in English,
897 for example C<'English'>, C<'French'> or C<'Japanese'>.
898 The language is always one of the languages in your C<supported> list.
899  
900 Variants are handled sensibly.
901 If a visitor asks for American English (C<en-us>)
902 and your site only has British English (C<en-gb>),
903 C<language()> returns C<'English'>.
904  
905 If none of the languages that the visitor wants is in your C<supported> list,
906 C<language()> returns the string C<'Unknown'>.
907 It never returns C<undef>.
908  
909 =head3 API SPECIFICATION
910  
911 =head4 Input
912  
913 {}
914  
915 =head4 Output
916  
917 {
918 type => 'string',
919 min => 1,
920 }
921  
922 =head3 EXAMPLE
923  
924 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'fr,en;q=0.9';
925 my $l = CGI::Lingua->new(supported => ['en', 'fr']);
926 print $l->language(); # "French"
927  
928 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'de';
929 my $l = CGI::Lingua->new(supported => ['en', 'fr']);
930 print $l->language(); # "Unknown"
931  
932 =head3 MESSAGES
933  
934 The first call to L</language> (or any other language method) warns, and
935 ignores the value, when one of its inputs is not acceptable:
936  
937 "lang parameter contains invalid characters; ignoring"
938 "HTTP_ACCEPT_LANGUAGE contains invalid characters; ignoring"
939 "LC_ALL contains invalid characters; ignoring"
940 "LC_MESSAGES contains invalid characters; ignoring"
941 "LANG contains invalid characters; ignoring"
942  
943 It also warns when it changes the deprecated tag C<en-uk> into C<en-gb>:
944  
945 "Resetting country code to GB for ..."
946  
947 =cut
948  
949 sub language {
950 my $self = $_[0];
951  
952 $self->_find_language() unless $self->{_slanguage};
953 return $self->{_slanguage};
954 }
955  
956 =head2 preferred_language
957  
958 Another name for L</language>. It takes no arguments and returns the same value.
959  
960 =head3 API SPECIFICATION
961  
962 =head4 Input
963  
964 {}
965  
966 =head4 Output
967  
968 {
969 type => 'string',
970 min => 1,
971 }
972  
973 =cut
974  
975 sub preferred_language
976 {
977 my $self = shift;
978 return $self->language(@_);
979 }
980  
981 =head2 name
982  
983 Another name for L</language>, so that a CGI::Lingua object can be used where a
984 L<Locale::Object::Language> object is expected.
985  
986 =head3 API SPECIFICATION
987  
988 =head4 Input
989  
990 {}
991  
992 =head4 Output
993  
994 {
995 type => 'string',
996 min => 1,
997 }
998  
999 =cut
1000  
1001 sub name {
1002 my $self = $_[0];
1003 return $self->language();
1004 }
1005  
1006 =head2 sublanguage
1007  
1008 Returns the name of the variant (usually a country) of the chosen language,
1009 for example C<'United Kingdom'> when the chosen language is C<en-gb>.
1010  
1011 Returns C<undef> when there is no variant, for example when the chosen
1012 language is just C<en>, or when no language was found.
1013  
1014 =head3 API SPECIFICATION
1015  
1016 =head4 Input
1017  
1018 {}
1019  
1020 =head4 Output
1021  
1022 {
1023 type => 'string',
1024 min => 1,
1025 optional => 1,
1026 }
1027  
1028 =head3 EXAMPLE
1029  
1030 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'en-gb';
1031 my $l = CGI::Lingua->new(supported => ['en-gb']);
1032 print $l->sublanguage(); # "United Kingdom"
1033  
1034 =cut
1035  
1036 sub sublanguage {
1037 my $self = $_[0];
1038  
1039 $self->_trace('Entered sublanguage');
1040 $self->_find_language() unless $self->{_slanguage};
1041 $self->_trace('Leaving sublanguage ', ($self->{_sublanguage} || 'undef'));
1042 return $self->{_sublanguage};
1043 }
1044  
1045 =head2 language_code_alpha2
1046  
1047 Returns the two-letter code (ISO 639-1) of the chosen language,
1048 for example C<'en'> when the chosen language is C<en-gb>.
1049  
1050 Returns C<undef> when none of the languages that the visitor wants is in your
1051 C<supported> list (that is, when L</language> returns C<'Unknown'>).
1052  
1053 =head3 API SPECIFICATION
1054  
1055 =head4 Input
1056  
1057 {}
1058  
1059 =head4 Output
1060  
1061 {
1062 type => 'string',
1063 min => 2,
1064 max => 2,
1065 optional => 1,
1066 }
1067  
1068 =head3 EXAMPLE
1069  
1070 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'en-gb';
1071 my $l = CGI::Lingua->new(supported => ['en-gb']);
1072 print $l->language_code_alpha2(); # "en"
1073  
1074 =cut
1075  
1076 sub language_code_alpha2 {
1077 my $self = $_[0];
1078  
1079 $self->_trace('Entered language_code_alpha2');
1080 $self->_find_language() unless $self->{_slanguage};
1081 $self->_trace('language_code_alpha2 returns ', $self->{_slanguage_code_alpha2});
1082 return $self->{_slanguage_code_alpha2};
1083 }
1084  
1085 =head2 code_alpha2
1086  
1087 Another name for L</language_code_alpha2>, kept so that old programs still work.
1088  
1089 =head3 API SPECIFICATION
1090  
1091 =head4 Input
1092  
1093 {}
1094  
1095 =head4 Output
1096  
1097 {
1098 type => 'string',
1099 min => 2,
1100 max => 2,
1101 optional => 1,
1102 }
1103  
1104 =cut
1105  
1106 sub code_alpha2 {
1107 my $self = $_[0];
1108 return $self->language_code_alpha2();
1109 }
1110  
1111 =head2 sublanguage_code_alpha2
1112  
1113 Returns the two-letter code of the variant of the chosen language,
1114 in lower case, for example C<'gb'> when the chosen language is C<en-gb>.
1115  
1116 Returns C<undef> when there is no variant.
1117  
1118 =head3 API SPECIFICATION
1119  
1120 =head4 Input
1121  
1122 {}
1123  
1124 =head4 Output
1125  
1126 {
1127 type => 'string',
1128 min => 2,
1129 max => 2,
1130 optional => 1,
1131 }
1132  
1133 =head3 EXAMPLE
1134  
1135 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'en-gb';
1136 my $l = CGI::Lingua->new(supported => ['en-gb']);
1137 print $l->sublanguage_code_alpha2(); # "gb"
1138  
1139 =cut
1140  
1141 sub sublanguage_code_alpha2 {
1142 my $self = $_[0];
1143  
1144 $self->_find_language() unless $self->{_slanguage};
1145 return $self->{_sublanguage_code_alpha2};
1146 }
1147  
1148 =head2 requested_language
1149  
1150 Returns, in English, the language that the visitor asked for,
1151 B<whether or not your site supports it>.
1152 Use it to tell the visitor that their language is not available.
1153  
1154 If the visitor asked for a variant, it is shown in brackets,
1155 for example C<'English (United Kingdom)'>. A variant that is not a known
1156 country code is shown as it was sent, for example C<'English (Unknown: zz)'>.
1157  
1158 Returns C<'Unknown'> when the visitor's language cannot be found at all.
1159 It never returns C<undef>.
1160  
1161 =head3 API SPECIFICATION
1162  
1163 =head4 Input
1164  
1165 {}
1166  
1167 =head4 Output
1168  
1169 {
1170 type => 'string',
1171 min => 1,
1172 }
1173  
1174 =head3 EXAMPLE
1175  
1176 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'en-gb';
1177 my $l = CGI::Lingua->new(supported => ['en']);
1178 print $l->language(); # "English"
1179 print $l->requested_language(); # "English (United Kingdom)"
1180  
1181 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'de';
1182 my $l = CGI::Lingua->new(supported => ['en']);
1183 print $l->language(); # "Unknown"
1184 print $l->requested_language(); # "German"
1185  
1186 =cut
1187  
1188 sub requested_language {
1189 my $self = $_[0];
1190  
1191 $self->_find_language() unless $self->{_rlanguage};
1192 # _find_language() can leave it undef; the API promises a string
1193 $self->{_rlanguage} //= 'Unknown';
1194 return $self->{_rlanguage};
1195 }
1196  
1197 # -- _find_language ---------------------------------------------------------
1198 # Purpose: Populate _slanguage, _rlanguage, _sublanguage, and the
1199 # various code fields by working through the detection pipeline:
1200 # Accept-Language header -> I18N::AcceptLanguage -> IP country.
1201 # Entry: $self->{_slanguage} must be undef (guards repeated calls).
1202 # Exit: $self->{_slanguage} is set to a language name or 'Unknown'.
1203 # Side Effects: Populates _rlanguage, _sublanguage, *_code_alpha2 fields.
1204 sub _find_language
1205 {
1206 my $self = shift;
1207 # Called by every language accessor; the evals and file tests below must
1208 # not change the caller's $@ or $!
1209 local ($@, $!);
1210  
1211 $self->_trace('Entered _find_language');
1212  
1213 $self->{_rlanguage} = 'Unknown';
1214 $self->{_slanguage} = 'Unknown';
1215  
1216 my $http_accept_language = $self->_what_language();
1217  
1218 # RFC 7231 section 5.3.1: q=0 means "not acceptable", so drop those tags
1219 # before matching, or "fr;q=0, en;q=0.5" would choose French. A q value
1220 # outside the RFC grammar (0 to 1, at most three decimals: "q=abc",
1221 # "q=1e309", "q=-1") makes the tag malformed, so drop it too, rather than
1222 # let I18N::AcceptLanguage guess and warn.
1223 if(defined($http_accept_language) && ($http_accept_language =~ /;\s*q\s*=/i)) {
1224 my @acceptable;
1225 for my $tag (split(/\s*,\s*/, $http_accept_language)) {
1226 if($tag =~ /;\s*q\s*=\s*(\S*?)\s*\z/i) {
1227 my $q = $1;
1228 next unless $q =~ /^(?:0(?:\.[0-9]{0,3})?|1(?:\.0{0,3})?)\z/;
1229 next if $q == 0;
1230 }
1231 push @acceptable, $tag;
1232 }
1233 $http_accept_language = @acceptable ? join(',', @acceptable) : undef;
1234 $self->_debug('Accept-Language after dropping unacceptable tags: ', $http_accept_language // '(none)');
1235 }
1236  
1237 if(defined($http_accept_language)) {
1238 $self->_debug(
1239 "language wanted: $http_accept_language, "
1240 . 'languages supported: '
1241 . join(', ', @{$self->{_supported}} // '')
1242 );
1243  
1244 # Normalise the deprecated en-uk tag that some browsers send, wherever
1245 # it is in the list (not only when it is the whole header)
1246 my $sent = $http_accept_language;
1247 if($http_accept_language =~ s/(?<![A-Za-z0-9-])\Q$DEPRECATED_EN_UK\E(?![A-Za-z0-9-])/$CANONICAL_EN_GB/gi) {
1248 $self->_warn({ warning => "Resetting country code to GB for $sent" });
1249 }
1250  
1251 # Run the header through the Accept-Language resolver
1252 my ($l, $requested_sublanguage) =
1253 $self->_accept_language_match($http_accept_language);
1254  
1255 # Resolve the matched code to a full language/sublanguage
1256 if($l) {
1257 return if $self->_resolve_match($l, $requested_sublanguage, $http_accept_language);
1258 } elsif($http_accept_language =~ /;/) {
1259 # e.g. de-DE,de;q=0.9,en-US;q=0.8 and we support none of those
1260 $self->_notice(
1261 __PACKAGE__, ': ', __LINE__,
1262 ": couldn't honour HTTP_ACCEPT_LANGUAGE=$http_accept_language,"
1263 . ' supported languages are: '
1264 . join(',', @{$self->{_supported}})
1265 );
1266 }
1267  
1268 # Last-chance: 2-char or xx-xx header where we have no match
1269 if(
1270 ((!$self->{_rlanguage}) || ($self->{_rlanguage} eq 'Unknown'))
1271 && ((length($http_accept_language) == 2) || ($http_accept_language =~ /^..-..$/))
1272 ) {
1273 $self->{_rlanguage} = $self->_code2language($http_accept_language) || 'Unknown';
1274 }
1275 $self->{_slanguage} = 'Unknown';
1276 }
1277  
1278 return if $self->{_dont_use_ip};
1279  
1280 # Fall back to the official language of the visitor's country
1281 $self->_find_language_from_ip($http_accept_language);
1282 }
1283  
1284 # -- _accept_language_match ------------------------------------------------
1285 # Purpose: Run I18N::AcceptLanguage strict matching plus two fallback
1286 # left-to-right scan passes against $self->{_supported}.
1287 # Entry: $http_accept_language -- validated, untainted Accept-Language value.
1288 # Exit: Returns ($matched_code, $requested_sublanguage) or (undef, undef).
1289 # Side Effects: Logs debug messages.
1290 sub _accept_language_match
1291 {
1292 my ($self, $http_accept_language) = @_;
1293  
1294 my $i18n = I18N::AcceptLanguage->new(debug => $self->{_debug}, strict => 1);
1295 my $l;
1296 {
1297 # Suppress I18N::AcceptLanguage's uninitialized-value warnings (RT 74338)
1298 local $SIG{__WARN__} = _warn_filter(qr/^Use of uninitialized value/);
1299 $l = $i18n->accepts($http_accept_language, $self->{_supported});
1300 }
1301  
1302 # I18N-AcceptLanguage strict mode can return a sublanguage variant when
1303 # the request contains a sublanguage we don't support; force a retry.
1304 if($l && ($http_accept_language =~ /-/) && ($http_accept_language !~ qr/$l/i)) {
1305 $self->_debug('Forcing fallback');
1306 undef $l;
1307 }
1308  
1309 my $requested_sublanguage;
1310 if(!$l) {
1311 # Sort tokens by q-value once; both scan passes share the ordered list
1312 my $sorted = $self->_sorted_tokens($http_accept_language);
1313 # First fallback: scan for xx-yy pairs, try base language xx
1314 ($l, $requested_sublanguage) =
1315 $self->_scan_sublanguage_pairs($i18n, $sorted);
1316 if(!$l) {
1317 # Second fallback: scan plain tokens without sublanguages
1318 $l = $self->_scan_plain_tokens($i18n, $sorted);
1319 undef $requested_sublanguage if $l;
1320 }
1321 }
1322  
1323 return ($l, $requested_sublanguage);
1324 }
1325  
1326 # -- _sorted_tokens --------------------------------------------------------
1327 # Purpose: Parse an Accept-Language header into tokens sorted by
1328 # descending quality value so fallback scans honour q= priority.
1329 # Entry: $header -- validated Accept-Language string.
1330 # Exit: Arrayref of [$language_tag, $quality] pairs, highest q first.
1331 sub _sorted_tokens
1332 {
1333 my ($self, $header) = @_;
1334 my @tokens;
1335 for my $token (split /,/, $header) {
1336 $token =~ s/^\s+|\s+$//g;
1337 my $q = 1.0;
1338 if($token =~ s/;\s*q\s*=\s*(\d+(?:\.\d+)?)//) {
1339 $q = $1 + 0;
1340 }
1341 $token =~ s/^\s+|\s+$//g;
1342 push @tokens, [$token, $q] if length $token;
1343 }
1344 return [sort { $b->[1] <=> $a->[1] } @tokens];
1345 }
1346  
1347 # -- _scan_sublanguage_pairs -----------------------------------------------
1348 # Purpose: Walk q-sorted tokens looking for xx-yy pairs; try accepting
1349 # the base language xx from the supported list.
1350 # Entry: $i18n -- I18N::AcceptLanguage instance;
1351 # $sorted -- arrayref from _sorted_tokens.
1352 # Exit: ($matched_code, $sublanguage_code) or (undef, undef).
1353 # Side Effects: Debug logging.
1354 sub _scan_sublanguage_pairs
1355 {
1356 my ($self, $i18n, $sorted) = @_;
1357  
1358 $self->_debug(__PACKAGE__, ': ', __LINE__, ': scan q-sorted tokens for xx-yy pairs');
1359 for my $entry (@{$sorted}) {
1360 my ($tag) = @{$entry};
1361 next unless $tag =~ /^(..)-(..)$/;
1362 my ($base, $sub) = ($1, $2);
1363 $self->_debug(__PACKAGE__, ': ', __LINE__, ": see if $base is supported");
1364 if($i18n->accepts($base, $self->{_supported})) {
1365 $self->_debug("Fallback to $base as sublanguage $sub is not supported");
1366 return ($base, $sub);
1367 }
1368 }
1369 return (undef, undef);
1370 }
1371  
1372 # -- _scan_plain_tokens ----------------------------------------------------
1373 # Purpose: Walk q-sorted tokens that have no sublanguage suffix and try
1374 # accepting each against the supported list.
1375 # Entry: $i18n -- I18N::AcceptLanguage instance;
1376 # $sorted -- arrayref from _sorted_tokens.
1377 # Exit: Matched code string, or undef.
1378 # Side Effects: Debug logging.
1379 sub _scan_plain_tokens
1380 {
1381 my ($self, $i18n, $sorted) = @_;
1382  
1383 $self->_debug(__PACKAGE__, ': ', __LINE__, ': scan q-sorted tokens for plain alternatives');
1384 for my $entry (@{$sorted}) {
1385 my ($tag) = @{$entry};
1386 next if $tag =~ /^..-../; # already tried in the pair scan
1387 $self->_debug(__PACKAGE__, ': ', __LINE__, ": see if $tag is supported");
1388 if($i18n->accepts($tag, $self->{_supported})) {
1389 $self->_debug("Fallback to $tag as best alternative");
1390 return $tag;
1391 }
1392 }
1393 return;
1394 }
1395  
1396 # -- _resolve_match --------------------------------------------------------
1397 # Purpose: Given a matched code $l (possibly xx or xx-yy), populate all
1398 # of _slanguage, _rlanguage, _sublanguage and their code fields.
1399 # Entry: $l -- 2-char or xx-yy language code; $requested_sublanguage --
1400 # 2-char variety code or undef; $http_accept_language -- full header.
1401 # Exit: Returns true (1) if the caller should return immediately.
1402 # Side Effects: Mutates $self->{_slanguage}, _rlanguage, _sublanguage, etc.
1403 sub _resolve_match
1404 {
1405 my ($self, $l, $requested_sublanguage, $http_accept_language) = @_;
1406  
1407 $self->_debug("l: $l");
1408  
1409 if($l !~ /^..-../) {
1410 # Base-language match (e.g. 'en') -- no sublanguage component
1411 return $self->_resolve_base_match($l, $requested_sublanguage, $http_accept_language);
1412 } elsif($l =~ /(.+)-(..)$/) {
1413 # Sublanguage match (e.g. 'en-gb') -- resolve both language and variant
1414 return $self->_resolve_sublanguage_match($l, $1, $2, $http_accept_language);
1415 }
1416 return 0;
1417 }
1418  
1419 # -- _resolve_base_match ---------------------------------------------------
1420 # Purpose: Handle the case where a base-language code matched (no hyphen).
1421 # Sets _slanguage, _rlanguage; appends sublanguage name to rlanguage
1422 # when the client requested one we don't support.
1423 # Entry: $l -- 2-char code; $requested_sublanguage -- optional; $header.
1424 # Exit: 1 to signal caller should return, 0 otherwise.
1425 # Side Effects: Mutates slanguage, rlanguage, slanguage_code_alpha2.
1426 sub _resolve_base_match
1427 {
1428 my ($self, $l, $requested_sublanguage, $header) = @_;
1429  
1430 $self->{_slanguage} = $self->_code2language($l);
1431 return 0 unless $self->{_slanguage};
1432  
1433 $self->_debug("_slanguage: $self->{_slanguage}");
1434 $self->{_slanguage_code_alpha2} = $l;
1435 $self->{_rlanguage} = $self->{_slanguage};
1436  
1437 # Attempt to name the sublanguage the client actually asked for
1438 my $sl;
1439 if($header =~ /..-(..)$/) {
1440 $self->_debug($1);
1441 $sl = $self->_code2country($1);
1442 $requested_sublanguage //= $1;
1443 } elsif($header =~ /..-([a-z]{2,3})$/i) {
1444 if($_locale_object_db_ok // 1) {
1445 eval { $sl = Locale::Object::Country->new(code_alpha3 => $1) };
1446 if($@) {
1447 $_locale_object_db_ok = 0 if $@ =~ /database was not in/;
1448 $self->_info($@);
1449 } else {
1450 $_locale_object_db_ok = 1;
1451 }
1452 }
1453 }
1454  
1455 if($sl) {
1456 $self->{_rlanguage} .= ' (' . $sl->name() . ')';
1457 } elsif($requested_sublanguage) {
1458 if(my $c = $self->_code2countryname($requested_sublanguage)) {
1459 $self->{_rlanguage} .= " ($c)";
1460 } else {
1461 $self->{_rlanguage} .= " (Unknown: $requested_sublanguage)";
1462 }
1463 }
1464 return 1;
1465 }
1466  
1467 # -- _resolve_sublanguage_match --------------------------------------------
1468 # Purpose: Handle the case where the full xx-yy code matched in the
1469 # supported list. Resolves the variety name and caches results.
1470 # Entry: $l -- full code e.g. 'en-gb'; $alpha2 -- 'en'; $variety -- 'gb';
1471 # $header -- full Accept-Language value.
1472 # Exit: 1 to signal caller should return, 0 otherwise.
1473 # Side Effects: Mutates _slanguage, _rlanguage, _sublanguage and code fields;
1474 # writes to cache.
1475 sub _resolve_sublanguage_match
1476 {
1477 my ($self, $l, $alpha2, $variety, $header) = @_;
1478  
1479 my $i18n = I18N::AcceptLanguage->new(strict => 1);
1480 my $accepts = $i18n->accepts($l, $self->{_supported});
1481 $self->_debug('accepts = ', $accepts // 'undef');
1482  
1483 # $l is an entry of the supported list with a hyphen (e.g. 'en-gb'), so a
1484 # strict match always gives back that same hyphenated entry. (An earlier
1485 # branch for a hyphen-less answer could never run, and was removed.)
1486 delete $self->{_slanguage} if $accepts;
1487  
1488 # Accepts returned something but we couldn't resolve a language name --
1489 # try harder using the variety code directly
1490 $self->{_rlanguage} = $self->_code2language($alpha2);
1491 $self->_debug("_rlanguage: $self->{_rlanguage}");
1492  
1493 return 0 unless $accepts;
1494  
1495 $self->_debug("http_accept_language = $header");
1496 $l =~ /(..)-(..)/;
1497 $variety = lc($2);
1498  
1499 # Skip numeric/region codes like en-029
1500 if(($variety =~ /[a-z]{2,3}/) && !defined($self->{_sublanguage})) {
1501 $self->_get_closest($alpha2, $alpha2);
1502 $self->_debug("Find the country code for $variety");
1503  
1504 my ($from_cache, $language_name, $db_error);
1505 if($self->{_cache}) {
1506 $from_cache = $self->_cache_get_valid($CACHE_NS . "variety:$variety", $NAME_CODE_RE);
1507 }
1508  
1509 if(defined($from_cache)) {
1510 $self->_debug("$variety is in cache as $from_cache");
1511 # Cache stores "countryname=langcode" (e.g. "United Kingdom=en").
1512 # Splitting on = gives the country name as the first field.
1513 ($language_name) = split(/=/, $from_cache);
1514 # A poisoned entry such as "=en" has an empty name; treat it as a miss
1515 undef $language_name unless defined($language_name) && length($language_name);
1516 } elsif($_locale_object_db_ok // 1) {
1517 # Locale::Object's SQLite database is absent on some Windows
1518 # installations; the sentinel avoids repeated failed new() calls.
1519 # Keep the error in a lexical: $@ itself may still hold an
1520 # unrelated error from the caller when this branch is skipped.
1521 eval {
1522 my $db = Locale::Object::DB->new();
1523 my @results = @{$db->lookup(
1524 table => 'country',
1525 result_column => 'name',
1526 search_column => 'code_alpha2',
1527 value => $variety
1528 )};
1529 $_locale_object_db_ok = 1;
1530 if(defined($results[0])) {
1531 $language_name = $self->_code2countryname($variety);
1532 } else {
1533 $self->_debug("Can't find the country code for $variety in Locale::Object::DB");
1534 }
1535 1;
1536 } or $db_error = ($@ || 'unknown error');
1537 if($db_error) {
1538 $_locale_object_db_ok = 0
1539 if $db_error =~ /database was not in/;
1540 # fall through: $language_name stays undef, caught below
1541 }
1542 }
1543  
1544 if($db_error || !defined($language_name)) {
1545 $self->_warn({ warning => $db_error }) if $db_error;
1546 # Locale::Object DB may be absent (common on Windows CI); fall back to
1547 # the short-name table / Locale::Codes before giving up.
1548 $language_name = $self->_country_short_name($variety);
1549 }
1550 if(!defined($language_name)) {
1551 $self->_debug(__PACKAGE__, ': ', __LINE__, ': setting sublanguage to Unknown');
1552 $self->{_sublanguage} = 'Unknown';
1553 $self->_warn({ warning => "Can't determine values for $header" });
1554 } else {
1555 $self->{_sublanguage} = $language_name;
1556 $self->_debug('variety name ', $self->{_sublanguage});
1557 if($self->{_cache} && !defined($from_cache)) {
1558 # Store "countryname=langcode" so future cache hits return the country
1559 # name in the first field. Previously this stored the language name
1560 # ("English=en" for en-gb) which was wrong -- the cache-hit branch
1561 # split on = and used the first field as the sublanguage (country) name.
1562 $self->_debug("Set variety:$variety to $language_name=$self->{_slanguage_code_alpha2}");
1563 $self->_cache_call($self->{_cache}, 'set',
1564 $CACHE_NS . "variety:$variety",
1565 "$language_name=$self->{_slanguage_code_alpha2}",
1566 $CACHE_TTL_LONG
1567 );
1568 }
1569 }
1570 }
1571  
1572 if(defined($self->{_sublanguage})) {
1573 $self->{_rlanguage} = "$self->{_slanguage} ($self->{_sublanguage})";
1574 $self->{_sublanguage_code_alpha2} = $variety;
1575 return 1;
1576 }
1577 return 0;
1578 }
1579  
1580 # -- _find_language_from_ip ------------------------------------------------
1581 # Purpose: Fall back to the visitor's IP country when the Accept-Language
1582 # header produced no usable match. Looks up the official language
1583 # of the country and checks it against the supported list.
1584 # Entry: $http_accept_language -- may be undef if no header was present.
1585 # Exit: Mutates _slanguage, _rlanguage via _get_closest if a match found.
1586 # Side Effects: Calls country(); may write to cache.
1587 sub _find_language_from_ip
1588 {
1589 my ($self, $http_accept_language) = @_;
1590  
1591 my $country = $self->country();
1592  
1593 # If country() returned nothing, try to derive from the locale's territory
1594 # (_what_language gives LANG=fr_FR.UTF-8 as "fr-FR"). Only a locale's
1595 # hyphen counts: a header's "fr-CA" is the reader's language, not where
1596 # they are, and was never read as a country.
1597 if(!defined($country) && (my $c = $self->_what_language())) {
1598 if($c =~ /^(..)_(..)/) {
1599 $country = $2;
1600 } elsif($self->{_what_language_from_locale} && ($c =~ /^[A-Za-z]{2,3}-([A-Za-z]{2})\z/)) {
1601 $country = $1;
1602 } elsif($c =~ /^(..)$/) {
1603 $country = $1;
1604 }
1605 }
1606 return unless defined $country;
1607  
1608 $self->_debug("country: $country");
1609  
1610 my ($language_name, $language_code2, $from_cache);
1611 if($self->{_cache}) {
1612 $from_cache = $self->_cache_get_valid($CACHE_NS . 'language_name:' . $country, $NAME_CODE_RE);
1613 }
1614  
1615 if($from_cache) {
1616 $self->_debug("$country is in cache as $from_cache");
1617 ($language_name, $language_code2) = split(/=/, $from_cache);
1618 } else {
1619 my $l = $self->_code2country(uc($country));
1620 if($l) {
1621 $l = ($l->languages_official)[0];
1622 if(defined $l) {
1623 $language_name = $l->name;
1624 $language_code2 = $l->code_alpha2;
1625 $self->_debug("Official language: $language_name") if $language_name;
1626 }
1627 }
1628 }
1629  
1630 # REMOTE_ADDR is absent when the country came from LANG (command-line use)
1631 my $ip = $ENV{'REMOTE_ADDR'} // '(none)';
1632 return unless $language_name;
1633  
1634 if((!defined($self->{_rlanguage})) || ($self->{_rlanguage} eq 'Unknown')) {
1635 $self->{_rlanguage} = $language_name;
1636 }
1637  
1638 unless((exists $self->{_slanguage}) && ($self->{_slanguage} ne 'Unknown')) {
1639 my $code;
1640  
1641 if($language_name && $language_code2 && !defined($http_accept_language)) {
1642 # Fast-path for search engines that hit with no Accept-Language
1643 $self->_debug("Fast assign to $language_code2");
1644 $code = $language_code2;
1645 } else {
1646 $self->_debug("Call language2code on $self->{_rlanguage}");
1647 $code = Locale::Language::language2code($self->{_rlanguage});
1648  
1649 unless($code) {
1650 if($http_accept_language && ($http_accept_language ne $self->{_rlanguage})) {
1651 $self->_debug("Call language2code on $http_accept_language");
1652 $code = Locale::Language::language2code($http_accept_language);
1653 }
1654 unless($code) {
1655 # Norwegian (Nynorsk) -- strip the parenthetical qualifier
1656 if($self->{_rlanguage} =~ /(.+)\s\(.+/) {
1657 if((!defined($http_accept_language)) || ($1 ne $self->{_rlanguage})) {
1658 $self->_debug("Call language2code on $1");
1659 $code = Locale::Language::language2code($1);
1660 }
1661 }
1662 unless($code) {
1663 $self->_warn({
1664 warning => "Can't determine code from IP $ip for requested language $self->{_rlanguage}"
1665 });
1666 }
1667 }
1668 }
1669 }
1670  
1671 if($code) {
1672 $self->_get_closest($code, $language_code2);
1673 unless($self->{_slanguage}) {
1674 $self->_warn({
1675 warning => "Couldn't determine closest language for $language_name in "
1676 . join(', ', @{$self->{_supported}})
1677 });
1678 } else {
1679 $self->_debug("language set to $self->{_slanguage}, code set to $code");
1680 }
1681 }
1682 }
1683  
1684 if(!defined($self->{_slanguage_code_alpha2})) {
1685 $self->_debug("Can't determine slanguage_code_alpha2");
1686 } elsif(!defined($from_cache) && $self->{_cache} && defined($self->{_slanguage_code_alpha2})) {
1687 $self->_debug("Set $country to $language_name=$self->{_slanguage_code_alpha2}");
1688 $self->_cache_call($self->{_cache}, 'set',
1689 $CACHE_NS . 'language_name:' . $country,
1690 "$language_name=$self->{_slanguage_code_alpha2}",
1691 $CACHE_TTL_LONG
1692 );
1693 }
1694 }
1695  
1696 # -- _get_closest ---------------------------------------------------------
1697 # Purpose: If $language_string matches the base language of any supported
1698 # entry, set _slanguage and _slanguage_code_alpha2.
1699 # Entry: $language_string -- base code e.g. 'en'; $alpha2 -- same or variant.
1700 # Exit: Mutates _slanguage and _slanguage_code_alpha2 on match.
1701 sub _get_closest
1702 {
1703 my ($self, $language_string, $alpha2) = @_;
1704  
1705 # Map each supported entry to its base language code
1706 my %base_languages =
1707 map { /^(.+)-/ ? ($1 => $_) : ($_ => $_) } @{$self->{_supported}};
1708  
1709 if(exists $base_languages{$language_string}) {
1710 $self->{_slanguage} = $self->{_rlanguage};
1711 $self->{_slanguage_code_alpha2} = $alpha2;
1712 }
1713 }
1714  
1715 # -- _what_language --------------------------------------------------------
1716 # Purpose: Return the raw (validated, untainted) Accept-Language string,
1717 # consulting in priority order: cached value, CGI lang= param,
1718 # HTTP_ACCEPT_LANGUAGE env var, LANG env var (local/debug mode).
1719 # Entry: May be called as a class method (no $self->{...} access) or
1720 # as an object method.
1721 # Exit: A validated language string, or undef if nothing available.
1722 # Side Effects: Caches result in $self->{_what_language} on object calls.
1723 sub _what_language {
1724 my $self = $_[0];
1725  
1726 if(ref($self)) {
1727 $self->_trace('Entered _what_language');
1728 if(defined($self->{_what_language})) {
1729 $self->_trace('_what_language: returning cached value: ', $self->{_what_language});
1730 return $self->{_what_language};
1731 }
1732 if(my $info = $self->{_info}) {
1733 if(my $rc = _info_lang($info, $self)) {
1734 $self->_trace("_what_language set language to $rc from the lang argument");
1735 return $self->{_what_language} = $rc;
1736 }
1737 }
1738 }
1739  
1740 if(my $raw_lang = $ENV{'HTTP_ACCEPT_LANGUAGE'}) {
1741 # Validate and untaint -- RFC 7231 section 5.3.5 character set plus * wildcard.
1742 # Spaces and tabs only, not \s: CR and LF would carry header, log-line
1743 # and Memcached-command injection into the cache key and messages.
1744 if($raw_lang =~ $ACCEPT_LANG_RE) {
1745 my $rc = $1; # untainted
1746 if(ref($self)) {
1747 return $self->{_what_language} = $rc;
1748 }
1749 return $rc;
1750 } elsif(ref($self)) {
1751 $self->_warn({ warning => 'HTTP_ACCEPT_LANGUAGE contains invalid characters; ignoring' });
1752 }
1753 }
1754  
1755 # Running locally (the command line) - derive from the system locale.
1756 # POSIX takes the language of messages from LC_ALL, then LC_MESSAGES,
1757 # then LANG: the first that is set and not empty decides, even when it
1758 # names no language (LC_ALL=C), so a later one is not consulted.
1759 for my $var (@LOCALE_VARS) {
1760 my $locale = $ENV{$var};
1761 next unless defined($locale) && length($locale);
1762  
1763 # The same untainting discipline as HTTP_ACCEPT_LANGUAGE: only the
1764 # characters of a POSIX locale name (e.g. "en_US.UTF-8",
1765 # "sr_RS@latin", "ja"). Anything else is malformed or an injection
1766 # attempt, and is ignored with a warning.
1767 unless($locale =~ $LOCALE_RE) {
1768 $self->_warn({ warning => "$var contains invalid characters; ignoring" }) if(ref($self));
1769 return;
1770 }
1771  
1772 # A locale is not a language tag, and what follows matches tags:
1773 # "en_US.UTF-8" read as one names no language at all. So pass on the
1774 # tag the locale stands for, "en-US". "C" and "POSIX" name none.
1775 my $tag = _locale_tag($1);
1776 return unless defined($tag);
1777 if(ref($self)) {
1778 $self->_trace("_what_language set language to $tag from $var");
1779 $self->{_what_language_from_locale} = 1;
1780 return $self->{_what_language} = $tag;
1781 }
1782 return $tag;
1783 }
1784 return;
1785 }
1786  
1787 # -- _locale_tag -----------------------------------------------------------
1788 # Purpose: The language tag a POSIX locale name stands for.
1789 # Entry: $locale -- an untainted locale name ("en_US.UTF-8", "de_DE@euro",
1790 # "fr", "C").
1791 # Exit: "en-US", "de-DE", "fr"; undef for a name that is not a
1792 # language ("C", "POSIX", "C.UTF-8").
1793 sub _locale_tag
1794 {
1795 my $locale = $_[0];
1796  
1797 return undef unless(defined($locale) && ($locale =~ $LOCALE_TAG_RE));
1798 return defined($2) ? "$1-$2" : $1;
1799 }
1800  
1801 =head2 country
1802  
1803 Returns the two-letter country code (ISO 3166-1) of the visitor,
1804 in lower case, for example C<'us'>, C<'gb'> or C<'fr'>.
1805  
1806 Returns C<undef> when the country cannot be found, for example when
1807 C<REMOTE_ADDR> is not set, is not a valid IP address, or is a private
1808 (C<192.168.1.1>) or loopback (C<127.0.0.1>) address.
1809  
1810 In one special case it returns the string C<'Unknown'>:
1811 when a source says the address is in the European Union (C<EU>),
1812 which is not a country.
1813  
1814 Two answers are corrected: C<hk> (Hong Kong) is returned as C<cn>, and a Whois
1815 record that says C<US> with the state C<PR> is returned as C<pr> (Puerto Rico
1816 has its own country code; RT#131347).
1817  
1818 See L</Finding the country> for the order in which the sources are tried.
1819 If you have no GeoIP2 / GeoLite2 database and none of L<IP::Country>,
1820 L<Geo::IP> or L<Geo::IPfree> installed,
1821 every look-up goes over the network, so please use a C<cache> (see L</new>).
1822  
1823 The answer is remembered, so a second call on the same object is fast.
1824  
1825 Note that as of October 2026 geoplugin.net, one of the remote
1826 fallbacks, no longer has a free tier: it answers with an HTTP 403 and
1827 a "please upgrade to a paid plan" message, which contains no country
1828 code, so the lookup falls through to Whois.
1829 The geoplugin.net code is kept in case that changes.
1830  
1831 Legacy MaxMind F<GeoIP.dat> databases, as used by L<Geo::IP>, are no
1832 longer updated (Debian's C<geoip-database> package is frozen at
1833 2019-12-24), so they can give the wrong country for addresses that
1834 have been reallocated since then.
1835 A MaxMind GeoLite2 database is free (it needs a MaxMind account), is
1836 updated twice a week, and is used before any other local database.
1837 Install L<IP::Geolocation::MMDB> or L<MaxMind::DB::Reader> to read it,
1838 and keep it up to date with MaxMind's C<geoipupdate> program,
1839 which writes it to F</var/lib/GeoIP> on Debian and Ubuntu.
1840  
1841 =head3 API SPECIFICATION
1842  
1843 =head4 Input
1844  
1845 {}
1846  
1847 =head4 Output
1848  
1849 {
1850 type => 'string',
1851 matches => qr/^(?:[a-z][a-z]|Unknown)$/,
1852 optional => 1,
1853 }
1854  
1855 =head3 EXAMPLE
1856  
1857 # Behind Apache mod_geoip: no IP look-up is needed
1858 local $ENV{GEOIP_COUNTRY_CODE} = 'DE';
1859 my $l = CGI::Lingua->new(supported => ['en']);
1860 print $l->country(); # "de"
1861  
1862 # From the IP address (the answer depends on your geo database)
1863 local $ENV{REMOTE_ADDR} = '8.8.8.8';
1864 my $l = CGI::Lingua->new(supported => ['en']);
1865 print $l->country() // 'not known'; # "us"
1866  
1867 =head3 MESSAGES
1868  
1869 These are warnings. C<country()> does not die.
1870  
1871 "GEOIP_COUNTRY_CODE contains an invalid country code; ignoring"
1872 "HTTP_CF_IPCOUNTRY contains an invalid country code; ignoring"
1873 "X.X.X.X isn't a valid IP address"
1874 "cache contains a numeric country: N"
1875 "IP matches to a numeric country"
1876 "geoplugin returned unparseable JSON: ..."
1877 "Discarding malformed country code '...'"
1878 "geoplugin lookup failed: ..."
1879 "Cache get failed: ...", "Cache set failed: ...", "Cache remove failed: ..."
1880 "Discarding malformed cache entry for ..."
1881 "Can't open ... with Geo::IP; not using it"
1882 "Can't open ... with IP::Geolocation::MMDB or MaxMind::DB::Reader; not using it"
1883  
1884 These are debug messages, sent only to the logger:
1885  
1886 "Can't determine country from LAN connection X"
1887 "Can't determine country from loopback connection X"
1888  
1889 =head3 PSEUDOCODE
1890  
1891 1. Return the remembered answer if there is one
1892 2. Check GEOIP_COUNTRY_CODE env var (mod_geoip); validate /^[A-Z]{2}\z/
1893 3. Check HTTP_CF_IPCOUNTRY (Cloudflare); skip 'XX'; validate /^[A-Z]{2}\z/
1894 4. Untaint and validate REMOTE_ADDR; return undef if absent or invalid;
1895 change ::ffff:a.b.c.d into a.b.c.d
1896 5. Skip private and loopback IPs (return undef)
1897 6. Check CHI cache; return cached value if present
1898 7. Try a GeoIP2 / GeoLite2 .mmdb file from @GEOIP2_MMDB (local DB,
1899 read with IP::Geolocation::MMDB or MaxMind::DB::Reader)
1900 8. Try IP::Country::Fast (local DB)
1901 9. Try Geo::IP (local DB)
1902 10. Try Geo::IPfree (local DB, skip $BROKEN_GEOIPFREE)
1903 11. Try geoplugin.net JSON API (LWP::Simple::WithCache;
1904 no free tier as of October 2026, so normally yields nothing)
1905 12. Last resort: Net::Whois::IP then Net::Whois::IANA
1906 13. Sanitise: discard numeric, normalise HK->CN, handle EU special case,
1907 discard anything that is not two lower-case letters
1908 14. Store in CHI cache; return result
1909  
1910 =cut
1911  
1912 sub country {
1913 my $self = shift;
1914 local ($@, $!); # evals and lazy requires below must not leak to the caller
1915  
1916 $self->_trace(__PACKAGE__, ': Entered country()');
1917  
1918 # Return cached result immediately if a previous call already resolved it.
1919 # Note: undef results (private/loopback IPs) are NOT cached here because
1920 # country() reads REMOTE_ADDR at call time, not construction time; caching
1921 # undef would give wrong answers if REMOTE_ADDR changes between calls on
1922 # the same object (the documented lazy-read design). See LIMITATIONS.
1923 if($self->{_country}) {
1924 $self->_trace('quick return: ', $self->{_country});
1925 return $self->{_country};
1926 }
1927  
1928 # mod_geoip: validate against ISO 3166-1 alpha-2 before trusting
1929 if(defined($ENV{'GEOIP_COUNTRY_CODE'})) {
1930 if($ENV{'GEOIP_COUNTRY_CODE'} =~ /^([A-Z]{2})\z/a) {
1931 $self->{_country} = lc($1);
1932 return $self->{_country};
1933 } else {
1934 $self->_warn({ warning => 'GEOIP_COUNTRY_CODE contains an invalid country code; ignoring' });
1935 }
1936 }
1937  
1938 # Cloudflare: 'XX' means Cloudflare couldn't determine country -- skip it
1939 if(($ENV{'HTTP_CF_IPCOUNTRY'}) && ($ENV{'HTTP_CF_IPCOUNTRY'} ne 'XX')) {
1940 if($ENV{'HTTP_CF_IPCOUNTRY'} =~ /^([A-Z]{2})\z/a) {
1941 $self->{_country} = lc($1);
1942 return $self->{_country};
1943 } else {
1944 $self->_warn({ warning => 'HTTP_CF_IPCOUNTRY contains an invalid country code; ignoring' });
1945 }
1946 }
1947  
1948 my $raw_ip = $ENV{'REMOTE_ADDR'};
1949 return undef unless defined $raw_ip;
1950  
1951 # Validate and untaint the IP address before passing to any geo module
1952 my $ip = _untaint_ip($raw_ip);
1953 unless(defined($ip)) {
1954 $self->_warn({ warning => "$raw_ip isn't a valid IP address" });
1955 return undef;
1956 }
1957  
1958 # Data::Validate::IP depends on NetAddr::IP, which fails to build on Windows
1959 # (NetAddr::IP::UtilPP::mask4to6 bad-argument error). Try to load it once;
1960 # on failure install pure-Perl aliases for the four bare function names used
1961 # below so the rest of the function is unchanged on both platforms.
1962 # Import only those four: a plain import() installs all 29 of the module's
1963 # exports here, where they would become methods of every object.
1964 if(!defined($_have_dvip)) {
1965 local $SIG{__DIE__};
1966 if(eval { require Data::Validate::IP; Data::Validate::IP->import(qw(is_ipv4 is_ipv6 is_private_ip is_loopback_ip)); 1 }) {
1967 $_have_dvip = 1;
1968 } else {
1969 $_have_dvip = 0;
1970 no warnings 'redefine';
1971 *CGI::Lingua::is_ipv4 = \&_is_ipv4;
1972 *CGI::Lingua::is_ipv6 = \&_is_ipv6;
1973 *CGI::Lingua::is_private_ip = \&_is_private_ip;
1974 *CGI::Lingua::is_loopback_ip = \&_is_loopback_ip;
1975 }
1976 }
1977  
1978 if(!is_ipv4($ip)) {
1979 $self->_debug("$ip isn't IPv4. Is it IPv6?");
1980 if($ip eq '::1') {
1981 $ip = '127.0.0.1'; # normalise loopback
1982 } elsif($ip =~ /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i) {
1983 $ip = $1; # normalise IPv4-mapped IPv6 (::ffff:a.b.c.d) to plain IPv4
1984 # \d{1,3} matches 0-999; validate range before geo lookups because
1985 # some inet_aton implementations wrap out-of-range octets modulo 256,
1986 # turning 999.999.999.999 into a real routable address.
1987 unless(is_ipv4($ip)) {
1988 $self->_warn({ warning => "$ip isn't a valid IP address" });
1989 return undef;
1990 }
1991 } elsif(!is_ipv6($ip)) {
1992 $self->_warn({ warning => "$ip isn't a valid IP address" });
1993 return undef;
1994 }
1995 }
1996 if(is_private_ip($ip)) {
1997 $self->_debug("Can't determine country from LAN connection $ip");
1998 return undef;
1999 }
2000 if(is_loopback_ip($ip)) {
2001 $self->_debug("Can't determine country from loopback connection $ip");
2002 return undef;
2003 }
2004  
2005 # Cache look-up -- skip for LAN/loopback (already returned above)
2006 if($self->{_cache}) {
2007 $self->{_country} = $self->_cache_call($self->{_cache}, 'get', $CACHE_NS . "country:$ip");
2008 if(defined($self->{_country})) {
2009 if(!ref($self->{_country}) && ($self->{_country} !~ /\D/)) {
2010 $self->_warn({ warning => 'cache contains a numeric country: ' . $self->{_country} });
2011 $self->_cache_call($self->{_cache}, 'remove', $CACHE_NS . "country:$ip");
2012 delete $self->{_country};
2013 } elsif(ref($self->{_country}) || ($self->{_country} !~ $COUNTRY_RE)) {
2014 # Poisoned entry ("gb<script>", a hashref): same checks as a
2015 # fresh look-up, or the cache would bypass them
2016 $self->_warn({ warning => "Discarding malformed cache entry for ${CACHE_NS}country:$ip" });
2017 $self->_cache_call($self->{_cache}, 'remove', $CACHE_NS . "country:$ip");
2018 delete $self->{_country};
2019 } else {
2020 $self->_debug("Get $ip from cache = $self->{_country}");
2021 return $self->{_country};
2022 }
2023 }
2024 $self->_debug("$ip isn't in the cache");
2025 }
2026  
2027 # Try a GeoIP2 / GeoLite2 database first: it is the only local source
2028 # that is still updated. The record comes from a file, so check its
2029 # shape like any other upstream answer.
2030 if(my $record = $self->_mmdb_record($ip)) {
2031 my $cc = (ref($record->{country}) eq 'HASH') ? $record->{country}{iso_code} : undef;
2032 if(defined($cc) && !ref($cc) && ($cc =~ /^([A-Za-z]{2})\z/a)) {
2033 $self->{_country} = lc($1);
2034 } else {
2035 $self->_debug("$ip has no country in the GeoIP2 database");
2036 }
2037 }
2038  
2039 # Then IP::Country (fast, local database)
2040 unless(defined($self->{_country})) {
2041 if($self->{_have_ipcountry} == $GEO_UNKNOWN) {
2042 if(eval { require IP::Country::Fast }) {
2043 # Require the concrete class directly; IP::Country->import() is not needed
2044 # because IP::Country::Fast->new() is a fully-qualified class method call.
2045 $self->{_have_ipcountry} = $GEO_PRESENT;
2046 $self->{_ipcountry} = IP::Country::Fast->new();
2047 } else {
2048 $self->{_have_ipcountry} = $GEO_ABSENT;
2049 }
2050 }
2051 $self->_debug("have_ipcountry $self->{_have_ipcountry}");
2052  
2053 if($self->{_have_ipcountry}) {
2054 $self->{_country} = $self->{_ipcountry}->inet_atocc($ip);
2055 if($self->{_country}) {
2056 $self->{_country} = lc($self->{_country});
2057 } elsif(is_ipv4($ip)) {
2058 $self->_debug("$ip is not known by IP::Country");
2059 }
2060 }
2061 }
2062  
2063 # Try Geo::IP if IP::Country gave nothing
2064 unless(defined($self->{_country})) {
2065 if($self->{_have_geoip} == $GEO_UNKNOWN) {
2066 $self->_load_geoip();
2067 }
2068 if($self->{_have_geoip} == $GEO_PRESENT) {
2069 $self->{_country} = $self->{_geoip}->country_code_by_addr($ip);
2070 }
2071  
2072 # Geo::IPfree has a known-broken entry for $BROKEN_GEOIPFREE
2073 if(!defined($self->{_country}) && ($ip ne $BROKEN_GEOIPFREE)) {
2074 if($self->{_have_geoipfree} == $GEO_UNKNOWN) {
2075 eval { require Geo::IPfree };
2076 unless($@) {
2077 # No ->import(): Geo::IPfree uses only OO (->LookUp); the old
2078 # Geo::IPfree::IP->import() call was a wrong package and could
2079 # clobber Test::Mockingbird mocks on some versions.
2080 $self->{_have_geoipfree} = $GEO_PRESENT;
2081 $self->{_geoipfree} = Geo::IPfree->new();
2082 } else {
2083 $self->{_have_geoipfree} = $GEO_ABSENT;
2084 }
2085 }
2086 if($self->{_have_geoipfree} == $GEO_PRESENT) {
2087 if(my $country = ($self->{_geoipfree}->LookUp($ip))[0]) {
2088 $self->{_country} = lc($country);
2089 }
2090 }
2091 }
2092 }
2093  
2094 # 'eu' is not a real country -- discard
2095 if($self->{_country} && ($self->{_country} eq 'eu')) {
2096 delete $self->{_country};
2097 }
2098  
2099 # Remote JSON lookup via geoplugin
2100 if((!$self->{_country}) &&
2101 (eval { require LWP::Simple::WithCache; require JSON::Parse })) {
2102 $self->_debug("Look up $ip on geoplugin");
2103  
2104 # A timeout or connection error must not take down the request;
2105 # fall through to Whois instead
2106 my $data = eval { local $SIG{__DIE__}; LWP::Simple::WithCache::get("https://www.geoplugin.net/json.gp?ip=$ip") };
2107 $self->_warn({ warning => "geoplugin lookup failed: $@" }) if $@;
2108 if($data) {
2109 eval { $self->{_country} = JSON::Parse::parse_json($data)->{'geoplugin_countryCode'} };
2110 $self->_warn({ warning => "geoplugin returned unparseable JSON: $@" }) if $@;
2111 }
2112  
2113 # Check the answer now rather than at the end: a junk value (an object,
2114 # "GB<script>") is true, so it would stop the Whois fallback below and
2115 # then be thrown away, leaving no country at all
2116 my $v = $self->{_country};
2117 if(defined($v) && (ref($v) || $v !~ /^[A-Za-z]{2}\z/)) {
2118 if(!ref($v) && length($v) && ($v !~ /\D/)) {
2119 $self->_warn({ warning => 'IP matches to a numeric country' });
2120 } elsif(ref($v) || length($v)) {
2121 $self->_warn({ warning => q{Discarding malformed country code '} . lc($v) . q{'} });
2122 }
2123 delete $self->{_country};
2124 }
2125 }
2126  
2127 # Last resort: Whois
2128 unless($self->{_country}) {
2129 $self->_resolve_country_via_whois($ip);
2130 }
2131  
2132 # Sanitise and normalise whatever we found
2133 if($self->{_country}) {
2134 if($self->{_country} !~ /\D/) {
2135 $self->_warn({ warning => 'IP matches to a numeric country' });
2136 delete $self->{_country};
2137 } else {
2138 $self->{_country} = lc($self->{_country});
2139  
2140 # Legacy mappings
2141 if($self->{_country} eq 'hk') {
2142 $self->{_country} = 'cn'; # HK is no longer a separate country in Whois
2143 } elsif($self->{_country} eq 'eu') {
2144 $self->_handle_eu_country($ip);
2145 }
2146  
2147 if($self->{_country} && ($self->{_country} !~ /\D/)) {
2148 $self->_warn({ warning => "cache contains a numeric country: $self->{_country}" });
2149 delete $self->{_country};
2150 } elsif($self->{_country} &&
2151 $self->{_country} ne 'Unknown' &&
2152 ($self->{_country} !~ /^[a-z]{2}$/)) {
2153 # Reject anything that is not exactly 2 lowercase ASCII letters,
2154 # unless it is the 'Unknown' sentinel written by _handle_eu_country
2155 # for EU addresses that do not map to a specific country.
2156 # Guards against Whois CRLF injection leftovers ("gbx-header: evil")
2157 # and XSS payloads in JSON API responses ("gb<script>...</script>").
2158 $self->_warn({ warning => "Discarding malformed country code '$self->{_country}'" });
2159 delete $self->{_country};
2160 } elsif($self->{_country} && $self->{_cache}) {
2161 $self->_debug("Set $ip to $self->{_country}");
2162 $self->_cache_call($self->{_cache}, 'set',
2163 $CACHE_NS . "country:$ip",
2164 $self->{_country},
2165 $CACHE_TTL_SHORT
2166 );
2167 }
2168 }
2169 }
2170  
2171 return $self->{_country};
2172 }
2173  
2174 # -- _resolve_country_via_whois ---------------------------------------------
2175 # Purpose: Attempt Net::Whois::IP then Net::Whois::IANA as a last resort.
2176 # Entry: $ip -- validated, untainted IP string.
2177 # Exit: Sets $self->{_country} if a result was found.
2178 # Side Effects: Network I/O; logs debug messages.
2179 sub _resolve_country_via_whois
2180 {
2181 my ($self, $ip) = @_;
2182  
2183 $self->_debug("Look up $ip on Whois");
2184  
2185 require Net::Whois::IP;
2186 # No ->import(): whoisip_query is called fully-qualified, so import is unneeded
2187 # and on some versions reinstalls the real function, clobbering Test::Mockingbird mocks.
2188  
2189 my $whois;
2190 eval {
2191 # Catch connection timeouts by converting Carp::carp into a die
2192 local $SIG{__WARN__} = sub { die $_[0] };
2193 $whois = Net::Whois::IP::whoisip_query($ip);
2194 };
2195  
2196 unless($@ || !defined($whois) || (ref($whois) ne 'HASH')) {
2197 if(defined($whois->{Country})) {
2198 $self->{_country} = $whois->{Country};
2199 } elsif(defined($whois->{country})) {
2200 $self->{_country} = $whois->{country};
2201 }
2202 if($self->{_country}) {
2203 if($self->{_country} eq 'EU') {
2204 delete $self->{_country};
2205 } elsif(($self->{_country} eq 'US') && defined($whois->{'StateProv'}) && ($whois->{'StateProv'} eq 'PR')) {
2206 # RT#131347: Puerto Rico is not the US
2207 $self->{_country} = 'pr';
2208 }
2209 }
2210 }
2211  
2212 if($self->{_country}) {
2213 $self->_debug("Found $ip on Net::Whois::IP as ", $self->{_country});
2214 $self->{_country} = _clean_country_code($self->{_country});
2215 # _clean_country_code returns undef for malformed values (e.g. CRLF
2216 # injection leftovers); if so, fall through to the IANA look-up.
2217 return if defined $self->{_country};
2218 delete $self->{_country};
2219 }
2220  
2221 $self->_debug("Look up $ip on IANA");
2222  
2223 require Net::Whois::IANA;
2224 # No ->import(): Net::Whois::IANA->new() is a class method; import not needed.
2225  
2226 # The whole IANA exchange is in one eval: new(), the query and the parse
2227 # of the answer can all die on a network or protocol error, and this is
2228 # the last resort, so a failure simply means "no country"
2229 my $country;
2230 if(eval {
2231 local $SIG{__DIE__};
2232 my $iana = Net::Whois::IANA->new();
2233 $iana->whois_query(-ip => $ip);
2234 $country = $iana->country();
2235 1;
2236 }) {
2237 $self->{_country} = $country;
2238 $self->_debug("IANA reports $ip as ", $self->{_country});
2239 } else {
2240 $self->_debug("IANA look-up of $ip failed: $@");
2241 }
2242  
2243 if($self->{_country}) {
2244 $self->{_country} = _clean_country_code($self->{_country});
2245 delete $self->{_country} unless defined $self->{_country};
2246 }
2247 }
2248  
2249 # -- _clean_country_code ---------------------------------------------------
2250 # Purpose: Strip carriage returns and trailing "#..." comments that some
2251 # Whois servers append to their country field
2252 # (e.g. "US\r", "GB # United Kingdom").
2253 # Entry: $raw -- raw country string from a Whois response.
2254 # Exit: Cleaned 2-char country code string.
2255 sub _clean_country_code
2256 {
2257 my ($raw) = @_;
2258 return unless defined($raw);
2259 $raw =~ s/[\r\n]//g;
2260 # Accept exactly 2 alpha chars, optionally followed by whitespace and a
2261 # comment (e.g. "GB # United Kingdom"). Anything else (CRLF injection
2262 # leftovers, embedded headers) returns undef so the caller can discard it
2263 # rather than propagating a malformed string through the geo pipeline.
2264 if($raw =~ /^([A-Za-z]{2})\s*(?:#.*)?$/) {
2265 return $1;
2266 }
2267 return;
2268 }
2269  
2270 # -- _in_baidu_subnet ------------------------------------------------------
2271 # Purpose: Pure-Perl fallback check for the Baidu IPv4 subnet
2272 # 185.10.104.0/22. Used when Net::Subnet is absent (e.g. on
2273 # Windows where its Socket6 dependency fails to build).
2274 # Entry: $ip -- untainted IPv4 string.
2275 # Exit: Returns true if $ip is within the /22 block, false otherwise.
2276 sub _in_baidu_subnet
2277 {
2278 my $ip = shift;
2279 return 0 unless defined($ip) && $ip =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\z/a;
2280 # pack('C') wraps octets above 255 (300 becomes 44), which would put a
2281 # malformed address such as 185.10.104.300 inside the subnet
2282 return 0 if grep { $_ > 255 } ($1, $2, $3, $4);
2283 # pack/unpack avoids signed-integer overflow on 32-bit Perl
2284 my $n = unpack('N', pack('C4', $1, $2, $3, $4));
2285 my $net = unpack('N', pack('C4', 185, 10, 104, 0));
2286 return (($n & 0xFFFFFC00) == ($net & 0xFFFFFC00));
2287 }
2288  
2289 # -- _handle_eu_country ----------------------------------------------------
2290 # Purpose: Resolve the ambiguous 'eu' country code. RT-86809 shows that
2291 # Baidu reports itself as EU when it is actually in CN. All
2292 # other 'eu' addresses are logged as Unknown.
2293 # Entry: $ip -- validated, untainted IP string.
2294 # Exit: Sets $self->{_country} to 'cn' or 'Unknown'.
2295 # Side Effects: Optionally loads Net::Subnet; writes info log entry.
2296 sub _handle_eu_country
2297 {
2298 my ($self, $ip) = @_;
2299  
2300 # Prefer Net::Subnet for correctness; fall back to the pure-Perl helper
2301 # when it is absent (Socket6, its indirect dep, fails to build on Windows).
2302 my $in_baidu;
2303 if(eval { require Net::Subnet; Net::Subnet->import(); 1 }) {
2304 $in_baidu = subnet_matcher($BAIDU_SUBNET)->($ip);
2305 } else {
2306 $in_baidu = _in_baidu_subnet($ip);
2307 }
2308  
2309 if($in_baidu) {
2310 $self->{_country} = 'cn';
2311 } else {
2312 $self->_info("$ip has country of eu");
2313 $self->{_country} = 'Unknown';
2314 }
2315 }
2316  
2317 # -- _load_geoip -----------------------------------------------------------
2318 # Purpose: Probe for the Geo::IP database file and the Geo::IP module;
2319 # set _have_geoip and initialise _geoip on success.
2320 # Entry: _have_geoip must be GEO_UNKNOWN.
2321 # Exit: _have_geoip set to GEO_PRESENT or GEO_ABSENT.
2322 # Side Effects: Requires Geo::IP; opens GeoIP.dat.
2323 sub _load_geoip
2324 {
2325 my $self = shift;
2326  
2327 # Check for the database file before even trying to load the module
2328 # (avoids noisy errors on Windows -- CPANTESTERS report 54117bd0)
2329 my ($dat) = grep { -f $_ && -r _ } @GEOIP_DAT;
2330 unless(defined($dat)) {
2331 $self->{_have_geoip} = $GEO_ABSENT;
2332 return;
2333 }
2334  
2335 unless(eval { local $SIG{__DIE__}; require Geo::IP; 1 }) {
2336 $self->{_have_geoip} = $GEO_ABSENT;
2337 return;
2338 }
2339  
2340 # No ->import(): Geo::IP->open() is a class method. GEOIP_STANDARD = 0
2341 # (the constant cannot be used by name). A corrupt or truncated file makes
2342 # open() die or return undef; treat that as no database, rather than let
2343 # country() call a method on undef later.
2344 my $geoip = eval { local $SIG{__DIE__}; Geo::IP->open($dat, 0) };
2345 if(Scalar::Util::blessed($geoip)) {
2346 $self->{_have_geoip} = $GEO_PRESENT;
2347 $self->{_geoip} = $geoip;
2348 } else {
2349 $self->_warn({ warning => "Can't open $dat with Geo::IP; not using it" });
2350 $self->{_have_geoip} = $GEO_ABSENT;
2351 }
2352 }
2353  
2354 # -- _load_mmdb ------------------------------------------------------------
2355 # Purpose: Find a GeoIP2 / GeoLite2 database in @GEOIP2_MMDB and open it
2356 # with the first module in @MMDB_READERS that can.
2357 # Entry: _have_mmdb must be GEO_UNKNOWN.
2358 # Exit: _have_mmdb set to GEO_PRESENT (and _mmdb to the reader) or
2359 # GEO_ABSENT. Warns if a reader is installed but none can open
2360 # the file (corrupt or truncated download).
2361 # Side Effects: Requires the reader modules; opens the .mmdb file.
2362 sub _load_mmdb
2363 {
2364 my $self = shift;
2365  
2366 $self->{_have_mmdb} = $GEO_ABSENT;
2367  
2368 # Look for the file before loading a module, as _load_geoip() does
2369 my ($file) = grep { -f $_ && -r _ } @GEOIP2_MMDB;
2370 return unless defined($file);
2371  
2372 my $have_reader = 0;
2373 for my $class (@MMDB_READERS) {
2374 (my $pm = "$class.pm") =~ s{::}{/}g;
2375 next unless eval { local $SIG{__DIE__}; require $pm; 1 };
2376 $have_reader = 1;
2377  
2378 # No ->import(): both are used only through new() and methods
2379 my $reader = eval { local $SIG{__DIE__}; $class->new(file => $file) };
2380 if(Scalar::Util::blessed($reader)) {
2381 $self->_debug("Using $file with $class");
2382 $self->{_have_mmdb} = $GEO_PRESENT;
2383 $self->{_mmdb} = $reader;
2384 return;
2385 }
2386 }
2387 if($have_reader) {
2388 # Not $@: MaxMind::DB::Reader's message carries a whole stack trace
2389 $self->_warn({ warning => "Can't open $file with " . join(' or ', @MMDB_READERS) . '; not using it' });
2390 }
2391 }
2392  
2393 # -- _mmdb_record ----------------------------------------------------------
2394 # Purpose: Look an address up in the GeoIP2 / GeoLite2 database.
2395 # Entry: $ip, already untainted and validated.
2396 # Exit: The record (a hashref, e.g. { country => { iso_code => 'GB' },
2397 # location => { time_zone => 'Europe/London' } }), or undef if
2398 # there is no database, no record, or the look-up died (an IPv6
2399 # address in an IPv4-only database dies in IP::Geolocation::MMDB).
2400 sub _mmdb_record
2401 {
2402 my ($self, $ip) = @_;
2403  
2404 $self->_load_mmdb() if $self->{_have_mmdb} == $GEO_UNKNOWN;
2405 return undef unless $self->{_have_mmdb} == $GEO_PRESENT;
2406  
2407 my $record = eval { local $SIG{__DIE__}; $self->{_mmdb}->record_for_address($ip) };
2408 return (ref($record) eq 'HASH') ? $record : undef;
2409 }
2410  
2411 =head2 locale
2412  
2413 Returns a L<Locale::Object::Country> object for the visitor's country.
2414 You can use it to find, for example, the currency or the country's name.
2415  
2416 HTTP does not send a browser's local settings (such as the currency or the
2417 date format), so this is a B<best guess>. It is not always right.
2418  
2419 It tries these, in order:
2420  
2421 =over 4
2422  
2423 =item 1. A language tag such as C<en-GB> inside the C<HTTP_USER_AGENT> string.
2424  
2425 =item 2. L<HTTP::BrowserDetect>, if it is installed.
2426  
2427 =item 3. L</country>.
2428  
2429 =item 4. C<GEOIP_COUNTRY_CODE>.
2430  
2431 =back
2432  
2433 Returns C<undef> when nothing is found.
2434  
2435 =head3 API SPECIFICATION
2436  
2437 =head4 Input
2438  
2439 {}
2440  
2441 =head4 Output
2442  
2443 {
2444 type => 'object',
2445 isa => 'Locale::Object::Country',
2446 optional => 1,
2447 }
2448  
2449 =head3 EXAMPLE
2450  
2451 local $ENV{REMOTE_ADDR} = '8.8.8.8';
2452 my $l = CGI::Lingua->new(supported => ['en']);
2453 if(my $locale = $l->locale()) {
2454 print $locale->name(), "\n"; # e.g. "United States"
2455 print $locale->currency()->code(), "\n"; # e.g. "USD"
2456 }
2457  
2458 =head3 MESSAGES
2459  
2460 "HTTP_USER_AGENT contains invalid characters or exceeds length limit; ignoring"
2461  
2462 =head3 PSEUDOCODE
2463  
2464 1. Return the remembered answer if there is one
2465 2. Parse HTTP_USER_AGENT parenthetical for xx-YY language tag
2466 3. Try HTTP::BrowserDetect on the full User-Agent string
2467 4. Fall back to country() IP lookup
2468 5. Fall back to GEOIP_COUNTRY_CODE env var (ISO 3166-1 validated)
2469 6. Return undef if all strategies fail
2470  
2471 =cut
2472  
2473 sub locale {
2474 my $self = shift;
2475 local ($@, $!); # evals below must not leak to the caller
2476  
2477 # One store, so a failed search (undef) is tried again next time
2478 return $self->{_locale} ||= $self->_find_locale();
2479 }
2480  
2481 # -- _find_locale --------------------------------------------------------------
2482 #
2483 # Purpose: Search for the visitor's Locale::Object::Country, without
2484 # remembering it (locale() does that).
2485 # Entry: $self -- a CGI::Lingua object.
2486 # Exit: A Locale::Object::Country object, or undef.
2487 # Side effects: May call country(), which caches the country.
2488 sub _find_locale {
2489 my $self = shift;
2490  
2491 # Validate and untaint HTTP_USER_AGENT before passing to any parser.
2492 # The User-Agent header is attacker-controlled; apply the same discipline
2493 # as HTTP_ACCEPT_LANGUAGE. Printable ASCII (0x20-0x7e), bounded length.
2494 my $agent;
2495 if(defined(my $raw_agent = $ENV{'HTTP_USER_AGENT'})) {
2496 if($raw_agent =~ /^([\x20-\x7e]{1,$UA_MAX})$/a) {
2497 $agent = $1; # untainted
2498 } else {
2499 $self->_warn({ warning => 'HTTP_USER_AGENT contains invalid characters or exceeds length limit; ignoring' });
2500 }
2501 }
2502  
2503 # First try: parse the language tag from the User-Agent parenthetical
2504 if(defined($agent) && ($agent =~ /\((.+)\)/)) {
2505 foreach(split(/;/, $1)) {
2506 my $candidate = $_;
2507 $candidate =~ s/^\s+|\s+$//g; # trim both ends
2508  
2509 if($candidate =~ /^[a-zA-Z]{2}-([a-zA-Z]{2})$/) {
2510 local $SIG{__WARN__} = undef;
2511 if(my $c = $self->_code2country($1)) {
2512 return $c;
2513 }
2514 }
2515 }
2516  
2517 # Second try: HTTP::BrowserDetect (works for more User-Agents)
2518 if(eval { require HTTP::BrowserDetect }) {
2519 HTTP::BrowserDetect->import();
2520 my $browser = HTTP::BrowserDetect->new($agent);
2521 # Validate country() result before use -- the return value comes from
2522 # the third-party module and is not yet untainted or range-checked.
2523 if($browser) {
2524 my $bc = $browser->country() // '';
2525 if($bc =~ /^([A-Za-z]{2})$/a) {
2526 if(my $c = $self->_code2country($1)) {
2527 return $c;
2528 }
2529 }
2530 }
2531 }
2532 }
2533  
2534 # Third try: IP address
2535 my $country = $self->country();
2536 if($country) {
2537 $country =~ s/[\r\n]//g;
2538 my $c;
2539 eval {
2540 local $SIG{__WARN__} = sub { die $_[0] };
2541 $c = $self->_code2country($country);
2542 };
2543 unless($@) {
2544 if($c) {
2545 return $c;
2546 }
2547 }
2548 }
2549  
2550 # Fourth try: mod_geoip env var -- apply the same ISO 3166-1 validation
2551 # used in country() to guard against spoofed or malformed values
2552 if(defined($ENV{'GEOIP_COUNTRY_CODE'})) {
2553 if($ENV{'GEOIP_COUNTRY_CODE'} =~ /^([A-Z]{2})\z/a) {
2554 if(my $c = $self->_code2country(lc($1))) {
2555 return $c;
2556 }
2557 }
2558 }
2559 return undef;
2560 }
2561  
2562 =head2 time_zone
2563  
2564 Returns the visitor's time zone, as an IANA time zone name,
2565 for example C<'Europe/London'> or C<'America/New_York'>.
2566  
2567 When C<REMOTE_ADDR> is set, it uses a MaxMind GeoIP2 or GeoLite2 City database
2568 (see L</@CGI::Lingua::GEOIP2_MMDB>), then L<Geo::IP>, if a database is installed,
2569 and otherwise asks the ip-api.com web service (this needs
2570 L<LWP::Simple::WithCache> or L<LWP::Simple>, and L<JSON::Parse>).
2571  
2572 When C<REMOTE_ADDR> is not set (for example on the command line),
2573 it returns the time zone of the computer that runs the program.
2574  
2575 Returns C<undef> when the time zone cannot be found.
2576  
2577 =head3 API SPECIFICATION
2578  
2579 =head4 Input
2580  
2581 {}
2582  
2583 =head4 Output
2584  
2585 {
2586 type => 'string',
2587 matches => qr/^[A-Za-z][A-Za-z0-9_+\-\/]*$/,
2588 optional => 1,
2589 }
2590  
2591 =head3 EXAMPLE
2592  
2593 local $ENV{REMOTE_ADDR} = '8.8.8.8';
2594 my $l = CGI::Lingua->new(supported => ['en']);
2595 print $l->time_zone() // 'unknown'; # e.g. "America/New_York"
2596  
2597 =head3 MESSAGES
2598  
2599 These are warnings. C<time_zone()> does not die.
2600  
2601 "Couldn't determine the timezone"
2602 "X.X.X.X isn't a valid IP address"
2603 "LWP::Simple::WithCache and LWP::Simple are both absent; cannot contact ip-api.com"
2604 "JSON::Parse is absent; cannot read ip-api.com answers"
2605 "ip-api.com returned unparseable JSON: ..."
2606 "DateTime::TimeZone::Local failed: ..."
2607 "Discarding malformed timezone '...'"
2608 "ip-api.com lookup failed: ..."
2609 "Can't open ... with IP::Geolocation::MMDB or MaxMind::DB::Reader; not using it"
2610  
2611 =head3 PSEUDOCODE
2612  
2613 1. Return the remembered answer if there is one
2614 2. If REMOTE_ADDR is set:
2615 a. Untaint and validate the IP
2616 b. Try location/time_zone in a GeoIP2 / GeoLite2 City .mmdb (local DB)
2617 c. Try Geo::IP->time_zone() (local DB)
2618 d. Try LWP::Simple::WithCache + JSON::Parse against ip-api.com
2619 e. Fall back to LWP::Simple + JSON::Parse against ip-api.com
2620 f. Warn and return undef if neither LWP variant, or JSON::Parse,
2621 is installed (the warning names the missing module)
2622 3. If REMOTE_ADDR is absent (local/CLI mode):
2623 a. Read /etc/timezone if readable
2624 b. Fall back to DateTime::TimeZone::Local->TimeZone()->name()
2625 4. Discard the answer if it does not look like an IANA name
2626 5. Warn "Couldn't determine the timezone" and return undef if all fail
2627  
2628 =cut
2629  
2630 sub time_zone {
2631 my $self = shift;
2632 local ($@, $!); # evals, open() and HTTP calls must not leak to the caller
2633  
2634 $self->_trace('Entered time_zone');
2635  
2636 if($self->{_timezone}) {
2637 $self->_trace('quick return: ', $self->{_timezone});
2638 return $self->{_timezone};
2639 }
2640  
2641 my $raw_ip = $ENV{'REMOTE_ADDR'};
2642  
2643 if(defined $raw_ip) {
2644 # Untaint before any external use -- kept in sync with country()'s pattern,
2645 # including the mixed-notation branch for ::ffff:a.b.c.d addresses.
2646 my $ip = _untaint_ip($raw_ip);
2647 unless(defined($ip)) {
2648 $self->_warn({ warning => "$raw_ip isn't a valid IP address" });
2649 return undef;
2650 }
2651  
2652 # A GeoIP2 / GeoLite2 City database has the zone; a Country one does
2653 # not. The value is checked against $ZONE_RE below.
2654 if(my $record = $self->_mmdb_record($ip)) {
2655 if(ref($record->{location}) eq 'HASH') {
2656 $self->{_timezone} = $record->{location}{time_zone};
2657 }
2658 }
2659  
2660 unless($self->{_timezone}) {
2661 if($self->{_have_geoip} == $GEO_UNKNOWN) {
2662 $self->_load_geoip();
2663 }
2664 if($self->{_have_geoip} == $GEO_PRESENT) {
2665 eval { $self->{_timezone} = $self->{_geoip}->time_zone($ip) };
2666 }
2667 }
2668  
2669 unless($self->{_timezone}) {
2670 if(eval { require LWP::Simple::WithCache; require JSON::Parse }) {
2671 $self->_debug("Look up $ip on ip-api.com");
2672  
2673 my $data = eval { local $SIG{__DIE__}; LWP::Simple::WithCache::get("http://ip-api.com/json/$ip") };
2674 $self->_warn({ warning => "ip-api.com lookup failed: $@" }) if $@;
2675 if($data) {
2676 eval { $self->{_timezone} = JSON::Parse::parse_json($data)->{'timezone'} };
2677 $self->_warn({ warning => "ip-api.com returned unparseable JSON: $@" }) if $@;
2678 }
2679 } elsif(eval { require LWP::Simple; require JSON::Parse }) {
2680 $self->_debug("Look up $ip on ip-api.com");
2681  
2682 my $data = eval { local $SIG{__DIE__}; LWP::Simple::get("http://ip-api.com/json/$ip") };
2683 $self->_warn({ warning => "ip-api.com lookup failed: $@" }) if $@;
2684 if($data) {
2685 eval { $self->{_timezone} = JSON::Parse::parse_json($data)->{'timezone'} };
2686 $self->_warn({ warning => "ip-api.com returned unparseable JSON: $@" }) if $@;
2687 }
2688 } else {
2689 # A module is missing -- degrade gracefully rather than killing the
2690 # entire request with a croak; caller can check for undef. Name the
2691 # module that is really missing: an LWP may be present without JSON::Parse.
2692 if(eval { require LWP::Simple::WithCache; 1 } || eval { require LWP::Simple; 1 }) {
2693 $self->_warn({ warning => 'JSON::Parse is absent; cannot read ip-api.com answers' });
2694 } else {
2695 $self->_warn({ warning => 'LWP::Simple::WithCache and LWP::Simple are both absent; cannot contact ip-api.com' });
2696 }
2697 }
2698 }
2699 } else {
2700 # Local connection -- read from /etc/timezone or DateTime::TimeZone
2701 if(defined(my $tz = $self->_read_zone_file())) {
2702 $self->{_timezone} = $tz;
2703 } else {
2704 # DateTime::TimeZone::Local::TimeZone() is not available on all
2705 # platforms/versions (absent on some Windows Perl builds); guard
2706 # so time_zone() degrades to undef rather than dying.
2707 eval {
2708 local $SIG{__DIE__};
2709 require DateTime::TimeZone::Local;
2710 $self->{_timezone} = DateTime::TimeZone::Local->TimeZone()->name();
2711 };
2712 $self->_warn({ warning => "DateTime::TimeZone::Local failed: $@" }) if $@;
2713 }
2714 }
2715  
2716 # Validate the timezone string against a permissive but bounded IANA pattern.
2717 # Rejects XSS payloads (e.g. "Europe/London<script>...") from hostile JSON
2718 # responses while accepting all real IANA zone names (e.g. "America/New_York",
2719 # "Etc/GMT+8", "UTC").
2720 if(defined($self->{_timezone}) &&
2721 (ref($self->{_timezone}) || ($self->{_timezone} !~ $ZONE_RE))) {
2722 $self->_warn({ warning => "Discarding malformed timezone '" . _printable($self->{_timezone}) . "'" });
2723 delete $self->{_timezone};
2724 }
2725  
2726 unless(defined($self->{_timezone})) {
2727 $self->_warn({ warning => "Couldn't determine the timezone" });
2728 }
2729 return $self->{_timezone};
2730 }
2731  
2732 # -- _read_zone_file ------------------------------------------------------
2733 # Purpose: Read the system time zone name from $ZONE_FILE (normally
2734 # /etc/timezone) for command-line use.
2735 # Entry: none.
2736 # Exit: The zone name, or undef if the file is missing, unreadable,
2737 # not a regular file, empty, or does not hold a zone name.
2738 # Notes: Only a regular file is opened, and at most $ZONE_FILE_MAX bytes
2739 # are read: a symlink to /dev/zero or /dev/urandom, or a huge
2740 # file, must not hang the request or exhaust memory. CORE::
2741 # calls bypass autodie, so a failure returns undef, not a die.
2742 sub _read_zone_file
2743 {
2744 my $self = shift;
2745  
2746 return undef unless -f $ZONE_FILE && -r _;
2747 CORE::open(my $fin, '<', $ZONE_FILE) or return undef;
2748 my $got = CORE::read($fin, my $buf, $ZONE_FILE_MAX);
2749 CORE::close($fin);
2750 return undef unless $got;
2751  
2752 # First word of the file; surrounding spaces and newlines are not part of it
2753 my ($zone) = $buf =~ /\A\s*(\S+)/;
2754 unless(defined($zone) && ($zone =~ $ZONE_RE)) {
2755 $self->_debug("$ZONE_FILE does not hold a time zone name");
2756 return undef;
2757 }
2758 return $zone;
2759 }
2760  
2761 =head2 is_rtl
2762  
2763 Returns C<1> if the chosen language is written from right to left,
2764 and C<0> if it is not.
2765  
2766 The right-to-left languages are Arabic (C<ar>), Dhivehi (C<dv>),
2767 Persian (C<fa>), Hebrew (C<he>), Kurdish (C<ku>), Pashto (C<ps>),
2768 Sindhi (C<sd>), Uyghur (C<ug>), Urdu (C<ur>) and Yiddish (C<yi>).
2769  
2770 When no language was found, it returns C<0>.
2771  
2772 =head3 API SPECIFICATION
2773  
2774 =head4 Input
2775  
2776 {}
2777  
2778 =head4 Output
2779  
2780 {
2781 type => 'boolean',
2782 memberof => [0, 1],
2783 }
2784  
2785 =head3 EXAMPLE
2786  
2787 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'ar';
2788 my $l = CGI::Lingua->new(supported => ['ar', 'en']);
2789 print $l->is_rtl(); # 1
2790  
2791 =cut
2792  
2793 sub is_rtl
2794 {
2795 my $self = shift;
2796 return $RTL_LANGS{$self->language_code_alpha2() // ''} ? 1 : 0;
2797 }
2798  
2799 =head2 text_direction
2800  
2801 Returns C<'rtl'> (right to left) or C<'ltr'> (left to right) for the chosen
2802 language. You can use the value directly in the HTML C<dir> attribute.
2803  
2804 When no language was found, it returns C<'ltr'>.
2805  
2806 =head3 API SPECIFICATION
2807  
2808 =head4 Input
2809  
2810 {}
2811  
2812 =head4 Output
2813  
2814 {
2815 type => 'string',
2816 memberof => ['ltr', 'rtl'],
2817 }
2818  
2819 =head3 EXAMPLE
2820  
2821 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'he';
2822 my $l = CGI::Lingua->new(supported => ['he', 'en']);
2823 print '<html dir="', $l->text_direction(), '">'; # <html dir="rtl">
2824  
2825 =cut
2826  
2827 sub text_direction
2828 {
2829 my $self = shift;
2830 return $self->is_rtl() ? 'rtl' : 'ltr';
2831 }
2832  
2833 =head2 plural_category($n)
2834  
2835 Many languages use a different word form for different numbers.
2836 English has two forms ("1 file", "2 files"); Russian has more;
2837 Japanese has only one.
2838  
2839 C<plural_category($n)> tells you which form to use for the number C<$n>
2840 in the chosen language.
2841 It returns one of C<'zero'>, C<'one'>, C<'two'>, C<'few'>, C<'many'> or
2842 C<'other'>. These are the Unicode CLDR plural category names.
2843  
2844 The rules for about 70 languages are built in, including Arabic (6 forms),
2845 Slavic languages (3 or 4 forms), Celtic languages (up to 6 forms), Hebrew,
2846 Maltese, Romanian, Latvian, Lithuanian and Slovenian.
2847 Other languages use the English rule: C<'one'> for 1, otherwise C<'other'>.
2848  
2849 When no language was found, it always returns C<'other'>.
2850  
2851 C<$n> should be a whole number that is zero or more.
2852 A number with a fractional part is cut down to a whole number first
2853 (2.7 becomes 2).
2854 For full CLDR rules, including fractions, use L<Locale::CLDR>.
2855  
2856 =head3 API SPECIFICATION
2857  
2858 =head4 Input
2859  
2860 [
2861 { type => 'number', min => 0 },
2862 ]
2863  
2864 =head4 Output
2865  
2866 {
2867 type => 'string',
2868 memberof => ['zero', 'one', 'two', 'few', 'many', 'other'],
2869 }
2870  
2871 =head3 EXAMPLE
2872  
2873 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'ru';
2874 my $l = CGI::Lingua->new(supported => ['ru']);
2875 print $l->plural_category(1); # "one"
2876 print $l->plural_category(3); # "few"
2877 print $l->plural_category(11); # "many"
2878  
2879 =head3 MESSAGES
2880  
2881 "plural_category: $n must be defined"
2882 - dies (croak) when $n is undef
2883  
2884 =cut
2885  
2886 # CLDR plural category rules (https://unicode.org/cldr/charts/42/supplemental/language_plural_rules.html).
2887 # Values are coderefs: ($n) -> category string. Languages absent from this
2888 # table fall back to the standard one/other rule inside plural_category().
2889 my %PLURAL_RULES = (
2890  
2891 # -- No plural distinction (always 'other') ----------------------------
2892 (map { $_ => sub { 'other' } }
2893 qw(az bm bo dz id ig ii in ja jbo jv jw kde kea km ko lkt lo ms
2894 my nqo root sah ses sg th to vi wo yo zh)),
2895  
2896 # -- Standard: n == 1 -> 'one', else 'other' ---------------------------
2897 (map { $_ => sub { int($_[0]) == 1 ? 'one' : 'other' } }
2898 qw(af an ast bg bn brx ca cgg da de el en eo es et eu fi
2899 gl gsw gu ha haw hu ia it kcg kk kl lb lg mas ml mn mr
2900 nb nd ne nl nn nyn om or pa pap rm rof rwk saq seh sn so
2901 sq ss ssy st sv sw ta te teo tig tk tl tn ts ur wae xh xog)),
2902  
2903 # -- French / Portuguese-BR: n <= 1 -> 'one' ----------------------------
2904 (map { $_ => sub { int($_[0]) <= 1 ? 'one' : 'other' } } qw(fr pt_BR)),
2905  
2906 # -- Arabic: zero/one/two/few/many/other -------------------------------
2907 ar => sub {
2908 my $n = int($_[0]);
2909 my $m100 = $n % 100;
2910 return 'zero' if $n == 0;
2911 return 'one' if $n == 1;
2912 return 'two' if $n == 2;
2913 return 'few' if $m100 >= 3 && $m100 <= 10;
2914 return 'many' if $m100 >= 11 && $m100 <= 99;
2915 return 'other';
2916 },
2917  
2918 # -- Hebrew: one/two/many/other ----------------------------------------
2919 he => sub {
2920 my $n = int($_[0]);
2921 return 'one' if $n == 1;
2922 return 'two' if $n == 2;
2923 return 'many' if $n != 0 && $n % 10 == 0;
2924 return 'other';
2925 },
2926  
2927 # -- Russian / Ukrainian / Belarusian: one/few/many --------------------
2928 (map { $_ => sub {
2929 my $n = int($_[0]);
2930 my $m10 = $n % 10;
2931 my $m100 = $n % 100;
2932 return 'one' if $m10 == 1 && $m100 != 11;
2933 return 'few' if $m10 >= 2 && $m10 <= 4 && ($m100 < 10 || $m100 >= 20);
2934 return 'many';
2935 } } qw(ru uk be)),
2936  
2937 # -- Polish: one/few/many ----------------------------------------------
2938 pl => sub {
2939 my $n = int($_[0]);
2940 my $m10 = $n % 10;
2941 my $m100 = $n % 100;
2942 return 'one' if $n == 1;
2943 return 'few' if $m10 >= 2 && $m10 <= 4 && ($m100 < 10 || $m100 >= 20);
2944 return 'many';
2945 },
2946  
2947 # -- Czech / Slovak: one/few/other ------------------------------------
2948 (map { $_ => sub {
2949 my $n = int($_[0]);
2950 return 'one' if $n == 1;
2951 return 'few' if $n >= 2 && $n <= 4;
2952 return 'other';
2953 } } qw(cs sk)),
2954  
2955 # -- Romanian: one/few/other -------------------------------------------
2956 ro => sub {
2957 my $n = int($_[0]);
2958 my $m100 = $n % 100;
2959 return 'one' if $n == 1;
2960 return 'few' if $n == 0 || ($m100 >= 1 && $m100 <= 19);
2961 return 'other';
2962 },
2963  
2964 # -- Latvian: zero/one/other -------------------------------------------
2965 lv => sub {
2966 my $n = int($_[0]);
2967 my $m10 = $n % 10;
2968 my $m100 = $n % 100;
2969 return 'zero' if $m10 == 0 || ($m100 >= 11 && $m100 <= 19);
2970 return 'one' if $m10 == 1 && $m100 != 11;
2971 return 'other';
2972 },
2973  
2974 # -- Lithuanian: one/few/other -----------------------------------------
2975 lt => sub {
2976 my $n = int($_[0]);
2977 my $m10 = $n % 10;
2978 my $m100 = $n % 100;
2979 return 'one' if $m10 == 1 && ($m100 < 10 || $m100 >= 20);
2980 return 'few' if $m10 >= 2 && ($m100 < 10 || $m100 >= 20);
2981 return 'other';
2982 },
2983  
2984 # -- Slovenian: one/two/few/other --------------------------------------
2985 sl => sub {
2986 my $m100 = int($_[0]) % 100;
2987 return 'one' if $m100 == 1;
2988 return 'two' if $m100 == 2;
2989 return 'few' if $m100 == 3 || $m100 == 4;
2990 return 'other';
2991 },
2992  
2993 # -- Welsh: zero/one/two/few/many/other -------------------------------
2994 cy => sub {
2995 my $n = int($_[0]);
2996 return 'zero' if $n == 0;
2997 return 'one' if $n == 1;
2998 return 'two' if $n == 2;
2999 return 'few' if $n == 3;
3000 return 'many' if $n == 6;
3001 return 'other';
3002 },
3003  
3004 # -- Irish: one/two/few/many/other ------------------------------------
3005 ga => sub {
3006 my $n = int($_[0]);
3007 return 'one' if $n == 1;
3008 return 'two' if $n == 2;
3009 return 'few' if $n >= 3 && $n <= 6;
3010 return 'many' if $n >= 7 && $n <= 10;
3011 return 'other';
3012 },
3013  
3014 # -- Maltese: one/two/few/many/other ----------------------------------
3015 mt => sub {
3016 my $n = int($_[0]);
3017 my $m100 = $n % 100;
3018 return 'one' if $n == 1;
3019 return 'two' if $n == 2;
3020 return 'few' if $n == 0 || ($m100 >= 3 && $m100 <= 10);
3021 return 'many' if $m100 >= 11 && $m100 <= 19;
3022 return 'other';
3023 },
3024 );
3025  
3026 sub plural_category
3027 {
3028 my ($self, $n) = @_;
3029 Carp::croak('plural_category: $n must be defined') unless defined $n;
3030 my $code = $self->language_code_alpha2() // return 'other';
3031 my $rule = $PLURAL_RULES{$code} // sub { int($_[0]) == 1 ? 'one' : 'other' };
3032 return $rule->($n);
3033 }
3034  
3035 =head2 translation_file($dir, $ext)
3036  
3037 Finds the translation file for the chosen language in the directory C<$dir>,
3038 and returns its path.
3039  
3040 It tries these file names, in order, and returns the first one that is a
3041 readable regular file:
3042  
3043 =over 4
3044  
3045 =item 1. C<$dir/$lang-$sublang.$ext> (for example F<en-gb.json>)
3046  
3047 =item 2. C<$dir/$lang.$ext> (for example F<en.json>)
3048  
3049 =back
3050  
3051 C<$ext> is the file extension. It is C<'json'> if you do not give it.
3052 You can write it with or without the dot (C<'po'> or C<'.po'>).
3053  
3054 Returns C<undef> when no such file exists, when no language was found,
3055 when C<$dir> is C<undef>, or when C<$dir> or C<$ext> is unsafe (see below).
3056 A directory, a device (such as F</dev/urandom>), a broken symbolic link or a
3057 file you cannot read is never returned, even if it has the right name.
3058  
3059 For safety, C<$dir> must be a non-empty string (not a reference) without
3060 C<..> or a null byte, and C<$ext> may only contain letters, digits and C<->.
3061 Control characters in a rejected value are shown as C<\xNN> in the warning.
3062  
3063 =head3 API SPECIFICATION
3064  
3065 =head4 Input
3066  
3067 [
3068 { type => 'string', min => 1 },
3069 { type => 'string', min => 1, matches => qr/^\.?[A-Za-z0-9-]+$/, optional => 1 },
3070 ]
3071  
3072 =head4 Output
3073  
3074 {
3075 type => 'string',
3076 optional => 1,
3077 }
3078  
3079 =head3 EXAMPLE
3080  
3081 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'en-gb';
3082 my $l = CGI::Lingua->new(supported => ['en-gb', 'en']);
3083  
3084 my $path = $l->translation_file('/var/www/i18n');
3085 # '/var/www/i18n/en-gb.json' if it exists,
3086 # else '/var/www/i18n/en.json' if it exists,
3087 # else undef
3088  
3089 # A different extension
3090 my $po = $l->translation_file('/var/www/i18n', 'po');
3091  
3092 =head3 MESSAGES
3093  
3094 These are warnings. C<translation_file()> does not die.
3095  
3096 "translation_file: unsafe directory '...' rejected"
3097 "translation_file: unsafe extension '...' rejected"
3098  
3099 =cut
3100  
3101 sub translation_file
3102 {
3103 my ($self, $dir, $ext) = @_;
3104 local $!; # a failed file test sets $!
3105 return undef unless defined $dir;
3106  
3107 # Reject traversal attempts in the directory argument. A real translation
3108 # directory never needs '..' or null bytes; an empty name would mean "/",
3109 # and a reference would be used as the string "ARRAY(0x...)".
3110 if(ref($dir) || !length($dir) || $dir =~ /\.\./ || $dir =~ /\x00/) {
3111 $self->_warn({ warning => "translation_file: unsafe directory '" . _printable($dir) . "' rejected" });
3112 return undef;
3113 }
3114  
3115 $ext //= 'json';
3116 $ext =~ s/^\.//; # accept '.json' or 'json'
3117  
3118 # Valid extensions are letters, digits and hyphens only (e.g. 'json', 'po',
3119 # 'yml'); \z, not $, so "json\n" is refused too
3120 unless($ext =~ /^[A-Za-z0-9\-]+\z/) {
3121 $self->_warn({ warning => "translation_file: unsafe extension '" . _printable($ext) . "' rejected" });
3122 return undef;
3123 }
3124  
3125 # The codes become part of a path, so check their shape even though they
3126 # come from the negotiated language
3127 my $lang = $self->language_code_alpha2();
3128 return undef unless defined($lang) && ($lang =~ $LANG_CODE_RE);
3129 my @candidates;
3130 if(defined(my $sub = $self->sublanguage_code_alpha2())) {
3131 push @candidates, "$lang-$sub" if $sub =~ $LANG_CODE_RE;
3132 }
3133 push @candidates, $lang;
3134  
3135 # A translation file must be a readable regular file: a directory, a
3136 # device such as /dev/urandom, a dangling symlink or an unreadable file
3137 # named en.json is not one, and handing it back would only fail later
3138 for my $code (@candidates) {
3139 my $path = "$dir/$code.$ext";
3140 return $path if -f $path && -r _;
3141 }
3142 return undef;
3143 }
3144  
3145 # -- _printable ------------------------------------------------------------
3146 # Purpose: Make a caller-supplied value safe to put in a log message:
3147 # control and non-ASCII characters (newlines that would forge
3148 # log lines, NULs, terminal escapes) become \xNN.
3149 # Entry: $value -- any scalar; a reference is shown as its type.
3150 # Exit: A printable ASCII string.
3151 sub _printable
3152 {
3153 my $value = shift;
3154 return 'undef' unless defined($value);
3155 return ref($value) . ' reference' if ref($value);
3156 $value =~ s/([^\x20-\x7e])/sprintf('\\x%02x', ord($1))/ge;
3157 return $value;
3158 }
3159  
3160 # -- _code2language --------------------------------------------------------
3161 # Purpose: Translate a 2-char language code to its English name, with
3162 # optional CHI caching.
3163 # Entry: $code -- 2-char ISO 639-1 code; must be defined and non-empty.
3164 # Exit: Human-readable language name string, or undef.
3165 # Side Effects: Reads/writes cache.
3166 sub _code2language
3167 {
3168 my ($self, $code) = @_;
3169  
3170 return unless $code;
3171 if(defined($self->{_country})) {
3172 $self->_debug("_code2language $code, country ", $self->{_country});
3173 } else {
3174 $self->_debug("_code2language $code");
3175 }
3176  
3177 unless($self->{_cache}) {
3178 return Locale::Language::code2language($code);
3179 }
3180  
3181 if(my $from_cache = $self->_cache_get_valid($CACHE_NS . "code2language:$code", $NAME_RE)) {
3182 $self->_trace("_code2language found in cache $from_cache");
3183 return $from_cache;
3184 }
3185  
3186 # Compute, cache, then return the value separately --
3187 # CHI->set() is not guaranteed to return the stored value across all drivers
3188 $self->_trace('_code2language not in cache, storing');
3189 my $name = Locale::Language::code2language($code);
3190 if(defined $name) {
3191 $self->_cache_call($self->{_cache}, 'set', $CACHE_NS . "code2language:$code", $name, $CACHE_TTL_LONG);
3192 }
3193 return $name;
3194 }
3195  
3196 # -- _code2country ---------------------------------------------------------
3197 # Purpose: Translate a 2-char country code to a Locale::Object::Country
3198 # object, suppressing the expected "No result found" warning.
3199 # Entry: $code -- 2-char ISO 3166-1 alpha-2 code (any case).
3200 # Exit: Locale::Object::Country object, or undef.
3201 # Side Effects: None beyond the Locale::Object::Country look-up.
3202 sub _code2country
3203 {
3204 my ($self, $code) = @_;
3205  
3206 return unless $code;
3207 if($self->{_country}) {
3208 $self->_trace(">_code2country $code, country ", $self->{_country});
3209 } else {
3210 $self->_trace(">_code2country $code");
3211 }
3212  
3213 my $rc;
3214 if($_locale_object_db_ok // 1) {
3215 # Suppress the routine "No result found" warning; catch the database-
3216 # absent exception that Windows installations sometimes throw.
3217 local $SIG{__WARN__} = _warn_filter(qr/No result found in country table/);
3218 eval { $rc = Locale::Object::Country->new(code_alpha2 => $code) };
3219 if($@) {
3220 $_locale_object_db_ok = 0
3221 if $@ =~ /database was not in/;
3222 $rc = undef;
3223 } else {
3224 $_locale_object_db_ok = 1;
3225 }
3226 }
3227 $self->_trace('<_code2country ', $code || 'undef');
3228 return $rc;
3229 }
3230  
3231 # -- _country_short_name ---------------------------------------------------
3232 # Purpose: Return the common short English name for an ISO 3166-1 alpha-2
3233 # code when Locale::Object's database is unavailable. Uses
3234 # %COUNTRY_SHORT_NAMES overrides for codes where Locale::Codes
3235 # returns the full ISO official name rather than the short form.
3236 # Entry: $code -- 2-char country code (any case).
3237 # Exit: Short name string, or undef.
3238 sub _country_short_name
3239 {
3240 my ($self, $code) = @_;
3241 return unless defined($code);
3242 my $lc = lc($code);
3243 return $COUNTRY_SHORT_NAMES{$lc} if exists $COUNTRY_SHORT_NAMES{$lc};
3244 # Locale::Object may have partially initialised Locale::Codes::Country as a
3245 # dependency before we get here; suppress the spurious 'redefine' warning
3246 # that some Perl/Locale::Codes combinations produce on first full load.
3247 { local $SIG{__WARN__} = _warn_filter(qr/redefined/);
3248 require Locale::Codes::Country; }
3249 return Locale::Codes::Country::code2country($lc, 'alpha-2');
3250 }
3251  
3252 # -- _code2countryname -----------------------------------------------------
3253 # Purpose: Translate a 2-char country code to its English name string,
3254 # with optional CHI caching.
3255 # Entry: $code -- 2-char ISO 3166-1 alpha-2 code.
3256 # Exit: Country name string, or undef.
3257 # Side Effects: Reads/writes cache.
3258 sub _code2countryname
3259 {
3260 my ($self, $code) = @_;
3261  
3262 return unless $code;
3263 $self->_trace(">_code2countryname $code");
3264  
3265 unless($self->{_cache}) {
3266 my $country = $self->_code2country($code);
3267 return $country->name if defined($country);
3268 return $self->_country_short_name($code);
3269 }
3270  
3271 if(my $from_cache = $self->_cache_get_valid($CACHE_NS . "code2countryname:$code", $NAME_RE)) {
3272 $self->_trace("_code2countryname found in cache $from_cache");
3273 return $from_cache;
3274 }
3275  
3276 my $name;
3277 if(my $country = $self->_code2country($code)) {
3278 $name = $country->name();
3279 } else {
3280 # Locale::Object database absent (common on Windows); fall back to
3281 # Locale::Codes::Country with a short-name correction table.
3282 $name = $self->_country_short_name($code);
3283 }
3284  
3285 if(defined($name)) {
3286 $self->_debug('_code2countryname not in cache, storing');
3287 $self->_trace('<_code2countryname ', $name);
3288 $self->_cache_call($self->{_cache}, 'set', $CACHE_NS . "code2countryname:$code", $name, $CACHE_TTL_LONG);
3289 return $name;
3290 }
3291 $self->_trace('<_code2countryname undef');
3292 return;
3293 }
3294  
3295 # -- _log ------------------------------------------------------------------
3296 # Purpose: Append a message to $self->{messages} and forward to the
3297 # optional logger object.
3298 # Entry: $level -- log level string (debug/info/notice/warn/trace/error);
3299 # @messages -- one or more strings to concatenate.
3300 # Exit: void
3301 # Side Effects: Mutates $self->{messages}; calls logger method if set.
3302 sub _log
3303 {
3304 my ($self, $level, @messages) = @_;
3305  
3306 return unless ref($self) && scalar(@messages);
3307  
3308 my $text = join('', grep defined, @messages);
3309 return unless length($text);
3310 push @{$self->{'messages'}}, { level => $level, message => $text };
3311  
3312 if(my $logger = $self->{'logger'}) {
3313 $logger->$level($text);
3314 }
3315 }
3316  
3317 sub _debug { my $self = shift; $self->_log('debug', @_) }
3318 sub _info { my $self = shift; $self->_log('info', @_) }
3319 sub _notice { my $self = shift; $self->_log('notice', @_) }
3320 sub _trace { my $self = shift; $self->_log('trace', @_) }
3321  
3322 # -- _warn -----------------------------------------------------------------
3323 # Purpose: Emit a warning through the logger (if set) or via Carp::carp.
3324 # Entry: A single hashref argument: { warning => 'message text' }.
3325 # All callers MUST use this structured form -- plain-string calls
3326 # silently lose the message when no logger is configured.
3327 # Exit: void
3328 # Side Effects: Calls logger->warn() or carp().
3329 sub _warn
3330 {
3331 my $self = shift;
3332  
3333 # Parse once; both branches need the same $msg.
3334 my $params = Params::Get::get_params('warning', @_);
3335 my $msg = (ref($params) ? $params->{'warning'} : undef) // join('', grep defined, @_);
3336  
3337 if(defined($self->{'logger'})) {
3338 $self->{'logger'}->warn($msg);
3339 } else {
3340 $self->_log('warn', $msg);
3341 Carp::carp($msg);
3342 }
3343 }
3344  
3345 # -- _warn_filter ----------------------------------------------------------
3346 # Purpose: Build a $SIG{__WARN__} handler that drops warnings matching
3347 # $skip and passes every other warning on to the handler that
3348 # was active when the filter was built.
3349 # Entry: $skip -- compiled regex of warnings to drop.
3350 # Exit: Code reference suitable for "local $SIG{__WARN__} = ...".
3351 # Notes: A plain "warn" inside a __WARN__ handler bypasses every handler
3352 # and goes straight to STDERR, so the caller's handler (a logger,
3353 # Test::Warnings, ...) would never see the warning; hence the
3354 # explicit call to the previous handler.
3355 sub _warn_filter
3356 {
3357 my $skip = shift;
3358 my $prev = $SIG{__WARN__};
3359  
3360 return sub {
3361 return if $_[0] =~ $skip;
3362 if(ref($prev) eq 'CODE') {
3363 $prev->(@_);
3364 } else {
3365 warn @_;
3366 }
3367 };
3368 }
3369  
3370 # -- Pure-Perl IP-validation helpers ------------------------------------------
3371 # These are installed into the CGI::Lingua symbol table as is_ipv4() etc. when
3372 # Data::Validate::IP / NetAddr::IP are unavailable (see country()).
3373  
3374 sub _is_ipv4 {
3375 my $ip = shift;
3376 # /a: without it \d also matches non-ASCII digits such as U+0661, which
3377 # then compare as 0 and make "\x{661}.\x{661}.\x{661}.\x{661}" look valid
3378 return unless defined($ip) && $ip =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\z/a;
3379 # A leading zero is refused, as Data::Validate::IP does: inet_aton reads
3380 # "010" as octal 8, while the range checks here would read it as 10
3381 return !(grep { ($_ > 255) || /^0\d/ } ($1, $2, $3, $4));
3382 }
3383  
3384 # RFC 4291 section 2.2 text form, parsed in Perl. Not Socket::inet_pton: on
3385 # Windows that is Winsock's InetPton, which fails for every address until
3386 # WSAStartup has run, and Perl only runs it when the first socket is made, so
3387 # a CGI script that has not opened a socket saw no IPv6 address as valid.
3388 sub _is_ipv6 {
3389 my $ip = shift;
3390 return unless defined($ip) && $ip =~ /:/;
3391  
3392 # A trailing dotted quad ("::ffff:1.2.3.4") stands for the last two groups
3393 if($ip =~ /^(.*:)(\d{1,3}(?:\.\d{1,3}){3})\z/as) {
3394 my ($head, $v4) = ($1, $2);
3395 return 0 unless _is_ipv4($v4);
3396 $ip = "${head}0:0";
3397 }
3398 return 0 unless $ip =~ /^[0-9A-Fa-f:]+\z/;
3399  
3400 # At most one "::", which stands for one or more groups of zeros
3401 my @halves = split(/::/, $ip, -1);
3402 return 0 if(scalar(@halves) > 2);
3403 my $groups = 0;
3404 for my $half (grep { length } @halves) {
3405 for my $group (split(/:/, $half, -1)) {
3406 return 0 unless $group =~ $IPV6_GROUP_RE;
3407 $groups++;
3408 }
3409 }
3410 return (scalar(@halves) == 2) ? ($groups < $IPV6_GROUPS) : ($groups == $IPV6_GROUPS);
3411 }
3412  
3413 sub _is_private_ip {
3414 my $ip = shift;
3415 return unless defined($ip);
3416 if($ip =~ /^(\d+)\.(\d+)/) {
3417 my ($a, $b) = ($1 + 0, $2 + 0);
3418 return 1 if $a == 10;
3419 return 1 if $a == 172 && $b >= 16 && $b <= 31;
3420 return 1 if $a == 192 && $b == 168;
3421 return 1 if $a == 169 && $b == 254; # link-local / APIPA
3422 return 0;
3423 }
3424 return 1 if $ip =~ /^fe[89ab][0-9a-f]:/i; # fe80::/10 link-local
3425 return 1 if $ip =~ /^f[cd]/i; # fc00::/7 ULA
3426 return 0;
3427 }
3428  
3429 sub _is_loopback_ip {
3430 my $ip = shift;
3431 return unless defined($ip);
3432 return 1 if $ip eq '::1';
3433 return $ip =~ /^127\./;
3434 }
3435  
3436 =head1 COMMON PITFALLS
3437  
3438 =over 4
3439  
3440 =item * B<Configuration files and environment variables win over your arguments>
3441  
3442 L</new> passes its arguments to L<Object::Configure>.
3443 If a configuration file (C<config_file>) or an environment variable such as
3444 C<CGI__Lingua__supported> sets a value, that value B<replaces> the value you
3445 gave to C<new()>.
3446  
3447 Values are replaced, not merged. If you pass C<< supported => ['en', 'fr'] >>
3448 and the configuration file says C<supported: [de]>, the object supports only
3449 C<de>, not C<en>, C<fr> and C<de>.
3450 For nested values (hashes inside hashes) see the rules in L<Object::Configure>.
3451  
3452 =item * B<A copy made with C<< $object->new() >> keeps old answers>
3453  
3454 When you call C<new()> on an object, the copy starts with every answer that the
3455 original has already worked out. So if the original has already called
3456 L</language>, the copy returns the same language,
3457 even if you give the copy a different C<supported> list:
3458  
3459 my $l = CGI::Lingua->new(supported => ['en', 'fr']);
3460 print $l->language(); # "French"
3461 my $copy = $l->new(supported => ['en']);
3462 print $copy->language(); # still "French"
3463  
3464 Make the copy before you call any other method, or create a new object with
3465 C<< CGI::Lingua->new() >>.
3466  
3467 =item * B<'Unknown' is not the same as undef>
3468  
3469 Some methods return the B<string> C<'Unknown'> and some return C<undef>
3470 when they do not know the answer. C<'Unknown'> is a true value in Perl,
3471 so C<if($l-E<gt>language())> is always true.
3472  
3473 Method When it does not know
3474 ------------------------ -----------------------------
3475 language() 'Unknown' (never undef)
3476 requested_language() 'Unknown' (never undef)
3477 sublanguage() undef
3478 language_code_alpha2() undef
3479 sublanguage_code_alpha2() undef
3480 country() undef ('Unknown' for EU addresses)
3481 locale() undef
3482 time_zone() undef
3483 translation_file() undef
3484 is_rtl() 0
3485 text_direction() 'ltr'
3486 plural_category() 'other'
3487  
3488 Always test with C<eq 'Unknown'> or C<defined()>, as the table shows.
3489  
3490 C<undef> really is one value, even in list context, so it is safe to build a
3491 hash from the results:
3492  
3493 my %vars = (country => $l->country(), zone => $l->time_zone());
3494 # $vars{zone} is the time zone even when country() is undef
3495  
3496 =item * B<plural_category() returns 'other' when there is no language>
3497  
3498 When no supported language was found, C<plural_category(1)> returns
3499 C<'other'>, not C<'one'>. Have an C<'other'> form for every message.
3500 C<plural_category(undef)> dies.
3501  
3502 =item * B<C<supported =E<gt> 0> and C<supported =E<gt> ''> count as missing>
3503  
3504 A false value for C<supported> is treated as if you did not give it,
3505 so C<new()> dies with "You must give a list of supported languages".
3506  
3507 =item * B<Answers are worked out once, then remembered>
3508  
3509 The first call to a language method reads C<%ENV> and remembers the answer.
3510 If you change C<%ENV> afterwards, the object does not notice.
3511 Create a new object for each web request.
3512  
3513 =item * B<country() reads REMOTE_ADDR when you call it>
3514  
3515 C<country()> reads C<$ENV{REMOTE_ADDR}> when you B<call> it,
3516 not when you create the object. In tests, call C<country()> while
3517 C<REMOTE_ADDR> still has the value you want:
3518  
3519 {
3520 local $ENV{REMOTE_ADDR} = '8.8.8.8';
3521 my $l = CGI::Lingua->new(supported => ['en']);
3522 $country = $l->country(); # correct: inside the block
3523 }
3524  
3525 =item * B<A bad header is ignored completely>
3526  
3527 If C<HTTP_ACCEPT_LANGUAGE> is longer than 256 characters, or contains a
3528 character that is not allowed (see L</ENCODING>), the whole header is ignored
3529 with a warning. CGI::Lingua then uses the locale (C<LC_ALL>, C<LC_MESSAGES>,
3530 C<LANG>) or the IP address instead.
3531  
3532 =item * B<The supported list holds tags, not names>
3533  
3534 C<< supported => ['english', 'fr'] >> supports only French: C<'english'> is not a
3535 language tag, so it is dropped (with a warning). Use C<'en'>.
3536  
3537 =item * B<Language names are in English>
3538  
3539 L</language> returns C<'French'>, not C<'Francais'>, and C<'German'>, not
3540 C<'Deutsch'>. Use L</language_code_alpha2> if you want to show the name in
3541 the language itself.
3542  
3543 =item * B<The logger you pass is replaced>
3544  
3545 L<Object::Configure> always changes C<logger> into a new L<Log::Abstraction>
3546 object, so C<< $l->{logger} >> is not the object you passed.
3547  
3548 =item * B<Whole objects are only cached when REMOTE_ADDR is set>
3549  
3550 The answers of an object are read from the cache in L</new>, and written to it
3551 when the object is destroyed, only when C<REMOTE_ADDR> is set.
3552 On the command line, only smaller look-ups (such as code-to-name) are cached.
3553  
3554 =item * B<Local geo databases can be out of date>
3555  
3556 Old F<GeoIP.dat> files can give the wrong country for some addresses
3557 (see L</country>); use a GeoLite2 database instead.
3558  
3559 =back
3560  
3561 =head1 ENCODING
3562  
3563 CGI::Lingua works with ASCII text. This table shows what each input accepts.
3564  
3565 Input Accepted characters Non-ASCII / UTF-8 / emoji
3566 ---------------------- ------------------------- -------------------------
3567 supported language tags (en, en-gb, no: entry is ignored,
3568 es-419); a plain string with a warning
3569 must be 2-5 chars
3570 HTTP_ACCEPT_LANGUAGE A-Z a-z 0-9 - , ; = . * no: header is ignored
3571 space and tab (never CR or
3572 LF); max 256 chars
3573 lang (CGI::Info) as HTTP_ACCEPT_LANGUAGE no: parameter is ignored
3574 LC_ALL, LC_MESSAGES, A-Z a-z 0-9 _ . - @ no: the variable is
3575 LANG ignored
3576 HTTP_USER_AGENT printable ASCII no: user agent ignored
3577 (0x20-0x7E), max 512 chars
3578 REMOTE_ADDR IPv4 or IPv6 address no: address is rejected
3579 GEOIP_COUNTRY_CODE exactly two of A-Z no: value is ignored
3580 HTTP_CF_IPCOUNTRY exactly two of A-Z no: value is ignored
3581 translation_file $dir any, except ".." and NUL yes, if your file system
3582 supports it (pass bytes
3583 encoded as the file
3584 system expects)
3585 translation_file $ext A-Z a-z 0-9 - no: undef is returned
3586 plural_category $n a number not applicable
3587  
3588 All values that CGI::Lingua returns are plain ASCII: language names
3589 (C<'French'>), country names (C<'Reunion'>), codes and time zone names.
3590 You do not need to decode them.
3591  
3592 =head1 CONFIGURATION VARIABLES
3593  
3594 Two package variables say where CGI::Lingua looks for files on the local
3595 machine. You do not normally need to change them; tests and unusual
3596 installations can, with C<local>:
3597  
3598 =over 4
3599  
3600 =item * C<$CGI::Lingua::ZONE_FILE>
3601  
3602 The file that L</time_zone> reads when there is no C<REMOTE_ADDR> (command-line
3603 use). The default is F</etc/timezone>. Only a readable regular file is used,
3604 and only its first 256 bytes are read; otherwise L<DateTime::TimeZone> is used.
3605  
3606 local $CGI::Lingua::ZONE_FILE = '/srv/myapp/timezone';
3607  
3608 =item * C<@CGI::Lingua::GEOIP_DAT>
3609  
3610 The places where L</country> and L</time_zone> look for the legacy MaxMind
3611 F<GeoIP.dat> used by L<Geo::IP>; the first readable regular file is used. The
3612 default is F</usr/share/GeoIP/GeoIP.dat> and F</usr/local/share/GeoIP/GeoIP.dat>
3613 (and F<c:/GeoIP/GeoIP.dat> first, on Windows). A file that L<Geo::IP> cannot
3614 open is skipped with the warning C<"Can't open ... with Geo::IP; not using it">.
3615  
3616 local @CGI::Lingua::GEOIP_DAT = ('/opt/geo/GeoIP.dat');
3617  
3618 =item * C<@CGI::Lingua::GEOIP2_MMDB>
3619  
3620 The places where L</country> and L</time_zone> look for a MaxMind GeoIP2 or
3621 GeoLite2 database (a F<.mmdb> file); the first readable regular file is used.
3622 The default is F<GeoIP2-City.mmdb>, F<GeoLite2-City.mmdb>,
3623 F<GeoIP2-Country.mmdb> and F<GeoLite2-Country.mmdb>, in that order, in each of
3624 F</var/lib/GeoIP>, F</usr/share/GeoIP> and F</usr/local/share/GeoIP> (and
3625 F<c:/GeoIP> first, on Windows). Only a City database holds time zones.
3626  
3627 The file is read with L<IP::Geolocation::MMDB> (fast, needs the libmaxminddb
3628 C library) or, if that is not installed, L<MaxMind::DB::Reader> (pure Perl,
3629 installed with L<GeoIP2::Database::Reader>). If neither is installed the
3630 database is not used. A file that neither can open is skipped with the warning
3631 C<"Can't open ... with IP::Geolocation::MMDB or MaxMind::DB::Reader; not using it">.
3632  
3633 local @CGI::Lingua::GEOIP2_MMDB = ('/srv/geo/GeoLite2-City.mmdb');
3634  
3635 =back
3636  
3637 =head1 LIMITATIONS
3638  
3639 =over 4
3640  
3641 =item * B<is_rtl() covers primary-script RTL languages only>
3642  
3643 C<is_rtl()> returns true for the 10 ISO 639-1 codes whose overwhelmingly
3644 dominant script is right-to-left. Languages with script variants (e.g.
3645 Azerbaijani C<az>, which uses Latin in modern Azerbaijan but Arabic in Iran)
3646 are treated as LTR. If you serve content in multiple scripts of the same
3647 language, inspect the sublanguage or Accept-Language header directly.
3648  
3649 =item * B<plural_category() uses embedded CLDR rules, not Locale::CLDR>
3650  
3651 The embedded rules cover ~70 languages and truncate fractional C<$n> to an
3652 integer. For full CLDR v42 accuracy (including fractional forms and
3653 languages not in the table) install and use C<Locale::CLDR> directly.
3654  
3655 =item * B<The logger is always a Log::Abstraction object>
3656  
3657 The C<logger> argument can be an object with C<warn()>, C<info()> and
3658 C<error()> methods, or any value that L<Object::Configure> accepts (such as an
3659 array reference or a hash reference of options). In every case
3660 L<Object::Configure> replaces it with a L<Log::Abstraction> object. An object
3661 that is missing one of the three methods is rejected by L</new>.
3662  
3663 =item * B<es-419 sublanguage returns undef>
3664  
3665 Three-part regional codes such as C<es-419> (Latin American Spanish) do not
3666 resolve to a C<sublanguage()> value because ISO 3166-1 does not define '419'.
3667 This is a known limitation of the Locale::Object layer.
3668  
3669 =item * B<Whois lookups are slow and unreliable>
3670  
3671 Without a GeoIP2 / GeoLite2 database, C<IP::Country>, C<Geo::IP>, or C<Geo::IPfree>, C<country()>
3672 falls back to Whois queries against live RIPE/ARIN/IANA servers. These can
3673 time out under load. Install at least one local geo-database module and enable
3674 the CHI cache to avoid this.
3675  
3676 =item * B<Private methods are accessible from outside the package>
3677  
3678 The C<_*> methods use the naming convention for privacy but Perl does not enforce
3679 it. C<Sub::Private> or C<Sub::Protected> should be added once all white-box
3680 tests (C<t/function.t>, C<t/extended_tests.t>) are updated to use the public API
3681 exclusively.
3682  
3683 =item * B<IPv4-mapped IPv6 addresses are normalised to IPv4>
3684  
3685 C<REMOTE_ADDR> values in the form C<::ffff:a.b.c.d> (RFC 4291 section 2.5.5)
3686 are silently rewritten to the embedded C<a.b.c.d> IPv4 address before any
3687 geo-lookup. This is correct for country detection purposes but means the raw
3688 address string is not preserved in cache keys or log messages.
3689  
3690 =item * B<EU country code is irresolvable (with one exception)>
3691  
3692 IP addresses that Whois reports as country C<EU> are mapped to C<'Unknown'>
3693 unless they fall within Baidu's known subnet (RT-86809). There is no ISO
3694 3166-1 country code for the European Union.
3695  
3696 =item * B<country() does not cache undef results>
3697  
3698 When C<country()> cannot determine a country (private IPs, loopback,
3699 unresolvable addresses), it returns C<undef> without storing the result. A
3700 second call on the same object repeats the full validation pipeline. This is
3701 intentional: C<country()> reads C<REMOTE_ADDR> at call time rather than at
3702 construction time, so caching C<undef> would return a wrong answer if
3703 C<REMOTE_ADDR> changes between calls. In practice this is rarely a problem
3704 because C<country()> is called once per request and CGI applications typically
3705 create a fresh object per request.
3706  
3707 =back
3708  
3709 =head1 AUTHOR
3710  
3711 Nigel Horne, C<< <njh at nigelhorne.com> >>
3712  
3713 =head1 BUGS
3714  
3715 If C<HTTP_ACCEPT_LANGUAGE> contains a sub-tag with a 3-digit UN M.49 region
3716 code (e.g. C<es-419> for Latin American Spanish), C<sublanguage()> returns
3717 C<undef> because ISO 3166-1 does not define numeric codes.
3718  
3719 Uses L<I18N::AcceptLanguage> to find the highest priority accepted language.
3720 This means that if you support languages at a lower priority, it may be missed.
3721  
3722 Please report any bugs or feature requests to C<bug-cgi-lingua at rt.cpan.org>,
3723 or through the web interface at
3724 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CGI-Lingua>.
3725 I will be notified, and then you'll
3726 automatically be notified of progress on your bug as I make changes.
3727  
3728 =head1 SEE ALSO
3729  
3730 =over 4
3731  
3732 =item * L<Configure an Object at Runtime|Object::Configure>
3733  
3734 =item * L<Test Dashboard|https://nigelhorne.github.io/CGI-Lingua/coverage/>
3735  
3736 =item * VWF - Versatile Web Framework L<https://github.com/nigelhorne/vwf>
3737  
3738 =item * L<HTTP::BrowserDetect>
3739  
3740 =item * L<I18N::AcceptLanguage>
3741  
3742 =item * L<Locale::Country>
3743  
3744 =back
3745  
3746 =head1 SUPPORT
3747  
3748 This module is provided as-is without any warranty.
3749  
3750 You can find documentation for this module with the perldoc command.
3751  
3752 perldoc CGI::Lingua
3753  
3754 You can also look for information at:
3755  
3756 =over 4
3757  
3758 =item * MetaCPAN
3759  
3760 L<https://metacpan.org/release/CGI-Lingua>
3761  
3762 =item * RT: CPAN's request tracker
3763  
3764 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=CGI-Lingua>
3765  
3766 =item * CPANTS
3767  
3768 L<http://cpants.cpanauthors.org/dist/CGI-Lingua>
3769  
3770 =item * CPAN Testers' Matrix
3771  
3772 L<http://matrix.cpantesters.org/?dist=CGI-Lingua>
3773  
3774 =item * CPAN Testers Dependencies
3775  
3776 L<http://deps.cpantesters.org/?module=CGI::Lingua>
3777  
3778 =back
3779  
3780 =encoding utf-8
3781  
3782 =head1 FORMAL SPECIFICATION
3783  
3784 This section describes each method in the Z notation.
3785 You do not need it to use the module.
3786  
3787 =head2 Types and state
3788  
3789 [LANGTAG, LANGNAME, CNAME, IPADDR, PATH, ZONE, LOCALE]
3790  
3791 CC2 == { s : seq CHAR | #s = 2 ∧ ran s ⊆ 'a'..'z' }
3792 LC2 == CC2
3793 PLURAL ::= zero | one | two | few | many | other
3794 GEO ::= unknown | absent | present
3795 DIR ::= ltr | rtl
3796 RTL_LANGS == { ar, dv, fa, he, ku, ps, sd, ug, ur, yi }
3797  
3798 ⊥ marks a value that has not been worked out yet (or is undef).
3799  
3800 ┌─ Lingua ──────────────────────────────────────────────────────
3801 │ supported : seq LANGTAG
3802 │ slanguage : LANGNAME ∪ {Unknown, ⊥}
3803 │ rlanguage : LANGNAME ∪ {Unknown, ⊥}
3804 │ code2 : LC2 ∪ {⊥}
3805 │ subcode2 : CC2 ∪ {⊥}
3806 │ sublanguage : CNAME ∪ {⊥}
3807 │ country : CC2 ∪ {Unknown, ⊥}
3808 │ locale : LOCALE ∪ {⊥}
3809 │ timezone : ZONE ∪ {⊥}
3810 │ ipc, gip, gipf : GEO
3811 │ dont_use_ip : 𝔹
3812 ├───────────────────────────────────────────────────────────────
3813 │ slanguage ∉ {Unknown, ⊥} ⇒
3814 │ code2 ≠ ⊥ ∧ (∃ t : ran supported • base(t) = code2)
3815 │ slanguage = Unknown ⇒ code2 = ⊥ ∧ subcode2 = ⊥
3816 │ subcode2 ≠ ⊥ ⇒ code2 ≠ ⊥
3817 │ sublanguage ≠ ⊥ ⇒ subcode2 ≠ ⊥
3818 │ (slanguage = ⊥) ⇔ (rlanguage = ⊥)
3819 └───────────────────────────────────────────────────────────────
3820  
3821 request : ENV ⇸ seq (LANGTAG × ℝ) -- lang param, Accept-Language or locale
3822 negotiate : seq (LANGTAG × ℝ) × seq LANGTAG ⇸ LANGTAG
3823 geo : IPADDR ⇸ CC2 -- first answer of the geo sources
3824 official : CC2 ⇸ LANGTAG -- official language of a country
3825  
3826 ┌─ Resolve ─────────────────────────────────────────────────────
3827 │ ΔLingua
3828 │ env? : ENV
3829 ├───────────────────────────────────────────────────────────────
3830 │ slanguage = ⊥
3831 │ let t == negotiate(request(env?), supported) •
3832 │ t ≠ ⊥ ⇒ slanguage' = name(base(t)) ∧ code2' = base(t)
3833 │ ∧ subcode2' = variety(t)
3834 │ t = ⊥ ∧ ¬ dont_use_ip ∧ official(geo(env?.REMOTE_ADDR)) ∈ ran supported
3835 │ ⇒ slanguage' = name(official(geo(env?.REMOTE_ADDR)))
3836 │ otherwise slanguage' = Unknown
3837 │ rlanguage' ≠ ⊥
3838 └───────────────────────────────────────────────────────────────
3839  
3840 EnsureResolved ≙ (Resolve ∨ (ΞLingua ∧ slanguage ≠ ⊥))
3841  
3842 =head2 new
3843  
3844 ┌─ New ─────────────────────────────────────────────────────────
3845 │ Lingua'
3846 │ supported? : LANGTAG ∪ seq LANGTAG
3847 │ cache? : CACHE ∪ {⊥}
3848 │ env? : ENV
3849 ├───────────────────────────────────────────────────────────────
3850 │ supported? ∈ LANGTAG ⇒ 2 ≤ #supported? ≤ 5
3851 │ supported' = (if supported? ∈ LANGTAG then ⟨supported?⟩ else supported?)
3852 │ ↾ SUPPORTED_TAGS -- other entries dropped, with a warning
3853 │ ipc' = gip' = gipf' = unknown
3854 │ dont_use_ip' = dont_use_ip? -- never taken from the cache
3855 │ let ip == untaint_ip(env?.REMOTE_ADDR); saved == decode(cache?(key(ip))) •
3856 │ (cache? ≠ ⊥ ∧ ip ≠ ⊥ ∧ key(ip) ∈ dom cache?
3857 │ ∧ (∀ f : dom saved ∩ dom RESTORABLE • saved(f) ∈ RESTORABLE(f)))
3858 │ ⇒ (∀ f : dom saved ∩ dom RESTORABLE • θLingua'.f = saved(f))
3859 │ (cache? ≠ ⊥ ∧ ip ≠ ⊥ ∧ key(ip) ∈ dom cache?
3860 │ ∧ (∃ f : dom saved ∩ dom RESTORABLE • saved(f) ∉ RESTORABLE(f)))
3861 │ ⇒ key(ip) ∉ dom cache?' -- poisoned entry removed, with a warning
3862 │ otherwise
3863 │ slanguage' = rlanguage' = country' = locale' = timezone' = ⊥
3864 └───────────────────────────────────────────────────────────────
3865  
3866 RESTORABLE : FIELD ⇸ ℙ seq CHAR
3867 RESTORABLE ≙ { slanguage, rlanguage, sublanguage ↦ NAME,
3868 slanguage_code_alpha2, sublanguage_code_alpha2 ↦ LANGCODE,
3869 country ↦ CC2 ∪ {Unknown} }
3870  
3871 NewError ≙ [ supported? = ⊥ ∨ supported? ∉ LANGTAG ∪ seq LANGTAG
3872 ∨ (info? ≠ ⊥ ∧ ¬ can(info?, lang) ∧ ¬ can(info?, AUTOLOAD)) ] ⇒ croak
3873  
3874 =head2 language
3875  
3876 ┌─ Language ────────────────────────────────────────────────────
3877 │ EnsureResolved
3878 │ result! : LANGNAME ∪ {Unknown}
3879 ├───────────────────────────────────────────────────────────────
3880 │ result! = slanguage'
3881 └───────────────────────────────────────────────────────────────
3882  
3883 PreferredLanguage ≙ Language
3884 Name ≙ Language
3885  
3886 =head2 sublanguage
3887  
3888 ┌─ Sublanguage ─────────────────────────────────────────────────
3889 │ EnsureResolved
3890 │ result! : CNAME ∪ {⊥}
3891 ├───────────────────────────────────────────────────────────────
3892 │ result! = sublanguage'
3893 └───────────────────────────────────────────────────────────────
3894  
3895 =head2 language_code_alpha2
3896  
3897 ┌─ LanguageCodeAlpha2 ──────────────────────────────────────────
3898 │ EnsureResolved
3899 │ result! : LC2 ∪ {⊥}
3900 ├───────────────────────────────────────────────────────────────
3901 │ result! = code2'
3902 │ slanguage' = Unknown ⇒ result! = ⊥
3903 └───────────────────────────────────────────────────────────────
3904  
3905 CodeAlpha2 ≙ LanguageCodeAlpha2
3906  
3907 =head2 sublanguage_code_alpha2
3908  
3909 ┌─ SublanguageCodeAlpha2 ───────────────────────────────────────
3910 │ EnsureResolved
3911 │ result! : CC2 ∪ {⊥}
3912 ├───────────────────────────────────────────────────────────────
3913 │ result! = subcode2'
3914 └───────────────────────────────────────────────────────────────
3915  
3916 =head2 requested_language
3917  
3918 ┌─ RequestedLanguage ───────────────────────────────────────────
3919 │ EnsureResolved
3920 │ result! : seq CHAR
3921 ├───────────────────────────────────────────────────────────────
3922 │ result! = rlanguage'
3923 │ -- rlanguage' = name(b) ⁀ " (" ⁀ cname(v) ⁀ ")" when the visitor
3924 │ -- asked for base b with variety v; name(b) when no variety;
3925 │ -- Unknown when nothing was asked for.
3926 └───────────────────────────────────────────────────────────────
3927  
3928 =head2 country
3929  
3930 ┌─ Country ─────────────────────────────────────────────────────
3931 │ ΔLingua
3932 │ env? : ENV
3933 │ result! : CC2 ∪ {Unknown, ⊥}
3934 ├───────────────────────────────────────────────────────────────
3935 │ country ≠ ⊥ ⇒ result! = country ∧ θLingua' = θLingua
3936 │ country = ⊥ ⇒
3937 │ ( env?.GEOIP_COUNTRY_CODE ∈ CC2↑ ⇒ result! = lc(env?.GEOIP_COUNTRY_CODE) )
3938 │ ( env?.HTTP_CF_IPCOUNTRY ∈ CC2↑ \ {XX} ⇒ result! = lc(env?.HTTP_CF_IPCOUNTRY) )
3939 │ ( ip = canon(env?.REMOTE_ADDR) ∈ PUBLIC_IP ⇒ result! = norm(geo(ip)) )
3940 │ ( ip ∉ PUBLIC_IP ⇒ result! = ⊥ )
3941 │ country' = result!
3942 │ ipc' ≠ unknown ∨ ipc' = ipc ; gip' ≠ unknown ∨ gip' = gip
3943 │ -- norm maps hk ↦ cn, eu ↦ Unknown (or cn for the Baidu subnet),
3944 │ -- and anything ∉ CC2 ↦ ⊥
3945 └───────────────────────────────────────────────────────────────
3946  
3947 where CC2↑ is CC2 in upper case, and canon(::ffff:a.b.c.d) = a.b.c.d.
3948  
3949 =head2 locale
3950  
3951 ┌─ Locale ──────────────────────────────────────────────────────
3952 │ ΔLingua
3953 │ env? : ENV
3954 │ result! : LOCALE ∪ {⊥}
3955 ├───────────────────────────────────────────────────────────────
3956 │ locale ≠ ⊥ ⇒ result! = locale ∧ θLingua' = θLingua
3957 │ locale = ⊥ ⇒ result! = first ⊥-free of
3958 │ ⟨ uatag(env?.HTTP_USER_AGENT), browserdetect(env?.HTTP_USER_AGENT),
3959 │ loc(Country.result!), loc(env?.GEOIP_COUNTRY_CODE) ⟩
3960 │ result! ≠ ⊥ ⇒ locale' = result!
3961 └───────────────────────────────────────────────────────────────
3962  
3963 =head2 time_zone
3964  
3965 ┌─ TimeZone ────────────────────────────────────────────────────
3966 │ ΔLingua
3967 │ env? : ENV
3968 │ result! : ZONE ∪ {⊥}
3969 ├───────────────────────────────────────────────────────────────
3970 │ timezone ≠ ⊥ ⇒ result! = timezone
3971 │ timezone = ⊥ ∧ env?.REMOTE_ADDR ≠ ⊥ ⇒
3972 │ result! = first ⊥-free of ⟨ mmdb_tz(ip), geoip_tz(ip), ipapi_tz(ip) ⟩
3973 │ timezone = ⊥ ∧ env?.REMOTE_ADDR = ⊥ ⇒
3974 │ result! = first ⊥-free of ⟨ etc_timezone, local_tz ⟩
3975 │ result! ∉ ZONE ⇒ result! = ⊥
3976 │ timezone' = result!
3977 └───────────────────────────────────────────────────────────────
3978  
3979 =head2 is_rtl
3980  
3981 ┌─ IsRtl ───────────────────────────────────────────────────────
3982 │ EnsureResolved
3983 │ result! : {0, 1}
3984 ├───────────────────────────────────────────────────────────────
3985 │ result! = 1 ⇔ code2' ∈ RTL_LANGS
3986 └───────────────────────────────────────────────────────────────
3987  
3988 =head2 text_direction
3989  
3990 ┌─ TextDirection ───────────────────────────────────────────────
3991 │ IsRtl
3992 │ dir! : DIR
3993 ├───────────────────────────────────────────────────────────────
3994 │ dir! = (if result! = 1 then rtl else ltr)
3995 └───────────────────────────────────────────────────────────────
3996  
3997 =head2 plural_category
3998  
3999 PLURAL_RULES : LC2 ⇸ (ℕ → PLURAL)
4000 english == λ n : ℕ • (if n = 1 then one else other)
4001  
4002 ┌─ PluralCategory ──────────────────────────────────────────────
4003 │ EnsureResolved
4004 │ n? : ℝ
4005 │ result! : PLURAL
4006 ├───────────────────────────────────────────────────────────────
4007 │ n? ≠ ⊥
4008 │ code2' = ⊥ ⇒ result! = other
4009 │ code2' ∈ dom PLURAL_RULES ⇒ result! = PLURAL_RULES(code2')(trunc n?)
4010 │ code2' ∉ dom PLURAL_RULES ∪ {⊥} ⇒ result! = english(trunc n?)
4011 └───────────────────────────────────────────────────────────────
4012  
4013 PluralError ≙ [ n? = ⊥ ] ⇒ croak
4014  
4015 =head2 translation_file
4016  
4017 ┌─ TranslationFile ─────────────────────────────────────────────
4018 │ EnsureResolved
4019 │ dir? : PATH ∪ {⊥}
4020 │ ext? : seq CHAR ∪ {⊥}
4021 │ files : ℙ PATH -- readable regular files
4022 │ result! : PATH ∪ {⊥}
4023 ├───────────────────────────────────────────────────────────────
4024 │ e == (if ext? = ⊥ then "json" else strip_dot(ext?))
4025 │ (dir? = ⊥ ∨ dir? = ⟨⟩ ∨ ".." ⊆ dir? ∨ NUL ∈ ran dir?
4026 │ ∨ ¬ (ran e ⊆ ALNUM ∪ {'-'})) ⇒ result! = ⊥
4027 │ otherwise
4028 │ cands == ⟨ code2' ⁀ "-" ⁀ subcode2' | subcode2' ≠ ⊥ ⟩ ⁀ ⟨ code2' | code2' ≠ ⊥ ⟩
4029 │ result! = first p : ran cands • dir? ⁀ "/" ⁀ p ⁀ "." ⁀ e ∈ files
4030 │ (⊥ if there is none)
4031 └───────────────────────────────────────────────────────────────
4032  
4033 =head1 STATE DIAGRAM
4034  
4035 A CGI::Lingua object has several independent parts. Each part starts
4036 empty and is filled in the first time a method needs it.
4037 After that, the part does not change (it is remembered).
4038  
4039 Part 1: the language (used by language(), sublanguage(),
4040 language_code_alpha2(), sublanguage_code_alpha2(), requested_language(),
4041 is_rtl(), text_direction(), plural_category(), translation_file())
4042  
4043 new()
4044 |
4045 v
4046 +---------------------------+
4047 | LANGUAGE NOT CHECKED |
4048 | _slanguage = undef |
4049 +---------------------------+
4050 |
4051 first call to any language method:
4052 read the lang param, HTTP_ACCEPT_LANGUAGE or LANG,
4053 and compare it with the supported list
4054 |
4055 +-----------------+------------------+
4056 | |
4057 a match no match
4058 | |
4059 | +-------------+-------------+
4060 | | |
4061 | dont_use_ip is false dont_use_ip
4062 | side effect: country() is true
4063 | is called (Part 2), and |
4064 | the country's official |
4065 | language is tried |
4066 | | | |
4067 | supported not supported |
4068 v v v v
4069 +----------------------------+ +------------------------------+
4070 | MATCHED | | UNMATCHED |
4071 | language() = 'English' ... | | language() = 'Unknown' |
4072 | language_code_alpha2() set | | language_code_alpha2() undef |
4073 +----------------------------+ +------------------------------+
4074  
4075 Both MATCHED and UNMATCHED are final: later calls return the same
4076 answers, even if %ENV changes.
4077  
4078 Part 2: the country (used by country(), locale(), and the language IP path)
4079  
4080 +----------------------+ country(): REMOTE_ADDR missing, invalid,
4081 | COUNTRY NOT KNOWN |---------------------------------------------+
4082 | _country = undef | private or loopback, or no source answers |
4083 +----------------------+<--------------------------------------------+
4084 | (returns undef; NOT remembered, so the
4085 | next call tries again)
4086 | country(): a source gives a valid code
4087 | side effects: geo modules loaded, sentinels set,
4088 | value stored in cache (if any)
4089 v
4090 +----------------------+
4091 | COUNTRY KNOWN | later calls return the same value
4092 | _country = 'xx' | (or 'Unknown' for EU addresses)
4093 +----------------------+
4094  
4095 Part 3: each geo source (GeoIP2 .mmdb, IP::Country, Geo::IP, Geo::IPfree)
4096  
4097 +-----------+ first use: module loads +-----------+
4098 | UNKNOWN |--------------------------->| PRESENT |
4099 | (-1) | | (1) |
4100 +-----------+--------------------------->+-----------+
4101 first use: module or +-----------+
4102 database is missing ----->| ABSENT |
4103 | (0) |
4104 +-----------+
4105  
4106 Part 4: locale() and time_zone()
4107  
4108 +------------+ locale() / time_zone() finds a value +------------+
4109 | NOT KNOWN |--------------------------------------->| KNOWN |
4110 | (undef) |<-------+ | remembered |
4111 +------------+ | nothing found: returns undef, +------------+
4112 | | stays NOT KNOWN (time_zone()
4113 +---------------+ also warns)
4114  
4115 Part 5: the life of the object
4116  
4117 new() ----------------------> ALIVE ----------------------> DESTROYED
4118 | no cache entry, or ^ object goes out of side effect:
4119 | no REMOTE_ADDR | scope (DESTROY) if cache and
4120 | | REMOTE_ADDR are
4121 +---- valid cache entry ------+ set and no entry
4122 | found (the six answer | exists yet, the
4123 | fields restored, each | answers are saved
4124 | checked; geo sentinels | to the cache as
4125 | reset to UNKNOWN) | JSON
4126 | |
4127 +---- malformed cache entry --+
4128 | found (removed, warned;
4129 | answers worked out again)
4130 |
4131 +---- REMOTE_ADDR not a valid address: the cache is not used
4132 |
4133 +---- bad arguments ---> croak (no object)
4134  
4135 $obj->new(...) makes a copy in the ALIVE state that keeps all the
4136 answers of $obj (all parts keep their current state).
4137  
4138 =head1 LICENSE AND COPYRIGHT
4139  
4140 Copyright 2010-2026 Nigel Horne.
4141  
4142 Usage is subject to the GPL2 licence terms.
4143 If you use it,
4144 please let me know.
4145  
4146 =cut
4147  
4148 1; # End of CGI::Lingua