3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Class CRM_Export_BAO_ExportProcessor
21 * Class to handle logic of export.
23 class CRM_Export_BAO_ExportProcessor
{
33 protected $exportMode;
36 * Array of fields in the main query.
40 protected $queryFields = [];
47 protected $queryOperator;
50 * Requested output fields.
52 * If set to NULL then it is 'primary fields only'
53 * which actually means pretty close to all fields!
57 protected $requestedFields;
60 * Is the contact being merged into a single household.
64 protected $isMergeSameHousehold;
67 * Should contacts with the same address be merged.
71 protected $isMergeSameAddress = FALSE;
74 * Fields that need to be retrieved for address merge purposes but should not be in output.
78 protected $additionalFieldsForSameAddressMerge = [];
81 * Fields used for merging same contacts.
85 protected $contactGreetingFields = [];
88 * An array of primary IDs of the entity being exported.
95 * Greeting options mapping to various greeting ids.
97 * This stores the option values for the addressee, postal_greeting & email_greeting
102 protected $greetingOptions = [];
105 * Get additional non-visible fields for address merge purposes.
109 public function getAdditionalFieldsForSameAddressMerge(): array {
110 return $this->additionalFieldsForSameAddressMerge
;
114 * Set additional non-visible fields for address merge purposes.
116 public function setAdditionalFieldsForSameAddressMerge() {
117 if ($this->isMergeSameAddress
) {
118 $fields = ['id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'];
119 foreach ($fields as $index => $field) {
120 if (!empty($this->getReturnProperties()[$field])) {
121 unset($fields[$index]);
124 $this->additionalFieldsForSameAddressMerge
= array_fill_keys($fields, 1);
129 * Should contacts with the same address be merged.
133 public function isMergeSameAddress(): bool {
134 return $this->isMergeSameAddress
;
138 * Set same address is to be merged.
140 * @param bool $isMergeSameAddress
142 public function setIsMergeSameAddress(bool $isMergeSameAddress) {
143 $this->isMergeSameAddress
= $isMergeSameAddress;
147 * Additional fields required to export postal fields.
151 protected $additionalFieldsForPostalExport = [];
154 * Get additional fields required to do a postal export.
158 public function getAdditionalFieldsForPostalExport() {
159 return $this->additionalFieldsForPostalExport
;
163 * Set additional fields required for a postal export.
165 public function setAdditionalFieldsForPostalExport() {
166 if ($this->getRequestedFields() && $this->isPostalableOnly()) {
167 $fields = ['is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'];
168 foreach ($fields as $index => $field) {
169 if (!empty($this->getReturnProperties()[$field])) {
170 unset($fields[$index]);
173 $this->additionalFieldsForPostalExport
= array_fill_keys($fields, 1);
178 * Only export contacts that can receive postal mail.
180 * Includes being alive, having an address & not having do_not_mail.
184 protected $isPostalableOnly;
187 * Key representing the head of household in the relationship array.
189 * e.g. ['8_b_a' => 'Household Member Is', '8_a_b = 'Household Member Of'.....]
193 protected $relationshipTypes = [];
196 * Array of properties to retrieve for relationships.
200 protected $relationshipReturnProperties = [];
203 * IDs of households that have already been exported.
207 protected $exportedHouseholds = [];
210 * Contacts to be merged by virtue of their shared address.
214 protected $contactsToMerge = [];
217 * Households to skip during export as they will be exported via their relationships anyway.
221 protected $householdsToSkip = [];
224 * Additional fields to return.
226 * This doesn't make much sense when we have a fields set but search build add it's own onto
227 * the 'Primary fields' (all) option.
231 protected $additionalRequestedReturnProperties = [];
234 * Get additional return properties.
238 public function getAdditionalRequestedReturnProperties() {
239 return $this->additionalRequestedReturnProperties
;
243 * Set additional return properties.
245 * @param array $value
247 public function setAdditionalRequestedReturnProperties($value) {
249 if (!empty($value['group'])) {
250 unset($value['group']);
251 $value['groups'] = 1;
253 $this->additionalRequestedReturnProperties
= $value;
257 * Get return properties by relationship.
260 public function getRelationshipReturnProperties() {
261 return $this->relationshipReturnProperties
;
265 * Export values for related contacts.
269 protected $relatedContactValues = [];
274 protected $returnProperties = [];
279 protected $outputSpecification = [];
284 protected $componentTable = '';
289 public function getComponentTable() {
290 return $this->componentTable
;
294 * Set the component table (if any).
296 * @param string $componentTable
298 public function setComponentTable($componentTable) {
299 $this->componentTable
= $componentTable;
303 * Clause from component search.
307 protected $componentClause = '';
312 public function getComponentClause() {
313 return $this->componentClause
;
317 * @param string $componentClause
319 public function setComponentClause($componentClause) {
320 $this->componentClause
= $componentClause;
324 * Name of a temporary table created to hold the results.
326 * Current decision making on when to create a temp table is kinda bad so this might change
327 * a bit as it is reviewed but basically we need a temp table or similar to calculate merging
328 * addresses. Merging households is handled in php. We create a temp table even when we don't need them.
332 protected $temporaryTable;
337 public function getTemporaryTable(): string {
338 return $this->temporaryTable
;
342 * @param string $temporaryTable
344 public function setTemporaryTable(string $temporaryTable) {
345 $this->temporaryTable
= $temporaryTable;
348 protected $postalGreetingTemplate;
353 public function getPostalGreetingTemplate() {
354 return $this->postalGreetingTemplate
;
358 * @param mixed $postalGreetingTemplate
360 public function setPostalGreetingTemplate($postalGreetingTemplate) {
361 $this->postalGreetingTemplate
= $postalGreetingTemplate;
367 public function getAddresseeGreetingTemplate() {
368 return $this->addresseeGreetingTemplate
;
372 * @param mixed $addresseeGreetingTemplate
374 public function setAddresseeGreetingTemplate($addresseeGreetingTemplate) {
375 $this->addresseeGreetingTemplate
= $addresseeGreetingTemplate;
378 protected $addresseeGreetingTemplate;
381 * CRM_Export_BAO_ExportProcessor constructor.
383 * @param int $exportMode
384 * @param array|null $requestedFields
385 * @param string $queryOperator
386 * @param bool $isMergeSameHousehold
387 * @param bool $isPostalableOnly
388 * @param bool $isMergeSameAddress
389 * @param array $formValues
390 * Values from the export options form on contact export. We currently support these keys
393 * - addresee_greeting
396 public function __construct($exportMode, $requestedFields, $queryOperator, $isMergeSameHousehold = FALSE, $isPostalableOnly = FALSE, $isMergeSameAddress = FALSE, $formValues = []) {
397 $this->setExportMode($exportMode);
398 $this->setQueryMode();
399 $this->setQueryOperator($queryOperator);
400 $this->setRequestedFields($requestedFields);
401 $this->setRelationshipTypes();
402 $this->setIsMergeSameHousehold($isMergeSameHousehold ||
$isMergeSameAddress);
403 $this->setIsPostalableOnly($isPostalableOnly);
404 $this->setIsMergeSameAddress($isMergeSameAddress);
405 $this->setReturnProperties($this->determineReturnProperties());
406 $this->setAdditionalFieldsForSameAddressMerge();
407 $this->setAdditionalFieldsForPostalExport();
408 $this->setHouseholdMergeReturnProperties();
409 $this->setGreetingStringsForSameAddressMerge($formValues);
410 $this->setGreetingOptions();
414 * Set the greeting options, if relevant.
416 public function setGreetingOptions() {
417 if ($this->isMergeSameAddress()) {
418 $this->greetingOptions
['addressee'] = CRM_Core_OptionGroup
::values('addressee');
419 $this->greetingOptions
['postal_greeting'] = CRM_Core_OptionGroup
::values('postal_greeting');
426 public function isPostalableOnly() {
427 return $this->isPostalableOnly
;
431 * @param bool $isPostalableOnly
433 public function setIsPostalableOnly($isPostalableOnly) {
434 $this->isPostalableOnly
= $isPostalableOnly;
440 public function getRequestedFields() {
441 return empty($this->requestedFields
) ?
NULL : $this->requestedFields
;
445 * @param array|null $requestedFields
447 public function setRequestedFields($requestedFields) {
448 $this->requestedFields
= $requestedFields;
454 public function getReturnProperties() {
455 return array_merge($this->returnProperties
, $this->getAdditionalRequestedReturnProperties(), $this->getAdditionalFieldsForSameAddressMerge(), $this->getAdditionalFieldsForPostalExport());
459 * @param array $returnProperties
461 public function setReturnProperties($returnProperties) {
462 $this->returnProperties
= $returnProperties;
468 public function getRelationshipTypes() {
469 return $this->relationshipTypes
;
474 public function setRelationshipTypes() {
475 $this->relationshipTypes
= CRM_Contact_BAO_Relationship
::getContactRelationshipType(
487 * Set the value for a relationship type field.
489 * In this case we are building up an array of properties for a related contact.
491 * These may be used for direct exporting or for merge to household depending on the
494 * @param string $relationshipType
495 * @param int $contactID
496 * @param string $field
497 * @param string $value
499 public function setRelationshipValue($relationshipType, $contactID, $field, $value) {
500 $this->relatedContactValues
[$relationshipType][$contactID][$field] = $value;
501 if ($field === 'id' && $this->isHouseholdMergeRelationshipTypeKey($relationshipType)) {
502 $this->householdsToSkip
[] = $value;
507 * Get the value for a relationship type field.
509 * In this case we are building up an array of properties for a related contact.
511 * These may be used for direct exporting or for merge to household depending on the
514 * @param string $relationshipType
515 * @param int $contactID
516 * @param string $field
520 public function getRelationshipValue($relationshipType, $contactID, $field) {
521 return $this->relatedContactValues
[$relationshipType][$contactID][$field] ??
'';
525 * Get the id of the related household.
527 * @param int $contactID
528 * @param string $relationshipType
532 public function getRelatedHouseholdID($contactID, $relationshipType) {
533 return $this->relatedContactValues
[$relationshipType][$contactID]['id'];
537 * Has the household already been exported.
539 * @param int $housholdContactID
543 public function isHouseholdExported($housholdContactID) {
544 return isset($this->exportedHouseholds
[$housholdContactID]);
551 public function isMergeSameHousehold() {
552 return $this->isMergeSameHousehold
;
556 * @param bool $isMergeSameHousehold
558 public function setIsMergeSameHousehold($isMergeSameHousehold) {
559 $this->isMergeSameHousehold
= $isMergeSameHousehold;
563 * Return relationship types for household merge.
567 public function getHouseholdRelationshipTypes() {
568 if (!$this->isMergeSameHousehold()) {
572 CRM_Utils_Array
::key('Household Member of', $this->getRelationshipTypes()),
573 CRM_Utils_Array
::key('Head of Household for', $this->getRelationshipTypes()),
581 public function isRelationshipTypeKey($fieldName) {
582 return array_key_exists($fieldName, $this->relationshipTypes
);
589 public function isHouseholdMergeRelationshipTypeKey($fieldName) {
590 return in_array($fieldName, $this->getHouseholdRelationshipTypes());
596 public function getQueryOperator() {
597 return $this->queryOperator
;
601 * @param string $queryOperator
603 public function setQueryOperator($queryOperator) {
604 $this->queryOperator
= $queryOperator;
610 public function getIds() {
617 public function setIds($ids) {
624 public function getQueryFields() {
627 $this->getComponentPaymentFields()
632 * @param array $queryFields
634 public function setQueryFields($queryFields) {
635 // legacy hacks - we add these to queryFields because this
636 // pseudometadata is currently required.
637 $queryFields['im_provider']['pseudoconstant']['var'] = 'imProviders';
638 $queryFields['country']['context'] = 'country';
639 $queryFields['world_region']['context'] = 'country';
640 $queryFields['state_province']['context'] = 'province';
641 $queryFields['contact_id'] = ['title' => ts('Contact ID'), 'type' => CRM_Utils_Type
::T_INT
];
642 $queryFields['tags']['type'] = CRM_Utils_Type
::T_LONGTEXT
;
643 $queryFields['groups']['type'] = CRM_Utils_Type
::T_LONGTEXT
;
644 $queryFields['notes']['type'] = CRM_Utils_Type
::T_LONGTEXT
;
645 // Set the label to gender for gender_id as we it's ... magic (not in a good way).
646 // In other places the query object offers e.g contribution_status & contribution_status_id
647 $queryFields['gender_id']['title'] = ts('Gender');
648 $this->queryFields
= $queryFields;
654 public function getQueryMode() {
655 return $this->queryMode
;
659 * Set the query mode based on the export mode.
661 public function setQueryMode() {
663 switch ($this->getExportMode()) {
664 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
665 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
668 case CRM_Export_Form_Select
::EVENT_EXPORT
:
669 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_EVENT
;
672 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
673 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_MEMBER
;
676 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
677 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_PLEDGE
;
680 case CRM_Export_Form_Select
::CASE_EXPORT
:
681 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_CASE
;
684 case CRM_Export_Form_Select
::GRANT_EXPORT
:
685 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_GRANT
;
688 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
689 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
693 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_CONTACTS
;
700 public function getExportMode() {
701 return $this->exportMode
;
705 * @param int $exportMode
707 public function setExportMode($exportMode) {
708 $this->exportMode
= $exportMode;
712 * Get the name for the export file.
716 public function getExportFileName() {
717 switch ($this->getExportMode()) {
718 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
719 return ts('CiviCRM Contact Search');
721 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
722 return ts('CiviCRM Contribution Search');
724 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
725 return ts('CiviCRM Member Search');
727 case CRM_Export_Form_Select
::EVENT_EXPORT
:
728 return ts('CiviCRM Participant Search');
730 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
731 return ts('CiviCRM Pledge Search');
733 case CRM_Export_Form_Select
::CASE_EXPORT
:
734 return ts('CiviCRM Case Search');
736 case CRM_Export_Form_Select
::GRANT_EXPORT
:
737 return ts('CiviCRM Grant Search');
739 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
740 return ts('CiviCRM Activity Search');
743 // Legacy code suggests the value could be 'financial' - ie. something
744 // other than what should be accepted. However, I suspect that this line is
746 return ts('CiviCRM Search');
751 * Get the label for the header row based on the field to output.
753 * @param string $field
757 public function getHeaderForRow($field) {
758 if (substr($field, -11) === 'campaign_id') {
759 // @todo - set this correctly in the xml rather than here.
760 // This will require a generalised handling cleanup
761 return ts('Campaign ID');
763 if ($this->isMergeSameHousehold() && !$this->isMergeSameAddress() && $field === 'id') {
764 // This is weird - even if we are merging households not every contact in the export is a household so this would not be accurate.
765 return ts('Household ID');
767 elseif (isset($this->getQueryFields()[$field]['title'])) {
768 return $this->getQueryFields()[$field]['title'];
770 elseif ($this->isExportPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
771 return CRM_Utils_Array
::value($field, $this->getcomponentPaymentFields())['title'];
784 public function runQuery($params, $order) {
785 $returnProperties = $this->getReturnProperties();
786 $params = array_merge($params, $this->getWhereParams());
788 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
789 FALSE, FALSE, $this->getQueryMode(),
790 FALSE, TRUE, TRUE, NULL, $this->getQueryOperator(),
796 $query->_sort
= $order;
797 [$select, $from, $where, $having] = $query->query();
798 $this->setQueryFields($query->_fields
);
799 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
800 if ($this->getComponentClause()) {
801 $whereClauses[] = $this->getComponentClause();
803 elseif ($this->getRequestedFields() && $this->getComponentTable() && $this->getComponentTable() !== 'civicrm_contact') {
804 $from .= " INNER JOIN " . $this->getComponentTable() . " ctTable ON ctTable.contact_id = contact_a.id ";
807 // CRM-13982 - check if is deleted
808 foreach ($params as $value) {
809 if ($value[0] === 'contact_is_deleted') {
810 unset($whereClauses['trash_clause']);
814 if ($this->isPostalableOnly
) {
815 if (array_key_exists('street_address', $returnProperties)) {
816 $addressWhere = " civicrm_address.street_address <> ''";
817 if (array_key_exists('supplemental_address_1', $returnProperties)) {
818 // We need this to be an OR rather than AND on the street_address so, hack it in.
819 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
820 'address_options', TRUE, NULL, TRUE
822 if (!empty($addressOptions['supplemental_address_1'])) {
823 $addressWhere .= " OR civicrm_address.supplemental_address_1 <> ''";
826 $whereClauses['address'] = '(' . $addressWhere . ')';
831 $where = 'WHERE ' . implode(' AND ', $whereClauses);
834 $where .= ' AND ' . implode(' AND ', $whereClauses);
837 $groupBy = $this->getGroupBy($query);
838 $queryString = "$select $from $where $having $groupBy";
840 // always add contact_a.id to the ORDER clause
841 // so the order is deterministic
843 if (strpos('contact_a.id', $order) === FALSE) {
844 $order .= ", contact_a.id";
847 [$field, $dir] = explode(' ', $order, 2);
848 $field = trim($field);
849 if (!empty($this->getReturnProperties()[$field])) {
851 $queryString .= " ORDER BY $order";
854 return [$query, $queryString];
858 * Add a row to the specification for how to output data.
861 * @param string $relationshipType
862 * @param string $locationType
863 * @param int $entityTypeID phone_type_id or provider_id for phone or im fields.
865 public function addOutputSpecification($key, $relationshipType = NULL, $locationType = NULL, $entityTypeID = NULL) {
868 if ($key === 'phone') {
869 $entityLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $entityTypeID);
872 $entityLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_IM', 'provider_id', $entityTypeID);
876 // These oddly constructed keys are for legacy reasons. Altering them will affect test success
877 // but in time it may be good to rationalise them.
878 $label = $this->getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel);
879 $index = $this->getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityTypeID);
880 $fieldKey = $this->getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityTypeID);
882 $this->outputSpecification
[$index]['header'] = $label;
883 $this->outputSpecification
[$index]['sql_columns'] = $this->getSqlColumnDefinition($fieldKey, $key);
885 if ($relationshipType && $this->isHouseholdMergeRelationshipTypeKey($relationshipType)) {
886 $this->setColumnAsCalculationOnly($index);
888 $this->outputSpecification
[$index]['metadata'] = $this->getMetaDataForField($key);
892 * Get the metadata for the given field.
898 public function getMetaDataForField($key) {
899 $mappings = ['contact_id' => 'id'];
900 if (isset($this->getQueryFields()[$key])) {
901 return $this->getQueryFields()[$key];
903 if (isset($mappings[$key])) {
904 return $this->getQueryFields()[$mappings[$key]];
912 public function setSqlColumnDefn($key) {
913 $this->outputSpecification
[$this->getMungedFieldName($key)]['sql_columns'] = $this->getSqlColumnDefinition($key, $this->getMungedFieldName($key));
917 * Mark a column as only required for calculations.
919 * Do not include the row with headers.
921 * @param string $column
923 public function setColumnAsCalculationOnly($column) {
924 $this->outputSpecification
[$column]['do_not_output_to_csv'] = TRUE;
930 public function getHeaderRows() {
932 foreach ($this->outputSpecification
as $key => $spec) {
933 if (empty($spec['do_not_output_to_csv'])) {
934 $headerRows[] = $spec['header'];
943 public function getSQLColumns() {
945 foreach ($this->outputSpecification
as $key => $spec) {
946 if (empty($spec['do_not_output_to_sql'])) {
947 $sqlColumns[$key] = $spec['sql_columns'];
956 public function getMetadata() {
958 foreach ($this->outputSpecification
as $key => $spec) {
959 $metadata[$key] = $spec['metadata'];
965 * Build the row for output.
967 * @param \CRM_Contact_BAO_Query $query
968 * @param CRM_Core_DAO $iterationDAO
969 * @param array $outputColumns
970 * @param $paymentDetails
971 * @param $addPaymentHeader
975 public function buildRow($query, $iterationDAO, $outputColumns, $paymentDetails, $addPaymentHeader) {
976 $paymentTableId = $this->getPaymentTableID();
977 if ($this->isHouseholdToSkip($iterationDAO->contact_id
)) {
980 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
983 $householdMergeRelationshipType = $this->getHouseholdMergeTypeForRow($iterationDAO->contact_id
);
984 if ($householdMergeRelationshipType) {
985 $householdID = $this->getRelatedHouseholdID($iterationDAO->contact_id
, $householdMergeRelationshipType);
986 if ($this->isHouseholdExported($householdID)) {
989 foreach (array_keys($outputColumns) as $column) {
990 $row[$column] = $this->getRelationshipValue($householdMergeRelationshipType, $iterationDAO->contact_id
, $column);
992 $this->markHouseholdExported($householdID);
996 $query->convertToPseudoNames($iterationDAO);
998 //first loop through output columns so that we return what is required, and in same order.
999 foreach ($outputColumns as $field => $value) {
1000 // add im_provider to $dao object
1001 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
1002 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
1005 //build row values (data)
1007 if (property_exists($iterationDAO, $field)) {
1008 $fieldValue = $iterationDAO->$field;
1009 // to get phone type from phone type id
1010 if ($field == 'provider_id' ||
$field == 'im_provider') {
1011 $fieldValue = $imProviders[$fieldValue] ??
NULL;
1013 elseif (strstr($field, 'master_id')) {
1014 // @todo - why not just $field === 'master_id' - what else would it be?
1015 $masterAddressId = $iterationDAO->$field ??
NULL;
1016 // get display name of contact that address is shared.
1017 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
1021 if ($this->isRelationshipTypeKey($field)) {
1022 $this->buildRelationshipFieldsForRow($row, $iterationDAO->contact_id
, $value, $field);
1025 $row[$field] = $this->getTransformedFieldValue($field, $iterationDAO, $fieldValue, $paymentDetails);
1029 // If specific payment fields have been selected for export, payment
1030 // data will already be in $row. Otherwise, add payment related
1031 // information, if appropriate.
1032 if ($addPaymentHeader) {
1033 if (!$this->isExportSpecifiedPaymentFields()) {
1034 $nullContributionDetails = array_fill_keys(array_keys($this->getPaymentHeaders()), NULL);
1035 if ($this->isExportPaymentFields()) {
1036 $paymentData = $paymentDetails[$row[$paymentTableId]] ??
NULL;
1037 if (!is_array($paymentData) ||
empty($paymentData)) {
1038 $paymentData = $nullContributionDetails;
1040 $row = array_merge($row, $paymentData);
1042 elseif (!empty($paymentDetails)) {
1043 $row = array_merge($row, $nullContributionDetails);
1047 //remove organization name for individuals if it is set for current employer
1048 if (!empty($row['contact_type']) &&
1049 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1051 $row['organization_name'] = '';
1057 * If this row has a household whose details we should use get the relationship type key.
1063 public function getHouseholdMergeTypeForRow($contactID) {
1064 if (!$this->isMergeSameHousehold()) {
1067 foreach ($this->getHouseholdRelationshipTypes() as $relationshipType) {
1068 if (isset($this->relatedContactValues
[$relationshipType][$contactID])) {
1069 return $relationshipType;
1075 * Mark the given household as already exported.
1077 * @param $householdID
1079 public function markHouseholdExported($householdID) {
1080 $this->exportedHouseholds
[$householdID] = $householdID;
1085 * @param $iterationDAO
1086 * @param $fieldValue
1087 * @param $paymentDetails
1090 * @throws \CRM_Core_Exception
1091 * @throws \CiviCRM_API3_Exception
1093 public function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $paymentDetails) {
1095 $i18n = CRM_Core_I18n
::singleton();
1096 if ($field == 'id') {
1097 return $iterationDAO->contact_id
;
1098 // special case for calculated field
1100 elseif ($field == 'source_contact_id') {
1101 return $iterationDAO->contact_id
;
1103 elseif ($field == 'pledge_balance_amount') {
1104 return $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
1105 // special case for calculated field
1107 elseif ($field == 'pledge_next_pay_amount') {
1108 return $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
1110 elseif (isset($fieldValue) &&
1113 //check for custom data
1114 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
1115 $html_type = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'html_type');
1117 //need to calculate the link to the file for file custom data
1118 if ($html_type === 'File' && $fieldValue) {
1119 $result = civicrm_api3('attachment', 'get', ['return' => ['url'], 'id' => $fieldValue]);
1120 return $result['values'][$result['id']]['url'];
1123 // Do not export HTML markup for links
1124 if ($html_type === 'Link' && $fieldValue) {
1128 return CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1130 elseif (in_array($field, [
1135 //special case for greeting replacement
1136 $fldValue = "{$field}_display";
1137 return $iterationDAO->$fldValue;
1140 //normal fields with a touch of CRM-3157
1143 case 'world_region':
1144 return $i18n->crm_translate($fieldValue, ['context' => 'country']);
1146 case 'state_province':
1147 return $i18n->crm_translate($fieldValue, ['context' => 'province']);
1150 case 'preferred_communication_method':
1151 case 'preferred_mail_format':
1152 case 'communication_style':
1153 return $i18n->crm_translate($fieldValue);
1156 $fieldSpec = $this->outputSpecification
[$this->getMungedFieldName($field)]['metadata'];
1157 // No I don't know why we do it this way & whether we could
1158 // make better use of pseudoConstants.
1159 if (!empty($fieldSpec['context'])) {
1160 return $i18n->crm_translate($fieldValue, $fieldSpec);
1162 if (!empty($fieldSpec['pseudoconstant']) && !empty($fieldSpec['hasLocationType']) && $fieldSpec['name'] !== 'phone_type_id') {
1163 if (!empty($fieldSpec['bao'])) {
1164 $transformedValue = CRM_Core_PseudoConstant
::getLabel($fieldSpec['bao'], $fieldSpec['name'], $fieldValue);
1165 if ($transformedValue) {
1166 return $transformedValue;
1170 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1171 // but I have to reach a stable point....
1172 $varName = $fieldSpec['pseudoconstant']['var'];
1173 if ($varName === 'imProviders') {
1174 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
1181 elseif ($this->isExportSpecifiedPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
1182 $paymentTableId = $this->getPaymentTableID();
1183 $paymentData = $paymentDetails[$iterationDAO->$paymentTableId] ??
NULL;
1185 'componentPaymentField_total_amount' => 'total_amount',
1186 'componentPaymentField_contribution_status' => 'contribution_status',
1187 'componentPaymentField_payment_instrument' => 'pay_instru',
1188 'componentPaymentField_transaction_id' => 'trxn_id',
1189 'componentPaymentField_received_date' => 'receive_date',
1191 return CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1194 // if field is empty or null
1200 * Get array of fields to return, over & above those defined in the main contact exportable fields.
1202 * These include export mode specific fields & some fields apparently required as 'exportableFields'
1203 * but not returned by the function of the same name.
1206 * Array of fields to return in the format ['field_name' => 1,...]
1208 public function getAdditionalReturnProperties() {
1209 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
1210 $componentSpecificFields = [];
1213 $componentSpecificFields = CRM_Contact_BAO_Query
::defaultReturnProperties($this->getQueryMode());
1215 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_PLEDGE
) {
1216 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Pledge_BAO_Query
::extraReturnProperties($this->getQueryMode()));
1217 unset($componentSpecificFields['contribution_status_id']);
1218 unset($componentSpecificFields['pledge_status_id']);
1219 unset($componentSpecificFields['pledge_payment_status_id']);
1221 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CASE
) {
1222 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Case_BAO_Query
::extraReturnProperties($this->getQueryMode()));
1224 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
1225 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
1226 unset($componentSpecificFields['contribution_status_id']);
1228 return $componentSpecificFields;
1232 * Should payment fields be appended to the export.
1234 * (This is pretty hacky so hopefully this function won't last long - notice
1235 * how obviously it should be part of the above function!).
1237 public function isExportPaymentFields() {
1238 if ($this->getRequestedFields() === NULL
1239 && in_array($this->getQueryMode(), [
1240 CRM_Contact_BAO_Query
::MODE_EVENT
,
1241 CRM_Contact_BAO_Query
::MODE_MEMBER
,
1242 CRM_Contact_BAO_Query
::MODE_PLEDGE
,
1246 elseif ($this->isExportSpecifiedPaymentFields()) {
1253 * Has specific payment fields been requested (as opposed to via all fields).
1255 * If specific fields have been requested then they get added at various points.
1259 public function isExportSpecifiedPaymentFields() {
1260 if ($this->getRequestedFields() !== NULL && $this->hasRequestedComponentPaymentFields()) {
1266 * Get the name of the id field in the table that connects contributions to the export entity.
1268 public function getPaymentTableID() {
1269 if ($this->getRequestedFields() === NULL) {
1271 CRM_Contact_BAO_Query
::MODE_EVENT
=> 'participant_id',
1272 CRM_Contact_BAO_Query
::MODE_MEMBER
=> 'membership_id',
1273 CRM_Contact_BAO_Query
::MODE_PLEDGE
=> 'pledge_payment_id',
1275 return isset($mapping[$this->getQueryMode()]) ?
$mapping[$this->getQueryMode()] : '';
1277 elseif ($this->hasRequestedComponentPaymentFields()) {
1278 return 'participant_id';
1284 * Have component payment fields been requested.
1288 protected function hasRequestedComponentPaymentFields() {
1289 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_EVENT
) {
1290 $participantPaymentFields = array_intersect_key($this->getComponentPaymentFields(), $this->getReturnProperties());
1291 if (!empty($participantPaymentFields)) {
1299 * Get fields that indicate payment fields have been requested for a component.
1301 * Ideally this should be protected but making it temporarily public helps refactoring..
1305 public function getComponentPaymentFields() {
1307 'componentPaymentField_total_amount' => ['title' => ts('Total Amount'), 'type' => CRM_Utils_Type
::T_MONEY
],
1308 'componentPaymentField_contribution_status' => ['title' => ts('Contribution Status'), 'type' => CRM_Utils_Type
::T_STRING
],
1309 'componentPaymentField_received_date' => ['title' => ts('Date Received'), 'type' => CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
],
1310 'componentPaymentField_payment_instrument' => ['title' => ts('Payment Method'), 'type' => CRM_Utils_Type
::T_STRING
],
1311 'componentPaymentField_transaction_id' => ['title' => ts('Transaction ID'), 'type' => CRM_Utils_Type
::T_STRING
],
1316 * Get headers for payment fields.
1318 * Returns an array of contribution fields when the entity supports payment fields and specific fields
1319 * are not specified. This is a transitional function for refactoring legacy code.
1321 public function getPaymentHeaders() {
1322 if ($this->isExportPaymentFields() && !$this->isExportSpecifiedPaymentFields()) {
1323 return CRM_Utils_Array
::collect('title', $this->getcomponentPaymentFields());
1329 * Get the default properties when not specified.
1331 * In the UI this appears as 'Primary fields only' but in practice it's
1332 * most of the kitchen sink and the hallway closet thrown in.
1334 * Since CRM-952 custom fields are excluded, but no other form of mercy is shown.
1338 public function getDefaultReturnProperties() {
1339 $returnProperties = [];
1340 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
1341 $skippedFields = ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CONTACTS
) ?
[] : [
1347 foreach ($fields as $key => $var) {
1348 if ($key && (substr($key, 0, 6) != 'custom') && !in_array($key, $skippedFields)) {
1349 $returnProperties[$key] = 1;
1352 $returnProperties = array_merge($returnProperties, $this->getAdditionalReturnProperties());
1353 return $returnProperties;
1357 * Add the field to relationship return properties & return it.
1359 * This function is doing both setting & getting which is yuck but it is an interim
1362 * @param array $value
1363 * @param string $relationshipKey
1367 public function setRelationshipReturnProperties($value, $relationshipKey) {
1368 $relationField = $value['name'];
1369 $relIMProviderId = NULL;
1370 $relLocTypeId = $value['location_type_id'] ??
NULL;
1371 $locationName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_Address', 'location_type_id', $relLocTypeId);
1372 $relPhoneTypeId = CRM_Utils_Array
::value('phone_type_id', $value, ($locationName ?
'Primary' : NULL));
1373 $relIMProviderId = CRM_Utils_Array
::value('im_provider_id', $value, ($locationName ?
'Primary' : NULL));
1374 if (in_array($relationField, $this->getValidLocationFields()) && $locationName) {
1375 if ($relationField === 'phone') {
1376 $this->relationshipReturnProperties
[$relationshipKey]['location'][$locationName]['phone-' . $relPhoneTypeId] = 1;
1378 elseif ($relationField === 'im') {
1379 $this->relationshipReturnProperties
[$relationshipKey]['location'][$locationName]['im-' . $relIMProviderId] = 1;
1382 $this->relationshipReturnProperties
[$relationshipKey]['location'][$locationName][$relationField] = 1;
1386 $this->relationshipReturnProperties
[$relationshipKey][$relationField] = 1;
1388 return $this->relationshipReturnProperties
[$relationshipKey];
1392 * Add the main return properties to the household merge properties if needed for merging.
1394 * If we are using household merge we need to add these to the relationship properties to
1397 public function setHouseholdMergeReturnProperties() {
1398 if ($this->isMergeSameHousehold()) {
1399 $returnProperties = $this->getReturnProperties();
1400 $returnProperties = array_diff_key($returnProperties, array_fill_keys(['location_type', 'im_provider'], 1));
1401 foreach ($this->getHouseholdRelationshipTypes() as $householdRelationshipType) {
1402 $this->relationshipReturnProperties
[$householdRelationshipType] = $returnProperties;
1408 * Get the default location fields to request.
1412 public function getValidLocationFields() {
1415 'supplemental_address_1',
1416 'supplemental_address_2',
1417 'supplemental_address_3',
1420 'postal_code_suffix',
1432 * Get the sql column definition for the given field.
1434 * @param string $fieldName
1435 * @param string $columnName
1439 public function getSqlColumnDefinition($fieldName, $columnName) {
1441 // early exit for master_id, CRM-12100
1442 // in the DB it is an ID, but in the export, we retrieve the display_name of the master record
1443 if ($columnName === 'master_id') {
1444 return "`$fieldName` varchar(128)";
1447 $queryFields = $this->getQueryFields();
1448 // @todo remove the e-notice avoidance here, ensure all columns are declared.
1449 // tests will fail on the enotices until they all are & then all the 'else'
1451 $fieldSpec = $queryFields[$columnName] ??
[];
1452 $type = $fieldSpec['type'] ??
($fieldSpec['data_type'] ??
'');
1453 // set the sql columns
1456 case CRM_Utils_Type
::T_INT
:
1457 case CRM_Utils_Type
::T_BOOLEAN
:
1458 if (in_array(CRM_Utils_Array
::value('data_type', $fieldSpec), ['Country', 'StateProvince', 'ContactReference'])) {
1459 return "`$fieldName` varchar(255)";
1461 // some of those will be exported as a (localisable) string
1462 // @see https://lab.civicrm.org/dev/core/-/issues/2164
1463 return "`$fieldName` varchar(64)";
1465 case CRM_Utils_Type
::T_STRING
:
1466 if (isset($fieldSpec['maxlength'])) {
1467 // A localized string for the preferred_mail_format does not fit
1468 // into the varchar(8) field.
1469 // @see https://lab.civicrm.org/dev/core/-/issues/2645
1470 switch ($fieldName) {
1471 case 'preferred_mail_format':
1472 return "`$fieldName` text(16)";
1475 return "`$fieldName` varchar({$fieldSpec['maxlength']})";
1478 $dataType = $fieldSpec['data_type'] ??
'';
1479 // set the sql columns for custom data
1480 switch ($dataType) {
1482 // May be option labels, which could be up to 512 characters
1483 $length = max(512, CRM_Utils_Array
::value('text_length', $fieldSpec));
1484 return "`$fieldName` varchar($length)";
1487 return "`$fieldName` text";
1490 return "`$fieldName` varchar(255)";
1493 case CRM_Utils_Type
::T_TEXT
:
1494 case CRM_Utils_Type
::T_LONGTEXT
:
1495 case CRM_Utils_Type
::T_BLOB
:
1496 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1497 return "`$fieldName` longtext";
1499 case CRM_Utils_Type
::T_FLOAT
:
1500 case CRM_Utils_Type
::T_ENUM
:
1501 case CRM_Utils_Type
::T_DATE
:
1502 case CRM_Utils_Type
::T_TIME
:
1503 case CRM_Utils_Type
::T_TIMESTAMP
:
1504 case CRM_Utils_Type
::T_MONEY
:
1505 case CRM_Utils_Type
::T_EMAIL
:
1506 case CRM_Utils_Type
::T_URL
:
1507 case CRM_Utils_Type
::T_CCNUM
:
1509 return "`$fieldName` varchar(32)";
1513 if (substr($fieldName, -3, 3) === '_id') {
1514 return "`$fieldName` varchar(255)";
1516 return "`$fieldName` text";
1521 * Get the munged field name.
1523 * @param string $field
1526 public function getMungedFieldName($field) {
1527 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1528 if ($fieldName == 'id') {
1529 $fieldName = 'civicrm_primary_id';
1535 * In order to respect the history of this class we need to index kinda illogically.
1537 * On the bright side - this stuff is tested within a nano-byte of it's life.
1539 * e.g '2-a-b_Home-City'
1541 * @param string $key
1542 * @param string $relationshipType
1543 * @param string $locationType
1544 * @param $entityLabel
1548 protected function getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityLabel) {
1549 if (!$relationshipType ||
$key !== 'id') {
1550 $key = $this->getMungedFieldName($key);
1552 return $this->getMungedFieldName(
1553 ($relationshipType ?
($relationshipType . '_') : '')
1554 . ($locationType ?
($locationType . '_') : '')
1556 . ($entityLabel ?
('_' . $entityLabel) : '')
1561 * Get the compiled label for the column.
1563 * e.g 'Gender', 'Employee Of-Home-city'
1565 * @param string $key
1566 * @param string $relationshipType
1567 * @param string $locationType
1568 * @param string $entityLabel
1572 protected function getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel) {
1573 return ($relationshipType ?
$this->getRelationshipTypes()[$relationshipType] . '-' : '')
1574 . ($locationType ?
$locationType . '-' : '')
1575 . $this->getHeaderForRow($key)
1576 . ($entityLabel ?
'-' . $entityLabel : '');
1580 * Get the mysql field name key.
1582 * This key is locked in by tests but the reasons for the specific conventions -
1583 * ie. headings are used for keying fields in some cases, are likely
1584 * accidental rather than deliberate.
1586 * This key is used for the output sql array.
1588 * @param string $key
1589 * @param $relationshipType
1590 * @param $locationType
1591 * @param $entityLabel
1595 protected function getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityLabel) {
1596 if (!$relationshipType ||
$key !== 'id') {
1597 $key = $this->getMungedFieldName($key);
1599 $fieldKey = $this->getMungedFieldName(
1600 ($relationshipType ?
($relationshipType . '_') : '')
1601 . ($locationType ?
($locationType . '_') : '')
1603 . ($entityLabel ?
('_' . $entityLabel) : '')
1609 * Get params for the where criteria.
1613 public function getWhereParams() {
1614 if (!$this->isPostalableOnly()) {
1617 $params['is_deceased'] = ['is_deceased', '=', 0, CRM_Contact_BAO_Query
::MODE_CONTACTS
];
1618 $params['do_not_mail'] = ['do_not_mail', '=', 0, CRM_Contact_BAO_Query
::MODE_CONTACTS
];
1628 protected function buildRelationshipFieldsForRow(&$row, $contactID, $value, $field) {
1629 foreach (array_keys($value) as $property) {
1630 if ($property === 'location') {
1631 // @todo just undo all this nasty location wrangling!
1632 foreach ($value['location'] as $locationKey => $locationFields) {
1633 foreach (array_keys($locationFields) as $locationField) {
1634 $fieldKey = str_replace(' ', '_', $locationKey . '-' . $locationField);
1635 $row[$field . '_' . $fieldKey] = $this->getRelationshipValue($field, $contactID, $fieldKey);
1640 $row[$field . '_' . $property] = $this->getRelationshipValue($field, $contactID, $property);
1646 * Is this contact a household that is already set to be exported by virtue of it's household members.
1648 * @param int $contactID
1652 protected function isHouseholdToSkip($contactID) {
1653 return in_array($contactID, $this->householdsToSkip
);
1657 * Get the various arrays that we use to structure our output.
1659 * The extraction of these has been moved to a separate function for clarity and so that
1660 * tests can be added - in particular on the $outputHeaders array.
1662 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1663 * as a step on the refactoring path rather than how it should be.
1666 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1667 * alias for the field generated by BAO_Query object.
1668 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1669 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1670 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1671 * I'm too embarassed to discuss here.
1673 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1674 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1675 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1676 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1677 * - a) the function used is more efficient or
1678 * - b) this code is old & outdated. Submit your answers to circular bin or better
1679 * yet find a way to comment them for posterity.
1681 public function getExportStructureArrays() {
1682 $outputColumns = [];
1683 $queryFields = $this->getQueryFields();
1684 foreach ($this->getReturnProperties() as $key => $value) {
1685 if (($key != 'location' ||
!is_array($value)) && !$this->isRelationshipTypeKey($key)) {
1686 $outputColumns[$key] = $value;
1687 $this->addOutputSpecification($key);
1689 elseif ($this->isRelationshipTypeKey($key)) {
1690 $outputColumns[$key] = $value;
1691 foreach ($value as $relationField => $relationValue) {
1692 // below block is same as primary block (duplicate)
1693 if (isset($queryFields[$relationField]['title'])) {
1694 $this->addOutputSpecification($relationField, $key);
1696 elseif (is_array($relationValue) && $relationField == 'location') {
1697 // fix header for location type case
1698 foreach ($relationValue as $ltype => $val) {
1699 foreach (array_keys($val) as $fld) {
1700 $type = explode('-', $fld);
1701 $this->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array
::value(1, $type));
1708 foreach ($value as $locationType => $locationFields) {
1709 foreach (array_keys($locationFields) as $locationFieldName) {
1710 $type = explode('-', $locationFieldName);
1712 $actualDBFieldName = $type[0];
1713 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1715 if (!empty($type[1])) {
1716 $daoFieldName .= "-" . $type[1];
1718 $this->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array
::value(1, $type));
1719 $outputColumns[$daoFieldName] = TRUE;
1724 return [$outputColumns];
1728 * Get default return property for export based on mode
1731 * Default Return property
1733 public function defaultReturnProperty() {
1734 // hack to add default return property based on export mode
1736 $exportMode = $this->getExportMode();
1737 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
1738 $property = 'contribution_id';
1740 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1741 $property = 'participant_id';
1743 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1744 $property = 'membership_id';
1746 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1747 $property = 'pledge_id';
1749 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1750 $property = 'case_id';
1752 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
1753 $property = 'grant_id';
1755 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1756 $property = 'activity_id';
1762 * Determine the required return properties from the input parameters.
1766 public function determineReturnProperties() {
1767 if ($this->getRequestedFields()) {
1768 $returnProperties = [];
1769 foreach ($this->getRequestedFields() as $key => $value) {
1770 $fieldName = $value['name'];
1771 $locationName = !empty($value['location_type_id']) ? CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_Address', 'location_type_id', $value['location_type_id']) : NULL;
1772 $relationshipTypeKey = !empty($value['relationship_type_id']) ?
$value['relationship_type_id'] . '_' . $value['relationship_direction'] : NULL;
1773 if (!$fieldName ||
$this->isHouseholdMergeRelationshipTypeKey($relationshipTypeKey)) {
1777 if ($this->isRelationshipTypeKey($relationshipTypeKey)) {
1778 $returnProperties[$relationshipTypeKey] = $this->setRelationshipReturnProperties($value, $relationshipTypeKey);
1780 elseif ($locationName) {
1781 if ($fieldName === 'phone') {
1782 $returnProperties['location'][$locationName]['phone-' . $value['phone_type_id'] ??
NULL] = 1;
1784 elseif ($fieldName === 'im') {
1785 $returnProperties['location'][$locationName]['im-' . $value['im_provider_id'] ??
NULL] = 1;
1788 $returnProperties['location'][$locationName][$fieldName] = 1;
1792 //hack to fix component fields
1793 //revert mix of event_id and title
1794 if ($fieldName == 'event_id') {
1795 $returnProperties['event_id'] = 1;
1798 $returnProperties[$fieldName] = 1;
1802 $defaultExportMode = $this->defaultReturnProperty();
1803 if ($defaultExportMode) {
1804 $returnProperties[$defaultExportMode] = 1;
1808 $returnProperties = $this->getDefaultReturnProperties();
1810 if ($this->isMergeSameHousehold()) {
1811 $returnProperties['id'] = 1;
1813 if ($this->isMergeSameAddress()) {
1814 $returnProperties['addressee'] = 1;
1815 $returnProperties['postal_greeting'] = 1;
1816 $returnProperties['email_greeting'] = 1;
1817 $returnProperties['street_name'] = 1;
1818 $returnProperties['household_name'] = 1;
1819 $returnProperties['street_address'] = 1;
1820 $returnProperties['city'] = 1;
1821 $returnProperties['state_province'] = 1;
1824 return $returnProperties;
1828 * @param object $query
1829 * CRM_Contact_BAO_Query
1834 public function getGroupBy($query) {
1836 $returnProperties = $this->getReturnProperties();
1837 $exportMode = $this->getExportMode();
1838 $queryMode = $this->getQueryMode();
1839 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
1840 CRM_Utils_Array
::value('notes', $returnProperties) ||
1842 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
1844 $groupBy = "contact_a.id";
1847 switch ($exportMode) {
1848 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1849 $groupBy = 'civicrm_contribution.id';
1850 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
1851 // especial group by when soft credit columns are included
1852 $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
1856 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1857 $groupBy = 'civicrm_participant.id';
1860 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1861 $groupBy = "civicrm_membership.id";
1865 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
1866 $groupBy = "civicrm_activity.id ";
1869 return $groupBy ?
' GROUP BY ' . implode(', ', (array) $groupBy) : '';
1873 * Replace contact greetings in merged contacts.
1875 * @param int $contactID
1878 * @throws \API_Exception
1879 * @throws \CRM_Core_Exception
1881 public function replaceMergeTokens(int $contactID): array {
1882 $messageTemplate = [
1883 'postal_greeting' => $this->getPostalGreetingTemplate() ??
'',
1884 'addressee' => $this->getAddresseeGreetingTemplate() ??
'',
1886 if (array_filter($messageTemplate)) {
1887 return CRM_Core_TokenSmarty
::render($messageTemplate, ['contactId' => $contactID]);
1889 return $messageTemplate;
1893 * Build array for merging same addresses.
1895 * @param string $sql
1897 public function buildMasterCopyArray($sql) {
1900 $dao = CRM_Core_DAO
::executeQuery($sql);
1902 while ($dao->fetch()) {
1903 $masterID = $dao->master_id
;
1904 $copyID = $dao->copy_id
;
1906 $this->cacheContactGreetings((int) $dao->master_contact_id
);
1907 $this->cacheContactGreetings((int) $dao->copy_contact_id
);
1909 if (!isset($this->contactsToMerge
[$masterID])) {
1910 // check if this is an intermediate child
1911 // this happens if there are 3 or more matches a,b, c
1912 // the above query will return a, b / a, c / b, c
1913 // we might be doing a bit more work, but for now its ok, unless someone
1914 // knows how to fix the query above
1915 if (isset($parents[$masterID])) {
1916 $masterID = $parents[$masterID];
1919 $this->contactsToMerge
[$masterID] = [
1920 'addressee' => $this->getContactGreeting((int) $dao->master_contact_id
, 'addressee', $dao->master_addressee
),
1922 'postalGreeting' => $this->getContactGreeting((int) $dao->master_contact_id
, 'postal_greeting', $dao->master_postal_greeting
),
1924 $this->contactsToMerge
[$masterID]['emailGreeting'] = &$this->contactsToMerge
[$masterID]['postalGreeting'];
1927 $parents[$copyID] = $masterID;
1929 if (!array_key_exists($copyID, $this->contactsToMerge
[$masterID]['copy'])) {
1930 $copyPostalGreeting = $this->getContactPortionOfGreeting((int) $dao->copy_contact_id
, (int) $dao->copy_postal_greeting_id
, 'postal_greeting', $dao->copy_postal_greeting
);
1931 if ($copyPostalGreeting) {
1932 $this->contactsToMerge
[$masterID]['postalGreeting'] = "{$this->contactsToMerge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1933 // if there happens to be a duplicate, remove it
1934 $this->contactsToMerge
[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $this->contactsToMerge
[$masterID]['postalGreeting']);
1937 $copyAddressee = $this->getContactPortionOfGreeting((int) $dao->copy_contact_id
, (int) $dao->copy_addressee_id
, 'addressee', $dao->copy_addressee
);
1938 if ($copyAddressee) {
1939 $this->contactsToMerge
[$masterID]['addressee'] = "{$this->contactsToMerge[$masterID]['addressee']}, " . trim($copyAddressee);
1942 if (!isset($this->contactsToMerge
[$masterID]['copy'][$copyID])) {
1943 // If it was set in the first run through - share routine, don't subsequently clobber.
1944 $this->contactsToMerge
[$masterID]['copy'][$copyID] = $copyAddressee ??
$dao->copy_addressee
;
1950 * Merge contacts with the same address.
1952 public function mergeSameAddress() {
1954 $tableName = $this->getTemporaryTable();
1956 // find all the records that have the same street address BUT not in a household
1957 // require match on city and state as well
1959 SELECT r1.id as master_id,
1960 r1.civicrm_primary_id as master_contact_id,
1961 r1.postal_greeting as master_postal_greeting,
1962 r1.postal_greeting_id as master_postal_greeting_id,
1963 r1.addressee as master_addressee,
1964 r1.addressee_id as master_addressee_id,
1966 r2.civicrm_primary_id as copy_contact_id,
1967 r2.postal_greeting as copy_postal_greeting,
1968 r2.postal_greeting_id as copy_postal_greeting_id,
1969 r2.addressee as copy_addressee,
1970 r2.addressee_id as copy_addressee_id
1972 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1973 r1.city = r2.city AND
1974 r1.state_province_id = r2.state_province_id )
1975 WHERE ( r1.street_address != '' )
1979 $this->buildMasterCopyArray($sql);
1981 foreach ($this->contactsToMerge
as $masterID => $values) {
1984 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1988 1 => [CRM_Utils_String
::ellipsify($values['addressee'], 255), 'String'],
1989 2 => [$values['postalGreeting'], 'String'],
1990 3 => [$values['emailGreeting'], 'String'],
1991 4 => [$masterID, 'Integer'],
1993 CRM_Core_DAO
::executeQuery($sql, $params);
1995 // delete all copies
1996 $deleteIDs = array_keys($values['copy']);
1997 $deleteIDString = implode(',', $deleteIDs);
1999 DELETE FROM $tableName
2000 WHERE id IN ( $deleteIDString )
2002 CRM_Core_DAO
::executeQuery($sql);
2007 * The function unsets static part of the string, if token is the dynamic part.
2009 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
2010 * i.e 'Hello Alan' => converted to => 'Alan'
2012 * @param string $parsedString
2013 * @param string $defaultGreeting
2014 * @param string $greetingLabel
2018 public function trimNonTokensFromAddressString(
2019 &$parsedString, $defaultGreeting,
2022 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
2024 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
2025 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
2026 foreach ($stringsToBeReplaced as $key => $string) {
2027 // to keep one space
2028 $stringsToBeReplaced[$key] = ltrim($string);
2030 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
2032 return $parsedString;
2036 * Preview export output.
2041 public function getPreview($limit) {
2043 [$outputColumns] = $this->getExportStructureArrays();
2044 $query = $this->runQuery([], '');
2045 CRM_Core_DAO
::disableFullGroupByMode();
2046 $result = CRM_Core_DAO
::executeQuery($query[1] . ' LIMIT ' . (int) $limit);
2047 CRM_Core_DAO
::reenableFullGroupByMode();
2048 while ($result->fetch()) {
2049 $rows[] = $this->buildRow($query[0], $result, $outputColumns, [], []);
2055 * Set the template strings to be used when merging two contacts with the same address.
2057 * @param array $formValues
2058 * Values from first form. In this case we care about the keys
2061 * - address_greeting
2066 protected function setGreetingStringsForSameAddressMerge($formValues) {
2067 $greetingOptions = CRM_Export_Form_Select
::getGreetingOptions();
2069 if (!empty($greetingOptions)) {
2070 // Greeting options is keyed by 'postal_greeting' or 'addressee'.
2071 foreach ($greetingOptions as $key => $value) {
2072 $option = $formValues[$key] ??
NULL;
2074 if ($greetingOptions[$key][$option] == ts('Other')) {
2075 $formValues[$key] = $formValues["{$key}_other"];
2077 elseif ($greetingOptions[$key][$option] == ts('List of names')) {
2078 $formValues[$key] = '';
2081 $formValues[$key] = $greetingOptions[$key][$option];
2086 if (!empty($formValues['postal_greeting'])) {
2087 $this->setPostalGreetingTemplate($formValues['postal_greeting']);
2089 if (!empty($formValues['addressee'])) {
2090 $this->setAddresseeGreetingTemplate($formValues['addressee']);
2095 * Create the temporary table for output.
2097 public function createTempTable() {
2098 //creating a temporary table for the search result that need be exported
2099 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export');
2100 $sqlColumns = $this->getSQLColumns();
2101 // also create the sql table
2102 $exportTempTable->drop();
2104 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
2105 if (!empty($sqlColumns)) {
2106 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
2109 $sql .= "\n PRIMARY KEY ( id )";
2111 // add indexes for street_address and household_name if present
2115 'civicrm_primary_id',
2118 foreach ($addIndices as $index) {
2119 if (isset($sqlColumns[$index])) {
2121 INDEX index_{$index}( $index )
2126 $exportTempTable->createWithColumns($sql);
2127 $this->setTemporaryTable($exportTempTable->getName());
2131 * Get the values of linked household contact.
2133 * @param CRM_Core_DAO $relDAO
2134 * @param array $value
2135 * @param string $field
2138 * @throws \Exception
2140 public function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
2141 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
2142 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
2143 $i18n = CRM_Core_I18n
::singleton();
2144 $field = $field . '_';
2146 foreach ($value as $relationField => $relationValue) {
2147 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
2148 $fieldValue = $relDAO->$relationField;
2149 if ($relationField == 'provider_id') {
2150 $fieldValue = $imProviders[$relationValue] ??
NULL;
2153 elseif (is_object($relDAO) && in_array($relationField, [
2158 //special case for greeting replacement
2159 $fldValue = "{$relationField}_display";
2160 $fieldValue = $relDAO->$fldValue;
2163 elseif (is_object($relDAO) && $relationField == 'state_province') {
2164 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
2166 elseif (is_object($relDAO) && $relationField == 'country') {
2167 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
2172 $relPrefix = $field . $relationField;
2174 if (is_object($relDAO) && $relationField == 'id') {
2175 $row[$relPrefix] = $relDAO->contact_id
;
2177 elseif (is_array($relationValue) && $relationField == 'location') {
2178 foreach ($relationValue as $ltype => $val) {
2179 // If the location name has a space in it the we need to handle that. This
2180 // is kinda hacky but specifically covered in the ExportTest so later efforts to
2181 // improve it should be secure in the knowled it will be caught.
2182 $ltype = str_replace(' ', '_', $ltype);
2183 foreach (array_keys($val) as $fld) {
2184 $type = explode('-', $fld);
2185 $fldValue = "{$ltype}-" . $type[0];
2186 if (!empty($type[1])) {
2187 $fldValue .= "-" . $type[1];
2189 // CRM-3157: localise country, region (both have ‘country’ context)
2190 // and state_province (‘province’ context)
2192 case (!is_object($relDAO)):
2193 $row[$field . '_' . $fldValue] = '';
2196 case in_array('country', $type):
2197 case in_array('world_region', $type):
2198 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2199 ['context' => 'country']
2203 case in_array('state_province', $type):
2204 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2205 ['context' => 'province']
2210 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
2216 elseif (isset($fieldValue) && $fieldValue != '') {
2217 //check for custom data
2218 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
2219 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
2222 //normal relationship fields
2223 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
2224 switch ($relationField) {
2226 case 'world_region':
2227 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
2230 case 'state_province':
2231 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
2235 $row[$relPrefix] = $fieldValue;
2241 // if relation field is empty or null
2242 $row[$relPrefix] = '';
2248 * Write to the csv from the temp table.
2250 public function writeCSVFromTable() {
2252 $headerRows = $this->getHeaderRows();
2253 $exportTempTable = $this->getTemporaryTable();
2254 $exportMode = $this->getExportMode();
2255 $sqlColumns = $this->getSQLColumns();
2256 $componentTable = $this->getComponentTable();
2257 $ids = $this->getIds();
2258 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
2259 if ($exportMode !== $this->getExportMode() ||
$componentTable !== $this->getComponentTable()) {
2260 CRM_Core_Error
::deprecatedFunctionWarning('altering the export mode and/or component table in the hook is no longer supported.');
2262 if ($ids !== $this->getIds()) {
2263 CRM_Core_Error
::deprecatedFunctionWarning('altering the ids in the hook is no longer supported.');
2265 if ($exportTempTable !== $this->getTemporaryTable()) {
2266 CRM_Core_Error
::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
2267 $this->setTemporaryTable($exportTempTable);
2269 $exportTempTable = $this->getTemporaryTable();
2270 $writeHeader = TRUE;
2272 // increase this number a lot to avoid making too many queries
2273 // LIMIT is not much faster than a no LIMIT query
2277 $query = "SELECT * FROM $exportTempTable";
2279 $this->instantiateTempTable($headerRows);
2281 $limitQuery = $query . "
2282 LIMIT $offset, $limit
2284 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
2290 $componentDetails = [];
2291 while ($dao->fetch()) {
2294 foreach (array_keys($sqlColumns) as $column) {
2295 $row[$column] = $dao->$column;
2297 $componentDetails[] = $row;
2299 $this->writeRows($headerRows, $componentDetails);
2306 * Set up the temp table.
2308 * @param array $headerRows
2310 protected function instantiateTempTable(array $headerRows) {
2311 CRM_Utils_System
::download(CRM_Utils_String
::munge($this->getExportFileName()),
2313 CRM_Core_DAO
::$_nullObject,
2317 // Output UTF BOM so that MS Excel copes with diacritics. This is recommended as
2318 // the Windows variant but is tested with MS Excel for Mac (Office 365 v 16.31)
2319 // and it continues to work on Libre Office, Numbers, Notes etc.
2320 echo "\xEF\xBB\xBF";
2321 CRM_Core_Report_Excel
::makeCSVTable($headerRows, [], TRUE);
2325 * Write rows to the csv.
2327 * @param array $headerRows
2328 * @param array $rows
2330 protected function writeRows(array $headerRows, array $rows) {
2331 if (!empty($rows)) {
2332 CRM_Core_Report_Excel
::makeCSVTable($headerRows, $rows, FALSE);
2337 * Cache the greeting fields for the given contact.
2339 * @param int $contactID
2341 protected function cacheContactGreetings(int $contactID) {
2342 if (!isset($this->contactGreetingFields
[$contactID])) {
2343 $this->contactGreetingFields
[$contactID] = $this->replaceMergeTokens($contactID);
2348 * Get the greeting value for the given contact.
2350 * The values have already been cached so we are grabbing the value at this point.
2352 * @param int $contactID
2353 * @param string $type
2354 * postal_greeting|addressee|email_greeting
2355 * @param string $default
2359 protected function getContactGreeting(int $contactID, string $type, string $default): string {
2360 return empty($this->contactGreetingFields
[$contactID][$type]) ?
$default : $this->contactGreetingFields
[$contactID][$type];
2364 * Get the portion of the greeting string that relates to the contact.
2366 * For example if the greeting id 'Dear Sarah' we are going to combine it with 'Dear Mike'
2367 * so we want to strip the 'Dear ' and just get 'Sarah
2368 * @param int $contactID
2369 * @param int $greetingID
2370 * @param string $type
2371 * postal_greeting, addressee (email_greeting not currently implemented for unknown reasons.
2372 * @param string $defaultGreeting
2374 * @return mixed|string
2376 protected function getContactPortionOfGreeting(int $contactID, int $greetingID, string $type, string $defaultGreeting) {
2377 $copyPostalGreeting = $this->getContactGreeting($contactID, $type, $defaultGreeting);
2378 $template = $type === 'postal_greeting' ?
$this->getPostalGreetingTemplate() : $this->getAddresseeGreetingTemplate();
2379 if ($copyPostalGreeting) {
2380 $copyPostalGreeting = $this->trimNonTokensFromAddressString($copyPostalGreeting,
2381 $this->greetingOptions
[$type][$greetingID],
2385 return $copyPostalGreeting;