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

5
# Sympa - SYsteme de Multi-Postage Automatique
6
7
8
9
#
# Copyright (c) 1997, 1998, 1999 Institut Pasteur & Christophe Wolfhugel
# Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
# 2006, 2007, 2008, 2009, 2010, 2011 Comite Reseau des Universites
10
# Copyright (c) 2011, 2012, 2013, 2014, 2015, 2016, 2017 GIP RENATER
11
12
# Copyright 2017, 2018 The Sympa Community. See the AUTHORS.md file at the
# top-level directory of this distribution and at
13
# <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
=encoding utf-8
29

30
31
32
#=head1 NAME 
#
#I<Family.pm> - Handles list families
33
34
35
36
37
38
39

=head1 DESCRIPTION 

Sympa allows lists creation and management by sets. These are the families, sets of lists sharing common properties. This module gathers all the family-specific operations.

=cut 

40
package Sympa::Family;
41
42

use strict;
43
use warnings;
44
use English qw(-no_match_vars);
45
use File::Copy qw();
46
use Term::ProgressBar;
47
use XML::LibXML;
48

49
use Sympa;
50
use Sympa::Aliases;
51
use Conf;
52
use Sympa::Config_XML;
53
use Sympa::DatabaseManager;
54
use Sympa::List;
55
use Sympa::LockedFile;
56
use Sympa::Log;
57
use Sympa::Regexps;
58
59
use Sympa::Spindle::ProcessRequest;
use Sympa::Template;
60
use Sympa::Tools::File;
61

IKEDA Soji's avatar
IKEDA Soji committed
62
my $log = Sympa::Log->instance;
63

64
my %list_of_families;
65
66
67
68
69
my @uncompellable_param = (
    'msg_topic.keywords',
    'owner_include.source_parameters',
    'editor_include.source_parameters'
);
70

71
72
73
74
75
76
77
78
79
80
81
82
83
84
=pod 

=head1 SUBFUNCTIONS 

This is the description of the subfunctions contained by Family.pm

=cut 

=pod 

=head1 Class methods 

=cut 

85
86
87
## Class methods
################

88
=head2 sub get_families(Robot $robot)
89
90
91
92
93
94
95

Returns the list of existing families in the Sympa installation.

=head3 Arguments 

=over 

96
=item * I<$robot>, the robot the family list of which we want to get.
97
98
99

=back 

100
=head3 Returns
101
102
103

=over 

104
=item * An arrayref containing all the robot's family names.
105
106
107
108
109

=back 

=cut

110
111
sub get_families {
    my $robot_id = shift;
112

113
    my @families;
114

115
    foreach my $dir (
116
        reverse @{Sympa::get_search_path($robot_id, subdir => 'families')}) {
117
        next unless -d $dir;
118
119

        unless (opendir FAMILIES, $dir) {
120
            $log->syslog('err', 'Can\'t open dir %s: %m', $dir);
121
122
123
            next;
        }

124
        # If we can create a Sympa::Family object with what we find in the
125
        # family directory, then it is worth being added to the list.
126
        foreach my $subdir (grep !/^\.\.?$/, readdir FAMILIES) {
127
            next unless -d ("$dir/$subdir");
128
            if (my $family = Sympa::Family->new($subdir, $robot_id)) {
129
                push @families, $family;
130
131
132
133
            }
        }
    }

134
    return \@families;
135
}
136

137
138
139
140
141
142
sub get_available_families {
    my $robot_id = shift;
    my $families;
    my %hash;
    if ($families = get_families($robot_id)) {
        foreach my $family (@$families) {
143
            if (ref $family eq 'Sympa::Family') {
144
145
146
147
148
149
150
151
                $hash{$family->{'name'}} = $family;
            }
        }
        return %hash;
    } else {
        return undef;
    }
}
152
153
154
155
156

=head1 Instance methods 

=cut 

157
158
159
## Instance methods
###################

160
161
162
163
=pod 

=head2 sub new(STRING $name, STRING $robot)

164
Creates a new Sympa::Family object of name $name, belonging to the robot $robot.
165
166
167
168
169

=head3 Arguments 

=over 

170
=item * I<$class>, the class in which we're supposed to create the object (namely "Sympa::Family"),
171
172
173
174
175
176
177
178
179
180
181

=item * I<$name>, a character string containing the family name,

=item * I<$robot>, a character string containing the name of the robot which the family is/will be installed in.

=back 

=head3 Return 

=over 

182
=item * I<$self>, the Sympa::Family object 
183
184
185
186
187

