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

# Sympa - SYsteme de Multi-Postage Automatique
#
IKEDA Soji's avatar
IKEDA Soji committed
7
8
# Copyright 2018, 2019, 2020 The Sympa Community. See the AUTHORS.md
# file at the top-level directory of this distribution and at
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# <https://github.com/sympa-community/sympa.git>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

package Sympa::Spindle::ProcessTask;

use strict;
use warnings;
use English qw(-no_match_vars);

use Sympa;
use Conf;
use Sympa::DatabaseManager;
use Sympa::List;
use Sympa::Log;
use Sympa::Scenario;
use Sympa::Spool;
37
use Sympa::Spool::Listmaster;
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use Sympa::Task;
use Sympa::Ticket;
use Sympa::Tools::File;
use Sympa::Tools::Time;
use Sympa::Tools::Text;
use Sympa::Tracking;
use Sympa::User;

use base qw(Sympa::Spindle);

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

use constant _distaff => 'Sympa::Spool::Task';

sub _init {
    my $self  = shift;
    my $state = shift;

    if ($state == 1) {
        # Process grouped notifications.
58
        Sympa::Spool::Listmaster->instance->flush;
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
    }

    1;
}

sub _twist {
    my $self = shift;
    my $task = shift;

    my $that = $task->{context};
    if (ref $that eq 'Sympa::List' and $that->{'admin'}{'status'} ne 'open') {
        # Skip closed lists: Remove task.
        return 1;
    }

    return _execute($self, $task);
}

### TASK EXECUTION SUBROUTINES ###

my %comm = (
    stop                        => 'do_stop',
    next                        => 'do_next',
    create                      => 'do_create',
    exec                        => 'do_exec',
    expire_bounce               => 'do_expire_bounce',
    purge_user_table            => 'do_purge_user_table',
    purge_logs_table            => 'do_purge_logs_table',
    purge_session_table         => 'do_purge_session_table',
    purge_spools                => 'do_purge_spools',
    purge_tables                => 'do_purge_tables',
    purge_one_time_ticket_table => 'do_purge_one_time_ticket_table',
    sync_include                => 'do_sync_include',
    purge_orphan_bounces        => 'do_purge_orphan_bounces',
    eval_bouncers               => 'do_eval_bouncers',
    process_bouncers            => 'do_process_bouncers',

    # commands which use a variable
    send_msg => 'do_send_msg',
    rm_file  => 'do_rm_file',

    # commands which return a variable
    select_subs => 'do_select_subs',

    # commands which return and use a variable
    delete_subs => 'do_delete_subs',
);

# Old name: execute() in task_manager.pl.
sub _execute {
    my $self = shift;
    my $task = shift;

    $log->syslog('notice', 'Running task %s', $task);

    die 'bug in logic. Ask developer' unless $task->{_parsed};

    my %vars;    # list of task vars
    my @lines = $task->lines;

    my $label = $task->{label};
    return undef if $label eq 'ERROR';

    if (defined $label and length $label) {
        my $line;
        while ($line = shift @lines) {
            next unless defined $line->{label};
            last if $line->{label} eq $label;
        }
    }

    # Execution.
    my $status;
    foreach my $line (@lines) {
        if ($line->{nature} eq 'assignment') {
            # Processing of the assignments.
            $status = $vars{$line->{var}} =
                _cmd_process($self, $task, $line, \%vars);
            last if not defined $status;
        } elsif ($line->{nature} eq 'command') {
            # Processing of the commands.
            $status = _cmd_process($self, $task, $line, \%vars);
            last if not defined $status or $status < 0;
        }
    }

    if (not defined $status) {
        $log->syslog('err', 'Error while processing task %s', $task);
        # Remove task.
        return undef;
    } elsif ($status < 0) {
        $log->syslog('notice', 'The task %s is now useless. Removing it',
            $task);
        # Remove task.
        return 1;
    } else {
        # Keep task.
        return 0;
    }
}

# Old name: cmd_process() in task_manager.pl.
sub _cmd_process {
    $log->syslog('debug2', '(%s, %s, %s, %s, %s, %s)', @_);
    my $self  = shift;
    my $task  = shift;
    my $line  = shift;
    my $Rvars = shift;    # variable list of the task

    my $command = $line->{command};    # command name

    unless (defined $comm{$command}) {
        return undef;
    } else {
        no strict 'refs';
        return $comm{$command}->($self, $task, $line, $Rvars);
    }
}

### command subroutines ###

# remove files whose name is given in the key 'file' of the hash
# Old name: rm_file() in task_manager.pl.
sub do_rm_file {
    my $self  = shift;
    my $task  = shift;
    my $line  = shift;
    my $Rvars = shift;

    my @tab = @{$line->{Rarguments} || []};
    my $var = $tab[0];

    foreach my $key (keys %{$Rvars->{$var}}) {
        my $file = $Rvars->{$var}{$key}{'file'};
        next unless $file;
        unless (unlink $file) {
            _error($task,
                "error in rm_file command : unable to remove $file");
            return undef;
        }
    }

    return 1;
}

# Old name: stop() in task_manager.pl.
sub do_stop {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    $log->syslog('notice', '%s: stop %s', $line->{line}, $task);
    return -1;    # Remove task.
}

