Sympa.pm 37.6 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 GIP RENATER
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
#
# 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/>.

## Note to developers:
## This corresponds to Sympa::ConfigurableObject (and Sympa::Site) package
## in trunk.

=encoding utf-8

=head1 NAME

Sympa - Future base class of Sympa functional objects

=head1 DESCRIPTION

This module aims to be the base class for functional objects of Sympa:
Site, Robot, Family and List.

=cut

package Sympa;

use strict;
use warnings;
#use Cwd qw();
use DateTime;
use Digest::MD5;
use English qw(-no_match_vars);
50
use Scalar::Util qw();
51
52
53
54
55

use Conf;
use Sympa::Constants;
use Sympa::Language;
use Sympa::Log;
56
use Sympa::Spindle::ProcessTemplate;
57
use Sympa::Ticket;
58
59
use tools;
use Sympa::Tools::Data;
60
use Sympa::Tools::Text;
61
62
63
64
65
66
67
68
69

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

=head2 Functions

=head3 Handling the Authentication Token

=over

70
71
=item compute_auth ( context =E<gt> $that, email =E<gt> $email,
action =E<gt> $cmd )
72
73
74
75
76
77
78

Genererate a MD5 checksum using private cookie and parameters.

Parameters:

=over

79
=item context =E<gt> $that
80
81
82

L<Sympa::List>, Robot or Site.

83
=item email =E<gt> $email
84
85
86

Recipient (the person who asked for the command).

87
=item action =E<gt> $cmd
88

89
TBD.
90
91
92
93
94
95
96
97
98
99
100
101
102
103

=back

Returns:

Authenticaton key.

=back

=cut

# Old name: List::compute_auth().
sub compute_auth {
    $log->syslog('debug3', '(%s, %s, %s)', @_);
104
105
106
107
108
    my %options = @_;

    my $that  = $options{context};
    my $email = $options{email};
    my $cmd   = $options{action};
109
110
    # Compat. <= 6.2.12.
    $cmd = 'remind' if $cmd eq 'global_remind';
111
112
113
114
115
116
117
118
119
120

    my ($list, $robot);
    if (ref $that eq 'Sympa::List') {
        $list = $that;
    } elsif ($that and $that ne '*') {
        $robot = $that;
    } else {
        $robot = '*';
    }

121
122
123
    $email = '' unless defined $email;
    $email =~ tr/A-Z/a-z/;
    $cmd   =~ tr/A-Z/a-z/;
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

    my ($cookie, $key, $listname);

    if ($list) {
        $listname = $list->{'name'};
        $cookie   = $list->{'admin'}{'cookie'}
            || Conf::get_robot_conf($robot, 'cookie');
    } else {
        $listname = '';
        $cookie = Conf::get_robot_conf($robot, 'cookie');
    }

    $key = substr(
        Digest::MD5::md5_hex(join('/', $cookie, $listname, $email, $cmd)),
        -8);

    return $key;
}

=over

145
146
=item request_auth ( context =E<gt> $that, sender =E<gt> $sender,
action =E<gt> $cmd, [ email =E<gt> $email ], [ other options... ] )
147
148
149
150
151
152
153
154

Sends an authentication request for a requested
command.

Parameters:

=over

155
=item context =E<gt> $that
156
157
158

L<Sympa::List>, Robot or Site.

159
=item sender =E<gt> $email
160
161
162

Recipient (the person who asked for the command)

163
=item action =E<gt> $cmd
164
165

'signoff', 'subscribe', 'add', 'del' or 'remind' if $that is List.
166
'global_remind' else.
167

168
169
170
=item email =E<gt> $email

Used if $cmd is add|del|invite|signoff.
171

172
173
174
=item gecos =E<gt> $comment

May be used if $cmd is C<'add'> or C<'subscribe'>.
175
176
177
178
179
180
181
182
183
184
185
186
187
188

=back

Returns:

C<1> or C<undef>.

=back

=cut

