Merge pull request #4997 from monishdeb/CRM-15536
[civicrm-core.git] / CRM / Core / BAO / PrevNextCache.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
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 +--------------------------------------------------------------------+
e70a7fc0 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * BAO object for civicrm_prevnext_cache table
38 */
39class CRM_Core_BAO_PrevNextCache extends CRM_Core_DAO_PrevNextCache {
40
b5c2afd0
EM
41 /**
42 * @param $cacheKey
43 * @param $id1
44 * @param $id2
100fef9d 45 * @param int $mergeId
e60f24eb
TO
46 * @param NULL $join
47 * @param NULL $where
b5c2afd0
EM
48 * @param bool $flip
49 *
50 * @return array
51 */
00be9182 52 public static function getPositions($cacheKey, $id1, $id2, &$mergeId = NULL, $join = NULL, $where = NULL, $flip = FALSE) {
6a488035
TO
53 if ($flip) {
54 list($id1, $id2) = array($id2, $id1);
55 }
56
57 if ($mergeId == NULL) {
58 $query = "
59SELECT id
60FROM civicrm_prevnext_cache
61WHERE cacheKey = %3 AND
62 entity_id1 = %1 AND
63 entity_id2 = %2 AND
64 entity_table = 'civicrm_contact'
65";
66
6ea503d4
TO
67 $params = array(
68 1 => array($id1, 'Integer'),
69 2 => array($id2, 'Integer'),
70 3 => array($cacheKey, 'String'),
6a488035
TO
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 }
6ea503d4
TO
85 $p = array(
86 1 => array($mergeId, 'Integer'),
87 2 => array($cacheKey, 'String'),
6a488035 88 );
353ffa53 89 $sql = "SELECT pn.id, pn.entity_id1, pn.entity_id2, pn.data FROM civicrm_prevnext_cache pn {$join} ";
6a488035 90 $wherePrev = " WHERE pn.id < %1 AND pn.cacheKey = %2 {$where} ORDER BY ID DESC LIMIT 1";
353ffa53 91 $sqlPrev = $sql . $wherePrev;
6a488035 92
6a488035
TO
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
b5c2afd0 115 /**
100fef9d 116 * @param int $id
e60f24eb 117 * @param NULL $cacheKey
b5c2afd0
EM
118 * @param string $entityTable
119 */
00be9182 120 public static function deleteItem($id = NULL, $cacheKey = NULL, $entityTable = 'civicrm_contact') {
6a488035
TO
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
b5c2afd0
EM
138 /**
139 * @param $id1
140 * @param $id2
e60f24eb 141 * @param NULL $cacheKey
b5c2afd0
EM
142 * @param bool $isViceVersa
143 * @param string $entityTable
144 */
00be9182 145 public static function deletePair($id1, $id2, $cacheKey = NULL, $isViceVersa = FALSE, $entityTable = 'civicrm_contact') {
6a488035
TO
146 $sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = %1";
147 $params = array(1 => array($entityTable, 'String'));
148
ae5ffbb7 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)";
6a488035
TO
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');
157 }
158
159 CRM_Core_DAO::executeQuery($sql, $params);
160 }
161
b5c2afd0
EM
162 /**
163 * @param $cacheKey
e60f24eb
TO
164 * @param NULL $join
165 * @param NULL $where
b5c2afd0
EM
166 * @param int $offset
167 * @param int $rowCount
168 *
169 * @return array
170 */
00be9182 171 public static function retrieve($cacheKey, $join = NULL, $where = NULL, $offset = 0, $rowCount = 0) {
6a488035
TO
172 $query = "
173SELECT data
174FROM civicrm_prevnext_cache pn
175 {$join}
176WHERE cacheKey = %1
177";
178 $params = array(1 => array($cacheKey, 'String'));
179
180 if ($where) {
181 $query .= " AND {$where}";
182 }
183
184 if ($rowCount) {
bf00d1b6
DL
185 $offset = CRM_Utils_Type::escape($offset, 'Int');
186 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
187
6a488035
TO
188 $query .= " LIMIT {$offset}, {$rowCount}";
189 }
190
191 $dao = CRM_Core_DAO::executeQuery($query, $params);
192
193 $main = array();
194 while ($dao->fetch()) {
195 if (self::is_serialized($dao->data)) {
196 $main[] = unserialize($dao->data);
197 }
198 else {
199 $main[] = $dao->data;
200 }
201 }
202
203 return $main;
204 }
205
b5c2afd0
EM
206 /**
207 * @param $string
208 *
209 * @return bool
210 */
6a488035 211 public static function is_serialized($string) {
ab8a593e 212 return (@unserialize($string) !== FALSE);
6a488035
TO
213 }
214
b5c2afd0
EM
215 /**
216 * @param $values
217 */
00be9182 218 public static function setItem($values) {
6a488035
TO
219 $insert = "INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES \n";
220 $query = $insert . implode(",\n ", $values);
221
222 //dump the dedupe matches in the prevnext_cache table
223 CRM_Core_DAO::executeQuery($query);
224 }
225
b5c2afd0
EM
226 /**
227 * @param $cacheKey
e60f24eb
TO
228 * @param NULL $join
229 * @param NULL $where
b5c2afd0
EM
230 * @param string $op
231 *
232 * @return int
233 */
00be9182 234 public static function getCount($cacheKey, $join = NULL, $where = NULL, $op = "=") {
6a488035
TO
235 $query = "
236SELECT COUNT(*) FROM civicrm_prevnext_cache pn
237 {$join}
238WHERE cacheKey $op %1
239";
240 if ($where) {
241 $query .= " AND {$where}";
242 }
243
244 $params = array(1 => array($cacheKey, 'String'));
64951b63 245 return (int) CRM_Core_DAO::singleValueQuery($query, $params, TRUE, FALSE);
6a488035
TO
246 }
247
b5c2afd0 248 /**
100fef9d
CW
249 * @param int $rgid
250 * @param int $gid
e60f24eb 251 * @param NULL $cacheKeyString
b5c2afd0 252 */
00be9182 253 public static function refillCache($rgid = NULL, $gid = NULL, $cacheKeyString = NULL) {
6a488035
TO
254 if (!$cacheKeyString && $rgid) {
255 $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
256 $cacheKeyString = "merge {$contactType}";
257 $cacheKeyString .= $rgid ? "_{$rgid}" : '_0';
258 $cacheKeyString .= $gid ? "_{$gid}" : '_0';
259 }
260
261 if (!$cacheKeyString) {
262 return FALSE;
263 }
264
265 // 1. Clear cache if any
266 $sql = "DELETE FROM civicrm_prevnext_cache WHERE cacheKey LIKE %1";
267 CRM_Core_DAO::executeQuery($sql, array(1 => array("{$cacheKeyString}%", 'String')));
268
269 // FIXME: we need to start using temp tables / queries here instead of arrays.
270 // And cleanup code in CRM/Contact/Page/DedupeFind.php
271
272 // 2. FILL cache
273 $foundDupes = array();
274 if ($rgid && $gid) {
275 $foundDupes = CRM_Dedupe_Finder::dupesInGroup($rgid, $gid);
276 }
277 elseif ($rgid) {
278 $foundDupes = CRM_Dedupe_Finder::dupes($rgid);
279 }
280
281 if (!empty($foundDupes)) {
282 $cids = $displayNames = $values = array();
283 foreach ($foundDupes as $dupe) {
284 $cids[$dupe[0]] = 1;
285 $cids[$dupe[1]] = 1;
286 }
287 $cidString = implode(', ', array_keys($cids));
353ffa53
TO
288 $sql = "SELECT id, display_name FROM civicrm_contact WHERE id IN ($cidString) ORDER BY sort_name";
289 $dao = new CRM_Core_DAO();
6a488035
TO
290 $dao->query($sql);
291 while ($dao->fetch()) {
292 $displayNames[$dao->id] = $dao->display_name;
293 }
294
295 $session = CRM_Core_Session::singleton();
296 $userId = $session->get('userID');
297
298 foreach ($foundDupes as $dupes) {
299 $srcID = $dupes[0];
300 $dstID = $dupes[1];
301 if ($dstID == $userId) {
302 $srcID = $dupes[1];
303 $dstID = $dupes[0];
304 }
305
306 $row = array(
307 'srcID' => $srcID,
308 'srcName' => $displayNames[$srcID],
309 'dstID' => $dstID,
310 'dstName' => $displayNames[$dstID],
311 'weight' => $dupes[2],
312 'canMerge' => TRUE,
313 );
314
315 $data = CRM_Core_DAO::escapeString(serialize($row));
316 $values[] = " ( 'civicrm_contact', $srcID, $dstID, '$cacheKeyString', '$data' ) ";
317 }
318 self::setItem($values);
319 }
320 }
321
00be9182 322 public static function cleanupCache() {
6a488035
TO
323 // clean up all prev next caches older than $cacheTimeIntervalDays days
324 $cacheTimeIntervalDays = 2;
325
326 // first find all the cacheKeys that match this
327 $sql = "
328DELETE pn, c
329FROM civicrm_cache c
330INNER JOIN civicrm_prevnext_cache pn ON c.path = pn.cacheKey
331WHERE c.group_name = %1
332AND c.created_date < date_sub( NOW( ), INTERVAL %2 day )
333";
334 $params = array(
335 1 => array('CiviCRM Search PrevNextCache', 'String'),
336 2 => array($cacheTimeIntervalDays, 'Integer'),
337 );
338 CRM_Core_DAO::executeQuery($sql, $params);
339 }
340
b5c2afd0 341 /**
c490a46a
CW
342 * Save checkbox selections
343 *
b5c2afd0
EM
344 * @param $cacheKey
345 * @param string $action
c490a46a 346 * @param array $cIds
b5c2afd0
EM
347 * @param string $entity_table
348 */
00be9182 349 public static function markSelection($cacheKey, $action = 'unselect', $cIds = NULL, $entity_table = 'civicrm_contact') {
6a488035
TO
350 if (!$cacheKey) {
351 return;
352 }
353 $params = array();
354
355 $entity_whereClause = " AND entity_table = '{$entity_table}'";
356 if ($cIds && $cacheKey && $action) {
357 if (is_array($cIds)) {
358 $cIdFilter = "(" . implode(',', $cIds) . ")";
359 $whereClause = "
360WHERE cacheKey LIKE %1
361AND (entity_id1 IN {$cIdFilter} OR entity_id2 IN {$cIdFilter})
362";
363 }
364 else {
365 $whereClause = "
366WHERE cacheKey LIKE %1
367AND (entity_id1 = %2 OR entity_id2 = %2)
368";
369 $params[2] = array("{$cIds}", 'Integer');
370 }
371 if ($action == 'select') {
372 $whereClause .= "AND is_selected = 0";
373 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = 1 {$whereClause} {$entity_whereClause}";
55488e61 374 $params[1] = array("{$cacheKey}%", 'String');
6a488035
TO
375 }
376 elseif ($action == 'unselect') {
377 $whereClause .= "AND is_selected = 1";
378 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = 0 {$whereClause} {$entity_whereClause}";
379 $params[1] = array("%{$cacheKey}%", 'String');
380 }
381 // default action is reseting
382 }
383 elseif (!$cIds && $cacheKey && $action == 'unselect') {
384 $sql = "
385UPDATE civicrm_prevnext_cache
386SET is_selected = 0
387WHERE cacheKey LIKE %1 AND is_selected = 1
388 {$entity_whereClause}
389";
55488e61 390 $params[1] = array("{$cacheKey}%", 'String');
6a488035
TO
391 }
392 CRM_Core_DAO::executeQuery($sql, $params);
393 }
394
395 /**
100fef9d 396 * Get the selections
6a488035 397 *
6a0b768e
TO
398 * @param string $cacheKey
399 * Cache key.
400 * @param string $action
401 * Action.
6a488035
TO
402 * $action : get - get only selection records
403 * getall - get all the records of the specified cache key
6a0b768e
TO
404 * @param string $entity_table
405 * Entity table.
77b97be7 406 *
ae5ffbb7 407 * @return array|NULL
6a488035 408 */
00be9182 409 public static function getSelection($cacheKey, $action = 'get', $entity_table = 'civicrm_contact') {
6a488035 410 if (!$cacheKey) {
ae5ffbb7 411 return NULL;
6a488035
TO
412 }
413 $params = array();
414
415 $entity_whereClause = " AND entity_table = '{$entity_table}'";
416 if ($cacheKey && ($action == 'get' || $action == 'getall')) {
417 $actionGet = ($action == "get") ? " AND is_selected = 1 " : "";
418 $sql = "
419SELECT entity_id1, entity_id2 FROM civicrm_prevnext_cache
420WHERE cacheKey LIKE %1
421 $actionGet
422 $entity_whereClause
423ORDER BY id
424";
55488e61 425 $params[1] = array("{$cacheKey}%", 'String');
6a488035
TO
426
427 $contactIds = array($cacheKey => array());
428 $cIdDao = CRM_Core_DAO::executeQuery($sql, $params);
429 while ($cIdDao->fetch()) {
430 if ($cIdDao->entity_id1 == $cIdDao->entity_id2) {
431 $contactIds[$cacheKey][$cIdDao->entity_id1] = 1;
432 }
433 }
434 return $contactIds;
435 }
436 }
437
b5c2afd0
EM
438 /**
439 * @return array
440 */
00be9182 441 public static function getSelectedContacts() {
6a488035
TO
442 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String');
443 $cacheKey = "civicrm search {$qfKey}";
444 $query = "
445SELECT *
446FROM civicrm_prevnext_cache
447WHERE cacheKey LIKE %1
448 AND is_selected=1
449 AND cacheKey NOT LIKE %2
450";
55488e61
DL
451 $params1[1] = array("{$cacheKey}%", 'String');
452 $params1[2] = array("{$cacheKey}_alphabet%", 'String');
6a488035
TO
453 $dao = CRM_Core_DAO::executeQuery($query, $params1);
454
481a74f4 455 $val = array();
6a488035
TO
456 while ($dao->fetch()) {
457 $val[] = $dao->data;
458 }
459 return $val;
460 }
461
b5c2afd0 462 /**
c490a46a
CW
463 * @param CRM_Core_Form $form
464 * @param array $params
b5c2afd0
EM
465 *
466 * @return mixed
467 */
00be9182 468 public static function buildSelectedContactPager(&$form, &$params) {
6a488035
TO
469 $params['status'] = ts('Contacts %%StatusMessage%%');
470 $params['csvString'] = NULL;
471 $params['buttonTop'] = 'PagerTopButton';
472 $params['buttonBottom'] = 'PagerBottomButton';
c490a46a 473 $params['rowCount'] = $form->get(CRM_Utils_Pager::PAGE_ROWCOUNT);
6a488035
TO
474
475 if (!$params['rowCount']) {
476 $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
477 }
478
353ffa53 479 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
6a488035
TO
480 $cacheKey = "civicrm search {$qfKey}";
481
482 $query = "
483SELECT count(id)
484FROM civicrm_prevnext_cache
485WHERE cacheKey LIKE %1
486 AND is_selected = 1
487 AND cacheKey NOT LIKE %2
488";
55488e61
DL
489 $params1[1] = array("{$cacheKey}%", 'String');
490 $params1[2] = array("{$cacheKey}_alphabet%", 'String');
c490a46a 491 $paramsTotal = CRM_Core_DAO::singleValueQuery($query, $params1);
6a488035 492 $params['total'] = $paramsTotal;
c490a46a
CW
493 $form->_pager = new CRM_Utils_Pager($params);
494 $form->assign_by_ref('pager', $form->_pager);
495 list($offset, $rowCount) = $form->_pager->getOffsetAndRowCount();
6a488035
TO
496 $params['offset'] = $offset;
497 $params['rowCount1'] = $rowCount;
498 return $params;
499 }
96025800 500
6a488035 501}