# Old name: send_msg() in task_manager.pl.
sub do_send_msg {
    my $self  = shift;
    my $task  = shift;
    my $line  = shift;
    my $Rvars = shift;

    my @tab      = @{$line->{Rarguments} || []};
    my $template = $tab[1];
    my $var      = $tab[0];

    $log->syslog('notice', 'Line %s: send_msg (%s)',
        $line->{line}, join(',', @tab));

    foreach my $email (keys %{$Rvars->{$var}}) {
        $log->syslog('notice', '--> message sent to %s', $email);
        unless (
            Sympa::send_file(
                $task->{context}, $template,
                $email,           $Rvars->{$var}{$email}
            )
        ) {
            $log->syslog('notice', 'Unable to send template %s to %s',
                $template, $email);
        }
    }

    return 1;
}

# Old name: next_cmd() in task_manager.pl.
sub do_next {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    my @tab = @{$line->{Rarguments} || []};
    # conversion of the date argument into epoch format
    my $date  = Sympa::Tools::Time::epoch_conv($tab[0]);
    my $label = $tab[1];

    $log->syslog('notice', 'line %s of %s: next(%s, %s)',
        $line->{line}, $task->{model}, $date, $label);

    my $new_task = Sympa::Task->new(
        context => $task->{context},
        date    => $date,
        label   => $label,
        model   => $task->{model},
    );
    unless ($new_task and $self->{distaff}->store($new_task)) {
        _error($task,
            "error in create command : creation subroutine failure");
        return undef;
    }

    $log->syslog('notice', '--> new task %s', $new_task);

    return -1;    # Remove older task.
}

# Old name: select_subs() in task_manager.pl.
sub do_select_subs {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    my @tab = @{$line->{Rarguments} || []};
    my $condition = $tab[0];
    $log->syslog('debug2', 'Line %s: select_subs (%s)',
        $line->{line}, $condition);
285
286
287
288
289
290
291
292
293

    my ($func, $date);
    if ($condition =~ /(older|newer)[(]([^\)]*)[)]/) {
        ($func, $date) = ($1, $2);
        # Conversion of the date argument into epoch format.
        $date = Sympa::Tools::Time::epoch_conv($date);
    } else {
        $log->syslog('err', 'Illegal condition %s', $condition);
        return {};
294
295
    }

296
    my %selection;
297
    my $list = $task->{context};
298
299
300
301
302
    unless (ref $list eq 'Sympa::List') {
        $log->syslog('err', 'No list');
        return {};
    }

303
304
305
306
307
    for (
        my $user = $list->get_first_list_member();
        $user;
        $user = $list->get_next_list_member()
    ) {
308
309
        if (   $func eq 'newer' and $date < $user->{update_date}
            or $func eq 'older' and $user->{update_date} < $date) {
310
            $selection{$user->{'email'}} = undef;
311
            $log->syslog('info', '--> user %s has been selected',
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
                $user->{'email'});
        }
    }

    return \%selection;
}

# Old name: delete_subs_cmd() in task_manager.pl.
# Not yet used.
sub do_delete_subs {
    my $self  = shift;
    my $task  = shift;
    my $line  = shift;
    my $Rvars = shift;

    my @tab = @{$line->{Rarguments} || []};
    my $var = $tab[0];

    $log->syslog('notice', 'Line %s: delete_subs (%s)', $line->{line}, $var);

    my $list = $task->{context};
333
334
335
336
337
    unless (ref $list eq 'Sympa::List') {
        $log->syslog('err', 'No list');
        return {};
    }

338
339
340
341
    my %selection;    # hash of subscriber emails who are successfully deleted

    foreach my $email (keys %{$Rvars->{$var}}) {
        $log->syslog('notice', '%s', $email);
IKEDA Soji's avatar
IKEDA Soji committed
342
343
        my $result = Sympa::Scenario->new($list, 'del')->authz(
            'smime',
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
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
759
760
761
762
763
764
765
            {   'sender' => $Conf::Conf{'listmaster'},    #FIXME
                'email'  => $email,
            }
        );
        my $action;
        $action = $result->{'action'} if (ref($result) eq 'HASH');
        if ($action =~ /reject/i) {
            #FIXME
            _error($task,
                "error in delete_subs command : deletion of $email not allowed"
            );
        } else {
            my $u = $list->delete_list_member(
                users     => [$email],
                operation => 'auto_del'
            );
            $log->syslog('notice', '--> %s deleted', $email);
            $selection{$email} = {};
        }
    }

    return \%selection;
}

my $subarg_regexp = '(\w+)(|\((.*)\))';

# Old name: create_cmd() in task_manager.pl.
sub do_create {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    my @tab          = @{$line->{Rarguments} || []};
    my $arg          = $tab[0];
    my $model        = $tab[1];
    my $model_choice = $tab[2];

    $log->syslog('notice', 'line %s: create(%s, %s, %s)',
        $line->{line}, $arg, $model, $model_choice);

    # recovery of the object type and object
    my $that;
    if ($arg =~ /$subarg_regexp/) {
        my $type   = $1;
        my $object = $3;

        if ($type eq 'list') {
            my ($name, $robot) = split /\@/, $object, 2;
            $that = Sympa::List->new($name, $robot, {just_try => 1});
        } else {
            $that = '*';
        }
    }
    unless ($that) {
        _error($task,
            "error in create command : don't know how to create $arg");
        return undef;
    }

    my $new_task = Sympa::Task->new(
        context => $that,
        date    => $task->{date},
        model   => $model
    );
    unless ($new_task and $self->{distaff}->store($new_task)) {
        _error($task,
            "error in create command : creation subroutine failure");
        return undef;
    }

    return 1;
}

