2 #################################################################################
4 # File: $RCSfile: MAPS.pm,v $
5 # Revision: $Revision: 1.1 $
6 # Description: Main module for Mail Authentication and Permission System (MAPS)
7 # Author: Andrew@DeFaria.com
8 # Created: Fri Nov 29 14:17:21 2002
9 # Modified: $Date: 2013/06/12 14:05:47 $
12 # (c) Copyright 2000-2018, Andrew@DeFaria.com, all rights reserved.
14 ################################################################################
33 use base qw(Exporter);
40 my $userid = $ENV{MAPS_USERNAME} ? $ENV{MAPS_USERNAME} : $ENV{USER};
104 my $mapsbase = "$FindBin::Bin/..";
107 sub _cleanTables($$;$) {
108 my ($table, $timestamp, $dryrun) = @_;
110 my $condition = "userid = '$userid' and timestamp < '$timestamp'";
113 return $db->count($table, $condition);
115 my ($count, $msg) = $db->delete($table, $condition);
121 sub _retention2Days($) {
122 my ($retention) = @_;
124 # Of the retnetion periods I'm thinking of where they are <n> and then
125 # something like (days|weeks|months|years) none are tricky except for months
126 # because months, unlike (days|weeks|years) are ill-defined. Are there 28, 29
127 # 30 or 31 days in a month? Days are simple <n> days. Weeks are simple <n> * 7
128 # days. Years are simple - just change the year (a little oddity of 365 or
129 # 366) days this year? To keep things simple, we will ignore the oddities of
130 # leap years and just use 30 for number of days in month. We really don't need
131 # to be that accurate here...
133 # BTW we aren't checking for odd things like 34320 weeks or 5000 years...
134 if ($retention =~ /(\d+)\s+(day|days)/) {
136 } elsif ($retention =~ /(\d+)\s+(week|weeks)/){
138 } elsif ($retention =~ /(\d+)\s+(month|months)/) {
140 } elsif ($retention =~ /(\d+)\s+(year|years)/) {
150 my ($username, $password) = @_;
153 my $dbserver = $ENV{MAPS_SERVER} || 'localhost';
155 $db = MyDB->new($username, $password, $dbname, $dbserver);
157 croak "Unable to instantiate MyDB ($username\@$dbserver:$dbname)" unless $db;
163 my $MAPS_username = "maps";
164 my $MAPS_password = "spam";
166 OpenDB($MAPS_username, $MAPS_password);
169 sub Add2Blacklist(%) {
172 # Add2Blacklist will add an entry to the blacklist
173 # First SetContext to the userid whose black list we are adding to
174 SetContext($params{userid});
177 $params{sequence} = 0;
178 my ($err, $msg) = AddList(%params);
180 # Log that we black listed the sender
181 Info("Added $params{sender} to " . ucfirst $params{userid} . "'s black list");
184 my $count = DeleteEmail(
185 userid => $params{userid},
186 sender => $params{sender},
189 # Log out many emails we managed to remove
190 Info("Removed $count emails from $params{sender}");
195 sub Add2Nulllist(%) {
198 # First SetContext to the userid whose null list we are adding to
199 SetContext($params{userid});
202 $params{sequence} = 0;
203 my ($err, $msg) = AddList(%params);
205 # Log that we null listed the sender
206 Info("Added $params{sender} to " . ucfirst $params{userid }. "'s null list");
209 my $count = DeleteEmail(
210 userid => $params{userid},
211 sender => $params{sender},
214 # Log out many emails we managed to remove
215 Info("Removed $count emails from $params{sender}");
220 sub Add2Whitelist(%) {
223 # Add2Whitelist will add an entry to the whitelist
224 # First SetContext to the userid whose white list we are adding to
225 SetContext($params{userid});
228 $params{sequence} = 0;
230 my ($err, $msg) = AddList(%params);
232 return -$err, $msg if $err;
234 # Log that we registered a user
236 userid => $params{userid},
237 type => 'registered',
238 sender => $params{sender},
239 message => 'Registered new sender',
242 # Check to see if there are any old messages to deliver
243 ($err, $msg) = $db->find('email', "sender = '$params{sender}'", ['userid', 'sender', 'data']);
245 return ($err, $msg) if $err;
251 while (my $rec = $db->getnext) {
252 last unless $rec->{userid};
254 $status = Whitelist($rec->{sender}, $rec->{data});
261 # Return if we has a problem delivering email
262 return -1, 'Problem delivering some email' if $status;
264 # Remove delivered messages
266 userid => $params{userid},
267 sender => $params{sender},
270 return $messages, 'Messages delivered';
276 CheckParms(['userid', 'sender', 'subject', 'data'], \%rec);
278 $rec{timestamp} = UnixDatetime2SQLDatetime(scalar(localtime));
280 return $db->add('email', %rec);
286 CheckParms(['userid', 'type', 'sender', 'sequence'], \%rec);
288 croak "Type $rec{type} not valid. Must be one of white, black or null"
289 unless $rec{type} =~ /(white|black|null)/;
291 croak "Sender must contain \@" unless $rec{sender} =~ /\@/;
293 $rec{retention} //= '';
294 $rec{retention} = lc $rec{retention};
296 $rec{hit_count} //= $db->count(
298 "userid = '$rec{userid}' and sender like '%$rec{sender}%'"
301 ($rec{pattern}, $rec{domain}) = split /\@/, delete $rec{sender};
303 $rec{sequence} = GetNextSequenceNo(%rec);
305 $rec{last_hit} //= UnixDatetime2SQLDatetime(scalar (localtime));
307 return $db->add('list', %rec);
313 # Some email senders are coming in mixed case. We don't want that
314 $params{pattern} = $params{pattern} ? lc $params{pattern} : '';
315 $params{domain} = $params{domain} ? lc $params{domain} : '';
317 $params{timestamp} = UnixDatetime2SQLDatetime(scalar(localtime));
319 return $db->add('log', %params);
325 CheckParms(['userid', 'name', 'email', 'password'], \%rec);
327 return 1 if UserExists($rec{userid});
329 return $db->add('user', %rec);
332 sub AddUserOptions(%) {
335 croak('Userid is required') unless $rec{userid};
336 croak('No options to add') unless $rec{options};
338 return (1, "User doesn't exists") unless UserExist($rec{userid});
340 my %useropts = delete $rec{userid};
341 my %opts = delete $rec{options};
345 for my $key (%opts) {
346 $useropts{name} = $_;
347 $useropts{value} = $opts{$_};
349 ($err, $msg) = $db->add('useropts', %useropts);
354 return ($err, $msg) if $err;
359 # Blacklist will send a message back to the $sender telling them that
360 # they've been blacklisted. Currently we save a copy of the message.
361 # In the future we should just disregard the message.
364 # Check to see if this sender has already emailed us.
365 my $msg_count = $db->count('email', "userid='$rec{userid}' and sender like '%$rec{sender}%'");
367 if ($msg_count < 5) {
369 my @spammsg = split "\n", $rec{data};
372 userid => $rec{userid},
373 sender => $rec{sender},
374 subject => 'Your email has been discarded by MAPS',
375 msgfile => "$mapsbase/blacklist.html",
382 sender => $rec{sender},
383 message => 'Sent blacklist reply',
389 sender => $rec{sender},
390 message => 'Mail loop encountered',
394 $rec{hit_count}++ if $rec{sequence};
399 sequence => $rec{sequence},
400 hit_count => $rec{hit_count},
406 sub CheckEmail(;$$) {
407 my ($username, $domain) = @_;
409 return lc "$username\@$domain" if $username and $domain;
411 # Check to see if a full email address in either $username or $domain
413 if ($username =~ /(.*)\@(.*)/) {
416 return lc "$username\@";
419 if ($domain =~ /(.*)\@(.*)/) {
427 sub CheckOnList2 ($$;$) {
428 # CheckOnList will check to see if the $sender is on the list. Return 1 if
430 my ($listtype, $sender, $update) = @_;
434 my ($status, $rule, $sequence);
437 my $condition = "userid='$userid' and type='$listtype'";
439 my ($err, $errmsg) = $db->find($table, $condition, '*', 'order by sequence');
441 my ($email_on_file, $rec);
443 while ($rec = $db->getnext) {
444 unless ($rec->{domain}) {
445 $email_on_file = $rec->{pattern};
447 unless ($rec->{pattern}) {
448 $email_on_file = '@' . $rec->{domain};
450 $email_on_file = $rec->{pattern} . '@' . $rec->{domain};
454 # Escape some special characters
455 $email_on_file =~ s/\@/\\@/;
456 $email_on_file =~ s/^\*/.\*/;
458 # We want to terminate the search string with a "$" iff there's an
459 # "@" in there. This is because some "email_on_file" may have no
460 # domain (e.g. "mailer-daemon" with no domain). In that case we
461 # don't want to terminate the search string with a "$" rather we
462 # wish to terminate it with an "@". But in the case of say
463 # "@ti.com" if we don't terminate the search string with "$" then
464 # "@ti.com" would also match "@tixcom.com"!
465 my $search_for = $email_on_file =~ /\@/
467 : !defined $rec->{domain}
470 if ($sender and $sender =~ /$search_for/i) {
473 $rec->{hit_count} //= 0;
478 sequence => $rec->{sequence},
479 hit_count => $rec->{hit_count} + 1,
486 return ($status, $rec);
489 sub CheckOnList ($$;$) {
490 # CheckOnList will check to see if the $sender is on the list. Return 1 if
492 my ($listtype, $sender, $update) = @_;
497 my ($rule, $sequence);
500 my $condition = "userid='$userid' and type='$listtype'";
502 my ($err, $errmsg) = $db->find($table, $condition, '*', 'order by sequence');
504 my ($email_on_file, $rec);
506 while ($rec = $db->getnext) {
507 unless ($rec->{domain}) {
508 $email_on_file = $rec->{pattern};
510 unless ($rec->{pattern}) {
511 $email_on_file = '@' . $rec->{domain};
513 $email_on_file = $rec->{pattern} . '@' . $rec->{domain};
517 # Escape some special characters
518 $email_on_file =~ s/\@/\\@/;
519 $email_on_file =~ s/^\*/.\*/;
521 # We want to terminate the search string with a "$" iff there's an
522 # "@" in there. This is because some "email_on_file" may have no
523 # domain (e.g. "mailer-daemon" with no domain). In that case we
524 # don't want to terminate the search string with a "$" rather we
525 # wish to terminate it with an "@". But in the case of say
526 # "@ti.com" if we don't terminate the search string with "$" then
527 # "@ti.com" would also match "@tixcom.com"!
528 my $search_for = $email_on_file =~ /\@/
530 : !defined $rec->{domain}
533 if ($sender and $sender =~ /$search_for/i) {
534 my $comment = $rec->{comment} ? " - $rec->{comment}" : '';
536 $rule = "Matching rule: ($listtype:$rec->{sequence}) \"$email_on_file$comment\"";
537 $rule .= " - $rec->{comment}" if $rec->{comment};
540 $rec->{hit_count} //= 0;
545 sequence => $rec->{sequence},
546 hit_count => $rec->{hit_count} + 1,
553 return ($status, $rule, $rec->{sequence}, $rec->{hit_count});
556 sub CleanEmail($;$) {
557 my ($timestamp, $dryrun) = @_;
559 return _cleanTables 'email', $timestamp, $dryrun;
563 my ($timestamp, $dryrun) = @_;
565 return _cleanTables('log', $timestamp, $dryrun);
571 CheckParms(['userid', 'type'], \%params);
573 my $dryrunstr = $params{dryrun} ? '(dryrun)' : '';
576 my $condition = "userid='$params{userid}' and type='$params{type}'";
580 # First let's go through the list to see if we have an domain level entry
581 # (e.g. @spammer.com) and also individual entries (baddude@spammer.com) then
582 # we don't really need any of the individual entries since the domain block
584 $db->find($table, $condition, ['domain'], ' and pattern is null');
586 while (my $domains = $db->getnext) {
587 for my $recs ($db->get($table, $condition, ['sequence', 'pattern', 'domain'],
588 " and domain='$domains->{domain}' and pattern is not null")) {
589 if (@$recs and not $params{dryrun}) {
590 for my $rec (@$recs) {
592 userid => $params{userid},
593 type => $params{type},
594 sequence => $rec->{sequence},
597 $params{log}->msg("Deleted $params{userid}:$params{type}:$rec->{sequence} "
598 . "$rec->{pattern}\@$rec->{domain} $dryrunstr")
605 $params{log}->msg("The domain $domains->{domain} has the following subrecords");
607 for my $rec (@$recs) {
608 $params{log}->msg("$rec->{pattern}\@$rec->{domain}");
615 $condition = "userid='$params{userid}' and type='$params{type}' and retention is not null";
617 # First see if anything needs to be deleted
618 ($count, $msg) = $db->count($table, $condition);
620 return 0 unless $count;
624 my ($err, $errmsg) = $db->find($table, $condition);
626 croak "Unable to find $params{type} entries for $condition - $errmsg" if $err;
628 my $todaysDate = Today2SQLDatetime;
630 while (my $rec = $db->getnext) {
631 my $days = _retention2Days($rec->{retention});
633 my $agedDate = SubtractDays($todaysDate, $days);
635 # If last_hit < retentiondays then delete
636 if (Compare($rec->{last_hit}, $agedDate) == -1) {
637 unless ($params{dryrun}) {
639 userid => $params{userid},
640 type => $params{type},
641 sequence => $rec->{sequence},
645 $rec->{pattern} //= '';
646 $rec->{domain} //= '';
648 $params{log}->msg("Deleted $rec->{userid}:$params{type}:$rec->{sequence} "
649 . "$rec->{pattern}\@$rec->{domain} $dryrunstr");
650 $params{log}->dbug("last hit = $rec->{last_hit} < agedDate = $agedDate");
656 $params{log}->dbug("$rec->{userid}:$params{type}:$rec->{sequence}: nodelete $dryrunstr "
657 . "last hit = $rec->{last_hit} >= agedDate = $agedDate")
663 userid => $params{userid},
664 type => $params{type},
665 ) if $count && !$params{dryrun};
673 CheckParms(['userid'], \%params);
676 my $condition = "userid='$params{userid}'";
677 $condition .= " and $params{additional}" if $params{additional};
679 return $db->count($table, $condition);
685 CheckParms(['userid', 'type'], \%params);
688 my $condition = "userid='$params{userid}' and type='$params{type}'";
690 return $db->count($table, $condition);
696 CheckParms(['userid'], \%params);
698 my ($additional_condition) = delete $params{additional} || '';
700 my $condition = "userid='$userid'";
701 $condition .= " and $additional_condition" if $additional_condition;
703 return $db->count('log', $condition);
706 sub CountLogDistinct(%) {
709 CheckParms(['userid', 'column'], \%params);
711 my ($additional_condition) = delete $params{additional} || '';
713 my $condition = "userid='$userid'";
714 $condition .= " and $additional_condition" if $additional_condition;
716 return $db->count_distinct('log', $params{column}, $condition);
720 my ($password, $userid) = @_;
722 return $db->decode($password, $userid);
730 CheckParms(['userid', 'sender'], \%rec);
732 my ($username, $domain) = split /@/, $rec{sender};
736 $condition = "userid = '$rec{userid}' and sender = '$rec{sender}'";
738 $condition = "userid = '$rec{userid}' and sender like '%\@$domain'";
741 return $db->delete($table, $condition);
747 CheckParms(['userid', 'type', 'sequence'], \%rec);
749 my $condition = "userid = '$rec{userid}' and "
750 . "type = '$rec{type}' and "
751 . "sequence = $rec{sequence}";
753 return $db->delete('list', $condition);
757 my ($password, $userid) = @_;
759 return $db->encode($password, $userid);
765 CheckParms(['userid'], \%params);
768 my $condition = "userid='$params{userid}'";
769 $condition .= " and sender='$params{sender}'" if $params{sender};
770 $condition .= " and timestamp='$params{timestamp}'" if $params{timestamp};
772 return $db->find($table, $condition);
778 my ($type, $sender) = @_;
780 CheckParms(['userid', 'type'], \%params);
783 my $condition = "userid='$params{userid}' and type='$params{type}'";
785 if ($params{sender}) {
786 my ($username, $domain) = split /\@/, $params{sender};
788 # Split will return '' if either username or domain is missing. This messes
789 # up SQL's find as '' ~= NULL. Therefore we only specify username or domain
791 $condition .= " and pattern='$username'" if $username;
792 $condition .= " and domain='$domain'" if $domain;
795 return $db->find($table, $condition);
802 my $end_at = CountLog(
807 $start_at = $end_at - abs ($how_many);
808 $start_at = 0 if ($start_at < 0);
812 my $condition = "userid='$userid'";
813 my $additional = "order by timestamp limit $start_at, $end_at";
815 return $db->find($table, $condition, '*', $additional);
824 $condition = "userid='$userid'" if $params{userid};
826 return $db->find($table, $condition, $params{fields});
830 return $db->find('user', '', ['userid']);
849 sub GetNextSequenceNo(%) {
852 CheckParms(['userid', 'type'], \%rec);
855 my $condition = "userid='$rec{userid}' and type='$rec{type}'";
857 my $count = $db->count('list', $condition);
860 } # GetNextSequenceNo
869 return %{$db->getone('user', "userid='$userid'", ['name', 'email'])};
872 sub GetUserOptions($) {
875 my $table = 'useropts';
876 my $condition = "userid='$userid'";
878 $db->find($table, $condition);
882 while (my $rec = $db->getnext) {
883 $useropts{$rec->{name}} = $rec->{value};
890 my ($userid, $password) = @_;
892 $password = Encrypt($password, $userid);
894 # Check if user exists
895 my $dbpassword = UserExists($userid);
897 # Return -1 if user doesn't exist
898 return -1 unless $dbpassword;
900 # Return -2 if password does not match
901 if ($password eq $dbpassword) {
910 # Nulllist will simply discard the message.
911 my ($sender, $sequence, $hit_count) = @_;
916 sequence => $sequence,
917 hit_count => ++$hit_count,
925 message => 'Discarded message'
931 sub OnBlacklist($;$) {
932 my ($sender, $update) = @_;
934 return CheckOnList2('black', $sender, $update);
937 sub OnNulllist($;$) {
938 my ($sender, $update) = @_;
940 return CheckOnList2('null', $sender, $update);
943 sub OnWhitelist($;$$) {
944 my ($sender, $userid, $update) = @_;
946 SetContext($userid) if $userid;
948 return CheckOnList2('white', $sender, $update);
952 my @tables = qw(email list log user useropts);
954 my ($err, $msg) = $db->lock('read', \@tables);
956 croak "Unable to lock table - $msg" if $err;
958 ($err, $msg) = $db->check(\@tables);
960 croak 'Unable to check tables ' . $msg if $err;
962 ($err, $msg) = $db->optimize(\@tables);
964 croak 'Unable to optimize tables ' . $msg if $err;
966 return $db->unlock();
970 # Reads an email message file from $input. Returns sender, subject,
971 # date and data, which is a copy of the entire message.
975 my $sender_long = '';
976 my $envelope_sender = '';
982 # Find first message's "From " line indicating start of message
988 # If we hit eof here then the message was garbled. Return indication of this
990 $data = "Garbled message - unable to find From line";
991 return $sender, $sender_long, $reply_to, $subject, $data;
995 $envelope_sender = $1;
996 $sender_long = $envelope_sender;
999 push @data, $_ if /^From /;
1005 # Blank line indicates start of message body
1006 last if ($_ eq "" || $_ eq "\r");
1008 # Extract sender's address
1010 $_ = substr ($_, 6);
1014 if (/<(\S*)@(\S*)>/) {
1015 $sender = lc ("$1\@$2");
1016 } elsif (/(\S*)@(\S*)\ /) {
1017 $sender = lc ("$1\@$2");
1018 } elsif (/(\S*)@(\S*)/) {
1019 $sender = lc ("$1\@$2");
1021 } elsif (/^subject: .*/i) {
1022 $subject = substr ($_, 9);
1023 } elsif (/^reply-to: .*/i) {
1024 $_ = substr ($_, 10);
1025 if (/<(\S*)@(\S*)>/) {
1026 $reply_to = lc ("$1\@$2");
1027 } elsif (/(\S*)@(\S*)\ /) {
1028 $reply_to = lc ("$1\@$2");
1029 } elsif (/(\S*)@(\S*)/) {
1030 $reply_to = lc ("$1\@$2");
1043 # Set file pointer back by length of the line just read
1044 seek ($input, -length () - 1, 1) if !eof $input;
1046 # Sanitize email addresses
1047 $envelope_sender =~ s/\<//g;
1048 $envelope_sender =~ s/\>//g;
1049 $envelope_sender =~ s/\"//g;
1050 $envelope_sender =~ s/\'//g;
1055 $reply_to =~ s/\<//g;
1056 $reply_to =~ s/\>//g;
1057 $reply_to =~ s/\"//g;
1058 $reply_to =~ s/\'//g;
1060 # Determine best addresses
1061 $sender = $envelope_sender if $sender eq "";
1062 $reply_to = $sender if $reply_to eq "";
1064 return $sender, $sender_long, $reply_to, $subject, join "\n", @data;
1070 CheckParms(['userid', 'type', 'sequence', ], \%rec);
1072 my $current_date = UnixDatetime2SQLDatetime(scalar(localtime));
1075 my $condition = "userid='rec{userid} and type=$rec{type} and sequence='$rec{sequence}";
1079 condition => $condition,
1084 sub ResequenceList(%) {
1087 CheckParms(['userid', 'type'], \%params);
1090 return 1 unless $params{type} =~ /(white|black|null)/;
1091 return 2 unless UserExists($params{userid});
1094 my $condition = "userid='$params{userid}' and type ='$params{type}'";
1097 $db->lock('write', $table);
1099 # Get all records for $userid and $type
1100 my $listrecs = $db->get($table, $condition,'*', 'order by hit_count desc');
1102 # Delete all of the list entries for this $userid and $type
1103 my ($count, $msg) = $db->delete($table, $condition);
1105 # Now re-add list entries renumbering them
1109 $_->{sequence} = $sequence++;
1111 my ($err, $msg) = $db->add($table, %$_);
1124 CheckParms(['userid', 'type'], \%params);
1126 my $start_at = delete $params{start_at} || 0;
1127 my $lines = delete $params{lines} || 10;
1130 my $condition = "userid='$params{userid}' and type='$params{type}'";
1131 my $additional = "order by sequence limit $start_at, $lines";
1133 return $db->get($table, $condition, '*', $additional);
1139 # ReturnMsg will send back to the $sender the register message.
1140 # Messages are saved to be delivered when the $sender registers.
1142 # Added reply_to. Previously we passed reply_to into here as sender. This
1143 # caused a problem in that we were filtering as per sender but logging it
1144 # as reply_to. We only need reply_to for SendMsg so as to honor reply_to
1145 # so we now pass in both sender and reply_to
1147 CheckParms(['userid', 'sender', 'reply_to', 'subject', 'data'], \%params);
1149 #my ($sender, $reply_to, $subject, $data) = @_;
1151 # Check to see if this sender has already emailed us.
1152 my $msg_count = $db->count('email', "userid='$userid' and sender like '%$params{sender}%'");
1154 if ($msg_count < 5) {
1155 # Return register message
1157 userid => $params{userid},
1158 sender => $params{reply_to},
1159 subject => 'Your email has been returned by MAPS',
1160 msgfile => "$mapsbase/register.html",
1161 data => $params{data},
1162 ) if $msg_count == 0;
1165 userid => $params{userid},
1167 sender => $params{sender},
1168 message => 'Sent register reply',
1172 SaveMsg($params{sender}, $params{subject}, $params{data});
1174 Add2Nulllist($params{sender}, GetContext, "Auto Null List - Mail loop");
1177 userid => $params{userid},
1179 sender => $params{sender},
1180 message => 'Mail loop encountered',
1187 sub ReturnMessages(%) {
1190 CheckParms(['userid', 'sender'], \%params);
1192 my $table = 'email';
1193 my $condition = "userid='$params{userid}' and sender='$params{sender}'";
1194 my $fields = ['subject', 'timestamp'];
1195 my $additional = 'group by timestamp desc';
1197 return $db->get($table, $condition, $fields, $additional);
1200 sub ReturnSenders(%) {
1202 # This subroutine returns an array of senders in reverse chronological
1203 # order based on time timestamp from the log table of when we returned
1204 # their message. The complication here is that a single sender may
1205 # send multiple times in a single day. So if spammer@foo.com sends
1206 # spam @ 1 second after midnight and then again at 2 Pm there will be
1207 # at least two records in the log table saying that we returned his
1208 # email. Getting records sorted by timestamp desc will have
1209 # spammer@foo.com listed twice. But we want him listed only once, as
1210 # the first entry in the returned array. Plus we may be called
1211 # repeatedly with different $start_at's. Therefore we need to process
1212 # the whole list of returns for today, eliminate duplicate entries for
1213 # a single sender then slice the resulting array.
1214 CheckParms(['userid', 'type', 'lines'], \%params);
1217 my $condition = "userid='$params{userid}' and type='$params{type}'";
1218 my $additional = 'order by timestamp desc';
1220 $params{start_at} ||= 0;
1222 if ($params{date}) {
1223 $condition .= "and timestamp > '$params{date} 00:00:00' and "
1224 . "timestamp < '$params{date} 23:59:59'";
1227 $db->find($table, $condition, '*', $additional);
1229 # Watch the distinction between senders (plural) and sender (singular)
1232 # Run through the results and add to %senders by sender key. This
1233 # results in a hash that has the sender in it and the first
1234 # timestamp value. Since we already sorted timestamp desc by the
1235 # above select statement, and we've narrowed it down to only log
1236 # message that occurred for the given $date, we will have a hash
1237 # containing 1 sender and the latest timestamp for the day.
1238 while (my $rec = $db->getnext) {
1239 $senders{$rec->{sender}} = $rec->{timestamp}
1240 unless $senders{$rec->{sender}};
1243 my (@unsorted, @senders);
1245 # Here we have a hash in %senders that has email address and timestamp. In the
1246 # past we would merely create a reverse hash by timestamp and sort that. The
1247 # The problem is that it is possible for two emails to come in with the same
1248 # timestamp. By reversing the hash we clobber any row that has a dumplicte
1249 # timestamp. But we want to sort on timestamp. So first we convers this hash
1250 # to an array of hashes and then we can sort by timestamp later.
1251 while (my ($key, $value) = each %senders) {
1254 timestamp => $value,
1258 push @senders, $_->{sender} for sort { $b->{timestamp} cmp $a->{timestamp}} @unsorted;
1260 # Finally slice for the given range
1261 my $end_at = $params{start_at} + ($params{lines} - 1);
1263 $end_at = (@senders) - 1 if $end_at >= @senders;
1265 return (@senders) [$params{start_at} .. $end_at];
1269 my ($sender, $subject, $data) = @_;
1274 subject => $subject,
1281 sub SearchEmails(%) {
1284 CheckParms(['userid', 'search'], \%params);
1286 my $table = 'email';
1287 my $fields = ['sender', 'subject', 'timestamp'];
1288 my $condition = "userid='$params{userid}' and (sender like '\%$params{search}\%' "
1289 . "or subject like '\%$params{search}\%')";
1290 my $additional = 'order by timestamp desc';
1292 my ($err, $msg) = $db->find($table, $condition, $fields, $additional);
1296 while (my $rec = $db->getnext) {
1304 # SendMsg will send the message contained in $msgfile.
1307 #my ($sender, $subject, $msgfile, $userid, @spammsg) = @_;
1311 # Open return message template file
1312 open my $return_msg_file, '<', $params{msgfile}
1313 or die "Unable to open return msg file ($params{msgfile}): $!\n";
1315 # Read return message template file and print it to $msg_body
1316 while (<$return_msg_file>) {
1319 s/\$userid/$userid/;
1323 s/\$sender/$params{sender}/;
1329 close $return_msg_file;
1331 # Create the message, and set up the mail headers:
1332 my $msg = MIME::Entity->build(
1333 From => "MAPS\@DeFaria.com",
1334 To => $params{sender},
1335 Subject => $params{subject},
1336 Type => "text/html",
1340 # Need to obtain the spam message here...
1341 my @spammsg = split "\n", $params{data};
1345 Disposition => "attachment",
1350 open my $mail, '|-', '/usr/lib/sendmail -t -oi -oem'
1351 or croak "SendMsg: Unable to open pipe to sendmail $!";
1353 $msg->print(\*$mail);
1363 if (UserExists($to_user)) {
1366 return GetUserOptions $userid;
1375 my $total_space = 0;
1376 my $table = 'email';
1377 my $condition = "userid='$userid'";
1379 $db->find($table, $condition);
1381 while (my $rec = $db->getnext) {
1383 length($rec->{userid}) +
1384 length($rec->{sender}) +
1385 length($rec->{subject}) +
1386 length($rec->{timestamp}) +
1387 length($rec->{data});
1390 return $total_space;
1396 CheckParms(['userid', 'type', 'sequence'], \%rec);
1399 my $condition = "userid = '$rec{userid}' and type = '$rec{type}' and sequence = $rec{sequence}";
1401 if ($rec{pattern} =~ /\@/ && !$rec{domain}) {
1402 ($rec{pattern}, $rec{domain}) = split /\@/, $rec{pattern};
1403 } elsif (!$rec{pattern} && $rec{domain} =~ /\@/) {
1404 ($rec{pattern}, $rec{domain}) = split /\@/, $rec{domain};
1405 } elsif (!$rec{pattern} && !$rec{domain}) {
1406 return "Must specify either Username or Domain";
1409 $rec{pattern} //= 'null';
1410 $rec{domain} //= 'null';
1411 $rec{comment} //= 'null';
1413 if ($rec{retention}) {
1414 $rec{retention} = lc $rec{retention};
1417 return $db->update($table, $condition, %rec);
1423 CheckParms(['userid', 'name', 'email'], \%rec);
1425 return 1 unless UserExists($rec{userid});
1428 my $condition = "userid='$rec{userid}'";
1430 return $db->update($table, $condition, %rec);
1433 sub UpdateUserOptions ($@) {
1434 my ($userid, %options) = @_;
1436 return unless UserExists($userid);
1438 my $table = 'useropts';
1439 my $condition = "userid='$userid' and name=";
1441 $db->update($table, "$condition'$_'", (name=>$_, value=>$options{$_})) for (keys %options);
1444 } # UpdateUserOptions
1449 return 0 unless $userid;
1452 my $condition = "userid='$userid'";
1454 my $rec = $db->get($table, $condition);
1456 return 0 if scalar(@$rec) == 0;
1458 return $rec->[0]{password};
1461 sub Whitelist ($$;$$) {
1462 # Whitelist will deliver the message.
1463 my ($sender, $data, $sequence, $hit_count) = @_;
1465 my $userid = GetContext;
1467 # Dump message into a file
1468 open my $message, '>', "/tmp/MAPSMessage.$$"
1469 or Error("Unable to open message file (/tmp/MAPSMessage.$$): $!\n"), return -1;
1471 print $message $data;
1475 # Now call MAPSDeliver
1476 my $status = system "$FindBin::Bin/MAPSDeliver $userid /tmp/MAPSMessage.$$";
1478 unlink "/tmp/MAPSMessage.$$";
1483 type => 'whitelist',
1485 message => 'Delivered message',
1488 Error("Unable to deliver message - is MAPSDeliver setgid? - $!");
1491 $hit_count++ if $sequence;
1496 sequence => $sequence,
1497 hit_count => $hit_count,