Merge pull request #14913 from eileenmcnaughton/export
[civicrm-core.git] / CRM / Export / BAO / ExportProcessor.php
index b714d32e160bf488759f02a0ce3f6fd70ae1fb62..30bd8e1f7d5f5d853559fa73efbbae29a1e2a91e 100644 (file)
@@ -93,6 +93,13 @@ class CRM_Export_BAO_ExportProcessor {
    */
   protected $additionalFieldsForSameAddressMerge = [];
 
+  /**
+   * Fields used for merging same contacts.
+   *
+   * @var array
+   */
+  protected $contactGreetingFields = [];
+
   /**
    * Get additional non-visible fields for address merge purposes.
    *
@@ -263,6 +270,48 @@ class CRM_Export_BAO_ExportProcessor {
    */
   protected $outputSpecification = [];
 
+  /**
+   * @var string
+   */
+  protected $componentTable = '';
+
+  /**
+   * @return string
+   */
+  public function getComponentTable() {
+    return $this->componentTable;
+  }
+
+  /**
+   * Set the component table (if any).
+   *
+   * @param string $componentTable
+   */
+  public function setComponentTable($componentTable) {
+    $this->componentTable = $componentTable;
+  }
+
+  /**
+   * Clause from component search.
+   *
+   * @var string
+   */
+  protected $componentClause = '';
+
+  /**
+   * @return string
+   */
+  public function getComponentClause() {
+    return $this->componentClause;
+  }
+
+  /**
+   * @param string $componentClause
+   */
+  public function setComponentClause($componentClause) {
+    $this->componentClause = $componentClause;
+  }
+
   /**
    * Name of a temporary table created to hold the results.
    *
@@ -288,6 +337,38 @@ class CRM_Export_BAO_ExportProcessor {
     $this->temporaryTable = $temporaryTable;
   }
 
+  protected $postalGreetingTemplate;
+
+  /**
+   * @return mixed
+   */
+  public function getPostalGreetingTemplate() {
+    return $this->postalGreetingTemplate;
+  }
+
+  /**
+   * @param mixed $postalGreetingTemplate
+   */
+  public function setPostalGreetingTemplate($postalGreetingTemplate) {
+    $this->postalGreetingTemplate = $postalGreetingTemplate;
+  }
+
+  /**
+   * @return mixed
+   */
+  public function getAddresseeGreetingTemplate() {
+    return $this->addresseeGreetingTemplate;
+  }
+
+  /**
+   * @param mixed $addresseeGreetingTemplate
+   */
+  public function setAddresseeGreetingTemplate($addresseeGreetingTemplate) {
+    $this->addresseeGreetingTemplate = $addresseeGreetingTemplate;
+  }
+
+  protected $addresseeGreetingTemplate;
+
   /**
    * CRM_Export_BAO_ExportProcessor constructor.
    *
@@ -297,8 +378,14 @@ class CRM_Export_BAO_ExportProcessor {
    * @param bool $isMergeSameHousehold
    * @param bool $isPostalableOnly
    * @param bool $isMergeSameAddress
-   */
-  public function __construct($exportMode, $requestedFields, $queryOperator, $isMergeSameHousehold = FALSE, $isPostalableOnly = FALSE, $isMergeSameAddress = FALSE) {
+   * @param array $formValues
+   *   Values from the export options form on contact export. We currently support these keys
+   *   - postal_greeting
+   *   - postal_other
+   *   - addresee_greeting
+   *   - addressee_other
+   */
+  public function __construct($exportMode, $requestedFields, $queryOperator, $isMergeSameHousehold = FALSE, $isPostalableOnly = FALSE, $isMergeSameAddress = FALSE, $formValues = []) {
     $this->setExportMode($exportMode);
     $this->setQueryMode();
     $this->setQueryOperator($queryOperator);
@@ -311,6 +398,7 @@ class CRM_Export_BAO_ExportProcessor {
     $this->setAdditionalFieldsForSameAddressMerge();
     $this->setAdditionalFieldsForPostalExport();
     $this->setHouseholdMergeReturnProperties();
+    $this->setGreetingStringsForSameAddressMerge($formValues);
   }
 
   /**
@@ -651,8 +739,33 @@ class CRM_Export_BAO_ExportProcessor {
    */
   public function runQuery($params, $order) {
     $returnProperties = $this->getReturnProperties();
-    $addressWhere = '';
     $params = array_merge($params, $this->getWhereParams());
+
+    $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
+      FALSE, FALSE, $this->getQueryMode(),
+      FALSE, TRUE, TRUE, NULL, $this->getQueryOperator()
+    );
+
+    //sort by state
+    //CRM-15301
+    $query->_sort = $order;
+    list($select, $from, $where, $having) = $query->query();
+    $this->setQueryFields($query->_fields);
+    $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
+    if ($this->getRequestedFields() && ($this->getComponentTable())) {
+      $from .= " INNER JOIN " . $this->getComponentTable() . " ctTable ON ctTable.contact_id = contact_a.id ";
+    }
+    elseif ($this->getComponentClause()) {
+      $whereClauses[] = $this->getComponentClause();
+    }
+
+    // CRM-13982 - check if is deleted
+    foreach ($params as $value) {
+      if ($value[0] == 'contact_is_deleted') {
+        unset($whereClauses['trash_clause']);
+      }
+    }
+
     if ($this->isPostalableOnly) {
       if (array_key_exists('street_address', $returnProperties)) {
         $addressWhere = " civicrm_address.street_address <> ''";
@@ -665,20 +778,35 @@ class CRM_Export_BAO_ExportProcessor {
             $addressWhere .= " OR civicrm_address.supplemental_address_1 <> ''";
           }
         }
-        $addressWhere = ' AND (' . $addressWhere . ')';
+        $whereClauses['address'] = $addressWhere;
       }
     }
-    $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
-      FALSE, FALSE, $this->getQueryMode(),
-      FALSE, TRUE, TRUE, NULL, $this->getQueryOperator()
-    );
 
-    //sort by state
-    //CRM-15301
-    $query->_sort = $order;
-    list($select, $from, $where, $having) = $query->query();
-    $this->setQueryFields($query->_fields);
-    return [$query, $select, $from, $where . $addressWhere, $having];
+    if (empty($where)) {
+      $where = "WHERE " . implode(' AND ', $whereClauses);
+    }
+    else {
+      $where .= " AND " . implode(' AND ', $whereClauses);
+    }
+
+    $groupBy = $this->getGroupBy($query);
+    $queryString = "$select $from $where $having $groupBy";
+    if ($order) {
+      // always add contact_a.id to the ORDER clause
+      // so the order is deterministic
+      //CRM-15301
+      if (strpos('contact_a.id', $order) === FALSE) {
+        $order .= ", contact_a.id";
+      }
+
+      list($field, $dir) = explode(' ', $order, 2);
+      $field = trim($field);
+      if (!empty($this->getReturnProperties()[$field])) {
+        //CRM-15301
+        $queryString .= " ORDER BY $order";
+      }
+    }
+    return [$query, $queryString];
   }
 
   /**
@@ -797,11 +925,11 @@ class CRM_Export_BAO_ExportProcessor {
    * @param $metadata
    * @param $paymentDetails
    * @param $addPaymentHeader
-   * @param $paymentTableId
    *
    * @return array|bool
    */
