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
382 public function __construct($exportMode, $requestedFields, $queryOperator, $isMergeSameHousehold = FALSE, $isPostalableOnly = FALSE, $isMergeSameAddress = FALSE) {
383 $this->setExportMode($exportMode);
384 $this->setQueryMode();
385 $this->setQueryOperator($queryOperator);
386 $this->setRequestedFields($requestedFields);
387 $this->setRelationshipTypes();
388 $this->setIsMergeSameHousehold($isMergeSameHousehold);
389 $this->setIsPostalableOnly($isPostalableOnly);
390 $this->setIsMergeSameAddress($isMergeSameAddress);
391 $this->setReturnProperties($this->determineReturnProperties());
392 $this->setAdditionalFieldsForSameAddressMerge();
393 $this->setAdditionalFieldsForPostalExport();
394 $this->setHouseholdMergeReturnProperties();
400 public function isPostalableOnly() {
401 return $this->isPostalableOnly
;
405 * @param bool $isPostalableOnly
407 public function setIsPostalableOnly($isPostalableOnly) {
408 $this->isPostalableOnly
= $isPostalableOnly;
414 public function getRequestedFields() {
415 return empty($this->requestedFields
) ?
NULL : $this->requestedFields
;
419 * @param array|null $requestedFields
421 public function setRequestedFields($requestedFields) {
422 $this->requestedFields
= $requestedFields;
428 public function getReturnProperties() {
429 return array_merge($this->returnProperties
, $this->getAdditionalRequestedReturnProperties(), $this->getAdditionalFieldsForSameAddressMerge(), $this->getAdditionalFieldsForPostalExport());
433 * @param array $returnProperties
435 public function setReturnProperties($returnProperties) {
436 $this->returnProperties
= $returnProperties;
442 public function getRelationshipTypes() {
443 return $this->relationshipTypes
;
448 public function setRelationshipTypes() {
449 $this->relationshipTypes
= CRM_Contact_BAO_Relationship
::getContactRelationshipType(
461 * Set the value for a relationship type field.
463 * In this case we are building up an array of properties for a related contact.
465 * These may be used for direct exporting or for merge to household depending on the
468 * @param string $relationshipType
469 * @param int $contactID
470 * @param string $field
471 * @param string $value
473 public function setRelationshipValue($relationshipType, $contactID, $field, $value) {
474 $this->relatedContactValues
[$relationshipType][$contactID][$field] = $value;
475 if ($field === 'id') {
476 $this->householdsToSkip
[] = $value;
481 * Get the value for a relationship type field.
483 * In this case we are building up an array of properties for a related contact.
485 * These may be used for direct exporting or for merge to household depending on the
488 * @param string $relationshipType
489 * @param int $contactID
490 * @param string $field
494 public function getRelationshipValue($relationshipType, $contactID, $field) {
495 return isset($this->relatedContactValues
[$relationshipType][$contactID][$field]) ?
$this->relatedContactValues
[$relationshipType][$contactID][$field] : '';
499 * Get the id of the related household.
501 * @param int $contactID
502 * @param string $relationshipType
506 public function getRelatedHouseholdID($contactID, $relationshipType) {
507 return $this->relatedContactValues
[$relationshipType][$contactID]['id'];
511 * Has the household already been exported.
513 * @param int $housholdContactID
517 public function isHouseholdExported($housholdContactID) {
518 return isset($this->exportedHouseholds
[$housholdContactID]);
525 public function isMergeSameHousehold() {
526 return $this->isMergeSameHousehold
;
530 * @param bool $isMergeSameHousehold
532 public function setIsMergeSameHousehold($isMergeSameHousehold) {
533 $this->isMergeSameHousehold
= $isMergeSameHousehold;
537 * Return relationship types for household merge.
541 public function getHouseholdRelationshipTypes() {
542 if (!$this->isMergeSameHousehold()) {
546 CRM_Utils_Array
::key('Household Member of', $this->getRelationshipTypes()),
547 CRM_Utils_Array
::key('Head of Household for', $this->getRelationshipTypes()),
555 public function isRelationshipTypeKey($fieldName) {
556 return array_key_exists($fieldName, $this->relationshipTypes
);
563 public function isHouseholdMergeRelationshipTypeKey($fieldName) {
564 return in_array($fieldName, $this->getHouseholdRelationshipTypes());
570 public function getQueryOperator() {
571 return $this->queryOperator
;
575 * @param string $queryOperator
577 public function setQueryOperator($queryOperator) {
578 $this->queryOperator
= $queryOperator;
584 public function getQueryFields() {
585 return $this->queryFields
;
589 * @param array $queryFields
591 public function setQueryFields($queryFields) {
592 // legacy hacks - we add these to queryFields because this
593 // pseudometadata is currently required.
594 $queryFields['im_provider']['pseudoconstant']['var'] = 'imProviders';
595 $queryFields['country']['context'] = 'country';
596 $queryFields['world_region']['context'] = 'country';
597 $queryFields['state_province']['context'] = 'province';
598 $this->queryFields
= $queryFields;
604 public function getQueryMode() {
605 return $this->queryMode
;
609 * Set the query mode based on the export mode.
611 public function setQueryMode() {
613 switch ($this->getExportMode()) {
614 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
615 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
618 case CRM_Export_Form_Select
::EVENT_EXPORT
:
619 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_EVENT
;
622 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
623 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_MEMBER
;
626 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
627 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_PLEDGE
;
630 case CRM_Export_Form_Select
::CASE_EXPORT
:
631 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_CASE
;
634 case CRM_Export_Form_Select
::GRANT_EXPORT
:
635 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_GRANT
;
638 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
639 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
643 $this->queryMode
= CRM_Contact_BAO_Query
::MODE_CONTACTS
;
650 public function getExportMode() {
651 return $this->exportMode
;
655 * @param int $exportMode
657 public function setExportMode($exportMode) {
658 $this->exportMode
= $exportMode;
662 * Get the name for the export file.
666 public function getExportFileName() {
667 switch ($this->getExportMode()) {
668 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
669 return ts('CiviCRM Contact Search');
671 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
672 return ts('CiviCRM Contribution Search');
674 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
675 return ts('CiviCRM Member Search');
677 case CRM_Export_Form_Select
::EVENT_EXPORT
:
678 return ts('CiviCRM Participant Search');
680 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
681 return ts('CiviCRM Pledge Search');
683 case CRM_Export_Form_Select
::CASE_EXPORT
:
684 return ts('CiviCRM Case Search');
686 case CRM_Export_Form_Select
::GRANT_EXPORT
:
687 return ts('CiviCRM Grant Search');
689 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
690 return ts('CiviCRM Activity Search');
693 // Legacy code suggests the value could be 'financial' - ie. something
694 // other than what should be accepted. However, I suspect that this line is
696 return ts('CiviCRM Search');
701 * Get the label for the header row based on the field to output.
703 * @param string $field
707 public function getHeaderForRow($field) {
708 if (substr($field, -11) == 'campaign_id') {
709 // @todo - set this correctly in the xml rather than here.
710 // This will require a generalised handling cleanup
711 return ts('Campaign ID');
713 if ($this->isMergeSameHousehold() && $field === 'id') {
714 return ts('Household ID');
716 elseif (isset($this->getQueryFields()[$field]['title'])) {
717 return $this->getQueryFields()[$field]['title'];
719 elseif ($this->isExportPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
720 return CRM_Utils_Array
::value($field, $this->getcomponentPaymentFields());
733 public function runQuery($params, $order) {
734 $returnProperties = $this->getReturnProperties();
736 $params = array_merge($params, $this->getWhereParams());
737 if ($this->isPostalableOnly
) {
738 if (array_key_exists('street_address', $returnProperties)) {
739 $addressWhere = " civicrm_address.street_address <> ''";
740 if (array_key_exists('supplemental_address_1', $returnProperties)) {
741 // We need this to be an OR rather than AND on the street_address so, hack it in.
742 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
743 'address_options', TRUE, NULL, TRUE
745 if (!empty($addressOptions['supplemental_address_1'])) {
746 $addressWhere .= " OR civicrm_address.supplemental_address_1 <> ''";
749 $addressWhere = ' AND (' . $addressWhere . ')';
752 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
753 FALSE, FALSE, $this->getQueryMode(),
754 FALSE, TRUE, TRUE, NULL, $this->getQueryOperator()
759 $query->_sort
= $order;
760 list($select, $from, $where, $having) = $query->query();
761 $this->setQueryFields($query->_fields
);
762 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
763 if ($this->getRequestedFields() && ($this->getComponentTable())) {
764 $from .= " INNER JOIN " . $this->getComponentTable() . " ctTable ON ctTable.contact_id = contact_a.id ";
766 elseif ($this->getComponentClause()) {
767 $whereClauses[] = $this->getComponentClause();
770 // CRM-13982 - check if is deleted
771 foreach ($params as $value) {
772 if ($value[0] == 'contact_is_deleted') {
773 unset($whereClauses['trash_clause']);
778 $where = "WHERE " . implode(' AND ', $whereClauses);
781 $where .= " AND " . implode(' AND ', $whereClauses);
784 $groupBy = $this->getGroupBy($query);
785 $queryString = "$select $from $where $having $groupBy";
787 // always add contact_a.id to the ORDER clause
788 // so the order is deterministic
790 if (strpos('contact_a.id', $order) === FALSE) {
791 $order .= ", contact_a.id";
794 list($field, $dir) = explode(' ', $order, 2);
795 $field = trim($field);
796 if (!empty($this->getReturnProperties()[$field])) {
798 $queryString .= " ORDER BY $order";
801 return [$query, $queryString];
805 * Add a row to the specification for how to output data.
808 * @param string $relationshipType
809 * @param string $locationType
810 * @param int $entityTypeID phone_type_id or provider_id for phone or im fields.
812 public function addOutputSpecification($key, $relationshipType = NULL, $locationType = NULL, $entityTypeID = NULL) {
815 if ($key === 'phone') {
816 $entityLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $entityTypeID);
819 $entityLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_IM', 'provider_id', $entityTypeID);
823 // These oddly constructed keys are for legacy reasons. Altering them will affect test success
824 // but in time it may be good to rationalise them.
825 $label = $this->getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel);
826 $index = $this->getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityLabel);
827 $fieldKey = $this->getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityLabel);
829 $this->outputSpecification
[$index]['header'] = $label;
830 $this->outputSpecification
[$index]['sql_columns'] = $this->getSqlColumnDefinition($fieldKey, $key);
832 if ($relationshipType && $this->isHouseholdMergeRelationshipTypeKey($relationshipType)) {
833 $this->setColumnAsCalculationOnly($index);
835 $this->outputSpecification
[$index]['metadata'] = $this->getMetaDataForField($key);
839 * Get the metadata for the given field.
845 public function getMetaDataForField($key) {
846 $mappings = ['contact_id' => 'id'];
847 if (isset($this->getQueryFields()[$key])) {
848 return $this->getQueryFields()[$key];
850 if (isset($mappings[$key])) {
851 return $this->getQueryFields()[$mappings[$key]];
859 public function setSqlColumnDefn($key) {
860 $this->outputSpecification
[$this->getMungedFieldName($key)]['sql_columns'] = $this->getSqlColumnDefinition($key, $this->getMungedFieldName($key));
864 * Mark a column as only required for calculations.
866 * Do not include the row with headers.
868 * @param string $column
870 public function setColumnAsCalculationOnly($column) {
871 $this->outputSpecification
[$column]['do_not_output_to_csv'] = TRUE;
877 public function getHeaderRows() {
879 foreach ($this->outputSpecification
as $key => $spec) {
880 if (empty($spec['do_not_output_to_csv'])) {
881 $headerRows[] = $spec['header'];
890 public function getSQLColumns() {
892 foreach ($this->outputSpecification
as $key => $spec) {
893 if (empty($spec['do_not_output_to_sql'])) {
894 $sqlColumns[$key] = $spec['sql_columns'];
903 public function getMetadata() {
905 foreach ($this->outputSpecification
as $key => $spec) {
906 $metadata[$key] = $spec['metadata'];
912 * Build the row for output.
914 * @param \CRM_Contact_BAO_Query $query
915 * @param CRM_Core_DAO $iterationDAO
916 * @param array $outputColumns
918 * @param $paymentDetails
919 * @param $addPaymentHeader
923 public function buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader) {
924 $paymentTableId = $this->getPaymentTableID();
925 if ($this->isHouseholdToSkip($iterationDAO->contact_id
)) {
928 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
929 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
932 $householdMergeRelationshipType = $this->getHouseholdMergeTypeForRow($iterationDAO->contact_id
);
933 if ($householdMergeRelationshipType) {
934 $householdID = $this->getRelatedHouseholdID($iterationDAO->contact_id
, $householdMergeRelationshipType);
935 if ($this->isHouseholdExported($householdID)) {
938 foreach (array_keys($outputColumns) as $column) {
939 $row[$column] = $this->getRelationshipValue($householdMergeRelationshipType, $iterationDAO->contact_id
, $column);
941 $this->markHouseholdExported($householdID);
945 $query->convertToPseudoNames($iterationDAO);
947 //first loop through output columns so that we return what is required, and in same order.
948 foreach ($outputColumns as $field => $value) {
949 // add im_provider to $dao object
950 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
951 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
954 //build row values (data)
956 if (property_exists($iterationDAO, $field)) {
957 $fieldValue = $iterationDAO->$field;
958 // to get phone type from phone type id
959 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
960 $fieldValue = $phoneTypes[$fieldValue];
962 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
963 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
965 elseif (strstr($field, 'master_id')) {
966 $masterAddressId = NULL;
967 if (isset($iterationDAO->$field)) {
968 $masterAddressId = $iterationDAO->$field;
970 // get display name of contact that address is shared.
971 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
975 if ($this->isRelationshipTypeKey($field)) {
976 $this->buildRelationshipFieldsForRow($row, $iterationDAO->contact_id
, $value, $field);
979 $row[$field] = $this->getTransformedFieldValue($field, $iterationDAO, $fieldValue, $metadata, $paymentDetails);
983 // If specific payment fields have been selected for export, payment
984 // data will already be in $row. Otherwise, add payment related
985 // information, if appropriate.
986 if ($addPaymentHeader) {
987 if (!$this->isExportSpecifiedPaymentFields()) {
988 $nullContributionDetails = array_fill_keys(array_keys($this->getPaymentHeaders()), NULL);
989 if ($this->isExportPaymentFields()) {
990 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
991 if (!is_array($paymentData) ||
empty($paymentData)) {
992 $paymentData = $nullContributionDetails;
994 $row = array_merge($row, $paymentData);
996 elseif (!empty($paymentDetails)) {
997 $row = array_merge($row, $nullContributionDetails);
1001 //remove organization name for individuals if it is set for current employer
1002 if (!empty($row['contact_type']) &&
1003 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1005 $row['organization_name'] = '';
1011 * If this row has a household whose details we should use get the relationship type key.
1017 public function getHouseholdMergeTypeForRow($contactID) {
1018 if (!$this->isMergeSameHousehold()) {
1021 foreach ($this->getHouseholdRelationshipTypes() as $relationshipType) {
1022 if (isset($this->relatedContactValues
[$relationshipType][$contactID])) {
1023 return $relationshipType;
1029 * Mark the given household as already exported.
1031 * @param $householdID
1033 public function markHouseholdExported($householdID) {
1034 $this->exportedHouseholds
[$householdID] = $householdID;
1039 * @param $iterationDAO
1040 * @param $fieldValue
1042 * @param $paymentDetails
1046 public function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $metadata, $paymentDetails) {
1048 $i18n = CRM_Core_I18n
::singleton();
1049 if ($field == 'id') {
1050 return $iterationDAO->contact_id
;
1051 // special case for calculated field
1053 elseif ($field == 'source_contact_id') {
1054 return $iterationDAO->contact_id
;
1056 elseif ($field == 'pledge_balance_amount') {
1057 return $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
1058 // special case for calculated field
1060 elseif ($field == 'pledge_next_pay_amount') {
1061 return $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
1063 elseif (isset($fieldValue) &&
1066 //check for custom data
1067 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
1068 return CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1071 elseif (in_array($field, [
1076 //special case for greeting replacement
1077 $fldValue = "{$field}_display";
1078 return $iterationDAO->$fldValue;
1081 //normal fields with a touch of CRM-3157
1084 case 'world_region':
1085 return $i18n->crm_translate($fieldValue, ['context' => 'country']);
1087 case 'state_province':
1088 return $i18n->crm_translate($fieldValue, ['context' => 'province']);
1091 case 'preferred_communication_method':
1092 case 'preferred_mail_format':
1093 case 'communication_style':
1094 return $i18n->crm_translate($fieldValue);
1097 if (isset($metadata[$field])) {
1098 // No I don't know why we do it this way & whether we could
1099 // make better use of pseudoConstants.
1100 if (!empty($metadata[$field]['context'])) {
1101 return $i18n->crm_translate($fieldValue, $metadata[$field]);
1103 if (!empty($metadata[$field]['pseudoconstant'])) {
1104 if (!empty($metadata[$field]['bao'])) {
1105 return CRM_Core_PseudoConstant
::getLabel($metadata[$field]['bao'], $metadata[$field]['name'], $fieldValue);
1107 // This is not our normal syntax for pseudoconstants but I am a bit loath to
1108 // call an external function until sure it is not increasing php processing given this
1109 // may be iterated 100,000 times & we already have the $imProvider var loaded.
1110 // That can be next refactor...
1111 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1112 // but I have to reach a stable point....
1113 $varName = $metadata[$field]['pseudoconstant']['var'];
1114 if ($varName === 'imProviders') {
1115 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
1117 if ($varName === 'phoneTypes') {
1118 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
1127 elseif ($this->isExportSpecifiedPaymentFields() && array_key_exists($field, $this->getcomponentPaymentFields())) {
1128 $paymentTableId = $this->getPaymentTableID();
1129 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1131 'componentPaymentField_total_amount' => 'total_amount',
1132 'componentPaymentField_contribution_status' => 'contribution_status',
1133 'componentPaymentField_payment_instrument' => 'pay_instru',
1134 'componentPaymentField_transaction_id' => 'trxn_id',
1135 'componentPaymentField_received_date' => 'receive_date',
1137 return CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1140 // if field is empty or null
1146 * Get array of fields to return, over & above those defined in the main contact exportable fields.
1148 * These include export mode specific fields & some fields apparently required as 'exportableFields'
1149 * but not returned by the function of the same name.
1152 * Array of fields to return in the format ['field_name' => 1,...]
1154 public function getAdditionalReturnProperties() {
1155 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
1156 $componentSpecificFields = [];
1159 $componentSpecificFields = CRM_Contact_BAO_Query
::defaultReturnProperties($this->getQueryMode());
1161 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_PLEDGE
) {
1162 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Pledge_BAO_Query
::extraReturnProperties($this->getQueryMode()));
1163 unset($componentSpecificFields['contribution_status_id']);
1164 unset($componentSpecificFields['pledge_status_id']);
1165 unset($componentSpecificFields['pledge_payment_status_id']);
1167 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CASE
) {
1168 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Case_BAO_Query
::extraReturnProperties($this->getQueryMode()));
1170 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
1171 $componentSpecificFields = array_merge($componentSpecificFields, CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
1172 unset($componentSpecificFields['contribution_status_id']);
1174 return $componentSpecificFields;
1178 * Should payment fields be appended to the export.
1180 * (This is pretty hacky so hopefully this function won't last long - notice
1181 * how obviously it should be part of the above function!).
1183 public function isExportPaymentFields() {
1184 if ($this->getRequestedFields() === NULL
1185 && in_array($this->getQueryMode(), [
1186 CRM_Contact_BAO_Query
::MODE_EVENT
,
1187 CRM_Contact_BAO_Query
::MODE_MEMBER
,
1188 CRM_Contact_BAO_Query
::MODE_PLEDGE
,
1192 elseif ($this->isExportSpecifiedPaymentFields()) {
1199 * Has specific payment fields been requested (as opposed to via all fields).
1201 * If specific fields have been requested then they get added at various points.
1205 public function isExportSpecifiedPaymentFields() {
1206 if ($this->getRequestedFields() !== NULL && $this->hasRequestedComponentPaymentFields()) {
1212 * Get the name of the id field in the table that connects contributions to the export entity.
1214 public function getPaymentTableID() {
1215 if ($this->getRequestedFields() === NULL) {
1217 CRM_Contact_BAO_Query
::MODE_EVENT
=> 'participant_id',
1218 CRM_Contact_BAO_Query
::MODE_MEMBER
=> 'membership_id',
1219 CRM_Contact_BAO_Query
::MODE_PLEDGE
=> 'pledge_payment_id',
1221 return isset($mapping[$this->getQueryMode()]) ?
$mapping[$this->getQueryMode()] : '';
1223 elseif ($this->hasRequestedComponentPaymentFields()) {
1224 return 'participant_id';
1230 * Have component payment fields been requested.
1234 protected function hasRequestedComponentPaymentFields() {
1235 if ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_EVENT
) {
1236 $participantPaymentFields = array_intersect_key($this->getComponentPaymentFields(), $this->getReturnProperties());
1237 if (!empty($participantPaymentFields)) {
1245 * Get fields that indicate payment fields have been requested for a component.
1247 * Ideally this should be protected but making it temporarily public helps refactoring..
1251 public function getComponentPaymentFields() {
1253 'componentPaymentField_total_amount' => ts('Total Amount'),
1254 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1255 'componentPaymentField_received_date' => ts('Date Received'),
1256 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1257 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1262 * Get headers for payment fields.
1264 * Returns an array of contribution fields when the entity supports payment fields and specific fields
1265 * are not specified. This is a transitional function for refactoring legacy code.
1267 public function getPaymentHeaders() {
1268 if ($this->isExportPaymentFields() && !$this->isExportSpecifiedPaymentFields()) {
1269 return $this->getcomponentPaymentFields();
1275 * Get the default properties when not specified.
1277 * In the UI this appears as 'Primary fields only' but in practice it's
1278 * most of the kitchen sink and the hallway closet thrown in.
1280 * Since CRM-952 custom fields are excluded, but no other form of mercy is shown.
1284 public function getDefaultReturnProperties() {
1285 $returnProperties = [];
1286 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
1287 $skippedFields = ($this->getQueryMode() === CRM_Contact_BAO_Query
::MODE_CONTACTS
) ?
[] : [
1293 foreach ($fields as $key => $var) {
1294 if ($key && (substr($key, 0, 6) != 'custom') && !in_array($key, $skippedFields)) {
1295 $returnProperties[$key] = 1;
1298 $returnProperties = array_merge($returnProperties, $this->getAdditionalReturnProperties());
1299 return $returnProperties;
1303 * Add the field to relationship return properties & return it.
1305 * This function is doing both setting & getting which is yuck but it is an interim
1308 * @param array $value
1309 * @param string $relationshipKey
1313 public function setRelationshipReturnProperties($value, $relationshipKey) {
1314 $relationField = $value['name'];
1315 $relIMProviderId = NULL;
1316 $relLocTypeId = CRM_Utils_Array
::value('location_type_id', $value);
1317 $locationName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_Address', 'location_type_id', $relLocTypeId);
1318 $relPhoneTypeId = CRM_Utils_Array
::value('phone_type_id', $value, ($locationName ?
'Primary' : NULL));
1319 $relIMProviderId = CRM_Utils_Array
::value('im_provider_id', $value, ($locationName ?
'Primary' : NULL));
1320 if (in_array($relationField, $this->getValidLocationFields()) && $locationName) {
1321 if ($relationField === 'phone') {
1322 $this->relationshipReturnProperties
[$relationshipKey]['location'][$locationName]['phone-' . $relPhoneTypeId] = 1;
1324 elseif ($relationField === 'im') {
1325 $this->relationshipReturnProperties
[$relationshipKey]['location'][$locationName]['im-' . $relIMProviderId] = 1;
1328 $this->relationshipReturnProperties
[$relationshipKey]['location'][$locationName][$relationField] = 1;
1332 $this->relationshipReturnProperties
[$relationshipKey][$relationField] = 1;
1334 return $this->relationshipReturnProperties
[$relationshipKey];
1338 * Add the main return properties to the household merge properties if needed for merging.
1340 * If we are using household merge we need to add these to the relationship properties to
1343 public function setHouseholdMergeReturnProperties() {
1344 if ($this->isMergeSameHousehold()) {
1345 $returnProperties = $this->getReturnProperties();
1346 $returnProperties = array_diff_key($returnProperties, array_fill_keys(['location_type', 'im_provider'], 1));
1347 foreach ($this->getHouseholdRelationshipTypes() as $householdRelationshipType) {
1348 $this->relationshipReturnProperties
[$householdRelationshipType] = $returnProperties;
1354 * Get the default location fields to request.
1358 public function getValidLocationFields() {
1361 'supplemental_address_1',
1362 'supplemental_address_2',
1363 'supplemental_address_3',
1366 'postal_code_suffix',
1378 * Get the sql column definition for the given field.
1380 * @param string $fieldName
1381 * @param string $columnName
1385 public function getSqlColumnDefinition($fieldName, $columnName) {
1387 // early exit for master_id, CRM-12100
1388 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1389 // also for current_employer, CRM-16939
1390 if ($columnName == 'master_id' ||
$columnName == 'current_employer') {
1391 return "$fieldName varchar(128)";
1394 if (substr($fieldName, -11) == 'campaign_id') {
1396 return "$fieldName varchar(128)";
1399 $queryFields = $this->getQueryFields();
1400 $lookUp = ['prefix_id', 'suffix_id'];
1401 // set the sql columns
1402 if (isset($queryFields[$columnName]['type'])) {
1403 switch ($queryFields[$columnName]['type']) {
1404 case CRM_Utils_Type
::T_INT
:
1405 case CRM_Utils_Type
::T_BOOLEAN
:
1406 if (in_array($columnName, $lookUp)) {
1407 return "$fieldName varchar(255)";
1410 return "$fieldName varchar(16)";
1413 case CRM_Utils_Type
::T_STRING
:
1414 if (isset($queryFields[$columnName]['maxlength'])) {
1415 return "$fieldName varchar({$queryFields[$columnName]['maxlength']})";
1418 return "$fieldName varchar(255)";
1421 case CRM_Utils_Type
::T_TEXT
:
1422 case CRM_Utils_Type
::T_LONGTEXT
:
1423 case CRM_Utils_Type
::T_BLOB
:
1424 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1425 return "$fieldName longtext";
1427 case CRM_Utils_Type
::T_FLOAT
:
1428 case CRM_Utils_Type
::T_ENUM
:
1429 case CRM_Utils_Type
::T_DATE
:
1430 case CRM_Utils_Type
::T_TIME
:
1431 case CRM_Utils_Type
::T_TIMESTAMP
:
1432 case CRM_Utils_Type
::T_MONEY
:
1433 case CRM_Utils_Type
::T_EMAIL
:
1434 case CRM_Utils_Type
::T_URL
:
1435 case CRM_Utils_Type
::T_CCNUM
:
1437 return "$fieldName varchar(32)";
1441 if (substr($fieldName, -3, 3) == '_id') {
1442 return "$fieldName varchar(255)";
1444 elseif (substr($fieldName, -5, 5) == '_note') {
1445 return "$fieldName text";
1454 if (in_array($fieldName, $changeFields)) {
1455 return "$fieldName text";
1458 // set the sql columns for custom data
1459 if (isset($queryFields[$columnName]['data_type'])) {
1461 switch ($queryFields[$columnName]['data_type']) {
1463 // May be option labels, which could be up to 512 characters
1464 $length = max(512, CRM_Utils_Array
::value('text_length', $queryFields[$columnName]));
1465 return "$fieldName varchar($length)";
1468 case 'StateProvince':
1470 return "$fieldName varchar(255)";
1473 return "$fieldName text";
1476 return "$fieldName varchar(255)";
1480 return "$fieldName text";
1488 * Get the munged field name.
1490 * @param string $field
1493 public function getMungedFieldName($field) {
1494 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1495 if ($fieldName == 'id') {
1496 $fieldName = 'civicrm_primary_id';
1502 * In order to respect the history of this class we need to index kinda illogically.
1504 * On the bright side - this stuff is tested within a nano-byte of it's life.
1506 * e.g '2-a-b_Home-City'
1508 * @param string $key
1509 * @param string $relationshipType
1510 * @param string $locationType
1511 * @param $entityLabel
1515 protected function getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityLabel) {
1516 if ($entityLabel ||
$key === 'im') {
1517 // Just cos that's the history...
1518 if ($key !== 'master_id') {
1519 $key = $this->getHeaderForRow($key);
1522 if (!$relationshipType ||
$key !== 'id') {
1523 $key = $this->getMungedFieldName($key);
1525 return $this->getMungedFieldName(
1526 ($relationshipType ?
($relationshipType . '_') : '')
1527 . ($locationType ?
($locationType . '_') : '')
1529 . ($entityLabel ?
('_' . $entityLabel) : '')
1534 * Get the compiled label for the column.
1536 * e.g 'Gender', 'Employee Of-Home-city'
1538 * @param string $key
1539 * @param string $relationshipType
1540 * @param string $locationType
1541 * @param string $entityLabel
1545 protected function getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel) {
1546 return ($relationshipType ?
$this->getRelationshipTypes()[$relationshipType] . '-' : '')
1547 . ($locationType ?
$locationType . '-' : '')
1548 . $this->getHeaderForRow($key)
1549 . ($entityLabel ?
'-' . $entityLabel : '');
1553 * Get the mysql field name key.
1555 * This key is locked in by tests but the reasons for the specific conventions -
1556 * ie. headings are used for keying fields in some cases, are likely
1557 * accidental rather than deliberate.
1559 * This key is used for the output sql array.
1561 * @param string $key
1562 * @param $relationshipType
1563 * @param $locationType
1564 * @param $entityLabel
1568 protected function getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityLabel) {
1569 if ($entityLabel ||
$key === 'im') {
1570 if ($key !== 'state_province' && $key !== 'id') {
1571 // @todo - test removing this - indexing by $key should be fine...
1572 $key = $this->getHeaderForRow($key);
1575 if (!$relationshipType ||
$key !== 'id') {
1576 $key = $this->getMungedFieldName($key);
1578 $fieldKey = $this->getMungedFieldName(
1579 ($relationshipType ?
($relationshipType . '_') : '')
1580 . ($locationType ?
($locationType . '_') : '')
1582 . ($entityLabel ?
('_' . $entityLabel) : '')
1588 * Get params for the where criteria.
1592 public function getWhereParams() {
1593 if (!$this->isPostalableOnly()) {
1596 $params['is_deceased'] = ['is_deceased', '=', 0, CRM_Contact_BAO_Query
::MODE_CONTACTS
];
1597 $params['do_not_mail'] = ['do_not_mail', '=', 0, CRM_Contact_BAO_Query
::MODE_CONTACTS
];
1607 protected function buildRelationshipFieldsForRow(&$row, $contactID, $value, $field) {
1608 foreach (array_keys($value) as $property) {
1609 if ($property === 'location') {
1610 // @todo just undo all this nasty location wrangling!
1611 foreach ($value['location'] as $locationKey => $locationFields) {
1612 foreach (array_keys($locationFields) as $locationField) {
1613 $fieldKey = str_replace(' ', '_', $locationKey . '-' . $locationField);
1614 $row[$field . '_' . $fieldKey] = $this->getRelationshipValue($field, $contactID, $fieldKey);
1619 $row[$field . '_' . $property] = $this->getRelationshipValue($field, $contactID, $property);
1625 * Is this contact a household that is already set to be exported by virtue of it's household members.
1627 * @param int $contactID
1631 protected function isHouseholdToSkip($contactID) {
1632 return in_array($contactID, $this->householdsToSkip
);
1636 * Get the various arrays that we use to structure our output.
1638 * The extraction of these has been moved to a separate function for clarity and so that
1639 * tests can be added - in particular on the $outputHeaders array.
1641 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1642 * as a step on the refactoring path rather than how it should be.
1645 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1646 * alias for the field generated by BAO_Query object.
1647 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1648 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1649 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1650 * I'm too embarassed to discuss here.
1652 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1653 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1654 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1655 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1656 * - a) the function used is more efficient or
1657 * - b) this code is old & outdated. Submit your answers to circular bin or better
1658 * yet find a way to comment them for posterity.
1660 public function getExportStructureArrays() {
1661 $outputColumns = $metadata = [];
1662 $queryFields = $this->getQueryFields();
1663 foreach ($this->getReturnProperties() as $key => $value) {
1664 if (($key != 'location' ||
!is_array($value)) && !$this->isRelationshipTypeKey($key)) {
1665 $outputColumns[$key] = $value;
1666 $this->addOutputSpecification($key);
1668 elseif ($this->isRelationshipTypeKey($key)) {
1669 $outputColumns[$key] = $value;
1670 foreach ($value as $relationField => $relationValue) {
1671 // below block is same as primary block (duplicate)
1672 if (isset($queryFields[$relationField]['title'])) {
1673 $this->addOutputSpecification($relationField, $key);
1675 elseif (is_array($relationValue) && $relationField == 'location') {
1676 // fix header for location type case
1677 foreach ($relationValue as $ltype => $val) {
1678 foreach (array_keys($val) as $fld) {
1679 $type = explode('-', $fld);
1680 $this->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array
::value(1, $type));
1687 foreach ($value as $locationType => $locationFields) {
1688 foreach (array_keys($locationFields) as $locationFieldName) {
1689 $type = explode('-', $locationFieldName);
1691 $actualDBFieldName = $type[0];
1692 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1694 if (!empty($type[1])) {
1695 $daoFieldName .= "-" . $type[1];
1697 $this->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array
::value(1, $type));
1698 $metadata[$daoFieldName] = $this->getMetaDataForField($actualDBFieldName);
1699 $outputColumns[$daoFieldName] = TRUE;
1704 return [$outputColumns, $metadata];
1708 * Get default return property for export based on mode
1711 * Default Return property
1713 public function defaultReturnProperty() {
1714 // hack to add default return property based on export mode
1716 $exportMode = $this->getExportMode();
1717 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
1718 $property = 'contribution_id';
1720 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1721 $property = 'participant_id';
1723 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1724 $property = 'membership_id';
1726 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1727 $property = 'pledge_id';
1729 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1730 $property = 'case_id';
1732 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
1733 $property = 'grant_id';
1735 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1736 $property = 'activity_id';
1742 * Determine the required return properties from the input parameters.
1746 public function determineReturnProperties() {
1747 if ($this->getRequestedFields()) {
1748 $returnProperties = [];
1749 foreach ($this->getRequestedFields() as $key => $value) {
1750 $fieldName = $value['name'];
1751 $locationName = !empty($value['location_type_id']) ? CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_Address', 'location_type_id', $value['location_type_id']) : NULL;
1752 $relationshipTypeKey = !empty($value['relationship_type_id']) ?
$value['relationship_type_id'] . '_' . $value['relationship_direction'] : NULL;
1753 if (!$fieldName ||
$this->isHouseholdMergeRelationshipTypeKey($relationshipTypeKey)) {
1757 if ($this->isRelationshipTypeKey($relationshipTypeKey)) {
1758 $returnProperties[$relationshipTypeKey] = $this->setRelationshipReturnProperties($value, $relationshipTypeKey);
1760 elseif ($locationName) {
1761 if ($fieldName === 'phone') {
1762 $returnProperties['location'][$locationName]['phone-' . $value['phone_type_id'] ??
NULL] = 1;
1764 elseif ($fieldName === 'im') {
1765 $returnProperties['location'][$locationName]['im-' . $value['im_provider_id'] ??
NULL] = 1;
1768 $returnProperties['location'][$locationName][$fieldName] = 1;
1772 //hack to fix component fields
1773 //revert mix of event_id and title
1774 if ($fieldName == 'event_id') {
1775 $returnProperties['event_id'] = 1;
1778 $returnProperties[$fieldName] = 1;
1782 $defaultExportMode = $this->defaultReturnProperty();
1783 if ($defaultExportMode) {
1784 $returnProperties[$defaultExportMode] = 1;
1788 $returnProperties = $this->getDefaultReturnProperties();
1790 if ($this->isMergeSameHousehold()) {
1791 $returnProperties['id'] = 1;
1793 if ($this->isMergeSameAddress()) {
1794 $returnProperties['addressee'] = 1;
1795 $returnProperties['postal_greeting'] = 1;
1796 $returnProperties['email_greeting'] = 1;
1797 $returnProperties['street_name'] = 1;
1798 $returnProperties['household_name'] = 1;
1799 $returnProperties['street_address'] = 1;
1800 $returnProperties['city'] = 1;
1801 $returnProperties['state_province'] = 1;
1804 return $returnProperties;
1808 * @param object $query
1809 * CRM_Contact_BAO_Query
1814 public function getGroupBy($query) {
1816 $returnProperties = $this->getReturnProperties();
1817 $exportMode = $this->getExportMode();
1818 $queryMode = $this->getQueryMode();
1819 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
1820 CRM_Utils_Array
::value('notes', $returnProperties) ||
1822 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
1824 $groupBy = "contact_a.id";
1827 switch ($exportMode) {
1828 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1829 $groupBy = 'civicrm_contribution.id';
1830 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
1831 // especial group by when soft credit columns are included
1832 $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
1836 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1837 $groupBy = 'civicrm_participant.id';
1840 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1841 $groupBy = "civicrm_membership.id";
1845 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
1846 $groupBy = "civicrm_activity.id ";
1849 return $groupBy ?
' GROUP BY ' . implode(', ', (array) $groupBy) : '';
1853 * @param int $contactId
1857 public function replaceMergeTokens($contactId) {
1862 'postal_greeting' => $this->getPostalGreetingTemplate(),
1863 'addressee' => $this->getAddresseeGreetingTemplate(),
1865 foreach ($greetingFields as $greeting => $greetingLabel) {
1866 $tokens = CRM_Utils_Token
::getTokens($greetingLabel);
1867 if (!empty($tokens)) {
1868 if (empty($contact)) {
1873 $contact = civicrm_api('contact', 'get', $values);
1875 if (!empty($contact['is_error'])) {
1878 $contact = $contact['values'][$contact['id']];
1881 $tokens = ['contact' => $greetingLabel];
1882 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1889 * Build array for merging same addresses.
1892 * @param bool $sharedAddress
1896 public function buildMasterCopyArray($sql, $sharedAddress = FALSE) {
1898 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1899 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1901 $merge = $parents = [];
1902 $dao = CRM_Core_DAO
::executeQuery($sql);
1904 while ($dao->fetch()) {
1905 $masterID = $dao->master_id
;
1906 $copyID = $dao->copy_id
;
1907 $masterPostalGreeting = $dao->master_postal_greeting
;
1908 $masterAddressee = $dao->master_addressee
;
1909 $copyAddressee = $dao->copy_addressee
;
1911 if (!$sharedAddress) {
1912 if (!isset($this->contactGreetingFields
[$dao->master_contact_id
])) {
1913 $this->contactGreetingFields
[$dao->master_contact_id
] = $this->replaceMergeTokens($dao->master_contact_id
);
1915 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1916 $this->contactGreetingFields
[$dao->master_contact_id
], $dao->master_postal_greeting
1918 $masterAddressee = CRM_Utils_Array
::value('addressee',
1919 $this->contactGreetingFields
[$dao->master_contact_id
], $dao->master_addressee
1922 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1923 $this->contactGreetingFields
[$dao->copy_contact_id
] = $this->replaceMergeTokens($dao->copy_contact_id
);
1925 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1926 $this->contactGreetingFields
[$dao->copy_contact_id
], $dao->copy_postal_greeting
1928 $copyAddressee = CRM_Utils_Array
::value('addressee',
1929 $this->contactGreetingFields
[$dao->copy_contact_id
], $dao->copy_addressee
1933 if (!isset($merge[$masterID])) {
1934 // check if this is an intermediate child
1935 // this happens if there are 3 or more matches a,b, c
1936 // the above query will return a, b / a, c / b, c
1937 // we might be doing a bit more work, but for now its ok, unless someone
1938 // knows how to fix the query above
1939 if (isset($parents[$masterID])) {
1940 $masterID = $parents[$masterID];
1943 $merge[$masterID] = [
1944 'addressee' => $masterAddressee,
1946 'postalGreeting' => $masterPostalGreeting,
1948 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1951 $parents[$copyID] = $masterID;
1953 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1955 if ($copyPostalGreeting) {
1956 $this->trimNonTokensFromAddressString($copyPostalGreeting,
1957 $postalOptions[$dao->copy_postal_greeting_id
],
1958 $this->getPostalGreetingTemplate()
1960 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1961 // if there happens to be a duplicate, remove it
1962 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1965 if ($copyAddressee) {
1966 $this->trimNonTokensFromAddressString($copyAddressee,
1967 $addresseeOptions[$dao->copy_addressee_id
],
1968 $this->getAddresseeGreetingTemplate()
1970 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1973 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1980 * Merge contacts with the same address.
1982 * @param $sqlColumns
1983 * @param array $exportParams
1985 public function mergeSameAddress(&$sqlColumns, $exportParams) {
1986 $greetingOptions = CRM_Export_Form_Select
::getGreetingOptions();
1988 if (!empty($greetingOptions)) {
1989 // Greeting options is keyed by 'postal_greeting' or 'addressee'.
1990 foreach ($greetingOptions as $key => $value) {
1991 if ($option = CRM_Utils_Array
::value($key, $exportParams)) {
1992 if ($greetingOptions[$key][$option] == ts('Other')) {
1993 $exportParams[$key] = $exportParams["{$key}_other"];
1995 elseif ($greetingOptions[$key][$option] == ts('List of names')) {
1996 $exportParams[$key] = '';
1999 $exportParams[$key] = $greetingOptions[$key][$option];
2004 if (!empty($exportParams['postal_greeting'])) {
2005 $this->setPostalGreetingTemplate($exportParams['postal_greeting']);
2007 if (!empty($exportParams['addressee'])) {
2008 $this->setAddresseeGreetingTemplate($exportParams['addressee']);
2011 $tableName = $this->getTemporaryTable();
2012 // check if any records are present based on if they have used shared address feature,
2013 // and not based on if city / state .. matches.
2015 SELECT r1.id as copy_id,
2016 r1.civicrm_primary_id as copy_contact_id,
2017 r1.addressee as copy_addressee,
2018 r1.addressee_id as copy_addressee_id,
2019 r1.postal_greeting as copy_postal_greeting,
2020 r1.postal_greeting_id as copy_postal_greeting_id,
2022 r2.civicrm_primary_id as master_contact_id,
2023 r2.postal_greeting as master_postal_greeting,
2024 r2.postal_greeting_id as master_postal_greeting_id,
2025 r2.addressee as master_addressee,
2026 r2.addressee_id as master_addressee_id
2028 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
2029 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
2031 $linkedMerge = $this->buildMasterCopyArray($sql, TRUE);
2033 // find all the records that have the same street address BUT not in a household
2034 // require match on city and state as well
2036 SELECT r1.id as master_id,
2037 r1.civicrm_primary_id as master_contact_id,
2038 r1.postal_greeting as master_postal_greeting,
2039 r1.postal_greeting_id as master_postal_greeting_id,
2040 r1.addressee as master_addressee,
2041 r1.addressee_id as master_addressee_id,
2043 r2.civicrm_primary_id as copy_contact_id,
2044 r2.postal_greeting as copy_postal_greeting,
2045 r2.postal_greeting_id as copy_postal_greeting_id,
2046 r2.addressee as copy_addressee,
2047 r2.addressee_id as copy_addressee_id
2049 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
2050 r1.city = r2.city AND
2051 r1.state_province_id = r2.state_province_id )
2052 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
2053 AND ( r2.household_name IS NULL OR r2.household_name = '' )
2054 AND ( r1.street_address != '' )
2058 $merge = $this->buildMasterCopyArray($sql);
2060 // unset ids from $merge already present in $linkedMerge
2061 foreach ($linkedMerge as $masterID => $values) {
2062 $keys = [$masterID];
2063 $keys = array_merge($keys, array_keys($values['copy']));
2064 foreach ($merge as $mid => $vals) {
2065 if (in_array($mid, $keys)) {
2066 unset($merge[$mid]);
2069 foreach ($values['copy'] as $copyId) {
2070 if (in_array($copyId, $keys)) {
2071 unset($merge[$mid]['copy'][$copyId]);
2077 $merge = $merge +
$linkedMerge;
2079 foreach ($merge as $masterID => $values) {
2082 SET addressee = %1, postal_greeting = %2, email_greeting = %3
2086 1 => [$values['addressee'], 'String'],
2087 2 => [$values['postalGreeting'], 'String'],
2088 3 => [$values['emailGreeting'], 'String'],
2089 4 => [$masterID, 'Integer'],
2091 CRM_Core_DAO
::executeQuery($sql, $params);
2093 // delete all copies
2094 $deleteIDs = array_keys($values['copy']);
2095 $deleteIDString = implode(',', $deleteIDs);
2097 DELETE FROM $tableName
2098 WHERE id IN ( $deleteIDString )
2100 CRM_Core_DAO
::executeQuery($sql);
2103 // unset temporary columns that were added for postal mailing format
2104 // @todo - this part is pretty close to ready to be removed....
2105 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
2106 $unsetKeys = array_keys($sqlColumns);
2107 foreach ($unsetKeys as $headerKey => $sqlColKey) {
2108 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
2109 unset($sqlColumns[$sqlColKey]);
2116 * The function unsets static part of the string, if token is the dynamic part.
2118 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
2119 * i.e 'Hello Alan' => converted to => 'Alan'
2121 * @param string $parsedString
2122 * @param string $defaultGreeting
2123 * @param string $greetingLabel
2127 public function trimNonTokensFromAddressString(
2128 &$parsedString, $defaultGreeting,
2131 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
2133 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
2134 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
2135 foreach ($stringsToBeReplaced as $key => $string) {
2136 // to keep one space
2137 $stringsToBeReplaced[$key] = ltrim($string);
2139 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
2141 return $parsedString;
2145 * Preview export output.
2150 public function getPreview($limit) {
2152 list($outputColumns, $metadata) = $this->getExportStructureArrays();
2153 $query = $this->runQuery([], '');
2154 CRM_Core_DAO
::disableFullGroupByMode();
2155 $result = CRM_Core_DAO
::executeQuery($query[1] . ' LIMIT ' . (int) $limit);
2156 CRM_Core_DAO
::reenableFullGroupByMode();
2157 while ($result->fetch()) {
2158 $rows[] = $this->buildRow($query[0], $result, $outputColumns, $metadata, [], []);