| 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 | $customTables = array_keys($customTables); |
| 508 | } |
| 509 | |
| 510 | $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs)); |
| 511 | |
| 512 | // if there aren't any specific tables, don't affect the ones handled by relTables() |
| 513 | // also don't affect tables in locTables() CRM-15658 |
| 514 | $relTables = self::relTables(); |
| 515 | $handled = self::locTables(); |
| 516 | |
| 517 | foreach ($relTables as $params) { |
| 518 | $handled = array_merge($handled, $params['tables']); |
| 519 | } |
| 520 | $affected = array_diff($affected, $handled); |
| 521 | $affected = array_unique(array_merge($affected, $tables)); |
| 522 | |
| 523 | $mainId = (int) $mainId; |
| 524 | $otherId = (int) $otherId; |
| 525 | $multi_value_tables = array_keys(CRM_Dedupe_Merger::getMultiValueCustomSets('cidRefs')); |
| 526 | |
| 527 | $sqls = []; |
| 528 | foreach ($affected as $table) { |
| 529 | // skipping non selected single-value custom table's value migration |
| 530 | if (!in_array($table, $multi_value_tables)) { |
| 531 | if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) { |
| 532 | continue; |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | // Call custom processing function for objects that require it |
| 537 | if (isset($cpTables[$table])) { |
| 538 | foreach ($cpTables[$table] as $className => $fnName) { |
| 539 | $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations); |
| 540 | } |
| 541 | // Skip normal processing |
| 542 | continue; |
| 543 | } |
| 544 | |
| 545 | // use UPDATE IGNORE + DELETE query pair to skip on situations when |
| 546 | // there's a UNIQUE restriction on ($field, some_other_field) pair |
| 547 | if (isset($cidRefs[$table])) { |
| 548 | foreach ($cidRefs[$table] as $field) { |
| 549 | // carry related contributions CRM-5359 |
| 550 | if (in_array($table, $paymentTables)) { |
| 551 | $paymentSqls = self::paymentSql($table, $mainId, $otherId); |
| 552 | $sqls = array_merge($sqls, $paymentSqls); |
| 553 | |
| 554 | if (!empty($tables) && !in_array('civicrm_contribution', $tables)) { |
| 555 | $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment'); |
| 556 | $sqls = array_merge($sqls, $payOprSqls); |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations); |
| 561 | $sqls = array_merge($sqls, $preOperationSqls); |
| 562 | |
| 563 | if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self::customRecordExists($mainId, $table, $field)) { |
| 564 | $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)"; |
| 565 | } |
| 566 | $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId"; |
| 567 | $sqls[] = "DELETE FROM $table WHERE $field = $otherId"; |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | if (isset($eidRefs[$table])) { |
| 572 | foreach ($eidRefs[$table] as $entityTable => $entityId) { |
| 573 | $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'"; |
| 574 | $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'"; |
| 575 | } |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | // Allow hook_civicrm_merge() to add SQL statements for the merge operation. |
| 580 | CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables); |
| 581 | |
| 582 | // call the SQL queries in one transaction |
| 583 | $transaction = new CRM_Core_Transaction(); |
| 584 | foreach ($sqls as $sql) { |
| 585 | CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE); |
| 586 | } |
| 587 | CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId); |
| 588 | $transaction->commit(); |
| 589 | } |
| 590 | |
| 591 | /** |
| 592 | * Given a contact ID, will check if a record exists in given table. |
| 593 | * |
| 594 | * @param $contactID |
| 595 | * @param $table |
| 596 | * @param $idField |
| 597 | * Field where the contact's ID is stored in the table |
| 598 | * |
| 599 | * @return bool |
| 600 | * True if a record is found for the given contact ID, false otherwise |
| 601 | */ |
| 602 | private static function customRecordExists($contactID, $table, $idField) { |
| 603 | $sql = " |
| 604 | SELECT COUNT(*) AS count |
| 605 | FROM $table |
| 606 | WHERE $idField = $contactID |
| 607 | "; |
| 608 | $dbResult = CRM_Core_DAO::executeQuery($sql); |
| 609 | $dbResult->fetch(); |
| 610 | |
| 611 | if ($dbResult->count > 0) { |
| 612 | return TRUE; |
| 613 | } |
| 614 | |
| 615 | return FALSE; |
| 616 | } |
| 617 | |
| 618 | /** |
| 619 | * Load all non-empty fields for the contacts |
| 620 | * |
| 621 | * @param array $main |
| 622 | * Contact details. |
| 623 | * @param array $other |
| 624 | * Contact details. |
| 625 | * |
| 626 | * @return array |
| 627 | */ |
| 628 | public static function retrieveFields($main, $other) { |
| 629 | $result = [ |
| 630 | 'contact' => [], |
| 631 | 'custom' => [], |
| 632 | ]; |
| 633 | foreach (self::getContactFields() as $validField) { |
| 634 | // CRM-17556 Get all non-empty fields, to make comparison easier |
| 635 | if (!empty($main[$validField]) || !empty($other[$validField])) { |
| 636 | $result['contact'][] = $validField; |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']); |
| 641 | $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']); |
| 642 | $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs))); |
| 643 | foreach ($keys as $key) { |
| 644 | // Exclude multi-value fields CRM-13836 |
| 645 | if (strpos($key, '_')) { |
| 646 | continue; |
| 647 | } |
| 648 | $key1 = CRM_Utils_Array::value($key, $mainEvs); |
| 649 | $key2 = CRM_Utils_Array::value($key, $otherEvs); |
| 650 | // We wish to retain '0' as it has a different meaning than NULL on a checkbox. |
| 651 | // However I can't think of a case where an empty string is more meaningful than null |
| 652 | // or where it would be FALSE or something else nullish. |
| 653 | $valuesToIgnore = [NULL, '', []]; |
| 654 | if (!in_array($key1, $valuesToIgnore, TRUE) || !in_array($key2, $valuesToIgnore, TRUE)) { |
| 655 | $result['custom'][] = $key; |
| 656 | } |
| 657 | } |
| 658 | return $result; |
| 659 | } |
| 660 | |
| 661 | /** |
| 662 | * Batch merge a set of contacts based on rule-group and group. |
| 663 | * |
| 664 | * @param int $rgid |
| 665 | * Rule group id. |
| 666 | * @param int $gid |
| 667 | * Group id. |
| 668 | * @param string $mode |
| 669 | * Helps decide how to behave when there are conflicts. |
| 670 | * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive' |
| 671 | * mode does a force merge. |
| 672 | * @param int $batchLimit number of merges to carry out in one batch. |
| 673 | * @param int $isSelected if records with is_selected column needs to be processed. |
| 674 | * Note the option of '2' is only used in conjunction with $redirectForPerformance |
| 675 | * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered |
| 676 | * out in favour of explicitly passing in $reloadCacheIfEmpty |
| 677 | * |
| 678 | * @param array $criteria |
| 679 | * Criteria to use in the filter. |
| 680 | * |
| 681 | * @param bool $checkPermissions |
| 682 | * Respect logged in user permissions. |
| 683 | * @param bool|NULL $reloadCacheIfEmpty |
| 684 | * If not set explicitly this is calculated but it is preferred that it be set |
| 685 | * per comments on isSelected above. |
| 686 | * |
| 687 | * @return array|bool |
| 688 | */ |
| 689 | public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL) { |
| 690 | $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE; |
| 691 | |
| 692 | if (!isset($reloadCacheIfEmpty)) { |
| 693 | $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2); |
| 694 | } |
| 695 | if ($isSelected !== 0 && $isSelected !== 1) { |
| 696 | // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value. |
| 697 | $isSelected = NULL; |
| 698 | } |
| 699 | $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, '', ($mode == 'aggressive'), $criteria, $checkPermissions); |
| 700 | |
| 701 | $cacheParams = [ |
| 702 | 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions), |
| 703 | // @todo stop passing these parameters in & instead calculate them in the merge function based |
| 704 | // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected. |
| 705 | 'join' => self::getJoinOnDedupeTable(), |
| 706 | 'where' => self::getWhereString($isSelected), |
| 707 | 'limit' => (int) $batchLimit, |
| 708 | ]; |
| 709 | return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions); |
| 710 | } |
| 711 | |
| 712 | /** |
| 713 | * Get the string to join the prevnext cache to the dedupe table. |
| 714 | * |
| 715 | * @return string |
| 716 | * The join string to join prevnext cache on the dedupe table. |
| 717 | */ |
| 718 | public static function getJoinOnDedupeTable() { |
| 719 | return " |
| 720 | LEFT JOIN civicrm_dedupe_exception de |
| 721 | ON ( |
| 722 | pn.entity_id1 = de.contact_id1 |
| 723 | AND pn.entity_id2 = de.contact_id2 ) |
| 724 | "; |
| 725 | } |
| 726 | |
| 727 | /** |
| 728 | * Get where string for dedupe join. |
| 729 | * |
| 730 | * @param bool $isSelected |
| 731 | * |
| 732 | * @return string |
| 733 | */ |
| 734 | protected static function getWhereString($isSelected) { |
| 735 | $where = "de.id IS NULL"; |
| 736 | if ($isSelected === 0 || $isSelected === 1) { |
| 737 | $where .= " AND pn.is_selected = {$isSelected}"; |
| 738 | } |
| 739 | return $where; |
| 740 | } |
| 741 | |
| 742 | /** |
| 743 | * Update the statistics for the merge set. |
| 744 | * |
| 745 | * @param string $cacheKeyString |
| 746 | * @param array $result |
| 747 | */ |
| 748 | public static function updateMergeStats($cacheKeyString, $result = []) { |
| 749 | // gather latest stats |
| 750 | $merged = count($result['merged']); |
| 751 | $skipped = count($result['skipped']); |
| 752 | |
| 753 | if ($merged <= 0 && $skipped <= 0) { |
| 754 | return; |
| 755 | } |
| 756 | |
| 757 | // get previous stats |
| 758 | $previousStats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats"); |
| 759 | if (!empty($previousStats)) { |
| 760 | if ($previousStats[0]['merged']) { |
| 761 | $merged = $merged + $previousStats[0]['merged']; |
| 762 | } |
| 763 | if ($previousStats[0]['skipped']) { |
| 764 | $skipped = $skipped + $previousStats[0]['skipped']; |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | // delete old stats |
| 769 | CRM_Dedupe_Merger::resetMergeStats($cacheKeyString); |
| 770 | |
| 771 | // store the updated stats |
| 772 | $data = [ |
| 773 | 'merged' => $merged, |
| 774 | 'skipped' => $skipped, |
| 775 | ]; |
| 776 | $data = CRM_Core_DAO::escapeString(serialize($data)); |
| 777 | |
| 778 | $values = []; |
| 779 | $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) "; |
| 780 | CRM_Core_BAO_PrevNextCache::setItem($values); |
| 781 | } |
| 782 | |
| 783 | /** |
| 784 | * Delete information about merges for the given string. |
| 785 | * |
| 786 | * @param $cacheKeyString |
| 787 | */ |
| 788 | public static function resetMergeStats($cacheKeyString) { |
| 789 | CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats"); |
| 790 | } |
| 791 | |
| 792 | /** |
| 793 | * Get merge outcome statistics. |
| 794 | * |
| 795 | * @param string $cacheKeyString |
| 796 | * |
| 797 | * @return array |
| 798 | * Array of how many were merged and how many were skipped. |
| 799 | */ |
| 800 | public static function getMergeStats($cacheKeyString) { |
| 801 | $stats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats"); |
| 802 | if (!empty($stats)) { |
| 803 | $stats = $stats[0]; |
| 804 | } |
| 805 | return $stats; |
| 806 | } |
| 807 | |
| 808 | /** |
| 809 | * Get merge statistics message. |
| 810 | * |
| 811 | * @param array $stats |
| 812 | * |
| 813 | * @return string |
| 814 | */ |
| 815 | public static function getMergeStatsMsg($stats) { |
| 816 | $msg = ''; |
| 817 | if (!empty($stats['merged'])) { |
| 818 | $msg = '<p>' . ts('One contact merged.', [ |
| 819 | 'count' => $stats['merged'], |
| 820 | 'plural' => '%count contacts merged.', |
| 821 | ]) . '</p>'; |
| 822 | } |
| 823 | if (!empty($stats['skipped'])) { |
| 824 | $msg .= '<p>' . ts('One contact was skipped.', [ |
| 825 | 'count' => $stats['skipped'], |
| 826 | 'plural' => '%count contacts were skipped.', |
| 827 | ]) . '</p>'; |
| 828 | } |
| 829 | return $msg; |
| 830 | } |
| 831 | |
| 832 | /** |
| 833 | * Merge given set of contacts. Performs core operation. |
| 834 | * |
| 835 | * @param array $dupePairs |
| 836 | * Set of pair of contacts for whom merge is to be done. |
| 837 | * @param array $cacheParams |
| 838 | * Prev-next-cache params based on which next pair of contacts are computed. |
| 839 | * Generally used with batch-merge. |
| 840 | * @param string $mode |
| 841 | * Helps decide how to behave when there are conflicts. |
| 842 | * A 'safe' value skips the merge if there are any un-resolved conflicts. |
| 843 | * Does a force merge otherwise (aggressive mode). |
| 844 | * |
| 845 | * @param bool $redirectForPerformance |
| 846 | * Redirect to a url for batch processing. |
| 847 | * |
| 848 | * @param bool $checkPermissions |
| 849 | * Respect logged in user permissions. |
| 850 | * |
| 851 | * @return array|bool |
| 852 | */ |
| 853 | public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe', |
| 854 | $redirectForPerformance = FALSE, $checkPermissions = TRUE |
| 855 | ) { |
| 856 | $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams); |
| 857 | $resultStats = ['merged' => [], 'skipped' => []]; |
| 858 | |
| 859 | // we don't want dupe caching to get reset after every-merge, and therefore set the |
| 860 | CRM_Core_Config::setPermitCacheFlushMode(FALSE); |
| 861 | $deletedContacts = []; |
| 862 | |
| 863 | while (!empty($dupePairs)) { |
| 864 | foreach ($dupePairs as $index => $dupes) { |
| 865 | if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) { |
| 866 | unset($dupePairs[$index]); |
| 867 | continue; |
| 868 | } |
| 869 | CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']); |
| 870 | $mainId = $dupes['dstID']; |
| 871 | $otherId = $dupes['srcID']; |
| 872 | |
| 873 | if (!$mainId || !$otherId) { |
| 874 | // return error |
| 875 | return FALSE; |
| 876 | } |
| 877 | // Generate var $migrationInfo. The variable structure is exactly same as |
| 878 | // $formValues submitted during a UI merge for a pair of contacts. |
| 879 | $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, $checkPermissions); |
| 880 | // add additional details that we might need to resolve conflicts |
| 881 | $rowsElementsAndInfo['migration_info']['main_details'] = &$rowsElementsAndInfo['main_details']; |
| 882 | $rowsElementsAndInfo['migration_info']['other_details'] = &$rowsElementsAndInfo['other_details']; |
| 883 | $rowsElementsAndInfo['migration_info']['rows'] = &$rowsElementsAndInfo['rows']; |
| 884 | |
| 885 | self::dedupePair($rowsElementsAndInfo['migration_info'], $resultStats, $deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString); |
| 886 | } |
| 887 | |
| 888 | if ($cacheKeyString && !$redirectForPerformance) { |
| 889 | // retrieve next pair of dupes |
| 890 | // @todo call getDuplicatePairs. |
| 891 | $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, |
| 892 | $cacheParams['join'], |
| 893 | $cacheParams['where'], |
| 894 | 0, |
| 895 | $cacheParams['limit'], |
| 896 | [], |
| 897 | '', |
| 898 | FALSE |
| 899 | ); |
| 900 | } |
| 901 | else { |
| 902 | // do not proceed. Terminate the loop |
| 903 | unset($dupePairs); |
| 904 | } |
| 905 | } |
| 906 | |
| 907 | CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats); |
| 908 | return $resultStats; |
| 909 | } |
| 910 | |
| 911 | /** |
| 912 | * A function which uses various rules / algorithms for choosing which contact to bias to |
| 913 | * when there's a conflict (to handle "gotchas"). Plus the safest route to merge. |
| 914 | * |
| 915 | * @param int $mainId |
| 916 | * Main contact with whom merge has to happen. |
| 917 | * @param int $otherId |
| 918 | * Duplicate contact which would be deleted after merge operation. |
| 919 | * @param array $migrationInfo |
| 920 | * Array of information about which elements to merge. |
| 921 | * @param string $mode |
| 922 | * Helps decide how to behave when there are conflicts. |
| 923 | * - A 'safe' value skips the merge if there are any un-resolved conflicts. |
| 924 | * - Does a force merge otherwise (aggressive mode). |
| 925 | * |
| 926 | * @param array $conflicts |
| 927 | * |
| 928 | * @return bool |
| 929 | */ |
| 930 | public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) { |
| 931 | |
| 932 | $originalMigrationInfo = $migrationInfo; |
| 933 | foreach ($migrationInfo as $key => $val) { |
| 934 | if ($val === "null") { |
| 935 | // Rule: Never overwrite with an empty value (in any mode) |
| 936 | unset($migrationInfo[$key]); |
| 937 | continue; |
| 938 | } |
| 939 | elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or |
| 940 | substr($key, 0, 12) == 'move_custom_' |
| 941 | ) and $val != NULL |
| 942 | ) { |
| 943 | // Rule: If both main-contact, and other-contact have a field with a |
| 944 | // different value, then let $mode decide if to merge it or not |
| 945 | if ( |
| 946 | (!empty($migrationInfo['rows'][$key]['main']) |
| 947 | // For custom fields a 0 (e.g in an int field) could be a true conflict. This |
| 948 | // is probably true for other fields too - e.g. 'do_not_email' but |
| 949 | // leaving that investigation as a @todo - until tests can be written. |
| 950 | // Note the handling of this has test coverage - although the data-typing |
| 951 | // of '0' feels flakey we have insurance. |
| 952 | || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_') |
| 953 | ) |
| 954 | && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other'] |
| 955 | ) { |
| 956 | |
| 957 | // note it down & lets wait for response from the hook. |
| 958 | // For no response $mode will decide if to skip this merge |
| 959 | $conflicts[$key] = NULL; |
| 960 | } |
| 961 | } |
| 962 | elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) { |
| 963 | $locField = explode('_', $key); |
| 964 | $fieldName = $locField[2]; |
| 965 | $fieldCount = $locField[3]; |
| 966 | |
| 967 | // Rule: Catch address conflicts (same address type on both contacts) |
| 968 | if ( |
| 969 | isset($migrationInfo['main_details']['location_blocks'][$fieldName]) && |
| 970 | !empty($migrationInfo['main_details']['location_blocks'][$fieldName]) |
| 971 | ) { |
| 972 | |
| 973 | // Load the address we're inspecting from the 'other' contact |
| 974 | $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount]; |
| 975 | $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord); |
| 976 | |
| 977 | // If it exists on the 'main' contact already, skip it. Otherwise |
| 978 | // if the location type exists already, log a conflict. |
| 979 | foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) { |
| 980 | if (self::locationIsSame($addressRecord, $mainAddressRecord)) { |
| 981 | unset($migrationInfo[$key]); |
| 982 | break; |
| 983 | } |
| 984 | elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) { |
| 985 | $conflicts[$key] = NULL; |
| 986 | break; |
| 987 | } |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | // For other locations, don't merge/add if the values are the same |
| 992 | elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) { |
| 993 | unset($migrationInfo[$key]); |
| 994 | } |
| 995 | } |
| 996 | } |
| 997 | |
| 998 | // A hook to implement other algorithms for choosing which contact to bias to when |
| 999 | // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here |
| 1000 | // merge happens with new values filled in here. For a particular field / row not to be merged |
| 1001 | // field should be unset from fields_in_conflict. |
| 1002 | $migrationData = [ |
| 1003 | 'old_migration_info' => $originalMigrationInfo, |
| 1004 | 'mode' => $mode, |
| 1005 | 'fields_in_conflict' => $conflicts, |
| 1006 | 'merge_mode' => $mode, |
| 1007 | 'migration_info' => $migrationInfo, |
| 1008 | ]; |
| 1009 | CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId); |
| 1010 | $conflicts = $migrationData['fields_in_conflict']; |
| 1011 | // allow hook to override / manipulate migrationInfo as well |
| 1012 | $migrationInfo = $migrationData['migration_info']; |
| 1013 | |
| 1014 | if (!empty($conflicts)) { |
| 1015 | foreach ($conflicts as $key => $val) { |
| 1016 | if ($val === NULL and $mode == 'safe') { |
| 1017 | // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason. |
| 1018 | return TRUE; |
| 1019 | } |
| 1020 | else { |
| 1021 | // copy over the resolved values |
| 1022 | $migrationInfo[$key] = $val; |
| 1023 | } |
| 1024 | } |
| 1025 | // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges |
| 1026 | if (array_key_exists('skip_merge', $migrationData)) { |
| 1027 | return (bool) $migrationData['skip_merge']; |
| 1028 | } |
| 1029 | } |
| 1030 | return FALSE; |
| 1031 | } |
| 1032 | |
| 1033 | /** |
| 1034 | * Compare 2 addresses to see if they are the same. |
| 1035 | * |
| 1036 | * @param array $mainAddress |
| 1037 | * @param array $comparisonAddress |
| 1038 | * |
| 1039 | * @return bool |
| 1040 | */ |
| 1041 | public static function locationIsSame($mainAddress, $comparisonAddress) { |
| 1042 | $keysToIgnore = [ |
| 1043 | 'id', |
| 1044 | 'is_primary', |
| 1045 | 'is_billing', |
| 1046 | 'manual_geo_code', |
| 1047 | 'contact_id', |
| 1048 | 'reset_date', |
| 1049 | 'hold_date', |
| 1050 | ]; |
| 1051 | foreach ($comparisonAddress as $field => $value) { |
| 1052 | if (in_array($field, $keysToIgnore)) { |
| 1053 | continue; |
| 1054 | } |
| 1055 | if ((!empty($value) || $value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) { |
| 1056 | return FALSE; |
| 1057 | } |
| 1058 | } |
| 1059 | return TRUE; |
| 1060 | } |
| 1061 | |
| 1062 | /** |
| 1063 | * A function to build an array of information about location blocks that is |
| 1064 | * required when merging location fields |
| 1065 | * |
| 1066 | * @return array |
| 1067 | */ |
| 1068 | public static function getLocationBlockInfo() { |
| 1069 | $locationBlocks = [ |
| 1070 | 'address' => [ |
| 1071 | 'label' => 'Address', |
| 1072 | 'displayField' => 'display', |
| 1073 | 'sortString' => 'location_type_id', |
| 1074 | 'hasLocation' => TRUE, |
| 1075 | 'hasType' => FALSE, |
| 1076 | ], |
| 1077 | 'email' => [ |
| 1078 | 'label' => 'Email', |
| 1079 | 'displayField' => 'display', |
| 1080 | 'sortString' => 'location_type_id', |
| 1081 | 'hasLocation' => TRUE, |
| 1082 | 'hasType' => FALSE, |
| 1083 | ], |
| 1084 | 'im' => [ |
| 1085 | 'label' => 'IM', |
| 1086 | 'displayField' => 'name', |
| 1087 | 'sortString' => 'location_type_id,provider_id', |
| 1088 | 'hasLocation' => TRUE, |
| 1089 | 'hasType' => 'provider_id', |
| 1090 | ], |
| 1091 | 'phone' => [ |
| 1092 | 'label' => 'Phone', |
| 1093 | 'displayField' => 'phone', |
| 1094 | 'sortString' => 'location_type_id,phone_type_id', |
| 1095 | 'hasLocation' => TRUE, |
| 1096 | 'hasType' => 'phone_type_id', |
| 1097 | ], |
| 1098 | 'website' => [ |
| 1099 | 'label' => 'Website', |
| 1100 | 'displayField' => 'url', |
| 1101 | 'sortString' => 'website_type_id', |
| 1102 | 'hasLocation' => FALSE, |
| 1103 | 'hasType' => 'website_type_id', |
| 1104 | ], |
| 1105 | ]; |
| 1106 | return $locationBlocks; |
| 1107 | } |
| 1108 | |
| 1109 | /** |
| 1110 | * A function to build an array of information required by merge function and the merge UI. |
| 1111 | * |
| 1112 | * @param int $mainId |
| 1113 | * Main contact with whom merge has to happen. |
| 1114 | * @param int $otherId |
| 1115 | * Duplicate contact which would be deleted after merge operation. |
| 1116 | * @param bool $checkPermissions |
| 1117 | * Should the logged in user's permissions be ignore. Setting this to false is |
| 1118 | * highly risky as it could cause data to be lost due to conflicts not showing up. |
| 1119 | * OTOH there is a risk a merger might view custom data they do not have permission to. |
| 1120 | * Hence for now only making this really explicit and making it reflect perms in |
| 1121 | * an api call. |
| 1122 | * |
| 1123 | * @todo review permissions issue! |
| 1124 | * |
| 1125 | * @return array|bool|int |
| 1126 | * |
| 1127 | * rows => An array of arrays, each is row of merge information for the table |
| 1128 | * Format: move_fieldname, eg: move_contact_type |
| 1129 | * main => Value associated with the main contact |
| 1130 | * other => Value associated with the other contact |
| 1131 | * title => The title of the field to display in the merge table |
| 1132 | * |
| 1133 | * elements => An array of form elements for the merge UI |
| 1134 | * |
| 1135 | * rel_table_elements => An array of form elements for the merge UI for |
| 1136 | * entities related to the contact (eg: checkbox to move 'mailings') |
| 1137 | * |
| 1138 | * rel_tables => Stores the tables that have related entities for the contact |
| 1139 | * for example mailings, groups |
| 1140 | * |
| 1141 | * main_details => An array of core contact field values, eg: first_name, etc. |
| 1142 | * location_blocks => An array of location block data for the main contact |
| 1143 | * stored as the 'result' of an API call. |
| 1144 | * eg: main_details['location_blocks']['address'][0]['id'] |
| 1145 | * eg: main_details['location_blocks']['email'][1]['id'] |
| 1146 | * |
| 1147 | * other_details => As above, but for the 'other' contact |
| 1148 | * |
| 1149 | * migration_info => Stores the 'default' merge actions for each field which |
| 1150 | * is used when programatically merging contacts. It contains instructions |
| 1151 | * to move all fields from the 'other' contact to the 'main' contact, as |
| 1152 | * though the form had been submitted with those options. |
| 1153 | * |
| 1154 | * @throws \CRM_Core_Exception |
| 1155 | * @throws \CiviCRM_API3_Exception |
| 1156 | * @throws \Exception |
| 1157 | */ |
| 1158 | public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) { |
| 1159 | $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; |
| 1160 | $fields = self::getMergeFieldsMetadata(); |
| 1161 | |
| 1162 | $main = self::getMergeContactDetails($mainId); |
| 1163 | $other = self::getMergeContactDetails($otherId); |
| 1164 | $specialValues['main'] = self::getSpecialValues($main); |
| 1165 | $specialValues['other'] = self::getSpecialValues($other); |
| 1166 | |
| 1167 | $compareFields = self::retrieveFields($main, $other); |
| 1168 | |
| 1169 | $rows = $elements = $relTableElements = $migrationInfo = []; |
| 1170 | |
| 1171 | foreach ($compareFields['contact'] as $field) { |
| 1172 | if ($field == 'contact_sub_type') { |
| 1173 | // CRM-15681 don't display sub-types in UI |
| 1174 | continue; |
| 1175 | } |
| 1176 | foreach (['main', 'other'] as $moniker) { |
| 1177 | $contact = &$$moniker; |
| 1178 | $value = CRM_Utils_Array::value($field, $contact); |
| 1179 | if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) { |
| 1180 | $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR; |
| 1181 | } |
| 1182 | $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value; |
| 1183 | if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) { |
| 1184 | if ($value) { |
| 1185 | $value = str_replace('-', '', $value); |
| 1186 | $label = CRM_Utils_Date::customFormat($label); |
| 1187 | } |
| 1188 | else { |
| 1189 | $value = "null"; |
| 1190 | } |
| 1191 | } |
| 1192 | elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) { |
| 1193 | if ($label === '0') { |
| 1194 | $label = ts('[ ]'); |
| 1195 | } |
| 1196 | if ($label === '1') { |
| 1197 | $label = ts('[x]'); |
| 1198 | } |
| 1199 | } |
| 1200 | elseif ($field == 'prefix_id') { |
| 1201 | $label = CRM_Utils_Array::value('individual_prefix', $contact); |
| 1202 | } |
| 1203 | elseif ($field == 'suffix_id') { |
| 1204 | $label = CRM_Utils_Array::value('individual_suffix', $contact); |
| 1205 | } |
| 1206 | elseif ($field == 'gender_id' && !empty($value)) { |
| 1207 | $genderOptions = civicrm_api3('contact', 'getoptions', ['field' => 'gender_id']); |
| 1208 | $label = $genderOptions['values'][$value]; |
| 1209 | } |
| 1210 | elseif ($field == 'current_employer_id' && !empty($value)) { |
| 1211 | $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")"; |
| 1212 | } |
| 1213 | $rows["move_$field"][$moniker] = $label; |
| 1214 | if ($moniker == 'other') { |
| 1215 | //CRM-14334 |
| 1216 | if ($value === NULL || $value == '') { |
| 1217 | $value = 'null'; |
| 1218 | } |
| 1219 | if ($value === 0 or $value === '0') { |
| 1220 | $value = $qfZeroBug; |
| 1221 | } |
| 1222 | if (is_array($value) && empty($value[1])) { |
| 1223 | $value[1] = NULL; |
| 1224 | } |
| 1225 | |
| 1226 | // Display a checkbox to migrate, only if the values are different |
| 1227 | if ($value != $main[$field]) { |
| 1228 | $elements[] = [ |
| 1229 | 'advcheckbox', |
| 1230 | "move_$field", |
| 1231 | NULL, |
| 1232 | NULL, |
| 1233 | NULL, |
| 1234 | $value, |
| 1235 | ]; |
| 1236 | } |
| 1237 | |
| 1238 | $migrationInfo["move_$field"] = $value; |
| 1239 | } |
| 1240 | } |
| 1241 | $rows["move_$field"]['title'] = $fields[$field]['title']; |
| 1242 | } |
| 1243 | |
| 1244 | // Handle location blocks. |
| 1245 | // @todo OpenID not in API yet, so is not supported here. |
| 1246 | |
| 1247 | // Set up useful information about the location blocks |
| 1248 | $locationBlocks = self::getLocationBlockInfo(); |
| 1249 | |
| 1250 | $locations = [ |
| 1251 | 'main' => [], |
| 1252 | 'other' => [], |
| 1253 | ]; |
| 1254 | |
| 1255 | // @todo This could probably be defined and used earlier |
| 1256 | $mergeTargets = [ |
| 1257 | 'main' => $mainId, |
| 1258 | 'other' => $otherId, |
| 1259 | ]; |
| 1260 | |
| 1261 | foreach ($locationBlocks as $blockName => $blockInfo) { |
| 1262 | |
| 1263 | // Collect existing fields from both 'main' and 'other' contacts first |
| 1264 | // This allows us to match up location/types when building the table rows |
| 1265 | foreach ($mergeTargets as $moniker => $cid) { |
| 1266 | $searchParams = [ |
| 1267 | 'contact_id' => $cid, |
| 1268 | // CRM-17556 Order by field-specific criteria |
| 1269 | 'options' => [ |
| 1270 | 'sort' => $blockInfo['sortString'], |
| 1271 | ], |
| 1272 | ]; |
| 1273 | $values = civicrm_api3($blockName, 'get', $searchParams); |
| 1274 | if ($values['count']) { |
| 1275 | $cnt = 0; |
| 1276 | foreach ($values['values'] as $value) { |
| 1277 | $locations[$moniker][$blockName][$cnt] = $value; |
| 1278 | // Fix address display |
| 1279 | if ($blockName == 'address') { |
| 1280 | CRM_Core_BAO_Address::fixAddress($value); |
| 1281 | $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address::format($value); |
| 1282 | } |
| 1283 | // Fix email display |
| 1284 | elseif ($blockName == 'email') { |
| 1285 | $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Mail::format($value); |
| 1286 | } |
| 1287 | |
| 1288 | $cnt++; |
| 1289 | } |
| 1290 | } |
| 1291 | } |
| 1292 | |
| 1293 | // Now, build the table rows appropriately, based off the information on |
| 1294 | // the 'other' contact |
| 1295 | if (!empty($locations['other']) && !empty($locations['other'][$blockName])) { |
| 1296 | foreach ($locations['other'][$blockName] as $count => $value) { |
| 1297 | |
| 1298 | $displayValue = $value[$blockInfo['displayField']]; |
| 1299 | |
| 1300 | // Add this value to the table rows |
| 1301 | $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue; |
| 1302 | |
| 1303 | // CRM-17556 Only display 'main' contact value if it's the same location + type |
| 1304 | // Look it up from main values... |
| 1305 | |
| 1306 | $lookupLocation = FALSE; |
| 1307 | if ($blockInfo['hasLocation']) { |
| 1308 | $lookupLocation = $value['location_type_id']; |
| 1309 | } |
| 1310 | |
| 1311 | $lookupType = FALSE; |
| 1312 | if ($blockInfo['hasType']) { |
| 1313 | $lookupType = CRM_Utils_Array::value($blockInfo['hasType'], $value); |
| 1314 | } |
| 1315 | |
| 1316 | // Hold ID of main contact's matching block |
| 1317 | $mainContactBlockId = 0; |
| 1318 | |
| 1319 | if (!empty($locations['main'][$blockName])) { |
| 1320 | foreach ($locations['main'][$blockName] as $mainValueCheck) { |
| 1321 | // No location/type, or matching location and type |
| 1322 | if ( |
| 1323 | (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id']) |
| 1324 | && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']]) |
| 1325 | ) { |
| 1326 | // Set this value as the default against the 'other' contact value |
| 1327 | $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']]; |
| 1328 | $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary']; |
| 1329 | $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName; |
| 1330 | $mainContactBlockId = $mainValueCheck['id']; |
| 1331 | break; |
| 1332 | } |
| 1333 | } |
| 1334 | } |
| 1335 | |
| 1336 | // Add checkbox to migrate data from 'other' to 'main' |
| 1337 | $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"]; |
| 1338 | |
| 1339 | // Add checkbox to set the 'other' location as primary |
| 1340 | $elements[] = [ |
| 1341 | 'advcheckbox', |
| 1342 | "location_blocks[$blockName][$count][set_other_primary]", |
| 1343 | NULL, |
| 1344 | ts('Set as primary'), |
| 1345 | ]; |
| 1346 | |
| 1347 | // Flag up this field to skipMerge function (@todo: do we need to?) |
| 1348 | $migrationInfo["move_location_{$blockName}_{$count}"] = 1; |
| 1349 | |
| 1350 | // Add a hidden field to store the ID of the target main contact block |
| 1351 | $elements[] = [ |
| 1352 | 'hidden', |
| 1353 | "location_blocks[$blockName][$count][mainContactBlockId]", |
| 1354 | $mainContactBlockId, |
| 1355 | ]; |
| 1356 | |
| 1357 | // Setup variables |
| 1358 | $thisTypeId = FALSE; |
| 1359 | $thisLocId = FALSE; |
| 1360 | |
| 1361 | // Provide a select drop-down for the location's location type |
| 1362 | // eg: Home, Work... |
| 1363 | |
| 1364 | if ($blockInfo['hasLocation']) { |
| 1365 | |
| 1366 | // Load the location options for this entity |
| 1367 | $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']); |
| 1368 | |
| 1369 | $thisLocId = $value['location_type_id']; |
| 1370 | |
| 1371 | // Put this field's location type at the top of the list |
| 1372 | $tmpIdList = $locationOptions['values']; |
| 1373 | $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]]; |
| 1374 | unset($tmpIdList[$thisLocId]); |
| 1375 | |
| 1376 | // Add the element |
| 1377 | $elements[] = [ |
| 1378 | 'select', |
| 1379 | "location_blocks[$blockName][$count][locTypeId]", |
| 1380 | NULL, |
| 1381 | $defaultLocId + $tmpIdList, |
| 1382 | ]; |
| 1383 | |
| 1384 | // Add the relevant information to the $migrationInfo |
| 1385 | // Keep location-type-id same as that of other-contact |
| 1386 | // @todo Check this logic out |
| 1387 | $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId; |
| 1388 | if ($blockName != 'address') { |
| 1389 | $elements[] = [ |
| 1390 | 'advcheckbox', |
| 1391 | "location_blocks[{$blockName}][$count][operation]", |
| 1392 | NULL, |
| 1393 | ts('Add new'), |
| 1394 | ]; |
| 1395 | // always use add operation |
| 1396 | $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1; |
| 1397 | } |
| 1398 | |
| 1399 | } |
| 1400 | |
| 1401 | // Provide a select drop-down for the location's type/provider |
| 1402 | // eg websites: Google+, Facebook... |
| 1403 | |
| 1404 | if ($blockInfo['hasType']) { |
| 1405 | |
| 1406 | // Load the type options for this entity |
| 1407 | $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]); |
| 1408 | |
| 1409 | $thisTypeId = CRM_Utils_Array::value($blockInfo['hasType'], $value); |
| 1410 | |
| 1411 | // Put this field's location type at the top of the list |
| 1412 | $tmpIdList = $typeOptions['values']; |
| 1413 | $defaultTypeId = [$thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList)]; |
| 1414 | unset($tmpIdList[$thisTypeId]); |
| 1415 | |
| 1416 | // Add the element |
| 1417 | $elements[] = [ |
| 1418 | 'select', |
| 1419 | "location_blocks[$blockName][$count][typeTypeId]", |
| 1420 | NULL, |
| 1421 | $defaultTypeId + $tmpIdList, |
| 1422 | ]; |
| 1423 | |
| 1424 | // Add the information to the migrationInfo |
| 1425 | $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId; |
| 1426 | |
| 1427 | } |
| 1428 | |
| 1429 | // Set the label for this row |
| 1430 | $rowTitle = $blockInfo['label'] . ' ' . ($count + 1); |
| 1431 | if (!empty($thisLocId)) { |
| 1432 | $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')'; |
| 1433 | } |
| 1434 | if (!empty($thisTypeId)) { |
| 1435 | $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')'; |
| 1436 | } |
| 1437 | $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle; |
| 1438 | |
| 1439 | } // End loop through 'other' locations of this type |
| 1440 | |
| 1441 | } // End if 'other' location for this type exists |
| 1442 | |
| 1443 | } // End loop through each location block entity |
| 1444 | |
| 1445 | // add the related tables and unset the ones that don't sport any of the duplicate contact's info |
| 1446 | $config = CRM_Core_Config::singleton(); |
| 1447 | $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId); |
| 1448 | $mainUser = NULL; |
| 1449 | if ($mainUfId) { |
| 1450 | // d6 compatible |
| 1451 | if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { |
| 1452 | $mainUser = user_load($mainUfId); |
| 1453 | } |
| 1454 | elseif ($config->userFramework == 'Joomla') { |
| 1455 | $mainUser = JFactory::getUser($mainUfId); |
| 1456 | } |
| 1457 | } |
| 1458 | $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId); |
| 1459 | $otherUser = NULL; |
| 1460 | if ($otherUfId) { |
| 1461 | // d6 compatible |
| 1462 | if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { |
| 1463 | $otherUser = user_load($otherUfId); |
| 1464 | } |
| 1465 | elseif ($config->userFramework == 'Joomla') { |
| 1466 | $otherUser = JFactory::getUser($otherUfId); |
| 1467 | } |
| 1468 | } |
| 1469 | |
| 1470 | $relTables = CRM_Dedupe_Merger::relTables(); |
| 1471 | $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId); |
| 1472 | $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId); |
| 1473 | foreach ($relTables as $name => $null) { |
| 1474 | if (!in_array($name, $activeRelTables) && |
| 1475 | !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables)) |
| 1476 | ) { |
| 1477 | unset($relTables[$name]); |
| 1478 | continue; |
| 1479 | } |
| 1480 | |
| 1481 | $relTableElements[] = ['checkbox', "move_$name"]; |
| 1482 | $migrationInfo["move_$name"] = 1; |
| 1483 | |
| 1484 | $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']); |
| 1485 | $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']); |
| 1486 | if ($name == 'rel_table_users') { |
| 1487 | $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']); |
| 1488 | $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']); |
| 1489 | $find = ['$ufid', '$ufname']; |
| 1490 | if ($mainUser) { |
| 1491 | $replace = [$mainUfId, $mainUser->name]; |
| 1492 | $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']); |
| 1493 | } |
| 1494 | if ($otherUser) { |
| 1495 | $replace = [$otherUfId, $otherUser->name]; |
| 1496 | $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']); |
| 1497 | } |
| 1498 | } |
| 1499 | if ($name == 'rel_table_memberships') { |
| 1500 | //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact. |
| 1501 | $attributes = ['checked' => 'checked']; |
| 1502 | $otherContactMemberships = CRM_Member_BAO_Membership::getAllContactMembership($otherId); |
| 1503 | foreach ($otherContactMemberships as $membership) { |
| 1504 | $mainMembership = CRM_Member_BAO_Membership::getContactMembership($mainId, $membership['membership_type_id'], FALSE); |
| 1505 | if ($mainMembership) { |
| 1506 | $attributes = []; |
| 1507 | } |
| 1508 | } |
| 1509 | $elements[] = [ |
| 1510 | 'checkbox', |
| 1511 | "operation[move_{$name}][add]", |
| 1512 | NULL, |
| 1513 | ts('add new'), |
| 1514 | $attributes, |
| 1515 | ]; |
| 1516 | $migrationInfo["operation"]["move_{$name}"]['add'] = 1; |
| 1517 | } |
| 1518 | } |
| 1519 | foreach ($relTables as $name => $null) { |
| 1520 | $relTables["move_$name"] = $relTables[$name]; |
| 1521 | unset($relTables[$name]); |
| 1522 | } |
| 1523 | |
| 1524 | // handle custom fields |
| 1525 | $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1, |
| 1526 | CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions |
| 1527 | ); |
| 1528 | $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $otherId, -1, |
| 1529 | CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions |
| 1530 | ); |
| 1531 | |
| 1532 | foreach ($otherTree as $gid => $group) { |
| 1533 | $foundField = FALSE; |
| 1534 | if (!isset($group['fields'])) { |
| 1535 | continue; |
| 1536 | } |
| 1537 | |
| 1538 | foreach ($group['fields'] as $fid => $field) { |
| 1539 | if (in_array($fid, $compareFields['custom'])) { |
| 1540 | if (!$foundField) { |
| 1541 | $rows["custom_group_$gid"]['title'] = $group['title']; |
| 1542 | $foundField = TRUE; |
| 1543 | } |
| 1544 | if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) { |
| 1545 | foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { |
| 1546 | $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid); |
| 1547 | } |
| 1548 | } |
| 1549 | $value = "null"; |
| 1550 | if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) { |
| 1551 | foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { |
| 1552 | $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid); |
| 1553 | if ($values['data'] === 0 || $values['data'] === '0') { |
| 1554 | $values['data'] = $qfZeroBug; |
| 1555 | } |
| 1556 | $value = ($values['data']) ? $values['data'] : $value; |
| 1557 | } |
| 1558 | } |
| 1559 | $rows["move_custom_$fid"]['title'] = $field['label']; |
| 1560 | |
| 1561 | $elements[] = [ |
| 1562 | 'advcheckbox', |
| 1563 | "move_custom_$fid", |
| 1564 | NULL, |
| 1565 | NULL, |
| 1566 | NULL, |
| 1567 | $value, |
| 1568 | ]; |
| 1569 | $migrationInfo["move_custom_$fid"] = $value; |
| 1570 | } |
| 1571 | } |
| 1572 | } |
| 1573 | |
| 1574 | $result = [ |
| 1575 | 'rows' => $rows, |
| 1576 | 'elements' => $elements, |
| 1577 | 'rel_table_elements' => $relTableElements, |
| 1578 | 'rel_tables' => $relTables, |
| 1579 | 'main_details' => $main, |
| 1580 | 'other_details' => $other, |
| 1581 | 'migration_info' => $migrationInfo, |
| 1582 | ]; |
| 1583 | |
| 1584 | $result['main_details']['location_blocks'] = $locations['main']; |
| 1585 | $result['other_details']['location_blocks'] = $locations['other']; |
| 1586 | |
| 1587 | return $result; |
| 1588 | } |
| 1589 | |
| 1590 | /** |
| 1591 | * Based on the provided two contact_ids and a set of tables, move the belongings of the |
| 1592 | * other contact to the main one - be it Location / CustomFields or Contact .. related info. |
| 1593 | * A superset of moveContactBelongings() function. |
| 1594 | * |
| 1595 | * @param int $mainId |
| 1596 | * Main contact with whom merge has to happen. |
| 1597 | * @param int $otherId |
| 1598 | * Duplicate contact which would be deleted after merge operation. |
| 1599 | * |
| 1600 | * @param $migrationInfo |
| 1601 | * |
| 1602 | * @param bool $checkPermissions |
| 1603 | * Respect logged in user permissions. |
| 1604 | * |
| 1605 | * @return bool |
| 1606 | */ |
| 1607 | public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) { |
| 1608 | if (empty($migrationInfo)) { |
| 1609 | return FALSE; |
| 1610 | } |
| 1611 | |
| 1612 | $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; |
| 1613 | $relTables = CRM_Dedupe_Merger::relTables(); |
| 1614 | $submittedCustomFields = $moveTables = $locationMigrationInfo = $tableOperations = $removeTables = []; |
| 1615 | |
| 1616 | foreach ($migrationInfo as $key => $value) { |
| 1617 | if ($value == $qfZeroBug) { |
| 1618 | $value = '0'; |
| 1619 | } |
| 1620 | |
| 1621 | if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) { |
| 1622 | $submitted[substr($key, 5)] = $value; |
| 1623 | $submittedCustomFields[] = substr($key, 12); |
| 1624 | } |
| 1625 | elseif (in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) && $value != NULL) { |
| 1626 | $submitted[substr($key, 5)] = $value; |
| 1627 | } |
| 1628 | // Set up initial information for handling migration of location blocks |
| 1629 | elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) { |
| 1630 | $locationMigrationInfo[$key] = $value; |
| 1631 | } |
| 1632 | elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') { |
| 1633 | $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']); |
| 1634 | if (array_key_exists('operation', $migrationInfo)) { |
| 1635 | foreach ($relTables[substr($key, 5)]['tables'] as $table) { |
| 1636 | if (array_key_exists($key, $migrationInfo['operation'])) { |
| 1637 | $tableOperations[$table] = $migrationInfo['operation'][$key]; |
| 1638 | } |
| 1639 | } |
| 1640 | } |
| 1641 | } |
| 1642 | elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') { |
| 1643 | $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']); |
| 1644 | } |
| 1645 | } |
| 1646 | self::mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo); |
| 1647 | |
| 1648 | // **** Do contact related migrations |
| 1649 | $customTablesToCopyValues = self::getAffectedCustomTables($submittedCustomFields); |
| 1650 | CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues); |
| 1651 | unset($moveTables, $tableOperations); |
| 1652 | |
| 1653 | // **** Do table related removals |
| 1654 | if (!empty($removeTables)) { |
| 1655 | // **** CRM-20421 |
| 1656 | CRM_Dedupe_Merger::removeContactBelongings($otherId, $removeTables); |
| 1657 | $removeTables = []; |
| 1658 | } |
| 1659 | |
| 1660 | // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact() |
| 1661 | $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender']; |
| 1662 | $names['individual_prefix'] = [ |
| 1663 | 'newName' => 'prefix_id', |
| 1664 | 'groupName' => 'individual_prefix', |
| 1665 | ]; |
| 1666 | $names['individual_suffix'] = [ |
| 1667 | 'newName' => 'suffix_id', |
| 1668 | 'groupName' => 'individual_suffix', |
| 1669 | ]; |
| 1670 | $names['communication_style'] = [ |
| 1671 | 'newName' => 'communication_style_id', |
| 1672 | 'groupName' => 'communication_style', |
| 1673 | ]; |
| 1674 | $names['addressee'] = [ |
| 1675 | 'newName' => 'addressee_id', |
| 1676 | 'groupName' => 'addressee', |
| 1677 | ]; |
| 1678 | $names['email_greeting'] = [ |
| 1679 | 'newName' => 'email_greeting_id', |
| 1680 | 'groupName' => 'email_greeting', |
| 1681 | ]; |
| 1682 | $names['postal_greeting'] = [ |
| 1683 | 'newName' => 'postal_greeting_id', |
| 1684 | 'groupName' => 'postal_greeting', |
| 1685 | ]; |
| 1686 | CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE); |
| 1687 | |
| 1688 | // fix custom fields so they're edible by createProfileContact() |
| 1689 | $treeCache = []; |
| 1690 | if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) { |
| 1691 | $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree( |
| 1692 | $migrationInfo['main_details']['contact_type'], |
| 1693 | NULL, |
| 1694 | NULL, |
| 1695 | -1, |
| 1696 | [], |
| 1697 | NULL, |
| 1698 | TRUE, |
| 1699 | NULL, |
| 1700 | FALSE, |
| 1701 | FALSE |
| 1702 | ); |
| 1703 | } |
| 1704 | |
| 1705 | $cFields = []; |
| 1706 | foreach ($treeCache[$migrationInfo['main_details']['contact_type']] as $key => $group) { |
| 1707 | if (!isset($group['fields'])) { |
| 1708 | continue; |
| 1709 | } |
| 1710 | foreach ($group['fields'] as $fid => $field) { |
| 1711 | $cFields[$fid]['attributes'] = $field; |
| 1712 | } |
| 1713 | } |
| 1714 | |
| 1715 | if (!isset($submitted)) { |
| 1716 | $submitted = []; |
| 1717 | } |
| 1718 | foreach ($submitted as $key => $value) { |
| 1719 | if (substr($key, 0, 7) == 'custom_') { |
| 1720 | $fid = (int) substr($key, 7); |
| 1721 | if (empty($cFields[$fid])) { |
| 1722 | continue; |
| 1723 | } |
| 1724 | $htmlType = $cFields[$fid]['attributes']['html_type']; |
| 1725 | switch ($htmlType) { |
| 1726 | case 'File': |
| 1727 | $customFiles[] = $fid; |
| 1728 | unset($submitted["custom_$fid"]); |
| 1729 | break; |
| 1730 | |
| 1731 | case 'Select Country': |
| 1732 | case 'Select State/Province': |
| 1733 | $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid); |
| 1734 | break; |
| 1735 | |
| 1736 | case 'Select Date': |
| 1737 | if ($cFields[$fid]['attributes']['is_view']) { |
| 1738 | $submitted[$key] = date('YmdHis', strtotime($submitted[$key])); |
| 1739 | } |
| 1740 | break; |
| 1741 | |
| 1742 | case 'CheckBox': |
| 1743 | case 'Multi-Select': |
| 1744 | case 'Multi-Select Country': |
| 1745 | case 'Multi-Select State/Province': |
| 1746 | // Merge values from both contacts for multivalue fields, CRM-4385 |
| 1747 | // get the existing custom values from db. |
| 1748 | $customParams = ['entityID' => $mainId, $key => TRUE]; |
| 1749 | $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams); |
| 1750 | if (!empty($customfieldValues[$key])) { |
| 1751 | $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]); |
| 1752 | if (is_array($existingValue) && !empty($existingValue)) { |
| 1753 | $mergeValue = $submittedCustomFields = []; |
| 1754 | if ($value == 'null') { |
| 1755 | // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it. |
| 1756 | $submitted[$key] = $value; |
| 1757 | } |
| 1758 | else { |
| 1759 | if ($value) { |
| 1760 | $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); |
| 1761 | } |
| 1762 | |
| 1763 | // CRM-19653: overwrite or add the existing custom field value with dupicate contact's |
| 1764 | // custom field value stored at $submittedCustomValue. |
| 1765 | foreach ($submittedCustomFields as $k => $v) { |
| 1766 | if ($v != '' && !in_array($v, $mergeValue)) { |
| 1767 | $mergeValue[] = $v; |
| 1768 | } |
| 1769 | } |
| 1770 | |
| 1771 | //keep state and country as array format. |
| 1772 | //for checkbox and m-select format w/ VALUE_SEPARATOR |
| 1773 | if (in_array($htmlType, [ |
| 1774 | 'CheckBox', |
| 1775 | 'Multi-Select', |
| 1776 | ])) { |
| 1777 | $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, |
| 1778 | $mergeValue |
| 1779 | ) . CRM_Core_DAO::VALUE_SEPARATOR; |
| 1780 | } |
| 1781 | else { |
| 1782 | $submitted[$key] = $mergeValue; |
| 1783 | } |
| 1784 | } |
| 1785 | } |
| 1786 | } |
| 1787 | elseif (in_array($htmlType, [ |
| 1788 | 'Multi-Select Country', |
| 1789 | 'Multi-Select State/Province', |
| 1790 | ])) { |
| 1791 | //we require submitted values should be in array format |
| 1792 | if ($value) { |
| 1793 | $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); |
| 1794 | //hack to remove null values from array. |
| 1795 | $mergeValue = []; |
| 1796 | foreach ($mergeValueArray as $k => $v) { |
| 1797 | if ($v != '') { |
| 1798 | $mergeValue[] = $v; |
| 1799 | } |
| 1800 | } |
| 1801 | $submitted[$key] = $mergeValue; |
| 1802 | } |
| 1803 | } |
| 1804 | break; |
| 1805 | |
| 1806 | default: |
| 1807 | break; |
| 1808 | } |
| 1809 | } |
| 1810 | } |
| 1811 | |
| 1812 | // **** Do file custom fields related migrations |
| 1813 | // FIXME: move this someplace else (one of the BAOs) after discussing |
| 1814 | // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually, |
| 1815 | // like, delete a file... |
| 1816 | |
| 1817 | if (!isset($customFiles)) { |
| 1818 | $customFiles = []; |
| 1819 | } |
| 1820 | foreach ($customFiles as $customId) { |
| 1821 | list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId); |
| 1822 | |
| 1823 | // get the contact_id -> file_id mapping |
| 1824 | $fileIds = []; |
| 1825 | $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})"; |
| 1826 | $dao = CRM_Core_DAO::executeQuery($sql); |
| 1827 | while ($dao->fetch()) { |
| 1828 | $fileIds[$dao->entity_id] = $dao->file_id; |
| 1829 | if ($dao->entity_id == $mainId) { |
| 1830 | CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId); |
| 1831 | } |
| 1832 | } |
| 1833 | $dao->free(); |
| 1834 | |
| 1835 | // move the other contact's file to main contact |
| 1836 | //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record |
| 1837 | if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) { |
| 1838 | $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}"; |
| 1839 | } |
| 1840 | else { |
| 1841 | $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )"; |
| 1842 | } |
| 1843 | CRM_Core_DAO::executeQuery($sql); |
| 1844 | |
| 1845 | if (CRM_Core_DAO::singleValueQuery(" |
| 1846 | SELECT id |
| 1847 | FROM civicrm_entity_file |
| 1848 | WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}") |
| 1849 | ) { |
| 1850 | $sql = " |
| 1851 | UPDATE civicrm_entity_file |
| 1852 | SET entity_id = {$mainId} |
| 1853 | WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}"; |
| 1854 | } |
| 1855 | else { |
| 1856 | $sql = " |
| 1857 | INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id ) |
| 1858 | VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )"; |
| 1859 | } |
| 1860 | CRM_Core_DAO::executeQuery($sql); |
| 1861 | } |
| 1862 | |
| 1863 | // move view only custom fields CRM-5362 |
| 1864 | $viewOnlyCustomFields = []; |
| 1865 | foreach ($submitted as $key => $value) { |
| 1866 | $fid = CRM_Core_BAO_CustomField::getKeyID($key); |
| 1867 | if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view']) |
| 1868 | ) { |
| 1869 | $viewOnlyCustomFields[$key] = $value; |
| 1870 | } |
| 1871 | } |
| 1872 | // special case to set values for view only, CRM-5362 |
| 1873 | if (!empty($viewOnlyCustomFields)) { |
| 1874 | $viewOnlyCustomFields['entityID'] = $mainId; |
| 1875 | CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields); |
| 1876 | } |
| 1877 | |
| 1878 | if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') && |
| 1879 | CRM_Core_Permission::check('delete contacts')) |
| 1880 | ) { |
| 1881 | // if ext id is submitted then set it null for contact to be deleted |
| 1882 | if (!empty($submitted['external_identifier'])) { |
| 1883 | $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}"; |
| 1884 | CRM_Core_DAO::executeQuery($query); |
| 1885 | } |
| 1886 | civicrm_api3('contact', 'delete', ['id' => $otherId]); |
| 1887 | } |
| 1888 | |
| 1889 | // CRM-15681 merge sub_types |
| 1890 | if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) { |
| 1891 | if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) { |
| 1892 | $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types)); |
| 1893 | } |
| 1894 | else { |
| 1895 | $submitted['contact_sub_type'] = $other_sub_types; |
| 1896 | } |
| 1897 | } |
| 1898 | |
| 1899 | // **** Update contact related info for the main contact |
| 1900 | if (!empty($submitted)) { |
| 1901 | $submitted['contact_id'] = $mainId; |
| 1902 | |
| 1903 | //update current employer field |
| 1904 | if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) { |
| 1905 | if (!CRM_Utils_System::isNull($currentEmloyerId)) { |
| 1906 | $submitted['current_employer'] = $submitted['current_employer_id']; |
| 1907 | } |
| 1908 | else { |
| 1909 | $submitted['current_employer'] = ''; |
| 1910 | } |
| 1911 | unset($submitted['current_employer_id']); |
| 1912 | } |
| 1913 | |
| 1914 | //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name |
| 1915 | if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) { |
| 1916 | $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id']; |
| 1917 | } |
| 1918 | if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) { |
| 1919 | $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id']; |
| 1920 | } |
| 1921 | |
| 1922 | CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId); |
| 1923 | } |
| 1924 | |
| 1925 | CRM_Utils_Hook::post('merge', 'Contact', $mainId); |
| 1926 | self::createMergeActivities($mainId, $otherId); |
| 1927 | |
| 1928 | return TRUE; |
| 1929 | } |
| 1930 | |
| 1931 | /** |
| 1932 | * Builds an Array of Custom tables for given custom field ID's. |
| 1933 | * |
| 1934 | * @param $customFieldIDs |
| 1935 | * |
| 1936 | * @return array |
| 1937 | * Array of custom table names |
| 1938 | */ |
| 1939 | private static function getAffectedCustomTables($customFieldIDs) { |
| 1940 | $customTableToCopyValues = []; |
| 1941 | |
| 1942 | foreach ($customFieldIDs as $fieldID) { |
| 1943 | if (!empty($fieldID)) { |
| 1944 | $customField = civicrm_api3('custom_field', 'getsingle', [ |
| 1945 | 'id' => $fieldID, |
| 1946 | 'is_active' => TRUE, |
| 1947 | ]); |
| 1948 | if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) { |
| 1949 | $customGroup = civicrm_api3('custom_group', 'getsingle', [ |
| 1950 | 'id' => $customField['custom_group_id'], |
| 1951 | 'is_active' => TRUE, |
| 1952 | ]); |
| 1953 | |
| 1954 | if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) { |
| 1955 | $customTableToCopyValues[] = $customGroup['table_name']; |
| 1956 | } |
| 1957 | } |
| 1958 | } |
| 1959 | } |
| 1960 | |
| 1961 | return $customTableToCopyValues; |
| 1962 | } |
| 1963 | |
| 1964 | /** |
| 1965 | * Get fields in the contact table suitable for merging. |
| 1966 | * |
| 1967 | * @return array |
| 1968 | * Array of field names to be potentially merged. |
| 1969 | */ |
| 1970 | public static function getContactFields() { |
| 1971 | $contactFields = CRM_Contact_DAO_Contact::fields(); |
| 1972 | $invalidFields = [ |
| 1973 | 'api_key', |
| 1974 | 'created_date', |
| 1975 | 'display_name', |
| 1976 | 'hash', |
| 1977 | 'id', |
| 1978 | 'modified_date', |
| 1979 | 'primary_contact_id', |
| 1980 | 'sort_name', |
| 1981 | 'user_unique_id', |
| 1982 | ]; |
| 1983 | foreach ($contactFields as $field => $value) { |
| 1984 | if (in_array($field, $invalidFields)) { |
| 1985 | unset($contactFields[$field]); |
| 1986 | } |
| 1987 | } |
| 1988 | return array_keys($contactFields); |
| 1989 | } |
| 1990 | |
| 1991 | /** |
| 1992 | * Added for CRM-12695 |
| 1993 | * Based on the contactID provided |
| 1994 | * add/update membership(s) to related contacts |
| 1995 | * |
| 1996 | * @param int $contactID |
| 1997 | */ |
| 1998 | public static function addMembershipToRealtedContacts($contactID) { |
| 1999 | $dao = new CRM_Member_DAO_Membership(); |
| 2000 | $dao->contact_id = $contactID; |
| 2001 | $dao->is_test = 0; |
| 2002 | $dao->find(); |
| 2003 | |
| 2004 | //checks membership of contact itself |
| 2005 | while ($dao->fetch()) { |
| 2006 | $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id'); |
| 2007 | if ($relationshipTypeId) { |
| 2008 | $membershipParams = [ |
| 2009 | 'id' => $dao->id, |
| 2010 | 'contact_id' => $dao->contact_id, |
| 2011 | 'membership_type_id' => $dao->membership_type_id, |
| 2012 | 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date), |
| 2013 | 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date), |
| 2014 | 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date), |
| 2015 | 'source' => $dao->source, |
| 2016 | 'status_id' => $dao->status_id, |
| 2017 | ]; |
| 2018 | // create/update membership(s) for related contact(s) |
| 2019 | CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao); |
| 2020 | } // end of if relationshipTypeId |
| 2021 | } |
| 2022 | } |
| 2023 | |
| 2024 | /** |
| 2025 | * Create activities tracking the merge on affected contacts. |
| 2026 | * |
| 2027 | * @param int $mainId |
| 2028 | * @param int $otherId |
| 2029 | * |
| 2030 | * @throws \CiviCRM_API3_Exception |
| 2031 | */ |
| 2032 | public static function createMergeActivities($mainId, $otherId) { |
| 2033 | $params = [ |
| 2034 | 1 => $otherId, |
| 2035 | 2 => $mainId, |
| 2036 | ]; |
| 2037 | $activity = civicrm_api3('activity', 'create', [ |
| 2038 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : |
| 2039 | $mainId, |
| 2040 | 'subject' => ts('Contact ID %1 has been merged and deleted.', $params), |
| 2041 | 'target_contact_id' => $mainId, |
| 2042 | 'activity_type_id' => 'Contact Merged', |
| 2043 | 'status_id' => 'Completed', |
| 2044 | ]); |
| 2045 | if (civicrm_api3('Setting', 'getvalue', [ |
| 2046 | 'name' => 'contact_undelete', |
| 2047 | 'group' => 'CiviCRM Preferences', |
| 2048 | ])) { |
| 2049 | civicrm_api3('activity', 'create', [ |
| 2050 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : |
| 2051 | $otherId, |
| 2052 | 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params), |
| 2053 | 'target_contact_id' => $otherId, |
| 2054 | 'activity_type_id' => 'Contact Deleted by Merge', |
| 2055 | 'parent_id' => $activity['id'], |
| 2056 | 'status_id' => 'Completed', |
| 2057 | ]); |
| 2058 | } |
| 2059 | } |
| 2060 | |
| 2061 | /** |
| 2062 | * Get Duplicate Pairs based on a rule for a group. |
| 2063 | * |
| 2064 | * @param int $rule_group_id |
| 2065 | * @param int $group_id |
| 2066 | * @param bool $reloadCacheIfEmpty |
| 2067 | * Should the cache be reloaded if empty - this must be false when in a dedupe action! |
| 2068 | * @param int $batchLimit |
| 2069 | * @param bool $isSelected |
| 2070 | * Limit to selected pairs. |
| 2071 | * @param array|string $orderByClause |
| 2072 | * @param bool $includeConflicts |
| 2073 | * @param array $criteria |
| 2074 | * Additional criteria to narrow down the merge group. |
| 2075 | * |
| 2076 | * @param bool $checkPermissions |
| 2077 | * Respect logged in user permissions. |
| 2078 | * |
| 2079 | * @param int $searchLimit |
| 2080 | * Limit to searching for matches against this many contacts. |
| 2081 | * |
| 2082 | * @return array |
| 2083 | * Array of matches meeting the criteria. |
| 2084 | */ |
| 2085 | public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $orderByClause = '', $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0) { |
| 2086 | $where = self::getWhereString($isSelected); |
| 2087 | $cacheKeyString = self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions); |
| 2088 | $join = self::getJoinOnDedupeTable(); |
| 2089 | $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, $batchLimit, [], $orderByClause, $includeConflicts); |
| 2090 | if (empty($dupePairs) && $reloadCacheIfEmpty) { |
| 2091 | // If we haven't found any dupes, probably cache is empty. |
| 2092 | // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any |
| 2093 | // until we have done some processing. |
| 2094 | CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions, $searchLimit); |
| 2095 | $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, 0, $batchLimit, [], $orderByClause, $includeConflicts); |
| 2096 | return $dupePairs; |
| 2097 | } |
| 2098 | return $dupePairs; |
| 2099 | } |
| 2100 | |
| 2101 | /** |
| 2102 | * Get the cache key string for the merge action. |
| 2103 | * |
| 2104 | * @param int $rule_group_id |
| 2105 | * @param int $group_id |
| 2106 | * @param array $criteria |
| 2107 | * Additional criteria to narrow down the merge group. |
| 2108 | * Currently we are only supporting the key 'contact' within it. |
| 2109 | * |
| 2110 | * @param bool $checkPermissions |
| 2111 | * Respect the users permissions. |
| 2112 | * |
| 2113 | * @return string |
| 2114 | */ |
| 2115 | public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = [], $checkPermissions = TRUE) { |
| 2116 | $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id); |
| 2117 | $cacheKeyString = "merge_{$contactType}"; |
| 2118 | $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0'; |
| 2119 | $cacheKeyString .= $group_id ? "_{$group_id}" : '_0'; |
| 2120 | $cacheKeyString .= !empty($criteria) ? md5(serialize($criteria)) : '_0'; |
| 2121 | if ($checkPermissions) { |
| 2122 | $contactID = CRM_Core_Session::getLoggedInContactID(); |
| 2123 | if (!$contactID) { |
| 2124 | // Distinguish between no permission check & no logged in user. |
| 2125 | $contactID = 'null'; |
| 2126 | } |
| 2127 | $cacheKeyString .= '_' . $contactID; |
| 2128 | } |
| 2129 | else { |
| 2130 | $cacheKeyString .= '_0'; |
| 2131 | } |
| 2132 | return $cacheKeyString; |
| 2133 | } |
| 2134 | |
| 2135 | /** |
| 2136 | * @param array $contact |
| 2137 | * @return array |
| 2138 | * $specialValues |
| 2139 | */ |
| 2140 | public static function getSpecialValues($contact) { |
| 2141 | $preferred_communication_method = CRM_Utils_Array::value('preferred_communication_method', $contact); |
| 2142 | $value = empty($preferred_communication_method) ? [] : $preferred_communication_method; |
| 2143 | $specialValues = [ |
| 2144 | 'preferred_communication_method' => $value, |
| 2145 | 'communication_style_id' => $value, |
| 2146 | ]; |
| 2147 | |
| 2148 | if (!empty($contact['preferred_communication_method'])) { |
| 2149 | // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct |
| 2150 | $prefCommList = is_array($specialValues['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues['preferred_communication_method']) : $specialValues['preferred_communication_method']; |
| 2151 | $specialValues['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR; |
| 2152 | } |
| 2153 | $names = [ |
| 2154 | 'preferred_communication_method' => [ |
| 2155 | 'newName' => 'preferred_communication_method_display', |
| 2156 | 'groupName' => 'preferred_communication_method', |
| 2157 | ], |
| 2158 | ]; |
| 2159 | CRM_Core_OptionGroup::lookupValues($specialValues, $names); |
| 2160 | |
| 2161 | if (!empty($contact['communication_style'])) { |
| 2162 | $specialValues['communication_style_id_display'] = $contact['communication_style']; |
| 2163 | } |
| 2164 | return $specialValues; |
| 2165 | } |
| 2166 | |
| 2167 | /** |
| 2168 | * Get the metadata for the merge fields. |
| 2169 | * |
| 2170 | * This is basically the contact metadata, augmented with fields to |
| 2171 | * represent email greeting, postal greeting & addressee. |
| 2172 | * |
| 2173 | * @return array |
| 2174 | */ |
| 2175 | public static function getMergeFieldsMetadata() { |
| 2176 | if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) { |
| 2177 | return \Civi::$statics[__CLASS__]['merge_fields_metadata']; |
| 2178 | } |
| 2179 | $fields = CRM_Contact_DAO_Contact::fields(); |
| 2180 | static $optionValueFields = []; |
| 2181 | if (empty($optionValueFields)) { |
| 2182 | $optionValueFields = CRM_Core_OptionValue::getFields(); |
| 2183 | } |
| 2184 | foreach ($optionValueFields as $field => $params) { |
| 2185 | $fields[$field]['title'] = $params['title']; |
| 2186 | } |
| 2187 | \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields; |
| 2188 | return \Civi::$statics[__CLASS__]['merge_fields_metadata']; |
| 2189 | } |
| 2190 | |
| 2191 | /** |
| 2192 | * Get the details of the contact to be merged. |
| 2193 | * |
| 2194 | * @param int $contact_id |
| 2195 | * |
| 2196 | * @return array |
| 2197 | * |
| 2198 | * @throws CRM_Core_Exception |
| 2199 | */ |
| 2200 | public static function getMergeContactDetails($contact_id) { |
| 2201 | $params = [ |
| 2202 | 'contact_id' => $contact_id, |
| 2203 | 'version' => 3, |
| 2204 | 'return' => array_merge(['display_name'], self::getContactFields()), |
| 2205 | ]; |
| 2206 | $result = civicrm_api('contact', 'get', $params); |
| 2207 | |
| 2208 | // CRM-18480: Cancel the process if the contact is already deleted |
| 2209 | if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) { |
| 2210 | throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [ |
| 2211 | 1 => $contact_id, |
| 2212 | ])); |
| 2213 | } |
| 2214 | |
| 2215 | return $result['values'][$contact_id]; |
| 2216 | } |
| 2217 | |
| 2218 | /** |
| 2219 | * Merge location. |
| 2220 | * |
| 2221 | * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts. |
| 2222 | * |
| 2223 | * The data is in the format received from the merge form (which is a fairly confusing format). |
| 2224 | * |
| 2225 | * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook |
| 2226 | * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have |
| 2227 | * been calculated and before saving because |
| 2228 | * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile |
| 2229 | * - passing to a hook right before save means calculations only have to be done once |
| 2230 | * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just |
| 2231 | * ugly. |
| 2232 | * |
| 2233 | * The use of the new hook is tested, including the fact it is called before contributions are merged, as this |
| 2234 | * is likely to be significant data in merge hooks. |
| 2235 | * |
| 2236 | * @param int $mainId |
| 2237 | * @param int $otherId |
| 2238 | * @param array $locationMigrationInfo |
| 2239 | * Portion of the migration_info that holds location migration information. |
| 2240 | * |
| 2241 | * @param array $migrationInfo |
| 2242 | * Migration info for the merge. This is passed to the hook as informational only. |
| 2243 | */ |
| 2244 | public static function mergeLocations($mainId, $otherId, $locationMigrationInfo, $migrationInfo) { |
| 2245 | foreach ($locationMigrationInfo as $key => $value) { |
| 2246 | $locField = explode('_', $key); |
| 2247 | $fieldName = $locField[2]; |
| 2248 | $fieldCount = $locField[3]; |
| 2249 | |
| 2250 | // Set up the operation type (add/overwrite) |
| 2251 | // Ignore operation for websites |
| 2252 | // @todo Tidy this up |
| 2253 | $operation = 0; |
| 2254 | if ($fieldName != 'website') { |
| 2255 | $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]); |
| 2256 | } |
| 2257 | // default operation is overwrite. |
| 2258 | if (!$operation) { |
| 2259 | $operation = 2; |
| 2260 | } |
| 2261 | $locBlocks[$fieldName][$fieldCount]['operation'] = $operation; |
| 2262 | } |
| 2263 | $blocksDAO = []; |
| 2264 | |
| 2265 | // @todo Handle OpenID (not currently in API). |
| 2266 | if (!empty($locBlocks)) { |
| 2267 | $locationBlocks = self::getLocationBlockInfo(); |
| 2268 | |
| 2269 | $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_primary' => 1]); |
| 2270 | $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_billing' => 1]); |
| 2271 | |
| 2272 | foreach ($locBlocks as $name => $block) { |
| 2273 | $blocksDAO[$name] = ['delete' => [], 'update' => []]; |
| 2274 | if (!is_array($block) || CRM_Utils_System::isNull($block)) { |
| 2275 | continue; |
| 2276 | } |
| 2277 | $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label']; |
| 2278 | $changePrimary = FALSE; |
| 2279 | $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL; |
| 2280 | $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL; |
| 2281 | |
| 2282 | foreach ($block as $blkCount => $values) { |
| 2283 | $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]); |
| 2284 | $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0); |
| 2285 | if (!$otherBlockId) { |
| 2286 | continue; |
| 2287 | } |
| 2288 | |
| 2289 | // For the block which belongs to other-contact, link the location block to main-contact |
| 2290 | $otherBlockDAO = new $daoName(); |
| 2291 | $otherBlockDAO->contact_id = $mainId; |
| 2292 | |
| 2293 | // Get the ID of this block on the 'other' contact, otherwise skip |
| 2294 | $otherBlockDAO->id = $otherBlockId; |
| 2295 | |
| 2296 | // Add/update location and type information from the form, if applicable |
| 2297 | if ($locationBlocks[$name]['hasLocation']) { |
| 2298 | $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]); |
| 2299 | $otherBlockDAO->location_type_id = $locTypeId; |
| 2300 | } |
| 2301 | if ($locationBlocks[$name]['hasType']) { |
| 2302 | $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]); |
| 2303 | $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId; |
| 2304 | } |
| 2305 | |
| 2306 | // If we're deliberately setting this as primary then add the flag |
| 2307 | // and remove it from the current primary location (if there is one). |
| 2308 | // But only once for each entity. |
| 2309 | $set_primary = CRM_Utils_Array::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]); |
| 2310 | if (!$changePrimary && $set_primary == "1") { |
| 2311 | $otherBlockDAO->is_primary = 1; |
| 2312 | if ($primaryDAOId) { |
| 2313 | $removePrimaryDAO = new $daoName(); |
| 2314 | $removePrimaryDAO->id = $primaryDAOId; |
| 2315 | $removePrimaryDAO->is_primary = 0; |
| 2316 | $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO; |
| 2317 | } |
| 2318 | $changePrimary = TRUE; |
| 2319 | } |
| 2320 | // Otherwise, if main contact already has primary, set it to 0. |
| 2321 | elseif ($primaryDAOId) { |
| 2322 | $otherBlockDAO->is_primary = 0; |
| 2323 | } |
| 2324 | |
| 2325 | // If the main contact already has a billing location, set this to 0. |
| 2326 | if ($billingDAOId) { |
| 2327 | $otherBlockDAO->is_billing = 0; |
| 2328 | } |
| 2329 | |
| 2330 | $operation = CRM_Utils_Array::value('operation', $values, 2); |
| 2331 | // overwrite - need to delete block which belongs to main-contact. |
| 2332 | if (!empty($mainBlockId) && ($operation == 2)) { |
| 2333 | $deleteDAO = new $daoName(); |
| 2334 | $deleteDAO->id = $mainBlockId; |
| 2335 | $deleteDAO->find(TRUE); |
| 2336 | |
| 2337 | // if we about to delete a primary / billing block, set the flags for new block |
| 2338 | // that we going to assign to main-contact |
| 2339 | if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) { |
| 2340 | $otherBlockDAO->is_primary = 1; |
| 2341 | } |
| 2342 | if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) { |
| 2343 | $otherBlockDAO->is_billing = 1; |
| 2344 | } |
| 2345 | $blocksDAO[$name]['delete'][$deleteDAO->id] = $deleteDAO; |
| 2346 | } |
| 2347 | $blocksDAO[$name]['update'][$otherBlockDAO->id] = $otherBlockDAO; |
| 2348 | } |
| 2349 | } |
| 2350 | } |
| 2351 | |
| 2352 | CRM_Utils_Hook::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo); |
| 2353 | foreach ($blocksDAO as $blockDAOs) { |
| 2354 | if (!empty($blockDAOs['update'])) { |
| 2355 | foreach ($blockDAOs['update'] as $blockDAO) { |
| 2356 | $blockDAO->save(); |
| 2357 | } |
| 2358 | } |
| 2359 | if (!empty($blockDAOs['delete'])) { |
| 2360 | foreach ($blockDAOs['delete'] as $blockDAO) { |
| 2361 | $blockDAO->delete(); |
| 2362 | } |
| 2363 | } |
| 2364 | } |
| 2365 | } |
| 2366 | |
| 2367 | /** |
| 2368 | * Dedupe a pair of contacts. |
| 2369 | * |
| 2370 | * @param array $migrationInfo |
| 2371 | * @param array $resultStats |
| 2372 | * @param array $deletedContacts |
| 2373 | * @param string $mode |
| 2374 | * @param bool $checkPermissions |
| 2375 | * @param int $mainId |
| 2376 | * @param int $otherId |
| 2377 | * @param string $cacheKeyString |
| 2378 | */ |
| 2379 | protected static function dedupePair(&$migrationInfo, &$resultStats, &$deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString) { |
| 2380 | |
| 2381 | // go ahead with merge if there is no conflict |
| 2382 | $conflicts = []; |
| 2383 | if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) { |
| 2384 | CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions); |
| 2385 | $resultStats['merged'][] = [ |
| 2386 | 'main_id' => $mainId, |
| 2387 | 'other_id' => $otherId, |
| 2388 | ]; |
| 2389 | $deletedContacts[] = $otherId; |
| 2390 | } |
| 2391 | else { |
| 2392 | $resultStats['skipped'][] = [ |
| 2393 | 'main_id' => $mainId, |
| 2394 | 'other_id' => $otherId, |
| 2395 | ]; |
| 2396 | } |
| 2397 | |
| 2398 | // store any conflicts |
| 2399 | if (!empty($conflicts)) { |
| 2400 | foreach ($conflicts as $key => $dnc) { |
| 2401 | $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'"; |
| 2402 | } |
| 2403 | CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts); |
| 2404 | } |
| 2405 | else { |
| 2406 | // delete entry from PrevNextCache table so we don't consider the pair next time |
| 2407 | // pair may have been flipped, so make sure we delete using both orders |
| 2408 | CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString, TRUE); |
| 2409 | } |
| 2410 | } |
| 2411 | |
| 2412 | } |