Merge pull request #15300 from civicrm/5.18
[civicrm-core.git] / CRM / Export / BAO / ExportProcessor.php
index 242dc689845c3632eb066b7dca3bdcb7ed6b4b5a..6983115f7506ec9d193e2b5eba27cb6c7dc7cec8 100644 (file)
@@ -100,6 +100,13 @@ class CRM_Export_BAO_ExportProcessor {
    */
   protected $contactGreetingFields = [];
 
+  /**
+   * An array of primary IDs of the entity being exported.
+   *
+   * @var array
+   */
+  protected $ids = [];
+
   /**
    * Get additional non-visible fields for address merge purposes.
    *
@@ -585,11 +592,28 @@ class CRM_Export_BAO_ExportProcessor {
     $this->queryOperator = $queryOperator;
   }
 
+  /**
+   * @return array
+   */
+  public function getIds() {
+    return $this->ids;
+  }
+
+  /**
+   * @param array $ids
+   */
+  public function setIds($ids) {
+    $this->ids = $ids;
+  }
+
   /**
    * @return array
    */
   public function getQueryFields() {
-    return $this->queryFields;
+    return array_merge(
+      $this->queryFields,
+      $this->getComponentPaymentFields()
+    );
   }
 
   /**
@@ -602,6 +626,7 @@ class CRM_Export_BAO_ExportProcessor {
     $queryFields['country']['context'] = 'country';
     $queryFields['world_region']['context'] = 'country';
     $queryFields['state_province']['context'] = 'province';
+    $queryFields['contact_id'] = ['title' => ts('Contact ID'), 'type' => CRM_Utils_Type::T_INT];
     $this->queryFields = $queryFields;
   }
 
@@ -724,7 +749,7 @@ class CRM_Export_BAO_ExportProcessor {
       return $this->getQueryFields()[$field]['title'];
     }
     elseif ($this->isExportPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
-      return CRM_Utils_Array::value($field, $this->getcomponentPaymentFields());
+      return CRM_Utils_Array::value($field, $this->getcomponentPaymentFields())['title'];
     }
     else {
       return $field;
@@ -739,23 +764,8 @@ class CRM_Export_BAO_ExportProcessor {
    */
   public function runQuery($params, $order) {
     $returnProperties = $this->getReturnProperties();
-    $addressWhere = '';
     $params = array_merge($params, $this->getWhereParams());
-    if ($this->isPostalableOnly) {
-      if (array_key_exists('street_address', $returnProperties)) {
-        $addressWhere = " civicrm_address.street_address <> ''";
-        if (array_key_exists('supplemental_address_1', $returnProperties)) {
-          // We need this to be an OR rather than AND on the street_address so, hack it in.
-          $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
-            'address_options', TRUE, NULL, TRUE
-          );
-          if (!empty($addressOptions['supplemental_address_1'])) {
-            $addressWhere .= " OR civicrm_address.supplemental_address_1 <> ''";
-          }
-        }
-        $addressWhere = ' AND (' . $addressWhere . ')';
-      }
-    }
+
     $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
       FALSE, FALSE, $this->getQueryMode(),
       FALSE, TRUE, TRUE, NULL, $this->getQueryOperator()
@@ -781,6 +791,22 @@ class CRM_Export_BAO_ExportProcessor {
       }
     }
 
+    if ($this->isPostalableOnly) {
+      if (array_key_exists('street_address', $returnProperties)) {
+        $addressWhere = " civicrm_address.street_address <> ''";
+        if (array_key_exists('supplemental_address_1', $returnProperties)) {
+          // We need this to be an OR rather than AND on the street_address so, hack it in.
+          $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
+            'address_options', TRUE, NULL, TRUE
+          );
+          if (!empty($addressOptions['supplemental_address_1'])) {
+            $addressWhere .= " OR civicrm_address.supplemental_address_1 <> ''";
+          }
+        }
+        $whereClauses['address'] = $addressWhere;
+      }
+    }
+
     if (empty($where)) {
       $where = "WHERE " . implode(' AND ', $whereClauses);
     }