# Old name: exec_cmd() in task_manager.pl.
sub do_exec {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    my @tab = @{$line->{Rarguments} || []};
    my $file = $tab[0];

    $log->syslog('notice', 'Line %s: exec (%s)', $line->{line}, $file);
    system($file);

    return 1;
}

# Old name: purge_logs_table() in task_manager.pl.
sub do_purge_logs_table {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    unless (_db_log_del()) {
        $log->syslog('err', 'Failed to delete logs');
        return undef;
    }

    $log->syslog('notice', 'Logs purged');

    if ($log->aggregate_stat) {
        $log->syslog('notice', 'Stats aggregated');
    }

    return 1;
}

# Deletes logs in RDBMS.
# If a log is older than $list->get_latest_distribution_date() - $delay
# expire the log.
# Old name: _db_log_del() in task_manager.pl.
sub _db_log_del {
    my ($exp, $date);

    my $sdm = Sympa::DatabaseManager->instance;

    $exp = Conf::get_robot_conf('*', 'logs_expiration_period');
    $date = time - ($exp * 31 * 24 * 60 * 60);
    unless (
        $sdm
        and $sdm->do_prepared_query(
            q{DELETE FROM logs_table
              WHERE date_logs <= ?},
            $date
        )
    ) {
        $log->syslog('err',
            'Unable to delete db_log entry from the database');
        return undef;
    }

    $exp = Conf::get_robot_conf('*', 'stats_expiration_period');
    $date = time - ($exp * 31 * 24 * 60 * 60);
    unless (
        $sdm->do_prepared_query(
            q{DELETE FROM stat_table
              WHERE date_stat <= ?},
            $date
        )
    ) {
        $log->syslog('err',
            'Unable to delete db_log entry from the database');
        return undef;
    }
    unless (
        $sdm->do_prepared_query(
            q{DELETE FROM stat_counter_table
              WHERE end_date_counter <= ?},
            $date
        )
    ) {
        $log->syslog('err',
            'Unable to delete db_log entry from the database');
        return undef;
    }

    return 1;
}

# Remove sessions from session_table if older than session_table_ttl or
# anonymous_session_table_ttl.
# Old name: Sympa::Session::purge_old_sessions(),
# purge_session_table() in task_manager.pl.
sub do_purge_session_table {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    my $delay =
        Sympa::Tools::Time::duration_conv($Conf::Conf{'session_table_ttl'});
    my $anonymous_delay = Sympa::Tools::Time::duration_conv(
        $Conf::Conf{'anonymous_session_table_ttl'});

    unless ($delay) {
        $log->syslog('info', 'Exit with delay null');
        return undef;
    }
    unless ($anonymous_delay) {
        $log->syslog('info', 'Exit with anonymous delay null');
        return undef;
    }

    my @sessions;
    my $sth;
    my $sdm = Sympa::DatabaseManager->instance;
    unless ($sdm) {
        $log->syslog('err', 'Unavailable database connection');
        return undef;
    }

    my (@conditions, @anonymous_conditions);
    push @conditions, sprintf('%d > date_session', time - $delay) if $delay;
    push @anonymous_conditions,
        sprintf('%d > date_session', time - $anonymous_delay)
        if $anonymous_delay;

    my $condition           = join ' AND ', @conditions;
    my $anonymous_condition = join ' AND ', @anonymous_conditions,
        "email_session = 'nobody'", 'hit_session = 1';

    my $count_statement =
        sprintf q{SELECT COUNT(*) FROM session_table WHERE %s}, $condition;
    my $anonymous_count_statement =
        sprintf q{SELECT COUNT(*) FROM session_table WHERE %s},
        $anonymous_condition;

    my $statement = sprintf q{DELETE FROM session_table WHERE %s}, $condition;
    my $anonymous_statement = sprintf q{DELETE FROM session_table WHERE %s},
        $anonymous_condition;

    unless ($sth = $sdm->do_query($count_statement)) {
        $log->syslog('err', 'Unable to count old session');
        return undef;
    }

    my $total = $sth->fetchrow;
    if ($total == 0) {
        $log->syslog('debug', 'No sessions to expire');
    } else {
        unless ($sth = $sdm->do_query($statement)) {
            $log->syslog('err', 'Unable to purge old sessions');
            return undef;
        }
    }
    unless ($sth = $sdm->do_query($anonymous_count_statement)) {
        $log->syslog('err', 'Unable to count anonymous sessions');
        return undef;
    }
    my $anonymous_total = $sth->fetchrow;
    if ($anonymous_total == 0) {
        $log->syslog('debug', 'No anonymous sessions to expire');
    } else {
        unless ($sth = $sdm->do_query($anonymous_statement)) {
            $log->syslog('err', 'Unable to purge anonymous sessions');
            return undef;
        }
    }

    $log->syslog(
        'notice',
        '%s row removed in session_table',
        $total + $anonymous_total
    );
    return 1;
}

