Tracking.pm 21.6 KB
Newer Older
1
2
3
# -*- indent-tabs-mode: nil; -*-
# vim:ft=perl:et:sw=4
# $Id$
4
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, 2016, 2017 GIP RENATER
11
12
13
# Copyright 2017 The Sympa Community. See the AUTHORS.md file at the top-level
# directory of this distribution and at
# <https://github.com/sympa-community/sympa.git>.
14
15
16
17
18
19
20
21
22
23
24
25
#
# 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
26
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
27

28
package Sympa::Tracking;
29
30

use strict;
31
use warnings;
32
use DateTime::Format::Mail;
33
use English qw(-no_match_vars);
34

35
use Conf;
36
use Sympa::Constants;
37
use Sympa::DatabaseManager;
38
use Sympa::Log;
39
use Sympa::Tools::File;
40
use Sympa::Tools::Text;
41

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

44
45
sub new {
    my $class = shift;
46
47
48
49
50
51
52
53

    my $list;
    if (ref $_[0]) {    # Compat., not recommended.
        $list = shift;
    } else {
        my %options = @_;
        $list = $options{context};
    }
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

    die 'Bug in logic.  Ask developer'
        unless ref $list eq 'Sympa::List';

    my $self = bless {
        directory => $list->get_bounce_dir,
        context   => $list,
    } => $class;

    $self->_create_spool;

    return $self;
}

sub _create_spool {
    my $self = shift;

    my $umask = umask oct $Conf::Conf{'umask'};
    foreach my $directory (($self->{directory})) {
        unless (-d $directory) {
74
            $log->syslog('info', 'Creating spool %s', $directory);
75
76
77
78
79
80
81
            unless (
                mkdir($directory, 0755)
                and Sympa::Tools::File::set_file_rights(
                    file  => $directory,
                    user  => Sympa::Constants::USER(),
                    group => Sympa::Constants::GROUP()
                )
Luc Didry's avatar
Luc Didry committed
82
            ) {
83
84
85
86
87
88
                die sprintf 'Cannot create %s: %s', $directory, $ERRNO;
            }
        }
    }
    umask $umask;
}
89
90
91
92