=back 

=cut

188
#########################################
189
# new
190
#########################################
191
# constructor of the class Sympa::Family :
192
193
194
#   check family existence (required files
#   and directory)
#
195
# IN : -$class
196
197
198
199
200
201
#      -$name : family name
#      -robot : family robot
# OUT : -$self
#########################################
sub new {
    my $class = shift;
202
    my $name  = shift;
203
    my $robot = shift;
204
    $log->syslog('debug2', '(%s, %s)', $name, $robot);
205

206
207
    my $self = {};

208
    if ($list_of_families{$robot}{$name}) {
209
        # use the current family in memory and update it
210
        $self = $list_of_families{$robot}{$name};
211
###########
212
213
214
215
216
217
        # the robot can be different from latest new ...
        if ($robot eq $self->{'robot'}) {
            return $self;
        } else {
            $self = {};
        }
218
    }
219
220
221
    # create a new object family
    bless $self, $class;
    $list_of_families{$robot}{$name} = $self;
222

223
    my $family_name_regexp = Sympa::Regexps::family_name();
224

225
    ## family name
226
    unless ($name && ($name =~ /^$family_name_regexp$/io)) {
227
        $log->syslog('err', 'Incorrect family name "%s"', $name);
228
        return undef;
229
230
231
232
233
234
235
236
    }

    ## Lowercase the family name.
    $name =~ tr/A-Z/a-z/;
    $self->{'name'} = $name;

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

237
    ## Adding configuration related to automatic lists.
238
239
    my $all_families_config =
        Conf::get_robot_conf($robot, 'automatic_list_families');
240
241
    my $family_config = $all_families_config->{$name};
    foreach my $key (keys %{$family_config}) {
242
        $self->{$key} = $family_config->{$key};
243
244
    }

245
246
247
    ## family directory
    $self->{'dir'} = $self->_get_directory();
    unless (defined $self->{'dir'}) {
248
        $log->syslog('err', '(%s, %s) The family directory does not exist',
249
250
            $name, $robot);
        return undef;
251
252
253
    }

    ## family files
254
    if (my $file_names = $self->_check_mandatory_files()) {
255
256
        $log->syslog('err',
            '(%s, %s) Definition family files are missing: %s',
257
258
            $name, $robot, $file_names);
        return undef;
259
260
261
    }

    ## file mtime
262
    $self->{'mtime'}{'param_constraint_conf'} = undef;
263

264
265
266
    ## hash of parameters constraint
    $self->{'param_constraint_conf'} = undef;

267
268
    ## state of the family for the use of check_param_constraint : 'no_check'
    ## or 'normal'
269
    ## check_param_constraint  only works in state "normal"
270
    $self->{'state'} = 'normal';
271
272
    return $self;
}
273

274
275
# Merged to: Sympa::Request::Handler::create_automatic_list::_twist().
#sub add_list;
276

277
278
279
280
281
282
283
284
285
286
=pod 

=head2 sub modify_list(FILE_HANDLE $fh)

Adds a list to the family.

=head3 Arguments 

=over 

287
=item * I<$self>, the Sympa::Family object,
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302

=item * I<$fh>, a file handle on the XML B<list> configuration file.

=back 

=head3 Return 

=over 

=item * I<$return>, a ref to a hash containing the execution state of the method. If everything went well, the "ok" key must be associated to the value "1".

=back 

=cut