# Old name: List::request_auth().
sub request_auth {
    $log->syslog('debug2', '(%s, %s, %s, %s)', @_);
189
    my %options = @_;
190

191
    # Suppress warnings on uninitialized value.
192
193
    foreach my $i (qw(sender email gecos)) {
        $options{$i} = '' unless defined $options{$i};
194
195
    }

196
197
198
199
200
201
202
203
204
    my $that   = $options{context} || '*';
    my $sender = $options{sender};
    my $cmd    = $options{action};
    my $email  = $options{email};
    my $gecos  = $options{gecos};
    my $quiet  = $options{quiet};

    $cmd = "quiet $cmd" if $quiet;

205
206
207
208
209
210
211
212
213
214
215
    my ($list, $robot);
    if (ref $that eq 'Sympa::List') {
        $list  = $that;
        $robot = $that->{'domain'};
    } elsif ($that and $that ne '*') {
        $robot = $that;
    } else {
        $robot = '*';
    }

    my $keyauth;
216
    my $data = {'to' => $sender};
217
218
219
220
221
222

    if ($list) {
        my $listname = $list->{'name'};
        $data->{'list_context'} = 1;

        if ($cmd =~ /signoff$/) {
223
224
225
226
227
228
229
            $email ||= $sender;
            $keyauth = Sympa::compute_auth(
                context => $list,
                email   => $email,
                action  => 'signoff'
            );
            $data->{'command'} = "auth $keyauth $cmd $listname $email";
230
231
232
            $data->{'type'}    = 'signoff';

        } elsif ($cmd =~ /subscribe$/) {
233
234
235
236
237
238
            $keyauth = Sympa::compute_auth(
                context => $list,
                email   => $sender,
                action  => 'subscribe'
            );
            $data->{'command'} = "auth $keyauth $cmd $listname $gecos";
239
240
241
            $data->{'type'}    = 'subscribe';

        } elsif ($cmd =~ /add$/) {
242
243
244
245
246
247
248
            $keyauth = Sympa::compute_auth(
                context => $list,
                email   => $email,
                action  => 'add'
            );
            $data->{'command'} = "auth $keyauth $cmd $listname $email $gecos";
            $data->{'type'}    = 'add';
249
250

        } elsif ($cmd =~ /del$/) {
251
252
253
254
255
256
            my $keyauth = Sympa::compute_auth(
                context => $list,
                email   => $email,
                action  => 'del'
            );
            $data->{'command'} = "auth $keyauth $cmd $listname $email";
257
258
259
            $data->{'type'}    = 'del';

        } elsif ($cmd eq 'remind') {
260
261
            my $keyauth =
                Sympa::compute_auth(context => $list, action => 'remind');
262
263
264
265
            $data->{'command'} = "auth $keyauth $cmd $listname";
            $data->{'type'}    = 'remind';

        } elsif ($cmd eq 'invite') {
266
267
268
269
270
271
            my $keyauth = Sympa::compute_auth(
                context => $list,
                email   => $email,
                action  => 'invite'
            );
            $data->{'command'} = "auth $keyauth $cmd $listname $email";
272
            $data->{'type'}    = 'invite';
273
        } elsif ($cmd eq 'review') {
274
275
            my $keyauth =
                Sympa::compute_auth(context => $list, action => 'review');
276
277
            $data->{'command'} = "auth $keyauth $cmd $listname";
            $data->{'type'}    = 'review';
278
279
280
281
        }

        $data->{'command_escaped'} = tools::escape_url($data->{'command'});
        $data->{'auto_submitted'}  = 'auto-replied';
282
        unless (Sympa::send_file($list, 'request_auth', $sender, $data)) {
283
            $log->syslog('notice',
284
                'Unable to send template "request_auth" to %s', $sender);
285
286
287
288
            return undef;
        }

    } else {
289
        if ($cmd eq 'global_remind') {
sikeda's avatar
sikeda committed
290
291
292
293
            my $keyauth = Sympa::compute_auth(
                context => '*',
                action  => 'global_remind'
            );
294
            $data->{'command'} = "auth $keyauth remind *";
295
296
297
298
299
300
            $data->{'command_escaped'} =
                tools::escape_url($data->{'command'});
            $data->{'type'} = 'remind';

        }
        $data->{'auto_submitted'} = 'auto-replied';
301
        unless (Sympa::send_file($robot, 'request_auth', $sender, $data)) {
302
            $log->syslog('notice',
303
                'Unable to send template "request_auth" to %s', $sender);
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
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
453
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
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
            return undef;
        }
    }

    return 1;
}

=head3 Finding config files and templates

=over 4

=item search_fullpath ( $that, $name, [ opt => val, ...] )

    # To get file name for global site
    $file = Sympa::search_fullpath('*', $name);
    # To get file name for a robot
    $file = Sympa::search_fullpath($robot_id, $name);
    # To get file name for a family
    $file = Sympa::search_fullpath($family, $name);
    # To get file name for a list
    $file = Sympa::search_fullpath($list, $name);

Look for a file in the list > robot > site > default locations.

Possible values for options:
    order     => 'all'
    subdir    => directory ending each path
    lang      => language
    lang_only => if paths without lang subdirectory would be omitted

Returns full path of target file C<I<root>/I<subdir>/I<lang>/I<name>>
or C<I<root>/I<subdir>/I<name>>.
I<root> is the location determined by target object $that.
I<subdir> and I<lang> are optional.
If C<lang_only> option is set, paths without I<lang> subdirectory is omitted.

=back

=cut

