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