PrivateTempStore.php 7.8 KB

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