include.pm 26.4 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 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# <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::Request::Handler::include;

use strict;
use warnings;

use Sympa;
use Sympa::DatabaseManager;
use Sympa::DataSource;
use Sympa::LockedFile;
use Sympa::Log;

use base qw(Sympa::Request::Handler);

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

use constant _action_scenario => undef;
use constant _context_class   => 'Sympa::List';

my %config_ca_map = (
    'include_ldap_ca'        => 'Sympa::DataSource::LDAP',
    'include_ldap_2level_ca' => 'Sympa::DataSource::LDAP2',
    'include_sql_ca'         => 'Sympa::DataSource::SQL',
);

my %config_user_map = (
    'include_file'              => 'Sympa::DataSource::File',
    'include_remote_file'       => 'Sympa::DataSource::RemoteFile',
    'include_list'              => 'Sympa::DataSource::List',      # Obsoleted
    'include_sympa_list'        => 'Sympa::DataSource::List',
    'include_remote_sympa_list' => 'Sympa::DataSource::RemoteDump',
    'include_ldap_query'        => 'Sympa::DataSource::LDAP',
    'include_ldap_2level_query' => 'Sympa::DataSource::LDAP2',
    'include_sql_query'         => 'Sympa::DataSource::SQL',
);

IKEDA Soji's avatar
IKEDA Soji committed
59
# Internal function.
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
sub _get_data_sources {
    my $list = shift;
    my $role = shift;

    my @dss;

    if ($role eq 'custom_attribute') {
        foreach my $ptype (sort keys %config_ca_map) {
            my @config = grep {$_} @{$list->{'admin'}{$ptype} || []};
            my $type = $config_ca_map{$ptype};
            push @dss, map {
                Sympa::DataSource->new($type, $role, context => $list, %$_)
            } @config;
        }
    } elsif ($role eq 'member') {
75
        #FIXME: Use Sympa::Config.
76
77
78
79
80
81
82
83
84
85
        my @config_files = map { $list->_load_include_admin_user_file($_) }
            @{$list->{'admin'}{'member_include'} || []};

        foreach my $ptype (sort keys %config_user_map) {
            my @config = grep {$_} (
                @{$list->{'admin'}{$ptype} || []},
                map { @{$_->{$ptype} || []} } @config_files
            );
            # Special case: include_file is not paragraph.
            if ($ptype eq 'include_file') {
86
87
88
89
                @config = map {
                    my $name = substr [split m{/}, $_]->[-1], 0, 15;
                    {name => $name, path => $_};
                } @config;
90
91
92
93
94
95
96
97
            }
            my $type = $config_user_map{$ptype};
            push @dss, map {
                Sympa::DataSource->new($type, $role, context => $list, %$_)
            } @config;
        }
    } else {
        my $pname = ($role eq 'owner') ? 'owner_include' : 'editor_include';
98
        #FIXME: Use Sympa::Config.
99
100
101
102
103
104
105
106
        my @config_files = map { $list->_load_include_admin_user_file($_) }
            @{$list->{'admin'}{$pname} || []};

        foreach my $ptype (sort keys %config_user_map) {
            my @config = grep {$_}
                map { @{$_->{$ptype} || []} } @config_files;
            # Special case: include_file is not paragraph.
            if ($ptype eq 'include_file') {
107
108
109
110
                @config = map {
                    my $name = substr [split m{/}, $_]->[-1], 0, 15;
                    {name => $name, path => $_};
                } @config;
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
            }
            my $type = $config_user_map{$ptype};
            push @dss, map {
                Sympa::DataSource->new($type, $role, context => $list, %$_)
            } @config;
        }
    }

    return [@dss];
}

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

    my $list = $request->{context};
    my $role = $request->{role};

129
130
    my $delay = $request->{delay};

131
    die 'bug in logic. Ask developer'
