List.pm 371 KB
Newer Older
1
2
3
4
# -*- indent-tabs-mode: nil; -*-
# vim:ft=perl:et:sw=4
# $Id$

5
# Sympa - SYsteme de Multi-Postage Automatique
6
7
8
9
#
# 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 GIP RENATER
11
12
13
14
15
16
17
18
19
20
21
#
# 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.
#
22
23
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
root's avatar
root committed
24

25
package Sympa::List;
root's avatar
root committed
26
27

use strict;
28
use warnings;
29
30
use Digest::MD5 qw();
use Encode qw();
31
32
use English;    # FIXME: drop $POSTMATCH usage
use HTML::Entities qw();
33
use HTTP::Request;
34
use IO::Scalar;
35
use LWP::UserAgent;
36
use MIME::Charset;
37
use MIME::EncWords;
sikeda's avatar
sikeda committed
38
use POSIX qw();
39
use Storable qw();
sikeda's avatar
sikeda committed
40
use Time::Local qw();
41
use URI::Escape qw();
42
use XML::LibXML;
43

44
45
use Sympa::Archive;
use Sympa::Auth;
46
use Sympa::Bulk;
47
use Conf;
48
use Sympa::ConfDef;
49
use Sympa::Constants;
50
use Sympa::Database;
51
52
53
use Sympa::Datasource;
use Sympa::Family;
use Sympa::Fetch;
54
use Sympa::Language;
55
use Sympa::ListDef;
56
use Sympa::LockedFile;
57
use Log;
58
use Sympa::Message;
59
use Sympa::Message::Plugin;
60
use Sympa::Regexps;
61
62
use Sympa::Robot;
use Sympa::Scenario;
63
use SDM;
64
use Sympa::Task;
65
use tools;
66
67
use Sympa::Tools::Data;
use Sympa::Tools::File;
68
use Sympa::Tools::Password;
69
use Sympa::Tools::SMIME;
70
use Sympa::Tools::Text;
71
use Sympa::Tracking;
72
use tt2;
73
use Sympa::User;
74

75
my @sources_providing_listmembers = qw/
76
77
78
79
80
81
82
83
84
85
    include_file
    include_ldap_2level_query
    include_ldap_query
    include_list
    include_remote_file
    include_remote_sympa_list
    include_sql_query
    /;

#XXX include_admin
86
my @more_data_sources = qw/
87
88
    editor_include
    owner_include
89
    member_include
90
    /;
91
92

# All non-pluggable sources are in the admin user file
93
94
my %config_in_admin_user_file = map +($_ => 1),
    @sources_providing_listmembers;
95

96
97
98
99
100
# Language context
my $language = Sympa::Language->instance;

=encoding utf-8

101
102
103
104
=head1 NAME

List - Mailing list

root's avatar
root committed
105
106
=head1 CONSTRUCTOR

107
108
=over

root's avatar
root committed
109
110
=item new( [PHRASE] )

111
 Sympa::List->new();
root's avatar
root committed
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

Creates a new object which will be used for a list and
eventually loads the list if a name is given. Returns
a List object.

=back

=head1 METHODS

=over 4

=item load ( LIST )

Loads the indicated list into the object.

=item save ( LIST )

Saves the indicated list object to the disk files.

=item savestats ()

Saves updates the statistics file on disk.

=item update_stats( BYTES )

Updates the stats, argument is number of bytes, returns the next
sequence number. Does nothing if no stats.

=item send_sub_to_owner ( WHO, COMMENT )
Send a message to the list owners telling that someone
wanted to subscribe to the list.

144
=item delete_list_member ( ARRAY )
root's avatar
root committed
145
146
147

Delete the indicated users from the list.
 
148
=item delete_list_admin ( ROLE, ARRAY )
149
150
151

Delete the indicated admin user with the predefined role from the list.

root's avatar
root committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
=item get_cookie ()

Returns the cookie for a list, if available.

=item get_max_size ()

Returns the maximum allowed size for a message.

=item get_reply_to ()

Returns an array with the Reply-To values.

=item get_default_user_options ()

Returns a default option of the list for subscription.

=item get_total ()

Returns the number of subscribers to the list.

172

173
=item get_global_user ( USER )
root's avatar
root committed
174

175
Returns a hash with the information regarding the indicated
root's avatar
root committed
176
177
user.

178
=item get_list_member ( USER )
179
180

Returns a subscriber of the list.
david.verdin's avatar
david.verdin committed
181

182
=item get_list_admin ( ROLE, USER)
183
184
185

Return an admin user of the list with predefined role

186
=item get_first_list_member ()
root's avatar
root committed
187
188
189

Returns a hash to the first user on the list.

190
=item get_first_list_admin ( ROLE )
191

192
Returns a hash to the first admin user with predefined role on the list.
193

194
=item get_next_list_member ()
root's avatar
root committed
195
196
197
198

Returns a hash to the next users, until we reach the end of
the list.

199
=item get_next_list_admin ()
200
201
202
203

Returns a hash to the next admin users, until we reach the end of
the list.

204
=item update_list_member ( USER, HASHPTR )
root's avatar
root committed
205
206
207

Sets the new values given in the hash for the user.

208
=item update_list_admin ( USER, ROLE, HASHPTR )
209
210
211

Sets the new values given in the hash for the admin user.

212
=item add_list_member ( USER, HASHPTR )
root's avatar
root committed
213
214
215
216

Adds a new user to the list. May overwrite existing
entries.

217
218
219
220
221
=item add_admin_user ( USER, ROLE, HASHPTR )

Adds a new admin user to the list. May overwrite existing
entries.