# Remove messages from spools if older than duration given by configuration.
# Old name: purge_spools() in task_manager.pl.
sub do_purge_spools {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    # Expiring bad messages in incoming spools and archive spool.
    foreach my $queue (qw(queue queueautomatic queuebounce queueoutgoing)) {
        my $directory   = $Conf::Conf{$queue} . '/bad';
        my $clean_delay = $Conf::Conf{'clean_delay_' . $queue};
        if (-e $directory) {
            _clean_spool($directory, $clean_delay);
        }
    }

    # Expiring bad messages in digest spool.
    if (opendir my $dh, $Conf::Conf{'queuedigest'}) {
        my $base_dir = $Conf::Conf{'queuedigest'};
        my @dirs = grep { !/\A\./ and -d $base_dir . '/' . $_ } readdir $dh;
        closedir $dh;
        foreach my $subdir (@dirs) {
            my $directory   = $base_dir . '/' . $subdir . '/bad';
            my $clean_delay = $Conf::Conf{'clean_delay_queuedigest'};
            if (-e $directory) {
                _clean_spool($directory, $clean_delay);
            }
        }
    }

    # Expiring bad packets and messages in bulk spool.
    foreach my $subdir (qw(pct msg)) {
        my $directory   = $Conf::Conf{'queuebulk'} . '/bad/' . $subdir;
        my $clean_delay = $Conf::Conf{'clean_delay_queuebulk'};
        if (-e $directory) {
            _clean_spool($directory, $clean_delay);
        }
    }

    # Expiring moderation spools except mod, topic spool and temporary files.
    foreach my $queue (
        qw(queueauth queueautomatic queuesubscribe queuetopic tmpdir)) {
        my $directory   = $Conf::Conf{$queue};
        my $clean_delay = $Conf::Conf{'clean_delay_' . $queue};
        if (-e $directory) {
            _clean_spool($directory, $clean_delay);
        }
    }

    # Expiring mod spool.
    my $modqueue = $Conf::Conf{'queuemod'};
    if (opendir my $dh, $modqueue) {
        my @qfiles = sort readdir $dh;
        closedir $dh;
        foreach my $i (@qfiles) {
            next if $i =~ /\A[.]/;
            next unless -f $modqueue . '/' . $i;

            $i =~ /\A(.+)_[.\w]+\z/;
            my $list = Sympa::List->new($1, '*', {just_try => 1}) if $1;
            my $moddelay;
            if (ref $list eq 'Sympa::List') {
                $moddelay = $list->{'admin'}{'clean_delay_queuemod'};
            } else {
                $moddelay = $Conf::Conf{'clean_delay_queuemod'};
            }
            if ($moddelay) {
                my $mtime =
                    Sympa::Tools::File::get_mtime($modqueue . '/' . $i);
                if ($mtime < time - $moddelay * 86400) {
                    unlink($modqueue . '/' . $i);
                    $log->syslog('notice',
                        'Deleting unmoderated message %s, too old', $i);
                }
            }
        }
    }

    # Expiring formatted held messages.
    if (opendir my $dh, $Conf::Conf{'viewmail_dir'} . '/mod') {
        my $base_dir = $Conf::Conf{'viewmail_dir'} . '/mod';
        my @dirs = grep { !/\A\./ and -d $base_dir . '/' . $_ } readdir $dh;
        closedir $dh;
        foreach my $list_id (@dirs) {
            my $clean_delay;
            my $list = Sympa::List->new($list_id, '*', {just_try => 1});
            if (ref $list eq 'Sympa::List') {
                $clean_delay = $list->{'admin'}{'clean_delay_queuemod'};
            } else {
                $clean_delay = $Conf::Conf{'clean_delay_queuemod'};
            }
            my $directory = $base_dir . '/' . $list_id;
            if ($clean_delay and -e $directory) {
                _clean_spool($directory, $clean_delay);
            }
        }
    }

    # Removing messages in bulk spool with no more packet.
    my $pct_directory = $Conf::Conf{'queuebulk'} . '/pct';
    my $msg_directory = $Conf::Conf{'queuebulk'} . '/msg';
    if (opendir my $dh, $pct_directory) {
        my $msgpath;
        while ($msgpath = readdir $dh) {
            next if $msgpath =~ /\A\./;
            next unless -d $pct_directory . '/' . $msgpath;
            next
                if time - 3600 < Sympa::Tools::File::get_mtime(
                $pct_directory . '/' . $msgpath);

            # If packet directory is empty, remove message also.
            unlink($msg_directory . '/' . $msgpath)
                if rmdir($pct_directory . '/' . $msgpath);
        }
        closedir $dh;
    }

    return 1;
}

