mhamain.pl untested

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