Template.pm 18.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
# -*- indent-tabs-mode: nil; -*-
# vim:ft=perl:et:sw=4
# $Id$

# Sympa - SYsteme de Multi-Postage Automatique
#
# Copyright (c) 1997, 1998, 1999 Institut Pasteur & Christophe Wolfhugel
# Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
# 2006, 2007, 2008, 2009, 2010, 2011 Comite Reseau des Universites
10
# Copyright (c) 2011, 2012, 2013, 2014, 2015, 2016, 2017 GIP RENATER
11
12
# Copyright 2018, 2020 The Sympa Community. See the AUTHORS.md
# file at the top-level directory of this distribution and at
13
# <https://github.com/sympa-community/sympa.git>.
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

package Sympa::Message::Template;

use strict;
use warnings;
use DateTime;
use Encode qw();
use MIME::EncWords;

36
use Sympa;
37
38
39
40
41
42
43
44
45
use Conf;
use Sympa::Constants;
use Sympa::Language;
use Sympa::Log;
use Sympa::Spool;
use Sympa::Template;
use Sympa::Tools::Data;
use Sympa::Tools::Password;
use Sympa::Tools::SMIME;
46
use Sympa::Tools::Text;
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use Sympa::User;

use base qw(Sympa::Message);

my $language = Sympa::Language->instance;
my $log      = Sympa::Log->instance;