##############################################
#   get_recipients_status
##############################################
93
# Function use to get mail addresses and status of
94
95
# the recipients who have a different DSN status than "delivered"
# Use the pk identifiant of the mail
96
#
97
98
99
#     -$pk_mail (+): the identifiant of the stored mail
#
# OUT : @pk_notifs |undef
100
#
101
102
##############################################
sub get_recipients_status {
103
    $log->syslog('debug2', '(%s, %s, %s)', @_);
104
105
106
    my $msgid    = shift;
    my $listname = shift;
    my $robot    = shift;
107

108
    $msgid = Sympa::Tools::Text::canonic_message_id($msgid);
109

110
    my $sth;
111
    my $sdm = Sympa::DatabaseManager->instance;
112

113
114
115
    # the message->head method return message-id including <blabla@dom> where
    # mhonarc return blabla@dom that's why we test both of them
    unless (
116
117
        $sdm
        and $sth = $sdm->do_prepared_query(
118
119
            q{SELECT message_id_notification AS message_id,
                     recipient_notification AS recipient,
120
121
122
                     reception_option_notification AS reception_option,
                     status_notification AS status,
                     arrival_date_notification AS arrival_date,
123
                     arrival_epoch_notification AS arrival_epoch,
124
125
                     type_notification AS "type",
                     pk_notification AS envid
126
127
128
129
130
131
132
              FROM notification_table
              WHERE list_notification = ? AND robot_notification = ? AND
                    (message_id_notification = ? OR
                     message_id_notification = ?)},
            $listname, $robot,
            $msgid,
            '<' . $msgid . '>'
133
        )
Luc Didry's avatar
Luc Didry committed
134
    ) {
135
        $log->syslog(
136
            'err',
137
            'Unable to retrieve tracking information for message %s, list %s@%s',
138
139
140
141
142
143
144
145
146
147
            $msgid,
            $listname,
            $robot
        );
        return undef;
    }
    my @pk_notifs;
    while (my $pk_notif = $sth->fetchrow_hashref) {
        push @pk_notifs, $pk_notif;
    }
148
149
    $sth->finish;

150
    return \@pk_notifs;
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
sub db_fetch {
    my $self    = shift;
    my %options = @_;

    my $list = $self->{context};

    my $recipient = $options{recipient};
    my $envid     = $options{envid};
    return undef unless $recipient and $envid;

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

    unless (
        $sdm
        and $sth = $sdm->do_prepared_query(
            q{SELECT message_id_notification AS message_id,
                     recipient_notification AS recipient,
                     reception_option_notification AS reception_option,
                     status_notification AS status,
                     arrival_date_notification AS arrival_date,
                     arrival_epoch_notification AS arrival_epoch,
                     type_notification AS "type",
                     pk_notification AS envid
              FROM notification_table
              WHERE list_notification = ? AND robot_notification = ? AND
                    recipient_notification = ? AND pk_notification = ?},
            $list->{'name'}, $list->{'domain'},
            $recipient,      $envid
        )
Luc Didry's avatar
Luc Didry committed
183
    ) {
184
185
186
187
188
189
190
191
192
193
194
195
196
197
        $log->syslog(
            'err',
            'Unable to retrieve tracking information for message %s, list %s',
            $recipient,
            $list
        );
        return undef;
    }
    my $pk_notif = $sth->fetchrow_hashref;
    $sth->finish;

    return $pk_notif;
}

198
199
200
201
202
203
204
205
206
207
208
209
# Old name: Sympa::Tracking::db_init_notification_table()
sub register {
    my $self    = shift;
    my $message = shift;
    my $rcpt    = shift;
    my %params  = @_;

    # What ever the message is transformed because of the reception option,
    # tracking use the original message ID.
    my $msgid            = $message->{message_id};
    my $listname         = $self->{context}->{'name'};
    my $robot            = $self->{context}->{'domain'};
210
    my $reception_option = $params{'reception_option'};
211
    my @rcpt             = @{$rcpt || []};
212

213
214
    $log->syslog('debug2',
        '(msgid = %s, listname = %s, reception_option = %s',
215
        $msgid, $listname, $reception_option);
216
217
218

    my $time = time;

219
    my $sdm = Sympa::DatabaseManager->instance;
220
221
222
223
    foreach my $email (@rcpt) {
        my $email = lc($email);

        unless (
224
225
            $sdm
            and $sdm->do_prepared_query(
226
227
228
229
230
231
                q{INSERT INTO notification_table
                  (message_id_notification, recipient_notification,
                   reception_option_notification,
                   list_notification, robot_notification, date_notification)
                  VALUES (?, ?, ?, ?, ?, ?)},
                $msgid, $email, $reception_option, $listname, $robot, $time
232
            )
Luc Didry's avatar
Luc Didry committed
233
        ) {
234
            $log->syslog(
235
236
237
238
239
240
241
242
243
244
                'err',
                'Unable to prepare notification table for user %s, message %s, list %s@%s',
                $email,
                $msgid,
                $listname,
                $robot
            );
            return undef;
        }
    }
245
246
247
    return 1;
}

248
249
250
# copy the bounce to the appropriate filename
# Old name: store_bounce() in bounced.pl
sub store {
251
    $log->syslog('debug2', '(%s, %s, %s, %s, ...)', @_);
252
253
254
255
    my $self    = shift;
    my $message = shift;
    my $rcpt    = shift;
    my %options = @_;
256
257
258
259

    my $bounce_dir = $self->{directory};

    # Store bounce
260
    my $ofh;
261
262

    my $filename;
263
264
265
266
    if (defined $options{envid} and length $options{envid}) {
        unless (_db_insert_notification($rcpt, %options)) {
            return undef;
        }
267
268
        $filename = sprintf '%s__%08s',
            Sympa::Tools::Text::encode_filesystem_safe($rcpt),
269
            $options{envid};
270
    } else {
271
272
273
        unless (
            $self->_update_subscriber_bounce_history($rcpt, $options{status}))
        {
274
275
276
277
            $log->syslog('err', 'No user %s to be updated in list %s',
                $rcpt, $self->{context});
            return undef;
        }
278
        $filename = Sympa::Tools::Text::encode_filesystem_safe($rcpt);
279
280
    }
    unless (open $ofh, '>', $bounce_dir . '/' . $filename) {
281
        $log->syslog('err', 'Unable to write %s/%s', $bounce_dir, $filename);
282
283
        return undef;
    }
284
    print $ofh $message->as_string;
285
286
    close $ofh;

287
288
289
290
291
292
293
294
295
296
297
    $log->syslog('notice', '%s is stored into %s as <%s>',
        $message, $self, $filename);

    # Remove earlier HTML view.
    Sympa::Tools::File::remove_dir(
        join('/',
            $Conf::Conf{'viewmail_dir'}, 'bounce',
            $self->{context}->get_id,    $filename)
    );

    return $filename;
298
299
}

300
##############################################
301
#   _db_insert_notification
302
##############################################
303
# Function used to add a notification entry
304
305
306
307
# corresponding to a new report. This function
# is called when a report has been received.
# It build a new connection with the database
# using the default database parameter. Then it
308
309
# search the notification entry identifiant which
# correspond to the received report. Finally it
310
311
# update the recipient entry concerned by the report.
#
312
313
# IN :-$rcpt (+): original recipient of the initial mail
#     -$id (+): the identifiant entry of the initial mail
314
315
#     -$type (+): the notification entry type (DSN|MDN)
#     -$recipient (+): the list subscriber who correspond to this entry
316
317
#     -$status (+): the new state of the recipient entry depending of the
#     report data
318
319
320
#     -$arrival_date (+): the mail arrival date.
#
# OUT : 1 | undef
321
#
322
##############################################
323
sub _db_insert_notification {
324
325
326
327
    $log->syslog('debug3', '(%s, %s => %s, %s => %s, %s => %s, %s => %s)',
        @_);
    my $rcpt    = shift;
    my %options = @_;
328

329
330
    my ($notification_id, $type, $status, $arrival_date) =
        @options{qw(envid type status arrival_date)};
331
    chomp $arrival_date;
332
    my $arrival_epoch = eval {
333
334
335
        DateTime::Format::Mail->new->loose->parse_datetime($arrival_date)
            ->epoch;
    };
336

337
    my $sdm = Sympa::DatabaseManager->instance;
338
339
    my $sth;

340
    unless (
341
        $sdm
342
        and $sth = $sdm->do_prepared_query(
343
            q{UPDATE notification_table
344
345
              SET status_notification = ?, type_notification = ?,
                  arrival_date_notification = ?,
346
                  arrival_epoch_notification = ?
347
              WHERE recipient_notification = ? AND pk_notification = ?},
348
349
            $status, $type,
            $arrival_date,
350
            $arrival_epoch,
351
            $rcpt, $notification_id
352
        )
Luc Didry's avatar
Luc Didry committed
353
    ) {
354
        $log->syslog('err', 'Unable to update notification <%s> in database',
355
356
            $notification_id);
        return undef;
357
    }
358
359
360
361
362
363
    # Unknown combination of rcpt and envid.
    unless ($sth->rows) {
        $log->syslog('err', 'No notification <%s> for <%s> to be updated',
            $rcpt, $notification_id);
        return 0;
    }
364
365
366
367

    return 1;
}

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
# update subscriber information
# $bouncefor : the email address the bounce is related for (may be extracted
#              using VERP)
# $status : delivery status in format /\d+[.]\d+[.]\d+/.
# Old name: _update_subscriber_bounce_history() in bounced.pl.
sub _update_subscriber_bounce_history {
    $log->syslog('debug', '(%s, %s, %s, %s)', @_);
    my $self      = shift;
    my $bouncefor = shift;
    my $status    = shift || '';

    if ($status =~ /(\d+[.]\d+[.]\d+)/) {
        $status = $1;
    } else {
        $status = '';
    }

    my $user = $self->{context}->get_list_member($bouncefor);
    return undef unless $user;

    if ($status =~ /\A[45]/) {
        my ($first, $last, $count);

        $last = time;
        if (    $user->{'bounce'}
            and $user->{'bounce'} =~ /^(\d+)\s\d+\s+(\d+)/) {
            ($first, $count) = ($1, $2);
        } else {
            ($first, $count) = ($last, 0);
        }
        $count++;

sikeda's avatar
sikeda committed
400
401
        $self->{context}->update_list_member($bouncefor,
            bounce => sprintf('%s %s %s %s', $first, $last, $count, $status));
402
403
404
405
    }
    return 1;
}

406
407
408
409
##############################################
#   find_notification_id_by_message
##############################################
# return the tracking_id find by recipeint,message-id,listname and robot
410
# tracking_id areinitialized by sympa.pl by Sympa::List::distribute_msg
411
#
412
# used by bulk.pl in order to set return_path when tracking is required.
413
#
414
415
##############################################

416
sub find_notification_id_by_message {
417
    $log->syslog('debug2', '(%s, %s, %s, %s)', @_);
418
419
    my $recipient = shift;
    my $msgid     = shift;
420
421
422
    my $listname  = shift;
    my $robot     = shift;

423
    $msgid = Sympa::Tools::Text::canonic_message_id($msgid);
424
425

    my $sth;
426
    my $sdm = Sympa::DatabaseManager->instance;
427

428
429
430
    # the message->head method return message-id including <blabla@dom> where
    # mhonarc return blabla@dom that's why we test both of them
    unless (
431
432
        $sdm
        and $sth = $sdm->do_prepared_query(
433
434
435
436
437
438
439
440
441
442
            q{SELECT pk_notification
              FROM notification_table
              WHERE recipient_notification = ? AND
                    list_notification = ? AND robot_notification = ? AND
                    (message_id_notification = ? OR
                     message_id_notification = ?)},
            $recipient,
            $listname, $robot,
            $msgid,
            '<' . $msgid . '>'
443
        )
Luc Didry's avatar
Luc Didry committed
444
    ) {
445
        $log->syslog(
446
            'err',
447
            'Unable to retrieve the tracking information for user %s, message %s, list %s@%s',
448
449
450
451
452
453
            $recipient,
            $msgid,
            $listname,
            $robot
        );
        return undef;
454
    }
455

456
    my @pk_notifications = $sth->fetchrow_array;
457
458
    $sth->finish;

459
    if (scalar @pk_notifications > 1) {
460
        $log->syslog(
461
            'err',
462
            'Found more then one envelope ID maching (recipient=%s, msgis=%s, listname=%s, robot%s)',
463
464
465
466
467
468
            $recipient,
            $msgid,
            $listname,
            $robot
        );
        # we should return undef...
469
    }
470
    return $pk_notifications[0];
471
472
}

473
474
475
476
477
478
479
480
481
sub remove_message_by_email {
    $log->syslog('debug2', '(%s, %s)', @_);
    my $self  = shift;
    my $email = shift;

    $email = Sympa::Tools::Text::canonic_email($email);
    return undef unless $email;

    my $bounce_dir    = $self->{directory};
482
    my $escaped_email = Sympa::Tools::Text::encode_filesystem_safe($email);
Luc Didry's avatar
Luc Didry committed
483
    my $ret           = unlink sprintf('%s/%s', $bounce_dir, $escaped_email);
484
485
486
487
488
489
490
491
492
493
494

    # Remove HTML view.
    Sympa::Tools::File::remove_dir(
        join('/',
            $Conf::Conf{'viewmail_dir'}, 'bounce',
            $self->{context}->get_id,    $escaped_email)
    );

    return $ret;
}

495
##############################################
496
#   remove_message_by_id
497
##############################################
498
499
# Function use to remove notifications
#
500
# IN : $msgid : id of related message
501
502
503
504
#    : $listname
#    : $robot
#
# OUT : $sth | undef
505
#
506
##############################################
507
sub remove_message_by_id {
508
    $log->syslog('debug2', '(%s, %s, %s)', @_);
509
510
511
512
513
    my $self  = shift;
    my $msgid = shift;

    my $listname = $self->{context}->{'name'};
    my $robot    = $self->{context}->{'domain'};
514
515

    my $sth;
516
    my $sdm = Sympa::DatabaseManager->instance;
517
518
519

    # Remove messages in bounce directory.
    unless (
520
521
        $sdm
        and $sth = $sdm->do_prepared_query(
522
523
524
525
526
527
528
529
            q{SELECT recipient_notification AS recipient,
                     pk_notification AS envid
              FROM notification_table
              WHERE message_id_notification = ? AND
                    list_notification = ? AND robot_notification = ?},
            $msgid,
            $listname, $robot
        )
Luc Didry's avatar
Luc Didry committed
530
    ) {
531
        $log->syslog(
532
533
534
535
536
537
538
539
540
            'err',
            'Unable to search tracking information for message %s, list %s@%s',
            $msgid,
            $listname,
            $robot
        );
        return undef;
    }
    while (my $info = $sth->fetchrow_hashref('NAME_lc')) {
541
542
        my $bounce_dir = $self->{directory};
        my $escaped_email =
543
            Sympa::Tools::Text::encode_filesystem_safe($info->{'recipient'});
544
        my $envid = $info->{'envid'};
545
        unlink sprintf('%s/%s__%08s', $bounce_dir, $escaped_email, $envid);
546
547
548
549
    }
    $sth->finish;

    # Remove row in notification table.
550
    unless (
551
        $sth = $sdm->do_prepared_query(
552
553
554
555
556
            q{DELETE FROM notification_table
              WHERE message_id_notification = ? AND
                    list_notification = ? AND robot_notification = ?},
            $msgid,
            $listname, $robot
557
        )
Luc Didry's avatar
Luc Didry committed
558
    ) {
559
        $log->syslog(
560
            'err',
561
            'Unable to remove the tracking information for message %s, list %s@%s',
562
563
564
565
566
            $msgid,
            $listname,
            $robot
        );
        return undef;
567
    }
568

569
570
571
    return 1;
}

572
573
574
##############################################
#   remove_message_by_period
##############################################
575
# Function use to remove notifications older than number of days
576
#
577
578
579
580
581
# IN : $period
#    : $listname
#    : $robot
#
# OUT : $sth | undef
582
#
583
##############################################
584
sub remove_message_by_period {
585
    $log->syslog('debug2', '(%s, %s, %s)', @_);
586
587
588
589
590
    my $self   = shift;
    my $period = shift;

    my $listname = $self->{context}->{'name'};
    my $robot    = $self->{context}->{'domain'};
591
592
593
594
595

    my $sth;

    my $limit = time - ($period * 24 * 60 * 60);

596
    # Remove messages in bounce directory.
597
    my $sdm = Sympa::DatabaseManager->instance;
598
    unless (
599
600
        $sdm
        and $sth = $sdm->do_prepared_query(
601
602
603
604
605
606
607
608
            q{SELECT recipient_notification AS recipient,
                     pk_notification AS envid
              FROM notification_table
              WHERE date_notification < ? AND
                    list_notification = ? AND robot_notification = ?},
            $limit,
            $listname, $robot
        )
Luc Didry's avatar
Luc Didry committed
609
    ) {
610
        $log->syslog(
611
612
613
614
615
616
617
618
619
            'err',
            'Unable to search tracking information for older than %s days for list %s@%s',
            $limit,
            $listname,
            $robot
        );
        return undef;
    }
    while (my $info = $sth->fetchrow_hashref('NAME_lc')) {
620
621
        my $bounce_dir = $self->{directory};
        my $escaped_email =
622
            Sympa::Tools::Text::encode_filesystem_safe($info->{'recipient'});
623
        my $envid = $info->{'envid'};
624
        unlink sprintf('%s/%s__%08s', $bounce_dir, $escaped_email, $envid);
625
626
627
628
    }
    $sth->finish;

    # Remove rows in notification table.
629
    unless (
630
        $sth = $sdm->do_prepared_query(
631
632
633
            q{DELETE FROM notification_table
              WHERE date_notification < ? AND
              list_notification = ? AND robot_notification = ?},
634
            $limit,
635
            $listname, $robot
636
        )
Luc Didry's avatar
Luc Didry committed
637
    ) {
638
        $log->syslog(
639
            'err',
640
            'Unable to remove the tracking information older than %s days for list %s@%s',
641
642
643
644
645
            $limit,
            $listname,
            $robot
        );
        return undef;
646
    }
647

648
649
650
651
    my $deleted = $sth->rows;
    return $deleted;
}

652
1;
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
__END__

=encoding utf-8

=head1 NAME

Sympa::Tracking - Spool for message tracking

=head1 SYNOPSIS

TBD.

=head1 DESCRIPTION

The tracking feature is a way to request Delivery Status Notification (DSN) or
DSN and Message Disposition Notification (MDN) when sending a 
message to each subscribers. In that case, Sympa (bounced.pl) collect both 
DSN and MDN and store them in tracking spools.
Thus, for each message, the user can know which subscribers has displayed,
received or not received the message. This can be used for some important 
list where list owner need to collect the proof of reception or display of 
each message.

=head2 Methods

=over

680
=item new ( context =E<gt> $list )
681
682
683
684
685
686
687
688

I<Constructor>.
Creates new L<Sympa::Tracking> instance.

Parameter:

=over

689
=item context =E<gt> $list
690
691
692
693
694
695
696
697
698
699

L<Sympa::List> object.

=back

Returns:

New L<Sympa::Tracking> object or C<undef>.
If unrecoverable error occurred, this method will die.

700
701
702
703
=item db_fetch ( recipient =E<gt> $email, envid =E<gt> $envid )

TBD.

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
766
767
768
769
=item get_recipients_status

TBD.

=item register ( $message, $rcpts, reception_option => $mode )

I<Instance method>.
Initializes notification table for each subscriber.

Parameters:

=over

=item $message

The message.

=item $rcpts

An arrayref of recipients.

=item reception_option =E<gt> $mode

The reception option of those subscribers.

=back

Returns:

C<1> or C<undef>.

=item store ( $message, $rcpt,
[ envid =E<gt> $envid, status =E<gt> $status, type =E<gt> $type,
arrival_date =E<gt> $datestring ] )

I<Instance method>.
Store notification into tracking spool.

Parameters:

=over

=item $message

Notification message.

=item $rcpt

E-mail address of recipient of original message.

=item envid =E<gt> $envid, status =E<gt> $status, type =E<gt> $type,
arrival_date =E<gt> $datestring

If these optional parameters are specified,
notification table is updated.

=back

Returns:

True value if storing succeed.  Otherwise false.

=item find_notification_id_by_message

TBD.

770
771
772
773
774
=item remove_message_by_email

TBD.
Introduced on Sympa 6.2.19b.

775
776
777
778
779
780
781
782
783
784
785
786
=item remove_message_by_id

TBD.

=item remove_message_by_period

TBD.

=back

=head1 SEE ALSO

787
bounced(8), L<Sympa::Message>, L<Sympa::Spool::Bounce>.
788
789
790
791
792
793
794
795
796
797

=head1 HISTORY

The tracking feature was contributed by
Guillaume Colotte and laurent Cailleux,
French army DGA Information Superiority.

L<Sympa::Tracking> module appeared on Sympa 6.2.

=cut