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