Merge branch 'master' of git.freeside.biz:/home/git/freeside
[freeside.git] / rt / lib / RT / I18N.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2014 Best Practical Solutions, LLC
6 #                                          <sales@bestpractical.com>
7 #
8 # (Except where explicitly superseded by other copyright notices)
9 #
10 #
11 # LICENSE:
12 #
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
16 # from www.gnu.org.
17 #
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 # General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
28 #
29 #
30 # CONTRIBUTION SUBMISSION POLICY:
31 #
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
37 #
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
46 #
47 # END BPS TAGGED BLOCK }}}
48
49 =head1 NAME
50
51 RT::I18N - a base class for localization of RT
52
53 =cut
54
55 package RT::I18N;
56
57 use strict;
58 use warnings;
59
60
61 use Locale::Maketext 1.04;
62 use Locale::Maketext::Lexicon 0.25;
63 use base 'Locale::Maketext::Fuzzy';
64
65 use MIME::Entity;
66 use MIME::Head;
67 use File::Glob;
68
69 # I decree that this project's first language is English.
70
71 our %Lexicon = (
72    'TEST_STRING' => 'Concrete Mixer',
73
74     '__Content-Type' => 'text/plain; charset=utf-8',
75
76   '_AUTO' => 1,
77   # That means that lookup failures can't happen -- if we get as far
78   #  as looking for something in this lexicon, and we don't find it,
79   #  then automagically set $Lexicon{$key} = $key, before possibly
80   #  compiling it.
81   
82   # The exception is keys that start with "_" -- they aren't auto-makeable.
83
84 );
85 # End of lexicon.
86
87 =head2 Init
88
89 Initializes the lexicons used for localization.
90
91
92 =cut
93
94 sub Init {
95
96     my @lang = RT->Config->Get('LexiconLanguages');
97     @lang = ('*') unless @lang;
98
99     # load default functions
100     require substr(__FILE__, 0, -3) . '/i_default.pm';
101
102     # Load language-specific functions
103     foreach my $file ( File::Glob::bsd_glob(substr(__FILE__, 0, -3) . "/*.pm") ) {
104         unless ( $file =~ /^([-\w\s\.\/\\~:]+)$/ ) {
105             warn("$file is tainted. not loading");
106             next;
107         }
108         $file = $1;
109
110         my ($lang) = ($file =~ /([^\\\/]+?)\.pm$/);
111         next unless grep $_ eq '*' || $_ eq $lang, @lang;
112         require $file;
113     }
114
115     my %import;
116     foreach my $l ( @lang ) {
117         $import{$l} = [
118             Gettext => $RT::LexiconPath."/$l.po",
119         ];
120         push @{ $import{$l} }, map {(Gettext => "$_/$l.po")} RT->PluginDirs('po');
121         push @{ $import{$l} }, (Gettext => $RT::LocalLexiconPath."/*/$l.po",
122                                 Gettext => $RT::LocalLexiconPath."/$l.po");
123     }
124
125     # Acquire all .po files and iterate them into lexicons
126     Locale::Maketext::Lexicon->import({ _decode => 1, %import });
127
128     return 1;
129 }
130
131 sub LoadLexicons {
132
133     no strict 'refs';
134     foreach my $k (keys %{RT::I18N::} ) {
135         next if $k eq 'main::';
136         next unless index($k, '::', -2) >= 0;
137         next unless exists ${ 'RT::I18N::'. $k }{'Lexicon'};
138
139         my $lex = *{ ${'RT::I18N::'. $k }{'Lexicon'} }{HASH};
140         # run fetch to force load
141         my $tmp = $lex->{'foo'};
142         # XXX: untie may fail with "untie attempted
143         # while 1 inner references still exist"
144         # TODO: untie that has to lower fetch impact
145         # untie %$lex if tied %$lex;
146     }
147 }
148
149 =head2 encoding
150
151 Returns the encoding of the current lexicon, as yanked out of __ContentType's "charset" field.
152 If it can't find anything, it returns 'ISO-8859-1'
153
154
155
156 =cut
157
158
159 sub encoding { 'utf-8' }
160
161
162 =head2 SetMIMEEntityToUTF8 $entity
163
164 An utility function which will try to convert entity body into utf8.
165 It's now a wrap-up of SetMIMEEntityToEncoding($entity, 'utf-8').
166
167 =cut
168
169 sub SetMIMEEntityToUTF8 {
170     RT::I18N::SetMIMEEntityToEncoding(shift, 'utf-8');
171 }
172
173
174
175 =head2 IsTextualContentType $type
176
177 An utility function that determines whether $type is I<textual>, meaning
178 that it can sensibly be converted to Unicode text.
179
180 Currently, it returns true iff $type matches this regular expression
181 (case-insensitively):
182
183     ^(?:text/(?:plain|html)|message/rfc822)\b
184
185
186 =cut
187
188 sub IsTextualContentType {
189     my $type = shift;
190     ($type =~ m{^(?:text/(?:plain|html)|message/rfc822)\b}i) ? 1 : 0;
191 }
192
193
194 =head2 SetMIMEEntityToEncoding $entity, $encoding
195
196 An utility function which will try to convert entity body into specified
197 charset encoding (encoded as octets, *not* unicode-strings).  It will
198 iterate all the entities in $entity, and try to convert each one into
199 specified charset if whose Content-Type is 'text/plain'.
200
201 This function doesn't return anything meaningful.
202
203 =cut
204
205 sub SetMIMEEntityToEncoding {
206     my ( $entity, $enc, $preserve_words ) = ( shift, shift, shift );
207
208     # do the same for parts first of all
209     SetMIMEEntityToEncoding( $_, $enc, $preserve_words ) foreach $entity->parts;
210
211     my $head = $entity->head;
212
213     my $charset = _FindOrGuessCharset($entity);
214     if ( $charset ) {
215         unless( Encode::find_encoding($charset) ) {
216             $RT::Logger->warning("Encoding '$charset' is not supported");
217             $charset = undef;
218         }
219     }
220     unless ( $charset ) {
221         $head->replace( "X-RT-Original-Content-Type" => $head->mime_attr('Content-Type') );
222         $head->mime_attr('Content-Type' => 'application/octet-stream');
223         return;
224     }
225
226     SetMIMEHeadToEncoding(
227         $head,
228         _FindOrGuessCharset($entity, 1) => $enc,
229         $preserve_words
230     );
231
232     # If this is a textual entity, we'd need to preserve its original encoding
233     $head->replace( "X-RT-Original-Encoding" => Encode::encode( "UTF-8", $charset ) )
234         if $head->mime_attr('content-type.charset') or IsTextualContentType($head->mime_type);
235
236     return unless IsTextualContentType($head->mime_type);
237
238     my $body = $entity->bodyhandle;
239
240     if ( $body && ($enc ne $charset || $enc =~ /^utf-?8(?:-strict)?$/i) ) {
241         my $string = $body->as_string or return;
242         RT::Util::assert_bytes($string);
243
244         $RT::Logger->debug( "Converting '$charset' to '$enc' for "
245               . $head->mime_type . " - "
246               . ( Encode::decode("UTF-8",$head->get('subject')) || 'Subjectless message' ) );
247
248         Encode::from_to( $string, $charset => $enc );
249
250         my $new_body = MIME::Body::InCore->new($string);
251
252         # set up the new entity
253         $head->mime_attr( "content-type" => 'text/plain' )
254           unless ( $head->mime_attr("content-type") );
255         $head->mime_attr( "content-type.charset" => $enc );
256         $entity->bodyhandle($new_body);
257     }
258 }
259
260 =head2 DecodeMIMEWordsToUTF8 $raw
261
262 An utility method which mimics MIME::Words::decode_mimewords, but only
263 limited functionality.  Despite its name, this function returns the
264 bytes of the string, in UTF-8.
265
266 =cut
267
268 sub DecodeMIMEWordsToUTF8 {
269     my $str = shift;
270     return DecodeMIMEWordsToEncoding($str, 'utf-8', @_);
271 }
272
273 sub DecodeMIMEWordsToEncoding {
274     my $str = shift;
275     my $to_charset = _CanonicalizeCharset(shift);
276     my $field = shift || '';
277
278     # handle filename*=ISO-8859-1''%74%E9%73%74%2E%74%78%74, parameter value
279     # continuations, and similar syntax from RFC 2231
280     if ($field =~ /^Content-(Type|Disposition)/i) {
281         # This concatenates continued parameters and normalizes encoded params
282         # to QB encoded-words which we handle below
283         $str = MIME::Field::ParamVal->parse($str)->stringify;
284     }
285
286     # Pre-parse by removing all whitespace between encoded words
287     my $encoded_word = qr/
288                  =\?            # =?
289                  ([^?]+?)       # charset
290                  (?:\*[^?]+)?   # optional '*language'
291                  \?             # ?
292                  ([QqBb])       # encoding
293                  \?             # ?
294                  ([^?]+)        # encoded string
295                  \?=            # ?=
296                  /x;
297     $str =~ s/($encoded_word)\s+(?=$encoded_word)/$1/g;
298
299     # Also merge quoted-printable sections together, in case multiple
300     # octets of a single encoded character were split between chunks.
301     # Though not valid according to RFC 2047, this has been seen in the
302     # wild.
303     1 while $str =~ s/(=\?[^?]+\?[Qq]\?)([^?]+)\?=\1([^?]+)\?=/$1$2$3?=/i;
304
305     # XXX TODO: use decode('MIME-Header', ...) and Encode::Alias to replace our
306     # custom MIME word decoding and charset canonicalization.  We can't do this
307     # until we parse before decode, instead of the other way around.
308     my @list = $str =~ m/(.*?)          # prefix
309                          $encoded_word
310                          ([^=]*)        # trailing
311                         /xgcs;
312
313     if ( @list ) {
314         # add everything that hasn't matched to the end of the latest
315         # string in array this happen when we have 'key="=?encoded?="; key="plain"'
316         $list[-1] .= substr($str, pos $str);
317
318         $str = "";
319         while (@list) {
320             my ($prefix, $charset, $encoding, $enc_str, $trailing) =
321                     splice @list, 0, 5;
322             $charset  = _CanonicalizeCharset($charset);
323             $encoding = lc $encoding;
324
325             $trailing =~ s/\s?\t?$//;               # Observed from Outlook Express
326
327             if ( $encoding eq 'q' ) {
328                 use MIME::QuotedPrint;
329                 $enc_str =~ tr/_/ /;            # Observed from Outlook Express
330                 $enc_str = decode_qp($enc_str);
331             } elsif ( $encoding eq 'b' ) {
332                 use MIME::Base64;
333                 $enc_str = decode_base64($enc_str);
334             } else {
335                 $RT::Logger->warning("Incorrect encoding '$encoding' in '$str', "
336                     ."only Q(uoted-printable) and B(ase64) are supported");
337             }
338
339             # now we have got a decoded subject, try to convert into the encoding
340             if ( $charset ne $to_charset || $charset =~ /^utf-?8(?:-strict)?$/i ) {
341                 if ( Encode::find_encoding($charset) ) {
342                     Encode::from_to( $enc_str, $charset, $to_charset );
343                 } else {
344                     $RT::Logger->warning("Charset '$charset' is not supported");
345                     $enc_str =~ s/[^[:print:]]/\357\277\275/g;
346                     Encode::from_to( $enc_str, 'UTF-8', $to_charset )
347                         unless $to_charset eq 'utf-8';
348                 }
349             }
350
351             # XXX TODO: RT doesn't currently do the right thing with mime-encoded headers
352             # We _should_ be preserving them encoded until after parsing is completed and
353             # THEN undo the mime-encoding.
354             #
355             # This routine should be translating the existing mimeencoding to utf8 but leaving
356             # things encoded.
357             #
358             # It's legal for headers to contain mime-encoded commas and semicolons which
359             # should not be treated as address separators. (Encoding == quoting here)
360             #
361             # until this is fixed, we must escape any string containing a comma or semicolon
362             # this is only a bandaid
363
364             # Some _other_ MUAs encode quotes _already_, and double quotes
365             # confuse us a lot, so only quote it if it isn't quoted
366             # already.
367             $enc_str = qq{"$enc_str"}
368                 if $enc_str =~ /[,;]/
369                 and $enc_str !~ /^".*"$/
370                 and $prefix !~ /"$/ and $trailing !~ /^"/
371                 and (!$field || $field =~ /^(?:To$|From$|B?Cc$|Content-)/i);
372
373             $str .= $prefix . $enc_str . $trailing;
374         }
375     }
376
377     # We might have \n without trailing whitespace, which will result in
378     # invalid headers.
379     $str =~ s/\n//g;
380
381     return ($str)
382 }
383
384
385
386 =head2 _FindOrGuessCharset MIME::Entity, $head_only
387
388 When handed a MIME::Entity will first attempt to read what charset the message is encoded in. Failing that, will use Encode::Guess to try to figure it out
389
390 If $head_only is true, only guesses charset for head parts.  This is because header's encoding (e.g. filename="...") may be different from that of body's.
391
392 =cut
393
394 sub _FindOrGuessCharset {
395     my $entity = shift;
396     my $head_only = shift;
397     my $head = $entity->head;
398
399     if ( my $charset = $head->mime_attr("content-type.charset") ) {
400         return _CanonicalizeCharset($charset);
401     }
402
403     if ( !$head_only and $head->mime_type =~ m{^text/} ) {
404         my $body = $entity->bodyhandle or return;
405         return _GuessCharset( $body->as_string );
406     }
407     else {
408
409         # potentially binary data -- don't guess the body
410         return _GuessCharset( $head->as_string );
411     }
412 }
413
414
415
416 =head2 _GuessCharset STRING
417
418 use Encode::Guess to try to figure it out the string's encoding.
419
420 =cut
421
422 use constant HAS_ENCODE_GUESS => do { local $@; eval { require Encode::Guess; 1 } };
423 use constant HAS_ENCODE_DETECT => do { local $@; eval { require Encode::Detect::Detector; 1 } };
424
425 sub _GuessCharset {
426     my $fallback = _CanonicalizeCharset('iso-8859-1');
427
428     # if $_[0] is null/empty, we don't guess its encoding
429     return $fallback
430         unless defined $_[0] && length $_[0];
431
432     my @encodings = RT->Config->Get('EmailInputEncodings');
433     unless ( @encodings ) {
434         $RT::Logger->warning("No EmailInputEncodings set, fallback to $fallback");
435         return $fallback;
436     }
437
438     if ( $encodings[0] eq '*' ) {
439         shift @encodings;
440         if ( HAS_ENCODE_DETECT ) {
441             my $charset = Encode::Detect::Detector::detect( $_[0] );
442             if ( $charset ) {
443                 $RT::Logger->debug("Encode::Detect::Detector guessed encoding: $charset");
444                 return _CanonicalizeCharset( Encode::resolve_alias( $charset ) );
445             }
446             else {
447                 $RT::Logger->debug("Encode::Detect::Detector failed to guess encoding");
448             }
449         }
450         else {
451             $RT::Logger->error(
452                 "You requested to guess encoding, but we couldn't"
453                 ." load Encode::Detect::Detector module"
454             );
455         }
456     }
457
458     unless ( @encodings ) {
459         $RT::Logger->warning("No EmailInputEncodings set except '*', fallback to $fallback");
460         return $fallback;
461     }
462
463     unless ( HAS_ENCODE_GUESS ) {
464         $RT::Logger->error("We couldn't load Encode::Guess module, fallback to $fallback");
465         return $fallback;
466     }
467
468     Encode::Guess->set_suspects( @encodings );
469     my $decoder = Encode::Guess->guess( $_[0] );
470     unless ( defined $decoder ) {
471         $RT::Logger->warning("Encode::Guess failed: decoder is undefined; fallback to $fallback");
472         return $fallback;
473     }
474
475     if ( ref $decoder ) {
476         my $charset = $decoder->name;
477         $RT::Logger->debug("Encode::Guess guessed encoding: $charset");
478         return _CanonicalizeCharset( $charset );
479     }
480     elsif ($decoder =~ /(\S+ or .+)/) {
481         my %matched = map { $_ => 1 } split(/ or /, $1);
482         return 'utf-8' if $matched{'utf8'}; # one and only normalization
483
484         foreach my $suspect (RT->Config->Get('EmailInputEncodings')) {
485             next unless $matched{$suspect};
486             $RT::Logger->debug("Encode::Guess ambiguous ($decoder); using $suspect");
487             return _CanonicalizeCharset( $suspect );
488         }
489     }
490     else {
491         $RT::Logger->warning("Encode::Guess failed: $decoder; fallback to $fallback");
492     }
493
494     return $fallback;
495 }
496
497 =head2 _CanonicalizeCharset NAME
498
499 canonicalize charset, return lowercase version.
500 special cases are: gb2312 => gbk, utf8 => utf-8
501
502 =cut
503
504 sub _CanonicalizeCharset {
505     my $charset = lc shift;
506     return $charset unless $charset;
507
508     # Canonicalize aliases if they're known
509     if (my $canonical = Encode::resolve_alias($charset)) {
510         $charset = $canonical;
511     }
512
513     if ( $charset eq 'utf8' || $charset eq 'utf-8-strict' ) {
514         return 'utf-8';
515     }
516     elsif ( $charset eq 'euc-cn' ) {
517         # gbk is superset of gb2312/euc-cn so it's safe
518         return 'gbk';
519         # XXX TODO: gb18030 is an even larger, more permissive superset of gbk,
520         # but needs Encode::HanExtra installed
521     }
522     else {
523         return $charset;
524     }
525 }
526
527
528 =head2 SetMIMEHeadToEncoding HEAD OLD_CHARSET NEW_CHARSET
529
530 Converts a MIME Head from one encoding to another. This totally violates the RFC.
531 We should never need this. But, Surprise!, MUAs are badly broken and do this kind of stuff
532 all the time
533
534
535 =cut
536
537 sub SetMIMEHeadToEncoding {
538     my ( $head, $charset, $enc, $preserve_words ) = ( shift, shift, shift, shift );
539
540     $charset = _CanonicalizeCharset($charset);
541     $enc     = _CanonicalizeCharset($enc);
542
543     return if $charset eq $enc and $preserve_words;
544
545     RT::Util::assert_bytes( $head->as_string );
546     foreach my $tag ( $head->tags ) {
547         next unless $tag; # seen in wild: headers with no name
548         my @values = $head->get_all($tag);
549         $head->delete($tag);
550         foreach my $value (@values) {
551             if ( $charset ne $enc || $enc =~ /^utf-?8(?:-strict)?$/i ) {
552                 Encode::from_to( $value, $charset => $enc );
553             }
554             $value = DecodeMIMEWordsToEncoding( $value, $enc, $tag )
555                 unless $preserve_words;
556
557             # We intentionally add a leading space when re-adding the
558             # header; Mail::Header strips it before storing, but it
559             # serves to prevent it from "helpfully" canonicalizing
560             # $head->add("Subject", "Subject: foo") into the same as
561             # $head->add("Subject", "foo");
562             $head->add( $tag, " " . $value );
563         }
564     }
565
566 }
567
568 RT::Base->_ImportOverlays();
569
570 1;  # End of module.
571