blib/lib/Lemonldap/NG/Portal/Lib/SMTP.pm

filter: Statementstmt 25.1% 44 / 175 Branchbran 1.8% 1 / 54 Conditioncond 0.0% 0 / 29 MC/DCmcdc 0.0% 0 / 16 Subroutinesub 52.0% 13 / 25 Podpod 12.5% 1 / 8 totaltotal 19.2% 59 / 307 CC 45 SCAR 41.9
CC
45
Cov
17%
sendEmail
182.0
send_mail
110.0
translate
72.0
CRAP 65.9
« blib/lib/Lemonldap/NG/Portal/Plugins/BruteForceProtection.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Plugins/FindUser.pm »
1 ##@file
2 # SMTP common functions
3  
4 ##@class
5 # SMTP common functions
6 package Lemonldap::NG::Portal::Lib::SMTP;
7  
8 144 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 144 ▶use Mouse;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 144 ▶use JSON qw(from_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 144 ▶use MIME::Entity;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 144 ▶use Lemonldap::NG::Common::EmailAddress qw(format_email);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 144 ▶use Email::Sender::Simple qw(sendmail);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 144 ▶use Email::Date::Format qw(email_date);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 144 ▶use HTML::FormatText::WithLinks;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 144 ▶use Lemonldap::NG::Common::EmailTransport;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 144 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 144 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 144 our $VERSION = '2.23.3';
21  
22 144 our $transport;
23  
24 # PROPERTIES
25  
26 has random => (
27 is => 'rw',
28 341 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
29 341 return Lemonldap::NG::Common::Crypto::srandom();
30 }
31 144 );
32 has charset => (
33 is => 'rw',
34 lazy => 1,
35 0 ▶ default => sub { return $_[0]->{conf}->{mailCharset} || 'utf-8' }
Subroutine __ANON__: not called CC=2 SCAR=17.9
Condition0%0/2
$_[0]{'conf'}{'mailCharset'} || 'utf-8'
l!l
00
MC/DC0%0/1
$_[0]{'conf'}{'mailCharset'} || 'utf-8'
$_[0]{'conf'}{'mailCharset'}
Truth table0%0/2
A
A= $_[0]{'conf'}{'mailCharset'}
Aresult
11
00
36 144 );
37 has transport => (
38 is => 'rw',
39 lazy => 1,
40 0 ▶ default => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
41 0 ▶ return $transport if $transport;
Branch: 1 branch
BranchTrueFalseTotal
if $Lemonldap::NG::Portal::Lib::SMTP::transport 0 0 0
42 0 my $conf = $_[0]->{conf};
43 0 $transport = Lemonldap::NG::Common::EmailTransport->new($conf);
44 0 return $transport;
45 },
46 144 );
47 has htmlParser => (
48 is => 'ro',
49 lazy => 1,
50 0 ▶ default => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
51 0 return HTML::FormatText::WithLinks->new;
52 },
53 144 );
54  
55 # Refuse to load any mail related plugin if SMTPAuthMech is set but can't be
56 # used: without this check mails would be sent using another mechanism than the
57 # configured one, which is exactly what this parameter tries to avoid
58 355 ▶sub BUILD {
Subroutine BUILD: called CC=2 SCAR=7.1
Pod documented
59 355 my ($self) = @_;
60 my $error =
61 355 Lemonldap::NG::Common::EmailTransport->checkSasl( $self->{conf} );
62 355 ▶ die "$error\n" if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 0 355 355
63 }
64  
65 0 ▶sub loadMailTemplate {
Subroutine loadMailTemplate: not called CC=2 SCAR=17.9
Pod undocumented
66 0 my ( $self, $req, $name, %prm ) = @_;
67  
68 # HTML::Template cache interferes with email translation (#1897)
69 0 ▶ $prm{cache} = 0 unless defined $prm{cache};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $prm{"cache"} 0 0 0
70 0 $prm{params}->{STATIC_PREFIX} = $self->p->staticPrefix;
71 0 $prm{params}->{MAIN_LOGO} = $self->conf->{portalMainLogo};
72  
73 0 return $self->loadTemplate( $req, $name, %prm );
74 }
75  
76 0 ▶sub translate {
Subroutine translate: not called CC=8 SCAR=42.8
Pod undocumented
77 0 my ( $self, $req ) = @_;
78  
79 0 my $lang_code = $self->p->getLanguage($req);
80 0 my $json = $self->conf->{templateDir} . "/common/mail/$lang_code.json";
81 0 ▶ $json = $self->conf->{templateDir} . '/common/mail/en.json'
Branch: 1 branch
BranchTrueFalseTotal
unless -f $json 0 0 0
82 unless ( -f $json );
83 0 ▶ open F, '<', $json
Branch: 1 branch
BranchTrueFalseTotal
open F, "<", $json or die 'Installation error: ' . $! . qq[ ($self->{"conf"}{"templateDir"}/$lang_code.json or $self->{"conf"}{"templateDir"}/common/mail/en.json)] 0 0 0
84 or die 'Installation error: '
85 . $!
86 . " ($self->{conf}->{templateDir}/$lang_code.json or $self->{conf}->{templateDir}/common/mail/en.json)";
87 0 $json = join '', <F>;
88 0 close F;
89 0 my $lang = from_json( $json, { allow_nonref => 1 } );
90 0 my $langOver =
91 from_json( $self->p->getTrOver($req), { allow_nonref => 1 } );
92  
93 0 ▶ if ($langOver) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langOver) 0 0 0
94 0 ▶ for my $k ( keys %{ $langOver->{all} || {} } ) {
Condition0%0/2
$langOver->{'all'} || {}
l!l
00
MC/DC0%0/1
$langOver->{'all'} || {}
$langOver->{'all'}
Truth table0%0/2
A
A= $langOver->{'all'}
Aresult
11
00
95 0 $lang->{$k} = $langOver->{all}->{$k};
96 }
97 0 ▶ for my $k ( keys %{ $langOver->{$lang_code} || {} } ) {
Condition0%0/2
$langOver->{$lang_code} || {}
l!l
00
MC/DC0%0/1
$langOver->{$lang_code} || {}
$langOver->{$lang_code}
Truth table0%0/2
A
A= $langOver->{$lang_code}
Aresult
11
00
98 0 $lang->{$k} = $langOver->{$lang_code}->{$k};
99 }
100 }
101 0 ▶ return sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
102 0 ($_) = @_;
103 0 ▶ $$_ =~ s/\s+trspan="(\w+?)"(.*?)>.*?</"$2>".($lang->{$1}||$1).'<'/gse;
Condition0%0/3
$lang->{$1} || $1
l!l&&r!l&&!r
000
MC/DC0%0/2
$lang->{$1} || $1
$lang->{$1} $1
Truth table0%0/3
A || B
A= $lang->{$1}B= $1
ABresult
1X1
011
000
104 0 ▶ $$_ =~ s/^(\w+)$/$lang->{$1}||$1/es;
Condition0%0/3
$lang->{$1} || $1
l!l&&r!l&&!r
000
MC/DC0%0/2
$lang->{$1} || $1
$lang->{$1} $1
Truth table0%0/3
A || B
A= $lang->{$1}B= $1
ABresult
1X1
011
000
105 0 };
106 }
107  
108 # Generate a complex password based on a regular expression
109 # @param regexp regular expression
110 0 ▶sub gen_password {
Subroutine gen_password: not called CC=1 SCAR=6.9
Pod undocumented
111 0 my ( $self, $regexp ) = @_;
112 my $password = join '',
113 0 sort { int( rand(3) ) - 1 } split //,
114 $self->random->randregex($regexp);
115 0 return $password;
116 }
117  
118 # Send mail (legacy API, using sendEmail is recommended instead)
119 # @param mail recipient address
120 # @param subject mail subject
121 # @param body mail body
122 # @param html optional set content type to HTML
123 # @return boolean result
124 0 ▶sub send_mail {
Subroutine send_mail: not called CC=10 SCAR=47.0
Pod undocumented
125 0 my ( $self, $mail, $subject, $body, $html ) = @_;
126  
127 0 ▶ if ( $mail =~ /^\S+\@\S+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mail =~ /^\S+\@\S+$/) 0 0 0
128 0 $mail = format_email( $mail, $mail );
129 }
130  
131 0 $self->logger->info("send_mail called to send \"$subject\" to $mail");
132  
133 # Encode the body with the given charset
134 0 $body = encode( $self->charset, decode( 'utf-8', $body ) );
135 0 $subject = encode( $self->charset, decode( 'utf-8', $subject ) );
136  
137 # Debug messages
138 0 $self->logger->debug( "SMTP From " . $self->conf->{mailFrom} );
139 0 $self->logger->debug( "SMTP To " . $mail );
140 0 $self->logger->debug( "SMTP Subject " . $subject );
141 0 $self->logger->debug( "SMTP Body " . $body );
142 0 ▶ $self->logger->debug( "SMTP HTML flag " . ( $html ? "on" : "off" ) );
Branch: 1 branch
BranchTrueFalseTotal
$html ? : 0 0 0
143 $self->logger->debug( "SMTP Reply-To " . $self->conf->{mailReplyTo} )
144 0 ▶ if $self->conf->{mailReplyTo};
Branch: 1 branch
BranchTrueFalseTotal
if $self->conf->{"mailReplyTo"} 0 0 0
145  
146 # Encode the subject
147 0 $subject = encode_base64( $subject, '' );
148 0 $subject =~ s/\s//gs;
149 0 $subject = '=?' . $self->charset . "?B?$subject?=";
150  
151 # Detect included images (cid)
152 0 my %cid = ( $body =~ m/"cid:([^:]+):([^"]+)"/g );
153  
154 # Replace cid in body
155 0 $body =~ s/"cid:([^:]+):([^"]+)"/"cid:$1"/g;
156  
157 0 eval {
158  
159 # Create message
160 0 my $message;
161  
162 # HTML case
163 0 ▶ if ($html) {
Branch: 1 branch
BranchTrueFalseTotal
if ($html) { } 0 0 0
164 $message = MIME::Entity->build(
165 From => $self->conf->{mailFrom},
166 To => $mail,
167 (
168 $self->conf->{mailReplyTo}
169 ? ( "Reply-To" => $self->conf->{mailReplyTo} )
170 0 ▶ : ()
Branch: 1 branch
BranchTrueFalseTotal
$self->conf->{'mailReplyTo'} ? : 0 0 0
171 ),
172 Subject => $subject,
173 Type => 'multipart/mixed',
174 Date => email_date,
175 );
176  
177 0 my $alternative =
178 $message->attach( Type => 'multipart/alternative' );
179  
180 # Text message
181 0 $alternative->attach(
182 Type => 'text/plain; charset=' . $self->charset,
183 Data => $self->htmlParser->parse($body),
184 );
185  
186 0 my $related = $alternative->attach( Type => 'multipart/related' );
187  
188 # Attach HTML message
189 0 $related->attach(
190 Type => 'text/html; charset=' . $self->charset,
191 Data => $body,
192 );
193  
194 # Attach included images
195 0 foreach ( keys %cid ) {
196 $related->attach(
197 Type => "image/" . ( $cid{$_} =~ m/\.(\w+)/ )[0],
198 Id => $_,
199 0 Path => $self->_search_attachment( $cid{$_} ),
200 );
201 }
202 }
203  
204 # Plain text case
205 else {
206 $message = MIME::Entity->build(
207 From => $self->conf->{mailFrom},
208 To => $mail,
209 "Reply-To" => $self->conf->{mailReplyTo},
210 0 Subject => $subject,
211 Type => 'TEXT',
212 Data => $body,
213 Type => 'text/plain',
214 Charset => $self->charset,
215 Date => email_date,
216 );
217 }
218  
219 # Send the mail
220 0 ▶ sendmail( $message->stringify,
Branch: 1 branch
BranchTrueFalseTotal
$self->transport ? : 0 0 0
221 ( $self->transport ? { transport => $self->transport } : () ) );
222 };
223 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
224 0 ▶ $self->logger->error( "Send message failed: "
Branch: 1 branch
BranchTrueFalseTotal
$@->isa('Throwable::Error') ? : 0 0 0
225 . ( $@->isa('Throwable::Error') ? $@->message : $@ ) );
226 0 return 0;
227 }
228  
229 0 return 1;
230 }
231  
232 0 ▶sub _search_attachment {
Subroutine _search_attachment: not called CC=2 SCAR=17.9
233 0 my ( $self, $filename ) = @_;
234  
235 my $from_skin =
236 0 $self->p->getSkinTplDir( $self->conf->{portalSkin} ) . "/" . $filename;
237  
238 0 ▶ if ( -e $from_skin ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $from_skin) { } 0 0 0
239 0 $self->logger->debug("found attachment at $from_skin");
240 0 return $from_skin;
241 }
242 else {
243 my $from_bootstrap =
244 0 $self->conf->{templateDir} . "/bootstrap/" . $filename;
245 0 $self->logger->debug("returning attachment at $from_bootstrap");
246 0 return $from_bootstrap;
247 }
248 }
249  
250 ## @method string getMailSession(string user)
251 # Check if a mail session exists
252 # @param user the value of the user key in session
253 # @return the first session id found or nothing if no session
254 0 ▶sub getMailSession {
Subroutine getMailSession: not called CC=5 SCAR=34.0
Pod undocumented
255 0 my ( $self, $user ) = @_;
256  
257 0 ▶ my $moduleOptions = $self->conf->{globalStorageOptions} || {};
Condition0%0/2
$self->conf->{'globalStorageOptions'} || {}
l!l
00
MC/DC0%0/1
$self->conf->{'globalStorageOptions'} || {}
$self->conf->{'globalStorageOptions'}
Truth table0%0/2
A
A= $self->conf->{'globalStorageOptions'}
Aresult
11
00
258 0 $moduleOptions->{backend} = $self->conf->{globalStorage};
259 0 my $module = "Lemonldap::NG::Common::Apache::Session";
260  
261 # Search on mail sessions
262 0 my $sessions = $module->searchOn( $moduleOptions, "user", $user );
263  
264 # Browse found sessions to check if it's a mail session
265 0 foreach my $id ( keys %$sessions ) {
266 0 my $mailSession =
267 $self->p->getApacheSession( $id, kind => "TOKEN", hashStore => 0, );
268 0 ▶ next unless ($mailSession);
Branch: 1 branch
BranchTrueFalseTotal
unless $mailSession 0 0 0
269 0 ▶ return $mailSession if ( $mailSession->data->{_type} =~ /^mail$/ );
Branch: 1 branch
BranchTrueFalseTotal
if $mailSession->data->{"_type"} =~ /^mail$/ 0 0 0
270 }
271  
272 # No mail session found, return empty string
273 0 return "";
274 }
275  
276 ## @method string getRegisterSession(string mail)
277 # Check if a register session exists
278 # @param mail the value of the mail key in session
279 # @return the first session id found or nothing if no session
280 0 ▶sub getRegisterSession {
Subroutine getRegisterSession: not called CC=6 SCAR=37.4
Pod undocumented
281 0 my ( $self, $mail ) = @_;
282  
283 0 ▶ my $moduleOptions = $self->conf->{globalStorageOptions} || {};
Condition0%0/2
$self->conf->{'globalStorageOptions'} || {}
l!l
00
MC/DC0%0/1
$self->conf->{'globalStorageOptions'} || {}
$self->conf->{'globalStorageOptions'}
Truth table0%0/2
A
A= $self->conf->{'globalStorageOptions'}
Aresult
11
00
284 0 $moduleOptions->{backend} = $self->conf->{globalStorage};
285 0 my $module = "Lemonldap::NG::Common::Apache::Session";
286  
287 # Search on register sessions
288 0 my $sessions = $module->searchOn( $moduleOptions, "mail", $mail );
289  
290 # Browse found sessions to check if it's a register session
291 0 foreach my $id ( keys %$sessions ) {
292 0 my $registerSession =
293 $self->p->getApacheSession( $id, kind => "TOKEN", hashStore => 0, );
294 0 ▶ next unless ($registerSession);
Branch: 1 branch
BranchTrueFalseTotal
unless $registerSession 0 0 0
295 return $id
296 if ( $registerSession->data->{_type}
297 0 ▶ and $registerSession->data->{_type} =~ /^register$/ );
Branch: 1 branch
BranchTrueFalseTotal
if $registerSession->data->{"_type"} and $registerSession->data->{"_type"} =~ /^register$/ 0 0 0
Condition0%0/3
$registerSession->data->{"_type"} and $registerSession->data->{"_type"} =~ /^register$/
!ll&&!rl&&r
000
MC/DC0%0/2
$registerSession->data->{"_type"} and $registerSession->data->{"_type"} =~ /^register$/
$registerSession->data->{"_type"} $registerSession->data->{"_type"} =~ /^register$/
Truth table0%0/3
A and B
A= $registerSession->data->{"_type"}B= $registerSession->data->{"_type"} =~ /^register$/
ABresult
0X0
100
111
298 }
299  
300 # No register session found, return empty string
301 0 return "";
302 }
303  
304 ## @method string sendEmail(string mail)
305 # High-level method for sending a templated email
306 # Takes a hash of parameters
307 # @param dest the destination email address
308 # @param subject the plaintext subject, will not be translated
309 # @param subject_trmsg the translation key that will be used as subject
310 # @param body the plaintext body, may contain $variable placeholders
311 # @param body_template the name of the template file to render as body
312 # @param params a hashref of parameters
313 # @return success status as a boolean
314 0 ▶sub sendEmail {
Subroutine sendEmail: not called CC=13 SCAR=52.0
Pod undocumented
315 0 my ( $self, $req, %params ) = @_;
316  
317 0 my $subject_trmsg = $params{subject_trmsg};
318 0 my $subject = $params{subject};
319 0 my $body = $params{body};
320 0 my $body_template = $params{body_template};
321 0 ▶ my %variables = %{ $params{params} || {} };
Condition0%0/2
$params{'params'} || {}
l!l
00
MC/DC0%0/1
$params{'params'} || {}
$params{'params'}
Truth table0%0/2
A
A= $params{'params'}
Aresult
11
00
322 0 my $dest = $params{dest};
323  
324 # Build mail content
325 0 my $tr = $self->translate($req);
326 0 ▶ unless ($subject) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($subject) 0 0 0
327 0 $subject = $subject_trmsg;
328 0 $tr->( \$subject );
329 }
330 0 my $html;
331 0 ▶ if ($body) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body) { } 0 0 0
332  
333 # Replace supplied variables in body, and also handle session variables
334 0 ▶ while ( my ( $k, $v ) = each %variables ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %variables) 0 0 0
335 0 $body =~ s/\$\Q$k\E\b/$v/g;
336 }
337 0 ▶ $body =~ s/\$(\w+)/$req->{sessionInfo}->{$1} || ''/ge;
Condition0%0/2
$req->{'sessionInfo'}{$1} || ''
l!l
00
MC/DC0%0/1
$req->{'sessionInfo'}{$1} || ''
$req->{'sessionInfo'}{$1}
Truth table0%0/2
A
A= $req->{'sessionInfo'}{$1}
Aresult
11
00
338 }
339 else {
340  
341 # Use HTML template
342 0 $body = $self->loadMailTemplate(
343 $req,
344 $body_template,
345 filter => $tr,
346 params => \%variables
347 );
348 0 $html = 1;
349 }
350 0 ▶ if ( $dest && $subject && $body ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dest and $subject and $body) { } 0 0 0
Condition0%0/6
$dest and $subject and $body
!ll&&!rl&&r
000
$dest and $subject
!ll&&!rl&&r
000
MC/DC0%0/3
$dest and $subject and $body
$dest $subject $body
Truth table0%0/4
A and B and C
A= $destB= $subjectC= $body
ABCresult
0XX0
10X0
1100
1111
351 0 ▶ if ( $self->send_mail( $dest, $subject, $body, $html ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->send_mail($dest, $subject, $body, $html)) { } 0 0 0
352 0 $self->auditLog(
353 $req,
354 message => "Email ($body_template) sent "
355 . "to $dest with subject '$subject'",
356 code => "EMAIL_SENT",
357 body_template => $body_template,
358 subject => $subject,
359 subject_trmsg => $subject_trmsg,
360 dest => $dest,
361 );
362 0 return 1;
363 }
364 else {
365 0 return 0;
366 }
367 }
368 else {
369 0 my $message = "Could not send email:";
370 0 ▶ $message .= " missing destination," unless $dest;
Branch: 1 branch
BranchTrueFalseTotal
unless $dest 0 0 0
371 0 ▶ $message .= " missing subject," unless $subject;
Branch: 1 branch
BranchTrueFalseTotal
unless $subject 0 0 0
372 0 ▶ $message .= " missing body," unless $body;
Branch: 1 branch
BranchTrueFalseTotal
unless $body 0 0 0
373 0 chop($message);
374 0 $message .= ".";
375 0 $self->logger->warn($message);
376 0 return 0;
377 }
378 }
379  
380 144 1;
« blib/lib/Lemonldap/NG/Portal/Plugins/BruteForceProtection.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Plugins/FindUser.pm »