# Old names: (part of) mail::mail_file(), mail::parse_tt2_messageasstring(),
# List::send_file(), List::send_global_file().
sub new {
    my $class   = shift;
    my %options = @_;

    my $that    = $options{context};
    my $tpl     = $options{template};
    my $who     = $options{rcpt};
    my $context = $options{data} || {};

    die 'Parameter $tpl is not defined'
        unless defined $tpl and length $tpl;

68
    my ($list, $family, $robot_id, $domain);
69
70
71
    if (ref $that eq 'Sympa::List') {
        $robot_id = $that->{'domain'};
        $list     = $that;
72
        $domain   = $that->{'domain'};
73
    } elsif (ref $that eq 'Sympa::Family') {
74
        $robot_id = $that->{'domain'};
75
        $family   = $that;
76
        $domain   = $that->{'domain'};
77
78
    } elsif ($that and $that ne '*') {
        $robot_id = $that;
Luc Didry's avatar
Luc Didry committed
79
        $domain = Conf::get_robot_conf($that, 'domain');
80
81
    } else {
        $robot_id = '*';
82
        $domain   = $Conf::Conf{'domain'};
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
    }

    my $data = Sympa::Tools::Data::dup_var($context);

    ## Any recipients
    if (not $who or (ref $who and !@$who)) {
        $log->syslog('err', 'No recipient for sending %s', $tpl);
        return undef;
    }

    ## Unless multiple recipients
    unless (ref $who) {
        unless ($data->{'user'}) {
            $data->{'user'} = Sympa::User->new($who);
        }

        if ($list) {
            # FIXME: Don't overwrite date & update_date.  Format datetime on
            # the template.
            my $subscriber =
                Sympa::Tools::Data::dup_var($list->get_list_member($who));
            if ($subscriber) {
                $data->{'subscriber'}{'date'} =
                    $language->gettext_strftime("%d %b %Y",
                    localtime($subscriber->{'date'}));
                $data->{'subscriber'}{'update_date'} =
                    $language->gettext_strftime("%d %b %Y",
                    localtime($subscriber->{'update_date'}));
                if ($subscriber->{'bounce'}) {
                    $subscriber->{'bounce'} =~
                        /^(\d+)\s+(\d+)\s+(\d+)(\s+(.*))?$/;

                    $data->{'subscriber'}{'first_bounce'} =
                        $language->gettext_strftime("%d %b %Y", localtime $1);
                }
            }
        }

        unless ($data->{'user'}{'password'}) {
            $data->{'user'}{'password'} =
                Sympa::Tools::Password::tmp_passwd($who);
        }

    }

    # Lang
    $language->push_lang(
        $data->{'lang'},
        $data->{'user'}{'lang'},
        ($list ? $list->{'admin'}{'lang'} : undef),
        Conf::get_robot_conf($robot_id, 'lang'), 'en'
    );
    $data->{'lang'} = $language->get_lang;
    $language->pop_lang;

    if ($list) {
        # Trying to use custom_vars
        if (defined $list->{'admin'}{'custom_vars'}) {
            $data->{'custom_vars'} = {};
            foreach my $var (@{$list->{'admin'}{'custom_vars'}}) {
                $data->{'custom_vars'}{$var->{'name'}} = $var->{'value'};
            }
        }
    }

    foreach my $p (
Luc Didry's avatar
Luc Didry committed
149
150
151
        'email', 'gecos', 'listmaster', 'wwsympa_url',
        'title', 'listmaster_email'
    ) {
152
153
        $data->{'conf'}{$p} = Conf::get_robot_conf($robot_id, $p);
    }
154
155
156
157
    $data->{'domain'} = $domain;
    $data->{'conf'}{'version'} = Sympa::Constants::VERSION();
    $data->{'sender'} ||= $who;

158
    # Compat.: Deprecated attributes of Robot.
159
    $data->{'conf'}{'sympa'} = Sympa::get_address($robot_id);
160
    $data->{'conf'}{'request'} = Sympa::get_address($robot_id, 'owner');
161
162
163
164
    # No longer used.
    $data->{'robot_domain'} = $domain;
    # Compat. < 6.2.32
    $data->{'conf'}{'host'} = $domain;
165
166
167
168
169
170
171
172
173

    if ($list) {
        $data->{'list'}{'lang'}    = $list->{'admin'}{'lang'};
        $data->{'list'}{'name'}    = $list->{'name'};
        $data->{'list'}{'subject'} = $list->{'admin'}{'subject'};
        $data->{'list'}{'owner'}   = [$list->get_admins('owner')];
        $data->{'list'}{'dir'} = $list->{'dir'};    #FIXME: Required?
        $data->{'list'}{'family'} = {name => $list->get_family->{'name'}}
            if $list->get_family;
174
175
176
        # Compat. < 6.2.32
        $data->{'list'}{'domain'} = $list->{'domain'};
        $data->{'list'}{'host'}   = $list->{'domain'};
177
    } elsif ($family) {
IKEDA Soji's avatar
IKEDA Soji committed
178
        $data->{family} = {name => $family->{'name'},};
179
180
181
182
183
184
185
186
187
188
189
    }

    # Sign mode
    my $smime_sign = Sympa::Tools::SMIME::find_keys($that, 'sign');

    if ($list) {
        # if the list have it's private_key and cert sign the message
        # . used only for the welcome message, could be useful in other case?
        # . a list should have several certificates and use if possible a
        #   certificate issued by the same CA as the recipient CA if it exists
        if ($smime_sign) {
190
            $data->{'fromlist'} = Sympa::get_address($list);
191
            $data->{'replyto'} = Sympa::get_address($list, 'owner');
192
        } else {
193
            $data->{'fromlist'} = Sympa::get_address($list, 'owner');
194
195
        }
    }
196
    $data->{'boundary'} = '----------=_' . Sympa::unique_message_id($robot_id)
197
198
        unless $data->{'boundary'};

199
200
    my $self = $class->_new_from_template($that, $tpl . '.tt2',
        $who, $data, %options);
201
202
203
204
205
206
    return undef unless $self;

    # Shelve S/MIME signing.
    $self->{shelved}{smime_sign} = 1
        if $smime_sign;
    # Shelve DKIM signing.
IKEDA Soji's avatar
IKEDA Soji committed
207
    if (Conf::get_robot_conf($robot_id, 'dkim_feature') eq 'on') {
208
209
210
211
212
213
214
215
216
        my $dkim_add_signature_to =
            Conf::get_robot_conf($robot_id, 'dkim_add_signature_to');
        if ($list and $dkim_add_signature_to =~ /list/
            or not $list and $dkim_add_signature_to =~ /robot/) {
            $self->{shelved}{dkim_sign} = 1;
        }
    }

    # Set default envelope sender.
217
218
219
220
    if (exists $options{envelope_sender}) {
        $self->{envelope_sender} = $options{envelope_sender};
    } elsif ($list) {
        $self->{envelope_sender} = Sympa::get_address($list, 'return_path');
221
    } else {
222
        $self->{envelope_sender} = Sympa::get_address($robot_id, 'owner');
223
224
225
226
227
    }

    # Set default delivery date.
    $self->{date} = (exists $options{date}) ? $options{date} : time;

228
229
230
231
232
233
234
235
    # Set priority if specified.
    $self->{priority} = $options{priority}
        if exists $options{priority};

    # Shelve tracking if speficied.
    $self->{shelved}{tracking} = $options{tracking}
        if exists $options{tracking};

236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
    # Assign unique ID and log it.
    my $marshalled =
        Sympa::Spool::marshal_metadata($self, '%s@%s.%ld.%ld,%d',
        [qw(localpart domainpart date PID RAND)]);
    $self->{messagekey} = $marshalled;

    return $self;
}

