3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
35 * This class contains the functions for Component export
38 class CRM_Export_BAO_Export
{
39 // increase this number a lot to avoid making too many queries
40 // LIMIT is not much faster than a no LIMIT query
42 const EXPORT_ROW_COUNT
= 100000;
44 protected static $relationshipReturnProperties = [];
47 * Key representing the head of household in the relationship array.
53 protected static $headOfHouseholdRelationshipKey;
56 * Key representing the head of household in the relationship array.
62 protected static $memberOfHouseholdRelationshipKey;
65 * Key representing the head of household in the relationship array.
67 * e.g. ['8_b_a' => 'Household Member Is', '8_a_b = 'Household Member Of'.....]
71 protected static $relationshipTypes = [];
75 * @param $locationTypeFields
76 * @param $relationshipTypes
80 protected static function setRelationshipReturnProperties($value, $locationTypeFields, $relationshipTypes) {
81 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
82 $relPhoneTypeId = $relIMProviderId = NULL;
83 if (!empty($value[2])) {
84 $relationField = CRM_Utils_Array
::value(2, $value);
85 if (trim(CRM_Utils_Array
::value(3, $value))) {
86 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
89 $relLocTypeId = 'Primary';
92 if ($relationField == 'phone') {
93 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
95 elseif ($relationField == 'im') {
96 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
99 elseif (!empty($value[4])) {
100 $relationField = CRM_Utils_Array
::value(4, $value);
101 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
102 if ($relationField == 'phone') {
103 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
105 elseif ($relationField == 'im') {
106 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
109 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
110 if ($relPhoneTypeId) {
111 self
::$relationshipReturnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
113 elseif ($relIMProviderId) {
114 self
::$relationshipReturnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
117 self
::$relationshipReturnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
121 self
::$relationshipReturnProperties[$relationshipTypes][$relationField] = 1;
123 return array($relationField);
129 public static function getRelationshipReturnProperties() {
130 return self
::relationshipReturnProperties
;
134 * Get default return property for export based on mode
136 * @param int $exportMode
139 * @return string $property
140 * Default Return property
142 public static function defaultReturnProperty($exportMode) {
143 // hack to add default return property based on export mode
145 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
146 $property = 'contribution_id';
148 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
149 $property = 'participant_id';
151 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
152 $property = 'membership_id';
154 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
155 $property = 'pledge_id';
157 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
158 $property = 'case_id';
160 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
161 $property = 'grant_id';
163 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
164 $property = 'activity_id';
170 * Get Export component
172 * @param int $exportMode
175 * @return string $component
176 * CiviCRM Export Component
178 public static function exportComponent($exportMode) {
179 switch ($exportMode) {
180 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
181 $component = 'civicrm_contribution';
184 case CRM_Export_Form_Select
::EVENT_EXPORT
:
185 $component = 'civicrm_participant';
188 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
189 $component = 'civicrm_membership';
192 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
193 $component = 'civicrm_pledge';
196 case CRM_Export_Form_Select
::GRANT_EXPORT
:
197 $component = 'civicrm_grant';
204 * Get Query Group By Clause
205 * @param int $exportMode
207 * @param string $queryMode
209 * @param array $returnProperties
211 * @param object $query
212 * CRM_Contact_BAO_Query
214 * @return string $groupBy
217 public static function getGroupBy($exportMode, $queryMode, $returnProperties, $query) {
219 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
220 CRM_Utils_Array
::value('notes', $returnProperties) ||
222 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
224 $groupBy = "contact_a.id";
227 switch ($exportMode) {
228 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
229 $groupBy = 'civicrm_contribution.id';
230 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
231 // especial group by when soft credit columns are included
232 $groupBy = array('contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id');
236 case CRM_Export_Form_Select
::EVENT_EXPORT
:
237 $groupBy = 'civicrm_participant.id';
240 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
241 $groupBy = "civicrm_membership.id";
245 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
246 $groupBy = "civicrm_activity.id ";
249 if (!empty($groupBy)) {
250 if (!Civi
::settings()->get('searchPrimaryDetailsOnly')) {
251 CRM_Core_DAO
::disableFullGroupByMode();
253 $groupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($query->_select
, $groupBy);
260 * Define extra properties for the export based on query mode
262 * @param string $queryMode
264 * @return array $extraProperties
267 public static function defineExtraProperties($queryMode) {
268 switch ($queryMode) {
269 case CRM_Contact_BAO_Query
::MODE_EVENT
:
270 $paymentFields = TRUE;
271 $paymentTableId = 'participant_id';
272 $extraReturnProperties = array();
275 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
276 $paymentFields = TRUE;
277 $paymentTableId = 'membership_id';
278 $extraReturnProperties = array();
281 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
282 $extraReturnProperties = CRM_Pledge_BAO_Query
::extraReturnProperties($queryMode);
283 $paymentFields = TRUE;
284 $paymentTableId = 'pledge_payment_id';
287 case CRM_Contact_BAO_Query
::MODE_CASE
:
288 $extraReturnProperties = CRM_Case_BAO_Query
::extraReturnProperties($queryMode);
289 $paymentFields = FALSE;
290 $paymentTableId = '';
294 $paymentFields = FALSE;
295 $paymentTableId = '';
296 $extraReturnProperties = array();
298 $extraProperties = array(
299 'paymentFields' => $paymentFields,
300 'paymentTableId' => $paymentTableId,
301 'extraReturnProperties' => $extraReturnProperties,
303 return $extraProperties;
307 * Get the list the export fields.
309 * @param int $selectAll
310 * User preference while export.
313 * @param array $params
314 * Associated array of fields.
315 * @param string $order
317 * @param array $fields
318 * Associated array of fields.
319 * @param array $moreReturnProperties
320 * Additional return fields.
321 * @param int $exportMode
323 * @param string $componentClause
325 * @param string $componentTable
327 * @param bool $mergeSameAddress
328 * Merge records if they have same address.
329 * @param bool $mergeSameHousehold
330 * Merge records if they belong to the same household.
332 * @param array $exportParams
333 * @param string $queryOperator
336 * An array can be requested from within a unit test.
338 * @throws \CRM_Core_Exception
340 public static function exportComponents(
346 $moreReturnProperties = NULL,
347 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
348 $componentClause = NULL,
349 $componentTable = NULL,
350 $mergeSameAddress = FALSE,
351 $mergeSameHousehold = FALSE,
352 $exportParams = array(),
353 $queryOperator = 'AND'
356 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $queryOperator);
357 $returnProperties = array();
358 $paymentFields = $selectedPaymentFields = $paymentTableId = FALSE;
360 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
361 // Warning - this imProviders var is used in a somewhat fragile way - don't rename it
362 // without manually testing the export of IM provider still works.
363 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
364 self
::$relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
373 //also merge Head of Household
374 self
::$memberOfHouseholdRelationshipKey = CRM_Utils_Array
::key('Household Member of', self
::$relationshipTypes);
375 self
::$headOfHouseholdRelationshipKey = CRM_Utils_Array
::key('Head of Household for', self
::$relationshipTypes);
377 $queryMode = $processor->getQueryMode();
380 //construct return properties
381 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
382 $locationTypeFields = array(
384 'supplemental_address_1',
385 'supplemental_address_2',
386 'supplemental_address_3',
389 'postal_code_suffix',
399 foreach ($fields as $key => $value) {
400 $fieldName = CRM_Utils_Array
::value(1, $value);
405 if (array_key_exists($fieldName, self
::$relationshipTypes) && (!empty($value[2]) ||
!empty($value[4]))) {
406 self
::setRelationshipReturnProperties($value, $locationTypeFields, $fieldName);
407 // @todo we can later not add this to this array but maintain a separate array.
408 $returnProperties = array_merge($returnProperties, self
::$relationshipReturnProperties);
410 elseif (is_numeric(CRM_Utils_Array
::value(2, $value))) {
411 $locTypeId = $value[2];
412 if ($fieldName == 'phone') {
413 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . CRM_Utils_Array
::value(3, $value)] = 1;
415 elseif ($fieldName == 'im') {
416 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . CRM_Utils_Array
::value(3, $value)] = 1;
419 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
423 //hack to fix component fields
424 //revert mix of event_id and title
425 if ($fieldName == 'event_id') {
426 $returnProperties['event_id'] = 1;
429 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
430 array_key_exists($fieldName, self
::componentPaymentFields())
432 $selectedPaymentFields = TRUE;
433 $paymentTableId = 'participant_id';
434 $returnProperties[$fieldName] = 1;
437 $returnProperties[$fieldName] = 1;
441 $defaultExportMode = self
::defaultReturnProperty($exportMode);
442 if ($defaultExportMode) {
443 $returnProperties[$defaultExportMode] = 1;
447 $returnProperties = [
448 'location_type' => 1,
450 'phone_type_id' => 1,
452 'current_employer' => 1,
454 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
455 foreach ($fields as $key => $var) {
456 if ($key && (substr($key, 0, 6) != 'custom')) {
458 $returnProperties[$key] = 1;
462 $extraProperties = self
::defineExtraProperties($queryMode);
463 $paymentFields = $extraProperties['paymentFields'];
464 $extraReturnProperties = $extraProperties['extraReturnProperties'];
465 $paymentTableId = $extraProperties['paymentTableId'];
467 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
468 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
469 if ($queryMode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
470 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
471 $componentReturnProperties = array_merge(
472 $componentReturnProperties,
473 CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
475 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
477 if (!empty($extraReturnProperties)) {
478 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
481 // unset non exportable fields for components
482 $nonExpoFields = array(
486 'contribution_status_id',
488 'pledge_payment_status_id',
490 foreach ($nonExpoFields as $value) {
491 unset($returnProperties[$value]);
496 if ($mergeSameAddress) {
497 //make sure the addressee fields are selected
498 //while using merge same address feature
499 $returnProperties['addressee'] = 1;
500 $returnProperties['postal_greeting'] = 1;
501 $returnProperties['email_greeting'] = 1;
502 $returnProperties['street_name'] = 1;
503 $returnProperties['household_name'] = 1;
504 $returnProperties['street_address'] = 1;
505 $returnProperties['city'] = 1;
506 $returnProperties['state_province'] = 1;
508 // some columns are required for assistance incase they are not already present
509 $exportParams['merge_same_address']['temp_columns'] = array();
510 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
511 foreach ($tempColumns as $column) {
512 if (!array_key_exists($column, $returnProperties)) {
513 $returnProperties[$column] = 1;
514 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
515 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
520 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
521 // If an Additional Group is selected, then all contacts in that group are
522 // added to the export set (filtering out duplicates).
524 INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_contact gc WHERE gc.group_id = {$exportParams['additional_group']} ON DUPLICATE KEY UPDATE {$componentTable}.contact_id = gc.contact_id";
525 CRM_Core_DAO
::executeQuery($query);
528 if ($moreReturnProperties) {
530 if (!empty($moreReturnProperties['group'])) {
531 unset($moreReturnProperties['group']);
532 $moreReturnProperties['groups'] = 1;
534 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
537 $exportParams['postal_mailing_export']['temp_columns'] = array();
538 if ($exportParams['exportOption'] == 2 &&
539 isset($exportParams['postal_mailing_export']) &&
540 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
542 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
543 foreach ($postalColumns as $column) {
544 if (!array_key_exists($column, $returnProperties)) {
545 $returnProperties[$column] = 1;
546 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
551 // rectify params to what proximity search expects if there is a value for prox_distance
553 if (!empty($params)) {
554 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
557 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
559 if ($mergeSameHousehold == 1) {
560 if (empty($returnProperties['id'])) {
561 $returnProperties['id'] = 1;
564 foreach ($returnProperties as $key => $value) {
565 if (!array_key_exists($key, self
::$relationshipTypes)) {
566 $returnProperties[self
::$memberOfHouseholdRelationshipKey][$key] = $value;
567 $returnProperties[self
::$headOfHouseholdRelationshipKey][$key] = $value;
571 unset($returnProperties[self
::$memberOfHouseholdRelationshipKey]['location_type']);
572 unset($returnProperties[self
::$memberOfHouseholdRelationshipKey]['im_provider']);
573 unset($returnProperties[self
::$headOfHouseholdRelationshipKey]['location_type']);
574 unset($returnProperties[self
::$headOfHouseholdRelationshipKey]['im_provider']);
577 list($relationQuery, $allRelContactArray) = self
::buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode);
579 // make sure the groups stuff is included only if specifically specified
580 // by the fields param (CRM-1969), else we limit the contacts outputted to only
581 // ones that are part of a group
582 if (!empty($returnProperties['groups'])) {
583 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
584 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
585 // total hack for export, CRM-3618
586 $from = str_replace($oldClause,
592 if (!$selectAll && $componentTable) {
593 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
595 elseif ($componentClause) {
597 $where = "WHERE $componentClause";
600 $where .= " AND $componentClause";
604 // CRM-13982 - check if is deleted
605 $excludeTrashed = TRUE;
606 foreach ($params as $value) {
607 if ($value[0] == 'contact_is_deleted') {
608 $excludeTrashed = FALSE;
611 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
614 $where = "WHERE $trashClause";
617 $where .= " AND $trashClause";
620 $queryString = "$select $from $where $having";
622 $groupBy = self
::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
624 $queryString .= $groupBy;
627 // always add contact_a.id to the ORDER clause
628 // so the order is deterministic
630 if (strpos('contact_a.id', $order) === FALSE) {
631 $order .= ", contact_a.id";
634 list($field, $dir) = explode(' ', $order, 2);
635 $field = trim($field);
636 if (!empty($returnProperties[$field])) {
638 $queryString .= " ORDER BY $order";
642 $addPaymentHeader = FALSE;
644 $paymentDetails = array();
645 if ($paymentFields ||
$selectedPaymentFields) {
647 // get payment related in for event and members
648 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
649 //get all payment headers.
650 // If we haven't selected specific payment fields, load in all the
652 if (!$selectedPaymentFields) {
653 $paymentHeaders = self
::componentPaymentFields();
654 if (!empty($paymentDetails)) {
655 $addPaymentHeader = TRUE;
658 // If we have selected specific payment fields, leave the payment headers
659 // as an empty array; the headers for each selected field will be added
662 $paymentHeaders = array();
664 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
667 $componentDetails = array();
670 $rowCount = self
::EXPORT_ROW_COUNT
;
672 // we write to temp table often to avoid using too much memory
677 // for CRM-3157 purposes
678 $i18n = CRM_Core_I18n
::singleton();
680 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor, $relationQuery, $selectedPaymentFields);
682 $limitReached = FALSE;
683 while (!$limitReached) {
684 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
685 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
686 // If this is less than our limit by the end of the iteration we do not need to run the query again to
687 // check if some remain.
688 $rowsThisIteration = 0;
690 while ($iterationDAO->fetch()) {
692 $rowsThisIteration++
;
694 $query->convertToPseudoNames($iterationDAO);
696 //first loop through output columns so that we return what is required, and in same order.
697 foreach ($outputColumns as $field => $value) {
699 // add im_provider to $dao object
700 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
701 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
704 //build row values (data)
706 if (property_exists($iterationDAO, $field)) {
707 $fieldValue = $iterationDAO->$field;
708 // to get phone type from phone type id
709 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
710 $fieldValue = $phoneTypes[$fieldValue];
712 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
713 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
715 elseif (strstr($field, 'master_id')) {
716 $masterAddressId = NULL;
717 if (isset($iterationDAO->$field)) {
718 $masterAddressId = $iterationDAO->$field;
720 // get display name of contact that address is shared.
721 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
725 if (array_key_exists($field, self
::$relationshipTypes)) {
726 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
727 $relationQuery[$field]->convertToPseudoNames($relDAO);
728 self
::fetchRelationshipDetails($relDAO, $value, $field, $row);
731 $row[$field] = self
::getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $selectedPaymentFields, $paymentDetails, $paymentTableId);
735 // add payment headers if required
736 if ($addPaymentHeader && $paymentFields) {
737 // @todo rather than do this for every single row do it before the loop starts.
738 // where other header definitions take place.
739 $headerRows = array_merge($headerRows, $paymentHeaders);
740 foreach (array_keys($paymentHeaders) as $paymentHdr) {
741 self
::sqlColumnDefn($processor, $sqlColumns, $paymentHdr);
746 $exportTempTable = self
::createTempTable($sqlColumns);
749 //build header only once
752 // If specific payment fields have been selected for export, payment
753 // data will already be in $row. Otherwise, add payment related
754 // information, if appropriate.
755 if ($addPaymentHeader) {
756 if (!$selectedPaymentFields) {
757 if ($paymentFields) {
758 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
759 if (!is_array($paymentData) ||
empty($paymentData)) {
760 $paymentData = $nullContributionDetails;
762 $row = array_merge($row, $paymentData);
764 elseif (!empty($paymentDetails)) {
765 $row = array_merge($row, $nullContributionDetails);
769 //remove organization name for individuals if it is set for current employer
770 if (!empty($row['contact_type']) &&
771 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
773 $row['organization_name'] = '';
776 // add component info
777 // write the row to a file
778 $componentDetails[] = $row;
780 // output every $tempRowCount rows
781 if ($count %
$tempRowCount == 0) {
782 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
783 $componentDetails = array();
786 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
787 $limitReached = TRUE;
789 $offset +
= $rowCount;
792 if ($exportTempTable) {
793 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
795 // if postalMailing option is checked, exclude contacts who are deceased, have
796 // "Do not mail" privacy setting, or have no street address
797 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
798 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
800 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
803 // do merge same address and merge same household processing
804 if ($mergeSameAddress) {
805 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
808 // merge the records if they have corresponding households
809 if ($mergeSameHousehold) {
810 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$memberOfHouseholdRelationshipKey);
811 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$headOfHouseholdRelationshipKey);
815 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
817 // In order to be able to write a unit test against this function we need to suppress
818 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
819 if (empty($exportParams['suppress_csv_for_testing'])) {
820 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
823 // return tableName and sqlColumns in test context
824 return array($exportTempTable, $sqlColumns);
827 // delete the export temp table and component table
828 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
829 CRM_Core_DAO
::executeQuery($sql);
830 CRM_Core_DAO
::reenableFullGroupByMode();
831 CRM_Utils_System
::civiExit();
834 CRM_Core_DAO
::reenableFullGroupByMode();
835 throw new CRM_Core_Exception(ts('No records to export'));
840 * Name of the export file based on mode.
842 * @param string $output
850 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
852 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
853 return ts('CiviCRM Contact Search');
855 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
856 return ts('CiviCRM Contribution Search');
858 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
859 return ts('CiviCRM Member Search');
861 case CRM_Export_Form_Select
::EVENT_EXPORT
:
862 return ts('CiviCRM Participant Search');
864 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
865 return ts('CiviCRM Pledge Search');
867 case CRM_Export_Form_Select
::CASE_EXPORT
:
868 return ts('CiviCRM Case Search');
870 case CRM_Export_Form_Select
::GRANT_EXPORT
:
871 return ts('CiviCRM Grant Search');
873 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
874 return ts('CiviCRM Activity Search');
879 * Handle import error file creation.
881 public static function invoke() {
882 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
883 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
884 if (empty($parserName) ||
empty($type)) {
888 // clean and ensure parserName is a valid string
889 $parserName = CRM_Utils_String
::munge($parserName);
890 $parserClass = explode('_', $parserName);
892 // make sure parserClass is in the CRM namespace and
893 // at least 3 levels deep
894 if ($parserClass[0] == 'CRM' &&
895 count($parserClass) >= 3
897 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
898 // ensure the functions exists
899 if (method_exists($parserName, 'errorFileName') &&
900 method_exists($parserName, 'saveFileName')
902 $errorFileName = $parserName::errorFileName($type);
903 $saveFileName = $parserName::saveFileName($type);
904 if (!empty($errorFileName) && !empty($saveFileName)) {
905 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
906 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
907 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
908 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
909 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
911 readfile($errorFileName);
915 CRM_Utils_System
::civiExit();
919 * @param $customSearchClass
923 public static function exportCustom($customSearchClass, $formValues, $order) {
924 $ext = CRM_Extension_System
::singleton()->getMapper();
925 if (!$ext->isExtensionClass($customSearchClass)) {
926 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
929 require_once $ext->classToPath($customSearchClass);
931 $search = new $customSearchClass($formValues);
933 $includeContactIDs = FALSE;
934 if ($formValues['radio_ts'] == 'ts_sel') {
935 $includeContactIDs = TRUE;
938 $sql = $search->all(0, 0, $order, $includeContactIDs);
940 $columns = $search->columns();
942 $header = array_keys($columns);
943 $fields = array_values($columns);
946 $dao = CRM_Core_DAO
::executeQuery($sql);
948 if (method_exists($search, 'alterRow')) {
951 while ($dao->fetch()) {
954 foreach ($fields as $field) {
955 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
956 $row[$field] = $dao->$unqualified_field;
959 $search->alterRow($row);
964 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
965 CRM_Utils_System
::civiExit();
969 * @param \CRM_Export_BAO_ExportProcessor $processor
973 public static function sqlColumnDefn($processor, &$sqlColumns, $field) {
974 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
977 $queryFields = $processor->getQueryFields();
979 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
980 if ($fieldName == 'id') {
981 $fieldName = 'civicrm_primary_id';
984 // early exit for master_id, CRM-12100
985 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
986 // also for current_employer, CRM-16939
987 if ($fieldName == 'master_id' ||
$fieldName == 'current_employer') {
988 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
992 if (substr($fieldName, -11) == 'campaign_id') {
994 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
998 $lookUp = array('prefix_id', 'suffix_id');
999 // set the sql columns
1000 if (isset($queryFields[$field]['type'])) {
1001 switch ($queryFields[$field]['type']) {
1002 case CRM_Utils_Type
::T_INT
:
1003 case CRM_Utils_Type
::T_BOOLEAN
:
1004 if (in_array($field, $lookUp)) {
1005 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1008 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1012 case CRM_Utils_Type
::T_STRING
:
1013 if (isset($queryFields[$field]['maxlength'])) {
1014 $sqlColumns[$fieldName] = "$fieldName varchar({$queryFields[$field]['maxlength']})";
1017 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1021 case CRM_Utils_Type
::T_TEXT
:
1022 case CRM_Utils_Type
::T_LONGTEXT
:
1023 case CRM_Utils_Type
::T_BLOB
:
1024 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1025 $sqlColumns[$fieldName] = "$fieldName longtext";
1028 case CRM_Utils_Type
::T_FLOAT
:
1029 case CRM_Utils_Type
::T_ENUM
:
1030 case CRM_Utils_Type
::T_DATE
:
1031 case CRM_Utils_Type
::T_TIME
:
1032 case CRM_Utils_Type
::T_TIMESTAMP
:
1033 case CRM_Utils_Type
::T_MONEY
:
1034 case CRM_Utils_Type
::T_EMAIL
:
1035 case CRM_Utils_Type
::T_URL
:
1036 case CRM_Utils_Type
::T_CCNUM
:
1038 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1043 if (substr($fieldName, -3, 3) == '_id') {
1044 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1046 elseif (substr($fieldName, -5, 5) == '_note') {
1047 $sqlColumns[$fieldName] = "$fieldName text";
1050 $changeFields = array(
1056 if (in_array($fieldName, $changeFields)) {
1057 $sqlColumns[$fieldName] = "$fieldName text";
1060 // set the sql columns for custom data
1061 if (isset($queryFields[$field]['data_type'])) {
1063 switch ($queryFields[$field]['data_type']) {
1065 // May be option labels, which could be up to 512 characters
1066 $length = max(512, CRM_Utils_Array
::value('text_length', $queryFields[$field]));
1067 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1071 case 'StateProvince':
1073 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1077 $sqlColumns[$fieldName] = "$fieldName text";
1081 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1086 $sqlColumns[$fieldName] = "$fieldName text";
1094 * @param string $tableName
1096 * @param $sqlColumns
1098 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1099 if (empty($details)) {
1108 $id = CRM_Core_DAO
::singleValueQuery($sql);
1113 $sqlClause = array();
1115 foreach ($details as $dontCare => $row) {
1117 $valueString = array($id);
1118 foreach ($row as $dontCare => $value) {
1119 if (empty($value)) {
1120 $valueString[] = "''";
1123 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1126 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1129 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1131 $sqlValueString = implode(",\n", $sqlClause);
1134 INSERT INTO $tableName $sqlColumnString
1135 VALUES $sqlValueString
1137 CRM_Core_DAO
::executeQuery($sql);
1141 * @param $sqlColumns
1145 public static function createTempTable(&$sqlColumns) {
1146 //creating a temporary table for the search result that need be exported
1147 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export')->getName();
1149 // also create the sql table
1150 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1151 CRM_Core_DAO
::executeQuery($sql);
1154 CREATE TABLE {$exportTempTable} (
1155 id int unsigned NOT NULL AUTO_INCREMENT,
1157 $sql .= implode(",\n", array_values($sqlColumns));
1162 // add indexes for street_address and household_name if present
1163 $addIndices = array(
1166 'civicrm_primary_id',
1169 foreach ($addIndices as $index) {
1170 if (isset($sqlColumns[$index])) {
1172 INDEX index_{$index}( $index )
1178 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1181 CRM_Core_DAO
::executeQuery($sql);
1182 return $exportTempTable;
1186 * @param string $tableName
1187 * @param $headerRows
1188 * @param $sqlColumns
1189 * @param array $exportParams
1191 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1192 // check if any records are present based on if they have used shared address feature,
1193 // and not based on if city / state .. matches.
1195 SELECT r1.id as copy_id,
1196 r1.civicrm_primary_id as copy_contact_id,
1197 r1.addressee as copy_addressee,
1198 r1.addressee_id as copy_addressee_id,
1199 r1.postal_greeting as copy_postal_greeting,
1200 r1.postal_greeting_id as copy_postal_greeting_id,
1202 r2.civicrm_primary_id as master_contact_id,
1203 r2.postal_greeting as master_postal_greeting,
1204 r2.postal_greeting_id as master_postal_greeting_id,
1205 r2.addressee as master_addressee,
1206 r2.addressee_id as master_addressee_id
1208 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1209 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1211 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1213 // find all the records that have the same street address BUT not in a household
1214 // require match on city and state as well
1216 SELECT r1.id as master_id,
1217 r1.civicrm_primary_id as master_contact_id,
1218 r1.postal_greeting as master_postal_greeting,
1219 r1.postal_greeting_id as master_postal_greeting_id,
1220 r1.addressee as master_addressee,
1221 r1.addressee_id as master_addressee_id,
1223 r2.civicrm_primary_id as copy_contact_id,
1224 r2.postal_greeting as copy_postal_greeting,
1225 r2.postal_greeting_id as copy_postal_greeting_id,
1226 r2.addressee as copy_addressee,
1227 r2.addressee_id as copy_addressee_id
1229 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1230 r1.city = r2.city AND
1231 r1.state_province_id = r2.state_province_id )
1232 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1233 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1234 AND ( r1.street_address != '' )
1238 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1240 // unset ids from $merge already present in $linkedMerge
1241 foreach ($linkedMerge as $masterID => $values) {
1242 $keys = array($masterID);
1243 $keys = array_merge($keys, array_keys($values['copy']));
1244 foreach ($merge as $mid => $vals) {
1245 if (in_array($mid, $keys)) {
1246 unset($merge[$mid]);
1249 foreach ($values['copy'] as $copyId) {
1250 if (in_array($copyId, $keys)) {
1251 unset($merge[$mid]['copy'][$copyId]);
1257 $merge = $merge +
$linkedMerge;
1259 foreach ($merge as $masterID => $values) {
1262 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1266 1 => array($values['addressee'], 'String'),
1267 2 => array($values['postalGreeting'], 'String'),
1268 3 => array($values['emailGreeting'], 'String'),
1269 4 => array($masterID, 'Integer'),
1271 CRM_Core_DAO
::executeQuery($sql, $params);
1273 // delete all copies
1274 $deleteIDs = array_keys($values['copy']);
1275 $deleteIDString = implode(',', $deleteIDs);
1277 DELETE FROM $tableName
1278 WHERE id IN ( $deleteIDString )
1280 CRM_Core_DAO
::executeQuery($sql);
1283 // unset temporary columns that were added for postal mailing format
1284 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1285 $unsetKeys = array_keys($sqlColumns);
1286 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1287 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1288 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1295 * @param int $contactId
1296 * @param array $exportParams
1300 public static function _replaceMergeTokens($contactId, $exportParams) {
1301 $greetings = array();
1304 $greetingFields = array(
1308 foreach ($greetingFields as $greeting) {
1309 if (!empty($exportParams[$greeting])) {
1310 $greetingLabel = $exportParams[$greeting];
1311 if (empty($contact)) {
1316 $contact = civicrm_api('contact', 'get', $values);
1318 if (!empty($contact['is_error'])) {
1321 $contact = $contact['values'][$contact['id']];
1324 $tokens = array('contact' => $greetingLabel);
1325 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1332 * The function unsets static part of the string, if token is the dynamic part.
1334 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1335 * i.e 'Hello Alan' => converted to => 'Alan'
1337 * @param string $parsedString
1338 * @param string $defaultGreeting
1339 * @param bool $addressMergeGreetings
1340 * @param string $greetingType
1344 public static function _trimNonTokens(
1345 &$parsedString, $defaultGreeting,
1346 $addressMergeGreetings, $greetingType = 'postal_greeting'
1348 if (!empty($addressMergeGreetings[$greetingType])) {
1349 $greetingLabel = $addressMergeGreetings[$greetingType];
1351 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1353 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1354 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1355 foreach ($stringsToBeReplaced as $key => $string) {
1356 // to keep one space
1357 $stringsToBeReplaced[$key] = ltrim($string);
1359 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1361 return $parsedString;
1366 * @param array $exportParams
1367 * @param bool $sharedAddress
1371 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1372 static $contactGreetingTokens = array();
1374 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1375 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1377 $merge = $parents = array();
1378 $dao = CRM_Core_DAO
::executeQuery($sql);
1380 while ($dao->fetch()) {
1381 $masterID = $dao->master_id
;
1382 $copyID = $dao->copy_id
;
1383 $masterPostalGreeting = $dao->master_postal_greeting
;
1384 $masterAddressee = $dao->master_addressee
;
1385 $copyAddressee = $dao->copy_addressee
;
1387 if (!$sharedAddress) {
1388 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1389 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1391 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1392 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1394 $masterAddressee = CRM_Utils_Array
::value('addressee',
1395 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1398 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1399 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1401 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1402 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1404 $copyAddressee = CRM_Utils_Array
::value('addressee',
1405 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1409 if (!isset($merge[$masterID])) {
1410 // check if this is an intermediate child
1411 // this happens if there are 3 or more matches a,b, c
1412 // the above query will return a, b / a, c / b, c
1413 // we might be doing a bit more work, but for now its ok, unless someone
1414 // knows how to fix the query above
1415 if (isset($parents[$masterID])) {
1416 $masterID = $parents[$masterID];
1419 $merge[$masterID] = array(
1420 'addressee' => $masterAddressee,
1422 'postalGreeting' => $masterPostalGreeting,
1424 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1427 $parents[$copyID] = $masterID;
1429 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1431 if (!empty($exportParams['postal_greeting_other']) &&
1432 count($merge[$masterID]['copy']) >= 1
1434 // use static greetings specified if no of contacts > 2
1435 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1437 elseif ($copyPostalGreeting) {
1438 self
::_trimNonTokens($copyPostalGreeting,
1439 $postalOptions[$dao->copy_postal_greeting_id
],
1442 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1443 // if there happens to be a duplicate, remove it
1444 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1447 if (!empty($exportParams['addressee_other']) &&
1448 count($merge[$masterID]['copy']) >= 1
1450 // use static greetings specified if no of contacts > 2
1451 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1453 elseif ($copyAddressee) {
1454 self
::_trimNonTokens($copyAddressee,
1455 $addresseeOptions[$dao->copy_addressee_id
],
1456 $exportParams, 'addressee'
1458 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1461 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1468 * Merge household record into the individual record
1471 * @param string $exportTempTable
1472 * Temporary temp table that stores the records.
1473 * @param array $headerRows
1474 * Array of headers for the export file.
1475 * @param array $sqlColumns
1476 * Array of names of the table columns of the temp table.
1477 * @param string $prefix
1478 * Name of the relationship type that is prefixed to the table columns.
1480 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1481 $prefixColumn = $prefix . '_';
1482 $allKeys = array_keys($sqlColumns);
1483 $replaced = array();
1484 $headerRows = array_values($headerRows);
1486 // name map of the non standard fields in header rows & sql columns
1487 $mappingFields = array(
1488 'civicrm_primary_id' => 'id',
1489 'contact_source' => 'source',
1490 'current_employer_id' => 'employer_id',
1491 'contact_is_deleted' => 'is_deleted',
1492 'name' => 'address_name',
1493 'provider_id' => 'im_service_provider',
1494 'phone_type_id' => 'phone_type',
1497 //figure out which columns are to be replaced by which ones
1498 foreach ($sqlColumns as $columnNames => $dontCare) {
1499 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1500 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1503 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1505 if (!empty($sqlColumns[$householdColName])) {
1506 $replaced[$columnNames] = $householdColName;
1510 $query = "UPDATE $exportTempTable SET ";
1513 foreach ($replaced as $from => $to) {
1514 $clause[] = "$from = $to ";
1515 unset($sqlColumns[$to]);
1516 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1517 unset($headerRows[$key]);
1520 $query .= implode(",\n", $clause);
1521 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1523 CRM_Core_DAO
::executeQuery($query);
1525 //drop the table columns that store redundant household info
1526 $dropQuery = "ALTER TABLE $exportTempTable ";
1527 foreach ($replaced as $householdColumns) {
1528 $dropClause[] = " DROP $householdColumns ";
1530 $dropQuery .= implode(",\n", $dropClause);
1532 CRM_Core_DAO
::executeQuery($dropQuery);
1534 // also drop the temp table if exists
1535 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1536 CRM_Core_DAO
::executeQuery($sql);
1538 // clean up duplicate records
1540 CREATE TABLE {$exportTempTable}_temp SELECT *
1541 FROM {$exportTempTable}
1542 GROUP BY civicrm_primary_id ";
1544 CRM_Core_DAO
::executeQuery($query);
1546 $query = "DROP TABLE $exportTempTable";
1547 CRM_Core_DAO
::executeQuery($query);
1549 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1550 CRM_Core_DAO
::executeQuery($query);
1554 * @param $exportTempTable
1555 * @param $headerRows
1556 * @param $sqlColumns
1557 * @param $exportMode
1558 * @param null $saveFile
1559 * @param string $batchItems
1561 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1562 $writeHeader = TRUE;
1564 $limit = self
::EXPORT_ROW_COUNT
;
1566 $query = "SELECT * FROM $exportTempTable";
1569 $limitQuery = $query . "
1570 LIMIT $offset, $limit
1572 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1578 $componentDetails = array();
1579 while ($dao->fetch()) {
1582 foreach ($sqlColumns as $column => $dontCare) {
1583 $row[$column] = $dao->$column;
1585 $componentDetails[] = $row;
1587 if ($exportMode == 'financial') {
1588 $getExportFileName = 'CiviCRM Contribution Search';
1591 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1593 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1600 if ($saveFile && !empty($csvRows)) {
1601 $batchItems .= $csvRows;
1604 $writeHeader = FALSE;
1610 * Manipulate header rows for relationship fields.
1612 * @param $headerRows
1614 public static function manipulateHeaderRows(&$headerRows) {
1615 foreach ($headerRows as & $header) {
1616 $split = explode('-', $header);
1617 if ($relationTypeName = CRM_Utils_Array
::value($split[0], self
::$relationshipTypes)) {
1618 $split[0] = $relationTypeName;
1619 $header = implode('-', $split);
1625 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1626 * or have no street address
1627 * @param $exportTempTable
1628 * @param $headerRows
1629 * @param $sqlColumns
1630 * @param $exportParams
1632 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1633 $whereClause = array();
1635 if (array_key_exists('is_deceased', $sqlColumns)) {
1636 $whereClause[] = 'is_deceased = 1';
1639 if (array_key_exists('do_not_mail', $sqlColumns)) {
1640 $whereClause[] = 'do_not_mail = 1';
1643 if (array_key_exists('street_address', $sqlColumns)) {
1644 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1646 // check for supplemental_address_1
1647 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1648 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1649 'address_options', TRUE, NULL, TRUE
1651 if (!empty($addressOptions['supplemental_address_1'])) {
1652 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1653 // enclose it again, since we are doing an AND in between a set of ORs
1654 $addressWhereClause = "( $addressWhereClause )";
1658 $whereClause[] = $addressWhereClause;
1661 if (!empty($whereClause)) {
1662 $whereClause = implode(' OR ', $whereClause);
1665 FROM $exportTempTable
1666 WHERE {$whereClause}";
1667 CRM_Core_DAO
::singleValueQuery($query);
1670 // unset temporary columns that were added for postal mailing format
1671 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1672 $unsetKeys = array_keys($sqlColumns);
1673 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1674 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1675 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1682 * Build componentPayment fields.
1684 public static function componentPaymentFields() {
1685 static $componentPaymentFields;
1686 if (!isset($componentPaymentFields)) {
1687 $componentPaymentFields = array(
1688 'componentPaymentField_total_amount' => ts('Total Amount'),
1689 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1690 'componentPaymentField_received_date' => ts('Date Received'),
1691 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1692 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1695 return $componentPaymentFields;
1699 * Set the definition for the header rows and sql columns based on the field to output.
1701 * @param string $field
1702 * @param array $headerRows
1703 * @param array $sqlColumns
1704 * Columns to go in the temp table.
1705 * @param \CRM_Export_BAO_ExportProcessor $processor
1706 * @param array|string $value
1707 * @param array $phoneTypes
1708 * @param array $imProviders
1709 * @param string $relationQuery
1710 * @param array $selectedPaymentFields
1713 public static function setHeaderRows($field, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields) {
1715 $queryFields = $processor->getQueryFields();
1716 // Split campaign into 2 fields for id and title
1717 if (substr($field, -14) == 'campaign_title') {
1718 $headerRows[] = ts('Campaign Title');
1720 elseif (substr($field, -11) == 'campaign_id') {
1721 $headerRows[] = ts('Campaign ID');
1723 elseif (isset($queryFields[$field]['title'])) {
1724 $headerRows[] = $queryFields[$field]['title'];
1726 elseif ($field == 'phone_type_id') {
1727 $headerRows[] = ts('Phone Type');
1729 elseif ($field == 'provider_id') {
1730 $headerRows[] = ts('IM Service Provider');
1732 elseif (substr($field, 0, 5) == 'case_' && $queryFields['case'][$field]['title']) {
1733 $headerRows[] = $queryFields['case'][$field]['title'];
1735 elseif (array_key_exists($field, self
::$relationshipTypes)) {
1736 foreach ($value as $relationField => $relationValue) {
1737 // below block is same as primary block (duplicate)
1738 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
1739 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
1740 $headerName = $field . '-' . $relationField;
1743 if ($relationField == 'current_employer') {
1744 $headerName = $field . '-' . 'current_employer';
1747 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
1751 $headerRows[] = $headerName;
1753 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1755 elseif ($relationField == 'phone_type_id') {
1756 $headerName = $field . '-' . 'Phone Type';
1757 $headerRows[] = $headerName;
1758 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1760 elseif ($relationField == 'provider_id') {
1761 $headerName = $field . '-' . 'Im Service Provider';
1762 $headerRows[] = $headerName;
1763 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1765 elseif ($relationField == 'state_province_id') {
1766 $headerName = $field . '-' . 'state_province_id';
1767 $headerRows[] = $headerName;
1768 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1770 elseif (is_array($relationValue) && $relationField == 'location') {
1771 // fix header for location type case
1772 foreach ($relationValue as $ltype => $val) {
1773 foreach (array_keys($val) as $fld) {
1774 $type = explode('-', $fld);
1776 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
1778 if (!empty($type[1])) {
1779 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1780 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1782 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1783 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1786 $headerName = $field . '-' . $hdr;
1787 $headerRows[] = $headerName;
1788 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1793 self
::manipulateHeaderRows($headerRows);
1795 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1796 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
1799 $headerRows[] = $field;
1802 self
::sqlColumnDefn($processor, $sqlColumns, $field);
1804 return array($headerRows, $sqlColumns);
1808 * Get the various arrays that we use to structure our output.
1810 * The extraction of these has been moved to a separate function for clarity and so that
1811 * tests can be added - in particular on the $outputHeaders array.
1813 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1814 * as a step on the refactoring path rather than how it should be.
1816 * @param array $returnProperties
1817 * @param \CRM_Export_BAO_ExportProcessor $processor
1818 * @param string $relationQuery
1819 * @param array $selectedPaymentFields
1821 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1822 * alias for the field generated by BAO_Query object.
1823 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1824 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1825 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1826 * I'm too embarassed to discuss here.
1828 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1829 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1830 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1831 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1832 * - a) the function used is more efficient or
1833 * - b) this code is old & outdated. Submit your answers to circular bin or better
1834 * yet find a way to comment them for posterity.
1836 public static function getExportStructureArrays($returnProperties, $processor, $relationQuery, $selectedPaymentFields) {
1837 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1838 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1839 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1841 $queryFields = $processor->getQueryFields();
1842 foreach ($returnProperties as $key => $value) {
1843 if ($key != 'location' ||
!is_array($value)) {
1844 $outputColumns[$key] = $value;
1845 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1848 foreach ($value as $locationType => $locationFields) {
1849 foreach (array_keys($locationFields) as $locationFieldName) {
1850 $type = explode('-', $locationFieldName);
1852 $actualDBFieldName = $type[0];
1853 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
1854 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1856 if (!empty($type[1])) {
1857 $daoFieldName .= "-" . $type[1];
1858 if ($actualDBFieldName == 'phone') {
1859 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1861 elseif ($actualDBFieldName == 'im') {
1862 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1865 if ($type[0] == 'im_provider') {
1866 // Warning: shame inducing hack.
1867 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1869 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1870 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1871 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
1872 $metadata[$daoFieldName] = array('context' => 'country');
1874 if ($actualDBFieldName == 'state_province') {
1875 $metadata[$daoFieldName] = array('context' => 'province');
1877 $outputColumns[$daoFieldName] = TRUE;
1882 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1886 * Get the values of linked household contact.
1888 * @param CRM_Core_DAO $relDAO
1889 * @param array $value
1890 * @param string $field
1893 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1894 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1895 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1896 $i18n = CRM_Core_I18n
::singleton();
1897 foreach ($value as $relationField => $relationValue) {
1898 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1899 $fieldValue = $relDAO->$relationField;
1900 if ($relationField == 'phone_type_id') {
1901 $fieldValue = $phoneTypes[$relationValue];
1903 elseif ($relationField == 'provider_id') {
1904 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1907 elseif (is_object($relDAO) && in_array($relationField, array(
1913 //special case for greeting replacement
1914 $fldValue = "{$relationField}_display";
1915 $fieldValue = $relDAO->$fldValue;
1918 elseif (is_object($relDAO) && $relationField == 'state_province') {
1919 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1921 elseif (is_object($relDAO) && $relationField == 'country') {
1922 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1927 $field = $field . '_';
1928 $relPrefix = $field . $relationField;
1930 if (is_object($relDAO) && $relationField == 'id') {
1931 $row[$relPrefix] = $relDAO->contact_id
;
1933 elseif (is_array($relationValue) && $relationField == 'location') {
1934 foreach ($relationValue as $ltype => $val) {
1935 foreach (array_keys($val) as $fld) {
1936 $type = explode('-', $fld);
1937 $fldValue = "{$ltype}-" . $type[0];
1938 if (!empty($type[1])) {
1939 $fldValue .= "-" . $type[1];
1941 // CRM-3157: localise country, region (both have ‘country’ context)
1942 // and state_province (‘province’ context)
1944 case (!is_object($relDAO)):
1945 $row[$field . '_' . $fldValue] = '';
1948 case in_array('country', $type):
1949 case in_array('world_region', $type):
1950 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1951 array('context' => 'country')
1955 case in_array('state_province', $type):
1956 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1957 array('context' => 'province')
1962 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1968 elseif (isset($fieldValue) && $fieldValue != '') {
1969 //check for custom data
1970 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1971 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1974 //normal relationship fields
1975 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1976 switch ($relationField) {
1978 case 'world_region':
1979 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1982 case 'state_province':
1983 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1987 $row[$relPrefix] = $fieldValue;
1993 // if relation field is empty or null
1994 $row[$relPrefix] = '';
2000 * Get the ids that we want to get related contact details for.
2003 * @param int $exportMode
2007 protected static function getIDsForRelatedContact($ids, $exportMode) {
2008 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
2011 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
2013 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
2014 $dao = CRM_Core_DAO
::executeQuery("
2015 SELECT contact_id FROM civicrm_activity_contact
2016 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
2017 record_type_id = {$sourceID}
2020 while ($dao->fetch()) {
2021 $relIDs[] = $dao->contact_id
;
2025 $component = self
::exportComponent($exportMode);
2027 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
2028 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
2031 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
2038 * @param $exportMode
2039 * @param $componentTable
2040 * @param $returnProperties
2044 protected static function buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode) {
2045 $allRelContactArray = $relationQuery = array();
2047 foreach (self
::$relationshipTypes as $rel => $dnt) {
2048 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
2049 $allRelContactArray[$rel] = array();
2050 // build Query for each relationship
2051 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
2052 NULL, FALSE, FALSE, $queryMode
2054 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
2056 list($id, $direction) = explode('_', $rel, 2);
2057 // identify the relationship direction
2058 $contactA = 'contact_id_a';
2059 $contactB = 'contact_id_b';
2060 if ($direction == 'b_a') {
2061 $contactA = 'contact_id_b';
2062 $contactB = 'contact_id_a';
2064 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
2066 $relationshipJoin = $relationshipClause = '';
2067 if (!$selectAll && $componentTable) {
2068 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
2070 elseif (!empty($relIDs)) {
2071 $relID = implode(',', $relIDs);
2072 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
2075 $relationFrom = " {$relationFrom}
2076 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
2077 {$relationshipJoin} ";
2079 //check for active relationship status only
2080 $today = date('Ymd');
2081 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
2082 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
2083 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
2084 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
2085 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
2087 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
2088 while ($allRelContactDAO->fetch()) {
2089 //FIX Me: Migrate this to table rather than array
2090 // build the array of all related contacts
2091 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
2093 $allRelContactDAO->free();
2096 return array($relationQuery, $allRelContactArray);
2101 * @param $iterationDAO
2102 * @param $fieldValue
2105 * @param $selectedPaymentFields
2106 * @param $paymentDetails
2107 * @param string $paymentTableId
2110 protected static function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $selectedPaymentFields, $paymentDetails, $paymentTableId) {
2112 if ($field == 'id') {
2113 return $iterationDAO->contact_id
;
2114 // special case for calculated field
2116 elseif ($field == 'source_contact_id') {
2117 return $iterationDAO->contact_id
;
2119 elseif ($field == 'pledge_balance_amount') {
2120 return $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
2121 // special case for calculated field
2123 elseif ($field == 'pledge_next_pay_amount') {
2124 return $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
2126 elseif (isset($fieldValue) &&
2129 //check for custom data
2130 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
2131 return CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
2134 elseif (in_array($field, array(
2139 //special case for greeting replacement
2140 $fldValue = "{$field}_display";
2141 return $iterationDAO->$fldValue;
2144 //normal fields with a touch of CRM-3157
2147 case 'world_region':
2148 return $i18n->crm_translate($fieldValue, array('context' => 'country'));
2150 case 'state_province':
2151 return $i18n->crm_translate($fieldValue, array('context' => 'province'));
2154 case 'preferred_communication_method':
2155 case 'preferred_mail_format':
2156 case 'communication_style':
2157 return $i18n->crm_translate($fieldValue);
2160 if (isset($metadata[$field])) {
2161 // No I don't know why we do it this way & whether we could
2162 // make better use of pseudoConstants.
2163 if (!empty($metadata[$field]['context'])) {
2164 return $i18n->crm_translate($fieldValue, $metadata[$field]);
2166 if (!empty($metadata[$field]['pseudoconstant'])) {
2167 // This is not our normal syntax for pseudoconstants but I am a bit loath to
2168 // call an external function until sure it is not increasing php processing given this
2169 // may be iterated 100,000 times & we already have the $imProvider var loaded.
2170 // That can be next refactor...
2171 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
2172 // but I have to reach a stable point....
2173 $varName = $metadata[$field]['pseudoconstant']['var'];
2174 if ($varName === 'imProviders') {
2175 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
2177 if ($varName === 'phoneTypes') {
2178 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
2187 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
2188 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
2189 $payFieldMapper = array(
2190 'componentPaymentField_total_amount' => 'total_amount',
2191 'componentPaymentField_contribution_status' => 'contribution_status',
2192 'componentPaymentField_payment_instrument' => 'pay_instru',
2193 'componentPaymentField_transaction_id' => 'trxn_id',
2194 'componentPaymentField_received_date' => 'receive_date',
2196 return CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
2199 // if field is empty or null