132
133
134
135
136
        unless $role and grep { $role eq $_ } qw(member owner editor);

    return 0
        unless $list->has_data_sources($role)
        or $list->has_included_users($role);
137
138
139
140

    my $dss = _get_data_sources($list, $role);

    # Get an Exclusive lock.
141
142
    my $lock_file = $list->{'dir'} . '/' . $role . '.include';
    my $lock_fh = Sympa::LockedFile->new($lock_file, -1, '+>>');
143
    unless ($lock_fh) {
144
145
        $log->syslog('info', '%s: Locked, skip inclusion', $list);
        $self->add_stash($request, 'notice', 'include_skip',
146
            {listname => $list->{'name'}, role => $role});
147
148
149
        return 0;
    }

IKEDA Soji's avatar
IKEDA Soji committed
150
151
    # I. Start.

152
153
154
    my (%start_times, $start_time);

    my $last_start_time;
IKEDA Soji's avatar
IKEDA Soji committed
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    seek $lock_fh, 0, 0;
    while (my $line = <$lock_fh>) {
        next unless $line =~ /\A(\w+)\s+(\d+)/;
        my $t = $2 + 0;
        $start_times{$1} = $t;

        $last_start_time = $t
            if not defined $last_start_time or $t < $last_start_time;
    }
    $start_time = time;
    if (defined $last_start_time and $start_time < $last_start_time) {
        # Avoid retrace of clock e.g. by outage of NTP server.
        $log->syslog('info', '%s: Clock got behind, skip inclusion', $list);
        $self->add_stash($request, 'notice', 'include_skip',
169
            {listname => $list->{'name'}, role => $role});
IKEDA Soji's avatar
IKEDA Soji committed
170
171
        return 0;
    }
172
173
174
175
176
177
178
179
180
181
182
    if (    defined $last_start_time
        and defined $delay
        and $start_time < $last_start_time + $delay) {
        # Skip inclusion if the last inclusion has not taken configured
        # duration.
        $log->syslog('info',
            '%s: The last inclusion is recent, skip inclusion', $list);
        $self->add_stash($request, 'notice', 'include_skip',
            {listname => $list->{'name'}, role => $role});
        return 0;
    }
IKEDA Soji's avatar
IKEDA Soji committed
183

184
    my $sdm = Sympa::DatabaseManager->instance;
IKEDA Soji's avatar
IKEDA Soji committed
185
    return undef unless $sdm;
186
    my $sth;
187
188
189
190
    my ($t, $r) =
          ($role eq 'member')
        ? ('subscriber', '')
        : ('admin', sprintf ' AND role_admin = %s', $sdm->quote($role));
191

192
193
    # II. Include new entries.

194
195
    my %result =
        (added => 0, deleted => 0, updated => 0, kept => 0, held => 0);
196
    my $succeeded = 0;
197
198
199
    foreach my $ds (@{$dss || []}) {
        $lock_fh->extend;

200
        next unless $ds->is_allowed_to_sync;
IKEDA Soji's avatar
IKEDA Soji committed
201
        my %res = _update_users($ds, $start_time);
202
203
204
205
206
207
208
209
210
211
212
213
        unless (%res) {
            $self->add_stash(
                $request, 'notice',
                'include_failed',
                {   listname => $list->{'name'},
                    role     => $role,
                    id       => $ds->get_short_id,
                    name     => $ds->name,
                }
            );
            next;
        }
214
215

        # Update time of allowed and succeeded data sources.
IKEDA Soji's avatar
IKEDA Soji committed
216
        $start_times{$ds->get_short_id} = $start_time;
217
        $succeeded++;
IKEDA Soji's avatar
IKEDA Soji committed
218
219
220
221

        # Special treatment for Sympa::DataSource::List.
        _update_inclusion_table($ds, $start_time)
            if ref $ds eq 'Sympa::DataSource::List';
222
223
224
225
226
227
228
229
230

        $log->syslog(
            'info', '%s: %d included, %d deleted, %d updated, %d kept',
            $ds,    @res{qw(added deleted updated kept)}
        );
        $self->add_stash(
            $request, 'notice',
            'include',
            {   listname => $list->{'name'},
231
                role     => $role,
232
233
234
                id       => $ds->get_short_id,
                name     => $ds->name,
                result   => {%res}
235
            }
236
237
238
        );
        foreach my $key (keys %res) {
            $result{$key} += $res{$key} if exists $result{$key};
239
        }
240
    }
