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