mhamain.pl untested

filter: Statementstmt 0.0% 0 / 817 Branchbran 0.0% 0 / 488 Conditioncond 0.0% 0 / 193 Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 1549 CC 245 SCAR 74.5
CC
245
Cov
0%
output_mail
3306.0
doit
2550.0
write_pages
2162.0
CRAP 1717.9
1 ##---------------------------------------------------------------------------##
2 ## File:
3 ## $Id: mhamain.pl,v 2.102 2014/04/22 02:33:10 ehood Exp $
4 ## Author:
5 ## Earl Hood mhonarc@mhonarc.org
6 ## Description:
7 ## Main library for MHonArc.
8 ##---------------------------------------------------------------------------##
9 ## MHonArc -- Internet mail-to-HTML converter
10 ## Copyright (C) 1995-2012 Earl Hood, mhonarc@mhonarc.org
11 ##
12 ## This program is free software; you can redistribute it and/or modify
13 ## it under the terms of the GNU General Public License as published by
14 ## the Free Software Foundation; either version 2 of the License, or
15 ## (at your option) any later version.
16 ##
17 ## This program is distributed in the hope that it will be useful,
18 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ## GNU General Public License for more details.
21 ##
22 ## You should have received a copy of the GNU General Public License
23 ## along with this program; if not, write to the Free Software
24 ## Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
25 ## 02111-1307, USA
26 ##---------------------------------------------------------------------------##
27  
28 package mhonarc;
29 use MHonArc;
30  
31 require 5;
32  
33 $VERSION = '2.6.23';
34 $VINFO = <<EndOfInfo;
35 MHonArc v$VERSION (Perl $] $^O)
36 Copyright (C) 1995-2014 Earl Hood, mhonarc\@mhonarc.org
37 MHonArc comes with ABSOLUTELY NO WARRANTY and MHonArc may be copied only
38 under the terms of the GNU General Public License, which may be found in
39 the MHonArc distribution.
40 EndOfInfo
41  
42 ###############################################################################
43 BEGIN {
44 ## Check what system we are executing under
45 require 'osinit.pl';
46 &OSinit();
47  
48 ## Check if running setuid/setgid
49 $TaintMode = 0;
50 if ($UNIX && (($< != $>) || ($( != $)))) {
51 ## We do not support setuid since there are too many
52 ## security problems to handle, and if we did, mhonarc
53 ## would probably not be very useful.
54 die "ERROR: setuid/setgid execution not supported!\n";
55  
56 #$TaintMode = 1;
57 #$ENV{'PATH'} = '/bin:/usr/bin';
58 #$ENV{'SHELL'} = '/bin/sh' if exists $ENV{'SHELL'};
59 #delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
60 }
61 }
62 ###############################################################################
63  
64 $DEBUG = 0;
65 $CODE = 0;
66 $ERROR = "";
67 @OrgARGV = ();
68 $ArchiveOpen = 0;
69  
70 $_msgid_cnt = 0;
71  
72 my %_sig_org = ();
73 my @_term_sigs = qw(
74 ABRT ALRM BUS FPE HUP ILL INT IOT PIPE POLL PROF QUIT SEGV
75 TERM TRAP USR1 USR2 VTALRM XCPU XFSZ
76 );
77  
78 ###############################################################################
79 ## Public routines
80 ###############################################################################
81  
82 ##---------------------------------------------------------------------------
83 ## initialize() does some initialization stuff. Should be called
84 ## right after mhamain.pl is called.
85 ##
86 sub initialize {
87 ## Turn off buffered I/O to terminal
88 my ($curfh) = select(STDOUT);
89 $| = 1;
90 select($curfh);
91  
92 ## Require essential libraries
93 require 'mhlock.pl';
94 require 'mhopt.pl';
95  
96 ## Init some variables
97 $ISLOCK = 0; # Database lock flag
98  
99 $StartTime = 0; # CPU start time of processing
100 $EndTime = 0; # CPU end time of processing
101 }
102  
103 ##---------------------------------------------------------------------------
104 ## open_archive opens the archive
105 ##
106 sub open_archive {
107 eval { $StartTime = (times)[0]; };
108  
109 ## Set @ARGV if options passed in
110 if (@_) { @OrgARGV = @ARGV; @ARGV = @_; }
111  
112 ## Get options
113 my ($optstatus);
114 eval {
115 set_handler();
116 $optstatus = get_resources();
117 };
118  
119 ## Check for error
120 if ($@ || $optstatus <= 0) {
121 if ($@) {
122 if ($@ =~ /signal caught/) {
123 $CODE = 0;
124 } else {
125 $CODE = int($!) ? int($!) : 255;
126 }
127 $ERROR = $@;
128 warn "\n", $ERROR;
129  
130 } else {
131 if ($optstatus < 0) {
132 $CODE = $! = 255;
133 $ERROR = "ERROR: Problem loading resources\n";
134 } else {
135 $CODE = 0;
136 }
137 }
138 close_archive();
139 return 0;
140 }
141 $ArchiveOpen = 1;
142 1;
143 }
144  
145 ##---------------------------------------------------------------------------
146 ## close_archive closes the archive.
147 ##
148 sub close_archive {
149 my $reset_sigs = shift;
150  
151 ## Remove lock
152 &$UnlockFunc() if defined(&$UnlockFunc);
153  
154 ## Reset signal handlers
155 reset_handler() if $reset_sigs;
156  
157 ## Stop timing
158 eval { $EndTime = (times)[0]; };
159 my $cputime = $EndTime - $StartTime;
160  
161 ## Output time (if specified)
162 if ($TIME) {
163 printf(STDERR "\nTime: %.2f CPU seconds\n", $cputime);
164 }
165  
166 ## Restore @ARGV
167 if (@OrgARGV) { @ARGV = @OrgARGV; }
168  
169 $ArchiveOpen = 0;
170  
171 ## Return time
172 $cputime;
173 }
174  
175 ##---------------------------------------------------------------------------
176 ## Routine to process input. If no errors, routine returns the
177 ## CPU time taken. If an error, returns undef.
178 ##
179 sub process_input {
180  
181 ## Do processing
182 if ($ArchiveOpen) {
183 # archive already open, so doit
184 eval { doit(); };
185  
186 } else {
187 # open archive first (implictely pass @_ to open_archive)
188 if (&open_archive) {
189 eval { doit(); };
190 } else {
191 return undef;
192 }
193 }
194  
195 # check for error
196 if ($@) {
197 if ($@ =~ /signal caught/) {
198 $CODE = 0 unless $CODE;
199 } else {
200 $CODE = (int($!) ? int($!) : 255) unless $CODE;
201 }
202 $ERROR = $@;
203 close_archive();
204 warn "\n", $ERROR;
205 return undef;
206 }
207  
208 ## Cleanup
209 close_archive();
210 }
211  
212 ###############################################################################
213 ## Private routines
214 ###############################################################################
215  
216 ##---------------------------------------------------------------------------
217 ## Routine that does the work
218 ##
219 sub doit {
220  
221 ## Check for non-archive modification modes.
222  
223 ## Just converting a single message to HTML
224 if ($SINGLE) {
225 single();
226 return 1;
227 }
228  
229 ## Text message listing of archive to standard output.
230 if ($SCAN) {
231 scan();
232 return 1;
233 }
234  
235 ## Annotating messages
236 if ($ANNOTATE) {
237 print STDOUT "Annotating messages in $OUTDIR ...\n" unless $QUIET;
238  
239 if (!defined($NoteText)) {
240 print STDOUT
241 "Please enter note text (terminated with EOF char):\n"
242 unless $QUIET;
243 $NoteText = join("", <$MhaStdin>);
244 }
245 return annotate(@ARGV, $NoteText);
246 }
247  
248 ## Removing messages
249 if ($RMM) {
250 print STDOUT "Removing messages from $OUTDIR ...\n"
251 unless $QUIET;
252 return rmm(@ARGV);
253 }
254  
255 ## HTML message listing to standard output.
256 if ($IDXONLY) {
257 IDXPAGE: {
258 compute_page_total();
259 if ($IdxPageNum && $MULTIIDX) {
260 if ($IdxPageNum =~ /first/i) {
261 $IdxPageNum = 1;
262 last IDXPAGE;
263 }
264 if ($IdxPageNum =~ /last/i) {
265 $IdxPageNum = $NumOfPages;
266 last IDXPAGE;
267 }
268 $IdxPageNum = int($IdxPageNum);
269 last IDXPAGE if $IdxPageNum;
270 }
271 $MULTIIDX = 0;
272 $IdxPageNum = 1;
273 $NumOfPages = 1;
274 $NumOfPrintedPages = 1;
275 }
276 if ($THREAD) {
277 compute_threads();
278 write_thread_index($IdxPageNum);
279 } else {
280 write_main_index($IdxPageNum);
281 }
282 return 1;
283 }
284  
285 ## Get here, we are processing mail folders
286 my ($index, $fields, $fh, $cur_msg_cnt);
287  
288 $cur_msg_cnt = $NumOfMsgs;
289 ##-------------------##
290 ## Read mail folders ##
291 ##-------------------##
292 ## Just editing pages
293 if ($EDITIDX) {
294 print STDOUT "Editing $OUTDIR layout ...\n" unless $QUIET;
295  
296 ## Adding a single message
297 } elsif ($ADDSINGLE) {
298 print STDOUT "Adding message to $OUTDIR\n" unless $QUIET;
299 $handle = $ADD;
300  
301 ## Read mail head
302 ($index, $fields) = read_mail_header($handle);
303  
304 if ($index) {
305 if (defined(read_mail_body($handle, $index, $fields, $NoMsgPgs)))
306 {
307 $AddIndex{$index} = 1;
308 ## Invoke callback if defined
309 if ( defined($CBMessageConverted)
310 && defined(&$CBMessageConverted)) {
311 &$CBMessageConverted(
312 $fields,
313 +{ folder => undef,
314 file => '-',
315 }
316 );
317 }
318 }
319 }
320  
321 ## Adding/converting mail{boxes,folders}
322 } else {
323 print STDOUT ($ADD ? "Adding" : "Converting"), " messages to $OUTDIR"
324 unless $QUIET;
325 my ($mbox, $mesgfile, @files);
326  
327 MAILFOLDER: foreach $mbox (@ARGV) {
328  
329 ## MH mail folder (a directory)
330 if (-d $mbox) {
331 if (!opendir(MAILDIR, $mbox)) {
332 warn "\nWarning: Unable to open $mbox\n";
333 next;
334 }
335 $MBOX = 0;
336 $MH = 1;
337 print STDOUT "\nReading $mbox " unless $QUIET;
338 @files =
339 sort { $a <=> $b } grep(/$MHPATTERN/o, readdir(MAILDIR));
340 closedir(MAILDIR);
341  
342 local ($_);
343 MHFILE: foreach (@files) {
344 $mesgfile = join($DIRSEP, $mbox, $_);
345 eval { $fh = file_open($mesgfile); };
346 if ($@) {
347 warn $@, qq/...Skipping "$mesgfile"\n/;
348 next MHFILE;
349 }
350 print STDOUT "." unless $QUIET;
351 ($index, $fields) = read_mail_header($fh);
352  
353 # Process message if valid
354 if ($index) {
355 if (defined(
356 read_mail_body(
357 $fh, $index, $fields, $NoMsgPgs
358 )
359 )
360 ) {
361 if ($ADD && !$SLOW) { $AddIndex{$index} = 1; }
362  
363 # Check if conserving memory
364 if ($SLOW && $DoArchive) {
365 output_mail($index, 1, 1);
366 $Update{$IndexNum{$index}} = 1;
367 }
368 if ($SLOW || !$DoArchive) {
369 delete $MsgHead{$index};
370 delete $Message{$index};
371 }
372 ## Invoke callback if defined
373 if ( defined($CBMessageConverted)
374 && defined(&$CBMessageConverted)) {
375 &$CBMessageConverted(
376 $fields,
377 +{ folder => $mbox,
378 file => $mesgfile,
379 }
380 );
381 }
382  
383 } else {
384 $index = undef;
385 }
386 }
387 close($fh);
388 }
389  
390 ## UUCP mail box file
391 } else {
392 if ($mbox eq "-") {
393 $fh = $MhaStdin;
394 } else {
395 eval { $fh = file_open($mbox); };
396 if ($@) {
397 warn $@, qq/...Skipping "$mbox"\n/;
398 next MAILFOLDER;
399 }
400 }
401  
402 $MBOX = 1;
403 $MH = 0;
404 print STDOUT "\nReading $mbox " unless $QUIET;
405 # while (<$fh>) { last if /$FROM/o; }
406 MBOX: while (!eof($fh)) {
407 print STDOUT "." unless $QUIET;
408 ($index, $fields) = read_mail_header($fh);
409  
410 if ($index) {
411 if (defined(
412 read_mail_body(
413 $fh, $index, $fields, $NoMsgPgs
414 )
415 )
416 ) {
417 if ($ADD && !$SLOW) { $AddIndex{$index} = 1; }
418  
419 if ($SLOW && $DoArchive) {
420 output_mail($index, 1, 1);
421 $Update{$IndexNum{$index}} = 1;
422 }
423 if ($SLOW || !$DoArchive) {
424 delete $MsgHead{$index};
425 delete $Message{$index};
426 }
427 ## Invoke callback if defined
428 if ( defined($CBMessageConverted)
429 && defined(&$CBMessageConverted)) {
430 &$CBMessageConverted(
431 $fields,
432 +{ folder => $mbox,
433 file => undef,
434 }
435 );
436 }
437 } else {
438 $index = undef;
439 }
440  
441 } else {
442 # skip passed message body
443 read_mail_body($fh, $index, $fields, 1);
444 }
445 }
446 close($fh);
447  
448 } # END: else UUCP mailbox
449  
450 ## Invoke callback if defined
451 if ( defined($CBMailFolderRead)
452 && defined(&$CBMailFolderRead)) {
453 &$CBMailFolderRead($mbox);
454 }
455  
456 } # END: foreach $mbox
457 } # END: Else converting mailboxes
458 print "\n" unless $QUIET;
459  
460 ## All done if not creating an archive
461 if (!$DoArchive) {
462 return 1;
463 }
464  
465 ## Check if there are any new messages
466 if ( !$EDITIDX
467 && ($cur_msg_cnt > 0)
468 && !scalar(%AddIndex)
469 && !scalar(%Update)) {
470 print STDOUT "No new messages\n" unless $QUIET;
471 return 1;
472 }
473 $NewMsgCnt = $NumOfMsgs - $cur_msg_cnt;
474  
475 ## Write pages
476 &write_pages();
477 1;
478 }
479  
480 ##---------------------------------------------------------------------------
481 ## write_pages writes out all archive pages and db
482 ##
483 sub write_pages {
484 my ($i, $j, $key, $index, $tmp, $tmp2);
485 my (@array2);
486 my ($mloc, $tloc);
487  
488 ## Remove old message if hit maximum size or expiration
489 if ( ($MAXSIZE && ($NumOfMsgs > $MAXSIZE))
490 || $ExpireTime
491 || $ExpireDateTime) {
492  
493 ## Set @MListOrder and %Index2MLoc for properly marking messages
494 ## to be updated when a related messages are removed. Thread
495 ## data should be around from db.
496  
497 @MListOrder = sort_messages();
498 @Index2MLoc{@MListOrder} = (0 .. $#MListOrder);
499  
500 # Ignore termination signals
501 &ign_signals();
502  
503 ## Expiration based upon time
504 foreach $index (sort_messages(0, 0, 0, 0)) {
505 last
506 unless ($MAXSIZE && ($NumOfMsgs > $MAXSIZE))
507 || (&expired_time($Time{$index}));
508  
509 &delmsg($index);
510  
511 # Mark messages that need to be updated
512 if (!$NoMsgPgs && !$KeepOnRmm) {
513 $mloc = $Index2MLoc{$index};
514 $tloc = $Index2TLoc{$index};
515 $Update{$IndexNum{$MListOrder[$mloc - 1]}} = 1
516 if $mloc - 1 >= 0;
517 $Update{$IndexNum{$MListOrder[$mloc + 1]}} = 1
518 if $mloc + 1 <= $#MListOrder;
519 $Update{$IndexNum{$TListOrder[$tloc - 1]}} = 1
520 if $tloc - 1 >= 0;
521 $Update{$IndexNum{$TListOrder[$tloc + 1]}} = 1
522 if $tloc + 1 <= $#TListOrder;
523 for ($i = 2; $i <= $TSliceNBefore; ++$i) {
524 $Update{$IndexNum{$TListOrder[$tloc - $i]}} = 1
525 if $tloc - $i >= 0;
526 }
527 for ($i = 2; $i <= $TSliceNAfter; ++$i) {
528 $Update{$IndexNum{$TListOrder[$tloc + $i]}} = 1
529 if $tloc - $i >= $#TListOrder;
530 }
531 foreach (@{$FollowOld{$index}}) {
532 $Update{$IndexNum{$_}} = 1;
533 }
534 }
535  
536 # Mark where index page updates start
537 if ($MULTIIDX) {
538 $tmp = int($Index2MLoc{$index} / $IDXSIZE) + 1;
539 $IdxMinPg = $tmp
540 if ($tmp < $IdxMinPg || $IdxMinPg < 0);
541 $tmp = int($Index2TLoc{$index} / $IDXSIZE) + 1;
542 $TIdxMinPg = $tmp
543 if ($tmp < $TIdxMinPg || $TIdxMinPg < 0);
544 }
545 }
546 }
547  
548 ## Reset MListOrder
549 @MListOrder = sort_messages();
550 @Index2MLoc{@MListOrder} = (0 .. $#MListOrder);
551  
552 ## Compute follow up messages
553 compute_follow_ups(\@MListOrder);
554  
555 ## Compute thread information (sets ThreadList, TListOrder, Index2TLoc)
556 compute_threads();
557  
558 ## Check for which messages to update when adding to archive
559 if ($ADD) {
560 if ($UPDATE_ALL) {
561 foreach $index (@MListOrder) { $Update{$IndexNum{$index}} = 1; }
562 $IdxMinPg = 0;
563 $TIdxMinPg = 0;
564  
565 } else {
566 $i = 0;
567 foreach $index (@MListOrder) {
568 ## Check for New follow-up links
569 if (is_follow_ups_diff($index)) {
570 $Update{$IndexNum{$index}} = 1;
571 }
572 ## Check if new message; must update links in prev/next msgs
573 if ($AddIndex{$index}) {
574  
575 # Mark where main index page updates start
576 if ($MULTIIDX) {
577 $tmp = int($Index2MLoc{$index} / $IDXSIZE) + 1;
578 $IdxMinPg = $tmp
579 if ($tmp < $IdxMinPg || $IdxMinPg < 0);
580 }
581  
582 # Mark previous/next messages
583 $Update{$IndexNum{$MListOrder[$i - 1]}} = 1
584 if $i > 0;
585 $Update{$IndexNum{$MListOrder[$i + 1]}} = 1
586 if $i < $#MListOrder;
587 }
588 ## Check for New reference links
589 foreach (@{$Refs{$index}}) {
590 $tmp = $MsgId{$_};
591 if (defined($IndexNum{$tmp}) && $AddIndex{$tmp}) {
592 $Update{$IndexNum{$index}} = 1;
593 }
594 }
595 $i++;
596 }
597 $i = 0;
598 foreach $index (@TListOrder) {
599 ## Check if new message; must update links in prev/next msgs
600 if ($AddIndex{$index}) {
601  
602 # Mark where thread index page updates start
603 if ($MULTIIDX) {
604 $tmp = int($Index2TLoc{$index} / $IDXSIZE) + 1;
605 $TIdxMinPg = $tmp
606 if ($tmp < $TIdxMinPg || $TIdxMinPg < 0);
607 }
608  
609 # Mark previous/next message in thread
610 $Update{$IndexNum{$TListOrder[$i - 1]}} = 1
611 if $i > 0;
612 $Update{$IndexNum{$TListOrder[$i + 1]}} = 1
613 if $i < $#TListOrder;
614  
615 $tloc = $Index2TLoc{$index};
616 for ($j = 2; $j <= $TSliceNBefore; ++$j) {
617 $Update{$IndexNum{$TListOrder[$tloc - $j]}} = 1
618 if $tloc - $j >= 0;
619 }
620 for ($j = 2; $j <= $TSliceNAfter; ++$j) {
621 $Update{$IndexNum{$TListOrder[$tloc + $j]}} = 1
622 if $tloc - $j >= $#TListOrder;
623 }
624 }
625 $i++;
626 }
627 }
628 }
629  
630 ## Compute total number of pages
631 $i = $NumOfPages;
632 compute_page_total();
633  
634 ## Update all pages for $LASTPG$
635 if ($UsingLASTPG && ($i != $NumOfPages)) {
636 $IdxMinPg = 0;
637 $TIdxMinPg = 0;
638 }
639  
640 ##------------##
641 ## Write Data ##
642 ##------------##
643 ign_signals(); # Ignore termination signals
644 print STDOUT "\n" unless $QUIET;
645  
646 ## Write indexes and mail
647 write_mail() unless $NoMsgPgs;
648 write_main_index() if $MAIN;
649 write_thread_index() if $THREAD;
650  
651 ## Write database
652 print STDOUT "Writing database ...\n" unless $QUIET;
653 output_db($DBPathName);
654  
655 ## Write any alternate indexes
656 $IdxMinPg = 0;
657 $TIdxMinPg = 0;
658 my ($rc, $rcfile);
659 OTHERIDX: foreach $rc (@OtherIdxs) {
660 $THREAD = 0;
661  
662 ## find other index resource file
663 IDXFIND: {
664 if (-e $rc) {
665 # in current working directory
666 $rcfile = $rc;
667 last IDXFIND;
668 }
669 if (defined $MainRcDir) {
670 # check if located with main resource file
671 $rcfile = join($DIRSEP, $MainRcDir, $rc);
672 last IDXFIND if -e $rcfile;
673 }
674 if (defined $ENV{'HOME'}) {
675 # check if in home directory
676 $rcfile = join($DIRSEP, $ENV{'HOME'}, $rc);
677 last IDXFIND if -e $rcfile;
678 }
679  
680 # check if in archive directory
681 $rcfile = join($DIRSEP, $OUTDIR, $rc);
682 last IDXFIND if -e $rcfile;
683  
684 # look thru @INC to find file
685 local ($_);
686 foreach (@INC) {
687 $rcfile = join($DIRSEP, $_, $rc);
688 if (-e $rcfile) {
689 last IDXFIND;
690 }
691 }
692 warn qq/Warning: Unable to find resource file "$rc"\n/;
693 next OTHERIDX;
694 }
695  
696 ## read resource file and print index
697 if (read_resource_file($rcfile)) {
698 if ($THREAD) {
699 @TListOrder = ();
700 write_thread_index();
701 } else {
702 @MListOrder = ();
703 write_main_index();
704 }
705 }
706 }
707  
708 unless ($QUIET) {
709 print STDOUT "$NewMsgCnt new messages\n" if $NewMsgCnt > 0;
710 print STDOUT "$NumOfMsgs total messages\n";
711 }
712  
713 } ## End: write_pages()
714  
715 ##---------------------------------------------------------------------------
716 ## Compute follow-ups
717 ##
718 sub compute_follow_ups {
719 my $idxlst = shift;
720 my ($index, $tmp, $tmp2);
721  
722 %Follow = ();
723 foreach $index (@$idxlst) {
724 $FolCnt{$index} = 0 unless $FolCnt{$index};
725 if (defined($Refs{$index}) && scalar(@{$Refs{$index}})) {
726 $tmp2 = $Refs{$index}->[-1];
727 next
728 unless defined($MsgId{$tmp2})
729 && defined($IndexNum{$MsgId{$tmp2}});
730 $tmp = $MsgId{$tmp2};
731 if ($Follow{$tmp}) { push(@{$Follow{$tmp}}, $index); }
732 else { $Follow{$tmp} = [$index]; }
733 ++$FolCnt{$tmp};
734 }
735 }
736 }
737  
738 ##---------------------------------------------------------------------------
739 ## Compute total number of pages
740 ##
741 sub compute_page_total {
742 if ($MULTIIDX && $IDXSIZE) {
743 $NumOfPages = int($NumOfMsgs / $IDXSIZE);
744 ++$NumOfPages if ($NumOfMsgs / $IDXSIZE) > $NumOfPages;
745 $NumOfPages = 1 if $NumOfPages == 0;
746  
747 $NumOfPrintedPages = $NumOfPages;
748 if (($MAXPGS > 0) && ($MAXPGS < $NumOfPages)) {
749 $NumOfPrintedPages = $MAXPGS;
750 }
751  
752 } else {
753 $NumOfPages = 1;
754 $NumOfPrintedPages = 1;
755 }
756  
757 }
758  
759 ##---------------------------------------------------------------------------
760 ## write_mail outputs converted mail. It takes a reference to an
761 ## array containing indexes of messages to output.
762 ##
763 sub write_mail {
764 my ($hack) = (0);
765 print STDOUT "Writing mail " unless $QUIET;
766  
767 if ($SLOW && !$ADD) {
768 $ADD = 1;
769 $hack = 1;
770 }
771  
772 foreach $index (@MListOrder) {
773 print STDOUT "." unless $QUIET;
774 output_mail($index, $AddIndex{$index}, 0);
775 }
776  
777 if ($hack) {
778 $ADD = 0;
779 }
780  
781 print STDOUT "\n" unless $QUIET;
782 }
783  
784 ##---------------------------------------------------------------------------
785 ## read_mail_header() is responsible for parsing the header of
786 ## a mail message and loading message information into hash
787 ## structures.
788 ##
789 ## ($index, $header_fields_ref) = read_mail_header($filehandle);
790 ##
791 sub read_mail_header {
792 my $handle = shift;
793 my ($date, $tmp, $i, $field, $value);
794 my ($from, $sub, $msgid, $ctype);
795 local ($_);
796  
797 my $index = undef;
798 my $msgnum = undef;
799 my @refs = ();
800 my @array = ();
801 my ($fields, $header) = readmail::MAILread_file_header($handle);
802  
803 ##---------------------------##
804 ## Check for no archive flag ##
805 ##---------------------------##
806 if ($CheckNoArchive
807 && (( defined($fields->{'restrict'})
808 && grep {/no-external-archive/i} @{$fields->{'restrict'}}
809 )
810 || (defined($fields->{'x-no-archive'})
811 && grep {/yes/i} @{$fields->{'x-no-archive'}})
812 )
813 ) {
814 return undef;
815 }
816  
817 ##----------------------------------##
818 ## Check for user-defined exclusion ##
819 ##----------------------------------##
820 if ($MsgExcFilter) {
821 return undef if mhonarc::message_exclude($header);
822 }
823  
824 ##------------##
825 ## Get Msg-ID ##
826 ##------------##
827 $msgid =
828 $fields->{'message-id'}[0]
829 || $fields->{'msg-id'}[0]
830 || $fields->{'content-id'}[0];
831 if (defined($msgid)) {
832 if ($msgid =~ /<([^>]*)>/) {
833 $msgid = $1;
834 } else {
835 $msgid =~ s/^\s+//;
836 $msgid =~ s/\s+$//;
837 }
838 } else {
839 # create bogus ID if none exists
840 eval {
841 # create message-id using md5 digest of header;
842 # can potentially skip over already archived messages w/o id
843 require Digest::MD5;
844 $msgid = join("",
845 Digest::MD5::md5_hex($header),
846 '@NO-ID-FOUND.mhonarc.org');
847 };
848 if ($@) {
849 # unable to require, so create arbitary message-id
850 $msgid = join("",
851 $$, '.', time, '.', $_msgid_cnt++,
852 '@NO-ID-FOUND.mhonarc.org');
853 }
854 }
855  
856 ## Return if message already exists in archive
857 if ($msgid && defined($index = $MsgId{$msgid})) {
858 if ($Reconvert) {
859 $msgnum = $IndexNum{$index};
860 delmsg($index);
861 $index = undef;
862 } else {
863 return undef;
864 }
865 }
866  
867 ##----------##
868 ## Get date ##
869 ##----------##
870 $date = "";
871 foreach (@_DateFields) {
872 ($field, $i) = @{$_}[0, 1];
873 next
874 unless defined($fields->{$field})
875 && defined($value = $fields->{$field}[$i]);
876  
877 ## Treat received field specially
878 if ($field eq 'received') {
879 @array = split(/;/, $value);
880 # if ((scalar(@array) <= 1) || (scalar(@array) > 2)) {
881 # warn qq/\nWarning: Received header field looks improper:\n/,
882 # qq/ Received: $value\n/,
883 # qq/ Message-Id: <$msgid>\n/;
884 # }
885 $date = pop @array;
886 ## Any other field should just be a date
887 } else {
888 $date = $value;
889 }
890 $date =~ s/^\s+//;
891 $date =~ s/\s+$//;
892  
893 ## See if time_t can be determined.
894 if (($date =~ /\w/) && (@array = parse_date($date))) {
895 $index = get_time_from_date(@array[1 .. $#array]);
896 last;
897 }
898 }
899 if (!$index) {
900 warn qq/\nWarning: Could not parse date for message\n/,
901 qq/ Message-Id: <$msgid>\n/,
902 qq/ Date: $date\n/;
903 # Use current time
904 $index = time;
905 # Set date string to local date if not defined
906 $date = &time2str("", $index, 1) unless $date =~ /\S/;
907 }
908  
909 ## Return if message too old to add (note, $index just contains time).
910 if (&expired_time($index)) {
911 return undef;
912 }
913  
914 ##-------------##
915 ## Get Subject ##
916 ##-------------##
917 if (defined($fields->{'subject'})) {
918 ($sub = $fields->{'subject'}[0]) =~ s/\s+$//;
919 if ($SubStripCode) {
920 $fields->{'x-mha-org-subject'} = $sub;
921 $sub = subject_strip($sub);
922 }
923 $fields->{'subject'} = [$sub]; # Make sure only one subject
924 } else {
925 $sub = '';
926 }
927  
928 ##----------##
929 ## Get From ##
930 ##----------##
931 $from = "";
932 foreach (@FromFields) {
933 next unless defined $fields->{$_};
934 $from = $fields->{$_}[0];
935 last;
936 }
937 $from = 'Unknown' unless $from;
938  
939 ##----------------##
940 ## Get References ##
941 ##----------------##
942 if (defined($fields->{'references'})) {
943 $tmp = $fields->{'references'}[0];
944 while ($tmp =~ s/<([^<>]+)>//) {
945 push(@refs, $1);
946 }
947 }
948 if (defined($fields->{'in-reply-to'})) {
949 my $irtoid;
950 foreach (@{$fields->{'in-reply-to'}}) {
951 $tmp = $_;
952 $irtoid = "";
953 while ($tmp =~ s/<([^<>]+)>//) { $irtoid = $1 }
954 push(@refs, $irtoid) if $irtoid;
955 }
956 }
957 @refs = remove_dups(\@refs); # Remove duplicate msg-ids
958  
959 ##------------------##
960 ## Get Content-Type ##
961 ##------------------##
962 if (defined($fields->{'content-type'})) {
963 ($ctype = $fields->{'content-type'}[0]) =~ m%^\s*([\w\-\./]+)%;
964 $ctype = lc($1 || 'text/plain');
965 } else {
966 $ctype = 'text/plain';
967 }
968  
969 ## Insure uniqueness of index
970 my $t = $index;
971 $index .=
972 $X . sprintf('%d', (defined($msgnum) ? $msgnum : ($LastMsgNum + 1)));
973  
974 ## Set mhonarc fields. Note how values are NOT arrays.
975 $fields->{'x-mha-index'} = $index;
976 $fields->{'x-mha-message-id'} = $msgid;
977 $fields->{'x-mha-from'} = $from;
978 $fields->{'x-mha-subject'} = $sub;
979 $fields->{'x-mha-content-type'} = $ctype;
980  
981 ## Invoke callback if defined
982 if (defined($CBMessageHeadRead) && defined(&$CBMessageHeadRead)) {
983 return undef unless &$CBMessageHeadRead($fields, $header);
984 }
985  
986 $Time{$index} = $t;
987 $From{$index} = $from;
988 $FromName{$index} = extract_email_name($from) if $DoFromName;
989 $FromAddr{$index} = extract_email_address($from) if $DoFromAddr;
990 $Date{$index} = $date;
991 $Subject{$index} = $sub;
992 $MsgHead{$index} = htmlize_header($fields);
993 $ContentType{$index} = $ctype;
994 if ($msgid) {
995 $MsgId{$msgid} = $index;
996 $NewMsgId{$msgid} = $index; # Track new message-ids
997 $Index2MsgId{$index} = $msgid;
998 }
999 if (defined($msgnum)) {
1000 $IndexNum{$index} = $msgnum;
1001 ++$NumOfMsgs; # Counteract decrement by delmsg
1002 } else {
1003 $IndexNum{$index} = getNewMsgNum();
1004 }
1005  
1006 $Refs{$index} = [@refs] if (@refs);
1007  
1008 ## Grab any extra fields to store
1009 foreach $field (@ExtraHFields) {
1010 next unless $fields->{$field};
1011 if (!defined($tmp = $ExtraHFields{$index})) {
1012 $tmp = $ExtraHFields{$index} = {};
1013 }
1014 if ($HFieldsAddr{$field}) {
1015 $tmp->{$field} = join(', ', @{$fields->{$field}});
1016 } else {
1017 $tmp->{$field} = join(' ', @{$fields->{$field}});
1018 }
1019 }
1020  
1021 ($index, $fields);
1022 }
1023  
1024 ##---------------------------------------------------------------------------
1025 ## read_mail_body() reads in the body of a message. The returned
1026 ## filtered body is in $ret.
1027 ##
1028 ## $html = read_mail_body($fh, $index, $fields_hash_ref,
1029 ## $skipConversion);
1030 ##
1031 sub read_mail_body {
1032 my ($handle, $index, $fields, $skip) = @_;
1033 my ($ret, $data) = ('', '');
1034 my (@files);
1035 local ($_);
1036  
1037 ## Slurp up message body
1038 ## UUCP mailbox
1039 if ($MBOX) {
1040 if ($CONLEN && defined($fields->{"content-length"})) {
1041 my ($len, $cnt) = ($fields->{"content-length"}[0], 0);
1042 if ($len) {
1043 while (<$handle>) {
1044 $cnt += length($_); # Increment byte count
1045 $data .= $_ unless $skip; # Save data
1046 last if $cnt >= $len # Last if hit length
1047 }
1048 }
1049 # Slurp up bogus data if required (should I do this?)
1050 while (!/$FROM/o && !eof($handle)) {
1051 $_ = <$handle>;
1052 }
1053  
1054 } else { # No content-length
1055 while (<$handle>) {
1056 last if /$FROM/o;
1057 $data .= $_ unless $skip;
1058 }
1059 }
1060  
1061 ## MH message file
1062 } elsif (!$skip) {
1063 local $/ = undef;
1064 $data = <$handle>;
1065 }
1066 if ($DEBUG) {
1067 print STDERR "read_mail_body(): Body data loaded into memory\n";
1068 }
1069  
1070 return '' if $skip;
1071  
1072 ## Invoke callback if defined
1073 if (defined($CBRawMessageBodyRead) && defined(&$CBRawMessageBodyRead)) {
1074 if ($DEBUG) {
1075 print STDERR "read_mail_body(): Calling CBRawMessageBodyRead\n";
1076 }
1077 if (!&$CBRawMessageBodyRead($fields, \$data)) {
1078 # reverse effect of read_mail_header()
1079 delmsg_from_hashes($index);
1080 return undef;
1081 }
1082 }
1083  
1084 ## Define "globals" for use by filters
1085 ## NOTE: This stuff can be handled better, and will be done
1086 ## when/if I get around to rewriting mhonarc in (OO) Perl 5.
1087 $MHAindex = $index;
1088 $MHAmsgnum = &fmt_msgnum($IndexNum{$index});
1089 $MHAmsgid = $Index2MsgId{$index};
1090  
1091 ## Filter data
1092 if ($DEBUG) {
1093 print STDERR "read_mail_body(): Calling readmail::MAILread_body\n";
1094 }
1095 ($ret, @files) = &readmail::MAILread_body($fields, \$data);
1096 if ($DEBUG) {
1097 print STDERR "read_mail_body(): readmail::MAILread_body DONE\n";
1098 }
1099 $ret = '' unless defined $ret;
1100 @files = () unless @files;
1101  
1102 ## Invoke callback if defined
1103 if (defined($CBMessageBodyRead) && defined(&$CBMessageBodyRead)) {
1104 if (!&$CBMessageBodyRead($fields, \$ret, \@files)) {
1105 # reverse effect of read_mail_header()
1106 delmsg_from_hashes($index);
1107 return undef;
1108 }
1109 $Message{$index} = $ret;
1110 } else {
1111 $Message{$index} = $ret;
1112 }
1113  
1114 if (!defined($ret) || $ret eq '') {
1115 warn qq/\n/,
1116 qq/Warning: Empty body data generated:\n/,
1117 qq/ Message-Id: $MHAmsgid\n/,
1118 qq/ Message Subject: /, $fields->{'x-mha-subject'},
1119 qq/\n/,
1120 qq/ Message Number: $MHAmsgnum\n/,
1121 qq/ Content-Type: /,
1122 ($fields->{'content-type'}[0] || 'text/plain'),
1123 qq/\n/;
1124 $ret = '';
1125 }
1126 if (@files) {
1127 $Derived{$index} = [@files];
1128 }
1129 $ret;
1130 }
1131  
1132 ##---------------------------------------------------------------------------
1133 ## Output/edit a mail message.
1134 ## $index => current index (== $array[$i])
1135 ## $force => flag if mail is written and not editted, regardless
1136 ## $nocustom => ignore sections with user customization
1137 ##
1138 ## This function returns ($msgnum, $filename) if everything went
1139 ## okay, but no calls to this routine check the return values.
1140 ##
1141 sub output_mail {
1142 my ($index, $force, $nocustom) = @_;
1143 my ($msgi, $tmp, $tmp2, $template, @array2);
1144 my ($msghandle, $msginfh);
1145  
1146 my $msgnum = $IndexNum{$index};
1147 if (!$SINGLE && !defined($msgnum)) {
1148 # Something bad must have happened to message, so we just
1149 # quietly return.
1150 return;
1151 }
1152  
1153 my $adding = ($ADD && !$force && !$SINGLE);
1154 my $i_p0 = fmt_msgnum($msgnum);
1155 my $filename = msgnum_filename($msgnum);
1156 my $filepathname = join($DIRSEP, $OUTDIR, $filename);
1157 my $tmppathname;
1158  
1159 if ($adding) {
1160 return ($i_p0, $filename) unless $Update{$msgnum};
1161 #&file_rename($filepathname, $tmppathname);
1162 eval { $msginfh = file_open($filepathname); };
1163 if ($@) {
1164 # Something is screwed up with archive: We try to delete
1165 # message from database since message file appears to have
1166 # disappeared
1167 warn $@, qq/...Will attempt to remove message and continue on\n/;
1168 delmsg($index);
1169  
1170 # Nothing else to do, so return.
1171 return;
1172 }
1173 }
1174 if ($SINGLE) {
1175 $msghandle = \*STDOUT;
1176 } else {
1177 ($msghandle, $tmppathname) =
1178 file_temp('tmsg' . $i_p0 . '_XXXXXXXXXX', $OUTDIR);
1179 }
1180  
1181 ## Output HTML header
1182 if ($adding) {
1183 while (<$msginfh>) {
1184 last if /<!--X-Body-Begin/;
1185 }
1186 }
1187 if (!$nocustom) {
1188 #&defineIndex2MsgId();
1189  
1190 $template = ($MSGPGSSMARKUP ne '') ? $MSGPGSSMARKUP : $SSMARKUP;
1191 if ($template ne '') {
1192 $template =~ s/$VarExp/&replace_li_var($1,$index)/geo;
1193 print $msghandle $template;
1194 }
1195  
1196 # Output comments -- more informative, but can be used for
1197 # error recovering.
1198 print $msghandle "<!-- ", commentize("MHonArc v$VERSION"), " -->\n";
1199 if ($PrintXComments) {
1200 print $msghandle
1201 "<!--X-Subject: ",
1202 commentize($Subject{$index}), " -->\n",
1203 "<!--X-From-R13: ",
1204 commentize(mrot13($From{$index})), " -->\n",
1205 "<!--X-Date: ",
1206 commentize($Date{$index}), " -->\n",
1207 "<!--X-Message-Id: ",
1208 commentize($Index2MsgId{$index}), " -->\n",
1209 "<!--X-Content-Type: ",
1210 commentize($ContentType{$index}), " -->\n";
1211  
1212 if (defined($Refs{$index})) {
1213 foreach (@{$Refs{$index}}) {
1214 print $msghandle "<!--X-Reference: ", commentize($_),
1215 " -->\n";
1216 #Reference-Id
1217 }
1218 }
1219 if (defined($Derived{$index})) {
1220 foreach (@{$Derived{$index}}) {
1221 print $msghandle "<!--X-Derived: ", commentize($_),
1222 " -->\n";
1223 }
1224 }
1225 }
1226 print $msghandle "<!--X-Head-End-->\n";
1227  
1228 # Add in user defined markup
1229 ($template = $MSGPGBEG) =~ s/$VarExp/&replace_li_var($1,$index)/geo;
1230 print $msghandle $template;
1231 }
1232 print $msghandle "<!--X-Body-Begin-->\n";
1233  
1234 ## Output header
1235 if ($adding) {
1236 while (<$msginfh>) {
1237 last if /<!--X-User-Header-End/ || /<!--X-TopPNI--/;
1238 }
1239 }
1240 print $msghandle "<!--X-User-Header-->\n";
1241 if (!$nocustom) {
1242 ($template = $MSGHEAD) =~ s/$VarExp/&replace_li_var($1,$index)/geo;
1243 print $msghandle $template;
1244 }
1245 print $msghandle "<!--X-User-Header-End-->\n";
1246  
1247 ## Output Prev/Next/Index links at top
1248 if ($adding) {
1249 while (<$msginfh>) { last if /<!--X-TopPNI-End/; }
1250 }
1251 print $msghandle "<!--X-TopPNI-->\n";
1252 if (!$nocustom && !$SINGLE) {
1253 ($template = $TOPLINKS) =~ s/$VarExp/&replace_li_var($1,$index)/geo;
1254 print $msghandle $template;
1255 }
1256 print $msghandle "\n<!--X-TopPNI-End-->\n";
1257  
1258 ## Output message data
1259 if ($adding) {
1260 $tmp2 = "";
1261 while (<$msginfh>) {
1262 # check if subject header delimited
1263 if (/<!--X-Subject-Header-Begin/) {
1264 $tmp2 =~ s/($HAddrExp)/&link_refmsgid($1,1)/geo;
1265 print $msghandle $tmp2;
1266 $tmp2 = "";
1267  
1268 while (<$msginfh>) { last if /<!--X-Subject-Header-End/; }
1269 print $msghandle "<!--X-Subject-Header-Begin-->\n";
1270 if (!$nocustom) {
1271 ($template = $SUBJECTHEADER) =~
1272 s/$VarExp/&replace_li_var($1,$index)/geo;
1273 print $msghandle $template;
1274 }
1275 print $msghandle "<!--X-Subject-Header-End-->\n";
1276 next;
1277 }
1278 # check if head/body separator delimited
1279 if (/<!--X-Head-Body-Sep-Begin/) {
1280 $tmp2 =~ s/($HAddrExp)/&link_refmsgid($1,1)/geo;
1281 print $msghandle $tmp2;
1282 $tmp2 = "";
1283  
1284 while (<$msginfh>) { last if /<!--X-Head-Body-Sep-End/; }
1285 print $msghandle "<!--X-Head-Body-Sep-Begin-->\n";
1286 if (!$nocustom) {
1287 ($template = $HEADBODYSEP) =~
1288 s/$VarExp/&replace_li_var($1,$index)/geo;
1289 print $msghandle $template;
1290 }
1291 print $msghandle "<!--X-Head-Body-Sep-End-->\n";
1292 next;
1293 }
1294  
1295 $tmp2 .= $_;
1296 last if /<!--X-MsgBody-End/;
1297 }
1298 $tmp2 =~ s/($HAddrExp)/&link_refmsgid($1,1)/geo;
1299 print $msghandle $tmp2;
1300  
1301 } else {
1302 print $msghandle "<!--X-MsgBody-->\n";
1303 print $msghandle "<!--X-Subject-Header-Begin-->\n";
1304 ($template = $SUBJECTHEADER) =~
1305 s/$VarExp/&replace_li_var($1,$index)/geo;
1306 print $msghandle $template;
1307 print $msghandle "<!--X-Subject-Header-End-->\n";
1308  
1309 $MsgHead{$index} =~ s/($HAddrExp)/&link_refmsgid($1)/geo;
1310 $Message{$index} =~ s/($HAddrExp)/&link_refmsgid($1)/geo;
1311  
1312 print $msghandle "<!--X-Head-of-Message-->\n";
1313 print $msghandle $MsgHead{$index};
1314 print $msghandle "<!--X-Head-of-Message-End-->\n";
1315 print $msghandle "<!--X-Head-Body-Sep-Begin-->\n";
1316 ($template = $HEADBODYSEP) =~
1317 s/$VarExp/&replace_li_var($1,$index)/geo;
1318 print $msghandle $template;
1319 print $msghandle "<!--X-Head-Body-Sep-End-->\n";
1320 print $msghandle "<!--X-Body-of-Message-->\n";
1321 print $msghandle $Message{$index}, "\n";
1322 print $msghandle "<!--X-Body-of-Message-End-->\n";
1323 print $msghandle "<!--X-MsgBody-End-->\n";
1324 }
1325  
1326 ## Output any followup messages
1327 if ($adding) {
1328 while (<$msginfh>) { last if /<!--X-Follow-Ups-End/; }
1329 }
1330 print $msghandle "<!--X-Follow-Ups-->\n";
1331 ($template = $MSGBODYEND) =~ s/$VarExp/&replace_li_var($1,$index)/geo;
1332 print $msghandle $template;
1333 if (!$nocustom && $DoFolRefs && defined($Follow{$index})) {
1334 if (scalar(@{$Follow{$index}})) {
1335 ($template = $FOLUPBEGIN) =~
1336 s/$VarExp/&replace_li_var($1,$index)/geo;
1337 print $msghandle $template;
1338 foreach (@{$Follow{$index}}) {
1339 ($template = $FOLUPLITXT) =~
1340 s/$VarExp/&replace_li_var($1,$_)/geo;
1341 print $msghandle $template;
1342 }
1343 ($template = $FOLUPEND) =~
1344 s/$VarExp/&replace_li_var($1,$index)/geo;
1345 print $msghandle $template;
1346 }
1347 }
1348 print $msghandle "<!--X-Follow-Ups-End-->\n";
1349  
1350 ## Output any references
1351 if ($adding) {
1352 while (<$msginfh>) { last if /<!--X-References-End/; }
1353 }
1354 print $msghandle "<!--X-References-->\n";
1355 if (!$nocustom && $DoFolRefs && defined($Refs{$index})) {
1356 $tmp2 = 0; # flag for when first ref printed
1357 if (scalar(@{$Refs{$index}})) {
1358 my ($ref_msgid, $ref_index, $ref_num);
1359 foreach $ref_msgid (@{$Refs{$index}}) {
1360 next unless defined($ref_index = $MsgId{$ref_msgid});
1361 next unless defined($ref_num = $IndexNum{$ref_index});
1362 if (!$tmp2) {
1363 ($template = $REFSBEGIN) =~
1364 s/$VarExp/&replace_li_var($1,$index)/geo;
1365 print $msghandle $template;
1366 $tmp2 = 1;
1367 }
1368 ($template = $REFSLITXT) =~
1369 s/$VarExp/&replace_li_var($1,$ref_index)/geo;
1370 print $msghandle $template;
1371 }
1372  
1373 if ($tmp2) {
1374 ($template = $REFSEND) =~
1375 s/$VarExp/&replace_li_var($1,$index)/geo;
1376 print $msghandle $template;
1377 }
1378 }
1379 }
1380 print $msghandle "<!--X-References-End-->\n";
1381  
1382 ## Output verbose links to prev/next message in list
1383 if ($adding) {
1384 while (<$msginfh>) { last if /<!--X-BotPNI-End/; }
1385 }
1386 print $msghandle "<!--X-BotPNI-->\n";
1387 if (!$nocustom && !$SINGLE) {
1388 ($template = $BOTLINKS) =~ s/$VarExp/&replace_li_var($1,$index)/geo;
1389 print $msghandle $template;
1390 }
1391 print $msghandle "\n<!--X-BotPNI-End-->\n";
1392  
1393 ## Output footer
1394 if ($adding) {
1395 while (<$msginfh>) {
1396 last if /<!--X-User-Footer-End/;
1397 }
1398 }
1399 print $msghandle "<!--X-User-Footer-->\n";
1400 if (!$nocustom) {
1401 ($template = $MSGFOOT) =~ s/$VarExp/&replace_li_var($1,$index)/geo;
1402 print $msghandle $template;
1403 }
1404 print $msghandle "<!--X-User-Footer-End-->\n";
1405  
1406 if (!$nocustom) {
1407 ($template = $MSGPGEND) =~ s/$VarExp/&replace_li_var($1,$index)/geo;
1408 print $msghandle $template;
1409 }
1410  
1411 close($msghandle) if (!$SINGLE);
1412 if ($adding) {
1413 close($msginfh);
1414 #&file_remove($tmppathname);
1415 }
1416 if (!$SINGLE) {
1417 file_gzip($tmppathname) if $GzipFiles;
1418 file_chmod(file_rename($tmppathname, $filepathname));
1419 }
1420  
1421 ## Create user defined files
1422 my ($drvfh);
1423 foreach (keys %UDerivedFile) {
1424 ($tmp = $_) =~ s/$VarExp/&replace_li_var($1,$index)/geo;
1425 ($drvfh, $tmppathname) = file_temp('drvXXXXXXXXXX', $OUTDIR);
1426 ($template = $UDerivedFile{$_}) =~
1427 s/$VarExp/&replace_li_var($1,$index)/geo;
1428 print $drvfh $template;
1429 close($drvfh);
1430 file_gzip($tmppathname) if $GzipFiles;
1431 file_chmod(file_rename($tmppathname, join($DIRSEP, $OUTDIR, $tmp)));
1432  
1433 if (defined($Derived{$index})) {
1434 push(@{$Derived{$index}}, $tmp);
1435 } else {
1436 $Derived{$index} = [$tmp];
1437 }
1438 }
1439 if (defined($Derived{$index})) {
1440 $Derived{$index} = [remove_dups($Derived{$index})];
1441 }
1442  
1443 ## Set modification times -- Use eval incase OS does not support utime.
1444 if ($MODTIME && !$SINGLE) {
1445 eval {
1446 $tmp = $Time{$index};
1447 if (defined($Derived{$index})) {
1448 @array2 = @{$Derived{$index}};
1449 grep($_ = $OUTDIR . $DIRSEP . $_, @array2);
1450 } else {
1451 @array2 = ();
1452 }
1453 unshift(@array2, $filepathname);
1454 file_utime($tmp, $tmp, @array2);
1455 };
1456 if ($@) {
1457 warn qq/\nWarning: Your platform does not support setting file/,
1458 qq/ modification times\n/;
1459 $MODTIME = 0;
1460 }
1461 }
1462  
1463 ($i_p0, $filename);
1464 }
1465  
1466 #############################################################################
1467 ## Miscellaneous routines
1468 #############################################################################
1469  
1470 ##---------------------------------------------------------------------------
1471 ## delmsg deletes a message from the archive.
1472 ##
1473 sub delmsg {
1474 my $key = shift;
1475 my ($filename, $derived) = delmsg_from_hashes($key);
1476 return 0 unless defined($filename);
1477  
1478 if (!$KeepOnRmm) {
1479 file_remove($filename);
1480 if (defined($derived)) {
1481 my $pathname;
1482 foreach $filename (@{$derived}) {
1483 $pathname =
1484 (OSis_absolute_path($filename))
1485 ? $filename
1486 : join($DIRSEP, $OUTDIR, $filename);
1487 if (-d $pathname) {
1488 dir_remove($pathname);
1489 } else {
1490 file_remove($pathname);
1491 }
1492 }
1493 }
1494 }
1495 1;
1496 }
1497  
1498 ##---------------------------------------------------------------------------
1499 ## delmsg_from_hashes deletes all message info from db hashes.
1500 ## Return value is a list of two items: pathname to message
1501 ## file and array ref to any derived files.
1502 ##
1503 sub delmsg_from_hashes {
1504 my $key = shift;
1505  
1506 #&defineIndex2MsgId();
1507 my $msgnum = $IndexNum{$key};
1508 return (undef, undef) if ($msgnum eq '');
1509 my $filename = join($DIRSEP, $OUTDIR, &msgnum_filename($msgnum));
1510  
1511 delete $ContentType{$key};
1512 delete $Date{$key};
1513 delete $From{$key};
1514 delete $IndexNum{$key};
1515 delete $Refs{$key};
1516 delete $Subject{$key};
1517 delete $ExtraHFields{$key};
1518 delete $MsgId{$Index2MsgId{$key}};
1519  
1520 my $derived = $Derived{$key};
1521 delete $Derived{$key};
1522  
1523 $NumOfMsgs--;
1524 ($filename, $derived);
1525 }
1526  
1527 ##---------------------------------------------------------------------------
1528 ## Routine to convert a msgid to an anchor
1529 ##
1530 sub link_refmsgid {
1531 my $refmsgid = dehtmlize(shift);
1532 my $onlynew = shift;
1533  
1534 if ( defined($MsgId{$refmsgid})
1535 && defined($IndexNum{$MsgId{$refmsgid}})
1536 && (!$onlynew || $NewMsgId{$refmsgid})) {
1537 my ($lreftmpl) = $MSGIDLINK;
1538 $lreftmpl =~ s/$VarExp/&replace_li_var($1,$MsgId{$refmsgid})/geo;
1539 return $lreftmpl;
1540 }
1541 htmlize($refmsgid);
1542 }
1543  
1544 ##---------------------------------------------------------------------------
1545 ## Retrieve next available message number. Should only be used
1546 ## when an archive is locked.
1547 ##
1548 sub getNewMsgNum {
1549 $NumOfMsgs++;
1550 $LastMsgNum++;
1551 $LastMsgNum;
1552 }
1553  
1554 ##---------------------------------------------------------------------------
1555 ## ign_signals() sets mhonarc to ignore termination signals. This
1556 ## routine is called right before an archive is written/edited to
1557 ## help prevent archive corruption.
1558 ##
1559 sub ign_signals {
1560 @SIG{@_term_sigs} = ('IGNORE') x scalar(@_term_sigs);
1561 }
1562  
1563 ##---------------------------------------------------------------------------
1564 ## set_handler() sets up the signal_catch() routine to be called when
1565 ## termination signals are sent to mhonarc.
1566 ##
1567 sub set_handler {
1568 %_sig_org = ();
1569 @_sig_org{@_term_sigs} = @SIG{@_term_sigs};
1570 @SIG{@_term_sigs} = (\&mhonarc::signal_catch) x scalar(@_term_sigs);
1571 }
1572  
1573 ##---------------------------------------------------------------------------
1574 ## reset_handler() resets the original signal handlers.
1575 ##
1576 sub reset_handler {
1577 @SIG{@_term_sigs} = @_sig_org{@_term_sigs};
1578 }
1579  
1580 ##---------------------------------------------------------------------------
1581 ## signal_catch(): Function for handling signals that would cause
1582 ## termination.
1583 ##
1584 sub signal_catch {
1585 my $signame = shift;
1586 close_archive(1);
1587 &{$_sig_org{$signame}}($signame) if defined(&{$_sig_org{$signame}});
1588 reset_handler();
1589 die qq/Processing stopped, signal caught: SIG$signame\n/;
1590 }
1591  
1592 ##---------------------------------------------------------------------------
1593 ## Create Index2MsgId if not defined
1594 ##
1595 sub defineIndex2MsgId {
1596 no warnings qw(deprecated);
1597 unless (%Index2MsgId) {
1598 foreach (keys %MsgId) {
1599 $Index2MsgId{$MsgId{$_}} = $_;
1600 }
1601 }
1602 }
1603  
1604 ##---------------------------------------------------------------------------
1605 1;