DataInconsistency
2 weeks ago
License
2 months ago
Notices
2 months ago
pQuery
2 months ago
APIPermissionHelper.php
1 year ago
CdnAssetUrl.php
3 years ago
ConflictResolver.php
1 month ago
Cookies.php
2 months ago
DBCollationChecker.php
2 months ago
DOM.php
2 years ago
DateConverter.php
3 years ago
FreeDomains.php
3 years ago
Headers.php
1 year ago
Helpers.php
1 month ago
Installation.php
1 year ago
LegacyDatabase.php
1 year ago
Request.php
2 months ago
SecondLevelDomainNames.php
3 years ago
Security.php
2 months ago
ThirdPartyOutput.php
1 month ago
Url.php
2 months ago
index.php
3 years ago
Cookies.php
68 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\Util; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use InvalidArgumentException; |
| 9 | |
| 10 | class Cookies { |
| 11 | const DEFAULT_OPTIONS = [ |
| 12 | 'expires' => 0, |
| 13 | 'path' => '', |
| 14 | 'domain' => '', |
| 15 | 'secure' => false, |
| 16 | 'httponly' => false, |
| 17 | ]; |
| 18 | |
| 19 | public function set($name, $value, array $options = []) { |
| 20 | if ($this->headersSent()) { |
| 21 | return; |
| 22 | } |
| 23 | $options = $options + self::DEFAULT_OPTIONS; |
| 24 | $value = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); |
| 25 | $error = json_last_error(); |
| 26 | if ($error || ($value === false)) { |
| 27 | throw new InvalidArgumentException('Failed to JSON-encode cookie value'); |
| 28 | } |
| 29 | |
| 30 | $this->setCookie($name, $value, $options); |
| 31 | } |
| 32 | |
| 33 | public function get($name) { |
| 34 | if (!array_key_exists($name, $_COOKIE) || !is_string($_COOKIE[$name])) { |
| 35 | return null; |
| 36 | } |
| 37 | $value = json_decode(sanitize_text_field(wp_unslash($_COOKIE[$name])), true); |
| 38 | $error = json_last_error(); |
| 39 | if ($error) { |
| 40 | return null; |
| 41 | } |
| 42 | return $value; |
| 43 | } |
| 44 | |
| 45 | public function delete($name, array $options = []) { |
| 46 | if (!$this->headersSent()) { |
| 47 | $options = $options + self::DEFAULT_OPTIONS; |
| 48 | $options['expires'] = time() - 3600; |
| 49 | $this->setCookie($name, '', $options); |
| 50 | |
| 51 | if ($options['path'] === '') { |
| 52 | $options['path'] = '/'; |
| 53 | $this->setCookie($name, '', $options); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | unset($_COOKIE[$name]); |
| 58 | } |
| 59 | |
| 60 | protected function headersSent(): bool { |
| 61 | return headers_sent(); |
| 62 | } |
| 63 | |
| 64 | protected function setCookie($name, string $value, array $options): void { |
| 65 | setcookie($name, $value, $options); |
| 66 | } |
| 67 | } |
| 68 |