1<?php
2namespace GuzzleHttp\Cookie;
3
4/**
5 * Set-Cookie object
6 */
7class SetCookie
8{
9    /** @var array */
10    private static $defaults = [
11        'Name'     => null,
12        'Value'    => null,
13        'Domain'   => null,
14        'Path'     => '/',
15        'Max-Age'  => null,
16        'Expires'  => null,
17        'Secure'   => false,
18        'Discard'  => false,
19        'HttpOnly' => false
20    ];
21
22    /** @var array Cookie data */
23    private $data;
24
25    /**
26     * Create a new SetCookie object from a string
27     *
28     * @param string $cookie Set-Cookie header string
29     *
30     * @return self
31     */
32    public static function fromString($cookie)
33    {
34        // Create the default return array
35        $data = self::$defaults;
36        // Explode the cookie string using a series of semicolons
37        $pieces = array_filter(array_map('trim', explode(';', $cookie)));
38        // The name of the cookie (first kvp) must exist and include an equal sign.
39        if (empty($pieces[0]) || !strpos($pieces[0], '=')) {
40            return new self($data);
41        }
42
43        // Add the cookie pieces into the parsed data array
44        foreach ($pieces as $part) {
45            $cookieParts = explode('=', $part, 2);
46            $key = trim($cookieParts[0]);
47            $value = isset($cookieParts[1])
48                ? trim($cookieParts[1], " \n\r\t\0\x0B")
49                : true;
50
51            // Only check for non-cookies when cookies have been found
52            if (empty($data['Name'])) {
53                $data['Name'] = $key;
54                $data['Value'] = $value;
55            } else {
56                foreach (array_keys(self::$defaults) as $search) {
57                    if (!strcasecmp($search, $key)) {
58                        $data[$search] = $value;
59                        continue 2;
60                    }
61                }
62                $data[$key] = $value;
63            }
64        }
65
66        return new self($data);
67    }
68
69    /**
70     * @param array $data Array of cookie data provided by a Cookie parser
71     */
72    public function __construct(array $data = [])
73    {
74        $this->data = array_replace(self::$defaults, $data);
75        // Extract the Expires value and turn it into a UNIX timestamp if needed
76        if (!$this->getExpires() && $this->getMaxAge()) {
77            // Calculate the Expires date
78            $this->setExpires(time() + $this->getMaxAge());
79        } elseif ($this->getExpires() && !is_numeric($this->getExpires())) {
80            $this->setExpires($this->getExpires());
81        }
82    }
83
84    public function __toString()
85    {
86        $str = $this->data['Name'] . '=' . $this->data['Value'] . '; ';
87        foreach ($this->data as $k => $v) {
88            if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
89                if ($k === 'Expires') {
90                    $str .= 'Expires=' . gmdate('D, d M Y H:i:s \G\M\T', $v) . '; ';
91                } else {
92                    $str .= ($v === true ? $k : "{$k}={$v}") . '; ';
93                }
94            }
95        }
96
97        return rtrim($str, '; ');
98    }
99
100    public function toArray()
101    {
102        return $this->data;
103    }
104
105    /**
106     * Get the cookie name
107     *
108     * @return string
109     */
110    public function getName()
111    {
112        return $this->data['Name'];
113    }
114
115    /**
116     * Set the cookie name
117     *
118     * @param string $name Cookie name
119     */
120    public function setName($name)
121    {
122        $this->data['Name'] = $name;
123    }
124
125    /**
126     * Get the cookie value
127     *
128     * @return string
129     */
130    public function getValue()
131    {
132        return $this->data['Value'];
133    }
134
135    /**
136     * Set the cookie value
137     *
138     * @param string $value Cookie value
139     */
140    public function setValue($value)
141    {
142        $this->data['Value'] = $value;
143    }
144
145    /**
146     * Get the domain
147     *
148     * @return string|null
149     */
150    public function getDomain()
151    {
152        return $this->data['Domain'];
153    }
154
155    /**
156     * Set the domain of the cookie
157     *
158     * @param string $domain
159     */
160    public function setDomain($domain)
161    {
162        $this->data['Domain'] = $domain;
163    }
164
165    /**
166     * Get the path
167     *
168     * @return string
169     */
170    public function getPath()
171    {
172        return $this->data['Path'];
173    }
174
175    /**
176     * Set the path of the cookie
177     *
178     * @param string $path Path of the cookie
179     */
180    public function setPath($path)
181    {
182        $this->data['Path'] = $path;
183    }
184
185    /**
186     * Maximum lifetime of the cookie in seconds
187     *
188     * @return int|null
189     */
190    public function getMaxAge()
191    {
192        return $this->data['Max-Age'];
193    }
194
195    /**
196     * Set the max-age of the cookie
197     *
198     * @param int $maxAge Max age of the cookie in seconds
199     */
200    public function setMaxAge($maxAge)
201    {
202        $this->data['Max-Age'] = $maxAge;
203    }
204
205    /**
206     * The UNIX timestamp when the cookie Expires
207     *
208     * @return mixed
209     */
210    public function getExpires()
211    {
212        return $this->data['Expires'];
213    }
214
215    /**
216     * Set the unix timestamp for which the cookie will expire
217     *
218     * @param int $timestamp Unix timestamp
219     */
220    public function setExpires($timestamp)
221    {
222        $this->data['Expires'] = is_numeric($timestamp)
223            ? (int) $timestamp
224            : strtotime($timestamp);
225    }
226
227    /**
228     * Get whether or not this is a secure cookie
229     *
230     * @return bool|null
231     */
232    public function getSecure()
233    {
234        return $this->data['Secure'];
235    }
236
237    /**
238     * Set whether or not the cookie is secure
239     *
240     * @param bool $secure Set to true or false if secure
241     */
242    public function setSecure($secure)
243    {
244        $this->data['Secure'] = $secure;
245    }
246
247    /**
248     * Get whether or not this is a session cookie
249     *
250     * @return bool|null
251     */
252    public function getDiscard()
253    {
254        return $this->data['Discard'];
255    }
256
257    /**
258     * Set whether or not this is a session cookie
259     *
260     * @param bool $discard Set to true or false if this is a session cookie
261     */
262    public function setDiscard($discard)
263    {
264        $this->data['Discard'] = $discard;
265    }
266
267    /**
268     * Get whether or not this is an HTTP only cookie
269     *
270     * @return bool
271     */
272    public function getHttpOnly()
273    {
274        return $this->data['HttpOnly'];
275    }
276
277    /**
278     * Set whether or not this is an HTTP only cookie
279     *
280     * @param bool $httpOnly Set to true or false if this is HTTP only
281     */
282    public function setHttpOnly($httpOnly)
283    {
284        $this->data['HttpOnly'] = $httpOnly;
285    }
286
287    /**
288     * Check if the cookie matches a path value.
289     *
290     * A request-path path-matches a given cookie-path if at least one of
291     * the following conditions holds:
292     *
293     * - The cookie-path and the request-path are identical.
294     * - The cookie-path is a prefix of the request-path, and the last
295     *   character of the cookie-path is %x2F ("/").
296     * - The cookie-path is a prefix of the request-path, and the first
297     *   character of the request-path that is not included in the cookie-
298     *   path is a %x2F ("/") character.
299     *
300     * @param string $requestPath Path to check against
301     *
302     * @return bool
303     */
304    public function matchesPath($requestPath)
305    {
306        $cookiePath = $this->getPath();
307
308        // Match on exact matches or when path is the default empty "/"
309        if ($cookiePath === '/' || $cookiePath == $requestPath) {
310            return true;
311        }
312
313        // Ensure that the cookie-path is a prefix of the request path.
314        if (0 !== strpos($requestPath, $cookiePath)) {
315            return false;
316        }
317
318        // Match if the last character of the cookie-path is "/"
319        if (substr($cookiePath, -1, 1) === '/') {
320            return true;
321        }
322
323        // Match if the first character not included in cookie path is "/"
324        return substr($requestPath, strlen($cookiePath), 1) === '/';
325    }
326
327    /**
328     * Check if the cookie matches a domain value
329     *
330     * @param string $domain Domain to check against
331     *
332     * @return bool
333     */
334    public function matchesDomain($domain)
335    {
336        // Remove the leading '.' as per spec in RFC 6265.
337        // http://tools.ietf.org/html/rfc6265#section-5.2.3
338        $cookieDomain = ltrim($this->getDomain(), '.');
339
340        // Domain not set or exact match.
341        if (!$cookieDomain || !strcasecmp($domain, $cookieDomain)) {
342            return true;
343        }
344
345        // Matching the subdomain according to RFC 6265.
346        // http://tools.ietf.org/html/rfc6265#section-5.1.3
347        if (filter_var($domain, FILTER_VALIDATE_IP)) {
348            return false;
349        }
350
351        return (bool) preg_match('/\.' . preg_quote($cookieDomain, '/') . '$/', $domain);
352    }
353
354    /**
355     * Check if the cookie is expired
356     *
357     * @return bool
358     */
359    public function isExpired()
360    {
361        return $this->getExpires() !== null && time() > $this->getExpires();
362    }
363
364    /**
365     * Check if the cookie is valid according to RFC 6265
366     *
367     * @return bool|string Returns true if valid or an error message if invalid
368     */
369    public function validate()
370    {
371        // Names must not be empty, but can be 0
372        $name = $this->getName();
373        if (empty($name) && !is_numeric($name)) {
374            return 'The cookie name must not be empty';
375        }
376
377        // Check if any of the invalid characters are present in the cookie name
378        if (preg_match(
379            '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/',
380            $name
381        )) {
382            return 'Cookie name must not contain invalid characters: ASCII '
383                . 'Control characters (0-31;127), space, tab and the '
384                . 'following characters: ()<>@,;:\"/?={}';
385        }
386
387        // Value must not be empty, but can be 0
388        $value = $this->getValue();
389        if (empty($value) && !is_numeric($value)) {
390            return 'The cookie value must not be empty';
391        }
392
393        // Domains must not be empty, but can be 0
394        // A "0" is not a valid internet domain, but may be used as server name
395        // in a private network.
396        $domain = $this->getDomain();
397        if (empty($domain) && !is_numeric($domain)) {
398            return 'The cookie domain must not be empty';
399        }
400
401        return true;
402    }
403}
404