Merge pull request #7036 from eileenmcnaughton/master
[civicrm-core.git] / CRM / Core / BAO / PrevNextCache.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
32 * $Id$
33 *
34 */
35
36 /**
37 * BAO object for civicrm_prevnext_cache table
38 */
39 class CRM_Core_BAO_PrevNextCache extends CRM_Core_DAO_PrevNextCache {
40
41 /**
42 * @param $cacheKey
43 * @param $id1
44 * @param $id2
45 * @param int $mergeId
46 * @param NULL $join
47 * @param NULL $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) = array($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 = array(
68 1 => array($id1, 'Integer'),
69 2 => array($id2, 'Integer'),
70 3 => array($cacheKey, 'String'),
71 );
72
73 $mergeId = CRM_Core_DAO::singleValueQuery($query, $params);
74 }
75
76 $pos = array('foundEntry' => 0);
77 if ($mergeId) {
78 $pos['foundEntry'] = 1;
79
80 if ($where) {
81
82 $where = " AND {$where}";
83
84 }
85 $p = array(
86 1 => array($mergeId, 'Integer'),
87 2 => array($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 * @param int $id
117 * @param NULL $cacheKey
118 * @param string $entityTable
119 */
120 public static function deleteItem($id = NULL, $cacheKey = NULL, $entityTable = 'civicrm_contact') {
121
122 //clear cache
123 $sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = %1";
124 $params = array(1 => array($entityTable, 'String'));
125
126 if (is_numeric($id)) {
127 $sql .= " AND ( entity_id1 = %2 OR entity_id2 = %2 )";
128 $params[2] = array($id, 'Integer');
129 }
130
131 if (isset($cacheKey)) {
132 $sql .= " AND cacheKey LIKE %3";
133 $params[3] = array("{$cacheKey}%", 'String');
134 }
135 CRM_Core_DAO::executeQuery($sql, $params);
136 }
137
138 /**
139 * @param $id1
140 * @param $id2
141 * @param NULL $cacheKey
142 * @param bool $isViceVersa
143 * @param string $entityTable
144 */
145 public static function deletePair($id1, $id2, $cacheKey = NULL, $isViceVersa = FALSE, $entityTable = 'civicrm_contact') {
146 $sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = %1";
147 $params = array(1 => array($entityTable, 'String'));
148
149 $pair = !$isViceVersa ? "entity_id1 = %2 AND entity_id2 = %3" : "(entity_id1 = %2 AND entity_id2 = %3) OR (entity_id1 = %3 AND entity_id2 = %2)";
150 $sql .= " AND ( {$pair} )";
151 $params[2] = array($id1, 'Integer');
152 $params[3] = array($id2, 'Integer');
153
154 if (isset($cacheKey)) {
155 $sql .= " AND cacheKey LIKE %4";
156 $params[4] = array("{$cacheKey}%", 'String'); // used % to address any row with conflict-cacheKey e.g "merge Individual_8_0_conflicts"
157 }
158
159 CRM_Core_DAO::executeQuery($sql, $params);
160 }
161
162 public static function markConflict($id1, $id2, $cacheKey, $conflicts) {
163 if (empty($cacheKey) || empty($conflicts)) {
164 return FALSE;
165 }
166
167 $sql = "SELECT pn.*
168 FROM civicrm_prevnext_cache pn
169 WHERE
170 ((pn.entity_id1 = %1 AND pn.entity_id2 = %2) OR (pn.entity_id1 = %2 AND pn.entity_id2 = %1)) AND
171 (cacheKey = %3 OR cacheKey = %4)";
172 $params = array(
173 1 => array($id1, 'Integer'),
174 2 => array($id2, 'Integer'),
175 3 => array("{$cacheKey}", 'String'),
176 4 => array("{$cacheKey}_conflicts", 'String'),
177 );
178 $pncFind = CRM_Core_DAO::executeQuery($sql, $params);
179
180 while ($pncFind->fetch()) {
181 $data = $pncFind->data;
182 if (!empty($data)) {
183 $data = unserialize($data);
184 $data['conflicts'] = implode(",", array_values($conflicts));
185
186 $pncUp = new CRM_Core_DAO_PrevNextCache();
187 $pncUp->id = $pncFind->id;
188 if ($pncUp->find(TRUE)) {
189 $pncUp->data = serialize($data);
190 $pncUp->cacheKey = "{$cacheKey}_conflicts";
191 $pncUp->save();
192 }
193 }
194 }
195 return TRUE;
196 }
197
198 /**
199 * Retrieve from prev-next cache.
200 *
201 * @param string $cacheKey
202 * @param string $join
203 * @param string $where
204 * @param int $offset
205 * @param int $rowCount
206 *
207 * @param array $select
208 *
209 * @return array
210 */
211 public static function retrieve($cacheKey, $join = NULL, $where = NULL, $offset = 0, $rowCount = 0, $select = array()) {
212 $selectString = 'pn.*';
213 if (!empty($select)) {
214 $aliasArray = array();
215 foreach ($select as $column => $alias) {
216 $aliasArray[] = $column . ' as ' . $alias;
217 }
218 $selectString .= " , " . implode(' , ', $aliasArray);
219 }
220 $query = "
221 SELECT SQL_CALC_FOUND_ROWS {$selectString}
222 FROM civicrm_prevnext_cache pn
223 {$join}
224 WHERE (pn.cacheKey = %1 OR pn.cacheKey = %2)
225 ";
226 $params = array(
227 1 => array($cacheKey, 'String'),
228 2 => array("{$cacheKey}_conflicts", 'String'),
229 );
230
231 if ($where) {
232 $query .= " AND {$where}";
233 }
234
235 if ($rowCount) {
236 $offset = CRM_Utils_Type::escape($offset, 'Int');
237 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
238
239 $query .= " LIMIT {$offset}, {$rowCount}";
240 }
241
242 $dao = CRM_Core_DAO::executeQuery($query, $params);
243
244 $main = array();
245 $count = 0;
246 while ($dao->fetch()) {
247 if (self::is_serialized($dao->data)) {
248 $main[$count] = unserialize($dao->data);
249 }
250 else {
251 $main[$count] = $dao->data;
252 }
253
254 if (!empty($select)) {
255 $extraData = array();
256 foreach ($select as $dfield => $sfield) {
257 $extraData[$sfield] = $dao->$sfield;
258 }
259 $main[$count] = array(
260 'prevnext_id' => $dao->id,
261 'is_selected' => $dao->is_selected,
262 'entity_id1' => $dao->entity_id1,
263 'entity_id2' => $dao->entity_id2,
264 'data' => $main[$count],
265 );
266 $main[$count] = array_merge($main[$count], $extraData);
267 }
268 $count++;
269 }
270
271 return $main;
272 }
273
274 /**
275 * @param $string
276 *
277 * @return bool
278 */
279 public static function is_serialized($string) {
280 return (@unserialize($string) !== FALSE);
281 }
282
283 /**
284 * @param $values
285 */
286 public static function setItem($values) {
287 $insert = "INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES \n";
288 $query = $insert . implode(",\n ", $values);
289
290 //dump the dedupe matches in the prevnext_cache table
291 CRM_Core_DAO::executeQuery($query);
292 }
293
294 /**
295 * @param $cacheKey
296 * @param NULL $join
297 * @param NULL $where
298 * @param string $op
299 *
300 * @return int
301 */
302 public static function getCount($cacheKey, $join = NULL, $where = NULL, $op = "=") {
303 $query = "
304 SELECT COUNT(*) FROM civicrm_prevnext_cache pn
305 {$join}
306 WHERE (pn.cacheKey $op %1 OR pn.cacheKey $op %2)
307 ";
308 if ($where) {
309 $query .= " AND {$where}";
310 }
311
312 $params = array(
313 1 => array($cacheKey, 'String'),
314 2 => array("{$cacheKey}_conflicts", 'String'),
315 );
316 return (int) CRM_Core_DAO::singleValueQuery($query, $params, TRUE, FALSE);
317 }
318
319 /**
320 * @param int $rgid
321 * @param int $gid
322 * @param NULL $cacheKeyString
323 *
324 * @return bool
325 */
326 public static function refillCache($rgid = NULL, $gid = NULL, $cacheKeyString = NULL) {
327 if (!$cacheKeyString && $rgid) {
328 $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
329 $cacheKeyString = "merge {$contactType}";
330 $cacheKeyString .= $rgid ? "_{$rgid}" : '_0';
331 $cacheKeyString .= $gid ? "_{$gid}" : '_0';
332 }
333
334 if (!$cacheKeyString) {
335 return FALSE;
336 }
337
338 // 1. Clear cache if any
339 $sql = "DELETE FROM civicrm_prevnext_cache WHERE cacheKey LIKE %1";
340 CRM_Core_DAO::executeQuery($sql, array(1 => array("{$cacheKeyString}%", 'String')));
341
342 // FIXME: we need to start using temp tables / queries here instead of arrays.
343 // And cleanup code in CRM/Contact/Page/DedupeFind.php
344
345 // 2. FILL cache
346 $foundDupes = array();
347 if ($rgid && $gid) {
348 $foundDupes = CRM_Dedupe_Finder::dupesInGroup($rgid, $gid);
349 }
350 elseif ($rgid) {
351 $foundDupes = CRM_Dedupe_Finder::dupes($rgid);
352 }
353
354 if (!empty($foundDupes)) {
355 $cids = $displayNames = $values = array();
356 foreach ($foundDupes as $dupe) {
357 $cids[$dupe[0]] = 1;
358 $cids[$dupe[1]] = 1;
359 }
360 $cidString = implode(', ', array_keys($cids));
361 $sql = "SELECT id, display_name FROM civicrm_contact WHERE id IN ($cidString) ORDER BY sort_name";
362 $dao = new CRM_Core_DAO();
363 $dao->query($sql);
364 while ($dao->fetch()) {
365 $displayNames[$dao->id] = $dao->display_name;
366 }
367
368 $session = CRM_Core_Session::singleton();
369 $userId = $session->get('userID');
370
371 foreach ($foundDupes as $dupes) {
372 $srcID = $dupes[0];
373 $dstID = $dupes[1];
374 if ($dstID == $userId) {
375 $srcID = $dupes[1];
376 $dstID = $dupes[0];
377 }
378
379 $row = array(
380 'srcID' => $srcID,
381 'srcName' => $displayNames[$srcID],
382 'dstID' => $dstID,
383 'dstName' => $displayNames[$dstID],
384 'weight' => $dupes[2],
385 'canMerge' => TRUE,
386 );
387
388 $data = CRM_Core_DAO::escapeString(serialize($row));
389 $values[] = " ( 'civicrm_contact', $srcID, $dstID, '$cacheKeyString', '$data' ) ";
390 }
391 self::setItem($values);
392 }
393 }
394
395 public static function cleanupCache() {
396 // clean up all prev next caches older than $cacheTimeIntervalDays days
397 $cacheTimeIntervalDays = 2;
398
399 // first find all the cacheKeys that match this
400 $sql = "
401 DELETE pn, c
402 FROM civicrm_cache c
403 INNER JOIN civicrm_prevnext_cache pn ON c.path = pn.cacheKey
404 WHERE c.group_name = %1
405 AND c.created_date < date_sub( NOW( ), INTERVAL %2 day )
406 ";
407 $params = array(
408 1 => array('CiviCRM Search PrevNextCache', 'String'),
409 2 => array($cacheTimeIntervalDays, 'Integer'),
410 );
411 CRM_Core_DAO::executeQuery($sql, $params);
412 }
413
414 /**
415 * Save checkbox selections.
416 *
417 * @param $cacheKey
418 * @param string $action
419 * @param array $cIds
420 * @param string $entity_table
421 */
422 public static function markSelection($cacheKey, $action = 'unselect', $cIds = NULL, $entity_table = 'civicrm_contact') {
423 if (!$cacheKey) {
424 return;
425 }
426 $params = array();
427
428 $entity_whereClause = " AND entity_table = '{$entity_table}'";
429 if ($cIds && $cacheKey && $action) {
430 if (is_array($cIds)) {
431 $cIdFilter = "(" . implode(',', $cIds) . ")";
432 $whereClause = "
433 WHERE cacheKey LIKE %1
434 AND (entity_id1 IN {$cIdFilter} OR entity_id2 IN {$cIdFilter})
435 ";
436 }
437 else {
438 $whereClause = "
439 WHERE cacheKey LIKE %1
440 AND (entity_id1 = %2 OR entity_id2 = %2)
441 ";
442 $params[2] = array("{$cIds}", 'Integer');
443 }
444 if ($action == 'select') {
445 $whereClause .= "AND is_selected = 0";
446 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = 1 {$whereClause} {$entity_whereClause}";
447 $params[1] = array("{$cacheKey}%", 'String');
448 }
449 elseif ($action == 'unselect') {
450 $whereClause .= "AND is_selected = 1";
451 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = 0 {$whereClause} {$entity_whereClause}";
452 $params[1] = array("%{$cacheKey}%", 'String');
453 }
454 // default action is reseting
455 }
456 elseif (!$cIds && $cacheKey && $action == 'unselect') {
457 $sql = "
458 UPDATE civicrm_prevnext_cache
459 SET is_selected = 0
460 WHERE cacheKey LIKE %1 AND is_selected = 1
461 {$entity_whereClause}
462 ";
463 $params[1] = array("{$cacheKey}%", 'String');
464 }
465 CRM_Core_DAO::executeQuery($sql, $params);
466 }
467
468 /**
469 * Get the selections.
470 *
471 * @param string $cacheKey
472 * Cache key.
473 * @param string $action
474 * Action.
475 * $action : get - get only selection records
476 * getall - get all the records of the specified cache key
477 * @param string $entity_table
478 * Entity table.
479 *
480 * @return array|NULL
481 */
482 public static function getSelection($cacheKey, $action = 'get', $entity_table = 'civicrm_contact') {
483 if (!$cacheKey) {
484 return NULL;
485 }
486 $params = array();
487
488 $entity_whereClause = " AND entity_table = '{$entity_table}'";
489 if ($cacheKey && ($action == 'get' || $action == 'getall')) {
490 $actionGet = ($action == "get") ? " AND is_selected = 1 " : "";
491 $sql = "
492 SELECT entity_id1, entity_id2 FROM civicrm_prevnext_cache
493 WHERE cacheKey LIKE %1
494 $actionGet
495 $entity_whereClause
496 ORDER BY id
497 ";
498 $params[1] = array("{$cacheKey}%", 'String');
499
500 $contactIds = array($cacheKey => array());
501 $cIdDao = CRM_Core_DAO::executeQuery($sql, $params);
502 while ($cIdDao->fetch()) {
503 if ($cIdDao->entity_id1 == $cIdDao->entity_id2) {
504 $contactIds[$cacheKey][$cIdDao->entity_id1] = 1;
505 }
506 }
507 return $contactIds;
508 }
509 }
510
511 /**
512 * @return array
513 */
514 public static function getSelectedContacts() {
515 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String');
516 $cacheKey = "civicrm search {$qfKey}";
517 $query = "
518 SELECT *
519 FROM civicrm_prevnext_cache
520 WHERE cacheKey LIKE %1
521 AND is_selected=1
522 AND cacheKey NOT LIKE %2
523 ";
524 $params1[1] = array("{$cacheKey}%", 'String');
525 $params1[2] = array("{$cacheKey}_alphabet%", 'String');
526 $dao = CRM_Core_DAO::executeQuery($query, $params1);
527
528 $val = array();
529 while ($dao->fetch()) {
530 $val[] = $dao->data;
531 }
532 return $val;
533 }
534
535 /**
536 * @param CRM_Core_Form $form
537 * @param array $params
538 *
539 * @return mixed
540 */
541 public static function buildSelectedContactPager(&$form, &$params) {
542 $params['status'] = ts('Contacts %%StatusMessage%%');
543 $params['csvString'] = NULL;
544 $params['buttonTop'] = 'PagerTopButton';
545 $params['buttonBottom'] = 'PagerBottomButton';
546 $params['rowCount'] = $form->get(CRM_Utils_Pager::PAGE_ROWCOUNT);
547
548 if (!$params['rowCount']) {
549 $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
550 }
551
552 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
553 $cacheKey = "civicrm search {$qfKey}";
554
555 $query = "
556 SELECT count(id)
557 FROM civicrm_prevnext_cache
558 WHERE cacheKey LIKE %1
559 AND is_selected = 1
560 AND cacheKey NOT LIKE %2
561 ";
562 $params1[1] = array("{$cacheKey}%", 'String');
563 $params1[2] = array("{$cacheKey}_alphabet%", 'String');
564 $paramsTotal = CRM_Core_DAO::singleValueQuery($query, $params1);
565 $params['total'] = $paramsTotal;
566 $form->_pager = new CRM_Utils_Pager($params);
567 $form->assign_by_ref('pager', $form->_pager);
568 list($offset, $rowCount) = $form->_pager->getOffsetAndRowCount();
569 $params['offset'] = $offset;
570 $params['rowCount1'] = $rowCount;
571 return $params;
572 }
573
574 }