Completed
Push — 4 ( 6c0917...fa3556 )
by Guy
40s queued 26s
created

CookieJar::cookieIsSecure()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Control;
4
5
use SilverStripe\ORM\FieldType\DBDatetime;
6
use LogicException;
7
8
/**
9
 * A default backend for the setting and getting of cookies
10
 *
11
 * This backend allows one to better test Cookie setting and separate cookie
12
 * handling from the core
13
 *
14
 * @todo Create a config array for defaults (eg: httpOnly, secure, path, domain, expiry)
15
 * @todo A getter for cookies that haven't been sent to the browser yet
16
 * @todo Tests / a way to set the state without hacking with $_COOKIE
17
 * @todo Store the meta information around cookie setting (path, domain, secure, etc)
18
 */
19
class CookieJar implements Cookie_Backend
20
{
21
    /**
22
     * Hold the cookies that were existing at time of instantiation (ie: The ones
23
     * sent to PHP by the browser)
24
     *
25
     * @var array Existing cookies sent by the browser
26
     */
27
    protected $existing = [];
28
29
    /**
30
     * Hold the current cookies (ie: a mix of those that were sent to us and we
31
     * have set without the ones we've cleared)
32
     *
33
     * @var array The state of cookies once we've sent the response
34
     */
35
    protected $current = [];
36
37
    /**
38
     * Hold any NEW cookies that were set by the application and will be sent
39
     * in the next response
40
     *
41
     * @var array New cookies set by the application
42
     */
43
    protected $new = [];
44
45
    /**
46
     * When creating the backend we want to store the existing cookies in our
47
     * "existing" array. This allows us to distinguish between cookies we received
48
     * or we set ourselves (and didn't get from the browser)
49
     *
50
     * @param array $cookies The existing cookies to load into the cookie jar.
51
     * Omit this to default to $_COOKIE
52
     */
53
    public function __construct($cookies = [])
54
    {
55
        $this->current = $this->existing = func_num_args()
56
            ? ($cookies ?: []) // Convert empty values to blank arrays
57
            : $_COOKIE;
58
    }
59
60
    /**
61
     * Set a cookie
62
     *
63
     * @param string $name The name of the cookie
64
     * @param string $value The value for the cookie to hold
65
     * @param float $expiry The number of days until expiry; 0 indicates a cookie valid for the current session
66
     * @param string $path The path to save the cookie on (falls back to site base)
67
     * @param string $domain The domain to make the cookie available on
68
     * @param boolean $secure Can the cookie only be sent over SSL?
69
     * @param boolean $httpOnly Prevent the cookie being accessible by JS
70
     */
71
    public function set($name, $value, $expiry = 90, $path = null, $domain = null, $secure = false, $httpOnly = true)
72
    {
73
        //are we setting or clearing a cookie? false values are reserved for clearing cookies (see PHP manual)
74
        $clear = false;
75
        if ($value === false || $value === '' || $expiry < 0) {
76
            $clear = true;
77
            $value = false;
78
        }
79
80
        //expiry === 0 is a special case where we set a cookie for the current user session
81
        if ($expiry !== 0) {
82
            //don't do the maths if we are clearing
83
            $expiry = $clear ? -1 : DBDatetime::now()->getTimestamp() + (86400 * $expiry);
84
        }
85
        //set the path up
86
        $path = $path ? $path : Director::baseURL();
87
        //send the cookie
88
        $this->outputCookie($name, $value, $expiry, $path, $domain, $secure, $httpOnly);
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type false; however, parameter $value of SilverStripe\Control\CookieJar::outputCookie() does only seem to accept array|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

88
        $this->outputCookie($name, /** @scrutinizer ignore-type */ $value, $expiry, $path, $domain, $secure, $httpOnly);
Loading history...
Bug introduced by
It seems like $expiry can also be of type double; however, parameter $expiry of SilverStripe\Control\CookieJar::outputCookie() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

88
        $this->outputCookie($name, $value, /** @scrutinizer ignore-type */ $expiry, $path, $domain, $secure, $httpOnly);
Loading history...
89
        //keep our variables in check
90
        if ($clear) {
91
            unset($this->new[$name], $this->current[$name]);
92
        } else {
93
            $this->new[$name] = $this->current[$name] = $value;
94
        }
95
    }
96
97
    /**
98
     * Get the cookie value by name
99
     *
100
     * Cookie names are normalised to work around PHP's behaviour of replacing incoming variable name . with _
101
     *
102
     * @param string $name The name of the cookie to get
103
     * @param boolean $includeUnsent Include cookies we've yet to send when fetching values
104
     *
105
     * @return string|null The cookie value or null if unset
106
     */
107
    public function get($name, $includeUnsent = true)
108
    {
109
        $cookies = $includeUnsent ? $this->current : $this->existing;
110
        if (isset($cookies[$name])) {
111
            return $cookies[$name];
112
        }
113
114
        //Normalise cookie names by replacing '.' with '_'
115
        $safeName = str_replace('.', '_', $name ?? '');
116
        if (isset($cookies[$safeName])) {
117
            return $cookies[$safeName];
118
        }
119
        return null;
120
    }
121
122
    /**
123
     * Get all the cookies
124
     *
125
     * @param boolean $includeUnsent Include cookies we've yet to send
126
     * @return array All the cookies
127
     */
128
    public function getAll($includeUnsent = true)
129
    {
130
        return $includeUnsent ? $this->current : $this->existing;
131
    }
132
133
    /**
134
     * Force the expiry of a cookie by name
135
     *
136
     * @param string $name The name of the cookie to expire
137
     * @param string $path The path to save the cookie on (falls back to site base)
138
     * @param string $domain The domain to make the cookie available on
139
     * @param boolean $secure Can the cookie only be sent over SSL?
140
     * @param boolean $httpOnly Prevent the cookie being accessible by JS
141
     */
142
    public function forceExpiry($name, $path = null, $domain = null, $secure = false, $httpOnly = true)
143
    {
144
        $this->set($name, false, -1, $path, $domain, $secure, $httpOnly);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $value of SilverStripe\Control\CookieJar::set(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

144
        $this->set($name, /** @scrutinizer ignore-type */ false, -1, $path, $domain, $secure, $httpOnly);
Loading history...
145
    }
146
147
    /**
148
     * The function that actually sets the cookie using PHP
149
     *
150
     * @see http://uk3.php.net/manual/en/function.setcookie.php
151
     *
152
     * @param string $name The name of the cookie
153
     * @param string|array $value The value for the cookie to hold
154
     * @param int $expiry A Unix timestamp indicating when the cookie expires; 0 means it will expire at the end of the session
155
     * @param string $path The path to save the cookie on (falls back to site base)
156
     * @param string $domain The domain to make the cookie available on
157
     * @param boolean $secure Can the cookie only be sent over SSL?
158
     * @param boolean $httpOnly Prevent the cookie being accessible by JS
159
     * @return boolean If the cookie was set or not; doesn't mean it's accepted by the browser
160
     */
161
    protected function outputCookie(
162
        $name,
163
        $value,
164
        $expiry = 90,
165
        $path = null,
166
        $domain = null,
167
        $secure = false,
168
        $httpOnly = true
169
    ) {
170
        $sameSite = $this->getSameSite($name);
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\Control\CookieJar::getSameSite() has been deprecated: 5.0 The relevant methods will include a `$sameSite` parameter instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

170
        $sameSite = /** @scrutinizer ignore-deprecated */ $this->getSameSite($name);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
171
        Cookie::validateSameSite($sameSite);
172
        // if headers aren't sent, we can set the cookie
173
        if (!headers_sent($file, $line)) {
174
            return setcookie($name ?? '', $value ?? '', [
0 ignored issues
show
Bug introduced by
It seems like $value ?? '' can also be of type array; however, parameter $value of setcookie() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

174
            return setcookie($name ?? '', /** @scrutinizer ignore-type */ $value ?? '', [
Loading history...
175
                'expires' => $expiry ?? 0,
176
                'path' => $path ?? '',
177
                'domain' => $domain ?? '',
178
                'secure' => $this->cookieIsSecure($sameSite, (bool) $secure),
179
                'httponly' => $httpOnly ?? false,
180
                'samesite' => $sameSite,
181
            ]);
182
        }
183
184
        if (Cookie::config()->uninherited('report_errors')) {
185
            throw new LogicException(
186
                "Cookie '$name' can't be set. The site started outputting content at line $line in $file"
187
            );
188
        }
189
        return false;
190
    }
191
192
    /**
193
     * Cookies must be secure if samesite is "None"
194
     */
195
    private function cookieIsSecure(string $sameSite, bool $secure): bool
196
    {
197
        return $sameSite === 'None' ? true : $secure;
198
    }
199
200
    /**
201
     * Get the correct samesite value - Session cookies use a different configuration variable.
202
     *
203
     * @deprecated 5.0 The relevant methods will include a `$sameSite` parameter instead.
204
     */
205
    private function getSameSite(string $name): string
206
    {
207
        if ($name === session_name()) {
208
            return Session::config()->get('cookie_samesite');
209
        }
210
        return Cookie::config()->get('default_samesite');
211
    }
212
}
213