222
=item is_list_member ( USER )
root's avatar
root committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265

Returns true if the indicated user is member of the list.
 
=item am_i ( FUNCTION, USER )

Returns true is USER has FUNCTION (owner, editor) on the
list.

=item get_state ( FLAG )

Returns the value for a flag : sig or sub.

=item may_do ( ACTION, USER )

Chcks is USER may do the ACTION for the list. ACTION can be
one of following : send, review, index, getm add, del,
reconfirm, purge.

=item is_moderated ()

Returns true if the list is moderated.

=item archive_exist ( FILE )

Returns true if the indicated file exists.

=item archive_send ( WHO, FILE )

Send the indicated archive file to the user, if it exists.

=item archive_ls ()

Returns the list of available files, if any.

=item archive_msg ( MSG )

Archives the Mail::Internet message given as argument.

=item is_archived ()

Returns true is the list is configured to keep archives of
its messages.

266
267
268
269
270
=item is_archiving_enabled ( )

Returns true is the list is configured to keep archives of
its messages, i.e. process_archive parameter is set to "on".

root's avatar
root committed
271
272
273
274
275
276
277
=item get_stats ( OPTION )

Returns either a formatted printable strings or an array whith
the statistics. OPTION can be 'text' or 'array'.

=item print_info ( FDNAME )

278
Print the list information to the given file descriptor, or the
root's avatar
root committed
279
280
currently selected descriptor.

281
282
=back

root's avatar
root committed
283
284
285
=cut

## Database and SQL statement handlers
286
my ($sth, @sth_stack);
287
288
289

my %list_cache;

290
291
## DB fields with numeric type
## We should not do quote() for these while inserting data
292
293
294
295
296
297
298
299
300
my %numeric_field = (
    'cookie_delay_user'       => 1,
    'bounce_score_subscriber' => 1,
    'subscribed_subscriber'   => 1,
    'included_subscriber'     => 1,
    'subscribed_admin'        => 1,
    'included_admin'          => 1,
    'wrong_login_count'       => 1,
);
root's avatar
root committed
301