# Old name: tools::CleanSpool(), Sympa::Tools::File::CleanDir(),
# _clean_spool() in task_manager.pl.
sub _clean_spool {
    $log->syslog('debug2', '(%s, %s)', @_);
    my ($directory, $clean_delay) = @_;

    return 1 unless $clean_delay;

    my $dh;
    unless (opendir $dh, $directory) {
        $log->syslog('err', 'Unable to open "%s" spool: %m', $directory);
        return undef;
    }
    my @qfile = sort grep { !/\A\.+\z/ and !/\Abad\z/ } readdir $dh;
    closedir $dh;

    my ($curlist, $moddelay);
    foreach my $f (@qfile) {
        if (Sympa::Tools::File::get_mtime("$directory/$f") <
            time - $clean_delay * 60 * 60 * 24) {
            if (-f "$directory/$f") {
                unlink("$directory/$f");
                $log->syslog('notice', 'Deleting old file %s',
                    "$directory/$f");
            } elsif (-d "$directory/$f") {
                unless (Sympa::Tools::File::remove_dir("$directory/$f")) {
                    $log->syslog('err', 'Cannot remove old directory %s: %m',
                        "$directory/$f");
                    next;
                }
                $log->syslog('notice', 'Deleting old directory %s',
                    "$directory/$f");
            }
        }
    }

    return 1;
}

## remove messages from bulkspool table when no more packet have any pointer
## to this message
# Old name: purge_tables() in task_manager.pl.
sub do_purge_tables {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    my $removed;

    $removed = 0;
    foreach my $robot (Sympa::List::get_robots()) {
        my $all_lists = Sympa::List::get_lists($robot);

        foreach my $list (@{$all_lists || []}) {
            my $tracking = Sympa::Tracking->new(context => $list);
766
            next unless $tracking;
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
832
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913

            $removed +=
                $tracking->remove_message_by_period(
                $list->{'admin'}{'tracking'}{'retention_period'});
        }
    }
    $log->syslog('notice', "%s rows removed in tracking table", $removed);

    return 1;
}

## remove one time ticket table if older than
## $Conf::Conf{'one_time_ticket_table_ttl'}
# Old name: purge_one_time_ticket_table() in task_manager.pl.
sub do_purge_one_time_ticket_table {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    $log->syslog('info', '');
    my $removed = Sympa::Ticket::purge_old_tickets('*');
    unless (defined $removed) {
        $log->syslog('err', 'Failed to remove old tickets');
        return undef;
    }
    $log->syslog('notice', '%s row removed in one_time_ticket_table',
        $removed);
    return 1;
}

# Old name: purge_user_table() in task_manager.pl.
sub do_purge_user_table {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    my $sdm = Sympa::DatabaseManager->instance;

    my $time = time;

    # Marking super listmasters
    foreach my $l (Sympa::get_listmasters_email('*')) {
        unless (
            $sdm
            and $sdm->do_prepared_query(
                q{UPDATE user_table
                  SET last_active_date_user = ?
                  WHERE email_user = ?},
                $time, lc $l
            )
        ) {
            $log->syslog('err', 'Failed to check activity of users');
            return undef;
        }
    }
    # Marking per-robot listmasters.
    foreach my $robot_id (Sympa::List::get_robots()) {
        foreach my $l (Sympa::get_listmasters_email($robot_id)) {
            unless (
                $sdm->do_prepared_query(
                    q{UPDATE user_table
                      SET last_active_date_user = ?
                      WHERE email_user = ?},
                    $time, lc $l
                )
            ) {
                $log->syslog('err', 'Failed to check activity of users');
                return undef;
            }
        }
    }
    # Marking new users, owners/editors and subscribers.
    unless (
        $sdm->do_prepared_query(
            q{UPDATE user_table
              SET last_active_date_user = ?
              WHERE last_active_date_user IS NULL
              OR EXISTS (
                SELECT 1
                FROM admin_table
                WHERE admin_table.user_admin = user_table.email_user
              )
              OR EXISTS (
                SELECT 1
                FROM subscriber_table
                WHERE subscriber_table.user_subscriber = user_table.email_user
              )},
            $time
        )
    ) {
        $log->syslog('err', 'Failed to check activity of users');
        return undef;
    }

    # Look for unused entries.
    my @purged_users;
    my $sth;
    unless (
        $sth = $sdm->do_prepared_query(
            q{SELECT email_user
              FROM user_table
              WHERE last_active_date_user IS NOT NULL AND
                    last_active_date_user < ?},
            $time
        )
    ) {
        $log->syslog('err', 'Failed to get inactive users');
        return undef;
    }
    @purged_users =
        grep {$_} map { $_->[0] } @{$sth->fetchall_arrayref || []};
    $sth->finish;

    # Purge unused entries.
    foreach my $email (@purged_users) {
        my $user = Sympa::User->new($email);
        next unless $user;

        unless ($user->expire) {
            $log->syslog('err', 'Failed to purge inactive user %s', $user);
            return undef;
        } else {
            $log->syslog('info', 'User %s was expired', $user);
        }
    }

    return scalar @purged_users;
}

