File:  [LON-CAPA] / loncom / localize / lonlocal.pm
Revision 1.35: download - view: text, annotated - select for diffs
Thu Nov 10 19:19:51 2005 UTC (18 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Display timezone for absolute dates and times.

    1: # The LearningOnline Network with CAPA
    2: # Localization routines
    3: #
    4: # $Id: lonlocal.pm,v 1.35 2005/11/10 19:19:51 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ######################################################################
   29: ######################################################################
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: Apache::lonlocal - provides localization services
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: lonlocal provides localization services for LON-CAPA programmers based
   40: on Locale::Maketext. See
   41: C<http://search.cpan.org/dist/Locale-Maketext/lib/Locale/Maketext.pod>
   42: for more information on Maketext.
   43: 
   44: =head1 OVERVIEWX<internationalization>
   45: 
   46: As of LON-CAPA 1.1, we've started to localize LON-CAPA using the
   47: Locale::Maketext module. Internationalization is the bulk of the work
   48: right now (pre-1.1); localizing can be done anytime, and involves 
   49: little or no programming.
   50: 
   51: The internationalization process involves putting a wrapper around
   52: on-screen user messages and menus and turning them into keys,
   53: which the MaketextX<Maketext> library translates into the desired
   54: language output using a look-up table ("lexicon").X<lexicon>
   55: 
   56: As keys we are currently using the plain English messages, and
   57: Maketext is configured to replace the message by its own key if no
   58: translation is found. This makes it easy to phase in the
   59: internationalization without disturbing the screen output.
   60: 
   61: Internationalization is somewhat tedious and effectively impossible
   62: for a non-fluent speaker to perform, but is fairly easy to create
   63: translations, requiring no programming skill. As a result, this is one
   64: area where you can really help LON-CAPA out, even if you aren't a
   65: programmer, and we'd really appreciate it.
   66: 
   67: =head1 How To Localize Handlers For Programmers
   68: 
   69: Into the "use" section of a module, we need to insert
   70: 
   71:  use Apache::lonlocal;
   72: 
   73: Note that there are B<no parentheses>, we B<want> to pollute our
   74: namespace. 
   75: 
   76: Inside might be something like this
   77: 
   78:  sub message {
   79:      my $status=shift;
   80:      my $message='Status unknown';
   81:      if ($status eq 'WON') {
   82:         $message='You have won.';
   83:      } elsif ($status eq 'LOST') {
   84:         $message='You are a total looser.';
   85:      }
   86:      return $message;
   87:  }
   88:  ...
   89:  $r->print('<h3>Gamble your Homework Points</h3>');
   90:  ...
   91:  $r->print(<<ENDMSG);
   92:  <font size="1">Rules:</font>
   93:  <font size="0">No purchase necessary. Illegal where not allowed.</font>
   94:  ENDMSG
   95: 
   96: We have to now wrap the subroutine &mt()X<mt> ("maketext") around our 
   97: messages, but not around markup, etc. We also want minimal disturbance. 
   98: The first two examples are easy:
   99: 
  100:  sub message {
  101:      my $status=shift;
  102:      my $message='Status unknown';
  103:      if ($status eq 'WON') {
  104:         $message='You have won.';
  105:      } elsif ($status eq 'LOST') {
  106:         $message='You are a total looser.';
  107:      }
  108:      return &mt($message);
  109:  }
  110:  ...
  111:  $r->print('<h3>'.&mt('Gamble your Homework Points').'</h3>');
  112: 
  113: The last one is a bummer, since you cannot call subroutines inside of 
  114: (<<MARKER). I have written a little subroutine to generate a translated 
  115: hash for that purpose:
  116: 
  117:  my %lt=&Apache::lonlocal::texthash('header' => 'Rules', 'disclaimer' => 
  118:  'No purchase necessary. Illegal where not allowed.');
  119:  $r->print(<<ENDMSG);
  120:  <font size="1">$lt{'header'}:</font>
  121:  <font size="0">$lt{'disclaimer'}</font>
  122:  ENDMSG
  123: 
  124: As a programmer, your job is done here. If everything worked, you 
  125: should see no changes on the screen.
  126: 
  127: =head1 How To Localize LON-CAPA for Translators
  128: 
  129: As a translator, you need to provide the lexicon for the keys, which in 
  130: this case is the plain text message. The lexicons sit in 
  131: loncom/localize/localize, with the language code as filename, for 
  132: example de.pm for the German translation. The file then simply looks 
  133: like this:
  134: 
  135:     'You have won.'
  136:  => 'Sie haben gewonnen.',
  137: 
  138:     'You are a total looser.'
  139:  => 'Sie sind der totale Verlierer.',
  140: 
  141:     'Rules'
  142:  => 'Regeln',
  143: 
  144:     'No purchase necessary. Illegal where not allowed.'
  145:  => 'Es ist erlaubt, einfach zu verlieren, und das ist Ihre Schuld.'
  146: 
  147: 
  148: Comments may be added with the # symbol, which outside of a string
  149: (the things with the apostrophe surrounding them, which are the 
  150: keys and translations) will cause the translation routines to
  151: ignore the rest of the line.
  152: 
  153: This is a relatively easy task, and any help is appreciated.
  154: 
  155: Maketext can do a whole lot more, see
  156: C<http://search.cpan.org/dist/Locale-Maketext/lib/Locale/Maketext.pod>
  157: but for most purposes, we do not have to mess with that.
  158: 
  159: =cut
  160: 
  161: package Apache::lonlocal;
  162: 
  163: use strict;
  164: use Apache::Constants qw(:common);
  165: use Apache::localize;
  166: use Apache::File;
  167: use locale;
  168: use POSIX qw(locale_h);
  169: 
  170: require Exporter;
  171: 
  172: our @ISA = qw (Exporter);
  173: our @EXPORT = qw(mt mtn ns);
  174: 
  175: # ========================================================= The language handle
  176: 
  177: use vars qw($lh);
  178: 
  179: # ===================================================== The "MakeText" function
  180: 
  181: sub mt (@) {
  182: #    my $fh=Apache::File->new('>>/home/www/loncapa/loncom/localize/localize/newphrases.txt');
  183: #    print $fh @_[0]."\n";
  184: #    $fh->close();
  185:     if ($lh) {
  186: 	return $lh->maketext(@_);
  187:     } else {
  188: 	if (wantarray) {
  189: 	    return @_;
  190: 	} else {
  191: 	    return $_[0];
  192: 	}
  193:     }
  194: }
  195: 
  196: # ============================================================== What language?
  197: 
  198: sub current_language {
  199:     if ($lh) {
  200: 	my $lang=$lh->maketext('language_code');
  201: 	return ($lang eq 'language_code'?'en':$lang);
  202:     }
  203:     return 'en';
  204: }
  205: 
  206: # ============================================================== What encoding?
  207: 
  208: sub current_encoding {
  209:     my $default='UTF-8';
  210:     if ($Apache::lonnet::env{'browser.os'} eq 'win' && 
  211: 	$Apache::lonnet::env{'browser.type'} eq 'explorer') {
  212:         $default='ISO-8859-1';
  213:     }
  214:     if ($lh) {
  215: 	my $enc=$lh->maketext('char_encoding');
  216: 	return ($enc eq 'char_encoding'?$default:$enc);
  217:     } else {
  218: 	return $default;
  219:     }
  220: }
  221: 
  222: # =============================================================== Which locale?
  223: # Refer to locale -a
  224: #
  225: sub current_locale {
  226:     if ($lh) {
  227: 	my $enc=$lh->maketext('lang_locale');
  228: 	return ($enc eq 'lang_locale'?'':$enc);
  229:     } else {
  230: 	return undef;
  231:     }
  232: }
  233: 
  234: # ============================================================== Translate hash
  235: 
  236: sub texthash {
  237:     my %hash=@_;
  238:     foreach (keys %hash) {
  239: 	$hash{$_}=&mt($hash{$_});
  240:     }
  241:     return %hash;
  242: }
  243: 
  244: # ========= Get a handle (do not invoke in vain, leave this to access handlers)
  245: 
  246: sub get_language_handle {
  247:     my $r=shift;
  248:     if ($r) {
  249: 	my $headers=$r->headers_in;
  250: 	$ENV{'HTTP_ACCEPT_LANGUAGE'}=$headers->{'Accept-language'};
  251:     }
  252:     my @languages=&Apache::loncommon::preferred_languages;
  253:     $ENV{'HTTP_ACCEPT_LANGUAGE'}='';
  254:     $lh=Apache::localize->get_handle(@languages);
  255:     if ($r && &Apache::lonnet::mod_perl_version == 1) {
  256: 	$r->content_languages([&current_language()]);
  257:     }
  258: ###    setlocale(LC_ALL,&current_locale);
  259: }
  260: 
  261: # ========================================================== Localize localtime
  262: sub gettimezone {
  263:     return ' ('.$Apache::lonnet::env{'server.timezone'}.')';
  264: }
  265: 
  266: sub locallocaltime {
  267:     my $thistime=shift;
  268:     if ((&current_language=~/^en/) || (!$lh)) {
  269: 	return ''.localtime($thistime).&gettimezone();
  270:     } else {
  271: 	my $format=$lh->maketext('date_locale');
  272: 	if ($format eq 'date_locale') {
  273: 	    return ''.localtime($thistime);
  274: 	}
  275: 	my ($seconds,$minutes,$twentyfour,$day,$mon,$year,$wday,$yday,$isdst)=
  276: 	    localtime($thistime);
  277: 	my $month=(split(/\,/,$lh->maketext('date_months')))[$mon];
  278: 	my $weekday=(split(/\,/,$lh->maketext('date_days')))[$wday];
  279: 	if ($seconds<10) {
  280: 	    $seconds='0'.$seconds;
  281: 	}
  282: 	if ($minutes<10) {
  283: 	    $minutes='0'.$minutes;
  284: 	}
  285: 	$year+=1900;
  286: 	my $twelve=$twentyfour;
  287: 	my $ampm;
  288: 	if ($twelve>12) {
  289: 	    $twelve-=12;
  290: 	    $ampm=$lh->maketext('date_pm');
  291: 	} else {
  292: 	    $ampm=$lh->maketext('date_am');
  293: 	}
  294: 	foreach 
  295: 	('seconds','minutes','twentyfour','twelve','day','year',
  296: 	 'month','weekday','ampm') {
  297: 	    $format=~s/\$$_/eval('$'.$_)/gse;
  298: 	}
  299: 	return $format.&gettimezone();
  300:     }
  301: }
  302: 
  303: # ==================== Normalize string (reduce fragility in the lexicon files)
  304: 
  305: # This normalizes a string to reduce fragility in the lexicon files of
  306: # huge messages (such as are used by the helper), and allow useful
  307: # formatting: reduce all consecutive whitespace to a single space,
  308: # and remove all HTML
  309: sub normalize_string {
  310:     my $s = shift;
  311:     $s =~ s/\s+/ /g;
  312:     $s =~ s/<[^>]+>//g;
  313:     # Pop off beginning or ending spaces, which aren't good
  314:     $s =~ s/^\s+//;
  315:     $s =~ s/\s+$//;
  316:     return $s;
  317: }
  318: 
  319: # alias for normalize_string; recommend using it only in the lexicon
  320: sub ns {
  321:     return normalize_string(@_);
  322: }
  323: 
  324: # mtn: call the mt function and the normalization function easily.
  325: # Returns original non-normalized string if there was no translation
  326: sub mtn (@) {
  327:     my @args = @_; # don't want to modify caller's string; if we
  328: 		   # didn't care about that we could set $_[0]
  329: 		   # directly
  330:     $args[0] = normalize_string($args[0]);
  331:     my $translation = &mt(@args);
  332:     if ($translation ne $args[0]) {
  333: 	return $translation;
  334:     } else {
  335: 	return $_[0];
  336:     }
  337: }
  338: 
  339: # ---------------------------------------------------- Replace MT{...} in files
  340: 
  341: sub transstatic {
  342:     my $strptr=shift;
  343:     $$strptr=~s/MT\{([^\}]*)\}/&mt($1)/gse;
  344: }
  345: 
  346: # ----------------------------------------------- Handler Routine /adm/localize
  347: sub handler {
  348:     my $r=shift;
  349:     &Apache::lonlocal::get_language_handle($r);
  350:     &Apache::loncommon::content_type($r,'text/html');
  351:     $r->send_http_header;
  352:     return OK if $r->header_only;
  353: 
  354:     my $uri=$r->uri;
  355:     $uri=~s/^\/adm\/localize//;
  356:     my $fn=$Apache::lonnet::perlvar{'lonDocRoot'}.$uri;
  357: 
  358:     my $file=&Apache::lonnet::getfile($fn);
  359:     &transstatic(\$file);
  360:     $r->print($file);
  361:     return OK;
  362: }
  363: 
  364: 1;
  365: 
  366: __END__

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>