help.pl - bugfix module usage (HTML::Template::Pro)
[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 C4::Context;
25 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $DEBUG);
26
27 BEGIN {
28         $VERSION = 3.00;
29         require Exporter;
30         @ISA    = qw(Exporter);
31         @EXPORT = qw(
32                 &getFrameworkLanguages
33                 &getTranslatedLanguages
34                 &getAllLanguages
35         );
36         @EXPORT_OK = qw(getFrameworkLanguages getTranslatedLanguages getAllLanguages get_bidi regex_lang_subtags language_get_description accept_language);
37         $DEBUG = 0;
38 }
39
40 =head1 NAME
41
42 C4::Languages - Perl Module containing language list functions for Koha 
43
44 =head1 SYNOPSIS
45
46 use C4::Languages;
47
48 =head1 DESCRIPTION
49
50 =head1 FUNCTIONS
51
52 =head2 getFrameworkLanguages
53
54 Returns a reference to an array of hashes:
55
56  my $languages = getFrameworkLanguages();
57  for my $language(@$languages) {
58     print "$language->{language_code}\n"; # language code in iso 639-2
59     print "$language->{language_name}\n"; # language name in native script
60     print "$language->{language_locale_name}\n"; # language name in current locale
61  }
62
63 =cut
64
65 sub getFrameworkLanguages {
66     # get a hash with all language codes, names, and locale names
67     my $all_languages = getAllLanguages();
68     my @languages;
69     
70     # find the available directory names
71     my $dir=C4::Context->config('intranetdir')."/installer/data/";
72     opendir (MYDIR,$dir);
73     my @listdir= grep { !/^\.|CVS/ && -d "$dir/$_"} readdir(MYDIR);    
74     closedir MYDIR;
75
76     # pull out all data for the dir names that exist
77     for my $dirname (@listdir) {
78         for my $language_set (@$all_languages) {
79
80             if ($dirname eq $language_set->{language_code}) {
81                 push @languages, {
82                                         'language_code'=>$dirname, 
83                                         'language_description'=>$language_set->{language_description}, 
84                                         'native_descrition'=>$language_set->{language_native_description} }
85             }
86         }
87     }
88     return \@languages;
89 }
90
91 =head2 getTranslatedLanguages
92
93 Returns a reference to an array of hashes:
94
95  my $languages = getTranslatedLanguages();
96  print "Available translated langauges:\n";
97  for my $language(@$trlanguages) {
98     print "$language->{language_code}\n"; # language code in iso 639-2
99     print "$language->{language_name}\n"; # language name in native script
100     print "$language->{language_locale_name}\n"; # language name in current locale
101  }
102
103 =cut
104
105 sub getTranslatedLanguages {
106     my ($interface, $theme) = @_;
107     my $htdocs;
108     my $all_languages = getAllLanguages();
109     my @languages;
110     my $lang;
111     
112     if ($interface && $interface eq 'opac' ) {
113         $htdocs = C4::Context->config('opachtdocs');
114         if ( $theme and -d "$htdocs/$theme" ) {
115             (@languages) = _get_language_dirs($htdocs,$theme);
116             return _build_languages_arrayref($all_languages,@languages);
117         }
118         else {
119             for my $theme ( _get_themes('opac') ) {
120                 push @languages, _get_language_dirs($htdocs,$theme);
121             }
122             return _build_languages_arrayref($all_languages,@languages);
123         }
124     }
125     elsif ($interface && $interface eq 'intranet' ) {
126         $htdocs = C4::Context->config('intrahtdocs');
127         if ( $theme and -d "$htdocs/$theme" ) {
128             @languages = _get_language_dirs($htdocs,$theme);
129             return _build_languages_arrayref($all_languages,@languages);
130         }
131         else {
132             foreach my $theme ( _get_themes('opac') ) {
133                 push @languages, _get_language_dirs($htdocs,$theme);
134             }
135             return _build_languages_arrayref($all_languages,@languages);
136         }
137     }
138     else {
139         my $htdocs = C4::Context->config('intrahtdocs');
140         foreach my $theme ( _get_themes('intranet') ) {
141             push @languages, _get_language_dirs($htdocs,$theme);
142         }
143         $htdocs = C4::Context->config('opachtdocs');
144         foreach my $theme ( _get_themes('opac') ) {
145             push @languages, _get_language_dirs($htdocs,$theme);
146         }
147         return _build_languages_arrayref($all_languages,@languages);
148     }
149 }
150
151 =head2 getAllLanguages
152
153 Returns a reference to an array of hashes:
154
155  my $alllanguages = getAllLanguages();
156  print "Available translated langauges:\n";
157  for my $language(@$alllanguages) {
158     print "$language->{language_code}\n";
159     print "$language->{language_name}\n";
160     print "$language->{language_locale_name}\n";
161  }
162
163 =cut
164
165 sub getAllLanguages {
166         my @languages_loop;
167         my $dbh=C4::Context->dbh;
168         my $current_language = 'en';
169         my $sth = $dbh->prepare('SELECT * FROM language_subtag_registry WHERE type=\'language\'');
170         $sth->execute();
171         while (my $language_subtag_registry = $sth->fetchrow_hashref) {
172
173                 # pull out all the script descriptions for each language
174                 my $sth2= $dbh->prepare('SELECT * FROM language_descriptions WHERE type=\'language\' AND subtag =?');
175                 $sth2->execute($language_subtag_registry->{subtag});
176
177                 # add the correct description info
178                 while (my $language_descriptions = $sth2->fetchrow_hashref) {
179                         
180                         # Insert the language description using the current language script
181                         #if ( $language_subtag_registry->{subtag}
182                         if ( $current_language eq $language_descriptions->{lang} ) {
183                                 $language_subtag_registry->{language_description} = $language_descriptions->{description};
184                                 #warn "CUR:".$language_subtag_registry->{description};
185                         }
186
187                         # Insert the language name using the script     native to the language (FIXME: should really be based on script)
188                         if  ($language_subtag_registry->{subtag} eq $language_descriptions->{lang}) {
189                                 $language_subtag_registry->{language_native_description} = $language_descriptions->{description};
190                                 #warn "NAT: Desc:$language_descriptions->{description} SubtagDesc: $language_subtag_registry->{language_description}";
191                         }
192                 }       
193                 push @languages_loop, $language_subtag_registry;
194         }
195     return \@languages_loop;
196 }
197
198 =head2 _get_themes
199
200 Internal function, returns an array of all available themes.
201
202   (@themes) = &_get_themes('opac');
203   (@themes) = &_get_themes('intranet');
204
205 =cut
206
207 sub _get_themes {
208     my $interface = shift;
209     my $htdocs;
210     my @themes;
211     if ( $interface eq 'intranet' ) {
212         $htdocs = C4::Context->config('intrahtdocs');
213     }
214     else {
215         $htdocs = C4::Context->config('opachtdocs');
216     }
217     opendir D, "$htdocs";
218     my @dirlist = readdir D;
219     foreach my $directory (@dirlist) {
220         # if there's an en dir, it's a valid theme
221         -d "$htdocs/$directory/en" and push @themes, $directory;
222     }
223     return @themes;
224 }
225
226 =head2 _get_language_dirs
227
228 Internal function, returns an array of directory names, excluding non-language directories
229
230 =cut
231
232 sub _get_language_dirs {
233     my ($htdocs,$theme) = @_;
234     my @languages;
235     opendir D, "$htdocs/$theme";
236     for my $language ( readdir D ) {
237         next if $language =~/^\./;
238         next if $language eq 'all';
239         next if $language =~/png$/;
240         next if $language =~/css$/;
241         next if $language =~/CVS$/;
242         next if $language =~/\.txt$/i;     #Don't read the readme.txt !
243                 next if $language =~/img|images/;
244         push @languages, $language;
245     }
246         return (@languages);
247 }
248
249 =head2 _build_languages_arrayref 
250
251 Internal function for building the ref to array of hashes
252
253 FIXME: this could be rewritten and simplified using map
254
255 =cut
256
257 sub _build_languages_arrayref {
258         my ($all_languages,@languages) = @_;
259         my @final_languages;
260         my %seen_languages;
261                 my %found_languages;
262                 # Loop through the languages, pick the ones that are translated
263         for my $language (@languages) {
264
265                         # separate the language string into its subtag types
266                         my $language_subtags_hashref = regex_lang_subtags($language);
267             unless ($seen_languages{$language}) {
268                 for my $language_code (@$all_languages) {
269                     if ($language_subtags_hashref->{language} eq $language_code->{'subtag'}) {
270                                                 $language_code->{'language_lang'} = $language;
271                                                 $language_code->{'language_code'} = $language_subtags_hashref->{'language'};
272                                                 $language_code->{'script_code'} = $language_subtags_hashref->{'script'};
273                                                 $language_code->{'region_code'} = $language_subtags_hashref->{'region'};
274                                                 $language_code->{'variant_code'} = $language_subtags_hashref->{'variant'};
275                         push @final_languages, $language_code;
276                                                 $found_languages{$language}++;
277                     }
278                 }
279                 $seen_languages{$language}++;
280
281                                 # Handle languages not in our database with their code
282                                 unless ($found_languages{$language}) {
283                                         my $language_code;
284                                         $language_code->{'language_lang'} = $language;
285                                         $language_code->{'language_code'} = $language;
286                                         push @final_languages, $language_code;
287                                 }
288             }
289         }
290         return \@final_languages;
291 }
292
293 sub language_get_description {
294         my ($script,$lang,$type) = @_;
295         my $dbh = C4::Context->dbh;
296         my $desc;
297         my $sth = $dbh->prepare('SELECT description FROM language_descriptions WHERE subtag=? AND lang=? AND type=?');
298         $sth->execute($script,$lang,$type);
299         while (my $descriptions = $sth->fetchrow_hashref) {
300                 $desc = $descriptions->{'description'};
301         }
302         return $desc;
303 }
304 =head2 regex_lang_subtags
305
306 This internal sub takes a string composed according to RFC 4646 as
307 an input and returns a reference to a hash containing keys and values
308 for ( language, script, region, variant, extension, privateuse )
309
310 =cut
311
312 sub regex_lang_subtags {
313     my $string = shift;
314
315     # Regex for recognizing RFC 4646 well-formed tags
316     # http://www.rfc-editor.org/rfc/rfc4646.txt
317
318     # regexes based on : http://unicode.org/cldr/data/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
319     # The structure requires no forward references, so it reverses the order.
320     # The uppercase comments are fragments copied from RFC 4646
321     #
322     # Note: the tool requires that any real "=" or "#" or ";" in the regex be escaped.
323
324     my $alpha   = qr/[a-zA-Z]/ ;    # ALPHA
325     my $digit   = qr/[0-9]/ ;   # DIGIT
326     my $alphanum    = qr/[a-zA-Z0-9]/ ; # ALPHA / DIGIT
327     my $x   = qr/[xX]/ ;    # private use singleton
328     my $singleton = qr/[a-w y-z A-W Y-Z]/ ; # other singleton
329     my $s   = qr/[-]/ ; # separator -- lenient parsers will use [-_]
330
331     # Now do the components. The structure is slightly different to allow for capturing the right components.
332     # The notation (?:....) is a non-capturing version of (...): so the "?:" can be deleted if someone doesn't care about capturing.
333
334     my $extlang = qr{(?: $s $alpha{3} )}x ; # *3("-" 3ALPHA)
335     my $language    = qr{(?: $alpha{2,3} | $alpha{4,8} )}x ;
336     #my $language   = qr{(?: $alpha{2,3}$extlang{0,3} | $alpha{4,8} )}x ;   # (2*3ALPHA [ extlang ]) / 4ALPHA / 5*8ALPHA
337
338     my $script  = qr{(?: $alpha{4} )}x ;    # 4ALPHA 
339
340     my $region  = qr{(?: $alpha{2} | $digit{3} )}x ;     # 2ALPHA / 3DIGIT
341
342     my $variantSub  = qr{(?: $digit$alphanum{3} | $alphanum{5,8} )}x ;  # *("-" variant), 5*8alphanum / (DIGIT 3alphanum)
343     my $variant = qr{(?: $variantSub (?: $s$variantSub )* )}x ; # *("-" variant), 5*8alphanum / (DIGIT 3alphanum)
344
345     my $extensionSub    = qr{(?: $singleton (?: $s$alphanum{2,8} )+ )}x ;   # singleton 1*("-" (2*8alphanum))
346     my $extension   = qr{(?: $extensionSub (?: $s$extensionSub )* )}x ; # singleton 1*("-" (2*8alphanum))
347
348     my $privateuse  = qr{(?: $x (?: $s$alphanum{1,8} )+ )}x ;   # ("x"/"X") 1*("-" (1*8alphanum))
349
350     # Define certain grandfathered codes, since otherwise the regex is pretty useless.
351     # Since these are limited, this is safe even later changes to the registry --
352     # the only oddity is that it might change the type of the tag, and thus
353     # the results from the capturing groups.
354     # http://www.iana.org/assignments/language-subtag-registry
355     # Note that these have to be compared case insensitively, requiring (?i) below.
356
357     my $grandfathered   = qr{(?: (?i)
358         en $s GB $s oed
359     |   i $s (?: ami | bnn | default | enochian | hak | klingon | lux | mingo | navajo | pwn | tao | tay | tsu )
360     |   sgn $s (?: BE $s fr | BE $s nl | CH $s de)
361 )}x;
362
363     # For well-formedness, we don't need the ones that would otherwise pass, so they are commented out here
364
365     #   |   art $s lojban
366     #   |   cel $s gaulish
367     #   |   en $s (?: boont | GB $s oed | scouse )
368     #   |   no $s (?: bok | nyn)
369     #   |   zh $s (?: cmn | cmn $s Hans | cmn $s Hant | gan | guoyu | hakka | min | min $s nan | wuu | xiang | yue)
370
371     # Here is the final breakdown, with capturing groups for each of these components
372     # The language, variants, extensions, grandfathered, and private-use may have interior '-'
373
374     #my $root = qr{(?: ($language) (?: $s ($script) )? 40% (?: $s ($region) )? 40% (?: $s ($variant) )? 10% (?: $s ($extension) )? 5% (?: $s ($privateuse) )? 5% ) 90% | ($grandfathered) 5% | ($privateuse) 5% };
375
376         $string =~  qr{^ (?:($language)) (?:$s($script))? (?:$s($region))?  (?:$s($variant))?  (?:$s($extension))?  (?:$s($privateuse))? $}xi;  # |($grandfathered) | ($privateuse) $}xi;
377         my %subtag = (
378         'language' => $1,
379         'script' => $2,
380         'region' => $3,
381         'variant' => $4,
382         'extension' => $5,
383         'privateuse' => $6,
384     );
385     return \%subtag;
386 }
387
388 # Script Direction Resources:
389 # http://www.w3.org/International/questions/qa-scripts
390 sub get_bidi {
391         my ($language_script)= @_;
392         my $dbh = C4::Context->dbh;
393         my $bidi;
394         my $sth = $dbh->prepare('SELECT bidi FROM language_script_bidi WHERE rfc4646_subtag=?');
395         $sth->execute($language_script);
396         while (my $result = $sth->fetchrow_hashref) {
397                 $bidi = $result->{'bidi'};
398         }
399         return $bidi;
400 };
401
402 sub accept_language {
403         # referenced http://search.cpan.org/src/CGILMORE/I18N-AcceptLanguage-1.04/lib/I18N/AcceptLanguage.pm
404         my      ($clientPreferences,$supportedLanguages) = @_;
405         # There should be no whitespace anways, but a cleanliness/sanity check
406         $clientPreferences =~ s/\s//g;
407   
408         # Prepare the list of client-acceptable languages
409         my @languages = ();
410         foreach my $tag (split(/,/, $clientPreferences)) {
411                 my ($language, $quality) = split(/\;/, $tag);
412                 $quality =~ s/^q=//i if $quality;
413                 $quality = 1 unless $quality;
414                 next if $quality <= 0;
415                 # We want to force the wildcard to be last
416                 $quality = 0 if ($language eq '*');
417                 # Pushing lowercase language here saves processing later
418                 push(@languages, { quality => $quality,
419                        language => $language,
420                        lclanguage => lc($language) });
421         }
422         # Prepare the list of server-supported languages
423         my %supportedLanguages = ();
424         my %secondaryLanguages = ();
425         foreach my $language (@$supportedLanguages) {
426                 warn "SUP: ".$language->{language_code};
427                 $supportedLanguages{lc($language->{language_code})} = $language->{language_code};
428                 if ($language->{language_code} =~ /^([^-]+)-?/) {
429                         $secondaryLanguages{lc($1)} = $language->{language_code};
430                 }
431         }
432
433         # Reverse sort the list, making best quality at the front of the array
434         @languages = sort { $b->{quality} <=> $a->{quality} } @languages;
435         my $secondaryMatch = '';
436         foreach my $tag (@languages) {
437                 if (exists($supportedLanguages{$tag->{lclanguage}})) {
438                         # Client en-us eq server en-us
439                         return $supportedLanguages{$tag->{language}} if exists($supportedLanguages{$tag->{language}});
440                         return $supportedLanguages{$tag->{lclanguage}};
441                 } elsif (exists($secondaryLanguages{$tag->{lclanguage}})) {
442                         # Client en eq server en-us
443                         return $secondaryLanguages{$tag->{language}} if exists($secondaryLanguages{$tag->{language}});
444                         return $supportedLanguages{$tag->{lclanguage}};
445                 } elsif ($tag->{lclanguage} =~ /^([^-]+)-/ && exists($secondaryLanguages{$1}) && $secondaryMatch eq '') {
446                         # Client en-gb eq server en-us
447                         $secondaryMatch = $secondaryLanguages{$1};
448                 } elsif ($tag->{lclanguage} =~ /^([^-]+)-/ && exists($secondaryLanguages{$1}) && $secondaryMatch eq '') {
449                         # Client en-us eq server en
450                         $secondaryMatch = $supportedLanguages{$1};
451                 } elsif ($tag->{lclanguage} eq '*') {
452                 # * matches every language not already specified.
453                 # It doesn't care which we pick, so let's pick the default,
454                 # if available, then the first in the array.
455                 #return $acceptor->defaultLanguage() if $acceptor->defaultLanguage();
456                 return $supportedLanguages->[0];
457                 }
458         }
459         # No primary matches. Secondary? (ie, en-us requested and en supported)
460         return $secondaryMatch if $secondaryMatch;
461 }
462 1;
463
464 __END__
465
466 =head1 AUTHOR
467
468 Joshua Ferraro
469
470 =cut