303
#########################################
304
# modify_list
305
306
307
#########################################
# modify a list that belongs to the family
#  under to current robot:
308
# (the list modifications are described by the xml file)
309
#
310
311
312
# IN : -$self
#      -$fh : file handle on the xml file
# OUT : -$return->{'ok'} = 1(pas d'erreur fatale) or undef(erreur fatale)
313
#       -$return->{'string'} : string of results
314
315
316
#########################################
sub modify_list {
    my $self = shift;
317
    my $fh   = shift;
318
    $log->syslog('info', '(%s)', $self->{'name'});
319
320
321

    $self->{'state'} = 'no_check';
    my $return;
322
323
324
    $return->{'ok'}           = undef;
    $return->{'string_info'}  = undef;    ## info and simple errors
    $return->{'string_error'} = undef;    ## fatal errors
325
326

    #copy the xml file in another file
327
    unless (open FIC, '>', $self->{'dir'} . '/_mod_list.xml') {
328
        $log->syslog('err',
329
330
            'Impossible to create the temp file %s/_mod_list.xml: %m',
            $self->{'dir'});
331
332
    }
    while (<$fh>) {
333
        print FIC ($_);
334
335
336
337
    }
    close FIC;

    # get list data
338
    open(FIC, '<:raw', $self->{'dir'} . '/_mod_list.xml');
339
    my $config = Sympa::Config_XML->new(\*FIC);
340
341
    close FIC;
    unless (defined $config->createHash()) {
342
343
344
345
        push @{$return->{'string_error'}},
            "Error in representation data with these xml data";
        return $return;
    }
346
347

    my $hash_list = $config->getHash();
348
349
    # Compatibility: single topic on 6.2.24 or earlier.
    $hash_list->{config}{topics} ||= $hash_list->{config}{topic};
350
351
352
353
    # In old documentation "moderator" was single or multiple editors.
    my $mod = $hash_list->{config}{moderator};
    $hash_list->{config}{editor} ||=
        (ref $mod eq 'ARRAY') ? $mod : (ref $mod eq 'HASH') ? [$mod] : [];
354
355
356

    #getting list
    my $list;
sikeda's avatar
sikeda committed
357
358
359
360
361
    unless (
        $list = Sympa::List->new(
            $hash_list->{'config'}{'listname'}, $self->{'robot'}
        )
        ) {
362
363
364
        push @{$return->{'string_error'}},
            "The list $hash_list->{'config'}{'listname'} does not exist.";
        return $return;
365
    }
366

367
368
    ## check family name
    if (defined $list->{'admin'}{'family_name'}) {
369
370
371
372
373
        unless ($list->{'admin'}{'family_name'} eq $self->{'name'}) {
            push @{$return->{'string_error'}},
                "The list $list->{'name'} already belongs to family $list->{'admin'}{'family_name'}.";
            return $return;
        }
374
    } else {
375
376
377
        push @{$return->{'string_error'}},
            "The orphan list $list->{'name'} already exists.";
        return $return;
378
379
380
381
382
    }

    ## get allowed and forbidden list customizing
    my $custom = $self->_get_customizing($list);
    unless (defined $custom) {
383
        $log->syslog('err', 'Impossible to get list %s customizing',
384
385
386
            $list->{'name'});
        push @{$return->{'string_error'}},
            "Error during updating list $list->{'name'}, the list is set in status error_config.";
387
        $list->set_status_error_config('modify_list_family', $self->{'name'});
388
        return $return;
389
    }
390
391
    my $config_changes = $custom->{'config_changes'};
    my $old_status     = $list->{'admin'}{'status'};
392
393

    ## list config family updating
394
    my $result = $self->_update_list($list, $hash_list->{'config'});
395
    unless (defined $result) {
396
        $log->syslog('err', 'No object list resulting from updating list %s',
397
398
399
            $list->{'name'});
        push @{$return->{'string_error'}},
            "Error during updating list $list->{'name'}, the list is set in status error_config.";
400
        $list->set_status_error_config('modify_list_family', $self->{'name'});
401
        return $return;
402
403
    }
    $list = $result;
404

405
406
    ## set list customizing
    foreach my $p (keys %{$custom->{'allowed'}}) {
407
408
        $list->{'admin'}{$p} = $custom->{'allowed'}{$p};
        delete $list->{'admin'}{'defaults'}{$p};
409
        $log->syslog('info', 'Customizing: Keeping values for parameter %s',
410
            $p);
411
412
413
414
    }

    ## info file
    unless ($config_changes->{'file'}{'info'}) {
415
416
417
418
        $hash_list->{'config'}{'description'} =~ s/\r\n|\r/\n/g;

        unless (open INFO, '>', "$list->{'dir'}/info") {
            push @{$return->{'string_info'}},
419
420
                sprintf('Impossible to create new %s/info file: %s',
                $list->{'dir'}, $ERRNO);
421
422
423
        }
        print INFO $hash_list->{'config'}{'description'};
        close INFO;
424
425
426
    }

    foreach my $f (keys %{$config_changes->{'file'}}) {
427
        $log->syslog('info', 'Customizing: This file has been changed: %s',
428
            $f);
429
    }
430

431
    ## rename forbidden files
432
433
434
435
436
437
438
439
440
441
442
443
444
445
    #foreach my $f (@{$custom->{'forbidden'}{'file'}}) {
    #    unless (rename "$list->{'dir'}"."/"."info",
    #        "$list->{'dir'}"."/"."info.orig") {
    #        ###############
    #    }
    #    if ($f eq 'info') {
    #        $hash_list->{'config'}{'description'} =~ s/\r\n|\r/\n/g;
    #        unless (open INFO, '>', "$list_dir/info") {
    #            ###############
    #        }
    #        print INFO $hash_list->{'config'}{'description'};
    #        close INFO;
    #    }
    #}
446
447

    ## notify owner for forbidden customizing
448
449
450
    if (    #(scalar $custom->{'forbidden'}{'file'}) ||
        (scalar @{$custom->{'forbidden'}{'param'}})
        ) {
451
        #my $forbidden_files = join(',',@{$custom->{'forbidden'}{'file'}});
452
        my $forbidden_param = join(',', @{$custom->{'forbidden'}{'param'}});
453
        $log->syslog('notice',
454
455
456
            "These parameters aren't allowed in the new family definition, they are erased by a new instantiation family : \n $forbidden_param"
        );

457
458
        $list->send_notify_to_owner('erase_customizing',
            [$self->{'name'}, $forbidden_param]);
459
460
461
    }

    ## status
462
    $result = $self->_set_status_changes($list, $old_status);
463
464

    if ($result->{'aliases'} == 1) {
465
        push @{$return->{'string_info'}},
466
            sprintf('The %s list has been modified.', $list->{'name'});
467
468
    } elsif ($result->{'install_remove'} eq 'install') {
        push @{$return->{'string_info'}},
469
            sprintf('List %s has been modified, required aliases.',
470
            $list->{'name'});
471
472
    } else {
        push @{$return->{'string_info'}},
473
            sprintf('List %s has been modified, aliases need to be removed.',
474
            $list->{'name'});
475
476
477
478
479
    }

    ## config_changes
    foreach my $p (@{$custom->{'forbidden'}{'param'}}) {

480
481
482
        if (defined $config_changes->{'param'}{$p}) {
            delete $config_changes->{'param'}{$p};
        }
483
484
485

    }

486
    unless (open FILE, '>', "$list->{'dir'}/config_changes") {
487
        $list->set_status_error_config('error_copy_file', $self->{'name'});
488
        push @{$return->{'string_info'}},
489
490
491
            sprintf
            'Impossible to create file %s/config_changes : %s, the list is set in status error_config.',
            $list->{'dir'}, $ERRNO;
492
493
494
495
    }
    close FILE;

    my @kept_param = keys %{$config_changes->{'param'}};
496
    $list->update_config_changes('param', \@kept_param);
497
    my @kept_files = keys %{$config_changes->{'file'}};
498
    $list->update_config_changes('file', \@kept_files);
499

500
501
    $list->{'admin'}{'latest_instantiation'}{'email'} =
        Sympa::get_address($self, 'listmaster');
502
    $list->{'admin'}{'latest_instantiation'}{'date_epoch'} = time;
503
    $list->save_config(Sympa::get_address($self, 'listmaster'));
504
    $list->{'family'} = $self;
505
506

    ## check param_constraint.conf
507
508
509
    $self->{'state'} = 'normal';
    my $error = $self->check_param_constraint($list);
    $self->{'state'} = 'no_check';
510

511
    unless (defined $error) {
512
        $list->set_status_error_config('no_check_rules_family',
513
            $self->{'name'});
514
        push @{$return->{'string_error'}},
515
            "Impossible to check parameters constraint, see logs for more information. The list is set in status error_config";
516
        return $return;
517
    }
518

519
    if (ref($error) eq 'ARRAY') {
520
        $list->set_status_error_config('no_respect_rules_family',
521
            $self->{'name'});
522
523
524
        push @{$return->{'string_info'}},
            "The list does not respect the family rules : "
            . join(", ", @{$error});
525
    }
526

527
528
    ## copy files in the list directory : xml file

529
    unless ($self->_copy_files($list->{'dir'}, "_mod_list.xml")) {
530
        $list->set_status_error_config('error_copy_file', $self->{'name'});
531
532
        push @{$return->{'string_info'}},
            "Impossible to copy the xml file in the list directory, the list is set in status error_config.";
533
534
    }

535
536
    ## Synchronize list members if required
    if ($list->has_include_data_sources()) {
537
        $log->syslog('notice', "Synchronizing list members...");
538
        $list->sync_include();
539
540
    }

541
542
    ## END
    $self->{'state'} = 'normal';
543
    $return->{'ok'}  = 1;
544
545
546
547

    return $return;
}