## Subroutine which remove bounced message of no-more known users
# Old name: purge_orphan_bounces() in task_manager.pl.
sub do_purge_orphan_bounces {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    my $all_lists = Sympa::List::get_lists('*');
    foreach my $list (@{$all_lists || []}) {
        # First time: loading DB entries into %bounced_users,
        # hash {'bounced address' => 1}
        my %bounced_users;

        for (
            my $user_ref = $list->get_first_bouncing_list_member();
            $user_ref;
            $user_ref = $list->get_next_bouncing_list_member()
        ) {
914
915
916
917
918
            $bounced_users{
                Sympa::Tools::Text::encode_filesystem_safe(
                    $user_ref->{email}
                )
            } = 1;
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
        }

        my $bounce_dir = $list->get_bounce_dir();
        unless (-d $bounce_dir) {
            $log->syslog('notice', 'No bouncing subscribers in list %s',
                $list);
            next;
        }

        # Then reading Bounce directory & compare with %bounced_users
        my $dh;
        unless (opendir $dh, $bounce_dir) {
            $log->syslog('err', 'Error while opening bounce directory %s',
                $bounce_dir);
            return undef;
        }

        # Finally removing orphan files
        my $marshalled;
        while ($marshalled = readdir $dh) {
            my $metadata =
                Sympa::Spool::unmarshal_metadata($bounce_dir, $marshalled,
941
                qr/\A([^\s\@]+\@[\w\.\-*]+?)(?:__(\w+))?\z/,
942
943
                [qw(recipient envid)]);
            next unless $metadata;
944
            # Skip <email>__<envid> which is used by tracking feature.
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
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
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
            next if defined $metadata->{envid};

            unless ($bounced_users{$marshalled}) {
                $log->syslog('info',
                    'Removing orphan Bounce for user %s in list %s',
                    $marshalled, $list);
                unless (unlink($bounce_dir . '/' . $marshalled)) {
                    $log->syslog('err', 'Error while removing file %s/%s',
                        $bounce_dir, $marshalled);
                }
            }
        }

        closedir $dh;
    }
    return 1;
}

# If a bounce is older than $list->get_latest_distribution_date() - $delay
# expire the bounce.
# Old name: expire_bounce() in task_manager.pl.
sub do_expire_bounce {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    my @tab = @{$line->{Rarguments} || []};
    my $delay = $tab[0];

    my $all_lists = Sympa::List::get_lists('*');
    foreach my $list (@{$all_lists || []}) {
        my $listname = $list->{'name'};

        # the reference date is the date until which we expire bounces in
        # second
        # the latest_distribution_date is the date of last distribution #days
        # from 01 01 1970

        unless ($list->get_latest_distribution_date()) {
            $log->syslog(
                'debug2',
                'Bounce expiration: skipping list %s because could not get latest distribution date',
                $listname
            );
            next;
        }
        my $refdate =
            (($list->get_latest_distribution_date() - $delay) * 3600 * 24);

        for (
            my $u = $list->get_first_bouncing_list_member();
            $u;
            $u = $list->get_next_bouncing_list_member()
        ) {
            $u->{'bounce'} =~ /^(\d+)\s+(\d+)\s+(\d+)(\s+(.*))?$/;
            $u->{'last_bounce'} = $2;
            if ($u->{'last_bounce'} < $refdate) {
                my $email = $u->{'email'};

                unless ($list->is_list_member($email)) {
                    $log->syslog('info', '%s not subscribed', $email);
                    next;
                }

                unless (
                    $list->update_list_member(
                        $email,
                        bounce         => undef,
                        bounce_address => undef
                    )
                ) {
                    $log->syslog('info', 'Failed update database for %s',
                        $email);
                    next;
                }
1020
1021
                my $escaped_email =
                    Sympa::Tools::Text::encode_filesystem_safe($email);
1022
1023
1024
1025
1026
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
1134

                my $bounce_dir = $list->get_bounce_dir();

                unless (unlink $bounce_dir . '/' . $escaped_email) {
                    $log->syslog(
                        'info',
                        'Failed deleting %s',
                        $bounce_dir . '/' . $escaped_email
                    );
                    next;
                }
                $log->syslog(
                    'info',
                    'Expire bounces for subscriber %s of list %s (last distribution %s, last bounce %s)',
                    $email,
                    $listname,
                    POSIX::strftime(
                        "%Y-%m-%d",
                        localtime(
                            $list->get_latest_distribution_date() * 3600 * 24
                        )
                    ),
                    POSIX::strftime(
                        "%Y-%m-%d", localtime($u->{'last_bounce'})
                    )
                );
            }
        }
    }

    # Expiring formatted bounce messages.
    if (opendir my $dh, $Conf::Conf{'viewmail_dir'} . '/bounce') {
        my $base_dir = $Conf::Conf{'viewmail_dir'} . '/bounce';
        my @dirs = grep { !/\A\./ and -d $base_dir . '/' . $_ } readdir $dh;
        closedir $dh;
        foreach my $list_id (@dirs) {
            my $directory = $base_dir . '/' . $list_id;
            if (-e $directory) {
                _clean_spool($directory, $delay);
            }
        }
    }

    return 1;
}

# Removed because not yet fully implemented.  See r11771.
#sub chk_cert_expiration;

# Removed becuase not yet fully implemented.  See r11771.
#sub update_crl;

