List.pm 402 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
10
#
# 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
# Copyright (c) 2011, 2012, 2013, 2014 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
26
27

package List;

use strict;
28
use warnings;
29
30
31
use Digest::MD5 qw();
use Encode qw();
use HTTP::Request;
32
use IO::Scalar;
33
34
use Mail::Address;
use MIME::Charset;
35
36
use MIME::EncWords;
use MIME::Parser;
sikeda's avatar
sikeda committed
37
use POSIX qw();
38
use Storable qw();
sikeda's avatar
sikeda committed
39
use Time::Local qw();
40
use XML::LibXML;
41

42
use Archive;
43
use Auth;
44
45
use Conf;
use Sympa::Constants;
46
use Datasource;
47
use Family;
48
use Fetch;
49
use Sympa::Language;
50
use LDAPSource;
51
use Sympa::ListDef;
52
use Sympa::LockedFile;
53
54
55
56
use Log;
use mail;
use Message;
use PlainDigest;
57
58
59
60
61
62
use Sympa::Regexps;
use Scenario;
use SDM;
use SQLSource;
use Task;
use tools;
63
use tracking;
64
use tt2;
65
66
use Sympa::User;
use WebAgent;
67

68
my @sources_providing_listmembers = qw/
69
70
71
72
73
74
75
76
77
78
    include_file
    include_ldap_2level_query
    include_ldap_query
    include_list
    include_remote_file
    include_remote_sympa_list
    include_sql_query
    /;

#XXX include_admin
79
my @more_data_sources = qw/
80
81
82
    editor_include
    owner_include
    /;
83
84

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

88
89
90
91
92
# Language context
my $language = Sympa::Language->instance;

=encoding utf-8

root's avatar
root committed
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
=head1 CONSTRUCTOR

=item new( [PHRASE] )

 List->new();

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.

=item send_to_editor ( MSG )
131
    
root's avatar
root committed
132
133
134
135
136
137
138
139
140
141
Send a Mail::Internet type object to the editor (for approval).

=item send_msg ( MSG )

Sends the Mail::Internet message to the list.

=item send_file ( FILE, USER, GECOS )

Sends the file to the USER. FILE may only be welcome for now.

142
=item delete_list_member ( ARRAY )
root's avatar
root committed
143
144
145

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

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

root's avatar
root committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
=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.

170

171
=item get_global_user ( USER )
root's avatar
root committed
172

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

176
=item get_list_member ( USER )
177
178

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

180
=item get_list_admin ( ROLE, USER)
181
182
183

Return an admin user of the list with predefined role

184
=item get_first_list_member ()
root's avatar
root committed
185
186
187

Returns a hash to the first user on the list.

188
=item get_first_list_admin ( ROLE )
189

190
Returns a hash to the first admin user with predefined role on the list.
191

192
=item get_next_list_member ()
root's avatar
root committed
193
194
195
196

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

197
=item get_next_list_admin ()
198
199
200
201

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

202
=item update_list_member ( USER, HASHPTR )
root's avatar
root committed
203
204
205

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

206
=item update_list_admin ( USER, ROLE, HASHPTR )
207
208
209

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

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

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

215
216
217
218
219
=item add_admin_user ( USER, ROLE, HASHPTR )

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

220
=item is_list_member ( USER )
root's avatar
root committed
221
222
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
266
267
268
269
270

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.

=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 )

271
Print the list information to the given file descriptor, or the
root's avatar
root committed
272
273
274
275
276
currently selected descriptor.

=cut

## Database and SQL statement handlers
277
my ($sth, @sth_stack);
278
279
280

my %list_cache;

281
282
## DB fields with numeric type
## We should not do quote() for these while inserting data
283
284
285
286
287
288
289
290
291
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
292

293
294
295
296
297
298
299
300
301
302
303
304
305
306
## 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,
307
    # include_ldap_query.select, reply_to_header.value, dmarc_protection.mode
308
309
310
311
312
313
314
315
316
317
318
319
    '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,
320
321
    # spam_protection, dkim_signature_apply_on, web_archive_spam_protection,
    # dmarc_protection.mode
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
    'none' => {'gettext_id' => 'do nothing'},

    # bouncers_level2.notification, bouncers_level1.notification,
    # welcome_return_path, remind_return_path, rfc2369_header_fields,
    # archive.access
    '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,
337
338
    # inclusion_notification_feature, tracking.delivery_status_notification,
    # tracking.message_delivery_notification
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
    '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' =>
396
        {'gettext_id' => 'required to distribute message'},
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

    # 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'},

    # archive.access
    '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' =>
