Form: version nicht mehr in $::form cachen
[kivitendo-erp.git] / SL / Mailer.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21 # MA 02110-1335, USA.
22 #======================================================================
23
24 package Mailer;
25
26 use Email::Address;
27 use Email::MIME::Creator;
28 use File::MimeInfo::Magic;
29 use File::Slurp;
30 use List::UtilsBy qw(bundle_by);
31
32 use SL::Common;
33 use SL::DB::EmailJournal;
34 use SL::DB::EmailJournalAttachment;
35 use SL::DB::Employee;
36 use SL::Template;
37 use SL::Version;
38
39 use strict;
40
41 my $num_sent = 0;
42
43 my %mail_delivery_modules = (
44   sendmail => 'SL::Mailer::Sendmail',
45   smtp     => 'SL::Mailer::SMTP',
46 );
47
48 sub new {
49   my ($type, %params) = @_;
50   my $self = { %params };
51
52   bless $self, $type;
53 }
54
55 sub _create_driver {
56   my ($self) = @_;
57
58   my %params = (
59     mailer   => $self,
60     form     => $::form,
61     myconfig => \%::myconfig,
62   );
63
64   my $module = $mail_delivery_modules{ $::lx_office_conf{mail_delivery}->{method} };
65   eval "require $module" or return undef;
66
67   return $module->new(%params);
68 }
69
70 sub _cleanup_addresses {
71   my ($self) = @_;
72
73   foreach my $item (qw(to cc bcc)) {
74     next unless $self->{$item};
75
76     $self->{$item} =~ s/\&lt;/</g;
77     $self->{$item} =~ s/\$<\$/</g;
78     $self->{$item} =~ s/\&gt;/>/g;
79     $self->{$item} =~ s/\$>\$/>/g;
80   }
81 }
82
83 sub _create_message_id {
84   my ($self) = @_;
85
86   $num_sent  +=  1;
87   my $domain  =  $self->{from};
88   $domain     =~ s/.*\@//;
89   $domain     =~ s/>.*//;
90
91   return  "kivitendo-" . SL::Version->get_version . "-" . time() . "-${$}-${num_sent}\@$domain";
92 }
93
94 sub _create_address_headers {
95   my ($self) = @_;
96
97   # $self->{addresses} collects the recipients for use in e.g. the
98   # SMTP 'RCPT TO:' envelope command. $self->{headers} collects the
99   # headers that make up the actual email. 'BCC' should not be
100   # included there for certain transportation methods (SMTP).
101
102   $self->{addresses} = {};
103
104   foreach my $item (qw(from to cc bcc)) {
105     $self->{addresses}->{$item} = [];
106     next if !$self->{$item};
107
108     my @header_addresses;
109
110     foreach my $addr_obj (Email::Address->parse($self->{$item})) {
111       push @{ $self->{addresses}->{$item} }, $addr_obj->address;
112       next if $self->{driver}->keep_from_header($item);
113
114       my $phrase = $addr_obj->phrase();
115       if ($phrase) {
116         $phrase =~ s/^\"//;
117         $phrase =~ s/\"$//;
118         $addr_obj->phrase($phrase);
119       }
120
121       push @header_addresses, $addr_obj->format;
122     }
123
124     push @{ $self->{headers} }, ( ucfirst($item) => join(', ', @header_addresses) ) if @header_addresses;
125   }
126 }
127
128 sub _create_attachment_part {
129   my ($self, $attachment) = @_;
130
131   my %attributes = (
132     disposition  => 'attachment',
133     encoding     => 'base64',
134   );
135
136   my $attachment_content;
137   my $file_id       = 0;
138   my $email_journal = $::instance_conf->get_email_journal;
139
140   $::lxdebug->message(LXDebug->DEBUG2(), "mail5 att=" . $attachment . " email_journal=" . $email_journal . " id=" . $attachment->{id});
141
142   if (ref($attachment) eq "HASH") {
143     $attributes{filename}     = $attachment->{name};
144     $file_id                  = $attachment->{id}   || '0';
145     $attributes{content_type} = $attachment->{type} || 'application/pdf';
146     $attachment_content       = $attachment->{content};
147     $attachment_content       = eval { read_file($attachment->{path}) } if !$attachment_content;
148
149   } else {
150     $attributes{filename} =  $attachment;
151     $attributes{filename} =~ s:.*\Q$self->{fileid}\E:: if $self->{fileid};
152     $attributes{filename} =~ s:.*/::g;
153
154     my $application             = ($attachment =~ /(^\w+$)|\.(html|text|txt|sql)$/) ? 'text' : 'application';
155     $attributes{content_type}   = File::MimeInfo::Magic::magic($attachment);
156     $attributes{content_type} ||= "${application}/$self->{format}" if $self->{format};
157     $attributes{content_type} ||= 'application/octet-stream';
158     $attachment_content         = eval { read_file($attachment) };
159   }
160
161   return undef if $email_journal > 1 && !defined $attachment_content;
162
163   $attachment_content ||= ' ';
164   $attributes{charset}  = $self->{charset} if $self->{charset} && ($attributes{content_type} =~ m{^text/});
165
166   $::lxdebug->message(LXDebug->DEBUG2(), "mail6 mtype=" . $attributes{content_type} . " filename=" . $attributes{filename});
167
168   my $ent;
169   if ( $attributes{content_type} eq 'message/rfc822' ) {
170     $ent = Email::MIME->new($attachment_content);
171     $ent->header_str_set('Content-disposition' => 'attachment; filename='.$attributes{filename});
172   } else {
173     $ent = Email::MIME->create(
174       attributes => \%attributes,
175       body       => $attachment_content,
176     );
177   }
178
179   push @{ $self->{mail_attachments}} , SL::DB::EmailJournalAttachment->new(
180     name      => $attributes{filename},
181     mime_type => $attributes{content_type},
182     content   => ( $email_journal > 1 ? $attachment_content : ' '),
183     file_id   => $file_id,
184   );
185
186   return $ent;
187 }
188
189 sub _create_message {
190   my ($self) = @_;
191
192   my @parts;
193
194   push @{ $self->{headers} }, (Type => "multipart/mixed");
195
196   if ($self->{message}) {
197     push @parts, Email::MIME->create(
198       attributes => {
199         content_type => $self->{contenttype},
200         charset      => $self->{charset},
201         encoding     => 'quoted-printable',
202       },
203       body_str => $self->{message},
204     );
205
206     push @{ $self->{headers} }, (
207       'Content-Type' => qq|$self->{contenttype}; charset="$self->{charset}"|,
208     );
209   }
210
211   push @parts, grep { $_ } map { $self->_create_attachment_part($_) } @{ $self->{attachments} || [] };
212
213   return Email::MIME->create(
214       header_str => $self->{headers},
215       parts      => \@parts,
216   );
217 }
218
219 sub send {
220   my ($self) = @_;
221
222   # Create driver for delivery method (sendmail/SMTP)
223   $self->{driver} = eval { $self->_create_driver };
224   if (!$self->{driver}) {
225     my $error = $@;
226     $self->_store_in_journal('failed', 'driver could not be created; check your configuration & log files');
227     $::lxdebug->message(LXDebug::WARN(), "Mailer error during 'send': $error");
228
229     return $error;
230   }
231
232   # Set defaults & headers
233   $self->{charset}       =  'UTF-8';
234   $self->{contenttype} ||=  "text/plain";
235   $self->{headers}       =  [
236     Subject              => $self->{subject},
237     'Message-ID'         => '<' . $self->_create_message_id . '>',
238     'X-Mailer'           => "kivitendo " . SL::Version->get_version,
239   ];
240   $self->{mail_attachments} = [];
241   $self->{content_by_name}  = $::instance_conf->get_email_journal == 1 && $::instance_conf->get_doc_files;
242
243   my $error;
244   my $ok = eval {
245     # Clean up To/Cc/Bcc address fields
246     $self->_cleanup_addresses;
247     $self->_create_address_headers;
248
249     my $email = $self->_create_message;
250
251     #$::lxdebug->message(0, "message: " . $email->as_string);
252     # return "boom";
253
254     $::lxdebug->message(LXDebug->DEBUG2(), "mail1 from=".$self->{from}." to=".$self->{to});
255     my $from_obj = (Email::Address->parse($self->{from}))[0];
256
257     $self->{driver}->start_mail(from => $from_obj->address, to => [ $self->_all_recipients ]);
258     $self->{driver}->print($email->as_string);
259     $self->{driver}->send;
260
261     1;
262   };
263
264   $error = $@ if !$ok;
265
266   $self->{journalentry} = $self->_store_in_journal;
267
268   return $ok ? '' : ($error || "undefined error");
269 }
270
271 sub _all_recipients {
272   my ($self) = @_;
273   $self->{addresses} ||= {};
274   return map { @{ $self->{addresses}->{$_} || [] } } qw(to cc bcc);
275 }
276
277 sub _store_in_journal {
278   my ($self, $status, $extended_status) = @_;
279
280   my $journal_enable = $::instance_conf->get_email_journal;
281
282   return if $journal_enable == 0;
283
284   $status          //= $self->{driver}->status if $self->{driver};
285   $status          //= 'failed';
286   $extended_status //= $self->{driver}->extended_status if $self->{driver};
287   $extended_status //= 'unknown error';
288
289   my $headers = join "\r\n", (bundle_by { join(': ', @_) } 2, @{ $self->{headers} || [] });
290
291   my $jentry = SL::DB::EmailJournal->new(
292     sender          => SL::DB::Manager::Employee->current,
293     from            => $self->{from}    // '',
294     recipients      => join(', ', $self->_all_recipients),
295     subject         => $self->{subject} // '',
296     headers         => $headers,
297     body            => $self->{message} // '',
298     sent_on         => DateTime->now_local,
299     attachments     => \@{ $self->{mail_attachments} },
300     status          => $status,
301     extended_status => $extended_status,
302   )->save;
303   return $jentry->id;
304 }
305
306 1;