@@ -1255,11 +1281,11 @@ class CRM_Export_BAO_ExportProcessor {
    */
   public function getComponentPaymentFields() {
     return [
-      'componentPaymentField_total_amount' => ts('Total Amount'),
-      'componentPaymentField_contribution_status' => ts('Contribution Status'),
-      'componentPaymentField_received_date' => ts('Date Received'),
-      'componentPaymentField_payment_instrument' => ts('Payment Method'),
-      'componentPaymentField_transaction_id' => ts('Transaction ID'),
+      'componentPaymentField_total_amount' => ['title' => ts('Total Amount'), 'type' => CRM_Utils_Type::T_MONEY],
+      'componentPaymentField_contribution_status' => ['title' => ts('Contribution Status'), 'type' => CRM_Utils_Type::T_STRING],
+      'componentPaymentField_received_date' => ['title' => ts('Date Received'), 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME],
+      'componentPaymentField_payment_instrument' => ['title' => ts('Payment Method'), 'type' => CRM_Utils_Type::T_STRING],
+      'componentPaymentField_transaction_id' => ['title' => ts('Transaction ID'), 'type' => CRM_Utils_Type::T_STRING],
     ];
   }
 
@@ -1271,7 +1297,7 @@ class CRM_Export_BAO_ExportProcessor {
    */
   public function getPaymentHeaders() {
     if ($this->isExportPaymentFields() && !$this->isExportSpecifiedPaymentFields()) {
-      return $this->getcomponentPaymentFields();
+      return CRM_Utils_Array::collect('title', $this->getcomponentPaymentFields());
     }
     return [];
   }
@@ -1396,24 +1422,21 @@ class CRM_Export_BAO_ExportProcessor {
       return "$fieldName varchar(128)";
     }
 
-    if (substr($fieldName, -11) == 'campaign_id') {
-      // CRM-14398
-      return "$fieldName varchar(128)";
-    }
-
     $queryFields = $this->getQueryFields();
-    $lookUp = ['prefix_id', 'suffix_id'];
+    // @todo remove the enotice avoidance here, ensure all columns are declared.
+    // tests will fail on the enotices until they all are & then all the 'else'
+    // below can go.
+    $fieldSpec = $queryFields[$columnName] ?? [];
+
     // set the sql columns
-    if (isset($queryFields[$columnName]['type'])) {
-      switch ($queryFields[$columnName]['type']) {
+    if (isset($fieldSpec['type'])) {
+      switch ($fieldSpec['type']) {
         case CRM_Utils_Type::T_INT:
         case CRM_Utils_Type::T_BOOLEAN:
-          if (in_array($columnName, $lookUp)) {
+          if (in_array(CRM_Utils_Array::value('data_type', $fieldSpec), ['Country', 'StateProvince', 'ContactReference'])) {
             return "$fieldName varchar(255)";
           }
-          else {
-            return "$fieldName varchar(16)";
-          }
+          return "$fieldName varchar(16)";
 
         case CRM_Utils_Type::T_STRING:
           if (isset($queryFields[$columnName]['maxlength'])) {
@@ -1469,8 +1492,6 @@ class CRM_Export_BAO_ExportProcessor {
                 $length = max(512, CRM_Utils_Array::value('text_length', $queryFields[$columnName]));
                 return "$fieldName varchar($length)";
 
-              case 'Country':
-              case 'StateProvince':
               case 'Link':
                 return "$fieldName varchar(255)";
 
@@ -2203,4 +2224,184 @@ WHERE  id IN ( $deleteIDString )
     $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] = '';
+      }
+    }
+  }
+
+  /**
+   * Write to the csv from the temp table.
+   */
+  public function writeCSVFromTable() {
+    // call export hook
+    $headerRows = $this->getHeaderRows();
+    $exportTempTable = $this->getTemporaryTable();
+    $exportMode = $this->getExportMode();
+    $sqlColumns = $this->getSQLColumns();
+    $componentTable = $this->getComponentTable();
+    $ids = $this->getIds();
+    CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
+    if ($exportMode !== $this->getExportMode() || $componentTable !== $this->getComponentTable()) {
+      CRM_Core_Error::deprecatedFunctionWarning('altering the export mode and/or component table in the hook is no longer supported.');
+    }
+    if ($exportTempTable !== $this->getTemporaryTable()) {
+      CRM_Core_Error::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
+      $this->setTemporaryTable($exportTempTable);
+    }
+    $exportTempTable = $this->getTemporaryTable();
+    $writeHeader = TRUE;
+    $offset = 0;
+    // increase this number a lot to avoid making too many queries
+    // LIMIT is not much faster than a no LIMIT query
+    // CRM-7675
+    $limit = 100000;
+
+    $query = "SELECT * FROM $exportTempTable";
+
+    while (1) {
+      $limitQuery = $query . "
+LIMIT $offset, $limit
+";
+      $dao = CRM_Core_DAO::executeQuery($limitQuery);
+
+      if ($dao->N <= 0) {
+        break;
+      }
+
+      $componentDetails = [];
+      while ($dao->fetch()) {
+        $row = [];
+
+        foreach (array_keys($sqlColumns) as $column) {
+          $row[$column] = $dao->$column;
+        }
+        $componentDetails[] = $row;
+      }
+      CRM_Core_Report_Excel::writeCSVFile($this->getExportFileName(),
+        $headerRows,
+        $componentDetails,
+        NULL,
+        $writeHeader
+      );
+
+      $writeHeader = FALSE;
+      $offset += $limit;
+    }
+  }
+
 }