302
303
304
305
306
307
308
309
310
311
312
313
314
315
## List parameter values except for parameters below.
my %list_option = (

    # reply_to_header.apply
    'forced'  => {'gettext_id' => 'overwrite Reply-To: header field'},
    'respect' => {'gettext_id' => 'preserve existing header field'},

    # reply_to_header.value
    'sender' => {'gettext_id' => 'sender'},

    # reply_to_header.value, include_remote_sympa_list.cert
    'list' => {'gettext_id' => 'list'},

    # include_ldap_2level_query.select2, include_ldap_2level_query.select1,
316
    # include_ldap_query.select, reply_to_header.value, dmarc_protection.mode
317
318
319
320
321
322
323
324
325
326
327
328
    'all' => {'gettext_id' => 'all'},

    # reply_to_header.value
    'other_email' => {'gettext_id' => 'other email address'},

    # msg_topic_keywords_apply_on
    'subject'          => {'gettext_id' => 'subject field'},
    'body'             => {'gettext_id' => 'message body'},
    'subject_and_body' => {'gettext_id' => 'subject and body'},

    # bouncers_level2.notification, bouncers_level2.action,
    # bouncers_level1.notification, bouncers_level1.action,
329
330
    # spam_protection, dkim_signature_apply_on, web_archive_spam_protection,
    # dmarc_protection.mode
331
332
333
334
    'none' => {'gettext_id' => 'do nothing'},

    # bouncers_level2.notification, bouncers_level1.notification,
    # welcome_return_path, remind_return_path, rfc2369_header_fields,
335
    # archive.mail_access
336
337
338
339
340
341
342
343
344
345
    'owner' => {'gettext_id' => 'owner'},

    # bouncers_level2.notification, bouncers_level1.notification
    'listmaster' => {'gettext_id' => 'listmaster'},

    # bouncers_level2.action, bouncers_level1.action
    'remove_bouncers' => {'gettext_id' => 'remove bouncing users'},
    'notify_bouncers' => {'gettext_id' => 'send notify to bouncing users'},

    # pictures_feature, dkim_feature, merge_feature,
346
    # inclusion_notification_feature, tracking.delivery_status_notification,
347
    # tracking.message_disposition_notification
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
    'on'  => {'gettext_id' => 'enabled'},
    'off' => {'gettext_id' => 'disabled'},

    # include_remote_sympa_list.cert
    'robot' => {'gettext_id' => 'robot'},

    # include_ldap_2level_query.select2, include_ldap_2level_query.select1,
    # include_ldap_query.select
    'first' => {'gettext_id' => 'first entry'},

    # include_ldap_2level_query.select2, include_ldap_2level_query.select1
    'regex' => {'gettext_id' => 'entries matching regular expression'},

    # include_ldap_2level_query.scope2, include_ldap_2level_query.scope1,
    # include_ldap_query.scope
    'base' => {'gettext_id' => 'base'},
    'one'  => {'gettext_id' => 'one level'},
    'sub'  => {'gettext_id' => 'subtree'},

    # include_ldap_2level_query.use_ssl, include_ldap_query.use_ssl
    'yes' => {'gettext_id' => 'yes'},
    'no'  => {'gettext_id' => 'no'},

    # include_ldap_2level_query.ssl_version, include_ldap_query.ssl_version
    'sslv2' => {'gettext_id' => 'SSL version 2'},
    'sslv3' => {'gettext_id' => 'SSL version 3'},
    'tls'   => {'gettext_id' => 'TLS'},

    # editor.reception, owner_include.reception, owner.reception,
    # editor_include.reception
    'mail'   => {'gettext_id' => 'receive notification email'},
    'nomail' => {'gettext_id' => 'no notifications'},

    # editor.visibility, owner_include.visibility, owner.visibility,
    # editor_include.visibility
    'conceal'   => {'gettext_id' => 'concealed from list menu'},
    'noconceal' => {'gettext_id' => 'listed on the list menu'},

    # welcome_return_path, remind_return_path
    'unique' => {'gettext_id' => 'bounce management'},

    # owner_include.profile, owner.profile
    'privileged' => {'gettext_id' => 'privileged owner'},
    'normal'     => {'gettext_id' => 'normal owner'},

    # priority
    '0' => {'gettext_id' => '0 - highest priority'},
    '9' => {'gettext_id' => '9 - lowest priority'},
    'z' => {'gettext_id' => 'queue messages only'},

    # spam_protection, web_archive_spam_protection
    'at'         => {'gettext_id' => 'replace @ characters'},
    'javascript' => {'gettext_id' => 'use JavaScript'},

    # msg_topic_tagging
    'required_sender' => {'gettext_id' => 'required to post message'},
    'required_moderator' =>
405
        {'gettext_id' => 'required to distribute message'},
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422

    # msg_topic_tagging, custom_attribute.optional
    'optional' => {'gettext_id' => 'optional'},

    # custom_attribute.optional
    'required' => {'gettext_id' => 'required'},

    # custom_attribute.type
    'string'  => {'gettext_id' => 'string'},
    'text'    => {'gettext_id' => 'multi-line text'},
    'integer' => {'gettext_id' => 'number'},
    'enum'    => {'gettext_id' => 'set of keywords'},

    # footer_type
    'mime'   => {'gettext_id' => 'add a new MIME part'},
    'append' => {'gettext_id' => 'append to message body'},

423
    # archive.mail_access
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
    'open'    => {'gettext_id' => 'open'},
    'closed'  => {'gettext_id' => 'closed'},
    'private' => {'gettext_id' => 'subscribers only'},
    'public'  => {'gettext_id' => 'public'},

##    ## user_data_source
##    'database' => {'gettext_id' => 'RDBMS'},
##    'file'     => {'gettext_id' => 'include from local file'},
##    'include'  => {'gettext_id' => 'include from external source'},
##    'include2' => {'gettext_id' => 'general datasource'},

    # rfc2369_header_fields
    'help'        => {'gettext_id' => 'help'},
    'subscribe'   => {'gettext_id' => 'subscription'},
    'unsubscribe' => {'gettext_id' => 'unsubscription'},
    'post'        => {'gettext_id' => 'posting address'},
    'archive'     => {'gettext_id' => 'list archive'},

    # dkim_signature_apply_on
    'md5_authenticated_messages' =>
444
        {'gettext_id' => 'authenticated by password'},
445
    'smime_authenticated_messages' =>
446
        {'gettext_id' => 'authenticated by S/MIME signature'},
447
    'dkim_authenticated_messages' =>
448
        {'gettext_id' => 'authenticated by DKIM signature'},
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
    'editor_validated_messages' => {'gettext_id' => 'approved by editor'},
    'any'                       => {'gettext_id' => 'any messages'},

    # archive.period
    'day'     => {'gettext_id' => 'daily'},
    'week'    => {'gettext_id' => 'weekly'},
    'month'   => {'gettext_id' => 'monthly'},
    'quarter' => {'gettext_id' => 'quarterly'},
    'year'    => {'gettext_id' => 'yearly'},

    # web_archive_spam_protection
    'cookie' => {'gettext_id' => 'use HTTP cookie'},

    # verp_rate
    '100%' => {'gettext_id' => '100% - always'},
    '0%'   => {'gettext_id' => '0% - never'},

    # archive_crypted_msg
    'original'  => {'gettext_id' => 'original messages'},
    'decrypted' => {'gettext_id' => 'decrypted messages'},
469

470
    # tracking.message_disposition_notification
471
    'on_demand' => {'gettext_id' => 'on demand'},
472
473
474

    # dmarc_protection.mode
    'dkim_signature' => {'gettext_id' => 'DKIM signature exists'},
475
    'dmarc_any'      => {'gettext_id' => 'DMARC policy exists'},
476
    'dmarc_reject'   => {'gettext_id' => 'DMARC policy suggests rejection'},
477
478
479
    'dmarc_quarantine' =>
        {'gettext_id' => 'DMARC policy suggests quarantine'},
    'domain_regex' => {'gettext_id' => 'domain matching regular expression'},
480
481

    # dmarc_protection.phrase
482
483
484
    'display_name'        => {'gettext_id' => 'display name'},
    'name_and_email'      => {'gettext_id' => 'display name and e-mail'},
    'name_via_list'       => {'gettext_id' => 'name "via Mailing List"'},
485
    'name_email_via_list' => {'gettext_id' => 'e-mail "via Mailing List"'},
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
);

## Values for subscriber reception mode.
my %reception_mode = (
    'mail'        => {'gettext_id' => 'standard (direct reception)'},
    'digest'      => {'gettext_id' => 'digest MIME format'},
    'digestplain' => {'gettext_id' => 'digest plain text format'},
    'summary'     => {'gettext_id' => 'summary mode'},
    'notice'      => {'gettext_id' => 'notice mode'},
    'txt'         => {'gettext_id' => 'text-only mode'},
    'html'        => {'gettext_id' => 'html-only mode'},
    'urlize'      => {'gettext_id' => 'urlize mode'},
    'nomail'      => {'gettext_id' => 'no mail'},
    'not_me'      => {'gettext_id' => 'you do not receive your own posts'}
);

