| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | CiviCRM version 5 | |
| 5 | +--------------------------------------------------------------------+ |
| 6 | | Copyright CiviCRM LLC (c) 2004-2019 | |
| 7 | +--------------------------------------------------------------------+ |
| 8 | | This file is a part of CiviCRM. | |
| 9 | | | |
| 10 | | CiviCRM is free software; you can copy, modify, and distribute it | |
| 11 | | under the terms of the GNU Affero General Public License | |
| 12 | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | |
| 13 | | | |
| 14 | | CiviCRM is distributed in the hope that it will be useful, but | |
| 15 | | WITHOUT ANY WARRANTY; without even the implied warranty of | |
| 16 | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | |
| 17 | | See the GNU Affero General Public License for more details. | |
| 18 | | | |
| 19 | | You should have received a copy of the GNU Affero General Public | |
| 20 | | License and the CiviCRM Licensing Exception along | |
| 21 | | with this program; if not, contact CiviCRM LLC | |
| 22 | | at info[AT]civicrm[DOT]org. If you have questions about the | |
| 23 | | GNU Affero General Public License or the licensing of CiviCRM, | |
| 24 | | see the CiviCRM license FAQ at http://civicrm.org/licensing | |
| 25 | +--------------------------------------------------------------------+ |
| 26 | */ |
| 27 | |
| 28 | /** |
| 29 | * |
| 30 | * @package CRM |
| 31 | * @copyright CiviCRM LLC (c) 2004-2019 |
| 32 | */ |
| 33 | class CRM_Dedupe_Merger { |
| 34 | |
| 35 | /** |
| 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 |
| 39 | * @return array |
| 40 | */ |
| 41 | public static function relTables() { |
| 42 | |
| 43 | if (!isset(Civi::$statics[__CLASS__]['relTables'])) { |
| 44 | |
| 45 | // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below |
| 46 | // if the url can't be retrieved. A more standardised way to retrieve them is. |
| 47 | // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id & |
| 48 | // we may need a different function when it is not known. |
| 49 | $title = $userRecordUrl = ''; |
| 50 | |
| 51 | $config = CRM_Core_Config::singleton(); |
| 52 | if ($config->userSystem->is_drupal) { |
| 53 | $userRecordUrl = CRM_Utils_System::url('user/%ufid'); |
| 54 | $title = ts('%1 User: %2; user id: %3', [ |
| 55 | 1 => $config->userFramework, |
| 56 | 2 => '$ufname', |
| 57 | 3 => '$ufid', |
| 58 | ]); |
| 59 | } |
| 60 | elseif ($config->userFramework == 'Joomla') { |
| 61 | $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'; |
| 62 | $title = ts('%1 User: %2; user id: %3', [ |
| 63 | 1 => $config->userFramework, |
| 64 | 2 => '$ufname', |
| 65 | 3 => '$ufid', |
| 66 | ]); |
| 67 | } |
| 68 | |
| 69 | $relTables = [ |
| 70 | 'rel_table_contributions' => [ |
| 71 | 'title' => ts('Contributions'), |
| 72 | 'tables' => [ |
| 73 | 'civicrm_contribution', |
| 74 | 'civicrm_contribution_recur', |
| 75 | 'civicrm_contribution_soft', |
| 76 | ], |
| 77 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'), |
| 78 | ], |
| 79 | 'rel_table_contribution_page' => [ |
| 80 | 'title' => ts('Contribution Pages'), |
| 81 | 'tables' => ['civicrm_contribution_page'], |
| 82 | 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'), |
| 83 | ], |
| 84 | 'rel_table_memberships' => [ |
| 85 | 'title' => ts('Memberships'), |
| 86 | 'tables' => [ |
| 87 | 'civicrm_membership', |
| 88 | 'civicrm_membership_log', |
| 89 | 'civicrm_membership_type', |
| 90 | ], |
| 91 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'), |
| 92 | ], |
| 93 | 'rel_table_participants' => [ |
| 94 | 'title' => ts('Participants'), |
| 95 | 'tables' => ['civicrm_participant'], |
| 96 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'), |
| 97 | ], |
| 98 | 'rel_table_events' => [ |
| 99 | 'title' => ts('Events'), |
| 100 | 'tables' => ['civicrm_event'], |
| 101 | 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'), |
| 102 | ], |
| 103 | 'rel_table_activities' => [ |
| 104 | 'title' => ts('Activities'), |
| 105 | 'tables' => ['civicrm_activity', 'civicrm_activity_contact'], |
| 106 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'), |
| 107 | ], |
| 108 | 'rel_table_relationships' => [ |
| 109 | 'title' => ts('Relationships'), |
| 110 | 'tables' => ['civicrm_relationship'], |
| 111 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'), |
| 112 | ], |
| 113 | 'rel_table_custom_groups' => [ |
| 114 | 'title' => ts('Custom Groups'), |
| 115 | 'tables' => ['civicrm_custom_group'], |
| 116 | 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'), |
| 117 | ], |
| 118 | 'rel_table_uf_groups' => [ |
| 119 | 'title' => ts('Profiles'), |
| 120 | 'tables' => ['civicrm_uf_group'], |
| 121 | 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'), |
| 122 | ], |
| 123 | 'rel_table_groups' => [ |
| 124 | 'title' => ts('Groups'), |
| 125 | 'tables' => ['civicrm_group_contact'], |
| 126 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'), |
| 127 | ], |
| 128 | 'rel_table_notes' => [ |
| 129 | 'title' => ts('Notes'), |
| 130 | 'tables' => ['civicrm_note'], |
| 131 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'), |
| 132 | ], |
| 133 | 'rel_table_tags' => [ |
| 134 | 'title' => ts('Tags'), |
| 135 | 'tables' => ['civicrm_entity_tag'], |
| 136 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'), |
| 137 | ], |
| 138 | 'rel_table_mailings' => [ |
| 139 | 'title' => ts('Mailings'), |
| 140 | 'tables' => [ |
| 141 | 'civicrm_mailing', |
| 142 | 'civicrm_mailing_event_queue', |
| 143 | 'civicrm_mailing_event_subscribe', |
| 144 | ], |
| 145 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'), |
| 146 | ], |
| 147 | 'rel_table_cases' => [ |
| 148 | 'title' => ts('Cases'), |
| 149 | 'tables' => ['civicrm_case_contact'], |
| 150 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'), |
| 151 | ], |
| 152 | 'rel_table_grants' => [ |
| 153 | 'title' => ts('Grants'), |
| 154 | 'tables' => ['civicrm_grant'], |
| 155 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'), |
| 156 | ], |
| 157 | 'rel_table_pcp' => [ |
| 158 | 'title' => ts('PCPs'), |
| 159 | 'tables' => ['civicrm_pcp'], |
| 160 | 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'), |
| 161 | ], |
| 162 | 'rel_table_pledges' => [ |
| 163 | 'title' => ts('Pledges'), |
| 164 | 'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'], |
| 165 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'), |
| 166 | ], |
| 167 | 'rel_table_users' => [ |
| 168 | 'title' => $title, |
| 169 | 'tables' => ['civicrm_uf_match'], |
| 170 | 'url' => $userRecordUrl, |
| 171 | ], |
| 172 | ]; |
| 173 | |
| 174 | $relTables += self::getMultiValueCustomSets('relTables'); |
| 175 | |
| 176 | // Allow hook_civicrm_merge() to adjust $relTables |
| 177 | CRM_Utils_Hook::merge('relTables', $relTables); |
| 178 | |
| 179 | // Cache the results in a static variable |
| 180 | Civi::$statics[__CLASS__]['relTables'] = $relTables; |
| 181 | } |
| 182 | |
| 183 | return Civi::$statics[__CLASS__]['relTables']; |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Returns the related tables groups for which a contact has any info entered. |
| 188 | * |
| 189 | * @param int $cid |
| 190 | * |
| 191 | * @return array |
| 192 | */ |
| 193 | public static function getActiveRelTables($cid) { |
| 194 | $cid = (int) $cid; |
| 195 | $groups = []; |
| 196 | |
| 197 | $relTables = self::relTables(); |
| 198 | $cidRefs = self::cidRefs(); |
| 199 | $eidRefs = self::eidRefs(); |
| 200 | foreach ($relTables as $group => $params) { |
| 201 | $sqls = []; |
| 202 | foreach ($params['tables'] as $table) { |
| 203 | if (isset($cidRefs[$table])) { |
| 204 | foreach ($cidRefs[$table] as $field) { |
| 205 | $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid"; |
| 206 | } |
| 207 | } |
| 208 | if (isset($eidRefs[$table])) { |
| 209 | foreach ($eidRefs[$table] as $entityTable => $entityId) { |
| 210 | $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'"; |
| 211 | } |
| 212 | } |
| 213 | foreach ($sqls as $sql) { |
| 214 | if (CRM_Core_DAO::singleValueQuery($sql) > 0) { |
| 215 | $groups[] = $group; |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | return array_unique($groups); |
| 221 | } |
| 222 | |
| 223 | /** |
| 224 | * Get array tables and fields that reference civicrm_contact.id. |
| 225 | * |
| 226 | * This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call. |
| 227 | * The entityTypes hook is the recommended way to add tables to this result. |
| 228 | * |
| 229 | * I thought about adding another hook to alter tableReferences but decided it was unclear if there |
| 230 | * are use cases not covered by entityTables and instead we should wait & see. |
| 231 | */ |
| 232 | public static function cidRefs() { |
| 233 | if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) { |
| 234 | return \Civi::$statics[__CLASS__]['contact_references']; |
| 235 | } |
| 236 | |
| 237 | $contactReferences = $coreReferences = CRM_Core_DAO::getReferencesToContactTable(); |
| 238 | |
| 239 | CRM_Utils_Hook::merge('cidRefs', $contactReferences); |
| 240 | if ($contactReferences !== $coreReferences) { |
| 241 | Civi::log() |
| 242 | ->warning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.", ['civi.tag' => 'deprecated']); |
| 243 | } |
| 244 | \Civi::$statics[__CLASS__]['contact_references'] = $contactReferences; |
| 245 | return \Civi::$statics[__CLASS__]['contact_references']; |
| 246 | } |
| 247 | |
| 248 | /** |
| 249 | * Return tables and their fields referencing civicrm_contact.contact_id with entity_id |
| 250 | */ |
| 251 | public static function eidRefs() { |
| 252 | static $eidRefs; |
| 253 | if (!$eidRefs) { |
| 254 | // FIXME: this should be generated dynamically from the schema |
| 255 | // tables that reference contacts with entity_{id,table} |
| 256 | $eidRefs = [ |
| 257 | 'civicrm_acl' => ['entity_table' => 'entity_id'], |
| 258 | 'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'], |
| 259 | 'civicrm_entity_file' => ['entity_table' => 'entity_id'], |
| 260 | 'civicrm_log' => ['entity_table' => 'entity_id'], |
| 261 | 'civicrm_mailing_group' => ['entity_table' => 'entity_id'], |
| 262 | 'civicrm_note' => ['entity_table' => 'entity_id'], |
| 263 | ]; |
| 264 | |
| 265 | // Allow hook_civicrm_merge() to adjust $eidRefs |
| 266 | CRM_Utils_Hook::merge('eidRefs', $eidRefs); |
| 267 | } |
| 268 | return $eidRefs; |
| 269 | } |
| 270 | |
| 271 | /** |
| 272 | * Return tables using locations. |
| 273 | */ |
| 274 | public static function locTables() { |
| 275 | static $locTables; |
| 276 | if (!$locTables) { |
| 277 | $locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone']; |
| 278 | |
| 279 | // Allow hook_civicrm_merge() to adjust $locTables |
| 280 | CRM_Utils_Hook::merge('locTables', $locTables); |
| 281 | } |
| 282 | return $locTables; |
| 283 | } |
| 284 | |
| 285 | /** |
| 286 | * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc. |
| 287 | * @param string $request |
| 288 | * 'relTables' or 'cidRefs'. |
| 289 | * @return array |
| 290 | * @see CRM-13836 |
| 291 | */ |
| 292 | public static function getMultiValueCustomSets($request) { |
| 293 | |
| 294 | if (!isset(Civi::$statics[__CLASS__]['multiValueCustomSets'])) { |
| 295 | $data = [ |
| 296 | 'relTables' => [], |
| 297 | 'cidRefs' => [], |
| 298 | ]; |
| 299 | $result = civicrm_api3('custom_group', 'get', [ |
| 300 | 'is_multiple' => 1, |
| 301 | 'extends' => [ |
| 302 | 'IN' => [ |
| 303 | 'Individual', |
| 304 | 'Organization', |
| 305 | 'Household', |
| 306 | 'Contact', |
| 307 | ], |
| 308 | ], |
| 309 | 'return' => ['id', 'title', 'table_name', 'style'], |
| 310 | ]); |
| 311 | foreach ($result['values'] as $custom) { |
| 312 | $data['cidRefs'][$custom['table_name']] = ['entity_id']; |
| 313 | $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : ''; |
| 314 | $data['relTables']['rel_table_custom_' . $custom['id']] = [ |
| 315 | 'title' => $custom['title'], |
| 316 | 'tables' => [$custom['table_name']], |
| 317 | 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix), |
| 318 | ]; |
| 319 | } |
| 320 | |
| 321 | // Store the result in a static variable cache |
| 322 | Civi::$statics[__CLASS__]['multiValueCustomSets'] = $data; |
| 323 | } |
| 324 | |
| 325 | return Civi::$statics[__CLASS__]['multiValueCustomSets'][$request]; |
| 326 | } |
| 327 | |
| 328 | /** |
| 329 | * Tables which require custom processing should declare functions to call here. |
| 330 | * Doing so will override normal processing. |
| 331 | */ |
| 332 | public static function cpTables() { |
| 333 | static $tables; |
| 334 | if (!$tables) { |
| 335 | $tables = [ |
| 336 | 'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'], |
| 337 | 'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'], |
| 338 | // Empty array == do nothing - this table is handled by mergeGroupContact |
| 339 | 'civicrm_subscription_history' => [], |
| 340 | 'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'], |
| 341 | 'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'], |
| 342 | ]; |
| 343 | } |
| 344 | return $tables; |
| 345 | } |
| 346 | |
| 347 | /** |
| 348 | * Return payment related table. |
| 349 | */ |
| 350 | public static function paymentTables() { |
| 351 | static $tables; |
| 352 | if (!$tables) { |
| 353 | $tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant']; |
| 354 | } |
| 355 | return $tables; |
| 356 | } |
| 357 | |
| 358 | /** |
| 359 | * Return payment update Query. |
| 360 | * |
| 361 | * @param string $tableName |
| 362 | * @param int $mainContactId |
| 363 | * @param int $otherContactId |
| 364 | * |
| 365 | * @return array |
| 366 | */ |
| 367 | public static function paymentSql($tableName, $mainContactId, $otherContactId) { |
| 368 | $sqls = []; |
| 369 | if (!$tableName || !$mainContactId || !$otherContactId) { |
| 370 | return $sqls; |
| 371 | } |
| 372 | |
| 373 | $paymentTables = self::paymentTables(); |
| 374 | if (!in_array($tableName, $paymentTables)) { |
| 375 | return $sqls; |
| 376 | } |
| 377 | |
| 378 | switch ($tableName) { |
| 379 | case 'civicrm_pledge': |
| 380 | $sqls[] = " |
| 381 | UPDATE IGNORE civicrm_contribution contribution |
| 382 | INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id ) |
| 383 | INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id ) |
| 384 | SET contribution.contact_id = $mainContactId |
| 385 | WHERE pledge.contact_id = $otherContactId"; |
| 386 | break; |
| 387 | |
| 388 | case 'civicrm_membership': |
| 389 | $sqls[] = " |
| 390 | UPDATE IGNORE civicrm_contribution contribution |
| 391 | INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id ) |
| 392 | INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id ) |
| 393 | SET contribution.contact_id = $mainContactId |
| 394 | WHERE membership.contact_id = $otherContactId"; |
| 395 | break; |
| 396 | |
| 397 | case 'civicrm_participant': |
| 398 | $sqls[] = " |
| 399 | UPDATE IGNORE civicrm_contribution contribution |
| 400 | INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id ) |
| 401 | INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id ) |
| 402 | SET contribution.contact_id = $mainContactId |
| 403 | WHERE participant.contact_id = $otherContactId"; |
| 404 | break; |
| 405 | } |
| 406 | |
| 407 | return $sqls; |
| 408 | } |
| 409 | |
| 410 | /** |
| 411 | * @param int $mainId |
| 412 | * @param int $otherId |
| 413 | * @param string $tableName |
| 414 | * @param array $tableOperations |
| 415 | * @param string $mode |
| 416 | * |
| 417 | * @return array |
| 418 | */ |
| 419 | public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') { |
| 420 | $sqls = []; |
| 421 | if (!$tableName || !$mainId || !$otherId) { |
| 422 | return $sqls; |
| 423 | } |
| 424 | |
| 425 | switch ($tableName) { |
| 426 | case 'civicrm_membership': |
| 427 | if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) { |
| 428 | break; |
| 429 | } |
| 430 | if ($mode == 'add') { |
| 431 | $sqls[] = " |
| 432 | DELETE membership1.* FROM civicrm_membership membership1 |
| 433 | INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id |
| 434 | AND membership1.contact_id = {$mainId} |
| 435 | AND membership2.contact_id = {$otherId} "; |
| 436 | } |
| 437 | if ($mode == 'payment') { |
| 438 | $sqls[] = " |
| 439 | DELETE contribution.* FROM civicrm_contribution contribution |
| 440 | INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id |
| 441 | INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id |
| 442 | AND membership1.contact_id = {$mainId} |
| 443 | INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id |
| 444 | AND membership2.contact_id = {$otherId}"; |
| 445 | } |
| 446 | break; |
| 447 | |
| 448 | case 'civicrm_uf_match': |
| 449 | // normal queries won't work for uf_match since that will lead to violation of unique constraint, |
| 450 | // failing to meet intended result. Therefore we introduce this additional query: |
| 451 | $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}"; |
| 452 | break; |
| 453 | } |
| 454 | |
| 455 | return $sqls; |
| 456 | } |
| 457 | |
| 458 | /** |
| 459 | * Based on the provided two contact_ids and a set of tables, remove the |
| 460 | * belongings of the other contact and of their relations. |
| 461 | * |
| 462 | * @param int $otherID |
| 463 | * @param bool $tables |
| 464 | */ |
| 465 | public static function removeContactBelongings($otherID, $tables) { |
| 466 | // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact. |
| 467 | if (in_array("civicrm_membership", $tables)) { |
| 468 | $membershipIDs = CRM_Utils_Array::collect('id', |
| 469 | CRM_Utils_Array::value('values', |
| 470 | civicrm_api3("Membership", "get", [ |
| 471 | "contact_id" => $otherID, |
| 472 | "return" => "id", |
| 473 | ]) |
| 474 | ) |
| 475 | ); |
| 476 | |
| 477 | if (!empty($membershipIDs)) { |
| 478 | civicrm_api3("Membership", "get", [ |
| 479 | 'owner_membership_id' => ['IN' => $membershipIDs], |
| 480 | 'api.Membership.delete' => ['id' => '$value.id'], |
| 481 | ]); |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | /** |
| 487 | * Based on the provided two contact_ids and a set of tables, move the |
| 488 | * belongings of the other contact to the main one. |
| 489 | * |
| 490 | * @param int $mainId |
| 491 | * @param int $otherId |
| 492 | * @param bool $tables |
| 493 | * @param array $tableOperations |
| 494 | * @param array $customTableToCopyFrom |
| 495 | */ |
| 496 | public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = [], $customTableToCopyFrom = NULL) { |
| 497 | $cidRefs = self::cidRefs(); |
| 498 | $eidRefs = self::eidRefs(); |
| 499 | $cpTables = self::cpTables(); |
| 500 | $paymentTables = self::paymentTables(); |
| 501 | |
| 502 | // getting all custom tables |
| 503 | $customTables = []; |
| 504 | if ($customTableToCopyFrom !== NULL) { |
| 505 | // @todo this duplicates cidRefs? |
| 506 | CRM_Core_DAO::appendCustomTablesExtendingContacts($customTables); |
| 507 | CRM_Core_DAO::appendCustomContactReferenceFields($customTables); |
| 508 | $customTables = array_keys($customTables); |
| 509 | } |
| 510 | |
| 511 | $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs)); |
| 512 | |
| 513 | // if there aren't any specific tables, don't affect the ones handled by relTables() |
| 514 | // also don't affect tables in locTables() CRM-15658 |
| 515 | $relTables = self::relTables(); |
| 516 | $handled = self::locTables(); |
| 517 | |
| 518 | foreach ($relTables as $params) { |
| 519 | $handled = array_merge($handled, $params['tables']); |
| 520 | } |
| 521 | $affected = array_diff($affected, $handled); |
| 522 | $affected = array_unique(array_merge($affected, $tables)); |
| 523 | |
| 524 | $mainId = (int) $mainId; |
| 525 | $otherId = (int) $otherId; |
| 526 | $multi_value_tables = array_keys(CRM_Dedupe_Merger::getMultiValueCustomSets('cidRefs')); |
| 527 | |
| 528 | $sqls = []; |
| 529 | foreach ($affected as $table) { |
| 530 | // skipping non selected single-value custom table's value migration |
| 531 | if (!in_array($table, $multi_value_tables)) { |
| 532 | if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) { |
| 533 | if (isset($cidRefs[$table]) && ($delCol = array_search('entity_id', $cidRefs[$table])) !== FALSE) { |
| 534 | // remove entity_id from the field list |
| 535 | unset($cidRefs[$table][$delCol]); |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | // Call custom processing function for objects that require it |
| 541 | if (isset($cpTables[$table])) { |
| 542 | foreach ($cpTables[$table] as $className => $fnName) { |
| 543 | $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations); |
| 544 | } |
| 545 | // Skip normal processing |
| 546 | continue; |
| 547 | } |
| 548 | |
| 549 | // use UPDATE IGNORE + DELETE query pair to skip on situations when |
| 550 | // there's a UNIQUE restriction on ($field, some_other_field) pair |
| 551 | if (isset($cidRefs[$table])) { |
| 552 | foreach ($cidRefs[$table] as $field) { |
| 553 | // carry related contributions CRM-5359 |
| 554 | if (in_array($table, $paymentTables)) { |
| 555 | $paymentSqls = self::paymentSql($table, $mainId, $otherId); |
| 556 | $sqls = array_merge($sqls, $paymentSqls); |
| 557 | |
| 558 | if (!empty($tables) && !in_array('civicrm_contribution', $tables)) { |
| 559 | $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment'); |
| 560 | $sqls = array_merge($sqls, $payOprSqls); |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations); |
| 565 | $sqls = array_merge($sqls, $preOperationSqls); |
| 566 | |
| 567 | if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self::customRecordExists($mainId, $table, $field) && $field == 'entity_id') { |
| 568 | // this is the entity_id column of a custom field group where: |
| 569 | // - the custom table should be copied as indicated by $customTableToCopyFrom |
| 570 | // e.g. because a field in the group was selected in a form |
| 571 | // - AND no record exists yet for the $mainId contact |
| 572 | // we only do this for column "entity_id" as we wouldn't want to |
| 573 | // run this INSERT for ContactReference fields |
| 574 | $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)"; |
| 575 | } |
| 576 | $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId"; |
| 577 | $sqls[] = "DELETE FROM $table WHERE $field = $otherId"; |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | if (isset($eidRefs[$table])) { |
| 582 | foreach ($eidRefs[$table] as $entityTable => $entityId) { |
| 583 | $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'"; |
| 584 | $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'"; |
| 585 | } |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | // Allow hook_civicrm_merge() to add SQL statements for the merge operation. |
| 590 | CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables); |
| 591 | |
| 592 | foreach ($sqls as $sql) { |
| 593 | CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE); |
| 594 | } |
| 595 | CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId); |
| 596 | } |
| 597 | |
| 598 | /** |
| 599 | * Given a contact ID, will check if a record exists in given table. |
| 600 | * |
| 601 | * @param $contactID |
| 602 | * @param $table |
| 603 | * @param $idField |
| 604 | * Field where the contact's ID is stored in the table |
| 605 | * |
| 606 | * @return bool |
| 607 | * True if a record is found for the given contact ID, false otherwise |
| 608 | */ |
| 609 | private static function customRecordExists($contactID, $table, $idField) { |
| 610 | $sql = " |
| 611 | SELECT COUNT(*) AS count |
| 612 | FROM $table |
| 613 | WHERE $idField = $contactID |
| 614 | "; |
| 615 | $dbResult = CRM_Core_DAO::executeQuery($sql); |
| 616 | $dbResult->fetch(); |
| 617 | |
| 618 | if ($dbResult->count > 0) { |
| 619 | return TRUE; |
| 620 | } |
| 621 | |
| 622 | return FALSE; |
| 623 | } |
| 624 | |
| 625 | /** |
| 626 | * Load all non-empty fields for the contacts |
| 627 | * |
| 628 | * @param array $main |
| 629 | * Contact details. |
| 630 | * @param array $other |
| 631 | * Contact details. |
| 632 | * |
| 633 | * @return array |
| 634 | */ |
| 635 | public static function retrieveFields($main, $other) { |
| 636 | $result = [ |
| 637 | 'contact' => [], |
| 638 | 'custom' => [], |
| 639 | ]; |
| 640 | foreach (self::getContactFields() as $validField) { |
| 641 | // CRM-17556 Get all non-empty fields, to make comparison easier |
| 642 | if (!empty($main[$validField]) || !empty($other[$validField])) { |
| 643 | $result['contact'][] = $validField; |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']); |
| 648 | $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']); |
| 649 | $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs))); |
| 650 | foreach ($keys as $key) { |
| 651 | // Exclude multi-value fields CRM-13836 |
| 652 | if (strpos($key, '_')) { |
| 653 | continue; |
| 654 | } |
| 655 | $key1 = CRM_Utils_Array::value($key, $mainEvs); |
| 656 | $key2 = CRM_Utils_Array::value($key, $otherEvs); |
| 657 | // We wish to retain '0' as it has a different meaning than NULL on a checkbox. |
| 658 | // However I can't think of a case where an empty string is more meaningful than null |
| 659 | // or where it would be FALSE or something else nullish. |
| 660 | $valuesToIgnore = [NULL, '', []]; |
| 661 | if (!in_array($key1, $valuesToIgnore, TRUE) || !in_array($key2, $valuesToIgnore, TRUE)) { |
| 662 | $result['custom'][] = $key; |
| 663 | } |
| 664 | } |
| 665 | return $result; |
| 666 | } |
| 667 | |
| 668 | /** |
| 669 | * Batch merge a set of contacts based on rule-group and group. |
| 670 | * |
| 671 | * @param int $rgid |
| 672 | * Rule group id. |
| 673 | * @param int $gid |
| 674 | * Group id. |
| 675 | * @param string $mode |
| 676 | * Helps decide how to behave when there are conflicts. |
| 677 | * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive' |
| 678 | * mode does a force merge. |
| 679 | * @param int $batchLimit number of merges to carry out in one batch. |
| 680 | * @param int $isSelected if records with is_selected column needs to be processed. |
| 681 | * Note the option of '2' is only used in conjunction with $redirectForPerformance |
| 682 | * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered |
| 683 | * out in favour of explicitly passing in $reloadCacheIfEmpty |
| 684 | * |
| 685 | * @param array $criteria |
| 686 | * Criteria to use in the filter. |
| 687 | * |
| 688 | * @param bool $checkPermissions |
| 689 | * Respect logged in user permissions. |
| 690 | * @param bool|NULL $reloadCacheIfEmpty |
| 691 | * If not set explicitly this is calculated but it is preferred that it be set |
| 692 | * per comments on isSelected above. |
| 693 | * |
| 694 | * @param int $searchLimit |
| 695 | * Limit on number of contacts to search for duplicates for. |
| 696 | * This means that if the limit is 1000 then only duplicates for the first 1000 contacts |
| 697 | * matching criteria will be found and batchMerged (the number of merges could be less than or greater than 100) |
| 698 | * |
| 699 | * @return array|bool |
| 700 | * |
| 701 | * @throws \CRM_Core_Exception |
| 702 | * @throws \CiviCRM_API3_Exception |
| 703 | */ |
| 704 | public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL, $searchLimit = 0) { |
| 705 | $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE; |
| 706 | if ($mode === 'aggressive' && $checkPermissions && !CRM_Core_Permission::check('force merge duplicate contacts')) { |
| 707 | throw new CRM_Core_Exception(ts('Insufficient permissions for aggressive mode batch merge')); |
| 708 | } |
| 709 | if (!isset($reloadCacheIfEmpty)) { |
| 710 | $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2); |
| 711 | } |
| 712 | if ($isSelected !== 0 && $isSelected !== 1) { |
| 713 | // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value. |
| 714 | $isSelected = NULL; |
| 715 | } |
| 716 | $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode == 'aggressive'), $criteria, $checkPermissions); |
| 717 | |
| 718 | $cacheParams = [ |
| 719 | 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions, $searchLimit), |
| 720 | // @todo stop passing these parameters in & instead calculate them in the merge function based |
| 721 | // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected. |
| 722 | 'join' => self::getJoinOnDedupeTable(), |
| 723 | 'where' => self::getWhereString($isSelected), |
| 724 | 'limit' => (int) $batchLimit, |
| 725 | ]; |
| 726 | return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions); |
| 727 | } |
| 728 | |
| 729 | /** |
| 730 | * Get the string to join the prevnext cache to the dedupe table. |
| 731 | * |
| 732 | * @return string |
| 733 | * The join string to join prevnext cache on the dedupe table. |
| 734 | */ |
| 735 | public static function getJoinOnDedupeTable() { |
| 736 | return " |
| 737 | LEFT JOIN civicrm_dedupe_exception de |
| 738 | ON ( |
| 739 | pn.entity_id1 = de.contact_id1 |
| 740 | AND pn.entity_id2 = de.contact_id2 ) |
| 741 | "; |
| 742 | } |
| 743 | |
| 744 | /** |
| 745 | * Get where string for dedupe join. |
| 746 | * |
| 747 | * @param bool $isSelected |
| 748 | * |
| 749 | * @return string |
| 750 | */ |
| 751 | protected static function getWhereString($isSelected) { |
| 752 | $where = "de.id IS NULL"; |
| 753 | if ($isSelected === 0 || $isSelected === 1) { |
| 754 | $where .= " AND pn.is_selected = {$isSelected}"; |
| 755 | } |
| 756 | return $where; |
| 757 | } |
| 758 | |
| 759 | /** |
| 760 | * Update the statistics for the merge set. |
| 761 | * |
| 762 | * @param string $cacheKeyString |
| 763 | * @param array $result |
| 764 | */ |
| 765 | public static function updateMergeStats($cacheKeyString, $result = []) { |
| 766 | // gather latest stats |
| 767 | $merged = count($result['merged']); |
| 768 | $skipped = count($result['skipped']); |
| 769 | |
| 770 | if ($merged <= 0 && $skipped <= 0) { |
| 771 | return; |
| 772 | } |
| 773 | |
| 774 | // get previous stats |
| 775 | $previousStats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString); |
| 776 | if (!empty($previousStats)) { |
| 777 | if ($previousStats['merged']) { |
| 778 | $merged = $merged + $previousStats['merged']; |
| 779 | } |
| 780 | if ($previousStats['skipped']) { |
| 781 | $skipped = $skipped + $previousStats['skipped']; |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | // delete old stats |
| 786 | CRM_Dedupe_Merger::resetMergeStats($cacheKeyString); |
| 787 | |
| 788 | // store the updated stats |
| 789 | $data = [ |
| 790 | 'merged' => $merged, |
| 791 | 'skipped' => $skipped, |
| 792 | ]; |
| 793 | $data = CRM_Core_DAO::escapeString(serialize($data)); |
| 794 | |
| 795 | CRM_Core_BAO_PrevNextCache::setItem('civicrm_contact', 0, 0, $cacheKeyString . '_stats', $data); |
| 796 | } |
| 797 | |
| 798 | /** |
| 799 | * Delete information about merges for the given string. |
| 800 | * |
| 801 | * @param $cacheKeyString |
| 802 | */ |
| 803 | public static function resetMergeStats($cacheKeyString) { |
| 804 | CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats"); |
| 805 | } |
| 806 | |
| 807 | /** |
| 808 | * Get merge outcome statistics. |
| 809 | * |
| 810 | * @param string $cacheKeyString |
| 811 | * |
| 812 | * @return array |
| 813 | * Array of how many were merged and how many were skipped. |
| 814 | * |
| 815 | * @throws \CiviCRM_API3_Exception |
| 816 | */ |
| 817 | public static function getMergeStats($cacheKeyString) { |
| 818 | $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values']; |
| 819 | if (!empty($stats)) { |
| 820 | return $stats[0]['data']; |
| 821 | } |
| 822 | return []; |
| 823 | } |
| 824 | |
| 825 | /** |
| 826 | * Get merge statistics message. |
| 827 | * |
| 828 | * @param array $stats |
| 829 | * |
| 830 | * @return string |
| 831 | */ |
| 832 | public static function getMergeStatsMsg($stats) { |
| 833 | $msg = ''; |
| 834 | if (!empty($stats['merged'])) { |
| 835 | $msg = '<p>' . ts('One contact merged.', [ |
| 836 | 'count' => $stats['merged'], |
| 837 | 'plural' => '%count contacts merged.', |
| 838 | ]) . '</p>'; |
| 839 | } |
| 840 | if (!empty($stats['skipped'])) { |
| 841 | $msg .= '<p>' . ts('One contact was skipped.', [ |
| 842 | 'count' => $stats['skipped'], |
| 843 | 'plural' => '%count contacts were skipped.', |
| 844 | ]) . '</p>'; |
| 845 | } |
| 846 | return $msg; |
| 847 | } |
| 848 | |
| 849 | /** |
| 850 | * Merge given set of contacts. Performs core operation. |
| 851 | * |
| 852 | * @param array $dupePairs |
| 853 | * Set of pair of contacts for whom merge is to be done. |
| 854 | * @param array $cacheParams |
| 855 | * Prev-next-cache params based on which next pair of contacts are computed. |
| 856 | * Generally used with batch-merge. |
| 857 | * @param string $mode |
| 858 | * Helps decide how to behave when there are conflicts. |
| 859 | * A 'safe' value skips the merge if there are any un-resolved conflicts. |
| 860 | * Does a force merge otherwise (aggressive mode). |
| 861 | * |
| 862 | * @param bool $redirectForPerformance |
| 863 | * Redirect to a url for batch processing. |
| 864 | * |
| 865 | * @param bool $checkPermissions |
| 866 | * Respect logged in user permissions. |
| 867 | * |
| 868 | * @return array|bool |
| 869 | */ |
| 870 | public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe', |
| 871 | $redirectForPerformance = FALSE, $checkPermissions = TRUE |
| 872 | ) { |
| 873 | $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams); |
| 874 | $resultStats = ['merged' => [], 'skipped' => []]; |
| 875 | |
| 876 | // we don't want dupe caching to get reset after every-merge, and therefore set the |
| 877 | CRM_Core_Config::setPermitCacheFlushMode(FALSE); |
| 878 | $deletedContacts = []; |
| 879 | |
| 880 | while (!empty($dupePairs)) { |
| 881 | foreach ($dupePairs as $index => $dupes) { |
| 882 | if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) { |
| 883 | unset($dupePairs[$index]); |
| 884 | continue; |
| 885 | } |
| 886 | CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']); |
| 887 | $mainId = $dupes['dstID']; |
| 888 | $otherId = $dupes['srcID']; |
| 889 | |
| 890 | if (!$mainId || !$otherId) { |
| 891 | // return error |
| 892 | return FALSE; |
| 893 | } |
| 894 | |
| 895 | self::dedupePair($resultStats, $deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString); |
| 896 | } |
| 897 | |
| 898 | if ($cacheKeyString && !$redirectForPerformance) { |
| 899 | // retrieve next pair of dupes |
| 900 | // @todo call getDuplicatePairs. |
| 901 | $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, |
| 902 | $cacheParams['join'], |
| 903 | $cacheParams['where'], |
| 904 | 0, |
| 905 | $cacheParams['limit'], |
| 906 | [], |
| 907 | '', |
| 908 | FALSE |
| 909 | ); |
| 910 | } |
| 911 | else { |
| 912 | // do not proceed. Terminate the loop |
| 913 | unset($dupePairs); |
| 914 | } |
| 915 | } |
| 916 | |
| 917 | CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats); |
| 918 | return $resultStats; |
| 919 | } |
| 920 | |
| 921 | /** |
| 922 | * A function which uses various rules / algorithms for choosing which contact to bias to |
| 923 | * when there's a conflict (to handle "gotchas"). Plus the safest route to merge. |
| 924 | * |
| 925 | * @param int $mainId |
| 926 | * Main contact with whom merge has to happen. |
| 927 | * @param int $otherId |
| 928 | * Duplicate contact which would be deleted after merge operation. |
| 929 | * @param array $migrationInfo |
| 930 | * Array of information about which elements to merge. |
| 931 | * @param string $mode |
| 932 | * Helps decide how to behave when there are conflicts. |
| 933 | * - A 'safe' value skips the merge if there are any un-resolved conflicts. |
| 934 | * - Does a force merge otherwise (aggressive mode). |
| 935 | * |
| 936 | * @param array $conflicts |
| 937 | * An empty array to be filed with conflict information. |
| 938 | * |
| 939 | * @return bool |
| 940 | * |
| 941 | * @throws \CRM_Core_Exception |
| 942 | * @throws \CiviCRM_API3_Exception |
| 943 | * @throws \API_Exception |
| 944 | */ |
| 945 | public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) { |
| 946 | |
| 947 | $conflicts = self::getConflicts($migrationInfo, $mainId, $otherId, $mode); |
| 948 | |
| 949 | if (!empty($conflicts)) { |
| 950 | // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges |
| 951 | return (bool) $migrationInfo['skip_merge']; |
| 952 | } |
| 953 | return FALSE; |
| 954 | } |
| 955 | |
| 956 | /** |
| 957 | * Compare 2 addresses to see if they are the same. |
| 958 | * |
| 959 | * @param array $mainAddress |
| 960 | * @param array $comparisonAddress |
| 961 | * |
| 962 | * @return bool |
| 963 | */ |
| 964 | public static function locationIsSame($mainAddress, $comparisonAddress) { |
| 965 | $keysToIgnore = self::ignoredFields(); |
| 966 | foreach ($comparisonAddress as $field => $value) { |
| 967 | if (in_array($field, $keysToIgnore)) { |
| 968 | continue; |
| 969 | } |
| 970 | if ((!empty($value) || $value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) { |
| 971 | return FALSE; |
| 972 | } |
| 973 | } |
| 974 | return TRUE; |
| 975 | } |
| 976 | |
| 977 | /** |
| 978 | * A function to build an array of information about location blocks that is |
| 979 | * required when merging location fields |
| 980 | * |
| 981 | * @return array |
| 982 | */ |
| 983 | public static function getLocationBlockInfo() { |
| 984 | $locationBlocks = [ |
| 985 | 'address' => [ |
| 986 | 'label' => 'Address', |
| 987 | 'displayField' => 'display', |
| 988 | 'sortString' => 'location_type_id', |
| 989 | 'hasLocation' => TRUE, |
| 990 | 'hasType' => FALSE, |
| 991 | ], |
| 992 | 'email' => [ |
| 993 | 'label' => 'Email', |
| 994 | 'displayField' => 'display', |
| 995 | 'sortString' => 'location_type_id', |
| 996 | 'hasLocation' => TRUE, |
| 997 | 'hasType' => FALSE, |
| 998 | ], |
| 999 | 'im' => [ |
| 1000 | 'label' => 'IM', |
| 1001 | 'displayField' => 'name', |
| 1002 | 'sortString' => 'location_type_id,provider_id', |
| 1003 | 'hasLocation' => TRUE, |
| 1004 | 'hasType' => 'provider_id', |
| 1005 | ], |
| 1006 | 'phone' => [ |
| 1007 | 'label' => 'Phone', |
| 1008 | 'displayField' => 'phone', |
| 1009 | 'sortString' => 'location_type_id,phone_type_id', |
| 1010 | 'hasLocation' => TRUE, |
| 1011 | 'hasType' => 'phone_type_id', |
| 1012 | ], |
| 1013 | 'website' => [ |
| 1014 | 'label' => 'Website', |
| 1015 | 'displayField' => 'url', |
| 1016 | 'sortString' => 'website_type_id', |
| 1017 | 'hasLocation' => FALSE, |
| 1018 | 'hasType' => 'website_type_id', |
| 1019 | ], |
| 1020 | ]; |
| 1021 | return $locationBlocks; |
| 1022 | } |
| 1023 | |
| 1024 | /** |
| 1025 | * A function to build an array of information required by merge function and the merge UI. |
| 1026 | * |
| 1027 | * @param int $mainId |
| 1028 | * Main contact with whom merge has to happen. |
| 1029 | * @param int $otherId |
| 1030 | * Duplicate contact which would be deleted after merge operation. |
| 1031 | * @param bool $checkPermissions |
| 1032 | * Should the logged in user's permissions be ignore. Setting this to false is |
| 1033 | * highly risky as it could cause data to be lost due to conflicts not showing up. |
| 1034 | * OTOH there is a risk a merger might view custom data they do not have permission to. |
| 1035 | * Hence for now only making this really explicit and making it reflect perms in |
| 1036 | * an api call. |
| 1037 | * |
| 1038 | * @todo review permissions issue! |
| 1039 | * |
| 1040 | * @return array|bool|int |
| 1041 | * |
| 1042 | * rows => An array of arrays, each is row of merge information for the table |
| 1043 | * Format: move_fieldname, eg: move_contact_type |
| 1044 | * main => Value associated with the main contact |
| 1045 | * other => Value associated with the other contact |
| 1046 | * title => The title of the field to display in the merge table |
| 1047 | * |
| 1048 | * elements => An array of form elements for the merge UI |
| 1049 | * |
| 1050 | * rel_table_elements => An array of form elements for the merge UI for |
| 1051 | * entities related to the contact (eg: checkbox to move 'mailings') |
| 1052 | * |
| 1053 | * rel_tables => Stores the tables that have related entities for the contact |
| 1054 | * for example mailings, groups |
| 1055 | * |
| 1056 | * main_details => An array of core contact field values, eg: first_name, etc. |
| 1057 | * location_blocks => An array of location block data for the main contact |
| 1058 | * stored as the 'result' of an API call. |
| 1059 | * eg: main_details['location_blocks']['address'][0]['id'] |
| 1060 | * eg: main_details['location_blocks']['email'][1]['id'] |
| 1061 | * |
| 1062 | * other_details => As above, but for the 'other' contact |
| 1063 | * |
| 1064 | * migration_info => Stores the 'default' merge actions for each field which |
| 1065 | * is used when programatically merging contacts. It contains instructions |
| 1066 | * to move all fields from the 'other' contact to the 'main' contact, as |
| 1067 | * though the form had been submitted with those options. |
| 1068 | * |
| 1069 | * @throws \CRM_Core_Exception |
| 1070 | * @throws \CiviCRM_API3_Exception |
| 1071 | * @throws \Exception |
| 1072 | */ |
| 1073 | public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) { |
| 1074 | $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; |
| 1075 | $fields = self::getMergeFieldsMetadata(); |
| 1076 | |
| 1077 | $main = self::getMergeContactDetails($mainId); |
| 1078 | $other = self::getMergeContactDetails($otherId); |
| 1079 | |
| 1080 | $compareFields = self::retrieveFields($main, $other); |
| 1081 | |
| 1082 | $rows = $elements = $relTableElements = $migrationInfo = []; |
| 1083 | |
| 1084 | foreach ($compareFields['contact'] as $field) { |
| 1085 | if ($field == 'contact_sub_type') { |
| 1086 | // CRM-15681 don't display sub-types in UI |
| 1087 | continue; |
| 1088 | } |
| 1089 | foreach (['main' => $main, 'other' => $other] as $moniker => $contact) { |
| 1090 | $value = $label = CRM_Utils_Array::value($field, $contact); |
| 1091 | $fieldSpec = $fields[$field]; |
| 1092 | if (!empty($fieldSpec['serialize']) && is_array($value)) { |
| 1093 | // In practice this only applies to preferred_communication_method as the sub types are skipped above |
| 1094 | // and no others are serialized. |
| 1095 | $labels = []; |
| 1096 | foreach ($value as $individualValue) { |
| 1097 | $labels[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue); |
| 1098 | } |
| 1099 | $label = implode(', ', $labels); |
| 1100 | // We serialize this due to historic handling but it's likely that if we just left it as an |
| 1101 | // array all would be well & we would have less code. |
| 1102 | $value = CRM_Core_DAO::serializeField($value, $fieldSpec['serialize']); |
| 1103 | } |
| 1104 | elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type::T_DATE) { |
| 1105 | if ($value) { |
| 1106 | $value = str_replace('-', '', $value); |
| 1107 | $label = CRM_Utils_Date::customFormat($label); |
| 1108 | } |
| 1109 | else { |
| 1110 | $value = "null"; |
| 1111 | } |
| 1112 | } |
| 1113 | elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) { |
| 1114 | if ($label === '0') { |
| 1115 | $label = ts('[ ]'); |
| 1116 | } |
| 1117 | if ($label === '1') { |
| 1118 | $label = ts('[x]'); |
| 1119 | } |
| 1120 | } |
| 1121 | elseif (!empty($fieldSpec['pseudoconstant'])) { |
| 1122 | $label = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $value); |
| 1123 | } |
| 1124 | elseif ($field == 'current_employer_id' && !empty($value)) { |
| 1125 | $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")"; |
| 1126 | } |
| 1127 | $rows["move_$field"][$moniker] = $label; |
| 1128 | if ($moniker == 'other') { |
| 1129 | //CRM-14334 |
| 1130 | if ($value === NULL || $value == '') { |
| 1131 | $value = 'null'; |
| 1132 | } |
| 1133 | if ($value === 0 or $value === '0') { |
| 1134 | $value = $qfZeroBug; |
| 1135 | } |
| 1136 | if (is_array($value) && empty($value[1])) { |
| 1137 | $value[1] = NULL; |
| 1138 | } |
| 1139 | |
| 1140 | // Display a checkbox to migrate, only if the values are different |
| 1141 | if ($value != $main[$field]) { |
| 1142 | $elements[] = [ |
| 1143 | 'advcheckbox', |
| 1144 | "move_$field", |
| 1145 | NULL, |
| 1146 | NULL, |
| 1147 | NULL, |
| 1148 | $value, |
| 1149 | ]; |
| 1150 | } |
| 1151 | |
| 1152 | $migrationInfo["move_$field"] = $value; |
| 1153 | } |
| 1154 | } |
| 1155 | $rows["move_$field"]['title'] = $fields[$field]['title']; |
| 1156 | } |
| 1157 | |
| 1158 | // Handle location blocks. |
| 1159 | // @todo OpenID not in API yet, so is not supported here. |
| 1160 | |
| 1161 | // Set up useful information about the location blocks |
| 1162 | $locationBlocks = self::getLocationBlockInfo(); |
| 1163 | |
| 1164 | $locations = [ |
| 1165 | 'main' => [], |
| 1166 | 'other' => [], |
| 1167 | ]; |
| 1168 | |
| 1169 | // @todo This could probably be defined and used earlier |
| 1170 | $mergeTargets = [ |
| 1171 | 'main' => $mainId, |
| 1172 | 'other' => $otherId, |
| 1173 | ]; |
| 1174 | |
| 1175 | foreach ($locationBlocks as $blockName => $blockInfo) { |
| 1176 | |
| 1177 | // Collect existing fields from both 'main' and 'other' contacts first |
| 1178 | // This allows us to match up location/types when building the table rows |
| 1179 | foreach ($mergeTargets as $moniker => $cid) { |
| 1180 | $searchParams = [ |
| 1181 | 'contact_id' => $cid, |
| 1182 | // CRM-17556 Order by field-specific criteria |
| 1183 | 'options' => [ |
| 1184 | 'sort' => $blockInfo['sortString'], |
| 1185 | ], |
| 1186 | ]; |
| 1187 | $values = civicrm_api3($blockName, 'get', $searchParams); |
| 1188 | if ($values['count']) { |
| 1189 | $cnt = 0; |
| 1190 | foreach ($values['values'] as $value) { |
| 1191 | $locations[$moniker][$blockName][$cnt] = $value; |
| 1192 | // Fix address display |
| 1193 | if ($blockName == 'address') { |
| 1194 | // For performance avoid geocoding while merging https://issues.civicrm.org/jira/browse/CRM-21786 |
| 1195 | // we can expect existing geocode values to be retained. |
| 1196 | $value['skip_geocode'] = TRUE; |
| 1197 | CRM_Core_BAO_Address::fixAddress($value); |
| 1198 | unset($value['skip_geocode']); |
| 1199 | $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address::format($value); |
| 1200 | } |
| 1201 | // Fix email display |
| 1202 | elseif ($blockName == 'email') { |
| 1203 | $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Mail::format($value); |
| 1204 | } |
| 1205 | |
| 1206 | $cnt++; |
| 1207 | } |
| 1208 | } |
| 1209 | } |
| 1210 | |
| 1211 | // Now, build the table rows appropriately, based off the information on |
| 1212 | // the 'other' contact |
| 1213 | if (!empty($locations['other']) && !empty($locations['other'][$blockName])) { |
| 1214 | foreach ($locations['other'][$blockName] as $count => $value) { |
| 1215 | |
| 1216 | $displayValue = $value[$blockInfo['displayField']]; |
| 1217 | |
| 1218 | // Add this value to the table rows |
| 1219 | $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue; |
| 1220 | |
| 1221 | // CRM-17556 Only display 'main' contact value if it's the same location + type |
| 1222 | // Look it up from main values... |
| 1223 | |
| 1224 | $lookupLocation = FALSE; |
| 1225 | if ($blockInfo['hasLocation']) { |
| 1226 | $lookupLocation = $value['location_type_id']; |
| 1227 | } |
| 1228 | |
| 1229 | $lookupType = FALSE; |
| 1230 | if ($blockInfo['hasType']) { |
| 1231 | $lookupType = CRM_Utils_Array::value($blockInfo['hasType'], $value); |
| 1232 | } |
| 1233 | |
| 1234 | // Hold ID of main contact's matching block |
| 1235 | $mainContactBlockId = 0; |
| 1236 | |
| 1237 | if (!empty($locations['main'][$blockName])) { |
| 1238 | foreach ($locations['main'][$blockName] as $mainValueCheck) { |
| 1239 | // No location/type, or matching location and type |
| 1240 | if ( |
| 1241 | (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id']) |
| 1242 | && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']]) |
| 1243 | ) { |
| 1244 | // Set this value as the default against the 'other' contact value |
| 1245 | $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']]; |
| 1246 | $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary']; |
| 1247 | $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName; |
| 1248 | $mainContactBlockId = $mainValueCheck['id']; |
| 1249 | break; |
| 1250 | } |
| 1251 | } |
| 1252 | } |
| 1253 | |
| 1254 | // Add checkbox to migrate data from 'other' to 'main' |
| 1255 | $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"]; |
| 1256 | |
| 1257 | // Add checkbox to set the 'other' location as primary |
| 1258 | $elements[] = [ |
| 1259 | 'advcheckbox', |
| 1260 | "location_blocks[$blockName][$count][set_other_primary]", |
| 1261 | NULL, |
| 1262 | ts('Set as primary'), |
| 1263 | ]; |
| 1264 | |
| 1265 | // Flag up this field to skipMerge function (@todo: do we need to?) |
| 1266 | $migrationInfo["move_location_{$blockName}_{$count}"] = 1; |
| 1267 | |
| 1268 | // Add a hidden field to store the ID of the target main contact block |
| 1269 | $elements[] = [ |
| 1270 | 'hidden', |
| 1271 | "location_blocks[$blockName][$count][mainContactBlockId]", |
| 1272 | $mainContactBlockId, |
| 1273 | ]; |
| 1274 | |
| 1275 | // Setup variables |
| 1276 | $thisTypeId = FALSE; |
| 1277 | $thisLocId = FALSE; |
| 1278 | |
| 1279 | // Provide a select drop-down for the location's location type |
| 1280 | // eg: Home, Work... |
| 1281 | |
| 1282 | if ($blockInfo['hasLocation']) { |
| 1283 | |
| 1284 | // Load the location options for this entity |
| 1285 | $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']); |
| 1286 | |
| 1287 | $thisLocId = $value['location_type_id']; |
| 1288 | |
| 1289 | // Put this field's location type at the top of the list |
| 1290 | $tmpIdList = $locationOptions['values']; |
| 1291 | $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]]; |
| 1292 | unset($tmpIdList[$thisLocId]); |
| 1293 | |
| 1294 | // Add the element |
| 1295 | $elements[] = [ |
| 1296 | 'select', |
| 1297 | "location_blocks[$blockName][$count][locTypeId]", |
| 1298 | NULL, |
| 1299 | $defaultLocId + $tmpIdList, |
| 1300 | ]; |
| 1301 | |
| 1302 | // Add the relevant information to the $migrationInfo |
| 1303 | // Keep location-type-id same as that of other-contact |
| 1304 | // @todo Check this logic out |
| 1305 | $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId; |
| 1306 | if ($blockName != 'address') { |
| 1307 | $elements[] = [ |
| 1308 | 'advcheckbox', |
| 1309 | "location_blocks[{$blockName}][$count][operation]", |
| 1310 | NULL, |
| 1311 | ts('Add new'), |
| 1312 | ]; |
| 1313 | // always use add operation |
| 1314 | $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1; |
| 1315 | } |
| 1316 | |
| 1317 | } |
| 1318 | |
| 1319 | // Provide a select drop-down for the location's type/provider |
| 1320 | // eg websites: Google+, Facebook... |
| 1321 | |
| 1322 | if ($blockInfo['hasType']) { |
| 1323 | |
| 1324 | // Load the type options for this entity |
| 1325 | $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]); |
| 1326 | |
| 1327 | $thisTypeId = CRM_Utils_Array::value($blockInfo['hasType'], $value); |
| 1328 | |
| 1329 | // Put this field's location type at the top of the list |
| 1330 | $tmpIdList = $typeOptions['values']; |
| 1331 | $defaultTypeId = [$thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList)]; |
| 1332 | unset($tmpIdList[$thisTypeId]); |
| 1333 | |
| 1334 | // Add the element |
| 1335 | $elements[] = [ |
| 1336 | 'select', |
| 1337 | "location_blocks[$blockName][$count][typeTypeId]", |
| 1338 | NULL, |
| 1339 | $defaultTypeId + $tmpIdList, |
| 1340 | ]; |
| 1341 | |
| 1342 | // Add the information to the migrationInfo |
| 1343 | $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId; |
| 1344 | |
| 1345 | } |
| 1346 | |
| 1347 | // Set the label for this row |
| 1348 | $rowTitle = $blockInfo['label'] . ' ' . ($count + 1); |
| 1349 | if (!empty($thisLocId)) { |
| 1350 | $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')'; |
| 1351 | } |
| 1352 | if (!empty($thisTypeId)) { |
| 1353 | $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')'; |
| 1354 | } |
| 1355 | $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle; |
| 1356 | |
| 1357 | } // End loop through 'other' locations of this type |
| 1358 | |
| 1359 | } // End if 'other' location for this type exists |
| 1360 | |
| 1361 | } // End loop through each location block entity |
| 1362 | |
| 1363 | // add the related tables and unset the ones that don't sport any of the duplicate contact's info |
| 1364 | $config = CRM_Core_Config::singleton(); |
| 1365 | $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId); |
| 1366 | $mainUser = NULL; |
| 1367 | if ($mainUfId) { |
| 1368 | // d6 compatible |
| 1369 | if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { |
| 1370 | $mainUser = user_load($mainUfId); |
| 1371 | } |
| 1372 | elseif ($config->userFramework == 'Joomla') { |
| 1373 | $mainUser = JFactory::getUser($mainUfId); |
| 1374 | } |
| 1375 | } |
| 1376 | $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId); |
| 1377 | $otherUser = NULL; |
| 1378 | if ($otherUfId) { |
| 1379 | // d6 compatible |
| 1380 | if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { |
| 1381 | $otherUser = user_load($otherUfId); |
| 1382 | } |
| 1383 | elseif ($config->userFramework == 'Joomla') { |
| 1384 | $otherUser = JFactory::getUser($otherUfId); |
| 1385 | } |
| 1386 | } |
| 1387 | |
| 1388 | $relTables = CRM_Dedupe_Merger::relTables(); |
| 1389 | $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId); |
| 1390 | $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId); |
| 1391 | foreach ($relTables as $name => $null) { |
| 1392 | if (!in_array($name, $activeRelTables) && |
| 1393 | !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables)) |
| 1394 | ) { |
| 1395 | unset($relTables[$name]); |
| 1396 | continue; |
| 1397 | } |
| 1398 | |
| 1399 | $relTableElements[] = ['checkbox', "move_$name"]; |
| 1400 | $migrationInfo["move_$name"] = 1; |
| 1401 | |
| 1402 | $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']); |
| 1403 | $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']); |
| 1404 | if ($name == 'rel_table_users') { |
| 1405 | $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']); |
| 1406 | $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']); |
| 1407 | $find = ['$ufid', '$ufname']; |
| 1408 | if ($mainUser) { |
| 1409 | $replace = [$mainUfId, $mainUser->name]; |
| 1410 | $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']); |
| 1411 | } |
| 1412 | if ($otherUser) { |
| 1413 | $replace = [$otherUfId, $otherUser->name]; |
| 1414 | $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']); |
| 1415 | } |
| 1416 | } |
| 1417 | if ($name == 'rel_table_memberships') { |
| 1418 | //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact. |
| 1419 | $attributes = ['checked' => 'checked']; |
| 1420 | $otherContactMemberships = CRM_Member_BAO_Membership::getAllContactMembership($otherId); |
| 1421 | foreach ($otherContactMemberships as $membership) { |
| 1422 | $mainMembership = CRM_Member_BAO_Membership::getContactMembership($mainId, $membership['membership_type_id'], FALSE); |
| 1423 | if ($mainMembership) { |
| 1424 | $attributes = []; |
| 1425 | } |
| 1426 | } |
| 1427 | $elements[] = [ |
| 1428 | 'checkbox', |
| 1429 | "operation[move_{$name}][add]", |
| 1430 | NULL, |
| 1431 | ts('add new'), |
| 1432 | $attributes, |
| 1433 | ]; |
| 1434 | $migrationInfo["operation"]["move_{$name}"]['add'] = 1; |
| 1435 | } |
| 1436 | } |
| 1437 | foreach ($relTables as $name => $null) { |
| 1438 | $relTables["move_$name"] = $relTables[$name]; |
| 1439 | unset($relTables[$name]); |
| 1440 | } |
| 1441 | |
| 1442 | // handle custom fields |
| 1443 | $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1, |
| 1444 | CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions |
| 1445 | ); |
| 1446 | $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $otherId, -1, |
| 1447 | CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions |
| 1448 | ); |
| 1449 | |
| 1450 | foreach ($otherTree as $gid => $group) { |
| 1451 | $foundField = FALSE; |
| 1452 | if (!isset($group['fields'])) { |
| 1453 | continue; |
| 1454 | } |
| 1455 | |
| 1456 | foreach ($group['fields'] as $fid => $field) { |
| 1457 | if (in_array($fid, $compareFields['custom'])) { |
| 1458 | if (!$foundField) { |
| 1459 | $rows["custom_group_$gid"]['title'] = $group['title']; |
| 1460 | $foundField = TRUE; |
| 1461 | } |
| 1462 | if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) { |
| 1463 | foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { |
| 1464 | $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid); |
| 1465 | } |
| 1466 | } |
| 1467 | $value = "null"; |
| 1468 | if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) { |
| 1469 | foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { |
| 1470 | $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid); |
| 1471 | if ($values['data'] === 0 || $values['data'] === '0') { |
| 1472 | $values['data'] = $qfZeroBug; |
| 1473 | } |
| 1474 | $value = ($values['data']) ? $values['data'] : $value; |
| 1475 | } |
| 1476 | } |
| 1477 | $rows["move_custom_$fid"]['title'] = $field['label']; |
| 1478 | |
| 1479 | $elements[] = [ |
| 1480 | 'advcheckbox', |
| 1481 | "move_custom_$fid", |
| 1482 | NULL, |
| 1483 | NULL, |
| 1484 | NULL, |
| 1485 | $value, |
| 1486 | ]; |
| 1487 | $migrationInfo["move_custom_$fid"] = $value; |
| 1488 | } |
| 1489 | } |
| 1490 | } |
| 1491 | |
| 1492 | $result = [ |
| 1493 | 'rows' => $rows, |
| 1494 | 'elements' => $elements, |
| 1495 | 'rel_table_elements' => $relTableElements, |
| 1496 | 'rel_tables' => $relTables, |
| 1497 | 'main_details' => $main, |
| 1498 | 'other_details' => $other, |
| 1499 | 'migration_info' => $migrationInfo, |
| 1500 | ]; |
| 1501 | |
| 1502 | $result['main_details']['location_blocks'] = $locations['main']; |
| 1503 | $result['other_details']['location_blocks'] = $locations['other']; |
| 1504 | |
| 1505 | return $result; |
| 1506 | } |
| 1507 | |
| 1508 | /** |
| 1509 | * Based on the provided two contact_ids and a set of tables, move the belongings of the |
| 1510 | * other contact to the main one - be it Location / CustomFields or Contact .. related info. |
| 1511 | * A superset of moveContactBelongings() function. |
| 1512 | * |
| 1513 | * @param int $mainId |
| 1514 | * Main contact with whom merge has to happen. |
| 1515 | * @param int $otherId |
| 1516 | * Duplicate contact which would be deleted after merge operation. |
| 1517 | * |
| 1518 | * @param array $migrationInfo |
| 1519 | * |
| 1520 | * @param bool $checkPermissions |
| 1521 | * Respect logged in user permissions. |
| 1522 | * |
| 1523 | * @return bool |
| 1524 | * @throws \CiviCRM_API3_Exception |
| 1525 | */ |
| 1526 | public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) { |
| 1527 | if (empty($migrationInfo)) { |
| 1528 | return FALSE; |
| 1529 | } |
| 1530 | // Encapsulate in a transaction to avoid half-merges. |
| 1531 | $transaction = new CRM_Core_Transaction(); |
| 1532 | |
| 1533 | $contactType = $migrationInfo['main_details']['contact_type']; |
| 1534 | $relTables = CRM_Dedupe_Merger::relTables(); |
| 1535 | $submittedCustomFields = $moveTables = $tableOperations = $removeTables = []; |
| 1536 | |
| 1537 | self::swapOutFieldsAffectedByQFZeroBug($migrationInfo); |
| 1538 | foreach ($migrationInfo as $key => $value) { |
| 1539 | |
| 1540 | if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) { |
| 1541 | $submitted[substr($key, 5)] = $value; |
| 1542 | $submittedCustomFields[] = substr($key, 12); |
| 1543 | } |
| 1544 | elseif (in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) && $value != NULL) { |
| 1545 | $submitted[substr($key, 5)] = $value; |
| 1546 | } |
| 1547 | elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') { |
| 1548 | $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']); |
| 1549 | if (array_key_exists('operation', $migrationInfo)) { |
| 1550 | foreach ($relTables[substr($key, 5)]['tables'] as $table) { |
| 1551 | if (array_key_exists($key, $migrationInfo['operation'])) { |
| 1552 | $tableOperations[$table] = $migrationInfo['operation'][$key]; |
| 1553 | } |
| 1554 | } |
| 1555 | } |
| 1556 | } |
| 1557 | elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') { |
| 1558 | $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']); |
| 1559 | } |
| 1560 | } |
| 1561 | self::mergeLocations($mainId, $otherId, $migrationInfo); |
| 1562 | |
| 1563 | // **** Do contact related migrations |
| 1564 | $customTablesToCopyValues = self::getAffectedCustomTables($submittedCustomFields); |
| 1565 | // @todo - move all custom field processing to the move class & eventually have an |
| 1566 | // overridable DAO class for it. |
| 1567 | $customFieldBAO = new CRM_Core_BAO_CustomField(); |
| 1568 | $customFieldBAO->move($otherId, $mainId, $submittedCustomFields); |
| 1569 | CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues); |
| 1570 | unset($moveTables, $tableOperations); |
| 1571 | |
| 1572 | // **** Do table related removals |
| 1573 | if (!empty($removeTables)) { |
| 1574 | // **** CRM-20421 |
| 1575 | CRM_Dedupe_Merger::removeContactBelongings($otherId, $removeTables); |
| 1576 | $removeTables = []; |
| 1577 | } |
| 1578 | |
| 1579 | // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact() |
| 1580 | $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender']; |
| 1581 | $names['individual_prefix'] = [ |
| 1582 | 'newName' => 'prefix_id', |
| 1583 | 'groupName' => 'individual_prefix', |
| 1584 | ]; |
| 1585 | $names['individual_suffix'] = [ |
| 1586 | 'newName' => 'suffix_id', |
| 1587 | 'groupName' => 'individual_suffix', |
| 1588 | ]; |
| 1589 | $names['communication_style'] = [ |
| 1590 | 'newName' => 'communication_style_id', |
| 1591 | 'groupName' => 'communication_style', |
| 1592 | ]; |
| 1593 | $names['addressee'] = [ |
| 1594 | 'newName' => 'addressee_id', |
| 1595 | 'groupName' => 'addressee', |
| 1596 | ]; |
| 1597 | $names['email_greeting'] = [ |
| 1598 | 'newName' => 'email_greeting_id', |
| 1599 | 'groupName' => 'email_greeting', |
| 1600 | ]; |
| 1601 | $names['postal_greeting'] = [ |
| 1602 | 'newName' => 'postal_greeting_id', |
| 1603 | 'groupName' => 'postal_greeting', |
| 1604 | ]; |
| 1605 | CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE); |
| 1606 | // fix custom fields so they're edible by createProfileContact() |
| 1607 | $cFields = self::getCustomFieldMetadata($contactType); |
| 1608 | |
| 1609 | if (!isset($submitted)) { |
| 1610 | $submitted = []; |
| 1611 | } |
| 1612 | foreach ($submitted as $key => $value) { |
| 1613 | list($cFields, $submitted) = self::processCustomFields($mainId, $key, $cFields, $submitted, $value); |
| 1614 | } |
| 1615 | |
| 1616 | // move view only custom fields CRM-5362 |
| 1617 | $viewOnlyCustomFields = []; |
| 1618 | foreach ($submitted as $key => $value) { |
| 1619 | $fid = CRM_Core_BAO_CustomField::getKeyID($key); |
| 1620 | if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view']) |
| 1621 | ) { |
| 1622 | $viewOnlyCustomFields[$key] = $value; |
| 1623 | } |
| 1624 | } |
| 1625 | // special case to set values for view only, CRM-5362 |
| 1626 | if (!empty($viewOnlyCustomFields)) { |
| 1627 | $viewOnlyCustomFields['entityID'] = $mainId; |
| 1628 | CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields); |
| 1629 | } |
| 1630 | |
| 1631 | // dev/core#996 Ensure that the earliest created date is stored against the kept contact id |
| 1632 | $mainCreatedDate = civicrm_api3('Contact', 'getsingle', [ |
| 1633 | 'id' => $mainId, |
| 1634 | 'return' => ['created_date'], |
| 1635 | ])['created_date']; |
| 1636 | $otherCreatedDate = civicrm_api3('Contact', 'getsingle', [ |
| 1637 | 'id' => $otherId, |
| 1638 | 'return' => ['created_date'], |
| 1639 | ])['created_date']; |
| 1640 | if ($otherCreatedDate < $mainCreatedDate) { |
| 1641 | CRM_Core_DAO::executeQuery("UPDATE civicrm_contact SET created_date = %1 WHERE id = %2", [ |
| 1642 | 1 => [$otherCreatedDate, 'String'], |
| 1643 | 2 => [$mainId, 'Positive'], |
| 1644 | ]); |
| 1645 | } |
| 1646 | |
| 1647 | if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') && |
| 1648 | CRM_Core_Permission::check('delete contacts')) |
| 1649 | ) { |
| 1650 | // if ext id is submitted then set it null for contact to be deleted |
| 1651 | if (!empty($submitted['external_identifier'])) { |
| 1652 | $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}"; |
| 1653 | CRM_Core_DAO::executeQuery($query); |
| 1654 | } |
| 1655 | civicrm_api3('contact', 'delete', ['id' => $otherId]); |
| 1656 | } |
| 1657 | |
| 1658 | // CRM-15681 merge sub_types |
| 1659 | if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) { |
| 1660 | if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) { |
| 1661 | $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types)); |
| 1662 | } |
| 1663 | else { |
| 1664 | $submitted['contact_sub_type'] = $other_sub_types; |
| 1665 | } |
| 1666 | } |
| 1667 | |
| 1668 | // **** Update contact related info for the main contact |
| 1669 | if (!empty($submitted)) { |
| 1670 | $submitted['contact_id'] = $mainId; |
| 1671 | |
| 1672 | //update current employer field |
| 1673 | if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) { |
| 1674 | if (!CRM_Utils_System::isNull($currentEmloyerId)) { |
| 1675 | $submitted['current_employer'] = $submitted['current_employer_id']; |
| 1676 | } |
| 1677 | else { |
| 1678 | $submitted['current_employer'] = ''; |
| 1679 | } |
| 1680 | unset($submitted['current_employer_id']); |
| 1681 | } |
| 1682 | |
| 1683 | //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name |
| 1684 | if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) { |
| 1685 | $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id']; |
| 1686 | } |
| 1687 | if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) { |
| 1688 | $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id']; |
| 1689 | } |
| 1690 | $null = []; |
| 1691 | CRM_Contact_BAO_Contact::createProfileContact($submitted, $null, $mainId); |
| 1692 | } |
| 1693 | $transaction->commit(); |
| 1694 | CRM_Utils_Hook::post('merge', 'Contact', $mainId); |
| 1695 | self::createMergeActivities($mainId, $otherId); |
| 1696 | |
| 1697 | return TRUE; |
| 1698 | } |
| 1699 | |
| 1700 | /** |
| 1701 | * Builds an Array of Custom tables for given custom field ID's. |
| 1702 | * |
| 1703 | * @param $customFieldIDs |
| 1704 | * |
| 1705 | * @return array |
| 1706 | * Array of custom table names |
| 1707 | */ |
| 1708 | private static function getAffectedCustomTables($customFieldIDs) { |
| 1709 | $customTableToCopyValues = []; |
| 1710 | |
| 1711 | foreach ($customFieldIDs as $fieldID) { |
| 1712 | if (!empty($fieldID)) { |
| 1713 | $customField = civicrm_api3('custom_field', 'getsingle', [ |
| 1714 | 'id' => $fieldID, |
| 1715 | 'is_active' => TRUE, |
| 1716 | ]); |
| 1717 | if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) { |
| 1718 | $customGroup = civicrm_api3('custom_group', 'getsingle', [ |
| 1719 | 'id' => $customField['custom_group_id'], |
| 1720 | 'is_active' => TRUE, |
| 1721 | ]); |
| 1722 | |
| 1723 | if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) { |
| 1724 | $customTableToCopyValues[] = $customGroup['table_name']; |
| 1725 | } |
| 1726 | } |
| 1727 | } |
| 1728 | } |
| 1729 | |
| 1730 | return $customTableToCopyValues; |
| 1731 | } |
| 1732 | |
| 1733 | /** |
| 1734 | * Get fields in the contact table suitable for merging. |
| 1735 | * |
| 1736 | * @return array |
| 1737 | * Array of field names to be potentially merged. |
| 1738 | */ |
| 1739 | public static function getContactFields() { |
| 1740 | $contactFields = CRM_Contact_DAO_Contact::fields(); |
| 1741 | $invalidFields = [ |
| 1742 | 'api_key', |
| 1743 | 'created_date', |
| 1744 | 'display_name', |
| 1745 | 'hash', |
| 1746 | 'id', |
| 1747 | 'modified_date', |
| 1748 | 'primary_contact_id', |
| 1749 | 'sort_name', |
| 1750 | 'user_unique_id', |
| 1751 | ]; |
| 1752 | foreach ($contactFields as $field => $value) { |
| 1753 | if (in_array($field, $invalidFields)) { |
| 1754 | unset($contactFields[$field]); |
| 1755 | } |
| 1756 | } |
| 1757 | return array_keys($contactFields); |
| 1758 | } |
| 1759 | |
| 1760 | /** |
| 1761 | * Added for CRM-12695 |
| 1762 | * Based on the contactID provided |
| 1763 | * add/update membership(s) to related contacts |
| 1764 | * |
| 1765 | * @param int $contactID |
| 1766 | */ |
| 1767 | public static function addMembershipToRealtedContacts($contactID) { |
| 1768 | $dao = new CRM_Member_DAO_Membership(); |
| 1769 | $dao->contact_id = $contactID; |
| 1770 | $dao->is_test = 0; |
| 1771 | $dao->find(); |
| 1772 | |
| 1773 | //checks membership of contact itself |
| 1774 | while ($dao->fetch()) { |
| 1775 | $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id'); |
| 1776 | if ($relationshipTypeId) { |
| 1777 | $membershipParams = [ |
| 1778 | 'id' => $dao->id, |
| 1779 | 'contact_id' => $dao->contact_id, |
| 1780 | 'membership_type_id' => $dao->membership_type_id, |
| 1781 | 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date), |
| 1782 | 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date), |
| 1783 | 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date), |
| 1784 | 'source' => $dao->source, |
| 1785 | 'status_id' => $dao->status_id, |
| 1786 | ]; |
| 1787 | // create/update membership(s) for related contact(s) |
| 1788 | CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao); |
| 1789 | } // end of if relationshipTypeId |
| 1790 | } |
| 1791 | } |
| 1792 | |
| 1793 | /** |
| 1794 | * Create activities tracking the merge on affected contacts. |
| 1795 | * |
| 1796 | * @param int $mainId |
| 1797 | * @param int $otherId |
| 1798 | * |
| 1799 | * @throws \CiviCRM_API3_Exception |
| 1800 | */ |
| 1801 | public static function createMergeActivities($mainId, $otherId) { |
| 1802 | $params = [ |
| 1803 | 1 => $otherId, |
| 1804 | 2 => $mainId, |
| 1805 | ]; |
| 1806 | $activity = civicrm_api3('activity', 'create', [ |
| 1807 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : |
| 1808 | $mainId, |
| 1809 | 'subject' => ts('Contact ID %1 has been merged and deleted.', $params), |
| 1810 | 'target_contact_id' => $mainId, |
| 1811 | 'activity_type_id' => 'Contact Merged', |
| 1812 | 'status_id' => 'Completed', |
| 1813 | ]); |
| 1814 | if (civicrm_api3('Setting', 'getvalue', [ |
| 1815 | 'name' => 'contact_undelete', |
| 1816 | 'group' => 'CiviCRM Preferences', |
| 1817 | ])) { |
| 1818 | civicrm_api3('activity', 'create', [ |
| 1819 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : |
| 1820 | $otherId, |
| 1821 | 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params), |
| 1822 | 'target_contact_id' => $otherId, |
| 1823 | 'activity_type_id' => 'Contact Deleted by Merge', |
| 1824 | 'parent_id' => $activity['id'], |
| 1825 | 'status_id' => 'Completed', |
| 1826 | ]); |
| 1827 | } |
| 1828 | } |
| 1829 | |
| 1830 | /** |
| 1831 | * Get Duplicate Pairs based on a rule for a group. |
| 1832 | * |
| 1833 | * @param int $rule_group_id |
| 1834 | * @param int $group_id |
| 1835 | * @param bool $reloadCacheIfEmpty |
| 1836 | * Should the cache be reloaded if empty - this must be false when in a dedupe action! |
| 1837 | * @param int $batchLimit |
| 1838 | * @param bool $isSelected |
| 1839 | * Limit to selected pairs. |
| 1840 | * @param bool $includeConflicts |
| 1841 | * @param array $criteria |
| 1842 | * Additional criteria to narrow down the merge group. |
| 1843 | * |
| 1844 | * @param bool $checkPermissions |
| 1845 | * Respect logged in user permissions. |
| 1846 | * |
| 1847 | * @param int $searchLimit |
| 1848 | * Limit to searching for matches against this many contacts. |
| 1849 | * |
| 1850 | * @param int $isForceNewSearch |
| 1851 | * Should a new search be forced, bypassing any cache retrieval. |
| 1852 | * |
| 1853 | * @return array |
| 1854 | * Array of matches meeting the criteria. |
| 1855 | * |
| 1856 | * @throws \CRM_Core_Exception |
| 1857 | * @throws \CiviCRM_API3_Exception |
| 1858 | */ |
| 1859 | public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0, $isForceNewSearch = 0) { |
| 1860 | $dupePairs = $isForceNewSearch ? [] : self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit); |
| 1861 | if (empty($dupePairs) && $reloadCacheIfEmpty) { |
| 1862 | // If we haven't found any dupes, probably cache is empty. |
| 1863 | // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any |
| 1864 | // until we have done some processing. |
| 1865 | CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit); |
| 1866 | return self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions, $searchLimit); |
| 1867 | } |
| 1868 | return $dupePairs; |
| 1869 | } |
| 1870 | |
| 1871 | /** |
| 1872 | * Get the cache key string for the merge action. |
| 1873 | * |
| 1874 | * @param int $rule_group_id |
| 1875 | * @param int $group_id |
| 1876 | * @param array $criteria |
| 1877 | * Additional criteria to narrow down the merge group. |
| 1878 | * Currently we are only supporting the key 'contact' within it. |
| 1879 | * @param bool $checkPermissions |
| 1880 | * Respect the users permissions. |
| 1881 | * @param int $searchLimit |
| 1882 | * Number of contacts to seek dupes for (we need this because if |
| 1883 | * we change it the results won't be refreshed otherwise. Changing the limit |
| 1884 | * from 100 to 1000 SHOULD result in a new dedupe search). |
| 1885 | * |
| 1886 | * @return string |
| 1887 | */ |
| 1888 | public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit) { |
| 1889 | $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id); |
| 1890 | $cacheKeyString = "merge_{$contactType}"; |
| 1891 | $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0'; |
| 1892 | $cacheKeyString .= $group_id ? "_{$group_id}" : '_0'; |
| 1893 | $cacheKeyString .= '_' . (int) $searchLimit; |
| 1894 | $cacheKeyString .= !empty($criteria) ? md5(serialize($criteria)) : '_0'; |
| 1895 | if ($checkPermissions) { |
| 1896 | $contactID = CRM_Core_Session::getLoggedInContactID(); |
| 1897 | if (!$contactID) { |
| 1898 | // Distinguish between no permission check & no logged in user. |
| 1899 | $contactID = 'null'; |
| 1900 | } |
| 1901 | $cacheKeyString .= '_' . $contactID; |
| 1902 | } |
| 1903 | else { |
| 1904 | $cacheKeyString .= '_0'; |
| 1905 | } |
| 1906 | return $cacheKeyString; |
| 1907 | } |
| 1908 | |
| 1909 | /** |
| 1910 | * Get the metadata for the merge fields. |
| 1911 | * |
| 1912 | * This is basically the contact metadata, augmented with fields to |
| 1913 | * represent email greeting, postal greeting & addressee. |
| 1914 | * |
| 1915 | * @return array |
| 1916 | */ |
| 1917 | public static function getMergeFieldsMetadata() { |
| 1918 | if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) { |
| 1919 | return \Civi::$statics[__CLASS__]['merge_fields_metadata']; |
| 1920 | } |
| 1921 | $fields = CRM_Contact_DAO_Contact::fields(); |
| 1922 | static $optionValueFields = []; |
| 1923 | if (empty($optionValueFields)) { |
| 1924 | $optionValueFields = CRM_Core_OptionValue::getFields(); |
| 1925 | } |
| 1926 | foreach ($optionValueFields as $field => $params) { |
| 1927 | $fields[$field]['title'] = $params['title']; |
| 1928 | } |
| 1929 | \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields; |
| 1930 | return \Civi::$statics[__CLASS__]['merge_fields_metadata']; |
| 1931 | } |
| 1932 | |
| 1933 | /** |
| 1934 | * Get the details of the contact to be merged. |
| 1935 | * |
| 1936 | * @param int $contact_id |
| 1937 | * |
| 1938 | * @return array |
| 1939 | * |
| 1940 | * @throws CRM_Core_Exception |
| 1941 | */ |
| 1942 | public static function getMergeContactDetails($contact_id) { |
| 1943 | $params = [ |
| 1944 | 'contact_id' => $contact_id, |
| 1945 | 'version' => 3, |
| 1946 | 'return' => array_merge(['display_name'], self::getContactFields()), |
| 1947 | ]; |
| 1948 | $result = civicrm_api('contact', 'get', $params); |
| 1949 | |
| 1950 | // CRM-18480: Cancel the process if the contact is already deleted |
| 1951 | if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) { |
| 1952 | throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [ |
| 1953 | 1 => $contact_id, |
| 1954 | ])); |
| 1955 | } |
| 1956 | |
| 1957 | return $result['values'][$contact_id]; |
| 1958 | } |
| 1959 | |
| 1960 | /** |
| 1961 | * Merge location. |
| 1962 | * |
| 1963 | * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts. |
| 1964 | * |
| 1965 | * The data is in the format received from the merge form (which is a fairly confusing format). |
| 1966 | * |
| 1967 | * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook |
| 1968 | * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have |
| 1969 | * been calculated and before saving because |
| 1970 | * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile |
| 1971 | * - passing to a hook right before save means calculations only have to be done once |
| 1972 | * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just |
| 1973 | * ugly. |
| 1974 | * |
| 1975 | * The use of the new hook is tested, including the fact it is called before contributions are merged, as this |
| 1976 | * is likely to be significant data in merge hooks. |
| 1977 | * |
| 1978 | * @param int $mainId |
| 1979 | * @param int $otherId |
| 1980 | * |
| 1981 | * @param array $migrationInfo |
| 1982 | * Migration info for the merge. This is passed to the hook as informational only. |
| 1983 | */ |
| 1984 | public static function mergeLocations($mainId, $otherId, $migrationInfo) { |
| 1985 | foreach ($migrationInfo as $key => $value) { |
| 1986 | $isLocationField = (substr($key, 0, 14) == 'move_location_' and $value != NULL); |
| 1987 | if (!$isLocationField) { |
| 1988 | continue; |
| 1989 | } |
| 1990 | $locField = explode('_', $key); |
| 1991 | $fieldName = $locField[2]; |
| 1992 | $fieldCount = $locField[3]; |
| 1993 | |
| 1994 | // Set up the operation type (add/overwrite) |
| 1995 | // Ignore operation for websites |
| 1996 | // @todo Tidy this up |
| 1997 | $operation = 0; |
| 1998 | if ($fieldName != 'website') { |
| 1999 | $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]); |
| 2000 | } |
| 2001 | // default operation is overwrite. |
| 2002 | if (!$operation) { |
| 2003 | $operation = 2; |
| 2004 | } |
| 2005 | $locBlocks[$fieldName][$fieldCount]['operation'] = $operation; |
| 2006 | } |
| 2007 | $blocksDAO = []; |
| 2008 | |
| 2009 | // @todo Handle OpenID (not currently in API). |
| 2010 | if (!empty($locBlocks)) { |
| 2011 | $locationBlocks = self::getLocationBlockInfo(); |
| 2012 | |
| 2013 | $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_primary' => 1]); |
| 2014 | $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_billing' => 1]); |
| 2015 | |
| 2016 | foreach ($locBlocks as $name => $block) { |
| 2017 | $blocksDAO[$name] = ['delete' => [], 'update' => []]; |
| 2018 | if (!is_array($block) || CRM_Utils_System::isNull($block)) { |
| 2019 | continue; |
| 2020 | } |
| 2021 | $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label']; |
| 2022 | $changePrimary = FALSE; |
| 2023 | $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL; |
| 2024 | $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL; |
| 2025 | |
| 2026 | foreach ($block as $blkCount => $values) { |
| 2027 | $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]); |
| 2028 | $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0); |
| 2029 | if (!$otherBlockId) { |
| 2030 | continue; |
| 2031 | } |
| 2032 | |
| 2033 | // For the block which belongs to other-contact, link the location block to main-contact |
| 2034 | $otherBlockDAO = new $daoName(); |
| 2035 | $otherBlockDAO->contact_id = $mainId; |
| 2036 | |
| 2037 | // Get the ID of this block on the 'other' contact, otherwise skip |
| 2038 | $otherBlockDAO->id = $otherBlockId; |
| 2039 | |
| 2040 | // Add/update location and type information from the form, if applicable |
| 2041 | if ($locationBlocks[$name]['hasLocation']) { |
| 2042 | $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]); |
| 2043 | $otherBlockDAO->location_type_id = $locTypeId; |
| 2044 | } |
| 2045 | if ($locationBlocks[$name]['hasType']) { |
| 2046 | $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]); |
| 2047 | $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId; |
| 2048 | } |
| 2049 | |
| 2050 | // If we're deliberately setting this as primary then add the flag |
| 2051 | // and remove it from the current primary location (if there is one). |
| 2052 | // But only once for each entity. |
| 2053 | $set_primary = CRM_Utils_Array::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]); |
| 2054 | if (!$changePrimary && $set_primary == "1") { |
| 2055 | $otherBlockDAO->is_primary = 1; |
| 2056 | if ($primaryDAOId) { |
| 2057 | $removePrimaryDAO = new $daoName(); |
| 2058 | $removePrimaryDAO->id = $primaryDAOId; |
| 2059 | $removePrimaryDAO->is_primary = 0; |
| 2060 | $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO; |
| 2061 | } |
| 2062 | $changePrimary = TRUE; |
| 2063 | } |
| 2064 | // Otherwise, if main contact already has primary, set it to 0. |
| 2065 | elseif ($primaryDAOId) { |
| 2066 | $otherBlockDAO->is_primary = 0; |
| 2067 | } |
| 2068 | |
| 2069 | // If the main contact already has a billing location, set this to 0. |
| 2070 | if ($billingDAOId) { |
| 2071 | $otherBlockDAO->is_billing = 0; |
| 2072 | } |
| 2073 | |
| 2074 | $operation = CRM_Utils_Array::value('operation', $values, 2); |
| 2075 | // overwrite - need to delete block which belongs to main-contact. |
| 2076 | if (!empty($mainBlockId) && ($operation == 2)) { |
| 2077 | $deleteDAO = new $daoName(); |
| 2078 | $deleteDAO->id = $mainBlockId; |
| 2079 | $deleteDAO->find(TRUE); |
| 2080 | |
| 2081 | // if we about to delete a primary / billing block, set the flags for new block |
| 2082 | // that we going to assign to main-contact |
| 2083 | if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) { |
| 2084 | $otherBlockDAO->is_primary = 1; |
| 2085 | } |
| 2086 | if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) { |
| 2087 | $otherBlockDAO->is_billing = 1; |
| 2088 | } |
| 2089 | $blocksDAO[$name]['delete'][$deleteDAO->id] = $deleteDAO; |
| 2090 | } |
| 2091 | $blocksDAO[$name]['update'][$otherBlockDAO->id] = $otherBlockDAO; |
| 2092 | } |
| 2093 | } |
| 2094 | } |
| 2095 | |
| 2096 | CRM_Utils_Hook::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo); |
| 2097 | foreach ($blocksDAO as $blockDAOs) { |
| 2098 | if (!empty($blockDAOs['update'])) { |
| 2099 | foreach ($blockDAOs['update'] as $blockDAO) { |
| 2100 | $blockDAO->save(); |
| 2101 | } |
| 2102 | } |
| 2103 | if (!empty($blockDAOs['delete'])) { |
| 2104 | foreach ($blockDAOs['delete'] as $blockDAO) { |
| 2105 | $blockDAO->delete(); |
| 2106 | } |
| 2107 | } |
| 2108 | } |
| 2109 | } |
| 2110 | |
| 2111 | /** |
| 2112 | * Dedupe a pair of contacts. |
| 2113 | * |
| 2114 | * @param array $resultStats |
| 2115 | * @param array $deletedContacts |
| 2116 | * @param string $mode |
| 2117 | * @param bool $checkPermissions |
| 2118 | * @param int $mainId |
| 2119 | * @param int $otherId |
| 2120 | * @param string $cacheKeyString |
| 2121 | * |
| 2122 | * @throws \CRM_Core_Exception |
| 2123 | * @throws \CiviCRM_API3_Exception |
| 2124 | * @throws \API_Exception |
| 2125 | */ |
| 2126 | protected static function dedupePair(&$resultStats, &$deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString) { |
| 2127 | |
| 2128 | $migrationInfo = []; |
| 2129 | $conflicts = []; |
| 2130 | if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) { |
| 2131 | CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions); |
| 2132 | $resultStats['merged'][] = [ |
| 2133 | 'main_id' => $mainId, |
| 2134 | 'other_id' => $otherId, |
| 2135 | ]; |
| 2136 | $deletedContacts[] = $otherId; |
| 2137 | } |
| 2138 | else { |
| 2139 | $resultStats['skipped'][] = [ |
| 2140 | 'main_id' => $mainId, |
| 2141 | 'other_id' => $otherId, |
| 2142 | ]; |
| 2143 | } |
| 2144 | |
| 2145 | // store any conflicts |
| 2146 | if (!empty($conflicts)) { |
| 2147 | CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts, $mode); |
| 2148 | } |
| 2149 | else { |
| 2150 | CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString); |
| 2151 | } |
| 2152 | } |
| 2153 | |
| 2154 | /** |
| 2155 | * Replace the pseudo QFKey with zero if it is present. |
| 2156 | * |
| 2157 | * @todo - on the slim chance this is still relevant it should be moved to the form layer. |
| 2158 | * |
| 2159 | * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA |
| 2160 | * can still help. |
| 2161 | * |
| 2162 | * @param array $migrationInfo |
| 2163 | */ |
| 2164 | protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) { |
| 2165 | $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; |
| 2166 | foreach ($migrationInfo as $key => &$value) { |
| 2167 | if ($value == $qfZeroBug) { |
| 2168 | $value = '0'; |
| 2169 | } |
| 2170 | } |
| 2171 | } |
| 2172 | |
| 2173 | /** |
| 2174 | * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose. |
| 2175 | * |
| 2176 | * Update this function formats fields in preparation for them to be submitted to the |
| 2177 | * 'ProfileContactCreate action. This is a lot of code to do this & for |
| 2178 | * - for some fields it fails - e.g Country - per testMergeCustomFields. |
| 2179 | * |
| 2180 | * Goal is to move all custom field handling into 'move' functions on the various BAO |
| 2181 | * with an underlying DAO function. For custom fields it has been started on the BAO. |
| 2182 | * |
| 2183 | * @param $mainId |
| 2184 | * @param $key |
| 2185 | * @param $cFields |
| 2186 | * @param $submitted |
| 2187 | * @param $value |
| 2188 | * |
| 2189 | * @return array |
| 2190 | * @throws \Exception |
| 2191 | */ |
| 2192 | protected static function processCustomFields($mainId, $key, $cFields, $submitted, $value) { |
| 2193 | if (substr($key, 0, 7) == 'custom_') { |
| 2194 | $fid = (int) substr($key, 7); |
| 2195 | if (empty($cFields[$fid])) { |
| 2196 | return [$cFields, $submitted]; |
| 2197 | } |
| 2198 | $htmlType = $cFields[$fid]['attributes']['html_type']; |
| 2199 | switch ($htmlType) { |
| 2200 | case 'File': |
| 2201 | // Handled in CustomField->move(). Tested in testMergeCustomFields. |
| 2202 | unset($submitted["custom_$fid"]); |
| 2203 | break; |
| 2204 | |
| 2205 | case 'Select Country': |
| 2206 | // @todo Test in testMergeCustomFields disabled as this does not work, Handle in CustomField->move(). |
| 2207 | case 'Select State/Province': |
| 2208 | $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid); |
| 2209 | break; |
| 2210 | |
| 2211 | case 'Select Date': |
| 2212 | if ($cFields[$fid]['attributes']['is_view']) { |
| 2213 | $submitted[$key] = date('YmdHis', strtotime($submitted[$key])); |
| 2214 | } |
| 2215 | break; |
| 2216 | |
| 2217 | case 'CheckBox': |
| 2218 | case 'Multi-Select': |
| 2219 | case 'Multi-Select Country': |
| 2220 | case 'Multi-Select State/Province': |
| 2221 | // Merge values from both contacts for multivalue fields, CRM-4385 |
| 2222 | // get the existing custom values from db. |
| 2223 | $customParams = ['entityID' => $mainId, $key => TRUE]; |
| 2224 | $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams); |
| 2225 | if (!empty($customfieldValues[$key])) { |
| 2226 | $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]); |
| 2227 | if (is_array($existingValue) && !empty($existingValue)) { |
| 2228 | $mergeValue = $submittedCustomFields = []; |
| 2229 | if ($value == 'null') { |
| 2230 | // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it. |
| 2231 | $submitted[$key] = $value; |
| 2232 | } |
| 2233 | else { |
| 2234 | if ($value) { |
| 2235 | $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); |
| 2236 | } |
| 2237 | |
| 2238 | // CRM-19653: overwrite or add the existing custom field value with dupicate contact's |
| 2239 | // custom field value stored at $submittedCustomValue. |
| 2240 | foreach ($submittedCustomFields as $k => $v) { |
| 2241 | if ($v != '' && !in_array($v, $mergeValue)) { |
| 2242 | $mergeValue[] = $v; |
| 2243 | } |
| 2244 | } |
| 2245 | |
| 2246 | //keep state and country as array format. |
| 2247 | //for checkbox and m-select format w/ VALUE_SEPARATOR |
| 2248 | if (in_array($htmlType, [ |
| 2249 | 'CheckBox', |
| 2250 | 'Multi-Select', |
| 2251 | ])) { |
| 2252 | $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, |
| 2253 | $mergeValue |
| 2254 | ) . CRM_Core_DAO::VALUE_SEPARATOR; |
| 2255 | } |
| 2256 | else { |
| 2257 | $submitted[$key] = $mergeValue; |
| 2258 | } |
| 2259 | } |
| 2260 | } |
| 2261 | } |
| 2262 | elseif (in_array($htmlType, [ |
| 2263 | 'Multi-Select Country', |
| 2264 | 'Multi-Select State/Province', |
| 2265 | ])) { |
| 2266 | //we require submitted values should be in array format |
| 2267 | if ($value) { |
| 2268 | $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); |
| 2269 | //hack to remove null values from array. |
| 2270 | $mergeValue = []; |
| 2271 | foreach ($mergeValueArray as $k => $v) { |
| 2272 | if ($v != '') { |
| 2273 | $mergeValue[] = $v; |
| 2274 | } |
| 2275 | } |
| 2276 | $submitted[$key] = $mergeValue; |
| 2277 | } |
| 2278 | } |
| 2279 | break; |
| 2280 | |
| 2281 | default: |
| 2282 | break; |
| 2283 | } |
| 2284 | } |
| 2285 | return [$cFields, $submitted]; |
| 2286 | } |
| 2287 | |
| 2288 | /** |
| 2289 | * Get metadata for the custom fields for the merge. |
| 2290 | * |
| 2291 | * @param string $contactType |
| 2292 | * |
| 2293 | * @return array |
| 2294 | */ |
| 2295 | protected static function getCustomFieldMetadata($contactType) { |
| 2296 | $treeCache = []; |
| 2297 | if (!array_key_exists($contactType, $treeCache)) { |
| 2298 | $treeCache[$contactType] = CRM_Core_BAO_CustomGroup::getTree( |
| 2299 | $contactType, |
| 2300 | NULL, |
| 2301 | NULL, |
| 2302 | -1, |
| 2303 | [], |
| 2304 | NULL, |
| 2305 | TRUE, |
| 2306 | NULL, |
| 2307 | FALSE, |
| 2308 | FALSE |
| 2309 | ); |
| 2310 | } |
| 2311 | |
| 2312 | $cFields = []; |
| 2313 | foreach ($treeCache[$contactType] as $key => $group) { |
| 2314 | if (!isset($group['fields'])) { |
| 2315 | continue; |
| 2316 | } |
| 2317 | foreach ($group['fields'] as $fid => $field) { |
| 2318 | $cFields[$fid]['attributes'] = $field; |
| 2319 | } |
| 2320 | } |
| 2321 | return $cFields; |
| 2322 | } |
| 2323 | |
| 2324 | /** |
| 2325 | * Get conflicts for proposed merge pair. |
| 2326 | * |
| 2327 | * @param array $migrationInfo |
| 2328 | * This is primarily to inform hooks. The can also modify it which feels |
| 2329 | * pretty fragile to do it here - but it is historical. |
| 2330 | * @param int $mainId |
| 2331 | * Main contact with whom merge has to happen. |
| 2332 | * @param int $otherId |
| 2333 | * Duplicate contact which would be deleted after merge operation. |
| 2334 | * @param string $mode |
| 2335 | * Helps decide how to behave when there are conflicts. |
| 2336 | * - A 'safe' value skips the merge if there are any un-resolved conflicts. |
| 2337 | * - Does a force merge otherwise (aggressive mode). |
| 2338 | * |
| 2339 | * @return array |
| 2340 | * |
| 2341 | * @throws \CRM_Core_Exception |
| 2342 | * @throws \CiviCRM_API3_Exception |
| 2343 | */ |
| 2344 | public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) { |
| 2345 | $conflicts = []; |
| 2346 | // Generate var $migrationInfo. The variable structure is exactly same as |
| 2347 | // $formValues submitted during a UI merge for a pair of contacts. |
| 2348 | $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, FALSE); |
| 2349 | // add additional details that we might need to resolve conflicts |
| 2350 | $migrationInfo = $rowsElementsAndInfo['migration_info']; |
| 2351 | $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details']; |
| 2352 | $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details']; |
| 2353 | $migrationInfo['rows'] = &$rowsElementsAndInfo['rows']; |
| 2354 | // go ahead with merge if there is no conflict |
| 2355 | $originalMigrationInfo = $migrationInfo; |
| 2356 | foreach ($migrationInfo as $key => $val) { |
| 2357 | if ($val === "null") { |
| 2358 | // Rule: Never overwrite with an empty value (in any mode) |
| 2359 | unset($migrationInfo[$key]); |
| 2360 | continue; |
| 2361 | } |
| 2362 | elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or |
| 2363 | substr($key, 0, 12) == 'move_custom_' |
| 2364 | ) and $val != NULL |
| 2365 | ) { |
| 2366 | // Rule: If both main-contact, and other-contact have a field with a |
| 2367 | // different value, then let $mode decide if to merge it or not |
| 2368 | if ( |
| 2369 | (!empty($migrationInfo['rows'][$key]['main']) |
| 2370 | // For custom fields a 0 (e.g in an int field) could be a true conflict. This |
| 2371 | // is probably true for other fields too - e.g. 'do_not_email' but |
| 2372 | // leaving that investigation as a @todo - until tests can be written. |
| 2373 | // Note the handling of this has test coverage - although the data-typing |
| 2374 | // of '0' feels flakey we have insurance. |
| 2375 | || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_') |
| 2376 | ) |
| 2377 | && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other'] |
| 2378 | ) { |
| 2379 | |
| 2380 | // note it down & lets wait for response from the hook. |
| 2381 | // For no response $mode will decide if to skip this merge |
| 2382 | $conflicts[$key] = NULL; |
| 2383 | } |
| 2384 | } |
| 2385 | elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) { |
| 2386 | $locField = explode('_', $key); |
| 2387 | $fieldName = $locField[2]; |
| 2388 | $fieldCount = $locField[3]; |
| 2389 | |
| 2390 | // Rule: Catch address conflicts (same address type on both contacts) |
| 2391 | if ( |
| 2392 | isset($migrationInfo['main_details']['location_blocks'][$fieldName]) && |
| 2393 | !empty($migrationInfo['main_details']['location_blocks'][$fieldName]) |
| 2394 | ) { |
| 2395 | |
| 2396 | // Load the address we're inspecting from the 'other' contact |
| 2397 | $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount]; |
| 2398 | $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord); |
| 2399 | |
| 2400 | // If it exists on the 'main' contact already, skip it. Otherwise |
| 2401 | // if the location type exists already, log a conflict. |
| 2402 | foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) { |
| 2403 | if (self::locationIsSame($addressRecord, $mainAddressRecord)) { |
| 2404 | unset($migrationInfo[$key]); |
| 2405 | break; |
| 2406 | } |
| 2407 | elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) { |
| 2408 | $conflicts[$key] = NULL; |
| 2409 | break; |
| 2410 | } |
| 2411 | } |
| 2412 | } |
| 2413 | |
| 2414 | // For other locations, don't merge/add if the values are the same |
| 2415 | elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) { |
| 2416 | unset($migrationInfo[$key]); |
| 2417 | } |
| 2418 | } |
| 2419 | } |
| 2420 | |
| 2421 | // A hook to implement other algorithms for choosing which contact to bias to when |
| 2422 | // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here |
| 2423 | // merge happens with new values filled in here. For a particular field / row not to be merged |
| 2424 | // field should be unset from fields_in_conflict. |
| 2425 | $migrationData = [ |
| 2426 | 'old_migration_info' => $originalMigrationInfo, |
| 2427 | 'mode' => $mode, |
| 2428 | 'fields_in_conflict' => $conflicts, |
| 2429 | 'merge_mode' => $mode, |
| 2430 | 'migration_info' => $migrationInfo, |
| 2431 | ]; |
| 2432 | CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId); |
| 2433 | $conflicts = $migrationData['fields_in_conflict']; |
| 2434 | // allow hook to override / manipulate migrationInfo as well |
| 2435 | $migrationInfo = $migrationData['migration_info']; |
| 2436 | foreach ($conflicts as $key => $val) { |
| 2437 | if ($val !== NULL || $mode !== 'safe') { |
| 2438 | // copy over the resolved values |
| 2439 | $migrationInfo[$key] = $val; |
| 2440 | unset($conflicts[$key]); |
| 2441 | } |
| 2442 | } |
| 2443 | $migrationInfo['skip_merge'] = $migrationData['skip_merge'] ?? !empty($conflicts); |
| 2444 | return self::formatConflictArray($conflicts, $migrationInfo['rows'], $migrationInfo['main_details']['location_blocks'], $migrationInfo['other_details']['location_blocks'], $mainId, $otherId); |
| 2445 | } |
| 2446 | |
| 2447 | /** |
| 2448 | * @param array $conflicts |
| 2449 | * @param array $migrationInfo |
| 2450 | * @param $toKeepContactLocationBlocks |
| 2451 | * @param $toRemoveContactLocationBlocks |
| 2452 | * @param $toKeepID |
| 2453 | * @param $toRemoveID |
| 2454 | * |
| 2455 | * @return mixed |
| 2456 | * @throws \CRM_Core_Exception |
| 2457 | */ |
| 2458 | protected static function formatConflictArray($conflicts, $migrationInfo, $toKeepContactLocationBlocks, $toRemoveContactLocationBlocks, $toKeepID, $toRemoveID) { |
| 2459 | $return = []; |
| 2460 | foreach (array_keys($conflicts) as $index) { |
| 2461 | if (substr($index, 0, 14) === 'move_location_') { |
| 2462 | $parts = explode('_', $index); |
| 2463 | $entity = $parts[2]; |
| 2464 | $blockIndex = $parts[3]; |
| 2465 | $locationTypeID = $toKeepContactLocationBlocks[$entity][$blockIndex]['location_type_id']; |
| 2466 | $entityConflicts = [ |
| 2467 | 'location_type_id' => $locationTypeID, |
| 2468 | 'title' => $migrationInfo[$index]['title'], |
| 2469 | ]; |
| 2470 | foreach ($toKeepContactLocationBlocks[$entity][$blockIndex] as $fieldName => $fieldValue) { |
| 2471 | if (in_array($fieldName, self::ignoredFields())) { |
| 2472 | continue; |
| 2473 | } |
| 2474 | $toRemoveValue = CRM_Utils_Array::value($fieldName, $toRemoveContactLocationBlocks[$entity][$blockIndex]); |
| 2475 | if ($fieldValue !== $toRemoveValue) { |
| 2476 | $entityConflicts[$fieldName] = [ |
| 2477 | $toKeepID => $fieldValue, |
| 2478 | $toRemoveID => $toRemoveValue, |
| 2479 | ]; |
| 2480 | } |
| 2481 | } |
| 2482 | $return[$entity][] = $entityConflicts; |
| 2483 | } |
| 2484 | elseif (substr($index, 0, 5) === 'move_') { |
| 2485 | $contactFieldsToCompare[] = str_replace('move_', '', $index); |
| 2486 | $return['contact'][str_replace('move_', '', $index)] = [ |
| 2487 | 'title' => $migrationInfo[$index]['title'], |
| 2488 | $toKeepID => $migrationInfo[$index]['main'], |
| 2489 | $toRemoveID => $migrationInfo[$index]['other'], |
| 2490 | ]; |
| 2491 | } |
| 2492 | else { |
| 2493 | // Can't think of why this would be the case but perhaps it's ensuring it isn't as we |
| 2494 | // refactor this. |
| 2495 | throw new CRM_Core_Exception(ts('Unknown parameter') . $index); |
| 2496 | } |
| 2497 | } |
| 2498 | return $return; |
| 2499 | } |
| 2500 | |
| 2501 | /** |
| 2502 | * Get any duplicate merge pairs that have been previously cached. |
| 2503 | * |
| 2504 | * @param int $rule_group_id |
| 2505 | * @param int $group_id |
| 2506 | * @param int $batchLimit |
| 2507 | * @param bool $isSelected |
| 2508 | * @param bool $includeConflicts |
| 2509 | * @param array $criteria |
| 2510 | * @param int $checkPermissions |
| 2511 | * @param int $searchLimit |
| 2512 | * |
| 2513 | * @return array |
| 2514 | */ |
| 2515 | protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit = 0) { |
| 2516 | return CRM_Core_BAO_PrevNextCache::retrieve( |
| 2517 | self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit), |
| 2518 | self::getJoinOnDedupeTable(), |
| 2519 | self::getWhereString($isSelected), |
| 2520 | 0, $batchLimit, |
| 2521 | [], '', |
| 2522 | $includeConflicts |
| 2523 | ); |
| 2524 | } |
| 2525 | |
| 2526 | /** |
| 2527 | * @return array |
| 2528 | */ |
| 2529 | protected static function ignoredFields(): array { |
| 2530 | $keysToIgnore = [ |
| 2531 | 'id', |
| 2532 | 'is_primary', |
| 2533 | 'is_billing', |
| 2534 | 'manual_geo_code', |
| 2535 | 'contact_id', |
| 2536 | 'reset_date', |
| 2537 | 'hold_date', |
| 2538 | ]; |
| 2539 | return $keysToIgnore; |
| 2540 | } |
| 2541 | |
| 2542 | } |