Merge pull request #14605 from eileenmcnaughton/cust_deadlock
[civicrm-core.git] / CRM / Core / BAO / PrevNextCache.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * BAO object for civicrm_prevnext_cache table.
36 */
37 class CRM_Core_BAO_PrevNextCache extends CRM_Core_DAO_PrevNextCache {
38
39 /**
40 * Get the previous and next keys.
41 *
42 * @param string $cacheKey
43 * @param int $id1
44 * @param int $id2
45 * @param int $mergeId
46 * @param string $join
47 * @param string $where
48 * @param bool $flip
49 *
50 * @return array
51 */
52 public static function getPositions($cacheKey, $id1, $id2, &$mergeId = NULL, $join = NULL, $where = NULL, $flip = FALSE) {
53 if ($flip) {
54 list($id1, $id2) = [$id2, $id1];
55 }
56
57 if ($mergeId == NULL) {
58 $query = "
59 SELECT id
60 FROM civicrm_prevnext_cache
61 WHERE cachekey = %3 AND
62 entity_id1 = %1 AND
63 entity_id2 = %2 AND
64 entity_table = 'civicrm_contact'
65 ";
66
67 $params = [
68 1 => [$id1, 'Integer'],
69 2 => [$id2, 'Integer'],
70 3 => [$cacheKey, 'String'],
71 ];
72
73 $mergeId = CRM_Core_DAO::singleValueQuery($query, $params);
74 }
75
76 $pos = ['foundEntry' => 0];
77 if ($mergeId) {
78 $pos['foundEntry'] = 1;
79
80 if ($where) {
81
82 $where = " AND {$where}";
83
84 }
85 $p = [
86 1 => [$mergeId, 'Integer'],
87 2 => [$cacheKey, 'String'],
88 ];
89 $sql = "SELECT pn.id, pn.entity_id1, pn.entity_id2, pn.data FROM civicrm_prevnext_cache pn {$join} ";
90 $wherePrev = " WHERE pn.id < %1 AND pn.cachekey = %2 {$where} ORDER BY ID DESC LIMIT 1";
91 $sqlPrev = $sql . $wherePrev;
92
93 $dao = CRM_Core_DAO::executeQuery($sqlPrev, $p);
94 if ($dao->fetch()) {
95 $pos['prev']['id1'] = $dao->entity_id1;
96 $pos['prev']['id2'] = $dao->entity_id2;
97 $pos['prev']['mergeId'] = $dao->id;
98 $pos['prev']['data'] = $dao->data;
99 }
100
101 $whereNext = " WHERE pn.id > %1 AND pn.cachekey = %2 {$where} ORDER BY ID ASC LIMIT 1";
102 $sqlNext = $sql . $whereNext;
103
104 $dao = CRM_Core_DAO::executeQuery($sqlNext, $p);
105 if ($dao->fetch()) {
106 $pos['next']['id1'] = $dao->entity_id1;
107 $pos['next']['id2'] = $dao->entity_id2;
108 $pos['next']['mergeId'] = $dao->id;
109 $pos['next']['data'] = $dao->data;
110 }
111 }
112 return $pos;
113 }
114
115 /**
116 * Delete an item from the prevnext cache table based on the entity.
117 *
118 * @param int $id
119 * @param string $cacheKey
120 * @param string $entityTable
121 */
122 public static function deleteItem($id = NULL, $cacheKey = NULL, $entityTable = 'civicrm_contact') {
123
124 //clear cache
125 $sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = %1";
126 $params = [1 => [$entityTable, 'String']];
127
128 if (is_numeric($id)) {
129 $sql .= " AND ( entity_id1 = %2 OR entity_id2 = %2 )";
130 $params[2] = [$id, 'Integer'];
131 }
132
133 if (isset($cacheKey)) {
134 $sql .= " AND cachekey LIKE %3";
135 $params[3] = ["{$cacheKey}%", 'String'];
136 }
137 CRM_Core_DAO::executeQuery($sql, $params);
138 }
139
140 /**
141 * Delete pair from the previous next cache table to remove it from further merge consideration.
142 *
143 * The pair may have been flipped, so make sure we delete using both orders
144 *
145 * @param int $id1
146 * @param int $id2
147 * @param string $cacheKey
148 */
149 public static function deletePair($id1, $id2, $cacheKey = NULL) {
150 $sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = 'civicrm_contact'";
151
152 $pair = "(entity_id1 = %2 AND entity_id2 = %3) OR (entity_id1 = %3 AND entity_id2 = %2)";
153 $sql .= " AND ( {$pair} )";
154 $params[2] = [$id1, 'Integer'];
155 $params[3] = [$id2, 'Integer'];
156
157 if (isset($cacheKey)) {
158 $sql .= " AND cachekey LIKE %4";
159 // used % to address any row with conflict-cacheKey e.g "merge Individual_8_0_conflicts"
160 $params[4] = ["{$cacheKey}%", 'String'];
161 }
162
163 CRM_Core_DAO::executeQuery($sql, $params);
164 }
165
166 /**
167 * Mark contacts as being in conflict.
168 *
169 * @param int $id1
170 * @param int $id2
171 * @param string $cacheKey
172 * @param array $conflicts
173 *
174 * @return bool
175 */
176 public static function markConflict($id1, $id2, $cacheKey, $conflicts) {
177 if (empty($cacheKey) || empty($conflicts)) {
178 return FALSE;
179 }
180
181 $sql = "SELECT pn.*
182 FROM civicrm_prevnext_cache pn
183 WHERE
184 ((pn.entity_id1 = %1 AND pn.entity_id2 = %2) OR (pn.entity_id1 = %2 AND pn.entity_id2 = %1)) AND
185 (cachekey = %3 OR cachekey = %4)";
186 $params = [
187 1 => [$id1, 'Integer'],
188 2 => [$id2, 'Integer'],
189 3 => ["{$cacheKey}", 'String'],
190 4 => ["{$cacheKey}_conflicts", 'String'],
191 ];
192 $pncFind = CRM_Core_DAO::executeQuery($sql, $params);
193
194 while ($pncFind->fetch()) {
195 $data = $pncFind->data;
196 if (!empty($data)) {
197 $data = unserialize($data);
198 $data['conflicts'] = implode(",", array_values($conflicts));
199
200 $pncUp = new CRM_Core_DAO_PrevNextCache();
201 $pncUp->id = $pncFind->id;
202 if ($pncUp->find(TRUE)) {
203 $pncUp->data = serialize($data);
204 $pncUp->cachekey = "{$cacheKey}_conflicts";
205 $pncUp->save();
206 }
207 }
208 }
209 return TRUE;
210 }
211
212 /**
213 * Retrieve from prev-next cache.
214 *
215 * This function is used from a variety of merge related functions, although
216 * it would probably be good to converge on calling CRM_Dedupe_Merger::getDuplicatePairs.
217 *
218 * We seem to currently be storing stats in this table too & they might make more sense in
219 * the main cache table.
220 *
221 * @param string $cacheKey
222 * @param string $join
223 * @param string $whereClause
224 * @param int $offset
225 * @param int $rowCount
226 * @param array $select
227 * @param string $orderByClause
228 * @param bool $includeConflicts
229 * Should we return rows that have already been idenfified as having a conflict.
230 * When this is TRUE you should be careful you do not set up a loop.
231 * @param array $params
232 *
233 * @return array
234 */
235 public static function retrieve($cacheKey, $join = NULL, $whereClause = NULL, $offset = 0, $rowCount = 0, $select = [], $orderByClause = '', $includeConflicts = TRUE, $params = []) {
236 $selectString = 'pn.*';
237
238 if (!empty($select)) {
239 $aliasArray = [];
240 foreach ($select as $column => $alias) {
241 $aliasArray[] = $column . ' as ' . $alias;
242 }
243 $selectString .= " , " . implode(' , ', $aliasArray);
244 }
245
246 $params = [
247 1 => [$cacheKey, 'String'],
248 ] + $params;
249
250 if (!empty($whereClause)) {
251 $whereClause = " AND " . $whereClause;
252 }
253 if ($includeConflicts) {
254 $where = ' WHERE (pn.cachekey = %1 OR pn.cachekey = %2)' . $whereClause;
255 $params[2] = ["{$cacheKey}_conflicts", 'String'];
256 }
257 else {
258 $where = ' WHERE (pn.cachekey = %1)' . $whereClause;
259 }
260
261 $query = "
262 SELECT SQL_CALC_FOUND_ROWS {$selectString}
263 FROM civicrm_prevnext_cache pn
264 {$join}
265 $where
266 $orderByClause
267 ";
268
269 if ($rowCount) {
270 $offset = CRM_Utils_Type::escape($offset, 'Int');
271 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
272
273 $query .= " LIMIT {$offset}, {$rowCount}";
274 }
275
276 $dao = CRM_Core_DAO::executeQuery($query, $params);
277
278 $main = [];
279 $count = 0;
280 while ($dao->fetch()) {
281 if (self::is_serialized($dao->data)) {
282 $main[$count] = unserialize($dao->data);
283 }
284 else {
285 $main[$count] = $dao->data;
286 }
287
288 if (!empty($select)) {
289 $extraData = [];
290 foreach ($select as $sfield) {
291 $extraData[$sfield] = $dao->$sfield;
292 }
293 $main[$count] = [
294 'prevnext_id' => $dao->id,
295 'is_selected' => $dao->is_selected,
296 'entity_id1' => $dao->entity_id1,
297 'entity_id2' => $dao->entity_id2,
298 'data' => $main[$count],
299 ];
300 $main[$count] = array_merge($main[$count], $extraData);
301 }
302 $count++;
303 }
304
305 return $main;
306 }
307
308 /**
309 * @param $string
310 *
311 * @return bool
312 */
313 public static function is_serialized($string) {
314 return (@unserialize($string) !== FALSE);
315 }
316
317 /**
318 * @param $values
319 */
320 public static function setItem($values) {
321 $insert = "INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cachekey, data ) VALUES \n";
322 $query = $insert . implode(",\n ", $values);
323
324 //dump the dedupe matches in the prevnext_cache table
325 CRM_Core_DAO::executeQuery($query);
326 }
327
328 /**
329 * Get count of matching rows.
330 *
331 * @param string $cacheKey
332 * @param string $join
333 * @param string $where
334 * @param string $op
335 * @param array $params
336 * Extra query params to parse into the query.
337 *
338 * @return int
339 */
340 public static function getCount($cacheKey, $join = NULL, $where = NULL, $op = "=", $params = []) {
341 $query = "
342 SELECT COUNT(*) FROM civicrm_prevnext_cache pn
343 {$join}
344 WHERE (pn.cachekey $op %1 OR pn.cachekey $op %2)
345 ";
346 if ($where) {
347 $query .= " AND {$where}";
348 }
349
350 $params = [
351 1 => [$cacheKey, 'String'],
352 2 => ["{$cacheKey}_conflicts", 'String'],
353 ] + $params;
354 return (int) CRM_Core_DAO::singleValueQuery($query, $params, TRUE, FALSE);
355 }
356
357 /**
358 * Repopulate the cache of merge prospects.
359 *
360 * @param int $rgid
361 * @param int $gid
362 * @param array $criteria
363 * Additional criteria to filter by.
364 *
365 * @param bool $checkPermissions
366 * Respect logged in user's permissions.
367 *
368 * @param int $searchLimit
369 * Limit for the number of contacts to be used for comparison.
370 * The search methodology finds all matches for the searchedContacts so this limits
371 * the number of searched contacts, not the matches found.
372 *
373 * @throws \CRM_Core_Exception
374 * @throws \CiviCRM_API3_Exception
375 */
376 public static function refillCache($rgid, $gid, $criteria, $checkPermissions, $searchLimit = 0) {
377 $cacheKeyString = CRM_Dedupe_Merger::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions);
378
379 // 1. Clear cache if any
380 $sql = "DELETE FROM civicrm_prevnext_cache WHERE cachekey LIKE %1";
381 CRM_Core_DAO::executeQuery($sql, [1 => ["{$cacheKeyString}%", 'String']]);
382
383 // FIXME: we need to start using temp tables / queries here instead of arrays.
384 // And cleanup code in CRM/Contact/Page/DedupeFind.php
385
386 // 2. FILL cache
387 $foundDupes = [];
388 if ($rgid && $gid) {
389 $foundDupes = CRM_Dedupe_Finder::dupesInGroup($rgid, $gid, $searchLimit);
390 }
391 elseif ($rgid) {
392 $contactIDs = [];
393 // The thing we really need to filter out is any chaining that would 'DO SOMETHING' to the DB.
394 // criteria could be passed in via url so we want to ensure nothing could be in that url that
395 // would chain to a delete. Limiting to getfields for 'get' limits us to declared fields,
396 // although we might wish to revisit later to allow joins.
397 $validFieldsForRetrieval = civicrm_api3('Contact', 'getfields', ['action' => 'get'])['values'];
398 if (!empty($criteria)) {
399 $contacts = civicrm_api3('Contact', 'get', array_merge([
400 'options' => ['limit' => 0],
401 'return' => 'id',
402 'check_permissions' => TRUE,
403 ], array_intersect_key($criteria['contact'], $validFieldsForRetrieval)));
404 $contactIDs = array_keys($contacts['values']);
405 }
406 $foundDupes = CRM_Dedupe_Finder::dupes($rgid, $contactIDs, $checkPermissions, $searchLimit);
407 }
408
409 if (!empty($foundDupes)) {
410 CRM_Dedupe_Finder::parseAndStoreDupePairs($foundDupes, $cacheKeyString);
411 }
412 }
413
414 public static function cleanupCache() {
415 // clean up all prev next caches older than $cacheTimeIntervalDays days
416 $cacheTimeIntervalDays = 2;
417
418 // first find all the cacheKeys that match this
419 $sql = "
420 DELETE pn, c
421 FROM civicrm_cache c
422 INNER JOIN civicrm_prevnext_cache pn ON c.path = pn.cachekey
423 WHERE c.group_name = %1
424 AND c.created_date < date_sub( NOW( ), INTERVAL %2 day )
425 ";
426 $params = [
427 1 => [CRM_Core_BAO_Cache::cleanKey('CiviCRM Search PrevNextCache'), 'String'],
428 2 => [$cacheTimeIntervalDays, 'Integer'],
429 ];
430 CRM_Core_DAO::executeQuery($sql, $params);
431 }
432
433 /**
434 * Get the selections.
435 *
436 * NOTE: This stub has been preserved because one extension in `universe`
437 * was referencing the function.
438 *
439 * @deprecated
440 * @see CRM_Core_PrevNextCache_Sql::getSelection()
441 */
442 public static function getSelection($cacheKey, $action = 'get') {
443 return Civi::service('prevnext')->getSelection($cacheKey, $action);
444 }
445
446 /**
447 * Flip 2 contacts in the prevNext cache.
448 *
449 * @param array $prevNextId
450 * @param bool $onlySelected
451 * Only flip those which have been marked as selected.
452 */
453 public static function flipPair(array $prevNextId, $onlySelected) {
454 $dao = new CRM_Core_DAO_PrevNextCache();
455 if ($onlySelected) {
456 $dao->is_selected = 1;
457 }
458 foreach ($prevNextId as $id) {
459 $dao->id = $id;
460 if ($dao->find(TRUE)) {
461 $originalData = unserialize($dao->data);
462 $srcFields = ['ID', 'Name'];
463 $swapFields = ['srcID', 'srcName', 'dstID', 'dstName'];
464 $data = array_diff_assoc($originalData, array_fill_keys($swapFields, 1));
465 foreach ($srcFields as $key) {
466 $data['src' . $key] = $originalData['dst' . $key];
467 $data['dst' . $key] = $originalData['src' . $key];
468 }
469 $dao->data = serialize($data);
470 $dao->entity_id1 = $data['dstID'];
471 $dao->entity_id2 = $data['srcID'];
472 $dao->save();
473 }
474 }
475 }
476
477 /**
478 * Get a list of available backend services.
479 *
480 * @return array
481 * Array(string $id => string $label).
482 */
483 public static function getPrevNextBackends() {
484 return [
485 'default' => ts('Default (Auto-detect)'),
486 'sql' => ts('SQL'),
487 'redis' => ts('Redis'),
488 ];
489 }
490
491 /**
492 * Generate and assign an arbitrary value to a field of a test object.
493 *
494 * This specifically supports testing the dedupe use case.
495 *
496 * @param string $fieldName
497 * @param array $fieldDef
498 * @param int $counter
499 * The globally-unique ID of the test object.
500 */
501 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
502 if ($fieldName === 'cachekey') {
503 $this->cachekey = 'merge_' . rand();
504 return;
505 }
506 if ($fieldName === 'data') {
507 $this->data = serialize([]);
508 return;
509 }
510 parent::assignTestValue($fieldName, $fieldDef, $counter);
511 }
512
513 }