# Old names:
# [<=6.2a] tools::get_filename()
# [6.2b] tools::search_fullpath()
# [trunk] Sympa::ConfigurableObject::get_etc_filename()
sub search_fullpath {
    $log->syslog('debug3', '(%s, %s, %s)', @_);
    my $that    = shift;
    my $name    = shift;
    my %options = @_;

    my (@try, $default_name);

    ## template refers to a language
    ## => extend search to default tpls
    ## FIXME: family path precedes to list path.  Is it appropriate?
    if ($name =~ /^(\S+)\.([^\s\/]+)\.tt2$/) {
        $default_name = $1 . '.tt2';
        @try =
            map { ($_ . '/' . $name, $_ . '/' . $default_name) }
            @{Sympa::get_search_path($that, %options)};
    } else {
        @try =
            map { $_ . '/' . $name }
            @{Sympa::get_search_path($that, %options)};
    }

    my @result;
    foreach my $f (@try) {
##        if (-l $f) {
##            my $realpath = Cwd::abs_path($f);    # follow symlink
##            next unless $realpath and -r $realpath;
##        } elsif (!-r $f) {
##            next;
##        }
        next unless -r $f;
        $log->syslog('debug3', 'Name: %s; file %s', $name, $f);

        if ($options{'order'} and $options{'order'} eq 'all') {
            push @result, $f;
        } else {
            return $f;
        }
    }
    if ($options{'order'} and $options{'order'} eq 'all') {
        return @result;
    }

    return undef;
}

=over 4

=item get_search_path ( $that, [ opt => val, ... ] )

    # To make include path for global site
    @path = @{Sympa::get_search_path('*')};
    # To make include path for a robot
    @path = @{Sympa::get_search_path($robot_id)};
    # To make include path for a family
    @path = @{Sympa::get_search_path($family)};
    # To make include path for a list
    @path = @{Sympa::get_search_path($list)};

make an array of include path for tt2 parsing

IN :
      -$that(+) : ref(Sympa::List) | ref(Sympa::Family) | Robot | "*"
      -%options : options

Possible values for options:
    subdir    => directory ending each path
    lang      => language
    lang_only => if paths without lang subdirectory would be omitted

OUT : ref(ARRAY) of tt2 include path

=begin comment

Note:
As of 6.2b, argument $lang is recommended to be IETF language tag,
rather than locale name.

=end comment

=back

=cut

# Old names:
# [<=6.2a] tools::make_tt2_include_path()
# [6.2b] tools::get_search_path()
# [trunk] Sympa::ConfigurableObject::get_etc_include_path()
sub get_search_path {
    $log->syslog('debug3', '(%s, %s, %s)', @_);
    my $that    = shift;
    my %options = @_;

    my $subdir    = $options{'subdir'};
    my $lang      = $options{'lang'};
    my $lang_only = $options{'lang_only'};

    ## Get language subdirectories.
    my $lang_dirs;
    if ($lang) {
        ## For compatibility: add old-style "locale" directory at first.
        ## Add lang itself and fallback directories.
        $lang_dirs = [
            grep {$_} (
                Sympa::Language::lang2oldlocale($lang),
                Sympa::Language::implicated_langs($lang)
            )
        ];
    }

    return [_get_search_path($that, $subdir, $lang_dirs, $lang_only)];
}

sub _get_search_path {
    my $that = shift;
    my ($subdir, $lang_dirs, $lang_only) = @_;    # shift is not used

    my @search_path;

    if (ref $that and ref $that eq 'Sympa::List') {
        my $path_list;
        my $path_family;
        @search_path = _get_search_path($that->{'domain'}, @_);

        if ($subdir) {
            $path_list = $that->{'dir'} . '/' . $subdir;
        } else {
            $path_list = $that->{'dir'};
        }
        if ($lang_dirs) {
            unless ($lang_only) {
                unshift @search_path, $path_list;
            }
            unshift @search_path, map { $path_list . '/' . $_ } @$lang_dirs;
        } else {
            unshift @search_path, $path_list;
        }

        if (defined $that->get_family) {
            my $family = $that->get_family;
            if ($subdir) {
                $path_family = $family->{'dir'} . '/' . $subdir;
            } else {
                $path_family = $family->{'dir'};
            }
            if ($lang_dirs) {
                unless ($lang_only) {
                    unshift @search_path, $path_family;
                }
                unshift @search_path,
                    map { $path_family . '/' . $_ } @$lang_dirs;
            } else {
                unshift @search_path, $path_family;
            }
        }
    } elsif (ref $that and ref $that eq 'Sympa::Family') {
        my $path_family;
        @search_path = _get_search_path($that->{'robot'}, @_);

        if ($subdir) {
            $path_family = $that->{'dir'} . '/' . $subdir;
        } else {
            $path_family = $that->{'dir'};
        }
        if ($lang_dirs) {
            unless ($lang_only) {
                unshift @search_path, $path_family;
            }
            unshift @search_path, map { $path_family . '/' . $_ } @$lang_dirs;
        } else {
            unshift @search_path, $path_family;
        }
    } elsif (not ref $that and $that and $that ne '*') {    # Robot
        my $path_robot;
        @search_path = _get_search_path('*', @_);

        if ($subdir) {
            $path_robot = $Conf::Conf{'etc'} . '/' . $that . '/' . $subdir;
        } else {
            $path_robot = $Conf::Conf{'etc'} . '/' . $that;
        }
        if (-d $path_robot) {
            if ($lang_dirs) {
                unless ($lang_only) {
                    unshift @search_path, $path_robot;
                }
                unshift @search_path,
                    map { $path_robot . '/' . $_ } @$lang_dirs;
            } else {
                unshift @search_path, $path_robot;
            }
        }
    } elsif (not ref $that and $that eq '*') {    # Site
        my $path_etcbindir;
        my $path_etcdir;

        if ($subdir) {
            $path_etcbindir = Sympa::Constants::DEFAULTDIR . '/' . $subdir;
            $path_etcdir    = $Conf::Conf{'etc'} . '/' . $subdir;
        } else {
            $path_etcbindir = Sympa::Constants::DEFAULTDIR;
            $path_etcdir    = $Conf::Conf{'etc'};
        }
        if ($lang_dirs) {
            unless ($lang_only) {
                @search_path = (
                    (map { $path_etcdir . '/' . $_ } @$lang_dirs),
                    $path_etcdir,
                    (map { $path_etcbindir . '/' . $_ } @$lang_dirs),
                    $path_etcbindir
                );
            } else {
                @search_path = (
                    (map { $path_etcdir . '/' . $_ } @$lang_dirs),
                    (map { $path_etcbindir . '/' . $_ } @$lang_dirs)
                );
            }
        } else {
            @search_path = ($path_etcdir, $path_etcbindir);
        }
    } else {
        die 'bug in logic.  Ask developer';
    }

    return @search_path;
}