## Values for subscriber visibility mode.
my %visibility_mode = (
    'noconceal' => {'gettext_id' => 'listed in the list review page'},
    'conceal'   => {'gettext_id' => 'concealed'}
);

## Values for list status.
my %list_status = (
    'open'          => {'gettext_id' => 'in operation'},
    'pending'       => {'gettext_id' => 'list not yet activated'},
    'error_config'  => {'gettext_id' => 'erroneous configuration'},
    'family_closed' => {'gettext_id' => 'closed family instance'},
    'closed'        => {'gettext_id' => 'closed list'},
);

root's avatar
root committed
517
## This is the generic hash which keeps all lists in memory.
518
my %list_of_lists  = ();
salaun's avatar
salaun committed
519
my %list_of_robots = ();
salaun's avatar
salaun committed
520
521
my %edit_list_conf = ();

root's avatar
root committed
522
523
## Creates an object.
sub new {
524
525
    my ($pkg, $name, $robot, $options) = @_;
    my $list = {};
526
527
    Log::do_log('debug2', '(%s, %s, %s)', $name, $robot,
        join('/', keys %$options));
528

529
530
    ## Allow robot in the name
    if ($name =~ /\@/) {
531
532
533
        my @parts = split /\@/, $name;
        $robot ||= $parts[1];
        $name = $parts[0];
534
    }
root's avatar
root committed
535

536
    ## Look for the list if no robot was provided
sikeda's avatar
sikeda committed
537
    $robot ||= search_list_among_robots($name);
538

539
    unless ($robot) {
540
541
542
543
544
        Log::do_log('err',
            'Missing robot parameter, cannot create list object for %s',
            $name)
            unless ($options->{'just_try'});
        return undef;
545
546
    }

547
548
    $options = {} unless (defined $options);

root's avatar
root committed
549
    ## Only process the list if the name is valid.
550
    my $listname_regexp = Sympa::Regexps::listname();
551
552
553
554
    unless ($name and ($name =~ /^($listname_regexp)$/io)) {
        Log::do_log('err', 'Incorrect listname "%s"', $name)
            unless ($options->{'just_try'});
        return undef;
root's avatar
root committed
555
556
    }
    ## Lowercase the list name.
557
    $name = $1;
root's avatar
root committed
558
    $name =~ tr/A-Z/a-z/;
559

560
    ## Reject listnames with reserved list suffixes
561
562
563
564
565
566
567
568
569
570
    my $regx = Conf::get_robot_conf($robot, 'list_check_regexp');
    if ($regx) {
        if ($name =~ /^(\S+)-($regx)$/) {
            Log::do_log(
                'err',
                'Incorrect name: listname "%s" matches one of service aliases',
                $name
            ) unless ($options->{'just_try'});
            return undef;
        }
571
572
    }

573
    my $status;
574
    ## If list already in memory and not previously purged by another process
575
576
577
578
579
580
581
582
583
584
585
586
587
    if ($list_of_lists{$robot}{$name}
        and -d $list_of_lists{$robot}{$name}{'dir'}) {
        # use the current list in memory and update it
        $list = $list_of_lists{$robot}{$name};

        $status = $list->load($name, $robot, $options);
    } else {
        # create a new object list
        bless $list, $pkg;

        $options->{'first_access'} = 1;
        $status = $list->load($name, $robot, $options);
    }
588
    unless (defined $status) {
589
        return undef;
590
591
592
    }

    ## Config file was loaded or reloaded
593
594
    my $pertinent_ttl = $list->{'admin'}{'distribution_ttl'}
        || $list->{'admin'}{'ttl'};
595
    if ($status
596
597
598
599
600
601
602
603
        && (!$options->{'skip_sync_admin'}
            || (   $options->{'optional_sync_admin'}
                && $list->{'last_sync'} < time - $pertinent_ttl)
            || $options->{'force_sync_admin'}
        )
        ) {
        ## Update admin_table
        unless (defined $list->sync_include_admin()) {
604
            Log::do_log('err', '')
605
606
607
608
609
610
                unless ($options->{'just_try'});
        }
        if (   $list->get_nb_owners() < 1
            && $list->{'admin'}{'status'} ne 'error_config') {
            Log::do_log('err', 'The list "%s" has got no owner defined',
                $list->{'name'});
611
            $list->set_status_error_config('no_owner_defined');
612
        }
root's avatar
root committed
613
614
    }

615
616
617
    return $list;
}

618
619
620
## When no robot is specified, look for a list among robots
sub search_list_among_robots {
    my $listname = shift;
621

622
    unless ($listname) {
623
        Log::do_log('err', 'Missing list parameter');
624
        return undef;
625
    }
626

627
    ## Search in default robot
628
629
    if (-d $Conf::Conf{'home'} . '/' . $listname) {
        return $Conf::Conf{'domain'};
630
    }
631
632
633
634
635
636
637
638

    foreach my $r (keys %{$Conf::Conf{'robots'}}) {
        if (-d $Conf::Conf{'home'} . '/' . $r . '/' . $listname) {
            return $r;
        }
    }

    return 0;
639
640
}

641
642
## set the list in status error_config and send a notify to listmaster
sub set_status_error_config {
643
644
    Log::do_log('debug2', '(%s, %s, ...)', @_);
    my ($self, $msg, @param) = @_;
645

646
647
    unless ($self->{'admin'}
        and $self->{'admin'}{'status'} eq 'error_config') {
648
649
        $self->{'admin'}{'status'} = 'error_config';

650
651
652
653
654
655
656
657
658
        # No more save config in error...
        # $self->save_config(tools::get_address($self->{'domain'},
        #     'listmaster'));
        # $self->savestats();
        Log::do_log('err',
            'The list %s is set in status error_config: %s(%s)',
            $self, $msg, join(', ', @param));
        tools::send_notify_to_listmaster($self, $msg,
            [$self->{'name'}, @param]);
659
660
661
662
663
664
    }
}