-  public function buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId) {
+  public function buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader) {
+    $paymentTableId = $this->getPaymentTableID();
     if ($this->isHouseholdToSkip($iterationDAO->contact_id)) {
       return FALSE;
     }
@@ -843,10 +971,8 @@ class CRM_Export_BAO_ExportProcessor {
           $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
         }
         elseif (strstr($field, 'master_id')) {
-          $masterAddressId = NULL;
-          if (isset($iterationDAO->$field)) {
-            $masterAddressId = $iterationDAO->$field;
-          }
+          // @todo - why not just $field === 'master_id'  - what else would it be?
+          $masterAddressId = $iterationDAO->$field ?? NULL;
           // get display name of contact that address is shared.
           $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId);
         }
@@ -1512,6 +1638,78 @@ class CRM_Export_BAO_ExportProcessor {
     return in_array($contactID, $this->householdsToSkip);
   }
 
+  /**
+   * Get the various arrays that we use to structure our output.
+   *
+   * The extraction of these has been moved to a separate function for clarity and so that
+   * tests can be added - in particular on the $outputHeaders array.
+   *
+   * However it still feels a bit like something that I'm too polite to write down and this should be seen
+   * as a step on the refactoring path rather than how it should be.
+   *
+   * @return array
+   *   - outputColumns Array of columns to be exported. The values don't matter but the key must match the
+   *   alias for the field generated by BAO_Query object.
+   *   - headerRows Array of the column header strings to put in the csv header - non-associative.
+   *   - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
+   *   - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
+   *    I'm too embarassed to discuss here.
+   *    The keys need
+   *    - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
+   *    we could use does suggest further refactors. However, you future improver, do remember that every check you do
+   *    in the main DAO loop is done once per row & that coule be 100,000 times.)
+   *    Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
+   *    - a) the function used is more efficient or
+   *    - b) this code is old & outdated. Submit your answers to circular bin or better
+   *       yet find a way to comment them for posterity.
+   */
+  public function getExportStructureArrays() {
+    $outputColumns = $metadata = [];
+    $queryFields = $this->getQueryFields();
+    foreach ($this->getReturnProperties() as $key => $value) {
+      if (($key != 'location' || !is_array($value)) && !$this->isRelationshipTypeKey($key)) {
+        $outputColumns[$key] = $value;
+        $this->addOutputSpecification($key);
+      }
+      elseif ($this->isRelationshipTypeKey($key)) {
+        $outputColumns[$key] = $value;
+        foreach ($value as $relationField => $relationValue) {
+          // below block is same as primary block (duplicate)
+          if (isset($queryFields[$relationField]['title'])) {
+            $this->addOutputSpecification($relationField, $key);
+          }
+          elseif (is_array($relationValue) && $relationField == 'location') {
+            // fix header for location type case
+            foreach ($relationValue as $ltype => $val) {
+              foreach (array_keys($val) as $fld) {
+                $type = explode('-', $fld);
+                $this->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array::value(1, $type));
+              }
+            }
+          }
+        }
+      }
+      else {
+        foreach ($value as $locationType => $locationFields) {
+          foreach (array_keys($locationFields) as $locationFieldName) {
+            $type = explode('-', $locationFieldName);
+
+            $actualDBFieldName = $type[0];
+            $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName;
+
+            if (!empty($type[1])) {
+              $daoFieldName .= "-" . $type[1];
+            }
+            $this->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array::value(1, $type));
+            $metadata[$daoFieldName] = $this->getMetaDataForField($actualDBFieldName);
+            $outputColumns[$daoFieldName] = TRUE;
+          }
+        }
+      }
+    }
+    return [$outputColumns, $metadata];
+  }
+
   /**
    * Get default return property for export based on mode
    *
@@ -1612,23 +1810,67 @@ class CRM_Export_BAO_ExportProcessor {
     return $returnProperties;
   }
 
+  /**
+   * @param object $query
+   *   CRM_Contact_BAO_Query
+   *
+   * @return string
+   *   Group By Clause
+   */
+  public function getGroupBy($query) {
+    $groupBy = NULL;
+    $returnProperties = $this->getReturnProperties();
+    $exportMode = $this->getExportMode();
+    $queryMode = $this->getQueryMode();
+    if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) ||
+      CRM_Utils_Array::value('notes', $returnProperties) ||
+      // CRM-9552
+      ($queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy)
+    ) {
+      $groupBy = "contact_a.id";
+    }
+
+    switch ($exportMode) {
+      case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
+        $groupBy = 'civicrm_contribution.id';
+        if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
+          // especial group by  when soft credit columns are included
+          $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
+        }
+        break;
+
+      case CRM_Export_Form_Select::EVENT_EXPORT:
+        $groupBy = 'civicrm_participant.id';
+        break;
+
+      case CRM_Export_Form_Select::MEMBER_EXPORT:
+        $groupBy = "civicrm_membership.id";
+        break;
+    }
+
+    if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
+      $groupBy = "civicrm_activity.id ";
+    }
+
+    return $groupBy ? ' GROUP BY ' . implode(', ', (array) $groupBy) : '';
+  }
+
   /**
    * @param int $contactId
-   * @param array $exportParams
    *
    * @return array
    */