241

242
243
    # III. Expire outdated entries.

244
245
    if ($succeeded == scalar @$dss) {
        # All data sources succeeded.
246
        $lock_fh->extend;
IKEDA Soji's avatar
IKEDA Soji committed
247

248
249
250
251
252
253
254
255
        # Choose most earlier time of succeeding inclusions (if any of
        # data sources have not succeeded yet, time is not known).
        my $last_start_time = $start_time;
        foreach my $id (map { $_->get_short_id } @$dss) {
            $last_start_time = $start_times{$id}
                if $start_times{$id} < $last_start_time;
        }

IKEDA Soji's avatar
IKEDA Soji committed
256
257
        my %res = _expire_users($list, $role, $last_start_time);
        unless (%res) {
IKEDA Soji's avatar
IKEDA Soji committed
258
            $self->add_stash($request, 'intern');
IKEDA Soji's avatar
IKEDA Soji committed
259
            #FIMXE: Report error.
260
261
            return undef;
        }
IKEDA Soji's avatar
IKEDA Soji committed
262
263
        foreach my $key (keys %res) {
            $result{$key} += $res{$key} if exists $result{$key};
264
        }
IKEDA Soji's avatar
IKEDA Soji committed
265

266
        # Special treatment for Sympa::DataSource::List.
IKEDA Soji's avatar
IKEDA Soji committed
267
        _expire_inclusion_table($list, $role, $last_start_time);
268
    } else {
269
        # Part(s) or entire data sources failed.
270
271
272
273
274
275
276
277
278
279
280
281
282
        $lock_fh->extend;

        # Estimate number of held users, i.e. users not decided to
        # delete, update nor keep.
        my %res = _expire_users($list, $role, $start_time, dry_run => 1);
        unless (%res) {
            $self->add_stash($request, 'intern');
            #FIMXE: Report error.
            return undef;
        }
        foreach my $key (keys %res) {
            $result{$key} += $res{$key} if exists $result{$key};
        }
IKEDA Soji's avatar
IKEDA Soji committed
283
    }
284

285
    # IV. Update custom attributes.
286

IKEDA Soji's avatar
IKEDA Soji committed
287
    if ($role eq 'member') {
IKEDA Soji's avatar
IKEDA Soji committed
288
289
290
        foreach
            my $ds (@{_get_data_sources($list, 'custom_attribute') || []}) {
            next unless $ds->is_allowed_to_sync;
291

IKEDA Soji's avatar
IKEDA Soji committed
292
293
            $lock_fh->extend;
            _update_custom_attribute($ds);
294
295
296
        }
    }

297
    # V. Finish.
298

299
300
301
302
303
304
    # Write out updated times of succeeding inclusions.
    my $ofh;
    unless (open $ofh, '>', $lock_file . '.new') {
        $log->syslog('err', 'Can\'t open file %s: %m', $lock_file . '.new');
        $self->add_stash($request, 'intern');
        return undef;
305
    }
306
    foreach my $id (map { $_->get_short_id } @$dss) {
IKEDA Soji's avatar
IKEDA Soji committed
307
308
        printf $ofh "%s %d\n", $id, $start_times{$id}
            if defined $start_times{$id};
309
310
311
312
313
314
315
316
317
318
    }
    close $ofh;
    unlink $lock_file . '.old';
    unless ($lock_fh->rename($lock_file . '.old')
        and rename($lock_file . '.new', $lock_file)) {
        $log->syslog('err', 'Can\'t update file %s: %m', $lock_file);
        $self->add_stash($request, 'intern');
        return undef;
    }
    unlink $lock_file . '.old';
