summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Web/UserAgent.php
blob: 71c1a8b1c055898df487b73d4893c931d52dba13 (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
85
86
<?php
/* Icinga Web 2 | (c) 2021 Icinga GmbH | GPLv2+ */

namespace Icinga\Web;

/**
 * Class UserAgent
 *
 * This class helps to get user agent information like OS type and browser name
 *
 * @package Icinga\Web
 */
class UserAgent
{
    /**
     * $_SERVER['HTTP_USER_AGENT'] output string
     *
     * @var string|null
     */
    private $agent;

    public function __construct($agent = null)
    {
        $this->agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;

        if ($agent) {
            $this->agent = $agent->http_user_agent;
        }
    }

    /**
     * Return $_SERVER['HTTP_USER_AGENT'] output string of given or current device
     *
     * @return string
     */
    public function getAgent()
    {
        return $this->agent;
    }

    /**
     * Get Browser name
     *
     * @return string Browser name or unknown if not found
     */
    public function getBrowser()
    {
        // key => regex value
        $browsers = [
            "Internet Explorer"    => "/MSIE(.*)/i",
            "Seamonkey"            => "/Seamonkey(.*)/i",
            "MS Edge"              => "/Edg(.*)/i",
            "Opera"                => "/Opera(.*)/i",
            "Opera Browser"        => "/OPR(.*)/i",
            "Chromium"             => "/Chromium(.*)/i",
            "Firefox"              => "/Firefox(.*)/i",
            "Google Chrome"        => "/Chrome(.*)/i",
            "Safari"               => "/Safari(.*)/i"
        ];
        //TODO find a way to return also the version of the browser
        foreach ($browsers as $browser => $regex) {
            if (preg_match($regex, $this->agent)) {
                return $browser;
            }
        }

        return 'unknown';
    }

    /**
     * Get Operating system information
     *
     * @return string os information
     */
    public function getOs()
    {
        // get string before the first appearance of ')'
        $device = strstr($this->agent, ')', true);
        if (! $device) {
            return 'unknown';
        }

        // return string after the first appearance of '('
        return  substr($device, strpos($device, '(') + 1);
    }
}