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 = 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;
448 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
449 foreach ($fields as $key => $var) {
450 if ($key && (substr($key, 0, 6) != 'custom')) {
452 $returnProperties[$key] = 1;
457 $returnProperties['location_type'] = 1;
458 $returnProperties['im_provider'] = 1;
459 $returnProperties['phone_type_id'] = 1;
460 $returnProperties['provider_id'] = 1;
461 $returnProperties['current_employer'] = 1;
464 $extraProperties = self
::defineExtraProperties($queryMode);
465 $paymentFields = $extraProperties['paymentFields'];
466 $extraReturnProperties = $extraProperties['extraReturnProperties'];
467 $paymentTableId = $extraProperties['paymentTableId'];
469 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
470 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
471 if ($queryMode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
472 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
473 $componentReturnProperties = array_merge(
474 $componentReturnProperties,
475 CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
477 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
479 if (!empty($extraReturnProperties)) {
480 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
483 // unset non exportable fields for components
484 $nonExpoFields = array(
488 'contribution_status_id',
490 'pledge_payment_status_id',
492 foreach ($nonExpoFields as $value) {
493 unset($returnProperties[$value]);
498 if ($mergeSameAddress) {
499 //make sure the addressee fields are selected
500 //while using merge same address feature
501 $returnProperties['addressee'] = 1;
502 $returnProperties['postal_greeting'] = 1;
503 $returnProperties['email_greeting'] = 1;
504 $returnProperties['street_name'] = 1;
505 $returnProperties['household_name'] = 1;
506 $returnProperties['street_address'] = 1;
507 $returnProperties['city'] = 1;
508 $returnProperties['state_province'] = 1;
510 // some columns are required for assistance incase they are not already present
511 $exportParams['merge_same_address']['temp_columns'] = array();
512 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
513 foreach ($tempColumns as $column) {
514 if (!array_key_exists($column, $returnProperties)) {
515 $returnProperties[$column] = 1;
516 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
517 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
522 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
523 // If an Additional Group is selected, then all contacts in that group are
524 // added to the export set (filtering out duplicates).
526 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";
527 CRM_Core_DAO
::executeQuery($query);
530 if ($moreReturnProperties) {
532 if (!empty($moreReturnProperties['group'])) {
533 unset($moreReturnProperties['group']);
534 $moreReturnProperties['groups'] = 1;
536 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
539 $exportParams['postal_mailing_export']['temp_columns'] = array();
540 if ($exportParams['exportOption'] == 2 &&
541 isset($exportParams['postal_mailing_export']) &&
542 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
544 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
545 foreach ($postalColumns as $column) {
546 if (!array_key_exists($column, $returnProperties)) {
547 $returnProperties[$column] = 1;
548 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
553 // rectify params to what proximity search expects if there is a value for prox_distance
555 if (!empty($params)) {
556 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
559 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
561 if ($mergeSameHousehold == 1) {
562 if (empty($returnProperties['id'])) {
563 $returnProperties['id'] = 1;
566 foreach ($returnProperties as $key => $value) {
567 if (!array_key_exists($key, self
::$relationshipTypes)) {
568 $returnProperties[self
::$memberOfHouseholdRelationshipKey][$key] = $value;
569 $returnProperties[self
::$headOfHouseholdRelationshipKey][$key] = $value;
573 unset($returnProperties[self
::$memberOfHouseholdRelationshipKey]['location_type']);
574 unset($returnProperties[self
::$memberOfHouseholdRelationshipKey]['im_provider']);
575 unset($returnProperties[self
::$headOfHouseholdRelationshipKey]['location_type']);
576 unset($returnProperties[self
::$headOfHouseholdRelationshipKey]['im_provider']);
579 list($relationQuery, $allRelContactArray) = self
::buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode);
581 // make sure the groups stuff is included only if specifically specified
582 // by the fields param (CRM-1969), else we limit the contacts outputted to only
583 // ones that are part of a group
584 if (!empty($returnProperties['groups'])) {
585 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
586 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
587 // total hack for export, CRM-3618
588 $from = str_replace($oldClause,
594 if (!$selectAll && $componentTable) {
595 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
597 elseif ($componentClause) {
599 $where = "WHERE $componentClause";
602 $where .= " AND $componentClause";
606 // CRM-13982 - check if is deleted
607 $excludeTrashed = TRUE;
608 foreach ($params as $value) {
609 if ($value[0] == 'contact_is_deleted') {
610 $excludeTrashed = FALSE;
613 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
616 $where = "WHERE $trashClause";
619 $where .= " AND $trashClause";
622 $queryString = "$select $from $where $having";
624 $groupBy = self
::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
626 $queryString .= $groupBy;
629 // always add contact_a.id to the ORDER clause
630 // so the order is deterministic
632 if (strpos('contact_a.id', $order) === FALSE) {
633 $order .= ", contact_a.id";
636 list($field, $dir) = explode(' ', $order, 2);
637 $field = trim($field);
638 if (!empty($returnProperties[$field])) {
640 $queryString .= " ORDER BY $order";
644 $addPaymentHeader = FALSE;
646 $paymentDetails = array();
647 if ($paymentFields ||
$selectedPaymentFields) {
649 // get payment related in for event and members
650 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
651 //get all payment headers.
652 // If we haven't selected specific payment fields, load in all the
654 if (!$selectedPaymentFields) {
655 $paymentHeaders = self
::componentPaymentFields();
656 if (!empty($paymentDetails)) {
657 $addPaymentHeader = TRUE;
660 // If we have selected specific payment fields, leave the payment headers
661 // as an empty array; the headers for each selected field will be added
664 $paymentHeaders = array();
666 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
669 $componentDetails = array();
672 $rowCount = self
::EXPORT_ROW_COUNT
;
674 // we write to temp table often to avoid using too much memory
679 // for CRM-3157 purposes
680 $i18n = CRM_Core_I18n
::singleton();
682 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor, $relationQuery, $selectedPaymentFields);
684 $limitReached = FALSE;
685 while (!$limitReached) {
686 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
687 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
688 // If this is less than our limit by the end of the iteration we do not need to run the query again to
689 // check if some remain.
690 $rowsThisIteration = 0;
692 while ($iterationDAO->fetch()) {
694 $rowsThisIteration++
;
696 $query->convertToPseudoNames($iterationDAO);
698 //first loop through output columns so that we return what is required, and in same order.
699 foreach ($outputColumns as $field => $value) {
701 // add im_provider to $dao object
702 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
703 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
706 //build row values (data)
708 if (property_exists($iterationDAO, $field)) {
709 $fieldValue = $iterationDAO->$field;
710 // to get phone type from phone type id
711 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
712 $fieldValue = $phoneTypes[$fieldValue];
714 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
715 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
717 elseif (strstr($field, 'master_id')) {
718 $masterAddressId = NULL;
719 if (isset($iterationDAO->$field)) {
720 $masterAddressId = $iterationDAO->$field;
722 // get display name of contact that address is shared.
723 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
727 if ($field == 'id') {
728 $row[$field] = $iterationDAO->contact_id
;
729 // special case for calculated field
731 elseif ($field == 'source_contact_id') {
732 $row[$field] = $iterationDAO->contact_id
;
734 elseif ($field == 'pledge_balance_amount') {
735 $row[$field] = $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
736 // special case for calculated field
738 elseif ($field == 'pledge_next_pay_amount') {
739 $row[$field] = $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
741 elseif (array_key_exists($field, self
::$relationshipTypes)) {
742 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
743 $relationQuery[$field]->convertToPseudoNames($relDAO);
744 self
::fetchRelationshipDetails($relDAO, $value, $field, $row);
746 elseif (isset($fieldValue) &&
749 //check for custom data
750 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
751 $row[$field] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
754 elseif (in_array($field, array(
759 //special case for greeting replacement
760 $fldValue = "{$field}_display";
761 $row[$field] = $iterationDAO->$fldValue;
764 //normal fields with a touch of CRM-3157
768 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
771 case 'state_province':
772 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
776 case 'preferred_communication_method':
777 case 'preferred_mail_format':
778 case 'communication_style':
779 $row[$field] = $i18n->crm_translate($fieldValue);
783 if (isset($metadata[$field])) {
784 // No I don't know why we do it this way & whether we could
785 // make better use of pseudoConstants.
786 if (!empty($metadata[$field]['context'])) {
787 $row[$field] = $i18n->crm_translate($fieldValue, $metadata[$field]);
790 if (!empty($metadata[$field]['pseudoconstant'])) {
791 // This is not our normal syntax for pseudoconstants but I am a bit loath to
792 // call an external function until sure it is not increasing php processing given this
793 // may be iterated 100,000 times & we already have the $imProvider var loaded.
794 // That can be next refactor...
795 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
796 // but I have to reach a stable point....
797 $varName = $metadata[$field]['pseudoconstant']['var'];
799 $row[$field] = $labels[$fieldValue];
804 $row[$field] = $fieldValue;
809 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
810 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
811 $payFieldMapper = array(
812 'componentPaymentField_total_amount' => 'total_amount',
813 'componentPaymentField_contribution_status' => 'contribution_status',
814 'componentPaymentField_payment_instrument' => 'pay_instru',
815 'componentPaymentField_transaction_id' => 'trxn_id',
816 'componentPaymentField_received_date' => 'receive_date',
818 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
821 // if field is empty or null
826 // add payment headers if required
827 if ($addPaymentHeader && $paymentFields) {
828 // @todo rather than do this for every single row do it before the loop starts.
829 // where other header definitions take place.
830 $headerRows = array_merge($headerRows, $paymentHeaders);
831 foreach (array_keys($paymentHeaders) as $paymentHdr) {
832 self
::sqlColumnDefn($processor, $sqlColumns, $paymentHdr);
837 $exportTempTable = self
::createTempTable($sqlColumns);
840 //build header only once
843 // If specific payment fields have been selected for export, payment
844 // data will already be in $row. Otherwise, add payment related
845 // information, if appropriate.
846 if ($addPaymentHeader) {
847 if (!$selectedPaymentFields) {
848 if ($paymentFields) {
849 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
850 if (!is_array($paymentData) ||
empty($paymentData)) {
851 $paymentData = $nullContributionDetails;
853 $row = array_merge($row, $paymentData);
855 elseif (!empty($paymentDetails)) {
856 $row = array_merge($row, $nullContributionDetails);
860 //remove organization name for individuals if it is set for current employer
861 if (!empty($row['contact_type']) &&
862 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
864 $row['organization_name'] = '';
867 // add component info
868 // write the row to a file
869 $componentDetails[] = $row;
871 // output every $tempRowCount rows
872 if ($count %
$tempRowCount == 0) {
873 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
874 $componentDetails = array();
877 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
878 $limitReached = TRUE;
880 $offset +
= $rowCount;
883 if ($exportTempTable) {
884 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
886 // if postalMailing option is checked, exclude contacts who are deceased, have
887 // "Do not mail" privacy setting, or have no street address
888 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
889 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
891 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
894 // do merge same address and merge same household processing
895 if ($mergeSameAddress) {
896 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
899 // merge the records if they have corresponding households
900 if ($mergeSameHousehold) {
901 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$memberOfHouseholdRelationshipKey);
902 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$headOfHouseholdRelationshipKey);
906 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
908 // In order to be able to write a unit test against this function we need to suppress
909 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
910 if (empty($exportParams['suppress_csv_for_testing'])) {
911 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
914 // return tableName and sqlColumns in test context
915 return array($exportTempTable, $sqlColumns);
918 // delete the export temp table and component table
919 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
920 CRM_Core_DAO
::executeQuery($sql);
921 CRM_Core_DAO
::reenableFullGroupByMode();
922 CRM_Utils_System
::civiExit();
925 CRM_Core_DAO
::reenableFullGroupByMode();
926 throw new CRM_Core_Exception(ts('No records to export'));
931 * Name of the export file based on mode.
933 * @param string $output
941 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
943 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
944 return ts('CiviCRM Contact Search');
946 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
947 return ts('CiviCRM Contribution Search');
949 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
950 return ts('CiviCRM Member Search');
952 case CRM_Export_Form_Select
::EVENT_EXPORT
:
953 return ts('CiviCRM Participant Search');
955 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
956 return ts('CiviCRM Pledge Search');
958 case CRM_Export_Form_Select
::CASE_EXPORT
:
959 return ts('CiviCRM Case Search');
961 case CRM_Export_Form_Select
::GRANT_EXPORT
:
962 return ts('CiviCRM Grant Search');
964 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
965 return ts('CiviCRM Activity Search');
970 * Handle import error file creation.
972 public static function invoke() {
973 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
974 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
975 if (empty($parserName) ||
empty($type)) {
979 // clean and ensure parserName is a valid string
980 $parserName = CRM_Utils_String
::munge($parserName);
981 $parserClass = explode('_', $parserName);
983 // make sure parserClass is in the CRM namespace and
984 // at least 3 levels deep
985 if ($parserClass[0] == 'CRM' &&
986 count($parserClass) >= 3
988 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
989 // ensure the functions exists
990 if (method_exists($parserName, 'errorFileName') &&
991 method_exists($parserName, 'saveFileName')
993 $errorFileName = $parserName::errorFileName($type);
994 $saveFileName = $parserName::saveFileName($type);
995 if (!empty($errorFileName) && !empty($saveFileName)) {
996 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
997 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
998 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
999 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
1000 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
1002 readfile($errorFileName);
1006 CRM_Utils_System
::civiExit();
1010 * @param $customSearchClass
1011 * @param $formValues
1014 public static function exportCustom($customSearchClass, $formValues, $order) {
1015 $ext = CRM_Extension_System
::singleton()->getMapper();
1016 if (!$ext->isExtensionClass($customSearchClass)) {
1017 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
1020 require_once $ext->classToPath($customSearchClass);
1022 $search = new $customSearchClass($formValues);
1024 $includeContactIDs = FALSE;
1025 if ($formValues['radio_ts'] == 'ts_sel') {
1026 $includeContactIDs = TRUE;
1029 $sql = $search->all(0, 0, $order, $includeContactIDs);
1031 $columns = $search->columns();
1033 $header = array_keys($columns);
1034 $fields = array_values($columns);
1037 $dao = CRM_Core_DAO
::executeQuery($sql);
1039 if (method_exists($search, 'alterRow')) {
1042 while ($dao->fetch()) {
1045 foreach ($fields as $field) {
1046 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
1047 $row[$field] = $dao->$unqualified_field;
1050 $search->alterRow($row);
1055 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1056 CRM_Utils_System
::civiExit();
1060 * @param \CRM_Export_BAO_ExportProcessor $processor
1061 * @param $sqlColumns
1064 public static function sqlColumnDefn($processor, &$sqlColumns, $field) {
1065 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1068 $queryFields = $processor->getQueryFields();
1070 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1071 if ($fieldName == 'id') {
1072 $fieldName = 'civicrm_primary_id';
1075 // early exit for master_id, CRM-12100
1076 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1077 // also for current_employer, CRM-16939
1078 if ($fieldName == 'master_id' ||
$fieldName == 'current_employer') {
1079 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1083 if (substr($fieldName, -11) == 'campaign_id') {
1085 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1089 $lookUp = array('prefix_id', 'suffix_id');
1090 // set the sql columns
1091 if (isset($queryFields[$field]['type'])) {
1092 switch ($queryFields[$field]['type']) {
1093 case CRM_Utils_Type
::T_INT
:
1094 case CRM_Utils_Type
::T_BOOLEAN
:
1095 if (in_array($field, $lookUp)) {
1096 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1099 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1103 case CRM_Utils_Type
::T_STRING
:
1104 if (isset($queryFields[$field]['maxlength'])) {
1105 $sqlColumns[$fieldName] = "$fieldName varchar({$queryFields[$field]['maxlength']})";
1108 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1112 case CRM_Utils_Type
::T_TEXT
:
1113 case CRM_Utils_Type
::T_LONGTEXT
:
1114 case CRM_Utils_Type
::T_BLOB
:
1115 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1116 $sqlColumns[$fieldName] = "$fieldName longtext";
1119 case CRM_Utils_Type
::T_FLOAT
:
1120 case CRM_Utils_Type
::T_ENUM
:
1121 case CRM_Utils_Type
::T_DATE
:
1122 case CRM_Utils_Type
::T_TIME
:
1123 case CRM_Utils_Type
::T_TIMESTAMP
:
1124 case CRM_Utils_Type
::T_MONEY
:
1125 case CRM_Utils_Type
::T_EMAIL
:
1126 case CRM_Utils_Type
::T_URL
:
1127 case CRM_Utils_Type
::T_CCNUM
:
1129 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1134 if (substr($fieldName, -3, 3) == '_id') {
1135 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1137 elseif (substr($fieldName, -5, 5) == '_note') {
1138 $sqlColumns[$fieldName] = "$fieldName text";
1141 $changeFields = array(
1147 if (in_array($fieldName, $changeFields)) {
1148 $sqlColumns[$fieldName] = "$fieldName text";
1151 // set the sql columns for custom data
1152 if (isset($queryFields[$field]['data_type'])) {
1154 switch ($queryFields[$field]['data_type']) {
1156 // May be option labels, which could be up to 512 characters
1157 $length = max(512, CRM_Utils_Array
::value('text_length', $queryFields[$field]));
1158 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1162 case 'StateProvince':
1164 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1168 $sqlColumns[$fieldName] = "$fieldName text";
1172 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1177 $sqlColumns[$fieldName] = "$fieldName text";
1185 * @param string $tableName
1187 * @param $sqlColumns
1189 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1190 if (empty($details)) {
1199 $id = CRM_Core_DAO
::singleValueQuery($sql);
1204 $sqlClause = array();
1206 foreach ($details as $dontCare => $row) {
1208 $valueString = array($id);
1209 foreach ($row as $dontCare => $value) {
1210 if (empty($value)) {
1211 $valueString[] = "''";
1214 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1217 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1220 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1222 $sqlValueString = implode(",\n", $sqlClause);
1225 INSERT INTO $tableName $sqlColumnString
1226 VALUES $sqlValueString
1228 CRM_Core_DAO
::executeQuery($sql);
1232 * @param $sqlColumns
1236 public static function createTempTable(&$sqlColumns) {
1237 //creating a temporary table for the search result that need be exported
1238 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export')->getName();
1240 // also create the sql table
1241 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1242 CRM_Core_DAO
::executeQuery($sql);
1245 CREATE TABLE {$exportTempTable} (
1246 id int unsigned NOT NULL AUTO_INCREMENT,
1248 $sql .= implode(",\n", array_values($sqlColumns));
1253 // add indexes for street_address and household_name if present
1254 $addIndices = array(
1257 'civicrm_primary_id',
1260 foreach ($addIndices as $index) {
1261 if (isset($sqlColumns[$index])) {
1263 INDEX index_{$index}( $index )
1269 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1272 CRM_Core_DAO
::executeQuery($sql);
1273 return $exportTempTable;
1277 * @param string $tableName
1278 * @param $headerRows
1279 * @param $sqlColumns
1280 * @param array $exportParams
1282 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1283 // check if any records are present based on if they have used shared address feature,
1284 // and not based on if city / state .. matches.
1286 SELECT r1.id as copy_id,
1287 r1.civicrm_primary_id as copy_contact_id,
1288 r1.addressee as copy_addressee,
1289 r1.addressee_id as copy_addressee_id,
1290 r1.postal_greeting as copy_postal_greeting,
1291 r1.postal_greeting_id as copy_postal_greeting_id,
1293 r2.civicrm_primary_id as master_contact_id,
1294 r2.postal_greeting as master_postal_greeting,
1295 r2.postal_greeting_id as master_postal_greeting_id,
1296 r2.addressee as master_addressee,
1297 r2.addressee_id as master_addressee_id
1299 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1300 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1302 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1304 // find all the records that have the same street address BUT not in a household
1305 // require match on city and state as well
1307 SELECT r1.id as master_id,
1308 r1.civicrm_primary_id as master_contact_id,
1309 r1.postal_greeting as master_postal_greeting,
1310 r1.postal_greeting_id as master_postal_greeting_id,
1311 r1.addressee as master_addressee,
1312 r1.addressee_id as master_addressee_id,
1314 r2.civicrm_primary_id as copy_contact_id,
1315 r2.postal_greeting as copy_postal_greeting,
1316 r2.postal_greeting_id as copy_postal_greeting_id,
1317 r2.addressee as copy_addressee,
1318 r2.addressee_id as copy_addressee_id
1320 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1321 r1.city = r2.city AND
1322 r1.state_province_id = r2.state_province_id )
1323 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1324 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1325 AND ( r1.street_address != '' )
1329 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1331 // unset ids from $merge already present in $linkedMerge
1332 foreach ($linkedMerge as $masterID => $values) {
1333 $keys = array($masterID);
1334 $keys = array_merge($keys, array_keys($values['copy']));
1335 foreach ($merge as $mid => $vals) {
1336 if (in_array($mid, $keys)) {
1337 unset($merge[$mid]);
1340 foreach ($values['copy'] as $copyId) {
1341 if (in_array($copyId, $keys)) {
1342 unset($merge[$mid]['copy'][$copyId]);
1348 $merge = $merge +
$linkedMerge;
1350 foreach ($merge as $masterID => $values) {
1353 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1357 1 => array($values['addressee'], 'String'),
1358 2 => array($values['postalGreeting'], 'String'),
1359 3 => array($values['emailGreeting'], 'String'),
1360 4 => array($masterID, 'Integer'),
1362 CRM_Core_DAO
::executeQuery($sql, $params);
1364 // delete all copies
1365 $deleteIDs = array_keys($values['copy']);
1366 $deleteIDString = implode(',', $deleteIDs);
1368 DELETE FROM $tableName
1369 WHERE id IN ( $deleteIDString )
1371 CRM_Core_DAO
::executeQuery($sql);
1374 // unset temporary columns that were added for postal mailing format
1375 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1376 $unsetKeys = array_keys($sqlColumns);
1377 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1378 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1379 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1386 * @param int $contactId
1387 * @param array $exportParams
1391 public static function _replaceMergeTokens($contactId, $exportParams) {
1392 $greetings = array();
1395 $greetingFields = array(
1399 foreach ($greetingFields as $greeting) {
1400 if (!empty($exportParams[$greeting])) {
1401 $greetingLabel = $exportParams[$greeting];
1402 if (empty($contact)) {
1407 $contact = civicrm_api('contact', 'get', $values);
1409 if (!empty($contact['is_error'])) {
1412 $contact = $contact['values'][$contact['id']];
1415 $tokens = array('contact' => $greetingLabel);
1416 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1423 * The function unsets static part of the string, if token is the dynamic part.
1425 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1426 * i.e 'Hello Alan' => converted to => 'Alan'
1428 * @param string $parsedString
1429 * @param string $defaultGreeting
1430 * @param bool $addressMergeGreetings
1431 * @param string $greetingType
1435 public static function _trimNonTokens(
1436 &$parsedString, $defaultGreeting,
1437 $addressMergeGreetings, $greetingType = 'postal_greeting'
1439 if (!empty($addressMergeGreetings[$greetingType])) {
1440 $greetingLabel = $addressMergeGreetings[$greetingType];
1442 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1444 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1445 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1446 foreach ($stringsToBeReplaced as $key => $string) {
1447 // to keep one space
1448 $stringsToBeReplaced[$key] = ltrim($string);
1450 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1452 return $parsedString;
1457 * @param array $exportParams
1458 * @param bool $sharedAddress
1462 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1463 static $contactGreetingTokens = array();
1465 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1466 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1468 $merge = $parents = array();
1469 $dao = CRM_Core_DAO
::executeQuery($sql);
1471 while ($dao->fetch()) {
1472 $masterID = $dao->master_id
;
1473 $copyID = $dao->copy_id
;
1474 $masterPostalGreeting = $dao->master_postal_greeting
;
1475 $masterAddressee = $dao->master_addressee
;
1476 $copyAddressee = $dao->copy_addressee
;
1478 if (!$sharedAddress) {
1479 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1480 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1482 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1483 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1485 $masterAddressee = CRM_Utils_Array
::value('addressee',
1486 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1489 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1490 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1492 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1493 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1495 $copyAddressee = CRM_Utils_Array
::value('addressee',
1496 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1500 if (!isset($merge[$masterID])) {
1501 // check if this is an intermediate child
1502 // this happens if there are 3 or more matches a,b, c
1503 // the above query will return a, b / a, c / b, c
1504 // we might be doing a bit more work, but for now its ok, unless someone
1505 // knows how to fix the query above
1506 if (isset($parents[$masterID])) {
1507 $masterID = $parents[$masterID];
1510 $merge[$masterID] = array(
1511 'addressee' => $masterAddressee,
1513 'postalGreeting' => $masterPostalGreeting,
1515 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1518 $parents[$copyID] = $masterID;
1520 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1522 if (!empty($exportParams['postal_greeting_other']) &&
1523 count($merge[$masterID]['copy']) >= 1
1525 // use static greetings specified if no of contacts > 2
1526 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1528 elseif ($copyPostalGreeting) {
1529 self
::_trimNonTokens($copyPostalGreeting,
1530 $postalOptions[$dao->copy_postal_greeting_id
],
1533 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1534 // if there happens to be a duplicate, remove it
1535 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1538 if (!empty($exportParams['addressee_other']) &&
1539 count($merge[$masterID]['copy']) >= 1
1541 // use static greetings specified if no of contacts > 2
1542 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1544 elseif ($copyAddressee) {
1545 self
::_trimNonTokens($copyAddressee,
1546 $addresseeOptions[$dao->copy_addressee_id
],
1547 $exportParams, 'addressee'
1549 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1552 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1559 * Merge household record into the individual record
1562 * @param string $exportTempTable
1563 * Temporary temp table that stores the records.
1564 * @param array $headerRows
1565 * Array of headers for the export file.
1566 * @param array $sqlColumns
1567 * Array of names of the table columns of the temp table.
1568 * @param string $prefix
1569 * Name of the relationship type that is prefixed to the table columns.
1571 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1572 $prefixColumn = $prefix . '_';
1573 $allKeys = array_keys($sqlColumns);
1574 $replaced = array();
1575 $headerRows = array_values($headerRows);
1577 // name map of the non standard fields in header rows & sql columns
1578 $mappingFields = array(
1579 'civicrm_primary_id' => 'id',
1580 'contact_source' => 'source',
1581 'current_employer_id' => 'employer_id',
1582 'contact_is_deleted' => 'is_deleted',
1583 'name' => 'address_name',
1584 'provider_id' => 'im_service_provider',
1585 'phone_type_id' => 'phone_type',
1588 //figure out which columns are to be replaced by which ones
1589 foreach ($sqlColumns as $columnNames => $dontCare) {
1590 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1591 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1594 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1596 if (!empty($sqlColumns[$householdColName])) {
1597 $replaced[$columnNames] = $householdColName;
1601 $query = "UPDATE $exportTempTable SET ";
1604 foreach ($replaced as $from => $to) {
1605 $clause[] = "$from = $to ";
1606 unset($sqlColumns[$to]);
1607 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1608 unset($headerRows[$key]);
1611 $query .= implode(",\n", $clause);
1612 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1614 CRM_Core_DAO
::executeQuery($query);
1616 //drop the table columns that store redundant household info
1617 $dropQuery = "ALTER TABLE $exportTempTable ";
1618 foreach ($replaced as $householdColumns) {
1619 $dropClause[] = " DROP $householdColumns ";
1621 $dropQuery .= implode(",\n", $dropClause);
1623 CRM_Core_DAO
::executeQuery($dropQuery);
1625 // also drop the temp table if exists
1626 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1627 CRM_Core_DAO
::executeQuery($sql);
1629 // clean up duplicate records
1631 CREATE TABLE {$exportTempTable}_temp SELECT *
1632 FROM {$exportTempTable}
1633 GROUP BY civicrm_primary_id ";
1635 CRM_Core_DAO
::executeQuery($query);
1637 $query = "DROP TABLE $exportTempTable";
1638 CRM_Core_DAO
::executeQuery($query);
1640 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1641 CRM_Core_DAO
::executeQuery($query);
1645 * @param $exportTempTable
1646 * @param $headerRows
1647 * @param $sqlColumns
1648 * @param $exportMode
1649 * @param null $saveFile
1650 * @param string $batchItems
1652 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1653 $writeHeader = TRUE;
1655 $limit = self
::EXPORT_ROW_COUNT
;
1657 $query = "SELECT * FROM $exportTempTable";
1660 $limitQuery = $query . "
1661 LIMIT $offset, $limit
1663 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1669 $componentDetails = array();
1670 while ($dao->fetch()) {
1673 foreach ($sqlColumns as $column => $dontCare) {
1674 $row[$column] = $dao->$column;
1676 $componentDetails[] = $row;
1678 if ($exportMode == 'financial') {
1679 $getExportFileName = 'CiviCRM Contribution Search';
1682 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1684 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1691 if ($saveFile && !empty($csvRows)) {
1692 $batchItems .= $csvRows;
1695 $writeHeader = FALSE;
1701 * Manipulate header rows for relationship fields.
1703 * @param $headerRows
1705 public static function manipulateHeaderRows(&$headerRows) {
1706 foreach ($headerRows as & $header) {
1707 $split = explode('-', $header);
1708 if ($relationTypeName = CRM_Utils_Array
::value($split[0], self
::$relationshipTypes)) {
1709 $split[0] = $relationTypeName;
1710 $header = implode('-', $split);
1716 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1717 * or have no street address
1718 * @param $exportTempTable
1719 * @param $headerRows
1720 * @param $sqlColumns
1721 * @param $exportParams
1723 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1724 $whereClause = array();
1726 if (array_key_exists('is_deceased', $sqlColumns)) {
1727 $whereClause[] = 'is_deceased = 1';
1730 if (array_key_exists('do_not_mail', $sqlColumns)) {
1731 $whereClause[] = 'do_not_mail = 1';
1734 if (array_key_exists('street_address', $sqlColumns)) {
1735 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1737 // check for supplemental_address_1
1738 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1739 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1740 'address_options', TRUE, NULL, TRUE
1742 if (!empty($addressOptions['supplemental_address_1'])) {
1743 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1744 // enclose it again, since we are doing an AND in between a set of ORs
1745 $addressWhereClause = "( $addressWhereClause )";
1749 $whereClause[] = $addressWhereClause;
1752 if (!empty($whereClause)) {
1753 $whereClause = implode(' OR ', $whereClause);
1756 FROM $exportTempTable
1757 WHERE {$whereClause}";
1758 CRM_Core_DAO
::singleValueQuery($query);
1761 // unset temporary columns that were added for postal mailing format
1762 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1763 $unsetKeys = array_keys($sqlColumns);
1764 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1765 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1766 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1773 * Build componentPayment fields.
1775 public static function componentPaymentFields() {
1776 static $componentPaymentFields;
1777 if (!isset($componentPaymentFields)) {
1778 $componentPaymentFields = array(
1779 'componentPaymentField_total_amount' => ts('Total Amount'),
1780 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1781 'componentPaymentField_received_date' => ts('Date Received'),
1782 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1783 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1786 return $componentPaymentFields;
1790 * Set the definition for the header rows and sql columns based on the field to output.
1792 * @param string $field
1793 * @param array $headerRows
1794 * @param array $sqlColumns
1795 * Columns to go in the temp table.
1796 * @param \CRM_Export_BAO_ExportProcessor $processor
1797 * @param array|string $value
1798 * @param array $phoneTypes
1799 * @param array $imProviders
1800 * @param string $relationQuery
1801 * @param array $selectedPaymentFields
1804 public static function setHeaderRows($field, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields) {
1806 $queryFields = $processor->getQueryFields();
1807 // Split campaign into 2 fields for id and title
1808 if (substr($field, -14) == 'campaign_title') {
1809 $headerRows[] = ts('Campaign Title');
1811 elseif (substr($field, -11) == 'campaign_id') {
1812 $headerRows[] = ts('Campaign ID');
1814 elseif (isset($queryFields[$field]['title'])) {
1815 $headerRows[] = $queryFields[$field]['title'];
1817 elseif ($field == 'phone_type_id') {
1818 $headerRows[] = ts('Phone Type');
1820 elseif ($field == 'provider_id') {
1821 $headerRows[] = ts('IM Service Provider');
1823 elseif (substr($field, 0, 5) == 'case_' && $queryFields['case'][$field]['title']) {
1824 $headerRows[] = $queryFields['case'][$field]['title'];
1826 elseif (array_key_exists($field, self
::$relationshipTypes)) {
1827 foreach ($value as $relationField => $relationValue) {
1828 // below block is same as primary block (duplicate)
1829 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
1830 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
1831 $headerName = $field . '-' . $relationField;
1834 if ($relationField == 'current_employer') {
1835 $headerName = $field . '-' . 'current_employer';
1838 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
1842 $headerRows[] = $headerName;
1844 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1846 elseif ($relationField == 'phone_type_id') {
1847 $headerName = $field . '-' . 'Phone Type';
1848 $headerRows[] = $headerName;
1849 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1851 elseif ($relationField == 'provider_id') {
1852 $headerName = $field . '-' . 'Im Service Provider';
1853 $headerRows[] = $headerName;
1854 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1856 elseif ($relationField == 'state_province_id') {
1857 $headerName = $field . '-' . 'state_province_id';
1858 $headerRows[] = $headerName;
1859 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1861 elseif (is_array($relationValue) && $relationField == 'location') {
1862 // fix header for location type case
1863 foreach ($relationValue as $ltype => $val) {
1864 foreach (array_keys($val) as $fld) {
1865 $type = explode('-', $fld);
1867 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
1869 if (!empty($type[1])) {
1870 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1871 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1873 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1874 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1877 $headerName = $field . '-' . $hdr;
1878 $headerRows[] = $headerName;
1879 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1884 self
::manipulateHeaderRows($headerRows);
1886 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1887 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
1890 $headerRows[] = $field;
1893 self
::sqlColumnDefn($processor, $sqlColumns, $field);
1895 return array($headerRows, $sqlColumns);
1899 * Get the various arrays that we use to structure our output.
1901 * The extraction of these has been moved to a separate function for clarity and so that
1902 * tests can be added - in particular on the $outputHeaders array.
1904 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1905 * as a step on the refactoring path rather than how it should be.
1907 * @param array $returnProperties
1908 * @param \CRM_Export_BAO_ExportProcessor $processor
1909 * @param string $relationQuery
1910 * @param array $selectedPaymentFields
1912 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1913 * alias for the field generated by BAO_Query object.
1914 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1915 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1916 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1917 * I'm too embarassed to discuss here.
1919 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1920 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1921 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1922 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1923 * - a) the function used is more efficient or
1924 * - b) this code is old & outdated. Submit your answers to circular bin or better
1925 * yet find a way to comment them for posterity.
1927 public static function getExportStructureArrays($returnProperties, $processor, $relationQuery, $selectedPaymentFields) {
1928 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1929 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1930 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1932 $queryFields = $processor->getQueryFields();
1933 foreach ($returnProperties as $key => $value) {
1934 if ($key != 'location' ||
!is_array($value)) {
1935 $outputColumns[$key] = $value;
1936 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1939 foreach ($value as $locationType => $locationFields) {
1940 foreach (array_keys($locationFields) as $locationFieldName) {
1941 $type = explode('-', $locationFieldName);
1943 $actualDBFieldName = $type[0];
1944 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
1945 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1947 if (!empty($type[1])) {
1948 $daoFieldName .= "-" . $type[1];
1949 if ($actualDBFieldName == 'phone') {
1950 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1952 elseif ($actualDBFieldName == 'im') {
1953 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1956 if ($type[0] == 'im_provider') {
1957 // Warning: shame inducing hack.
1958 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1960 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1961 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1962 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
1963 $metadata[$daoFieldName] = array('context' => 'country');
1965 if ($actualDBFieldName == 'state_province') {
1966 $metadata[$daoFieldName] = array('context' => 'province');
1968 $outputColumns[$daoFieldName] = TRUE;
1973 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1977 * Get the values of linked household contact.
1979 * @param CRM_Core_DAO $relDAO
1980 * @param array $value
1981 * @param string $field
1984 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1985 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1986 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1987 $i18n = CRM_Core_I18n
::singleton();
1988 foreach ($value as $relationField => $relationValue) {
1989 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1990 $fieldValue = $relDAO->$relationField;
1991 if ($relationField == 'phone_type_id') {
1992 $fieldValue = $phoneTypes[$relationValue];
1994 elseif ($relationField == 'provider_id') {
1995 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1998 elseif (is_object($relDAO) && in_array($relationField, array(
2004 //special case for greeting replacement
2005 $fldValue = "{$relationField}_display";
2006 $fieldValue = $relDAO->$fldValue;
2009 elseif (is_object($relDAO) && $relationField == 'state_province') {
2010 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
2012 elseif (is_object($relDAO) && $relationField == 'country') {
2013 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
2018 $field = $field . '_';
2019 $relPrefix = $field . $relationField;
2021 if (is_object($relDAO) && $relationField == 'id') {
2022 $row[$relPrefix] = $relDAO->contact_id
;
2024 elseif (is_array($relationValue) && $relationField == 'location') {
2025 foreach ($relationValue as $ltype => $val) {
2026 foreach (array_keys($val) as $fld) {
2027 $type = explode('-', $fld);
2028 $fldValue = "{$ltype}-" . $type[0];
2029 if (!empty($type[1])) {
2030 $fldValue .= "-" . $type[1];
2032 // CRM-3157: localise country, region (both have ‘country’ context)
2033 // and state_province (‘province’ context)
2035 case (!is_object($relDAO)):
2036 $row[$field . '_' . $fldValue] = '';
2039 case in_array('country', $type):
2040 case in_array('world_region', $type):
2041 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2042 array('context' => 'country')
2046 case in_array('state_province', $type):
2047 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2048 array('context' => 'province')
2053 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
2059 elseif (isset($fieldValue) && $fieldValue != '') {
2060 //check for custom data
2061 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
2062 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
2065 //normal relationship fields
2066 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
2067 switch ($relationField) {
2069 case 'world_region':
2070 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
2073 case 'state_province':
2074 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
2078 $row[$relPrefix] = $fieldValue;
2084 // if relation field is empty or null
2085 $row[$relPrefix] = '';
2091 * Get the ids that we want to get related contact details for.
2094 * @param int $exportMode
2098 protected static function getIDsForRelatedContact($ids, $exportMode) {
2099 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
2102 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
2104 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
2105 $dao = CRM_Core_DAO
::executeQuery("
2106 SELECT contact_id FROM civicrm_activity_contact
2107 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
2108 record_type_id = {$sourceID}
2111 while ($dao->fetch()) {
2112 $relIDs[] = $dao->contact_id
;
2116 $component = self
::exportComponent($exportMode);
2118 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
2119 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
2122 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
2129 * @param $exportMode
2130 * @param $componentTable
2131 * @param $returnProperties
2135 protected static function buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode) {
2136 $allRelContactArray = $relationQuery = array();
2138 foreach (self
::$relationshipTypes as $rel => $dnt) {
2139 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
2140 $allRelContactArray[$rel] = array();
2141 // build Query for each relationship
2142 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
2143 NULL, FALSE, FALSE, $queryMode
2145 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
2147 list($id, $direction) = explode('_', $rel, 2);
2148 // identify the relationship direction
2149 $contactA = 'contact_id_a';
2150 $contactB = 'contact_id_b';
2151 if ($direction == 'b_a') {
2152 $contactA = 'contact_id_b';
2153 $contactB = 'contact_id_a';
2155 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
2157 $relationshipJoin = $relationshipClause = '';
2158 if (!$selectAll && $componentTable) {
2159 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
2161 elseif (!empty($relIDs)) {
2162 $relID = implode(',', $relIDs);
2163 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
2166 $relationFrom = " {$relationFrom}
2167 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
2168 {$relationshipJoin} ";
2170 //check for active relationship status only
2171 $today = date('Ymd');
2172 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
2173 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
2174 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
2175 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
2176 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
2178 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
2179 while ($allRelContactDAO->fetch()) {
2180 //FIX Me: Migrate this to table rather than array
2181 // build the array of all related contacts
2182 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
2184 $allRelContactDAO->free();
2187 return array($relationQuery, $allRelContactArray);