## set the list in status family_closed and send a notify to owners
sub set_status_family_closed {
    my ($self, $message, @param) = @_;
665
    Log::do_log('debug2', '');
666
667
668
669
670
671
672
673
674
675
676
677

    unless ($self->{'admin'}{'status'} eq 'family_closed') {

        my $host = Conf::get_robot_conf($self->{'domain'}, 'host');

        unless ($self->close_list("listmaster\@$host", 'family_closed')) {
            Log::do_log('err',
                'Impossible to set the list %s in status family_closed');
            return undef;
        }
        Log::do_log('info', 'The list "%s" is set in status family_closed',
            $self->{'name'});
678
679
        $self->send_notify_to_owner($message, \@param);
        # messages : close_list
680
681
    }
    return 1;
root's avatar
root committed
682
683
684
685
686
}

## Saves the statistics data to disk.
sub savestats {
    my $self = shift;
687
    Log::do_log('debug2', '');
688

root's avatar
root committed
689
690
    ## Be sure the list has been loaded.
    my $name = $self->{'name'};
691
    my $dir  = $self->{'dir'};
692
    return undef unless ($list_of_lists{$self->{'domain'}}{$name});
693
694

    unless (ref($self->{'stats'}) eq 'ARRAY') {
695
        Log::do_log('err', 'Incorrect parameter %s', $self->{'stats'});
696
        return undef;
697
    }
698
699
700
701

    ## Lock file
    my $lock_fh = Sympa::LockedFile->new($dir . '/stats', 2, '>');
    unless ($lock_fh) {
702
703
704
        Log::do_log('err', 'Could not create new lock');
        return undef;
    }
olivier.salaun's avatar
olivier.salaun committed
705

706
    printf $lock_fh "%d %.0f %.0f %.0f %d %d %d\n",
707
708
        @{$self->{'stats'}}, $self->{'total'}, $self->{'last_sync'},
        $self->{'last_sync_admin_user'};
709

olivier.salaun's avatar
olivier.salaun committed
710
    ## Release the lock
711
    unless ($lock_fh->close) {
712
        return undef;
olivier.salaun's avatar
olivier.salaun committed
713
714
    }

root's avatar
root committed
715
    ## Changed on disk
716
    $self->{'_mtime'}{'stats'} = time;
root's avatar
root committed
717
718
719
720

    return 1;
}

721
722
723
## msg count.
sub increment_msg_count {
    my $self = shift;
724
    Log::do_log('debug2', '(%s)', $self->{'name'});
725

726
727
728
    ## Be sure the list has been loaded.
    my $name = $self->{'name'};
    my $file = "$self->{'dir'}/msg_count";
729
730
731
732
733
734
735
736
737

    my %count;
    if (open(MSG_COUNT, $file)) {
        while (<MSG_COUNT>) {
            if ($_ =~ /^(\d+)\s(\d+)$/) {
                $count{$1} = $2;
            }
        }
        close MSG_COUNT;
738
739
740
    }
    my $today = int(time / 86400);
    if ($count{$today}) {
741
742
743
        $count{$today}++;
    } else {
        $count{$today} = 1;
744
    }
745

746
747
    unless (open(MSG_COUNT, ">$file.$PID")) {
        Log::do_log('err', 'Unable to create "%s.%s": %m', $file, $PID);
748
        return undef;
749
    }
750
751
    foreach my $key (sort { $a <=> $b } keys %count) {
        printf MSG_COUNT "%d\t%d\n", $key, $count{$key};
752
    }
753
754
    close MSG_COUNT;

755
756
    unless (rename("$file.$PID", $file)) {
        Log::do_log('err', 'Unable to write "%s": %m', $file);
757
        return undef;
758
759
760
761
    }
    return 1;
}

762
763
764
# Returns the number of messages sent to the list
sub get_msg_count {
    my $self = shift;
765
766
    Log::do_log('debug3', "Getting the number of messages for list %s",
        $self->{'name'});
767
768
769
770

    ## Be sure the list has been loaded.
    my $name = $self->{'name'};
    my $file = "$self->{'dir'}/stats";
771
772
773
774
775
776
777
778
779

    my $count = 0;
    if (open(MSG_COUNT, $file)) {
        while (<MSG_COUNT>) {
            if ($_ =~ /^(\d+)\s+(.*)$/) {
                $count = $1;
            }
        }
        close MSG_COUNT;
780
781
782
783
784
    }

    return $count;

}
785
786
787
## last date of distribution message .
sub get_latest_distribution_date {
    my $self = shift;
788
    Log::do_log('debug3', '(%s)', $self->{'name'});
789

790
791
792
    ## Be sure the list has been loaded.
    my $name = $self->{'name'};
    my $file = "$self->{'dir'}/msg_count";
793
794
795

    my %count;
    my $latest_date = 0;
salaun's avatar
salaun committed
796
    unless (open(MSG_COUNT, $file)) {
797
        Log::do_log('debug2', 'Unable to open %s', $file);
798
        return undef;
salaun's avatar
salaun committed
799
    }
800

801
802
803
804
    while (<MSG_COUNT>) {
        if ($_ =~ /^(\d+)\s(\d+)$/) {
            $latest_date = $1 if ($1 > $latest_date);
        }
805
    }
806
    close MSG_COUNT;
807

808
809
    return undef if ($latest_date == 0);
    return $latest_date;
810
811
}