#TODO: This would be merged in new() because used only by it.
sub _new_from_template {
    $log->syslog('debug2', '(%s, %s, %s, %s, %s)', @_);
    my $class    = shift;
    my $that     = shift || '*';
    my $filename = shift;
    my $rcpt     = shift;
    my $data     = shift;
253
    my %options  = @_;
254

255
    my ($list, $family, $robot_id);
256
257
258
    if (ref $that eq 'Sympa::List') {
        $list     = $that;
        $robot_id = $list->{'domain'};
259
260
    } elsif (ref $that eq 'Sympa::Family') {
        $family   = $that;
261
        $robot_id = $family->{'domain'};
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    } elsif ($that and $that ne '*') {
        $robot_id = $that;
    } else {
        $robot_id = '*';
    }

    my $message_as_string;
    my %header_ok;    # hash containing no missing headers
    my $existing_headers = 0;    # the message already contains headers

    ## We may receive a list of recipients
    die sprintf 'Wrong type of reference for $rcpt: %s', ref $rcpt
        if ref $rcpt and ref $rcpt ne 'ARRAY';

    ## Charset for encoding
277
    $data->{'charset'} ||= Conf::lang2charset($data->{'lang'});
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319

    # Template file parsing
    # If context is List, add list directory and list archives to get the
    # 'info' file and last message.
    my $template = Sympa::Template->new(
        $that,
        subdir => 'mail_tt2',
        lang   => $data->{'lang'},
        include_path =>
            ($list ? [$list->{'dir'}, $list->{'dir'} . '/archives'] : [])
    );
    unless ($template->parse($data, $filename, \$message_as_string)) {
        $log->syslog(
            'err',     'Can\'t parse template %s: %s',
            $filename, $template->{last_error}
        );
        return undef;
    }

    # Does the message include headers ?
    if ($data->{'headers'}) {
        foreach my $field (keys %{$data->{'headers'}}) {
            $field =~ tr/A-Z/a-z/;
            $header_ok{$field} = 1;
        }
    }

    foreach my $line (split /\n/, $message_as_string) {
        last if ($line =~ /^\s*$/);
        if ($line =~ /^[\w-]+:\s*/) {
            ## A header field
            $existing_headers = 1;
        } elsif ($existing_headers and $line =~ /^\s/) {
            ## Following of a header field
            next;
        } else {
            last;
        }

        foreach my $header (
            qw(message-id date to from subject reply-to
            mime-version content-type content-transfer-encoding)
Luc Didry's avatar
Luc Didry committed
320
        ) {
321
322
323
324
325
326
327
328
329
330
331
332
            if ($line =~ /^$header\s*:/i) {
                $header_ok{$header} = 1;
                last;
            }
        }
    }

    ## ADD MISSING HEADERS
    my $headers = "";

    unless ($header_ok{'message-id'}) {
        $headers .=
333
            sprintf("Message-Id: %s\n", Sympa::unique_message_id($robot_id));
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
    }

    unless ($header_ok{'date'}) {
        # Format current time.
        # If setting local timezone fails, fallback to UTC.
        my $date =
            (eval { DateTime->now(time_zone => 'local') } || DateTime->now)
            ->strftime('%a, %{day} %b %Y %H:%M:%S %z');
        $headers .= sprintf "Date: %s\n", $date;
    }

    unless ($header_ok{'to'}) {
        my $to;
        # Currently, bare e-mail address is assumed.  Complex ones such as
        # "phrase" <email> won't be allowed.
        if (ref($rcpt)) {
            if ($data->{'to'}) {
                $to = $data->{'to'};
            } else {
                $to = join(",\n   ", @{$rcpt});
            }
        } else {
            $to = $rcpt;
        }
        $headers .= "To: $to\n";
    }
    unless ($header_ok{'from'}) {
        unless (defined $data->{'from'}) {
362
363
364
365
366
367
368
369
            # DSN should not have command address <sympa> to prevent looping
            # by dumb auto-responder (including Sympa command robot itself).
            my $sympa =
                (       exists $options{envelope_sender}
                    and defined $options{envelope_sender}
                    and $options{envelope_sender} eq '<>')
                ? Sympa::get_address($robot_id, 'owner')    # sympa-request
                : Sympa::get_address($robot_id);
370
            $headers .= sprintf "From: %s\n",
371
                Sympa::Tools::Text::addrencode($sympa,
372
                Conf::get_robot_conf($robot_id, 'gecos'),
373
                $data->{'charset'});
374
375
376
377
        } elsif ($data->{'from'} eq 'sympa'
            or $data->{'from'} eq $data->{'conf'}{'sympa'}) {
            #XXX NOTREACHED: $data->{'from'} was obsoleted.
            $headers .= 'From: '
378
                . Sympa::Tools::Text::addrencode(
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
                $data->{'conf'}{'sympa'},
                $data->{'conf'}{'gecos'},
                $data->{'charset'}
                ) . "\n";
        } else {
            #XXX NOTREACHED: $data->{'from'} was obsoleted.
            $headers .= "From: "
                . MIME::EncWords::encode_mimewords(
                Encode::decode('utf8', $data->{'from'}),
                'Encoding' => 'A',
                'Charset'  => $data->{'charset'},
                'Field'    => 'From'
                ) . "\n";
        }
    }
    unless ($header_ok{'subject'}) {
        $headers .= "Subject: "
            . MIME::EncWords::encode_mimewords(
            Encode::decode('utf8', $data->{'subject'}),
            'Encoding' => 'A',
            'Charset'  => $data->{'charset'},
            'Field'    => 'Subject'
            ) . "\n";
    }
    unless ($header_ok{'reply-to'}) {
        $headers .= "Reply-to: "
            . MIME::EncWords::encode_mimewords(
            Encode::decode('utf8', $data->{'replyto'}),
            'Encoding' => 'A',
            'Charset'  => $data->{'charset'},
            'Field'    => 'Reply-to'
            )
            . "\n"
            if ($data->{'replyto'});
    }
    if ($data->{'headers'}) {
        foreach my $field (keys %{$data->{'headers'}}) {
            $headers .=
                $field . ': '
                . MIME::EncWords::encode_mimewords(
                Encode::decode('utf8', $data->{'headers'}{$field}),
                'Encoding' => 'A',
                'Charset'  => $data->{'charset'},
                'Field'    => $field
                ) . "\n";
        }
    }
    unless ($header_ok{'mime-version'}) {
        $headers .= "MIME-Version: 1.0\n";
    }
    unless ($header_ok{'content-type'}) {
        $headers .=
            "Content-Type: text/plain; charset=" . $data->{'charset'} . "\n";
    }
    unless ($header_ok{'content-transfer-encoding'}) {
        $headers .= "Content-Transfer-Encoding: 8bit\n";
    }

    # Determine what value the Auto-Submitted header field should take.
    # See RFC 3834.  The header field can have one of the following keywords:
    # "auto-generated", "auto-replied".
    # The header should not be set when WWSympa sends a command to sympa.pl
    # through its spool.
    # n.b. The keyword "auto-forwarded" was abandoned.
    unless ($data->{'not_auto_submitted'} || $header_ok{'auto_submitted'}) {
        ## Default value is 'auto-generated'
        my $header_value = $data->{'auto_submitted'} || 'auto-generated';
        $headers .= "Auto-Submitted: $header_value\n";
    }

    unless ($existing_headers) {
        $headers .= "\n";
    }

453
    # All these data provide mail attachments in service messages.
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
    my @msgs = ();
    if (ref($data->{'msg_list'}) eq 'ARRAY') {
        @msgs =
            map { $_->{'msg'} || $_->{'full_msg'} } @{$data->{'msg_list'}};
    } elsif ($data->{'spool'}) {
        @msgs = @{$data->{'spool'}};
    } elsif ($data->{'msg'}) {
        push @msgs, $data->{'msg'};
    } elsif ($data->{'msg_path'} and open IN, '<' . $data->{'msg_path'}) {
        push @msgs, join('', <IN>);
        close IN;
    } elsif ($data->{'file'} and open IN, '<' . $data->{'file'}) {
        push @msgs, join('', <IN>);
        close IN;
    }

    my $self =
        $class->SUPER::new($headers . $message_as_string, context => $that);
    return undef unless $self;

    unless ($self->reformat_utf8_message(\@msgs, $data->{'charset'})) {
        $log->syslog('err', 'Failed to reformat message');
    }

    return $self;
}

