3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * Class CRM_Export_BAO_ExportProcessor
37 * Class to handle logic of export.
39 class CRM_Export_BAO_ExportProcessor
{
49 protected $exportMode;
52 * Array of fields in the main query.
56 protected $queryFields = [];
63 protected $queryOperator;
66 * Requested output fields.
68 * If set to NULL then it is 'primary fields only'
69 * which actually means pretty close to all fields!
73 protected $requestedFields;
76 * Is the contact being merged into a single household.
80 protected $isMergeSameHousehold;
83 * Should contacts with the same address be merged.
87 protected $isMergeSameAddress = FALSE;
90 * Fields that need to be retrieved for address merge purposes but should not be in output.
94 protected $additionalFieldsForSameAddressMerge = [];
97 * Fields used for merging same contacts.
101 protected $contactGreetingFields = [];
104 * Get additional non-visible fields for address merge purposes.
108 public function getAdditionalFieldsForSameAddressMerge(): array {
109 return $this->additionalFieldsForSameAddressMerge
;
113 * Set additional non-visible fields for address merge purposes.
115 public function setAdditionalFieldsForSameAddressMerge() {
116 if ($this->isMergeSameAddress
) {
117 $fields = ['id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'];
118 foreach ($fields as $index => $field) {
119 if (!empty($this->getReturnProperties()[$field])) {
120 unset($fields[$index]);
123 $this->additionalFieldsForSameAddressMerge
= array_fill_keys($fields, 1);
128 * Should contacts with the same address be merged.
132 public function isMergeSameAddress(): bool {
133 return $this->isMergeSameAddress
;
137 * Set same address is to be merged.
139 * @param bool $isMergeSameAddress
141 public function setIsMergeSameAddress(bool $isMergeSameAddress) {
142 $this->isMergeSameAddress
= $isMergeSameAddress;
146 * Additional fields required to export postal fields.
150 protected $additionalFieldsForPostalExport = [];
153 * Get additional fields required to do a postal export.
157 public function getAdditionalFieldsForPostalExport() {
158 return $this->additionalFieldsForPostalExport
;
162 * Set additional fields required for a postal export.
164 public function setAdditionalFieldsForPostalExport() {
165 if ($this->getRequestedFields() && $this->isPostalableOnly()) {
166 $fields = ['is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'];
167 foreach ($fields as $index => $field) {
168 if (!empty($this->getReturnProperties()[$field])) {
169 unset($field[$index]);
172 $this->additionalFieldsForPostalExport
= array_fill_keys($fields, 1);
177 * Only export contacts that can receive postal mail.
179 * Includes being alive, having an address & not having do_not_mail.
183 protected $isPostalableOnly;
186 * Key representing the head of household in the relationship array.
188 * e.g. ['8_b_a' => 'Household Member Is', '8_a_b = 'Household Member Of'.....]
192 protected $relationshipTypes = [];
195 * Array of properties to retrieve for relationships.
199 protected $relationshipReturnProperties = [];
202 * IDs of households that have already been exported.
206 protected $exportedHouseholds = [];
209 * Households to skip during export as they will be exported via their relationships anyway.
213 protected $householdsToSkip = [];
216 * Additional fields to return.
218 * This doesn't make much sense when we have a fields set but search build add it's own onto
219 * the 'Primary fields' (all) option.
223 protected $additionalRequestedReturnProperties = [];
226 * Get additional return properties.
230 public function getAdditionalRequestedReturnProperties() {
231 return $this->additionalRequestedReturnProperties
;
235 * Set additional return properties.
237 * @param array $value
239 public function setAdditionalRequestedReturnProperties($value) {
241 if (!empty($value['group'])) {
242 unset($value['group']);
243 $value['groups'] = 1;
245 $this->additionalRequestedReturnProperties
= $value;
249 * Get return properties by relationship.
252 public function getRelationshipReturnProperties() {
253 return $this->relationshipReturnProperties
;
257 * Export values for related contacts.
261 protected $relatedContactValues = [];
266 protected $returnProperties = [];
271 protected $outputSpecification = [];
276 protected $componentTable = '';
281 public function getComponentTable() {
282 return $this->componentTable
;
286 * Set the component table (if any).
288 * @param string $componentTable
290 public function setComponentTable($componentTable) {
291 $this->componentTable
= $componentTable;
295 * Clause from component search.
299 protected $componentClause = '';
304 public function getComponentClause() {
305 return $this->componentClause
;
309 * @param string $componentClause
311 public function setComponentClause($componentClause) {
312 $this->componentClause
= $componentClause;
316 * Name of a temporary table created to hold the results.
318 * Current decision making on when to create a temp table is kinda bad so this might change
319 * a bit as it is reviewed but basically we need a temp table or similar to calculate merging
320 * addresses. Merging households is handled in php. We create a temp table even when we don't need them.
324 protected $temporaryTable;
329 public function getTemporaryTable(): string {
330 return $this->temporaryTable
;
334 * @param string $temporaryTable
336 public function setTemporaryTable(string $temporaryTable) {
337 $this->temporaryTable
= $temporaryTable;
340 protected $postalGreetingTemplate;
345 public function getPostalGreetingTemplate() {
346 return $this->postalGreetingTemplate
;
350 * @param mixed $postalGreetingTemplate
352 public function setPostalGreetingTemplate($postalGreetingTemplate) {
353 $this->postalGreetingTemplate
= $postalGreetingTemplate;
359 public function getAddresseeGreetingTemplate() {
360 return $this->addresseeGreetingTemplate
;
364 * @param mixed $addresseeGreetingTemplate
366 public function setAddresseeGreetingTemplate($addresseeGreetingTemplate) {
367 $this->addresseeGreetingTemplate
= $addresseeGreetingTemplate;
370 protected $addresseeGreetingTemplate;
373 * CRM_Export_BAO_ExportProcessor constructor.
375 * @param int $exportMode
376 * @param array|null $requestedFields
377 * @param string $queryOperator
378 * @param bool $isMergeSameHousehold
379 * @param bool $isPostalableOnly
380 * @param bool $isMergeSameAddress
381 * @param array $formValues
382 * Values from the export options form on contact export. We currently support these keys
385 * - addresee_greeting
388 public function __construct($exportMode, $requestedFields, $queryOperator, $isMergeSameHousehold = FALSE, $isPostalableOnly = FALSE, $isMergeSameAddress = FALSE, $formValues = []) {
389 $this->setExportMode($exportMode);
390 $this->setQueryMode();
391 $this->setQueryOperator($queryOperator);
392 $this->setRequestedFields($requestedFields);
393 $this->setRelationshipTypes();
394 $this->setIsMergeSameHousehold($isMergeSameHousehold);
395 $this->setIsPostalableOnly($isPostalableOnly);
396 $this->setIsMergeSameAddress($isMergeSameAddress);
397 $this->setReturnProperties($this->determineReturnProperties());
398 $this->setAdditionalFieldsForSameAddressMerge();
399 $this->setAdditionalFieldsForPostalExport();
400 $this->setHouseholdMergeReturnProperties();
401 $this->setGreetingStringsForSameAddressMerge($formValues);
407 public function isPostalableOnly() {
408 return $this->isPostalableOnly
;
412 * @param bool $isPostalableOnly
414 public function setIsPostalableOnly($isPostalableOnly) {
415 $this->isPostalableOnly
= $isPostalableOnly;
421 public function getRequestedFields() {
422 return empty($this->requestedFields
) ?
NULL : $this->requestedFields
;
426 * @param array|null $requestedFields
428 public function setRequestedFields($requestedFields) {
429 $this->requestedFields
= $requestedFields;
435 public function getReturnProperties() {
436 return array_merge($this->returnProperties
, $this->getAdditionalRequestedReturnProperties(), $this->getAdditionalFieldsForSameAddressMerge(), $this->getAdditionalFieldsForPostalExport());
440 * @param array $returnProperties
442 public function setReturnProperties($returnProperties) {
443 $this->returnProperties
= $returnProperties;
449 public function getRelationshipTypes() {
450 return $this->relationshipTypes
;
455 public function setRelationshipTypes() {
456 $this->relationshipTypes
= CRM_Contact_BAO_Relationship
::getContactRelationshipType(
468 * Set the value for a relationship type field.
470 * In this case we are building up an array of properties for a related contact.
472 * These may be used for direct exporting or for merge to household depending on the
475 * @param string $relationshipType
476 * @param int $contactID
477 * @param string $field
478 * @param string $value
480 public function setRelationshipValue($relationshipType, $contactID, $field, $value) {
481 $this->relatedContactValues
[$relationshipType][$contactID][$field] = $value;
482 if ($field === 'id') {
483 $this->householdsToSkip
[] = $value;
488 * Get the value for a relationship type field.
490 * In this case we are building up an array of properties for a related contact.
492 * These may be used for direct exporting or for merge to household depending on the
495 * @param string $relationshipType
496 * @param int $contactID
497 * @param string $field
501 public function getRelationshipValue($relationshipType, $contactID, $field) {
502 return isset($this->relatedContactValues
[$relationshipType][$contactID][$field]) ?
$this->relatedContactValues
[$relationshipType][$contactID][$field] : '';
506 * Get the id of the related household.
508 * @param int $contactID
509 * @param string $relationshipType
513 public function getRelatedHouseholdID($contactID, $relationshipType) {
514 return $this->relatedContactValues
[$relationshipType][$contactID]['id'];
518 * Has the household already been exported.
520 * @param int $housholdContactID
524 public function isHouseholdExported($housholdContactID) {
525 return isset($this->exportedHouseholds
[$housholdContactID]);
532 public function isMergeSameHousehold() {
533 return $this->isMergeSameHousehold
;
537 * @param bool $isMergeSameHousehold
539 public function setIsMergeSameHousehold($isMergeSameHousehold) {
540 $this->isMergeSameHousehold
= $isMergeSameHousehold;
544 * Return relationship types for household merge.
548 public function getHouseholdRelationshipTypes() {
549 if (!$this->isMergeSameHousehold()) {
553 CRM_Utils_Array
::key('Household Member of', $this->getRelationshipTypes()),
554 CRM_Utils_Array
::key('Head of Household for', $this->getRelationshipTypes()),
562 public function isRelationshipTypeKey($fieldName) {
563 return array_key_exists($fieldName, $this->relationshipTypes
);
570 public function isHouseholdMergeRelationshipTypeKey($fieldName) {
571 return in_array($fieldName, $this->getHouseholdRelationshipTypes());
577 public function getQueryOperator() {
578 return $this->queryOperator
;
582 * @param string $queryOperator
584 public function setQueryOperator($queryOperator) {
585 $this->queryOperator
= $queryOperator;
591 public function getQueryFields() {
592 return $this->queryFields
;
596 * @param array $queryFields
598 public function setQueryFields($queryFields) {
599 // legacy hacks - we add these to queryFields because this
600 // pseudometadata is currently required.
601 $queryFields['im_provider']['pseudoconstant']['var'] = 'imProviders';
602 $queryFields['country']['context'] = 'country';
603 $queryFields['world_region']['context'] = 'country';
604 $queryFields['state_province']['context'] = 'province';
605 $this->queryFields
= $queryFields;
611 public function getQueryMode() {
612 return $this->queryMode
;
616 * Set the query mode based on the export mode.
618 public function setQueryMode() {
620 switch ($this->getExportMode()) {
621 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
622 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
625 case CRM_Export_Form_Select
::EVENT_EXPORT
:
626 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_EVENT
;
629 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
630 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_MEMBER
;
633 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
634 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_PLEDGE
;
637 case CRM_Export_Form_Select
::CASE_EXPORT
:
638 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_CASE
;
641 case CRM_Export_Form_Select
::GRANT_EXPORT
:
642 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_GRANT
;
645 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
646 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
650 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_CONTACTS
;
657 public function getExportMode() {
658 return $this->exportMode
;
662 * @param int $exportMode
664 public function setExportMode($exportMode) {
665 $this->exportMode
= $exportMode;
669 * Get the name for the export file.
673 public function getExportFileName() {
674 switch ($this->getExportMode()) {
675 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
676 return ts('CiviCRM Contact Search');
678 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
679 return ts('CiviCRM Contribution Search');
681 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
682 return ts('CiviCRM Member Search');
684 case CRM_Export_Form_Select
::EVENT_EXPORT
:
685 return ts('CiviCRM Participant Search');
687 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
688 return ts('CiviCRM Pledge Search');
690 case CRM_Export_Form_Select
::CASE_EXPORT
:
691 return ts('CiviCRM Case Search');
693 case CRM_Export_Form_Select
::GRANT_EXPORT
:
694 return ts('CiviCRM Grant Search');
696 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
697 return ts('CiviCRM Activity Search');
700 // Legacy code suggests the value could be 'financial' - ie. something
701 // other than what should be accepted. However, I suspect that this line is
703 return ts('CiviCRM Search');
708 * Get the label for the header row based on the field to output.
710 * @param string $field
714 public function getHeaderForRow($field) {
715 if (substr($field, -11) == 'campaign_id') {
716 // @todo - set this correctly in the xml rather than here.
717 // This will require a generalised handling cleanup
718 return ts('Campaign ID');
720 if ($this->isMergeSameHousehold() && $field === 'id') {
721 return ts('Household ID');
723 elseif (isset($this->getQueryFields()[$field]['title'])) {
724 return $this->getQueryFields()[$field]['title'];
726 elseif ($this->isExportPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
727 return CRM_Utils_Array
::value($field, $this->getcomponentPaymentFields());
740 public function runQuery($params, $order) {
741 $returnProperties = $this->getReturnProperties();
742 $params = array_merge($params, $this->getWhereParams());
744 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
745 FALSE, FALSE, $this->getQueryMode(),
746 FALSE, TRUE, TRUE, NULL, $this->getQueryOperator()
751 $query->_sort
= $order;
752 list($select, $from, $where, $having) = $query->query();
753 $this->setQueryFields($query->_fields
);
754 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
755 if ($this->getRequestedFields() && ($this->getComponentTable())) {
756 $from .= " INNER JOIN " . $this->getComponentTable() . " ctTable ON ctTable.contact_id = contact_a.id ";
758 elseif ($this->getComponentClause()) {
759 $whereClauses[] = $this->getComponentClause();
762 // CRM-13982 - check if is deleted
763 foreach ($params as $value) {
764 if ($value[0] == 'contact_is_deleted') {
765 unset($whereClauses['trash_clause']);
769 if ($this->isPostalableOnly
) {
770 if (array_key_exists('street_address', $returnProperties)) {
771 $addressWhere = " civicrm_address.street_address <> ''";
772 if (array_key_exists('supplemental_address_1', $returnProperties)) {
773 // We need this to be an OR rather than AND on the street_address so, hack it in.
774 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
775 'address_options', TRUE, NULL, TRUE
777 if (!empty($addressOptions['supplemental_address_1'])) {
778 $addressWhere .= " OR civicrm_address.supplemental_address_1 <> ''";
781 $whereClauses['address'] = $addressWhere;
786 $where = "WHERE " . implode(' AND ', $whereClauses);
789 $where .= " AND " . implode(' AND ', $whereClauses);
792 $groupBy = $this->getGroupBy($query);
793 $queryString = "$select $from $where $having $groupBy";
795 // always add contact_a.id to the ORDER clause
796 // so the order is deterministic
798 if (strpos('contact_a.id', $order) === FALSE) {
799 $order .= ", contact_a.id";
802 list($field, $dir) = explode(' ', $order, 2);
803 $field = trim($field);
804 if (!empty($this->getReturnProperties()[$field])) {
806 $queryString .= " ORDER BY $order";
809 return [$query, $queryString];
813 * Add a row to the specification for how to output data.
816 * @param string $relationshipType
817 * @param string $locationType
818 * @param int $entityTypeID phone_type_id or provider_id for phone or im fields.
820 public function addOutputSpecification($key, $relationshipType = NULL, $locationType = NULL, $entityTypeID = NULL) {
823 if ($key === 'phone') {
824 $entityLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $entityTypeID);
827 $entityLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_IM', 'provider_id', $entityTypeID);
831 // These oddly constructed keys are for legacy reasons. Altering them will affect test success
832 // but in time it may be good to rationalise them.
833 $label = $this->getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel);
834 $index = $this->getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityLabel);
835 $fieldKey = $this->getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityLabel);
837 $this->outputSpecification
[$index]['header'] = $label;
838 $this->outputSpecification
[$index]['sql_columns'] = $this->getSqlColumnDefinition($fieldKey, $key);
840 if ($relationshipType && $this->isHouseholdMergeRelationshipTypeKey($relationshipType)) {
841 $this->setColumnAsCalculationOnly($index);
843 $this->outputSpecification
[$index]['metadata'] = $this->getMetaDataForField($key);
847 * Get the metadata for the given field.
853 public function getMetaDataForField($key) {
854 $mappings = ['contact_id' => 'id'];
855 if (isset($this->getQueryFields()[$key])) {
856 return $this->getQueryFields()[$key];
858 if (isset($mappings[$key])) {
859 return $this->getQueryFields()[$mappings[$key]];
867 public function setSqlColumnDefn($key) {
868 $this->outputSpecification
[$this->getMungedFieldName($key)]['sql_columns'] = $this->getSqlColumnDefinition($key, $this->getMungedFieldName($key));
872 * Mark a column as only required for calculations.
874 * Do not include the row with headers.
876 * @param string $column
878 public function setColumnAsCalculationOnly($column) {
879 $this->outputSpecification
[$column]['do_not_output_to_csv'] = TRUE;
885 public function getHeaderRows() {
887 foreach ($this->outputSpecification
as $key => $spec) {
888 if (empty($spec['do_not_output_to_csv'])) {
889 $headerRows[] = $spec['header'];
898 public function getSQLColumns() {
900 foreach ($this->outputSpecification
as $key => $spec) {
901 if (empty($spec['do_not_output_to_sql'])) {
902 $sqlColumns[$key] = $spec['sql_columns'];
911 public function getMetadata() {
913 foreach ($this->outputSpecification
as $key => $spec) {
914 $metadata[$key] = $spec['metadata'];
920 * Build the row for output.
922 * @param \CRM_Contact_BAO_Query $query
923 * @param CRM_Core_DAO $iterationDAO
924 * @param array $outputColumns
926 * @param $paymentDetails
927 * @param $addPaymentHeader
931 public function buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader) {
932 $paymentTableId = $this->getPaymentTableID();
933 if ($this->isHouseholdToSkip($iterationDAO->contact_id
)) {
936 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
937 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
940 $householdMergeRelationshipType = $this->getHouseholdMergeTypeForRow($iterationDAO->contact_id
);
941 if ($householdMergeRelationshipType) {
942 $householdID = $this->getRelatedHouseholdID($iterationDAO->contact_id
, $householdMergeRelationshipType);
943 if ($this->isHouseholdExported($householdID)) {
946 foreach (array_keys($outputColumns) as $column) {
947 $row[$column] = $this->getRelationshipValue($householdMergeRelationshipType, $iterationDAO->contact_id
, $column);
949 $this->markHouseholdExported($householdID);
953 $query->convertToPseudoNames($iterationDAO);
955 //first loop through output columns so that we return what is required, and in same order.
956 foreach ($outputColumns as $field => $value) {
957 // add im_provider to $dao object
958 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
959 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
962 //build row values (data)
964 if (property_exists($iterationDAO, $field)) {
965 $fieldValue = $iterationDAO->$field;
966 // to get phone type from phone type id
967 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
968 $fieldValue = $phoneTypes[$fieldValue];
970 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
971 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
973 elseif (strstr($field, 'master_id')) {
974 // @todo - why not just $field === 'master_id' - what else would it be?
975 $masterAddressId = $iterationDAO->$field ??
NULL;
976 // get display name of contact that address is shared.
977 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
981 if ($this->isRelationshipTypeKey($field)) {
982 $this->buildRelationshipFieldsForRow($row, $iterationDAO->contact_id
, $value, $field);
985 $row[$field] = $this->getTransformedFieldValue($field, $iterationDAO, $fieldValue, $metadata, $paymentDetails);
989 // If specific payment fields have been selected for export, payment
990 // data will already be in $row. Otherwise, add payment related
991 // information, if appropriate.
992 if ($addPaymentHeader) {
993 if (!$this->isExportSpecifiedPaymentFields()) {
994 $nullContributionDetails = array_fill_keys(array_keys($this->getPaymentHeaders()), NULL);
995 if ($this->isExportPaymentFields()) {
996 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
997 if (!is_array($paymentData) ||
empty($paymentData)) {
998 $paymentData = $nullContributionDetails;
1000 $row = array_merge($row, $paymentData);
1002 elseif (!empty($paymentDetails)) {
1003 $row = array_merge($row, $nullContributionDetails);
1007 //remove organization name for individuals if it is set for current employer
1008 if (!empty($row['contact_type']) &&
1009 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1011 $row['organization_name'] = '';
1017 * If this row has a household whose details we should use get the relationship type key.
1023 public function getHouseholdMergeTypeForRow($contactID) {
1024 if (!$this->isMergeSameHousehold()) {
1027 foreach ($this->getHouseholdRelationshipTypes() as $relationshipType) {
1028 if (isset($this->relatedContactValues
[$relationshipType][$contactID])) {
1029 return $relationshipType;
1035 * Mark the given household as already exported.
1037 * @param $householdID
1039 public function markHouseholdExported($householdID) {
1040 $this->exportedHouseholds
[$householdID] = $householdID;
1045 * @param $iterationDAO
1046 * @param $fieldValue
1048 * @param $paymentDetails
1052 public function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $metadata, $paymentDetails) {
1054 $i18n = CRM_Core_I18n
::singleton();
1055 if ($field == 'id') {
1056 return $iterationDAO->contact_id
;
1057 // special case for calculated field
1059 elseif ($field == 'source_contact_id') {
1060 return $iterationDAO->contact_id
;
1062 elseif ($field == 'pledge_balance_amount') {
1063 return $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
1064 // special case for calculated field
1066 elseif ($field == 'pledge_next_pay_amount') {
1067 return $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
1069 elseif (isset($fieldValue) &&
1072 //check for custom data
1073 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
1074 return CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1077 elseif (in_array($field, [
1082 //special case for greeting replacement
1083 $fldValue = "{$field}_display";
1084 return $iterationDAO->$fldValue;
1087 //normal fields with a touch of CRM-3157
1090 case 'world_region':
1091 return $i18n->crm_translate($fieldValue, ['context' => 'country']);
1093 case 'state_province':
1094 return $i18n->crm_translate($fieldValue, ['context' => 'province']);
1097 case 'preferred_communication_method':
1098 case 'preferred_mail_format':
1099 case 'communication_style':
1100 return $i18n->crm_translate($fieldValue);
1103 if (isset($metadata[$field])) {
1104 // No I don't know why we do it this way & whether we could
1105 // make better use of pseudoConstants.
1106 if (!empty($metadata[$field]['context'])) {
1107 return $i18n->crm_translate($fieldValue, $metadata[$field]);
1109 if (!empty($metadata[$field]['pseudoconstant'])) {
1110 if (!empty($metadata[$field]['bao'])) {
1111 return CRM_Core_PseudoConstant
::getLabel($metadata[$field]['bao'], $metadata[$field]['name'], $fieldValue);
1113 // This is not our normal syntax for pseudoconstants but I am a bit loath to
1114 // call an external function until sure it is not increasing php processing given this
1115 // may be iterated 100,000 times & we already have the $imProvider var loaded.
1116 // That can be next refactor...
1117 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1118 // but I have to reach a stable point....
1119 $varName = $metadata[$field]['pseudoconstant']['var'];
1120 if ($varName === 'imProviders') {
1121 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
1123 if ($varName === 'phoneTypes') {
1124 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
1133 elseif ($this->isExportSpecifiedPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
1134 $paymentTableId = $this->getPaymentTableID();
1135 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1137 'componentPaymentField_total_amount' => 'total_amount',
1138 'componentPaymentField_contribution_status' => 'contribution_status',
1139 'componentPaymentField_payment_instrument' => 'pay_instru',
1140 'componentPaymentField_transaction_id' => 'trxn_id',
1141 'componentPaymentField_received_date' => 'receive_date',
1143 return CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1146 // if field is empty or null
1152 * Get array of fields to return, over & above those defined in the main contact exportable fields.
1154 * These include export mode specific fields & some fields apparently required as 'exportableFields'
1155 * but not returned by the function of the same name.
1158 * Array of fields to return in the format ['field_name' => 1,...]
1160 public function getAdditionalReturnProperties() {
1161 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
1162 $componentSpecificFields = [];
1165 $componentSpecificFields = CRM_Contact_BAO_Query
::defaultReturnProperties($this->getQueryMode());
1167 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_PLEDGE
) {
1168 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Pledge_BAO_Query
::extraReturnProperties($this->getQueryMode()));
1169 unset($componentSpecificFields['contribution_status_id']);
1170 unset($componentSpecificFields['pledge_status_id']);
1171 unset($componentSpecificFields['pledge_payment_status_id']);
1173 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CASE
) {
1174 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Case_BAO_Query
::extraReturnProperties($this->getQueryMode()));
1176 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
1177 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
1178 unset($componentSpecificFields['contribution_status_id']);
1180 return $componentSpecificFields;
1184 * Should payment fields be appended to the export.
1186 * (This is pretty hacky so hopefully this function won't last long - notice
1187 * how obviously it should be part of the above function!).
1189 public function isExportPaymentFields() {
1190 if ($this->getRequestedFields() === NULL
1191 && in_array($this->getQueryMode(), [
1192 CRM_Contact_BAO_Query
::MODE_EVENT
,
1193 CRM_Contact_BAO_Query
::MODE_MEMBER
,
1194 CRM_Contact_BAO_Query
::MODE_PLEDGE
,
1198 elseif ($this->isExportSpecifiedPaymentFields()) {
1205 * Has specific payment fields been requested (as opposed to via all fields).
1207 * If specific fields have been requested then they get added at various points.
1211 public function isExportSpecifiedPaymentFields() {
1212 if ($this->getRequestedFields() !== NULL && $this->hasRequestedComponentPaymentFields()) {
1218 * Get the name of the id field in the table that connects contributions to the export entity.
1220 public function getPaymentTableID() {
1221 if ($this->getRequestedFields() === NULL) {
1223 CRM_Contact_BAO_Query
::MODE_EVENT
=> 'participant_id',
1224 CRM_Contact_BAO_Query
::MODE_MEMBER
=> 'membership_id',
1225 CRM_Contact_BAO_Query
::MODE_PLEDGE
=> 'pledge_payment_id',
1227 return isset($mapping[$this->getQueryMode()]) ?
$mapping[$this->getQueryMode()] : '';
1229 elseif ($this->hasRequestedComponentPaymentFields()) {
1230 return 'participant_id';
1236 * Have component payment fields been requested.
1240 protected function hasRequestedComponentPaymentFields() {
1241 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_EVENT
) {
1242 $participantPaymentFields = array_intersect_key($this->getComponentPaymentFields(), $this->getReturnProperties());
1243 if (!empty($participantPaymentFields)) {
1251 * Get fields that indicate payment fields have been requested for a component.
1253 * Ideally this should be protected but making it temporarily public helps refactoring..
1257 public function getComponentPaymentFields() {
1259 'componentPaymentField_total_amount' => ts('Total Amount'),
1260 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1261 'componentPaymentField_received_date' => ts('Date Received'),
1262 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1263 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1268 * Get headers for payment fields.
1270 * Returns an array of contribution fields when the entity supports payment fields and specific fields
1271 * are not specified. This is a transitional function for refactoring legacy code.
1273 public function getPaymentHeaders() {
1274 if ($this->isExportPaymentFields() && !$this->isExportSpecifiedPaymentFields()) {
1275 return $this->getcomponentPaymentFields();
1281 * Get the default properties when not specified.
1283 * In the UI this appears as 'Primary fields only' but in practice it's
1284 * most of the kitchen sink and the hallway closet thrown in.
1286 * Since CRM-952 custom fields are excluded, but no other form of mercy is shown.
1290 public function getDefaultReturnProperties() {
1291 $returnProperties = [];
1292 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
1293 $skippedFields = ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CONTACTS
) ?
[] : [
1299 foreach ($fields as $key => $var) {
1300 if ($key && (substr($key, 0, 6) != 'custom') && !in_array($key, $skippedFields)) {
1301 $returnProperties[$key] = 1;
1304 $returnProperties = array_merge($returnProperties, $this->getAdditionalReturnProperties());
1305 return $returnProperties;
1309 * Add the field to relationship return properties & return it.
1311 * This function is doing both setting & getting which is yuck but it is an interim
1314 * @param array $value
1315 * @param string $relationshipKey
1319 public function setRelationshipReturnProperties($value, $relationshipKey) {
1320 $relationField = $value['name'];
1321 $relIMProviderId = NULL;
1322 $relLocTypeId = CRM_Utils_Array
::value('location_type_id', $value);
1323 $locationName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_Address', 'location_type_id', $relLocTypeId);
1324 $relPhoneTypeId = CRM_Utils_Array
::value('phone_type_id', $value, ($locationName ?
'Primary' : NULL));
1325 $relIMProviderId = CRM_Utils_Array
::value('im_provider_id', $value, ($locationName ?
'Primary' : NULL));
1326 if (in_array($relationField, $this->getValidLocationFields()) && $locationName) {
1327 if ($relationField === 'phone') {
1328 $this->relationshipReturnProperties
[$relationshipKey]['location'][$locationName]['phone-' . $relPhoneTypeId] = 1;
1330 elseif ($relationField === 'im') {
1331 $this->relationshipReturnProperties
[$relationshipKey]['location'][$locationName]['im-' . $relIMProviderId] = 1;
1334 $this->relationshipReturnProperties
[$relationshipKey]['location'][$locationName][$relationField] = 1;
1338 $this->relationshipReturnProperties
[$relationshipKey][$relationField] = 1;
1340 return $this->relationshipReturnProperties
[$relationshipKey];
1344 * Add the main return properties to the household merge properties if needed for merging.
1346 * If we are using household merge we need to add these to the relationship properties to
1349 public function setHouseholdMergeReturnProperties() {
1350 if ($this->isMergeSameHousehold()) {
1351 $returnProperties = $this->getReturnProperties();
1352 $returnProperties = array_diff_key($returnProperties, array_fill_keys(['location_type', 'im_provider'], 1));
1353 foreach ($this->getHouseholdRelationshipTypes() as $householdRelationshipType) {
1354 $this->relationshipReturnProperties
[$householdRelationshipType] = $returnProperties;
1360 * Get the default location fields to request.
1364 public function getValidLocationFields() {
1367 'supplemental_address_1',
1368 'supplemental_address_2',
1369 'supplemental_address_3',
1372 'postal_code_suffix',
1384 * Get the sql column definition for the given field.
1386 * @param string $fieldName
1387 * @param string $columnName
1391 public function getSqlColumnDefinition($fieldName, $columnName) {
1393 // early exit for master_id, CRM-12100
1394 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1395 // also for current_employer, CRM-16939
1396 if ($columnName == 'master_id' ||
$columnName == 'current_employer') {
1397 return "$fieldName varchar(128)";
1400 $queryFields = $this->getQueryFields();
1401 // @todo remove the enotice avoidance here, ensure all columns are declared.
1402 // tests will fail on the enotices until they all are & then all the 'else'
1404 $fieldSpec = $queryFields[$columnName] ??
[];
1406 // set the sql columns
1407 if (isset($fieldSpec['type'])) {
1408 switch ($fieldSpec['type']) {
1409 case CRM_Utils_Type
::T_INT
:
1410 case CRM_Utils_Type
::T_BOOLEAN
:
1411 if (in_array(CRM_Utils_Array
::value('data_type', $fieldSpec), ['Country', 'StateProvince', 'ContactReference'])) {
1412 return "$fieldName varchar(255)";
1414 return "$fieldName varchar(16)";
1416 case CRM_Utils_Type
::T_STRING
:
1417 if (isset($queryFields[$columnName]['maxlength'])) {
1418 return "$fieldName varchar({$queryFields[$columnName]['maxlength']})";
1421 return "$fieldName varchar(255)";
1424 case CRM_Utils_Type
::T_TEXT
:
1425 case CRM_Utils_Type
::T_LONGTEXT
:
1426 case CRM_Utils_Type
::T_BLOB
:
1427 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1428 return "$fieldName longtext";
1430 case CRM_Utils_Type
::T_FLOAT
:
1431 case CRM_Utils_Type
::T_ENUM
:
1432 case CRM_Utils_Type
::T_DATE
:
1433 case CRM_Utils_Type
::T_TIME
:
1434 case CRM_Utils_Type
::T_TIMESTAMP
:
1435 case CRM_Utils_Type
::T_MONEY
:
1436 case CRM_Utils_Type
::T_EMAIL
:
1437 case CRM_Utils_Type
::T_URL
:
1438 case CRM_Utils_Type
::T_CCNUM
:
1440 return "$fieldName varchar(32)";
1444 if (substr($fieldName, -3, 3) == '_id') {
1445 return "$fieldName varchar(255)";
1447 elseif (substr($fieldName, -5, 5) == '_note') {
1448 return "$fieldName text";
1457 if (in_array($fieldName, $changeFields)) {
1458 return "$fieldName text";
1461 // set the sql columns for custom data
1462 if (isset($queryFields[$columnName]['data_type'])) {
1464 switch ($queryFields[$columnName]['data_type']) {
1466 // May be option labels, which could be up to 512 characters
1467 $length = max(512, CRM_Utils_Array
::value('text_length', $queryFields[$columnName]));
1468 return "$fieldName varchar($length)";
1471 return "$fieldName varchar(255)";
1474 return "$fieldName text";
1477 return "$fieldName varchar(255)";
1481 return "$fieldName text";
1489 * Get the munged field name.
1491 * @param string $field
1494 public function getMungedFieldName($field) {
1495 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1496 if ($fieldName == 'id') {
1497 $fieldName = 'civicrm_primary_id';
1503 * In order to respect the history of this class we need to index kinda illogically.
1505 * On the bright side - this stuff is tested within a nano-byte of it's life.
1507 * e.g '2-a-b_Home-City'
1509 * @param string $key
1510 * @param string $relationshipType
1511 * @param string $locationType
1512 * @param $entityLabel
1516 protected function getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityLabel) {
1517 if ($entityLabel ||
$key === 'im') {
1518 // Just cos that's the history...
1519 if ($key !== 'master_id') {
1520 $key = $this->getHeaderForRow($key);
1523 if (!$relationshipType ||
$key !== 'id') {
1524 $key = $this->getMungedFieldName($key);
1526 return $this->getMungedFieldName(
1527 ($relationshipType ?
($relationshipType . '_') : '')
1528 . ($locationType ?
($locationType . '_') : '')
1530 . ($entityLabel ?
('_' . $entityLabel) : '')
1535 * Get the compiled label for the column.
1537 * e.g 'Gender', 'Employee Of-Home-city'
1539 * @param string $key
1540 * @param string $relationshipType
1541 * @param string $locationType
1542 * @param string $entityLabel
1546 protected function getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel) {
1547 return ($relationshipType ?
$this->getRelationshipTypes()[$relationshipType] . '-' : '')
1548 . ($locationType ?
$locationType . '-' : '')
1549 . $this->getHeaderForRow($key)
1550 . ($entityLabel ?
'-' . $entityLabel : '');
1554 * Get the mysql field name key.
1556 * This key is locked in by tests but the reasons for the specific conventions -
1557 * ie. headings are used for keying fields in some cases, are likely
1558 * accidental rather than deliberate.
1560 * This key is used for the output sql array.
1562 * @param string $key
1563 * @param $relationshipType
1564 * @param $locationType
1565 * @param $entityLabel
1569 protected function getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityLabel) {
1570 if ($entityLabel ||
$key === 'im') {
1571 if ($key !== 'state_province' && $key !== 'id') {
1572 // @todo - test removing this - indexing by $key should be fine...
1573 $key = $this->getHeaderForRow($key);
1576 if (!$relationshipType ||
$key !== 'id') {
1577 $key = $this->getMungedFieldName($key);
1579 $fieldKey = $this->getMungedFieldName(
1580 ($relationshipType ?
($relationshipType . '_') : '')
1581 . ($locationType ?
($locationType . '_') : '')
1583 . ($entityLabel ?
('_' . $entityLabel) : '')
1589 * Get params for the where criteria.
1593 public function getWhereParams() {
1594 if (!$this->isPostalableOnly()) {
1597 $params['is_deceased'] = ['is_deceased', '=', 0, CRM_Contact_BAO_Query
::MODE_CONTACTS
];
1598 $params['do_not_mail'] = ['do_not_mail', '=', 0, CRM_Contact_BAO_Query
::MODE_CONTACTS
];
1608 protected function buildRelationshipFieldsForRow(&$row, $contactID, $value, $field) {
1609 foreach (array_keys($value) as $property) {
1610 if ($property === 'location') {
1611 // @todo just undo all this nasty location wrangling!
1612 foreach ($value['location'] as $locationKey => $locationFields) {
1613 foreach (array_keys($locationFields) as $locationField) {
1614 $fieldKey = str_replace(' ', '_', $locationKey . '-' . $locationField);
1615 $row[$field . '_' . $fieldKey] = $this->getRelationshipValue($field, $contactID, $fieldKey);
1620 $row[$field . '_' . $property] = $this->getRelationshipValue($field, $contactID, $property);
1626 * Is this contact a household that is already set to be exported by virtue of it's household members.
1628 * @param int $contactID
1632 protected function isHouseholdToSkip($contactID) {
1633 return in_array($contactID, $this->householdsToSkip
);
1637 * Get the various arrays that we use to structure our output.
1639 * The extraction of these has been moved to a separate function for clarity and so that
1640 * tests can be added - in particular on the $outputHeaders array.
1642 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1643 * as a step on the refactoring path rather than how it should be.
1646 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1647 * alias for the field generated by BAO_Query object.
1648 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1649 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1650 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1651 * I'm too embarassed to discuss here.
1653 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1654 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1655 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1656 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1657 * - a) the function used is more efficient or
1658 * - b) this code is old & outdated. Submit your answers to circular bin or better
1659 * yet find a way to comment them for posterity.
1661 public function getExportStructureArrays() {
1662 $outputColumns = $metadata = [];
1663 $queryFields = $this->getQueryFields();
1664 foreach ($this->getReturnProperties() as $key => $value) {
1665 if (($key != 'location' ||
!is_array($value)) && !$this->isRelationshipTypeKey($key)) {
1666 $outputColumns[$key] = $value;
1667 $this->addOutputSpecification($key);
1669 elseif ($this->isRelationshipTypeKey($key)) {
1670 $outputColumns[$key] = $value;
1671 foreach ($value as $relationField => $relationValue) {
1672 // below block is same as primary block (duplicate)
1673 if (isset($queryFields[$relationField]['title'])) {
1674 $this->addOutputSpecification($relationField, $key);
1676 elseif (is_array($relationValue) && $relationField == 'location') {
1677 // fix header for location type case
1678 foreach ($relationValue as $ltype => $val) {
1679 foreach (array_keys($val) as $fld) {
1680 $type = explode('-', $fld);
1681 $this->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array
::value(1, $type));
1688 foreach ($value as $locationType => $locationFields) {
1689 foreach (array_keys($locationFields) as $locationFieldName) {
1690 $type = explode('-', $locationFieldName);
1692 $actualDBFieldName = $type[0];
1693 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1695 if (!empty($type[1])) {
1696 $daoFieldName .= "-" . $type[1];
1698 $this->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array
::value(1, $type));
1699 $metadata[$daoFieldName] = $this->getMetaDataForField($actualDBFieldName);
1700 $outputColumns[$daoFieldName] = TRUE;
1705 return [$outputColumns, $metadata];
1709 * Get default return property for export based on mode
1712 * Default Return property
1714 public function defaultReturnProperty() {
1715 // hack to add default return property based on export mode
1717 $exportMode = $this->getExportMode();
1718 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
1719 $property = 'contribution_id';
1721 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1722 $property = 'participant_id';
1724 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1725 $property = 'membership_id';
1727 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1728 $property = 'pledge_id';
1730 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1731 $property = 'case_id';
1733 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
1734 $property = 'grant_id';
1736 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1737 $property = 'activity_id';
1743 * Determine the required return properties from the input parameters.
1747 public function determineReturnProperties() {
1748 if ($this->getRequestedFields()) {
1749 $returnProperties = [];
1750 foreach ($this->getRequestedFields() as $key => $value) {
1751 $fieldName = $value['name'];
1752 $locationName = !empty($value['location_type_id']) ? CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_Address', 'location_type_id', $value['location_type_id']) : NULL;
1753 $relationshipTypeKey = !empty($value['relationship_type_id']) ?
$value['relationship_type_id'] . '_' . $value['relationship_direction'] : NULL;
1754 if (!$fieldName ||
$this->isHouseholdMergeRelationshipTypeKey($relationshipTypeKey)) {
1758 if ($this->isRelationshipTypeKey($relationshipTypeKey)) {
1759 $returnProperties[$relationshipTypeKey] = $this->setRelationshipReturnProperties($value, $relationshipTypeKey);
1761 elseif ($locationName) {
1762 if ($fieldName === 'phone') {
1763 $returnProperties['location'][$locationName]['phone-' . $value['phone_type_id'] ??
NULL] = 1;
1765 elseif ($fieldName === 'im') {
1766 $returnProperties['location'][$locationName]['im-' . $value['im_provider_id'] ??
NULL] = 1;
1769 $returnProperties['location'][$locationName][$fieldName] = 1;
1773 //hack to fix component fields
1774 //revert mix of event_id and title
1775 if ($fieldName == 'event_id') {
1776 $returnProperties['event_id'] = 1;
1779 $returnProperties[$fieldName] = 1;
1783 $defaultExportMode = $this->defaultReturnProperty();
1784 if ($defaultExportMode) {
1785 $returnProperties[$defaultExportMode] = 1;
1789 $returnProperties = $this->getDefaultReturnProperties();
1791 if ($this->isMergeSameHousehold()) {
1792 $returnProperties['id'] = 1;
1794 if ($this->isMergeSameAddress()) {
1795 $returnProperties['addressee'] = 1;
1796 $returnProperties['postal_greeting'] = 1;
1797 $returnProperties['email_greeting'] = 1;
1798 $returnProperties['street_name'] = 1;
1799 $returnProperties['household_name'] = 1;
1800 $returnProperties['street_address'] = 1;
1801 $returnProperties['city'] = 1;
1802 $returnProperties['state_province'] = 1;
1805 return $returnProperties;
1809 * @param object $query
1810 * CRM_Contact_BAO_Query
1815 public function getGroupBy($query) {
1817 $returnProperties = $this->getReturnProperties();
1818 $exportMode = $this->getExportMode();
1819 $queryMode = $this->getQueryMode();
1820 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
1821 CRM_Utils_Array
::value('notes', $returnProperties) ||
1823 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
1825 $groupBy = "contact_a.id";
1828 switch ($exportMode) {
1829 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1830 $groupBy = 'civicrm_contribution.id';
1831 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
1832 // especial group by when soft credit columns are included
1833 $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
1837 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1838 $groupBy = 'civicrm_participant.id';
1841 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1842 $groupBy = "civicrm_membership.id";
1846 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
1847 $groupBy = "civicrm_activity.id ";
1850 return $groupBy ?
' GROUP BY ' . implode(', ', (array) $groupBy) : '';
1854 * @param int $contactId
1858 public function replaceMergeTokens($contactId) {
1863 'postal_greeting' => $this->getPostalGreetingTemplate(),
1864 'addressee' => $this->getAddresseeGreetingTemplate(),
1866 foreach ($greetingFields as $greeting => $greetingLabel) {
1867 $tokens = CRM_Utils_Token
::getTokens($greetingLabel);
1868 if (!empty($tokens)) {
1869 if (empty($contact)) {
1874 $contact = civicrm_api('contact', 'get', $values);
1876 if (!empty($contact['is_error'])) {
1879 $contact = $contact['values'][$contact['id']];
1882 $tokens = ['contact' => $greetingLabel];
1883 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1890 * Build array for merging same addresses.
1893 * @param bool $sharedAddress
1897 public function buildMasterCopyArray($sql, $sharedAddress = FALSE) {
1899 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1900 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1902 $merge = $parents = [];
1903 $dao = CRM_Core_DAO
::executeQuery($sql);
1905 while ($dao->fetch()) {
1906 $masterID = $dao->master_id
;
1907 $copyID = $dao->copy_id
;
1908 $masterPostalGreeting = $dao->master_postal_greeting
;
1909 $masterAddressee = $dao->master_addressee
;
1910 $copyAddressee = $dao->copy_addressee
;
1912 if (!$sharedAddress) {
1913 if (!isset($this->contactGreetingFields
[$dao->master_contact_id
])) {
1914 $this->contactGreetingFields
[$dao->master_contact_id
] = $this->replaceMergeTokens($dao->master_contact_id
);
1916 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1917 $this->contactGreetingFields
[$dao->master_contact_id
], $dao->master_postal_greeting
1919 $masterAddressee = CRM_Utils_Array
::value('addressee',
1920 $this->contactGreetingFields
[$dao->master_contact_id
], $dao->master_addressee
1923 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1924 $this->contactGreetingFields
[$dao->copy_contact_id
] = $this->replaceMergeTokens($dao->copy_contact_id
);
1926 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1927 $this->contactGreetingFields
[$dao->copy_contact_id
], $dao->copy_postal_greeting
1929 $copyAddressee = CRM_Utils_Array
::value('addressee',
1930 $this->contactGreetingFields
[$dao->copy_contact_id
], $dao->copy_addressee
1934 if (!isset($merge[$masterID])) {
1935 // check if this is an intermediate child
1936 // this happens if there are 3 or more matches a,b, c
1937 // the above query will return a, b / a, c / b, c
1938 // we might be doing a bit more work, but for now its ok, unless someone
1939 // knows how to fix the query above
1940 if (isset($parents[$masterID])) {
1941 $masterID = $parents[$masterID];
1944 $merge[$masterID] = [
1945 'addressee' => $masterAddressee,
1947 'postalGreeting' => $masterPostalGreeting,
1949 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1952 $parents[$copyID] = $masterID;
1954 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1956 if ($copyPostalGreeting) {
1957 $this->trimNonTokensFromAddressString($copyPostalGreeting,
1958 $postalOptions[$dao->copy_postal_greeting_id
],
1959 $this->getPostalGreetingTemplate()
1961 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1962 // if there happens to be a duplicate, remove it
1963 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1966 if ($copyAddressee) {
1967 $this->trimNonTokensFromAddressString($copyAddressee,
1968 $addresseeOptions[$dao->copy_addressee_id
],
1969 $this->getAddresseeGreetingTemplate()
1971 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1974 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1981 * Merge contacts with the same address.
1983 public function mergeSameAddress() {
1985 $tableName = $this->getTemporaryTable();
1986 // check if any records are present based on if they have used shared address feature,
1987 // and not based on if city / state .. matches.
1989 SELECT r1.id as copy_id,
1990 r1.civicrm_primary_id as copy_contact_id,
1991 r1.addressee as copy_addressee,
1992 r1.addressee_id as copy_addressee_id,
1993 r1.postal_greeting as copy_postal_greeting,
1994 r1.postal_greeting_id as copy_postal_greeting_id,
1996 r2.civicrm_primary_id as master_contact_id,
1997 r2.postal_greeting as master_postal_greeting,
1998 r2.postal_greeting_id as master_postal_greeting_id,
1999 r2.addressee as master_addressee,
2000 r2.addressee_id as master_addressee_id
2002 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
2003 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
2005 $linkedMerge = $this->buildMasterCopyArray($sql, TRUE);
2007 // find all the records that have the same street address BUT not in a household
2008 // require match on city and state as well
2010 SELECT r1.id as master_id,
2011 r1.civicrm_primary_id as master_contact_id,
2012 r1.postal_greeting as master_postal_greeting,
2013 r1.postal_greeting_id as master_postal_greeting_id,
2014 r1.addressee as master_addressee,
2015 r1.addressee_id as master_addressee_id,
2017 r2.civicrm_primary_id as copy_contact_id,
2018 r2.postal_greeting as copy_postal_greeting,
2019 r2.postal_greeting_id as copy_postal_greeting_id,
2020 r2.addressee as copy_addressee,
2021 r2.addressee_id as copy_addressee_id
2023 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
2024 r1.city = r2.city AND
2025 r1.state_province_id = r2.state_province_id )
2026 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
2027 AND ( r2.household_name IS NULL OR r2.household_name = '' )
2028 AND ( r1.street_address != '' )
2032 $merge = $this->buildMasterCopyArray($sql);
2034 // unset ids from $merge already present in $linkedMerge
2035 foreach ($linkedMerge as $masterID => $values) {
2036 $keys = [$masterID];
2037 $keys = array_merge($keys, array_keys($values['copy']));
2038 foreach ($merge as $mid => $vals) {
2039 if (in_array($mid, $keys)) {
2040 unset($merge[$mid]);
2043 foreach ($values['copy'] as $copyId) {
2044 if (in_array($copyId, $keys)) {
2045 unset($merge[$mid]['copy'][$copyId]);
2051 $merge = $merge +
$linkedMerge;
2053 foreach ($merge as $masterID => $values) {
2056 SET addressee = %1, postal_greeting = %2, email_greeting = %3
2060 1 => [$values['addressee'], 'String'],
2061 2 => [$values['postalGreeting'], 'String'],
2062 3 => [$values['emailGreeting'], 'String'],
2063 4 => [$masterID, 'Integer'],
2065 CRM_Core_DAO
::executeQuery($sql, $params);
2067 // delete all copies
2068 $deleteIDs = array_keys($values['copy']);
2069 $deleteIDString = implode(',', $deleteIDs);
2071 DELETE FROM $tableName
2072 WHERE id IN ( $deleteIDString )
2074 CRM_Core_DAO
::executeQuery($sql);
2079 * The function unsets static part of the string, if token is the dynamic part.
2081 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
2082 * i.e 'Hello Alan' => converted to => 'Alan'
2084 * @param string $parsedString
2085 * @param string $defaultGreeting
2086 * @param string $greetingLabel
2090 public function trimNonTokensFromAddressString(
2091 &$parsedString, $defaultGreeting,
2094 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
2096 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
2097 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
2098 foreach ($stringsToBeReplaced as $key => $string) {
2099 // to keep one space
2100 $stringsToBeReplaced[$key] = ltrim($string);
2102 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
2104 return $parsedString;
2108 * Preview export output.
2113 public function getPreview($limit) {
2115 list($outputColumns, $metadata) = $this->getExportStructureArrays();
2116 $query = $this->runQuery([], '');
2117 CRM_Core_DAO
::disableFullGroupByMode();
2118 $result = CRM_Core_DAO
::executeQuery($query[1] . ' LIMIT ' . (int) $limit);
2119 CRM_Core_DAO
::reenableFullGroupByMode();
2120 while ($result->fetch()) {
2121 $rows[] = $this->buildRow($query[0], $result, $outputColumns, $metadata, [], []);
2127 * Set the template strings to be used when merging two contacts with the same address.
2129 * @param array $formValues
2130 * Values from first form. In this case we care about the keys
2133 * - address_greeting
2138 protected function setGreetingStringsForSameAddressMerge($formValues) {
2139 $greetingOptions = CRM_Export_Form_Select
::getGreetingOptions();
2141 if (!empty($greetingOptions)) {
2142 // Greeting options is keyed by 'postal_greeting' or 'addressee'.
2143 foreach ($greetingOptions as $key => $value) {
2144 $option = CRM_Utils_Array
::value($key, $formValues);
2146 if ($greetingOptions[$key][$option] == ts('Other')) {
2147 $formValues[$key] = $formValues["{$key}_other"];
2149 elseif ($greetingOptions[$key][$option] == ts('List of names')) {
2150 $formValues[$key] = '';
2153 $formValues[$key] = $greetingOptions[$key][$option];
2158 if (!empty($formValues['postal_greeting'])) {
2159 $this->setPostalGreetingTemplate($formValues['postal_greeting']);
2161 if (!empty($formValues['addressee'])) {
2162 $this->setAddresseeGreetingTemplate($formValues['addressee']);
2167 * Create the temporary table for output.
2169 public function createTempTable() {
2170 //creating a temporary table for the search result that need be exported
2171 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export');
2172 $sqlColumns = $this->getSQLColumns();
2173 // also create the sql table
2174 $exportTempTable->drop();
2176 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
2177 if (!empty($sqlColumns)) {
2178 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
2181 $sql .= "\n PRIMARY KEY ( id )";
2183 // add indexes for street_address and household_name if present
2187 'civicrm_primary_id',
2190 foreach ($addIndices as $index) {
2191 if (isset($sqlColumns[$index])) {
2193 INDEX index_{$index}( $index )
2198 $exportTempTable->createWithColumns($sql);
2199 $this->setTemporaryTable($exportTempTable->getName());
2203 * Get the values of linked household contact.
2205 * @param CRM_Core_DAO $relDAO
2206 * @param array $value
2207 * @param string $field
2210 * @throws \Exception
2212 public function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
2213 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
2214 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
2215 $i18n = CRM_Core_I18n
::singleton();
2216 $field = $field . '_';
2218 foreach ($value as $relationField => $relationValue) {
2219 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
2220 $fieldValue = $relDAO->$relationField;
2221 if ($relationField == 'phone_type_id') {
2222 $fieldValue = $phoneTypes[$relationValue];
2224 elseif ($relationField == 'provider_id') {
2225 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
2228 elseif (is_object($relDAO) && in_array($relationField, [
2233 //special case for greeting replacement
2234 $fldValue = "{$relationField}_display";
2235 $fieldValue = $relDAO->$fldValue;
2238 elseif (is_object($relDAO) && $relationField == 'state_province') {
2239 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
2241 elseif (is_object($relDAO) && $relationField == 'country') {
2242 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
2247 $relPrefix = $field . $relationField;
2249 if (is_object($relDAO) && $relationField == 'id') {
2250 $row[$relPrefix] = $relDAO->contact_id
;
2252 elseif (is_array($relationValue) && $relationField == 'location') {
2253 foreach ($relationValue as $ltype => $val) {
2254 // If the location name has a space in it the we need to handle that. This
2255 // is kinda hacky but specifically covered in the ExportTest so later efforts to
2256 // improve it should be secure in the knowled it will be caught.
2257 $ltype = str_replace(' ', '_', $ltype);
2258 foreach (array_keys($val) as $fld) {
2259 $type = explode('-', $fld);
2260 $fldValue = "{$ltype}-" . $type[0];
2261 if (!empty($type[1])) {
2262 $fldValue .= "-" . $type[1];
2264 // CRM-3157: localise country, region (both have ‘country’ context)
2265 // and state_province (‘province’ context)
2267 case (!is_object($relDAO)):
2268 $row[$field . '_' . $fldValue] = '';
2271 case in_array('country', $type):
2272 case in_array('world_region', $type):
2273 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2274 ['context' => 'country']
2278 case in_array('state_province', $type):
2279 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2280 ['context' => 'province']
2285 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
2291 elseif (isset($fieldValue) && $fieldValue != '') {
2292 //check for custom data
2293 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
2294 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
2297 //normal relationship fields
2298 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
2299 switch ($relationField) {
2301 case 'world_region':
2302 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
2305 case 'state_province':
2306 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
2310 $row[$relPrefix] = $fieldValue;
2316 // if relation field is empty or null
2317 $row[$relPrefix] = '';
2323 * Write to the csv from the temp table.
2325 public function writeCSVFromTable() {
2327 $headerRows = $this->getHeaderRows();
2328 $exportTempTable = $this->getTemporaryTable();
2329 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
2330 if ($exportTempTable !== $this->getTemporaryTable()) {
2331 CRM_Core_Error
::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
2332 $this->setTemporaryTable($exportTempTable);
2334 $exportTempTable = $this->getTemporaryTable();
2335 $writeHeader = TRUE;
2337 // increase this number a lot to avoid making too many queries
2338 // LIMIT is not much faster than a no LIMIT query
2342 $query = "SELECT * FROM $exportTempTable";
2345 $limitQuery = $query . "
2346 LIMIT $offset, $limit
2348 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
2354 $componentDetails = [];
2355 while ($dao->fetch()) {
2358 foreach (array_keys($this->getSQLColumns()) as $column) {
2359 $row[$column] = $dao->$column;
2361 $componentDetails[] = $row;
2363 CRM_Core_Report_Excel
::writeCSVFile($this->getExportFileName(),
2370 $writeHeader = FALSE;