812
## Update the stats struct
root's avatar
root committed
813
814
815
## Input  : num of bytes of msg
## Output : num of msgs sent
sub update_stats {
816
    my ($self, $bytes) = @_;
817
    Log::do_log('debug2', '(%d)', $bytes);
root's avatar
root committed
818
819
820
821
822
823

    my $stats = $self->{'stats'};
    $stats->[0]++;
    $stats->[1] += $self->{'total'};
    $stats->[2] += $bytes;
    $stats->[3] += $bytes * $self->{'total'};
824
825
826
827

    ## Update 'msg_count' file, used for bounces management
    $self->increment_msg_count();

root's avatar
root committed
828
829
830
    return $stats->[0];
}

831
832
833
834
835
836
837
838
# Extract a set of rcpt for which VERP must be use from a rcpt_tab.
# Input  :  percent : the rate of subscribers that must be threaded using VERP
#           xseq    : the message sequence number
#           @rcpt   : a tab of emails
# return :  a tab of recipients for which recipients must be used depending on
#           the message sequence number, this way every subscriber is "VERPed"
#           from time to time input table @rcpt is spliced: recipients for
#           which VERP must be used are extracted from this table
839
sub extract_verp_rcpt {
840
841
842
    my $percent     = shift;
    my $xseq        = shift;
    my $refrcpt     = shift;
843
844
    my $refrcptverp = shift;

845
846
    Log::do_log('debug', '(%s, %s, %s, %s)',
        $percent, $xseq, $refrcpt, $refrcptverp);
847

848
    my @result;
849

850
    if ($percent ne '0%') {
851
852
853
854
        my $nbpart;
        if ($percent =~ /^(\d+)\%/) {
            $nbpart = 100 / $1;
        } else {
855
856
857
            Log::do_log('err',
                'Wrong format for parameter: %s. Can\'t process VERP',
                $percent);
858
859
860
861
862
863
864
            return undef;
        }

        my $modulo = $xseq % $nbpart;
        my $lenght = int(($#{$refrcpt} + 1) / $nbpart) + 1;

        @result = splice @$refrcpt, $lenght * $modulo, $lenght;
865
    }
866
    foreach my $verprcpt (@$refrcptverp) {
867
        push @result, $verprcpt;
868
    }
869
    return (@result);
870
871
}

root's avatar
root committed
872
873
## Dumps a copy of lists to disk, in text format
sub dump {
874
    my $self = shift;
875
    Log::do_log('debug2', '(%s)', $self->{'name'});
876

877
    unless (defined $self) {
878
879
        Log::do_log('err', 'Unknown list');
        return undef;
880
    }
881

882
    my $user_file_name = "$self->{'dir'}/subscribers.db.dump";
883

884
    unless ($self->_save_list_members_file($user_file_name)) {
885
886
        Log::do_log('err', 'Failed to save file %s', $user_file_name);
        return undef;
root's avatar
root committed
887
    }
888

889
    # Note: "subscribers" file was deprecated.
890
    $self->{'_mtime'} = {
891
892
        'config' => Sympa::Tools::File::get_mtime($self->{'dir'} . '/config'),
        'stats'  => Sympa::Tools::File::get_mtime($self->{'dir'} . '/stats'),
893
    };
894
895

    return 1;
root's avatar
root committed
896
897
898
899
900
}

## Saves the configuration file to disk
sub save_config {
    my ($self, $email) = @_;
901
    Log::do_log('debug3', '(%s, %s)', $self->{'name'}, $email);
root's avatar
root committed
902

903
904
    return undef
        unless ($self);
905
906
907
908

    my $config_file_name = "$self->{'dir'}/config";

    ## Lock file
909
910
    my $lock_fh = Sympa::LockedFile->new($config_file_name, 5, '+<');
    unless ($lock_fh) {
911
912
        Log::do_log('err', 'Could not create new lock');
        return undef;
913
914
    }

915
916
    my $name                 = $self->{'name'};
    my $old_serial           = $self->{'admin'}{'serial'};
salaun's avatar
salaun committed
917
    my $old_config_file_name = "$self->{'dir'}/config.$old_serial";
root's avatar
root committed
918
919
920

    ## Update management info
    $self->{'admin'}{'serial'}++;
921
    $self->{'admin'}{'update'} = {
922
923
924
925
926
927
        'email'      => $email,
        'date_epoch' => time,
        'date'       => $language->gettext_strftime(
            "%d %b %Y at %H:%M:%S",
            localtime time
        ),
928
    };
929

930
931
932
933
934
    unless (
        $self->_save_list_config_file(
            $config_file_name, $old_config_file_name
        )
        ) {
935
        Log::do_log('info', 'Unable to save config file %s',
936
937
938
            $config_file_name);
        $lock_fh->close();
        return undef;
root's avatar
root committed
939
    }
940

941
    ## Also update the binary version of the data structure
942
943
944
    if (Conf::get_robot_conf($self->{'domain'}, 'cache_list_config') eq
        'binary_file') {
        eval {
945
            Storable::store($self->{'admin'}, "$self->{'dir'}/config.bin");
946
947
948
949
950
951
        };
        if ($@) {
            Log::do_log('err',
                'Failed to save the binary config %s. error: %s',
                "$self->{'dir'}/config.bin", $@);
        }
952
953
    }

954
    ## Release the lock
955
    unless ($lock_fh->close()) {
956
        return undef;
957
958
    }

959
    if ($SDM::use_db) {
sikeda's avatar
sikeda committed
960
        unless ($self->_update_list_db) {
sikeda's avatar
sikeda committed
961
            Log::do_log('err', "Unable to update list_table");
962
963
964
        }
    }

root's avatar
root committed
965
966
967
968
969
    return 1;
}

## Loads the administrative data for a list
sub load {
970
    my ($self, $name, $robot, $options) = @_;
971
972
    Log::do_log('debug2', '(%s, %s, %s)', $name, $robot,
        join('/', keys %$options));
973

974
975
976
    ## Set of initializations ; only performed when the config is first loaded
    if ($options->{'first_access'}) {

977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
        ## Search robot if none was provided
        unless ($robot) {
            foreach my $r (keys %{$Conf::Conf{'robots'}}) {
                if (-d "$Conf::Conf{'home'}/$r/$name") {
                    $robot = $r;
                    last;
                }
            }

            ## Try default robot
            unless ($robot) {
                if (-d "$Conf::Conf{'home'}/$name") {
                    $robot = $Conf::Conf{'domain'};
                }
            }
        }

        if ($robot && (-d "$Conf::Conf{'home'}/$robot")) {
            $self->{'dir'} = "$Conf::Conf{'home'}/$robot/$name";
        } elsif (lc($robot) eq lc($Conf::Conf{'domain'})) {
            $self->{'dir'} = "$Conf::Conf{'home'}/$name";
        } else {
            Log::do_log('err', 'No such robot (virtual domain) %s', $robot)
                unless ($options->{'just_try'});
            return undef;
        }

        $self->{'domain'} = $robot;

        # default list host is robot domain
        $self->{'admin'}{'host'} ||= $self->{'domain'};
        $self->{'name'} = $name;
1009
    }
1010

1011
    unless ((-d $self->{'dir'}) && (-f "$self->{'dir'}/config")) {
1012
1013
1014
1015
        Log::do_log('debug2', 'Missing directory (%s) or config file for %s',
            $self->{'dir'}, $name)
            unless ($options->{'just_try'});
        return undef;
1016
    }
salaun's avatar
salaun committed
1017

1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
    # Last modification of list config ($last_time_config) and stats
    # ($last_time_stats) on memory cache.
    # Note: "subscribers" file was deprecated.
    my ($last_time_config, $last_time_stats);
    if ($self->{'_mtime'}) {
        $last_time_config = $self->{'_mtime'}{'config'};
        $last_time_stats  = $self->{'_mtime'}{'stats'};
    } else {
        $last_time_config = POSIX::INT_MIN();
        $last_time_stats  = POSIX::INT_MIN();
    }
1029

1030
1031
1032
1033
1034
1035
1036
    my $time_config = Sympa::Tools::File::get_mtime("$self->{'dir'}/config");
    my $time_config_bin =
        Sympa::Tools::File::get_mtime("$self->{'dir'}/config.bin");
    my $time_stats = Sympa::Tools::File::get_mtime("$self->{'dir'}/stats");
    my $main_config_time =
        Sympa::Tools::File::get_mtime(Sympa::Constants::CONFIG);
    # my $web_config_time  = Sympa::Tools::File::get_mtime(Sympa::Constants::WWSCONFIG);
1037
    my $config_reloaded = 0;
root's avatar
root committed
1038
    my $admin;
1039
1040

    if (Conf::get_robot_conf($self->{'domain'}, 'cache_list_config') eq
1041
1042
            'binary_file'
        and !$options->{'reload_config'}
1043
        and $time_config_bin > $last_time_config
1044
1045
        and $time_config_bin >= $time_config
        and $time_config_bin >= $main_config_time) {
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
        ## Get a shared lock on config file first
        my $lock_fh =
            Sympa::LockedFile->new($self->{'dir'} . '/config', 5, '<');
        unless ($lock_fh) {
            Log::do_log('err', 'Could not create new lock');
            return undef;
        }

        ## Load a binary version of the data structure
        ## unless config is more recent than config.bin
1056
        eval { $admin = Storable::retrieve("$self->{'dir'}/config.bin") };
1057
1058
1059
1060
1061
1062
1063
1064
        if ($@) {
            Log::do_log('err',
                'Failed to load the binary config %s, error: %s',
                "$self->{'dir'}/config.bin", $@);
            $lock_fh->close();
            return undef;
        }

1065
1066
        $config_reloaded  = 1;
        $last_time_config = $time_config_bin;
1067
        $lock_fh->close();
1068
    } elsif ($self->{'name'} ne $name
1069
        or $time_config > $last_time_config
1070
        or $options->{'reload_config'}) {
1071
        $admin =
sikeda's avatar
sikeda committed
1072
1073
            _load_list_config_file($self->{'dir'}, $self->{'domain'},
            'config');
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085

        ## Get a shared lock on config file first
        my $lock_fh =
            Sympa::LockedFile->new($self->{'dir'} . '/config', 5, '+<');
        unless ($lock_fh) {
            Log::do_log('err', 'Could not create new lock');
            return undef;
        }

        ## update the binary version of the data structure
        if (Conf::get_robot_conf($self->{'domain'}, 'cache_list_config') eq
            'binary_file') {
1086
            eval { Storable::store($admin, "$self->{'dir'}/config.bin") };
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
            if ($@) {
                Log::do_log('err',
                    'Failed to save the binary config %s. error: %s',
                    "$self->{'dir'}/config.bin", $@);
            }
        }

        $config_reloaded = 1;
        unless (defined $admin) {
            Log::do_log(
                'err',
                'Impossible to load list config file for list % set in status error_config',
                $self->{'name'}
            );
1101
            $self->set_status_error_config('load_admin_file_error');
1102
1103
1104
1105
            $lock_fh->close();
            return undef;
        }

1106
        $last_time_config = $time_config;
1107
        $lock_fh->close();
root's avatar
root committed
1108
    }
1109

1110
1111
    ## If config was reloaded...
    if ($admin) {
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
        $self->{'admin'} = $admin;

        ## check param_constraint.conf if belongs to a family and the config
        ## has been loaded
        if (defined $admin->{'family_name'}
            && ($admin->{'status'} ne 'error_config')) {
            my $family;
            unless ($family = $self->get_family()) {
                Log::do_log(
                    'err',
1122
                    'Impossible to get list %s family: %s. The list is set in status error_config',
1123
                    $self,
1124
1125
1126
                    $self->{'admin'}{'family_name'}
                );
                $self->set_status_error_config('no_list_family',
1127
                    $self->{'admin'}{'family_name'});
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
                return undef;
            }
            my $error = $family->check_param_constraint($self);
            unless ($error) {
                Log::do_log(
                    'err',
                    'Impossible to check parameters constraint for list % set in status error_config',
                    $self->{'name'}
                );
                $self->set_status_error_config('no_check_rules_family',
1138
                    $family->{'name'});
1139
1140
1141
1142
1143
1144
1145
1146
1147
            }
            if (ref($error) eq 'ARRAY') {
                Log::do_log(
                    'err',
                    'The list "%s" does not respect the rules from its family %s',
                    $self->{'name'},
                    $family->{'name'}
                );
                $self->set_status_error_config('no_respect_rules_family',
1148
                    $family->{'name'});
1149
1150
1151
1152
1153
1154
1155
1156
1157
            }
        }
    }

    $self->{'as_x509_cert'} = 1
        if ((-r "$self->{'dir'}/cert.pem")
        || (-r "$self->{'dir'}/cert.pem.enc"));

    ## Load stats file if first new() or stats file changed
1158
    my ($stats, $total);
1159
1160
    my $stats_file = $self->{'dir'} . '/stats';
    if (!-e $stats_file or $time_stats > $last_time_stats) {
1161
1162
        (   $stats, $total, $self->{'last_sync'},
            $self->{'last_sync_admin_user'}
1163
1164
        ) = _load_stats_file($stats_file);
        $last_time_stats = $time_stats;
1165

1166
1167
        $self->{'stats'} = $stats if (defined $stats);
        $self->{'total'} = $total if (defined $total);
1168
    }
1169

1170
1171
1172
1173
    $self->{'_mtime'} = {
        'config' => $last_time_config,
        'stats'  => $last_time_stats,
    };
root's avatar
root committed
1174

1175
    $list_of_lists{$self->{'domain'}}{$name} = $self;
1176
    return $config_reloaded;
root's avatar
root committed
1177
1178
}

1179
## Return a list of hash's owners and their param
1180
sub get_owners {
1181
    my ($self) = @_;
1182
    Log::do_log('debug3', '(%s)', $self->{'name'});
1183

1184
1185
    my $owners = ();

1186
1187
1188
1189
1190
1191
1192
1193
1194
    # owners are in the admin_table ; they might come from an include data
    # source
    for (
        my $owner = $self->get_first_list_admin('owner');
        $owner;
        $owner = $self->get_next_list_admin()
        ) {
        push(@{$owners}, $owner);
    }
1195
1196
1197
1198
1199

    return $owners;
}

sub get_nb_owners {
1200
    my ($self) = @_;
1201
    Log::do_log('debug3', '(%s)', $self->{'name'});
1202
1203

    my $resul  = 0;
1204
1205
1206
    my $owners = $self->get_owners;

    if (defined $owners) {
1207
        $resul = $#{$owners} + 1;
1208
1209
1210
1211
    }
    return $resul;
}

1212
1213
## Return a hash of list's editors and their param(empty if there isn't any
## editor)
1214
sub get_editors {
1215
    my ($self) = @_;
1216
    Log::do_log('debug3', '(%s)', $self->{'name'});
1217

1218
1219
    my $editors = ();

1220
1221
1222
1223
1224
1225
1226
1227
1228
    # editors are in the admin_table ; they might come from an include data
    # source
    for (
        my $editor = $self->get_first_list_admin('editor');
        $editor;
        $editor = $self->get_next_list_admin()
        ) {
        push(@{$editors}, $editor);
    }
1229
1230
1231
1232

    return $editors;
}

1233
## Returns an array of owners' email addresses
salaun's avatar
salaun committed
1234
sub get_owners_email {
1235
    my ($self, $param) = @_;
1236
1237
    Log::do_log('debug3', '(%s, %s)', $self->{'name'},
        $param->{'ignore_nomail'});
1238

1239
1240
    my @rcpt;
    my $owners = ();
salaun's avatar
salaun committed
1241

1242
    $owners = $self->get_owners();
1243

1244
1245
1246
1247
1248
1249
1250
1251
1252
    if ($param->{'ignore_nomail'}) {
        foreach my $o (@{$owners}) {
            push(@rcpt, lc($o->{'email'}));
        }
    } else {
        foreach my $o (@{$owners}) {
            next if ($o->{'reception'} eq 'nomail');
            push(@rcpt, lc($o->{'email'}));
        }
1253
1254
    }
    unless (@rcpt) {
1255
        Log::do_log('notice', 'Warning: No owner found for list %s',
1256
            $self->{'name'});
1257
    }
1258
1259
1260
    return @rcpt;
}

1261
## Returns an array of editors' email addresses
1262
#  o