435
        {'gettext_id' => 'authenticated by password'},
436
    'smime_authenticated_messages' =>
437
        {'gettext_id' => 'authenticated by S/MIME signature'},
438
    'dkim_authenticated_messages' =>
439
        {'gettext_id' => 'authenticated by DKIM signature'},
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
    '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'},
460
461
462

    # tracking.message_delivery_notification
    'on_demand' => {'gettext_id' => 'on demand'},
463
464
465

    # dmarc_protection.mode
    'dkim_signature' => {'gettext_id' => 'DKIM signature exists'},
466
    'dmarc_any'      => {'gettext_id' => 'DMARC policy exists'},
467
    'dmarc_reject'   => {'gettext_id' => 'DMARC policy suggests rejection'},
468
469
470
    'dmarc_quarantine' =>
        {'gettext_id' => 'DMARC policy suggests quarantine'},
    'domain_regex' => {'gettext_id' => 'domain matching regular expression'},
471
472

    # dmarc_protection.phrase
473
474
475
    '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"'},
476
    'name_email_via_list' => {'gettext_id' => 'e-mail "via Mailing List"'},
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
);

## 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
508
## This is the generic hash which keeps all lists in memory.
509
my %list_of_lists  = ();
salaun's avatar
salaun committed
510
my %list_of_robots = ();
511
our %list_of_topics = ();
salaun's avatar
salaun committed
512
513
514
515
my %edit_list_conf = ();

## Last modification times
my %mtime;
root's avatar
root committed
516
517

use DB_File;
518
$DB_BTREE->{compare} = \&_compare_addresses;
root's avatar
root committed
519

520
521
our %listmaster_messages_stack;

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
595
596
597
598
599
600
601
602
603
    my $pertinent_ttl = $list->{'admin'}{'distribution_ttl'}
        || $list->{'admin'}{'ttl'};
    if ($status == 1
        && (!$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
611
612
613
                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'});
            $list->set_status_error_config('no_owner_defined',
                $list->{'name'});
        }
root's avatar
root committed
614
615
    }

616
617
618
    return $list;
}

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

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

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

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

    return 0;
640
641
}

642
643
644
## set the list in status error_config and send a notify to listmaster
sub set_status_error_config {
    my ($self, $message, @param) = @_;
645
    Log::do_log('debug3', '');
646

647
648
649
650
651
652
653
654
655
    unless ($self->{'admin'}{'status'} eq 'error_config') {
        $self->{'admin'}{'status'} = 'error_config';

        #my $host = Conf::get_robot_conf($self->{'domain'}, 'host');
        ## No more save config in error...
        #$self->save_config("listmaster\@$host");
        #$self->savestats();
        Log::do_log('err', 'The list "%s" is set in status error_config',
            $self->{'name'});
656
        List::send_notify_to_listmaster($message, $self->{'domain'}, \@param);
657
658
659
660
661
662
    }
}

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

    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'});
676
677
        $self->send_notify_to_owner($message, \@param);
        # messages : close_list
678
679
    }
    return 1;
root's avatar
root committed
680
681
682
683
684
}

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

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

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

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

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

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

root's avatar
root committed
713
714
715
716
717
718
    ## Changed on disk
    $self->{'mtime'}[2] = time;

    return 1;
}

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

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

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

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

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

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

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

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

    return $count;

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

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

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

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

806
807
    return undef if ($latest_date == 0);
    return $latest_date;
808
809
}

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

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

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

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

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

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

847
    my @result;
848

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

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

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

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

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

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

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

890
    # Note: "subscribers" file was deprecated.
891
    $self->{'mtime'} = [
892
893
894
        tools::get_mtime("$self->{'dir'}/config"),
        undef,    # subscribers
        tools::get_mtime("$self->{'dir'}/stats")
895
    ];
896
897

    return 1;
root's avatar
root committed
898
899
900
901
902
}

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

905
906
    return undef
        unless ($self);
907
908
909
910

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

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

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

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

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

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

956
#    $self->{'mtime'}[0] = tools::get_mtime("$list->{'dir'}/config");
957

958
    ## Release the lock
959
    unless ($lock_fh->close()) {
960
        return undef;
961
962
    }

963
    if ($SDM::use_db) {
sikeda's avatar
sikeda committed
964
965
        unless (_update_list_db()) {
            Log::do_log('err', "Unable to update list_table");
966
967
968
        }
    }

root's avatar
root committed
969
970
971
972
973
    return 1;
}

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

salaun's avatar
salaun committed
978
    my $users;
979

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

983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        ## 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")) {