Passed
Push — master ( 8c2ab2...2e2336 )
by Nils
02:47
created

isUnattendedUpgradesUsable()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 12
rs 10
1
<?php
2
3
namespace Startwind\Inventorio\Collector\System\Security;
4
5
use Startwind\Inventorio\Collector\BasicCollector;
6
7
class GeneralSecurityCollector extends BasicCollector
8
{
9
    protected string $identifier = 'SystemSecurity';
10
11
    public function collect(): array
12
    {
13
        $available = $this->isUnattendedUpgradesUsable();
14
        $enabled = false;
15
        if ($available) {
16
            $enabled = $this->isUnattendedUpgradesEnabled();
17
        }
18
19
        return [
20
            'unattendedUpgradesAvailable' => $available,
21
            'unattendedUpgradesEnabled' => $enabled
22
        ];
23
    }
24
25
    private function isUnattendedUpgradesEnabled(): bool
26
    {
27
        $configFile = '/etc/apt/apt.conf.d/20auto-upgrades';
28
29
        if (!file_exists($configFile)) {
30
            return false;
31
        }
32
33
        $content = file_get_contents($configFile);
34
        if ($content === false) {
35
            return false;
36
        }
37
38
        $updateListEnabled = preg_match('/APT::Periodic::Update-Package-Lists\s+"1";/', $content);
39
        $unattendedUpgradeEnabled = preg_match('/APT::Periodic::Unattended-Upgrade\s+"1";/', $content);
40
41
        return $updateListEnabled && $unattendedUpgradeEnabled;
42
    }
43
44
    private function isUnattendedUpgradesUsable(): bool
45
    {
46
        if (stripos(PHP_OS, 'Linux') === false) {
47
            return false;
48
        }
49
50
        $whichApt = trim(shell_exec('which apt'));
51
        if (empty($whichApt)) {
52
            return false;
53
        }
54
55
        return !empty(shell_exec('apt-cache show unattended-upgrades 2>/dev/null'));
56
    }
57
}
58