CRM-19097 Cache cidRefs during merge
[civicrm-core.git] / CRM / Dedupe / Merger.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
6a488035
TO
32 */
33class CRM_Dedupe_Merger {
6a488035 34
e0ef6999 35 /**
4f1f1f2a
CW
36 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
37 * FIXME: the sub-pages references by the URLs should
38 * be loaded dynamically on the merge form instead
e0ef6999
EM
39 * @return array
40 */
00be9182 41 public static function relTables() {
6a488035
TO
42 static $relTables;
43
12d73bba 44 // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
45 // if the url can't be retrieved. A more standardised way to retrieve them is.
46 // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
47 // we may need a different function when it is not known.
48 $title = $userRecordUrl = '';
49
6a488035
TO
50 $config = CRM_Core_Config::singleton();
51 if ($config->userSystem->is_drupal) {
52 $userRecordUrl = CRM_Utils_System::url('user/%ufid');
53 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
54 }
55 elseif ($config->userFramework == 'Joomla') {
b8feed6e 56 $userRecordUrl = $config->userSystem->getVersion() > 1.5 ? $config->userFrameworkBaseURL . "index.php?option=com_users&view=user&task=user.edit&id=" . '%ufid' : $config->userFrameworkBaseURL . "index2.php?option=com_users&view=user&task=edit&id[]=" . '%ufid';
6a488035
TO
57 $title = ts('%1 User: %2; user id: %3', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
58 }
59
60 if (!$relTables) {
61 $relTables = array(
62 'rel_table_contributions' => array(
63 'title' => ts('Contributions'),
64 'tables' => array('civicrm_contribution', 'civicrm_contribution_recur', 'civicrm_contribution_soft'),
65 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
66 ),
67 'rel_table_contribution_page' => array(
68 'title' => ts('Contribution Pages'),
69 'tables' => array('civicrm_contribution_page'),
70 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
71 ),
72 'rel_table_memberships' => array(
73 'title' => ts('Memberships'),
74 'tables' => array('civicrm_membership', 'civicrm_membership_log', 'civicrm_membership_type'),
75 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
76 ),
77 'rel_table_participants' => array(
78 'title' => ts('Participants'),
79 'tables' => array('civicrm_participant'),
80 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
81 ),
82 'rel_table_events' => array(
83 'title' => ts('Events'),
84 'tables' => array('civicrm_event'),
85 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
86 ),
87 'rel_table_activities' => array(
88 'title' => ts('Activities'),
91da6cd5 89 'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
6a488035
TO
90 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
91 ),
92 'rel_table_relationships' => array(
93 'title' => ts('Relationships'),
94 'tables' => array('civicrm_relationship'),
95 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
96 ),
97 'rel_table_custom_groups' => array(
98 'title' => ts('Custom Groups'),
99 'tables' => array('civicrm_custom_group'),
100 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
101 ),
102 'rel_table_uf_groups' => array(
103 'title' => ts('Profiles'),
104 'tables' => array('civicrm_uf_group'),
105 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
106 ),
107 'rel_table_groups' => array(
108 'title' => ts('Groups'),
109 'tables' => array('civicrm_group_contact'),
110 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
111 ),
112 'rel_table_notes' => array(
113 'title' => ts('Notes'),
114 'tables' => array('civicrm_note'),
115 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
116 ),
117 'rel_table_tags' => array(
118 'title' => ts('Tags'),
119 'tables' => array('civicrm_entity_tag'),
120 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
121 ),
122 'rel_table_mailings' => array(
123 'title' => ts('Mailings'),
124 'tables' => array('civicrm_mailing', 'civicrm_mailing_event_queue', 'civicrm_mailing_event_subscribe'),
f521f375 125 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
6a488035
TO
126 ),
127 'rel_table_cases' => array(
128 'title' => ts('Cases'),
129 'tables' => array('civicrm_case_contact'),
130 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
131 ),
132 'rel_table_grants' => array(
133 'title' => ts('Grants'),
134 'tables' => array('civicrm_grant'),
135 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
136 ),
137 'rel_table_pcp' => array(
138 'title' => ts('PCPs'),
139 'tables' => array('civicrm_pcp'),
140 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
141 ),
142 'rel_table_pledges' => array(
143 'title' => ts('Pledges'),
144 'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
145 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
146 ),
147 'rel_table_users' => array(
148 'title' => $title,
149 'tables' => array('civicrm_uf_match'),
150 'url' => $userRecordUrl,
151 ),
152 );
153
76c53278
CW
154 $relTables += self::getMultiValueCustomSets('relTables');
155
6a488035
TO
156 // Allow hook_civicrm_merge() to adjust $relTables
157 CRM_Utils_Hook::merge('relTables', $relTables);
158 }
159 return $relTables;
160 }
161
162 /**
fe482240 163 * Returns the related tables groups for which a contact has any info entered.
ad37ac8e 164 *
165 * @param int $cid
166 *
167 * @return array
6a488035 168 */
00be9182 169 public static function getActiveRelTables($cid) {
6a488035
TO
170 $cid = (int) $cid;
171 $groups = array();
172
173 $relTables = self::relTables();
174 $cidRefs = self::cidRefs();
175 $eidRefs = self::eidRefs();
176 foreach ($relTables as $group => $params) {
177 $sqls = array();
178 foreach ($params['tables'] as $table) {
179 if (isset($cidRefs[$table])) {
180 foreach ($cidRefs[$table] as $field) {
181 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
182 }
183 }
184 if (isset($eidRefs[$table])) {
185 foreach ($eidRefs[$table] as $entityTable => $entityId) {
186 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
187 }
188 }
189 foreach ($sqls as $sql) {
190 if (CRM_Core_DAO::singleValueQuery($sql) > 0) {
191 $groups[] = $group;
192 }
193 }
194 }
195 }
196 return array_unique($groups);
197 }
198
199 /**
3ae0ae3d 200 * Get array tables and fields that reference civicrm_contact.id.
201 *
202 * This includes core tables, custom group tables, tables added by the merge
203 * hook and (somewhat randomly) the entity_tag table.
204 *
205 * Refer to CRM-17454 for information on the danger of querying the information
206 * schema to derive this.
207 *
e31c3de1 208 * This function calls the merge hook but the entityTypes hook is the recommended
209 * way to add tables to this result.
6a488035 210 */
00be9182 211 public static function cidRefs() {
e31c3de1 212 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) {
213 return \Civi::$statics[__CLASS__]['contact_references'];
214 }
215 $contactReferences = array();
3ae0ae3d 216 $coreReferences = CRM_Core_DAO::getReferencesToTable('civicrm_contact');
217 foreach ($coreReferences as $coreReference) {
218 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
e31c3de1 219 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
6a488035 220 }
3ae0ae3d 221 }
e31c3de1 222 self::addCustomTablesExtendingContactsToCidRefs($contactReferences);
64b3569d 223
3ae0ae3d 224 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
e31c3de1 225 $contactReferences['civicrm_entity_tag'][] = 'entity_id';
6a488035 226
3ae0ae3d 227 // Allow hook_civicrm_merge() to adjust $cidRefs.
e31c3de1 228 // Note that if entities are registered using the entityTypes hook there
229 // is no need to use this hook.
230 CRM_Utils_Hook::merge('cidRefs', $contactReferences);
231 \Civi::$statics[__CLASS__]['contact_references'] = $contactReferences;
232 return \Civi::$statics[__CLASS__]['contact_references'];
6a488035
TO
233 }
234
235 /**
236 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
237 */
00be9182 238 public static function eidRefs() {
6a488035
TO
239 static $eidRefs;
240 if (!$eidRefs) {
241 // FIXME: this should be generated dynamically from the schema
242 // tables that reference contacts with entity_{id,table}
243 $eidRefs = array(
244 'civicrm_acl' => array('entity_table' => 'entity_id'),
245 'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
246 'civicrm_entity_file' => array('entity_table' => 'entity_id'),
247 'civicrm_log' => array('entity_table' => 'entity_id'),
248 'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
249 'civicrm_note' => array('entity_table' => 'entity_id'),
6a488035
TO
250 );
251
252 // Allow hook_civicrm_merge() to adjust $eidRefs
253 CRM_Utils_Hook::merge('eidRefs', $eidRefs);
254 }
255 return $eidRefs;
256 }
257
9da04f20 258 /**
fe482240 259 * Return tables using locations.
9da04f20 260 */
00be9182 261 public static function locTables() {
9da04f20
AS
262 static $locTables;
263 if (!$locTables) {
481a74f4 264 $locTables = array('civicrm_email', 'civicrm_address', 'civicrm_phone');
9da04f20
AS
265
266 // Allow hook_civicrm_merge() to adjust $locTables
267 CRM_Utils_Hook::merge('locTables', $locTables);
268 }
269 return $locTables;
270 }
271
76c53278
CW
272 /**
273 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
98997235
TO
274 * @param string $request
275 * 'relTables' or 'cidRefs'.
76c53278
CW
276 * @see CRM-13836
277 */
00be9182 278 public static function getMultiValueCustomSets($request) {
76c53278
CW
279 static $data = NULL;
280 if ($data === NULL) {
281 $data = array(
282 'relTables' => array(),
283 'cidRefs' => array(),
284 );
285 $result = civicrm_api3('custom_group', 'get', array(
286 'is_multiple' => 1,
287 'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
288 'return' => array('id', 'title', 'table_name', 'style'),
289 ));
22e263ad 290 foreach ($result['values'] as $custom) {
76c53278
CW
291 $data['cidRefs'][$custom['table_name']] = array('entity_id');
292 $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
293 $data['relTables']['rel_table_custom_' . $custom['id']] = array(
294 'title' => $custom['title'],
295 'tables' => array($custom['table_name']),
296 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
297 );
298 }
299 }
300 return $data[$request];
301 }
302
6a488035
TO
303 /**
304 * Tables which require custom processing should declare functions to call here.
305 * Doing so will override normal processing.
306 */
00be9182 307 public static function cpTables() {
6a488035
TO
308 static $tables;
309 if (!$tables) {
310 $tables = array(
311 'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
312 'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
313 // Empty array == do nothing - this table is handled by mergeGroupContact
314 'civicrm_subscription_history' => array(),
315 'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
316 );
317 }
318 return $tables;
319 }
320
321 /**
100fef9d 322 * Return payment related table.
6a488035 323 */
00be9182 324 public static function paymentTables() {
6a488035
TO
325 static $tables;
326 if (!$tables) {
327 $tables = array('civicrm_pledge', 'civicrm_membership', 'civicrm_participant');
328 }
6a488035
TO
329 return $tables;
330 }
331
332 /**
100fef9d 333 * Return payment update Query.
54957108 334 *
335 * @param string $tableName
336 * @param int $mainContactId
337 * @param int $otherContactId
338 *
339 * @return array
6a488035 340 */
00be9182 341 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
6a488035
TO
342 $sqls = array();
343 if (!$tableName || !$mainContactId || !$otherContactId) {
344 return $sqls;
345 }
346
347 $paymentTables = self::paymentTables();
348 if (!in_array($tableName, $paymentTables)) {
349 return $sqls;
350 }
351
352 switch ($tableName) {
353 case 'civicrm_pledge':
354 $sqls[] = "
355 UPDATE IGNORE civicrm_contribution contribution
356INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
357INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
358 SET contribution.contact_id = $mainContactId
359 WHERE pledge.contact_id = $otherContactId";
360 break;
361
362 case 'civicrm_membership':
363 $sqls[] = "
364 UPDATE IGNORE civicrm_contribution contribution
365INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
366INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
367 SET contribution.contact_id = $mainContactId
368 WHERE membership.contact_id = $otherContactId";
369 break;
370
371 case 'civicrm_participant':
372 $sqls[] = "
373 UPDATE IGNORE civicrm_contribution contribution
374INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
375INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
376 SET contribution.contact_id = $mainContactId
377 WHERE participant.contact_id = $otherContactId";
378 break;
379 }
380
381 return $sqls;
382 }
383
e0ef6999 384 /**
100fef9d
CW
385 * @param int $mainId
386 * @param int $otherId
387 * @param string $tableName
e0ef6999
EM
388 * @param array $tableOperations
389 * @param string $mode
390 *
391 * @return array
392 */
00be9182 393 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = array(), $mode = 'add') {
6a488035
TO
394 $sqls = array();
395 if (!$tableName || !$mainId || !$otherId) {
396 return $sqls;
397 }
398
6a488035
TO
399 switch ($tableName) {
400 case 'civicrm_membership':
d58a19a1
TO
401 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
402 break;
403 }
404 if ($mode == 'add') {
405 $sqls[] = "
6a488035
TO
406DELETE membership1.* FROM civicrm_membership membership1
407 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
408 AND membership1.contact_id = {$mainId}
409 AND membership2.contact_id = {$otherId} ";
d58a19a1
TO
410 }
411 if ($mode == 'payment') {
412 $sqls[] = "
6a488035
TO
413DELETE contribution.* FROM civicrm_contribution contribution
414INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
415INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
416 AND membership1.contact_id = {$mainId}
417INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
418 AND membership2.contact_id = {$otherId}";
d58a19a1
TO
419 }
420 break;
6a488035
TO
421
422 case 'civicrm_uf_match':
423 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
b44e3f84 424 // failing to meet intended result. Therefore we introduce this additional query:
6a488035
TO
425 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
426 break;
427 }
428
429 return $sqls;
430 }
431
432 /**
433 * Based on the provided two contact_ids and a set of tables, move the
434 * belongings of the other contact to the main one.
435 *
54957108 436 * @param int $mainId
437 * @param int $otherId
438 * @param bool $tables
439 * @param array $tableOperations
6a488035 440 */
00be9182 441 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array()) {
6a488035
TO
442 $cidRefs = self::cidRefs();
443 $eidRefs = self::eidRefs();
444 $cpTables = self::cpTables();
445 $paymentTables = self::paymentTables();
c5c263ca
AH
446 // CRM-12695:
447 $membershipMerge = FALSE;
6a488035
TO
448
449 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
450 if ($tables !== FALSE) {
451 // if there are specific tables, sanitize the list
452 $affected = array_unique(array_intersect($affected, $tables));
453 }
454 else {
455 // if there aren't any specific tables, don't affect the ones handled by relTables()
9da04f20 456 // also don't affect tables in locTables() CRM-15658
6a488035 457 $relTables = self::relTables();
9da04f20 458 $handled = self::locTables();
6a488035
TO
459 foreach ($relTables as $params) {
460 $handled = array_merge($handled, $params['tables']);
461 }
462 $affected = array_diff($affected, $handled);
ada104d5
AW
463 /**
464 * CRM-12695
465 * Set $membershipMerge flag only once
466 * while doing contact related migration
467 * to call addMembershipToRealtedContacts()
468 * function only once.
469 * Since the current function (moveContactBelongings) is called twice
470 * with & without parameters $tables & $tableOperations
471 */
472 // retrieve main contact's related table(s)
473 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
474 // check if membership table exists in main contact's related table(s)
c5c263ca 475 // set membership flag - CRM-12695
ada104d5 476 if (in_array('rel_table_memberships', $activeMainRelTables)) {
c5c263ca 477 $membershipMerge = TRUE;
ada104d5 478 }
6a488035
TO
479 }
480
481 $mainId = (int) $mainId;
482 $otherId = (int) $otherId;
483
484 $sqls = array();
485 foreach ($affected as $table) {
486 // Call custom processing function for objects that require it
487 if (isset($cpTables[$table])) {
488 foreach ($cpTables[$table] as $className => $fnName) {
489 $className::$fnName($mainId, $otherId, $sqls);
490 }
491 // Skip normal processing
492 continue;
493 }
b3fdbf3d 494
6a488035
TO
495 // use UPDATE IGNORE + DELETE query pair to skip on situations when
496 // there's a UNIQUE restriction on ($field, some_other_field) pair
497 if (isset($cidRefs[$table])) {
498 foreach ($cidRefs[$table] as $field) {
499 // carry related contributions CRM-5359
500 if (in_array($table, $paymentTables)) {
6a488035
TO
501 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
502 $sqls = array_merge($sqls, $paymentSqls);
71560cf3
C
503
504 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
505 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
506 $sqls = array_merge($sqls, $payOprSqls);
507 }
6a488035
TO
508 }
509
510 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
511 $sqls = array_merge($sqls, $preOperationSqls);
512
513 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
514 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
515 }
516 }
517 if (isset($eidRefs[$table])) {
518 foreach ($eidRefs[$table] as $entityTable => $entityId) {
519 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
520 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
521 }
522 }
523 }
524
525 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
526 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
527
528 // call the SQL queries in one transaction
529 $transaction = new CRM_Core_Transaction();
530 foreach ($sqls as $sql) {
531 CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE);
532 }
ada104d5
AW
533 // CRM-12695
534 if ($membershipMerge) {
535 // call to function adding membership to related contacts
536 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
537 }
6a488035
TO
538 $transaction->commit();
539 }
540
541 /**
4eea8606 542 * Load all non-empty fields for the contacts
b3fdbf3d 543 *
98997235
TO
544 * @param array $main
545 * Contact details.
546 * @param array $other
547 * Contact details.
6a488035 548 *
77b97be7 549 * @return array
6a488035 550 */
4eea8606 551 public static function retrieveFields($main, $other) {
6a488035
TO
552 $result = array(
553 'contact' => array(),
554 'custom' => array(),
555 );
16254ae1 556 foreach (self::getContactFields() as $validField) {
eb61dc07
J
557 // CRM-17556 Get all non-empty fields, to make comparison easier
558 if (!empty($main[$validField]) || !empty($other[$validField])) {
6a488035
TO
559 $result['contact'][] = $validField;
560 }
561 }
562
563 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
564 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
565 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
566 foreach ($keys as $key) {
76c53278
CW
567 // Exclude multi-value fields CRM-13836
568 if (strpos($key, '_')) {
569 continue;
570 }
6a488035
TO
571 $key1 = CRM_Utils_Array::value($key, $mainEvs);
572 $key2 = CRM_Utils_Array::value($key, $otherEvs);
eb61dc07 573 // CRM-17556 Get all non-empty fields, to make comparison easier
08ef1f91 574 if (!empty($key1) || !empty($key2)) {
6a488035
TO
575 $result['custom'][] = $key;
576 }
577 }
578 return $result;
579 }
580
581 /**
100fef9d 582 * Batch merge a set of contacts based on rule-group and group.
6a488035 583 *
98997235
TO
584 * @param int $rgid
585 * Rule group id.
586 * @param int $gid
587 * Group id.
588 * @param string $mode
589 * Helps decide how to behave when there are conflicts.
15a793bb
EM
590 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
591 * mode does a force merge.
c301f76e 592 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
76ddbc8e 593 * Whether to let api decide which contact to retain and which to delete.
f931b74c 594 * @param int $batchLimit number of merges to carry out in one batch.
595 * @param int $isSelected if records with is_selected column needs to be processed.
6a488035 596 *
e23e26ec 597 * @param array $criteria
598 * Criteria to use in the filter.
599 *
3058f4d9 600 * @param bool $checkPermissions
601 * Respect logged in user permissions.
602 *
77b97be7 603 * @return array|bool
6a488035 604 */
3058f4d9 605 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $autoFlip = TRUE, $batchLimit = 1, $isSelected = 2, $criteria = array(), $checkPermissions = TRUE) {
63ef778e 606 $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
2988f5c7 607 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
3058f4d9 608 $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, '', ($mode == 'aggressive'), $criteria, $checkPermissions);
6a488035
TO
609
610 $cacheParams = array(
3058f4d9 611 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
2988f5c7 612 // @todo stop passing these parameters in & instead calculate them in the merge function based
613 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
614 'join' => self::getJoinOnDedupeTable(),
615 'where' => self::getWhereString($batchLimit, $isSelected),
6a488035 616 );
3058f4d9 617 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $autoFlip, $redirectForPerformance, $checkPermissions);
6a488035
TO
618 }
619
2ae26001 620 /**
621 * Get the string to join the prevnext cache to the dedupe table.
622 *
623 * @return string
624 * The join string to join prevnext cache on the dedupe table.
625 */
626 public static function getJoinOnDedupeTable() {
627 return "
628 LEFT JOIN civicrm_dedupe_exception de
629 ON (
630 pn.entity_id1 = de.contact_id1
631 AND pn.entity_id2 = de.contact_id2 )
632 ";
633 }
634
2988f5c7 635 /**
636 * Get where string for dedupe join.
637 *
638 * @param int $batchLimit
639 * @param bool $isSelected
640 *
641 * @return string
642 */
643 protected static function getWhereString($batchLimit, $isSelected) {
644 $where = "de.id IS NULL";
645 if ($isSelected === 0 || $isSelected === 1) {
646 $where .= " AND pn.is_selected = {$isSelected}";
647 }
648 // else consider all dupe pairs
649 // @todo Adding limit to Where??!!
650 $where .= " LIMIT {$batchLimit}";
651 return $where;
652 }
653
f931b74c 654 public static function updateMergeStats($cacheKeyString, $result = array()) {
63ef778e 655 // gather latest stats
656 $merged = count($result['merged']);
657 $skipped = count($result['skipped']);
658
659 if ($merged <= 0 && $skipped <= 0) {
660 return;
661 }
662
663 // get previous stats
664 $previousStats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
665 if (!empty($previousStats)) {
666 if ($previousStats[0]['merged']) {
667 $merged = $merged + $previousStats[0]['merged'];
668 }
669 if ($previousStats[0]['skipped']) {
670 $skipped = $skipped + $previousStats[0]['skipped'];
671 }
672 }
673
674 // delete old stats
675 CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
676
677 // store the updated stats
678 $data = array(
679 'merged' => $merged,
680 'skipped' => $skipped,
681 );
682 $data = CRM_Core_DAO::escapeString(serialize($data));
683
684 $values = array();
685 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
686 CRM_Core_BAO_PrevNextCache::setItem($values);
687 }
688
ae6455b2 689 /**
690 * Delete information about merges for the given string.
691 *
692 * @param $cacheKeyString
693 */
f931b74c 694 public static function resetMergeStats($cacheKeyString) {
ae6455b2 695 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
63ef778e 696 }
697
f931b74c 698 public static function getMergeStats($cacheKeyString) {
63ef778e 699 $stats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
700 if (!empty($stats)) {
701 $stats = $stats[0];
702 }
703 return $stats;
704 }
705
f931b74c 706 public static function getMergeStatsMsg($cacheKeyString) {
63ef778e 707 $msg = '';
708 $stats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
709 if (!empty($stats['merged'])) {
8dcd31bf 710 $msg = "{$stats['merged']} " . ts('Contact(s) were merged.');
63ef778e 711 }
712 if (!empty($stats['skipped'])) {
1fe557c2 713 $msg .= $stats['skipped'] . ts(' Contact(s) were skipped.');
63ef778e 714 }
715 return $msg;
716 }
717
6a488035 718 /**
100fef9d 719 * Merge given set of contacts. Performs core operation.
6a488035 720 *
98997235
TO
721 * @param array $dupePairs
722 * Set of pair of contacts for whom merge is to be done.
723 * @param array $cacheParams
724 * Prev-next-cache params based on which next pair of contacts are computed.
6a488035 725 * Generally used with batch-merge.
98997235
TO
726 * @param string $mode
727 * Helps decide how to behave when there are conflicts.
6a488035
TO
728 * A 'safe' value skips the merge if there are any un-resolved conflicts.
729 * Does a force merge otherwise (aggressive mode).
c301f76e 730 * @param bool $autoFlip to let api decide which contact to retain and which to delete.
3058f4d9 731 * Whether to let api decide which contact to retain and which to delete.
6a488035 732 *
77b97be7 733 * @param bool $redirectForPerformance
3058f4d9 734 * Redirect to a url for batch processing.
735 *
736 * @param bool $checkPermissions
737 * Respect logged in user permissions.
77b97be7
EM
738 *
739 * @return array|bool
6a488035 740 */
00be9182 741 public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
3058f4d9 742 $autoFlip = TRUE, $redirectForPerformance = FALSE, $checkPermissions = TRUE
6a488035
TO
743 ) {
744 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
745 $resultStats = array('merged' => array(), 'skipped' => array());
746
747 // we don't want dupe caching to get reset after every-merge, and therefore set the
748 // doNotResetCache flag
749 $config = CRM_Core_Config::singleton();
750 $config->doNotResetCache = 1;
78272750 751 $deletedContacts = array();
6a488035
TO
752
753 while (!empty($dupePairs)) {
78272750 754 foreach ($dupePairs as $index => $dupes) {
755 if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) {
756 unset($dupePairs[$index]);
757 continue;
758 }
1cf05c3e 759 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
6a488035
TO
760 $mainId = $dupes['dstID'];
761 $otherId = $dupes['srcID'];
e67dcaf8 762
6a488035
TO
763 if (!$mainId || !$otherId) {
764 // return error
765 return FALSE;
766 }
767
768 // Generate var $migrationInfo. The variable structure is exactly same as
769 // $formValues submitted during a UI merge for a pair of contacts.
201057c0 770 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, $checkPermissions);
6a488035
TO
771
772 $migrationInfo = &$rowsElementsAndInfo['migration_info'];
773
774 // add additional details that we might need to resolve conflicts
775 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
776 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
6a488035
TO
777 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
778
779 // go ahead with merge if there is no conflict
63ef778e 780 $conflicts = array();
781 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
3058f4d9 782 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
c940014d 783 $resultStats['merged'][] = array('main_id' => $mainId, 'other_id' => $otherId);
78272750 784 $deletedContacts[] = $otherId;
6a488035
TO
785 }
786 else {
c940014d 787 $resultStats['skipped'][] = array('main_id' => $mainId, 'other_id' => $otherId);
6a488035
TO
788 }
789
0971143c 790 // store any conflicts
63ef778e 791 if (!empty($conflicts)) {
fd630ef9 792 foreach ($conflicts as $key => $dnc) {
793 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
794 }
63ef778e 795 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
f931b74c 796 }
797 else {
63ef778e 798 // delete entry from PrevNextCache table so we don't consider the pair next time
799 // pair may have been flipped, so make sure we delete using both orders
800 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString, TRUE);
801 }
6a488035
TO
802
803 CRM_Core_DAO::freeResult();
804 unset($rowsElementsAndInfo, $migrationInfo);
805 }
806
807 if ($cacheKeyString && !$redirectForPerformance) {
808 // retrieve next pair of dupes
2988f5c7 809 // @todo call getDuplicatePairs.
6a488035
TO
810 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
811 $cacheParams['join'],
66eceb0b 812 $cacheParams['where'],
813 0,
814 0,
815 array(),
816 '',
817 FALSE
6a488035
TO
818 );
819 }
820 else {
821 // do not proceed. Terminate the loop
822 unset($dupePairs);
823 }
824 }
63ef778e 825
826 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
6a488035
TO
827 return $resultStats;
828 }
829
830 /**
831 * A function which uses various rules / algorithms for choosing which contact to bias to
832 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
833 *
98997235
TO
834 * @param int $mainId
835 * Main contact with whom merge has to happen.
836 * @param int $otherId
837 * Duplicate contact which would be deleted after merge operation.
838 * @param array $migrationInfo
839 * Array of information about which elements to merge.
840 * @param string $mode
841 * Helps decide how to behave when there are conflicts.
13919cf8
J
842 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
843 * - Does a force merge otherwise (aggressive mode).
6a488035 844 *
ad37ac8e 845 * @param array $conflicts
846 *
77b97be7 847 * @return bool
6a488035 848 */
63ef778e 849 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
0971143c 850
c08fae40 851 $originalMigrationInfo = $migrationInfo;
6a488035
TO
852 foreach ($migrationInfo as $key => $val) {
853 if ($val === "null") {
0971143c 854 // Rule: Never overwrite with an empty value (in any mode)
6a488035
TO
855 unset($migrationInfo[$key]);
856 continue;
857 }
16254ae1 858 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
6a488035 859 substr($key, 0, 12) == 'move_custom_'
353ffa53
TO
860 ) and $val != NULL
861 ) {
0971143c
J
862 // Rule: If both main-contact, and other-contact have a field with a
863 // different value, then let $mode decide if to merge it or not
4eea8606 864 if (
e2cecb9c 865 (!empty($migrationInfo['rows'][$key]['main'])
866 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
867 // is probably true for other fields too - e.g. 'do_not_email' but
868 // leaving that investigation as a @todo - until tests can be written.
869 // Note the handling of this has test coverage - although the data-typing
870 // of '0' feels flakey we have insurance.
871 || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
872 )
4eea8606
J
873 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
874 ) {
fd630ef9 875
876 // note it down & lets wait for response from the hook.
877 // For no response $mode will decide if to skip this merge
878 $conflicts[$key] = NULL;
6a488035
TO
879 }
880 }
881 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
882 $locField = explode('_', $key);
883 $fieldName = $locField[2];
884 $fieldCount = $locField[3];
885
4ece0d26 886 // Rule: Catch address conflicts (same address type on both contacts)
6a488035 887 if ($fieldName == 'address') {
4ece0d26
J
888 if (
889 isset($migrationInfo['main_details']['location_blocks']['address']) &&
890 !empty($migrationInfo['main_details']['location_blocks']['address'])
891 ) {
b982316c
J
892
893 // Load the address we're inspecting from the 'other' contact
894 $addressRecord = $migrationInfo['other_details']['location_blocks']['address'][$fieldCount];
895 $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord);
896
897 // If it exists on the 'main' contact already, skip it. Otherwise
898 // if the location type exists already, log a conflict.
899 foreach ($migrationInfo['main_details']['location_blocks']['address'] as $mainAddressKey => $mainAddressRecord) {
900 if (self::addressIsSame($addressRecord, $mainAddressRecord)) {
d48ad2c0 901 unset($migrationInfo[$key]);
b982316c 902 break;
d48ad2c0 903 }
b982316c 904 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
4ece0d26
J
905 $conflicts[$key] = NULL;
906 break;
6a488035
TO
907 }
908 }
b982316c 909
6a488035
TO
910 }
911 }
4ece0d26 912 // For other locations, don't merge/add if the values are the same
6a488035 913 elseif ($migrationInfo['rows'][$key]['main'] == $migrationInfo['rows'][$key]['other']) {
6a488035
TO
914 unset($migrationInfo[$key]);
915 }
916 }
917 }
918
919 // A hook to implement other algorithms for choosing which contact to bias to when
920 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
921 // merge happens with new values filled in here. For a particular field / row not to be merged
922 // field should be unset from fields_in_conflict.
c08fae40 923 $migrationData = array(
924 'old_migration_info' => $originalMigrationInfo,
925 'mode' => $mode,
926 'fields_in_conflict' => $conflicts,
927 'merge_mode' => $mode,
928 'migration_info' => $migrationInfo,
929 );
6a488035
TO
930 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
931 $conflicts = $migrationData['fields_in_conflict'];
63ef778e 932 // allow hook to override / manipulate migrationInfo as well
c08fae40 933 $migrationInfo = $migrationData['migration_info'];
6a488035
TO
934
935 if (!empty($conflicts)) {
936 foreach ($conflicts as $key => $val) {
937 if ($val === NULL and $mode == 'safe') {
63ef778e 938 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
6a488035
TO
939 return TRUE;
940 }
941 else {
942 // copy over the resolved values
943 $migrationInfo[$key] = $val;
944 }
945 }
fd630ef9 946 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
947 if (array_key_exists('skip_merge', $migrationData)) {
948 return (bool) $migrationData['skip_merge'];
949 }
6a488035
TO
950 }
951 return FALSE;
952 }
953
d48ad2c0 954 /**
955 * Compare 2 addresses to see if they are the same.
956 *
957 * @param array $mainAddress
958 * @param array $comparisonAddress
959 *
960 * @return bool
961 */
962 static protected function addressIsSame($mainAddress, $comparisonAddress) {
963 $keysToIgnore = array('id', 'is_primary', 'is_billing', 'manual_geo_code', 'contact_id');
964 foreach ($comparisonAddress as $field => $value) {
965 if (in_array($field, $keysToIgnore)) {
966 continue;
967 }
968 if (!empty($value) && $mainAddress[$field] != $value) {
969 return FALSE;
970 }
971 }
972 return TRUE;
973 }
974
34917198
J
975 /**
976 * A function to build an array of information about location blocks that is
977 * required when merging location fields
978 *
979 * @return array
980 */
981 public static function getLocationBlockInfo() {
982 $locationBlocks = array(
983 'address' => array(
984 'label' => 'Address',
985 'displayField' => 'display',
986 'sortString' => 'location_type_id',
987 'hasLocation' => TRUE,
988 'hasType' => FALSE,
989 ),
990 'email' => array(
991 'label' => 'Email',
992 'displayField' => 'email',
993 'sortString' => 'location_type_id',
994 'hasLocation' => TRUE,
995 'hasType' => FALSE,
996 ),
997 'im' => array(
998 'label' => 'IM',
999 'displayField' => 'name',
1000 'sortString' => 'location_type_id,provider_id',
1001 'hasLocation' => TRUE,
1002 'hasType' => 'provider_id',
1003 ),
1004 'phone' => array(
1005 'label' => 'Phone',
1006 'displayField' => 'phone',
1007 'sortString' => 'location_type_id,phone_type_id',
1008 'hasLocation' => TRUE,
1009 'hasType' => 'phone_type_id',
1010 ),
1011 'website' => array(
1012 'label' => 'Website',
1013 'displayField' => 'url',
1014 'sortString' => 'website_type_id',
1015 'hasLocation' => FALSE,
1016 'hasType' => 'website_type_id',
1017 ),
1018 );
1019 return $locationBlocks;
1020 }
1021
6a488035
TO
1022 /**
1023 * A function to build an array of information required by merge function and the merge UI.
1024 *
98997235
TO
1025 * @param int $mainId
1026 * Main contact with whom merge has to happen.
1027 * @param int $otherId
1028 * Duplicate contact which would be deleted after merge operation.
201057c0 1029 * @param bool $checkPermissions
1030 * Should the logged in user's permissions be ignore. Setting this to false is
1031 * highly risky as it could cause data to be lost due to conflicts not showing up.
1032 * OTOH there is a risk a merger might view custom data they do not have permission to.
1033 * Hence for now only making this really explicit and making it reflect perms in
1034 * an api call.
1035 *
1036 * @todo review permissions issue!
6a488035 1037 *
77b97be7 1038 * @return array|bool|int
1e3e0eed
J
1039 *
1040 * rows => An array of arrays, each is row of merge information for the table
1041 * Format: move_fieldname, eg: move_contact_type
1042 * main => Value associated with the main contact
1043 * other => Value associated with the other contact
1044 * title => The title of the field to display in the merge table
1045 *
1046 * elements => An array of form elements for the merge UI
1047 *
1048 * rel_table_elements => An array of form elements for the merge UI for
1049 * entities related to the contact (eg: checkbox to move 'mailings')
1050 *
1e3e0eed
J
1051 * rel_tables => Stores the tables that have related entities for the contact
1052 * for example mailings, groups
1053 *
1054 * main_details => An array of core contact field values, eg: first_name, etc.
1055 * location_blocks => An array of location block data for the main contact
1056 * stored as the 'result' of an API call.
1057 * eg: main_details['location_blocks']['address'][0]['id']
1058 * eg: main_details['location_blocks']['email'][1]['id']
1059 *
1060 * other_details => As above, but for the 'other' contact
1061 *
1062 * migration_info => Stores the 'default' merge actions for each field which
1063 * is used when programatically merging contacts. It contains instructions
1064 * to move all fields from the 'other' contact to the 'main' contact, as
1065 * though the form had been submitted with those options.
1066 *
3058f4d9 1067 * @throws \CRM_Core_Exception
1068 * @throws \CiviCRM_API3_Exception
1069 * @throws \Exception
6a488035 1070 */
201057c0 1071 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
6a488035
TO
1072 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1073
1074 // Fetch contacts
1075 foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) {
353ffa53
TO
1076 $params = array(
1077 'contact_id' => $cid,
1078 'version' => 3,
c301f76e 1079 'return' => array_merge(array('display_name'), self::getContactFields()),
353ffa53 1080 );
6a488035
TO
1081 $result = civicrm_api('contact', 'get', $params);
1082
1083 if (empty($result['values'][$cid]['contact_type'])) {
1084 return FALSE;
1085 }
9b96584d
J
1086
1087 // CRM-18480: Cancel the process if the contact is already deleted
1088 if (isset($result['values'][$cid]['contact_is_deleted']) && !empty($result['values'][$cid]['contact_is_deleted'])) {
78272750 1089 throw new CRM_Core_Exception(ts('Cannot merge because the \'%1\' contact (ID %2) has been deleted.', array(1 => $moniker, 2 => $cid)));
9b96584d
J
1090 }
1091
6a488035
TO
1092 $$moniker = $result['values'][$cid];
1093 }
1094
cbed7205 1095 $fields = CRM_Contact_DAO_Contact::fields();
6a488035
TO
1096
1097 // FIXME: there must be a better way
1098 foreach (array('main', 'other') as $moniker) {
1099 $contact = &$$moniker;
1100 $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact);
1101 $value = empty($preferred_communication_method) ? array() : $preferred_communication_method;
1102 $specialValues[$moniker] = array(
1103 'preferred_communication_method' => $value,
0e357872 1104 'communication_style_id' => $value,
6a488035
TO
1105 );
1106
9b873358 1107 if (!empty($contact['preferred_communication_method'])) {
d58a19a1
TO
1108 // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct
1109 $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method'];
6a488035
TO
1110 $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR;
1111 }
1112 $names = array(
c301f76e 1113 'preferred_communication_method' => array(
1114 'newName' => 'preferred_communication_method_display',
1115 'groupName' => 'preferred_communication_method',
1116 ),
6a488035
TO
1117 );
1118 CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names);
a14df814 1119
0e357872
C
1120 if (!empty($contact['communication_style'])) {
1121 $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style'];
1122 }
6a488035
TO
1123 }
1124
1125 static $optionValueFields = array();
1126 if (empty($optionValueFields)) {
1127 $optionValueFields = CRM_Core_OptionValue::getFields();
1128 }
1129 foreach ($optionValueFields as $field => $params) {
1130 $fields[$field]['title'] = $params['title'];
1131 }
1132
4eea8606 1133 $compareFields = self::retrieveFields($main, $other);
6a488035
TO
1134
1135 $rows = $elements = $relTableElements = $migrationInfo = array();
1136
4eea8606 1137 foreach ($compareFields['contact'] as $field) {
4d5f18cc 1138 if ($field == 'contact_sub_type') {
1139 // CRM-15681 don't display sub-types in UI
1140 continue;
1141 }
6a488035
TO
1142 foreach (array('main', 'other') as $moniker) {
1143 $contact = &$$moniker;
1144 $value = CRM_Utils_Array::value($field, $contact);
1145 if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) {
1146 $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
1147 }
1148 $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value;
a7488080 1149 if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) {
6a488035
TO
1150 if ($value) {
1151 $value = str_replace('-', '', $value);
1152 $label = CRM_Utils_Date::customFormat($label);
1153 }
1154 else {
1155 $value = "null";
1156 }
1157 }
a7488080 1158 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
6a488035
TO
1159 if ($label === '0') {
1160 $label = ts('[ ]');
1161 }
1162 if ($label === '1') {
1163 $label = ts('[x]');
1164 }
00f3da2e
BS
1165 }
1166 elseif ($field == 'individual_prefix' || $field == 'prefix_id') {
1167 $label = CRM_Utils_Array::value('individual_prefix', $contact);
6a488035
TO
1168 $value = CRM_Utils_Array::value('prefix_id', $contact);
1169 $field = 'prefix_id';
00f3da2e
BS
1170 }
1171 elseif ($field == 'individual_suffix' || $field == 'suffix_id') {
1172 $label = CRM_Utils_Array::value('individual_suffix', $contact);
6a488035
TO
1173 $value = CRM_Utils_Array::value('suffix_id', $contact);
1174 $field = 'suffix_id';
1175 }
4f88c9cf 1176 elseif ($field == 'gender_id' && !empty($value)) {
5b28be84
J
1177 $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id'));
1178 $label = $genderOptions['values'][$value];
4f88c9cf
C
1179 }
1180 elseif ($field == 'current_employer_id' && !empty($value)) {
1181 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
1182 }
6a488035
TO
1183 $rows["move_$field"][$moniker] = $label;
1184 if ($moniker == 'other') {
7154d2a4
BS
1185 //CRM-14334
1186 if ($value === NULL || $value == '') {
6a488035
TO
1187 $value = 'null';
1188 }
1189 if ($value === 0 or $value === '0') {
1190 $value = $qfZeroBug;
1191 }
8cc574cf 1192 if (is_array($value) && empty($value[1])) {
6a488035
TO
1193 $value[1] = NULL;
1194 }
13919cf8
J
1195
1196 // Display a checkbox to migrate, only if the values are different
1197 if ($value != $main[$field]) {
1198 $elements[] = array('advcheckbox', "move_$field", NULL, NULL, NULL, $value);
1199 }
1200
6a488035
TO
1201 $migrationInfo["move_$field"] = $value;
1202 }
1203 }
1204 $rows["move_$field"]['title'] = $fields[$field]['title'];
1205 }
1206
eb61dc07
J
1207 // Handle location blocks.
1208 // @todo OpenID not in API yet, so is not supported here.
65a35632 1209
087f00ec 1210 // Set up useful information about the location blocks
34917198 1211 $locationBlocks = self::getLocationBlockInfo();
087f00ec
J
1212
1213 $locations = array(
1214 'main' => array(),
1215 'other' => array(),
13919cf8 1216 );
b814df56 1217
087f00ec
J
1218 // @todo This could probably be defined and used earlier
1219 $mergeTargets = array(
1220 'main' => $mainId,
1221 'other' => $otherId,
1222 );
6a488035 1223
087f00ec 1224 foreach ($locationBlocks as $blockName => $blockInfo) {
6a488035 1225
087f00ec
J
1226 // Collect existing fields from both 'main' and 'other' contacts first
1227 // This allows us to match up location/types when building the table rows
1228 foreach ($mergeTargets as $moniker => $cid) {
6a488035 1229 $cnt = 1;
b932e89e
J
1230 $searchParams = array(
1231 'version' => 3,
1232 'contact_id' => $cid,
087f00ec
J
1233 // CRM-17556 Order by field-specific criteria
1234 'options' => array(
1235 'sort' => $blockInfo['sortString'],
1236 ),
b932e89e 1237 );
b932e89e 1238 $values = civicrm_api($blockName, 'get', $searchParams);
087f00ec
J
1239 if ($values['count']) {
1240 $cnt = 0;
1241 foreach ($values['values'] as $index => $value) {
1242 $locations[$moniker][$blockName][$cnt] = $value;
1243 // Fix address display
eb61dc07 1244 if ($blockName == 'address') {
087f00ec 1245 CRM_Core_BAO_Address::fixAddress($value);
ae6455b2 1246 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address::format($value);
6a488035 1247 }
abb422f9 1248
087f00ec 1249 $cnt++;
6a488035
TO
1250 }
1251 }
1252 }
6a488035 1253
087f00ec
J
1254 // Now, build the table rows appropriately, based off the information on
1255 // the 'other' contact
34917198
J
1256 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1257 foreach ($locations['other'][$blockName] as $count => $value) {
6a488035 1258
087f00ec 1259 $displayValue = $value[$blockInfo['displayField']];
65a35632 1260
087f00ec
J
1261 // Add this value to the table rows
1262 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
65a35632 1263
087f00ec
J
1264 // CRM-17556 Only display 'main' contact value if it's the same location + type
1265 // Look it up from main values...
65a35632 1266
087f00ec
J
1267 $lookupLocation = FALSE;
1268 if ($blockInfo['hasLocation']) {
1269 $lookupLocation = $value['location_type_id'];
1270 }
65a35632 1271
087f00ec
J
1272 $lookupType = FALSE;
1273 if ($blockInfo['hasType']) {
1274 $lookupType = $value[$blockInfo['hasType']];
1275 }
65a35632 1276
34917198
J
1277 // Hold ID of main contact's matching block
1278 $mainContactBlockId = 0;
1279
087f00ec
J
1280 if (!empty($locations['main'][$blockName])) {
1281 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1282 // No location/type, or matching location and type
1283 if (
1284 (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id'])
1285 && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])
1286 ) {
34917198 1287 // Set this value as the default against the 'other' contact value
087f00ec 1288 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
34917198 1289 $mainContactBlockId = $mainValueCheck['id'];
087f00ec
J
1290 break;
1291 }
6a488035 1292 }
087f00ec 1293 }
65a35632 1294
087f00ec
J
1295 // Add checkbox to migrate data from 'other' to 'main'
1296 $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}");
65a35632 1297
087f00ec
J
1298 // Flag up this field to skipMerge function (@todo: do we need to?)
1299 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
65a35632 1300
34917198 1301 // Add a hidden field to store the ID of the target main contact block
972947a7 1302 $elements[] = array('hidden', "location_blocks[$blockName][$count][mainContactBlockId]", $mainContactBlockId);
34917198 1303
087f00ec
J
1304 // Setup variables
1305 $thisTypeId = FALSE;
1306 $thisLocId = FALSE;
65a35632 1307
087f00ec
J
1308 // Provide a select drop-down for the location's location type
1309 // eg: Home, Work...
65a35632 1310
087f00ec 1311 $js = NULL;
65a35632 1312
087f00ec
J
1313 if ($blockInfo['hasLocation']) {
1314
5b28be84
J
1315 // Load the location options for this entity
1316 $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id'));
1317
087f00ec
J
1318 // JS lookup 'main' contact's location (if there are any)
1319 if (!empty($locations['main'][$blockName])) {
1320 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'locTypeId' );");
6a488035 1321 }
087f00ec
J
1322
1323 $thisLocId = $value['location_type_id'];
1324
1325 // Put this field's location type at the top of the list
5b28be84 1326 $tmpIdList = $locationOptions['values'];
087f00ec
J
1327 $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]);
1328 unset($tmpIdList[$thisLocId]);
1329
1330 // Add the element
eb61dc07
J
1331 $elements[] = array(
1332 'select',
972947a7 1333 "location_blocks[$blockName][$count][locTypeId]",
eb61dc07 1334 NULL,
087f00ec 1335 $defaultLocId + $tmpIdList,
eb61dc07 1336 $js,
6a488035 1337 );
087f00ec
J
1338
1339 // Add the relevant information to the $migrationInfo
1340 // Keep location-type-id same as that of other-contact
1341 // @todo Check this logic out
1342 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
abb422f9 1343 if ($blockName != 'address') {
972947a7 1344 $elements[] = array('advcheckbox', "location_blocks[{$blockName}][$count][operation]", NULL, ts('add new'));
087f00ec 1345 // always use add operation
abb422f9 1346 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
6a488035 1347 }
087f00ec 1348
6a488035 1349 }
6a488035 1350
087f00ec
J
1351 // Provide a select drop-down for the location's type/provider
1352 // eg websites: Google+, Facebook...
1353
6a488035 1354 $js = NULL;
087f00ec
J
1355
1356 if ($blockInfo['hasType']) {
1357
5b28be84
J
1358 // Load the type options for this entity
1359 $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType']));
1360
1361 // CRM-17556 Set up JS lookup of 'main' contact's value by type
087f00ec 1362 if (!empty($locations['main'][$blockName])) {
abb422f9 1363 $js = array('onChange' => "mergeBlock('$blockName', this, $count, 'typeTypeId' );");
087f00ec
J
1364 }
1365
1366 $thisTypeId = $value[$blockInfo['hasType']];
1367
1368 // Put this field's location type at the top of the list
5b28be84 1369 $tmpIdList = $typeOptions['values'];
087f00ec
J
1370 $defaultTypeId = array($thisTypeId => $tmpIdList[$thisTypeId]);
1371 unset($tmpIdList[$thisTypeId]);
1372
1373 // Add the element
65a35632
J
1374 $elements[] = array(
1375 'select',
972947a7 1376 "location_blocks[$blockName][$count][typeTypeId]",
65a35632 1377 NULL,
087f00ec 1378 $defaultTypeId + $tmpIdList,
65a35632
J
1379 $js,
1380 );
65a35632 1381
1e3e0eed 1382 // Add the information to the migrationInfo
34917198 1383 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
65a35632 1384
6a488035 1385 }
087f00ec
J
1386
1387 // Set the label for this row
34917198
J
1388 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
1389 if (!empty($thisLocId)) {
5b28be84 1390 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
6a488035 1391 }
34917198 1392 if (!empty($thisTypeId)) {
5b28be84 1393 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
34917198
J
1394 }
1395 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
65a35632 1396
34917198 1397 } // End loop through 'other' locations of this type
087f00ec 1398
34917198 1399 } // End if 'other' location for this type exists
6a488035 1400
34917198 1401 } // End loop through each location block entity
6a488035
TO
1402
1403 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1404 $config = CRM_Core_Config::singleton();
1405 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1406 $mainUser = NULL;
1407 if ($mainUfId) {
1408 // d6 compatible
1409 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1410 $mainUser = user_load($mainUfId);
1411 }
1412 elseif ($config->userFramework == 'Joomla') {
1413 $mainUser = JFactory::getUser($mainUfId);
1414 }
1415 }
1416 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1417 $otherUser = NULL;
1418 if ($otherUfId) {
1419 // d6 compatible
1420 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1421 $otherUser = user_load($otherUfId);
1422 }
1423 elseif ($config->userFramework == 'Joomla') {
1424 $otherUser = JFactory::getUser($otherUfId);
1425 }
1426 }
1427
1428 $relTables = CRM_Dedupe_Merger::relTables();
1429 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1430 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1431 foreach ($relTables as $name => $null) {
1432 if (!in_array($name, $activeRelTables) &&
1433 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1434 ) {
1435 unset($relTables[$name]);
1436 continue;
1437 }
1438
1439 $relTableElements[] = array('checkbox', "move_$name");
1440 $migrationInfo["move_$name"] = 1;
1441
1442 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1443 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1444 if ($name == 'rel_table_users') {
1445 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1446 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1447 $find = array('$ufid', '$ufname');
1448 if ($mainUser) {
1449 $replace = array($mainUfId, $mainUser->name);
1450 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1451 }
1452 if ($otherUser) {
1453 $replace = array($otherUfId, $otherUser->name);
1454 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1455 }
1456 }
1457 if ($name == 'rel_table_memberships') {
1458 $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new'));
1459 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1460 }
1461 }
1462 foreach ($relTables as $name => $null) {
1463 $relTables["move_$name"] = $relTables[$name];
1464 unset($relTables[$name]);
1465 }
1466
1467 // handle custom fields
201057c0 1468 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1,
1469 CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035
TO
1470 );
1471 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1,
201057c0 1472 CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035
TO
1473 );
1474 CRM_Core_DAO::freeResult();
1475
1476 foreach ($otherTree as $gid => $group) {
1477 $foundField = FALSE;
1478 if (!isset($group['fields'])) {
1479 continue;
1480 }
1481
1482 foreach ($group['fields'] as $fid => $field) {
4eea8606 1483 if (in_array($fid, $compareFields['custom'])) {
6a488035
TO
1484 if (!$foundField) {
1485 $rows["custom_group_$gid"]['title'] = $group['title'];
1486 $foundField = TRUE;
1487 }
a7488080 1488 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
6a488035 1489 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
51a3717f 1490 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1491 }
1492 }
1493 $value = "null";
a7488080 1494 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
6a488035 1495 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
51a3717f 1496 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1497 if ($values['data'] === 0 || $values['data'] === '0') {
1498 $values['data'] = $qfZeroBug;
d58a19a1 1499 }
6a488035 1500 $value = ($values['data']) ? $values['data'] : $value;
d58a19a1 1501 }
6a488035
TO
1502 }
1503 $rows["move_custom_$fid"]['title'] = $field['label'];
1504
1505 $elements[] = array('advcheckbox', "move_custom_$fid", NULL, NULL, NULL, $value);
1506 $migrationInfo["move_custom_$fid"] = $value;
1507 }
1508 }
1509 }
abb422f9 1510
6a488035
TO
1511 $result = array(
1512 'rows' => $rows,
1513 'elements' => $elements,
1514 'rel_table_elements' => $relTableElements,
6a488035
TO
1515 'rel_tables' => $relTables,
1516 'main_details' => $main,
1517 'other_details' => $other,
1518 'migration_info' => $migrationInfo,
1519 );
1520
34917198
J
1521 $result['main_details']['location_blocks'] = $locations['main'];
1522 $result['other_details']['location_blocks'] = $locations['other'];
6a488035
TO
1523
1524 return $result;
1525 }
1526
1527 /**
1528 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1529 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1530 * A superset of moveContactBelongings() function.
1531 *
98997235
TO
1532 * @param int $mainId
1533 * Main contact with whom merge has to happen.
1534 * @param int $otherId
1535 * Duplicate contact which would be deleted after merge operation.
77b97be7
EM
1536 *
1537 * @param $migrationInfo
6a488035 1538 *
3058f4d9 1539 * @param bool $checkPermissions
1540 * Respect logged in user permissions.
1541 *
77b97be7 1542 * @return bool
6a488035 1543 */
3058f4d9 1544 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
6a488035
TO
1545 if (empty($migrationInfo)) {
1546 return FALSE;
1547 }
1548
1549 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1550 $relTables = CRM_Dedupe_Merger::relTables();
1551 $moveTables = $locBlocks = $tableOperations = array();
1552 foreach ($migrationInfo as $key => $value) {
1553 if ($value == $qfZeroBug) {
1554 $value = '0';
1555 }
7154d2a4 1556 if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) ||
353ffa53 1557 substr($key, 0, 12) == 'move_custom_') &&
7154d2a4
BS
1558 $value != NULL
1559 ) {
6a488035
TO
1560 $submitted[substr($key, 5)] = $value;
1561 }
34917198
J
1562
1563 // Set up initial information for handling migration of location blocks
6a488035
TO
1564 elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
1565 $locField = explode('_', $key);
1566 $fieldName = $locField[2];
1567 $fieldCount = $locField[3];
34917198
J
1568
1569 // Set up the operation type (add/overwrite)
6832d4a9 1570 // Ignore operation for websites
34917198 1571 // @todo Tidy this up
6832d4a9
J
1572 $operation = 0;
1573 if ($fieldName != 'website') {
972947a7 1574 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
6832d4a9 1575 }
6a488035
TO
1576 // default operation is overwrite.
1577 if (!$operation) {
1578 $operation = 2;
1579 }
6a488035 1580 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
0971143c 1581
6a488035 1582 }
34917198 1583
6a488035
TO
1584 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1585 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1586 if (array_key_exists('operation', $migrationInfo)) {
1587 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1588 if (array_key_exists($key, $migrationInfo['operation'])) {
1589 $tableOperations[$table] = $migrationInfo['operation'][$key];
1590 }
1591 }
1592 }
1593 }
1594 }
1595
eb61dc07 1596 // **** Do location related migration.
eb61dc07 1597 // @todo Handle OpenID (not currently in API).
6a488035 1598 if (!empty($locBlocks)) {
13919cf8 1599
34917198 1600 $locationBlocks = self::getLocationBlockInfo();
6a488035
TO
1601
1602 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
1603 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
1604
1605 foreach ($locBlocks as $name => $block) {
1606 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1607 continue;
1608 }
34917198 1609 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
6a488035
TO
1610 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1611 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1612
1613 foreach ($block as $blkCount => $values) {
6a488035 1614
34917198
J
1615 // For the block which belongs to other-contact, link the location block to main-contact
1616 $otherBlockDAO = new $daoName();
1617 $otherBlockDAO->contact_id = $mainId;
6a488035 1618
34917198
J
1619 // Get the ID of this block on the 'other' contact, otherwise skip
1620 $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
6a488035
TO
1621 if (!$otherBlockId) {
1622 continue;
1623 }
6a488035 1624 $otherBlockDAO->id = $otherBlockId;
6a488035 1625
34917198
J
1626 // Add/update location and type information from the form, if applicable
1627 if ($locationBlocks[$name]['hasLocation']) {
972947a7 1628 $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
34917198 1629 $otherBlockDAO->location_type_id = $locTypeId;
08ef1f91 1630 }
34917198 1631 if ($locationBlocks[$name]['hasType']) {
972947a7 1632 $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
34917198 1633 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
08ef1f91
R
1634 }
1635
34917198 1636 // Get main block ID
972947a7 1637 $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
6a488035
TO
1638
1639 // if main contact already has primary & billing, set the flags to 0.
1640 if ($primaryDAOId) {
1641 $otherBlockDAO->is_primary = 0;
1642 }
1643 if ($billingDAOId) {
1644 $otherBlockDAO->is_billing = 0;
1645 }
1646
34917198 1647 $operation = CRM_Utils_Array::value('operation', $values, 2);
6a488035 1648 // overwrite - need to delete block which belongs to main-contact.
34917198 1649 if (!empty($mainBlockId) && ($operation == 2)) {
6a488035
TO
1650 $deleteDAO = new $daoName();
1651 $deleteDAO->id = $mainBlockId;
1652 $deleteDAO->find(TRUE);
1653
1654 // if we about to delete a primary / billing block, set the flags for new block
1655 // that we going to assign to main-contact
1656 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
1657 $otherBlockDAO->is_primary = 1;
1658 }
1659 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
1660 $otherBlockDAO->is_billing = 1;
1661 }
1662
1663 $deleteDAO->delete();
1664 $deleteDAO->free();
1665 }
1666
1667 $otherBlockDAO->update();
1668 $otherBlockDAO->free();
1669 }
1670 }
1671 }
1672
1673 // **** Do tables related migrations
1674 if (!empty($moveTables)) {
1675 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
1676 unset($moveTables, $tableOperations);
1677 }
1678
1679 // **** Do contact related migrations
1680 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
1681
1682 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1683 $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
1684 $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
1685 $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
aa62b355 1686 $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
6a488035
TO
1687 $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
1688 $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
1689 $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
1690 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1691
1692 // fix custom fields so they're edible by createProfileContact()
1693 static $treeCache = array();
1694 if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
1695 $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'],
1696 CRM_Core_DAO::$_nullObject, NULL, -1
1697 );
1698 }
1699 $cgTree = &$treeCache[$migrationInfo['main_details']['contact_type']];
1700
1701 $cFields = array();
1702 foreach ($cgTree as $key => $group) {
1703 if (!isset($group['fields'])) {
1704 continue;
1705 }
1706 foreach ($group['fields'] as $fid => $field) {
1707 $cFields[$fid]['attributes'] = $field;
1708 }
1709 }
1710
1711 if (!isset($submitted)) {
1712 $submitted = array();
1713 }
1714 foreach ($submitted as $key => $value) {
1715 if (substr($key, 0, 7) == 'custom_') {
1716 $fid = (int) substr($key, 7);
0e357872
C
1717 if (empty($cFields[$fid])) {
1718 continue;
1719 }
6a488035
TO
1720 $htmlType = $cFields[$fid]['attributes']['html_type'];
1721 switch ($htmlType) {
1722 case 'File':
1723 $customFiles[] = $fid;
1724 unset($submitted["custom_$fid"]);
1725 break;
1726
1727 case 'Select Country':
1728 case 'Select State/Province':
8cee0c70 1729 $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
6a488035
TO
1730 break;
1731
69239109 1732 case 'Select Date':
1733 if ($cFields[$fid]['attributes']['is_view']) {
1734 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
1735 }
1736 break;
1737
6a488035
TO
1738 case 'CheckBox':
1739 case 'AdvMulti-Select':
1740 case 'Multi-Select':
1741 case 'Multi-Select Country':
1742 case 'Multi-Select State/Province':
1743 // Merge values from both contacts for multivalue fields, CRM-4385
1744 // get the existing custom values from db.
1745 $customParams = array('entityID' => $mainId, $key => TRUE);
1746 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
a7488080 1747 if (!empty($customfieldValues[$key])) {
6a488035
TO
1748 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1749 if (is_array($existingValue) && !empty($existingValue)) {
1750 $mergeValue = $submmtedCustomValue = array();
1751 if ($value) {
1752 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1753 }
1754
1755 //hack to remove null and duplicate values from array.
1756 foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
1757 if ($v != '' && !in_array($v, $mergeValue)) {
1758 $mergeValue[] = $v;
1759 }
1760 }
1761
1762 //keep state and country as array format.
1763 //for checkbox and m-select format w/ VALUE_SEPARATOR
1764 if (in_array($htmlType, array(
353ffa53
TO
1765 'CheckBox',
1766 'Multi-Select',
c301f76e 1767 'AdvMulti-Select',
353ffa53 1768 ))) {
6a488035 1769 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
353ffa53
TO
1770 $mergeValue
1771 ) . CRM_Core_DAO::VALUE_SEPARATOR;
6a488035
TO
1772 }
1773 else {
1774 $submitted[$key] = $mergeValue;
1775 }
1776 }
1777 }
1778 elseif (in_array($htmlType, array(
353ffa53 1779 'Multi-Select Country',
c301f76e 1780 'Multi-Select State/Province',
353ffa53 1781 ))) {
6a488035
TO
1782 //we require submitted values should be in array format
1783 if ($value) {
1784 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1785 //hack to remove null values from array.
1786 $mergeValue = array();
1787 foreach ($mergeValueArray as $k => $v) {
1788 if ($v != '') {
1789 $mergeValue[] = $v;
1790 }
1791 }
1792 $submitted[$key] = $mergeValue;
1793 }
1794 }
1795 break;
1796
1797 default:
1798 break;
1799 }
1800 }
1801 }
1802
1803 // **** Do file custom fields related migrations
1804 // FIXME: move this someplace else (one of the BAOs) after discussing
b3fdbf3d 1805 // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
6a488035
TO
1806 // like, delete a file...
1807
1808 if (!isset($customFiles)) {
1809 $customFiles = array();
1810 }
1811 foreach ($customFiles as $customId) {
1812 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
1813
1814 // get the contact_id -> file_id mapping
1815 $fileIds = array();
1816 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
9d2678f4 1817 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
1818 while ($dao->fetch()) {
1819 $fileIds[$dao->entity_id] = $dao->file_id;
1820 }
1821 $dao->free();
1822
1823 // delete the main contact's file
1824 if (!empty($fileIds[$mainId])) {
b3fdbf3d 1825 CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
6a488035
TO
1826 }
1827
1828 // move the other contact's file to main contact
1829 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
481a74f4 1830 if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
d58a19a1 1831 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
6a488035
TO
1832 }
1833 else {
1834 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
1835 }
9d2678f4 1836 CRM_Core_DAO::executeQuery($sql);
6a488035 1837
481a74f4 1838 if (CRM_Core_DAO::singleValueQuery("
6a488035
TO
1839 SELECT id
1840 FROM civicrm_entity_file
353ffa53
TO
1841 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
1842 ) {
6a488035
TO
1843 $sql = "
1844 UPDATE civicrm_entity_file
1845 SET entity_id = {$mainId}
1846 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
1847 }
1848 else {
1849 $sql = "
1850 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
1851 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
1852 }
9d2678f4 1853 CRM_Core_DAO::executeQuery($sql);
6a488035
TO
1854 }
1855
1856 // move view only custom fields CRM-5362
1857 $viewOnlyCustomFields = array();
1858 foreach ($submitted as $key => $value) {
1859 $fid = (int) substr($key, 7);
8cc574cf 1860 if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
6a488035
TO
1861 $viewOnlyCustomFields[$key] = $value;
1862 }
1863 }
1864
1865 // special case to set values for view only, CRM-5362
1866 if (!empty($viewOnlyCustomFields)) {
1867 $viewOnlyCustomFields['entityID'] = $mainId;
1868 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1869 }
1870
3058f4d9 1871 if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') &&
1872 CRM_Core_Permission::check('delete contacts'))
6a488035
TO
1873 ) {
1874 // if ext id is submitted then set it null for contact to be deleted
a7488080 1875 if (!empty($submitted['external_identifier'])) {
6a488035
TO
1876 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1877 CRM_Core_DAO::executeQuery($query);
1878 }
5ea06a7b 1879 civicrm_api3('contact', 'delete', array('id' => $otherId));
6a488035 1880 }
6a488035 1881
4d5f18cc 1882 // CRM-15681 merge sub_types
1883 if ($other_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['other_details'])) {
1884 if ($main_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['main_details'])) {
481a74f4 1885 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
0db6c3e1
TO
1886 }
1887 else {
4d5f18cc 1888 $submitted['contact_sub_type'] = $other_sub_types;
1889 }
1890 }
1891
6a488035
TO
1892 // **** Update contact related info for the main contact
1893 if (!empty($submitted)) {
1894 $submitted['contact_id'] = $mainId;
1895
1896 //update current employer field
1897 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1898 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1899 $submitted['current_employer'] = $submitted['current_employer_id'];
0db6c3e1
TO
1900 }
1901 else {
6a488035
TO
1902 $submitted['current_employer'] = '';
1903 }
1904 unset($submitted['current_employer_id']);
1905 }
1906
00f3da2e 1907 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
481a74f4 1908 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
00f3da2e
BS
1909 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1910 }
481a74f4 1911 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
00f3da2e
BS
1912 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1913 }
1914
6a488035 1915 CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
6a488035
TO
1916 }
1917
61bc2c0f 1918 CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
f00283b5 1919 self::createMergeActivities($mainId, $otherId);
5ea06a7b 1920
6a488035
TO
1921 return TRUE;
1922 }
16254ae1
ARW
1923
1924 /**
f00283b5 1925 * Get fields in the contact table suitable for merging.
1926 *
a6c01b45 1927 * @return array
f00283b5 1928 * Array of field names to be potentially merged.
16254ae1 1929 */
00be9182 1930 public static function getContactFields() {
16254ae1 1931 $contactFields = CRM_Contact_DAO_Contact::fields();
353ffa53
TO
1932 $invalidFields = array(
1933 'api_key',
353ffa53
TO
1934 'created_date',
1935 'display_name',
1936 'hash',
1937 'id',
1938 'modified_date',
1939 'primary_contact_id',
1940 'sort_name',
c301f76e 1941 'user_unique_id',
353ffa53 1942 );
bdd7870e
RN
1943 foreach ($contactFields as $field => $value) {
1944 if (in_array($field, $invalidFields)) {
1945 unset($contactFields[$field]);
1946 }
1947 }
16254ae1
ARW
1948 return array_keys($contactFields);
1949 }
ada104d5
AW
1950
1951 /**
1952 * Added for CRM-12695
c301f76e 1953 * Based on the contactID provided
ada104d5
AW
1954 * add/update membership(s) to related contacts
1955 *
c301f76e 1956 * @param int $contactID
ada104d5 1957 */
00be9182 1958 public static function addMembershipToRealtedContacts($contactID) {
ada104d5
AW
1959 $dao = new CRM_Member_DAO_Membership();
1960 $dao->contact_id = $contactID;
1961 $dao->is_test = 0;
1962 $dao->find();
1963
1964 //checks membership of contact itself
1965 while ($dao->fetch()) {
1966 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1967 if ($relationshipTypeId) {
1968 $membershipParams = array(
1969 'id' => $dao->id,
1970 'contact_id' => $dao->contact_id,
1971 'membership_type_id' => $dao->membership_type_id,
1972 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1973 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1974 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1975 'source' => $dao->source,
21dfd5f5 1976 'status_id' => $dao->status_id,
ada104d5
AW
1977 );
1978 // create/update membership(s) for related contact(s)
1979 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1980 } // end of if relationshipTypeId
1981 }
1982 }
96025800 1983
3ae0ae3d 1984 /**
1985 * Add custom tables that extend contacts to the list of contact references.
1986 *
1987 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
1988 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
1989 * - the down side is it is not cached.
1990 *
1991 * Further changes should be include tests in the CRM_Core_MergerTest class
1992 * to ensure that disabled, subtype, multiple etc groups are still captured.
1993 *
1994 * @param array $cidRefs
1995 */
1996 public static function addCustomTablesExtendingContactsToCidRefs(&$cidRefs) {
1997 $customValueTables = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact');
1998 $customValueTables->find();
1999 while ($customValueTables->fetch()) {
2000 $cidRefs[$customValueTables->table_name] = array('entity_id');
2001 }
2002 }
2003
f00283b5 2004 /**
2005 * Create activities tracking the merge on affected contacts.
2006 *
2007 * @param int $mainId
2008 * @param int $otherId
2009 *
2010 * @throws \CiviCRM_API3_Exception
2011 */
2012 public static function createMergeActivities($mainId, $otherId) {
2013 $params = array(
2014 1 => $otherId,
2015 2 => $mainId,
2016 );
2017 $activity = civicrm_api3('activity', 'create', array(
dc33398e
J
2018 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
2019 $mainId,
f00283b5 2020 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
2021 'target_contact_id' => $mainId,
2022 'activity_type_id' => 'Contact Merged',
2023 'status_id' => 'Completed',
2024 ));
4d834a99 2025 if (civicrm_api3('Setting', 'getvalue', array('name' => 'contact_undelete', 'group' => 'CiviCRM Preferences'))) {
2026 civicrm_api3('activity', 'create', array(
dc33398e
J
2027 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
2028 $otherId,
4d834a99 2029 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
2030 'target_contact_id' => $otherId,
2031 'activity_type_id' => 'Contact Deleted by Merge',
2032 'parent_id' => $activity['id'],
2033 'status_id' => 'Completed',
2034 ));
2035 }
f00283b5 2036 }
2037
2988f5c7 2038 /**
2039 * Get Duplicate Pairs based on a rule for a group.
2040 *
2041 * @param int $rule_group_id
2042 * @param int $group_id
2043 * @param bool $reloadCacheIfEmpty
2044 * @param int $batchLimit
2045 * @param bool $isSelected
3058f4d9 2046 * @param array|string $orderByClause
66eceb0b 2047 * @param bool $includeConflicts
e23e26ec 2048 * @param array $criteria
2049 * Additional criteria to narrow down the merge group.
2988f5c7 2050 *
3058f4d9 2051 * @param bool $checkPermissions
2052 * Respect logged in user permissions.
2053 *
2988f5c7 2054 * @return array
3058f4d9 2055 * Array of matches meeting the criteria.
2988f5c7 2056 */
3058f4d9 2057 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $orderByClause = '', $includeConflicts = TRUE, $criteria = array(), $checkPermissions = TRUE) {
2988f5c7 2058 $where = self::getWhereString($batchLimit, $isSelected);
3058f4d9 2059 $cacheKeyString = self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions);
2988f5c7 2060 $join = self::getJoinOnDedupeTable();
66eceb0b 2061 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
2988f5c7 2062 if (empty($dupePairs) && $reloadCacheIfEmpty) {
2063 // If we haven't found any dupes, probably cache is empty.
66eceb0b 2064 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
2065 // until we have done some processing.
3058f4d9 2066 CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions);
66eceb0b 2067 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, 0, array(), $orderByClause, $includeConflicts);
2988f5c7 2068 return $dupePairs;
2069 }
2070 return $dupePairs;
2071 }
2072
2ae26001 2073 /**
2074 * Get the cache key string for the merge action.
2075 *
2076 * @param int $rule_group_id
2077 * @param int $group_id
e23e26ec 2078 * @param array $criteria
2079 * Additional criteria to narrow down the merge group.
2080 * Currently we are only supporting the key 'contact' within it.
2ae26001 2081 *
3058f4d9 2082 * @param bool $checkPermissions
2083 * Respect the users permissions.
2084 *
2ae26001 2085 * @return string
2086 */
3058f4d9 2087 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = array(), $checkPermissions = TRUE) {
2ae26001 2088 $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
2089 $cacheKeyString = "merge {$contactType}";
2090 $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
2091 $cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
e23e26ec 2092 $cacheKeyString .= !empty($criteria) ? serialize($criteria) : '_0';
3058f4d9 2093 if ($checkPermissions) {
2094 $contactID = CRM_Core_Session::getLoggedInContactID();
2095 if (!$contactID) {
2096 // Distinguish between no permission check & no logged in user.
2097 $contactID = 'null';
2098 }
2099 $cacheKeyString .= '_' . $contactID;
2100 }
2101 else {
2102 $cacheKeyString .= '_0';
2103 }
2ae26001 2104 return $cacheKeyString;
2105 }
2106
6a488035 2107}