319

320
321
    if ($succeeded == scalar @$dss) {
        # All data sources succeeded.
322
        $log->syslog(
323
            'info',   '%s: Success, %d added, %d deleted, %d updated',
324
325
326
327
328
            $request, @result{qw(added deleted updated)}
        );
        $self->add_stash($request, 'notice', 'include_performed',
            {listname => $list->{'name'}, role => $role, result => {%result}}
        );
329
330
331
332
333
334
335
336
337
    } elsif ($succeeded) {
        # Part(s) of data sources failed.
        $log->syslog(
            'info',   '%s: Partial, %d added, %d held, %d updated',
            $request, @result{qw(added held updated)}
        );
        $self->add_stash($request, 'notice', 'include_partial',
            {listname => $list->{'name'}, role => $role, result => {%result}}
        );
338
    } else {
339
        # All data sources failed.
340
        $log->syslog(
341
            'info',   '%s: Failure, %d added, %d held, %d updated',
342
343
344
345
346
347
            $request, @result{qw(added held updated)}
        );
        $self->add_stash($request, 'notice', 'include_incomplete',
            {listname => $list->{'name'}, role => $role, result => {%result}}
        );
    }
348
349
350
351
352
353
354
355
356
357
358
359
360

    # Compatibility to Sympa::List::_cache_*() that will be removed in near
    # future: If inclusion succeeded, reset cache.
    if ($succeeded == scalar @$dss or $succeeded) {
        my $stat_file;
        if ($role eq 'owner' or $role eq 'editor') {
            $stat_file = $list->{'dir'} . '/.last_change.admin';
        } else {
            $stat_file = $list->{'dir'} . '/.last_change.member';
        }
        unlink $stat_file;
    }

361
362
363
    return 1;
}

