Completed
Pull Request — master (#97)
by
unknown
03:19
created

Mail::getErrorHtml()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 16
cts 16
cp 1
rs 9.0856
c 0
b 0
f 0
cc 3
eloc 16
nc 2
nop 1
crap 3
1
<?php
2
namespace phpbu\App\Log;
3
4
use phpbu\App\Exception;
5
use phpbu\App\Event;
6
use phpbu\App\Listener;
7
use phpbu\App\Result;
8
use phpbu\App\Log\MailTemplate as TPL;
9
use phpbu\App\Util\Arr;
10
use phpbu\App\Util\Str;
11
use PHP_Timer;
12
use Swift_Mailer;
13
use Swift_Message;
14
15
/**
16
 * Mail Logger
17
 *
18
 * @package    phpbu
19
 * @subpackage Log
20
 * @author     Sebastian Feldmann <[email protected]>
21
 * @copyright  Sebastian Feldmann <[email protected]>
22
 * @license    https://opensource.org/licenses/MIT The MIT License (MIT)
23
 * @link       http://phpbu.de/
24
 * @since      Class available since Release 1.0.0
25
 */
26
class Mail implements Listener, Logger
27
{
28
    /**
29
     * Mailer instance
30
     *
31
     * @var Swift_Mailer
32
     */
33
    protected $mailer;
34
35
    /**
36
     * Mail subject
37
     *
38
     * @var string
39
     */
40
    protected $subject;
41
42
    /**
43
     * From email address
44
     *
45
     * @var string
46
     */
47
    protected $senderMail;
48
49
    /**
50
     * From name
51
     *
52
     * @var string
53
     */
54
    protected $senderName;
55
56
    /**
57
     * Transport type [mail|smtp|null]
58
     *
59
     * @var string
60
     */
61
    protected $transportType;
62
63
    /**
64
     * List of mail recipients
65
     *
66
     * @var array<string>
67
     */
68
    protected $recipients = [];
69
70
    /**
71
     * Amount of executed backups
72
     *
73
     * @var integer
74
     */
75
    private $numBackups = 0;
76
77
    /**
78
     * Amount of executed checks
79
     *
80
     * @var integer
81
     */
82
    private $numChecks = 0;
83
84
    /**
85
     * Amount of executed Syncs
86
     *
87
     * @var integer
88
     */
89
    private $numSyncs = 0;
90
91
    /**
92
     * Amount of executed Crypts
93
     *
94
     * @var integer
95
     */
96
    private $numCrypts = 0;
97
98
    /**
99
     * Amount of executed Cleanups
100
     *
101
     * @var integer
102
     */
103
    private $numCleanups = 0;
104
105
    /**
106
     * Send mail only if there was an error
107
     *
108
     * @var bool
109
     */
110
    private $sendOnlyOnError = false;
111
112
    /**
113
     * Returns an array of event names this subscriber wants to listen to.
114
     *
115
     * The array keys are event names and the value can be:
116
     *
117
     *  * The method name to call (priority defaults to 0)
118
     *  * An array composed of the method name to call and the priority
119
     *  * An array of arrays composed of the method names to call and respective
120
     *    priorities, or 0 if unset
121
     *
122
     * @return array The event names to listen to
123
     */
124 1
    public static function getSubscribedEvents()
125
    {
126
        return [
127 1
            'phpbu.backup_start'  => 'onBackupStart',
128
            'phpbu.check_start'   => 'onCheckStart',
129
            'phpbu.crypt_start'   => 'onCryptStart',
130
            'phpbu.sync_start'    => 'onSyncStart',
131
            'phpbu.cleanup_start' => 'onCleanupStart',
132
            'phpbu.app_end'       => 'onPhpbuEnd',
133
        ];
134
    }
135
136
    /**
137
     * Setup the Logger.
138
     *
139
     * @see    \phpbu\App\Log\Logger::setup
140
     * @param  array $options
141
     * @throws \phpbu\App\Exception
142
     */
143 12
    public function setup(array $options)
144
    {
145 12
        if (empty($options['recipients'])) {
146 1
            throw new Exception('no recipients given');
147
        }
148 11
        $mails                 = $options['recipients'];
149 11
        $server                = gethostname();
150 11
        $this->sendOnlyOnError = Str::toBoolean(Arr::getValue($options, 'sendOnlyOnError'), false);
151 11
        $this->subject         = Arr::getValue($options, 'subject', 'PHPBU backup report from ' . $server);
152 11
        $this->senderMail      = Arr::getValue($options, 'sender.mail', 'phpbu@' . $server);
153 11
        $this->senderName      = Arr::getValue($options, 'sender.name');
154 11
        $this->transportType   = Arr::getValue($options, 'transport', 'mail');
155 11
        $this->recipients      = array_map('trim', explode(';', $mails));
156
157
        // create transport an mailer
158 11
        $transport    = $this->createTransport($this->transportType, $options);
159 9
        $this->mailer = Swift_Mailer::newInstance($transport);
160 9
    }
161
162
    /**
163
     * Handle the phpbu end event.
164
     *
165
     * @param  \phpbu\App\Event\App\End $event
166
     * @throws \phpbu\App\Exception
167
     */
168 4
    public function onPhpbuEnd(Event\App\End $event)
169
    {
170 4
        $result  = $event->getResult();
171 4
        $allGood = $result->allOk();
172
173 4
        if (!$this->sendOnlyOnError || !$allGood) {
174 4
            $header  = $this->getHeaderHtml();
175 4
            $status  = $this->getStatusHtml($result);
176 4
            $errors  = $this->getErrorHtml($result);
177 4
            $info    = $this->getInfoHtml($result);
178 4
            $footer  = $this->getFooterHtml();
179 4
            $body    = '<html><body '. TPL::getSnippet('sBody') . '>'
180 4
                     . $header
181 4
                     . $status
182 4
                     . $errors
183 4
                     . $info
184 4
                     . $footer
185 4
                     . '</body></html>';
186 4
            $sent    = null;
187
188
            try {
189
                /** @var \Swift_Message $message */
190 4
                $message = Swift_Message::newInstance();
191 4
                $message->setSubject($this->subject)
192 4
                        ->setFrom($this->senderMail, $this->senderName)
193 4
                        ->setTo($this->recipients)
194 4
                        ->setBody($body, 'text/html');
195
196 4
                $sent = $this->mailer->send($message);
197
            } catch (\Exception $e) {
198
                throw new Exception($e->getMessage());
199
            }
200 4
            if (!$sent) {
201
                throw new Exception('mail could not be sent');
202
            }
203
        }
204 4
    }
205
206
    /**
207
     * Backup start event.
208
     *
209
     * @param \phpbu\App\Event\Backup\Start $event
210
     */
211 4
    public function onBackupStart(Event\Backup\Start $event)
212
    {
213 4
        $this->numBackups++;
214 4
    }
215
216
    /**
217
     * Check start event.
218
     *
219
     * @param \phpbu\App\Event\Check\Start $event
220
     */
221 1
    public function onCheckStart(Event\Check\Start $event)
222
    {
223 1
        $this->numChecks++;
224 1
    }
225
226
    /**
227
     * Crypt start event.
228
     *
229
     * @param \phpbu\App\Event\Crypt\Start $event
230
     */
231 1
    public function onCryptStart(Event\Crypt\Start $event)
232
    {
233 1
        $this->numCrypts++;
234 1
    }
235
236
    /**
237
     * Sync start event.
238
     *
239
     * @param \phpbu\App\Event\Sync\Start $event
240
     */
241 1
    public function onSyncStart(Event\Sync\Start $event)
242
    {
243 1
        $this->numSyncs++;
244 1
    }
245
246
    /**
247
     * Cleanup start event.
248
     *
249
     * @param \phpbu\App\Event\Cleanup\Start $event
250
     */
251 1
    public function onCleanupStart(Event\Cleanup\Start $event)
252
    {
253 1
        $this->numCleanups++;
254 1
    }
255
256
    /**
257
     * Create a Swift_Mailer_Transport.
258
     *
259
     * @param  string $type
260
     * @param  array  $options
261
     * @throws \phpbu\App\Exception
262
     * @return \Swift_Transport
263
     */
264 11
    protected function createTransport($type, array $options)
265
    {
266
        switch ($type) {
267
            // null transport, don't send any mails
268 11
            case 'null':
269
                 /* @var $transport \Swift_NullTransport */
270 4
                $transport = \Swift_NullTransport::newInstance();
271 4
                break;
272
273 7
            case 'smtp':
274 2
                $transport = $this->getSmtpTransport($options);
275 1
                break;
276
277 5
            case 'mail':
278 3
            case 'sendmail':
279 4
                $transport = $this->getSendmailTransport($options);
280 4
                break;
281
282
            // UPS! no transport given
283
            default:
284 1
                throw new Exception(sprintf('mail transport not supported: \'%s\'', $type));
285
        }
286 9
        return $transport;
287
    }
288
289
    /**
290
     * Create Swift Smtp Transport.
291
     *
292
     * @param  array $options
293
     * @return \Swift_SmtpTransport
294
     * @throws \phpbu\App\Exception
295
     */
296 2
    protected function getSmtpTransport(array $options)
297
    {
298 2
        if (!isset($options['smtp.host'])) {
299 1
            throw new Exception('option \'smtp.host\' ist missing');
300
        }
301 1
        $host       = $options['smtp.host'];
302 1
        $port       = Arr::getValue($options, 'smtp.port', 25);
303 1
        $username   = Arr::getValue($options, 'smtp.username');
304 1
        $password   = Arr::getValue($options, 'smtp.password');
305 1
        $encryption = Arr::getValue($options, 'smtp.encryption');
306
307
        /* @var $transport \Swift_SmtpTransport */
308 1
        $transport = \Swift_SmtpTransport::newInstance($host, $port);
309
310 1
        if ($username && $password) {
311 1
            $transport->setUsername($username)
312 1
                      ->setPassword($password);
313
        }
314 1
        if ($encryption) {
315 1
            $transport->setEncryption($encryption);
316
        }
317 1
        return $transport;
318
    }
319
320
    /**
321
     * Create a Swift Sendmail Transport.
322
     *
323
     * @param  array $options
324
     * @return \Swift_SendmailTransport
325
     */
326 4
    protected function getSendmailTransport(array $options)
327
    {
328 4
        if (isset($options['sendmail.path'])) {
329 1
            $path    = $options['sendmail.path'];
330 1
            $options = isset($options['sendmail.options']) ? ' ' . $options['sendmail.options'] : '';
331
            /* @var $transport \Swift_SendmailTransport */
332 1
            return \Swift_SendmailTransport::newInstance($path . $options);
333
        }
334 3
        return \Swift_SendmailTransport::newInstance();
335
    }
336
337
    /**
338
     * Return mail header html
339
     *
340
     * @return string
341
     */
342 4
    protected function getHeaderHtml()
343
    {
344 4
        return '<table ' . TPL::getSnippet('sTableContent') . '><tr><td ' . TPL::getSnippet('sTableContentCol') . '>' .
345 4
               '<table ' . TPL::getSnippet('sTableHeader') . '><tr><td>PHPBU - backup report</td></tr></table>';
346
    }
347
348
    /**
349
     * Return mail status html
350
     *
351
     * @param  \phpbu\App\Result $result
352
     * @return string
353
     */
354 4
    protected function getStatusHtml(Result $result)
355
    {
356 4
        if (count($result->getBackups()) === 0) {
357 1
            $color  = TPL::getSnippet('cStatusWARN');
358 1
            $status = 'WARNING';
359 3
        } elseif ($result->allOk()) {
360 1
            $color  = TPL::getSnippet('cStatusOK');
361 1
            $status = 'OK';
362 2
        } elseif ($result->backupOkButSkipsOrFails()) {
363 1
            $color  = TPL::getSnippet('cStatusWARN');
364 1
            $status = 'WARNING';
365
        } else {
366 1
            $color  = TPL::getSnippet('cStatusFAIL');
367 1
            $status = 'FAILURE';
368
        }
369 4
        $info = sprintf(
370 4
            '(%d %s, %d %s, %d %s, %d %s, %d %s)',
371 4
            count($result->getBackups()),
372 4
            Str::appendPluralS('backup', count($result->getBackups())),
373 4
            $this->numChecks,
374 4
            Str::appendPluralS('check', $this->numChecks),
375 4
            $this->numCrypts,
376 4
            Str::appendPluralS('crypt', $this->numCrypts),
377 4
            $this->numSyncs,
378 4
            Str::appendPluralS('sync', $this->numSyncs),
379 4
            $this->numCleanups,
380 4
            Str::appendPluralS('cleanup', $this->numCleanups)
381
        );
382 4
        $html = '<table ' . sprintf(TPL::getSnippet('sTableStatus'), $color) .'>' .
383 4
                 '<tr><td>' .
384 4
                  '<span ' . TPL::getSnippet('sTableStatusText') . '>' . date('Y-m-d H:i') . '</span>' .
385 4
                  '<h1 ' . TPL::getSnippet('sTableStatusHead') . '>' . $status . '</h1>' .
386 4
                  '<span ' . TPL::getSnippet('sTableStatusText') . '>' . $info . '</span>' .
387 4
                 '</td></tr>' .
388 4
                '</table>';
389
390 4
        return $html;
391
    }
392
393
    /**
394
     * Get error information.
395
     *
396
     * @param  \phpbu\App\Result $result
397
     * @return string
398
     */
399 4
    protected function getErrorHtml(Result $result)
400
    {
401 4
        $html   = '';
402 4
        $errors = $result->getErrors();
403 4
        if (count($errors)) {
404 1
            $html .= '<table ' . TPL::getSnippet('sTableError') . '>';
405
            /* @var $e Exception */
406 1
            foreach ($errors as $e) {
407 1
                $html .= '<tr><td ' . TPL::getSnippet('sTableErrorCol') . '>' .
408 1
                    sprintf(
409 1
                        "Exception '%s' with message '%s' in %s:%d",
410 1
                        get_class($e),
411 1
                        $e->getMessage(),
412 1
                        $e->getFile(),
413 1
                        $e->getLine()
414
                    ) .
415 1
                    '</td></tr>';
416
417
            }
418 1
            $html .= '</table>';
419
        }
420 4
        return $html;
421
    }
422
423
    /**
424
     * Return backup html information.
425
     *
426
     * @param  \phpbu\App\Result $result
427
     * @return string
428
     */
429 4
    protected function getInfoHtml(Result $result)
430
    {
431 4
        $html    = '';
432 4
        $backups = $result->getBackups();
433 4
        if (count($backups)) {
434 3
            $html .= '<table ' . TPL::getSnippet('sTableBackup') . '>';
435
            /** @var \phpbu\App\Result\Backup $backup */
436 3
            foreach ($backups as $backup) {
437 3
                if ($backup->allOk()) {
438 1
                    $color  = TPL::getSnippet('cStatusOK');
439 1
                    $status = 'OK';
440 2
                } elseif($backup->okButSkipsOrFails()) {
441 1
                    $color  = TPL::getSnippet('cStatusWARN');
442 1
                    $status = 'WARNING';
443
                } else {
444 1
                    $color  = TPL::getSnippet('cStatusFAIL');
445 1
                    $status = 'FAILURE';
446
                }
447
                $html .= '<tr>' .
448 3
                          '<td ' . sprintf(TPL::getSnippet('sTableBackupStatusColumn'), $color) . ' colspan="4">' .
449 3
                          sprintf('backup <em>%s</em>', $backup->getName()) .
450 3
                          ' <span ' . TPL::getSnippet('sTableBackupStatusText') . '>' . $status .'</span>'.
451 3
                          '</td>' .
452 3
                         '</tr>' .
453 3
                         '<tr>' .
454 3
                          '<td ' . TPL::getSnippet('sRowHead') . '>&nbsp;</td>' .
455 3
                          '<td ' . TPL::getSnippet('sRowHead') . ' align="right">executed</td>' .
456 3
                          '<td ' . TPL::getSnippet('sRowHead') . ' align="right">skipped</td>' .
457 3
                          '<td ' . TPL::getSnippet('sRowHead') . ' align="right">failed</td>' .
458 3
                         '</tr>';
459
460
                $html .= '<tr>' .
461 3
                          '<td ' . TPL::getSnippet('sRowCheck') . '>checks</td>' .
462 3
                          '<td ' . TPL::getSnippet('sRowCheck') . ' align="right">' .
463 3
                            $backup->checkCount() . '
464
                           </td>' .
465 3
                          '<td ' . TPL::getSnippet('sRowCheck') . ' align="right">
466
                            &nbsp;
467
                           </td>' .
468 3
                          '<td ' . TPL::getSnippet('sRowCheck') . ' align="right">' .
469 3
                            $backup->checkCountFailed() .
470 3
                          '</td>' .
471 3
                         '</tr>' .
472 3
                         '<tr>' .
473 3
                          '<td ' . TPL::getSnippet('sRowCrypt') . '>crypts</td>' .
474 3
                          '<td ' . TPL::getSnippet('sRowCrypt') . ' align="right">' .
475 3
                            $backup->cryptCount() .
476 3
                          '</td>' .
477 3
                          '<td ' . TPL::getSnippet('sRowCrypt') . ' align="right">' .
478 3
                            $backup->cryptCountSkipped() .
479 3
                          '</td>' .
480 3
                          '<td ' . TPL::getSnippet('sRowCrypt') . ' align="right">' .
481 3
                            $backup->cryptCountFailed() .
482 3
                          '</td>' .
483 3
                         '</tr>' .
484 3
                         '<tr>' .
485 3
                          '<td ' . TPL::getSnippet('sRowSync') . '>syncs</td>' .
486 3
                          '<td ' . TPL::getSnippet('sRowSync') . ' align="right">' .
487 3
                            $backup->syncCount() . '</td>' .
488 3
                          '<td ' . TPL::getSnippet('sRowSync') . ' align="right">' .
489 3
                            $backup->syncCountSkipped() .
490 3
                          '</td>' .
491 3
                          '<td ' . TPL::getSnippet('sRowSync') . ' align="right">' .
492 3
                            $backup->syncCountFailed() .
493 3
                          '</td>' .
494 3
                         '</tr>' .
495 3
                         '<tr>' .
496 3
                          '<td ' . TPL::getSnippet('sRowCleanup') . '>cleanups</td>' .
497 3
                          '<td ' . TPL::getSnippet('sRowCleanup') . ' align="right">' .
498 3
                            $backup->cleanupCount() .
499 3
                          '</td>' .
500 3
                          '<td ' . TPL::getSnippet('sRowCleanup') . ' align="right">' .
501 3
                            $backup->cleanupCountSkipped() .
502 3
                          '</td>' .
503 3
                          '<td ' . TPL::getSnippet('sRowCleanup') . ' align="right">' .
504 3
                            $backup->cleanupCountFailed() .
505 3
                          '</td>' .
506 3
                         '</tr>';
507
508
            }
509 3
            $html .= '</table>';
510
        }
511 4
        return $html;
512
    }
513
514
    /**
515
     * Return mail body footer.
516
     *
517
     * @return string
518
     */
519 4
    protected function getFooterHtml()
520
    {
521 4
        return '<p ' . TPL::getSnippet('sStats') . '>' . PHP_Timer::resourceUsage() . '</p>' .
522 4
               '</td></tr></table>';
523
    }
524
}
525