Archive.pm 32.2 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 GIP RENATER
11
12
13
14
15
16
17
18
19
20
21
22
#
# 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
23
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
root's avatar
root committed
24

25
package Sympa::Archive;
root's avatar
root committed
26

27
use strict;
28
use warnings;
sikeda's avatar
sikeda committed
29
use Cwd qw();
30
use Digest::MD5 qw();
sikeda's avatar
sikeda committed
31
use Encode qw();
32
33
use English qw(-no_match_vars);
use File::Path qw();
sikeda's avatar
sikeda committed
34
use HTML::Entities qw();
35
use POSIX qw();
36

37
use Sympa;
38
use Conf;
39
40
use Sympa::Constants;
use Sympa::LockedFile;
41
use Sympa::Log;
42
use Sympa::Message;
43
44
use Sympa::Spool;
use tools;
45
use Sympa::Tools::File;
root's avatar
root committed
46

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

49
50
sub new {
    my $class = shift;
51
52
53
54
55
56
57
58

    my $list;
    if (ref $_[0]) {    # Compat., not recommended.
        $list = shift;
    } else {
        my %options = @_;
        $list = $options{context};
    }
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

    die 'Bug in logic.  Ask developer' unless ref $list eq 'Sympa::List';
    my $robot_id = $list->{'domain'};
    my $arc_path = Conf::get_robot_conf($robot_id, 'arc_path');
    die sprintf
        'Robot %s has no archives directory. Check arc_path parameter in this robot.conf and in sympa.conf',
        $robot_id
        unless $arc_path;
    my $base_directory = $arc_path . '/' . $list->get_id;

    my $self = bless {
        context           => $list,
        base_directory    => $base_directory,
        arc_directory     => undef,
        directory         => undef,
        deleted_directory => undef,
        _metadatas        => undef,
    } => $class;

    $self->_create_spool();

    return $self;
}
root's avatar
root committed
82

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
sub _create_spool {
    my $self = shift;

    my $umask = umask oct $Conf::Conf{'umask'};
    foreach my $directory ($Conf::Conf{'arc_path'}, $self->{base_directory}) {
        unless (-d $directory) {
            $log->syslog('info', 'Creating spool %s', $directory);
            unless (
                mkdir($directory, 0755)
                and Sympa::Tools::File::set_file_rights(
                    file  => $directory,
                    user  => Sympa::Constants::USER(),
                    group => Sympa::Constants::GROUP()
                )
                ) {
                die sprintf 'Cannot create %s: %s', $directory, $ERRNO;
            }
        }
    }
    umask $umask;
}
root's avatar
root committed
104

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
sub add_archive {
    my $self = shift;
    my $arc  = shift;

    return undef unless $arc;
    return undef unless $arc =~ /\A\d{4}-\d{2}\z/;

    my $umask = umask oct $Conf::Conf{'umask'};
    my $error;
    File::Path::make_path(
        $self->{base_directory} . '/' . $arc . '/arctxt',
        {   mode  => 0775,
            owner => Sympa::Constants::USER(),
            group => Sympa::Constants::GROUP(),
            error => \$error
        }
    );
    umask $umask;
root's avatar
root committed
123

124
125
126
127
128
    if (@$error) {
        return undef;
    }
    return 1;
}
129

130
131
132
sub purge_archive {
    my $self = shift;
    my $arc  = shift;
133

134
135
    return undef unless $arc;
    return undef unless $arc =~ /\A\d{4}-\d{2}\z/;
136

137
138
139
    my $error;
    File::Path::remove_tree($self->{base_directory} . '/' . $arc,
        {error => \$error});
140

141
142
    if (@$error) {
        return undef;
salaun's avatar
salaun committed
143
    }
144
145
    return 1;
}
146

