(NFC) (dev/core#878) Simplify copyright header (templates/*)
[civicrm-core.git] / CRM / Core / PrevNextCache / Redis.php
CommitLineData
751f3d98
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
f299f7db 6 | Copyright CiviCRM LLC (c) 2004-2020 |
751f3d98
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28/**
29 * Class CRM_Core_PrevNextCache_Memory
30 *
31 * Store the previous/next cache in a Redis set.
32 *
33 * Each logical prev-next cache corresponds to three distinct items in Redis:
34 * - "{prefix}/{qfKey}/list" - Sorted set of `entity_id`, with all entities
35 * - "{prefix}/{qfkey}/sel" - Sorted set of `entity_id`, with only entities marked by user
36 * - "{prefix}/{qfkey}/data" - Hash mapping from `entity_id` to `data`
37 *
38 * @link https://github.com/phpredis/phpredis
39 */
40class CRM_Core_PrevNextCache_Redis implements CRM_Core_PrevNextCache_Interface {
41
42 const TTL = 21600;
43
44 /**
45 * @var Redis
46 */
47 protected $redis;
48
49 /**
50 * @var string
51 */
52 protected $prefix;
53
54 /**
55 * CRM_Core_PrevNextCache_Redis constructor.
56 * @param array $settings
57 */
58 public function __construct($settings) {
59 $this->redis = CRM_Utils_Cache_Redis::connect($settings);
60 $this->prefix = isset($settings['prefix']) ? $settings['prefix'] : '';
61 $this->prefix .= \CRM_Utils_Cache::DELIMITER . 'prevnext' . \CRM_Utils_Cache::DELIMITER;
62 }
63
2c8b42d5
SL
64 public function fillWithSql($cacheKey, $sql, $sqlParams = []) {
65 $dao = CRM_Core_DAO::executeQuery($sql, $sqlParams, FALSE, NULL, FALSE, TRUE, TRUE);
751f3d98
TO
66 if (is_a($dao, 'DB_Error')) {
67 throw new CRM_Core_Exception($dao->message);
68 }
69
70 list($allKey, $dataKey, , $maxScore) = $this->initCacheKey($cacheKey);
71
72 while ($dao->fetch()) {
73 list (, $entity_id, $data) = array_values($dao->toArray());
74 $maxScore++;
75 $this->redis->zAdd($allKey, $maxScore, $entity_id);
76 $this->redis->hSet($dataKey, $entity_id, $data);
77 }
78
751f3d98
TO
79 return TRUE;
80 }
81
82 public function fillWithArray($cacheKey, $rows) {
83 list($allKey, $dataKey, , $maxScore) = $this->initCacheKey($cacheKey);
84
85 foreach ($rows as $row) {
86 $maxScore++;
87 $this->redis->zAdd($allKey, $maxScore, $row['entity_id1']);
88 $this->redis->hSet($dataKey, $row['entity_id1'], $row['data']);
89 }
90
91 return TRUE;
92 }
93
94 public function fetch($cacheKey, $offset, $rowCount) {
95 $allKey = $this->key($cacheKey, 'all');
96 return $this->redis->zRange($allKey, $offset, $offset + $rowCount - 1);
97 }
98
99 public function markSelection($cacheKey, $action, $ids = NULL) {
100 $allKey = $this->key($cacheKey, 'all');
101 $selKey = $this->key($cacheKey, 'sel');
102
103 if ($action === 'select') {
104 foreach ((array) $ids as $id) {
105 $score = $this->redis->zScore($allKey, $id);
106 $this->redis->zAdd($selKey, $score, $id);
107 }
108 }
109 elseif ($action === 'unselect' && $ids === NULL) {
110 $this->redis->delete($selKey);
111 $this->redis->setTimeout($selKey, self::TTL);
112 }
113 elseif ($action === 'unselect' && $ids !== NULL) {
114 foreach ((array) $ids as $id) {
115 $this->redis->zDelete($selKey, $id);
116 }
117 }
118 }
119
120 public function getSelection($cacheKey, $action = 'get') {
121 $allKey = $this->key($cacheKey, 'all');
122 $selKey = $this->key($cacheKey, 'sel');
123
124 if ($action === 'get') {
125 $result = [];
126 foreach ($this->redis->zRange($selKey, 0, -1) as $entity_id) {
127 $result[$entity_id] = 1;
128 }
129 return [$cacheKey => $result];
130 }
131 elseif ($action === 'getall') {
132 $result = [];
133 foreach ($this->redis->zRange($allKey, 0, -1) as $entity_id) {
134 $result[$entity_id] = 1;
135 }
136 return [$cacheKey => $result];
137 }
138 else {
139 throw new \CRM_Core_Exception("Unrecognized action: $action");
140 }
141 }
142
143 public function getPositions($cacheKey, $id1) {
144 $allKey = $this->key($cacheKey, 'all');
145 $dataKey = $this->key($cacheKey, 'data');
146
147 $rank = $this->redis->zRank($allKey, $id1);
148 if (!is_int($rank) || $rank < 0) {
149 return ['foundEntry' => 0];
150 }
151
152 $pos = ['foundEntry' => 1];
153
154 if ($rank > 0) {
155 $pos['prev'] = [];
156 foreach ($this->redis->zRange($allKey, $rank - 1, $rank - 1) as $value) {
157 $pos['prev']['id1'] = $value;
158 }
159 $pos['prev']['data'] = $this->redis->hGet($dataKey, $pos['prev']['id1']);
160 }
161
162 $count = $this->getCount($cacheKey);
163 if ($count > $rank + 1) {
164 $pos['next'] = [];
165 foreach ($this->redis->zRange($allKey, $rank + 1, $rank + 1) as $value) {
166 $pos['next']['id1'] = $value;
167 }
168 $pos['next']['data'] = $this->redis->hGet($dataKey, $pos['next']['id1']);
169 }
170
171 return $pos;
172 }
173
174 public function deleteItem($id = NULL, $cacheKey = NULL) {
175 if ($id === NULL && $cacheKey !== NULL) {
176 // Delete by cacheKey.
177 $allKey = $this->key($cacheKey, 'all');
178 $selKey = $this->key($cacheKey, 'sel');
179 $dataKey = $this->key($cacheKey, 'data');
180 $this->redis->delete($allKey, $selKey, $dataKey);
181 }
182 elseif ($id === NULL && $cacheKey === NULL) {
183 // Delete everything.
184 $keys = $this->redis->keys($this->prefix . '*');
185 $this->redis->del($keys);
186 }
187 elseif ($id !== NULL && $cacheKey !== NULL) {
188 // Delete a specific contact, within a specific cache.
189 $this->redis->zDelete($this->key($cacheKey, 'all'), $id);
190 $this->redis->zDelete($this->key($cacheKey, 'sel'), $id);
191 $this->redis->hDel($this->key($cacheKey, 'data'), $id);
192 }
193 elseif ($id !== NULL && $cacheKey === NULL) {
194 // Delete a specific contact, across all prevnext caches.
195 $allKeys = $this->redis->keys($this->key('*', 'all'));
196 foreach ($allKeys as $allKey) {
197 $parts = explode(\CRM_Utils_Cache::DELIMITER, $allKey);
198 array_pop($parts);
199 $tmpCacheKey = array_pop($parts);
200 $this->deleteItem($id, $tmpCacheKey);
201 }
202 }
203 else {
204 throw new CRM_Core_Exception("Not implemented: Redis::deleteItem");
205 }
206 }
207
208 public function getCount($cacheKey) {
209 $allKey = $this->key($cacheKey, 'all');
210 return $this->redis->zSize($allKey);
211 }
212
213 /**
214 * Construct the full path to a cache item.
215 *
216 * @param string $cacheKey
217 * Identifier for this saved search.
218 * Ex: 'abcd1234abcd1234'.
219 * @param string $item
220 * Ex: 'list', 'rel', 'data'.
221 * @return string
222 * Ex: 'dmaster/prevnext/abcd1234abcd1234/list'
223 */
224 private function key($cacheKey, $item) {
225 return $this->prefix . $cacheKey . \CRM_Utils_Cache::DELIMITER . $item;
226 }
227
228 /**
229 * Initialize any data-structures or timeouts for the cache-key.
230 *
231 * This is non-destructive -- if data already exists, it's preserved.
232 *
233 * @return array
234 * 0 => string $allItemsCacheKey,
235 * 1 => string $dataItemsCacheKey,
236 * 2 => string $selectedItemsCacheKey,
237 * 3 => int $maxExistingScore
238 */
239 private function initCacheKey($cacheKey) {
240 $allKey = $this->key($cacheKey, 'all');
241 $selKey = $this->key($cacheKey, 'sel');
242 $dataKey = $this->key($cacheKey, 'data');
243
244 $this->redis->setTimeout($allKey, self::TTL);
245 $this->redis->setTimeout($dataKey, self::TTL);
246 $this->redis->setTimeout($selKey, self::TTL);
247
248 $maxScore = 0;
249 foreach ($this->redis->zRange($allKey, -1, -1, TRUE) as $lastElem => $lastScore) {
250 $maxScore = $lastScore;
251 }
be2fb01f 252 return [$allKey, $dataKey, $selKey, $maxScore];
751f3d98
TO
253 }
254
435fc552
SL
255 /**
256 * @inheritDoc
257 */
258 public function cleanup() {
259 // Redis already handles cleaning up stale keys.
260 return;
261 }
262
751f3d98 263}