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