=head3 Sending Notifications

=over 4

=item send_dsn ( $that, $message,
[ { key => val, ... }, [ $status, [ $diag ] ] ] )

    # To send site-wide DSN
    Sympa::send_dsn('*', $message, {'recipient' => $rcpt},
        '5.1.2', 'Unknown robot');
    # To send DSN related to a robot
    Sympa::send_dsn($robot, $message, {'listname' => $name},
        '5.1.1', 'Unknown list');
    # To send DSN specific to a list
    Sympa::send_dsn($list, $message, {}, '2.1.5', 'Success');

Sends a delivery status notification (DSN) to SENDER
592
by parsing delivery_status_notification.tt2 template.
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614

=back

=cut

# Default diagnostic messages taken from IANA registry:
# http://www.iana.org/assignments/smtp-enhanced-status-codes/
# They should be modified to fit in Sympa.
my %diag_messages = (
    'default' => 'Other undefined Status',
    # success
    '2.1.5' => 'Destination address valid',
    # no available family, dynamic list creation failed, etc.
    '4.2.1' => 'Mailbox disabled, not accepting messages',
    # no subscribers in dynamic list
    '4.2.4' => 'Mailing list expansion problem',
    # unknown list address
    '5.1.1' => 'Bad destination mailbox address',
    # unknown robot
    '5.1.2' => 'Bad destination system address',
    # too large
    '5.2.3' => 'Message length exceeds administrative limit',
615
616
    # could not store message into spool or mailer
    '5.3.0' => 'Other or undefined mail system status',
617
618
619
620
    # misconfigured family list
    '5.3.5' => 'System incorrectly configured',
    # loop detected
    '5.4.6' => 'Routing loop detected',
621
622
    # message contains commands
    '5.6.0' => 'Other or undefined media error',
623
624
    # no command found in message
    '5.6.1' => 'Media not supported',
625
626
627
628
    # failed to personalize (merge_feature)
    '5.6.5' => 'Conversion Failed',
    # virus found
    '5.7.0' => 'Other or undefined security status',
629
630
    # message is not authorized and is rejected
    '5.7.1' => 'Delivery not authorized, message refused',
631
632
633
634
635
636
637
638
639
640
641
642
    # failed to re-encrypt decrypted message
    '5.7.5' => 'Cryptographic failure',
);

