3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
35 * BAO object for civicrm_prevnext_cache table.
37 class CRM_Core_BAO_PrevNextCache
extends CRM_Core_DAO_PrevNextCache
{
40 * Get the previous and next keys.
42 * @param string $cacheKey
47 * @param string $where
52 public static function getPositions($cacheKey, $id1, $id2, &$mergeId = NULL, $join = NULL, $where = NULL, $flip = FALSE) {
54 list($id1, $id2) = array($id2, $id1);
57 if ($mergeId == NULL) {
60 FROM civicrm_prevnext_cache
61 WHERE cacheKey = %3 AND
64 entity_table = 'civicrm_contact'
68 1 => array($id1, 'Integer'),
69 2 => array($id2, 'Integer'),
70 3 => array($cacheKey, 'String'),
73 $mergeId = CRM_Core_DAO
::singleValueQuery($query, $params);
76 $pos = array('foundEntry' => 0);
78 $pos['foundEntry'] = 1;
82 $where = " AND {$where}";
86 1 => array($mergeId, 'Integer'),
87 2 => array($cacheKey, 'String'),
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;
93 $dao = CRM_Core_DAO
::executeQuery($sqlPrev, $p);
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
;
101 $whereNext = " WHERE pn.id > %1 AND pn.cacheKey = %2 {$where} ORDER BY ID ASC LIMIT 1";
102 $sqlNext = $sql . $whereNext;
104 $dao = CRM_Core_DAO
::executeQuery($sqlNext, $p);
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
;
116 * Delete an item from the prevnext cache table based on the entity.
119 * @param string $cacheKey
120 * @param string $entityTable
122 public static function deleteItem($id = NULL, $cacheKey = NULL, $entityTable = 'civicrm_contact') {
125 $sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = %1";
126 $params = array(1 => array($entityTable, 'String'));
128 if (is_numeric($id)) {
129 $sql .= " AND ( entity_id1 = %2 OR entity_id2 = %2 )";
130 $params[2] = array($id, 'Integer');
133 if (isset($cacheKey)) {
134 $sql .= " AND cacheKey LIKE %3";
135 $params[3] = array("{$cacheKey}%", 'String');
137 CRM_Core_DAO
::executeQuery($sql, $params);
141 * Delete from the previous next cache table for a pair of ids.
145 * @param string $cacheKey
146 * @param bool $isViceVersa
147 * @param string $entityTable
149 public static function deletePair($id1, $id2, $cacheKey = NULL, $isViceVersa = FALSE, $entityTable = 'civicrm_contact') {
150 $sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = %1";
151 $params = array(1 => array($entityTable, 'String'));
153 $pair = !$isViceVersa ?
"entity_id1 = %2 AND entity_id2 = %3" : "(entity_id1 = %2 AND entity_id2 = %3) OR (entity_id1 = %3 AND entity_id2 = %2)";
154 $sql .= " AND ( {$pair} )";
155 $params[2] = array($id1, 'Integer');
156 $params[3] = array($id2, 'Integer');
158 if (isset($cacheKey)) {
159 $sql .= " AND cacheKey LIKE %4";
160 $params[4] = array("{$cacheKey}%", 'String'); // used % to address any row with conflict-cacheKey e.g "merge Individual_8_0_conflicts"
163 CRM_Core_DAO
::executeQuery($sql, $params);
167 * Mark contacts as being in conflict.
171 * @param string $cacheKey
172 * @param array $conflicts
176 public static function markConflict($id1, $id2, $cacheKey, $conflicts) {
177 if (empty($cacheKey) ||
empty($conflicts)) {
182 FROM civicrm_prevnext_cache pn
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)";
187 1 => array($id1, 'Integer'),
188 2 => array($id2, 'Integer'),
189 3 => array("{$cacheKey}", 'String'),
190 4 => array("{$cacheKey}_conflicts", 'String'),
192 $pncFind = CRM_Core_DAO
::executeQuery($sql, $params);
194 while ($pncFind->fetch()) {
195 $data = $pncFind->data
;
197 $data = unserialize($data);
198 $data['conflicts'] = implode(",", array_values($conflicts));
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";
213 * Retrieve from prev-next cache.
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.
218 * We seem to currently be storing stats in this table too & they might make more sense in
219 * the main cache table.
221 * @param string $cacheKey
222 * @param string $join
223 * @param string $whereClause
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
235 public static function retrieve($cacheKey, $join = NULL, $whereClause = NULL, $offset = 0, $rowCount = 0, $select = array(), $orderByClause = '', $includeConflicts = TRUE, $params = array()) {
236 $selectString = 'pn.*';
238 if (!empty($select)) {
239 $aliasArray = array();
240 foreach ($select as $column => $alias) {
241 $aliasArray[] = $column . ' as ' . $alias;
243 $selectString .= " , " . implode(' , ', $aliasArray);
247 1 => array($cacheKey, 'String'),
250 if (!empty($whereClause)) {
251 $whereClause = " AND " . $whereClause;
253 if ($includeConflicts) {
254 $where = ' WHERE (pn.cacheKey = %1 OR pn.cacheKey = %2)' . $whereClause;
255 $params[2] = array("{$cacheKey}_conflicts", 'String');
258 $where = ' WHERE (pn.cacheKey = %1)' . $whereClause;
262 SELECT SQL_CALC_FOUND_ROWS {$selectString}
263 FROM civicrm_prevnext_cache pn
270 $offset = CRM_Utils_Type
::escape($offset, 'Int');
271 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
273 $query .= " LIMIT {$offset}, {$rowCount}";
276 $dao = CRM_Core_DAO
::executeQuery($query, $params);
280 while ($dao->fetch()) {
281 if (self
::is_serialized($dao->data
)) {
282 $main[$count] = unserialize($dao->data
);
285 $main[$count] = $dao->data
;
288 if (!empty($select)) {
289 $extraData = array();
290 foreach ($select as $sfield) {
291 $extraData[$sfield] = $dao->$sfield;
293 $main[$count] = array(
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],
300 $main[$count] = array_merge($main[$count], $extraData);
313 public static function is_serialized($string) {
314 return (@unserialize
($string) !== FALSE);
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);
324 //dump the dedupe matches in the prevnext_cache table
325 CRM_Core_DAO
::executeQuery($query);
329 * Get count of matching rows.
331 * @param string $cacheKey
332 * @param string $join
333 * @param string $where
335 * @param array $params
336 * Extra query params to parse into the query.
340 public static function getCount($cacheKey, $join = NULL, $where = NULL, $op = "=", $params = array()) {
342 SELECT COUNT(*) FROM civicrm_prevnext_cache pn
344 WHERE (pn.cacheKey $op %1 OR pn.cacheKey $op %2)
347 $query .= " AND {$where}";
351 1 => array($cacheKey, 'String'),
352 2 => array("{$cacheKey}_conflicts", 'String'),
354 return (int) CRM_Core_DAO
::singleValueQuery($query, $params, TRUE, FALSE);
358 * Repopulate the cache of merge prospects.
362 * @param NULL $cacheKeyString
363 * @param array $criteria
364 * Additional criteria to filter by.
366 * @param bool $checkPermissions
367 * Respect logged in user's permissions.
369 * @param int $searchLimit
370 * Limit for the number of contacts to be used for comparison.
371 * The search methodology finds all matches for the searchedContacts so this limits
372 * the number of searched contacts, not the matches found.
375 * @throws \CRM_Core_Exception
376 * @throws \CiviCRM_API3_Exception
378 public static function refillCache($rgid, $gid, $cacheKeyString, $criteria, $checkPermissions, $searchLimit = 0) {
379 if (!$cacheKeyString && $rgid) {
380 $cacheKeyString = CRM_Dedupe_Merger
::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions);
383 if (!$cacheKeyString) {
387 // 1. Clear cache if any
388 $sql = "DELETE FROM civicrm_prevnext_cache WHERE cacheKey LIKE %1";
389 CRM_Core_DAO
::executeQuery($sql, array(1 => array("{$cacheKeyString}%", 'String')));
391 // FIXME: we need to start using temp tables / queries here instead of arrays.
392 // And cleanup code in CRM/Contact/Page/DedupeFind.php
395 $foundDupes = array();
397 $foundDupes = CRM_Dedupe_Finder
::dupesInGroup($rgid, $gid, $searchLimit);
400 $contactIDs = array();
401 if (!empty($criteria)) {
402 $contacts = civicrm_api3('Contact', 'get', array_merge(array('options' => array('limit' => 0), 'return' => 'id'), $criteria['contact']));
403 $contactIDs = array_keys($contacts['values']);
405 $foundDupes = CRM_Dedupe_Finder
::dupes($rgid, $contactIDs, $checkPermissions, $searchLimit);
408 if (!empty($foundDupes)) {
409 CRM_Dedupe_Finder
::parseAndStoreDupePairs($foundDupes, $cacheKeyString);
413 public static function cleanupCache() {
414 // clean up all prev next caches older than $cacheTimeIntervalDays days
415 $cacheTimeIntervalDays = 2;
417 // first find all the cacheKeys that match this
421 INNER JOIN civicrm_prevnext_cache pn ON c.path = pn.cacheKey
422 WHERE c.group_name = %1
423 AND c.created_date < date_sub( NOW( ), INTERVAL %2 day )
426 1 => array('CiviCRM Search PrevNextCache', 'String'),
427 2 => array($cacheTimeIntervalDays, 'Integer'),
429 CRM_Core_DAO
::executeQuery($sql, $params);
433 * Save checkbox selections.
436 * @param string $action
438 * @param string $entity_table
440 public static function markSelection($cacheKey, $action = 'unselect', $cIds = NULL, $entity_table = 'civicrm_contact') {
446 $entity_whereClause = " AND entity_table = '{$entity_table}'";
447 if ($cIds && $cacheKey && $action) {
448 if (is_array($cIds)) {
449 $cIdFilter = "(" . implode(',', $cIds) . ")";
451 WHERE cacheKey LIKE %1
452 AND (entity_id1 IN {$cIdFilter} OR entity_id2 IN {$cIdFilter})
457 WHERE cacheKey LIKE %1
458 AND (entity_id1 = %2 OR entity_id2 = %2)
460 $params[2] = array("{$cIds}", 'Integer');
462 if ($action == 'select') {
463 $whereClause .= "AND is_selected = 0";
464 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = 1 {$whereClause} {$entity_whereClause}";
465 $params[1] = array("{$cacheKey}%", 'String');
467 elseif ($action == 'unselect') {
468 $whereClause .= "AND is_selected = 1";
469 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = 0 {$whereClause} {$entity_whereClause}";
470 $params[1] = array("%{$cacheKey}%", 'String');
472 // default action is reseting
474 elseif (!$cIds && $cacheKey && $action == 'unselect') {
476 UPDATE civicrm_prevnext_cache
478 WHERE cacheKey LIKE %1 AND is_selected = 1
479 {$entity_whereClause}
481 $params[1] = array("{$cacheKey}%", 'String');
483 CRM_Core_DAO
::executeQuery($sql, $params);
487 * Get the selections.
489 * @param string $cacheKey
491 * @param string $action
493 * $action : get - get only selection records
494 * getall - get all the records of the specified cache key
495 * @param string $entity_table
500 public static function getSelection($cacheKey, $action = 'get', $entity_table = 'civicrm_contact') {
506 $entity_whereClause = " AND entity_table = '{$entity_table}'";
507 if ($cacheKey && ($action == 'get' ||
$action == 'getall')) {
508 $actionGet = ($action == "get") ?
" AND is_selected = 1 " : "";
510 SELECT entity_id1, entity_id2 FROM civicrm_prevnext_cache
511 WHERE cacheKey LIKE %1
516 $params[1] = array("{$cacheKey}%", 'String');
518 $contactIds = array($cacheKey => array());
519 $cIdDao = CRM_Core_DAO
::executeQuery($sql, $params);
520 while ($cIdDao->fetch()) {
521 if ($cIdDao->entity_id1
== $cIdDao->entity_id2
) {
522 $contactIds[$cacheKey][$cIdDao->entity_id1
] = 1;
532 public static function getSelectedContacts() {
533 $qfKey = CRM_Utils_Request
::retrieve('qfKey', 'String');
534 $cacheKey = "civicrm search {$qfKey}";
537 FROM civicrm_prevnext_cache
538 WHERE cacheKey LIKE %1
540 AND cacheKey NOT LIKE %2
542 $params1[1] = array("{$cacheKey}%", 'String');
543 $params1[2] = array("{$cacheKey}_alphabet%", 'String');
544 $dao = CRM_Core_DAO
::executeQuery($query, $params1);
547 while ($dao->fetch()) {
554 * @param CRM_Core_Form $form
555 * @param array $params
559 public static function buildSelectedContactPager(&$form, &$params) {
560 $params['status'] = ts('Contacts %%StatusMessage%%');
561 $params['csvString'] = NULL;
562 $params['buttonTop'] = 'PagerTopButton';
563 $params['buttonBottom'] = 'PagerBottomButton';
564 $params['rowCount'] = $form->get(CRM_Utils_Pager
::PAGE_ROWCOUNT
);
566 if (!$params['rowCount']) {
567 $params['rowCount'] = CRM_Utils_Pager
::ROWCOUNT
;
570 $qfKey = CRM_Utils_Request
::retrieve('qfKey', 'String', $form);
571 $cacheKey = "civicrm search {$qfKey}";
575 FROM civicrm_prevnext_cache
576 WHERE cacheKey LIKE %1
578 AND cacheKey NOT LIKE %2
580 $params1[1] = array("{$cacheKey}%", 'String');
581 $params1[2] = array("{$cacheKey}_alphabet%", 'String');
582 $paramsTotal = CRM_Core_DAO
::singleValueQuery($query, $params1);
583 $params['total'] = $paramsTotal;
584 $form->_pager
= new CRM_Utils_Pager($params);
585 $form->assign_by_ref('pager', $form->_pager
);
586 list($offset, $rowCount) = $form->_pager
->getOffsetAndRowCount();
587 $params['offset'] = $offset;
588 $params['rowCount1'] = $rowCount;
593 * Flip 2 contacts in the prevNext cache.
595 * @param array $prevNextId
596 * @param bool $onlySelected
597 * Only flip those which have been marked as selected.
599 public static function flipPair(array $prevNextId, $onlySelected) {
600 $dao = new CRM_Core_DAO_PrevNextCache();
602 $dao->is_selected
= 1;
604 foreach ($prevNextId as $id) {
606 if ($dao->find(TRUE)) {
607 $originalData = unserialize($dao->data
);
608 $srcFields = array('ID', 'Name');
609 $swapFields = array('srcID', 'srcName', 'dstID', 'dstName');
610 $data = array_diff_assoc($originalData, array_fill_keys($swapFields, 1));
611 foreach ($srcFields as $key) {
612 $data['src' . $key] = $originalData['dst' . $key];
613 $data['dst' . $key] = $originalData['src' . $key];
615 $dao->data
= serialize($data);
616 $dao->entity_id1
= $data['dstID'];
617 $dao->entity_id2
= $data['srcID'];