#!/usr/bin/perl use strict; use warnings; use Encode; use FindBin; use lib "$FindBin::Bin/lib", "$FindBin::Bin/exlib"; use Getopt::Std; use File::Basename; use Net::POP3; use MIME::Parser; use Mail::Address; use HTTP::Date; use Process::PIDFile; use BlogCMS::Config; use BlogCMS::DB; use BlogCMS::Blog; my $PIDFile = "$FindBin::Bin/var/pop3client.pid"; my $Debug; sub usage { my ($msg) = @_; my $cmd = basename($0); print STDERR "$msg\n\n" if defined $msg; print STDERR <new($server) or die "Can't connect $server ."; my $num = $pop->login($user, $passwd) or die "Login failed."; if ($num == 0) { # $num eq "0E0" # no mail $pop->quit; return 0; } my $msgnums = $pop->list; # hashref of msgnum => size my $users = get_users() or die "Can't get users."; foreach my $msgnum (keys %$msgnums) { $mail_n++; my $msg = $pop->get($msgnum); my $parser = new MIME::Parser; $parser->output_to_core(1); # no output to disk $parser->decode_headers(1); # decode MIME headers my $entity = $parser->parse_data(join("", @$msg)); my $head = $entity->head; my $subject = $head->get("Subject"); if (not defined $subject) {$subject = "";} my $from_addr = ""; if (my $h_from = $head->get("From")) { my ($mail_addr) = Mail::Address->parse($h_from); $from_addr = $mail_addr->address if $mail_addr; } $from_addr =~ m/^ch(\d+)@(.+)$/ or goto NEXT_MAIL; # Skip my $sending_ch = $1; my $send_time = 0; if (my $h_date = $head->get("Date")) { if (!($send_time = str2time($h_date))) { $send_time = 0; } } # Distribute to all users. foreach my $user (@$users) { # 対応送信Ch.に対する設定を行っているユーザのみに配信 next if !lookup_blog($user->{user_id}, $sending_ch); my $mail = {user_id => $user->{user_id}, title => enc_todb($subject), body => enc_todb($entity->stringify_body), from_addr => $from_addr, send_time => $send_time, rcv_time => time, update_time => 0, post_time => 0, }; add_mail($mail) or die "Can't insert mail data to database."; } NEXT_MAIL: $pop->delete($msgnum) if !$Debug; } $pop->quit; # Rotate mail box foreach my $user (@$users) { rotate_mail($user->{user_id}); } return $mail_n; } { my %args; getopts("dh", \%args) or usage; if ($args{h}) {usage} if ($args{d}) {$Debug = 1;} } # start up $SIG{'INT'} = sub {cleanup(); exit 0;}; $SIG{'TERM'} = $SIG{'INT'}; $SIG{'HUP'} = $SIG{'INT'}; if (Process::PIDFile::isRunning($PIDFile)) { logging("pop3client is already running."); exit 1; } Process::PIDFile::Create($PIDFile); eval { my $n = download_mail; print "$n mails received.\n"; logging("pop3client finished. ($n mails received)"); }; if ($@) { my $msg = "pop3client aborted. ($@)"; $msg =~ s/[\r\n]//g; print STDERR $msg, "\n"; logging($msg, "ERR"); cleanup(); exit 1; } cleanup; 0;