# Old names: tools::send_dsn(), Sympa::ConfigurableObject::send_dsn().
sub send_dsn {
    my $that    = shift;
    my $message = shift;
    my $param   = shift || {};
    my $status  = shift;
    my $diag    = shift;

643
644
    unless (Scalar::Util::blessed($message)
        and $message->isa('Sympa::Message')) {
645
646
647
648
649
650
651
652
653
654
655
656
657
        $log->syslog('err', 'object %s is not Message', $message);
        return undef;
    }

    my $sender;
    if (defined($sender = $message->{'envelope_sender'})) {
        ## Won't reply to message with null envelope sender.
        return 0 if $sender eq '<>';
    } elsif (!defined($sender = $message->{'sender'})) {
        $log->syslog('err', 'No sender found');
        return undef;
    }

658
    $param->{listname} ||= $message->{localpart};
659
    if (ref $that eq 'Sympa::List') {
660
661
        $param->{recipient} ||=
            $param->{listname} . '@' . $that->{'admin'}{'host'};
662
        $status ||= '5.1.1';
663
664
665
666
667

        if ($status eq '5.2.3') {
            my $max_size = $that->{'admin'}{'max_size'};
            $param->{msg_size} = int($message->{'size'} / 1024);
            $param->{max_size} = int($max_size / 1024);
668
        }
669
670
671
    } elsif (!ref $that and $that and $that ne '*') {
        $param->{recipient} ||=
            $param->{listname} . '@' . Conf::get_robot_conf($that, 'host');
672
673
        $status ||= '5.1.1';
    } elsif ($that eq '*') {
674
675
        $param->{recipient} ||=
            $param->{listname} . '@' . $Conf::Conf{'host'};
676
677
678
679
680
681
682
683
684
685
        $status ||= '5.1.2';
    } else {
        die 'bug in logic.  Ask developer';
    }

    # Diagnostic message.
    $diag ||= $diag_messages{$status} || $diag_messages{'default'};
    # Delivery result, "failed" or "delivered".
    my $action = (index($status, '2') == 0) ? 'delivered' : 'failed';

686
687
688
689
690
691
692
    # Attach original (not decrypted) content.
    my $msg_string = $message->as_string(original => 1);
    $msg_string =~ s/\AReturn-Path: (.*?)\n(?![ \t])//s;
    my $header =
        ($msg_string =~ /\A\r?\n/)
        ? ''
        : [split /(?<=\n)\r?\n/, $msg_string, 2]->[0];
693
694
695
696
697

    my $date =
        (eval { DateTime->now(time_zone => 'local') } || DateTime->now)
        ->strftime('%a, %{day} %b %Y %H:%M:%S %z');

698
    my $spindle = Sympa::Spindle::ProcessTemplate->new(
699
700
701
702
703
        context  => $that,
        template => 'delivery_status_notification',
        rcpt     => $sender,
        data     => {
            %$param,
704
705
            'to'              => $sender,
            'date'            => $date,
706
            'msg'             => $msg_string,
707
708
709
710
711
            'header'          => $header,
            'auto_submitted'  => 'auto-replied',
            'action'          => $action,
            'status'          => $status,
            'diagnostic_code' => $diag,
712
        },
713
        # Set envelope sender.  DSN _must_ have null envelope sender.
714
715
716
        envelope_sender => '<>',
    );
    unless ($spindle and $spindle->spin and $spindle->{finish} eq 'success') {
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
        $log->syslog('err', 'Unable to send DSN to %s', $sender);
        return undef;
    }

    return 1;
}

=over

=item send_file ( $that, $tpl, $who, [ $context, [ options... ] ] )

    # To send site-global (not relative to a list or a robot)
    # message
    Sympa::send_file('*', $template, $who, ...);
    # To send global (not relative to a list, but relative to a
    # robot) message
    Sympa::send_file($robot, $template, $who, ...);
    # To send message relative to a list
    Sympa::send_file($list, $template, $who, ...);

Send a message to user(s).
Find the tt2 file according to $tpl, set up
$data for the next parsing (with $context and
configuration)
Message is signed if the list has a key and a
certificate

Note: List::send_global_file() was deprecated.

=back

=cut

# Old name: List::send_file() and List::send_global_file().
sub send_file {
    $log->syslog('debug2', '(%s, %s, %s, ...)', @_);
    my $that    = shift;
    my $tpl     = shift;
    my $who     = shift;
    my $context = shift || {};
    my %options = @_;

759
    my $spindle = Sympa::Spindle::ProcessTemplate->new(
760
761
762
763
764
765
        context  => $that,
        template => $tpl,
        rcpt     => $who,
        data     => $context,
        %options
    );
766
    unless ($spindle and $spindle->spin and $spindle->{finish} eq 'success') {
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
        $log->syslog('err', 'Could not send template %s to %s', $tpl, $who);
        return undef;
    }

    return 1;
}

=over 4

=item send_notify_to_listmaster ( $that, $operation, $data )

    # To send notify to super listmaster(s)
    Sympa::send_notify_to_listmaster('*', 'css_updated', ...);
    # To send notify to normal (per-robot) listmaster(s)
    Sympa::send_notify_to_listmaster($robot, 'web_tt2_error', ...);
    # To send notify to normal listmaster(s) of robot the list belongs to.
    Sympa::send_notify_to_listmaster($list, 'request_list_creation', ...);

Sends a notice to (super or normal) listmaster by parsing
listmaster_notification.tt2 template.

Parameters:

=over

=item $self

L<Sympa::List>, Robot or Site.

=item $operation

Notification type.

=item $param

Hashref or arrayref.
Values for template parsing.

=back

Returns:

C<1> or C<undef>.

=back

=cut