548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# update a list : used by sympa.pl--instantiate_family
# with family concept when the list already exists
#
# IN  : - $list : the list to update
#       - $param : ref on parameters of the new
#          config list with obligatory :
#         $param->{'listname'}
#         $param->{'subject'}
#         $param->{'owner'} (or owner_include):
#          array of hash,with key email obligatory
#         $param->{'owner_include'} array of hash :
#              with key source obligatory
#       - $self : the family object
#       - $robot : the list's robot
#
# OUT : - $list : the updated list or undef
#
# Old name: Sympa::Admin::update_list().
sub _update_list {
    $log->syslog('info', '(%s, %s, %s)', @_);
568
569
    my $self  = shift;
    my $list  = shift;
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
    my $param = shift;

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

    ## mandatory list parameters
    foreach my $arg ('listname') {
        unless ($param->{$arg}) {
            $log->syslog('err', 'Missing list param %s', $arg);
            return undef;
        }
    }

    ## template file
    my $template_file = Sympa::search_fullpath($self, 'config.tt2');
    unless (defined $template_file) {
        $log->syslog('err', 'No config template from family %s@%s',
            $self->{'name'}, $robot);
        return undef;
    }

    ### Check topics
    #if (defined $param->{'topics'}) {
    #    unless (_check_topics($param->{'topics'}, $robot)) {
    #        $log->syslog('err', 'Topics param %s not defined in topics.conf',
    #            $param->{'topics'});
    #    }
    #}

    ## Lock config before openning the config file
    my $lock_fh = Sympa::LockedFile->new($list->{'dir'} . '/config', 5, '>');
    unless ($lock_fh) {
        $log->syslog('err', 'Impossible to create %s/config: %s',
            $list->{'dir'}, $ERRNO);
        return undef;
    }

    my $template =
        Sympa::Template->new(undef, include_path => [$self->{'dir'}]);
    unless ($template->parse($param, 'config.tt2', $lock_fh)) {
        $log->syslog('err', 'Can\'t parse %s/config.tt2: %s',
            $self->{'dir'}, $template->{last_error});
        return undef;
    }
    ## Unlock config file
    $lock_fh->close;

    ## Create list object
    unless ($list = Sympa::List->new($param->{'listname'}, $robot)) {
        $log->syslog('err', 'Unable to create list %s', $param->{'listname'});
        return undef;
    }

    $list->{'admin'}{'creation'}{'date_epoch'} = time;
    $list->{'admin'}{'creation'}{'email'}      = $param->{'creation_email'}
        || Sympa::get_address($robot, 'listmaster');
    $list->{'admin'}{'status'} = $param->{'status'} || 'open';
    $list->{'admin'}{'family_name'} = $self->{'name'};

    ## Create associated files if a template was given.
    my @files_to_parse;
    foreach my $file (split ',',
        Conf::get_robot_conf($robot, 'parsed_family_files')) {
        $file =~ s{\s}{}g;
        push @files_to_parse, $file;
    }
    for my $file (@files_to_parse) {
        my $template_file = Sympa::search_fullpath($self, $file . ".tt2");
        if (defined $template_file) {
            my $file_content;

            my $template =
641
                Sympa::Template->new(undef, include_path => [$self->{'dir'}]);
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
            my $tt_result =
                $template->parse($param, $file . ".tt2", \$file_content);
            unless ($tt_result) {
                $log->syslog(
                    'err',
                    'Template error. List %s from family %s@%s, file %s: %s',
                    $param->{'listname'},
                    $self->{'name'},
                    $robot,
                    $file,
                    $template->{last_error}
                );
                next;    #FIXME: Abort processing and rollback.
            }
            unless (open FILE, '>', "$list->{'dir'}/$file") {
                $log->syslog('err', 'Impossible to create %s/%s: %s',
                    $list->{'dir'}, $file, $!);
            }
            print FILE $file_content;
            close FILE;
        }
    }

    ## Synchronize list members if required
    if ($list->has_include_data_sources()) {
        $log->syslog('notice', "Synchronizing list members...");
        $list->sync_include();
    }

    return $list;
}

