blib/lib/CGI/Lingua.pm untested

filter: Statementstmt 0.0% 0 / 1026 Branchbran 0.0% 0 / 616 Conditioncond 0.0% 0 / 290 MC/DCmcdc 0.0% 0 / 175 Subroutinesub 0.0% 0 / 76 Podpod 0.0% 0 / 48 totaltotal 0.0% 0 / 2231 CC 271 SCAR 61.3
CC
271
Cov
0%
country
2162.0
_resolve_sublanguage_match
650.0
_find_language_from_ip
600.0
CRAP 461.4
1 package CGI::Lingua;
2  
3 use warnings;
4 use strict;
5 use autodie qw(:all);
6  
7 use Carp qw(croak carp);
8 use Object::Configure 0.23;
9 use Params::Get 0.15; # 0.15 fast-path: unblessed hashref returned directly
10 use Readonly;
11 use Scalar::Util qw(blessed);
12 use JSON::PP ();
13 use Class::Autouse qw{
14 Locale::Language
15 Locale::Object::Country
16 Locale::Object::DB
17 I18N::AcceptLanguage
18 I18N::LangTags::Detect
19 };
20  
21 our $VERSION = '0.86';
22  
23 # Gathering magic strings here makes behavioural changes one-edit operations.
24  
25 Readonly my $CACHE_TTL_LONG => '1 month';
26 Readonly my $CACHE_TTL_SHORT => '1 hour';
27 Readonly my $CACHE_NS => 'CGI::Lingua:'; # namespace prefix for every key
28 Readonly my $BROKEN_GEOIPFREE => '45.128.139.41'; # https://github.com/bricas/geo-ipfree/issues/10
29 Readonly my $BAIDU_SUBNET => '185.10.104.0/22';# RT-86809: Baidu misreports as EU
30 Readonly my $DEPRECATED_EN_UK => 'en-uk'; # some browsers still send this
31 Readonly my $CANONICAL_EN_GB => 'en-gb';
32 Readonly my $ACCEPT_LANG_MAX => 256; # max bytes we accept from the header
33 Readonly my $UA_MAX => 512; # max bytes we accept from HTTP_USER_AGENT
34 Readonly my $GEO_UNKNOWN => -1; # geo-module sentinel: not yet probed
35 Readonly my $GEO_ABSENT => 0; # geo-module sentinel: unavailable
36 Readonly my $GEO_PRESENT => 1; # geo-module sentinel: loaded OK
37  
38 # Package-level sentinel for Locale::Object's SQLite database. undef = not yet
39 # probed; 0 = database absent (Windows installers often omit it); 1 = available.
40 # Package-level (not per-object) because the database either exists on the
41 # filesystem or it doesn't — there is no per-request variability.
42 my $_locale_object_db_ok;
43  
44 # Package-level sentinel for Data::Validate::IP / NetAddr::IP availability.
45 # NetAddr::IP::UtilPP fails to build on Windows (mask4to6 bad-argument error),
46 # which cascades to Data::Validate::IP. undef = not yet probed; 0 = broken;
47 # 1 = available. On first country() call we try to load the module and, if it
48 # fails, install pure-Perl aliases for the four functions we use.
49 my $_have_dvip;
50  
51 # Short-name overrides used when Locale::Object's database is absent and we
52 # fall back to Locale::Codes::Country. Locale::Codes carries full ISO official
53 # names (e.g. "United Kingdom of Great Britain and Northern Ireland") while
54 # Locale::Object returns the common short form ("United Kingdom"). Only
55 # entries that differ are listed; everything else comes from Locale::Codes.
56 my %COUNTRY_SHORT_NAMES = (
57 bo => 'Bolivia',
58 cd => 'Democratic Republic of the Congo',
59 fk => 'Falkland Islands',
60 fm => 'Micronesia',
61 gb => 'United Kingdom',
62 ir => 'Iran',
63 kp => 'North Korea',
64 kr => 'South Korea',
65 md => 'Moldova',
66 nl => 'Netherlands',
67 ps => 'Palestine',
68 tw => 'Taiwan',
69 tz => 'Tanzania',
70 us => 'United States',
71 ve => 'Venezuela',
72 );
73  
74 Readonly my %RTL_LANGS => (map { $_ => 1 } # ISO 639-1 codes whose primary script is RTL
75 qw(ar dv fa he ku ps sd ug ur yi));
76  
77 =head1 NAME
78  
79 CGI::Lingua - Create a multilingual web page
80  
81 =head1 VERSION
82  
83 Version 0.86
84  
85 =cut
86  
87 =head1 SYNOPSIS
88  
89 CGI::Lingua is a powerful module for multilingual web applications
90 offering extensive language/country detection strategies.
91  
92 No longer does your website need to be in English only.
93 CGI::Lingua provides a simple basis to determine which language to display a website.
94 The website tells CGI::Lingua which languages it supports.
95 Based on that list CGI::Lingua tells the application which language the user would like to use.
96  
97 use CGI::Lingua;
98 # ...
99 my $l = CGI::Lingua->new(['en', 'fr', 'en-gb', 'en-us']);
100 my $language = $l->language();
101 if ($language eq 'English') {
102 print '<P>Hello</P>';
103 } elsif($language eq 'French') {
104 print '<P>Bonjour</P>';
105 } else { # $language eq 'Unknown'
106 my $rl = $l->requested_language();
107 print "<P>Sorry for now this page is not available in $rl.</P>";
108 }
109 my $c = $l->country();
110 if ($c eq 'us') {
111 # print contact details in the US
112 } elsif ($c eq 'ca') {
113 # print contact details in Canada
114 } else {
115 # print worldwide contact details
116 }
117  
118 # ...
119  
120 use CHI;
121 use CGI::Lingua;
122 # ...
123 my $cache = CHI->new(driver => 'File', root_dir => '/tmp/cache', namespace => 'CGI::Lingua-countries');
124 $l = CGI::Lingua->new({ supported => ['en', 'fr'], cache => $cache });
125  
126 =head1 SUBROUTINES/METHODS
127  
128 =head2 new
129  
130 Creates a CGI::Lingua object.
131  
132 =head3 API SPECIFICATION
133  
134 Input:
135 supported => ArrayRef[Str] | Str # required; RFC-1766 language codes
136 cache => Object # optional; CHI-compatible (get/set)
137 config_file => Str # optional; YAML/XML/INI config path
138 logger => Object # optional; must implement warn/info/error
139 info => Object # optional; CGI::Info-compatible
140 data => Any # optional; forwarded to I18N::AcceptLanguage
141 dont_use_ip => Bool # optional; disable IP-based fallback
142 syslog => Bool | HashRef # optional; Sys::Syslog integration
143 debug => Bool # optional; enable debug logging
144  
145 Returns: CGI::Lingua blessed hashref, or a clone when called on an object.
146  
147 =head3 EXAMPLE
148  
149 # Array-ref of supported codes (most common form)
150 my $l = CGI::Lingua->new({ supported => ['en', 'fr', 'de'] });
151  
152 # Single scalar code
153 my $l = CGI::Lingua->new(supported => 'en');
154  
155 # With cache, logger, and CGI::Info object
156 use CHI;
157 my $cache = CHI->new(driver => 'File', root_dir => '/tmp/lingua-cache');
158 my $l = CGI::Lingua->new({
159 supported => ['en', 'fr'],
160 cache => $cache,
161 logger => $my_log_object,
162 });
163  
164 # Clone an existing object with different supported list
165 my $clone = $l->new(supported => ['de']);
166  
167 =head3 MESSAGES
168  
169 "You must give a list of supported languages" - no 'supported' key provided
170 "List of supported languages must be an array ref" - supported is wrong ref type
171 "Supported languages must be the short code" - string too short or too long
172 "Logger must be a blessed object with warn/info/error methods" - bad logger arg
173  
174 =head3 PSEUDOCODE
175  
176 1. Normalise args via Params::Get and Object::Configure
177 2. Validate logger (must be blessed with warn/info/error) if provided
178 3. Validate supported (required, string or arrayref)
179 4. If cache and REMOTE_ADDR set, attempt to thaw a previously stored state
180 5. Bless and return fresh object with sentinel flags set to GEO_UNKNOWN
181  
182 =cut
183  
184 sub new
185 {
186 my $class = shift;
187 my $params = Params::Get::get_params('supported', @_);
188  
189 # Handle ::new() misuse
190 if(!defined($class)) {
191 if($params) {
192 if(my $logger = $params->{'logger'}) {
193 $logger->error(__PACKAGE__ . ' use ->new() not ::new() to instantiate');
194 }
195 croak(__PACKAGE__ . ' use ->new() not ::new() to instantiate');
196 }
197 $class = __PACKAGE__;
198 } elsif(ref($class)) {
199 # Clone: overlay new params onto existing object state
200 $params->{_supported} ||= $params->{supported} if defined $params->{'supported'};
201 return bless { %{$class}, %{$params} }, ref($class);
202 }
203  
204 # Validate blessed logger objects before Object::Configure runs.
205 # Non-blessed values (arrayrefs, hashrefs) are valid config forms that
206 # Object::Configure knows how to convert into a Log::Abstraction instance.
207 if(defined $params->{'logger'} && blessed($params->{'logger'})) {
208 unless(
209 $params->{'logger'}->can('warn')
210 && $params->{'logger'}->can('info')
211 && $params->{'logger'}->can('error')
212 ) {
213 croak('Logger must be a blessed object with warn/info/error methods');
214 }
215 }
216  
217 $params = Object::Configure::configure($class, $params);
218  
219 # Normalise supported / supported_languages alias
220 $params->{'supported'} ||= $params->{'supported_languages'};
221 if(defined($params->{supported})) {
222 # Validate supported type/length
223 if(ref($params->{supported})) {
224 if(ref($params->{supported}) ne 'ARRAY') {
225 croak('List of supported languages must be an array ref');
226 }
227 } elsif((length($params->{supported}) < 2) || (length($params->{supported}) > 5)) {
228 croak('Supported languages must be the short code');
229 }
230 } else {
231 if(my $logger = $params->{'logger'}) {
232 $logger->error('You must give a list of supported languages');
233 }
234 croak('You must give a list of supported languages');
235 }
236  
237 my $cache = $params->{cache};
238 my $info = $params->{info};
239  
240 # Try to restore a frozen state from the cache before doing any work
241 if($cache && $ENV{'REMOTE_ADDR'}) {
242 my $key = _build_cache_key($ENV{'REMOTE_ADDR'}, $params, $class, $info);
243 if(my $frozen = $cache->get($key)) {
244 # JSON::PP is used in preference to Storable::thaw because Storable
245 # can execute arbitrary Perl code via STORABLE_thaw hooks if an
246 # attacker manages to write a crafted blob to the cache backend.
247 # JSON cannot execute code regardless of its content.
248 # If the blob is not valid JSON (e.g. a legacy Storable entry), the
249 # eval catches the error and we fall through to fresh construction.
250 my $rc = eval { local $SIG{__DIE__}; JSON::PP::decode_json($frozen) };
251 unless(defined $rc && ref($rc) eq 'HASH') {
252 $rc = undef; # stale or corrupt entry — rebuild below
253 }
254 if(defined $rc) {
255 bless $rc, $class;
256 # Re-inject transient/non-serialisable fields
257 $rc->{logger} = $params->{'logger'};
258 $rc->{_syslog} = $params->{syslog};
259 $rc->{_cache} = $cache;
260 $rc->{_supported} = $params->{supported};
261 $rc->{_info} = $info;
262 $rc->{_have_ipcountry} = $GEO_UNKNOWN;
263 $rc->{_have_geoip} = $GEO_UNKNOWN;
264 $rc->{_have_geoipfree} = $GEO_UNKNOWN;
265  
266 # If lang= CGI param is active, the cached language choice may be stale
267 if(($rc->{_what_language} || $rc->{_rlanguage}) && $info && $info->lang()) {
268 delete @{$rc}{qw(_what_language _rlanguage _country)};
269 }
270 return $rc;
271 }
272 }
273 }
274  
275 return bless {
276 %{$params},
277 _supported => ref($params->{supported}) ? $params->{supported} : [ $params->{'supported'} ],
278 _cache => $cache,
279 _info => $info,
280 _syslog => $params->{syslog},
281 _dont_use_ip => $params->{dont_use_ip} || 0,
282 _have_ipcountry => $GEO_UNKNOWN,
283 _have_geoip => $GEO_UNKNOWN,
284 _have_geoipfree => $GEO_UNKNOWN,
285 _debug => $params->{debug} || 0,
286 }, $class;
287 }
288  
289 # ── _build_cache_key ──────────────────────────────────────────────────────────
290 # Purpose: Produce a deterministic string key for the per-request cache
291 # entry stored in new() and DESTROY().
292 # Entry: $addr — IP string (not yet taint-checked; used read-only here)
293 # $params — constructor params hashref
294 # $class — package name
295 # $info — optional CGI::Info object
296 # Exit: A plain string key of the form "ip/lang/lang1/lang2/..."
297 sub _build_cache_key
298 {
299 my ($addr, $params, $class, $info) = @_;
300  
301 my $key = "$addr/";
302  
303 # Include the requested language (if determinable) so different
304 # Accept-Language values get distinct cache slots for the same IP.
305 my $l;
306 if($info && ($l = $info->lang())) {
307 $key .= "$l/";
308 } elsif($l = $class->_what_language()) {
309 $key .= "$l/";
310 }
311  
312 # Fix: was ref($params->{'supported'} eq 'ARRAY') — eq was inside ref(),
313 # so ref() always received a boolean (1 or ''), never the arrayref itself.
314 # Result: arrayref-supported always fell through to the else branch and
315 # stringified to 'ARRAY(0x...)' — a different address every request —
316 # making cache lookups in new() permanently fail.
317 if(ref($params->{'supported'}) eq 'ARRAY') {
318 $key .= join('/', @{$params->{supported}});
319 } else {
320 $key .= $params->{'supported'};
321 }
322  
323 return $key;
324 }
325  
326 # Some of the information takes a long time to work out, so cache what we can
327 sub DESTROY {
328 if(defined($^V) && ($^V ge 'v5.14.0')) {
329 return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
330 }
331 return unless $ENV{'REMOTE_ADDR'};
332  
333 my $self = shift;
334 return unless ref($self);
335  
336 my $cache = $self->{_cache};
337 return unless $cache;
338  
339 my $key = _build_cache_key(
340 $ENV{'REMOTE_ADDR'},
341 { supported => $self->{_supported} },
342 ref($self),
343 $self->{_info},
344 );
345 return if $cache->get($key);
346  
347 $self->_debug("Storing self in cache as $key");
348  
349 # Serialise only the computed state — not loggers, file handles, or
350 # geo-module objects (they are re-initialised on next construction).
351 # JSON::PP is used instead of Storable so that a compromised cache backend
352 # cannot deliver a blob that executes code via STORABLE_thaw hooks.
353 my %state = (
354 _slanguage => $self->{_slanguage},
355 _slanguage_code_alpha2 => $self->{_slanguage_code_alpha2},
356 _sublanguage_code_alpha2 => $self->{_sublanguage_code_alpha2},
357 _country => $self->{_country},
358 _rlanguage => $self->{_rlanguage},
359 _dont_use_ip => $self->{_dont_use_ip},
360 _have_ipcountry => $self->{_have_ipcountry},
361 _have_geoip => $self->{_have_geoip},
362 _have_geoipfree => $self->{_have_geoipfree},
363 );
364  
365 $cache->set($key, JSON::PP::encode_json(\%state), $CACHE_TTL_LONG);
366 }
367  
368 =head2 language
369  
370 Tells the CGI application in what language to display its messages.
371 The language is the natural name e.g. 'English' or 'Japanese'.
372  
373 Sublanguages are handled sensibly, so that if a client requests U.S. English
374 on a site that only serves British English, language() will return 'English'.
375  
376 If none of the requested languages is included within the supported lists,
377 language() returns 'Unknown'.
378  
379 =head3 EXAMPLE
380  
381 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'fr,en;q=0.9';
382 my $l = CGI::Lingua->new(supported => ['en', 'fr']);
383 print $l->language(); # "French"
384  
385 =head3 API SPECIFICATION
386  
387 Input: none beyond $self
388 Returns: Str - human-readable language name, or 'Unknown'
389  
390 =cut
391  
392 sub language {
393 my $self = $_[0];
394  
395 $self->_find_language() unless $self->{_slanguage};
396 return $self->{_slanguage};
397 }
398  
399 =head2 preferred_language
400  
401 Same as language().
402  
403 =cut
404  
405 sub preferred_language
406 {
407 my $self = shift;
408 return $self->language(@_);
409 }
410  
411 =head2 name
412  
413 Synonym for language, for compatibility with Locale::Object::Language.
414  
415 =cut
416  
417 sub name {
418 my $self = $_[0];
419 return $self->language();
420 }
421  
422 =head2 sublanguage
423  
424 Tells the CGI what variant to use e.g. 'United Kingdom', or undef if
425 it can't be determined.
426  
427 =head3 EXAMPLE
428  
429 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'en-gb';
430 my $l = CGI::Lingua->new(supported => ['en-gb']);
431 print $l->sublanguage(); # "United Kingdom"
432  
433 =head3 API SPECIFICATION
434  
435 Input: none beyond $self
436 Returns: Str | undef
437  
438 =cut
439  
440 sub sublanguage {
441 my $self = $_[0];
442  
443 $self->_trace('Entered sublanguage');
444 $self->_find_language() unless $self->{_slanguage};
445 $self->_trace('Leaving sublanguage ', ($self->{_sublanguage} || 'undef'));
446 return $self->{_sublanguage};
447 }
448  
449 =head2 language_code_alpha2
450  
451 Gives the two-character representation of the supported language, e.g. 'en'
452 when you've asked for en-gb.
453  
454 If none of the requested languages is included within the supported lists,
455 language_code_alpha2() returns undef.
456  
457 =head3 EXAMPLE
458  
459 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'en-gb';
460 my $l = CGI::Lingua->new(supported => ['en-gb']);
461 print $l->language_code_alpha2(); # "en"
462  
463 =head3 API SPECIFICATION
464  
465 Input: none beyond $self
466 Returns: Str (2 chars) | undef
467  
468 =cut
469  
470 sub language_code_alpha2 {
471 my $self = $_[0];
472  
473 $self->_trace('Entered language_code_alpha2');
474 $self->_find_language() unless $self->{_slanguage};
475 $self->_trace('language_code_alpha2 returns ', $self->{_slanguage_code_alpha2});
476 return $self->{_slanguage_code_alpha2};
477 }
478  
479 =head2 code_alpha2
480  
481 Synonym for language_code_alpha2, kept for historical reasons.
482  
483 =cut
484  
485 sub code_alpha2 {
486 my $self = $_[0];
487 return $self->language_code_alpha2();
488 }
489  
490 =head2 sublanguage_code_alpha2
491  
492 Gives the two-character representation of the supported language, e.g. 'gb'
493 when you've asked for en-gb, or undef.
494  
495 =head3 EXAMPLE
496  
497 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'en-gb';
498 my $l = CGI::Lingua->new(supported => ['en-gb']);
499 print $l->sublanguage_code_alpha2(); # "gb"
500  
501 =head3 API SPECIFICATION
502  
503 Input: none beyond $self
504 Returns: Str (2 chars) | undef
505  
506 =cut
507  
508 sub sublanguage_code_alpha2 {
509 my $self = $_[0];
510  
511 $self->_find_language() unless $self->{_slanguage};
512 return $self->{_sublanguage_code_alpha2};
513 }
514  
515 =head2 requested_language
516  
517 Gives a human-readable rendition of what language the user asked for whether
518 or not it is supported.
519  
520 Returns the sublanguage (if appropriate) in parentheses,
521 e.g. "English (United Kingdom)"
522  
523 =head3 EXAMPLE
524  
525 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'en-gb';
526 my $l = CGI::Lingua->new(supported => ['en']);
527 print $l->requested_language(); # "English (United Kingdom)"
528  
529 =head3 API SPECIFICATION
530  
531 Input: none beyond $self
532 Returns: Str - e.g. "English (United Kingdom)" or "Unknown"
533  
534 =cut
535  
536 sub requested_language {
537 my $self = $_[0];
538  
539 $self->_find_language() unless $self->{_rlanguage};
540 return $self->{_rlanguage};
541 }
542  
543 # ── _find_language ─────────────────────────────────────────────────────────
544 # Purpose: Populate _slanguage, _rlanguage, _sublanguage, and the
545 # various code fields by working through the detection pipeline:
546 # Accept-Language header → I18N::AcceptLanguage → IP country.
547 # Entry: $self->{_slanguage} must be undef (guards repeated calls).
548 # Exit: $self->{_slanguage} is set to a language name or 'Unknown'.
549 # Side Effects: Populates _rlanguage, _sublanguage, *_code_alpha2 fields.
550 sub _find_language
551 {
552 my $self = shift;
553  
554 $self->_trace('Entered _find_language');
555  
556 $self->{_rlanguage} = 'Unknown';
557 $self->{_slanguage} = 'Unknown';
558  
559 my $http_accept_language = $self->_what_language();
560 if(defined($http_accept_language)) {
561 $self->_debug(
562 "language wanted: $http_accept_language, "
563 . 'languages supported: '
564 . join(', ', @{$self->{_supported}} // '')
565 );
566  
567 # Normalise the deprecated en-uk tag that some browsers send
568 if($http_accept_language eq $DEPRECATED_EN_UK) {
569 $self->_debug("Resetting country code to GB for $http_accept_language");
570 $http_accept_language = $CANONICAL_EN_GB;
571 }
572  
573 # Run the header through the Accept-Language resolver
574 my ($l, $requested_sublanguage) =
575 $self->_accept_language_match($http_accept_language);
576  
577 # Resolve the matched code to a full language/sublanguage
578 if($l) {
579 return if $self->_resolve_match($l, $requested_sublanguage, $http_accept_language);
580 } elsif($http_accept_language =~ /;/) {
581 # e.g. de-DE,de;q=0.9,en-US;q=0.8 and we support none of those
582 $self->_notice(
583 __PACKAGE__, ': ', __LINE__,
584 ": couldn't honour HTTP_ACCEPT_LANGUAGE=$http_accept_language,"
585 . ' supported languages are: '
586 . join(',', @{$self->{_supported}})
587 );
588 }
589  
590 # Detected slanguage but rlanguage still Unknown — try I18N::LangTags
591 if($self->{_slanguage} && ($self->{_slanguage} ne 'Unknown')) {
592 if($self->{_rlanguage} eq 'Unknown') {
593 $self->{_rlanguage} = I18N::LangTags::Detect::detect();
594 }
595 if($self->{_rlanguage}) {
596 if(my $resolved = $self->_code2language($self->{_rlanguage})) {
597 $self->{_rlanguage} = $resolved;
598 }
599 return;
600 }
601 }
602  
603 # Last-chance: 2-char or xx-xx header where we have no match
604 if(
605 ((!$self->{_rlanguage}) || ($self->{_rlanguage} eq 'Unknown'))
606 && ((length($http_accept_language) == 2) || ($http_accept_language =~ /^..-..$/))
607 ) {
608 $self->{_rlanguage} = $self->_code2language($http_accept_language) || 'Unknown';
609 }
610 $self->{_slanguage} = 'Unknown';
611 }
612  
613 return if $self->{_dont_use_ip};
614  
615 # Fall back to the official language of the visitor's country
616 $self->_find_language_from_ip($http_accept_language);
617 }
618  
619 # ── _accept_language_match ────────────────────────────────────────────────
620 # Purpose: Run I18N::AcceptLanguage strict matching plus two fallback
621 # left-to-right scan passes against $self->{_supported}.
622 # Entry: $http_accept_language — validated, untainted Accept-Language value.
623 # Exit: Returns ($matched_code, $requested_sublanguage) or (undef, undef).
624 # Side Effects: Logs debug messages.
625 sub _accept_language_match
626 {
627 my ($self, $http_accept_language) = @_;
628  
629 # Suppress I18N::AcceptLanguage's uninitialized-value warnings (RT 74338)
630 local $SIG{__WARN__} = sub {
631 warn $_[0] unless $_[0] =~ /^Use of uninitialized value/;
632 };
633 my $i18n = I18N::AcceptLanguage->new(debug => $self->{_debug}, strict => 1);
634 my $l = $i18n->accepts($http_accept_language, $self->{_supported});
635 local $SIG{__WARN__} = 'DEFAULT';
636  
637 # I18N-AcceptLanguage strict mode can return a sublanguage variant when
638 # the request contains a sublanguage we don't support; force a retry.
639 if($l && ($http_accept_language =~ /-/) && ($http_accept_language !~ qr/$l/i)) {
640 $self->_debug('Forcing fallback');
641 undef $l;
642 }
643  
644 my $requested_sublanguage;
645 if(!$l) {
646 # Sort tokens by q-value once; both scan passes share the ordered list
647 my $sorted = $self->_sorted_tokens($http_accept_language);
648 # First fallback: scan for xx-yy pairs, try base language xx
649 ($l, $requested_sublanguage) =
650 $self->_scan_sublanguage_pairs($i18n, $sorted);
651 if(!$l) {
652 # Second fallback: scan plain tokens without sublanguages
653 $l = $self->_scan_plain_tokens($i18n, $sorted);
654 undef $requested_sublanguage if $l;
655 }
656 }
657  
658 return ($l, $requested_sublanguage);
659 }
660  
661 # ── _sorted_tokens ────────────────────────────────────────────────────────
662 # Purpose: Parse an Accept-Language header into tokens sorted by
663 # descending quality value so fallback scans honour q= priority.
664 # Entry: $header — validated Accept-Language string.
665 # Exit: Arrayref of [$language_tag, $quality] pairs, highest q first.
666 sub _sorted_tokens
667 {
668 my ($self, $header) = @_;
669 my @tokens;
670 for my $token (split /,/, $header) {
671 $token =~ s/^\s+|\s+$//g;
672 my $q = 1.0;
673 if($token =~ s/;\s*q\s*=\s*(\d+(?:\.\d+)?)//) {
674 $q = $1 + 0;
675 }
676 $token =~ s/^\s+|\s+$//g;
677 push @tokens, [$token, $q] if length $token;
678 }
679 return [sort { $b->[1] <=> $a->[1] } @tokens];
680 }
681  
682 # ── _scan_sublanguage_pairs ───────────────────────────────────────────────
683 # Purpose: Walk q-sorted tokens looking for xx-yy pairs; try accepting
684 # the base language xx from the supported list.
685 # Entry: $i18n — I18N::AcceptLanguage instance;
686 # $sorted — arrayref from _sorted_tokens.
687 # Exit: ($matched_code, $sublanguage_code) or (undef, undef).
688 # Side Effects: Debug logging.
689 sub _scan_sublanguage_pairs
690 {
691 my ($self, $i18n, $sorted) = @_;
692  
693 $self->_debug(__PACKAGE__, ': ', __LINE__, ': scan q-sorted tokens for xx-yy pairs');
694 for my $entry (@{$sorted}) {
695 my ($tag) = @{$entry};
696 next unless $tag =~ /^(..)-(..)$/;
697 my ($base, $sub) = ($1, $2);
698 $self->_debug(__PACKAGE__, ': ', __LINE__, ": see if $base is supported");
699 if($i18n->accepts($base, $self->{_supported})) {
700 $self->_debug("Fallback to $base as sublanguage $sub is not supported");
701 return ($base, $sub);
702 }
703 }
704 return (undef, undef);
705 }
706  
707 # ── _scan_plain_tokens ────────────────────────────────────────────────────
708 # Purpose: Walk q-sorted tokens that have no sublanguage suffix and try
709 # accepting each against the supported list.
710 # Entry: $i18n — I18N::AcceptLanguage instance;
711 # $sorted — arrayref from _sorted_tokens.
712 # Exit: Matched code string, or undef.
713 # Side Effects: Debug logging.
714 sub _scan_plain_tokens
715 {
716 my ($self, $i18n, $sorted) = @_;
717  
718 $self->_debug(__PACKAGE__, ': ', __LINE__, ': scan q-sorted tokens for plain alternatives');
719 for my $entry (@{$sorted}) {
720 my ($tag) = @{$entry};
721 next if $tag =~ /^..-../; # already tried in the pair scan
722 $self->_debug(__PACKAGE__, ': ', __LINE__, ": see if $tag is supported");
723 if($i18n->accepts($tag, $self->{_supported})) {
724 $self->_debug("Fallback to $tag as best alternative");
725 return $tag;
726 }
727 }
728 return;
729 }
730  
731 # ── _resolve_match ────────────────────────────────────────────────────────
732 # Purpose: Given a matched code $l (possibly xx or xx-yy), populate all
733 # of _slanguage, _rlanguage, _sublanguage and their code fields.
734 # Entry: $l — 2-char or xx-yy language code; $requested_sublanguage —
735 # 2-char variety code or undef; $http_accept_language — full header.
736 # Exit: Returns true (1) if the caller should return immediately.
737 # Side Effects: Mutates $self->{_slanguage}, _rlanguage, _sublanguage, etc.
738 sub _resolve_match
739 {
740 my ($self, $l, $requested_sublanguage, $http_accept_language) = @_;
741  
742 $self->_debug("l: $l");
743  
744 if($l !~ /^..-../) {
745 # Base-language match (e.g. 'en') — no sublanguage component
746 return $self->_resolve_base_match($l, $requested_sublanguage, $http_accept_language);
747 } elsif($l =~ /(.+)-(..)$/) {
748 # Sublanguage match (e.g. 'en-gb') — resolve both language and variant
749 return $self->_resolve_sublanguage_match($l, $1, $2, $http_accept_language);
750 }
751 return 0;
752 }
753  
754 # ── _resolve_base_match ───────────────────────────────────────────────────
755 # Purpose: Handle the case where a base-language code matched (no hyphen).
756 # Sets _slanguage, _rlanguage; appends sublanguage name to rlanguage
757 # when the client requested one we don't support.
758 # Entry: $l — 2-char code; $requested_sublanguage — optional; $header.
759 # Exit: 1 to signal caller should return, 0 otherwise.
760 # Side Effects: Mutates slanguage, rlanguage, slanguage_code_alpha2.
761 sub _resolve_base_match
762 {
763 my ($self, $l, $requested_sublanguage, $header) = @_;
764  
765 $self->{_slanguage} = $self->_code2language($l);
766 return 0 unless $self->{_slanguage};
767  
768 $self->_debug("_slanguage: $self->{_slanguage}");
769 $self->{_slanguage_code_alpha2} = $l;
770 $self->{_rlanguage} = $self->{_slanguage};
771  
772 # Attempt to name the sublanguage the client actually asked for
773 my $sl;
774 if($header =~ /..-(..)$/) {
775 $self->_debug($1);
776 $sl = $self->_code2country($1);
777 $requested_sublanguage //= $1;
778 } elsif($header =~ /..-([a-z]{2,3})$/i) {
779 if($_locale_object_db_ok // 1) {
780 eval { $sl = Locale::Object::Country->new(code_alpha3 => $1) };
781 if($@) {
782 $_locale_object_db_ok = 0 if $@ =~ /database was not in/;
783 $self->_info($@);
784 } else {
785 $_locale_object_db_ok = 1;
786 }
787 }
788 }
789  
790 if($sl) {
791 $self->{_rlanguage} .= ' (' . $sl->name() . ')';
792 } elsif($requested_sublanguage) {
793 if(my $c = $self->_code2countryname($requested_sublanguage)) {
794 $self->{_rlanguage} .= " ($c)";
795 } else {
796 $self->{_rlanguage} .= " (Unknown: $requested_sublanguage)";
797 }
798 }
799 return 1;
800 }
801  
802 # ── _resolve_sublanguage_match ────────────────────────────────────────────
803 # Purpose: Handle the case where the full xx-yy code matched in the
804 # supported list. Resolves the variety name and caches results.
805 # Entry: $l — full code e.g. 'en-gb'; $alpha2 — 'en'; $variety — 'gb';
806 # $header — full Accept-Language value.
807 # Exit: 1 to signal caller should return, 0 otherwise.
808 # Side Effects: Mutates _slanguage, _rlanguage, _sublanguage and code fields;
809 # writes to cache.
810 sub _resolve_sublanguage_match
811 {
812 my ($self, $l, $alpha2, $variety, $header) = @_;
813  
814 my $i18n = I18N::AcceptLanguage->new(strict => 1);
815 my $accepts = $i18n->accepts($l, $self->{_supported});
816 $self->_debug("accepts = $accepts");
817  
818 if($accepts) {
819 $self->_debug("accepts: $accepts");
820  
821 if($accepts =~ /\-/) {
822 delete $self->{_slanguage};
823 } else {
824 # Cache look-up for the base-language name
825 my $from_cache;
826 if($self->{_cache}) {
827 $from_cache = $self->{_cache}->get($CACHE_NS . "accepts:$accepts");
828 }
829 my $slanguage;
830 if($from_cache) {
831 $self->_debug("$accepts is in cache as $from_cache");
832 $slanguage = (split(/=/, $from_cache))[0];
833 } else {
834 $slanguage = $self->_code2language($accepts);
835 }
836  
837 if($slanguage) {
838 $self->{_slanguage} = $slanguage;
839  
840 # Normalise deprecated en-uk variety
841 if($variety eq 'uk') {
842 $self->_warn({ warning => "Resetting country code to GB for $header" });
843 $variety = 'gb';
844 }
845  
846 if(defined(my $c = $self->_code2countryname($variety))) {
847 $self->_debug(__PACKAGE__, ': ', __LINE__, ": setting sublanguage to $c");
848 $self->{_sublanguage} = $c;
849 }
850 $self->{_slanguage_code_alpha2} = $accepts;
851 $self->{_sublanguage_code_alpha2} = $variety;
852  
853 if($self->{_sublanguage}) {
854 $self->{_rlanguage} = "$self->{_slanguage} ($self->{_sublanguage})";
855 $self->_debug(__PACKAGE__, ': ', __LINE__, ": _rlanguage: $self->{_rlanguage}");
856 }
857  
858 unless($from_cache) {
859 $self->_debug("Set $variety to $slanguage=$accepts");
860 $self->{_cache}->set(
861 $CACHE_NS . "accepts:$variety",
862 "$slanguage=$accepts",
863 $CACHE_TTL_LONG
864 ) if $self->{_cache};
865 }
866 return 1;
867 }
868 }
869 }
870  
871 # Accepts returned something but we couldn't resolve a language name —
872 # try harder using the variety code directly
873 $self->{_rlanguage} = $self->_code2language($alpha2);
874 $self->_debug("_rlanguage: $self->{_rlanguage}");
875  
876 return 0 unless $accepts;
877  
878 $self->_debug("http_accept_language = $header");
879 $l =~ /(..)-(..)/;
880 $variety = lc($2);
881  
882 # Skip numeric/region codes like en-029
883 if(($variety =~ /[a-z]{2,3}/) && !defined($self->{_sublanguage})) {
884 $self->_get_closest($alpha2, $alpha2);
885 $self->_debug("Find the country code for $variety");
886  
887 if($variety eq 'uk') {
888 $self->_warn({ warning => "Resetting country code to GB for $header" });
889 $variety = 'gb';
890 }
891  
892 my ($from_cache, $language_name);
893 if($self->{_cache}) {
894 $from_cache = $self->{_cache}->get($CACHE_NS . "variety:$variety");
895 }
896  
897 if(defined($from_cache)) {
898 $self->_debug("$variety is in cache as $from_cache");
899 # Cache stores "countryname=langcode" (e.g. "United Kingdom=en").
900 # Splitting on = gives the country name as the first field.
901 ($language_name) = split(/=/, $from_cache);
902 } elsif($_locale_object_db_ok // 1) {
903 # Locale::Object's SQLite database is absent on some Windows
904 # installations; the sentinel avoids repeated failed new() calls.
905 eval {
906 my $db = Locale::Object::DB->new();
907 my @results = @{$db->lookup(
908 table => 'country',
909 result_column => 'name',
910 search_column => 'code_alpha2',
911 value => $variety
912 )};
913 $_locale_object_db_ok = 1;
914 if(defined($results[0])) {
915 $language_name = $self->_code2countryname($variety);
916 } else {
917 $self->_debug("Can't find the country code for $variety in Locale::Object::DB");
918 }
919 };
920 if($@) {
921 $_locale_object_db_ok = 0
922 if $@ =~ /database was not in/;
923 # fall through: $language_name stays undef, caught below
924 }
925 }
926  
927 if($@ || !defined($language_name)) {
928 $self->_warn({ warning => $@ }) if $@;
929 # Locale::Object DB may be absent (common on Windows CI); fall back to
930 # the short-name table / Locale::Codes before giving up.
931 $language_name = $self->_country_short_name($variety);
932 }
933 if(!defined($language_name)) {
934 $self->_debug(__PACKAGE__, ': ', __LINE__, ': setting sublanguage to Unknown');
935 $self->{_sublanguage} = 'Unknown';
936 $self->_warn({ warning => "Can't determine values for $header" });
937 } else {
938 $self->{_sublanguage} = $language_name;
939 $self->_debug('variety name ', $self->{_sublanguage});
940 if($self->{_cache} && !defined($from_cache)) {
941 # Store "countryname=langcode" so future cache hits return the country
942 # name in the first field. Previously this stored the language name
943 # ("English=en" for en-gb) which was wrong — the cache-hit branch
944 # split on = and used the first field as the sublanguage (country) name.
945 $self->_debug("Set variety:$variety to $language_name=$self->{_slanguage_code_alpha2}");
946 $self->{_cache}->set(
947 $CACHE_NS . "variety:$variety",
948 "$language_name=$self->{_slanguage_code_alpha2}",
949 $CACHE_TTL_LONG
950 );
951 }
952 }
953 }
954  
955 if(defined($self->{_sublanguage})) {
956 $self->{_rlanguage} = "$self->{_slanguage} ($self->{_sublanguage})";
957 $self->{_sublanguage_code_alpha2} = $variety;
958 return 1;
959 }
960 return 0;
961 }
962  
963 # ── _find_language_from_ip ────────────────────────────────────────────────
964 # Purpose: Fall back to the visitor's IP country when the Accept-Language
965 # header produced no usable match. Looks up the official language
966 # of the country and checks it against the supported list.
967 # Entry: $http_accept_language — may be undef if no header was present.
968 # Exit: Mutates _slanguage, _rlanguage via _get_closest if a match found.
969 # Side Effects: Calls country(); may write to cache.
970 sub _find_language_from_ip
971 {
972 my ($self, $http_accept_language) = @_;
973  
974 my $country = $self->country();
975  
976 # If country() returned nothing, try to derive from the LANG env var
977 if(!defined($country) && (my $c = $self->_what_language())) {
978 if($c =~ /^(..)_(..)/) {
979 $country = $2;
980 } elsif($c =~ /^(..)$/) {
981 $country = $1;
982 }
983 }
984 return unless defined $country;
985  
986 $self->_debug("country: $country");
987  
988 my ($language_name, $language_code2, $from_cache);
989 if($self->{_cache}) {
990 $from_cache = $self->{_cache}->get($CACHE_NS . 'language_name:' . $country);
991 }
992  
993 if($from_cache) {
994 $self->_debug("$country is in cache as $from_cache");
995 ($language_name, $language_code2) = split(/=/, $from_cache);
996 } else {
997 my $l = $self->_code2country(uc($country));
998 if($l) {
999 $l = ($l->languages_official)[0];
1000 if(defined $l) {
1001 $language_name = $l->name;
1002 $language_code2 = $l->code_alpha2;
1003 $self->_debug("Official language: $language_name") if $language_name;
1004 }
1005 }
1006 }
1007  
1008 my $ip = $ENV{'REMOTE_ADDR'};
1009 return unless $language_name;
1010  
1011 if((!defined($self->{_rlanguage})) || ($self->{_rlanguage} eq 'Unknown')) {
1012 $self->{_rlanguage} = $language_name;
1013 }
1014  
1015 unless((exists $self->{_slanguage}) && ($self->{_slanguage} ne 'Unknown')) {
1016 my $code;
1017  
1018 if($language_name && $language_code2 && !defined($http_accept_language)) {
1019 # Fast-path for search engines that hit with no Accept-Language
1020 $self->_debug("Fast assign to $language_code2");
1021 $code = $language_code2;
1022 } else {
1023 $self->_debug("Call language2code on $self->{_rlanguage}");
1024 $code = Locale::Language::language2code($self->{_rlanguage});
1025  
1026 unless($code) {
1027 if($http_accept_language && ($http_accept_language ne $self->{_rlanguage})) {
1028 $self->_debug("Call language2code on $http_accept_language");
1029 $code = Locale::Language::language2code($http_accept_language);
1030 }
1031 unless($code) {
1032 # Norwegian (Nynorsk) — strip the parenthetical qualifier
1033 if($self->{_rlanguage} =~ /(.+)\s\(.+/) {
1034 if((!defined($http_accept_language)) || ($1 ne $self->{_rlanguage})) {
1035 $self->_debug("Call language2code on $1");
1036 $code = Locale::Language::language2code($1);
1037 }
1038 }
1039 unless($code) {
1040 $self->_warn({
1041 warning => "Can't determine code from IP $ip for requested language $self->{_rlanguage}"
1042 });
1043 }
1044 }
1045 }
1046 }
1047  
1048 if($code) {
1049 $self->_get_closest($code, $language_code2);
1050 unless($self->{_slanguage}) {
1051 $self->_warn({
1052 warning => "Couldn't determine closest language for $language_name in $self->{_supported}"
1053 });
1054 } else {
1055 $self->_debug("language set to $self->{_slanguage}, code set to $code");
1056 }
1057 }
1058 }
1059  
1060 if(!defined($self->{_slanguage_code_alpha2})) {
1061 $self->_debug("Can't determine slanguage_code_alpha2");
1062 } elsif(!defined($from_cache) && $self->{_cache} && defined($self->{_slanguage_code_alpha2})) {
1063 $self->_debug("Set $country to $language_name=$self->{_slanguage_code_alpha2}");
1064 $self->{_cache}->set(
1065 $CACHE_NS . 'language_name:' . $country,
1066 "$language_name=$self->{_slanguage_code_alpha2}",
1067 $CACHE_TTL_LONG
1068 );
1069 }
1070 }
1071  
1072 # ── _get_closest ─────────────────────────────────────────────────────────
1073 # Purpose: If $language_string matches the base language of any supported
1074 # entry, set _slanguage and _slanguage_code_alpha2.
1075 # Entry: $language_string — base code e.g. 'en'; $alpha2 — same or variant.
1076 # Exit: Mutates _slanguage and _slanguage_code_alpha2 on match.
1077 sub _get_closest
1078 {
1079 my ($self, $language_string, $alpha2) = @_;
1080  
1081 # Map each supported entry to its base language code
1082 my %base_languages =
1083 map { /^(.+)-/ ? ($1 => $_) : ($_ => $_) } @{$self->{_supported}};
1084  
1085 if(exists $base_languages{$language_string}) {
1086 $self->{_slanguage} = $self->{_rlanguage};
1087 $self->{_slanguage_code_alpha2} = $alpha2;
1088 }
1089 }
1090  
1091 # ── _what_language ────────────────────────────────────────────────────────
1092 # Purpose: Return the raw (validated, untainted) Accept-Language string,
1093 # consulting in priority order: cached value, CGI lang= param,
1094 # HTTP_ACCEPT_LANGUAGE env var, LANG env var (local/debug mode).
1095 # Entry: May be called as a class method (no $self->{...} access) or
1096 # as an object method.
1097 # Exit: A validated language string, or undef if nothing available.
1098 # Side Effects: Caches result in $self->{_what_language} on object calls.
1099 sub _what_language {
1100 my $self = $_[0];
1101  
1102 if(ref($self)) {
1103 $self->_trace('Entered _what_language');
1104 if(defined($self->{_what_language})) {
1105 $self->_trace('_what_language: returning cached value: ', $self->{_what_language});
1106 return $self->{_what_language};
1107 }
1108 if(my $info = $self->{_info}) {
1109 if(my $rc = $info->lang()) {
1110 $self->_trace("_what_language set language to $rc from the lang argument");
1111 return $self->{_what_language} = $rc;
1112 }
1113 }
1114 }
1115  
1116 if(my $raw_lang = $ENV{'HTTP_ACCEPT_LANGUAGE'}) {
1117 # Validate and untaint — RFC 7231 §5.3.5 character set plus * wildcard
1118 if($raw_lang =~ /^([A-Za-z0-9\-,;=.*\s]{1,$ACCEPT_LANG_MAX})$/a) {
1119 my $rc = $1; # untainted
1120 if(ref($self)) {
1121 return $self->{_what_language} = $rc;
1122 }
1123 return $rc;
1124 } elsif(ref($self)) {
1125 $self->_warn({ warning => 'HTTP_ACCEPT_LANGUAGE contains invalid characters; ignoring' });
1126 }
1127 }
1128  
1129 if(defined($ENV{'LANG'})) {
1130 # Running locally (debug mode) — derive from system locale.
1131 # Apply the same untainting discipline as HTTP_ACCEPT_LANGUAGE: only
1132 # alphanumeric, hyphen, underscore, and dot are legitimate in a POSIX
1133 # locale name (e.g. "en_US.UTF-8", "de_DE", "ja"). Anything else is
1134 # either malformed or an injection attempt; discard it silently.
1135 if($ENV{'LANG'} =~ /^([A-Za-z0-9_.\-]{1,$ACCEPT_LANG_MAX})$/a) {
1136 my $rc = $1; # untainted
1137 if(ref($self)) {
1138 return $self->{_what_language} = $rc;
1139 }
1140 return $rc;
1141 } elsif(ref($self)) {
1142 $self->_warn({ warning => 'LANG contains invalid characters; ignoring' });
1143 }
1144 }
1145 return;
1146 }
1147  
1148 =head2 country
1149  
1150 Returns the two-character country code of the remote end in lowercase.
1151  
1152 If L<IP::Country>, L<Geo::IPfree> or L<Geo::IP> is installed,
1153 CGI::Lingua will make use of that, otherwise, it will do a Whois lookup.
1154 If you do not have any of those installed I recommend you use the
1155 caching capability of CGI::Lingua.
1156  
1157 =head3 API SPECIFICATION
1158  
1159 Input: none beyond $self
1160 Returns: Str (2 lowercase chars) | undef
1161 'Unknown' is only returned in the Baidu-EU special case via _handle_eu_country.
1162  
1163 =head3 EXAMPLE
1164  
1165 # With mod_geoip (fastest - no IP lookup at all):
1166 local $ENV{GEOIP_COUNTRY_CODE} = 'DE';
1167 print $l->country(); # "de"
1168  
1169 # With REMOTE_ADDR and IP::Country installed:
1170 local $ENV{REMOTE_ADDR} = '8.8.8.8';
1171 print $l->country(); # "us" (depends on geo database)
1172  
1173 =head3 MESSAGES
1174  
1175 "GEOIP_COUNTRY_CODE contains an invalid country code; ignoring"
1176 "HTTP_CF_IPCOUNTRY contains an invalid country code; ignoring"
1177 "X.X.X.X isn't a valid IP address"
1178 "Can't determine country from LAN connection X"
1179 "Can't determine country from loopback connection X"
1180 "cache contains a numeric country: N"
1181 "IP matches to a numeric country"
1182  
1183 =head3 PSEUDOCODE
1184  
1185 1. Return cached _country if set
1186 2. Check GEOIP_COUNTRY_CODE env var (mod_geoip); validate /^[A-Z]{2}$/
1187 3. Check HTTP_CF_IPCOUNTRY (Cloudflare); skip 'XX'; validate /^[A-Z]{2}$/
1188 4. Untaint and validate REMOTE_ADDR; return undef if absent or invalid
1189 5. Skip private and loopback IPs (return undef)
1190 6. Check CHI cache; return cached value if present
1191 7. Try IP::Country::Fast (local DB, fastest)
1192 8. Try Geo::IP (local DB)
1193 9. Try Geo::IPfree (local DB, skip $BROKEN_GEOIPFREE)
1194 10. Try geoplugin.net JSON API (LWP::Simple::WithCache or LWP::Simple)
1195 11. Last resort: Net::Whois::IP then Net::Whois::IANA
1196 12. Sanitise: discard numeric, normalise HK->CN, handle EU special case
1197 13. Store in CHI cache; return result
1198  
1199 =cut
1200  
1201 sub country {
1202 my $self = shift;
1203  
1204 $self->_trace(__PACKAGE__, ': Entered country()');
1205  
1206 # Return cached result immediately if a previous call already resolved it.
1207 # Note: undef results (private/loopback IPs) are NOT cached here because
1208 # country() reads REMOTE_ADDR at call time, not construction time; caching
1209 # undef would give wrong answers if REMOTE_ADDR changes between calls on
1210 # the same object (the documented lazy-read design). See LIMITATIONS.
1211 if($self->{_country}) {
1212 $self->_trace('quick return: ', $self->{_country});
1213 return $self->{_country};
1214 }
1215  
1216 # mod_geoip: validate against ISO 3166-1 alpha-2 before trusting
1217 if(defined($ENV{'GEOIP_COUNTRY_CODE'})) {
1218 if($ENV{'GEOIP_COUNTRY_CODE'} =~ /^([A-Z]{2})$/a) {
1219 $self->{_country} = lc($1);
1220 return $self->{_country};
1221 } else {
1222 $self->_warn({ warning => 'GEOIP_COUNTRY_CODE contains an invalid country code; ignoring' });
1223 }
1224 }
1225  
1226 # Cloudflare: 'XX' means Cloudflare couldn't determine country — skip it
1227 if(($ENV{'HTTP_CF_IPCOUNTRY'}) && ($ENV{'HTTP_CF_IPCOUNTRY'} ne 'XX')) {
1228 if($ENV{'HTTP_CF_IPCOUNTRY'} =~ /^([A-Z]{2})$/a) {
1229 $self->{_country} = lc($1);
1230 return $self->{_country};
1231 } else {
1232 $self->_warn({ warning => 'HTTP_CF_IPCOUNTRY contains an invalid country code; ignoring' });
1233 }
1234 }
1235  
1236 my $raw_ip = $ENV{'REMOTE_ADDR'};
1237 return unless defined $raw_ip;
1238  
1239 # Validate and untaint the IP address before passing to any geo module
1240 my $ip;
1241 if($raw_ip =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/a) {
1242 $ip = $1; # untainted IPv4
1243 } elsif($raw_ip =~ /^([0-9a-fA-F:]{2,39}|[0-9a-fA-F:]{2,30}:(?:\d{1,3}\.){3}\d{1,3})$/a) {
1244 $ip = $1; # untainted IPv6, including mixed notation (e.g. ::ffff:192.0.2.1)
1245 } else {
1246 $self->_warn({ warning => "$raw_ip isn't a valid IP address" });
1247 return;
1248 }
1249  
1250 # Data::Validate::IP depends on NetAddr::IP, which fails to build on Windows
1251 # (NetAddr::IP::UtilPP::mask4to6 bad-argument error). Try to load it once;
1252 # on failure install pure-Perl aliases for the four bare function names used
1253 # below so the rest of the function is unchanged on both platforms.
1254 if(!defined($_have_dvip)) {
1255 local $SIG{__DIE__};
1256 if(eval { require Data::Validate::IP; Data::Validate::IP->import(); 1 }) {
1257 $_have_dvip = 1;
1258 } else {
1259 $_have_dvip = 0;
1260 no warnings 'redefine';
1261 *CGI::Lingua::is_ipv4 = \&_is_ipv4;
1262 *CGI::Lingua::is_ipv6 = \&_is_ipv6;
1263 *CGI::Lingua::is_private_ip = \&_is_private_ip;
1264 *CGI::Lingua::is_loopback_ip = \&_is_loopback_ip;
1265 }
1266 }
1267  
1268 if(!is_ipv4($ip)) {
1269 $self->_debug("$ip isn't IPv4. Is it IPv6?");
1270 if($ip eq '::1') {
1271 $ip = '127.0.0.1'; # normalise loopback
1272 } elsif($ip =~ /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i) {
1273 $ip = $1; # normalise IPv4-mapped IPv6 (::ffff:a.b.c.d) to plain IPv4
1274 # \d{1,3} matches 0-999; validate range before geo lookups because
1275 # some inet_aton implementations wrap out-of-range octets modulo 256,
1276 # turning 999.999.999.999 into a real routable address.
1277 unless(is_ipv4($ip)) {
1278 $self->_warn({ warning => "$ip isn't a valid IP address" });
1279 return;
1280 }
1281 } elsif(!is_ipv6($ip)) {
1282 $self->_warn({ warning => "$ip isn't a valid IP address" });
1283 return;
1284 }
1285 }
1286 if(is_private_ip($ip)) {
1287 $self->_debug("Can't determine country from LAN connection $ip");
1288 return;
1289 }
1290 if(is_loopback_ip($ip)) {
1291 $self->_debug("Can't determine country from loopback connection $ip");
1292 return;
1293 }
1294  
1295 # Cache look-up — skip for LAN/loopback (already returned above)
1296 if($self->{_cache}) {
1297 $self->{_country} = $self->{_cache}->get($CACHE_NS . "country:$ip");
1298 if(defined($self->{_country})) {
1299 if($self->{_country} !~ /\D/) {
1300 $self->_warn({ warning => 'cache contains a numeric country: ' . $self->{_country} });
1301 $self->{_cache}->remove($CACHE_NS . "country:$ip");
1302 delete $self->{_country};
1303 } else {
1304 $self->_debug("Get $ip from cache = $self->{_country}");
1305 return $self->{_country};
1306 }
1307 }
1308 $self->_debug("$ip isn't in the cache");
1309 }
1310  
1311 # Try IP::Country first (fastest, local database)
1312 if($self->{_have_ipcountry} == $GEO_UNKNOWN) {
1313 if(eval { require IP::Country::Fast }) {
1314 # Require the concrete class directly; IP::Country->import() is not needed
1315 # because IP::Country::Fast->new() is a fully-qualified class method call.
1316 $self->{_have_ipcountry} = $GEO_PRESENT;
1317 $self->{_ipcountry} = IP::Country::Fast->new();
1318 } else {
1319 $self->{_have_ipcountry} = $GEO_ABSENT;
1320 }
1321 }
1322 $self->_debug("have_ipcountry $self->{_have_ipcountry}");
1323  
1324 if($self->{_have_ipcountry}) {
1325 $self->{_country} = $self->{_ipcountry}->inet_atocc($ip);
1326 if($self->{_country}) {
1327 $self->{_country} = lc($self->{_country});
1328 } elsif(is_ipv4($ip)) {
1329 $self->_debug("$ip is not known by IP::Country");
1330 }
1331 }
1332  
1333 # Try Geo::IP if IP::Country gave nothing
1334 unless(defined($self->{_country})) {
1335 if($self->{_have_geoip} == $GEO_UNKNOWN) {
1336 $self->_load_geoip();
1337 }
1338 if($self->{_have_geoip} == $GEO_PRESENT) {
1339 $self->{_country} = $self->{_geoip}->country_code_by_addr($ip);
1340 }
1341  
1342 # Geo::IPfree has a known-broken entry for $BROKEN_GEOIPFREE
1343 if(!defined($self->{_country}) && ($ip ne $BROKEN_GEOIPFREE)) {
1344 if($self->{_have_geoipfree} == $GEO_UNKNOWN) {
1345 eval { require Geo::IPfree };
1346 unless($@) {
1347 # No ->import(): Geo::IPfree uses only OO (->LookUp); the old
1348 # Geo::IPfree::IP->import() call was a wrong package and could
1349 # clobber Test::Mockingbird mocks on some versions.
1350 $self->{_have_geoipfree} = $GEO_PRESENT;
1351 $self->{_geoipfree} = Geo::IPfree->new();
1352 } else {
1353 $self->{_have_geoipfree} = $GEO_ABSENT;
1354 }
1355 }
1356 if($self->{_have_geoipfree} == $GEO_PRESENT) {
1357 if(my $country = ($self->{_geoipfree}->LookUp($ip))[0]) {
1358 $self->{_country} = lc($country);
1359 }
1360 }
1361 }
1362 }
1363  
1364 # 'eu' is not a real country — discard
1365 if($self->{_country} && ($self->{_country} eq 'eu')) {
1366 delete $self->{_country};
1367 }
1368  
1369 # Remote JSON lookup via geoplugin
1370 if((!$self->{_country}) &&
1371 (eval { require LWP::Simple::WithCache; require JSON::Parse })) {
1372 $self->_debug("Look up $ip on geoplugin");
1373  
1374 if(my $data = LWP::Simple::WithCache::get("https://www.geoplugin.net/json.gp?ip=$ip")) {
1375 eval { $self->{_country} = JSON::Parse::parse_json($data)->{'geoplugin_countryCode'} };
1376 $self->_warn({ warning => "geoplugin returned unparseable JSON: $@" }) if $@;
1377 }
1378 }
1379  
1380 # Last resort: Whois
1381 unless($self->{_country}) {
1382 $self->_resolve_country_via_whois($ip);
1383 }
1384  
1385 # Sanitise and normalise whatever we found
1386 if($self->{_country}) {
1387 if($self->{_country} !~ /\D/) {
1388 $self->_warn({ warning => 'IP matches to a numeric country' });
1389 delete $self->{_country};
1390 } else {
1391 $self->{_country} = lc($self->{_country});
1392  
1393 # Legacy mappings
1394 if($self->{_country} eq 'hk') {
1395 $self->{_country} = 'cn'; # HK is no longer a separate country in Whois
1396 } elsif($self->{_country} eq 'eu') {
1397 $self->_handle_eu_country($ip);
1398 }
1399  
1400 if($self->{_country} && ($self->{_country} !~ /\D/)) {
1401 $self->_warn({ warning => "cache contains a numeric country: $self->{_country}" });
1402 delete $self->{_country};
1403 } elsif($self->{_country} &&
1404 $self->{_country} ne 'Unknown' &&
1405 ($self->{_country} !~ /^[a-z]{2}$/)) {
1406 # Reject anything that is not exactly 2 lowercase ASCII letters,
1407 # unless it is the 'Unknown' sentinel written by _handle_eu_country
1408 # for EU addresses that do not map to a specific country.
1409 # Guards against Whois CRLF injection leftovers ("gbx-header: evil")
1410 # and XSS payloads in JSON API responses ("gb<script>...</script>").
1411 $self->_warn({ warning => "Discarding malformed country code '$self->{_country}'" });
1412 delete $self->{_country};
1413 } elsif($self->{_country} && $self->{_cache}) {
1414 $self->_debug("Set $ip to $self->{_country}");
1415 $self->{_cache}->set(
1416 $CACHE_NS . "country:$ip",
1417 $self->{_country},
1418 $CACHE_TTL_SHORT
1419 );
1420 }
1421 }
1422 }
1423  
1424 return $self->{_country};
1425 }
1426  
1427 # ── _resolve_country_via_whois ─────────────────────────────────────────────
1428 # Purpose: Attempt Net::Whois::IP then Net::Whois::IANA as a last resort.
1429 # Entry: $ip — validated, untainted IP string.
1430 # Exit: Sets $self->{_country} if a result was found.
1431 # Side Effects: Network I/O; logs debug messages.
1432 sub _resolve_country_via_whois
1433 {
1434 my ($self, $ip) = @_;
1435  
1436 $self->_debug("Look up $ip on Whois");
1437  
1438 require Net::Whois::IP;
1439 # No ->import(): whoisip_query is called fully-qualified, so import is unneeded
1440 # and on some versions reinstalls the real function, clobbering Test::Mockingbird mocks.
1441  
1442 my $whois;
1443 eval {
1444 # Catch connection timeouts by converting Carp::carp into a die
1445 local $SIG{__WARN__} = sub { die $_[0] };
1446 $whois = Net::Whois::IP::whoisip_query($ip);
1447 };
1448  
1449 unless($@ || !defined($whois) || (ref($whois) ne 'HASH')) {
1450 if(defined($whois->{Country})) {
1451 $self->{_country} = $whois->{Country};
1452 } elsif(defined($whois->{country})) {
1453 $self->{_country} = $whois->{country};
1454 }
1455 if($self->{_country}) {
1456 if($self->{_country} eq 'EU') {
1457 delete $self->{_country};
1458 } elsif(($self->{_country} eq 'US') && defined($whois->{'StateProv'}) && ($whois->{'StateProv'} eq 'PR')) {
1459 # RT#131347: Puerto Rico is not the US
1460 $self->{_country} = 'pr';
1461 }
1462 }
1463 }
1464  
1465 if($self->{_country}) {
1466 $self->_debug("Found $ip on Net::Whois::IP as ", $self->{_country});
1467 $self->{_country} = _clean_country_code($self->{_country});
1468 # _clean_country_code returns undef for malformed values (e.g. CRLF
1469 # injection leftovers); if so, fall through to the IANA look-up.
1470 return if defined $self->{_country};
1471 delete $self->{_country};
1472 }
1473  
1474 $self->_debug("Look up $ip on IANA");
1475  
1476 require Net::Whois::IANA;
1477 # No ->import(): Net::Whois::IANA->new() is a class method; import not needed.
1478  
1479 my $iana = Net::Whois::IANA->new();
1480 eval { $iana->whois_query(-ip => $ip) };
1481 unless($@) {
1482 $self->{_country} = $iana->country();
1483 $self->_debug("IANA reports $ip as ", $self->{_country});
1484 }
1485  
1486 if($self->{_country}) {
1487 $self->{_country} = _clean_country_code($self->{_country});
1488 delete $self->{_country} unless defined $self->{_country};
1489 }
1490 }
1491  
1492 # ── _clean_country_code ───────────────────────────────────────────────────
1493 # Purpose: Strip carriage returns and trailing "#…" comments that some
1494 # Whois servers append to their country field
1495 # (e.g. "US\r", "GB # United Kingdom").
1496 # Entry: $raw — raw country string from a Whois response.
1497 # Exit: Cleaned 2-char country code string.
1498 sub _clean_country_code
1499 {
1500 my ($raw) = @_;
1501 $raw =~ s/[\r\n]//g;
1502 # Accept exactly 2 alpha chars, optionally followed by whitespace and a
1503 # comment (e.g. "GB # United Kingdom"). Anything else (CRLF injection
1504 # leftovers, embedded headers) returns undef so the caller can discard it
1505 # rather than propagating a malformed string through the geo pipeline.
1506 if($raw =~ /^([A-Za-z]{2})\s*(?:#.*)?$/) {
1507 return $1;
1508 }
1509 return;
1510 }
1511  
1512 # ── _in_baidu_subnet ──────────────────────────────────────────────────────
1513 # Purpose: Pure-Perl fallback check for the Baidu IPv4 subnet
1514 # 185.10.104.0/22. Used when Net::Subnet is absent (e.g. on
1515 # Windows where its Socket6 dependency fails to build).
1516 # Entry: $ip — untainted IPv4 string.
1517 # Exit: Returns true if $ip is within the /22 block, false otherwise.
1518 sub _in_baidu_subnet
1519 {
1520 my $ip = shift;
1521 return 0 unless $ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
1522 # pack/unpack avoids signed-integer overflow on 32-bit Perl
1523 my $n = unpack('N', pack('C4', $1, $2, $3, $4));
1524 my $net = unpack('N', pack('C4', 185, 10, 104, 0));
1525 return (($n & 0xFFFFFC00) == ($net & 0xFFFFFC00));
1526 }
1527  
1528 # ── _handle_eu_country ────────────────────────────────────────────────────
1529 # Purpose: Resolve the ambiguous 'eu' country code. RT-86809 shows that
1530 # Baidu reports itself as EU when it is actually in CN. All
1531 # other 'eu' addresses are logged as Unknown.
1532 # Entry: $ip — validated, untainted IP string.
1533 # Exit: Sets $self->{_country} to 'cn' or 'Unknown'.
1534 # Side Effects: Optionally loads Net::Subnet; writes info log entry.
1535 sub _handle_eu_country
1536 {
1537 my ($self, $ip) = @_;
1538  
1539 # Prefer Net::Subnet for correctness; fall back to the pure-Perl helper
1540 # when it is absent (Socket6, its indirect dep, fails to build on Windows).
1541 my $in_baidu;
1542 if(eval { require Net::Subnet; Net::Subnet->import(); 1 }) {
1543 $in_baidu = subnet_matcher($BAIDU_SUBNET)->($ip);
1544 } else {
1545 $in_baidu = _in_baidu_subnet($ip);
1546 }
1547  
1548 if($in_baidu) {
1549 $self->{_country} = 'cn';
1550 } else {
1551 $self->_info("$ip has country of eu");
1552 $self->{_country} = 'Unknown';
1553 }
1554 }
1555  
1556 # ── _load_geoip ───────────────────────────────────────────────────────────
1557 # Purpose: Probe for the Geo::IP database file and the Geo::IP module;
1558 # set _have_geoip and initialise _geoip on success.
1559 # Entry: _have_geoip must be GEO_UNKNOWN.
1560 # Exit: _have_geoip set to GEO_PRESENT or GEO_ABSENT.
1561 # Side Effects: Requires Geo::IP; opens GeoIP.dat.
1562 sub _load_geoip
1563 {
1564 my $self = shift;
1565  
1566 # Check for the database file before even trying to load the module
1567 # (avoids noisy errors on Windows — CPANTESTERS report 54117bd0)
1568 my $db_present = (
1569 (($^O eq 'MSWin32') && (-r 'c:/GeoIP/GeoIP.dat'))
1570 || (-r '/usr/local/share/GeoIP/GeoIP.dat')
1571 || (-r '/usr/share/GeoIP/GeoIP.dat')
1572 );
1573  
1574 unless($db_present) {
1575 $self->{_have_geoip} = $GEO_ABSENT;
1576 return;
1577 }
1578  
1579 eval { require Geo::IP };
1580 if($@) {
1581 $self->{_have_geoip} = $GEO_ABSENT;
1582 return;
1583 }
1584  
1585 # No ->import(): Geo::IP->open() and Geo::IP->new() are class methods; import unneeded.
1586 $self->{_have_geoip} = $GEO_PRESENT;
1587  
1588 # GEOIP_STANDARD = 0 (can't use the constant name directly)
1589 if(-r '/usr/share/GeoIP/GeoIP.dat') {
1590 $self->{_geoip} = Geo::IP->open('/usr/share/GeoIP/GeoIP.dat', 0);
1591 } else {
1592 $self->{_geoip} = Geo::IP->new(0);
1593 }
1594 }
1595  
1596 =head2 locale
1597  
1598 HTTP doesn't have a way of transmitting a browser's localisation information
1599 which would be useful for default currency, date formatting, etc.
1600  
1601 This method attempts to detect the information, but it is a best guess
1602 and is not 100% reliable. But it's better than nothing ;-)
1603  
1604 Returns a L<Locale::Object::Country> object.
1605  
1606 =head3 EXAMPLE
1607  
1608 local $ENV{REMOTE_ADDR} = '8.8.8.8';
1609 my $locale = $l->locale();
1610 if (defined $locale) {
1611 print $locale->name(); # e.g. "United States"
1612 print $locale->currency_code(); # e.g. "USD"
1613 }
1614  
1615 =head3 API SPECIFICATION
1616  
1617 Input: none beyond $self
1618 Returns: Locale::Object::Country | undef
1619  
1620 =head3 PSEUDOCODE
1621  
1622 1. Return cached _locale immediately if already computed
1623 2. Parse HTTP_USER_AGENT parenthetical for xx-YY language tag
1624 3. Try HTTP::BrowserDetect on the full User-Agent string
1625 4. Fall back to country() IP lookup
1626 5. Fall back to GEOIP_COUNTRY_CODE env var (ISO 3166-1 validated)
1627 6. Return undef if all strategies fail
1628  
1629 =cut
1630  
1631 sub locale {
1632 my $self = shift;
1633  
1634 return $self->{_locale} if $self->{_locale};
1635  
1636 # Validate and untaint HTTP_USER_AGENT before passing to any parser.
1637 # The User-Agent header is attacker-controlled; apply the same discipline
1638 # as HTTP_ACCEPT_LANGUAGE. Printable ASCII (0x20-0x7e), bounded length.
1639 my $agent;
1640 if(defined(my $raw_agent = $ENV{'HTTP_USER_AGENT'})) {
1641 if($raw_agent =~ /^([\x20-\x7e]{1,$UA_MAX})$/a) {
1642 $agent = $1; # untainted
1643 } else {
1644 $self->_warn({ warning => 'HTTP_USER_AGENT contains invalid characters or exceeds length limit; ignoring' });
1645 }
1646 }
1647  
1648 # First try: parse the language tag from the User-Agent parenthetical
1649 if(defined($agent) && ($agent =~ /\((.+)\)/)) {
1650 foreach(split(/;/, $1)) {
1651 my $candidate = $_;
1652 $candidate =~ s/^\s+|\s+$//g; # trim both ends
1653  
1654 if($candidate =~ /^[a-zA-Z]{2}-([a-zA-Z]{2})$/) {
1655 local $SIG{__WARN__} = undef;
1656 if(my $c = $self->_code2country($1)) {
1657 $self->{_locale} = $c;
1658 return $c;
1659 }
1660 }
1661 }
1662  
1663 # Second try: HTTP::BrowserDetect (works for more User-Agents)
1664 if(eval { require HTTP::BrowserDetect }) {
1665 HTTP::BrowserDetect->import();
1666 my $browser = HTTP::BrowserDetect->new($agent);
1667 # Validate country() result before use — the return value comes from
1668 # the third-party module and is not yet untainted or range-checked.
1669 if($browser) {
1670 my $bc = $browser->country() // '';
1671 if($bc =~ /^([A-Za-z]{2})$/a) {
1672 if(my $c = $self->_code2country($1)) {
1673 $self->{_locale} = $c;
1674 return $c;
1675 }
1676 }
1677 }
1678 }
1679 }
1680  
1681 # Third try: IP address
1682 my $country = $self->country();
1683 if($country) {
1684 $country =~ s/[\r\n]//g;
1685 my $c;
1686 eval {
1687 local $SIG{__WARN__} = sub { die $_[0] };
1688 $c = $self->_code2country($country);
1689 };
1690 unless($@) {
1691 if($c) {
1692 $self->{_locale} = $c;
1693 return $c;
1694 }
1695 }
1696 }
1697  
1698 # Fourth try: mod_geoip env var — apply the same ISO 3166-1 validation
1699 # used in country() to guard against spoofed or malformed values
1700 if(defined($ENV{'GEOIP_COUNTRY_CODE'})) {
1701 if($ENV{'GEOIP_COUNTRY_CODE'} =~ /^([A-Z]{2})$/a) {
1702 if(my $c = $self->_code2country(lc($1))) {
1703 $self->{_locale} = $c;
1704 return $c;
1705 }
1706 }
1707 }
1708 return;
1709 }
1710  
1711 =head2 time_zone
1712  
1713 Returns the timezone of the web client.
1714  
1715 If L<Geo::IP> is installed,
1716 CGI::Lingua will make use of that, otherwise it will use L<ip-api.com>
1717  
1718 =head3 API SPECIFICATION
1719  
1720 Input: none beyond $self
1721 Returns: Str (IANA timezone name) | undef
1722  
1723 =head3 EXAMPLE
1724  
1725 local $ENV{REMOTE_ADDR} = '8.8.8.8';
1726 my $tz = $l->time_zone();
1727 print $tz // 'unknown'; # e.g. "America/New_York"
1728  
1729 =head3 MESSAGES
1730  
1731 "Couldn't determine the timezone"
1732 "LWP::Simple::WithCache and LWP::Simple are both absent; cannot contact ip-api.com"
1733 Returns undef rather than croaking; install either LWP variant to enable ip-api lookups.
1734  
1735 =head3 PSEUDOCODE
1736  
1737 1. Return cached _timezone immediately if already computed
1738 2. If REMOTE_ADDR is set:
1739 a. Untaint and validate the IP
1740 b. Try Geo::IP->time_zone() (local DB)
1741 c. Try LWP::Simple::WithCache + JSON::Parse against ip-api.com
1742 d. Fall back to LWP::Simple + JSON::Parse against ip-api.com
1743 e. Warn and return undef if neither LWP variant is installed
1744 3. If REMOTE_ADDR is absent (local/CLI mode):
1745 a. Read /etc/timezone if readable
1746 b. Fall back to DateTime::TimeZone::Local->TimeZone()->name()
1747 4. Warn "Couldn't determine the timezone" and return undef if all fail
1748  
1749 =cut
1750  
1751 sub time_zone {
1752 my $self = shift;
1753  
1754 $self->_trace('Entered time_zone');
1755  
1756 if($self->{_timezone}) {
1757 $self->_trace('quick return: ', $self->{_timezone});
1758 return $self->{_timezone};
1759 }
1760  
1761 my $raw_ip = $ENV{'REMOTE_ADDR'};
1762  
1763 if(defined $raw_ip) {
1764 # Untaint before any external use — kept in sync with country()'s pattern,
1765 # including the mixed-notation branch for ::ffff:a.b.c.d addresses.
1766 my $ip;
1767 if($raw_ip =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/a) {
1768 $ip = $1;
1769 } elsif($raw_ip =~ /^([0-9a-fA-F:]{2,39}|[0-9a-fA-F:]{2,30}:(?:\d{1,3}\.){3}\d{1,3})$/a) {
1770 $ip = $1;
1771 } else {
1772 $self->_warn({ warning => "$raw_ip isn't a valid IP address" });
1773 return;
1774 }
1775  
1776 if($self->{_have_geoip} == $GEO_UNKNOWN) {
1777 $self->_load_geoip();
1778 }
1779 if($self->{_have_geoip} == $GEO_PRESENT) {
1780 eval { $self->{_timezone} = $self->{_geoip}->time_zone($ip) };
1781 }
1782  
1783 unless($self->{_timezone}) {
1784 if(eval { require LWP::Simple::WithCache; require JSON::Parse }) {
1785 $self->_debug("Look up $ip on ip-api.com");
1786  
1787 if(my $data = LWP::Simple::WithCache::get("http://ip-api.com/json/$ip")) {
1788 eval { $self->{_timezone} = JSON::Parse::parse_json($data)->{'timezone'} };
1789 $self->_warn({ warning => "ip-api.com returned unparseable JSON: $@" }) if $@;
1790 }
1791 } elsif(eval { require LWP::Simple; require JSON::Parse }) {
1792 $self->_debug("Look up $ip on ip-api.com");
1793  
1794 if(my $data = LWP::Simple::get("http://ip-api.com/json/$ip")) {
1795 eval { $self->{_timezone} = JSON::Parse::parse_json($data)->{'timezone'} };
1796 $self->_warn({ warning => "ip-api.com returned unparseable JSON: $@" }) if $@;
1797 }
1798 } else {
1799 # Neither LWP variant is available — degrade gracefully rather than
1800 # killing the entire request with a croak; caller can check for undef.
1801 $self->_warn({ warning => 'LWP::Simple::WithCache and LWP::Simple are both absent; cannot contact ip-api.com' });
1802 }
1803 }
1804 } else {
1805 # Local connection — read from /etc/timezone or DateTime::TimeZone
1806 if(CORE::open(my $fin, '<', '/etc/timezone')) {
1807 my $tz = <$fin>;
1808 chomp $tz;
1809 $self->{_timezone} = $tz;
1810 } else {
1811 # DateTime::TimeZone::Local::TimeZone() is not available on all
1812 # platforms/versions (absent on some Windows Perl builds); guard
1813 # so time_zone() degrades to undef rather than dying.
1814 eval {
1815 local $SIG{__DIE__};
1816 require DateTime::TimeZone::Local;
1817 $self->{_timezone} = DateTime::TimeZone::Local->TimeZone()->name();
1818 };
1819 $self->_warn({ warning => "DateTime::TimeZone::Local failed: $@" }) if $@;
1820 }
1821 }
1822  
1823 # Validate the timezone string against a permissive but bounded IANA pattern.
1824 # Rejects XSS payloads (e.g. "Europe/London<script>...") from hostile JSON
1825 # responses while accepting all real IANA zone names (e.g. "America/New_York",
1826 # "Etc/GMT+8", "UTC").
1827 if(defined($self->{_timezone}) &&
1828 $self->{_timezone} !~ /^[A-Za-z][A-Za-z0-9_+\-\/]{0,50}$/) {
1829 $self->_warn({ warning => "Discarding malformed timezone '$self->{_timezone}'" });
1830 delete $self->{_timezone};
1831 }
1832  
1833 unless(defined($self->{_timezone})) {
1834 $self->_warn({ warning => "Couldn't determine the timezone" });
1835 }
1836 return $self->{_timezone};
1837 }
1838  
1839 =head2 is_rtl
1840  
1841 Returns true (1) if the negotiated language is written right-to-left, false (0)
1842 otherwise. Covers Arabic, Hebrew, Persian, Urdu, Yiddish, Dhivehi, Pashto,
1843 Sindhi, Uyghur, and Kurdish.
1844  
1845 =head3 EXAMPLE
1846  
1847 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'ar';
1848 my $l = CGI::Lingua->new(supported => ['ar', 'en']);
1849 print $l->is_rtl(); # 1
1850  
1851 =head3 API SPECIFICATION
1852  
1853 Input: none beyond $self
1854 Returns: 1 | 0
1855  
1856 =cut
1857  
1858 sub is_rtl
1859 {
1860 my $self = shift;
1861 return $RTL_LANGS{$self->language_code_alpha2() // ''} ? 1 : 0;
1862 }
1863  
1864 =head2 text_direction
1865  
1866 Returns C<'rtl'> or C<'ltr'> for the negotiated language, suitable for direct
1867 use as an HTML C<dir> attribute value.
1868  
1869 =head3 EXAMPLE
1870  
1871 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'he';
1872 my $l = CGI::Lingua->new(supported => ['he', 'en']);
1873 print qq(<html dir="} . $l->text_direction() . qq(">); # dir="rtl"
1874  
1875 =head3 API SPECIFICATION
1876  
1877 Input: none beyond $self
1878 Returns: 'rtl' | 'ltr'
1879  
1880 =cut
1881  
1882 sub text_direction
1883 {
1884 my $self = shift;
1885 return $self->is_rtl() ? 'rtl' : 'ltr';
1886 }
1887  
1888 =head2 plural_category
1889  
1890 Returns the CLDR plural category for the integer C<$n> in the negotiated
1891 language. The returned string is one of C<'zero'>, C<'one'>, C<'two'>,
1892 C<'few'>, C<'many'>, or C<'other'>.
1893  
1894 Rules are embedded for ~70 languages including Arabic (6 forms), Slavic
1895 languages (3-4 forms), Celtic languages (up to 6 forms), and Hebrew, Maltese,
1896 Romanian, Latvian, Lithuanian, and Slovenian. Languages not in the table fall
1897 back to the English rule (n == 1 => C<'one'>, else C<'other'>).
1898  
1899 For fractional numbers or full CLDR v42+ accuracy, use C<Locale::CLDR>.
1900  
1901 =head3 EXAMPLE
1902  
1903 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'ru';
1904 my $l = CGI::Lingua->new(supported => ['ru']);
1905 print $l->plural_category(1); # "one"
1906 print $l->plural_category(3); # "few"
1907 print $l->plural_category(11); # "many"
1908  
1909 =head3 API SPECIFICATION
1910  
1911 Input: $n - non-negative integer (fractional values are truncated)
1912 Returns: Str - one of zero/one/two/few/many/other
1913  
1914 =cut
1915  
1916 # CLDR plural category rules (https://unicode.org/cldr/charts/42/supplemental/language_plural_rules.html).
1917 # Values are coderefs: ($n) → category string. Languages absent from this
1918 # table fall back to the standard one/other rule inside plural_category().
1919 my %PLURAL_RULES = (
1920  
1921 # ── No plural distinction (always 'other') ────────────────────────────
1922 (map { $_ => sub { 'other' } }
1923 qw(az bm bo dz id ig ii in ja jbo jv jw kde kea km ko lkt lo ms
1924 my nqo root sah ses sg th to vi wo yo zh)),
1925  
1926 # ── Standard: n == 1 → 'one', else 'other' ───────────────────────────
1927 (map { $_ => sub { int($_[0]) == 1 ? 'one' : 'other' } }
1928 qw(af an ast bg bn brx ca cgg da de el en eo es et eu fi
1929 gl gsw gu ha haw hu ia it kcg kk kl lb lg mas ml mn mr
1930 nb nd ne nl nn nyn om or pa pap rm rof rwk saq seh sn so
1931 sq ss ssy st sv sw ta te teo tig tk tl tn ts ur wae xh xog)),
1932  
1933 # ── French / Portuguese-BR: n ≤ 1 → 'one' ────────────────────────────
1934 (map { $_ => sub { int($_[0]) <= 1 ? 'one' : 'other' } } qw(fr pt_BR)),
1935  
1936 # ── Arabic: zero/one/two/few/many/other ───────────────────────────────
1937 ar => sub {
1938 my $n = int($_[0]);
1939 my $m100 = $n % 100;
1940 return 'zero' if $n == 0;
1941 return 'one' if $n == 1;
1942 return 'two' if $n == 2;
1943 return 'few' if $m100 >= 3 && $m100 <= 10;
1944 return 'many' if $m100 >= 11 && $m100 <= 99;
1945 return 'other';
1946 },
1947  
1948 # ── Hebrew: one/two/many/other ────────────────────────────────────────
1949 he => sub {
1950 my $n = int($_[0]);
1951 return 'one' if $n == 1;
1952 return 'two' if $n == 2;
1953 return 'many' if $n != 0 && $n % 10 == 0;
1954 return 'other';
1955 },
1956  
1957 # ── Russian / Ukrainian / Belarusian: one/few/many ────────────────────
1958 (map { $_ => sub {
1959 my $n = int($_[0]);
1960 my $m10 = $n % 10;
1961 my $m100 = $n % 100;
1962 return 'one' if $m10 == 1 && $m100 != 11;
1963 return 'few' if $m10 >= 2 && $m10 <= 4 && ($m100 < 10 || $m100 >= 20);
1964 return 'many';
1965 } } qw(ru uk be)),
1966  
1967 # ── Polish: one/few/many ──────────────────────────────────────────────
1968 pl => sub {
1969 my $n = int($_[0]);
1970 my $m10 = $n % 10;
1971 my $m100 = $n % 100;
1972 return 'one' if $n == 1;
1973 return 'few' if $m10 >= 2 && $m10 <= 4 && ($m100 < 10 || $m100 >= 20);
1974 return 'many';
1975 },
1976  
1977 # ── Czech / Slovak: one/few/other ────────────────────────────────────
1978 (map { $_ => sub {
1979 my $n = int($_[0]);
1980 return 'one' if $n == 1;
1981 return 'few' if $n >= 2 && $n <= 4;
1982 return 'other';
1983 } } qw(cs sk)),
1984  
1985 # ── Romanian: one/few/other ───────────────────────────────────────────
1986 ro => sub {
1987 my $n = int($_[0]);
1988 my $m100 = $n % 100;
1989 return 'one' if $n == 1;
1990 return 'few' if $n == 0 || ($m100 >= 1 && $m100 <= 19);
1991 return 'other';
1992 },
1993  
1994 # ── Latvian: zero/one/other ───────────────────────────────────────────
1995 lv => sub {
1996 my $n = int($_[0]);
1997 my $m10 = $n % 10;
1998 my $m100 = $n % 100;
1999 return 'zero' if $m10 == 0 || ($m100 >= 11 && $m100 <= 19);
2000 return 'one' if $m10 == 1 && $m100 != 11;
2001 return 'other';
2002 },
2003  
2004 # ── Lithuanian: one/few/other ─────────────────────────────────────────
2005 lt => sub {
2006 my $n = int($_[0]);
2007 my $m10 = $n % 10;
2008 my $m100 = $n % 100;
2009 return 'one' if $m10 == 1 && ($m100 < 10 || $m100 >= 20);
2010 return 'few' if $m10 >= 2 && ($m100 < 10 || $m100 >= 20);
2011 return 'other';
2012 },
2013  
2014 # ── Slovenian: one/two/few/other ──────────────────────────────────────
2015 sl => sub {
2016 my $m100 = int($_[0]) % 100;
2017 return 'one' if $m100 == 1;
2018 return 'two' if $m100 == 2;
2019 return 'few' if $m100 == 3 || $m100 == 4;
2020 return 'other';
2021 },
2022  
2023 # ── Welsh: zero/one/two/few/many/other ───────────────────────────────
2024 cy => sub {
2025 my $n = int($_[0]);
2026 return 'zero' if $n == 0;
2027 return 'one' if $n == 1;
2028 return 'two' if $n == 2;
2029 return 'few' if $n == 3;
2030 return 'many' if $n == 6;
2031 return 'other';
2032 },
2033  
2034 # ── Irish: one/two/few/many/other ────────────────────────────────────
2035 ga => sub {
2036 my $n = int($_[0]);
2037 return 'one' if $n == 1;
2038 return 'two' if $n == 2;
2039 return 'few' if $n >= 3 && $n <= 6;
2040 return 'many' if $n >= 7 && $n <= 10;
2041 return 'other';
2042 },
2043  
2044 # ── Maltese: one/two/few/many/other ──────────────────────────────────
2045 mt => sub {
2046 my $n = int($_[0]);
2047 my $m100 = $n % 100;
2048 return 'one' if $n == 1;
2049 return 'two' if $n == 2;
2050 return 'few' if $n == 0 || ($m100 >= 3 && $m100 <= 10);
2051 return 'many' if $m100 >= 11 && $m100 <= 19;
2052 return 'other';
2053 },
2054 );
2055  
2056 sub plural_category
2057 {
2058 my ($self, $n) = @_;
2059 croak('plural_category: $n must be defined') unless defined $n;
2060 my $code = $self->language_code_alpha2() // return 'other';
2061 my $rule = $PLURAL_RULES{$code} // sub { int($_[0]) == 1 ? 'one' : 'other' };
2062 return $rule->($n);
2063 }
2064  
2065 =head2 translation_file
2066  
2067 Returns the filesystem path to the best matching translation file for the
2068 negotiated language in the given directory.
2069  
2070 The lookup tries (in order):
2071  
2072 =over 4
2073  
2074 =item 1. C<$dir/$lang-$sublang.$ext> (e.g. C<en-gb.json>)
2075  
2076 =item 2. C<$dir/$lang.$ext> (e.g. C<en.json>)
2077  
2078 =back
2079  
2080 Returns C<undef> if no matching file exists.
2081  
2082 =head3 API SPECIFICATION
2083  
2084 Input:
2085 $dir - Str path to the directory containing translation files
2086 $ext - Str file extension without leading dot (default: 'json')
2087 Returns: Str (absolute or relative path) | undef
2088  
2089 =head3 EXAMPLE
2090  
2091 local $ENV{HTTP_ACCEPT_LANGUAGE} = 'en-gb';
2092 my $l = CGI::Lingua->new(supported => ['en-gb', 'en']);
2093 my $path = $l->translation_file('/var/www/i18n');
2094 # Returns '/var/www/i18n/en-gb.json' if it exists,
2095 # then '/var/www/i18n/en.json', or undef.
2096  
2097 # Custom extension:
2098 my $path = $l->translation_file('/var/www/i18n', 'po');
2099  
2100 =head3 MESSAGES
2101  
2102 (none - returns undef silently when no file is found)
2103  
2104 =cut
2105  
2106 sub translation_file
2107 {
2108 my ($self, $dir, $ext) = @_;
2109 return unless defined $dir;
2110  
2111 # Reject traversal attempts in the directory argument. A real translation
2112 # directory never needs '..', null bytes, or other shell metacharacters.
2113 # The caller is responsible for not passing user-controlled data as $dir,
2114 # but we guard here as a defence-in-depth measure.
2115 if($dir =~ /\.\./ || $dir =~ /\x00/) {
2116 $self->_warn({ warning => "translation_file: unsafe directory '$dir' rejected" });
2117 return;
2118 }
2119  
2120 $ext //= 'json';
2121 $ext =~ s/^\.//; # accept '.json' or 'json'
2122  
2123 # Reject extensions containing path-traversal sequences or shell metacharacters.
2124 # Valid extensions are word characters and hyphens only (e.g. 'json', 'po', 'yml').
2125 unless($ext =~ /^[A-Za-z0-9\-]+$/) {
2126 $self->_warn({ warning => "translation_file: unsafe extension '$ext' rejected" });
2127 return;
2128 }
2129  
2130 my @candidates;
2131 if(my $sub = $self->sublanguage_code_alpha2()) {
2132 push @candidates, $self->language_code_alpha2() . '-' . $sub;
2133 }
2134 push @candidates, $self->language_code_alpha2()
2135 if defined $self->language_code_alpha2();
2136  
2137 for my $code (@candidates) {
2138 my $path = "$dir/$code.$ext";
2139 return $path if -e $path;
2140 }
2141 return;
2142 }
2143  
2144 # ── _code2language ────────────────────────────────────────────────────────
2145 # Purpose: Translate a 2-char language code to its English name, with
2146 # optional CHI caching.
2147 # Entry: $code — 2-char ISO 639-1 code; must be defined and non-empty.
2148 # Exit: Human-readable language name string, or undef.
2149 # Side Effects: Reads/writes cache.
2150 sub _code2language
2151 {
2152 my ($self, $code) = @_;
2153  
2154 return unless $code;
2155 if(defined($self->{_country})) {
2156 $self->_debug("_code2language $code, country ", $self->{_country});
2157 } else {
2158 $self->_debug("_code2language $code");
2159 }
2160  
2161 unless($self->{_cache}) {
2162 return Locale::Language::code2language($code);
2163 }
2164  
2165 if(my $from_cache = $self->{_cache}->get($CACHE_NS . "code2language:$code")) {
2166 $self->_trace("_code2language found in cache $from_cache");
2167 return $from_cache;
2168 }
2169  
2170 # Compute, cache, then return the value separately —
2171 # CHI->set() is not guaranteed to return the stored value across all drivers
2172 $self->_trace('_code2language not in cache, storing');
2173 my $name = Locale::Language::code2language($code);
2174 if(defined $name) {
2175 $self->{_cache}->set($CACHE_NS . "code2language:$code", $name, $CACHE_TTL_LONG);
2176 }
2177 return $name;
2178 }
2179  
2180 # ── _code2country ─────────────────────────────────────────────────────────
2181 # Purpose: Translate a 2-char country code to a Locale::Object::Country
2182 # object, suppressing the expected "No result found" warning.
2183 # Entry: $code — 2-char ISO 3166-1 alpha-2 code (any case).
2184 # Exit: Locale::Object::Country object, or undef.
2185 # Side Effects: None beyond the Locale::Object::Country look-up.
2186 sub _code2country
2187 {
2188 my ($self, $code) = @_;
2189  
2190 return unless $code;
2191 if($self->{_country}) {
2192 $self->_trace(">_code2country $code, country ", $self->{_country});
2193 } else {
2194 $self->_trace(">_code2country $code");
2195 }
2196  
2197 my $rc;
2198 if($_locale_object_db_ok // 1) {
2199 # Suppress the routine "No result found" warning; catch the database-
2200 # absent exception that Windows installations sometimes throw.
2201 local $SIG{__WARN__} = sub {
2202 warn $_[0] unless $_[0] =~ /No result found in country table/;
2203 };
2204 eval { $rc = Locale::Object::Country->new(code_alpha2 => $code) };
2205 if($@) {
2206 $_locale_object_db_ok = 0
2207 if $@ =~ /database was not in/;
2208 $rc = undef;
2209 } else {
2210 $_locale_object_db_ok = 1;
2211 }
2212 }
2213 $self->_trace('<_code2country ', $code || 'undef');
2214 return $rc;
2215 }
2216  
2217 # ── _country_short_name ───────────────────────────────────────────────────
2218 # Purpose: Return the common short English name for an ISO 3166-1 alpha-2
2219 # code when Locale::Object's database is unavailable. Uses
2220 # %COUNTRY_SHORT_NAMES overrides for codes where Locale::Codes
2221 # returns the full ISO official name rather than the short form.
2222 # Entry: $code — 2-char country code (any case).
2223 # Exit: Short name string, or undef.
2224 sub _country_short_name
2225 {
2226 my ($self, $code) = @_;
2227 return unless defined($code);
2228 my $lc = lc($code);
2229 return $COUNTRY_SHORT_NAMES{$lc} if exists $COUNTRY_SHORT_NAMES{$lc};
2230 # Locale::Object may have partially initialised Locale::Codes::Country as a
2231 # dependency before we get here; suppress the spurious 'redefine' warning
2232 # that some Perl/Locale::Codes combinations produce on first full load.
2233 { local $SIG{__WARN__} = sub { warn $_[0] unless $_[0] =~ /redefined/ };
2234 require Locale::Codes::Country; }
2235 return Locale::Codes::Country::code2country($lc, 'alpha-2');
2236 }
2237  
2238 # ── _code2countryname ─────────────────────────────────────────────────────
2239 # Purpose: Translate a 2-char country code to its English name string,
2240 # with optional CHI caching.
2241 # Entry: $code — 2-char ISO 3166-1 alpha-2 code.
2242 # Exit: Country name string, or undef.
2243 # Side Effects: Reads/writes cache.
2244 sub _code2countryname
2245 {
2246 my ($self, $code) = @_;
2247  
2248 return unless $code;
2249 $self->_trace(">_code2countryname $code");
2250  
2251 unless($self->{_cache}) {
2252 my $country = $self->_code2country($code);
2253 return $country->name if defined($country);
2254 return $self->_country_short_name($code);
2255 }
2256  
2257 if(my $from_cache = $self->{_cache}->get($CACHE_NS . "code2countryname:$code")) {
2258 $self->_trace("_code2countryname found in cache $from_cache");
2259 return $from_cache;
2260 }
2261  
2262 my $name;
2263 if(my $country = $self->_code2country($code)) {
2264 $name = $country->name();
2265 } else {
2266 # Locale::Object database absent (common on Windows); fall back to
2267 # Locale::Codes::Country with a short-name correction table.
2268 $name = $self->_country_short_name($code);
2269 }
2270  
2271 if(defined($name)) {
2272 $self->_debug('_code2countryname not in cache, storing');
2273 $self->_trace('<_code2countryname ', $name);
2274 $self->{_cache}->set($CACHE_NS . "code2countryname:$code", $name, $CACHE_TTL_LONG);
2275 return $name;
2276 }
2277 $self->_trace('<_code2countryname undef');
2278 return;
2279 }
2280  
2281 # ── _log ──────────────────────────────────────────────────────────────────
2282 # Purpose: Append a message to $self->{messages} and forward to the
2283 # optional logger object.
2284 # Entry: $level — log level string (debug/info/notice/warn/trace/error);
2285 # @messages — one or more strings to concatenate.
2286 # Exit: void
2287 # Side Effects: Mutates $self->{messages}; calls logger method if set.
2288 sub _log
2289 {
2290 my ($self, $level, @messages) = @_;
2291  
2292 return unless ref($self) && scalar(@messages);
2293  
2294 my $text = join('', grep defined, @messages);
2295 return unless length($text);
2296 push @{$self->{'messages'}}, { level => $level, message => $text };
2297  
2298 if(my $logger = $self->{'logger'}) {
2299 $logger->$level($text);
2300 }
2301 }
2302  
2303 sub _debug { my $self = shift; $self->_log('debug', @_) }
2304 sub _info { my $self = shift; $self->_log('info', @_) }
2305 sub _notice { my $self = shift; $self->_log('notice', @_) }
2306 sub _trace { my $self = shift; $self->_log('trace', @_) }
2307  
2308 # ── _warn ─────────────────────────────────────────────────────────────────
2309 # Purpose: Emit a warning through the logger (if set) or via Carp::carp.
2310 # Entry: A single hashref argument: { warning => 'message text' }.
2311 # All callers MUST use this structured form — plain-string calls
2312 # silently lose the message when no logger is configured.
2313 # Exit: void
2314 # Side Effects: Calls logger->warn() or carp().
2315 sub _warn
2316 {
2317 my $self = shift;
2318  
2319 # Parse once; both branches need the same $msg.
2320 my $params = Params::Get::get_params('warning', @_);
2321 my $msg = (ref($params) ? $params->{'warning'} : undef) // join('', grep defined, @_);
2322  
2323 if(defined($self->{'logger'})) {
2324 $self->{'logger'}->warn($msg);
2325 } else {
2326 $self->_log('warn', $msg);
2327 carp($msg);
2328 }
2329 }
2330  
2331 # ── Pure-Perl IP-validation helpers ──────────────────────────────────────────
2332 # These are installed into the CGI::Lingua symbol table as is_ipv4() etc. when
2333 # Data::Validate::IP / NetAddr::IP are unavailable (see country()).
2334  
2335 sub _is_ipv4 {
2336 my $ip = shift;
2337 return unless defined($ip) && $ip =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
2338 return !(grep { $_ > 255 } ($1, $2, $3, $4));
2339 }
2340  
2341 sub _is_ipv6 {
2342 my $ip = shift;
2343 return unless defined($ip) && $ip =~ /:/;
2344 # Socket::inet_pton is core since Perl 5.14 and validates IPv6 reliably
2345 if(defined &Socket::inet_pton) {
2346 require Socket;
2347 return defined Socket::inet_pton(Socket::AF_INET6(), $ip);
2348 }
2349 # Structural fallback: hex+colons, at least two colons, at most one ::
2350 return ($ip =~ /^[0-9a-fA-F:]+$/ || $ip =~ /^[0-9a-fA-F:]+:\d{1,3}(?:\.\d{1,3}){3}$/)
2351 && ($ip =~ tr/:://) <= 1
2352 && ($ip =~ tr/://) >= 2;
2353 }
2354  
2355 sub _is_private_ip {
2356 my $ip = shift;
2357 return unless defined($ip);
2358 if($ip =~ /^(\d+)\.(\d+)/) {
2359 my ($a, $b) = ($1 + 0, $2 + 0);
2360 return 1 if $a == 10;
2361 return 1 if $a == 172 && $b >= 16 && $b <= 31;
2362 return 1 if $a == 192 && $b == 168;
2363 return 1 if $a == 169 && $b == 254; # link-local / APIPA
2364 return 0;
2365 }
2366 return 1 if $ip =~ /^fe[89ab][0-9a-f]:/i; # fe80::/10 link-local
2367 return 1 if $ip =~ /^f[cd]/i; # fc00::/7 ULA
2368 return 0;
2369 }
2370  
2371 sub _is_loopback_ip {
2372 my $ip = shift;
2373 return unless defined($ip);
2374 return 1 if $ip eq '::1';
2375 return $ip =~ /^127\./;
2376 }
2377  
2378 =head1 LIMITATIONS
2379  
2380 =over 4
2381  
2382 =item * B<is_rtl() covers primary-script RTL languages only>
2383  
2384 C<is_rtl()> returns true for the 10 ISO 639-1 codes whose overwhelmingly
2385 dominant script is right-to-left. Languages with script variants (e.g.
2386 Azerbaijani C<az>, which uses Latin in modern Azerbaijan but Arabic in Iran)
2387 are treated as LTR. If you serve content in multiple scripts of the same
2388 language, inspect the sublanguage or Accept-Language header directly.
2389  
2390 =item * B<plural_category() uses embedded CLDR rules, not Locale::CLDR>
2391  
2392 The embedded rules cover ~70 languages and truncate fractional C<$n> to an
2393 integer. For full CLDR v42 accuracy (including fractional forms and
2394 languages not in the table) install and use C<Locale::CLDR> directly.
2395  
2396 =item * B<Logger must be a blessed object>
2397  
2398 The C<logger> parameter is documented as accepting a code ref, array ref, or
2399 filename, but the current implementation calls C<< $logger->$level() >> and will
2400 die on non-blessed values. Wrap alternative logger types in a
2401 C<Log::Abstraction> instance before passing them to C<new()>.
2402  
2403 =item * B<es-419 sublanguage returns undef>
2404  
2405 Three-part regional codes such as C<es-419> (Latin American Spanish) do not
2406 resolve to a C<sublanguage()> value because ISO 3166-1 does not define '419'.
2407 This is a known limitation of the Locale::Object layer.
2408  
2409 =item * B<Whois lookups are slow and unreliable>
2410  
2411 Without C<IP::Country>, C<Geo::IP>, or C<Geo::IPfree> installed, C<country()>
2412 falls back to Whois queries against live RIPE/ARIN/IANA servers. These can
2413 time out under load. Install at least one local geo-database module and enable
2414 the CHI cache to avoid this.
2415  
2416 =item * B<Private methods are accessible from outside the package>
2417  
2418 The C<_*> methods use the naming convention for privacy but Perl does not enforce
2419 it. C<Sub::Private> or C<Sub::Protected> should be added once all white-box
2420 tests (C<t/function.t>, C<t/extended_tests.t>) are updated to use the public API
2421 exclusively.
2422  
2423 =item * B<IPv4-mapped IPv6 addresses are normalised to IPv4>
2424  
2425 C<REMOTE_ADDR> values in the form C<::ffff:a.b.c.d> (RFC 4291 section 2.5.5)
2426 are silently rewritten to the embedded C<a.b.c.d> IPv4 address before any
2427 geo-lookup. This is correct for country detection purposes but means the raw
2428 address string is not preserved in cache keys or log messages.
2429  
2430 =item * B<EU country code is irresolvable (with one exception)>
2431  
2432 IP addresses that Whois reports as country C<EU> are mapped to C<'Unknown'>
2433 unless they fall within Baidu's known subnet (RT-86809). There is no ISO
2434 3166-1 country code for the European Union.
2435  
2436 =item * B<country() does not cache undef results>
2437  
2438 When C<country()> cannot determine a country (private IPs, loopback,
2439 unresolvable addresses), it returns C<undef> without storing the result. A
2440 second call on the same object repeats the full validation pipeline. This is
2441 intentional: C<country()> reads C<REMOTE_ADDR> at call time rather than at
2442 construction time, so caching C<undef> would return a wrong answer if
2443 C<REMOTE_ADDR> changes between calls. In practice this is rarely a problem
2444 because C<country()> is called once per request and CGI applications typically
2445 create a fresh object per request.
2446  
2447 =back
2448  
2449 =head1 AUTHOR
2450  
2451 Nigel Horne, C<< <njh at nigelhorne.com> >>
2452  
2453 =head1 BUGS
2454  
2455 Please report any bugs or feature requests to the author.
2456  
2457 If C<HTTP_ACCEPT_LANGUAGE> contains a sub-tag with a 3-digit UN M.49 region
2458 code (e.g. C<es-419> for Latin American Spanish), C<sublanguage()> returns
2459 C<undef> because ISO 3166-1 does not define numeric codes.
2460  
2461 Please report any bugs or feature requests to C<bug-cgi-lingua at rt.cpan.org>,
2462 or through the web interface at
2463 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CGI-Lingua>.
2464 I will be notified, and then you'll
2465 automatically be notified of progress on your bug as I make changes.
2466  
2467 Uses L<I18N::AcceptLanguage> to find the highest priority accepted language.
2468 This means that if you support languages at a lower priority, it may be missed.
2469  
2470 =head1 SEE ALSO
2471  
2472 =over 4
2473  
2474 =item * L<Configure an Object at Runtime|Object::Configure>
2475  
2476 =item * L<Test Dashboard|https://nigelhorne.github.io/CGI-Lingua/coverage/>
2477  
2478 =item * VWF - Versatile Web Framework L<https://github.com/nigelhorne/vwf>
2479  
2480 =item * L<HTTP::BrowserDetect>
2481  
2482 =item * L<I18N::AcceptLanguage>
2483  
2484 =item * L<Locale::Country>
2485  
2486 =back
2487  
2488 =head1 SUPPORT
2489  
2490 This module is provided as-is without any warranty.
2491  
2492 You can find documentation for this module with the perldoc command.
2493  
2494 perldoc CGI::Lingua
2495  
2496 You can also look for information at:
2497  
2498 =over 4
2499  
2500 =item * MetaCPAN
2501  
2502 L<https://metacpan.org/release/CGI-Lingua>
2503  
2504 =item * RT: CPAN's request tracker
2505  
2506 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=CGI-Lingua>
2507  
2508 =item * CPANTS
2509  
2510 L<http://cpants.cpanauthors.org/dist/CGI-Lingua>
2511  
2512 =item * CPAN Testers' Matrix
2513  
2514 L<http://matrix.cpantesters.org/?dist=CGI-Lingua>
2515  
2516 =item * CPAN Testers Dependencies
2517  
2518 L<http://deps.cpantesters.org/?module=CGI::Lingua>
2519  
2520 =back
2521  
2522 =encoding utf-8
2523  
2524 =head1 FORMAL SPECIFICATION
2525  
2526 =head2 new
2527  
2528 new : Class × Params → CGI::Lingua
2529 ∀ p : Params • p.supported ≠ ∅ ⟹ result.language ∈ (p.supported ∪ {'Unknown'})
2530  
2531 =head2 language
2532  
2533 language : CGI::Lingua → Str
2534 result ∈ {name(l) | l ∈ supported} ∪ {'Unknown'}
2535  
2536 =head2 sublanguage
2537  
2538 sublanguage : CGI::Lingua -> Str | undef
2539 result = country_name(sublanguage_code_alpha2(self))
2540 when sublanguage_code_alpha2(self) is defined,
2541 undef otherwise
2542  
2543 =head2 language_code_alpha2
2544  
2545 language_code_alpha2 : CGI::Lingua -> Str(2) | undef
2546 result = base_code(matched_supported_entry)
2547 when a supported language was matched, undef otherwise
2548  
2549 =head2 sublanguage_code_alpha2
2550  
2551 sublanguage_code_alpha2 : CGI::Lingua -> Str(2) | undef
2552 result = variety_code(matched_supported_entry) | undef
2553  
2554 =head2 requested_language
2555  
2556 requested_language : CGI::Lingua -> Str
2557 result = name(base) + " (" + name(variety) + ")"
2558 when variety is known,
2559 = name(base) when no variety,
2560 = 'Unknown' when no language detected
2561  
2562 =head2 country
2563  
2564 country : CGI::Lingua -> Str(2,lowercase) | undef
2565 -- 'Unknown' returned only in the EU/Baidu special case
2566 result = lc(code) where code satisfies ISO 3166-1 alpha-2
2567 | undef when IP is private, loopback, or unresolvable
2568  
2569 =head2 locale
2570  
2571 locale : CGI::Lingua -> Locale::Object::Country | undef
2572 -- Best-guess detection; not guaranteed accurate.
2573 result = first defined value from:
2574 1. UA parenthetical language tag
2575 2. HTTP::BrowserDetect country
2576 3. country() IP lookup
2577 4. GEOIP_COUNTRY_CODE env var
2578  
2579 =head2 time_zone
2580  
2581 time_zone : CGI::Lingua -> Str | undef
2582 result is an IANA timezone name (e.g. 'Europe/London') or undef
2583  
2584 =head2 is_rtl
2585  
2586 is_rtl : CGI::Lingua → Bool
2587 is_rtl(s) ≙ language_code_alpha2(s) ∈ RTL_LANGS
2588  
2589 =head2 text_direction
2590  
2591 text_direction : CGI::Lingua → {'rtl', 'ltr'}
2592 text_direction(s) ≙ is_rtl(s) ? 'rtl' : 'ltr'
2593  
2594 =head2 plural_category
2595  
2596 plural_category : CGI::Lingua x N -> PluralCategory
2597 plural_category(s, n) = PLURAL_RULES[language_code_alpha2(s)](trunc(n))
2598 -- Falls back to English rule (n=1 -> 'one'; else 'other')
2599 -- when language_code_alpha2(s) is undef or not in the rules table.
2600  
2601 =head2 translation_file
2602  
2603 translation_file : CGI::Lingua × Path × Ext → Path | undef
2604 translation_file(s, d, e) ≙
2605 first p ∈ candidates(s) • ∃ file d/p.e
2606 where candidates(s) = [lang(s)-sublang(s), lang(s)] \ {undef}
2607  
2608 =head1 ACKNOWLEDGEMENTS
2609  
2610 =head1 LICENSE AND COPYRIGHT
2611  
2612 Copyright 2010-2026 Nigel Horne.
2613  
2614 Usage is subject to the GPL2 licence terms.
2615 If you use it,
2616 please let me know.
2617  
2618 =cut
2619  
2620 1; # End of CGI::Lingua