# Old name: List::send_notify_to_listmaster()
sub send_notify_to_listmaster {
    $log->syslog('debug2', '(%s, %s, %s)', @_) unless $_[1] eq 'logs_failed';
    my $that      = shift;
    my $operation = shift;
    my $data      = shift;

    my ($list, $robot_id);
    if (ref $that eq 'Sympa::List') {
        $list     = $that;
        $robot_id = $list->{'domain'};
    } elsif ($that and $that ne '*') {
        $robot_id = $that;
    } else {
        $robot_id = '*';
    }

832
    my @listmasters = Sympa::get_listmasters_email($that);
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
    my $to =
          Conf::get_robot_conf($robot_id, 'listmaster_email') . '@'
        . Conf::get_robot_conf($robot_id, 'host');

    if (ref $data ne 'HASH' and ref $data ne 'ARRAY') {
        die
            'Error on incoming parameter "$data", it must be a ref on HASH or a ref on ARRAY';
    }

    if (ref $data ne 'HASH') {
        my $d = {};
        foreach my $i ((0 .. $#{$data})) {
            $d->{"param$i"} = $data->[$i];
        }
        $data = $d;
    }

    $data->{'to'}             = $to;
    $data->{'type'}           = $operation;
    $data->{'auto_submitted'} = 'auto-generated';

    my @tosend;

    if ($operation eq 'no_db' or $operation eq 'db_restored') {
        $data->{'db_name'} = Conf::get_robot_conf($robot_id, 'db_name');
    }

    if (   $operation eq 'request_list_creation'
        or $operation eq 'request_list_renaming') {
862
        foreach my $email (@listmasters) {
863
864
            my $cdata = Sympa::Tools::Data::dup_var($data);
            $cdata->{'one_time_ticket'} =
865
866
                Sympa::Ticket::create($email, $robot_id, 'get_pending_lists',
                $cdata->{'ip'});
867
868
869
870
871
872
873
874
875
            push @tosend,
                {
                email => $email,
                data  => $cdata
                };
        }
    } else {
        push @tosend,
            {
876
            email => [@listmasters],
877
878
879
880
881
882
883
884
885
886
887
888
889
            data  => $data
            };
    }

    foreach my $ts (@tosend) {
        my $email = $ts->{'email'};
        # Skip DB access because DB is not accessible
        $email = [$email]
            if not ref $email
                and (  $operation eq 'missing_dbd'
                    or $operation eq 'no_db'
                    or $operation eq 'db_restored');

890
        my $spindle = Sympa::Spindle::ProcessTemplate->new(
891
892
893
            context  => $that,
            template => 'listmaster_notification',
            rcpt     => $email,
894
            data     => $ts->{'data'},
895

896
897
898
899
900
            splicing_to => ['Sympa::Spindle::ToAlarm'],
        );
        unless ($spindle
            and $spindle->spin
            and $spindle->{finish} eq 'success') {
901
902
903
904
            $log->syslog(
                'notice',
                'Unable to send template "listmaster_notification" to %s listmaster %s',
                $robot_id,
905
                $ts->{'email'}
906
907
908
909
910
911
912
913
            ) unless $operation eq 'logs_failed';
            return undef;
        }
    }

    return 1;
}

914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
=over

=item send_notify_to_user ( $that, $operation, $user, $param )

Send a notice to a user (sender, subscriber or another user)
by parsing user_notification.tt2 template.

Parameters:

=over

=item $that

L<Sympa::List>, Robot or Site.

=item $operation

Notification type.

=item $user

E-mail of notified user.

=item $param

Hashref or arrayref.  Values for template parsing.

=back

Returns:

C<1> or C<undef>.

=back

=cut

sub send_notify_to_user {
    $log->syslog('debug2', '(%s, %s, %s, ...)', @_);
    my $that      = shift;
    my $operation = shift;
    my $user      = shift;
    my $param     = shift || {};

    my ($list, $robot_id);
    if (ref $that eq 'Sympa::List') {
        $list     = $that;
        $robot_id = $list->{'domain'};
    } elsif ($that and $that ne '*') {
        $robot_id = $that;
    } else {
        $robot_id = '*';
    }

    $param->{'auto_submitted'} = 'auto-generated';

    die 'Missing parameter "operation"' unless $operation;
    die 'missing parameter "user"'      unless $user;

    if (ref $param eq "HASH") {
        $param->{'to'}   = $user;
        $param->{'type'} = $operation;

        if ($operation eq 'ticket_to_signoff') {
            $param->{one_time_ticket} =
979
                Sympa::Ticket::create($user, $robot_id,
980
981
982
983
984
                'signoff/' . $list->{'name'},
                $param->{ip})
                or return undef;
        } elsif ($operation eq 'ticket_to_family_signoff') {
            $param->{one_time_ticket} =
985
                Sympa::Ticket::create($user, $robot_id,
986
987
988
989
990
                'family_signoff/' . $param->{family} . '/' . $user,
                $param->{ip})
                or return undef;
        } elsif ($operation eq 'ticket_to_send') {
            $param->{'one_time_ticket'} =
991
                Sympa::Ticket::create($user, $robot_id,
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
                'change_email/' . $param->{email},
                $param->{ip})
                or return undef;
        }

        unless (Sympa::send_file($that, 'user_notification', $user, $param)) {
            $log->syslog('notice',
                'Unable to send template "user_notification" to %s', $user);
            return undef;
        }
    } elsif (ref $param eq "ARRAY") {
        my $data = {
            'to'   => $user,
            'type' => $operation
        };

        for my $i (0 .. $#{$param}) {
            $data->{"param$i"} = $param->[$i];
        }
        unless (Sympa::send_file($that, 'user_notification', $user, $data)) {
            $log->syslog('notice',
                'Unable to send template "user_notification" to %s', $user);
            return undef;
        }
    } else {
        $log->syslog(
            'err',
            'error on incoming parameter "%s", it must be a ref on HASH or a ref on ARRAY',
            $param
        );
        return undef;
    }
    return 1;
}

1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
=head3 Internationalization

=over

=item best_language ( LANG, ... )

    # To get site-wide best language.
    $lang = Sympa::best_language('*', 'de', 'en-US;q=0.9');
    # To get robot-wide best language.
    $lang = Sympa::best_language($robot, 'de', 'en-US;q=0.9');
    # To get list-specific best language.
    $lang = Sympa::best_language($list, 'de', 'en-US;q=0.9');

Chooses best language under the context of List, Robot or Site.
Arguments are language codes (see L<Language>) or ones with quality value.
If no arguments are given, the value of C<HTTP_ACCEPT_LANGUAGE> environment
variable will be used.

Returns language tag or, if negotiation failed, lang of object.

=back

=cut

sub best_language {
    my $that = shift;
    my $accept_string = join ',', grep { $_ and $_ =~ /\S/ } @_;
    $accept_string ||= $ENV{HTTP_ACCEPT_LANGUAGE} || '*';

    my @supported_languages;
    my %supported_languages;
    my @langs = ();
    my $lang;

    if (ref $that eq 'Sympa::List') {
        @supported_languages =
            Sympa::get_supported_languages($that->{'domain'});
        $lang = $that->{'admin'}{'lang'};
    } elsif (!ref $that) {
        @supported_languages = Sympa::get_supported_languages($that || '*');
        $lang = Conf::get_robot_conf($that || '*', 'lang');
    } else {
        die 'bug in logic.  Ask developer';
    }
    %supported_languages = map { $_ => 1 } @supported_languages;
    push @langs, $lang
        if $supported_languages{$lang};

    if (ref $that eq 'Sympa::List') {
        my $lang = Conf::get_robot_conf($that->{'domain'}, 'lang');
        push @langs, $lang
            if $supported_languages{$lang} and !grep { $_ eq $lang } @langs;
    }
    if (ref $that eq 'Sympa::List' or !ref $that and $that and $that ne '*') {
        my $lang = $Conf::Conf{'lang'};
        push @langs, $lang
            if $supported_languages{$lang} and !grep { $_ eq $lang } @langs;
    }
    foreach my $lang (@supported_languages) {
        push @langs, $lang
            if !grep { $_ eq $lang } @langs;
    }

    return Sympa::Language::negotiate_lang($accept_string, @langs) || $lang;
}

=over 4

=item get_supported_languages ( $that )

I<Function>.
Gets supported languages, canonicalized.
In array context, returns array of supported languages.
In scalar context, returns arrayref to them.

=back

=cut

#FIXME: Inefficient.  Would be cached.
#FIXME: Would also accept Sympa::List object.
# Old name: [trunk] Sympa::Site::supported_languages().
sub get_supported_languages {
    my $robot = shift;

    my @lang_list = ();
    if (%Conf::Conf) {    # configuration loaded.
        my $supported_lang;

        if ($robot and $robot ne '*') {
            $supported_lang = Conf::get_robot_conf($robot, 'supported_lang');
        } else {
            $supported_lang = $Conf::Conf{'supported_lang'};
        }

        my $language = Sympa::Language->instance;
        $language->push_lang;
        @lang_list =
            grep { $_ and $_ = $language->set_lang($_) }
            split /[\s,]+/, $supported_lang;
        $language->pop_lang;
    }
    @lang_list = ('en') unless @lang_list;
    return @lang_list if wantarray;
    return \@lang_list;
}

1134
=head3 Addresses and users
1135
1136
1137
1138
1139

These are accessors derived from configuration parameters.

=over

1140
1141
1142
=item get_address ( $that, [ $type ] )

    # Get address bound for super listmaster(s).
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
    Sympa::get_address('*', 'listmaster');     # <listmaster@DEFAULT_HOST>
    # Get address for command robot and robot listmaster(s).
    Sympa::get_address($robot, 'sympa');       # <sympa@HOST>
    Sympa::get_address($robot, 'listmaster');  # <listmaster@HOST>
    # Get address for command robot and robot listmaster(s).
    Sympa::get_address($family, 'sympa');      # <sympa@HOST>
    Sympa::get_address($family, 'listmaster'); # listmaster@HOST>
    # Get address bound for the list and its owner(s) etc.
    Sympa::get_address($list);                 # <NAME@HOST>
    Sympa::get_address($list, 'owner');        # <NAME-request@HOST>
    Sympa::get_address($list, 'editor');       # <NAME-editor@HOST>
    Sympa::get_address($list, 'return_path');  # <NAME-owner@HOST>
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210

Site or robot:
Returns the site or robot email address of type $type: email command address
(default, <sympa> address), "owner" (<sympa-request> address) or "listmaster".

List:
Returns the list email address of type $type: posting address (default),
"owner" (<LIST-request> address), "editor", non-VERP "return_path"
(<LIST-owner> address), "subscribe" or "unsubscribe".

Note:
%Conf::Conf or Conf::get_robot_conf() may return <sympa> and
<sympa-request> addresses by "sympa" and "request" arguments, respectively.
They are obsoleted.  Use this function instead.

=back

=cut

sub get_address {
    my $that = shift || '*';
    my $type = shift || '';

    if (ref $that eq 'Sympa::List') {
        unless ($type) {
            return $that->{'name'} . '@' . $that->{'admin'}{'host'};
        } elsif ($type eq 'owner') {
            return
                  $that->{'name'}
                . '-request' . '@'
                . $that->{'admin'}{'host'};
        } elsif ($type eq 'editor') {
            return
                  $that->{'name'}
                . '-editor' . '@'
                . $that->{'admin'}{'host'};
        } elsif ($type eq 'return_path') {
            return $that->{'name'}
                . Conf::get_robot_conf($that->{'domain'},
                'return_path_suffix')
                . '@'
                . $that->{'admin'}{'host'};
        } elsif ($type eq 'subscribe') {
            return
                  $that->{'name'}
                . '-subscribe' . '@'
                . $that->{'admin'}{'host'};
        } elsif ($type eq 'unsubscribe') {
            return
                  $that->{'name'}
                . '-unsubscribe' . '@'
                . $that->{'admin'}{'host'};
        } elsif ($type eq 'sympa' or $type eq 'listmaster') {
            # robot address, for convenience.
            return Sympa::get_address($that->{'domain'}, $type);
        }
1211
1212
1213
    } elsif (ref $that eq 'Sympa::Family') {
        # robot address, for convenience.
        return Sympa::get_address($that->{'robot'}, $type);
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
    } else {
        unless ($type) {
            return Conf::get_robot_conf($that, 'email') . '@'
                . Conf::get_robot_conf($that, 'host');
        } elsif ($type eq 'sympa') {    # same as above, for convenience
            return Conf::get_robot_conf($that, 'email') . '@'
                . Conf::get_robot_conf($that, 'host');
        } elsif ($type eq 'owner' or $type eq 'request') {
            return
                  Conf::get_robot_conf($that, 'email')
                . '-request' . '@'
                . Conf::get_robot_conf($that, 'host');
        } elsif ($type eq 'listmaster') {
            return Conf::get_robot_conf($that, 'listmaster_email') . '@'
                . Conf::get_robot_conf($that, 'host');
        } elsif ($type eq 'return_path') {
            return
                  Conf::get_robot_conf($that, 'email')
                . Conf::get_robot_conf($that, 'return_path_suffix') . '@'
                . Conf::get_robot_conf($that, 'host');
        }
    }

    $log->syslog('err', 'Unknown type of address "%s" for %s', $type, $that);
    return undef;
}

=over

1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
=item get_listmasters_email ( $that )

    # To get addresses of super-listmasters.
    @addrs = Sympa::get_listmasters_email('*');
    # To get addresses of normal listmasters of a robot.
    @addrs = Sympa::get_listmasters_email($robot);
    # To get addresses of normal listmasters of the robot of a family.
    @addrs = Sympa::get_listmasters_email($family);
    # To get addresses of normal listmasters of the robot of a list.
    @addrs = Sympa::get_listmasters_email($list);

Gets valid email addresses of listmasters. In array context, returns array of
addresses. In scalar context, returns arrayref to them.

=back

=cut

# Old names:
# [6.2b] Conf::get_robot_conf(..., 'listmasters'), $Conf::Conf{'listmasters'}.
# [trunk] Site::listmasters().
sub get_listmasters_email {
    my $that = shift;

    my $listmaster;
    if (ref $that eq 'Sympa::List') {
        $listmaster = Conf::get_robot_conf($that->{'domain'}, 'listmaster');
    } elsif (ref $that eq 'Sympa::Family') {
        $listmaster = Conf::get_robot_conf($that->{'robot'}, 'listmaster');
    } elsif (not ref($that) and $that and $that ne '*') {
        $listmaster = Conf::get_robot_conf($that, 'listmaster');
    } else {
        $listmaster = Conf::get_robot_conf('*', 'listmaster');
    }

    my @listmasters =
        grep { tools::valid_email($_) } split /\s*,\s*/, $listmaster;
1280
1281
1282
1283
1284
1285
    # If no valid adresses found, use listmaster of site config.
    unless (@listmasters or (not ref $that and $that eq '*')) {
        $log->syslog('notice', 'Warning: No listmasters found for %s', $that);
        @listmasters = Sympa::get_listmasters_email('*');
    }

1286
1287
1288
    return wantarray ? @listmasters : [@listmasters];
}

1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
=over

=item is_listmaster ( $that, $who )

Is the user listmaster?

=back

=cut

# Old names: [6.2b-6.2.3] Sympa::Robot::is_listmaster($who, $robot_id)
sub is_listmaster {
    my $that = shift;
1302
    my $who  = Sympa::Tools::Text::canonic_email(shift);
1303

1304
    return undef unless defined $who;
1305
1306
1307
1308
1309
    return 1 if grep { lc $_ eq $who } Sympa::get_listmasters_email($that);
    return 1 if grep { lc $_ eq $who } Sympa::get_listmasters_email('*');
    return 0;
}

1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1;
__END__

=head1 SEE ALSO

L<Sympa::Site> (not yet available),
L<Sympa::Robot> (not yet available),
L<Sympa::Family>,
L<Sympa::List>.

=cut