summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Web/Helper/CookieHelper.php
blob: cc7c44893c649ac33a95a0dfd7f474bccec5f1f2 (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
<?php
/* Icinga Web 2 | (c) 2013 Icinga Development Team | GPLv2+ */

namespace Icinga\Web\Helper;

use Icinga\Web\Request;

/**
 * Helper Class Cookie
 */
class CookieHelper
{
    /**
     * The name of the control cookie
     */
    const CHECK_COOKIE = '_chc';

    /**
     * The request
     *
     * @var Request
     */
    protected $request;

    /**
     * Create a new cookie
     *
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * Check whether cookies are supported or not
     *
     * @return bool
     */
    public function isSupported()
    {
        if (! empty($_COOKIE)) {
            $this->cleanupCheck();
            return true;
        }

        $url = $this->request->getUrl();

        if ($url->hasParam('_checkCookie') && empty($_COOKIE)) {
            return false;
        }

        if (! $url->hasParam('_checkCookie')) {
            $this->provideCheck();
        }

        return false;
    }

    /**
     * Prepare check to detect cookie support
     */
    public function provideCheck()
    {
        setcookie(self::CHECK_COOKIE, '1');

        $requestUri = $this->request->getUrl()->addParams(array('_checkCookie' => 1));
        $this->request->getResponse()->redirectAndExit($requestUri);
    }

    /**
     * Cleanup the cookie support check
     */
    public function cleanupCheck()
    {
        if ($this->request->getUrl()->hasParam('_checkCookie') && isset($_COOKIE[self::CHECK_COOKIE])) {
            $requestUri =$this->request->getUrl()->without('_checkCookie');
            $this->request->getResponse()->redirectAndExit($requestUri);
        }
    }
}