#webliberty::Sendmail.pm (2006/03/26)
#Copyright(C) 2002-2006 Knight, All rights reserved.

package webliberty::Sendmail;

use strict;
use Jcode;
use webliberty::Encoder;

### コンストラクタ
sub new {
	my $class = shift;

	my $self = {
		sendmail  => shift,
		send_to   => undef,
		send_from => undef,
		subject   => undef,
		name      => undef,
		message   => undef,
		x_mailer  => undef
	};
	bless $self, $class;

	return $self;
}

### メール送信
sub sendmail {
	my $self = shift;
	my %args = @_;

	$self->{send_to}   = $args{'send_to'};
	$self->{send_from} = $args{'send_from'};
	$self->{subject}   = $args{'subject'};
	$self->{name}      = $args{'name'};
	$self->{message}   = $args{'message'};
	$self->{x_mailer}  = $args{'x_mailer'};

	if (!$self->{send_to}) {
		$self->{send_to} = 'dammy@dammy.com';
	}
	if (!$self->{send_from}) {
		$self->{send_from} = 'dammy@dammy.com';
	}
	if (!$self->{subject}) {
		$self->{subject} = 'No Subject';
	}
	if (!$self->{name}) {
		$self->{name} = 'No Name';
	}
	if (!$self->{message}) {
		$self->{message} = 'No Message';
	}
	if (!$self->{x_mailer}) {
		$self->{x_mailer} = 'Web Liberty';
	}

	foreach ($self->{subject}, $self->{name}, $self->{message}) {
		$_ =~ s/<br \/>/\n/g;
		$_ =~ s/&amp;/&/g;
		$_ =~ s/&lt;/</g;
		$_ =~ s/&gt;/>/g;
		$_ =~ s/&quot;/"/g;
	}

	$self->{subject} = $self->_encode($self->{subject});
	$self->{name}    = $self->_encode($self->{name});

	$self->{message} =~ s/\xEF\xBD\x9E/\a/g;
	my $jcode_ins = new Jcode($self->{message}, 'utf8');
	$self->{message} = $jcode_ins->jis;
	$self->{message} =~ s/\a/\x1B\x24B\x21A\x1B\x28B/g;

	open(MAIL, "| $self->{sendmail} -t") or return(0, "Sendmail Error : $self->{sendmail}");
	print MAIL "X-Mailer: $self->{x_mailer}\n";
	print MAIL "To: $self->{send_to}\n";
	print MAIL "From: \"$self->{name}\" <$self->{send_from}>\n";
	print MAIL "Subject: $self->{subject}\n";
	print MAIL "Content-Transfer-Encoding: 7bit\n";
	print MAIL "Content-Type: text/plain; charset=iso-2022-jp\n\n";
	print MAIL "$self->{message}\n";
	close(MAIL);

	return 1;
}

### エンコードデータ作成
sub _encode {
	my $self = shift;
	my $text = shift;

	$text =~ s/\xEF\xBD\x9E/\a/g;
	my $jcode_ins = new Jcode($text, 'utf8');
	$text = $jcode_ins->jis;
	$text =~ s/\a/\x1B\x24B\x21A\x1B\x28B/g;

	$text =~ s/\x1b\x28\x42/\x1b\x28\x4a/g;

	my $string_ins = new webliberty::Encoder($text);
	$string_ins->base64_encode;

	$text = '=?iso-2022-jp?B?' . $string_ins->get_string . '?=';

	return $text;
}

1;