## Subroutine for bouncers evaluation:
# give a score for each bouncing user
# Old name: eval_bouncers() in task_manager.pl.
sub do_eval_bouncers {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    my $all_lists = Sympa::List::get_lists('*');
    foreach my $list (@{$all_lists || []}) {
        my $listname     = $list->{'name'};
        my $list_traffic = {};

        $log->syslog('info', '(%s)', $listname);

        ## Analizing file Msg-count and fill %$list_traffic
        unless (open(COUNT, $list->{'dir'} . '/msg_count')) {
            $log->syslog('debug',
                '** Could not open msg_count FILE for list %s', $listname);
            next;
        }
        while (<COUNT>) {
            if (/^(\w+)\s+(\d+)/) {
                my ($a, $b) = ($1, $2);
                $list_traffic->{$a} = $b;
            }
        }
        close(COUNT);

        #for each bouncing user
        for (
            my $user_ref = $list->get_first_bouncing_list_member();
            $user_ref;
            $user_ref = $list->get_next_bouncing_list_member()
        ) {
            my $score = _get_score($user_ref, $list_traffic) || 0;

            # Copying score into database.
            unless (
                $list->update_list_member(
                    $user_ref->{'email'}, bounce_score => $score
                )
            ) {
                $log->syslog('err', 'Error while updating DB for user %s',
                    $user_ref->{'email'});
                next;
            }
        }
    }
    return 1;
}

# Routine for automatic bouncing users management
#
# This sub apply a treatment foreach category of bouncing-users
#
# The relation between possible actions and correponding subroutines
# is indicated by the following hash (%actions).
# It's possible to add actions by completing this hash and the one in list
# config (file List.pm, in sections "bouncers_levelX"). Then you must write
# the code for your action:
IKEDA Soji's avatar
IKEDA Soji committed
1135
1136
1137
1138
# The action subroutines have two parameters:
# - current list
# - a reference on users email list
# Look at the _remove_bouncers() for an example.
1139
1140
1141
1142
1143
1144
1145
1146
# Old name: process_bouncers() in task_manager.pl.
sub do_process_bouncers {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    ## possible actions
    my %actions = (
IKEDA Soji's avatar
IKEDA Soji committed
1147
1148
1149
        'remove_bouncers' => \&_remove_bouncers,
        'notify_bouncers' => \&_notify_bouncers,
        'none'            => sub {1},
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
    );

    my $all_lists = Sympa::List::get_lists('*');
    foreach my $list (@{$all_lists || []}) {
        my @bouncers;
        # @bouncers = (
        #     ['email1', 'email2', 'email3',....,],    There is one line
        #     ['email1', 'email2', 'email3',....,],    foreach bounce
        #     ['email1', 'email2', 'email3',....,],    level.
        # );

        my $max_level;
        for (
            my $level = 1;
            defined($list->{'admin'}{'bouncers_level' . $level});
            $level++
        ) {
            $max_level = $level;
        }

        ##  first, bouncing email are sorted in @bouncer
        for (
            my $user_ref = $list->get_first_bouncing_list_member();
            $user_ref;
            $user_ref = $list->get_next_bouncing_list_member()
        ) {
            # Skip included users (cannot be removed)
1177
            next if defined $user_ref->{'inclusion'};
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

            for (my $level = $max_level; ($level >= 1); $level--) {
                if ($user_ref->{'bounce_score'} >=
                    $list->{'admin'}{'bouncers_level' . $level}{'rate'}) {
                    push(@{$bouncers[$level]}, $user_ref->{'email'});
                    $level = ($level - $max_level);
                }
            }
        }

        ## then, calling action foreach level
        for (my $level = $max_level; ($level >= 1); $level--) {
            my $action =
                $list->{'admin'}{'bouncers_level' . $level}{'action'};
            my $notification =
                $list->{'admin'}{'bouncers_level' . $level}{'notification'};
            my $robot_id = $list->{'domain'};

            if (@{$bouncers[$level] || []}) {
                ## calling action subroutine with (list,email list) in
                ## parameter
                unless ($actions{$action}->($list, $bouncers[$level])) {
                    $log->syslog(
                        'err',
                        'Error while calling action sub for bouncing users in list %s',
IKEDA Soji's avatar
IKEDA Soji committed
1203
                        $list
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
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
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
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
                    );
                    return undef;
                }

                # Notify owner or listmaster with list, action, email list.
                my $param = {
                    #'listname'  => $listname, # No longer used (<=6.1)
                    'action'    => $action,
                    'user_list' => \@{$bouncers[$level]},
                    'total'     => scalar(@{$bouncers[$level]}),
                };
                if ($notification eq 'owner') {
                    $list->send_notify_to_owner('automatic_bounce_management',
                        $param);
                } elsif ($notification eq 'listmaster') {
                    Sympa::send_notify_to_listmaster($list,
                        'automatic_bounce_management', $param);
                }
            }
        }
    }
    return 1;
}