674
675
=pod 

676
=head2 sub close_family()
677
678
679
680
681
682
683

Closes every list family.

=head3 Arguments 

=over 

684
=item * I<$self>, the Sympa::Family object
685
686
687
688
689
690
691
692
693
694
695
696
697

=back 

=head3 Return 

=over 

=item * I<$string>, a character string containing a message to display describing the results of the sub.

=back 

=cut

698
#########################################
699
# close_family
700
701
702
#########################################
# closure family action :
#  - close every list family
703
#
704
705
706
# IN : -$self
# OUT : -$string
#########################################
707
sub close_family {
708
    my $self = shift;
709
    $log->syslog('info', '(%s)', $self->{'name'});
710

711
    my $family_lists = Sympa::List::get_lists($self);
712
713
714
    my @impossible_close;
    my @close_ok;

715
    foreach my $list (@{$family_lists}) {
716
717
718
        my $listname = $list->{'name'};

        unless (defined $list) {
719
            $log->syslog(
720
721
722
723
724
725
726
727
                'err',
                'The %s list belongs to %s family but the list does not exist',
                $listname,
                $self->{'name'}
            );
            next;
        }

728
        my $spindle = Sympa::Spindle::ProcessRequest->new(
729
730
731
732
            context          => $self->{'robot'},
            action           => 'close_list',
            current_list     => $list,
            sender           => Sympa::get_address($self, 'listmaster'),
733
734
735
736
            scenario_context => {skip => 1},
        );
        unless ($spindle and $spindle->spin and $spindle->success) {
            push @impossible_close, $list->{'name'};
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
            next;
        }
        push(@close_ok, $list->{'name'});
    }
    my $string =
        "\n\n******************************************************************************\n";
    $string .=
        "\n******************** CLOSURE of $self->{'name'} FAMILY ********************\n";
    $string .=
        "\n******************************************************************************\n\n";

    unless ($#impossible_close < 0) {
        $string .= "\nImpossible list closure for : \n  "
            . join(", ", @impossible_close) . "\n";
    }

    $string .= "\n****************************************\n";

    unless ($#close_ok < 0) {
        $string .=
            "\nThese lists are closed : \n  " . join(", ", @close_ok) . "\n";
    }
759

760
761
    $string .=
        "\n******************************************************************************\n";
762

763
764
    return $string;
}
765

