summaryrefslogtreecommitdiff
path: root/lib/JWebmail/Plugin/I18N2.pm
blob: 5084c97e9cdd3bb87a6e9bad6c18473d7c8fa91d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package JWebmail::Plugin::I18N2;

use Mojo::Base 'Mojolicious::Plugin';

use Mojolicious::Controller;
use Mojo::File;
use Mojo::Util 'monkey_patch';

use Config::Tiny;


package JWebmail::Plugin::I18N2::Match {
    use Mojo::Base 'Mojolicious::Routes::Match';

    has '_i18n2_stash';

    sub path_for {
        my $self = shift;
        if (my $lang = $self->_i18n2_stash->{lang}) {
            if (ref $_[0] eq 'HASH') {
                $_[0]->{lang} ||= $lang;
            }
            elsif (ref $_[1] eq 'HASH') {
                $_[1]->{lang} ||= $lang;
            }
            else {
                my ($dom, %args) = @_%2 == 0 ? (undef, @_) : @_;
                $args{lang} ||= $lang;
                @_ = ($dom, %args);
                shift @_ unless defined $_[0];
            }
        }
        $self->next::method(@_)
    }
}


has '_language_loaded' => sub { {} };


sub register {
    my ($self, $app, $conf) = @_;
    $conf //= {};

    my $i18n_log = $app->log->context('[' . __PACKAGE__ . ']');

    # config
    # 1. what languages
    # 2. where are the files
    # 3. fallback language
    #
    # look for languages automatically
    my $defaultLang = $conf->{default_language} || 'en';
    my $fileLocation = $conf->{directory} && Mojo::File->new($conf->{directory})->is_abs
                       ? $conf->{directory}
                       : $app->home->child($conf->{directory} || 'lang');
    my @languages = keys %{$conf->{languages} // {}};

    unless (@languages) {
        @languages = map { $_ =~ s|^.*/(..)\.lang$|$1|r } glob("$fileLocation/*.lang");
    }

    $app->defaults(languages => [@languages]);

    # load languages
    my $TXT;
    for my $l (@languages) {
        $TXT->{$l} = _loadi18n($fileLocation, $l, $i18n_log);
    }

    {
        local $" = ',';
        $i18n_log->debug("loaded languages (@languages)");
    }

    $self->_language_loaded( { map { $_ => 1 } @languages } );

    # add translator as helper
    my $i18n = sub {
        my ($lang, $word) = @_;
        $TXT->{$lang}{$word} || scalar(
            local $" = ' ',
            $lang && $word ? $app->log->debug('[' . __PACKAGE__ . "] missing translation for $lang:$word @{[ caller(2) ]}[0..2]") : (),
            '',
        )
    };
    $app->helper( l => sub { my $c = shift; $i18n->($c->stash->{lang}, shift) } );

    # modify incoming url
    $app->hook(before_dispatch => sub {
        my $c = shift;
        unshift @{ $c->req->url->path->parts }, ''
            unless $self->_language_loaded->{$c->req->url->path->parts->[0] || ''};
    });

    # modify generated url
    $app->hook(before_dispatch => sub {
        my $c = shift;
        $c->match(JWebmail::Plugin::I18N2::Match->new(
            root         => $c->app->routes,
            _i18n2_stash => $c->stash,
        ));
    });

    return $app->routes->any('/:lang' => {lang => $defaultLang});
}


sub _loadi18n {

    my $langsubdir = shift;
    my $lang = shift;
    my $log = shift;

    my $langFile = "$langsubdir/$lang.lang";
    my $TXT;

    if ( -f $langFile ) {
        $TXT = Config::Tiny->read($langFile, 'utf8')->{'_'};
        if ($@ || !defined $TXT) {
            $log->error("error reading file $langFile: $@");
        }
    }
    else {
        $log->warn("language file $langFile does not exist!");
    }
    return $TXT;
}


1

__END__

=encoding utf8 

=head1 NAME

JWebmail::Plugin::I18N2 - Custom Made I18N Support an alternative to JWebmail::Plugin::I18N

=head1 SYNOPSIS

  $app->plugin('I18N2', {
    languages => [qw(en de es)],
    default_language => 'en',
    directory => '/path/to/language/files/',
  })

  # in your controller
  $c->l('hello')

  # in your templates
  <%= l 'hello' %>

  @@ de.lang
  login = anmelden
  userid = nuzerkennung
  passwd = passwort
  failed = fehlgeschlagen
  about = über

  example.com/de/myroute # $c->stash('lang') eq 'de'
  example.com/myroute    # $c->stash('lang') eq $defaultLanguage

  # on example.com/de/myroute
  url_for('my_other_route') #=> example.com/de/my_other_route

  url_for('my_other_route', lang => 'es') #=> example.com/es/my_other_route

=head1 DESCRIPTION

L<JWebmail::Plugin::I18N2> provides I18N support.

The language will be taken from the first path segment of the url.
Be carefult with colliding routes.

Mojolicious::Controller::url_for is patched so that the current language will be kept for
router named urls.

=head1 OPTIONS

=head2 default_language

The default language when no other information is provided.

=head2 directory

Directory to look for language files.

=head2 languages

List of allowed languages.
Files of the pattern "$lang.lang" will be looked for.

=head1 HELPERS

=head2 l

This is used for your translations.

  $c->l('hello')
  $app->helper('hello')->()

=cut