IKEDA Soji's avatar
IKEDA Soji committed
364
365
# Internal function.
sub _update_users {
366
    my $ds         = shift;
IKEDA Soji's avatar
IKEDA Soji committed
367
    my $start_time = shift;
368
369

    return unless $ds->open;
370
371
372
373
374
375
376
377
378
379
380
381
382
    my $list = $ds->{context};
    my $role = $ds->role;

    my $sdm = Sympa::DatabaseManager->instance;
    return undef unless $sdm;

    my ($t, $r) =
        ($role eq 'member')
            ? ('subscriber', '')
            : ('admin', sprintf ' AND role_admin = %s', $sdm->quote($role));

    my $is_external_ds = not (ref $ds eq 'Sympa::DataSource::List'
        and [ split /\@/, $ds->{listname}, 2 ]->[1] eq $list->{'domain'});
383
384

    my %result = (added => 0, deleted => 0, updated => 0, kept => 0);
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

    my $time = time;
    # Avoid retrace of clock e.g. by outage of NTP server.
    $time = $start_time unless $start_time <= time;

    my $user_query;
    $user_query = $sdm->do_prepared_query(qq{ SELECT user_$t, inclusion_$t, inclusion_ext_$t
                    FROM ${t}_table
                    WHERE list_$t = ? AND robot_$t = ?$r
                   }, $list->{'name'}, $list->{'domain'});

    my %users = ();

    while (my @row = $user_query->fetchrow_array) {
        my $user_email = $row[0];
        my $user_inclusion = $row[1];
        my $user_inclusion_ext = $row[2];
        $users{$user_email} = [ $user_inclusion, $user_inclusion_ext ];
    }

    my %exclusion_list;
    my $exclusion_list_query = $sdm->do_prepared_query(q{SELECT user_exclusion
                        FROM exclusion_table
                        WHERE list_exclusion = ?  AND
                        robot_exclusion = ?},
        $list->{'name'},
        $list->{'domain'});

    while (my @row = $exclusion_list_query->fetchrow_array) {
        $exclusion_list{$row[0]} = 1;
    }

    my %to_be_inserted;

    $sdm->__dbh->begin_work;

421
    while (my $entry = $ds->next) {
422
        my ($email, $gecos) = @$entry;
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
        next unless Sympa::Tools::Text::valid_email($email);
        $email = Sympa::Tools::Text::canonic_email($email);


        # 1. If role of the data source is 'member' and the user is excluded:
        #    Do nothing.
        next (none => 0) if $role eq 'member' and exists $exclusion_list{$email};

        if (exists $users{$email}) {

            # 2. Keep
            if ($is_external_ds) {
                if ($users{$email}[0] ne "" && $start_time <= int($users{$email}[0])
                    && $users{$email}[1] ne "" && $start_time <= int($users{$email}[1])) {
                    $result{'kept'}++;
                    next;
                }
            }
            else {

                if ($users{$email}[0] ne "" && $start_time <= int($users{$email}[0])) {
                    $result{'kept'}++;
                    next;
                }
            }

            # 3. Update
            my %res = __update_user($ds, $email, $start_time, $list, $t, $r, $is_external_ds, $time);

            unless (%res) {
                $ds->close;
                $log->syslog('info', '%s: Aborted update', $ds);
                $sdm->__dbh->rollback;
                return;
            }
            foreach my $res (keys %res) {
                $result{$res} += $res{$res} if exists $result{$res};
            }
462
        }
463
464
465
466
467
468
469
470
471
472
        else {
            $to_be_inserted{$email} = $gecos;
        }
    }

    unless ($sdm->__dbh->{AutoCommit}) {
        my $rc = $sdm->__dbh->commit;
        unless ($rc) {
            $log->syslog('err', 'Error at update user commit: %s', $sdm->errstr);
            $sdm->__dbh->rollback;
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
    my @list_of_new_users;
    for (keys %to_be_inserted) {
        my $user = {
            email           => $_,
            gecos           => $to_be_inserted{$_},
            subscribed      => 0,
            date            => $time,
            update_date     => $time,
            inclusion       => $time,
            ($is_external_ds ? (inclusion_ext => $time) : ()),
            inclusion_label => $ds->name,
        };
        my @defkeys = @{$ds->{_defkeys} || []};
        my @defvals = @{$ds->{_defvals} || []};
        @{$user}{@defkeys} = @defvals if @defkeys;

        push(@list_of_new_users, $user);
        $result{'added'}++;

    }

    # 4. Otherwise, i.e. a new user:
    #    INSERT new user with:
    #    email, gecos, subscribed=0, date, update, inclusion,
    #    (optional) inclusion_ext, inclusion_label and
    #    default attributes.
    if ($role eq 'member') {
        $list->add_list_member(@list_of_new_users);

        foreach my $new_user (@list_of_new_users) {
            if ($list->{'admin'}{'inclusion_notification_feature'} eq 'on') {
                unless ($list->send_probe_to_user('welcome', $new_user->{'email'})) {
                    $log->syslog('err',
                        'Unable to send "welcome" probe to %s', $new_user->{'email'});
                }
            }

        }
    }
    else {
        $list->add_list_admin($role, @list_of_new_users);
    }
518
519
520
521
522
523
    $ds->close;

    return %result;
}

# Internal function.
IKEDA Soji's avatar
IKEDA Soji committed
524
sub __update_user {
525
526
527
528
529
530
531
532
    my $ds             = shift;
    my $email          = shift;
    my $start_time     = shift;
    my $list           = shift;
    my $t              = shift;
    my $r              = shift;
    my $is_external_ds = shift;
    my $time           = shift;
533

534
    my $sdm = Sympa::DatabaseManager->instance;
IKEDA Soji's avatar
IKEDA Soji committed
535
    return undef unless $sdm;
536
537
538
    my $sth;


539
540
    # 3. If user (has not been updated by the other data sources and) exists:
    #    UPDATE inclusion.
541
    if ($is_external_ds) {
542
543
544
        # Already updated by the other non-external data source but not yet
        # by any other external ones:
        # Update inclusion_ext (and inclusion) field, but not inclusion_label.
545
546
547
548
549
550
551
552
553
554
555
        return unless $sth = $sdm->do_prepared_query(
            qq{UPDATE ${t}_table
               SET inclusion_$t = ?, inclusion_ext_$t = ?
               WHERE user_$t = ? AND list_$t = ? AND robot_$t = ?$r AND
                     inclusion_$t IS NOT NULL AND ? <= inclusion_$t},
            $time, $time,
            $email, $list->{'name'}, $list->{'domain'},
            $start_time
        );
        return (updated => 0) if $sth->rows;

556
557
        # Not yet updated by any other data sources:
        # Update inclusion_ext (and inclusion), and assign inclusion_label.
558
559
        return unless $sth = $sdm->do_prepared_query(
            qq{UPDATE ${t}_table
560
               SET inclusion_$t = ?, inclusion_ext_$t = ?,
IKEDA Soji's avatar
IKEDA Soji committed
561
                   inclusion_label_$t = ?
562
563
               WHERE user_$t = ? AND list_$t = ? AND robot_$t = ?$r},
            $time, $time,
564
            $ds->name,
565
566
            $email, $list->{'name'}, $list->{'domain'}
        );
567
        return (updated => 1) if $sth->rows;
568
    } else {
569
570
        # Not yet updated by any other data sources:
        # Update inclusion, and assign inclusion_label.
571
572
        return unless $sth = $sdm->do_prepared_query(
            qq{UPDATE ${t}_table
573
574
               SET inclusion_$t = ?,
                   inclusion_label_$t = ?
575
576
               WHERE user_$t = ? AND list_$t = ? AND robot_$t = ?$r},
            $time,
577
            $ds->name,
578
579
            $email, $list->{'name'}, $list->{'domain'}
        );
580
        return (updated => 1) if $sth->rows;
581
    }
582

583
584
}

IKEDA Soji's avatar
IKEDA Soji committed
585
586
587
588
sub _expire_users {
    my $list            = shift;
    my $role            = shift;
    my $last_start_time = shift;
589
    my %options         = @_;
IKEDA Soji's avatar
IKEDA Soji committed
590
591
592
593
594
595
596
597
598

    my $sdm = Sympa::DatabaseManager->instance;
    return unless $sdm;
    my $sth;
    my ($t, $r) =
          ($role eq 'member')
        ? ('subscriber', '')
        : ('admin', sprintf ' AND role_admin = %s', $sdm->quote($role));

599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
    if ($options{dry_run}) {
        unless (
            $sth = $sdm->do_prepared_query(
                qq{SELECT COUNT(*)
               FROM ${t}_table
               WHERE (subscribed_$t IS NULL OR subscribed_$t <> 1) AND
                     inclusion_$t IS NOT NULL AND inclusion_$t < ? AND
                     list_$t = ? AND robot_$t = ?$r},
                $last_start_time,
                $list->{'name'}, $list->{'domain'}
            )
        ) {
            return undef;
        }
        my ($count) = $sth->fetchrow_array;
        $sth->finish;

        return (held => ($count || 0));
    }

IKEDA Soji's avatar
IKEDA Soji committed
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
    my $deleted = 0;
    # Remove list users not subscribing (only included) and
    # not included anymore.
    unless (
        $sth = $sdm->do_prepared_query(
            qq{SELECT user_$t AS email
               FROM ${t}_table
               WHERE (subscribed_$t IS NULL OR subscribed_$t <> 1) AND
                     inclusion_$t IS NOT NULL AND inclusion_$t < ? AND
                     list_$t = ? AND robot_$t = ?$r},
            $last_start_time,
            $list->{'name'}, $list->{'domain'}
        )
    ) {
        return;
    } else {
        my @emails = map { $_->[0] } @{$sth->fetchall_arrayref || []};
        $sth->finish;

638
639
640
641
642
643
644
        if ($role eq 'member') {
            $list->delete_list_member(users => \@emails);
        }
        else {
            $list->delete_list_admin($role, \@emails);
        }

IKEDA Soji's avatar
IKEDA Soji committed
645
        foreach my $email (@emails) {
646
647
648
649
650
651
652
            # Send notification if the list config authorizes it only.
            if ($list->{'admin'}{'inclusion_notification_feature'} eq
                'on') {
                unless (Sympa::send_file($list, 'removed', $email, {})) {
                    $log->syslog('err',
                        'Unable to send template "removed" to %s',
                        $email);
IKEDA Soji's avatar
IKEDA Soji committed
653
654
655
656
657
658
659
660
661
662
663
                }
            }
            $deleted += 1;
        }
    }

    # Cancel inclusion of users subscribing (and also included) and
    # not included anymore.
    unless (
        $sdm->do_prepared_query(
            qq{UPDATE ${t}_table
664
665
               SET inclusion_$t = NULL, inclusion_ext_$t = NULL,
                   inclusion_label_$t = NULL
IKEDA Soji's avatar
IKEDA Soji committed
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
               WHERE subscribed_$t = 1 AND
                     inclusion_$t IS NOT NULL AND inclusion_$t < ? AND
                     list_$t = ? AND robot_$t = ?$r},
            $last_start_time,
            $list->{'name'}, $list->{'domain'}
        )
        and $sdm->do_prepared_query(
            qq{UPDATE ${t}_table
               SET inclusion_ext_$t = NULL
               WHERE subscribed_$t = 1 AND
                     inclusion_ext_$t IS NOT NULL AND inclusion_ext_$t < ? AND
                     list_$t = ? AND robot_$t = ?$r},
            $last_start_time,
            $list->{'name'}, $list->{'domain'}
        )
    ) {
        #FIXME: report error
    }

    return (deleted => $deleted);
}

# Internal function.
689
690
691
692
# Update inclusion_table: This feature was added on 6.2.16.
# Related only to Sympa::DataSource::List class.
# Old name: (part of) Sympa::List::_update_inclusion_table().
sub _update_inclusion_table {
693
    my $ds         = shift;
IKEDA Soji's avatar
IKEDA Soji committed
694
    my $start_time = shift;
695
696
697
698
699
700

    my $list   = $ds->{context};
    my $role   = $ds->role;
    my $inlist = Sympa::List->new($ds->{listname});

    my $time = time;
701
    # Avoid retrace of clock e.g. by outage of NTP server.
IKEDA Soji's avatar
IKEDA Soji committed
702
    $time = $start_time unless $start_time <= $time;
703
704

    my $sdm = Sympa::DatabaseManager->instance;
IKEDA Soji's avatar
IKEDA Soji committed
705
    return undef unless $sdm;
706
707
708
    my $sth;

    unless (
IKEDA Soji's avatar
IKEDA Soji committed
709
        $sth = $sdm->do_prepared_query(
710
            q{UPDATE inclusion_table
IKEDA Soji's avatar
IKEDA Soji committed
711
712
713
714
715
716
              SET update_epoch_inclusion = ?
              WHERE target_inclusion = ? AND
                    role_inclusion = ? AND
                    source_inclusion = ? AND
                    (update_epoch_inclusion IS NULL OR
                     update_epoch_inclusion < ?)},
717
718
719
            $time, $list->get_id, $role, $inlist->get_id, $time
        )
        and $sth->rows
IKEDA Soji's avatar
IKEDA Soji committed
720
        or $sth = $sdm->do_prepared_query(
721
            q{INSERT INTO inclusion_table
IKEDA Soji's avatar
IKEDA Soji committed
722
723
724
              (target_inclusion, role_inclusion, source_inclusion,
               update_epoch_inclusion)
              VALUES (?, ?, ?, ?)},
725
726
727
728
729
730
731
732
733
734
735
            $list->get_id, $role, $inlist->get_id, $time
        )
        and $sth->rows
    ) {
        $log->syslog('err', 'Unable to update list %s in database', $list);
        return undef;
    }

    return 1;
}

IKEDA Soji's avatar
IKEDA Soji committed
736
# Internal function.
737
738
# Old name: (part of) Sympa::List::_update_inclusion_table().
# Related only to Sympa::DataSource::List class.
IKEDA Soji's avatar
IKEDA Soji committed
739
740
741
742
sub _expire_inclusion_table {
    my $list            = shift;
    my $role            = shift;
    my $last_start_time = shift;
743
744
745
746
747
748

    my $sdm = Sympa::DatabaseManager->instance;
    $sdm and $sdm->do_prepared_query(
        q{DELETE FROM inclusion_table
          WHERE target_inclusion = ? AND role_inclusion = ? AND
                update_epoch_inclusion < ?},
IKEDA Soji's avatar
IKEDA Soji committed
749
750
        $list->get_id, $role,
        $last_start_time
751
752
753
    );
}

IKEDA Soji's avatar
IKEDA Soji committed
754
755
756
757
758
759
760
761
762
763
764
765
766
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
# Internal function.
sub _update_custom_attribute {
    my $ds = shift;

    die 'bug in logic. Ask developer' unless $ds->role eq 'custom_attribute';

    return unless $ds->open;

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

    my $updated = 0;
    while (my $entry = $ds->next) {
        my ($email, $ca_update) = @$entry;

        my $member = $list->get_list_member($email);
        next unless $member;
        my $ca = $member->{custom_attribute} || {};

        my $changed;
        foreach my $key (sort keys %{$ca_update || {}}) {
            my $cur = $ca->{$key};
            $cur = '' unless defined $cur;
            my $new = $ca_update->{$key};
            $new = '' unless defined $new;
            next if $cur eq $new;

            $ca->{$key} = $new;
            $changed = 1;
        }
        next unless $changed;

        $list->update_list_member($email, custom_attribute => $ca_update);
        $updated++;
    }

    $ds->close;

    return (updated => $updated);
}

794
795
# Enforce uniqueness in a comma separated list of user source ID's.
# Old name: (part of) Sympa::List::add_source_id().
796
797
# No longer used.
#sub _add_source_id;
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816

# Returns a real unique ID for an include datasource.
sub get_id {
    shift->{context};
}

1;
__END__

=encoding utf-8

=head1 NAME

Sympa::Request::Hander::include - include request handler

=head1 DESCRIPTION

Includes users from data sources to a list.

IKEDA Soji's avatar
IKEDA Soji committed
817
Opens data sources, include or update list users with each of them and closes.
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
TBD.

=head1 SEE ALSO

L<Sympa::DataSource>, L<Sympa::List>.

L<"admin_table"|sympa_database(5)/"admin_table">,
L<"exclusion_table"|sympa_database(5)/"exclusion_table">,
L<"inclusion_table"|sympa_database(5)/"inclusion_table"> and
L<"subscriber_table"|sympa_database(5)/"subscriber_table">
in L<sympa_database(5)>.

=head1 HISTORY

The feature to include subscribers from data sources was introduced on
Sympa 3.3.6b.4.
Inclusion of owners and moderators was introduced on Sympa 4.2b.5.

L<Datasource> module appeared on Sympa 5.3a.9.
Entirely rewritten and renamed L<Sympa::DataSource> module and
838
L<Sympa::Request::Hander::include> module appeared on Sympa 6.2.45b.
839
840

=cut