8eb66938253eabd8d39465a25ebe0b486a0a933c
[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, $current_language) = @_;
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,$current_language);
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,$current_language);
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,$current_language);
131         }
132         else {
133             foreach my $theme ( _get_themes('intranet') ) {
134                 push @languages, _get_language_dirs($htdocs,$theme);
135             }
136             return _build_languages_arrayref($all_languages,\@languages,$current_language);
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,$current_language);
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 LEFT JOIN language_rfc4646_to_iso639 on language_rfc4646_to_iso639.rfc4646_subtag = language_descriptions.subtag 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             # fill in the ISO6329 code
181             $language_subtag_registry->{iso639_2_code} = $language_descriptions->{iso639_2_code};
182             $language_subtag_registry->{language_description} = $language_descriptions->{description};
183         }
184         push @languages_loop, $language_subtag_registry;
185     }
186     return \@languages_loop;
187 }
188
189 =head2 _get_themes
190
191 Internal function, returns an array of all available themes.
192
193   (@themes) = &_get_themes('opac');
194   (@themes) = &_get_themes('intranet');
195
196 =cut
197
198 sub _get_themes {
199     my $interface = shift;
200     my $htdocs;
201     my @themes;
202     if ( $interface eq 'intranet' ) {
203         $htdocs = C4::Context->config('intrahtdocs');
204     }
205     else {
206         $htdocs = C4::Context->config('opachtdocs');
207     }
208     opendir D, "$htdocs";
209     my @dirlist = readdir D;
210     foreach my $directory (@dirlist) {
211         # if there's an en dir, it's a valid theme
212         -d "$htdocs/$directory/en" and push @themes, $directory;
213     }
214     return @themes;
215 }
216
217 =head2 _get_language_dirs
218
219 Internal function, returns an array of directory names, excluding non-language directories
220
221 =cut
222
223 sub _get_language_dirs {
224     my ($htdocs,$theme) = @_;
225     my @lang_strings;
226     opendir D, "$htdocs/$theme";
227     for my $lang_string ( readdir D ) {
228         next if $lang_string =~/^\./;
229         next if $lang_string eq 'all';
230         next if $lang_string =~/png$/;
231         next if $lang_string =~/css$/;
232         next if $lang_string =~/CVS$/;
233         next if $lang_string =~/\.txt$/i;     #Don't read the readme.txt !
234         next if $lang_string =~/img|images/;
235         push @lang_strings, $lang_string;
236     }
237         return (@lang_strings);
238 }
239
240 =head2 _build_languages_arrayref 
241
242 Internal function for building the ref to array of hashes
243
244 FIXME: this could be rewritten and simplified using map
245
246 =cut
247
248 sub _build_languages_arrayref {
249         my ($all_languages,$translated_languages,$current_language) = @_;
250         my @translated_languages = @$translated_languages;
251         my @languages_loop; # the final reference to an array of hashrefs
252         my %seen_languages; # the language tags we've seen
253         my %found_languages;
254         my $language_groups;
255         my $track_language_groups;
256         my $current_language_regex = regex_lang_subtags($current_language);
257         # Loop through the translated languages
258         for my $translated_language (@translated_languages) {
259
260             # separate the language string into its subtag types
261             my $language_subtags_hashref = regex_lang_subtags($translated_language);
262             
263             # group this language, key by langtag
264             $language_subtags_hashref->{'sublanguage_current'} = 1 if $translated_language eq $current_language;
265             $language_subtags_hashref->{'rfc4646_subtag'} = $translated_language;
266             $language_subtags_hashref->{'native_description'} = language_get_description($language_subtags_hashref->{language},$language_subtags_hashref->{language},'language');
267             $language_subtags_hashref->{'script_description'} = language_get_description($language_subtags_hashref->{script},$language_subtags_hashref->{'language'},'script');
268             $language_subtags_hashref->{'region_description'} = language_get_description($language_subtags_hashref->{region},$language_subtags_hashref->{'language'},'region');
269             $language_subtags_hashref->{'variant_description'} = language_get_description($language_subtags_hashref->{variant},$language_subtags_hashref->{'language'},'variant');
270             $track_language_groups->{$language_subtags_hashref->{'language'}}++;
271             push ( @{ $language_groups->{$language_subtags_hashref->{language}} }, $language_subtags_hashref );
272         }
273         # $key is a language subtag like 'en'
274         while( my ($key, $value) = each %$language_groups) {
275             push @languages_loop,  {
276                             # this is only use if there is one
277                             rfc4646_subtag => @$value[0]->{rfc4646_subtag},
278                             native_description => language_get_description($key,$key,'language'),
279                             language => $key,
280                             sublanguages_loop => $value,
281                             plural => $track_language_groups->{$key} >1 ? 1 : 0,
282                             current => $current_language_regex->{language} eq $key ? 1 : 0,
283                            };
284         }
285         return \@languages_loop;
286 }
287
288 sub language_get_description {
289     my ($script,$lang,$type) = @_;
290     my $dbh = C4::Context->dbh;
291     my $desc;
292     my $sth = $dbh->prepare("SELECT description FROM language_descriptions WHERE subtag=? AND lang=? AND type=?");
293     #warn "QUERY: SELECT description FROM language_descriptions WHERE subtag=$script AND lang=$lang AND type=$type";
294     $sth->execute($script,$lang,$type);
295     while (my $descriptions = $sth->fetchrow_hashref) {
296         $desc = $descriptions->{'description'};
297     }
298     unless ($desc) {
299         $sth = $dbh->prepare("SELECT description FROM language_descriptions WHERE subtag=? AND lang=? AND type=?");
300         $sth->execute($script,'en',$type);
301         while (my $descriptions = $sth->fetchrow_hashref) {
302             $desc = $descriptions->{'description'};
303         }
304     }
305     return $desc;
306 }
307 =head2 regex_lang_subtags
308
309 This internal sub takes a string composed according to RFC 4646 as
310 an input and returns a reference to a hash containing keys and values
311 for ( language, script, region, variant, extension, privateuse )
312
313 =cut
314
315 sub regex_lang_subtags {
316     my $string = shift;
317
318     # Regex for recognizing RFC 4646 well-formed tags
319     # http://www.rfc-editor.org/rfc/rfc4646.txt
320
321     # regexes based on : http://unicode.org/cldr/data/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
322     # The structure requires no forward references, so it reverses the order.
323     # The uppercase comments are fragments copied from RFC 4646
324     #
325     # Note: the tool requires that any real "=" or "#" or ";" in the regex be escaped.
326
327     my $alpha   = qr/[a-zA-Z]/ ;    # ALPHA
328     my $digit   = qr/[0-9]/ ;   # DIGIT
329     my $alphanum    = qr/[a-zA-Z0-9]/ ; # ALPHA / DIGIT
330     my $x   = qr/[xX]/ ;    # private use singleton
331     my $singleton = qr/[a-w y-z A-W Y-Z]/ ; # other singleton
332     my $s   = qr/[-]/ ; # separator -- lenient parsers will use [-_]
333
334     # Now do the components. The structure is slightly different to allow for capturing the right components.
335     # The notation (?:....) is a non-capturing version of (...): so the "?:" can be deleted if someone doesn't care about capturing.
336
337     my $extlang = qr{(?: $s $alpha{3} )}x ; # *3("-" 3ALPHA)
338     my $language    = qr{(?: $alpha{2,3} | $alpha{4,8} )}x ;
339     #my $language   = qr{(?: $alpha{2,3}$extlang{0,3} | $alpha{4,8} )}x ;   # (2*3ALPHA [ extlang ]) / 4ALPHA / 5*8ALPHA
340
341     my $script  = qr{(?: $alpha{4} )}x ;    # 4ALPHA 
342
343     my $region  = qr{(?: $alpha{2} | $digit{3} )}x ;     # 2ALPHA / 3DIGIT
344
345     my $variantSub  = qr{(?: $digit$alphanum{3} | $alphanum{5,8} )}x ;  # *("-" variant), 5*8alphanum / (DIGIT 3alphanum)
346     my $variant = qr{(?: $variantSub (?: $s$variantSub )* )}x ; # *("-" variant), 5*8alphanum / (DIGIT 3alphanum)
347
348     my $extensionSub    = qr{(?: $singleton (?: $s$alphanum{2,8} )+ )}x ;   # singleton 1*("-" (2*8alphanum))
349     my $extension   = qr{(?: $extensionSub (?: $s$extensionSub )* )}x ; # singleton 1*("-" (2*8alphanum))
350
351     my $privateuse  = qr{(?: $x (?: $s$alphanum{1,8} )+ )}x ;   # ("x"/"X") 1*("-" (1*8alphanum))
352
353     # Define certain grandfathered codes, since otherwise the regex is pretty useless.
354     # Since these are limited, this is safe even later changes to the registry --
355     # the only oddity is that it might change the type of the tag, and thus
356     # the results from the capturing groups.
357     # http://www.iana.org/assignments/language-subtag-registry
358     # Note that these have to be compared case insensitively, requiring (?i) below.
359
360     my $grandfathered   = qr{(?: (?i)
361         en $s GB $s oed
362     |   i $s (?: ami | bnn | default | enochian | hak | klingon | lux | mingo | navajo | pwn | tao | tay | tsu )
363     |   sgn $s (?: BE $s fr | BE $s nl | CH $s de)
364 )}x;
365
366     # For well-formedness, we don't need the ones that would otherwise pass, so they are commented out here
367
368     #   |   art $s lojban
369     #   |   cel $s gaulish
370     #   |   en $s (?: boont | GB $s oed | scouse )
371     #   |   no $s (?: bok | nyn)
372     #   |   zh $s (?: cmn | cmn $s Hans | cmn $s Hant | gan | guoyu | hakka | min | min $s nan | wuu | xiang | yue)
373
374     # Here is the final breakdown, with capturing groups for each of these components
375     # The language, variants, extensions, grandfathered, and private-use may have interior '-'
376
377     #my $root = qr{(?: ($language) (?: $s ($script) )? 40% (?: $s ($region) )? 40% (?: $s ($variant) )? 10% (?: $s ($extension) )? 5% (?: $s ($privateuse) )? 5% ) 90% | ($grandfathered) 5% | ($privateuse) 5% };
378
379     $string =~  qr{^ (?:($language)) (?:$s($script))? (?:$s($region))?  (?:$s($variant))?  (?:$s($extension))?  (?:$s($privateuse))? $}xi;  # |($grandfathered) | ($privateuse) $}xi;
380     my %subtag = (
381         'rfc4646_subtag' => $string,
382         'language' => $1,
383         'script' => $2,
384         'region' => $3,
385         'variant' => $4,
386         'extension' => $5,
387         'privateuse' => $6,
388     );
389     return \%subtag;
390 }
391
392 # Script Direction Resources:
393 # http://www.w3.org/International/questions/qa-scripts
394 sub get_bidi {
395     my ($language_script)= @_;
396     my $dbh = C4::Context->dbh;
397     my $bidi;
398     my $sth = $dbh->prepare('SELECT bidi FROM language_script_bidi WHERE rfc4646_subtag=?');
399     $sth->execute($language_script);
400     while (my $result = $sth->fetchrow_hashref) {
401         $bidi = $result->{'bidi'};
402     }
403     return $bidi;
404 };
405
406 sub accept_language {
407     # referenced http://search.cpan.org/src/CGILMORE/I18N-AcceptLanguage-1.04/lib/I18N/AcceptLanguage.pm
408     # FIXME: since this is only used in Output.pm as of Jan 8 2008, maybe it should be IN Output.pm
409     my ($clientPreferences,$supportedLanguages) = @_;
410     my @languages = ();
411     if ($clientPreferences) {
412         # There should be no whitespace anways, but a cleanliness/sanity check
413         $clientPreferences =~ s/\s//g;
414
415         # Prepare the list of client-acceptable languages
416         foreach my $tag (split(/,/, $clientPreferences)) {
417             my ($language, $quality) = split(/\;/, $tag);
418             $quality =~ s/^q=//i if $quality;
419             $quality = 1 unless $quality;
420             next if $quality <= 0;
421             # We want to force the wildcard to be last
422             $quality = 0 if ($language eq '*');
423             # Pushing lowercase language here saves processing later
424             push(@languages, { quality => $quality,
425                language => $language,
426                lclanguage => lc($language) });
427         }
428     } else {
429         carp "accept_language(x,y) called with no clientPreferences (x).";
430     }
431     # Prepare the list of server-supported languages
432     my %supportedLanguages = ();
433     my %secondaryLanguages = ();
434     foreach my $language (@$supportedLanguages) {
435         # warn "Language supported: " . $language->{language_code};
436         $supportedLanguages{lc($language->{language_code})} = $language->{language_code};
437         if ($language->{language_code} =~ /^([^-]+)-?/) {
438             $secondaryLanguages{lc($1)} = $language->{language_code};
439         }
440     }
441
442     # Reverse sort the list, making best quality at the front of the array
443     @languages = sort { $b->{quality} <=> $a->{quality} } @languages;
444     my $secondaryMatch = '';
445     foreach my $tag (@languages) {
446         if (exists($supportedLanguages{$tag->{lclanguage}})) {
447             # Client en-us eq server en-us
448             return $supportedLanguages{$tag->{language}} if exists($supportedLanguages{$tag->{language}});
449             return $supportedLanguages{$tag->{lclanguage}};
450         } elsif (exists($secondaryLanguages{$tag->{lclanguage}})) {
451             # Client en eq server en-us
452             return $secondaryLanguages{$tag->{language}} if exists($secondaryLanguages{$tag->{language}});
453             return $supportedLanguages{$tag->{lclanguage}};
454         } elsif ($tag->{lclanguage} =~ /^([^-]+)-/ && exists($secondaryLanguages{$1}) && $secondaryMatch eq '') {
455             # Client en-gb eq server en-us
456             $secondaryMatch = $secondaryLanguages{$1};
457         } elsif ($tag->{lclanguage} =~ /^([^-]+)-/ && exists($secondaryLanguages{$1}) && $secondaryMatch eq '') {
458             # FIXME: We just checked the exact same conditional!
459             # Client en-us eq server en
460             $secondaryMatch = $supportedLanguages{$1};
461         } elsif ($tag->{lclanguage} eq '*') {
462         # * matches every language not already specified.
463         # It doesn't care which we pick, so let's pick the default,
464         # if available, then the first in the array.
465         #return $acceptor->defaultLanguage() if $acceptor->defaultLanguage();
466         return $supportedLanguages->[0];
467         }
468     }
469     # No primary matches. Secondary? (ie, en-us requested and en supported)
470     return $secondaryMatch if $secondaryMatch;
471     return undef;   # else, we got nothing.
472 }
473 1;
474
475 __END__
476
477 =head1 AUTHOR
478
479 Joshua Ferraro
480
481 =cut