Incorporate searchLimit in dedupe cacheKey
[civicrm-core.git] / CRM / Contact / Form / Merge.php
index 08d826ede616b1d4eae9c684a7bbf57d1515ef78..da804021ea2ce1ab7eafde17ca6349518af0f62f 100644 (file)
  */
 class CRM_Contact_Form_Merge extends CRM_Core_Form {
   // The id of the contact that there's a duplicate for; this one will
-  // possibly inherit some of $_oid's properties and remain in the system.
-  var $_cid = NULL;
+  /**
+   * possibly inherit some of $_oid's properties and remain in the system.
+   * @var int
+   */
+  public $_cid = NULL;
 
-  // The id of the other contact - the duplicate one that will get deleted.
-  var $_oid = NULL;
+  /**
+   * The id of the other contact - the duplicate one that will get deleted.
+   * @var int
+   */
+  public $_oid = NULL;
 
-  var $_contactType = NULL;
+  public $_contactType = NULL;
 
   /**
    * @var array
    */
-  public $criteria = array();
+  public $criteria = [];
 
   /**
    * Query limit to be retained in the urls.
    *
    * @var int
    */
-  var $limit;
+  public $limit;
 
   /**
    * String for quickform bug handling.
@@ -66,7 +72,7 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
    *
    * @var string
    */
-  var $_qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
+  public $_qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
 
   public function preProcess() {
     try {
@@ -85,28 +91,30 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
 
       $this->bounceIfInvalid($this->_cid, $this->_oid);
 
-      $this->_contactType = civicrm_api3('Contact', 'getvalue', array(
-        'id' => $this->_cid,
-        'return' => 'contact_type',
-      ));
+      $contacts = civicrm_api3('Contact', 'get', [
+        'id' => ['IN' => [$this->_cid, $this->_oid]],
+        'return' => ['contact_type', 'modified_date', 'created_date', 'contact_sub_type'],
+      ])['values'];
+
+      $this->_contactType = $contacts[$this->_cid]['contact_type'];
 
       $browseUrl = CRM_Utils_System::url('civicrm/contact/dedupefind', array_merge($urlParams, ['action' => 'browse']));
 
       if (!$this->_rgid) {
         // Unset browse URL as we have come from the search screen.
         $browseUrl = '';
-        $this->_rgid = civicrm_api3('RuleGroup', 'getvalue', array(
+        $this->_rgid = civicrm_api3('RuleGroup', 'getvalue', [
           'contact_type' => $this->_contactType,
           'used' => 'Supervised',
           'return' => 'id',
-        ));
+        ]);
       }
       $this->assign('browseUrl', $browseUrl);
       if ($browseUrl) {
         CRM_Core_Session::singleton()->pushUserContext($browseUrl);
       }
 
-      $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid, json_decode($this->criteria, TRUE));
+      $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $gid, json_decode($this->criteria, TRUE), TRUE, $this->limit);
 
       $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
       $where = "de.id IS NULL";
@@ -134,10 +142,10 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
       $this->assign('flip', $flipUrl);
 
       $this->prev = $this->next = NULL;
-      foreach (array(
-                 'prev',
-                 'next',
-               ) as $position) {
+      foreach ([
+        'prev',
+        'next',
+      ] as $position) {
         if (!empty($pos[$position])) {
           if ($pos[$position]['id1'] && $pos[$position]['id2']) {
             $rowParams = array_merge($urlParams, [
@@ -175,11 +183,28 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
       $this->assign('main_cid', $main['contact_id']);
       $this->assign('other_cid', $other['contact_id']);
       $this->assign('rgid', $this->_rgid);
+      $this->assignSummaryRowsToTemplate($contacts);
 
-      $this->addElement('checkbox', 'toggleSelect', NULL, NULL, array('class' => 'select-rows'));
+      $this->addElement('checkbox', 'toggleSelect', NULL, NULL, ['class' => 'select-rows']);
 
       $this->assign('mainLocBlock', json_encode($rowsElementsAndInfo['main_details']['location_blocks']));
       $this->assign('locationBlockInfo', json_encode(CRM_Dedupe_Merger::getLocationBlockInfo()));
+      $this->assign('mainContactTypeIcon', CRM_Contact_BAO_Contact_Utils::getImage($contacts[$this->_cid]['contact_sub_type'] ? $contacts[$this->_cid]['contact_sub_type'] : $contacts[$this->_cid]['contact_type'],
+        FALSE,
+        $this->_cid
+      ));
+      $this->assign('otherContactTypeIcon', CRM_Contact_BAO_Contact_Utils::getImage($contacts[$this->_oid]['contact_sub_type'] ? $contacts[$this->_oid]['contact_sub_type'] : $contacts[$this->_oid]['contact_type'],
+        FALSE,
+        $this->_oid
+      ));
+
+      if (isset($rowsElementsAndInfo['rows']['move_contact_type'])) {
+        // We don't permit merging contacts of different types so this is just clutter - putting
+        // the icon next to the contact name is consistent with elsewhere and permits hover-info
+        // https://lab.civicrm.org/dev/core/issues/824
+        unset($rowsElementsAndInfo['rows']['move_contact_type']);
+      }
+
       $this->assign('rows', $rowsElementsAndInfo['rows']);
 
       // add elements
@@ -189,16 +214,16 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
         // on the form.
         if (substr($element[1], 0, 13) === 'move_location') {
           $element[4] = array_merge(
-            (array) CRM_Utils_Array::value(4, $element, array()),
-            array(
+            (array) CRM_Utils_Array::value(4, $element, []),
+            [
               'data-location' => substr($element[1], 14),
               'data-is_location' => TRUE,
-            ));
+            ]);
         }
         if (substr($element[1], 0, 15) === 'location_blocks') {
           // @todo We could add some data elements here to make jquery manipulation more straight-forward
           // @todo consider enabling if it is an add & defaulting to true.
-          $element[4] = array_merge((array) CRM_Utils_Array::value(4, $element, array()), array('disabled' => TRUE));
+          $element[4] = array_merge((array) CRM_Utils_Array::value(4, $element, []), ['disabled' => TRUE]);
         }
         $this->addElement($element[0],
           $element[1],
@@ -220,7 +245,7 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
         ->readUserContext());
     }
     catch (CRM_Core_Exception $e) {
-      CRM_Core_Error::statusBounce(ts($e->getMessage()));
+      CRM_Core_Error::statusBounce($e->getMessage());
     }
   }
 
@@ -229,35 +254,35 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
 
   public function buildQuickForm() {
     $this->unsavedChangesWarn = FALSE;
-    CRM_Utils_System::setTitle(ts('Merge %1 contacts', array(1 => $this->_contactType)));
-    $buttons = array();
+    CRM_Utils_System::setTitle(ts('Merge %1 contacts', [1 => $this->_contactType]));
+    $buttons = [];
 
-    $buttons[] = array(
+    $buttons[] = [
       'type' => 'next',
       'name' => $this->next ? ts('Merge and go to Next Pair') : ts('Merge'),
       'isDefault' => TRUE,
       'icon' => $this->next ? 'fa-play-circle' : 'check',
-    );
+    ];
 
     if ($this->next || $this->prev) {
-      $buttons[] = array(
+      $buttons[] = [
         'type' => 'submit',
         'name' => ts('Merge and go to Listing'),
-      );
-      $buttons[] = array(
+      ];
+      $buttons[] = [
         'type' => 'done',
         'name' => ts('Merge and View Result'),
         'icon' => 'fa-check-circle',
-      );
+      ];
     }
 
-    $buttons[] = array(
+    $buttons[] = [
       'type' => 'cancel',
       'name' => ts('Cancel'),
-    );
+    ];
 
     $this->addButtons($buttons);
-    $this->addFormRule(array('CRM_Contact_Form_Merge', 'formRule'), $this);
+    $this->addFormRule(['CRM_Contact_Form_Merge', 'formRule'], $this);
   }
 
   /**
@@ -268,13 +293,13 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
    * @return array
    */
   public static function formRule($fields, $files, $self) {
-    $errors = array();
+    $errors = [];
     $link = CRM_Utils_System::href(ts('Flip between the original and duplicate contacts.'),
       'civicrm/contact/merge',
       'reset=1&action=update&cid=' . $self->_oid . '&oid=' . $self->_cid . '&rgid=' . $self->_rgid . '&flip=1'
     );
     if (CRM_Contact_BAO_Contact::checkDomainContact($self->_oid)) {
-      $errors['_qf_default'] = ts("The Default Organization contact cannot be merged into another contact record. It is associated with the CiviCRM installation for this domain and contains information used for system functions. If you want to merge these records, you can: %1", array(1 => $link));
+      $errors['_qf_default'] = ts("The Default Organization contact cannot be merged into another contact record. It is associated with the CiviCRM installation for this domain and contains information used for system functions. If you want to merge these records, you can: %1", [1 => $link]);
     }
     return $errors;
   }
@@ -284,12 +309,12 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
 
     $formValues['main_details'] = $this->_mainDetails;
     $formValues['other_details'] = $this->_otherDetails;
-    $migrationData = array('migration_info' => $formValues);
+    $migrationData = ['migration_info' => $formValues];
     CRM_Utils_Hook::merge('form', $migrationData, $this->_cid, $this->_oid);
     CRM_Dedupe_Merger::moveAllBelongings($this->_cid, $this->_oid, $migrationData['migration_info']);
 
     $name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_cid, 'display_name');
-    $message = '<ul><li>' . ts('%1 has been updated.', array(1 => $name)) . '</li><li>' . ts('Contact ID %1 has been deleted.', array(1 => $this->_oid)) . '</li></ul>';
+    $message = '<ul><li>' . ts('%1 has been updated.', [1 => $name]) . '</li><li>' . ts('Contact ID %1 has been deleted.', [1 => $this->_oid]) . '</li></ul>';
     CRM_Core_Session::setStatus($message, ts('Contacts Merged'), 'success');
 
     $urlParams = ['reset' => 1, 'cid' => $this->_cid, 'rgid' => $this->_rgid, 'gid' => $this->_gid, 'limit' => $this->limit, 'criteria' => $this->criteria];
@@ -306,7 +331,7 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
     }
 
     if ($this->next && $this->_mergeId) {
-      $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid, json_decode($this->criteria, TRUE));
+      $cacheKey = CRM_Dedupe_Merger::getMergeCacheKeyString($this->_rgid, $this->_gid, json_decode($this->criteria, TRUE), TRUE, $this->limit);
 
       $join = CRM_Dedupe_Merger::getJoinOnDedupeTable();
       $where = "de.id IS NULL";
@@ -347,7 +372,7 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
     }
 
     if (!CRM_Dedupe_BAO_Rule::validateContacts($cid, $oid)) {
-      CRM_Core_Error::statusBounce(ts('The selected pair of contacts are marked as non duplicates. If these records should be merged, you can remove this exception on the <a href="%1">Dedupe Exceptions</a> page.', array(1 => CRM_Utils_System::url('civicrm/dedupe/exception', 'reset=1'))));
+      CRM_Core_Error::statusBounce(ts('The selected pair of contacts are marked as non duplicates. If these records should be merged, you can remove this exception on the <a href="%1">Dedupe Exceptions</a> page.', [1 => CRM_Utils_System::url('civicrm/dedupe/exception', 'reset=1')]));
     }
 
     if (!(CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT) &&
@@ -359,10 +384,40 @@ class CRM_Contact_Form_Merge extends CRM_Core_Form {
     // ensure that oid is not the current user, if so refuse to do the merge
     if (CRM_Core_Session::singleton()->getLoggedInContactID() == $oid) {
       $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.',
-        array(1 => CRM_Core_Session::singleton()->getLoggedInContactDisplayName())
+        [1 => CRM_Core_Session::singleton()->getLoggedInContactDisplayName()]
       );
       CRM_Core_Error::statusBounce($message);
     }
   }
 
+  /**
+   * Assign the summary_rows variable to the tpl.
+   *
+   * This adds rows to the beginning of the block that will help in making merge choices.
+   *
+   * It can be modified by a hook by altering what is assigned. Although not technically supported this
+   * is an easy tweak with no earth-shattering impacts if later changes stop if from working.
+   *
+   * https://lab.civicrm.org/dev/core/issues/824
+   *
+   * @param array $contacts
+   */
+  protected function assignSummaryRowsToTemplate($contacts) {
+    $mostRecent = ($contacts[$this->_cid]['modified_date'] < $contacts[$this->_oid]['modified_date']) ? $this->_oid : $this->_cid;
+    $this->assign('summary_rows', [
+      [
+        'name' => 'created_date',
+        'label' => ts('Created'),
+        'main_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_cid]['created_date']),
+        'other_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_oid]['created_date']),
+      ],
+      [
+        'name' => 'modified_date',
+        'label' => ts('Last Modified'),
+        'main_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_cid]['modified_date']) . ($mostRecent == $this->_cid ? ' (' . ts('Most Recent') . ')' : ''),
+        'other_contact_value' => CRM_Utils_Date::customFormat($contacts[$this->_oid]['modified_date']) . ($mostRecent == $this->_oid ? ' (' . ts('Most Recent') . ')' : ''),
+      ],
+    ]);
+  }
+
 }