summaryrefslogtreecommitdiffstats
path: root/library/X509/ExpirationWidget.php
blob: dffc3a8076269a9db3b49e1430cc85740ac824f6 (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
<?php

// Icinga Web 2 X.509 Module | (c) 2018 Icinga GmbH | GPLv2

namespace Icinga\Module\X509;

use Icinga\Date\DateFormatter;
use ipl\Html\BaseHtmlElement;
use ipl\Html\Html;
use ipl\Html\HtmlString;
use ipl\Web\Compat\StyleWithNonce;

class ExpirationWidget extends BaseHtmlElement
{
    protected $tag = 'div';

    protected $defaultAttributes = ['class' => 'expiration-widget'];

    protected $from;

    protected $to;

    public function __construct($from, $to)
    {
        $this->from = $from;
        $this->to = $to;
    }

    protected function assemble()
    {
        $now = time();

        $from = $this->from;

        if ($from->getTimestamp() > $now) {
            $ratio = 0;
            $dateTip = $from->format('Y-m-d H:i:s');
            $message = sprintf(mt('x509', 'not until after %s'), DateFormatter::timeUntil($from->getTimestamp(), true));
        } else {
            $to = $this->to;

            $secondsRemaining = $to->getTimestamp() - $now;
            $daysRemaining = ($secondsRemaining - $secondsRemaining % 86400) / 86400;
            if ($daysRemaining > 0) {
                $secondsTotal = $to->getTimestamp() - $from->getTimestamp();
                $daysTotal = ($secondsTotal - $secondsTotal % 86400) / 86400;

                $ratio = min(100, 100 - round(($daysRemaining * 100) / $daysTotal, 2));
                $message = sprintf(mt('x509', 'in %d days'), $daysRemaining);
            } else {
                $ratio = 100;
                if ($daysRemaining < 0) {
                    $message = sprintf(mt('x509', '%d days ago'), $daysRemaining * -1);
                } else {
                    $message = mt('x509', 'today');
                }
            }

            $dateTip = $to->format('Y-m-d H:i:s');
        }

        if ($ratio >= 75) {
            if ($ratio >= 90) {
                $state = 'state-critical';
            } else {
                $state = 'state-warning';
            }
        } else {
            $state = 'state-ok';
        }

        $progressBar = Html::tag('div', ['class' => "bg-stateful $state"], new HtmlString('&nbsp;'));
        $progressBarStyle = (new StyleWithNonce())
            ->setModule('x509')
            ->addFor($progressBar, ['width' => sprintf('%F%%', $ratio)]);

        $this->addHtml(Html::tag('span', ['class' => 'progress-bar-label', 'title' => $dateTip], $message));
        $this->addHtml($progressBarStyle, Html::tag('div', ['class' => 'progress-bar dont-print'], $progressBar));
    }
}