PhpCookieManager.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Stdlib\Cookie;
  7. use Magento\Framework\App\ObjectManager;
  8. use Magento\Framework\Exception\InputException;
  9. use Magento\Framework\Stdlib\CookieManagerInterface;
  10. use Magento\Framework\Phrase;
  11. use Magento\Framework\HTTP\Header as HttpHeader;
  12. use Psr\Log\LoggerInterface;
  13. /**
  14. * CookieManager helps manage the setting, retrieving and deleting of cookies.
  15. *
  16. * To aid in security, the cookie manager will make it possible for the application to indicate if the cookie contains
  17. * sensitive data so that extra protection can be added to the contents of the cookie as well as how the browser
  18. * stores the cookie.
  19. *
  20. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  21. */
  22. class PhpCookieManager implements CookieManagerInterface
  23. {
  24. /**#@+
  25. * Constants for Cookie manager.
  26. * RFC 2109 - Page 15
  27. * http://www.ietf.org/rfc/rfc6265.txt
  28. */
  29. const MAX_NUM_COOKIES = 50;
  30. const MAX_COOKIE_SIZE = 4096;
  31. const EXPIRE_NOW_TIME = 1;
  32. const EXPIRE_AT_END_OF_SESSION_TIME = 0;
  33. /**#@-*/
  34. /**#@+
  35. * Constant for metadata array key
  36. */
  37. const KEY_EXPIRE_TIME = 'expiry';
  38. /**#@-*/
  39. /**#@-*/
  40. private $scope;
  41. /**
  42. * @var CookieReaderInterface
  43. */
  44. private $reader;
  45. /**
  46. * Logger for warning details.
  47. *
  48. * @var LoggerInterface
  49. */
  50. private $logger;
  51. /**
  52. * Object that provides access to HTTP headers.
  53. *
  54. * @var HttpHeader
  55. */
  56. private $httpHeader;
  57. /**
  58. * @param CookieScopeInterface $scope
  59. * @param CookieReaderInterface $reader
  60. * @param LoggerInterface $logger
  61. * @param HttpHeader $httpHeader
  62. */
  63. public function __construct(
  64. CookieScopeInterface $scope,
  65. CookieReaderInterface $reader,
  66. LoggerInterface $logger = null,
  67. HttpHeader $httpHeader = null
  68. ) {
  69. $this->scope = $scope;
  70. $this->reader = $reader;
  71. $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class);
  72. $this->httpHeader = $httpHeader ?: ObjectManager::getInstance()->get(HttpHeader::class);
  73. }
  74. /**
  75. * Set a value in a private cookie with the given $name $value pairing.
  76. *
  77. * Sensitive cookies cannot be accessed by JS. HttpOnly will always be set to true for these cookies.
  78. *
  79. * @param string $name
  80. * @param string $value
  81. * @param SensitiveCookieMetadata $metadata
  82. * @return void
  83. * @throws FailureToSendException Cookie couldn't be sent to the browser. If this exception isn't thrown,
  84. * there is still no guarantee that the browser received and accepted the cookie.
  85. * @throws CookieSizeLimitReachedException Thrown when the cookie is too big to store any additional data.
  86. * @throws InputException If the cookie name is empty or contains invalid characters.
  87. */
  88. public function setSensitiveCookie($name, $value, SensitiveCookieMetadata $metadata = null)
  89. {
  90. $metadataArray = $this->scope->getSensitiveCookieMetadata($metadata)->__toArray();
  91. $this->setCookie($name, $value, $metadataArray);
  92. }
  93. /**
  94. * Set a value in a public cookie with the given $name $value pairing.
  95. *
  96. * Public cookies can be accessed by JS. HttpOnly will be set to false by default for these cookies,
  97. * but can be changed to true.
  98. *
  99. * @param string $name
  100. * @param string $value
  101. * @param PublicCookieMetadata $metadata
  102. * @return void
  103. * @throws FailureToSendException If cookie couldn't be sent to the browser.
  104. * @throws CookieSizeLimitReachedException Thrown when the cookie is too big to store any additional data.
  105. * @throws InputException If the cookie name is empty or contains invalid characters.
  106. */
  107. public function setPublicCookie($name, $value, PublicCookieMetadata $metadata = null)
  108. {
  109. $metadataArray = $this->scope->getPublicCookieMetadata($metadata)->__toArray();
  110. $this->setCookie($name, $value, $metadataArray);
  111. }
  112. /**
  113. * Set a value in a cookie with the given $name $value pairing.
  114. *
  115. * @param string $name
  116. * @param string $value
  117. * @param array $metadataArray
  118. * @return void
  119. * @throws FailureToSendException If cookie couldn't be sent to the browser.
  120. * @throws CookieSizeLimitReachedException Thrown when the cookie is too big to store any additional data.
  121. * @throws InputException If the cookie name is empty or contains invalid characters.
  122. */
  123. protected function setCookie($name, $value, array $metadataArray)
  124. {
  125. $expire = $this->computeExpirationTime($metadataArray);
  126. $this->checkAbilityToSendCookie($name, $value);
  127. $phpSetcookieSuccess = setcookie(
  128. $name,
  129. $value,
  130. $expire,
  131. $this->extractValue(CookieMetadata::KEY_PATH, $metadataArray, ''),
  132. $this->extractValue(CookieMetadata::KEY_DOMAIN, $metadataArray, ''),
  133. $this->extractValue(CookieMetadata::KEY_SECURE, $metadataArray, false),
  134. $this->extractValue(CookieMetadata::KEY_HTTP_ONLY, $metadataArray, false)
  135. );
  136. if (!$phpSetcookieSuccess) {
  137. $params['name'] = $name;
  138. if ($value == '') {
  139. throw new FailureToSendException(
  140. new Phrase('The cookie with "%name" cookieName couldn\'t be deleted.', $params)
  141. );
  142. } else {
  143. throw new FailureToSendException(
  144. new Phrase('The cookie with "%name" cookieName couldn\'t be sent. Please try again later.', $params)
  145. );
  146. }
  147. }
  148. }
  149. /**
  150. * Retrieve the size of a cookie.
  151. * The size of a cookie is determined by the length of 'name=value' portion of the cookie.
  152. *
  153. * @param string $name
  154. * @param string $value
  155. * @return int
  156. */
  157. private function sizeOfCookie($name, $value)
  158. {
  159. // The constant '1' is the length of the equal sign in 'name=value'.
  160. return strlen($name) + 1 + strlen($value);
  161. }
  162. /**
  163. * Determines whether or not it is possible to send the cookie, based on the number of cookies that already
  164. * exist and the size of the cookie.
  165. *
  166. * @param string $name
  167. * @param string|null $value
  168. * @return void if it is possible to send the cookie
  169. * @throws CookieSizeLimitReachedException Thrown when the cookie is too big to store any additional data.
  170. * @throws InputException If the cookie name is empty or contains invalid characters.
  171. */
  172. private function checkAbilityToSendCookie($name, $value)
  173. {
  174. if ($name == '' || preg_match("/[=,; \t\r\n\013\014]/", $name)) {
  175. throw new InputException(
  176. new Phrase(
  177. 'Cookie name cannot be empty and cannot contain these characters: =,; \\t\\r\\n\\013\\014'
  178. )
  179. );
  180. }
  181. $numCookies = count($_COOKIE);
  182. if (!isset($_COOKIE[$name])) {
  183. $numCookies++;
  184. }
  185. $sizeOfCookie = $this->sizeOfCookie($name, $value);
  186. if ($numCookies > static::MAX_NUM_COOKIES) {
  187. $this->logger->warning(
  188. new Phrase('Unable to send the cookie. Maximum number of cookies would be exceeded.'),
  189. array_merge($_COOKIE, ['user-agent' => $this->httpHeader->getHttpUserAgent()])
  190. );
  191. }
  192. if ($sizeOfCookie > static::MAX_COOKIE_SIZE) {
  193. throw new CookieSizeLimitReachedException(
  194. new Phrase(
  195. 'Unable to send the cookie. Size of \'%name\' is %size bytes.',
  196. [
  197. 'name' => $name,
  198. 'size' => $sizeOfCookie,
  199. ]
  200. )
  201. );
  202. }
  203. }
  204. /**
  205. * Determines the expiration time of a cookie.
  206. *
  207. * @param array $metadataArray
  208. * @return int in seconds since the Unix epoch.
  209. */
  210. private function computeExpirationTime(array $metadataArray)
  211. {
  212. if (isset($metadataArray[PhpCookieManager::KEY_EXPIRE_TIME])
  213. && $metadataArray[PhpCookieManager::KEY_EXPIRE_TIME] < time()
  214. ) {
  215. $expireTime = $metadataArray[PhpCookieManager::KEY_EXPIRE_TIME];
  216. } else {
  217. if (isset($metadataArray[CookieMetadata::KEY_DURATION])) {
  218. $expireTime = $metadataArray[CookieMetadata::KEY_DURATION] + time();
  219. } else {
  220. $expireTime = PhpCookieManager::EXPIRE_AT_END_OF_SESSION_TIME;
  221. }
  222. }
  223. return $expireTime;
  224. }
  225. /**
  226. * Determines the value to be used as a $parameter.
  227. * If $metadataArray[$parameter] is not set, returns the $defaultValue.
  228. *
  229. * @param string $parameter
  230. * @param array $metadataArray
  231. * @param string|boolean|int|null $defaultValue
  232. * @return string|boolean|int|null
  233. */
  234. private function extractValue($parameter, array $metadataArray, $defaultValue)
  235. {
  236. if (array_key_exists($parameter, $metadataArray)) {
  237. return $metadataArray[$parameter];
  238. } else {
  239. return $defaultValue;
  240. }
  241. }
  242. /**
  243. * Retrieve a value from a cookie.
  244. *
  245. * @param string $name
  246. * @param string|null $default The default value to return if no value could be found for the given $name.
  247. * @return string|null
  248. */
  249. public function getCookie($name, $default = null)
  250. {
  251. return $this->reader->getCookie($name, $default);
  252. }
  253. /**
  254. * Deletes a cookie with the given name.
  255. *
  256. * @param string $name
  257. * @param CookieMetadata $metadata
  258. * @return void
  259. * @throws FailureToSendException If cookie couldn't be sent to the browser.
  260. * If this exception isn't thrown, there is still no guarantee that the browser
  261. * received and accepted the request to delete this cookie.
  262. * @throws InputException If the cookie name is empty or contains invalid characters.
  263. */
  264. public function deleteCookie($name, CookieMetadata $metadata = null)
  265. {
  266. $metadataArray = $this->scope->getCookieMetadata($metadata)->__toArray();
  267. // explicitly set an expiration time in the metadataArray.
  268. $metadataArray[PhpCookieManager::KEY_EXPIRE_TIME] = PhpCookieManager::EXPIRE_NOW_TIME;
  269. $this->checkAbilityToSendCookie($name, '');
  270. // cookie value set to empty string to delete from the remote client
  271. $this->setCookie($name, '', $metadataArray);
  272. // Remove the cookie
  273. unset($_COOKIE[$name]);
  274. }
  275. }