147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
sub select_archive {
    my $self    = shift;
    my $arc     = shift;
    my %options = @_;

    return undef unless $arc;
    return undef unless $arc =~ /\A\d{4}-\d{2}\z/;

    my $arc_directory     = $self->{base_directory} . '/' . $arc;
    my $directory         = $arc_directory . '/arctxt';
    my $deleted_directory = $arc_directory . '/deleted';

    my $dh;
    return undef unless opendir $dh, $directory;
    closedir $dh;

    undef $self->{_metadatas};
sikeda's avatar
sikeda committed
164
    undef $self->{_html_metadatas};
165
166
167
168
169
170
    $self->{arc_directory}     = $arc_directory;
    $self->{directory}         = $directory;
    $self->{deleted_directory} = $deleted_directory;

    if ($options{info}) {
        return {
171
172
            size  => Sympa::Tools::File::get_dir_size($directory),
            mtime => Sympa::Tools::File::get_mtime($directory),
173
        };
sikeda's avatar
sikeda committed
174
175
176
177
178
179
180
181
    } elsif ($options{count}) {
        my $count;
        if (open my $fh, '<', $self->{arc_directory} . '/index') {
            $count = <$fh>;
            chomp $count;
            close $fh;
        }
        return {count => ($count || 0)};
182
183
184
    } else {
        return $arc;
    }
root's avatar
root committed
185
186
}

187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
sub fetch {
    my $self    = shift;
    my %options = @_;

    undef $self->{_metadatas};    # Rewind cache.
    while (1) {
        my ($message, $handle) = $self->next;
        last unless $handle;      # No more messages.
        next unless $message;     # Malformed message.

        if ($options{message_id}) {
            my $message_id =
                tools::clean_msg_id($message->get_header('Message-Id')) || '';
            if ($message_id eq $options{message_id}) {
                undef $self->{_metadatas};    # Rewind cache.
                return ($message, $handle);
            }
        }
    }

    return;
}
sympa-authors's avatar
   
sympa-authors committed
209