481
482
483
484
485
486
487
488
489
490
491
492
493
# Methods compatible to Sympa::Spool.

sub next {
    my $self = shift;

    return if delete $self->{_done_next};
    $self->{_done_next} = 1;
    return ($self, 1);
}

use constant quarantine => 1;
use constant remove     => 1;

494
495
496
497
498
499
500
501
502
1;
__END__

=encoding utf-8

=head1 NAME

Sympa::Message::Template - Mail message generated from template

503
=head1 SYNOPSIS
504
505
506
507
508
509
510
511
512
513
514
515

  use Sympa::Message::Template;
  my $message = Sympa::Message::Template->new(
      context => $list, template => "name", rcpt => [$email], data => {});

=head1 DESCRIPTION

=head2 Methods

=over

=item new ( context =E<gt> $that, template =E<gt> $filename,
516
rcpt =E<gt> $rcpt, [ data =E<gt> $data ], [ options... ] )
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536

I<Constructor>.
Creates L<Sympa::Message> object from template.

Parameters:

=over

=item context =E<gt> $that

Content: Sympa::List, robot or '*'.

=item template =E<gt> $filename

Template filename (without extension).

=item rcpt =E<gt> $rcpt

Scalar or arrayref: SMTP "RCPT TO:" field.

537
If it is a scalar, tries to retrieve information of the user
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
(See also L<Sympa::User>.

=item data =E<gt> $data

Hashref used to parse template, with keys:

=over

=item return_path

SMTP "MAIL FROM:" field if sent by SMTP (see L<Sympa::Mailer>),
"Return-Path:" field if sent by spool.

Note: This parameter was OBSOLETED.  Currently, {envelope_sender} attribute of
object is taken from the context.

=item to

"To:" header field

=item lang

Language tag used for parsing template.
See also L<Sympa::Language>.

=item from

"From:" field if not a full msg

Note:
This parameter was OBSOLETED.
The "From:" field will be filled in by "sympa" address if it is not found.

=item subject

"Subject:" field if not a full msg

=item replyto

"Reply-To:" field if not a full msg

=item body

Body message if $filename is C<''>.

Note: This feature has been deprecated.

=item headers

Additional headers, hashref with keys are field names.

=back

=back

Below are optional parameters.

=over

=item date =E<gt> $time

Delivery time of message.
By default current time will be used.

602
603
604
605
606
607
608
609
610
611
612
613
614
=item envelope_sender =E<gt> $email

Forces setting envelope sender.
C<'E<lt>E<gt>'> may be used for null envelope sender.

=item priority =E<gt> $priority

Forces setting priority if specified.

=item tracking =E<gt> $feature

Forces tracking if specified.

615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
=back

Returns:

New L<Sympa::Message> instance, or C<undef> if something went wrong.

=back

=head1 SEE ALSO

L<Sympa::Message>, L<Sympa::Template>.

=head1 HISTORY

L<Sympa::Message/"new_from_template"> appeared on Sympa 6.2.

It was renamed to L<Sympa::Message::Template/"new"> on Sympa 6.2.13.

=cut