3 # Copyright 2006 (C) LibLime
4 # Joshua Ferraro <jmf@liblime.com>
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA 02111-1307 USA
23 use warnings; #FIXME: turn off warnings before release
26 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $DEBUG);
33 &getFrameworkLanguages
34 &getTranslatedLanguages
37 @EXPORT_OK = qw(getFrameworkLanguages getTranslatedLanguages getAllLanguages get_bidi regex_lang_subtags language_get_description accept_language);
43 C4::Languages - Perl Module containing language list functions for Koha
53 =head2 getFrameworkLanguages
55 Returns a reference to an array of hashes:
57 my $languages = getFrameworkLanguages();
58 for my $language(@$languages) {
59 print "$language->{language_code}\n"; # language code in iso 639-2
60 print "$language->{language_name}\n"; # language name in native script
61 print "$language->{language_locale_name}\n"; # language name in current locale
66 sub getFrameworkLanguages {
67 # get a hash with all language codes, names, and locale names
68 my $all_languages = getAllLanguages();
71 # find the available directory names
72 my $dir=C4::Context->config('intranetdir')."/installer/data/";
74 my @listdir= grep { !/^\.|CVS/ && -d "$dir/$_"} readdir(MYDIR);
77 # pull out all data for the dir names that exist
78 for my $dirname (@listdir) {
79 for my $language_set (@$all_languages) {
81 if ($dirname eq $language_set->{language_code}) {
83 'language_code'=>$dirname,
84 'language_description'=>$language_set->{language_description},
85 'native_descrition'=>$language_set->{language_native_description} }
92 =head2 getTranslatedLanguages
94 Returns a reference to an array of hashes:
96 my $languages = getTranslatedLanguages();
97 print "Available translated langauges:\n";
98 for my $language(@$trlanguages) {
99 print "$language->{language_code}\n"; # language code in iso 639-2
100 print "$language->{language_name}\n"; # language name in native script
101 print "$language->{language_locale_name}\n"; # language name in current locale
106 sub getTranslatedLanguages {
107 my ($interface, $theme) = @_;
109 my $all_languages = getAllLanguages();
113 if ($interface && $interface eq 'opac' ) {
114 $htdocs = C4::Context->config('opachtdocs');
115 if ( $theme and -d "$htdocs/$theme" ) {
116 (@languages) = _get_language_dirs($htdocs,$theme);
117 return _build_languages_arrayref($all_languages,@languages);
120 for my $theme ( _get_themes('opac') ) {
121 push @languages, _get_language_dirs($htdocs,$theme);
123 return _build_languages_arrayref($all_languages,@languages);
126 elsif ($interface && $interface eq 'intranet' ) {
127 $htdocs = C4::Context->config('intrahtdocs');
128 if ( $theme and -d "$htdocs/$theme" ) {
129 @languages = _get_language_dirs($htdocs,$theme);
130 return _build_languages_arrayref($all_languages,@languages);
133 foreach my $theme ( _get_themes('opac') ) {
134 push @languages, _get_language_dirs($htdocs,$theme);
136 return _build_languages_arrayref($all_languages,@languages);
140 my $htdocs = C4::Context->config('intrahtdocs');
141 foreach my $theme ( _get_themes('intranet') ) {
142 push @languages, _get_language_dirs($htdocs,$theme);
144 $htdocs = C4::Context->config('opachtdocs');
145 foreach my $theme ( _get_themes('opac') ) {
146 push @languages, _get_language_dirs($htdocs,$theme);
148 return _build_languages_arrayref($all_languages,@languages);
152 =head2 getAllLanguages
154 Returns a reference to an array of hashes:
156 my $alllanguages = getAllLanguages();
157 print "Available translated langauges:\n";
158 for my $language(@$alllanguages) {
159 print "$language->{language_code}\n";
160 print "$language->{language_name}\n";
161 print "$language->{language_locale_name}\n";
166 sub getAllLanguages {
168 my $dbh=C4::Context->dbh;
169 my $current_language = 'en';
170 my $sth = $dbh->prepare('SELECT * FROM language_subtag_registry WHERE type=\'language\'');
172 while (my $language_subtag_registry = $sth->fetchrow_hashref) {
174 # pull out all the script descriptions for each language
175 my $sth2= $dbh->prepare('SELECT * FROM language_descriptions WHERE type=\'language\' AND subtag =?');
176 $sth2->execute($language_subtag_registry->{subtag});
178 # add the correct description info
179 while (my $language_descriptions = $sth2->fetchrow_hashref) {
181 # Insert the language description using the current language script
182 #if ( $language_subtag_registry->{subtag}
183 if ( $current_language eq $language_descriptions->{lang} ) {
184 $language_subtag_registry->{language_description} = $language_descriptions->{description};
185 #warn "CUR:".$language_subtag_registry->{description};
188 # Insert the language name using the script native to the language (FIXME: should really be based on script)
189 if ($language_subtag_registry->{subtag} eq $language_descriptions->{lang}) {
190 $language_subtag_registry->{language_native_description} = $language_descriptions->{description};
191 #warn "NAT: Desc:$language_descriptions->{description} SubtagDesc: $language_subtag_registry->{language_description}";
194 push @languages_loop, $language_subtag_registry;
196 return \@languages_loop;
201 Internal function, returns an array of all available themes.
203 (@themes) = &_get_themes('opac');
204 (@themes) = &_get_themes('intranet');
209 my $interface = shift;
212 if ( $interface eq 'intranet' ) {
213 $htdocs = C4::Context->config('intrahtdocs');
216 $htdocs = C4::Context->config('opachtdocs');
218 opendir D, "$htdocs";
219 my @dirlist = readdir D;
220 foreach my $directory (@dirlist) {
221 # if there's an en dir, it's a valid theme
222 -d "$htdocs/$directory/en" and push @themes, $directory;
227 =head2 _get_language_dirs
229 Internal function, returns an array of directory names, excluding non-language directories
233 sub _get_language_dirs {
234 my ($htdocs,$theme) = @_;
236 opendir D, "$htdocs/$theme";
237 for my $language ( readdir D ) {
238 next if $language =~/^\./;
239 next if $language eq 'all';
240 next if $language =~/png$/;
241 next if $language =~/css$/;
242 next if $language =~/CVS$/;
243 next if $language =~/\.txt$/i; #Don't read the readme.txt !
244 next if $language =~/img|images/;
245 push @languages, $language;
250 =head2 _build_languages_arrayref
252 Internal function for building the ref to array of hashes
254 FIXME: this could be rewritten and simplified using map
258 sub _build_languages_arrayref {
259 my ($all_languages,@languages) = @_;
263 # Loop through the languages, pick the ones that are translated
264 for my $language (@languages) {
266 # separate the language string into its subtag types
267 my $language_subtags_hashref = regex_lang_subtags($language);
268 unless ($seen_languages{$language}) {
269 for my $language_code (@$all_languages) {
270 if ($language_subtags_hashref->{language} eq $language_code->{'subtag'}) {
271 $language_code->{'language_lang'} = $language;
272 $language_code->{'language_code'} = $language_subtags_hashref->{'language'};
273 $language_code->{'script_code'} = $language_subtags_hashref->{'script'};
274 $language_code->{'region_code'} = $language_subtags_hashref->{'region'};
275 $language_code->{'variant_code'} = $language_subtags_hashref->{'variant'};
276 push @final_languages, $language_code;
277 $found_languages{$language}++;
280 $seen_languages{$language}++;
282 # Handle languages not in our database with their code
283 unless ($found_languages{$language}) {
285 $language_code->{'language_lang'} = $language;
286 $language_code->{'language_code'} = $language;
287 push @final_languages, $language_code;
291 return \@final_languages;
294 sub language_get_description {
295 my ($script,$lang,$type) = @_;
296 my $dbh = C4::Context->dbh;
298 my $sth = $dbh->prepare('SELECT description FROM language_descriptions WHERE subtag=? AND lang=? AND type=?');
299 $sth->execute($script,$lang,$type);
300 while (my $descriptions = $sth->fetchrow_hashref) {
301 $desc = $descriptions->{'description'};
305 =head2 regex_lang_subtags
307 This internal sub takes a string composed according to RFC 4646 as
308 an input and returns a reference to a hash containing keys and values
309 for ( language, script, region, variant, extension, privateuse )
313 sub regex_lang_subtags {
316 # Regex for recognizing RFC 4646 well-formed tags
317 # http://www.rfc-editor.org/rfc/rfc4646.txt
319 # regexes based on : http://unicode.org/cldr/data/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
320 # The structure requires no forward references, so it reverses the order.
321 # The uppercase comments are fragments copied from RFC 4646
323 # Note: the tool requires that any real "=" or "#" or ";" in the regex be escaped.
325 my $alpha = qr/[a-zA-Z]/ ; # ALPHA
326 my $digit = qr/[0-9]/ ; # DIGIT
327 my $alphanum = qr/[a-zA-Z0-9]/ ; # ALPHA / DIGIT
328 my $x = qr/[xX]/ ; # private use singleton
329 my $singleton = qr/[a-w y-z A-W Y-Z]/ ; # other singleton
330 my $s = qr/[-]/ ; # separator -- lenient parsers will use [-_]
332 # Now do the components. The structure is slightly different to allow for capturing the right components.
333 # The notation (?:....) is a non-capturing version of (...): so the "?:" can be deleted if someone doesn't care about capturing.
335 my $extlang = qr{(?: $s $alpha{3} )}x ; # *3("-" 3ALPHA)
336 my $language = qr{(?: $alpha{2,3} | $alpha{4,8} )}x ;
337 #my $language = qr{(?: $alpha{2,3}$extlang{0,3} | $alpha{4,8} )}x ; # (2*3ALPHA [ extlang ]) / 4ALPHA / 5*8ALPHA
339 my $script = qr{(?: $alpha{4} )}x ; # 4ALPHA
341 my $region = qr{(?: $alpha{2} | $digit{3} )}x ; # 2ALPHA / 3DIGIT
343 my $variantSub = qr{(?: $digit$alphanum{3} | $alphanum{5,8} )}x ; # *("-" variant), 5*8alphanum / (DIGIT 3alphanum)
344 my $variant = qr{(?: $variantSub (?: $s$variantSub )* )}x ; # *("-" variant), 5*8alphanum / (DIGIT 3alphanum)
346 my $extensionSub = qr{(?: $singleton (?: $s$alphanum{2,8} )+ )}x ; # singleton 1*("-" (2*8alphanum))
347 my $extension = qr{(?: $extensionSub (?: $s$extensionSub )* )}x ; # singleton 1*("-" (2*8alphanum))
349 my $privateuse = qr{(?: $x (?: $s$alphanum{1,8} )+ )}x ; # ("x"/"X") 1*("-" (1*8alphanum))
351 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
352 # Since these are limited, this is safe even later changes to the registry --
353 # the only oddity is that it might change the type of the tag, and thus
354 # the results from the capturing groups.
355 # http://www.iana.org/assignments/language-subtag-registry
356 # Note that these have to be compared case insensitively, requiring (?i) below.
358 my $grandfathered = qr{(?: (?i)
360 | i $s (?: ami | bnn | default | enochian | hak | klingon | lux | mingo | navajo | pwn | tao | tay | tsu )
361 | sgn $s (?: BE $s fr | BE $s nl | CH $s de)
364 # For well-formedness, we don't need the ones that would otherwise pass, so they are commented out here
368 # | en $s (?: boont | GB $s oed | scouse )
369 # | no $s (?: bok | nyn)
370 # | zh $s (?: cmn | cmn $s Hans | cmn $s Hant | gan | guoyu | hakka | min | min $s nan | wuu | xiang | yue)
372 # Here is the final breakdown, with capturing groups for each of these components
373 # The language, variants, extensions, grandfathered, and private-use may have interior '-'
375 #my $root = qr{(?: ($language) (?: $s ($script) )? 40% (?: $s ($region) )? 40% (?: $s ($variant) )? 10% (?: $s ($extension) )? 5% (?: $s ($privateuse) )? 5% ) 90% | ($grandfathered) 5% | ($privateuse) 5% };
377 $string =~ qr{^ (?:($language)) (?:$s($script))? (?:$s($region))? (?:$s($variant))? (?:$s($extension))? (?:$s($privateuse))? $}xi; # |($grandfathered) | ($privateuse) $}xi;
389 # Script Direction Resources:
390 # http://www.w3.org/International/questions/qa-scripts
392 my ($language_script)= @_;
393 my $dbh = C4::Context->dbh;
395 my $sth = $dbh->prepare('SELECT bidi FROM language_script_bidi WHERE rfc4646_subtag=?');
396 $sth->execute($language_script);
397 while (my $result = $sth->fetchrow_hashref) {
398 $bidi = $result->{'bidi'};
403 sub accept_language {
404 # referenced http://search.cpan.org/src/CGILMORE/I18N-AcceptLanguage-1.04/lib/I18N/AcceptLanguage.pm
405 # FIXME: since this is only used in Output.pm as of Jan 8 2008, maybe it should be IN Output.pm
406 my ($clientPreferences,$supportedLanguages) = @_;
408 if ($clientPreferences) {
409 # There should be no whitespace anways, but a cleanliness/sanity check
410 $clientPreferences =~ s/\s//g;
412 # Prepare the list of client-acceptable languages
413 foreach my $tag (split(/,/, $clientPreferences)) {
414 my ($language, $quality) = split(/\;/, $tag);
415 $quality =~ s/^q=//i if $quality;
416 $quality = 1 unless $quality;
417 next if $quality <= 0;
418 # We want to force the wildcard to be last
419 $quality = 0 if ($language eq '*');
420 # Pushing lowercase language here saves processing later
421 push(@languages, { quality => $quality,
422 language => $language,
423 lclanguage => lc($language) });
426 carp "accept_language(x,y) called with no clientPreferences (x).";
428 # Prepare the list of server-supported languages
429 my %supportedLanguages = ();
430 my %secondaryLanguages = ();
431 foreach my $language (@$supportedLanguages) {
432 # warn "Language supported: " . $language->{language_code};
433 $supportedLanguages{lc($language->{language_code})} = $language->{language_code};
434 if ($language->{language_code} =~ /^([^-]+)-?/) {
435 $secondaryLanguages{lc($1)} = $language->{language_code};
439 # Reverse sort the list, making best quality at the front of the array
440 @languages = sort { $b->{quality} <=> $a->{quality} } @languages;
441 my $secondaryMatch = '';
442 foreach my $tag (@languages) {
443 if (exists($supportedLanguages{$tag->{lclanguage}})) {
444 # Client en-us eq server en-us
445 return $supportedLanguages{$tag->{language}} if exists($supportedLanguages{$tag->{language}});
446 return $supportedLanguages{$tag->{lclanguage}};
447 } elsif (exists($secondaryLanguages{$tag->{lclanguage}})) {
448 # Client en eq server en-us
449 return $secondaryLanguages{$tag->{language}} if exists($secondaryLanguages{$tag->{language}});
450 return $supportedLanguages{$tag->{lclanguage}};
451 } elsif ($tag->{lclanguage} =~ /^([^-]+)-/ && exists($secondaryLanguages{$1}) && $secondaryMatch eq '') {
452 # Client en-gb eq server en-us
453 $secondaryMatch = $secondaryLanguages{$1};
454 } elsif ($tag->{lclanguage} =~ /^([^-]+)-/ && exists($secondaryLanguages{$1}) && $secondaryMatch eq '') {
455 # FIXME: We just checked the exact same conditional!
456 # Client en-us eq server en
457 $secondaryMatch = $supportedLanguages{$1};
458 } elsif ($tag->{lclanguage} eq '*') {
459 # * matches every language not already specified.
460 # It doesn't care which we pick, so let's pick the default,
461 # if available, then the first in the array.
462 #return $acceptor->defaultLanguage() if $acceptor->defaultLanguage();
463 return $supportedLanguages->[0];
466 # No primary matches. Secondary? (ie, en-us requested and en supported)
467 return $secondaryMatch if $secondaryMatch;
468 return undef; # else, we got nothing.