766
767
=pod 

768
769
=head2 sub instantiate(FILEHANDLE $fh,
[ close_unknown =E<gt> 1 ], [ quiet =E<gt> 1 ] )
770
771
772
773
774
775
776

Creates family lists or updates them if they exist already.

=head3 Arguments 

=over 

777
=item * I<$self>, the Sympa::Family object corresponding to the family to create / update
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794

=back 

=head3 Return 

=over 

=item * I<$string>, a character string containing a message to display describing the results of the sub,

=item * I<$fh>, a file handle on the B<family> XML file,

=item * I<$close_unknown>: if true, the function will close old lists undefined in the new instantiation.

=back 

=cut

795
#########################################
796
# instantiate
797
798
799
800
#########################################
# instantiate family action :
#  - create family lists if they are not
#  - update family lists if they already exist
801
#
802
803
# IN : -$self
#      -$xml_fh : file handle on the xml file
804
805
806
807
#      -%options
#        - close_unknown : true if must close old lists undefined in new
#                          instantiation
#        - quiet         :
808
809
810
# OUT : -1 or undef
#########################################
sub instantiate {
811
812
813
814
    $log->syslog('debug2', '(%s, %s, ...)', @_);
    my $self     = shift;
    my $xml_file = shift;
    my %options  = @_;
815

816
    ## all the description variables are emptied.
817
    $self->_initialize_instantiation();
818

819
    ## set impossible checking (used by list->load)
820
    $self->{'state'} = 'no_check';
821

822
    ## get the currently existing lists in the family
823
    my $previous_family_lists =
824
        {(map { $_->{name} => $_ } @{Sympa::List::get_lists($self) || []})};
825

826
827
    ## Splits the family description XML file into a set of list description
    ## xml files
828
    ## and collects lists to be created in $self->{'list_to_generate'}.
829
    unless ($self->_split_xml_file($xml_file)) {
830
        $log->syslog('err', 'Errors during the parsing of family xml file');
831
832
833
        return undef;
    }

834
    my $created = 0;
835
836
837
    my $total;
    my $progress;
    unless ($self->{'list_to_generate'}) {
838
839
840
841
842
        $log->syslog('err', 'No list found in XML file %s.', $xml_file);
        $self->{'list_to_generate'} = [];
        $total = 0;
    } else {
        $total    = scalar @{$self->{'list_to_generate'}};
843
844
845
846
847
848
849
        $progress = Term::ProgressBar->new(
            {   name  => 'Creating lists',
                count => $total,
                ETA   => 'linear'
            }
        );
        $progress->max_update_rate(1);
850
    }
851
852
    my $next_update = 0;
    my $aliasmanager_output_file =
853
        $Conf::Conf{'tmpdir'} . '/aliasmanager.stdout.' . $PID;
854
    my $output_file =
855
        $Conf::Conf{'tmpdir'} . '/instantiate_family.stdout.' . $PID;
856
857
    my $output = '';

858
859
860
    ## EACH FAMILY LIST
    foreach my $listname (@{$self->{'list_to_generate'}}) {

861
        my $list = Sympa::List->new($listname, $self->{'robot'});
862
863

        ## get data from list XML file. Stored into $config (class
864
        ## Sympa::Config_XML).
865
        my $xml_fh;
866
        open $xml_fh, '<:raw', $self->{'dir'} . "/" . $listname . ".xml";
867
        my $config = Sympa::Config_XML->new($xml_fh);
868
869
870
871
872
873
874
875
        close $xml_fh;
        unless (defined $config->createHash()) {
            push(
                @{$self->{'errors'}{'create_hash'}},
                "$self->{'dir'}/$listname.xml"
            );
            if ($list) {
                $list->set_status_error_config('instantiation_family',
876
                    $self->{'name'});
877
878
879
880
881
882
            }
            next;
        }

        ## stores the list config into the hash referenced by $hash_list.
        my $hash_list = $config->getHash();
883
884
        # Compatibility: single topic on 6.2.24 or earlier.
        $hash_list->{config}{topics} ||= $hash_list->{config}{topic};
885
886
887
888
        # In old documentation "moderator" was single or multiple editors.
        my $mod = $hash_list->{config}{moderator};
        $hash_list->{config}{editor} ||=
            (ref $mod eq 'ARRAY') ? $mod : (ref $mod eq 'HASH') ? [$mod] : [];
889
890

        if ($list) {
891
            ## LIST ALREADY EXISTING
892
893
894
895
896
897
898
899
900
901

            delete $previous_family_lists->{$list->{'name'}};

            ## check family name
            if (defined $list->{'admin'}{'family_name'}) {
                unless ($list->{'admin'}{'family_name'} eq $self->{'name'}) {
                    push(
                        @{$self->{'errors'}{'listname_already_used'}},
                        $list->{'name'}
                    );
902
                    $log->syslog('err',
903
904
905
906
907
908
909
910
911
                        'The list %s already belongs to family %s',
                        $list->{'name'}, $list->{'admin'}{'family_name'});
                    next;
                }
            } else {
                push(
                    @{$self->{'errors'}{'listname_already_used'}},
                    $list->{'name'}
                );
912
                $log->syslog('err', 'The orphan list %s already exists',
913
914
915
916
917
918
919
920
921
                    $list->{'name'});
                next;
            }

            ## Update list config
            my $result = $self->_update_existing_list($list, $hash_list);
            unless (defined $result) {
                push(@{$self->{'errors'}{'update_list'}}, $list->{'name'});
                $list->set_status_error_config('instantiation_family',
922
                    $self->{'name'});
923
924
925
926
                next;
            }
            $list = $result;
        } else {
927
928
            # FIRST LIST CREATION

929
            ## Create the list
930
            my $spindle = Sympa::Spindle::ProcessRequest->new(
931
932
933
934
935
                context          => $self,
                action           => 'create_automatic_list',
                listname         => $hash_list->{config}{listname},
                parameters       => $hash_list->{config},
                sender           => Sympa::get_address($self, 'listmaster'),
936
937
938
                scenario_context => {skip => 1},
            );
            unless ($spindle and $spindle->spin and $spindle->success) {
939
940
941
942
943
944
                push(
                    @{$self->{'errors'}{'create_list'}},
                    $hash_list->{'config'}{'listname'}
                );
                next;
            }
945
946
            $list = Sympa::List->new($hash_list->{config}{listname},
                $self->{'robot'});
947
948

            ## aliases
949
950
            if (grep { $_->[1] eq 'notice' and $_->[2] eq 'auto_aliases' }
                @{$spindle->{stash} || []}) {
951
952
953
954
955
                push(
                    @{$self->{'created_lists'}{'with_aliases'}},
                    $list->{'name'}
                );
            } else {
956
957
                $self->{'created_lists'}{'without_aliases'}{$list->{'name'}} =
                    $list->{'name'};
958
959
960
            }

            # config_changes
961
            unless (open FILE, '>', $list->{'dir'} . '/config_changes') {
962
                $log->syslog('err',
963
964
                    'Impossible to create file %s/config_changes: %m',
                    $list->{'dir'});
965
966
967
968
969
                push(
                    @{$self->{'generated_lists'}{'file_error'}},
                    $list->{'name'}
                );
                $list->set_status_error_config('error_copy_file',
970
                    $self->{'name'});
971
972
973
974
975
976
            }
            close FILE;
        }

        ## ENDING : existing and new lists
        unless ($self->_end_update_list($list, 1)) {
977
            $log->syslog('err', 'Instantiation stopped on list %s',
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
                $list->{'name'});
            return undef;
        }
        $created++;
        $progress->message(
            sprintf(
                "List \"%s\" (%i/%i) created/updated",
                $list->{'name'}, $created, $total
            )
        );
        $next_update = $progress->update($created)
            if ($created > $next_update);

        if (-f $aliasmanager_output_file) {
            open OUT, $aliasmanager_output_file;
            while (<OUT>) {
                $output .= $_;
            }
            close OUT;
            unlink $aliasmanager_output_file; # remove file to catch next call
        }
    }

1001
    $progress->update($total) if $progress;
1002

1003
    if ($output and !$options{quiet}) {
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
        print STDOUT
            "There is unread output from the instantiation proccess (aliasmanager messages ...), do you want to see it ? (y or n)";
        my $answer = <STDIN>;
        chomp($answer);
        $answer ||= 'n';
        print $output if ($answer eq 'y');

        if (open OUT, '>' . $output_file) {
            print OUT $output;
            close OUT;
            print STDOUT "\nOutput saved in $output_file\n";
        } else {
            print STDERR "\nUnable to save output in $output_file\n";
        }
    }
1019
1020
1021

    ## PREVIOUS LIST LEFT
    foreach my $l (keys %{$previous_family_lists}) {
1022
        my $list;
1023
        unless ($list = Sympa::List->new($l, $self->{'robot'})) {
1024
1025
1026
1027
1028
            push(@{$self->{'errors'}{'previous_list'}}, $l);
            next;
        }

        my $answer;
1029
1030
        unless ($options{close_unknown}) {
            #while ($answer ne 'y' and $answer ne 'n') {
1031
1032
1033
1034
            print STDOUT
                "The list $l isn't defined in the new instantiation family, do you want to close it ? (y or n)";
            $answer = <STDIN>;
            chomp($answer);
1035
            #######################
1036
1037
1038
            $answer ||= 'y';
            #}
        }
1039
        if ($options{close_unknown} or $answer eq 'y') {
1040
            my $spindle = Sympa::Spindle::ProcessRequest->new(
1041
1042
1043
1044
                context          => $self->{'robot'},
                action           => 'close_list',
                current_list     => $list,
                sender           => Sympa::get_address($self, 'listmaster'),
1045
1046
1047
1048
1049
                scenario_context => {skip => 1},
            );
            unless ($spindle and $spindle->spin and $spindle->success) {
                push @{$self->{'family_closed'}{'impossible'}},
                    $list->{'name'};
1050
1051
1052
            }
            push(@{$self->{'family_closed'}{'ok'}}, $list->{'name'});

1053
        } elsif (lc($answer) eq 'n') {
1054
            next;
1055
1056
1057
        } else {
            ## get data from list xml file
            my $xml_fh;
1058
            open $xml_fh, '<:raw', $list->{'dir'} . '/instance.xml';
1059
            my $config = Sympa::Config_XML->new($xml_fh);
1060
1061
1062
1063
1064
1065
1066
            close $xml_fh;
            unless (defined $config->createHash()) {
                push(
                    @{$self->{'errors'}{'create_hash'}},
                    "$list->{'dir'}/instance.xml"
                );
                $list->set_status_error_config('instantiation_family',
1067
                    $self->{'name'});
1068
1069
1070
                next;
            }
            my $hash_list = $config->getHash();
1071
1072
            # Compatibility: single topic on 6.2.24 or earlier.
            $hash_list->{config}{topics} ||= $hash_list->{config}{topic};
1073
1074
1075
1076
            # In old documentation "moderator" was single or multiple editors.
            my $mod = $hash_list->{config}{moderator};
            $hash_list->{config}{editor} ||=
            (ref $mod eq 'ARRAY') ? $mod : (ref $mod eq 'HASH') ? [$mod] : [];
1077
1078
1079
1080
1081

            my $result = $self->_update_existing_list($list, $hash_list);
            unless (defined $result) {
                push(@{$self->{'errors'}{'update_list'}}, $list->{'name'});
                $list->set_status_error_config('instantiation_family',