PrivateTempStore.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. <?php
  2. namespace Drupal\Core\TempStore;
  3. use Drupal\Core\DependencyInjection\DependencySerializationTrait;
  4. use Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface;
  5. use Drupal\Core\Lock\LockBackendInterface;
  6. use Drupal\Core\Session\AccountProxyInterface;
  7. use Symfony\Component\HttpFoundation\RequestStack;
  8. /**
  9. * Stores and retrieves temporary data for a given owner.
  10. *
  11. * A PrivateTempStore can be used to make temporary, non-cache data available
  12. * across requests. The data for the PrivateTempStore is stored in one
  13. * key/value collection. PrivateTempStore data expires automatically after a
  14. * given timeframe.
  15. *
  16. * The PrivateTempStore is different from a cache, because the data in it is not
  17. * yet saved permanently and so it cannot be rebuilt. Typically, the
  18. * PrivateTempStore might be used to store work in progress that is later saved
  19. * permanently elsewhere, e.g. autosave data, multistep forms, or in-progress
  20. * changes to complex configuration that are not ready to be saved.
  21. *
  22. * The PrivateTempStore differs from the SharedTempStore in that all keys are
  23. * ensured to be unique for a particular user and users can never share data. If
  24. * you want to be able to share data between users or use it for locking, use
  25. * \Drupal\Core\TempStore\SharedTempStore.
  26. */
  27. class PrivateTempStore {
  28. use DependencySerializationTrait;
  29. /**
  30. * The key/value storage object used for this data.
  31. *
  32. * @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
  33. */
  34. protected $storage;
  35. /**
  36. * The lock object used for this data.
  37. *
  38. * @var \Drupal\Core\Lock\LockBackendInterface
  39. */
  40. protected $lockBackend;
  41. /**
  42. * The current user.
  43. *
  44. * @var \Drupal\Core\Session\AccountProxyInterface
  45. */
  46. protected $currentUser;
  47. /**
  48. * The request stack.
  49. *
  50. * @var \Symfony\Component\HttpFoundation\RequestStack
  51. */
  52. protected $requestStack;
  53. /**
  54. * The time to live for items in seconds.
  55. *
  56. * By default, data is stored for one week (604800 seconds) before expiring.
  57. *
  58. * @var int
  59. */
  60. protected $expire;
  61. /**
  62. * Constructs a new object for accessing data from a key/value store.
  63. *
  64. * @param \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface $storage
  65. * The key/value storage object used for this data. Each storage object
  66. * represents a particular collection of data and will contain any number
  67. * of key/value pairs.
  68. * @param \Drupal\Core\Lock\LockBackendInterface $lock_backend
  69. * The lock object used for this data.
  70. * @param \Drupal\Core\Session\AccountProxyInterface $current_user
  71. * The current user account.
  72. * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
  73. * The request stack.
  74. * @param int $expire
  75. * The time to live for items, in seconds.
  76. */
  77. public function __construct(KeyValueStoreExpirableInterface $storage, LockBackendInterface $lock_backend, AccountProxyInterface $current_user, RequestStack $request_stack, $expire = 604800) {
  78. $this->storage = $storage;
  79. $this->lockBackend = $lock_backend;
  80. $this->currentUser = $current_user;
  81. $this->requestStack = $request_stack;
  82. $this->expire = $expire;
  83. }
  84. /**
  85. * Retrieves a value from this PrivateTempStore for a given key.
  86. *
  87. * @param string $key
  88. * The key of the data to retrieve.
  89. *
  90. * @return mixed
  91. * The data associated with the key, or NULL if the key does not exist.
  92. */
  93. public function get($key) {
  94. $key = $this->createkey($key);
  95. if (($object = $this->storage->get($key)) && ($object->owner == $this->getOwner())) {
  96. return $object->data;
  97. }
  98. }
  99. /**
  100. * Stores a particular key/value pair in this PrivateTempStore.
  101. *
  102. * @param string $key
  103. * The key of the data to store.
  104. * @param mixed $value
  105. * The data to store.
  106. *
  107. * @throws \Drupal\Core\TempStore\TempStoreException
  108. * Thrown when a lock for the backend storage could not be acquired.
  109. */
  110. public function set($key, $value) {
  111. // Ensure that an anonymous user has a session created for them, as
  112. // otherwise subsequent page loads will not be able to retrieve their
  113. // tempstore data.
  114. if ($this->currentUser->isAnonymous()) {
  115. // @todo when https://www.drupal.org/node/2865991 is resolved, use force
  116. // start session API rather than setting an arbitrary value directly.
  117. $this->startSession();
  118. $this->requestStack
  119. ->getCurrentRequest()
  120. ->getSession()
  121. ->set('core.tempstore.private', TRUE);
  122. }
  123. $key = $this->createkey($key);
  124. if (!$this->lockBackend->acquire($key)) {
  125. $this->lockBackend->wait($key);
  126. if (!$this->lockBackend->acquire($key)) {
  127. throw new TempStoreException("Couldn't acquire lock to update item '$key' in '{$this->storage->getCollectionName()}' temporary storage.");
  128. }
  129. }
  130. $value = (object) [
  131. 'owner' => $this->getOwner(),
  132. 'data' => $value,
  133. 'updated' => (int) $this->requestStack->getMasterRequest()->server->get('REQUEST_TIME'),
  134. ];
  135. $this->storage->setWithExpire($key, $value, $this->expire);
  136. $this->lockBackend->release($key);
  137. }
  138. /**
  139. * Returns the metadata associated with a particular key/value pair.
  140. *
  141. * @param string $key
  142. * The key of the data to store.
  143. *
  144. * @return \Drupal\Core\TempStore\Lock|null
  145. * An object with the owner and updated time if the key has a value, or
  146. * NULL otherwise.
  147. */
  148. public function getMetadata($key) {
  149. $key = $this->createkey($key);
  150. // Fetch the key/value pair and its metadata.
  151. $object = $this->storage->get($key);
  152. if ($object) {
  153. // Don't keep the data itself in memory.
  154. unset($object->data);
  155. return new Lock($object->owner, $object->updated);
  156. }
  157. }
  158. /**
  159. * Deletes data from the store for a given key and releases the lock on it.
  160. *
  161. * @param string $key
  162. * The key of the data to delete.
  163. *
  164. * @return bool
  165. * TRUE if the object was deleted or does not exist, FALSE if it exists but
  166. * is not owned by $this->owner.
  167. *
  168. * @throws \Drupal\Core\TempStore\TempStoreException
  169. * Thrown when a lock for the backend storage could not be acquired.
  170. */
  171. public function delete($key) {
  172. $key = $this->createkey($key);
  173. if (!$object = $this->storage->get($key)) {
  174. return TRUE;
  175. }
  176. elseif ($object->owner != $this->getOwner()) {
  177. return FALSE;
  178. }
  179. if (!$this->lockBackend->acquire($key)) {
  180. $this->lockBackend->wait($key);
  181. if (!$this->lockBackend->acquire($key)) {
  182. throw new TempStoreException("Couldn't acquire lock to delete item '$key' from '{$this->storage->getCollectionName()}' temporary storage.");
  183. }
  184. }
  185. $this->storage->delete($key);
  186. $this->lockBackend->release($key);
  187. return TRUE;
  188. }
  189. /**
  190. * Ensures that the key is unique for a user.
  191. *
  192. * @param string $key
  193. * The key.
  194. *
  195. * @return string
  196. * The unique key for the user.
  197. */
  198. protected function createkey($key) {
  199. return $this->getOwner() . ':' . $key;
  200. }
  201. /**
  202. * Gets the current owner based on the current user or the session ID.
  203. *
  204. * @return string
  205. * The owner.
  206. */
  207. protected function getOwner() {
  208. $owner = $this->currentUser->id();
  209. if ($this->currentUser->isAnonymous()) {
  210. $this->startSession();
  211. $owner = $this->requestStack->getCurrentRequest()->getSession()->getId();
  212. }
  213. return $owner;
  214. }
  215. /**
  216. * Start session because it is required for a private temp store.
  217. *
  218. * Ensures that an anonymous user has a session created for them, as
  219. * otherwise subsequent page loads will not be able to retrieve their
  220. * tempstore data.
  221. *
  222. * @todo when https://www.drupal.org/node/2865991 is resolved, use force
  223. * start session API.
  224. */
  225. protected function startSession() {
  226. $has_session = $this->requestStack
  227. ->getCurrentRequest()
  228. ->hasSession();
  229. if (!$has_session) {
  230. /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface $session */
  231. $session = \Drupal::service('session');
  232. $this->requestStack->getCurrentRequest()->setSession($session);
  233. $session->start();
  234. }
  235. }
  236. }