6667b7a8086197e731d39f06452550f28f0bce0a
[koha.git] / C4 / Languages.pm
1 package C4::Languages;
2
3 # Copyright 2006 (C) LibLime
4 # Joshua Ferraro <jmf@liblime.com>
5 #
6 # This file is part of Koha.
7 #
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
11 # version.
12 #
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.
16 #
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
20
21
22 use strict; 
23 use warnings;   #FIXME: turn off warnings before release
24 use Carp;
25 use C4::Context;
26 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $DEBUG);
27
28 BEGIN {
29         $VERSION = 3.00;
30         require Exporter;
31         @ISA    = qw(Exporter);
32         @EXPORT = qw(
33                 &getFrameworkLanguages
34                 &getTranslatedLanguages
35                 &getAllLanguages
36         );
37         @EXPORT_OK = qw(getFrameworkLanguages getTranslatedLanguages getAllLanguages get_bidi regex_lang_subtags language_get_description accept_language);
38         $DEBUG = 0;
39 }
40
41 =head1 NAME
42
43 C4::Languages - Perl Module containing language list functions for Koha 
44
45 =head1 SYNOPSIS
46
47 use C4::Languages;
48
49 =head1 DESCRIPTION
50
51 =head1 FUNCTIONS
52
53 =head2 getFrameworkLanguages
54
55 Returns a reference to an array of hashes:
56
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
62  }
63
64 =cut
65
66 sub getFrameworkLanguages {
67     # get a hash with all language codes, names, and locale names
68     my $all_languages = getAllLanguages();
69     my @languages;
70     
71     # find the available directory names
72     my $dir=C4::Context->config('intranetdir')."/installer/data/";
73     opendir (MYDIR,$dir);
74     my @listdir= grep { !/^\.|CVS/ && -d "$dir/$_"} readdir(MYDIR);    
75     closedir MYDIR;
76
77     # pull out all data for the dir names that exist
78     for my $dirname (@listdir) {
79         for my $language_set (@$all_languages) {
80
81             if ($dirname eq $language_set->{language_code}) {
82                 push @languages, {
83                                         'language_code'=>$dirname, 
84                                         'language_description'=>$language_set->{language_description}, 
85                                         'native_descrition'=>$language_set->{language_native_description} }
86             }
87         }
88     }
89     return \@languages;
90 }
91
92 =head2 getTranslatedLanguages
93
94 Returns a reference to an array of hashes:
95
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
102  }
103
104 =cut
105
106 sub getTranslatedLanguages {
107     my ($interface, $theme) = @_;
108     my $htdocs;
109     my $all_languages = getAllLanguages();
110     my @languages;
111     my $lang;
112     
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);
118         }
119         else {
120             for my $theme ( _get_themes('opac') ) {
121                 push @languages, _get_language_dirs($htdocs,$theme);
122             }
123             return _build_languages_arrayref($all_languages,@languages);
124         }
125     }
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);
131         }
132         else {
133             foreach my $theme ( _get_themes('opac') ) {
134                 push @languages, _get_language_dirs($htdocs,$theme);
135             }
136             return _build_languages_arrayref($all_languages,@languages);
137         }
138     }
139     else {
140         my $htdocs = C4::Context->config('intrahtdocs');
141         foreach my $theme ( _get_themes('intranet') ) {
142             push @languages, _get_language_dirs($htdocs,$theme);
143         }
144         $htdocs = C4::Context->config('opachtdocs');
145         foreach my $theme ( _get_themes('opac') ) {
146             push @languages, _get_language_dirs($htdocs,$theme);
147         }
148         return _build_languages_arrayref($all_languages,@languages);
149     }
150 }
151
152 =head2 getAllLanguages
153
154 Returns a reference to an array of hashes:
155
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";
162  }
163
164 =cut
165
166 sub getAllLanguages {
167         my @languages_loop;
168         my $dbh=C4::Context->dbh;
169         my $current_language = 'en';
170         my $sth = $dbh->prepare('SELECT * FROM language_subtag_registry WHERE type=\'language\'');
171         $sth->execute();
172         while (my $language_subtag_registry = $sth->fetchrow_hashref) {
173
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});
177
178                 # add the correct description info
179                 while (my $language_descriptions = $sth2->fetchrow_hashref) {
180                         
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};
186                         }
187
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}";
192                         }
193                 }       
194                 push @languages_loop, $language_subtag_registry;
195         }
196     return \@languages_loop;
197 }
198
199 =head2 _get_themes
200
201 Internal function, returns an array of all available themes.
202
203   (@themes) = &_get_themes('opac');
204   (@themes) = &_get_themes('intranet');
205
206 =cut
207
208 sub _get_themes {
209     my $interface = shift;
210     my $htdocs;
211     my @themes;
212     if ( $interface eq 'intranet' ) {
213         $htdocs = C4::Context->config('intrahtdocs');
214     }
215     else {
216         $htdocs = C4::Context->config('opachtdocs');
217     }
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;
223     }
224     return @themes;
225 }
226
227 =head2 _get_language_dirs
228
229 Internal function, returns an array of directory names, excluding non-language directories
230
231 =cut
232
233 sub _get_language_dirs {
234     my ($htdocs,$theme) = @_;
235     my @languages;
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;
246     }
247         return (@languages);
248 }
249
250 =head2 _build_languages_arrayref 
251
252 Internal function for building the ref to array of hashes
253
254 FIXME: this could be rewritten and simplified using map
255
256 =cut
257
258 sub _build_languages_arrayref {
259         my ($all_languages,@languages) = @_;
260         my @final_languages;
261         my %seen_languages;
262                 my %found_languages;
263                 # Loop through the languages, pick the ones that are translated
264         for my $language (@languages) {
265
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}++;
278                     }
279                 }
280                 $seen_languages{$language}++;
281
282                                 # Handle languages not in our database with their code
283                                 unless ($found_languages{$language}) {
284                                         my $language_code;
285                                         $language_code->{'language_lang'} = $language;
286                                         $language_code->{'language_code'} = $language;
287                                         push @final_languages, $language_code;
288                                 }
289             }
290         }
291         return \@final_languages;
292 }
293
294 sub language_get_description {
295         my ($script,$lang,$type) = @_;
296         my $dbh = C4::Context->dbh;
297         my $desc;
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'};
302         }
303         return $desc;
304 }
305 =head2 regex_lang_subtags
306
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 )
310
311 =cut
312
313 sub regex_lang_subtags {
314     my $string = shift;
315
316     # Regex for recognizing RFC 4646 well-formed tags
317     # http://www.rfc-editor.org/rfc/rfc4646.txt
318
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
322     #
323     # Note: the tool requires that any real "=" or "#" or ";" in the regex be escaped.
324
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 [-_]
331
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.
334
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
338
339     my $script  = qr{(?: $alpha{4} )}x ;    # 4ALPHA 
340
341     my $region  = qr{(?: $alpha{2} | $digit{3} )}x ;     # 2ALPHA / 3DIGIT
342
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)
345
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))
348
349     my $privateuse  = qr{(?: $x (?: $s$alphanum{1,8} )+ )}x ;   # ("x"/"X") 1*("-" (1*8alphanum))
350
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.
357
358     my $grandfathered   = qr{(?: (?i)
359         en $s GB $s oed
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)
362 )}x;
363
364     # For well-formedness, we don't need the ones that would otherwise pass, so they are commented out here
365
366     #   |   art $s lojban
367     #   |   cel $s gaulish
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)
371
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 '-'
374
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% };
376
377         $string =~  qr{^ (?:($language)) (?:$s($script))? (?:$s($region))?  (?:$s($variant))?  (?:$s($extension))?  (?:$s($privateuse))? $}xi;  # |($grandfathered) | ($privateuse) $}xi;
378         my %subtag = (
379         'language' => $1,
380         'script' => $2,
381         'region' => $3,
382         'variant' => $4,
383         'extension' => $5,
384         'privateuse' => $6,
385     );
386     return \%subtag;
387 }
388
389 # Script Direction Resources:
390 # http://www.w3.org/International/questions/qa-scripts
391 sub get_bidi {
392         my ($language_script)= @_;
393         my $dbh = C4::Context->dbh;
394         my $bidi;
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'};
399         }
400         return $bidi;
401 };
402
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) = @_;
407         my @languages = ();
408         if ($clientPreferences) {
409                 # There should be no whitespace anways, but a cleanliness/sanity check
410                 $clientPreferences =~ s/\s//g;
411
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) });
424                 }
425         } else {
426                 carp "accept_language(x,y) called with no clientPreferences (x).";
427         }
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};
436                 }
437         }
438
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];
464                 }
465         }
466         # No primary matches. Secondary? (ie, en-us requested and en supported)
467         return $secondaryMatch if $secondaryMatch;
468         return undef;   # else, we got nothing.
469 }
470 1;
471
472 __END__
473
474 =head1 AUTHOR
475
476 Joshua Ferraro
477
478 =cut