summaryrefslogtreecommitdiffstats
path: root/library/Reporting/Actions/SendMail.php
blob: 7c70bf5d6a1bbf9f9c1ed46b684eb0e14fb99d9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
// Icinga Reporting | (c) 2018 Icinga GmbH | GPLv2

namespace Icinga\Module\Reporting\Actions;

use Icinga\Application\Config;
use Icinga\Module\Pdfexport\ProvidedHook\Pdfexport;
use Icinga\Module\Reporting\Hook\ActionHook;
use Icinga\Module\Reporting\Mail;
use Icinga\Module\Reporting\Report;
use ipl\Html\Form;

class SendMail extends ActionHook
{
    public function getName()
    {
        return 'Send Mail';
    }

    public function execute(Report $report, array $config)
    {
        $name = sprintf(
            '%s (%s) %s',
            $report->getName(),
            $report->getTimeframe()->getName(),
            date('Y-m-d H:i')
        );

        $mail = new Mail();

        $mail->setFrom(Config::module('reporting')->get('mail', 'from', 'reporting@icinga'));

        if (isset($config['subject'])) {
            $mail->setSubject($config['subject']);
        }

        switch ($config['type']) {
            case 'pdf':
                $mail->attachPdf(Pdfexport::first()->htmlToPdf($report->toPdf()), $name);

                break;
            case 'csv':
                $mail->attachCsv($report->toCsv(), $name);

                break;
            case 'json':
                $mail->attachJson($report->toJson(), $name);

                break;
            default:
                throw new \InvalidArgumentException();
        }

        $recipients = array_filter(preg_split('/[\s,]+/', $config['recipients']));

        $mail->send(null, $recipients);
    }

    public function initConfigForm(Form $form, Report $report)
    {
        $types = ['pdf' => 'PDF'];

        if ($report->providesData()) {
            $types['csv'] = 'CSV';
            $types['json'] = 'JSON';
        }

        $form->addElement('select', 'type', [
            'required'  => true,
            'label'     => t('Type'),
            'options'   => $types
        ]);

        $form->addElement('text', 'subject', [
            'label'         => t('Subject'),
            'placeholder'   => Mail::DEFAULT_SUBJECT
        ]);

        $form->addElement('textarea', 'recipients', [
            'required' => true,
            'label'    => t('Recipients')
        ]);
    }
}