-  public function replaceMergeTokens($contactId, $exportParams) {
+  public function replaceMergeTokens($contactId) {
     $greetings = [];
     $contact = NULL;
 
     $greetingFields = [
-      'postal_greeting',
-      'addressee',
+      'postal_greeting' => $this->getPostalGreetingTemplate(),
+      'addressee' => $this->getAddresseeGreetingTemplate(),
     ];
-    foreach ($greetingFields as $greeting) {
-      if (!empty($exportParams[$greeting])) {
-        $greetingLabel = $exportParams[$greeting];
+    foreach ($greetingFields as $greeting => $greetingLabel) {
+      $tokens = CRM_Utils_Token::getTokens($greetingLabel);
+      if (!empty($tokens)) {
         if (empty($contact)) {
           $values = [
             'id' => $contactId,
@@ -1653,13 +1895,11 @@ class CRM_Export_BAO_ExportProcessor {
    * Build array for merging same addresses.
    *
    * @param $sql
-   * @param array $exportParams
    * @param bool $sharedAddress
    *
    * @return array
    */
-  public function buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
-    static $contactGreetingTokens = [];
+  public function buildMasterCopyArray($sql, $sharedAddress = FALSE) {
 
     $addresseeOptions = CRM_Core_OptionGroup::values('addressee');
     $postalOptions = CRM_Core_OptionGroup::values('postal_greeting');
@@ -1675,24 +1915,24 @@ class CRM_Export_BAO_ExportProcessor {
       $copyAddressee = $dao->copy_addressee;
 
       if (!$sharedAddress) {
-        if (!isset($contactGreetingTokens[$dao->master_contact_id])) {
-          $contactGreetingTokens[$dao->master_contact_id] = $this->replaceMergeTokens($dao->master_contact_id, $exportParams);
+        if (!isset($this->contactGreetingFields[$dao->master_contact_id])) {
+          $this->contactGreetingFields[$dao->master_contact_id] = $this->replaceMergeTokens($dao->master_contact_id);
         }
         $masterPostalGreeting = CRM_Utils_Array::value('postal_greeting',
-          $contactGreetingTokens[$dao->master_contact_id], $dao->master_postal_greeting
+          $this->contactGreetingFields[$dao->master_contact_id], $dao->master_postal_greeting
         );
         $masterAddressee = CRM_Utils_Array::value('addressee',
-          $contactGreetingTokens[$dao->master_contact_id], $dao->master_addressee
+          $this->contactGreetingFields[$dao->master_contact_id], $dao->master_addressee
         );
 
         if (!isset($contactGreetingTokens[$dao->copy_contact_id])) {
-          $contactGreetingTokens[$dao->copy_contact_id] = $this->replaceMergeTokens($dao->copy_contact_id, $exportParams);
+          $this->contactGreetingFields[$dao->copy_contact_id] = $this->replaceMergeTokens($dao->copy_contact_id);
         }
         $copyPostalGreeting = CRM_Utils_Array::value('postal_greeting',
-          $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_postal_greeting
+          $this->contactGreetingFields[$dao->copy_contact_id], $dao->copy_postal_greeting
         );
         $copyAddressee = CRM_Utils_Array::value('addressee',
-          $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_addressee
+          $this->contactGreetingFields[$dao->copy_contact_id], $dao->copy_addressee
         );
       }
 
@@ -1718,32 +1958,20 @@ class CRM_Export_BAO_ExportProcessor {
 
       if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
 
-        if (!empty($exportParams['postal_greeting_other']) &&
-          count($merge[$masterID]['copy']) >= 1
-        ) {
-          // use static greetings specified if no of contacts > 2
-          $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
-        }
-        elseif ($copyPostalGreeting) {
+        if ($copyPostalGreeting) {
           $this->trimNonTokensFromAddressString($copyPostalGreeting,
             $postalOptions[$dao->copy_postal_greeting_id],
-            $exportParams
+            $this->getPostalGreetingTemplate()
           );
           $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
           // if there happens to be a duplicate, remove it
           $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
         }
 
-        if (!empty($exportParams['addressee_other']) &&
-          count($merge[$masterID]['copy']) >= 1
-        ) {
-          // use static greetings specified if no of contacts > 2
-          $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
-        }
-        elseif ($copyAddressee) {
+        if ($copyAddressee) {
           $this->trimNonTokensFromAddressString($copyAddressee,
             $addresseeOptions[$dao->copy_addressee_id],
-            $exportParams, 'addressee'
+            $this->getAddresseeGreetingTemplate()
           );
           $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
         }
@@ -1754,6 +1982,104 @@ class CRM_Export_BAO_ExportProcessor {
     return $merge;
   }
 
+  /**
+   * Merge contacts with the same address.
+   */
+  public function mergeSameAddress() {
+
+    $tableName = $this->getTemporaryTable();
+    // check if any records are present based on if they have used shared address feature,
+    // and not based on if city / state .. matches.
+    $sql = "
+SELECT    r1.id                 as copy_id,
+          r1.civicrm_primary_id as copy_contact_id,
+          r1.addressee          as copy_addressee,
+          r1.addressee_id       as copy_addressee_id,
+          r1.postal_greeting    as copy_postal_greeting,
+          r1.postal_greeting_id as copy_postal_greeting_id,
+          r2.id                 as master_id,
+          r2.civicrm_primary_id as master_contact_id,
+          r2.postal_greeting    as master_postal_greeting,
+          r2.postal_greeting_id as master_postal_greeting_id,
+          r2.addressee          as master_addressee,
+          r2.addressee_id       as master_addressee_id
+FROM      $tableName r1
+INNER JOIN civicrm_address adr ON r1.master_id   = adr.id
+INNER JOIN $tableName      r2  ON adr.contact_id = r2.civicrm_primary_id
+ORDER BY  r1.id";
+    $linkedMerge = $this->buildMasterCopyArray($sql, TRUE);
+
+    // find all the records that have the same street address BUT not in a household
+    // require match on city and state as well
+    $sql = "
+SELECT    r1.id                 as master_id,
+          r1.civicrm_primary_id as master_contact_id,
+          r1.postal_greeting    as master_postal_greeting,
+          r1.postal_greeting_id as master_postal_greeting_id,
+          r1.addressee          as master_addressee,
+          r1.addressee_id       as master_addressee_id,
+          r2.id                 as copy_id,
+          r2.civicrm_primary_id as copy_contact_id,
+          r2.postal_greeting    as copy_postal_greeting,
+          r2.postal_greeting_id as copy_postal_greeting_id,
+          r2.addressee          as copy_addressee,
+          r2.addressee_id       as copy_addressee_id
+FROM      $tableName r1
+LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
+               r1.city = r2.city AND
+               r1.state_province_id = r2.state_province_id )
+WHERE     ( r1.household_name IS NULL OR r1.household_name = '' )
+AND       ( r2.household_name IS NULL OR r2.household_name = '' )
+AND       ( r1.street_address != '' )
+AND       r2.id > r1.id
+ORDER BY  r1.id
+";
+    $merge = $this->buildMasterCopyArray($sql);
+
+    // unset ids from $merge already present in $linkedMerge
+    foreach ($linkedMerge as $masterID => $values) {
+      $keys = [$masterID];
+      $keys = array_merge($keys, array_keys($values['copy']));
+      foreach ($merge as $mid => $vals) {
+        if (in_array($mid, $keys)) {
+          unset($merge[$mid]);
+        }
+        else {
+          foreach ($values['copy'] as $copyId) {
+            if (in_array($copyId, $keys)) {
+              unset($merge[$mid]['copy'][$copyId]);
+            }
+          }
+        }
+      }
+    }
+    $merge = $merge + $linkedMerge;
+
+    foreach ($merge as $masterID => $values) {
+      $sql = "
+UPDATE $tableName
+SET    addressee = %1, postal_greeting = %2, email_greeting = %3
+WHERE  id = %4
+";
+      $params = [
+        1 => [$values['addressee'], 'String'],
+        2 => [$values['postalGreeting'], 'String'],
+        3 => [$values['emailGreeting'], 'String'],
+        4 => [$masterID, 'Integer'],
+      ];
+      CRM_Core_DAO::executeQuery($sql, $params);
+
+      // delete all copies
+      $deleteIDs = array_keys($values['copy']);
+      $deleteIDString = implode(',', $deleteIDs);
+      $sql = "
+DELETE FROM $tableName
+WHERE  id IN ( $deleteIDString )
+";
+      CRM_Core_DAO::executeQuery($sql);
+    }
+  }
+
   /**
    * The function unsets static part of the string, if token is the dynamic part.
    *
@@ -1762,18 +2088,14 @@ class CRM_Export_BAO_ExportProcessor {
    *
    * @param string $parsedString
    * @param string $defaultGreeting
-   * @param bool $addressMergeGreetings
-   * @param string $greetingType
+   * @param string $greetingLabel
    *
    * @return mixed
    */
   public function trimNonTokensFromAddressString(
     &$parsedString, $defaultGreeting,
-    $addressMergeGreetings, $greetingType = 'postal_greeting'
+    $greetingLabel
   ) {
-    if (!empty($addressMergeGreetings[$greetingType])) {
-      $greetingLabel = $addressMergeGreetings[$greetingType];
-    }
     $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel;
 
     $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
@@ -1787,4 +2109,219 @@ class CRM_Export_BAO_ExportProcessor {
     return $parsedString;
   }
 
+  /**
+   * Preview export output.
+   *
+   * @param int $limit
+   * @return array
+   */
+  public function getPreview($limit) {
+    $rows = [];
+    list($outputColumns, $metadata) = $this->getExportStructureArrays();
+    $query = $this->runQuery([], '');
+    CRM_Core_DAO::disableFullGroupByMode();
+    $result = CRM_Core_DAO::executeQuery($query[1] . ' LIMIT ' . (int) $limit);
+    CRM_Core_DAO::reenableFullGroupByMode();
+    while ($result->fetch()) {
+      $rows[] = $this->buildRow($query[0], $result, $outputColumns, $metadata, [], []);
+    }
+    return $rows;
+  }
+
+  /**
+   * Set the template strings to be used when merging two contacts with the same address.
+   *
+   * @param array $formValues
+   *   Values from first form. In this case we care about the keys
+   *   - postal_greeting
+   *   - postal_other
+   *   - address_greeting
+   *   - addressee_other
+   *
+   * @return mixed
+   */
+  protected function setGreetingStringsForSameAddressMerge($formValues) {
+    $greetingOptions = CRM_Export_Form_Select::getGreetingOptions();
+
+    if (!empty($greetingOptions)) {
+      // Greeting options is keyed by 'postal_greeting' or 'addressee'.
+      foreach ($greetingOptions as $key => $value) {
+        $option = CRM_Utils_Array::value($key, $formValues);
+        if ($option) {
+          if ($greetingOptions[$key][$option] == ts('Other')) {
+            $formValues[$key] = $formValues["{$key}_other"];
+          }
+          elseif ($greetingOptions[$key][$option] == ts('List of names')) {
+            $formValues[$key] = '';
+          }
+          else {
+            $formValues[$key] = $greetingOptions[$key][$option];
+          }
+        }
+      }
+    }
+    if (!empty($formValues['postal_greeting'])) {
+      $this->setPostalGreetingTemplate($formValues['postal_greeting']);
+    }
+    if (!empty($formValues['addressee'])) {
+      $this->setAddresseeGreetingTemplate($formValues['addressee']);
+    }
+  }
+
+  /**
+   * Create the temporary table for output.
+   */
+  public function createTempTable() {
+    //creating a temporary table for the search result that need be exported
+    $exportTempTable = CRM_Utils_SQL_TempTable::build()->setDurable()->setCategory('export');
+    $sqlColumns = $this->getSQLColumns();
+    // also create the sql table
+    $exportTempTable->drop();
+
+    $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
+    if (!empty($sqlColumns)) {
+      $sql .= implode(",\n", array_values($sqlColumns)) . ',';
+    }
+
+    $sql .= "\n PRIMARY KEY ( id )";
+
+    // add indexes for street_address and household_name if present
+    $addIndices = [
+      'street_address',
+      'household_name',
+      'civicrm_primary_id',
+    ];
+
+    foreach ($addIndices as $index) {
+      if (isset($sqlColumns[$index])) {
+        $sql .= ",
+  INDEX index_{$index}( $index )
+";
+      }
+    }
+
+    $exportTempTable->createWithColumns($sql);
+    $this->setTemporaryTable($exportTempTable->getName());
+  }
+
+  /**
+   * Get the values of linked household contact.
+   *
+   * @param CRM_Core_DAO $relDAO
+   * @param array $value
+   * @param string $field
+   * @param array $row
+   *
+   * @throws \Exception
+   */
+  public function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
+    $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
+    $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
+    $i18n = CRM_Core_I18n::singleton();
+    $field = $field . '_';
+
+    foreach ($value as $relationField => $relationValue) {
+      if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
+        $fieldValue = $relDAO->$relationField;
+        if ($relationField == 'phone_type_id') {
+          $fieldValue = $phoneTypes[$relationValue];
+        }
+        elseif ($relationField == 'provider_id') {
+          $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
+        }
+        // CRM-13995
+        elseif (is_object($relDAO) && in_array($relationField, [
+          'email_greeting',
+          'postal_greeting',
+          'addressee',
+        ])) {
+          //special case for greeting replacement
+          $fldValue = "{$relationField}_display";
+          $fieldValue = $relDAO->$fldValue;
+        }
+      }
+      elseif (is_object($relDAO) && $relationField == 'state_province') {
+        $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
+      }
+      elseif (is_object($relDAO) && $relationField == 'country') {
+        $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
+      }
+      else {
+        $fieldValue = '';
+      }
+      $relPrefix = $field . $relationField;
+
+      if (is_object($relDAO) && $relationField == 'id') {
+        $row[$relPrefix] = $relDAO->contact_id;
+      }
+      elseif (is_array($relationValue) && $relationField == 'location') {
+        foreach ($relationValue as $ltype => $val) {
+          // If the location name has a space in it the we need to handle that. This
+          // is kinda hacky but specifically covered in the ExportTest so later efforts to
+          // improve it should be secure in the knowled it will be caught.
+          $ltype = str_replace(' ', '_', $ltype);
+          foreach (array_keys($val) as $fld) {
+            $type = explode('-', $fld);
+            $fldValue = "{$ltype}-" . $type[0];
+            if (!empty($type[1])) {
+              $fldValue .= "-" . $type[1];
+            }
+            // CRM-3157: localise country, region (both have ‘country’ context)
+            // and state_province (‘province’ context)
+            switch (TRUE) {
+              case (!is_object($relDAO)):
+                $row[$field . '_' . $fldValue] = '';
+                break;
+
+              case in_array('country', $type):
+              case in_array('world_region', $type):
+                $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
+                  ['context' => 'country']
+                );
+                break;
+
+              case in_array('state_province', $type):
+                $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
+                  ['context' => 'province']
+                );
+                break;
+
+              default:
+                $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
+                break;
+            }
+          }
+        }
+      }
+      elseif (isset($fieldValue) && $fieldValue != '') {
+        //check for custom data
+        if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
+          $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
+        }
+        else {
+          //normal relationship fields
+          // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
+          switch ($relationField) {
+            case 'country':
+            case 'world_region':
+              $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
+              break;
+
+            case 'state_province':
+              $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
+              break;
+
+            default:
+              $row[$relPrefix] = $fieldValue;
+              break;
+          }
+        }
+      }
+      else {
+        // if relation field is empty or null
+        $row[$relPrefix] = '';
+      }
+    }
+  }
+
 }