# Old name: get_score() in task_manager.pl.
sub _get_score {

    my $user_ref     = shift;
    my $list_traffic = shift;

    $log->syslog('debug', '(%s)', $user_ref->{'email'});

    my $min_period    = $Conf::Conf{'minimum_bouncing_period'};
    my $min_msg_count = $Conf::Conf{'minimum_bouncing_count'};

    # Analizing bounce_subscriber_field and keep useful infos for notation
    $user_ref->{'bounce'} =~ /^(\d+)\s+(\d+)\s+(\d+)(\s+(.*))?$/;

    my $BO_period    = int($1 / 86400) - $Conf::Conf{'bounce_delay'};
    my $EO_period    = int($2 / 86400) - $Conf::Conf{'bounce_delay'};
    my $bounce_count = $3;
    my $bounce_type  = $4;

    my $msg_count = 0;
    my $min_day   = $EO_period;

    unless ($bounce_count >= $min_msg_count) {
        #not enough messages distributed to keep score
        $log->syslog('debug', 'Not enough messages for evaluation of user %s',
            $user_ref->{'email'});
        return undef;
    }

    unless (($EO_period - $BO_period) >= $min_period) {
        #too short bounce period to keep score
        $log->syslog('debug', 'Too short period for evaluate %s',
            $user_ref->{'email'});
        return undef;
    }

    # calculate number of messages distributed in list while user was bouncing
    foreach my $date (sort { $b <=> $a } keys(%$list_traffic)) {
        if (($date >= $BO_period) && ($date <= $EO_period)) {
            $min_day = $date;
            $msg_count += $list_traffic->{$date};
        }
    }

    # Adjust bounce_count when msg_count file is too recent, compared to the
    # bouncing period
    my $tmp_bounce_count = $bounce_count;
    unless ($EO_period == $BO_period) {
        my $ratio = (($EO_period - $min_day) / ($EO_period - $BO_period));
        $tmp_bounce_count *= $ratio;
    }

    ## Regularity rate tells how much user has bounced compared to list
    ## traffic
    $msg_count ||= 1;    ## Prevents "Illegal division by zero" error
    my $regularity_rate = $tmp_bounce_count / $msg_count;

    ## type rate depends on bounce type (5 = permanent ; 4 =tewmporary)
    my $type_rate = 1;
    $bounce_type =~ /(\d)\.(\d)\.(\d)/;
    if ($1 == 4) {       # if its a temporary Error: score = score/2
        $type_rate = .5;
    }

    my $note = $bounce_count * $regularity_rate * $type_rate;

    ## Note should be an integer
    $note = int($note + 0.5);

#    $note = 100 if ($note > 100); # shift between message ditrib & bounces =>
#    note > 100

    return $note;
}

IKEDA Soji's avatar
IKEDA Soji committed
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
# Sub for removing user
# Old name: Sympa::List::remove_bouncers().
sub _remove_bouncers {
    $log->syslog('debug2', '(%s, %s)', @_);
    my $list  = shift;
    my $users = shift;

    foreach my $u (@{$users || []}) {
        $log->syslog('notice', 'Removing bouncing subsrciber of list %s: %s',
            $list, $u);
    }
    $list->delete_list_member(
        users     => $users,
        exclude   => '1',
        operation => 'auto_del'
    );
    return 1;
1320
1321
}

IKEDA Soji's avatar
IKEDA Soji committed
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
# Sub for notifying users: "Be careful, you're bouncing".
# Old name: Sympa::List::notify_bouncers().
sub _notify_bouncers {
    $log->syslog('debug2', '(%s, %s)', @_);
    my $list  = shift;
    my $users = shift;

    foreach my $u (@{$users || []}) {
        $log->syslog('notice', 'Notifying bouncing subsrciber of list %s: %s',
            $list, $u);
        Sympa::send_notify_to_user($list, 'auto_notify_bouncers', $u);
    }
    return 1;
}

# Old name: none() in task_manager.pl.
# No longer used.
#sub _none;

1341
1342
1343
1344
1345
1346
1347
# Old name: sync_include() in task_manager.pl.
sub do_sync_include {
    my $self = shift;
    my $task = shift;
    my $line = shift;

    my $list = $task->{context};
1348
1349
1350
1351
    unless (ref $list eq 'Sympa::List') {
        $log->syslog('err', 'No list');
        return -1;
    }
1352

1353
1354
1355
1356
1357
    $list->sync_include('member');
    $list->sync_include('owner');
    $list->sync_include('editor');

    unless ($list->has_data_sources or $list->has_included_users) {
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
        $log->syslog('debug', 'List %s no more require sync_include task',
            $list);
        return -1;
    }
}

### MISCELLANEOUS SUBROUTINES ###

## change the label of a task file
# Old name: change_label() in task_manager.pl.
# No onger used.
#sub _change_label;

## send a error message to list-master, log it, and change the label task into
## 'ERROR'
sub _error {
    my $task    = shift;
    my $message = shift;

    my @param = (
        sprintf
            'An error has occurred during the execution of the task %s: %s',
        $task->get_id, $message
    );
    $log->syslog('err', '%s', $message);
    #FIXME: Coresponding mail template would be added.
    Sympa::send_notify_to_listmaster('*', 'error_in_task', \@param);
}

1;
__END__

=encoding utf-8

=head1 NAME

Sympa::Spindle::ProcessTask - Workflow of task processing

=head1 SYNOPSIS

  use Sympa::Spindle::ProcessTask;
  
  my $spindle = Sympa::Spindle::ProcessTask->new;
  $spindle->spin;

=head1 DESCRIPTION

L<Sympa::Spindle::ProcessTask> defines workflow to process tasks in
task spool.

When spin() method is invoked, tasks kept in task spool are processed.
Then, all global and list tasks are created as necessity.

=head1 SEE ALSO

L<task_manager(8)>, L<Sympa::Spindle>, L<Sympa::Spool::Task>, L<Sympa::Task>.

=head1 HISTORY

IKEDA Soji's avatar
IKEDA Soji committed
1417
L<Sympa::Spindle::ProcessTask> appeared on Sympa 6.2.37b.2.
1418
1419
1420

=cut