sikeda's avatar
sikeda committed
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
sub html_fetch {
    $log->syslog('debug2', '(%s, %s => %s)', @_);
    my $self    = shift;
    my %options = @_;

    return undef unless $self->{arc_directory};
    return undef unless $options{file};

    my $handle =
        IO::File->new($self->{arc_directory} . '/' . $options{file}, '<');
    return undef unless $handle;

    my $metadata = {};    # May be empty.
    while (<$handle>) {
        last if /^\s*$/;    ## Metadata end with an emtpy line

        if (/^<!--(\S+): (.*) -->$/) {
            my ($key, $value) = ($1, $2);
            $value =
                Encode::encode_utf8(
                HTML::Entities::decode_entities(Encode::decode_utf8($value)));
            if ($key eq 'X-From-R13') {
                $metadata->{'X-From'} = $value;
                # MHonArc protection of email addresses.
                $metadata->{'X-From'} =~ tr/N-Z[@A-Mn-za-m/@A-Z[a-z/;
                # Remove the gecos.
                $metadata->{'X-From'} =~ s/^.*<(.*)>/$1/g;
            }
            $metadata->{$key} = $value;
        }
    }
    seek $handle, 0, 0;
    $metadata->{html_content} = do { local $RS; <$handle> };
    $metadata->{filename} = $options{file};

    return $metadata;
}

248
sub next {
249
250
    my $self    = shift;
    my %options = @_;
251

252
    return unless $self->{directory};
sympa-authors's avatar
   
sympa-authors committed
253

254
255
256
257
258
259
260
261
262
263
264
265
266
    unless ($self->{_metadatas}) {
        my $dh;
        unless (opendir $dh, $self->{directory}) {
            die sprintf 'Cannot open dir %s: %s', $self->{directory}, $ERRNO;
        }
        $self->{_metadatas} = [
            sort _cmp_numeric grep {
                        !/,lock/
                    and !m{(?:\A|/)(?:\.|T\.|BAD-)}
                    and -f ($self->{directory} . '/' . $_)
                } readdir $dh
        ];
        closedir $dh;
267
268
269
270

        # The "reverse" option specific to this class is set.
        $self->{_metadatas} = [reverse @{$self->{_metadatas}}]
            if $options{reverse};
271
    }
272
273
274
    unless (@{$self->{_metadatas}}) {
        undef $self->{_metadatas};
        return;
275
    }
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295

    while (my $marshalled = shift @{$self->{_metadatas}}) {
        my ($lock_fh, $metadata, $message);

        # Try locking message.  Those locked or removed by other process will
        # be skipped.
        $lock_fh =
            Sympa::LockedFile->new($self->{directory} . '/' . $marshalled,
            -1, '+<');
        next unless $lock_fh;

        $metadata =
            Sympa::Spool::unmarshal_metadata($self->{directory}, $marshalled,
            qr{\A(\d+)\z}, [qw(serial)]);

        if ($metadata) {
            my $msg_string = do { local $RS; <$lock_fh> };
            $message = Sympa::Message->new($msg_string, %$metadata);
        }

sikeda's avatar
sikeda committed
296
297
298
        # Metadata doesn't contain context; add it.
        $message->{context} = $self->{context} if $message;

299
300
        # Though message might not be deserialized, anyway return the result.
        return ($message, $lock_fh);
root's avatar
root committed
301
    }
302
    return;
root's avatar
root committed
303
304
}

sikeda's avatar
sikeda committed
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
sub html_next {
    my $self    = shift;
    my %options = @_;

    return undef unless $self->{arc_directory};

    unless ($self->{_html_metadatas}) {
        my $dh;
        unless (opendir $dh, $self->{arc_directory}) {
            die sprintf 'Cannot open dir %s: %s', $self->{arc_directory},
                $ERRNO;
        }
        $self->{_html_metadatas} = [
            sort _cmp_numeric grep {
                        !/,lock/
                    and !m{(?:\A|/)(?:\.|T\.|BAD-)}
                    and -f ($self->{arc_directory} . '/' . $_)
                } readdir $dh
        ];
        closedir $dh;

        # The "reverse" option specific to this class is set.
        $self->{_html_metadatas} = [reverse @{$self->{_html_metadatas}}]
            if $options{reverse};
    }
    unless (@{$self->{_html_metadatas}}) {
        undef $self->{_html_metadatas};
        return undef;
    }

    while (my $marshalled = shift @{$self->{_html_metadatas}}) {
        return $self->html_fetch(file => $marshalled);
    }
    return undef;
}

341
sub _cmp_numeric {
sikeda's avatar
sikeda committed
342
343
344
345
    my $a_num = $1 if defined $a and $a =~ /(\d+)/;
    my $b_num = $1 if defined $b and $b =~ /(\d+)/;
    if (defined $a_num and defined $b_num) {
        return $a_num <=> $b_num || $a cmp $b;
346
347
348
349
350
351
352
353
354
355
356
    } else {
        return $a cmp $b;
    }
}

sub remove {
    $log->syslog('debug2', '(%s, %s)', @_);
    my $self   = shift;
    my $handle = shift;

    return undef unless $self->{arc_directory};
357

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

360
361
362
363
364
365
366
367
368
369
370
371
372
373
    # Move text message to deleted/ directory.
    unless (-d $self->{deleted_directory}) {
        my $umask = umask oct $Conf::Conf{'umask'};
        unless (mkdir $self->{deleted_directory}, 0777) {
            die sprintf 'Unable to create %s: %s',
                $self->{deleted_directory}, $ERRNO;
        }
        umask $umask;
    }
    unless (
        $handle->rename($self->{deleted_directory} . '/' . $handle->basename))
    {
        $log->syslog('info', 'Unable to rename message %s in archive %s: %s',
            $handle->basename, $self, Sympa::LockedFile->last_error);
374
        return undef;
sympa-authors's avatar
   
sympa-authors committed
375
    }
376

377
378
    # Remove directory if empty arctxt.
    rmdir $self->{directory};
379

380
381
    return 1;
}
sympa-authors's avatar
   
sympa-authors committed
382

383
# Old name: remove() in archived.pl.
sikeda's avatar
sikeda committed
384
sub html_remove {
385
386
    my $self  = shift;
    my $msgid = shift;
sympa-authors's avatar
   
sympa-authors committed
387

388
389
    return undef unless $self->{arc_directory};
    return undef unless $msgid and $msgid !~ /NO-ID-FOUND\.mhonarc\.org/;
sympa-authors's avatar
   
sympa-authors committed
390

391
    my $list = $self->{context};
sympa-authors's avatar
   
sympa-authors committed
392

393
394
395
396
397
398
    # Remove message from HTML archive.
    system(
        Conf::get_robot_conf($list->{'domain'}, 'mhonarc'),
        '-outdir' => $self->{arc_directory},
        '-rmm'    => $msgid
    );
sympa-authors's avatar
   
sympa-authors committed
399

400
401
402
403
    # Remomve urlized message.
    my $url_dir = $list->{'dir'} . '/urlized/' . tools::escape_chars($msgid);
    my $error;
    File::Path::remove_tree($url_dir, {error => \$error});
sympa-authors's avatar
   
sympa-authors committed
404

405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
    return 1;
}

# Does the real job : stores the message given as an argument into
# the indicated directory.
# Old name: (part of) mail2arc() in archived.pl.
sub store {
    my $self    = shift;
    my $message = shift;

    my $list = $self->{context};
    my $arc = POSIX::strftime('%Y-%m', localtime $message->{date});
    my $newfile;

    unless ($self->select_archive($arc)) {
        $self->add_archive($arc);
        unless ($self->select_archive($arc)) {
            $log->syslog('err', 'Cannot create directory %s in archive %s',
                $arc, $self);
            return undef;
        }
sympa-authors's avatar
   
sympa-authors committed
426
427
    }

428
429
430
431
432
433
434
435
436
437
438
439
440
    # Copy the file in the arctxt.
    if (-f $self->{arc_directory} . "/index") {
        open my $fh, '<', $self->{arc_directory} . '/index'
            or die sprintf 'Can\'t read index of %s in %s: %s', $arc, $self,
            $ERRNO;
        $newfile = <$fh>;
        chomp $newfile;
        $newfile++;
        close $fh;
    } else {
        # recreate index file if needed and update it
        $newfile = _create_idx($self->{arc_directory}) + 1;
    }
sympa-authors's avatar
   
sympa-authors committed
441

442
443
444
445
446
447
    # Save arctxt dump of original message.
    open my $fh, '>', $self->{directory} . '/' . $newfile
        or die sprintf 'Can\'t open file %s/%s: %s', $self->{directory},
        $newfile, $ERRNO;
    print $fh $message->as_string;
    close $fh;
sympa-authors's avatar
   
sympa-authors committed
448

449
    _save_idx($self->{arc_directory} . '/index', $newfile);
sympa-authors's avatar
   
sympa-authors committed
450

451
452
453
454
    $log->syslog('notice', 'Message %s is stored into archive %s as <%s>',
        $message, $self, $newfile);
    return $newfile;
}
455

456
# Old name: (part of) mail2arc in archived.pl.
sikeda's avatar
sikeda committed
457
sub html_store {
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
    my $self    = shift;
    my $message = shift->dup;

    my $list = $self->{context};
    my $arc  = POSIX::strftime('%Y-%m', localtime $message->{date});
    my $yyyy = POSIX::strftime('%Y', localtime $message->{date});
    my $mm   = POSIX::strftime('%m', localtime $message->{date});

    unless ($self->select_archive($arc)) {
        $self->add_archive($arc);
        unless ($self->select_archive($arc)) {
            $log->syslog('err', 'Cannot create directory %s in archive %s',
                $arc, $self);
            return undef;
        }
    }
474

475
476
477
    # Prepare clean message content (HTML parts are cleaned)
    unless ($message->clean_html) {
        $log->syslog('err', "Could not clean message, ignoring message");
478
479
        return undef;
    }
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495

    my $mhonarc_ressources =
        Sympa::search_fullpath($list, 'mhonarc-ressources.tt2');

    $log->syslog(
        'debug',
        'Calling %s for list %s',
        Conf::get_robot_conf($list->{'domain'}, 'mhonarc'), $list
    );

    my $tag = _get_tag($list);
    if (    $list->{'admin'}{'web_archive_spam_protection'} ne 'none'
        and $list->{'admin'}{'web_archive_spam_protection'} ne 'cookie') {
        _set_hidden_mode($tag);
    } else {
        _unset_hidden_mode();
sympa-authors's avatar
   
sympa-authors committed
496
    }
497
498
499
500
501
502
503
504
505
506
507

    # Call mhonarc on cleaned message source to make clean htlm view of
    # message.
    my @cmd = (
        Conf::get_robot_conf($list->{'domain'}, 'mhonarc'),
        '-add',
        '-modifybodyaddresses',
        '-addressmodifycode' => $ENV{'M2H_ADDRESSMODIFYCODE'},
        '-rcfile'            => $mhonarc_ressources,
        '-outdir'            => $self->{arc_directory},
        '-definevars'        => sprintf(
508
            "listname='%s' hostname=%s yyyy=%s mois=%s yyyymm=%s-%s wdir=%s base=%s/arc tag=%s with_tslice=1 with_powered_by=1",
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
            $list->{'name'},
            $list->{'domain'},
            $yyyy,
            $mm,
            $yyyy,
            $mm,
            Conf::get_robot_conf($list->{'domain'}, 'arc_path'),
            Conf::get_robot_conf($list->{'domain'}, 'wwsympa_url'),
            $tag
        ),
        '-umask' => $Conf::Conf{'umask'}
    );

    $log->syslog('debug', 'System call: %s', join(' ', @cmd));

    my $pipeout;
    unless (open $pipeout, '|-', @cmd) {
        $log->syslog('err', 'Could not open pipe: %m');
527
        return undef;
sympa-authors's avatar
   
sympa-authors committed
528
    }
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
    print $pipeout $message->as_string;
    close $pipeout;
    my $status = $? >> 8;

    ## Remove lock if required
    if ($status == 75) {
        $log->syslog(
            'notice',
            'Removing lock directory %s',
            $self->{arc_directory} . '/.mhonarc.lck'
        );
        rmdir $self->{arc_directory} . '/.mhonarc.lck';

        my $pipeout;
        unless (open $pipeout, '|-', @cmd) {
            $log->syslog('err', 'Could not open pipe: %m');
            return undef;
546
        }
547
548
549
        print $pipeout $message->as_string;
        close $pipeout;
        $status = $? >> 8;
sympa-authors's avatar
   
sympa-authors committed
550
    }
551
552
553
554
555
556
557
558
559
    if ($status) {
        $log->syslog(
            'err',
            'Command %s failed with exit code %s',
            join(' ', @cmd), $status
        );
    }

    return 1;
sympa-authors's avatar
   
sympa-authors committed
560
561
}

562
563
# DEPRECATED.  No longer used.
#sub store_last;
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600

# DEPRECATED.  Use get_archives() and select_archive().
#sub list;

# Lists the files included in the archive, preformatted for printing
# Returns an array.
sub get_archives {
    $log->syslog('debug2', '(%s)', @_);
    my $self = shift;

    my $base_directory = $self->{base_directory};

    my $dh;
    unless ($base_directory and opendir $dh, $base_directory) {
        $log->syslog('err', 'Cannot open directory %s: %m', $base_directory);
        return;
    }
    my @arcs =
        grep {
        /\A\d\d\d\d\-\d\d\z/
            and -d $base_directory . '/' 
            . $_
            . '/arctxt'
        }
        sort readdir $dh;
    closedir $dh;

    return @arcs;
}

# DEPRECATED.  Use select_archive() and next().
#sub scan_dir_archive;

# DEPRECATED.  Use select_archive() and fetch().
#sub search_msgid;

# OBSOLETED.  No longer used.
root's avatar
root committed
601
sub exist {
602
    my ($name, $file) = @_;
root's avatar
root committed
603
    my $fn = "$name/$file";
604

root's avatar
root committed
605
606
607
608
    return $fn if (-r $fn && -f $fn);
    return undef;
}

sympa-authors's avatar
sympa-authors committed
609
# return path for latest message distributed in the list
610
611
# DEPRECATED.  No longer used.
#sub last_path;
612
613
614

## Load an archived message, returns the mhonarc metadata
## IN : file_path
sikeda's avatar
sikeda committed
615
616
# DEPRECATED.  Use html_fetch() or html_next().
#sub load_html_message;
617

618
# Old name: rebuild() in archived.pl.
sikeda's avatar
sikeda committed
619
sub html_rebuild {
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
    my $self = shift;
    my $arc  = shift;

    $arc =~ /^(\d{4})-(\d{2})$/;
    my $yyyy = $1;
    my $mm   = $2;

    return unless $self->select_archive($arc);

    my $list          = $self->{context};
    my $listname      = $list->{'name'};
    my $robot_id      = $list->{'domain'};
    my $arc_directory = $self->{arc_directory};

    my $tag = _get_tag($list);
    my $mhonarc_ressources =
        Sympa::search_fullpath($list, 'mhonarc-ressources.tt2');

    if (    $list->{'admin'}{'web_archive_spam_protection'} ne 'none'
        and $list->{'admin'}{'web_archive_spam_protection'} ne 'cookie') {
        _set_hidden_mode($tag);
    } else {
        _unset_hidden_mode();
    }

    # Remove existing HTML files and .mhonarc.db.
    my $dh;
    opendir $dh, $arc_directory;
    unlink map { $arc_directory . '/' . $_ }
        grep {
                $_ ne 'arctxt'
            and $_ ne 'index'
            and $_ ne 'deleted'
            and !/\A\.+\z/
        } readdir $dh;
    closedir $dh;

    my $dir_to_rebuild = $self->{directory};
    my $arcs_dir       = $self->_clean_archive_directory($arc);
    if ($arcs_dir) {
        $dir_to_rebuild = $arcs_dir->{'dir_to_rebuild'};
    }

    # recreate index file if needed
    unless (-f $arc_directory . '/index') {
        _create_idx($arc_directory);
    }

    my @cmd = (
        Conf::get_robot_conf($robot_id, 'mhonarc'),
        '-modifybodyaddresses',
        '-addressmodifycode' => $ENV{'M2H_ADDRESSMODIFYCODE'},
        '-rcfile'            => $mhonarc_ressources,
        '-outdir'            => $arc_directory,
        '-definevars'        => sprintf(
675
            "listname='%s' hostname=%s yyyy=%s mois=%s yyyymm=%s-%s wdir=%s base=%s/arc tag=%s with_tslice=1 with_powered_by=1",
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
            $listname,
            $robot_id,
            $yyyy,
            $mm,
            $yyyy,
            $mm,
            Conf::get_robot_conf($robot_id, 'arc_path'),
            Conf::get_robot_conf($robot_id, 'wwsympa_url'),
            $tag
        ),
        '-umask' => $Conf::Conf{'umask'},
        $dir_to_rebuild
    );
    my $exitcode = system(@cmd) >> 8;

    # Delete temporary directory containing files with escaped HTML.
    if ($arcs_dir and -d $arcs_dir->{'cleaned_dir'}) {
        my $error;
        File::Path::remove_tree($arcs_dir->{'cleaned_dir'},
            {error => \$error});
    }

    ## Remove lock if required
    if ($exitcode == 75) {
        $log->syslog(
            'notice',
            'Removing lock directory %s',
            $arc_directory . '/.mhonarc.lck'
        );
        rmdir $arc_directory . '/.mhonarc.lck';

        $exitcode = system(@cmd) >> 8;
    }
    if ($exitcode) {
        $log->syslog(
            'err',
            'Command %s failed with exit code %s',
            join(' ', @cmd), $exitcode
        );
    }
}

# Sets the value of $ENV{'M2H_ADDRESSMODIFYCODE'} and
# $ENV{'M2H_MODIFYBODYADDRESSES'}.
#* $tag a character string (containing the result of _get_tag($list))
sub _set_hidden_mode {
    # Tag is used as variable elements in tags to prevent message contents to
    # be parsed
    my $tag = shift;

    # $ENV{'M2H_MODIFYBODYADDRESSES'} à positionner si le corps du message est
    # parse.
    $ENV{'M2H_ADDRESSMODIFYCODE'} =
        "s|^([^\@]+)\@([^\@]+)\$|\($tag\%hidden_head\%$tag\)\$1\($tag\%hidden_at\%$tag\)\$2\($tag\%hidden_end\%$tag\)|g";
    $ENV{'M2H_MODIFYBODYADDRESSES'} = 1;
}

# Empties $ENV{'M2H_ADDRESSMODIFYCODE'}.
sub _unset_hidden_mode {
    # Be careful, the .mhonarc.db file keeps track of previous
    # M2H_ADDRESSMODIFYCODE setup.
    $ENV{'M2H_ADDRESSMODIFYCODE'} = '';
}

# Saves the archives index file
#* $index, a string corresponding to the file name to which save an index.
#* $lst, a character string
# Old name: save_idx() in archived.pl.
sub _save_idx {
    my ($index, $lst) = @_;

    return unless $lst;

    open INDEXF, '>', $index
        or die sprintf 'Couldn\'t overwrite index %s: %s', $index, $!;
    print INDEXF "$lst\n";
    close INDEXF;
}

# Create the 'index' file for one archive subdir
# Old name: create_idx() in archived.pl.
sub _create_idx {
    my $arc_dir = shift;    ## corresponds to the yyyy-mm directory

    my $arc_txt_dir = $arc_dir . '/arctxt';

    unless (opendir(DIR, $arc_txt_dir)) {
        $log->syslog('err', 'Failed to open directory "%s"', $arc_txt_dir);
        return undef;
    }

    my @files = (sort { $a <=> $b; } grep(/^\d+$/, (readdir DIR)));
    my $index = $files[$#files] || 0;
    _save_idx($arc_dir . '/index', $index);

    closedir DIR;

    return $index;
}

# Old name: clean_archive_directory().
sub _clean_archive_directory {
    $log->syslog('debug3', '(%s, %s)', @_);
    my $self = shift;
    my $arc  = shift;

    return undef unless $self->select_archive($arc);
783
784

    my $answer;
785
786
787
    $answer->{'dir_to_rebuild'} = $self->{directory};
    $answer->{'cleaned_dir'}    = sprintf '%s/%s/%s/arctxt',
        $Conf::Conf{'tmpdir'}, $self->{context}->get_id, $arc;
788
    unless (
789
790
791
        my $number_of_copies = Sympa::Tools::File::copy_dir(
            $answer->{'dir_to_rebuild'},
            $answer->{'cleaned_dir'}
792
793
        )
        ) {
794
        $log->syslog(
795
            'err',
796
            'Unable to create a temporary directory where to store files for HTML escaping (%s). Cancelling',
797
798
799
800
801
802
803
804
805
            $number_of_copies
        );
        return undef;
    }
    if (opendir ARCDIR, $answer->{'cleaned_dir'}) {
        my $files_left_uncleaned = 0;
        foreach my $file (readdir(ARCDIR)) {
            next if ($file =~ /^\./);
            $files_left_uncleaned++
806
807
                unless _clean_archived_message(
                $self->{context}->{'domain'},    #FIXME
808
809
810
                $answer->{'cleaned_dir'} . '/' . $file,
                $answer->{'cleaned_dir'} . '/' . $file
                );
811
        }
812
        closedir ARCDIR;
813
        if ($files_left_uncleaned) {
814
            $log->syslog('err',
815
                'HTML cleaning failed for %s files in the directory %s',
816
817
818
819
                $files_left_uncleaned, $answer->{'dir_to_rebuild'});
        }
        $answer->{'dir_to_rebuild'} = $answer->{'cleaned_dir'};
    } else {
820
        $log->syslog(
821
            'err',
822
823
            'Unable to open directory %s: %m',
            $answer->{'dir_to_rebuild'}
824
        );
825
        Sympa::Tools::File::del_dir($answer->{'cleaned_dir'});
826
827
828
829
        return undef;
    }
    return $answer;
}
830

831
832
# Old name: clean_archived_message().
sub _clean_archived_message {
833
    $log->syslog('debug2', '(%s, %s, %s)', @_);
834
835
    my $robot  = shift;
    my $input  = shift;
836
837
    my $output = shift;

838
    my $message = Sympa::Message->new_from_file($input, context => $robot);
839
    unless ($message) {
840
        $log->syslog('err', 'Unable to create a Message object with file %s',
841
842
843
            $input);
        return undef;
    }
844

845
    if ($message->clean_html) {
846
847
        if (open TMP, '>', $output) {
            print TMP $message->as_string;
848
849
850
            close TMP;
            return 1;
        } else {
851
            $log->syslog(
852
                'err',
853
                'Unable to create a tmp file to write clean HTML to file %s',
854
855
                $output
            );
856
857
858
            return undef;
        }
    } else {
859
        $log->syslog('err', 'HTML cleaning in file %s failed', $output);
860
        return undef;
861
862
    }
}
root's avatar
root committed
863

sikeda's avatar
sikeda committed
864
865
866
867
# Old names archive::convert_single_msg_2_html(),
# Sympa::Archive::convert_single_message().
sub html_format {
    my $message = shift;
868
    my %opts    = @_;
869

sikeda's avatar
sikeda committed
870
    my $that = $message->{context};
871
872
873
874
    my $list;
    my $robot;
    my $listname;
    my $hostname;
875
    if (ref $that eq 'Sympa::List') {
876
877
878
879
880
881
882
883
884
        $list     = $that;
        $robot    = $that->{'domain'};
        $listname = $that->{'name'};
        $hostname = $that->{'admin'}{'host'};
    } elsif (!ref($that) and $that and $that ne '*') {
        $list     = '';
        $robot    = $that;
        $listname = '';
        $hostname = Conf::get_robot_conf($that, 'host');
885
    } else {
886
        die 'bug in logic.  Ask developer';
887
888
    }

sikeda's avatar
sikeda committed
889
    my $msg_as_string = $message->as_string;
root's avatar
root committed
890

891
892
893
    my $destination_dir = $opts{'destination_dir'};
    my $attachement_url = $opts{'attachement_url'};

894
    my $mhonarc_ressources =
895
        Sympa::search_fullpath($that, 'mhonarc-ressources.tt2');
896
    unless ($mhonarc_ressources) {
897
        $log->syslog('notice', 'Cannot find any MhOnArc ressource file');
898
        return undef;
899
900
901
    }

    unless (-d $destination_dir) {
902
        unless (Sympa::Tools::File::mkdir_all($destination_dir, 0755)) {
903
            $log->syslog('err', 'Unable to create %s', $destination_dir);
904
905
            return undef;
        }
906
    }
907
908
909

    my $msg_file = $destination_dir . '/msg00000.txt';
    unless (open OUT, '>', $msg_file) {
sikeda's avatar
sikeda committed
910
        $log->syslog('notice', 'Can\'t open %s', $msg_file);
911
        return undef;
912
    }
913
914
915
    print OUT $msg_as_string;
    close OUT;

916
    # mhonarc require du change workdir so this proc must retore it
sikeda's avatar
sikeda committed
917
    my $pwd = Cwd::getcwd();
918

919
920
    ## generate HTML
    unless (chdir $destination_dir) {
921
        $log->syslog('err', 'Could not change working directory to %s',
922
923
            $destination_dir);
        return undef;
924
925
    }

926
    my $tag      = _get_tag($that);
927
    my $exitcode = system(
sikeda's avatar
sikeda committed
928
929
930
        Conf::get_robot_conf($robot, 'mhonarc'),
        '-single',
        '-rcfile'     => $mhonarc_ressources,
931
        '-definevars' => sprintf(
932
            "listname='%s' hostname=%s yyyy='' mois='' tag=%s with_tslice='' with_powered_by=''",
sikeda's avatar
sikeda committed
933
934
            $listname, $hostname, $tag
        ),
935
        '-outdir'        => $destination_dir,
936
937
938
939
        '-attachmentdir' => $destination_dir,
        '-attachmenturl' => $attachement_url,
        '-umask'         => $Conf::Conf{'umask'},
        '-stdout'        => "$destination_dir/msg00000.html",
sikeda's avatar
sikeda committed
940
941
        '--',
        $msg_file
942
    ) >> 8;
943

944
945
    # restore current wd
    chdir $pwd;
946

947
    if ($exitcode) {
948
        $log->syslog(
949
950
951
952
            'err',
            'Command %s failed with exit code %d',
            Conf::get_robot_conf($robot, 'mhonarc'), $exitcode
        );
953
954
    }

955
956
957
    return 1;
}

958
959
960
# Old name: Sympa::Archive::get_tag(), get_tag() in archived.pl.
sub _get_tag {
    my $that = shift;
961

962
963
964
965
966
967
968
969
    my $name;
    if (ref $that eq 'Sympa::List') {
        $name = $that->{'name'};
    } elsif (!ref($that) and $that and $that ne '*') {
        $name = $that;
    } elsif (!ref($that)) {
        $name = '*';
    }
970

971
972
973
974
    my $cookie = $Conf::Conf{'cookie'};
    $cookie = '' unless defined $cookie;
    return substr(Digest::MD5::md5_hex(join '/', $cookie, $name), -10);
}
975

976
977
sub get_id {
    my $self = shift;
978

979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    my $context = $self->{context};
    unless (ref $context eq 'Sympa::List') {
        return '';
    } elsif ($self->{arc_directory}) {
        return sprintf '%s/%s', $context->get_id,
            [split '/', $self->{arc_directory}]->[-1];
    } else {
        return $context->get_id;
    }
}

1;
__END__

=encoding utf-8

=head1 NAME

Sympa::Archive - Archives of Sympa

=head1 SYNOPSIS

For faster browsing, not all history is shown. View entire blame